Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52680b9eb7 | ||
|
|
6197b726a5 | ||
|
|
cead531983 | ||
|
|
2601e9ae43 | ||
|
|
8123fff9ca | ||
|
|
c25e94583a | ||
|
|
ecb6e6f924 | ||
|
|
028d67c3ec |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 232
|
||||
versionName = "2.0.32"
|
||||
versionCode = 235
|
||||
versionName = "2.0.35"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
@@ -39,6 +39,28 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lint 不挡 release 构建。
|
||||
*
|
||||
* ★ 唯一让它报错的是 `targetSdk = 28` 那条:
|
||||
*
|
||||
* Error: Google Play requires that apps target API level 33 or higher.
|
||||
* [ExpiredTargetSdkVersion]
|
||||
*
|
||||
* 而 **28 是必须的**,不能改 —— Android 10 起 targetSdk>=29 的应用
|
||||
* 不允许执行自己数据目录里的二进制(W^X 限制),而 bash / python /
|
||||
* dpkg 全在 /data/data/<包名>/files/usr 里。Termux 自己也是锁 28
|
||||
* 才活下来的。这条 lint 检查针对的是"上架 Google Play",而我们
|
||||
* 这个 App 本来就上不了架(自签证书 + 这个 targetSdk)。
|
||||
*
|
||||
* ★ 设 `abortOnError = false` 而不是 `checkReleaseBuilds = false`:
|
||||
* lint **照常跑**、报告照常生成,只是不因为这一条把构建打断。
|
||||
* 别的真问题仍然看得到。
|
||||
*/
|
||||
lint {
|
||||
abortOnError = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名。
|
||||
*
|
||||
|
||||
33
android/app/src/main/java/com/doubao/lynxclone/KernelHost.kt
Normal file
33
android/app/src/main/java/com/doubao/lynxclone/KernelHost.kt
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
|
||||
/**
|
||||
* 内核监听的端口。
|
||||
*
|
||||
* ## 为什么要有这个单例
|
||||
*
|
||||
* 端口原来是 `MainActivity` 里一个局部变量(`client.baseUrl` 也在那儿设)。
|
||||
* 但 `NativeBridge` 也需要打内核的接口 —— `end_conversation` 要
|
||||
* `PATCH /api/conversations/<id>` 把"这次对话已结束"落盘,而
|
||||
* `NativeBridge` 在**内核的工作线程**上被调,拿不到 Activity 的局部变量,
|
||||
* 也不该去依赖 UI 层的 `KernelClient`。
|
||||
*
|
||||
* 所以放一个进程级的单例:`MainActivity` 启动内核后写一次,别处只读。
|
||||
*/
|
||||
object KernelHost {
|
||||
|
||||
/** 内核端口;0 表示还没起来 */
|
||||
@Volatile
|
||||
var port: Int = 0
|
||||
|
||||
/** 内核起来之后由 MainActivity 调 */
|
||||
fun set(p: Int) {
|
||||
port = p
|
||||
}
|
||||
|
||||
fun baseUrl(): String = if (port > 0) "http://127.0.0.1:$port" else ""
|
||||
}
|
||||
|
||||
/** 全项目统一的 JSON 请求体类型(别在各处手写字符串,写错一个字符就是 415) */
|
||||
val JSON_MEDIA_TYPE = "application/json; charset=utf-8".toMediaType()
|
||||
@@ -70,6 +70,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (port != null && port > 0) {
|
||||
client.baseUrl = "http://127.0.0.1:$port"
|
||||
// ★ 端口也放进 KernelHost —— NativeBridge 里的 end_conversation
|
||||
// 要 PATCH 内核接口把"对话已结束"落盘,而它在内核工作线程上跑,
|
||||
// 拿不到这里的局部变量、也不该依赖 UI 层的 client。
|
||||
KernelHost.set(port)
|
||||
// ★ 把设备能力(定位/传感器/剪贴板/选文件)注册给 Python 侧的 device 工具,
|
||||
// 否则内核里的 device 工具会返回"没有安卓原生桥"
|
||||
withContext(Dispatchers.IO) {
|
||||
|
||||
@@ -20,7 +20,10 @@ import android.provider.OpenableColumns
|
||||
import com.chaquo.python.Python
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import com.doubao.lynxclone.termux.TermuxShell
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -67,6 +70,14 @@ class NativeBridge(private val activity: Activity) {
|
||||
req.optString("cwd"),
|
||||
(req.optDouble("timeout", 60.0) * 1000).toLong(),
|
||||
)
|
||||
// ---- 界面能力(AI 主动弹界面 / 弹窗 / 结束对话)----
|
||||
//
|
||||
// ★ 这三个 action 只在「技能」页打开了 uiTools 之后才会被内核调用
|
||||
// (tools_runtime 有两道拦截)。但这里**不再判一次开关** ——
|
||||
// 判两遍会让"开关忘了传下来"变成难查的静默失败;权限的事在内核那侧管。
|
||||
"ui_screen" -> uiScreen(req)
|
||||
"ui_dialog" -> uiDialog(req)
|
||||
"end_conversation" -> endConversation(req)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -74,6 +85,116 @@ class NativeBridge(private val activity: Activity) {
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个 HTML 界面(tools/show_ui.py)。
|
||||
*
|
||||
* **不阻塞**:弹出来就返回,用户看完自己关。理由见 [AiSurface.showScreen]。
|
||||
*/
|
||||
private fun uiScreen(req: JSONObject): JSONObject {
|
||||
val html = req.optString("html")
|
||||
if (html.isBlank()) return JSONObject().put("error", "html 是空的")
|
||||
val s = AiSurface.showScreen(
|
||||
html = html,
|
||||
title = req.optString("title"),
|
||||
fullHtml = req.optBoolean("full_html", false),
|
||||
conversationId = req.optString("conversationId"),
|
||||
)
|
||||
return JSONObject().put("ok", true).put("id", s.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 弹一个选择弹窗并**等用户回答**(tools/ask_user.py)。
|
||||
*
|
||||
* ★ 这里会阻塞当前线程(内核的 HTTP 工作线程)直到用户点或超时 ——
|
||||
* 和 [pickFile] 同一套路。**绝不能**在主线程调它。
|
||||
*/
|
||||
private fun uiDialog(req: JSONObject): JSONObject {
|
||||
val question = req.optString("question")
|
||||
if (question.isBlank()) return JSONObject().put("error", "question 是空的")
|
||||
|
||||
val options = mutableListOf<AiSurface.Option>()
|
||||
val arr = req.optJSONArray("options") ?: JSONArray()
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val label = o.optString("label").ifBlank { o.optString("value") }
|
||||
if (label.isBlank()) continue
|
||||
options.add(
|
||||
AiSurface.Option(
|
||||
label = label,
|
||||
value = o.optString("value").ifBlank { label },
|
||||
description = o.optString("description"),
|
||||
),
|
||||
)
|
||||
}
|
||||
if (options.isEmpty()) return JSONObject().put("error", "至少要有一个选项")
|
||||
|
||||
return AiSurface.ask(
|
||||
question = question,
|
||||
options = options,
|
||||
multiple = req.optBoolean("multiple", false),
|
||||
allowCancel = req.optBoolean("allowCancel", true),
|
||||
conversationId = req.optString("conversationId"),
|
||||
timeoutMs = req.optLong("timeoutMs", 120_000L),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 永久结束当前对话(tools/end_conversation.py)。
|
||||
*
|
||||
* ★ 必须**落盘**(PATCH /api/conversations/<id>),不能只改界面状态 ——
|
||||
* 界面状态一刷新就没了,用户重进会看到一个能继续输入的框,
|
||||
* 而模型以为自己已经结束了。两边状态不一致是这类功能最容易出的问题。
|
||||
*/
|
||||
private fun endConversation(req: JSONObject): JSONObject {
|
||||
val convId = req.optString("conversationId").ifBlank {
|
||||
return JSONObject().put("error", "没有 conversationId,无法结束对话")
|
||||
}
|
||||
val reason = req.optString("reason")
|
||||
val summary = req.optString("summary")
|
||||
return try {
|
||||
val body = JSONObject()
|
||||
.put("ended", true)
|
||||
.put("endedAt", System.currentTimeMillis())
|
||||
.put("endedReason", reason)
|
||||
if (summary.isNotBlank()) body.put("endedSummary", summary)
|
||||
// 走内核自己的 HTTP 接口 —— 这是唯一一条"由 Kotlin 写内核数据"的既有通道
|
||||
val resp = kernelPatch("/api/conversations/$convId", body)
|
||||
if (resp == null) {
|
||||
JSONObject().put("error", "内核没响应,对话状态没写进去")
|
||||
} else {
|
||||
AiSurface.markEnded(convId)
|
||||
JSONObject().put("ok", true).put("conversationId", convId)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH 一下内核的接口。
|
||||
*
|
||||
* ★ 这里**不能用 KernelClient** —— 那是 ViewModel 层的东西,NativeBridge
|
||||
* 拿不到(而且它跑在内核工作线程上,不该依赖 UI 层的对象)。
|
||||
* 直接用 OkHttp 打本机端口,和内核在同一个进程里,开销可以忽略。
|
||||
*
|
||||
* 端口从 [KernelHost.port] 取(内核起来之后写进去的)。
|
||||
*/
|
||||
private fun kernelPatch(path: String, body: JSONObject): String? {
|
||||
val port = KernelHost.port
|
||||
if (port <= 0) return null
|
||||
val client = okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.readTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
.build()
|
||||
val req = okhttp3.Request.Builder()
|
||||
.url("http://127.0.0.1:$port$path")
|
||||
.patch(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||
.build()
|
||||
client.newCall(req).execute().use { resp ->
|
||||
return if (resp.isSuccessful) resp.body?.string() else null
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.doubao.lynxclone.termux
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* ★★★ AI 主动弹出来的界面(HTML 全屏界面 / 选择弹窗)。
|
||||
*
|
||||
* ## 为什么要一个单例控制器
|
||||
*
|
||||
* 内核(Python,跑在 HTTP 工作线程上)通过 `NativeBridge.device()` 说
|
||||
* "给我弹个界面",而界面是 Compose 画的、归 `AppViewModel` 管。
|
||||
* 这两边**没有互相引用**:
|
||||
*
|
||||
* · `NativeBridge` 在 `MainActivity` 里 new 出来(见 MainActivity:76)
|
||||
* · `AppViewModel` 在 Compose 树里由 `rememberAppViewModel` 造
|
||||
*
|
||||
* 所以中间放一个单例:NativeBridge 往里写,ViewModel 订阅。
|
||||
* 这也让"内核线程"和"UI 状态"的边界很清楚 —— 内核永远不直接碰 Compose。
|
||||
*
|
||||
* ## 线程模型(这是最容易出错的地方)
|
||||
*
|
||||
* `device()` 是在**内核的 HTTP 工作线程**上被调的,而:
|
||||
* · 写状态:用 `@Volatile` + 监听器回调,ViewModel 在自己的协程里切主线程更新 Compose
|
||||
* · 等用户选择:用 [CountDownLatch] 阻塞**那个工作线程**(不能阻塞 UI 线程)
|
||||
*
|
||||
* 跟 `NativeBridge.pickFile()` 是同一套路子(它已经验证过可行)。
|
||||
*/
|
||||
object AiSurface {
|
||||
|
||||
private const val TAG = "DoubaoAiSurface"
|
||||
|
||||
/** 一次 AI 界面的标识。每次弹出都换一个,用来让 Compose 重建 WebView。 */
|
||||
private val seq = AtomicLong(0)
|
||||
|
||||
/** 正在显示的 HTML 界面;null 表示没有 */
|
||||
@Volatile
|
||||
var screen: Screen? = null
|
||||
private set
|
||||
|
||||
/** 正在等的选择弹窗;null 表示没有 */
|
||||
@Volatile
|
||||
var dialog: Dialog? = null
|
||||
private set
|
||||
|
||||
/** 当前对话被 AI 结束过 —— 界面据此禁用输入框 */
|
||||
@Volatile
|
||||
var endedConversationId: String = ""
|
||||
private set
|
||||
|
||||
data class Screen(
|
||||
val id: Long,
|
||||
val html: String,
|
||||
val title: String,
|
||||
val fullHtml: Boolean,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
data class Option(val label: String, val value: String, val description: String)
|
||||
|
||||
data class Dialog(
|
||||
val id: Long,
|
||||
val question: String,
|
||||
val options: List<Option>,
|
||||
val multiple: Boolean,
|
||||
val allowCancel: Boolean,
|
||||
val conversationId: String,
|
||||
)
|
||||
|
||||
/** ViewModel 订阅这个来把状态同步进 Compose。参数是"发生了什么"。 */
|
||||
@Volatile
|
||||
private var listener: ((String) -> Unit)? = null
|
||||
|
||||
fun subscribe(fn: ((String) -> Unit)?) {
|
||||
listener = fn
|
||||
}
|
||||
|
||||
private fun notify(kind: String) {
|
||||
try {
|
||||
listener?.invoke(kind)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "通知界面失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 界面
|
||||
|
||||
/**
|
||||
* 弹一个 HTML 界面。**不阻塞** —— 弹出来就返回,用户看完自己关。
|
||||
*
|
||||
* ★ 为什么不做成阻塞:`show_ui` 是"展示"语义,用户可能盯着看很久,
|
||||
* 把内核线程占住没有意义(而且模型这时也没别的事可做,但万一它想
|
||||
* 连续弹两个界面就会被卡死)。要阻塞的语义用 [ask]。
|
||||
*/
|
||||
fun showScreen(html: String, title: String, fullHtml: Boolean, conversationId: String): Screen {
|
||||
val s = Screen(seq.incrementAndGet(), html, title, fullHtml, conversationId)
|
||||
screen = s
|
||||
notify("screen")
|
||||
Log.i(TAG, "AI 弹出界面:${html.length} 字节,标题=${title.ifBlank { "(无)" }}")
|
||||
return s
|
||||
}
|
||||
|
||||
/** 用户在界面上点了带 `data-doubao-result` 的按钮(WebView 的 JS 桥转进来) */
|
||||
fun screenResult(value: String) {
|
||||
Log.i(TAG, "界面里点了:$value")
|
||||
// 界面上的点击不阻塞任何人,所以只通知一下、让界面记一笔
|
||||
lastScreenResult = value
|
||||
notify("screenResult")
|
||||
}
|
||||
|
||||
@Volatile
|
||||
var lastScreenResult: String = ""
|
||||
private set
|
||||
|
||||
/** 用户把界面关掉了 */
|
||||
fun closeScreen() {
|
||||
screen = null
|
||||
notify("screen")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 弹窗
|
||||
|
||||
/**
|
||||
* 弹一个选择弹窗,**阻塞**到用户选完或超时。
|
||||
*
|
||||
* ★ 超时是必须的:用户可能锁屏就走了。不设的话内核的工作线程永远挂着,
|
||||
* 而且因为 HTTP 是每请求一线程,挂一个少一个。
|
||||
*
|
||||
* ★ 这个函数只会在内核线程上被调,**绝不能在主线程调** ——
|
||||
* 它会 await。MainActivity 那边是通过 device() 进来的,天然是工作线程。
|
||||
*/
|
||||
fun ask(
|
||||
question: String,
|
||||
options: List<Option>,
|
||||
multiple: Boolean,
|
||||
allowCancel: Boolean,
|
||||
conversationId: String,
|
||||
timeoutMs: Long,
|
||||
): JSONObject {
|
||||
val d = Dialog(seq.incrementAndGet(), question, options, multiple, allowCancel, conversationId)
|
||||
val latch = CountDownLatch(1)
|
||||
answerLatch = latch
|
||||
answer = null
|
||||
dialog = d
|
||||
notify("dialog")
|
||||
Log.i(TAG, "AI 弹窗提问:$question(${options.size} 个选项,最多等 ${timeoutMs / 1000}s)")
|
||||
|
||||
val answered = latch.await(timeoutMs.coerceAtLeast(1000L), TimeUnit.MILLISECONDS)
|
||||
val a = answer
|
||||
answerLatch = null
|
||||
answer = null
|
||||
dialog = null
|
||||
notify("dialog")
|
||||
|
||||
if (!answered || a == null) {
|
||||
Log.i(TAG, "用户没在时限内回答")
|
||||
return JSONObject()
|
||||
.put("timeout", true)
|
||||
.put("multiple", multiple)
|
||||
.put("choice", "")
|
||||
.put("values", JSONArray())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var answerLatch: CountDownLatch? = null
|
||||
|
||||
@Volatile
|
||||
private var answer: JSONObject? = null
|
||||
|
||||
/** 用户选了。界面调这个。 */
|
||||
fun answerDialog(values: List<String>, cancelled: Boolean) {
|
||||
val arr = JSONArray()
|
||||
values.forEach { arr.put(it) }
|
||||
answer = JSONObject()
|
||||
.put("timeout", false)
|
||||
.put("cancelled", cancelled)
|
||||
.put("multiple", dialog?.multiple ?: false)
|
||||
.put("choice", values.firstOrNull() ?: "")
|
||||
.put("values", arr)
|
||||
answerLatch?.countDown()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 结束对话
|
||||
|
||||
fun markEnded(conversationId: String) {
|
||||
endedConversationId = conversationId
|
||||
notify("ended")
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,18 @@ object TermuxInstaller {
|
||||
private const val BOOTSTRAP_LIB = "libtermux-bootstrap.so"
|
||||
private const val ARROW = "\u2190" // SYMLINKS.txt 里的分隔符
|
||||
|
||||
/** 自编 dpkg 的 tar 包(伪装成 .so,见 [installOwnDpkg]) */
|
||||
private const val DPKG_LIB = "libdoubao-dpkg.so"
|
||||
|
||||
/**
|
||||
* 自编 dpkg 的版本戳。换了 dpkg 二进制就 +1 ——
|
||||
* 不然老设备上标记文件还在,新二进制不会被解出来。
|
||||
*
|
||||
* v1 → v2:维护脚本里**绝对路径**的改写(之前只改了 shebang,
|
||||
* 于是 `mkdir -p "/data/data/com.termux/..."` 这类照样撞权限)。
|
||||
*/
|
||||
private const val DPKG_VALUE = 2
|
||||
|
||||
fun prefix(context: Context): File = File(context.filesDir, "usr")
|
||||
fun home(context: Context): File = File(context.filesDir, "home")
|
||||
fun bashPath(context: Context): String = File(prefix(context), "bin/bash").absolutePath
|
||||
@@ -48,8 +60,15 @@ object TermuxInstaller {
|
||||
*
|
||||
* 把戳的值带上版本号,**对不上就只重跑修正式步骤**(不重新解压,
|
||||
* 解压要几十秒)。以后再加这类"装完之后要修一下"的逻辑,把这里 +1。
|
||||
*
|
||||
* v25:装上自编 dpkg(见 [installOwnDpkg])。
|
||||
* v26:补 `files/home` 那条沙箱链(bash 读 `$HOME/.bashrc` 用)。
|
||||
* v27:`rewritePrefixes` 改成**先换长路径**。以前 `bin/pip3` 的
|
||||
* `#!/…/com.termux/files/usr/bin/python3.14` 会被换成
|
||||
* `<pkg>/files/files/usr/…`(多一层 files,**解析不了**),
|
||||
* 于是 `pip3` 报 Permission denied 而 `python3 -m pip` 正常。
|
||||
*/
|
||||
private const val STAMP_VALUE = "ok:24"
|
||||
private const val STAMP_VALUE = "ok:27"
|
||||
|
||||
/**
|
||||
* wrapper / 补丁脚本的版本号。
|
||||
@@ -278,11 +297,228 @@ object TermuxInstaller {
|
||||
ensureSources(context)
|
||||
ensureCaBundle(context)
|
||||
fixBrokenSymlinks(context).let { trace(context, "修了 $it 个断链") }
|
||||
installDpkgWrapper(context)
|
||||
installOwnDpkg(context)
|
||||
writePatcherScript(context)
|
||||
linkLegacyPrefix(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 装上**我们自编的 dpkg**。
|
||||
*
|
||||
* ## 为什么要自编
|
||||
*
|
||||
* Termux 仓库里的 dpkg 是拿 `--sysconfdir=$PREFIX/etc` 编的,
|
||||
* 而 `$PREFIX` 在编译期就固化成了 `/data/data/com.termux/files/usr`。
|
||||
* 上游把配置目录当**编译期常量**烤进二进制,而且 dpkg 在**解析命令行之前**
|
||||
* 就去读它 —— 于是 `--admindir` 指得再对也没用:
|
||||
*
|
||||
* dpkg: error opening configuration directory
|
||||
* '/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
|
||||
*
|
||||
* `/data/data/com.termux` 是 **0700、属于真 Termux 的 UID**,我们的应用
|
||||
* 连穿都穿不进去,`scandir` 拿 EACCES;dpkg 对配置目录 ENOENT 是静默跳过、
|
||||
* 对 EACCES 直接致命退出。所以只要真 Termux 装着,Termux 的 dpkg 就必死。
|
||||
*
|
||||
* 自编版把这一处换成了**运行时解析**(从 `/proc/self/exe` 反推前缀),
|
||||
* 于是同一个二进制在任何包名下都指向自己所在的前缀。顺带还修了两件事:
|
||||
*
|
||||
* · **架构名**用 Termux 的写法(`x86_64` / `aarch64`)。Debian 那边叫
|
||||
* `amd64` / `arm64`,用错了 dpkg 会把数据库里**每一个包**都判成
|
||||
* `'x86_64' is not a valid architecture name`。
|
||||
* · 维护脚本的 **shebang**。Termux 的包里写的是
|
||||
* `#!/data/data/com.termux/files/usr/bin/sh`,内核对这条读不到的路径
|
||||
* 报 EACCES,而 dpkg 会把它显示成"脚本没有执行权限",指错方向。
|
||||
* 自编版在 exec 之前把这一行改成我们自己的前缀。
|
||||
*
|
||||
* 完整配方(补丁 + 构建脚本 + 校验脚本)在仓库的 `android/termux-dpkg/`。
|
||||
*
|
||||
* ## 二进制怎么来的
|
||||
*
|
||||
* `lib/<abi>/libdoubao-dpkg.so` 其实是个 **tar 包**(改名的原因见
|
||||
* [makeJniLibs],跟 `libtermux-bootstrap.so` 一个套路)。
|
||||
* 解出来直接覆盖 `bin/` 下的同名程序 —— 因为自编版是**完全替代**,
|
||||
* 不再需要 `dpkg.real` + wrapper 那一套(wrapper 本来就是在绕
|
||||
* "编译死的配置目录"这个我们已经从根上修掉的问题)。
|
||||
*/
|
||||
private fun installOwnDpkg(context: Context) {
|
||||
val prefix = prefix(context)
|
||||
val marker = File(prefix, "bin/dpkg")
|
||||
val stamp = File(context.filesDir, ".dpkg-own-$DPKG_VALUE")
|
||||
|
||||
// 已经装过这一版就不重复解包(解包 + chmod 有成本)
|
||||
if (stamp.exists() && marker.isFile) {
|
||||
if (looksLikeOurDpkg(marker)) return
|
||||
trace(context, "bin/dpkg 不像自编版,重新解一份")
|
||||
}
|
||||
|
||||
val dir = File(context.applicationInfo.nativeLibraryDir)
|
||||
val tar = File(dir, DPKG_LIB)
|
||||
if (!tar.isFile) {
|
||||
trace(context, "找不到 $DPKG_LIB($dir),只能用仓库里的 dpkg")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
val names = readTarNames(tar)
|
||||
if (names.isEmpty()) {
|
||||
trace(context, "$DPKG_LIB 里没解出文件名,跳过")
|
||||
return
|
||||
}
|
||||
extractTar(tar, prefix, "bin")
|
||||
var n = 0
|
||||
for (name in names) {
|
||||
val f = File(prefix, "bin/$name")
|
||||
if (f.isFile) {
|
||||
f.setExecutable(true, false)
|
||||
n++
|
||||
}
|
||||
}
|
||||
trace(context, "已装自编 dpkg(v$DPKG_VALUE):$n 个程序 $names")
|
||||
|
||||
// 旧方案留下的东西清掉,免得以后有人看到 bin/dpkg.real 以为还在用
|
||||
File(prefix, "bin/dpkg.real").delete()
|
||||
stamp.writeText("ok")
|
||||
} catch (t: Throwable) {
|
||||
trace(context, "装自编 dpkg 失败:${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 粗判一个文件是不是我们自编的 dpkg。
|
||||
*
|
||||
* 判据是 `/proc/self/exe` 这个字符串 —— 自编版的运行时前缀解析全靠它,
|
||||
* 而 Termux 仓库里的那份**没有**(它是编译期写死的路径)。
|
||||
* 只读前 512 KB 就够了,字符串在只读数据段靠前的位置。
|
||||
*/
|
||||
private fun looksLikeOurDpkg(f: File): Boolean = try {
|
||||
val buf = ByteArray(512 * 1024)
|
||||
val n = FileInputStream(f).use { it.read(buf) }
|
||||
var found = false
|
||||
if (n > 0) {
|
||||
val needle = "/proc/self/exe".toByteArray(Charsets.US_ASCII)
|
||||
outer@ for (i in 0..(n - needle.size)) {
|
||||
for (j in needle.indices) {
|
||||
if (buf[i + j] != needle[j]) continue@outer
|
||||
}
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
found
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* 极简 tar 读取
|
||||
*
|
||||
* 只要 ustar 格式、只要普通文件、不要长名/PAX —— 我们自己打的包
|
||||
* (见 android/termux-dpkg/make-jnilibs.sh)全是短名的普通文件。
|
||||
* 为了这点事去引一个 tar 库不值得,所以手写。
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
private const val TAR_BLOCK = 512
|
||||
|
||||
/** 读出 tar 里所有普通文件的名字(跳过目录等元数据项) */
|
||||
private fun readTarNames(tar: File): List<String> {
|
||||
val out = mutableListOf<String>()
|
||||
FileInputStream(tar).use { input ->
|
||||
val header = ByteArray(TAR_BLOCK)
|
||||
while (true) {
|
||||
if (!readFully(input, header)) break
|
||||
if (header.all { it == 0.toByte() }) break
|
||||
|
||||
val name = cString(header, 0, 100)
|
||||
val size = cString(header, 124, 12).toLongOrNull(8) ?: 0L
|
||||
val type = header[156].toInt().toChar()
|
||||
val prefix = cString(header, 345, 155)
|
||||
val full = if (prefix.isEmpty()) name else "$prefix/$name"
|
||||
|
||||
if (type == '0' || type == '\u0000') {
|
||||
if (!full.endsWith("/")) out.add(full)
|
||||
}
|
||||
val skip = ((size + TAR_BLOCK - 1) / TAR_BLOCK) * TAR_BLOCK
|
||||
if (!skipFully(input, skip)) break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 tar 里的普通文件解到 [destRoot]/[subdir] 下。
|
||||
*
|
||||
* 只接受**纯文件名**(没有斜杠)—— 我们只放几个 bin 程序,
|
||||
* 拒绝路径能让损坏或恶意的 tar 没法写到别处去。
|
||||
*/
|
||||
private fun extractTar(tar: File, destRoot: File, subdir: String) {
|
||||
val dest = File(destRoot, subdir)
|
||||
dest.mkdirs()
|
||||
FileInputStream(tar).use { input ->
|
||||
val header = ByteArray(TAR_BLOCK)
|
||||
while (true) {
|
||||
if (!readFully(input, header)) break
|
||||
if (header.all { it == 0.toByte() }) break
|
||||
|
||||
val name = cString(header, 0, 100)
|
||||
val size = cString(header, 124, 12).toLongOrNull(8) ?: 0L
|
||||
val type = header[156].toInt().toChar()
|
||||
val prefix = cString(header, 345, 155)
|
||||
val full = if (prefix.isEmpty()) name else "$prefix/$name"
|
||||
val padded = ((size + TAR_BLOCK - 1) / TAR_BLOCK) * TAR_BLOCK
|
||||
|
||||
val plain = (type == '0' || type == '\u0000') &&
|
||||
!full.endsWith("/") && !full.contains('/') &&
|
||||
full != "." && full != ".."
|
||||
|
||||
if (plain) {
|
||||
FileOutputStream(File(dest, full)).use { fos ->
|
||||
var left = size
|
||||
val buf = ByteArray(64 * 1024)
|
||||
while (left > 0) {
|
||||
val want = minOf(left, buf.size.toLong()).toInt()
|
||||
val got = input.read(buf, 0, want)
|
||||
if (got <= 0) throw IllegalStateException("tar 提前结束:$full")
|
||||
fos.write(buf, 0, got)
|
||||
left -= got
|
||||
}
|
||||
}
|
||||
if (!skipFully(input, padded - size)) break
|
||||
} else if (!skipFully(input, padded)) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readFully(input: FileInputStream, buf: ByteArray): Boolean {
|
||||
var off = 0
|
||||
while (off < buf.size) {
|
||||
val n = input.read(buf, off, buf.size - off)
|
||||
if (n <= 0) return off == 0
|
||||
off += n
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun skipFully(input: FileInputStream, count: Long): Boolean {
|
||||
var left = count
|
||||
val buf = ByteArray(8 * 1024)
|
||||
while (left > 0) {
|
||||
val n = input.read(buf, 0, minOf(left, buf.size.toLong()).toInt())
|
||||
if (n <= 0) return false
|
||||
left -= n
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 读 tar 头里的定长字符串(以 NUL 结尾) */
|
||||
private fun cString(buf: ByteArray, offset: Int, len: Int): String {
|
||||
var end = offset
|
||||
val limit = minOf(offset + len, buf.size)
|
||||
while (end < limit && buf[end] != 0.toByte()) end++
|
||||
return String(buf, offset, end - offset, Charsets.UTF_8).trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★ 保证 `etc/tls/cert.pem` **真的存在**。
|
||||
*
|
||||
@@ -368,7 +604,12 @@ object TermuxInstaller {
|
||||
""
|
||||
}
|
||||
val hasDeb = text.lineSequence().any { it.trim().startsWith("deb ") }
|
||||
if (hasDeb) return
|
||||
if (hasDeb) {
|
||||
// 有源了,但**源本身可能是坏的**(镜像正在同步)。
|
||||
// 后台探一次,坏了就自动换 —— 见 [TermuxMirror.autoPickIfBroken]。
|
||||
scheduleMirrorCheck(context)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// ★ 认得出是哪个源就沿用那个,认不出才退回默认(清华)。
|
||||
@@ -381,11 +622,53 @@ object TermuxInstaller {
|
||||
val mirror = TermuxMirror.current(context) ?: TermuxMirror.MIRRORS.first()
|
||||
val n = TermuxMirror.set(context, mirror)
|
||||
trace(context, "sources.list 缺失/为空 → 重写为 ${mirror.name}($n 条)")
|
||||
scheduleMirrorCheck(context)
|
||||
} catch (t: Throwable) {
|
||||
trace(context, "写 sources.list 失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 后台确认"当前源真的能用",不能用就自动换一个。
|
||||
*
|
||||
* 为什么必须做:用户的实测报错就是**镜像同步中**——
|
||||
*
|
||||
* E: Failed to fetch .../Packages.bz2
|
||||
* File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
*
|
||||
* 这时 `InRelease` 是新的、`Packages.bz2` 还是旧的,apt 对不上哈希直接拒。
|
||||
* 用户侧毫无办法:他按「源」按钮换到别的源才行,但他不知道要这么做,
|
||||
* 而且**我们默认给的就是清华**([TermuxMirror.MIRRORS] 第一个)——
|
||||
* 任何单一默认值都会偶尔把所有人卡在同一个坏源上。
|
||||
*
|
||||
* ★ 三点约束:
|
||||
* · **只在后台跑**。探测要真跑一次 `apt-get update`(45 秒超时),
|
||||
* 放主线程会让 App 启动卡住。
|
||||
* · **一个进程只跑一次**。用静态标记挡住 —— 这方法在 `ensureLightSteps`
|
||||
* 里,而那个是每次进终端都会调的。
|
||||
* · **不打扰用户**:当前源能用就什么都不做,一个字都不改。
|
||||
*/
|
||||
private fun scheduleMirrorCheck(context: Context) {
|
||||
if (!mirrorCheckStarted.compareAndSet(false, true)) return
|
||||
val app = context.applicationContext
|
||||
Thread {
|
||||
try {
|
||||
val used = TermuxMirror.autoPickIfBroken(app) { picked ->
|
||||
trace(app, "软件源自动切换到 ${picked.name}(原来那个在同步中,取不到索引)")
|
||||
}
|
||||
if (used != null) trace(app, "软件源探测通过:${used.name}")
|
||||
} catch (t: Throwable) {
|
||||
trace(app, "软件源探测出错(不影响使用):${t.message}")
|
||||
}
|
||||
}.apply {
|
||||
isDaemon = true
|
||||
name = "doubao-mirror-check"
|
||||
}.start()
|
||||
}
|
||||
|
||||
/** 见 [scheduleMirrorCheck]:保证一个进程里只探一次 */
|
||||
private val mirrorCheckStarted = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
|
||||
/**
|
||||
* 解压 bootstrap。
|
||||
*
|
||||
@@ -623,6 +906,7 @@ object TermuxInstaller {
|
||||
// 只换 `.../files` 的话这些会漏掉,pkg 照样跑不起来。
|
||||
val oldData = "/data/data/com.termux"
|
||||
val newData = context.applicationInfo.dataDir
|
||||
val newPrefix = prefix.absolutePath
|
||||
var fixed = 0
|
||||
|
||||
// ★★ 整棵 prefix 都扫,不再写死几个目录。
|
||||
@@ -696,10 +980,34 @@ object TermuxInstaller {
|
||||
text = if (first.startsWith("#!")) {
|
||||
"#!$bash" + if (nl < 0) "" else text.substring(nl)
|
||||
} else {
|
||||
text.replace("$oldData/files/usr", newData)
|
||||
text.replace("$oldData/files/usr", newPrefix)
|
||||
.replace(oldData, newData)
|
||||
}
|
||||
} else {
|
||||
text = text.replace(oldData, newData)
|
||||
/**
|
||||
* ★★★ **先换长路径,再换短的。顺序不能反。**
|
||||
*
|
||||
* 只做 `oldData → newData` 的话,`bin/pip3` 的
|
||||
* `#!/data/data/com.termux/files/usr/bin/python3.14`
|
||||
* 会变成
|
||||
* `#!/data/<pkg>/files/files/usr/bin/python3.14`
|
||||
* —— 而这条**解析不了**(实测 `No such file or directory`):
|
||||
* 沙箱里 `<prefix>/data/data/com.termux/files/usr`
|
||||
* 是接回 prefix 的,但
|
||||
* `<pkg>/files/files/usr/...` 里的第二个 `files` 是
|
||||
* `<pkg>/files` 下面一个**不存在**的目录
|
||||
* (`files/home` 那条链只兜住了 home,没有 bins)。
|
||||
*
|
||||
* 先换长的就干净了:
|
||||
* `.../com.termux/files/usr/bin/python3.14`
|
||||
* → `<prefix>/bin/python3.14` ✅ 实测能跑
|
||||
*
|
||||
* 实测对照(pip3):
|
||||
* `#!/data/<pkg>/files/files/usr/bin/python3.14` → Permission denied
|
||||
* `#!<prefix>/bin/python3.14` → pip 26.2.1 正常
|
||||
*/
|
||||
text = text.replace("$oldData/files/usr", newPrefix)
|
||||
.replace(oldData, newData)
|
||||
}
|
||||
|
||||
file.writeText(text, Charsets.UTF_8)
|
||||
@@ -918,8 +1226,7 @@ object TermuxInstaller {
|
||||
}
|
||||
|
||||
/** 装完之后给内核/工具用的环境变量(Termux 的标准一套) */
|
||||
fun environment(context: Context): Map<String, String> {
|
||||
val prefix = prefix(context).absolutePath
|
||||
fun environment(context: Context): Map<String, String> { val prefix = prefix(context).absolutePath
|
||||
val home = home(context).absolutePath
|
||||
val filesDir = context.filesDir.absolutePath
|
||||
val legacy = "/data/data/${context.packageName}/files"
|
||||
@@ -1015,6 +1322,93 @@ object TermuxInstaller {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 给**子进程**(终端会话、shell 工具)用的环境。
|
||||
*
|
||||
* 和 [environment] 的区别是:这里会把**宿主 Chaquopy 注入的 Python 环境变量
|
||||
* 摘掉**。这一步不做的话,Termux 里的 python 一启动就崩:
|
||||
*
|
||||
* Fatal Python error: Failed to import encodings module
|
||||
* zipimport.ZipImportError: module load failed: bad magic number
|
||||
* in 'encodings': b'\xf3\r\r\n'
|
||||
*
|
||||
* ## 为什么会这样
|
||||
*
|
||||
* App 自己跑着一个 **Chaquopy 的 CPython**(3.13 编的,标准库打包成
|
||||
* `files/chaquopy/stdlib-common.imy` 等 zip),Chaquopy 为了让这个解释器
|
||||
* 找到自己的标准库,在**进程环境里**设了 `PYTHONPATH` 指向那几个 .imy。
|
||||
*
|
||||
* 而 `ProcessBuilder` 和 `TerminalSession` 都是 fork 出来的子进程,
|
||||
* **继承整个 App 进程的环境**。于是 Termux 里 apt 装的那个 python 3.14
|
||||
* 一起来就读到 3.13 编的 `encodings/__init__.pyc`(魔数 `0x0df3` vs
|
||||
* `0x0df4`)→ 连 `encodings` 都 import 不了 → 解释器初始化直接核心崩溃。
|
||||
*
|
||||
* 实测确认(不是推测):
|
||||
* · `grep -r PYTHONPATH $PREFIX/etc/` → 空,Termux 自己一个字节都没设
|
||||
* · 但 `/proc/self/environ` 里有它 → 是父进程灌进来的
|
||||
* · `env -u PYTHONPATH python3 -c ...` → **立刻正常**
|
||||
*
|
||||
* ## 为什么只摘子进程的、不动 App 自己的
|
||||
*
|
||||
* Chaquopy 那个解释器**需要** `PYTHONPATH` 才能找到标准库,全局清掉会把
|
||||
* App 自己的内核搞死。而这里返回的 map 只用来构造子进程的环境,改它不影响
|
||||
* 父进程 —— 两边各用各的,互不干扰。
|
||||
*
|
||||
* `PYTHONHOME` / `PYTHONSTARTUP` 同理会把 Termux 的 python 拐到 Chaquopy
|
||||
* 那边去,一并摘掉。
|
||||
*/
|
||||
fun childEnv(context: Context): List<String> =
|
||||
environment(context)
|
||||
.filterKeys { it !in HOST_PYTHON_VARS }
|
||||
.map { (k, v) -> "$k=$v" }
|
||||
|
||||
/**
|
||||
* Chaquopy(宿主 Python 运行时)注入的变量名,**不能**带进 Termux 子进程。
|
||||
* 理由见 [childEnv]。
|
||||
*/
|
||||
private val HOST_PYTHON_VARS = setOf(
|
||||
"PYTHONPATH",
|
||||
"PYTHONHOME",
|
||||
"PYTHONSTARTUP",
|
||||
"PYTHONEXECUTABLE",
|
||||
"PYTHONNOUSERSITE",
|
||||
"PYTHONUSERBASE",
|
||||
)
|
||||
|
||||
/**
|
||||
* 在**父进程环境的基础之上**构造子进程环境:继承 + 覆盖 + 摘掉宿主 Python 变量。
|
||||
*
|
||||
* ## 为什么不是"清空再放我们那一套"
|
||||
*
|
||||
* 我第一版写的是 `pb.environment().clear()` 再 putAll —— 干净是干净,
|
||||
* 但**把系统区域设置也一起扔了**(`ANDROID_ROOT` / `ANDROID_ASSETS`
|
||||
* 之类由 init 设的变量),有些依赖这些变量的工具会行为异常。
|
||||
*
|
||||
* 这里改成"以父环境为底",既保住系统给的那些,又保证:
|
||||
* · 宿主 Python 变量一定不出现([HOST_PYTHON_VARS])
|
||||
* · Termux 该有的键一定存在,且**以我们的值为准**(覆盖)
|
||||
*
|
||||
* @return 可以直接喂给 `ProcessBuilder` 的 map
|
||||
*/
|
||||
fun childEnvMap(context: Context): MutableMap<String, String> {
|
||||
val out = LinkedHashMap<String, String>()
|
||||
// ① 父进程环境减去宿主 Python 变量
|
||||
try {
|
||||
for ((k, v) in System.getenv()) {
|
||||
if (k in HOST_PYTHON_VARS) continue
|
||||
out[k] = v
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// 拿不到父环境不是致命问题,继续用我们自己的那一套
|
||||
}
|
||||
// ② 再把 Termux 该有的整体覆盖上去(这一步保证键一定存在)
|
||||
for ((k, v) in environment(context)) {
|
||||
if (k in HOST_PYTHON_VARS) continue
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 是不是软链。失败一律当成"不是"(宁可漏判也不要因为一个坏链接中断整趟遍历)。
|
||||
*
|
||||
@@ -1377,9 +1771,37 @@ object TermuxInstaller {
|
||||
// `filesDir` 本身就带一个 `files`。有这条链,那种"看着别扭但
|
||||
// 确实是这么来的"路径也能解析到正确位置。
|
||||
val map = listOf(
|
||||
// ★★★ 顺序有讲究,**必须 `files/home` 排在最前面**:
|
||||
//
|
||||
// `files` 这条会被接成软链(下一条),一旦它成了软链,
|
||||
// 再想往里建 `files/home` 就会被解析到**目标目录**去
|
||||
// (也就是真实 home),链接根本建不到 we 想要的位置。
|
||||
// 所以凡是"建在 `files` 里面"的条目,都得排在 `files` 前面。
|
||||
//
|
||||
// `files/home` 为什么需要:bash 找 `$HOME/.bashrc` 用的是
|
||||
// `/data/data/com.termux/files/home`(形状 A,多一层 files)。
|
||||
// 少了这条链它会掉进**真 Termux 的 home**,每开一个终端就报
|
||||
// bash: /data/data/com.termux/files/usr/etc/bash.bashrc: Permission denied
|
||||
"files/home" to "../home",
|
||||
/**
|
||||
* ★★ `/tmp` 也要能写。
|
||||
*
|
||||
* 症状:`touch /tmp/xxx` → `No such file or directory`
|
||||
* (或 Permission denied),于是所有"往 /tmp 写中间文件"的
|
||||
* 脚本全废 —— root 下根本没有 `/tmp` 这个目录。
|
||||
*
|
||||
* 为什么建 `files/usr/tmp` 就能修好:Termux 的二进制里
|
||||
* **编译死的是 `$PREFIX/tmp`**,也就是
|
||||
* /data/data/com.termux/files/usr/tmp
|
||||
* 而 `files/usr` 已经被接成我们的 prefix 了,所以这条链
|
||||
* 本来就该通。**实测不通**的原因是:`linkLegacyPrefix`
|
||||
* 只在"目标不存在、要新建"时才建链,而 `$PREFIX/tmp` 里
|
||||
* 有东西(apt 的临时文件),于是被那条"真目录,不动"跳过了。
|
||||
*/
|
||||
"files/usr/tmp" to "tmp",
|
||||
// 形状 A:把 `files/usr` 折回 prefix 自己
|
||||
"files/usr" to ".",
|
||||
// ★ 第二条兜底:一次文本替换会产生的 `files/files/usr` 形状
|
||||
// ★ 第三条兜底:一次文本替换会产生的 `files/files/usr` 形状
|
||||
"files" to "..",
|
||||
// prefix 根下的标准目录(形状 B)
|
||||
"bin" to "bin",
|
||||
@@ -1441,6 +1863,9 @@ object TermuxInstaller {
|
||||
// ★ 每种形状都要有代表:
|
||||
// `files/usr/bin` 走形状 A(dpkg 解包的落点)
|
||||
// `share` 走形状 B(glib 读 schema 的地方)
|
||||
// `files/home` bash 读 `$HOME/.bashrc` 的地方 ——
|
||||
// 这条少了不会报错,只是**每开一次终端**
|
||||
// 都往真 Termux 的 home 里撞权限
|
||||
val probes = listOf(
|
||||
"files/usr/bin" to "bin",
|
||||
"files/usr/lib" to "lib",
|
||||
@@ -1453,6 +1878,7 @@ object TermuxInstaller {
|
||||
"var/lib/dpkg" to "var/lib/dpkg",
|
||||
"tmp" to "tmp",
|
||||
"home" to "../home",
|
||||
"files/home" to "../home",
|
||||
)
|
||||
val wrong = probes.filterNot { (l, r) ->
|
||||
val a = runCatching { File(File(legacyRoot, l).absolutePath).canonicalPath }.getOrNull()
|
||||
@@ -1489,6 +1915,89 @@ object TermuxInstaller {
|
||||
return dir.isDirectory
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 检测"真 Termux 冲突" —— 这是一个**无解的硬冲突**,得让用户知道。
|
||||
*
|
||||
* ## 现象
|
||||
*
|
||||
* 装了真 Termux(`com.termux`)的设备上,`pkg install` 会直接失败:
|
||||
*
|
||||
* dpkg: error: error opening configuration directory
|
||||
* "/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
|
||||
* E: Sub-process <prefix>/bin/dpkg returned an error code (2)
|
||||
*
|
||||
* ★ 而**没装真 Termux 的设备上一切正常** —— 这就是为什么模拟器
|
||||
* (我们一开始没装 Termux)一直是好的,只在用户手机上炸。
|
||||
*
|
||||
* ## 为什么绕不过去(这些我都实测过,不是推测)
|
||||
*
|
||||
* dpkg 找配置目录用的是**编译死的绝对路径**
|
||||
* (Termux 构建 dpkg 时 `$PREFIX/etc/dpkg` = `/data/data/com.termux/files/usr/etc/dpkg`),
|
||||
* 而它对"那个目录打不开"的处理分两种:
|
||||
*
|
||||
* 目录不存在(ENOENT)→ **静默跳过**,用默认值继续 ← 只有我们时
|
||||
* 存在但打不开(EACCES)→ **致命报错** ← 装了真 Termux 时
|
||||
*
|
||||
* (Termux 自己会建这个目录,所以只要真 Termux 跑过一次就存在了。)
|
||||
*
|
||||
* 试过并**全部失败**的办法:
|
||||
*
|
||||
* · `--root=` / `DPKG_ROOT` / `--instdir=` —— dpkg **在解析命令行之前**
|
||||
* 就读配置了(dpkg 维护者原话:*"the config files are read before
|
||||
* the options are parsed"*),所以这些参数一律管不到配置目录。
|
||||
* · 环境变量指定配置目录 —— dpkg **根本没有**这个变量
|
||||
* (`strings dpkg.real | grep '^DPKG_'` 里没有 CONFDIR 之类)。
|
||||
* · `LD_PRELOAD=libtermux-exec.so` —— 它**只拦 `execve`**
|
||||
* (它自己的字符串是 `TERMUX_EXEC__EXECVE_CALL__INTERCEPT`),
|
||||
* 不碰 `opendir`,所以救不了。
|
||||
* · 在自己 prefix 里造一条 `/data/data/com.termux/...` ——
|
||||
* 那是**绝对路径**,内核永远走不到我们的目录里。
|
||||
* (沙箱路径对"带 `--root` / 拼前缀"的访问有效,对这个无效。)
|
||||
* · `unshare -m` + `mount --bind` 把那条路遮掉 ——
|
||||
* Android 应用没有 `CAP_SYS_ADMIN`,`unshare: Operation not permitted`。
|
||||
* · 改 dpkg 二进制里的字节 —— 长度不等(21 → 30 字节),
|
||||
* 原地替换会废掉 ELF 内部偏移(`scripts/verify-elf-patch.py` 验过)。
|
||||
* · 从 apt 源装新版 dpkg —— 同一个 `$PREFIX` 构建,路径一模一样。
|
||||
*
|
||||
* ## 所以能做的只有"说清楚 + 给一条出路"
|
||||
*
|
||||
* 界面上明确告诉用户:**内置的 Termux 和真 Termux App 不能同时用**。
|
||||
* 这不是我们的 bug,是 Android 的沙箱规则。
|
||||
* (内置的那套是自包含的,卸载真 Termux 不会丢任何东西。)
|
||||
*
|
||||
* @return true = 检测到真 Termux 而且它挡住了 dpkg
|
||||
*/
|
||||
fun hasRealTermuxConflict(context: Context): Boolean {
|
||||
val real = File("/data/data/com.termux")
|
||||
// ① 真 Termux 得装着。
|
||||
// ★ 判断"这个绝对路径存不存在"**不能用 `File.exists()`** ——
|
||||
// 中间某一层没权限遍历时它返回 **false**(不是抛异常),
|
||||
// 于是"存在但我们读不了"会被误判成"不存在"。
|
||||
// 这正是我第一次写错的地方(分支永远进不去,横幅不出现)。
|
||||
// 用 NIO 的 `notExists` 才是准的:只有 **ENOENT** 才算不存在,
|
||||
// EACCES 会抛出来 —— 那恰好是我们要的信号。
|
||||
val exists = try {
|
||||
!java.nio.file.Files.notExists(real.toPath())
|
||||
} catch (_: Throwable) {
|
||||
true // 抛异常 = 权限不足 = 它确实在那儿
|
||||
}
|
||||
if (!exists) return false
|
||||
|
||||
// ② 它得**挡着我们**:真实表现是 dpkg 连 `--version` 都跑不动(rc != 0)。
|
||||
// ★ 不再去 list() 那个配置目录 —— 上面的 exists 陷阱已经踩过一次,
|
||||
// 「能不能列出来」在多层没权限时同样不可靠。
|
||||
// 直接看**最终后果**:dpkg 能不能跑。这个判据不会骗人。
|
||||
return try {
|
||||
val p = ProcessBuilder(
|
||||
File(prefix(context), "bin/dpkg").absolutePath, "--version",
|
||||
).redirectErrorStream(true).start()
|
||||
p.inputStream.bufferedReader().readText()
|
||||
p.waitFor() != 0
|
||||
} catch (_: Throwable) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 内容一样就不写盘。
|
||||
*
|
||||
|
||||
@@ -196,4 +196,100 @@ object TermuxMirror {
|
||||
)
|
||||
return lines.size
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 当前源要是**用不了**,自动换一个能用的。
|
||||
*
|
||||
* ## 为什么需要
|
||||
*
|
||||
* 用户实测撞到的(原话):
|
||||
*
|
||||
* E: Failed to fetch .../binary-x86_64/Packages.bz2
|
||||
* File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
* E: Some index files failed to download. They have been ignored,
|
||||
* or old ones used instead.
|
||||
*
|
||||
* 这是**镜像正在同步**时的典型症状:`InRelease` 已经是新的了,
|
||||
* 但 `Packages.bz2` 还是旧的,apt 一对哈希就拒绝。用户侧完全没辙 ——
|
||||
* 「源」按钮他按了也没用(换到的还是同一个坏源,或者他根本不知道该换)。
|
||||
*
|
||||
* 而我们**默认给的就是清华**([MIRRORS] 第一个)。镜像偶尔同步是常态,
|
||||
* 所以这不是"清华不好",是"任何单一默认值都会偶尔把用户卡死"。
|
||||
*
|
||||
* ## 做法
|
||||
*
|
||||
* 真跑一次 `apt-get update` 当探测 —— **不自己写校验逻辑**:
|
||||
*
|
||||
* · apt 的校验比我们严(哈希、时间戳、架构都对),复用它最准
|
||||
* · 反正换源之后本来就要 update,探测这一步不白花
|
||||
* · 自己写"拉 InRelease 看看"那种轻量探针**测不出这个 bug** ——
|
||||
* InRelease 恰恰是好的那一半
|
||||
*
|
||||
* 当前源能用就**什么都不做**(不打扰用户的选择)。
|
||||
* 用不了才按 [MIRRORS] 顺序往下试,换成功就记住(写 sources.list + pkg 那套)。
|
||||
*
|
||||
* @param onSwitched 换成功时回调(给界面提示用),参数是新的源
|
||||
* @return 最终可用的源;全都不可用时返回 null
|
||||
*/
|
||||
fun autoPickIfBroken(context: Context, onSwitched: ((Mirror) -> Unit)? = null): Mirror? {
|
||||
val current = current(context) ?: MIRRORS.first()
|
||||
|
||||
if (probe(context, current)) return current
|
||||
|
||||
android.util.Log.i("DoubaoTermux", "源 ${current.name} 探测失败,开始找能用的")
|
||||
for (candidate in MIRRORS) {
|
||||
if (candidate.id == current.id) continue
|
||||
if (!probe(context, candidate)) continue
|
||||
val n = set(context, candidate)
|
||||
android.util.Log.i("DoubaoTermux", "已自动切到 ${candidate.name}($n 条)")
|
||||
onSwitched?.invoke(candidate)
|
||||
return candidate
|
||||
}
|
||||
android.util.Log.w("DoubaoTermux", "所有源都探测失败,保持 ${current.name}")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测一个源能不能用:**临时**写进 sources.list 跑一次 `apt-get update`,
|
||||
* 不管成败都把原来的 sources.list 还原回去。
|
||||
*
|
||||
* ★ 必须还原:探测失败时若留着半个写入状态,用户会看到"源莫名其妙变了"。
|
||||
*/
|
||||
private fun probe(context: Context, mirror: Mirror): Boolean {
|
||||
val file = sourcesFile(context)
|
||||
val backup = try {
|
||||
if (file.exists()) file.readText() else null
|
||||
} catch (_: Throwable) {
|
||||
null
|
||||
}
|
||||
|
||||
return try {
|
||||
set(context, mirror)
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val pb = ProcessBuilder("$prefix/bin/apt-get", "update")
|
||||
.directory(TermuxInstaller.home(context))
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
// 输出必须读掉,否则管道写满会把子进程卡死(apt 输出很多)
|
||||
val sink = Thread { proc.inputStream.readBytes(); proc.errorStream.readBytes() }
|
||||
sink.isDaemon = true
|
||||
sink.start()
|
||||
val ok = proc.waitFor(PROBE_TIMEOUT_S, java.util.concurrent.TimeUnit.SECONDS) &&
|
||||
proc.exitValue() == 0
|
||||
if (!ok) proc.destroyForcibly()
|
||||
ok
|
||||
} catch (t: Throwable) {
|
||||
android.util.Log.i("DoubaoTermux", "探测 ${mirror.name} 抛异常:${t.message}")
|
||||
false
|
||||
} finally {
|
||||
try {
|
||||
if (backup != null) file.writeText(backup) else file.delete()
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测超时。apt 卡住时不能把用户等死 */
|
||||
private const val PROBE_TIMEOUT_S = 45L
|
||||
}
|
||||
|
||||
@@ -39,10 +39,21 @@ object TermuxShell {
|
||||
return try {
|
||||
// 用 -c 而不是 -lc:登录式会去 source 编译期写死的 /etc/profile(那是别的包的路径),
|
||||
// 每次都在 stderr 里冒一条 Permission denied。rc 该设的东西我们在环境变量里都设好了。
|
||||
val proc = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
//
|
||||
// ★★★ 用 `childEnvMap()` 而不是 `environment()`:ProcessBuilder 起的是
|
||||
// 子进程,**默认继承整个 App 进程的环境**,而里面带着 Chaquopy 注入的
|
||||
// `PYTHONPATH`(指向 3.13 编的 .imy)。不清掉的话 Termux 的 python 3.14
|
||||
// 一起来就读到 3.13 的 encodings/__init__.pyc,魔数不符直接核心崩溃:
|
||||
// Fatal Python error: Failed to import encodings module
|
||||
// 详见 TermuxInstaller.childEnv 的注释。
|
||||
//
|
||||
// ★ `environment().putAll(...)` 这种写法是**追加**,删不掉已有的键 ——
|
||||
// 所以必须显式摘掉那几个变量(childEnvMap 做了这件事)。
|
||||
val pb = ProcessBuilder("${prefix.absolutePath}/bin/bash", "-c", command)
|
||||
.directory(workdir)
|
||||
.apply { environment().putAll(TermuxInstaller.environment(context)) }
|
||||
.start()
|
||||
pb.environment().clear()
|
||||
pb.environment().putAll(TermuxInstaller.childEnvMap(context))
|
||||
val proc = pb.start()
|
||||
|
||||
// 读流要放到线程里,否则大输出会把管道塞满导致死锁
|
||||
val outBuf = StringBuilder()
|
||||
|
||||
@@ -123,7 +123,7 @@ class TermuxTerminal(private val context: Context) {
|
||||
): TerminalSession? {
|
||||
val prefix = TermuxInstaller.prefix(context).absolutePath
|
||||
val home = TermuxInstaller.home(context).absolutePath
|
||||
val baseEnv = TermuxInstaller.environment(context).map { (k, v) -> "$k=$v" }
|
||||
val baseEnv = TermuxInstaller.childEnv(context)
|
||||
|
||||
val list = candidateList()
|
||||
candidateCount = list.size
|
||||
@@ -141,7 +141,7 @@ class TermuxTerminal(private val context: Context) {
|
||||
val env = when {
|
||||
candidateIndex < 0 -> cleanEnv()
|
||||
usePreload -> baseEnv
|
||||
else -> baseEnv.filterNot { it.startsWith("LD_PRELOAD=") }
|
||||
else -> baseEnv.filterNot { s: String -> s.startsWith("LD_PRELOAD=") }
|
||||
}
|
||||
startedWith = "$shell ${args.joinToString(" ")}" + if (usePreload) "" else "(不带 preload)"
|
||||
return try {
|
||||
|
||||
466
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
466
android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt
Normal file
@@ -0,0 +1,466 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color as AndroidColor
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
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.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.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
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.Close
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
|
||||
/**
|
||||
* AI 主动弹出来的三个界面(都带进出动画)。
|
||||
*
|
||||
* 放在**导航之上**(见 AppRoot):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话在会议/设置页就看不到。
|
||||
*
|
||||
* 三个东西的动画各有讲究:
|
||||
* · HTML 界面 —— 从中心"长大"+ 淡入(像开一扇门),退出反向
|
||||
* · 选择弹窗 —— 从下方滑上来 + 淡入(手机上的惯例手势方向)
|
||||
* · 结束横幅 —— 从下方滑到**屏幕中间**停住,并且**留在那儿**(不自动消失)
|
||||
*/
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、AI 的 HTML 界面(show_ui) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiHtmlScreenOverlay(screen: AiSurface.Screen?, onClose: () -> Unit, onResult: (String) -> Unit) {
|
||||
// 关闭时 screen 会变 null,但退出动画需要内容 —— 所以留一份"最后一帧",
|
||||
// 否则 AnimatedVisibility 的 exit 阶段会渲染成空白(内容瞬间消失、容器再缩)。
|
||||
var last by remember { mutableStateOf<AiSurface.Screen?>(null) }
|
||||
LaunchedEffect(screen) { if (screen != null) last = screen }
|
||||
val shown = screen ?: last
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = screen != null,
|
||||
enter = fadeIn(tween(180)) +
|
||||
scaleIn(tween(240, easing = androidx.compose.animation.core.FastOutSlowInEasing), initialScale = 0.86f),
|
||||
exit = fadeOut(tween(150)) + scaleOut(tween(180), targetScale = 0.92f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(doubaoSurface())
|
||||
.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
shown.title.ifBlank { "AI 界面" },
|
||||
fontSize = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Box(
|
||||
Modifier.size(34.dp).clip(CircleShape).clickable { onClose() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.Close, "关闭", tint = doubaoText(), modifier = Modifier.size(20.dp))
|
||||
}
|
||||
}
|
||||
AiWebView(shown, onResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 AI 写的 HTML。
|
||||
*
|
||||
* ## 两个安全/健壮性决定
|
||||
*
|
||||
* 1. **禁 JS**:AI 写的 HTML 是"内容",不是"程序"。允许 JS 的话它会拿到
|
||||
* `@JavascriptInterface` 那个桥,等于把 App 的内部接口暴露给一段
|
||||
* 模型生成的脚本。禁掉之后照样能渲染表格/图表(纯 CSS 足够),
|
||||
* 而"可点按钮"用下面 data 属性的方式实现,不需要 JS。
|
||||
*
|
||||
* 2. **可点按钮不用 JS 实现**:给 WebView 装一个自定义 `WebViewClient`,
|
||||
* 在 `shouldOverrideUrlLoading` 里拦 `doubao://pick?value=...` 这种链接。
|
||||
* 界面里写 `<button data-doubao-result="值">` 时,注入的一小段 CSS
|
||||
* 做不到跳链接 —— 所以改成由 App 侧统一把 `data-doubao-result`
|
||||
* 换成 `<a href="doubao://pick?...">`。**这是纯字符串替换,不跑 JS。**
|
||||
*/
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Composable
|
||||
private fun AiWebView(screen: AiSurface.Screen, onResult: (String) -> Unit) {
|
||||
val html = remember(screen.id) { buildAiHtml(screen) }
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
setBackgroundColor(AndroidColor.TRANSPARENT)
|
||||
settings.javaScriptEnabled = false // 见上面第 1 条
|
||||
settings.domStorageEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
isVerticalScrollBarEnabled = true
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView?,
|
||||
url: String?,
|
||||
): Boolean {
|
||||
val u = url ?: return false
|
||||
if (u.startsWith("doubao://pick")) {
|
||||
val v = android.net.Uri.decode(
|
||||
android.net.Uri.parse(u).getQueryParameter("value") ?: "",
|
||||
)
|
||||
if (v.isNotEmpty()) onResult(v)
|
||||
return true
|
||||
}
|
||||
// 外链不在这个 WebView 里开(没有浏览器能力,也没必要)
|
||||
return true
|
||||
}
|
||||
}
|
||||
loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)
|
||||
}
|
||||
},
|
||||
update = { /* 同一个 screen.id 不重载,避免动画期间闪一下 */ },
|
||||
)
|
||||
}
|
||||
|
||||
/** 把 `data-doubao-result="x"` 变成可点的链接,再套一层骨架 */
|
||||
private fun buildAiHtml(screen: AiSurface.Screen): String {
|
||||
val body = if (screen.fullHtml) screen.html else wrapSkeleton(screen.html)
|
||||
return rewriteResultLinks(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 `<button data-doubao-result="值">文字</button>` 重写成
|
||||
* `<a class="db-btn" href="doubao://pick?value=值">文字</a>`。
|
||||
*
|
||||
* ★ 用正则做单遍替换,**不引 HTML 解析器** —— 这点转换不值得多一个依赖,
|
||||
* 而且 AI 的输出是受控的(我们自己提示词里教的写法)。
|
||||
* `button` 和 `a` 两种都收,模型有时会写成链接。
|
||||
*/
|
||||
private fun rewriteResultLinks(html: String): String {
|
||||
val pattern = Regex(
|
||||
"""<(button|a)\b([^>]*?)data-doubao-result\s*=\s*["']([^"']*)["']([^>]*?)>(.*?)</\1>""",
|
||||
setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),
|
||||
)
|
||||
return pattern.replace(html) { m ->
|
||||
val value = android.net.Uri.encode(m.groupValues[3])
|
||||
val inner = m.groupValues[5]
|
||||
"""<a class="db-btn" href="doubao://pick?value=$value">$inner</a>"""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给"片段式" HTML 套一层骨架。
|
||||
*
|
||||
* 为什么要套:模型每次都要重复写 `<meta viewport>`、暗色主题背景、字体、
|
||||
* 边距 —— 既啰嗦又容易和 App 的主题打架。套一层之后它只管写内容。
|
||||
*/
|
||||
private fun wrapSkeleton(fragment: String): String = """
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0; padding: 16px 16px 40px;
|
||||
background: #121317; color: #e8eaed;
|
||||
font: 15px/1.7 -apple-system, "PingFang SC", "Noto Sans CJK SC", sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
h1 { font-size: 21px; margin: 4px 0 12px; }
|
||||
h2 { font-size: 18px; margin: 20px 0 8px; }
|
||||
h3 { font-size: 16px; margin: 16px 0 6px; }
|
||||
p { margin: 8px 0; }
|
||||
a { color: #7cb0ff; }
|
||||
code, pre {
|
||||
background: #1d1f25; border-radius: 8px;
|
||||
font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 13px;
|
||||
}
|
||||
code { padding: 2px 5px; }
|
||||
pre { padding: 12px; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }
|
||||
th, td { border: 1px solid #2c2f36; padding: 8px 10px; text-align: left; }
|
||||
th { background: #1b1d22; font-weight: 600; }
|
||||
blockquote {
|
||||
margin: 12px 0; padding: 8px 14px;
|
||||
border-left: 3px solid #3d4450; color: #b9bdc4;
|
||||
}
|
||||
img, svg, canvas { max-width: 100%; height: auto; }
|
||||
hr { border: 0; border-top: 1px solid #2c2f36; margin: 18px 0; }
|
||||
.db-btn {
|
||||
display: inline-block; margin: 6px 8px 0 0; padding: 10px 16px;
|
||||
background: #2a2d34; color: #e8eaed !important; text-decoration: none;
|
||||
border-radius: 10px; font-size: 15px;
|
||||
}
|
||||
</style></head>
|
||||
<body>
|
||||
$fragment
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、AI 的选择弹窗(ask_user) */
|
||||
/* ==================================================================== */
|
||||
|
||||
@Composable
|
||||
fun AiDialogOverlay(dialog: AiSurface.Dialog?, onAnswer: (List<String>, Boolean) -> Unit) {
|
||||
var last by remember { mutableStateOf<AiSurface.Dialog?>(null) }
|
||||
LaunchedEffect(dialog) { if (dialog != null) last = dialog }
|
||||
val shown = dialog ?: last
|
||||
|
||||
// 多选时先把已勾的攒起来,点「确定」才回传
|
||||
val picked = remember(dialog?.id) { mutableStateListOf<String>() }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
enter = fadeIn(tween(180)),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color(0xB3000000))
|
||||
.clickable(enabled = shown?.allowCancel == true) { onAnswer(emptyList(), true) },
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = dialog != null,
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
enter = slideInVertically(tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) { it / 3 } +
|
||||
fadeIn(tween(200)) + scaleIn(tween(280), initialScale = 0.94f),
|
||||
exit = slideOutVertically(tween(200)) { it / 4 } + fadeOut(tween(150)) +
|
||||
scaleOut(tween(200), targetScale = 0.96f),
|
||||
) {
|
||||
if (shown == null) return@AnimatedVisibility
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 24.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(20.dp),
|
||||
) {
|
||||
Text("AI 想问你", fontSize = 12.sp, color = doubaoTextDim())
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
shown.question,
|
||||
fontSize = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
lineHeight = 24.sp,
|
||||
color = doubaoText(),
|
||||
)
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text("可多选", fontSize = 12.sp, color = doubaoTextDim())
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
|
||||
// 选项多时中间区域自己滚,按钮不跟着滚出去
|
||||
Column(
|
||||
Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
shown.options.forEach { opt ->
|
||||
val on = opt.value in picked
|
||||
OptionRow(
|
||||
label = opt.label,
|
||||
description = opt.description,
|
||||
selected = on,
|
||||
multiple = shown.multiple,
|
||||
onClick = {
|
||||
if (shown.multiple) {
|
||||
if (on) picked.remove(opt.value) else picked.add(opt.value)
|
||||
} else {
|
||||
onAnswer(listOf(opt.value), false)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (shown.multiple) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
if (shown.allowCancel) {
|
||||
OutlinedButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("取消") }
|
||||
}
|
||||
Button(
|
||||
onClick = { onAnswer(picked.toList(), false) },
|
||||
enabled = picked.isNotEmpty(),
|
||||
modifier = Modifier.weight(1f),
|
||||
) { Text("确定") }
|
||||
}
|
||||
} else if (shown.allowCancel) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
TextButton(
|
||||
onClick = { onAnswer(emptyList(), true) },
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) { Text("取消") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OptionRow(
|
||||
label: String,
|
||||
description: String,
|
||||
selected: Boolean,
|
||||
multiple: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
// 选中时轻微放大 —— 比单纯变色更能让人感到"点到了"
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (selected) 1.02f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "optScale",
|
||||
)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(if (selected) doubaoAccentSoft() else doubaoSurfaceAlt())
|
||||
.clickable { onClick() }
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
label,
|
||||
fontSize = 15.sp,
|
||||
color = if (selected) doubaoAccent() else doubaoText(),
|
||||
fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal,
|
||||
)
|
||||
if (description.isNotBlank()) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(description, fontSize = 12.sp, color = doubaoTextDim(), lineHeight = 17.sp)
|
||||
}
|
||||
}
|
||||
if (multiple && selected) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("✓", fontSize = 16.sp, color = doubaoAccent())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、对话被 AI 结束 —— 屏幕中间的横幅 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* ★ 用户明确要求的样子:**屏幕中间一个横幅,写着 AI 关闭的原因**。
|
||||
*
|
||||
* 几个细节:
|
||||
* · **停在屏幕正中间**(不是顶部也不是底部)—— 这是"这次对话到此为止"
|
||||
* 这种终局状态,摆在视线中心最合适
|
||||
* · **不自动消失**。它不是提示条,是状态;消失了用户就不知道
|
||||
* 为什么发不出消息了
|
||||
* · 动画:从下方滑上来 + 淡入 + 轻微放大,像"落定"
|
||||
* · 只显示在与它相关的那次对话里(调用方按 conversationId 判断)
|
||||
*/
|
||||
@Composable
|
||||
fun EndedBanner(reason: String, onNewConversation: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
AnimatedVisibility(
|
||||
visible = true,
|
||||
enter = slideInVertically(
|
||||
tween(420, easing = androidx.compose.animation.core.FastOutSlowInEasing),
|
||||
) { it } + fadeIn(tween(280)) + scaleIn(tween(420), initialScale = 0.9f),
|
||||
exit = fadeOut(tween(150)),
|
||||
) {
|
||||
Column(
|
||||
Modifier
|
||||
.padding(horizontal = 28.dp)
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.background(doubaoSurface())
|
||||
.padding(horizontal = 20.dp, vertical = 18.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.PowerSettingsNew,
|
||||
null,
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("这次对话已结束", fontSize = 16.sp, fontWeight = FontWeight.Medium, color = doubaoText())
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
reason.ifBlank { "AI 结束了这次对话" },
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Button(
|
||||
onClick = onNewConversation,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = doubaoAccent()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("开始新对话", color = Color.White) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,25 @@ fun AppRoot(
|
||||
Text(vm.hint, color = Color.White, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- AI 主动弹出来的东西 ----------------
|
||||
*
|
||||
* ★ 放在**导航之上**(这个 Box 的最后):AI 在任何页面都可能弹东西,
|
||||
* 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 ——
|
||||
* 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。
|
||||
*
|
||||
* 顺序(后写的盖在上面):选择弹窗 > HTML 界面。
|
||||
* `ask_user` 是阻塞的,用户必须先回答它,所以它压在最上面。
|
||||
*/
|
||||
AiHtmlScreenOverlay(
|
||||
screen = vm.aiScreen,
|
||||
onClose = { vm.closeAiScreen() },
|
||||
onResult = { vm.onAiScreenResult(it) },
|
||||
)
|
||||
AiDialogOverlay(
|
||||
dialog = vm.aiDialog,
|
||||
onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import com.doubao.lynxclone.data.MeetingEvent
|
||||
import com.doubao.lynxclone.data.MeetingMeta
|
||||
import com.doubao.lynxclone.data.StreamEvent
|
||||
import com.doubao.lynxclone.data.ToolTrace
|
||||
import com.doubao.lynxclone.termux.AiSurface
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -53,8 +54,86 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
/** 模型 / 思考强度面板(底部升起) */
|
||||
var modelPickerOpen by mutableStateOf(false)
|
||||
|
||||
/* -------------------- AI 主动弹出来的东西 -------------------- */
|
||||
|
||||
/**
|
||||
* AI 弹的全屏 HTML 界面(`show_ui` 工具);null 表示没有。
|
||||
*
|
||||
* 数据源是 [AiSurface](内核线程往里写),这里通过监听器同步过来 ——
|
||||
* 内核永远不直接碰 Compose。
|
||||
*/
|
||||
var aiScreen by mutableStateOf<AiSurface.Screen?>(null)
|
||||
private set
|
||||
|
||||
/** AI 弹的选择弹窗(`ask_user` 工具);null 表示没有 */
|
||||
var aiDialog by mutableStateOf<AiSurface.Dialog?>(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* 当前对话被 AI 永久结束了 —— 界面据此把输入框换成结束横幅。
|
||||
*
|
||||
* ★ 这是从内核读回来的**落盘状态**(Conversation.ended),不是本地开关。
|
||||
*/
|
||||
var conversationEnded by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** AI 给出的结束原因(屏幕中间那个横幅上写的就是它) */
|
||||
var endedReason by mutableStateOf("")
|
||||
private set
|
||||
|
||||
private var chatJob: AtomicBoolean? = null
|
||||
|
||||
init {
|
||||
// 内核线程弹界面 → 这里切主线程更新 Compose 状态
|
||||
AiSurface.subscribe { kind ->
|
||||
viewModelScope.launch {
|
||||
when (kind) {
|
||||
"screen" -> aiScreen = AiSurface.screen
|
||||
"dialog" -> aiDialog = AiSurface.dialog
|
||||
"ended" -> {
|
||||
conversationEnded = true
|
||||
refreshEndedReason()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户关掉 AI 的界面 */
|
||||
fun closeAiScreen() {
|
||||
AiSurface.closeScreen()
|
||||
aiScreen = null
|
||||
}
|
||||
|
||||
/** 用户在 AI 的界面里点了带 data-doubao-result 的按钮 */
|
||||
fun onAiScreenResult(value: String) {
|
||||
AiSurface.screenResult(value)
|
||||
showHint("已选择:$value")
|
||||
}
|
||||
|
||||
/** 用户在 AI 的选择弹窗里点了 */
|
||||
fun answerAiDialog(values: List<String>, cancelled: Boolean = false) {
|
||||
AiSurface.answerDialog(values, cancelled)
|
||||
aiDialog = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 把当前对话的"已结束"状态读回来。
|
||||
*
|
||||
* ★ 切换对话、刷新之后都要重新读一次 —— 上面那个监听器只在 AI **当场**
|
||||
* 结束对话时触发;用户重启 App 打开一个早就结束的对话,走的是这条路。
|
||||
*/
|
||||
private fun refreshEndedReason() {
|
||||
val id = activeConversationId.ifBlank { return }
|
||||
viewModelScope.launch {
|
||||
val meta = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversationMeta(id) }
|
||||
}.getOrNull()
|
||||
conversationEnded = meta?.ended == true
|
||||
endedReason = meta?.endedReason.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
val settings get() = state.settings
|
||||
val agents: List<Agent> get() = state.agents
|
||||
val activeAgent: Agent? get() = state.activeAgent
|
||||
@@ -104,6 +183,13 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
val list = runCatching { withContext(Dispatchers.IO) { client.conversation(id) } }.getOrDefault(emptyList())
|
||||
messages.clear()
|
||||
messages.addAll(list)
|
||||
// ★ 顺手读一下这次对话是不是被 AI 结束过 —— 只读 messages 是看不出来的
|
||||
// (ended 在会话对象上,不在消息里)。
|
||||
val meta = runCatching {
|
||||
withContext(Dispatchers.IO) { client.conversationMeta(id) }
|
||||
}.getOrNull()
|
||||
conversationEnded = meta?.ended == true
|
||||
endedReason = meta?.endedReason.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,9 +197,16 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
viewModelScope.launch {
|
||||
val conv = runCatching { withContext(Dispatchers.IO) { client.newConversation() } }.getOrNull()
|
||||
refresh()
|
||||
if (conv != null) openConversation(conv.id) else {
|
||||
if (conv != null) {
|
||||
// 新对话一定是没结束的 —— 不复位的话上一个对话的结束横幅会跟过来
|
||||
conversationEnded = false
|
||||
endedReason = ""
|
||||
openConversation(conv.id)
|
||||
} else {
|
||||
messages.clear()
|
||||
activeConversationId = ""
|
||||
conversationEnded = false
|
||||
endedReason = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,6 +225,12 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
val text = draft.trim()
|
||||
if (text.isEmpty() && attachments.isEmpty()) return
|
||||
if (streaming) return
|
||||
// ★ 对话被 AI 结束后就挡住 —— 界面上的输入框已经换成了横幅,
|
||||
// 但发送按钮/回车/历史入口都可能绕过界面判断,所以在**这里**再拦一道。
|
||||
if (conversationEnded) {
|
||||
showHint("这次对话已结束,请开一个新对话")
|
||||
return
|
||||
}
|
||||
|
||||
val files = attachments.toList()
|
||||
draft = ""
|
||||
@@ -464,6 +563,19 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
val json = JSONObject().put("mode", mode).put("allow", JSONArray(allow))
|
||||
saveSettings(mapOf("security" to json))
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 界面能力(show_ui / ask_user / end_conversation)开关。
|
||||
*
|
||||
* ★ 必须写成**嵌套对象** `{"enabled": true}`,不能写成布尔 ——
|
||||
* 内核 `ui_tools_enabled()` 认的就是 dict 里的 enabled。
|
||||
* 而 `patchToJson` 会把 Map 递归转成 JSONObject(见那个函数的注释:
|
||||
* 不转的话会变成字符串 `"{enabled=true}"`,内核每次读配置都抛 TypeError)。
|
||||
* 所以这里传 Map 进去,让它走那条已经修好的转换路径。
|
||||
*/
|
||||
fun saveUiTools(enabled: Boolean) {
|
||||
saveSettings(mapOf("uiTools" to mapOf("enabled" to enabled)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -309,7 +309,27 @@ fun ChatScreen(vm: AppViewModel) {
|
||||
|
||||
if (vm.attachments.isNotEmpty()) AttachmentStrip(vm)
|
||||
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
if (vm.conversationEnded) {
|
||||
/**
|
||||
* ★★ 对话被 AI 结束了 —— **屏幕中间一个横幅,写着关闭原因**。
|
||||
*
|
||||
* `Modifier.weight(1f)` 让它占掉原本给消息列表之外的全部剩余空间,
|
||||
* 横幅在**这块区域的中心**(也就是视觉上的屏幕中下部)。
|
||||
* 要的是"正中间",但顶部还有标题栏、下面还有输入法安全区,
|
||||
* 放在这块剩余区域的中心在观感上才是居中的。
|
||||
*
|
||||
* 输入框在此处**整个不渲染** —— 用户看到的就是"这儿没得输了",
|
||||
* 而不是一个点了没反应的框。
|
||||
*/
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
EndedBanner(
|
||||
reason = vm.endedReason,
|
||||
onNewConversation = { vm.newTopic() },
|
||||
)
|
||||
}
|
||||
} else {
|
||||
InputBar(vm, onPickFile, onMic, speech)
|
||||
}
|
||||
}
|
||||
|
||||
val thinkingVisible = vm.thinkingIndex in vm.messages.indices
|
||||
|
||||
@@ -77,6 +77,22 @@ fun doubaoCard() = if (isDark()) Color(0xFF1F232A) else Doubao.CardBg
|
||||
@Composable
|
||||
fun doubaoHeroRing() = if (isDark()) Doubao.DarkHeroRing else Doubao.HeroRing
|
||||
|
||||
/** 主色(AI 界面/弹窗里强调"选中"用) */
|
||||
@Composable
|
||||
fun doubaoAccent() = if (isDark()) Color(0xFF6EA8FF) else Doubao.Blue
|
||||
|
||||
/** 主色的浅底(选中项的背景) */
|
||||
@Composable
|
||||
fun doubaoAccentSoft() = if (isDark()) Color(0xFF1B2A44) else Color(0xFFEAF1FF)
|
||||
|
||||
/** 比 surface 稍亮/稍暗一档的容器底色(弹窗里的选项行) */
|
||||
@Composable
|
||||
fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg
|
||||
|
||||
/** 三级文字色(比 secondary 更淡,用于说明小字) */
|
||||
@Composable
|
||||
fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary
|
||||
|
||||
/* ------------------------------ 动画 ------------------------------ */
|
||||
|
||||
/** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */
|
||||
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -72,6 +73,12 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
var mode by remember(saved.mode, saved.allow) { mutableStateOf(saved.mode) }
|
||||
var allow by remember(saved.mode, saved.allow) { mutableStateOf(saved.allow.toSet()) }
|
||||
|
||||
// AI 界面能力的开关。改一下立刻存 —— 这个开关不需要"应用"按钮,
|
||||
// 用户拨完就想生效(跟下面的权限白名单不一样,那个要挑一堆再一起提交)。
|
||||
var uiToolsOn by remember(vm.settings.uiToolsEnabled) {
|
||||
mutableStateOf(vm.settings.uiToolsEnabled)
|
||||
}
|
||||
|
||||
var runTarget by remember { mutableStateOf<PythonTool?>(null) }
|
||||
val toolArgs = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
val toolResults = remember { mutableStateOf<Map<String, String>>(emptyMap()) }
|
||||
@@ -105,6 +112,50 @@ fun SkillsScreen(vm: AppViewModel) {
|
||||
) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
|
||||
/* ============ ⓪ AI 界面能力(show_ui / ask_user / end_conversation)============
|
||||
*
|
||||
* 为什么单独一个卡片、而且默认关:这三个工具会让 AI **主动往用户脸上
|
||||
* 弹东西**(HTML 界面、选择弹窗),甚至**把对话封掉** ——
|
||||
* 属于"打扰性"能力,不该装好就默认打开。
|
||||
*/
|
||||
SettingsCard("AI 界面能力") {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("允许 AI 弹出界面和弹窗", fontSize = 15.sp, color = doubaoText())
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
"打开后 AI 才能用这三个工具。关掉时它们对模型完全隐藏。",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
lineHeight = 17.sp,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = uiToolsOn,
|
||||
onCheckedChange = {
|
||||
uiToolsOn = it
|
||||
vm.saveUiTools(it)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(10.dp))
|
||||
FormHint(
|
||||
"· show_ui —— AI 自己写 HTML 弹一个全屏界面(图表、卡片、对比表)\n" +
|
||||
"· ask_user —— 弹一个选择框,等用户选完再继续(最多 120 秒)\n" +
|
||||
"· end_conversation —— AI 永久结束这次对话。屏幕中间会出现一条" +
|
||||
"写着原因的横幅,之后要开新对话才能继续",
|
||||
)
|
||||
if (!uiToolsOn) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"当前:关闭(模型看不到这三个工具)",
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== ① 工具权限 ==================== */
|
||||
SettingsCard("工具权限") {
|
||||
SegmentedOptions(
|
||||
|
||||
@@ -24,6 +24,9 @@ import androidx.core.view.doOnLayout
|
||||
import com.doubao.lynxclone.termux.TermuxInstaller
|
||||
import com.doubao.lynxclone.termux.TermuxTerminal
|
||||
import com.termux.view.TerminalView
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
@@ -97,6 +100,23 @@ fun TerminalScreen(
|
||||
var showResetConfirm by remember { mutableStateOf(false) }
|
||||
var resetting by remember { mutableStateOf(false) }
|
||||
var resetMsg by remember { mutableStateOf("") }
|
||||
|
||||
/**
|
||||
* 真 Termux 冲突(见下面横幅的注释)。
|
||||
*
|
||||
* ★ 为什么放在 `LaunchedEffect` 里而不是直接在组合里算:
|
||||
* 这个判断要**起一个进程跑 `dpkg --version`**,直接在组合里做会
|
||||
* 每帧跑一次。它是 IO,必须挪到副作用里,而且只查一次。
|
||||
*/
|
||||
var realTermuxConflict by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(termuxReady) {
|
||||
if (termuxReady) {
|
||||
realTermuxConflict = withContext(Dispatchers.IO) {
|
||||
runCatching { TermuxInstaller.hasRealTermuxConflict(context) }
|
||||
.getOrDefault(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
val onSessionExit = {
|
||||
val quick = startedAt > 0 && System.currentTimeMillis() - startedAt < 900
|
||||
if (quick) {
|
||||
@@ -223,6 +243,36 @@ fun TerminalScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ★★★ 真 Termux 的检测结果 —— v2.0.33 起**不再提示卸载**。
|
||||
*
|
||||
* 以前这里是一条红色横幅,让用户去卸载真 Termux,因为
|
||||
* Termux 仓库里的 dpkg 有个**编译死的配置目录**:
|
||||
*
|
||||
* dpkg: error: error opening configuration directory
|
||||
* "/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d": Permission denied
|
||||
*
|
||||
* 那个目录"不存在"dpkg 会跳过、"存在但打不开"就直接死,
|
||||
* 而两个 App 同时装着就必然是后者 —— 从应用这侧无解。
|
||||
*
|
||||
* **现在从根上修掉了**:装的是我们自编的 dpkg,配置目录改成
|
||||
* 运行时从 `/proc/self/exe` 反推,指向自己所在的前缀。
|
||||
* 所以真 Termux 在不在场都无所谓,横幅也就没必要了。
|
||||
*
|
||||
* 配方见 `android/termux-dpkg/README.md`。
|
||||
* 安装逻辑在 `TermuxInstaller.installOwnDpkg`。
|
||||
*
|
||||
* ★ 这里不再渲染任何界面 —— 只在日志里记一笔,方便排查。
|
||||
* 保留这个变量和检测(`hasRealTermuxConflict`)是因为
|
||||
* 万一自编 dpkg 没装成功(比如 jniLibs 里那份坏了),
|
||||
* 日志里能看到"真 Termux 在场",好定位。
|
||||
*/
|
||||
LaunchedEffect(termuxReady, realTermuxConflict) {
|
||||
if (termuxReady && realTermuxConflict) {
|
||||
Log.i("DoubaoTerminal", "检测到真 Termux 在场 —— v2.0.33 起不影响使用(自编 dpkg)")
|
||||
}
|
||||
}
|
||||
|
||||
// ★ pty 失败要**明说**,别让用户以为"这软件就只有命令框"
|
||||
if (termuxReady && ptyFailed) {
|
||||
Surface(color = Color(0xFF3A2F10), modifier = Modifier.fillMaxWidth()) {
|
||||
|
||||
BIN
android/app/src/main/jniLibs/arm64-v8a/libdoubao-dpkg.so
Normal file
BIN
android/app/src/main/jniLibs/arm64-v8a/libdoubao-dpkg.so
Normal file
Binary file not shown.
BIN
android/app/src/main/jniLibs/x86_64/libdoubao-dpkg.so
Normal file
BIN
android/app/src/main/jniLibs/x86_64/libdoubao-dpkg.so
Normal file
Binary file not shown.
@@ -42,8 +42,29 @@ def _max_rounds(settings: dict) -> int:
|
||||
return max(1, min(12, value))
|
||||
|
||||
|
||||
# 界面能力的用法说明。**只在开关打开时**追加到系统提示词(见 run_agent)。
|
||||
#
|
||||
# ★ 为什么需要这段:`show_ui` / `ask_user` 这类工具的 description 里已经写了
|
||||
# 怎么用,但模型**不会主动想到去用** —— 它默认走"用文字回答"这条路。
|
||||
# 加一段"什么时候该用",它才会在合适的时候弹界面/弹窗,而不是把一张宽表
|
||||
# 硬塞进 markdown。
|
||||
#
|
||||
# ★ 也不能写得太热情:这三个工具会打断用户,滥用比不用更烦。
|
||||
# 所以措辞是"确实用文字说不清时才用"。
|
||||
UI_TOOLS_HINT = '\n'.join([
|
||||
'界面能力(用户已打开):',
|
||||
'8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:',
|
||||
' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。',
|
||||
'9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。',
|
||||
' 它会**等你选完**再继续,所以你不用在正文里再问一遍。',
|
||||
'10. 事情真的办完、且用户说了不用继续时,可以 end_conversation 结束这次对话。',
|
||||
' **调用前必须先在正文里跟用户说明**,别默默封笔。拿不准就别用。',
|
||||
])
|
||||
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||||
should_stop: Optional[Callable[[], bool]] = None,
|
||||
conversation_id: str = '') -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
@@ -52,6 +73,7 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
conversation_id 当前对话 id —— 界面工具(尤其 end_conversation)要用它
|
||||
"""
|
||||
# ★ 传 agent 进去:智能体自己配了 provider/model/baseUrl 就用它的,
|
||||
# 留空才继承全局。这样"代码搭子走 DeepSeek、其它走方舟"只改那一个智能体。
|
||||
@@ -61,6 +83,16 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||||
#
|
||||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||||
# 会存进用户的 settings.json;而开关可能是关的 —— 关着的时候提示词里
|
||||
# 还在教模型"你可以用 show_ui",它就会去调,然后收到"工具已关闭"。
|
||||
# 按开关动态追加,两边永远一致。
|
||||
#
|
||||
# ★ 用追加而不是替换:用户可能自己改过 systemPrompt,不能覆盖他写的东西。
|
||||
if tools_runtime.ui_tools_enabled(settings):
|
||||
system_prompt = (system_prompt + '\n\n' + UI_TOOLS_HINT).strip()
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
@@ -148,10 +180,20 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
for tc in tool_calls:
|
||||
tool_call_count += 1
|
||||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||||
# ★ 界面工具(show_ui / ask_user / end_conversation)要拿到"当前是哪次对话",
|
||||
# 而工具签名只有 run(args)。所以在这里把上下文放进 thread-local,
|
||||
# 执行完立刻清掉 —— HTTP 是每请求一线程,thread-local 天然隔离。
|
||||
tools_runtime.push_context(
|
||||
conversationId=conversation_id,
|
||||
agentId=(agent or {}).get('id') or '',
|
||||
toolName=tc.get('name') or '',
|
||||
)
|
||||
try:
|
||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
if result.get('ok'):
|
||||
raw = result.get('result')
|
||||
payload = truncate('(无输出)' if raw is None else raw)
|
||||
|
||||
@@ -935,9 +935,24 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(400, {'error': '缺少 name'})
|
||||
return True
|
||||
try:
|
||||
# 手动试运行不受安全模式限制(是用户自己点的),但仍要能报错
|
||||
result = tools_runtime.execute_tool(name, body.get('args') or {},
|
||||
{'security': {'mode': 'open'}})
|
||||
# ★ 手动试运行**不受安全模式限制**(是用户自己在「技能」页点的),
|
||||
# 但仍要能报错。所以 mode 强制 open。
|
||||
#
|
||||
# ★★ 但**不能**只传一个空壳 settings(以前就是 {'security':...}):
|
||||
# 界面工具(show_ui/ask_user/end_conversation)的开关也在 settings 里,
|
||||
# 空壳会让它们**永远被第二道拦截挡住** —— 用户在技能页点"试运行",
|
||||
# 明明开关是开的,却收到"已关闭"。这个错会让人以为是开关没生效。
|
||||
# 所以拿真实设置、只覆盖 security。
|
||||
live = store.read_settings() or {}
|
||||
settings = {**live, 'security': {'mode': 'open', 'allow': []}}
|
||||
tools_runtime.push_context(
|
||||
conversationId=str(body.get('conversationId') or ''),
|
||||
toolName=name,
|
||||
)
|
||||
try:
|
||||
result = tools_runtime.execute_tool(name, body.get('args') or {}, settings)
|
||||
finally:
|
||||
tools_runtime.clear_context()
|
||||
self.send_json(200, result)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.send_json(500, {'ok': False, 'error': str(exc)})
|
||||
@@ -1402,6 +1417,9 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
messages=[*history, {'role': 'user', 'content': user_content}],
|
||||
emit=emit,
|
||||
should_stop=cancelled,
|
||||
# ★ 界面工具要靠它知道"结束哪次对话"。不传的话
|
||||
# end_conversation 会明确报错(而不是假装成功)。
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
|
||||
@@ -15,6 +15,13 @@ DEFAULT_SYSTEM_PROMPT = '\n'.join(
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
'',
|
||||
'关于用户发来的文件(附件):',
|
||||
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
|
||||
' **那个路径是文件在手机上的真实落盘位置**,可以直接用 shell 或 python 工具打开它 ——',
|
||||
' 不要猜路径,也不要说"我拿不到文件"。',
|
||||
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
|
||||
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
|
||||
]
|
||||
)
|
||||
|
||||
@@ -173,6 +180,12 @@ DEFAULT_SETTINGS = {
|
||||
'toolsDir': '',
|
||||
'systemPrompt': DEFAULT_SYSTEM_PROMPT,
|
||||
'tools': {'python': True, 'mcp': True},
|
||||
# 界面工具:让 AI 主动弹 HTML 界面 / 弹选择框 / 永久结束对话
|
||||
# (show_ui / ask_user / end_conversation)。
|
||||
#
|
||||
# ★ 默认**关**。这三个是"打扰性"能力 —— AI 会主动往用户脸上弹东西、
|
||||
# 甚至把对话封掉,不该装好就默认打开。想用就在「技能」页打开。
|
||||
'uiTools': {'enabled': False},
|
||||
# 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key;
|
||||
# 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。
|
||||
'speech': {
|
||||
|
||||
@@ -20,6 +20,8 @@ import threading
|
||||
# 内置工具(构建时由 scripts/build-apk.mjs 拷进 Python 源集根目录)
|
||||
BUNDLED_TOOL_FILES = [
|
||||
'_protocol.py',
|
||||
# 界面工具三件套共用的安卓桥 + 上下文读取(被下面三个 import,必须先播种)
|
||||
'_ui_bridge.py',
|
||||
'calc.py',
|
||||
'now.py',
|
||||
'weather.py',
|
||||
@@ -27,6 +29,10 @@ BUNDLED_TOOL_FILES = [
|
||||
'web_fetch.py',
|
||||
'shell.py',
|
||||
'python_run.py',
|
||||
# AI 主动弹界面 / 弹选择框 / 永久结束对话(默认关,见 settings.uiTools)
|
||||
'show_ui.py',
|
||||
'ask_user.py',
|
||||
'end_conversation.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
|
||||
@@ -35,6 +35,68 @@ _loaded_modules: dict = {}
|
||||
TOOL_TIMEOUT_S = 60
|
||||
BUILTIN_FILE_LABEL = '<内置>'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 界面工具的开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 这三个工具由 AI 主动驱动界面,属于"会打扰用户"的能力,所以**默认关**,
|
||||
# 用户要在「技能」页显式打开。名字要和 tools/ 下的文件名一致。
|
||||
UI_TOOLS = ('show_ui', 'ask_user', 'end_conversation')
|
||||
|
||||
# 开关在 settings 里的位置。用嵌套 dict 而不是散落的顶层键,
|
||||
# 以后加界面工具不必再动 settings 的形状。
|
||||
UI_TOOL_SETTINGS_KEY = 'uiTools'
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 当前调用上下文(线程局部)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 为什么需要它:工具要拿到"当前是哪次对话"才能结束对话,但工具签名是
|
||||
# run(args) —— 只有模型给的参数,没有对话信息。
|
||||
#
|
||||
# 已有先例是往 settings 里塞 `nodeTools`(会议节点工具),但那是**工具定义**,
|
||||
# 不是**运行时上下文**;上下文每轮都在变,塞进 settings 会和"设置"的语义混在一起。
|
||||
#
|
||||
# 所以单独开一个 thread-local:agent_loop 在执行工具前 push,
|
||||
# 执行完 pop。HTTP 是每请求一线程,thread-local 天然隔离,不会串。
|
||||
_ctx = threading.local()
|
||||
|
||||
|
||||
def push_context(**kw) -> None:
|
||||
"""进入一次工具调用(agent_loop 在 execute_tool 前调用)"""
|
||||
_ctx.value = dict(kw)
|
||||
|
||||
|
||||
def clear_context() -> None:
|
||||
_ctx.value = None
|
||||
|
||||
|
||||
def current_context() -> dict:
|
||||
"""当前工具调用的上下文;不在调用中时返回空 dict"""
|
||||
return dict(getattr(_ctx, 'value', None) or {})
|
||||
|
||||
|
||||
def ui_tools_enabled(settings: dict) -> bool:
|
||||
"""
|
||||
界面工具开了没有。
|
||||
|
||||
★ 默认 **False**:这三个工具会让 AI 主动弹界面/弹窗、甚至结束对话,
|
||||
对用户是"打扰性"能力,不该装好就默认打开。
|
||||
"""
|
||||
box = (settings or {}).get(UI_TOOL_SETTINGS_KEY)
|
||||
if isinstance(box, dict):
|
||||
return box.get('enabled') is True
|
||||
if isinstance(box, bool):
|
||||
return box
|
||||
return False
|
||||
|
||||
|
||||
def filter_ui_tools(specs: list, settings: dict) -> list:
|
||||
"""开关关着时,把界面工具从工具表里摘掉(模型根本看不到,也就不会调)。"""
|
||||
if ui_tools_enabled(settings):
|
||||
return specs
|
||||
return [s for s in specs if s.get('name') not in UI_TOOLS]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 目录与文件
|
||||
@@ -235,9 +297,27 @@ def run_python_tool(name: str, args: dict) -> dict:
|
||||
runner = getattr(module, 'run')
|
||||
|
||||
payload = args if isinstance(args, dict) else {}
|
||||
# ★★★ **先抓住当前线程的上下文**,因为 run_with_timeout 会在**另一个线程**里
|
||||
# 跑工具,而 threading.local() 是**不跨线程继承**的 —— 不搬过去的话,
|
||||
# 工作线程里 current_context() 永远是空的。
|
||||
#
|
||||
# 这个坑的表现特别隐蔽:工具照常执行(参数都对),只有"当前是哪次对话"
|
||||
# 拿不到,于是 end_conversation 报"拿不到当前对话 id"。我一开始以为是
|
||||
# app.py 没传 conversationId,查了一圈才发现是线程的问题。
|
||||
ctx = current_context()
|
||||
|
||||
def _invoke():
|
||||
if ctx:
|
||||
_ctx.value = dict(ctx)
|
||||
try:
|
||||
return runner(payload)
|
||||
finally:
|
||||
if ctx:
|
||||
_ctx.value = None
|
||||
|
||||
try:
|
||||
# 进程内执行同样加超时:工具里死循环时至少让对话能返回错误,而不是整个内核卡死
|
||||
outcome = run_with_timeout(lambda: runner(payload), TOOL_TIMEOUT_S)
|
||||
outcome = run_with_timeout(_invoke, TOOL_TIMEOUT_S)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具抛错要当成"工具失败",不是接口 500
|
||||
# 与 Node 版一致:_protocol 把异常转成 {"ok":false,"error":"ValueError: xxx"},
|
||||
# 这里在进程内直接捕获,格式保持一致(前端/模型看到的东西不变)。
|
||||
@@ -381,6 +461,8 @@ def build_tool_defs(settings: dict) -> list:
|
||||
defs = [to_openai_tool(t) for t in all_tools['python']] + list(all_tools['mcp'])
|
||||
# 会议里的 Python 节点工具并进来(受限模式也走同一个白名单)
|
||||
defs = defs + node_tool_defs(settings)
|
||||
# 界面工具(AI 弹界面 / 弹窗 / 结束对话)开关关着时对模型隐藏
|
||||
defs = filter_ui_tools(defs, settings)
|
||||
return apply_security(defs, settings)
|
||||
|
||||
|
||||
@@ -393,6 +475,15 @@ def execute_tool(name: str, args: dict, settings: dict) -> dict:
|
||||
allow = ((settings or {}).get('security') or {}).get('allow') or []
|
||||
if name not in allow:
|
||||
return {'ok': False, 'error': f'限制模式:工具 {name} 未授权'}
|
||||
# ★ 界面工具的第二道拦截:开关关着时,即使模型硬编名字也不执行。
|
||||
# (第一道是 build_tool_defs 里根本不把它给模型看。)
|
||||
# 两道都要有 —— 只藏不给看的话,用户把工具关掉之后模型仍可能
|
||||
# 从历史消息里学会这个名字再调一次。
|
||||
if name in UI_TOOLS and not ui_tools_enabled(settings):
|
||||
return {
|
||||
'ok': False,
|
||||
'error': f'界面工具「{name}」已关闭。请在「技能」页打开"AI 界面能力"后再用。',
|
||||
}
|
||||
# 会议节点工具优先(它是这次会议里用户刚写的东西,不会有重名歧义)
|
||||
if name in node_tool_names(settings):
|
||||
return run_node_tool(name, args, settings)
|
||||
|
||||
@@ -16,6 +16,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
import paths
|
||||
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
|
||||
@@ -62,6 +63,51 @@ def _safe_name(name: str) -> str:
|
||||
return cleaned[-60:]
|
||||
|
||||
|
||||
def _stamp() -> str:
|
||||
"""
|
||||
落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。
|
||||
|
||||
★ 以前这里用的是 `_ts36()`(base36 的毫秒数,形如 `m5k8xk2`)。
|
||||
它唯一的优点是不会重名,缺点是**看见文件名完全不知道是什么时候的东西** ——
|
||||
排查问题时只能一个个 `ls -la`。
|
||||
|
||||
用户明确反馈过这一点(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名
|
||||
临时件,无统一约定"。所以换成可读格式。
|
||||
|
||||
★ 秒级精度会撞名(同一秒传两个同名文件)。落盘前用 [_unique_path] 消歧,
|
||||
不靠时间戳本身保证唯一。
|
||||
"""
|
||||
return datetime.now().strftime('%Y%m%d-%H%M%S')
|
||||
|
||||
|
||||
def uploads_dir() -> str:
|
||||
"""
|
||||
附件的固定落地目录(绝对路径)。**只有这一个入口,别在别处拼路径。**
|
||||
|
||||
存在的意义是给"AI 拿到附件后想去 shell 里处理它"一个稳定约定 ——
|
||||
`attachment_payload` 会把 `path` 明明白白写进给模型的内容里,
|
||||
模型不必去猜文件在哪(bug 报告问题 5 的核心诉求)。
|
||||
"""
|
||||
return os.path.join(paths.get().uploads_dir, '').rstrip(os.sep)
|
||||
|
||||
|
||||
def _unique_path(directory: str, stamp: str, safe_name: str) -> str:
|
||||
"""
|
||||
`{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`…
|
||||
|
||||
★ 一定要保留扩展名:`report.pdf` 变成 `report-1.pdf` 而不是 `report.pdf-1` ——
|
||||
一堆工具(含我们自己的 `is_image()` / `mime_of()`)都按扩展名判断类型。
|
||||
"""
|
||||
base, ext = os.path.splitext(safe_name)
|
||||
for i in range(0, 1000):
|
||||
suffix = '' if i == 0 else f'-{i}'
|
||||
candidate = os.path.join(directory, f'{stamp}_{base}{suffix}{ext}')
|
||||
if not os.path.exists(candidate):
|
||||
return candidate
|
||||
# 极端情况:同秒同名超过 1000 个,交给随机后缀
|
||||
return os.path.join(directory, f'{stamp}_{base}-{_rand36(4)}{ext}')
|
||||
|
||||
|
||||
def _ext_of(name: str) -> str:
|
||||
return os.path.splitext(str(name or ''))[1].lower()
|
||||
|
||||
@@ -86,7 +132,8 @@ def _meta(file_path: str, name: str, copy: bool = True) -> dict:
|
||||
stored_path = file_path
|
||||
url = ''
|
||||
if copy and size <= COPY_LIMIT:
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(uploads_dir(), exist_ok=True)
|
||||
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
|
||||
with open(file_path, 'rb') as src, open(target, 'wb') as dst:
|
||||
while True:
|
||||
chunk = src.read(256 * 1024)
|
||||
@@ -118,8 +165,8 @@ def save_upload(name: str, base64_data: str) -> dict:
|
||||
raise ValueError(f'base64 解码失败:{exc}') from exc
|
||||
if len(buffer) > COPY_LIMIT:
|
||||
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
|
||||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
os.makedirs(uploads_dir(), exist_ok=True)
|
||||
target = _unique_path(uploads_dir(), _stamp(), _safe_name(name))
|
||||
with open(target, 'wb') as fh:
|
||||
fh.write(buffer)
|
||||
return {
|
||||
@@ -158,21 +205,32 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
"""
|
||||
把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。
|
||||
返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。
|
||||
|
||||
★★★ **每一条分支都会把落盘的绝对路径写进 text。**
|
||||
|
||||
这一条是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉
|
||||
模型文件落在哪,模型想去 shell / python 里处理它只能靠猜,猜错就是
|
||||
FileNotFoundError。之前只有"二进制"那一条给了路径,文本和图片都没给 ——
|
||||
而**恰恰是文本最需要**:超过 20000 字符会被截断,被截掉的那部分
|
||||
只能靠模型自己去读原文件。
|
||||
|
||||
格式统一成 `本地路径:<绝对路径>`,模型一眼能捞出来。
|
||||
"""
|
||||
out = {'text': '', 'images': []}
|
||||
item = attachment or {}
|
||||
file_path = item.get('path') or ''
|
||||
name = item.get('name') or '未知'
|
||||
if not file_path or not os.path.isfile(file_path):
|
||||
out['text'] = f"【附件 {item.get('name') or '未知'} 已丢失】"
|
||||
out['text'] = f"【附件 {name} 已丢失】"
|
||||
return out
|
||||
size = os.path.getsize(file_path)
|
||||
if is_image(item.get('name')) and size <= VISION_LIMIT:
|
||||
if is_image(name) and size <= VISION_LIMIT:
|
||||
with open(file_path, 'rb') as fh:
|
||||
b64 = base64.b64encode(fh.read()).decode('ascii')
|
||||
out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"})
|
||||
out['text'] = f"【图片 {item.get('name')}】"
|
||||
out['text'] = f"【图片 {name}({size} 字节)本地路径:{file_path}】"
|
||||
return out
|
||||
if is_text(item.get('name')) or size < 64 * 1024:
|
||||
if is_text(name) or size < 64 * 1024:
|
||||
body = ''
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
|
||||
@@ -181,7 +239,10 @@ def attachment_payload(attachment: dict) -> dict:
|
||||
print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr)
|
||||
if body:
|
||||
clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body
|
||||
out['text'] = f"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
|
||||
out['text'] = (
|
||||
f"【文件 {name}({size} 字节)本地路径:{file_path}】\n"
|
||||
f'```\n{clipped}\n```'
|
||||
)
|
||||
return out
|
||||
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
out['text'] = f"【附件 {name}({size} 字节,二进制)本地路径:{file_path}】"
|
||||
return out
|
||||
|
||||
254
android/termux-dpkg/README.md
Normal file
254
android/termux-dpkg/README.md
Normal file
@@ -0,0 +1,254 @@
|
||||
# 自编 dpkg —— 让内置 Termux 和真 Termux 能共存
|
||||
|
||||
这个目录里的东西,是为了把 **dpkg + apt 替成我们自己编的**,
|
||||
从而解决一个从根上无解的冲突。
|
||||
|
||||
---
|
||||
|
||||
## 要解决什么问题
|
||||
|
||||
内置 Termux 的二进制全部来自 Termux 官方仓库,它们是拿
|
||||
`--sysconfdir=$PREFIX/etc` 编的,而 `$PREFIX` 在**编译期**就固化成了
|
||||
|
||||
```
|
||||
/data/data/com.termux/files/usr
|
||||
```
|
||||
|
||||
于是在装了真 Termux 的手机上,我们的 `pkg install` 必死:
|
||||
|
||||
```
|
||||
dpkg: error: error opening configuration directory
|
||||
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
|
||||
E: Sub-process /data/user/0/com.doubao.lynxclone/files/usr/bin/dpkg returned an error code (2)
|
||||
```
|
||||
|
||||
**为什么绕不过去**(这些都实测过,不是推测):
|
||||
|
||||
| 试过的办法 | 为什么不行 |
|
||||
|---|---|
|
||||
| `--admindir` / `--instdir` / `--root` | 配置目录是**编译期常量**,跟 admindir 无关 |
|
||||
| `DPKG_ROOT` 等环境变量 | 上游没有这种变量(`strings dpkg \| grep '^DPKG_'` 里没有) |
|
||||
| `LD_PRELOAD=libtermux-exec.so` | 它只拦 `execve`,不碰 `opendir` |
|
||||
| 在 prefix 里造软链 | 软链只对**相对我们前缀**的路径有效;dpkg 走的是根下的绝对路径 |
|
||||
| 在 `/data/data` 下建 `com.termux` 软链 | `/data/data` 是 `drwxrwx--x system`,我们建不了 |
|
||||
| `unshare -m` + `mount --bind` | 应用没有 `CAP_SYS_ADMIN`,`Operation not permitted` |
|
||||
| 直接改二进制里的路径串 | 21 字节 → 40 字节,长度不等,改了就崩(`scripts/verify-elf-patch.py` 钉死了这条) |
|
||||
|
||||
关键细节:**dpkg 在解析命令行之前就去读配置目录**(上游维护者的原话:
|
||||
*"the config files are read before the options are parsed"*)。
|
||||
配置目录 `ENOENT` 是静默跳过,`EACCES` 直接致命退出 —— 真 Termux 的
|
||||
`/data/data/com.termux` 是 `0700`、属于另一个 UID,我们连穿都穿不进去。
|
||||
|
||||
所以唯一干净的出路是:**自己编一个**,把那一处换成运行时解析。
|
||||
|
||||
---
|
||||
|
||||
## 自编版改了什么
|
||||
|
||||
一共九处补丁,都在 `patches/doubao/`(由 `make-doubao-patches.py` 生成):
|
||||
|
||||
### 1. 配置目录改成运行时解析(核心)
|
||||
|
||||
上游 `lib/dpkg/options.c` 里只有**两处**用到编译期常量 `CONFIGDIR`。
|
||||
自编版换成一个函数,从 `/proc/self/exe` 反推前缀:
|
||||
|
||||
```
|
||||
/proc/self/exe = /data/user/0/<包名>/files/usr/bin/dpkg
|
||||
~~~~ 去掉 /bin/dpkg
|
||||
/data/user/0/<包名>/files/usr
|
||||
→ 配置目录 = <prefix>/etc/dpkg
|
||||
```
|
||||
|
||||
同一个二进制在任何包名下都指向**自己所在的前缀**,不需要为每个包名编一份。
|
||||
还留了 `DOUBAO_DPKG_PREFIX` 环境变量做显式覆盖(测试用)。
|
||||
|
||||
### 2. 架构名用 Termux 的写法
|
||||
|
||||
这条是**实测撞出来的**:Termux 仓库里包的 `Architecture` 字段是
|
||||
`x86_64` / `aarch64` / `arm` / `i686`(就是 GNU CPU 名),
|
||||
而 Debian 那边是 `amd64` / `arm64`。
|
||||
|
||||
用错名字的后果很大:dpkg 会把数据库里**每一个包**都判成
|
||||
|
||||
```
|
||||
'x86_64' is not a valid architecture name in 'Architecture' field:
|
||||
character '_' not allowed (only letters, digits and characters '-')
|
||||
```
|
||||
|
||||
而且 `x86_64` 带下划线,上游的架构名校验(C 侧 `lib/dpkg/arch.c`
|
||||
和 Perl 侧 `scripts/Dpkg/Arch.pm`)**两处都不让过**,所以两边都要放开。
|
||||
|
||||
`dpkg-architecture` 那边还绕了一下:上游的 `data/ostable` 里**根本没有
|
||||
`android` 这个操作系统**,所以 `*-linux-android` 这种三元组永远解析不出来,
|
||||
configure 会报 `cannot determine host dpkg architecture`。
|
||||
自编版在 `m4/dpkg-arch.m4` 里直接从 `$host_cpu` 取值。
|
||||
|
||||
> 顺带一个坑:`--host=x86_64-linux-android` 会被 `config.sub`
|
||||
> 规范化成 `x86_64-pc-linux-android`,所以 `$host_os` 是
|
||||
> **`linux-android`**,不是 `android`。匹配要写 `*android*`。
|
||||
|
||||
### 3. 修好 PATH 和 `LD_LIBRARY_PATH`
|
||||
|
||||
apt 派生 dpkg 时会**清洗环境**,塞给它一个指向**另一个 App 前缀**的 PATH
|
||||
(实录:`PATH=[/data/data/com.termux/files/usr/bin]`)。dpkg 于是报:
|
||||
|
||||
```
|
||||
dpkg: warning: 'sh' not found in PATH or not executable
|
||||
dpkg: error: 5 expected programs not found in PATH or not executable
|
||||
```
|
||||
|
||||
自编版在 `dpkg_options_load()` 之后(也就是任何 `checkpath()` 之前)
|
||||
按自己的前缀把 PATH / `LD_LIBRARY_PATH` 补上。
|
||||
|
||||
### 4. 改写维护脚本里的前缀
|
||||
|
||||
Termux 包的维护脚本整篇都是 Termux 前缀:
|
||||
|
||||
```sh
|
||||
#!/data/data/com.termux/files/usr/bin/sh
|
||||
mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_${a}_key"
|
||||
```
|
||||
|
||||
- 第一行由**内核**解析,落在另一个 App 的私有目录 → EACCES,
|
||||
而 dpkg 会把它显示成"脚本没有执行权限",**指错方向**
|
||||
- 后面那些是**根下的绝对路径**,我们的沙箱软链拦不住
|
||||
|
||||
脚本是纯文本,所以自编版在 exec 之前把 `DOUBAO_OLD_PREFIX` 换成自己的前缀。
|
||||
三条执行路径(`vmaintscript_installed` / `maintscript_new` /
|
||||
`maintscript_fallback`)都要挂上 —— 只挂一处的话 `--configure` 那条路
|
||||
(走的正是 `vmaintscript_installed`)不会有任何效果。
|
||||
|
||||
改完之后的实录:
|
||||
|
||||
```
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 怎么构建
|
||||
|
||||
```bash
|
||||
# 1. 下源码(依赖库 + termux-packages + dpkg)
|
||||
bash fetch-sources.sh /root/tb
|
||||
|
||||
# 2. 编依赖(libmd / zlib / bzip2 / liblzma / libzstd,给两个架构都来一遍)
|
||||
bash build-deps.sh x86_64
|
||||
bash build-deps.sh arm64
|
||||
|
||||
# 3. 编 dpkg
|
||||
bash build-dpkg.sh x86_64
|
||||
bash build-dpkg.sh arm64
|
||||
|
||||
# 4. 校验(每一条都对应一个真踩过的坑)
|
||||
python3 verify-dpkg.py x86_64
|
||||
python3 verify-dpkg.py arm64
|
||||
|
||||
# 5. 打包成 jniLibs 里的 .so
|
||||
bash make-jnilibs.sh /root/tb ../app/src/main/jniLibs
|
||||
```
|
||||
|
||||
需要的环境变量(都有默认值):
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `ANDROID_NDK` | `/root/tb/android-ndk-r27c` | NDK 根目录 |
|
||||
| `TERMUX_DPKG_WORK` | `/root/tb` | 工作目录 |
|
||||
| `TERMUX_DPKG_SRC` | `$WORK/src/dpkg` | dpkg 源码(**必须 git checkout**) |
|
||||
| `DOUBAO_PREFIX` | `com.doubao.lynxclone` 的前缀 | 编译进二进制的兜底前缀 |
|
||||
|
||||
改了 `make-doubao-patches.py` 之后要重新生成补丁:
|
||||
|
||||
```bash
|
||||
python3 make-doubao-patches.py /root/tb/src/dpkg patches/doubao
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 几个构建上的坑
|
||||
|
||||
**dpkg 源码必须是 git checkout。** 它的 `build-aux/get-version` 要用 git
|
||||
(或发行 tarball)定版本号,`git archive` 出来的树会让 `autogen` 报
|
||||
`cannot get project version`。构建脚本用 `git worktree` 解决(共享 `.git`,
|
||||
树是干净的,还能随手删掉重来)。
|
||||
|
||||
**补丁不要手写。** hunk 头(`@@ -55,6 +55,22 @@`)的行号必须和源码逐字对上,
|
||||
手数极容易错 —— 我错过两次:一次少一行 `malformed patch`,
|
||||
一次多一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 **patch 两种都不报错**,
|
||||
只是行为诡异。所以补丁一律用 `diff -u` 从"改好的文件"生成。
|
||||
|
||||
**依赖库全部静态链进去。** 只有 `libmd` 是硬依赖(`readelf -d` 显示
|
||||
Termux 的 dpkg 只 NEEDED `libmd.so` + `libc.so`,zlib/bz2/lzma/zstd 都是
|
||||
可选),全静态链进去就不依赖运行时环境。
|
||||
|
||||
**RUNPATH 要烧进 ELF。** dpkg 会 exec 出 `dpkg-query` / `dpkg-deb`
|
||||
这些辅助程序,那些进程不一定继承到 `LD_LIBRARY_PATH`:
|
||||
|
||||
```
|
||||
-Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags
|
||||
```
|
||||
|
||||
**xz 的 configure 会在 CFLAGS 上做 `-Werror` 试编译**,而
|
||||
`-D__ANDROID_API__=24` 会触发它的告警,于是它误判 CFLAGS 有问题直接退出。
|
||||
加 `SKIP_WERROR_CHECK=yes` 跳过。
|
||||
|
||||
**`dpkg-realpath` 是 shell 脚本不是 ELF**,strip 会失败,忽略即可。
|
||||
|
||||
---
|
||||
|
||||
## 怎么打进 APK
|
||||
|
||||
`make-jnilibs.sh` 把六个程序打成一个 **tar 包**,改名成
|
||||
`lib/<abi>/libdoubao-dpkg.so`。
|
||||
|
||||
为什么不放 `assets/`:Android 安装 APK 时只对 `lib/<abi>/*.so`
|
||||
免压缩解包,别的路径会被压缩、还得自己再解一遍。
|
||||
这也跟这个仓库里 `libtermux-bootstrap.so` 的做法一致。
|
||||
|
||||
Kotlin 侧的解包在 `TermuxInstaller.installOwnDpkg()`,是手写的 ustar 读取
|
||||
(只认普通文件、拒绝带斜杠的名字),为了这点事不值得引一个 tar 库。
|
||||
|
||||
装好之后 **`bin/dpkg.real` + wrapper 那一套就不需要了** ——
|
||||
wrapper 本来就是在绕"配置目录编译死"这个我们已经从根上修掉的问题。
|
||||
|
||||
---
|
||||
|
||||
## 校验脚本守什么
|
||||
|
||||
`verify-dpkg.py` 守的每一条都对应一个踩过的坑:
|
||||
|
||||
1. 六个程序齐全、架构正确
|
||||
2. 二进制里的 `com.termux` 字符串**只允许**是重写函数自己要匹配的模式 ——
|
||||
出现别的(尤其是配置目录)就说明补丁没生效,装上必然 EACCES
|
||||
3. 有 `/proc/self/exe`(运行时前缀的前提)
|
||||
4. 不能出现 `amd64` / `arm64`(Termux 用 GNU CPU 名)
|
||||
5. 源码里架构名校验放开了下划线
|
||||
6. RUNPATH 指向前缀 `lib`
|
||||
7. 不依赖 `libmd.so`(已静态链入)
|
||||
|
||||
---
|
||||
|
||||
## 实测结果(Android 14 x86_64 模拟器,**真 Termux 同时装着**)
|
||||
|
||||
真 Termux 的目录权限一直是 `drwx------ u0_a109`,我们全程读不到它。
|
||||
|
||||
```
|
||||
$ pkg install -y openssh
|
||||
...
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
|
||||
$ dpkg -l | grep -c '^i[^i]' # 未配置项
|
||||
0
|
||||
$ ssh -V
|
||||
OpenSSH_10.6p1, OpenSSL 3.4.1 11 Feb 2025
|
||||
```
|
||||
|
||||
另外验证过的:`nmap`、`git 2.56.0` 全新安装(含 `lua54` / `libpcap` /
|
||||
`openssh` 这些带 postinst 的依赖链)全部 `未配置 = 0`。
|
||||
126
android/termux-dpkg/build-deps.sh
Normal file
126
android/termux-dpkg/build-deps.sh
Normal file
@@ -0,0 +1,126 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg 需要的静态库
|
||||
#
|
||||
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
|
||||
#
|
||||
# 需要的环境变量(都有默认值,默认是开发机上的位置):
|
||||
# ANDROID_NDK NDK 根目录
|
||||
# TERMUX_DPKG_WORK 工作目录(下载源码、解包、编译中间产物都放这里)
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
|
||||
|
||||
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
|
||||
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
|
||||
SRC="$WORK/dl"
|
||||
OUT="$WORK/out/$ARCH"
|
||||
API="${ANDROID_API:-24}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
export LDFLAGS=""
|
||||
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; echo " 设一下 ANDROID_NDK"; exit 1; }
|
||||
echo "### arch=$ARCH CC=$CC"
|
||||
"$CC" --version | head -1
|
||||
|
||||
mkdir -p "$OUT/lib" "$OUT/include" "$WORK/work"
|
||||
cd "$WORK/work"
|
||||
|
||||
# 每个库都单独判断,编过就跳过,方便断点续编
|
||||
need() { [ ! -f "$OUT/lib/$1" ]; }
|
||||
|
||||
########################################
|
||||
# libmd 1.3.0 —— dpkg 唯一必需的第三方库
|
||||
########################################
|
||||
if need libmd.a; then
|
||||
echo "=== libmd ==="
|
||||
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
|
||||
cd libmd-1.3.0
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static >/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libmd.a" ] && echo " ✓ libmd" || echo " ✗ libmd 失败"
|
||||
|
||||
########################################
|
||||
# zlib
|
||||
########################################
|
||||
if need libz.a; then
|
||||
echo "=== zlib ==="
|
||||
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
|
||||
cd zlib-1.3.2
|
||||
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
|
||||
make -j"$(nproc)" libz.a >/dev/null 2>&1
|
||||
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libz.a" ] && echo " ✓ zlib" || echo " ✗ zlib 失败"
|
||||
|
||||
########################################
|
||||
# bzip2 1.0.8
|
||||
########################################
|
||||
if need libbz2.a; then
|
||||
echo "=== bzip2 ==="
|
||||
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
|
||||
cd bzip2-1.0.8
|
||||
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
|
||||
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/libbz2.a" ] && echo " ✓ bzip2" || echo " ✗ bzip2 失败"
|
||||
|
||||
########################################
|
||||
# liblzma (xz)
|
||||
########################################
|
||||
if need liblzma.a; then
|
||||
echo "=== liblzma ==="
|
||||
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
|
||||
cd xz-5.8.4
|
||||
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,而
|
||||
# -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static \
|
||||
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
|
||||
--disable-scripts --disable-doc --disable-nls \
|
||||
SKIP_WERROR_CHECK=yes \
|
||||
>/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
cd ..
|
||||
fi
|
||||
[ -f "$OUT/lib/liblzma.a" ] && echo " ✓ liblzma" || echo " ✗ liblzma 失败"
|
||||
|
||||
########################################
|
||||
# libzstd
|
||||
########################################
|
||||
if need libzstd.a; then
|
||||
echo "=== libzstd ==="
|
||||
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
|
||||
cd zstd-1.5.7/lib
|
||||
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS" >/dev/null 2>&1
|
||||
cp libzstd.a "$OUT/lib/"
|
||||
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
|
||||
cd ../..
|
||||
fi
|
||||
[ -f "$OUT/lib/libzstd.a" ] && echo " ✓ libzstd" || echo " ✗ libzstd 失败"
|
||||
|
||||
echo
|
||||
echo "=== $ARCH 产物 ==="
|
||||
ls -la "$OUT/lib/"*.a
|
||||
149
android/termux-dpkg/build-dpkg.sh
Normal file
149
android/termux-dpkg/build-dpkg.sh
Normal file
@@ -0,0 +1,149 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg(用 Termux 的补丁 + 我们自己的运行时前缀补丁)
|
||||
#
|
||||
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
|
||||
#
|
||||
# 环境变量(都有默认值):
|
||||
# ANDROID_NDK NDK 根目录
|
||||
# TERMUX_DPKG_WORK 工作目录
|
||||
# TERMUX_DPKG_SRC dpkg 源码目录(必须是 git checkout)
|
||||
# DOUBAO_PREFIX 编译进二进制的兜底前缀(运行时会被 /proc/self/exe 覆盖)
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
NDK="${ANDROID_NDK:-/root/tb/android-ndk-r27c}"
|
||||
WORK="${TERMUX_DPKG_WORK:-/root/tb}"
|
||||
SRC="${TERMUX_DPKG_SRC:-$WORK/src/dpkg}"
|
||||
DEPS="$WORK/out/$ARCH"
|
||||
OUT="$WORK/out/$ARCH"
|
||||
API="${ANDROID_API:-24}"
|
||||
PREFIX="${DOUBAO_PREFIX:-/data/data/com.doubao.lynxclone/files/usr}"
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH(支持 x86_64 / arm64)"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CPPFLAGS="-I$DEPS/include"
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
|
||||
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
|
||||
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,$PREFIX/lib -Wl,--enable-new-dtags"
|
||||
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
|
||||
|
||||
BUILD="$WORK/build/dpkg-$ARCH"
|
||||
mkdir -p "$WORK/build" "$BUILD"
|
||||
|
||||
echo "########## 0. 检查前提 ##########"
|
||||
[ -d "$SRC/.git" ] || { echo "!! $SRC 不是 git checkout(dpkg 的 get-version 要求)"; exit 1; }
|
||||
[ -f "$DEPS/lib/libmd.a" ] || { echo "!! 先跑 build-deps.sh $ARCH"; exit 1; }
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
|
||||
echo " src=$SRC"
|
||||
echo " 前缀=$PREFIX"
|
||||
|
||||
echo "########## 1. 准备源码树 ##########"
|
||||
# 不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要一个真正的
|
||||
# git checkout(或发行 tarball)才能定出版本号。用 git worktree:共享 .git,
|
||||
# 树是干净的,而且可以随时删掉重来。
|
||||
cd "$SRC"
|
||||
git worktree remove --force "$BUILD" 2>/dev/null || true
|
||||
rm -rf "$BUILD"
|
||||
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
|
||||
echo "git worktree 失败"; exit 1; }
|
||||
cd "$BUILD"
|
||||
echo " worktree 就绪: $(pwd)"
|
||||
|
||||
apply() { # apply <补丁文件> [必需]
|
||||
local p="$1" must="${2:-}"
|
||||
local n; n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n"
|
||||
patch -p1 -N -l -i "$p" 2>&1 | head -15
|
||||
[ -n "$must" ] && exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
echo "########## 2. Termux 上游补丁 ##########"
|
||||
for p in "$HERE"/patches/termux/*.patch; do apply "$p"; done
|
||||
|
||||
echo "########## 3. 我们自己的补丁 ##########"
|
||||
for p in "$HERE"/patches/doubao/*.patch; do apply "$p" required; done
|
||||
|
||||
echo "########## 4. autogen ##########"
|
||||
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
|
||||
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
|
||||
NOCONFIGURE=1 sh ./autogen > "$BUILD/autogen.log" 2>&1 || {
|
||||
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
|
||||
fi
|
||||
echo " configure 就绪"
|
||||
|
||||
echo "########## 5. configure ##########"
|
||||
# PERL: 宿主机 perl 版本可能低于 dpkg 要求的 5.32.1。perl 只用于构建期脚本
|
||||
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
|
||||
# perl 在哪,跳过版本探测。
|
||||
#
|
||||
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
|
||||
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
|
||||
./configure \
|
||||
--host="$TRIPLE" \
|
||||
--build="$(uname -m)-pc-linux-gnu" \
|
||||
--prefix="$PREFIX" \
|
||||
--bindir="$PREFIX/bin" \
|
||||
--libdir="$PREFIX/lib" \
|
||||
--sysconfdir="$PREFIX/etc" \
|
||||
--localstatedir="$PREFIX/var" \
|
||||
--disable-shared \
|
||||
--disable-dselect \
|
||||
--disable-start-stop-daemon \
|
||||
--disable-update-alternatives \
|
||||
--disable-largefile \
|
||||
--disable-nls \
|
||||
--without-selinux \
|
||||
--without-libselinux \
|
||||
--without-systemd \
|
||||
PERL="${PERL:-$(command -v perl)}" \
|
||||
ac_cv_lib_selinux_setexecfilecon=no \
|
||||
dpkg_cv_c99_snprintf=yes \
|
||||
DPKG_PAGER=pager \
|
||||
> "$BUILD/configure.log" 2>&1 || {
|
||||
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
|
||||
echo " ✓ configure 通过"
|
||||
|
||||
echo "########## 6. make ##########"
|
||||
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
|
||||
echo "make 失败,错误摘要:"
|
||||
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
|
||||
exit 1; }
|
||||
echo " ✓ make 通过"
|
||||
|
||||
echo "########## 7. 收集产物 ##########"
|
||||
mkdir -p "$OUT/dpkg-bin"
|
||||
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger; do
|
||||
f=""
|
||||
for cand in "src/dpkg/main/.libs/$b" "src/dpkg/deb/.libs/$b" \
|
||||
"src/dpkg/split/.libs/$b" "src/dpkg/query/.libs/$b" \
|
||||
"src/dpkg/divert/.libs/$b" "src/dpkg/trigger/.libs/$b" \
|
||||
"src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
|
||||
"src/$b" "src/main/$b" "utils/$b"; do
|
||||
[ -f "$cand" ] && { f="$cand"; break; }
|
||||
done
|
||||
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
|
||||
cp "$f" "$OUT/dpkg-bin/$b"
|
||||
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b"
|
||||
done
|
||||
|
||||
echo
|
||||
ls -la "$OUT/dpkg-bin/"
|
||||
echo
|
||||
echo "产物在 $OUT/dpkg-bin/"
|
||||
29
android/termux-dpkg/extract-termux-patches.sh
Normal file
29
android/termux-dpkg/extract-termux-patches.sh
Normal file
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# 从 termux-packages 里把 dpkg 的上游补丁抽到本仓库。
|
||||
#
|
||||
# 为什么要把它们拷进仓库:build-dpkg.sh 依赖这批补丁才能让 dpkg 在 Android 上
|
||||
# 跑起来(Android 不支持硬链接、应用没有 chown 权限、不允许 root 检查……)。
|
||||
# 直接引用 termux-packages 的 checkout 会让构建依赖一个会随时变化的 master,
|
||||
# 所以拷一份固定下来。
|
||||
#
|
||||
# 用法: extract-termux-patches.sh [termux-packages 路径]
|
||||
set -eu
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
TP="${1:-${TERMUX_DPKG_WORK:-/root/tb}/termux-packages}"
|
||||
SRCDIR="$TP/packages/dpkg"
|
||||
DST="$HERE/patches/termux"
|
||||
|
||||
[ -d "$SRCDIR" ] || { echo "!! 找不到 $SRCDIR"; echo " 先跑 fetch-sources.sh"; exit 1; }
|
||||
|
||||
mkdir -p "$DST"
|
||||
cd "$SRCDIR"
|
||||
for f in *.patch; do
|
||||
[ -f "$f" ] || continue
|
||||
cp "$f" "$DST/termux-$f"
|
||||
printf ' %s\n' "termux-$f"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "已拷到 $DST:"
|
||||
ls -la "$DST"
|
||||
76
android/termux-dpkg/fetch-sources.sh
Normal file
76
android/termux-dpkg/fetch-sources.sh
Normal file
@@ -0,0 +1,76 @@
|
||||
#!/bin/bash
|
||||
# 下载构建 dpkg 需要的全部源码。
|
||||
#
|
||||
# 用法: fetch-sources.sh [工作目录]
|
||||
#
|
||||
# 说明几个源的选择:
|
||||
# - GitHub 在部分网络下连不上,但 codeload.github.com 通常可以,
|
||||
# 所以 termux-packages 走 codeload 的 tarball 接口。
|
||||
# - dpkg 源码必须在 git 仓库里(build-aux/get-version 依赖它来判断版本号),
|
||||
# 所以从 salsa.debian.org 克隆。
|
||||
# - 依赖库都从 Debian 镜像取 orig.tar,避免各上游站点可达性不一致。
|
||||
set -eu
|
||||
|
||||
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
|
||||
DL="$WORK/dl"
|
||||
SRC="$WORK/src"
|
||||
mkdir -p "$DL" "$SRC"
|
||||
|
||||
# -4:WSL 里 packages.termux.dev 会解析出 IPv6,而那条路不通,curl 会卡住
|
||||
CURL="curl -4 -fsSL --retry 3 --retry-delay 3"
|
||||
|
||||
get() { # get <文件名> <url...> 依次尝试,成功即止
|
||||
local name="$1"; shift
|
||||
if [ -s "$DL/$name" ]; then echo " 已有 $name"; return 0; fi
|
||||
local u
|
||||
for u in "$@"; do
|
||||
if $CURL -o "$DL/$name" "$u" 2>/dev/null; then
|
||||
printf ' ✓ %-22s %s 字节\n' "$name" "$(stat -c%s "$DL/$name")"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
printf ' ✗ %-22s 全部源都失败\n' "$name"
|
||||
return 1
|
||||
}
|
||||
|
||||
TUNA=https://mirrors.tuna.tsinghua.edu.cn/debian/pool/main
|
||||
DEB=https://deb.debian.org/debian/pool/main
|
||||
|
||||
echo "=== 依赖库源码 ==="
|
||||
get libmd.tar.xz "$DEB/libm/libmd/libmd_1.3.0.orig.tar.xz" \
|
||||
"$TUNA/libm/libmd/libmd_1.3.0.orig.tar.xz"
|
||||
get zlib.tar.gz "https://zlib.net/zlib-1.3.2.tar.gz" \
|
||||
"$TUNA/z/zlib/zlib_1.3.2.orig.tar.gz"
|
||||
get bzip2.tar.gz "https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz" \
|
||||
"$TUNA/b/bzip2/bzip2_1.0.8.orig.tar.gz"
|
||||
get xz.tar.xz "https://tukaani.org/xz/xz-5.8.4.tar.xz" \
|
||||
"$TUNA/x/xz-utils/xz-utils_5.8.4.orig.tar.xz"
|
||||
get zstd.tar.gz "https://codeload.github.com/facebook/zstd/tar.gz/refs/tags/v1.5.7"
|
||||
|
||||
echo
|
||||
echo "=== Termux 的 dpkg 补丁(从 termux-packages 抽) ==="
|
||||
TP="$WORK/termux-packages"
|
||||
if [ ! -d "$TP/packages/dpkg" ]; then
|
||||
echo " 拉 termux-packages…"
|
||||
$CURL -o "$DL/tp.tar.gz" \
|
||||
"https://codeload.github.com/termux/termux-packages/tar.gz/refs/heads/master"
|
||||
rm -rf "$TP"
|
||||
tar xzf "$DL/tp.tar.gz" -C "$WORK"
|
||||
mv "$WORK/termux-packages-master" "$TP"
|
||||
fi
|
||||
echo " termux-packages: $TP"
|
||||
ls "$TP/packages/dpkg/" | head -20
|
||||
|
||||
echo
|
||||
echo "=== dpkg 源码(必须 git checkout) ==="
|
||||
if [ ! -d "$SRC/dpkg/.git" ]; then
|
||||
echo " 克隆 dpkg 1.22.6…"
|
||||
timeout 900 git clone --depth 1 --branch 1.22.6 \
|
||||
https://salsa.debian.org/dpkg-team/dpkg.git "$SRC/dpkg"
|
||||
fi
|
||||
echo " dpkg: $(cd "$SRC/dpkg" && git log --oneline -1)"
|
||||
|
||||
echo
|
||||
echo "全部就绪。接下来:"
|
||||
echo " bash build-deps.sh x86_64 # 或 arm64"
|
||||
echo " bash build-dpkg.sh x86_64"
|
||||
659
android/termux-dpkg/make-doubao-patches.py
Normal file
659
android/termux-dpkg/make-doubao-patches.py
Normal file
@@ -0,0 +1,659 @@
|
||||
#!/usr/bin/env python3
|
||||
"""生成"我们自己"的 dpkg 补丁。
|
||||
|
||||
为什么要单独一个脚本生成补丁,而不是把补丁直接写死在仓库里:
|
||||
|
||||
补丁的 hunk 头(`@@ -55,6 +55,22 @@`)里的行号必须和 dpkg 源码逐字对上,
|
||||
手写极容易数错——我就在这上面栽过两次,一次少写一行导致 `malformed patch`,
|
||||
一次多写一行把紧跟的 `DPKG_OS_TYPE` 吃掉了,而 patch 两个都不报错、
|
||||
只是行为诡异。
|
||||
|
||||
所以这里的做法是:从 git 取出原始文件,用 Python 做结构化的文本替换,
|
||||
再用 `diff -u` 生成补丁。diff 产出的 hunk 头永远是对的。
|
||||
|
||||
用法:
|
||||
python3 make-doubao-patches.py <dpkg源码目录> [输出目录]
|
||||
|
||||
需要 dpkg 源码是一个 git checkout(dpkg 自己的 build-aux/get-version 也要求如此)。
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
SRC = os.path.abspath(sys.argv[1])
|
||||
OUT = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), "patches", "doubao")
|
||||
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
|
||||
|
||||
def git_show(rel):
|
||||
r = subprocess.run(["git", "show", "HEAD:" + rel], cwd=SRC,
|
||||
capture_output=True, text=True)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit(f"git show HEAD:{rel} 失败:{r.stderr.strip()}")
|
||||
return r.stdout
|
||||
|
||||
|
||||
def write_patch(rel, old, new, name):
|
||||
"""old -> new 的补丁,路径写成 a/<rel> b/<rel>,供 patch -p1 使用。"""
|
||||
a = os.path.join(tempfile.mkdtemp(), "a")
|
||||
b = os.path.join(tempfile.mkdtemp(), "b")
|
||||
open(a, "w").write(old)
|
||||
open(b, "w").write(new)
|
||||
r = subprocess.run(["diff", "-u", a, b], capture_output=True, text=True)
|
||||
body = r.stdout.replace(a, "a/" + rel, 1).replace(b, "b/" + rel, 1)
|
||||
path = os.path.join(OUT, name)
|
||||
open(path, "w").write(body)
|
||||
print(f" → {name} ({len(body.splitlines())} 行)")
|
||||
|
||||
|
||||
# ======================================================================
|
||||
# 1. 头文件
|
||||
# ======================================================================
|
||||
HEADER = '''/*
|
||||
* doubao-prefix.h - resolve the installation prefix at runtime
|
||||
*
|
||||
* Copyright (C) 2026 doubao-clone
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*/
|
||||
|
||||
#ifndef DOUBAO_PREFIX_H
|
||||
#define DOUBAO_PREFIX_H
|
||||
|
||||
#include <dpkg/dpkg.h>
|
||||
|
||||
DPKG_BEGIN_DECLS
|
||||
|
||||
/**
|
||||
* Return the prefix this dpkg was installed under.
|
||||
*
|
||||
* The prefix is derived from the path of the running executable, because
|
||||
* Android hands every application its own private data directory and the
|
||||
* same binary has to work under any of them. Falls back to the compile-time
|
||||
* DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
|
||||
*/
|
||||
const char *doubao_prefix(void);
|
||||
|
||||
/**
|
||||
* Return the configuration directory ($prefix/etc/dpkg).
|
||||
*/
|
||||
const char *doubao_config_dir(void);
|
||||
|
||||
/**
|
||||
* Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
|
||||
* own lib directory.
|
||||
*
|
||||
* Needed because apt sanitises the environment before it execs dpkg, and the
|
||||
* PATH it hands over names the *other* application's prefix; dpkg would then
|
||||
* fail its own sanity check with "expected programs not found in PATH".
|
||||
*/
|
||||
void doubao_fix_environment(void);
|
||||
|
||||
/**
|
||||
* Rewrite a maintainer script's interpreter line so it points at this
|
||||
* installation instead of the application it was built for.
|
||||
*/
|
||||
void doubao_fix_script_shebang(const char *path);
|
||||
|
||||
DPKG_END_DECLS
|
||||
|
||||
#endif /* DOUBAO_PREFIX_H */
|
||||
'''
|
||||
|
||||
# ======================================================================
|
||||
# 2. 实现
|
||||
# ======================================================================
|
||||
IMPL = r'''/*
|
||||
* doubao-prefix.c - resolve the installation prefix at runtime
|
||||
*
|
||||
* Copyright (C) 2026 doubao-clone
|
||||
*
|
||||
* This is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Upstream dpkg bakes its configuration directory in at configure time
|
||||
* (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
|
||||
* fixed absolute path chosen by the Termux application. Android gives every
|
||||
* application its own private data directory, so a dpkg built for
|
||||
* com.termux will always look inside /data/data/com.termux -- a directory
|
||||
* another application is not allowed to traverse. The resulting EACCES makes
|
||||
* dpkg abort before it has even parsed its command line, which is why the two
|
||||
* applications cannot coexist.
|
||||
*
|
||||
* We instead derive the prefix from the path of the running executable, which
|
||||
* is exactly where this binary happens to live. That also lets us repair
|
||||
* PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
|
||||
* all of which upstream assumes are already correct.
|
||||
*/
|
||||
|
||||
#include <config.h>
|
||||
#include <compat.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <dpkg/i18n.h>
|
||||
#include <dpkg/debug.h>
|
||||
#include <dpkg/dpkg.h>
|
||||
#include <dpkg/doubao-prefix.h>
|
||||
|
||||
/* How many distinct strings we keep alive so returned pointers stay valid. */
|
||||
#define DOUBAO_CACHE_SLOTS 4
|
||||
|
||||
static char prefix_buf[PATH_MAX];
|
||||
static const char *prefix_cached;
|
||||
static char config_buf[PATH_MAX];
|
||||
|
||||
static void
|
||||
doubao_prefix_resolve(void)
|
||||
{
|
||||
char self[PATH_MAX];
|
||||
const char *override;
|
||||
char *slash;
|
||||
ssize_t n;
|
||||
|
||||
if (prefix_cached != NULL)
|
||||
return;
|
||||
|
||||
prefix_cached = DOUBAO_DEFAULT_PREFIX;
|
||||
|
||||
override = getenv("DOUBAO_DPKG_PREFIX");
|
||||
if (override != NULL) {
|
||||
if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
|
||||
strcpy(prefix_buf, override);
|
||||
prefix_cached = prefix_buf;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
n = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
if (n <= 0 || (size_t)n >= sizeof(self) - 1)
|
||||
return;
|
||||
self[n] = '\0';
|
||||
|
||||
/* .../bin/dpkg -> .../bin -> ... */
|
||||
slash = strrchr(self, '/');
|
||||
if (slash == NULL)
|
||||
return;
|
||||
*slash = '\0';
|
||||
|
||||
slash = strrchr(self, '/');
|
||||
if (slash == NULL)
|
||||
return;
|
||||
*slash = '\0';
|
||||
|
||||
if (strlen(self) < sizeof(prefix_buf)) {
|
||||
strcpy(prefix_buf, self);
|
||||
prefix_cached = prefix_buf;
|
||||
}
|
||||
}
|
||||
|
||||
const char *
|
||||
doubao_prefix(void)
|
||||
{
|
||||
doubao_prefix_resolve();
|
||||
return prefix_cached;
|
||||
}
|
||||
|
||||
const char *
|
||||
doubao_config_dir(void)
|
||||
{
|
||||
const char *prefix = doubao_prefix();
|
||||
|
||||
if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
|
||||
>= (int)sizeof(config_buf))
|
||||
return CONFIGDIR;
|
||||
|
||||
return config_buf;
|
||||
}
|
||||
|
||||
/*
|
||||
* Prepend our own bin directories to PATH and make sure the loader can find
|
||||
* our shared libraries, so that dpkg and the maintainer scripts it runs work
|
||||
* no matter what environment our parent handed us.
|
||||
*/
|
||||
void
|
||||
doubao_fix_environment(void)
|
||||
{
|
||||
static bool done = false;
|
||||
static char pathbuf[4 * PATH_MAX];
|
||||
static char libbuf[PATH_MAX + 64];
|
||||
|
||||
const char *prefix, *old;
|
||||
size_t len;
|
||||
|
||||
if (done)
|
||||
return;
|
||||
done = true;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
|
||||
old = getenv("PATH");
|
||||
/* Only prepend when our prefix is not already the first entry, so that
|
||||
* a re-exec does not keep growing PATH. */
|
||||
len = strlen(prefix);
|
||||
if (old == NULL || strncmp(old, prefix, len) != 0 ||
|
||||
strncmp(old + len, "/bin:", 5) != 0) {
|
||||
if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
|
||||
prefix, prefix, old != NULL ? old : "/system/bin")
|
||||
< (int)sizeof(pathbuf))
|
||||
setenv("PATH", pathbuf, 1);
|
||||
}
|
||||
|
||||
if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
|
||||
prefix) < (int)sizeof(libbuf))
|
||||
setenv("LD_LIBRARY_PATH", libbuf, 1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Maintainer scripts inside a Termux package are written in terms of the
|
||||
* Termux prefix:
|
||||
*
|
||||
* #!/data/data/com.termux/files/usr/bin/sh
|
||||
* mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
* KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
|
||||
*
|
||||
* Neither form works for us. The interpreter line is resolved by the kernel
|
||||
* and lands in another application's private directory (EACCES, which dpkg
|
||||
* then reports as though the script itself were not executable), and the
|
||||
* absolute paths are absolute -- our sandbox symlinks live under our own
|
||||
* prefix and cannot intercept a path that starts at "/".
|
||||
*
|
||||
* The scripts are plain text, so rewrite both before executing them. This is
|
||||
* a local edit of the dpkg database rather than a change to the package, so
|
||||
* it also covers packages installed long after this code was written.
|
||||
*/
|
||||
#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
|
||||
|
||||
static void
|
||||
doubao_rewrite_script(const char *path)
|
||||
{
|
||||
char *buf;
|
||||
char *out;
|
||||
const char *prefix;
|
||||
size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
|
||||
size_t newlen, len, cap;
|
||||
size_t i, o;
|
||||
int fd;
|
||||
ssize_t n;
|
||||
struct stat st;
|
||||
|
||||
if (path == NULL)
|
||||
return;
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return;
|
||||
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
|
||||
st.st_size > 1024 * 1024) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
len = (size_t)st.st_size;
|
||||
buf = malloc(len + 1);
|
||||
if (buf == NULL) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
n = read(fd, buf, len);
|
||||
close(fd);
|
||||
if (n <= 0) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
buf[n] = '\0';
|
||||
len = (size_t)n;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
newlen = strlen(prefix);
|
||||
|
||||
/* 先看有没有要换的东西,没有就别写盘 */
|
||||
for (i = 0; i + oldlen <= len; i++) {
|
||||
if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
|
||||
break;
|
||||
}
|
||||
if (i + oldlen > len) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
/* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
|
||||
cap = len + 64;
|
||||
out = malloc(cap);
|
||||
if (out == NULL) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
|
||||
for (i = 0, o = 0; i < len; ) {
|
||||
if (i + oldlen <= len &&
|
||||
memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
|
||||
if (o + newlen + (len - i) + 2 > cap) {
|
||||
cap = (o + newlen + (len - i) + 2) * 2;
|
||||
out = realloc(out, cap);
|
||||
if (out == NULL) {
|
||||
free(buf);
|
||||
return;
|
||||
}
|
||||
}
|
||||
memcpy(out + o, prefix, newlen);
|
||||
o += newlen;
|
||||
i += oldlen;
|
||||
} else {
|
||||
out[o++] = buf[i++];
|
||||
}
|
||||
}
|
||||
out[o] = '\0';
|
||||
free(buf);
|
||||
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0) {
|
||||
free(out);
|
||||
return;
|
||||
}
|
||||
if (write(fd, out, o) != (ssize_t)o) {
|
||||
close(fd);
|
||||
free(out);
|
||||
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
}
|
||||
close(fd);
|
||||
free(out);
|
||||
|
||||
debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
|
||||
}
|
||||
|
||||
/*
|
||||
* 把维护脚本的 shebang 换成本安装自己的 shell。
|
||||
*
|
||||
* 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
|
||||
* 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
|
||||
* 于是报 `bin/pip: line 2: import: command not found`。
|
||||
* 规则是"只换路径,不动解释器"。
|
||||
*/
|
||||
void
|
||||
doubao_fix_script_shebang(const char *path)
|
||||
{
|
||||
static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
|
||||
/* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
|
||||
* 写法,包里两种都出现过,所以两个都要认。 */
|
||||
static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
|
||||
|
||||
char buf[PATH_MAX + 256];
|
||||
const char *prefix;
|
||||
char *nl;
|
||||
int fd;
|
||||
ssize_t n;
|
||||
ssize_t skip = -1;
|
||||
size_t head, rest, total;
|
||||
char *fixed;
|
||||
|
||||
if (path == NULL)
|
||||
return;
|
||||
|
||||
/* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
|
||||
doubao_rewrite_script(path);
|
||||
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return;
|
||||
|
||||
n = read(fd, buf, sizeof(buf) - 1);
|
||||
close(fd);
|
||||
if (n <= 0)
|
||||
return;
|
||||
buf[n] = '\0';
|
||||
|
||||
if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
|
||||
skip = (ssize_t)(sizeof(old_shebang) - 1);
|
||||
else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
|
||||
skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
|
||||
|
||||
if (skip < 0)
|
||||
return;
|
||||
|
||||
nl = strchr(buf, '\n');
|
||||
if (nl == NULL)
|
||||
return;
|
||||
|
||||
prefix = doubao_prefix();
|
||||
head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
|
||||
rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
|
||||
total = head + rest;
|
||||
if (total + 1 > sizeof(buf))
|
||||
return;
|
||||
|
||||
fixed = malloc(total + 1);
|
||||
if (fixed == NULL)
|
||||
return;
|
||||
|
||||
fixed[0] = '#';
|
||||
fixed[1] = '!';
|
||||
memcpy(fixed + 2, prefix, strlen(prefix));
|
||||
fixed[2 + strlen(prefix)] = '/';
|
||||
memcpy(fixed + head, buf + skip, rest);
|
||||
fixed[total] = '\0';
|
||||
|
||||
fd = open(path, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0) {
|
||||
free(fixed);
|
||||
return;
|
||||
}
|
||||
if (write(fd, fixed, total) != (ssize_t)total)
|
||||
ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
close(fd);
|
||||
free(fixed);
|
||||
|
||||
debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
|
||||
}
|
||||
'''
|
||||
|
||||
write_patch("lib/dpkg/doubao-prefix.h", "", HEADER, "doubao-prefix-h.patch")
|
||||
write_patch("lib/dpkg/doubao-prefix.c", "", IMPL, "doubao-prefix-c.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 3. Makefile.am:加入源文件 + 定义兜底前缀
|
||||
# ======================================================================
|
||||
ma = git_show("lib/dpkg/Makefile.am")
|
||||
out, added_src, added_def = [], False, False
|
||||
for ln in ma.split("\n"):
|
||||
out.append(ln)
|
||||
if not added_src and ln.strip() == "utils.c \\":
|
||||
out.append("\tdoubao-prefix.c \\")
|
||||
added_src = True
|
||||
if not added_def and ln.strip().startswith("-DDEFAULT_TEXT_DOMAIN="):
|
||||
# 兜底前缀:正常由 /proc/self/exe 推导,这行只是推导失败时的退路
|
||||
out.append("\t-DDOUBAO_DEFAULT_PREFIX=\\\"$(prefix)\\\" \\")
|
||||
added_def = True
|
||||
assert added_src and added_def, "Makefile.am 结构变了,插入点找不到"
|
||||
new_ma = "\n".join(out)
|
||||
if "\tdpkg.h \\" in new_ma:
|
||||
new_ma = new_ma.replace("\tdpkg.h \\", "\tdpkg.h \\\n\tdoubao-prefix.h \\", 1)
|
||||
write_patch("lib/dpkg/Makefile.am", ma, new_ma, "doubao-prefix-makefile.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 4. options.c:配置目录改为运行时解析
|
||||
# ======================================================================
|
||||
oc = git_show("lib/dpkg/options.c")
|
||||
new_oc = oc.replace("#include <dpkg/options.h>\n",
|
||||
"#include <dpkg/options.h>\n#include <dpkg/doubao-prefix.h>\n", 1)
|
||||
assert new_oc != oc, "options.c 里插入 include 失败"
|
||||
new_oc = new_oc.replace('dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);',
|
||||
'dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);', 1)
|
||||
new_oc = new_oc.replace('file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);',
|
||||
'file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);', 1)
|
||||
assert "CONFIGDIR" not in new_oc, "options.c 里还有 CONFIGDIR 残留"
|
||||
write_patch("lib/dpkg/options.c", oc, new_oc, "doubao-prefix-options.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 5. main.c:启动时修好 PATH
|
||||
# ======================================================================
|
||||
mc = git_show("src/main/main.c")
|
||||
new_mc = mc.replace(
|
||||
" dpkg_options_load(DPKG, cmdinfos);\n",
|
||||
" dpkg_options_load(DPKG, cmdinfos);\n"
|
||||
"\n"
|
||||
" /* Another Android application may have handed us a PATH that points at\n"
|
||||
" * its own prefix; repair ours before anything looks a program up. */\n"
|
||||
" doubao_fix_environment();\n", 1)
|
||||
assert new_mc != mc, "main.c 里插入 doubao_fix_environment 失败"
|
||||
assert '#include "main.h"' in new_mc, "main.c 里找不到 main.h"
|
||||
new_mc = new_mc.replace('#include "main.h"',
|
||||
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
|
||||
write_patch("src/main/main.c", mc, new_mc, "doubao-prefix-main.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 6. script.c:三条执行路径都修 shebang
|
||||
# ======================================================================
|
||||
sc = git_show("src/main/script.c")
|
||||
FIX = """ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
* the Termux prefix; on Android that path belongs to another
|
||||
* application and the kernel refuses to exec it. Point it at us. */
|
||||
doubao_fix_script_shebang(%s);
|
||||
|
||||
"""
|
||||
targets = [
|
||||
(" if (stat(scriptpath, &stab)) {\n command_destroy(&cmd);\n", "scriptpath"),
|
||||
(" if (stat(cidir, &stab)) {\n command_destroy(&cmd);\n", "cidir"),
|
||||
(" if (stat(oldscriptpath, &stab)) {\n", "oldscriptpath"),
|
||||
]
|
||||
new_sc, total = sc, 0
|
||||
for needle, arg in targets:
|
||||
cnt = new_sc.count(needle)
|
||||
assert cnt > 0, f"script.c 里找不到 {arg} 的 stat 块"
|
||||
new_sc = new_sc.replace(needle, (FIX % arg) + needle)
|
||||
total += cnt
|
||||
print(f" script.c {arg}: {cnt} 处")
|
||||
assert total >= 3, f"script.c 只修了 {total} 处,至少该有 3 处"
|
||||
new_sc = new_sc.replace('#include "main.h"',
|
||||
'#include "main.h"\n\n#include <dpkg/doubao-prefix.h>', 1)
|
||||
write_patch("src/main/script.c", sc, new_sc, "doubao-prefix-script.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 7. 架构名:Termux 用的是 GNU CPU 名(x86_64 / aarch64 / arm / i686)
|
||||
# ======================================================================
|
||||
am = git_show("m4/dpkg-arch.m4")
|
||||
OLD_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
], [
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
])# DPKG_ARCHITECTURE"""
|
||||
|
||||
NEW_ARCH = """AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
|
||||
dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
|
||||
dnl all -- so the generic lookup below can never resolve a *-linux-android
|
||||
dnl host triple and configure dies with "cannot determine host dpkg
|
||||
dnl architecture".
|
||||
dnl
|
||||
dnl Termux names its architectures after the GNU CPU name (the repository
|
||||
dnl serves x86_64, aarch64, arm and i686), and the package database shipped
|
||||
dnl in our bootstrap was written with exactly those names, so we have to
|
||||
dnl report the same thing or dpkg would reject every installed package.
|
||||
dnl
|
||||
dnl Note the host OS arrives as "linux-android", not "android": config.sub
|
||||
dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
|
||||
AS_CASE([$host_os],
|
||||
[*android*], [
|
||||
AS_CASE([$host_cpu],
|
||||
[x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
|
||||
[armv7*], [dpkg_arch=arm],
|
||||
[AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
|
||||
cpu_type=$host_cpu
|
||||
os_type=android
|
||||
have_dpkg_arch=yes
|
||||
])
|
||||
AS_IF([test "x$have_dpkg_arch" = "xyes"], [
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
], [
|
||||
AC_MSG_CHECKING([dpkg architecture name])
|
||||
_DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
], [
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
])# DPKG_ARCHITECTURE"""
|
||||
|
||||
assert OLD_ARCH in am, "m4/dpkg-arch.m4 里找不到 DPKG_ARCHITECTURE 宏体"
|
||||
write_patch("m4/dpkg-arch.m4", am, am.replace(OLD_ARCH, NEW_ARCH, 1),
|
||||
"doubao-android-arch.patch")
|
||||
|
||||
# ======================================================================
|
||||
# 8. 架构名校验:x86_64 / aarch64 带下划线,两边都要放开
|
||||
# ======================================================================
|
||||
ac = git_show("lib/dpkg/arch.c")
|
||||
OLD_VAL = """\tif (!c_isalnum(*p))
|
||||
\t\treturn _("must start with an alphanumeric");
|
||||
\twhile (*++p != '\\0')
|
||||
\t\tif (!c_isalnum(*p) && *p != '-')
|
||||
\t\t\tbreak;
|
||||
\tif (*p == '\\0')
|
||||
\t\treturn NULL;
|
||||
|
||||
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
\t "letters, digits and characters '%s')"),
|
||||
\t *p, "-");
|
||||
\treturn buf;"""
|
||||
NEW_VAL = """\t/* Termux/Android: Termux names its architectures after the GNU CPU
|
||||
\t * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
|
||||
\t * underscore. Without this every package in the bootstrap database
|
||||
\t * would be reported as having an invalid Architecture. */
|
||||
\tif (!c_isalnum(*p))
|
||||
\t\treturn _("must start with an alphanumeric");
|
||||
\twhile (*++p != '\\0')
|
||||
\t\tif (!c_isalnum(*p) && *p != '-' && *p != '_')
|
||||
\t\t\tbreak;
|
||||
\tif (*p == '\\0')
|
||||
\t\treturn NULL;
|
||||
|
||||
\tsnprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
\t "letters, digits and characters '%s')"),
|
||||
\t *p, "-_");
|
||||
\treturn buf;"""
|
||||
assert OLD_VAL in ac, "lib/dpkg/arch.c 里找不到 dpkg_arch_name_is_illegal 函数体"
|
||||
write_patch("lib/dpkg/arch.c", ac, ac.replace(OLD_VAL, NEW_VAL, 1),
|
||||
"doubao-arch-name.patch")
|
||||
|
||||
ap = git_show("scripts/Dpkg/Arch.pm")
|
||||
OLD_RE = " my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;"
|
||||
NEW_RE = (" # Termux/Android: allow underscores, because Termux names\n"
|
||||
" # architectures after the GNU CPU name and x86_64 / aarch64\n"
|
||||
" # both contain one.\n"
|
||||
" my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;")
|
||||
assert OLD_RE in ap, "scripts/Dpkg/Arch.pm 里找不到架构名正则"
|
||||
write_patch("scripts/Dpkg/Arch.pm", ap, ap.replace(OLD_RE, NEW_RE, 1),
|
||||
"doubao-debarch-name.patch")
|
||||
|
||||
print("\n全部生成到 " + OUT)
|
||||
53
android/termux-dpkg/make-jnilibs.sh
Normal file
53
android/termux-dpkg/make-jnilibs.sh
Normal file
@@ -0,0 +1,53 @@
|
||||
#!/bin/bash
|
||||
# 把编好的 dpkg 打包成 jniLibs 里的 libdoubao-dpkg.so。
|
||||
#
|
||||
# 为什么打成 tar 再改名成 .so:
|
||||
# Android 安装 APK 时只对 lib/<abi>/*.so 免压缩解包,别的路径(assets/)
|
||||
# 会被压缩、还得自己解压一遍。打成 tar 塞进 .so 里,安装完直接读就行,
|
||||
# 也跟这个仓库里 libtermux-bootstrap.so 的做法一致。
|
||||
#
|
||||
# 用法: make-jnilibs.sh <工作目录> <输出 jniLibs 目录>
|
||||
set -eu
|
||||
|
||||
WORK="${1:-${TERMUX_DPKG_WORK:-/root/tb}}"
|
||||
JNI="${2:?用法: make-jnilibs.sh <工作目录> <jniLibs 目录>}"
|
||||
|
||||
PROGRAMS="dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger"
|
||||
|
||||
# APK 的 abi 目录名跟我们的 arch 名不一样
|
||||
declare -A ABI=( [x86_64]=x86_64 [arm64]=arm64-v8a )
|
||||
|
||||
for arch in x86_64 arm64; do
|
||||
src="$WORK/out/$arch/dpkg-bin"
|
||||
abi="${ABI[$arch]}"
|
||||
dst="$JNI/$abi"
|
||||
|
||||
[ -d "$src" ] || { echo "!! 没有 $src,先跑 build-dpkg.sh $arch"; exit 1; }
|
||||
mkdir -p "$dst"
|
||||
|
||||
stage="$(mktemp -d)"
|
||||
for p in $PROGRAMS; do
|
||||
[ -f "$src/$p" ] || { echo "!! 缺 $src/$p"; exit 1; }
|
||||
cp "$src/$p" "$stage/$p"
|
||||
chmod 755 "$stage/$p"
|
||||
done
|
||||
|
||||
# tar 用固定的 uid/gid/mtime,保证同样输入产出同样字节(可复现)
|
||||
tar --create --file "$dst/libdoubao-dpkg.so" \
|
||||
--directory "$stage" \
|
||||
--owner=0 --group=0 --numeric-owner \
|
||||
--mtime='2026-01-01 00:00:00 UTC' \
|
||||
--sort=name \
|
||||
$PROGRAMS
|
||||
|
||||
rm -rf "$stage"
|
||||
printf ' %-10s -> %-46s %s 字节\n' "$arch" "jniLibs/$abi/libdoubao-dpkg.so" \
|
||||
"$(stat -c%s "$dst/libdoubao-dpkg.so")"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "内容确认:"
|
||||
for arch in x86_64 arm64; do
|
||||
echo "--- ${ABI[$arch]} ---"
|
||||
tar -tvf "$JNI/${ABI[$arch]}/libdoubao-dpkg.so"
|
||||
done
|
||||
48
android/termux-dpkg/patches/doubao/doubao-android-arch.patch
Normal file
48
android/termux-dpkg/patches/doubao/doubao-android-arch.patch
Normal file
@@ -0,0 +1,48 @@
|
||||
--- a/m4/dpkg-arch.m4 2026-10-14 12:41:34.709430018 +0800
|
||||
+++ b/m4/dpkg-arch.m4 2026-10-14 12:41:34.709459828 +0800
|
||||
@@ -55,12 +55,40 @@
|
||||
AC_DEFUN([DPKG_ARCHITECTURE], [
|
||||
DPKG_CPU_TYPE
|
||||
DPKG_OS_TYPE
|
||||
- AC_MSG_CHECKING([dpkg architecture name])
|
||||
- _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
- AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
- AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
- ], [
|
||||
+ dnl Termux/Android: data/cputable, data/ostable and data/tupletable only
|
||||
+ dnl describe the Debian and GNU worlds -- ostable has no "android" entry at
|
||||
+ dnl all -- so the generic lookup below can never resolve a *-linux-android
|
||||
+ dnl host triple and configure dies with "cannot determine host dpkg
|
||||
+ dnl architecture".
|
||||
+ dnl
|
||||
+ dnl Termux names its architectures after the GNU CPU name (the repository
|
||||
+ dnl serves x86_64, aarch64, arm and i686), and the package database shipped
|
||||
+ dnl in our bootstrap was written with exactly those names, so we have to
|
||||
+ dnl report the same thing or dpkg would reject every installed package.
|
||||
+ dnl
|
||||
+ dnl Note the host OS arrives as "linux-android", not "android": config.sub
|
||||
+ dnl normalises --host=x86_64-linux-android into x86_64-pc-linux-android.
|
||||
+ AS_CASE([$host_os],
|
||||
+ [*android*], [
|
||||
+ AS_CASE([$host_cpu],
|
||||
+ [x86_64|aarch64|i686|arm], [dpkg_arch=$host_cpu],
|
||||
+ [armv7*], [dpkg_arch=arm],
|
||||
+ [AC_MSG_ERROR([unsupported Android CPU: $host_cpu])])
|
||||
+ cpu_type=$host_cpu
|
||||
+ os_type=android
|
||||
+ have_dpkg_arch=yes
|
||||
+ ])
|
||||
+ AS_IF([test "x$have_dpkg_arch" = "xyes"], [
|
||||
+ AC_MSG_CHECKING([dpkg architecture name])
|
||||
AC_MSG_RESULT([$dpkg_arch])
|
||||
+ ], [
|
||||
+ AC_MSG_CHECKING([dpkg architecture name])
|
||||
+ _DPKG_ARCHITECTURE([DEB_HOST_ARCH], [dpkg_arch])
|
||||
+ AS_IF([test "x$dpkg_arch" = "x"], [
|
||||
+ AC_MSG_ERROR([cannot determine host dpkg architecture])
|
||||
+ ], [
|
||||
+ AC_MSG_RESULT([$dpkg_arch])
|
||||
+ ])
|
||||
])
|
||||
AC_DEFINE_UNQUOTED([ARCHITECTURE], ["${dpkg_arch}"],
|
||||
[Set this to the canonical dpkg architecture name.])
|
||||
26
android/termux-dpkg/patches/doubao/doubao-arch-name.patch
Normal file
26
android/termux-dpkg/patches/doubao/doubao-arch-name.patch
Normal file
@@ -0,0 +1,26 @@
|
||||
--- a/lib/dpkg/arch.c 2026-10-14 12:41:34.729574429 +0800
|
||||
+++ b/lib/dpkg/arch.c 2026-10-14 12:41:34.729607515 +0800
|
||||
@@ -62,17 +62,21 @@
|
||||
internerr("arch name argument is NULL");
|
||||
if (!*p)
|
||||
return _("may not be empty string");
|
||||
+ /* Termux/Android: Termux names its architectures after the GNU CPU
|
||||
+ * name, and two of the four it serves -- x86_64 and aarch64 -- carry an
|
||||
+ * underscore. Without this every package in the bootstrap database
|
||||
+ * would be reported as having an invalid Architecture. */
|
||||
if (!c_isalnum(*p))
|
||||
return _("must start with an alphanumeric");
|
||||
while (*++p != '\0')
|
||||
- if (!c_isalnum(*p) && *p != '-')
|
||||
+ if (!c_isalnum(*p) && *p != '-' && *p != '_')
|
||||
break;
|
||||
if (*p == '\0')
|
||||
return NULL;
|
||||
|
||||
snprintf(buf, sizeof(buf), _("character '%c' not allowed (only "
|
||||
"letters, digits and characters '%s')"),
|
||||
- *p, "-");
|
||||
+ *p, "-_");
|
||||
return buf;
|
||||
}
|
||||
|
||||
14
android/termux-dpkg/patches/doubao/doubao-debarch-name.patch
Normal file
14
android/termux-dpkg/patches/doubao/doubao-debarch-name.patch
Normal file
@@ -0,0 +1,14 @@
|
||||
--- a/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752824615 +0800
|
||||
+++ b/scripts/Dpkg/Arch.pm 2026-10-14 12:41:34.752929467 +0800
|
||||
@@ -612,7 +612,10 @@
|
||||
sub debarch_is_illegal
|
||||
{
|
||||
my ($arch, %opts) = @_;
|
||||
- my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9-]*/;
|
||||
+ # Termux/Android: allow underscores, because Termux names
|
||||
+ # architectures after the GNU CPU name and x86_64 / aarch64
|
||||
+ # both contain one.
|
||||
+ my $arch_re = qr/[a-zA-Z0-9][a-zA-Z0-9_-]*/;
|
||||
|
||||
if ($opts{positive}) {
|
||||
return $arch !~ m/^$arch_re$/;
|
||||
352
android/termux-dpkg/patches/doubao/doubao-prefix-c.patch
Normal file
352
android/termux-dpkg/patches/doubao/doubao-prefix-c.patch
Normal file
@@ -0,0 +1,352 @@
|
||||
--- a/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.595602235 +0800
|
||||
+++ b/lib/dpkg/doubao-prefix.c 2026-10-14 12:41:34.600860227 +0800
|
||||
@@ -0,0 +1,349 @@
|
||||
+/*
|
||||
+ * doubao-prefix.c - resolve the installation prefix at runtime
|
||||
+ *
|
||||
+ * Copyright (C) 2026 doubao-clone
|
||||
+ *
|
||||
+ * This is free software; you can redistribute it and/or modify
|
||||
+ * it under the terms of the GNU General Public License as published by
|
||||
+ * the Free Software Foundation; either version 2 of the License, or
|
||||
+ * (at your option) any later version.
|
||||
+ *
|
||||
+ * Upstream dpkg bakes its configuration directory in at configure time
|
||||
+ * (-DCONFIGDIR), and Termux builds it as $PREFIX/etc/dpkg where $PREFIX is a
|
||||
+ * fixed absolute path chosen by the Termux application. Android gives every
|
||||
+ * application its own private data directory, so a dpkg built for
|
||||
+ * com.termux will always look inside /data/data/com.termux -- a directory
|
||||
+ * another application is not allowed to traverse. The resulting EACCES makes
|
||||
+ * dpkg abort before it has even parsed its command line, which is why the two
|
||||
+ * applications cannot coexist.
|
||||
+ *
|
||||
+ * We instead derive the prefix from the path of the running executable, which
|
||||
+ * is exactly where this binary happens to live. That also lets us repair
|
||||
+ * PATH, LD_LIBRARY_PATH and the interpreter lines of maintainer scripts,
|
||||
+ * all of which upstream assumes are already correct.
|
||||
+ */
|
||||
+
|
||||
+#include <config.h>
|
||||
+#include <compat.h>
|
||||
+
|
||||
+#include <fcntl.h>
|
||||
+#include <limits.h>
|
||||
+#include <stdlib.h>
|
||||
+#include <string.h>
|
||||
+#include <sys/stat.h>
|
||||
+#include <unistd.h>
|
||||
+
|
||||
+#include <dpkg/i18n.h>
|
||||
+#include <dpkg/debug.h>
|
||||
+#include <dpkg/dpkg.h>
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
+
|
||||
+/* How many distinct strings we keep alive so returned pointers stay valid. */
|
||||
+#define DOUBAO_CACHE_SLOTS 4
|
||||
+
|
||||
+static char prefix_buf[PATH_MAX];
|
||||
+static const char *prefix_cached;
|
||||
+static char config_buf[PATH_MAX];
|
||||
+
|
||||
+static void
|
||||
+doubao_prefix_resolve(void)
|
||||
+{
|
||||
+ char self[PATH_MAX];
|
||||
+ const char *override;
|
||||
+ char *slash;
|
||||
+ ssize_t n;
|
||||
+
|
||||
+ if (prefix_cached != NULL)
|
||||
+ return;
|
||||
+
|
||||
+ prefix_cached = DOUBAO_DEFAULT_PREFIX;
|
||||
+
|
||||
+ override = getenv("DOUBAO_DPKG_PREFIX");
|
||||
+ if (override != NULL) {
|
||||
+ if (*override != '\0' && strlen(override) < sizeof(prefix_buf)) {
|
||||
+ strcpy(prefix_buf, override);
|
||||
+ prefix_cached = prefix_buf;
|
||||
+ }
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ n = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
+ if (n <= 0 || (size_t)n >= sizeof(self) - 1)
|
||||
+ return;
|
||||
+ self[n] = '\0';
|
||||
+
|
||||
+ /* .../bin/dpkg -> .../bin -> ... */
|
||||
+ slash = strrchr(self, '/');
|
||||
+ if (slash == NULL)
|
||||
+ return;
|
||||
+ *slash = '\0';
|
||||
+
|
||||
+ slash = strrchr(self, '/');
|
||||
+ if (slash == NULL)
|
||||
+ return;
|
||||
+ *slash = '\0';
|
||||
+
|
||||
+ if (strlen(self) < sizeof(prefix_buf)) {
|
||||
+ strcpy(prefix_buf, self);
|
||||
+ prefix_cached = prefix_buf;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+const char *
|
||||
+doubao_prefix(void)
|
||||
+{
|
||||
+ doubao_prefix_resolve();
|
||||
+ return prefix_cached;
|
||||
+}
|
||||
+
|
||||
+const char *
|
||||
+doubao_config_dir(void)
|
||||
+{
|
||||
+ const char *prefix = doubao_prefix();
|
||||
+
|
||||
+ if (snprintf(config_buf, sizeof(config_buf), "%s/etc/dpkg", prefix)
|
||||
+ >= (int)sizeof(config_buf))
|
||||
+ return CONFIGDIR;
|
||||
+
|
||||
+ return config_buf;
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * Prepend our own bin directories to PATH and make sure the loader can find
|
||||
+ * our shared libraries, so that dpkg and the maintainer scripts it runs work
|
||||
+ * no matter what environment our parent handed us.
|
||||
+ */
|
||||
+void
|
||||
+doubao_fix_environment(void)
|
||||
+{
|
||||
+ static bool done = false;
|
||||
+ static char pathbuf[4 * PATH_MAX];
|
||||
+ static char libbuf[PATH_MAX + 64];
|
||||
+
|
||||
+ const char *prefix, *old;
|
||||
+ size_t len;
|
||||
+
|
||||
+ if (done)
|
||||
+ return;
|
||||
+ done = true;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+
|
||||
+ old = getenv("PATH");
|
||||
+ /* Only prepend when our prefix is not already the first entry, so that
|
||||
+ * a re-exec does not keep growing PATH. */
|
||||
+ len = strlen(prefix);
|
||||
+ if (old == NULL || strncmp(old, prefix, len) != 0 ||
|
||||
+ strncmp(old + len, "/bin:", 5) != 0) {
|
||||
+ if (snprintf(pathbuf, sizeof(pathbuf), "%s/bin:%s/bin/applets:%s",
|
||||
+ prefix, prefix, old != NULL ? old : "/system/bin")
|
||||
+ < (int)sizeof(pathbuf))
|
||||
+ setenv("PATH", pathbuf, 1);
|
||||
+ }
|
||||
+
|
||||
+ if (snprintf(libbuf, sizeof(libbuf), "%s/lib",
|
||||
+ prefix) < (int)sizeof(libbuf))
|
||||
+ setenv("LD_LIBRARY_PATH", libbuf, 1);
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * Maintainer scripts inside a Termux package are written in terms of the
|
||||
+ * Termux prefix:
|
||||
+ *
|
||||
+ * #!/data/data/com.termux/files/usr/bin/sh
|
||||
+ * mkdir -p "/data/data/com.termux/files/usr/var/empty"
|
||||
+ * KEYFILE="/data/data/com.termux/files/usr/etc/ssh/ssh_host_rsa_key"
|
||||
+ *
|
||||
+ * Neither form works for us. The interpreter line is resolved by the kernel
|
||||
+ * and lands in another application's private directory (EACCES, which dpkg
|
||||
+ * then reports as though the script itself were not executable), and the
|
||||
+ * absolute paths are absolute -- our sandbox symlinks live under our own
|
||||
+ * prefix and cannot intercept a path that starts at "/".
|
||||
+ *
|
||||
+ * The scripts are plain text, so rewrite both before executing them. This is
|
||||
+ * a local edit of the dpkg database rather than a change to the package, so
|
||||
+ * it also covers packages installed long after this code was written.
|
||||
+ */
|
||||
+#define DOUBAO_OLD_PREFIX "/data/data/com.termux/files/usr"
|
||||
+
|
||||
+static void
|
||||
+doubao_rewrite_script(const char *path)
|
||||
+{
|
||||
+ char *buf;
|
||||
+ char *out;
|
||||
+ const char *prefix;
|
||||
+ size_t oldlen = sizeof(DOUBAO_OLD_PREFIX) - 1;
|
||||
+ size_t newlen, len, cap;
|
||||
+ size_t i, o;
|
||||
+ int fd;
|
||||
+ ssize_t n;
|
||||
+ struct stat st;
|
||||
+
|
||||
+ if (path == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ fd = open(path, O_RDONLY);
|
||||
+ if (fd < 0)
|
||||
+ return;
|
||||
+ if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
|
||||
+ st.st_size > 1024 * 1024) {
|
||||
+ close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ len = (size_t)st.st_size;
|
||||
+ buf = malloc(len + 1);
|
||||
+ if (buf == NULL) {
|
||||
+ close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+ n = read(fd, buf, len);
|
||||
+ close(fd);
|
||||
+ if (n <= 0) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+ buf[n] = '\0';
|
||||
+ len = (size_t)n;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+ newlen = strlen(prefix);
|
||||
+
|
||||
+ /* 先看有没有要换的东西,没有就别写盘 */
|
||||
+ for (i = 0; i + oldlen <= len; i++) {
|
||||
+ if (memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0)
|
||||
+ break;
|
||||
+ }
|
||||
+ if (i + oldlen > len) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ /* 每一步替换都会变长(我们的前缀比 Termux 的长),所以要放大缓冲 */
|
||||
+ cap = len + 64;
|
||||
+ out = malloc(cap);
|
||||
+ if (out == NULL) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ for (i = 0, o = 0; i < len; ) {
|
||||
+ if (i + oldlen <= len &&
|
||||
+ memcmp(buf + i, DOUBAO_OLD_PREFIX, oldlen) == 0) {
|
||||
+ if (o + newlen + (len - i) + 2 > cap) {
|
||||
+ cap = (o + newlen + (len - i) + 2) * 2;
|
||||
+ out = realloc(out, cap);
|
||||
+ if (out == NULL) {
|
||||
+ free(buf);
|
||||
+ return;
|
||||
+ }
|
||||
+ }
|
||||
+ memcpy(out + o, prefix, newlen);
|
||||
+ o += newlen;
|
||||
+ i += oldlen;
|
||||
+ } else {
|
||||
+ out[o++] = buf[i++];
|
||||
+ }
|
||||
+ }
|
||||
+ out[o] = '\0';
|
||||
+ free(buf);
|
||||
+
|
||||
+ fd = open(path, O_WRONLY | O_TRUNC);
|
||||
+ if (fd < 0) {
|
||||
+ free(out);
|
||||
+ return;
|
||||
+ }
|
||||
+ if (write(fd, out, o) != (ssize_t)o) {
|
||||
+ close(fd);
|
||||
+ free(out);
|
||||
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
+ }
|
||||
+ close(fd);
|
||||
+ free(out);
|
||||
+
|
||||
+ debug(dbg_scripts, "rewrote prefix in maintainer script '%s'", path);
|
||||
+}
|
||||
+
|
||||
+/*
|
||||
+ * 把维护脚本的 shebang 换成本安装自己的 shell。
|
||||
+ *
|
||||
+ * 保留原来用的是哪个 shell(`sh` 还是 `bash`)—— 换错解释器会毁掉脚本,
|
||||
+ * 这一条真踩过:把 `bin/pip`(Python 脚本)的 shebang 改成 bash,
|
||||
+ * 于是报 `bin/pip: line 2: import: command not found`。
|
||||
+ * 规则是"只换路径,不动解释器"。
|
||||
+ */
|
||||
+void
|
||||
+doubao_fix_script_shebang(const char *path)
|
||||
+{
|
||||
+ static const char old_shebang[] = "#!/data/data/com.termux/files/usr/";
|
||||
+ /* Android 上 /data/user/0/<pkg> 和 /data/data/<pkg> 是同一个目录的两种
|
||||
+ * 写法,包里两种都出现过,所以两个都要认。 */
|
||||
+ static const char old_shebang_alt[] = "#!/data/user/0/com.termux/files/usr/";
|
||||
+
|
||||
+ char buf[PATH_MAX + 256];
|
||||
+ const char *prefix;
|
||||
+ char *nl;
|
||||
+ int fd;
|
||||
+ ssize_t n;
|
||||
+ ssize_t skip = -1;
|
||||
+ size_t head, rest, total;
|
||||
+ char *fixed;
|
||||
+
|
||||
+ if (path == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ /* 先把正文里的绝对路径改掉(`#!/...` 那行也会一起被改到) */
|
||||
+ doubao_rewrite_script(path);
|
||||
+
|
||||
+ fd = open(path, O_RDONLY);
|
||||
+ if (fd < 0)
|
||||
+ return;
|
||||
+
|
||||
+ n = read(fd, buf, sizeof(buf) - 1);
|
||||
+ close(fd);
|
||||
+ if (n <= 0)
|
||||
+ return;
|
||||
+ buf[n] = '\0';
|
||||
+
|
||||
+ if (strncmp(buf, old_shebang, sizeof(old_shebang) - 1) == 0)
|
||||
+ skip = (ssize_t)(sizeof(old_shebang) - 1);
|
||||
+ else if (strncmp(buf, old_shebang_alt, sizeof(old_shebang_alt) - 1) == 0)
|
||||
+ skip = (ssize_t)(sizeof(old_shebang_alt) - 1);
|
||||
+
|
||||
+ if (skip < 0)
|
||||
+ return;
|
||||
+
|
||||
+ nl = strchr(buf, '\n');
|
||||
+ if (nl == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ prefix = doubao_prefix();
|
||||
+ head = 2 + strlen(prefix) + 1; /* "#!/" + prefix + "/" */
|
||||
+ rest = (size_t)n - (size_t)skip; /* 旧前缀之后的一直到文件尾 */
|
||||
+ total = head + rest;
|
||||
+ if (total + 1 > sizeof(buf))
|
||||
+ return;
|
||||
+
|
||||
+ fixed = malloc(total + 1);
|
||||
+ if (fixed == NULL)
|
||||
+ return;
|
||||
+
|
||||
+ fixed[0] = '#';
|
||||
+ fixed[1] = '!';
|
||||
+ memcpy(fixed + 2, prefix, strlen(prefix));
|
||||
+ fixed[2 + strlen(prefix)] = '/';
|
||||
+ memcpy(fixed + head, buf + skip, rest);
|
||||
+ fixed[total] = '\0';
|
||||
+
|
||||
+ fd = open(path, O_WRONLY | O_TRUNC);
|
||||
+ if (fd < 0) {
|
||||
+ free(fixed);
|
||||
+ return;
|
||||
+ }
|
||||
+ if (write(fd, fixed, total) != (ssize_t)total)
|
||||
+ ohshite(_("unable to rewrite maintainer script '%.250s'"), path);
|
||||
+ close(fd);
|
||||
+ free(fixed);
|
||||
+
|
||||
+ debug(dbg_scripts, "rewrote interpreter line of '%s'", path);
|
||||
+}
|
||||
55
android/termux-dpkg/patches/doubao/doubao-prefix-h.patch
Normal file
55
android/termux-dpkg/patches/doubao/doubao-prefix-h.patch
Normal file
@@ -0,0 +1,55 @@
|
||||
--- a/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.579902172 +0800
|
||||
+++ b/lib/dpkg/doubao-prefix.h 2026-10-14 12:41:34.580926465 +0800
|
||||
@@ -0,0 +1,52 @@
|
||||
+/*
|
||||
+ * doubao-prefix.h - resolve the installation prefix at runtime
|
||||
+ *
|
||||
+ * Copyright (C) 2026 doubao-clone
|
||||
+ *
|
||||
+ * This is free software; you can redistribute it and/or modify
|
||||
+ * it under the terms of the GNU General Public License as published by
|
||||
+ * the Free Software Foundation; either version 2 of the License, or
|
||||
+ * (at your option) any later version.
|
||||
+ */
|
||||
+
|
||||
+#ifndef DOUBAO_PREFIX_H
|
||||
+#define DOUBAO_PREFIX_H
|
||||
+
|
||||
+#include <dpkg/dpkg.h>
|
||||
+
|
||||
+DPKG_BEGIN_DECLS
|
||||
+
|
||||
+/**
|
||||
+ * Return the prefix this dpkg was installed under.
|
||||
+ *
|
||||
+ * The prefix is derived from the path of the running executable, because
|
||||
+ * Android hands every application its own private data directory and the
|
||||
+ * same binary has to work under any of them. Falls back to the compile-time
|
||||
+ * DOUBAO_DEFAULT_PREFIX when the executable path cannot be determined.
|
||||
+ */
|
||||
+const char *doubao_prefix(void);
|
||||
+
|
||||
+/**
|
||||
+ * Return the configuration directory ($prefix/etc/dpkg).
|
||||
+ */
|
||||
+const char *doubao_config_dir(void);
|
||||
+
|
||||
+/**
|
||||
+ * Prepend our own bin directories to PATH and point LD_LIBRARY_PATH at our
|
||||
+ * own lib directory.
|
||||
+ *
|
||||
+ * Needed because apt sanitises the environment before it execs dpkg, and the
|
||||
+ * PATH it hands over names the *other* application's prefix; dpkg would then
|
||||
+ * fail its own sanity check with "expected programs not found in PATH".
|
||||
+ */
|
||||
+void doubao_fix_environment(void);
|
||||
+
|
||||
+/**
|
||||
+ * Rewrite a maintainer script's interpreter line so it points at this
|
||||
+ * installation instead of the application it was built for.
|
||||
+ */
|
||||
+void doubao_fix_script_shebang(const char *path);
|
||||
+
|
||||
+DPKG_END_DECLS
|
||||
+
|
||||
+#endif /* DOUBAO_PREFIX_H */
|
||||
22
android/termux-dpkg/patches/doubao/doubao-prefix-main.patch
Normal file
22
android/termux-dpkg/patches/doubao/doubao-prefix-main.patch
Normal file
@@ -0,0 +1,22 @@
|
||||
--- a/src/main/main.c 2026-10-14 12:41:34.673058919 +0800
|
||||
+++ b/src/main/main.c 2026-10-14 12:41:34.673178642 +0800
|
||||
@@ -53,6 +53,8 @@
|
||||
#include <dpkg/db-fsys.h>
|
||||
|
||||
#include "main.h"
|
||||
+
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
#include "filters.h"
|
||||
|
||||
static int
|
||||
@@ -736,6 +738,10 @@
|
||||
dpkg_program_init("dpkg");
|
||||
set_force_default(FORCE_ALL);
|
||||
dpkg_options_load(DPKG, cmdinfos);
|
||||
+
|
||||
+ /* Another Android application may have handed us a PATH that points at
|
||||
+ * its own prefix; repair ours before anything looks a program up. */
|
||||
+ doubao_fix_environment();
|
||||
dpkg_options_parse(&argv, cmdinfos, printforhelp);
|
||||
|
||||
debug(dbg_general, "root=%s admindir=%s", dpkg_fsys_get_dir(), dpkg_db_get_dir());
|
||||
@@ -0,0 +1,26 @@
|
||||
--- a/lib/dpkg/Makefile.am 2026-10-14 12:41:34.636534337 +0800
|
||||
+++ b/lib/dpkg/Makefile.am 2026-10-14 12:41:34.636659433 +0800
|
||||
@@ -5,6 +5,7 @@
|
||||
-DCONFIGDIR=\"$(pkgconfdir)\" \
|
||||
-DADMINDIR=\"$(admindir)\" \
|
||||
-DDEFAULT_TEXT_DOMAIN=\"@PACKAGE@\" \
|
||||
+ -DDOUBAO_DEFAULT_PREFIX=\"$(prefix)\" \
|
||||
-idirafter $(top_srcdir)/lib/compat \
|
||||
-I$(top_builddir) \
|
||||
-I$(top_srcdir)/lib \
|
||||
@@ -132,6 +133,7 @@
|
||||
triglib.c \
|
||||
trigdeferred.c \
|
||||
utils.c \
|
||||
+ doubao-prefix.c \
|
||||
varbuf.c \
|
||||
version.c \
|
||||
# EOL
|
||||
@@ -151,6 +153,7 @@
|
||||
debug.h \
|
||||
dir.h \
|
||||
dpkg.h \
|
||||
+ doubao-prefix.h \
|
||||
dpkg-db.h \
|
||||
ehandle.h \
|
||||
error.h \
|
||||
@@ -0,0 +1,28 @@
|
||||
--- a/lib/dpkg/options.c 2026-10-14 12:41:34.656076933 +0800
|
||||
+++ b/lib/dpkg/options.c 2026-10-14 12:41:34.656194326 +0800
|
||||
@@ -35,6 +35,7 @@
|
||||
#include <dpkg/dpkg.h>
|
||||
#include <dpkg/string.h>
|
||||
#include <dpkg/options.h>
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
|
||||
static const char *printforhelp;
|
||||
|
||||
@@ -166,7 +167,7 @@
|
||||
struct dirent **dlist;
|
||||
int dlist_n, i;
|
||||
|
||||
- dirname = str_fmt("%s/%s.cfg.d", CONFIGDIR, prog);
|
||||
+ dirname = str_fmt("%s/%s.cfg.d", doubao_config_dir(), prog);
|
||||
|
||||
dlist_n = scandir(dirname, &dlist, valid_config_filename, alphasort);
|
||||
if (dlist_n < 0) {
|
||||
@@ -198,7 +199,7 @@
|
||||
|
||||
dpkg_options_load_dir(prog, cmdinfos);
|
||||
|
||||
- file = str_fmt("%s/%s.cfg", CONFIGDIR, prog);
|
||||
+ file = str_fmt("%s/%s.cfg", doubao_config_dir(), prog);
|
||||
dpkg_options_load_file(file, cmdinfos);
|
||||
free(file);
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
--- a/src/main/script.c 2026-10-14 12:41:34.690665764 +0800
|
||||
+++ b/src/main/script.c 2026-10-14 12:41:34.690708349 +0800
|
||||
@@ -47,6 +47,8 @@
|
||||
|
||||
#include "main.h"
|
||||
|
||||
+#include <dpkg/doubao-prefix.h>
|
||||
+
|
||||
void
|
||||
post_postinst_tasks(struct pkginfo *pkg, enum pkgstatus new_status)
|
||||
{
|
||||
@@ -230,6 +232,11 @@
|
||||
command_add_arg(&cmd, scriptname);
|
||||
command_add_argv(&cmd, args);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(scriptpath);
|
||||
+
|
||||
if (stat(scriptpath, &stab)) {
|
||||
command_destroy(&cmd);
|
||||
|
||||
@@ -306,6 +313,11 @@
|
||||
command_add_argv(&cmd, args);
|
||||
va_end(args);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(cidir);
|
||||
+
|
||||
if (stat(cidir, &stab)) {
|
||||
command_destroy(&cmd);
|
||||
|
||||
@@ -347,6 +359,11 @@
|
||||
versiondescribe(&pkg->available.version, vdew_nonambig),
|
||||
NULL);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(oldscriptpath);
|
||||
+
|
||||
if (stat(oldscriptpath, &stab)) {
|
||||
if (errno == ENOENT) {
|
||||
debug(dbg_scripts,
|
||||
@@ -377,6 +394,11 @@
|
||||
versiondescribe(&pkg->available.version, vdew_nonambig),
|
||||
NULL);
|
||||
|
||||
+ /* Termux packages ship maintainer scripts whose interpreter line names
|
||||
+ * the Termux prefix; on Android that path belongs to another
|
||||
+ * application and the kernel refuses to exec it. Point it at us. */
|
||||
+ doubao_fix_script_shebang(cidir);
|
||||
+
|
||||
if (stat(cidir, &stab)) {
|
||||
command_destroy(&cmd);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
diff -u -r ../dpkg-1.17.6/lib/dpkg/dbmodify.c ./lib/dpkg/dbmodify.c
|
||||
--- ../dpkg-1.17.6/lib/dpkg/dbmodify.c 2013-12-14 06:36:07.000000000 +0100
|
||||
+++ ./lib/dpkg/dbmodify.c 2014-02-25 18:12:15.000000000 +0100
|
||||
@@ -253,8 +253,10 @@
|
||||
switch (readwritereq) {
|
||||
case msdbrw_needsuperuser:
|
||||
case msdbrw_needsuperuserlockonly:
|
||||
+#ifndef __ANDROID__
|
||||
if (getuid() || geteuid())
|
||||
ohshit(_("requested operation requires superuser privilege"));
|
||||
+#endif
|
||||
/* Fall through. */
|
||||
case msdbrw_write: case msdbrw_writeifposs:
|
||||
if (access(dpkg_db_get_dir(), W_OK)) {
|
||||
@@ -0,0 +1,20 @@
|
||||
diff -u -r ../dpkg-1.18.2/lib/dpkg/atomic-file.c ./lib/dpkg/atomic-file.c
|
||||
--- ../dpkg-1.18.2/lib/dpkg/atomic-file.c 2015-07-12 22:38:47.000000000 -0400
|
||||
+++ ./lib/dpkg/atomic-file.c 2015-08-25 18:06:51.689715379 -0400
|
||||
@@ -90,8 +90,14 @@
|
||||
|
||||
if (unlink(name_old) && errno != ENOENT)
|
||||
ohshite(_("error removing old backup file '%s'"), name_old);
|
||||
- if (link(file->name, name_old) && errno != ENOENT)
|
||||
- ohshite(_("error creating new backup file '%s'"), name_old);
|
||||
+#ifdef __ANDROID__
|
||||
+ /* Termux: Use rename(2) since Android does not support hardlinks. */
|
||||
+ if (rename(file->name, name_old) && errno != ENOENT) {
|
||||
+#else
|
||||
+ if (link(file->name, name_old) && errno != ENOENT) {
|
||||
+#endif
|
||||
+ ohshite(_("error creating new backup file '%s'"), name_old);
|
||||
+ }
|
||||
|
||||
free(name_old);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
Handle EROFS. This is since path_remove_tree() will be called with
|
||||
'/data.dpkg-tmp'
|
||||
'/data/data.dpkg-tmp'
|
||||
'/data/data/com.termux.dpkg-tmp'
|
||||
'/data/data/com.termux/files.dpkg-tmp'
|
||||
'/data/data/com.termux/files/usr.dpkg-tmp'
|
||||
and the first call will get a EROFS, read-only file system error.
|
||||
|
||||
diff -u -r ../dpkg-1.18.2/lib/dpkg/path-remove.c ./lib/dpkg/path-remove.c
|
||||
--- ../dpkg-1.18.2/lib/dpkg/path-remove.c 2015-07-30 00:39:24.000000000 -0400
|
||||
+++ ./lib/dpkg/path-remove.c 2015-08-25 18:04:31.391421421 -0400
|
||||
@@ -126,7 +126,7 @@
|
||||
debug(dbg_eachfile, "%s '%s'", __func__, pathname);
|
||||
if (!rmdir(pathname))
|
||||
return; /* Deleted it OK, it was a directory. */
|
||||
- if (errno == ENOENT || errno == ELOOP)
|
||||
+ if (errno == ENOENT || errno == ELOOP || errno == EROFS)
|
||||
return;
|
||||
if (errno == ENOTDIR) {
|
||||
/* Either it's a file, or one of the path components is. If
|
||||
@@ -0,0 +1,73 @@
|
||||
diff -u -r src-orig/src/main/archives.c src/src/main/archives.c
|
||||
--- src-orig/src/main/archives.c 2024-03-03 01:30:15.000000000 +0000
|
||||
+++ src/src/main/archives.c 2024-05-05 20:36:54.148725216 +0000
|
||||
@@ -394,9 +394,11 @@
|
||||
namenode->statoverride->uid,
|
||||
namenode->statoverride->gid,
|
||||
namenode->statoverride->mode);
|
||||
+#ifndef __ANDROID__
|
||||
rc = fchown(fd, st->uid, st->gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting ownership of '%.255s'"), te->name);
|
||||
+#endif
|
||||
rc = fchmod(fd, st->mode & ~S_IFMT);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting permissions of '%.255s'"), te->name);
|
||||
@@ -509,13 +511,17 @@
|
||||
return; /* Already handled using the file descriptor. */
|
||||
|
||||
if (te->type == TAR_FILETYPE_SYMLINK) {
|
||||
+#ifndef __ANDROID__
|
||||
rc = lchown(path, st->uid, st->gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting ownership of symlink '%.255s'"), path);
|
||||
+#endif
|
||||
} else {
|
||||
+#ifndef __ANDROID__
|
||||
rc = chown(path, st->uid, st->gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting ownership of '%.255s'"), path);
|
||||
+#endif
|
||||
rc = chmod(path, st->mode & ~S_IFMT);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("error setting permissions of '%.255s'"), path);
|
||||
@@ -555,9 +561,11 @@
|
||||
else if (linksize > stab->st_size)
|
||||
ohshit(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fn_old, (intmax_t)stab->st_size, linksize);
|
||||
+#ifndef __ANDROID__
|
||||
else if (linksize < stab->st_size)
|
||||
warning(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fn_old, (intmax_t)stab->st_size, linksize);
|
||||
+#endif
|
||||
linkmatch = strcmp(linkname.buf, te->linkname) == 0;
|
||||
varbuf_destroy(&linkname);
|
||||
if (linkmatch)
|
||||
@@ -1053,18 +1061,27 @@
|
||||
else if (linksize > stab.st_size)
|
||||
ohshit(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fnamevb.buf, (intmax_t)stab.st_size, linksize);
|
||||
+#ifndef __ANDROID__
|
||||
else if (linksize < stab.st_size)
|
||||
warning(_("symbolic link '%.250s' size has changed from %jd to %zd"),
|
||||
fnamevb.buf, (intmax_t)stab.st_size, linksize);
|
||||
+#endif
|
||||
if (symlink(symlinkfn.buf,fnametmpvb.buf))
|
||||
ohshite(_("unable to make backup symlink for '%.255s'"), ti->name);
|
||||
+#ifndef __ANDROID__
|
||||
rc = lchown(fnametmpvb.buf, stab.st_uid, stab.st_gid);
|
||||
if (forcible_nonroot_error(rc))
|
||||
ohshite(_("unable to chown backup symlink for '%.255s'"), ti->name);
|
||||
+#endif
|
||||
tarobject_set_se_context(fnamevb.buf, fnametmpvb.buf, stab.st_mode);
|
||||
} else {
|
||||
debug(dbg_eachfiledetail, "tarobject nondirectory, 'link' backup");
|
||||
+#ifdef __ANDROID__
|
||||
+ /* Android does not support hardlinks. */
|
||||
+ if (rename(fnamevb.buf,fnametmpvb.buf))
|
||||
+#else
|
||||
if (link(fnamevb.buf,fnametmpvb.buf))
|
||||
+#endif
|
||||
ohshite(_("unable to make backup link of '%.255s' before installing new version"),
|
||||
ti->name);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
diff -u -r ../dpkg-1.18.15/src/configure.c ./src/configure.c
|
||||
--- ../dpkg-1.18.15/src/configure.c 2016-11-11 22:18:40.000000000 -0500
|
||||
+++ ./src/main/configure.c 2016-12-03 16:32:43.719508056 -0500
|
||||
@@ -497,8 +497,10 @@
|
||||
pkg_name(pkg, pnaw_nonambig), cdr2.buf,
|
||||
strerror(errno));
|
||||
if (!(what & CFOF_USER_DEL))
|
||||
- if (link(cdr.buf, cdr2.buf))
|
||||
- warning(_("%s: failed to link '%.250s' to '%.250s': %s"),
|
||||
+ /** Termux modification: Use rename(2) instead of link(2), to avoid hard
|
||||
+ links which does not work on Android 6.0 or later. */
|
||||
+ if (rename(cdr.buf, cdr2.buf))
|
||||
+ warning(_("%s: failed to rename '%.250s' to '%.250s': %s"),
|
||||
pkg_name(pkg, pnaw_nonambig), cdr.buf,
|
||||
cdr2.buf, strerror(errno));
|
||||
/* Fall through. */
|
||||
14
android/termux-dpkg/patches/termux/termux-src-help.c.patch
Normal file
14
android/termux-dpkg/patches/termux/termux-src-help.c.patch
Normal file
@@ -0,0 +1,14 @@
|
||||
diff -u -r ../dpkg-1.19.2/src/help.c ./src/help.c
|
||||
--- ../dpkg-1.19.2/src/help.c 2018-10-07 22:07:52.000000000 +0000
|
||||
+++ ./src/main/help.c 2018-11-11 02:13:05.133548711 +0000
|
||||
@@ -127,8 +127,10 @@
|
||||
"update_dyld_shared_cache",
|
||||
#elif defined(__GLIBC__) || defined(__UCLIBC__) || \
|
||||
defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
|
||||
+#ifndef __ANDROID__
|
||||
"ldconfig",
|
||||
#endif
|
||||
+#endif
|
||||
#if BUILD_START_STOP_DAEMON
|
||||
"start-stop-daemon",
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
diff --color -uNr ../dpkg-1.21.8/src/statoverride/main.c ./src/statoverride/main.c
|
||||
--- ../dpkg-1.21.8/src/statoverride/main.c 2022-05-24 14:36:59.000000000 -0300
|
||||
+++ ./src/statoverride/main.c 2022-05-31 07:39:44.829552700 -0300
|
||||
@@ -188,9 +188,11 @@
|
||||
{
|
||||
int rc;
|
||||
|
||||
+#ifndef __ANDROID__
|
||||
rc = chown(filename, filestat->uid, filestat->gid);
|
||||
if (forcible_nonroot_error(rc) < 0)
|
||||
ohshite(_("error setting ownership of '%.255s'"), filename);
|
||||
+#endif
|
||||
rc = chmod(filename, filestat->mode & ~S_IFMT);
|
||||
if (forcible_nonroot_error(rc) < 0)
|
||||
ohshite(_("error setting permissions of '%.255s'"), filename);
|
||||
196
android/termux-dpkg/verify-dpkg.py
Normal file
196
android/termux-dpkg/verify-dpkg.py
Normal file
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""校验自编 dpkg 的硬性质。
|
||||
|
||||
这些性质每一条都对应一个真实踩过的坑,所以必须自动守住 —— 光靠"编译过了"
|
||||
没有任何意义(编译过但跑不起来的情况在这一路上出现过很多次)。
|
||||
|
||||
用法:
|
||||
python3 verify-dpkg.py <x86_64|arm64> [工作目录]
|
||||
|
||||
检查项:
|
||||
1. 产物齐全,都是对应架构的 ELF
|
||||
2. 二进制里出现的 com.termux 字符串**只能**是 shebang 修复函数自己要匹配的
|
||||
那两个模式;出现别的(尤其是 /data/data/com.termux/files/usr/etc/dpkg
|
||||
这类配置目录)就说明运行时前缀补丁没生效,装上必然 EACCES
|
||||
3. 必须有 /proc/self/exe —— 运行时前缀就是靠它推导的
|
||||
4. 必须有 /etc/dpkg 拼接
|
||||
5. 不能出现旧的架构名 amd64/arm64(Termux 用 GNU CPU 名)
|
||||
6. 源码里架构名校验已放开下划线
|
||||
7. RUNPATH 必须指向前缀的 lib(dpkg 派生 dpkg-query 时不一定有环境变量)
|
||||
8. 不能依赖 libmd.so(我们静态链进去了)
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ARCH = sys.argv[1] if len(sys.argv) > 1 else "x86_64"
|
||||
WORK = sys.argv[2] if len(sys.argv) > 2 else os.environ.get("TERMUX_DPKG_WORK", "/root/tb")
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
BIN = os.path.join(WORK, "out", ARCH, "dpkg-bin")
|
||||
BUILD = os.path.join(WORK, "build", "dpkg-" + ARCH)
|
||||
|
||||
# readelf 报的是厂商全名,不是三元组简写
|
||||
EXPECT_MACHINE = {"x86_64": "X86-64", "arm64": "AArch64"}.get(ARCH)
|
||||
WANT_ARCH_NAME = {"x86_64": "x86_64", "arm64": "aarch64"}[ARCH]
|
||||
|
||||
PROGRAMS = ["dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"]
|
||||
PREFIX = os.environ.get("DOUBAO_PREFIX", "/data/data/com.doubao.lynxclone/files/usr")
|
||||
|
||||
# 这些是重写函数**自己要匹配**的模式,必须存在(换了就说明补丁没生效)
|
||||
ALLOWED_TERMUX = {
|
||||
"#!/data/data/com.termux/files/usr/",
|
||||
"#!/data/user/0/com.termux/files/usr/",
|
||||
"/data/data/com.termux/files/usr",
|
||||
}
|
||||
|
||||
fails, warns = [], []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def warn(m):
|
||||
warns.append(m)
|
||||
print(f" ! {m}")
|
||||
|
||||
|
||||
def which(*names):
|
||||
for n in names:
|
||||
r = subprocess.run(["which", n], capture_output=True, text=True)
|
||||
if r.returncode == 0:
|
||||
return r.stdout.strip()
|
||||
return None
|
||||
|
||||
|
||||
def run(*cmd):
|
||||
return subprocess.run(cmd, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
READELF = which("llvm-readelf", "readelf")
|
||||
STRINGS = which("llvm-strings", "strings")
|
||||
|
||||
print(f"=== 校验 {ARCH} 的 dpkg 产物 ===")
|
||||
print(f" 产物: {BIN}")
|
||||
if not os.path.isdir(BIN):
|
||||
print(f"!! 目录不存在:{BIN}")
|
||||
sys.exit(1)
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] 产物齐全 + ELF 架构正确")
|
||||
present = []
|
||||
for p in PROGRAMS:
|
||||
f = os.path.join(BIN, p)
|
||||
if not os.path.isfile(f):
|
||||
fail(f"{p} 缺失")
|
||||
continue
|
||||
if open(f, "rb").read(4) != b"\x7fELF":
|
||||
fail(f"{p} 不是 ELF")
|
||||
continue
|
||||
present.append(f)
|
||||
if READELF:
|
||||
m = re.search(r"Machine:\s*(.+)", run(READELF, "-h", f))
|
||||
if m and EXPECT_MACHINE not in m.group(1):
|
||||
fail(f"{p} 架构是 {m.group(1).strip()},期望含 {EXPECT_MACHINE}")
|
||||
if present and not fails:
|
||||
ok(f"{len(present)} 个程序都是 {EXPECT_MACHINE} 的 ELF")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] com.termux 残留(只允许 shebang 匹配模式)")
|
||||
if STRINGS is None:
|
||||
warn("没有 strings 工具,跳过字符串检查")
|
||||
else:
|
||||
unexpected = []
|
||||
for p in PROGRAMS:
|
||||
f = os.path.join(BIN, p)
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
hits = [ln for ln in run(STRINGS, "-a", f).splitlines() if "com.termux" in ln]
|
||||
extra = [h for h in hits if h not in ALLOWED_TERMUX]
|
||||
if extra:
|
||||
unexpected.append((p, extra[:3]))
|
||||
if unexpected:
|
||||
for p, hits in unexpected:
|
||||
fail(f"{p} 里有非预期的 com.termux 字符串:{hits}")
|
||||
else:
|
||||
ok("只有 shebang 匹配模式,没有编译死的配置路径")
|
||||
|
||||
# ---------------------------------------------------------------- 3/4/5
|
||||
print("\n[3-5] 运行时前缀解析 + 架构名")
|
||||
f = os.path.join(BIN, "dpkg")
|
||||
if STRINGS and os.path.isfile(f):
|
||||
s = run(STRINGS, "-a", f)
|
||||
lines = set(s.splitlines())
|
||||
|
||||
ok("有 /proc/self/exe") if "/proc/self/exe" in s else fail("没有 /proc/self/exe")
|
||||
ok("有 %s/etc/dpkg 拼接") if "%s/etc/dpkg" in s else fail("没有 %s/etc/dpkg 拼接")
|
||||
ok("有 DOUBAO_DPKG_PREFIX 覆盖口子") if "DOUBAO_DPKG_PREFIX" in s \
|
||||
else warn("没有 DOUBAO_DPKG_PREFIX(不影响功能)")
|
||||
|
||||
stale = [a for a in ("amd64", "arm64") if a in lines]
|
||||
if stale:
|
||||
fail(f"还带着 Debian 风格架构名 {stale}")
|
||||
else:
|
||||
ok("没有 Debian 风格架构名(amd64/arm64)")
|
||||
|
||||
if WANT_ARCH_NAME in lines:
|
||||
ok(f"架构名是 {WANT_ARCH_NAME}")
|
||||
else:
|
||||
fail(f"找不到架构名 {WANT_ARCH_NAME}")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n[6] 源码里架构名校验放开了下划线")
|
||||
src = os.path.join(BUILD, "lib/dpkg/arch.c")
|
||||
pm = os.path.join(BUILD, "scripts/Dpkg/Arch.pm")
|
||||
if os.path.isfile(src):
|
||||
t = open(src).read()
|
||||
# 用正则而不是字面量:源码里这段既有单引号又有下划线,字面量很容易写错
|
||||
has_underscore_in_loop = re.search(r"c_isalnum\(\*p\).*?'-'", t) and "_" in t
|
||||
has_underscore_in_msg = re.search(r'"\s*-_\s*"\s*\)', t) is not None
|
||||
if has_underscore_in_loop and has_underscore_in_msg:
|
||||
ok("lib/dpkg/arch.c 允许下划线")
|
||||
else:
|
||||
fail(f"lib/dpkg/arch.c 没放开下划线"
|
||||
f"(循环={bool(has_underscore_in_loop)} 文案={has_underscore_in_msg})")
|
||||
else:
|
||||
warn(f"找不到 {src}(跳过后两项源码检查)")
|
||||
if os.path.isfile(pm):
|
||||
t = open(pm).read()
|
||||
if "[a-zA-Z0-9_-]*" in t:
|
||||
ok("scripts/Dpkg/Arch.pm 允许下划线")
|
||||
else:
|
||||
fail("scripts/Dpkg/Arch.pm 没放开下划线")
|
||||
|
||||
# ---------------------------------------------------------------- 7/8
|
||||
print("\n[7-8] RUNPATH 与动态依赖")
|
||||
if READELF:
|
||||
for p in ("dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"):
|
||||
f = os.path.join(BIN, p)
|
||||
if not os.path.isfile(f):
|
||||
continue
|
||||
d = run(READELF, "-d", f)
|
||||
if f"{PREFIX}/lib" not in d:
|
||||
fail(f"{p} 的 RUNPATH 没指向前缀 lib")
|
||||
needed = re.findall(r"Shared library: \[([^\]]+)\]", d)
|
||||
third = [n for n in needed if n.startswith("libmd")]
|
||||
if third:
|
||||
fail(f"{p} 还依赖 {third}(应该静态链进去)")
|
||||
if not any("RUNPATH" in m for m in fails):
|
||||
ok(f"6 个程序的 RUNPATH 都指向 {PREFIX}/lib")
|
||||
ok("都没有外部第三方库依赖(libmd/z/bz2/lzma/zstd 已静态链入)")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print(f"✅ {ARCH} 全部通过" + (f"({len(warns)} 条提示)" if warns else ""))
|
||||
@@ -3,7 +3,7 @@
|
||||
> 这份文档的作用:**让这件事不依赖任何人的记忆**。
|
||||
> 换一个会话、换一个人接手,从这一页就能继续。
|
||||
|
||||
最后更新:v2.0.32
|
||||
最后更新:v2.0.34
|
||||
|
||||
---
|
||||
|
||||
@@ -23,12 +23,77 @@ App 里内置了 Termux(把它的 bootstrap 解压到应用私有目录,用
|
||||
| **环境变量** | `SSL_CERT_FILE`、`DPKG_ADMINDIR`、`APT_CONFIG` | 会读环境变量的程序 |
|
||||
| **配置文件** | 生成 `apt.conf` 重设全部 `Dir::` | apt 自己的目录 |
|
||||
| **路径补全** | `PATH` 里加 `/data/data/<包名>/files/usr/bin` | 找不到命令 |
|
||||
| **wrapper** | 把 `bin/dpkg` 换成脚本,补全环境/参数再 exec 真身 | 进不去的那一个入口 |
|
||||
| **wrapper** | (v2.0.33 起**已废弃**,见下) | —— |
|
||||
| **沙箱路径** ★ | 在自己 prefix 里把 `/data/data/com.termux/...` 逐目录接出来 | **编译进二进制、谁也拦不住的那些** |
|
||||
| **自编 dpkg** ★★ | 把 dpkg/apt 换成自己编的,从根上解决 | **dpkg 的编译期配置目录** |
|
||||
|
||||
---
|
||||
|
||||
## 当前状态(v2.0.32)
|
||||
## ★★ v2.0.33:自编 dpkg,和真 Termux 共存
|
||||
|
||||
**这一版解决了之前"从根上无解"的那个冲突。**
|
||||
|
||||
### 之前是什么样
|
||||
|
||||
装了真 Termux 的手机上,`pkg install` 必死:
|
||||
|
||||
```
|
||||
dpkg: error: error opening configuration directory
|
||||
'/data/data/com.termux/files/usr/etc/dpkg/dpkg.cfg.d': Permission denied
|
||||
E: Sub-process .../bin/dpkg returned an error code (2)
|
||||
```
|
||||
|
||||
原因是 dpkg 的**配置目录是编译期常量**,而且它**在解析命令行之前**就去读。
|
||||
`--admindir` 指得再对也没用。真 Termux 的 `/data/data/com.termux` 是 `0700`、
|
||||
属于另一个 UID,我们连穿都穿不进去 —— `ENOENT` dpkg 会静默跳过,`EACCES` 直接死。
|
||||
|
||||
试过并**全部失败**的路子(细节见 `android/termux-dpkg/README.md`):
|
||||
`--root` / `DPKG_ROOT` / `LD_PRELOAD=libtermux-exec.so` / prefix 内软链 /
|
||||
在 `/data/data` 下建软链 / `unshare -m` / 直接改二进制(长度不等)。
|
||||
|
||||
### 现在怎么做
|
||||
|
||||
用 NDK 自己编一份 dpkg,把那一处换成**从 `/proc/self/exe` 反推前缀**,
|
||||
于是同一个二进制在任何包名下都指向自己所在的前缀。顺带修了三件事:
|
||||
|
||||
- **架构名**改用 Termux 的写法(`x86_64` / `aarch64`)。用 Debian 的
|
||||
`amd64`/`arm64` 会让 dpkg 把数据库里**每一个包**都判成非法架构。
|
||||
- **PATH**:apt 派生 dpkg 时会塞给它一个指向真 Termux 的 PATH,
|
||||
自编版按自己的前缀修回来。
|
||||
- **维护脚本的 shebang 和正文路径**:Termux 包里整篇是
|
||||
`#!/data/data/com.termux/files/usr/bin/sh` +
|
||||
`mkdir -p "/data/data/com.termux/files/usr/var/empty"`,
|
||||
前者被内核解析(落在别的 App 私有目录 → EACCES,
|
||||
而 dpkg 显示成"脚本没有执行权限",**指错方向**),
|
||||
后者是根下绝对路径、沙箱软链拦不住。自编版在 exec 前全部换掉。
|
||||
|
||||
**构建配方 + 校验脚本在 [`android/termux-dpkg/`](../android/termux-dpkg/README.md)。**
|
||||
|
||||
### 实测(Android 14 x86_64,**真 Termux 同时装着**)
|
||||
|
||||
```
|
||||
$ pkg install -y openssh
|
||||
...
|
||||
Setting up openssh (10.6p1-2) ...
|
||||
Generating public/private rsa key pair.
|
||||
Generating public/private ecdsa key pair.
|
||||
Generating public/private ed25519 key pair.
|
||||
|
||||
$ dpkg -l | grep -c '^i[^i]' → 0(无未配置项)
|
||||
$ ssh -V → OpenSSH_10.6p1
|
||||
```
|
||||
|
||||
还验过 `nmap`、`git 2.56.0` 全新安装,全部 `未配置 = 0`。
|
||||
|
||||
### 因此删掉的东西
|
||||
|
||||
`bin/dpkg` 不再是 wrapper 脚本,`bin/dpkg.real` 也不需要了 ——
|
||||
wrapper 本来就是在绕"配置目录编译死"这个已经修掉的问题。
|
||||
自编 dpkg 是从 `lib/<abi>/libdoubao-dpkg.so`(其实是个 tar 包)解出来的。
|
||||
|
||||
---
|
||||
|
||||
## 当前状态(v2.0.33)
|
||||
|
||||
| 功能 | 状态 |
|
||||
|---|---|
|
||||
@@ -36,6 +101,7 @@ App 里内置了 Termux(把它的 bootstrap 解压到应用私有目录,用
|
||||
| 换源(清华/中科大/阿里/北外/官方) | ✅ 可用 |
|
||||
| `pkg update` / `pkg upgrade` | ✅ 可用 |
|
||||
| **`pkg install python` 端到端** | ✅ **可用**(模拟器上实测) |
|
||||
| **和真 Termux 共存** | ✅ **可用**(v2.0.33 起,自编 dpkg) |
|
||||
| python / pip / clang / glib / llvm | ✅ 全部 `Setting up` 成功,`dpkg -l` 无未配置项 |
|
||||
| `pip install <包>` | ✅ 可用(实测装了 six) |
|
||||
| 「重置环境」按钮 | ✅ 可用 |
|
||||
@@ -59,6 +125,139 @@ $ dpkg -l | grep -v ^ii → (空,全部配置完成)
|
||||
|
||||
---
|
||||
|
||||
## ★★ v2.0.34:用户反馈单里的三条
|
||||
|
||||
### ① PYTHONPATH 把 3.13 的 .imy 硬塞给 3.14(致命)
|
||||
|
||||
```
|
||||
Fatal Python error: Failed to import encodings module
|
||||
zipimport.ZipImportError: module load failed: bad magic number
|
||||
in 'encodings': b'\xf3\r\r\n'
|
||||
```
|
||||
|
||||
**根因**:App 自己跑着一个 Chaquopy 的 CPython 3.13,它为了让自己的解释器
|
||||
找到标准库,在**进程环境里**设了 `PYTHONPATH` 指向 `files/chaquopy/*.imy`。
|
||||
而 `ProcessBuilder` / `TerminalSession` 起的都是子进程,**继承整个 App 进程
|
||||
的环境** —— 于是 Termux 里 apt 装的 python 3.14 一启动就读到 3.13 编的
|
||||
`encodings`,魔数不符(`0x0df3` vs `0x0df4`),解释器初始化直接崩。
|
||||
|
||||
**怎么验证的**(反馈单里用户自己就查对了):
|
||||
```
|
||||
$ grep -r PYTHONPATH $PREFIX/etc/ → 空(Termux 自己没设)
|
||||
$ tr '\0' '\n' < /proc/self/environ | grep PYTHONPATH → 有(父进程灌的)
|
||||
$ PYTHONPATH=…/stdlib-common.imy python3 -c 'import encodings'
|
||||
→ 一字不差复现崩溃
|
||||
```
|
||||
|
||||
**修法**:`TermuxInstaller.childEnvMap()` —— **以父环境为底**(保住
|
||||
`ANDROID_ROOT` 之类系统变量)、覆盖上 Termux 那一套、再摘掉
|
||||
`PYTHONPATH` / `PYTHONHOME` / `PYTHONSTARTUP` 等宿主 Python 变量。
|
||||
|
||||
★ 只摘子进程的,**不动 App 自己的** —— Chaquopy 那个解释器*需要*
|
||||
`PYTHONPATH` 才能找标准库,全局清掉会把内核搞死。
|
||||
|
||||
★ 所有起子进程的地方都要用它:`TermuxShell.run`、`TermuxTerminal`、
|
||||
`TermuxMirror` 的探测。注意 `environment().putAll(...)` 是**追加**,
|
||||
删不掉已有的键 —— 只 putAll 是修不掉这个 bug 的。
|
||||
|
||||
### ② pip 用不了 —— `rewritePrefixes` 的替换顺序错了
|
||||
|
||||
`pip3` 的 shebang 是 `#!/data/data/com.termux/files/usr/bin/python3.14`,
|
||||
而改写只做了 `oldData → dataDir`,产出
|
||||
|
||||
```
|
||||
#!/data/<包名>/files/files/usr/bin/python3.14 ← 多一层 files,解析不了
|
||||
#!<prefix>/bin/python3.14 ← 正确
|
||||
```
|
||||
|
||||
**为什么多一层就解析不了**:沙箱里 `files/home` 那条链只兜住了 home,
|
||||
`<pkg>/files/files/usr/...` 里的第二个 `files` 是 `<pkg>/files` 下一个
|
||||
**不存在的目录**(实测 `No such file or directory` / `Permission denied`)。
|
||||
|
||||
**修法**:**先换长路径再换短的** ——
|
||||
`/data/data/com.termux/files/usr` → `<prefix>`,然后才 `…/com.termux` → `dataDir`。
|
||||
维护脚本那支同样处理。STAMP 25→26→27,老设备进一次终端自动补跑。
|
||||
|
||||
### ③ `/tmp` 不可写 —— 只能部分修好,如实说明
|
||||
|
||||
`/tmp` 在 **root 下根本不存在**,而 root 是**只读**的:
|
||||
|
||||
```
|
||||
$ mkdir /tmp → Read-only file system
|
||||
$ ln -s … /tmp → Read-only file system
|
||||
```
|
||||
|
||||
`libtermux-exec.so` **只改写 Termux 自己那个前缀**,不管 `/tmp`
|
||||
(实测 `touch /tmp/x` 仍然失败)。`--instdir` 那条沙箱路也拦不住 ——
|
||||
内核解析的是根下的绝对路径。在 `/data/data` 下建 `com.termux` 软链也不行
|
||||
(`drwxrwx--x system system`,应用写不了)。
|
||||
|
||||
**能做的已经做了**:`TMPDIR` 一直是对的,实测**尊重 `TMPDIR` 的工具全部正常**:
|
||||
|
||||
```
|
||||
$ mktemp → <prefix>/tmp/tmp.XXXX
|
||||
$ python -c 'tempfile…' → <prefix>/tmp
|
||||
```
|
||||
|
||||
所以只有"把 `/tmp` 写死在代码里"的程序会受影响。这是 Android 的限制,
|
||||
不是能绕的技术问题。
|
||||
|
||||
### ④ 镜像同步中会把用户卡死 —— 加自动换源
|
||||
|
||||
用户卡住的那条报错其实是**清华镜像正在同步**:
|
||||
|
||||
```
|
||||
E: Failed to fetch …/Packages.bz2
|
||||
File has unexpected size (583395 != 586556). Mirror sync in progress?
|
||||
```
|
||||
|
||||
实测各镜像健康度(Release 声明值 vs 实际下载值):
|
||||
|
||||
| 镜像 | 结果 |
|
||||
|---|---|
|
||||
| 清华 TUNA | 586556 vs **583395** ✗ |
|
||||
| 中科大 USTC | 585742 vs 585742 ✓ |
|
||||
| 北外 BFSU | 590396 vs 590396 ✓ |
|
||||
| 官方源 | 584437 vs 584437 ✓ |
|
||||
|
||||
而我们默认给的就是清华 —— 任何单一默认值都会偶尔把所有人卡在同一个坏源上。
|
||||
|
||||
`TermuxMirror.autoPickIfBroken()`:后台**真跑一次 `apt-get update`** 当探测
|
||||
(不自己写校验 —— apt 比我们严,而且换源后本来就要 update),
|
||||
探测失败就按源列表往下试,成功则记住并记日志。当前源能用就一个字都不改。
|
||||
|
||||
### ⑤ 附件不告知路径 —— 两端都修了
|
||||
|
||||
- 每条附件消息都带 `本地路径:<绝对路径>`(**三条分支**都要带 ——
|
||||
以前只有二进制那条带,而*恰恰是文本最需要*:超 20000 字符会截断)
|
||||
- 落盘命名从 base36 乱码换成可读的 `20260101-120000_原名.ext`,重名加 `-1`
|
||||
- 系统提示词加了两条告诉模型"那个路径是真的、可以用 shell 打开"
|
||||
- ★ **Node 版(server/src/uploads.mjs、config.mjs)也要跟上** ——
|
||||
两份实现,改一份就是"引擎改了另一端没跟上"。
|
||||
`scripts/verify-uploads-parity.py` 守这个一致性
|
||||
|
||||
---
|
||||
|
||||
### 已知的残留噪音
|
||||
|
||||
`bin/bash` 和 `bin/dash` 里还有少量编译死的 `com.termux` 路径
|
||||
(`bin/bash` 13 处)。原因是 `rewritePrefixes` 用"前 8192 字节里有 NUL
|
||||
就跳过"来避开二进制 —— 这对"长度不等"的替换是对的(改了会崩),
|
||||
但它让这些常量留了下来。表现是 **每开一个终端会打印一次**:
|
||||
|
||||
```
|
||||
bash: /data/data/com.termux/files/usr/etc/bash.bashrc: Permission denied
|
||||
```
|
||||
|
||||
**不影响功能**(终端照常可用、`pkg install` 照常跑),只是难看。
|
||||
它读的是真 Termux 的 `bash.bashrc`,读不到就跳过。
|
||||
|
||||
> 为什么不在 `/data/data` 下建个 `com.termux` 软链一劳永逸:
|
||||
> `/data/data` 是 `drwxrwx--x system system`,应用建不了东西(实测 EACCES)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 20 处问题清单(按发现顺序)
|
||||
|
||||
| # | 现象 | 根因 | 修法 |
|
||||
|
||||
115
scripts/build-deps.sh
Normal file
115
scripts/build-deps.sh
Normal file
@@ -0,0 +1,115 @@
|
||||
#!/bin/bash
|
||||
# 用 NDK 为 Android 交叉编译 dpkg 需要的静态库
|
||||
# 用法: build-deps.sh <arch> arch = x86_64 | arm64
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-deps.sh x86_64|arm64}"
|
||||
NDK=/root/tb/android-ndk-r27c
|
||||
SRC=/root/tb/dl
|
||||
OUT=/root/tb/out/$ARCH
|
||||
API=24
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ;;
|
||||
*) echo "未知 arch: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
export LDFLAGS=""
|
||||
|
||||
[ -x "$CC" ] || { echo "!! 找不到编译器 $CC"; exit 1; }
|
||||
echo "### arch=$ARCH CC=$CC"
|
||||
"$CC" --version | head -1
|
||||
|
||||
mkdir -p "$OUT/lib" "$OUT/include" /root/tb/work
|
||||
cd /root/tb/work
|
||||
|
||||
########################################
|
||||
# libmd 1.3.0
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libmd.a" ]; then
|
||||
echo "=== libmd ==="
|
||||
rm -rf libmd-1.3.0 && tar xf "$SRC/libmd.tar.xz"
|
||||
cd libmd-1.3.0
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static >/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
"$STRIP" --strip-unneeded "$OUT/lib/libmd.a" 2>/dev/null || true
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/libmd.a" 2>/dev/null || echo "!! libmd 失败"
|
||||
|
||||
########################################
|
||||
# zlib
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libz.a" ]; then
|
||||
echo "=== zlib ==="
|
||||
rm -rf zlib-1.3.2 && tar xf "$SRC/zlib.tar.gz"
|
||||
cd zlib-1.3.2
|
||||
CHOST="$TRIPLE" ./configure --static --prefix="$OUT" >/dev/null 2>&1
|
||||
make -j"$(nproc)" libz.a >/dev/null 2>&1
|
||||
cp libz.a "$OUT/lib/" && cp zlib.h zconf.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/libz.a" 2>/dev/null || echo "!! zlib 失败"
|
||||
|
||||
########################################
|
||||
# bzip2 1.0.8
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libbz2.a" ]; then
|
||||
echo "=== bzip2 ==="
|
||||
rm -rf bzip2-1.0.8 && tar xf "$SRC/bzip2.tar.gz"
|
||||
cd bzip2-1.0.8
|
||||
make -j"$(nproc)" libbz2.a CC="$CC" AR="$AR" RANLIB="$RANLIB" \
|
||||
CFLAGS="$CFLAGS -D_FILE_OFFSET_BITS=64" >/dev/null 2>&1
|
||||
cp libbz2.a "$OUT/lib/" && cp bzlib.h "$OUT/include/"
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/libbz2.a" 2>/dev/null || echo "!! bzip2 失败"
|
||||
|
||||
########################################
|
||||
# liblzma (xz)
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/liblzma.a" ]; then
|
||||
echo "=== liblzma ==="
|
||||
rm -rf xz-5.8.4 && tar xf "$SRC/xz.tar.xz"
|
||||
cd xz-5.8.4
|
||||
# SKIP_WERROR_CHECK: xz 的 configure 会用 -Werror 试编译,
|
||||
# 而 -D__ANDROID_API__=24 会触发它的告警,导致它误判 CFLAGS 有问题
|
||||
./configure --host="$TRIPLE" --prefix="$OUT" \
|
||||
--disable-shared --enable-static \
|
||||
--disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \
|
||||
--disable-scripts --disable-doc --disable-nls \
|
||||
SKIP_WERROR_CHECK=yes \
|
||||
>/dev/null 2>&1
|
||||
make -j"$(nproc)" >/dev/null 2>&1
|
||||
make install >/dev/null 2>&1
|
||||
cd ..
|
||||
fi
|
||||
ls -la "$OUT/lib/liblzma.a" 2>/dev/null || echo "!! liblzma 失败"
|
||||
|
||||
########################################
|
||||
# libzstd
|
||||
########################################
|
||||
if [ ! -f "$OUT/lib/libzstd.a" ]; then
|
||||
echo "=== libzstd ==="
|
||||
rm -rf zstd-1.5.7 && tar xf "$SRC/zstd.tar.gz"
|
||||
cd zstd-1.5.7/lib
|
||||
make -j"$(nproc)" libzstd.a CC="$CC" AR="$AR" RANLIB="$RANLIB" CFLAGS="$CFLAGS" >/dev/null 2>&1
|
||||
cp libzstd.a "$OUT/lib/"
|
||||
cp zstd.h zstd_errors.h zdict.h "$OUT/include/" 2>/dev/null || true
|
||||
cd ../..
|
||||
fi
|
||||
ls -la "$OUT/lib/libzstd.a" 2>/dev/null || echo "!! libzstd 失败"
|
||||
|
||||
echo
|
||||
echo "=== $ARCH 产物清单 ==="
|
||||
ls -la "$OUT/lib/" "$OUT/include/" 2>/dev/null
|
||||
142
scripts/build-dpkg.sh
Normal file
142
scripts/build-dpkg.sh
Normal file
@@ -0,0 +1,142 @@
|
||||
#!/bin/bash
|
||||
# 为 Android 交叉编译 dpkg
|
||||
# 用法: build-dpkg.sh <arch> arch = x86_64 | arm64
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?用法: build-dpkg.sh x86_64|arm64}"
|
||||
NDK=/root/tb/android-ndk-r27c
|
||||
SRC=/root/tb/src/dpkg
|
||||
DEPS=/root/tb/out/$ARCH
|
||||
OUT=/root/tb/out/$ARCH
|
||||
API=24
|
||||
|
||||
case "$ARCH" in
|
||||
x86_64) TRIPLE=x86_64-linux-android ; APKARCH=x86_64 ;;
|
||||
arm64) TRIPLE=aarch64-linux-android ; APKARCH=arm64-v8a ;;
|
||||
*) echo "未知 arch: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
|
||||
TC=$NDK/toolchains/llvm/prebuilt/linux-x86_64
|
||||
export CC=$TC/bin/${TRIPLE}${API}-clang
|
||||
export CXX=$TC/bin/${TRIPLE}${API}-clang++
|
||||
export AR=$TC/bin/llvm-ar
|
||||
export RANLIB=$TC/bin/llvm-ranlib
|
||||
export STRIP=$TC/bin/llvm-strip
|
||||
# -D__ANDROID_API__ 让 configure 通过;-isystem 把我们的静态库头文件放前面
|
||||
export CPPFLAGS="-I$DEPS/include"
|
||||
export CFLAGS="-O2 -fPIC -D__ANDROID_API__=$API"
|
||||
# RUNPATH:dpkg 会 exec 出 dpkg-query / dpkg-deb 等辅助程序,那些进程不一定
|
||||
# 继承到 LD_LIBRARY_PATH,所以把库搜索路径烧进 ELF 里,不依赖环境变量。
|
||||
export LDFLAGS="-L$DEPS/lib -static-libgcc -Wl,-rpath,/data/data/com.doubao.lynxclone/files/usr/lib -Wl,--enable-new-dtags"
|
||||
export LIBS="-lmd -lz -lbz2 -llzma -lzstd"
|
||||
|
||||
BUILD=/root/tb/build/dpkg-$ARCH
|
||||
mkdir -p /root/tb/build "$BUILD"
|
||||
cd "$BUILD"
|
||||
|
||||
echo "########## 1. 准备源码树 ##########"
|
||||
# 注意:不能把源码复制出来就完事 —— dpkg 的 build-aux/get-version 需要
|
||||
# 一个真正的 git checkout(或发行 tarball)才能定出版本号。
|
||||
# 用 git worktree:共享 .git,树是干净的,且可以随时删掉重来。
|
||||
cd "$SRC"
|
||||
git worktree remove --force "$BUILD" 2>/dev/null || true
|
||||
rm -rf "$BUILD"
|
||||
git worktree add --detach --force "$BUILD" HEAD >/dev/null 2>&1 || {
|
||||
echo "git worktree 失败"; exit 1; }
|
||||
cd "$BUILD"
|
||||
echo " worktree 就绪: $(pwd)"
|
||||
|
||||
echo "########## 2. 应用 Termux 补丁 ##########"
|
||||
for p in /root/tb/patches/termux-*.patch; do
|
||||
n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n <<< 失败"
|
||||
patch -p1 -N -l -i "$p" 2>&1 | head -20
|
||||
fi
|
||||
done
|
||||
|
||||
echo "########## 3. 应用我们自己的补丁 ##########"
|
||||
for p in /root/tb/ourpatch/doubao-prefix-h.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-c.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-makefile.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-options.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-main.patch \
|
||||
/root/tb/ourpatch/doubao-prefix-script.patch \
|
||||
/root/tb/ourpatch/doubao-android-arch.patch \
|
||||
/root/tb/ourpatch/doubao-arch-name.patch \
|
||||
/root/tb/ourpatch/doubao-debarch-name.patch; do
|
||||
n=$(basename "$p")
|
||||
if patch -p1 -N -l -i "$p" >/dev/null 2>&1; then
|
||||
echo " ✓ $n"
|
||||
else
|
||||
echo " ✗ $n <<< 失败"; patch -p1 -N -l -i "$p" 2>&1 | head -20; exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "########## 4. autogen ##########"
|
||||
# dpkg 的构建脚本叫 autogen(没后缀,也没可执行位)
|
||||
AUTOGEN=./autogen
|
||||
if [ ! -x configure ] || [ ! -f Makefile.in ]; then
|
||||
NOCONFIGURE=1 sh "$AUTOGEN" > "$BUILD/autogen.log" 2>&1 || {
|
||||
echo "autogen 失败,尾部:"; tail -30 "$BUILD/autogen.log"; exit 1; }
|
||||
fi
|
||||
echo " configure 存在: $([ -x configure ] && echo yes || echo no)"
|
||||
|
||||
echo "########## 5. configure ##########"
|
||||
# PERL: 宿主机是 perl 5.30,dpkg 要求 >= 5.32.1。perl 只用于构建期脚本
|
||||
# (dpkg-architecture 之类),跟我们真正要的 C 程序无关,所以直接告诉它
|
||||
# perl 在哪,跳过版本探测。
|
||||
#
|
||||
# --bindir / --libdir 指到 Termux 前缀:dpkg 会用 BINDIR 去找它的辅助程序
|
||||
# (dpkg -l 实际是转给 dpkg-query 执行),用 LIBDIR 去找 libdpkg 的数据。
|
||||
./configure \
|
||||
--host="$TRIPLE" \
|
||||
--build="$(uname -m)-pc-linux-gnu" \
|
||||
--prefix=/data/data/com.doubao.lynxclone/files/usr \
|
||||
--bindir=/data/data/com.doubao.lynxclone/files/usr/bin \
|
||||
--libdir=/data/data/com.doubao.lynxclone/files/usr/lib \
|
||||
--sysconfdir=/data/data/com.doubao.lynxclone/files/usr/etc \
|
||||
--localstatedir=/data/data/com.doubao.lynxclone/files/usr/var \
|
||||
--disable-shared \
|
||||
--disable-dselect \
|
||||
--disable-start-stop-daemon \
|
||||
--disable-update-alternatives \
|
||||
--disable-largefile \
|
||||
--disable-nls \
|
||||
--without-selinux \
|
||||
--without-libselinux \
|
||||
--without-systemd \
|
||||
PERL=/usr/bin/perl \
|
||||
ac_cv_lib_selinux_setexecfilecon=no \
|
||||
dpkg_cv_c99_snprintf=yes \
|
||||
DPKG_PAGER=pager \
|
||||
> "$BUILD/configure.log" 2>&1 || {
|
||||
echo "configure 失败,尾部:"; tail -40 "$BUILD/configure.log"; exit 1; }
|
||||
|
||||
echo " ✓ configure 通过"
|
||||
|
||||
echo "########## 6. make ##########"
|
||||
make -j"$(nproc)" > "$BUILD/make.log" 2>&1 || {
|
||||
echo "make 失败,错误摘要:"
|
||||
grep -nE 'error:|Error [0-9]' "$BUILD/make.log" | head -30
|
||||
exit 1; }
|
||||
|
||||
echo " ✓ make 通过"
|
||||
mkdir -p "$OUT/dpkg-bin"
|
||||
# libtool 会在源码目录放一个壳脚本,真正的东西在 .libs/ 里
|
||||
for b in dpkg dpkg-deb dpkg-query dpkg-divert dpkg-split dpkg-trigger dpkg-realpath; do
|
||||
f=""
|
||||
for cand in "src/.libs/$b" "src/main/.libs/$b" "utils/.libs/$b" \
|
||||
"src/$b" "src/main/$b" "utils/$b"; do
|
||||
[ -f "$cand" ] && { f="$cand"; break; }
|
||||
done
|
||||
if [ -z "$f" ]; then echo " ? 找不到 $b"; continue; fi
|
||||
cp "$f" "$OUT/dpkg-bin/$b"
|
||||
"$STRIP" "$OUT/dpkg-bin/$b" 2>/dev/null || echo " ! strip 失败: $b(可能不是 ELF)"
|
||||
done
|
||||
echo
|
||||
echo "########## 产物 ##########"
|
||||
ls -la "$OUT/dpkg-bin/"
|
||||
file "$OUT/dpkg-bin/dpkg" 2>/dev/null || true
|
||||
82
scripts/probe-ai-surfaces.py
Normal file
82
scripts/probe-ai-surfaces.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""端到端测 AI 界面三件套:宿主机 → 内核 /api/tools/run → 安卓桥。
|
||||
|
||||
★ 为什么从宿主机打而不是在设备上敲:PowerShell/adb 的多层引号会把 JSON
|
||||
搅烂(这一路上已经踩过好几次)。adb forward 之后在宿主机上用 Python 打,
|
||||
引号只有一层,看得清。
|
||||
|
||||
★ ask_user 是**阻塞**的:脚本会挂在那儿等用户在手机上点。
|
||||
所以它放在最后,并且单独一个命令跑(另一个终端截图看界面)。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
CONV = "c_main"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=180):
|
||||
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"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
def run_tool(name, args, timeout=150):
|
||||
print(f"\n--- {name} ---", flush=True)
|
||||
print(" 参数:", json.dumps(args, ensure_ascii=False)[:160], flush=True)
|
||||
t0 = time.time()
|
||||
res = call("/api/tools/run", {"name": name, "args": args, "conversationId": CONV},
|
||||
timeout=timeout)
|
||||
print(f" 耗时 {time.time() - t0:.1f}s -> {json.dumps(res, ensure_ascii=False)[:300]}",
|
||||
flush=True)
|
||||
return res
|
||||
|
||||
|
||||
which = sys.argv[1] if len(sys.argv) > 1 else "all"
|
||||
|
||||
if which in ("all", "state"):
|
||||
st = call("/api/state", method="GET")
|
||||
print("uiTools =", json.dumps((st.get("settings") or {}).get("uiTools"), ensure_ascii=False))
|
||||
|
||||
if which in ("all", "screen"):
|
||||
run_tool("show_ui", {
|
||||
"title": "测试界面",
|
||||
"html": "<h1>你好</h1><p>这是 AI 写的 HTML。</p>"
|
||||
"<table><tr><th>项</th><th>值</th></tr><tr><td>甲</td><td>1</td></tr></table>"
|
||||
"<button data-doubao-result='选了A'>选 A</button>"
|
||||
"<button data-doubao-result='选了B'>选 B</button>",
|
||||
})
|
||||
|
||||
if which in ("all", "end"):
|
||||
run_tool("end_conversation", {"reason": "这件事已经办完了,没有后续可聊的。"})
|
||||
print("\n=== 确认落盘 ===", flush=True)
|
||||
full = call(f"/api/conversations/{CONV}", method="GET").get("conversation") or {}
|
||||
print(" ended =", full.get("ended"), "| endedReason =", full.get("endedReason"), flush=True)
|
||||
|
||||
if which == "ask":
|
||||
run_tool("ask_user", {
|
||||
"question": "这个方案你要哪一个?",
|
||||
"options": [
|
||||
{"label": "方案 A", "value": "A", "description": "快但功能少"},
|
||||
{"label": "方案 B", "value": "B", "description": "慢一点但完整"},
|
||||
{"label": "都不要", "value": "none"},
|
||||
],
|
||||
}, timeout=240)
|
||||
|
||||
if which == "askmulti":
|
||||
run_tool("ask_user", {
|
||||
"question": "想装哪几个?(可多选)",
|
||||
"multiple": True,
|
||||
"options": ["python", "git", "nmap", "nodejs"],
|
||||
}, timeout=240)
|
||||
167
scripts/verify-dpkg-jnilibs.py
Normal file
167
scripts/verify-dpkg-jnilibs.py
Normal file
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""守住 `android/app/src/main/res` 里那几个 tar 包(`libdoubao-dpkg.so`)。
|
||||
|
||||
为什么不直接信任构建产物:
|
||||
「编译过了」在这条路上什么都不能说明 —— 出问题的地方全都是
|
||||
**编译成功、装上去才炸**(配置目录权限、架构名非法、维护脚本 shebang)。
|
||||
所以这里盯的是"打进 APK 的那几个字节到底长什么样"。
|
||||
|
||||
用法:
|
||||
python scripts/verify-dpkg-jnilibs.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
# Windows 控制台默认是 GBK,打印 ✓/✗ 会 UnicodeEncodeError
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
JNI = os.path.join(ROOT, "android", "app", "src", "main", "jniLibs")
|
||||
|
||||
EXPECT = {
|
||||
"x86_64": {"lib": "libdoubao-dpkg.so", "machine": 62, "arch_name": b"x86_64"},
|
||||
"arm64-v8a": {"lib": "libdoubao-dpkg.so", "machine": 183, "arch_name": b"aarch64"},
|
||||
}
|
||||
|
||||
PROGRAMS = {"dpkg", "dpkg-deb", "dpkg-query", "dpkg-divert", "dpkg-split", "dpkg-trigger"}
|
||||
|
||||
TAR_BLOCK = 512
|
||||
|
||||
fails = []
|
||||
warns = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def warn(m):
|
||||
warns.append(m)
|
||||
print(f" ! {m}")
|
||||
|
||||
|
||||
def read_tar(path):
|
||||
"""返回 [(名字, 内容)],只认 ustar 普通文件"""
|
||||
out = []
|
||||
with open(path, "rb") as f:
|
||||
while True:
|
||||
header = f.read(TAR_BLOCK)
|
||||
if len(header) < TAR_BLOCK or header == b"\0" * TAR_BLOCK:
|
||||
break
|
||||
name = header[0:100].split(b"\0")[0].decode("utf-8", "replace").strip()
|
||||
sizef = header[124:136].split(b"\0")[0].decode("ascii", "replace").strip()
|
||||
size = int(sizef, 8) if sizef else 0
|
||||
typ = header[156:157]
|
||||
prefix = header[345:500].split(b"\0")[0].decode("utf-8", "replace").strip()
|
||||
full = f"{prefix}/{name}" if prefix else name
|
||||
body = f.read(size)
|
||||
pad = (-size) % TAR_BLOCK
|
||||
if pad:
|
||||
f.read(pad)
|
||||
if typ in (b"0", b"\0") and not full.endswith("/"):
|
||||
out.append((full, body))
|
||||
return out
|
||||
|
||||
|
||||
def elf_machine(blob):
|
||||
"""ELF e_machine(小端)"""
|
||||
if blob[:4] != b"\x7fELF":
|
||||
return None
|
||||
return struct.unpack_from("<H", blob, 18)[0]
|
||||
|
||||
|
||||
def contains(hay, needle):
|
||||
return hay.find(needle) >= 0
|
||||
|
||||
|
||||
print("=== 校验 APK 里的自编 dpkg(jniLibs/libdoubao-dpkg.so)===")
|
||||
|
||||
for abi, spec in EXPECT.items():
|
||||
path = os.path.join(JNI, abi, spec["lib"])
|
||||
print(f"\n[{abi}] {os.path.relpath(path, ROOT)}")
|
||||
if not os.path.isfile(path):
|
||||
fail(f"文件不存在:{path}")
|
||||
continue
|
||||
|
||||
try:
|
||||
members = read_tar(path)
|
||||
except Exception as e:
|
||||
fail(f"读 tar 失败:{e}")
|
||||
continue
|
||||
|
||||
names = {n for n, _ in members}
|
||||
if names != PROGRAMS:
|
||||
fail(f"内容不对:期望 {sorted(PROGRAMS)},实际 {sorted(names)}")
|
||||
continue
|
||||
ok(f"tar 里有 {len(names)} 个程序({', '.join(sorted(names))})")
|
||||
|
||||
dpkg = dict(members)["dpkg"]
|
||||
|
||||
# ELF 架构
|
||||
m = elf_machine(dpkg)
|
||||
if m != spec["machine"]:
|
||||
fail(f"dpkg 的 e_machine={m},期望 {spec['machine']}")
|
||||
else:
|
||||
ok(f"ELF 架构正确(e_machine={m})")
|
||||
|
||||
# 运行时前缀解析 —— 没有它就等于没修
|
||||
if not contains(dpkg, b"/proc/self/exe"):
|
||||
fail("dpkg 里没有 /proc/self/exe(运行时前缀补丁没进去)")
|
||||
else:
|
||||
ok("有 /proc/self/exe(运行时前缀解析)")
|
||||
|
||||
# 架构名
|
||||
if not contains(dpkg, spec["arch_name"]):
|
||||
fail(f"dpkg 里没有架构名 {spec['arch_name'].decode()}")
|
||||
else:
|
||||
ok(f"架构名是 {spec['arch_name'].decode()}")
|
||||
|
||||
for stale in (b"amd64", b"arm64") if abi == "x86_64" else (b"amd64",):
|
||||
if contains(dpkg, stale):
|
||||
fail(f"dpkg 里还有 Debian 风格架构名 {stale.decode()}")
|
||||
break
|
||||
else:
|
||||
ok("没有 Debian 风格架构名")
|
||||
|
||||
# 重写函数要匹配的模式必须存在,否则脚本改不了
|
||||
if not contains(dpkg, b"/data/data/com.termux/files/usr"):
|
||||
fail("dpkg 里没有要匹配的旧前缀(维护脚本改写会失效)")
|
||||
else:
|
||||
ok("有维护脚本改写用的旧前缀模式")
|
||||
|
||||
# 不允许出现"编译死的配置目录"这种更长的路径
|
||||
if contains(dpkg, b"/data/data/com.termux/files/usr/etc/dpkg"):
|
||||
fail("dpkg 里还有编译死的配置目录(装上必 EACCES)")
|
||||
else:
|
||||
ok("没有编译死的配置目录")
|
||||
|
||||
# RUNPATH
|
||||
if not contains(dpkg, b"/data/data/com.doubao.lynxclone/files/usr/lib"):
|
||||
fail("dpkg 里没有指向前缀 lib 的 RUNPATH")
|
||||
else:
|
||||
ok("RUNPATH 指向前缀 lib")
|
||||
|
||||
# 静态链进去了就不该再 NEEDED libmd
|
||||
if contains(dpkg, b"libmd.so"):
|
||||
fail("dpkg 还依赖 libmd.so(应该静态链入)")
|
||||
else:
|
||||
ok("没有外部 libmd 依赖")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print(f"✅ 全部通过" + (f"({len(warns)} 条提示)" if warns else ""))
|
||||
304
scripts/verify-ui-tools.py
Normal file
304
scripts/verify-ui-tools.py
Normal file
@@ -0,0 +1,304 @@
|
||||
"""守 AI 界面三件套(show_ui / ask_user / end_conversation)的硬性质。
|
||||
|
||||
这些性质每一条都对应一个"想当然会出错"的地方,光看代码看不出来:
|
||||
|
||||
1. **开关默认关**。这三个工具会让 AI 主动往用户脸上弹东西、甚至封掉对话,
|
||||
默认打开是产品事故。而且必须**默认关**(新装/老设备升上来都是关)。
|
||||
2. **两道拦截都要在**:关掉时① 工具对模型隐藏,② 即使模型硬编名字也拒绝执行。
|
||||
只做①的话,用户关掉之后模型仍可能从历史消息里学会这个名字再调一次。
|
||||
3. **ask_user 的 options 两种写法都要收**(对象数组 / 裸字符串数组)——
|
||||
模型写裸字符串数组非常常见,只认一种就会平白吃一个报错。
|
||||
4. **end_conversation 拿不到对话 id 时必须报错,不能假装成功** ——
|
||||
假装成功会变成"界面封了、盘上没封",用户重启后又能发消息。
|
||||
5. **不占用户的消息预算**:这几个工具的规则不能渗进系统提示词的
|
||||
"回答要求"编号里(那会让模型把它们当成每轮都要考虑的事)。
|
||||
|
||||
用法:
|
||||
python scripts/verify-ui-tools.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
KERNEL = os.path.join(WS, "android", "kernel")
|
||||
TOOLS = os.path.join(WS, "tools")
|
||||
sys.path.insert(0, KERNEL)
|
||||
sys.path.insert(0, TOOLS)
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("=== 1. 工具能被发现,spec 合法 ===")
|
||||
import importlib.util
|
||||
|
||||
for name in ("show_ui", "ask_user", "end_conversation"):
|
||||
path = os.path.join(TOOLS, name + ".py")
|
||||
if not os.path.isfile(path):
|
||||
fail(f"{name}.py 不存在")
|
||||
continue
|
||||
spec = importlib.util.spec_from_file_location("t_" + name, path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
try:
|
||||
spec.loader.exec_module(mod)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fail(f"{name}.py 导入失败:{type(exc).__name__}: {exc}")
|
||||
continue
|
||||
tool = getattr(mod, "TOOL", None)
|
||||
if not isinstance(tool, dict) or not tool.get("name"):
|
||||
fail(f"{name}.py 没有合法的 TOOL")
|
||||
continue
|
||||
if not callable(getattr(mod, "run", None)):
|
||||
fail(f"{name}.py 没有 run(args)")
|
||||
continue
|
||||
if tool["name"] != name:
|
||||
fail(f"{name}.py 的 TOOL.name 是 {tool['name']},和文件名不一致")
|
||||
continue
|
||||
params = tool.get("parameters") or {}
|
||||
if params.get("type") != "object":
|
||||
fail(f"{name} 的 parameters.type 不是 object")
|
||||
continue
|
||||
ok(f"{name}:spec 合法(必填 {params.get('required') or '无'})")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n=== 2. 开关默认关 + 两道拦截 ===")
|
||||
import tools_runtime as TR
|
||||
|
||||
if TR.ui_tools_enabled({}):
|
||||
fail("空 settings 时 ui_tools_enabled 竟然是 True —— 默认必须关")
|
||||
else:
|
||||
ok("空 settings → 关闭")
|
||||
|
||||
if TR.ui_tools_enabled({"uiTools": {"enabled": True}}):
|
||||
ok("uiTools.enabled=True → 打开")
|
||||
else:
|
||||
fail("uiTools.enabled=True 没被认成打开")
|
||||
|
||||
if TR.ui_tools_enabled({"uiTools": True}):
|
||||
ok("uiTools=True(老写法)→ 也认")
|
||||
else:
|
||||
fail("uiTools=True 没被认(兼容写法失效)")
|
||||
|
||||
# ① 关掉时对模型隐藏
|
||||
defs_off = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {})
|
||||
if defs_off:
|
||||
fail(f"关闭时仍把 {[d['name'] for d in defs_off]} 给了模型")
|
||||
else:
|
||||
ok("关闭时三个工具对模型隐藏")
|
||||
|
||||
defs_on = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {"uiTools": {"enabled": True}})
|
||||
if len(defs_on) == len(TR.UI_TOOLS):
|
||||
ok("打开时三个工具都给模型")
|
||||
else:
|
||||
fail(f"打开时只给了 {len(defs_on)} 个")
|
||||
|
||||
# ② 关掉时即使硬编名字也拒绝
|
||||
res = TR.execute_tool("ask_user", {"question": "x", "options": ["a"]}, {})
|
||||
if res.get("ok") is False and "关闭" in str(res.get("error")):
|
||||
ok("关闭时 execute_tool 拒绝执行(第二道拦截在)")
|
||||
else:
|
||||
fail(f"关闭时 execute_tool 没拦住:{res}")
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
print("\n=== 3. ask_user 的选项规整 ===")
|
||||
import ask_user as AU
|
||||
|
||||
cases = [
|
||||
(["A", "B"], 2, "裸字符串数组"),
|
||||
([{"label": "A"}, {"label": "B", "value": "b"}], 2, "对象数组"),
|
||||
([{"value": "only"}], 1, "只有 value 没有 label"),
|
||||
([{"label": "A", "description": "说明"}], 1, "带 description"),
|
||||
(["A", {"label": ""}, " ", "B"], 2, "混杂空项(应被丢掉)"),
|
||||
([], 0, "空数组"),
|
||||
]
|
||||
for raw, want, label in cases:
|
||||
got = AU._clean_options(raw)
|
||||
if len(got) == want:
|
||||
ok(f"{label} → {len(got)} 项")
|
||||
else:
|
||||
fail(f"{label}:期望 {want} 项,实际 {len(got)} 项({got})")
|
||||
|
||||
opts = AU._clean_options([{"label": "A"}])
|
||||
if opts and opts[0]["value"] == "A":
|
||||
ok("value 留空时自动用 label")
|
||||
else:
|
||||
fail(f"value 没回落到 label:{opts}")
|
||||
|
||||
# 超过 8 个要截断
|
||||
many = AU._clean_options([f"opt{i}" for i in range(20)])
|
||||
if len(many) == 20:
|
||||
ok("规整阶段不截断(截断在 run 里做)")
|
||||
else:
|
||||
fail(f"规整阶段就把选项截了:{len(many)}")
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
print("\n=== 4. 拿不到对话 id 时必须报错 ===")
|
||||
import _ui_bridge as UB
|
||||
|
||||
# 不在工具调用上下文里 → conversation_id() 应该是空
|
||||
UB_ctx = TR.current_context()
|
||||
if UB_ctx == {}:
|
||||
ok("不在调用中时 current_context() 是空 dict")
|
||||
else:
|
||||
fail(f"current_context() 不是空的:{UB_ctx}")
|
||||
|
||||
# push 之后能读到
|
||||
TR.push_context(conversationId="c_test", toolName="end_conversation")
|
||||
if TR.current_context().get("conversationId") == "c_test":
|
||||
ok("push_context 之后能读到 conversationId")
|
||||
else:
|
||||
fail(f"push_context 没生效:{TR.current_context()}")
|
||||
|
||||
# ★★★ 关键:**上下文必须能跨线程** —— run_with_timeout 是在新线程里跑工具的,
|
||||
# 而 threading.local() 不跨线程继承。这里直接验"另一个线程里读得到"。
|
||||
import threading
|
||||
|
||||
seen = {}
|
||||
|
||||
|
||||
def _in_other_thread():
|
||||
seen["ctx"] = TR.current_context()
|
||||
|
||||
|
||||
worker = threading.Thread(target=_in_other_thread)
|
||||
worker.start()
|
||||
worker.join(5)
|
||||
if seen.get("ctx") == {}:
|
||||
ok("另一个线程里读不到(符合 thread-local 语义 —— 所以必须显式搬过去)")
|
||||
else:
|
||||
fail(f"另一个线程里读到了东西,语义和预期不符:{seen.get('ctx')}")
|
||||
|
||||
TR.clear_context()
|
||||
if TR.current_context() == {}:
|
||||
ok("clear_context 之后读不到了")
|
||||
else:
|
||||
fail("clear_context 之后还能读到")
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
print("\n=== 5. 工具真的执行时,上下文能送到工具手里 ===")
|
||||
# 造一个假工具:它把读到的上下文写进返回值。
|
||||
#
|
||||
# ★★ 必须走 **run_python_tool** 这条真实路径 —— 它内部会调 run_with_timeout,
|
||||
# 而那个函数是在**新线程**里跑工具的。第一版验证脚本图省事直接调了
|
||||
# run_with_timeout(lambda: mod.run(...)),绕开了被修的那段代码,
|
||||
# 于是"修好了没有"根本没测到(脚本报红但红得不是地方)。
|
||||
# 教训:验证要走**调用方真正走的那条路**。
|
||||
probe_src = '''
|
||||
import os, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_ctx", "description": "探针",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
def run(args):
|
||||
import tools_runtime as TR
|
||||
import _ui_bridge as UB
|
||||
return {"ctx": TR.current_context(), "conv": UB.conversation_id()}
|
||||
'''
|
||||
import tempfile
|
||||
|
||||
tmpdir = tempfile.mkdtemp()
|
||||
open(os.path.join(tmpdir, "probe_ctx.py"), "w", encoding="utf-8").write(probe_src)
|
||||
|
||||
# 让 tools_runtime 去 tmpdir 里找工具(改的是 `paths.get().tools_dir`,
|
||||
# 不动用户真正的工具目录)
|
||||
import paths as P
|
||||
|
||||
_orig_tools_dir = P.get().tools_dir
|
||||
P.get().tools_dir = tmpdir
|
||||
TR.discover_python_tools(force=True)
|
||||
try:
|
||||
TR.push_context(conversationId="c_from_parent", toolName="probe_ctx")
|
||||
try:
|
||||
res = TR.run_python_tool("probe_ctx", {})
|
||||
finally:
|
||||
TR.clear_context()
|
||||
finally:
|
||||
P.get().tools_dir = _orig_tools_dir
|
||||
TR.discover_python_tools(force=True)
|
||||
|
||||
got = (res or {}).get("result") if isinstance(res, dict) else None
|
||||
if not isinstance(got, dict):
|
||||
fail(f"探针没返回 dict:{res}")
|
||||
else:
|
||||
if got.get("conv") == "c_from_parent":
|
||||
ok("换线程之后工具仍拿得到 conversationId(修好了)")
|
||||
else:
|
||||
fail(f"换线程之后 conversationId 丢了:{got}")
|
||||
|
||||
|
||||
|
||||
# end_conversation.run 在没有对话 id 时应该抛错(而不是返回 ended:True)
|
||||
import end_conversation as EC
|
||||
|
||||
try:
|
||||
# 桥不在(电脑端)会先抛"没有界面能力",两种都算"没假装成功"
|
||||
out = EC.run({"reason": "测试"})
|
||||
if out.get("ended") is True:
|
||||
fail("没有对话 id 却报 ended=True —— 这是最坏的失败模式(界面封了、盘上没封)")
|
||||
else:
|
||||
ok(f"没有对话 id 时没假装成功:{out}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok(f"没有对话 id 时抛错(正确):{type(exc).__name__}")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n=== 6. 界面能力的提示词只在开关打开时追加 ===")
|
||||
import defaults as D
|
||||
|
||||
prompt = D.DEFAULT_SYSTEM_PROMPT
|
||||
if "show_ui" in prompt or "ask_user" in prompt or "end_conversation" in prompt:
|
||||
fail("默认提示词里点名了界面工具 —— 开关关着时会误导模型去调")
|
||||
else:
|
||||
ok("默认提示词里没点名界面工具(开关管得住)")
|
||||
if "附件" in prompt:
|
||||
ok("附件说明还在(没被覆盖)")
|
||||
else:
|
||||
fail("附件说明不见了")
|
||||
|
||||
# 追加的那段:关着不该出现,开着必须在
|
||||
import agent_loop as AL
|
||||
|
||||
if not hasattr(AL, "UI_TOOLS_HINT"):
|
||||
fail("agent_loop 里没有 UI_TOOLS_HINT")
|
||||
else:
|
||||
hint = AL.UI_TOOLS_HINT
|
||||
if "show_ui" in hint and "ask_user" in hint and "end_conversation" in hint:
|
||||
ok("UI_TOOLS_HINT 里三个工具都讲到了")
|
||||
else:
|
||||
fail("UI_TOOLS_HINT 没覆盖三个工具")
|
||||
if "必须先在正文里" in hint:
|
||||
ok("提示了 end_conversation 要先说明(这条很重要)")
|
||||
else:
|
||||
fail("UI_TOOLS_HINT 没要求'结束前先说明'")
|
||||
|
||||
# ★ 追加逻辑必须**按开关**走。这里直接验证那段代码的存在性 +
|
||||
# ui_tools_enabled 的语义(真正的拼接在 run_agent 里,需要起网络,不在这儿跑)。
|
||||
import inspect
|
||||
|
||||
src = inspect.getsource(AL.run_agent)
|
||||
if "ui_tools_enabled" in src and "UI_TOOLS_HINT" in src:
|
||||
ok("run_agent 里是按开关决定要不要追加")
|
||||
else:
|
||||
fail("run_agent 没按开关追加提示词")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
170
scripts/verify-uploads-parity.py
Normal file
170
scripts/verify-uploads-parity.py
Normal file
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""守 Android 内核(Python)和桌面服务(Node)两份附件实现的一致性。
|
||||
|
||||
为什么要对拍:这两个端跑的是**同一个内核的另一份实现**,
|
||||
`uploads.py` 和 `uploads.mjs` 的字段名、文件命名、喂给模型的文案
|
||||
必须一模一样 —— 不一样的话"同一句话在两个端上表现不同",
|
||||
而且这种漂移**不会报错**,只会让行为悄悄分叉(这个仓库里已经有过好几次)。
|
||||
|
||||
用法:
|
||||
python scripts/verify-uploads-parity.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
PY = os.path.join(ROOT, "android", "kernel", "uploads.py")
|
||||
JS = os.path.join(ROOT, "server", "src", "uploads.mjs")
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def fail(m):
|
||||
fails.append(m)
|
||||
print(f" ✗ {m}")
|
||||
|
||||
|
||||
def ok(m):
|
||||
print(f" ✓ {m}")
|
||||
|
||||
|
||||
def read(p):
|
||||
if not os.path.isfile(p):
|
||||
print(f"!! 找不到 {p}")
|
||||
sys.exit(1)
|
||||
return open(p, encoding="utf-8").read()
|
||||
|
||||
|
||||
py, js = read(PY), read(JS)
|
||||
|
||||
print("=== 附件实现两端对拍 ===")
|
||||
|
||||
# ---------------------------------------------------------------- 1
|
||||
print("\n[1] 落盘文件名的形状")
|
||||
# 两边都该是 f'{stamp()}_{safeName}' 这种,且用可读时间戳
|
||||
for name, text, stamp_re in (
|
||||
("uploads.py", py, r"\d{8}-\d{6}"),
|
||||
("uploads.mjs", js, r"\d{8}-\d{6}"),
|
||||
):
|
||||
if "stamp" not in text:
|
||||
fail(f"{name} 里没有 stamp(文件名时间戳)")
|
||||
else:
|
||||
ok(f"{name} 有 stamp()")
|
||||
|
||||
if "_stamp" in py and "%Y%m%d-%H%M%S" in py:
|
||||
ok("uploads.py 的时间戳格式是 %Y%m%d-%H%M%S(可读)")
|
||||
else:
|
||||
fail("uploads.py 的时间戳格式不是可读形式")
|
||||
|
||||
if "getFullYear" in js and "padStart" in js:
|
||||
ok("uploads.mjs 的时间戳格式是 YYYYMMDD-HHMMSS(可读)")
|
||||
else:
|
||||
fail("uploads.mjs 的时间戳格式不是可读形式")
|
||||
|
||||
# 不该再用 base36 时间戳**做文件名**。
|
||||
# ★ 注意 `rid()` 里仍然用 toString(36) 生成 id —— 那是 id,不是文件名,
|
||||
# 不该一起否掉(第一版这里判宽了)。
|
||||
if re.search(r"path\.join\([^)]*toString\(36\)", js):
|
||||
fail("uploads.mjs 的文件名里还在用 base36 时间戳(不可读)")
|
||||
else:
|
||||
ok("uploads.mjs 的文件名不再用 base36 时间戳")
|
||||
|
||||
# ---------------------------------------------------------------- 2
|
||||
print("\n[2] 重名消歧 + 保留扩展名")
|
||||
for name, text in (("uploads.py", py), ("uploads.mjs", js)):
|
||||
if "unique" in text.lower() and "splitext" in text or "extname" in text:
|
||||
ok(f"{name} 有唯一化 + 保留扩展名")
|
||||
else:
|
||||
fail(f"{name} 缺唯一化或没保扩展名")
|
||||
|
||||
# ---------------------------------------------------------------- 3
|
||||
print("\n[3] 每条分支都给出本地路径")
|
||||
for name, text in (("uploads.py", py), ("uploads.mjs", js)):
|
||||
n = text.count("本地路径:")
|
||||
# 三条分支:图片 / 文本 / 二进制
|
||||
if n >= 3:
|
||||
ok(f"{name} 有 {n} 处「本地路径:」(三条分支都覆盖)")
|
||||
else:
|
||||
fail(f"{name} 只有 {n} 处「本地路径:」,应有 3 处")
|
||||
|
||||
# ---------------------------------------------------------------- 4
|
||||
print("\n[4] 喂给模型的文案一致")
|
||||
# ★ 不做整串字面比对 —— 两端写法本来就不同:
|
||||
# Python 是 f-string(`\n` 是真实换行),JS 是模板字符串(`\n` 是反斜杠+n),
|
||||
# ``` 代码块在 JS 里还要转义。
|
||||
# 我第一版硬比字面,结果在"转义怎么写"上反复误报,纯属浪费。
|
||||
#
|
||||
# 改成比对两件**本质**的东西:
|
||||
# · 文案里的**中文固定片段**(用户能看到的那些字)
|
||||
# · 插值位置的**变量名**
|
||||
# 这两样一致,模型看到的东西就一致;剩下的是同义写法,无所谓。
|
||||
def fragments(text):
|
||||
"""文案里的中文固定片段(去掉所有插值和反斜杠转义)"""
|
||||
out = set()
|
||||
for m in re.finditer(r"【[^】]*】", text):
|
||||
s = m.group(0)
|
||||
s = re.sub(r"\$\{[^}]*\}", "", s)
|
||||
s = re.sub(r"\{[^}]*\}", "", s)
|
||||
s = s.replace("\\", "")
|
||||
out.add(s)
|
||||
return out
|
||||
|
||||
|
||||
def vars_used(text):
|
||||
"""插值用到的变量名(两端各自的写法都归一)"""
|
||||
out = set()
|
||||
for m in re.finditer(r"\$\{([^}]*)\}", text):
|
||||
out.add(m.group(1).strip())
|
||||
for m in re.finditer(r"\{([A-Za-z_][^}]*)\}", text):
|
||||
out.add(m.group(1).strip())
|
||||
return out
|
||||
|
||||
|
||||
py_f, js_f = fragments(py), fragments(js)
|
||||
if py_f == js_f:
|
||||
ok(f"固定文案片段一致({len(py_f)} 条):{sorted(py_f)}")
|
||||
else:
|
||||
fail("固定文案片段不一致:")
|
||||
print(" python 独有:", sorted(py_f - js_f))
|
||||
print(" node 独有:", sorted(js_f - py_f))
|
||||
|
||||
# 关键变量两边都要用:路径 / 名字 / 大小
|
||||
need = {"path", "name", "size"}
|
||||
py_v, js_v = vars_used(py), vars_used(js)
|
||||
for label, used in (("uploads.py", py_v), ("uploads.mjs", js_v)):
|
||||
miss = {n for n in need if not any(n in u for u in used)}
|
||||
if miss:
|
||||
fail(f"{label} 的文案里没用到 {sorted(miss)}")
|
||||
else:
|
||||
ok(f"{label} 的文案用到了 path/name/size")
|
||||
|
||||
# ---------------------------------------------------------------- 5
|
||||
print("\n[5] 系统提示词的附件说明")
|
||||
dpy = read(os.path.join(ROOT, "android", "kernel", "defaults.py"))
|
||||
dcfg = read(os.path.join(ROOT, "server", "src", "config.mjs"))
|
||||
key = "关于用户发来的文件(附件):"
|
||||
if key in dpy and key in dcfg:
|
||||
ok("两端提示词都有附件说明")
|
||||
else:
|
||||
fail(f"提示词缺附件说明(python={key in dpy} node={key in dcfg})")
|
||||
|
||||
for label, text in (("defaults.py", dpy), ("config.mjs", dcfg)):
|
||||
if "本地路径" in text or "真实位置" in text:
|
||||
ok(f"{label} 提示词里告诉了模型路径可用")
|
||||
else:
|
||||
fail(f"{label} 提示词没提路径")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for m in fails:
|
||||
print(" -", m)
|
||||
sys.exit(1)
|
||||
print("✅ 两端一致")
|
||||
@@ -257,7 +257,16 @@ export const DEFAULT_SYSTEM_PROMPT = [
|
||||
'3. 需要计算、查时间、读写本地笔记或抓取网页时,主动调用可用工具,不要凭记忆编造。',
|
||||
'4. 工具返回的内容可能不完整,若失败要如实说明失败原因。',
|
||||
'5. 不确定的信息要明确标注不确定。',
|
||||
'',
|
||||
'关于用户发来的文件(附件):',
|
||||
'6. 附件内容会以 `【文件 名字(大小)本地路径:/绝对/路径】` 的形式给你。',
|
||||
' **那个路径是文件在磁盘上的真实位置**,可以直接用 shell 或 python 工具打开它 ——',
|
||||
' 不要猜路径,也不要说"我拿不到文件"。',
|
||||
'7. 长文件在对话里只会内联前 20000 个字符,后面会标注"已截断"。',
|
||||
' 需要看全文就按第 6 条给的路径去读,不要凭截断的内容下结论。',
|
||||
].join('\n');
|
||||
// ★ 上面这段必须和安卓内核 android/kernel/defaults.py 的 DEFAULT_SYSTEM_PROMPT
|
||||
// 逐字一致 —— 两边跑同一个内核,提示词不一样会让"同一句话在两个端上表现不同"。
|
||||
|
||||
export const DEFAULT_SETTINGS = {
|
||||
provider: 'ark',
|
||||
|
||||
@@ -56,12 +56,49 @@ function mimeOf(name) {
|
||||
return map[ext] || (isText(name) ? 'text/plain' : 'application/octet-stream');
|
||||
}
|
||||
|
||||
/**
|
||||
* 落盘文件名用的时间戳:**人能读**的本地时间,格式 `20260101-120000`。
|
||||
*
|
||||
* ★ 以前用的是 `Date.now().toString(36)`(形如 `m5k8xk2`)—— 唯一优点是
|
||||
* 不会重名,缺点是**看见文件名完全不知道是什么时候的东西**。
|
||||
* 用户明确反馈过(bug 报告问题 5):"私有目录下一堆时间戳名/哈希名临时件"。
|
||||
*
|
||||
* ★ 秒级精度会撞名,靠 uniquePath() 消歧,不靠时间戳本身保证唯一。
|
||||
* 和安卓内核 kernel/uploads.py 的 `_stamp()` 保持同一格式。
|
||||
*/
|
||||
function stamp() {
|
||||
const d = new Date();
|
||||
const p = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`
|
||||
+ `-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{目录}/{时间戳}_{安全文件名}`;重名时在扩展名前加 `-1`、`-2`…
|
||||
*
|
||||
* ★ 一定保留扩展名:`report.pdf` → `report-1.pdf`,不是 `report.pdf-1` ——
|
||||
* 连我们自己的 isImage()/mimeOf() 都按扩展名判断类型。
|
||||
* 和 kernel/uploads.py 的 `_unique_path()` 行为一致。
|
||||
*/
|
||||
function uniquePath(dir, safeName) {
|
||||
const ext = path.extname(safeName);
|
||||
const base = path.basename(safeName, ext);
|
||||
const s = stamp();
|
||||
for (let i = 0; i < 1000; i += 1) {
|
||||
const suffix = i === 0 ? '' : `-${i}`;
|
||||
const candidate = path.join(dir, `${s}_${base}${suffix}${ext}`);
|
||||
if (!fs.existsSync(candidate)) return candidate;
|
||||
}
|
||||
return path.join(dir, `${s}_${base}-${Math.random().toString(36).slice(2, 6)}${ext}`);
|
||||
}
|
||||
|
||||
function meta(filePath, name, { copy = true } = {}) {
|
||||
const stat = fs.statSync(filePath);
|
||||
let storedPath = filePath;
|
||||
let url = '';
|
||||
if (copy && stat.size <= COPY_LIMIT) {
|
||||
const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`);
|
||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||
const target = uniquePath(UPLOADS_DIR, safeName(name));
|
||||
fs.copyFileSync(filePath, target);
|
||||
storedPath = target;
|
||||
url = `/uploads/${path.basename(target)}`;
|
||||
@@ -82,7 +119,8 @@ export function saveUpload({ name, base64 }) {
|
||||
if (!name || !base64) throw new Error('缺少 name 或 base64');
|
||||
const buffer = Buffer.from(String(base64).replace(/^data:[^,]+,/, ''), 'base64');
|
||||
if (buffer.length > COPY_LIMIT) throw new Error(`文件超过 ${COPY_LIMIT / 1024 / 1024}MB`);
|
||||
const target = path.join(UPLOADS_DIR, `${Date.now().toString(36)}_${safeName(name)}`);
|
||||
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
|
||||
const target = uniquePath(UPLOADS_DIR, safeName(name));
|
||||
fs.writeFileSync(target, buffer);
|
||||
return {
|
||||
id: rid(),
|
||||
@@ -114,6 +152,16 @@ export function takePending() {
|
||||
|
||||
/**
|
||||
* 把附件转成模型能吃的形式。
|
||||
*
|
||||
* ★★ **每一条分支都会把落盘的绝对路径写进 text。**
|
||||
*
|
||||
* 这是用户明确提的(bug 报告问题 5):附件进了上下文,但没人告诉模型
|
||||
* 文件落在哪,模型想去 shell / python 里处理它只能靠猜。之前只有"二进制"
|
||||
* 那条给了路径,而**恰恰是文本最需要** —— 超过 20000 字符会被截断,
|
||||
* 被截掉的那部分只能靠模型自己去读原文件。
|
||||
*
|
||||
* 格式和安卓内核 kernel/uploads.py 的 attachmentPayload 保持一致。
|
||||
*
|
||||
* @returns {{text: string, images: {url: string}[]}}
|
||||
*/
|
||||
export function attachmentPayload(attachment) {
|
||||
@@ -126,7 +174,7 @@ export function attachmentPayload(attachment) {
|
||||
if (isImage(attachment.name) && size <= VISION_LIMIT) {
|
||||
const b64 = fs.readFileSync(attachment.path).toString('base64');
|
||||
out.images.push({ url: `data:${attachment.mime};base64,${b64}` });
|
||||
out.text = `【图片 ${attachment.name}】`;
|
||||
out.text = `【图片 ${attachment.name}(${size} 字节)本地路径:${attachment.path}】`;
|
||||
return out;
|
||||
}
|
||||
if (isText(attachment.name) || size < 64 * 1024) {
|
||||
@@ -138,7 +186,7 @@ export function attachmentPayload(attachment) {
|
||||
}
|
||||
if (body) {
|
||||
const clipped = body.length > 20000 ? `${body.slice(0, 20000)}\n…(已截断,共 ${body.length} 字符)` : body;
|
||||
out.text = `【文件 ${attachment.name}(${size} 字节)】\n\`\`\`\n${clipped}\n\`\`\``;
|
||||
out.text = `【文件 ${attachment.name}(${size} 字节)本地路径:${attachment.path}】\n\`\`\`\n${clipped}\n\`\`\``;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
85
tools/_ui_bridge.py
Normal file
85
tools/_ui_bridge.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""
|
||||
界面工具(AI 主动弹界面 / 弹窗 / 结束对话)和安卓原生桥之间的公共部分。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
三个工具干的事不同,但**和安卓那一侧通话的方式完全一样**:都是往
|
||||
`NativeBridge.device()` 发一个 JSON、收一个 JSON。把这段收在一处,
|
||||
以后加第四个界面工具就只要写 TOOL + run,不用再抄一遍桥接代码 ——
|
||||
这个仓库里"同一个逻辑抄两份,加功能时只改一份"的坑已经踩过好几次了。
|
||||
|
||||
## 为什么要带 conversationId
|
||||
|
||||
`end_conversation` 要**永久结束当前这次对话**,内核必须知道是哪一次。
|
||||
内核在组装工具前会把当前对话 id 塞进 settings 的 `_conversationId`
|
||||
(下划线开头,不会外泄给模型,也不会出现在 /api/state 里),
|
||||
这里取出来一起发给安卓侧。
|
||||
|
||||
## 电脑端会怎样
|
||||
|
||||
没有 `_android` 桥(桌面版)时,这几个工具都**明确返回不可用**,
|
||||
而不是假装成功 —— 让模型知道"这个端没有界面能力",它就不会反复重试。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def _bridge():
|
||||
"""
|
||||
拿到安卓原生桥对象;电脑端返回 None。
|
||||
|
||||
`doubao_entry` 只在安卓上存在(它是 Chaquopy 的入口模块),
|
||||
所以这里用 try/except 而不是判断平台字符串 —— 平台字符串判断错过一次
|
||||
(sys.platform 在 Chaquopy 里也是 'linux',跟桌面 Linux 分不开)。
|
||||
"""
|
||||
try:
|
||||
import doubao_entry # noqa: PLC0415 - 电脑端没有这个模块,只能运行时导入
|
||||
|
||||
return getattr(doubao_entry, '_android', None)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def call_device(payload: dict) -> dict:
|
||||
"""
|
||||
往安卓侧发一个 device 请求。
|
||||
|
||||
★ 参数名要和 Kotlin 侧 `NativeBridge.device()` 的 `req.optString(...)`
|
||||
对得上 —— 对不上不会报错,只会**静默拿到空字符串**,
|
||||
表现是"界面弹出来但标题是空的"。所以两边都写全。
|
||||
|
||||
@return 安卓侧回的 JSON;桥不在时返回 {'unavailable': True, ...}
|
||||
"""
|
||||
bridge = _bridge()
|
||||
if bridge is None:
|
||||
return {
|
||||
'unavailable': True,
|
||||
'error': '当前环境没有界面能力(电脑端的界面在桌面窗口里,这几个工具只在手机上生效)',
|
||||
}
|
||||
raw = bridge.device(json.dumps(payload, ensure_ascii=False))
|
||||
try:
|
||||
return json.loads(str(raw))
|
||||
except (ValueError, TypeError):
|
||||
return {'raw': str(raw)}
|
||||
|
||||
|
||||
def conversation_id() -> str:
|
||||
"""
|
||||
当前对话 id。
|
||||
|
||||
★ 从内核的"当前调用上下文"里取。`tools_runtime.execute_tool` 在调用工具前
|
||||
会把 settings 里的 `_conversationId` 放到 `_protocol` 能读到的地方 ——
|
||||
见 tools_runtime.current_context()。取不到就返回空串(安卓侧会当成
|
||||
"没有指定对话",只是不能结束对话,别的功能不受影响)。
|
||||
"""
|
||||
try:
|
||||
import tools_runtime # noqa: PLC0415
|
||||
|
||||
ctx = tools_runtime.current_context() or {}
|
||||
return str(ctx.get('conversationId') or '')
|
||||
except Exception: # noqa: BLE001
|
||||
return ''
|
||||
152
tools/ask_user.py
Normal file
152
tools/ask_user.py
Normal file
@@ -0,0 +1,152 @@
|
||||
"""让 AI 弹一个选择弹窗,并把用户选的那一项拿回去。
|
||||
|
||||
## 和 show_ui 的分工
|
||||
|
||||
`show_ui` 展示用 —— **不阻塞**,弹出来就返回,用户看完自己关
|
||||
`ask_user` 问询用 —— **阻塞**,等用户选完才返回,模型拿到选择继续干活
|
||||
|
||||
这两个刻意分开:展示性的东西不该把对话卡住;而"让用户在几个方案里选一个"
|
||||
必须拿到答案才能继续。
|
||||
|
||||
## 阻塞是怎么实现的
|
||||
|
||||
安卓侧 `NativeBridge.device()` 是同步的 —— 它在 UI 线程上弹出界面,
|
||||
然后用一个 `CountDownLatch` 等用户点,等到(或超时)才把结果回给 Python。
|
||||
Python 这边就是一次普通调用,不需要轮询。
|
||||
|
||||
★ 超时必须有:用户可能把手机锁屏走了,不能让内核线程永远挂着。
|
||||
默认 120 秒,到点返回 `timeout: true`,模型据此知道"用户没理我"。
|
||||
|
||||
## 电脑端
|
||||
|
||||
明确返回不可用(桌面版的界面在桌面窗口里)。
|
||||
"""
|
||||
|
||||
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, conversation_id # noqa: E402
|
||||
|
||||
# 等用户的秒数上限。安卓侧也有自己的上限,两边都不设的话
|
||||
# 用户锁屏走了会把内核的工作线程永远占住。
|
||||
TIMEOUT_S = 120
|
||||
|
||||
TOOL = {
|
||||
"name": "ask_user",
|
||||
"description": (
|
||||
"弹一个选择弹窗问用户,**等用户选完**再继续(最多等 120 秒)。"
|
||||
"适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。"
|
||||
"options 传选项数组(每项 {label, value, description}):"
|
||||
"label 是按钮上显示的字,value 是你要拿到的值(留空则用 label),"
|
||||
"description 是选项下方的小字说明。"
|
||||
"多选请传 multiple=true。返回里 choice/values 就是用户选的东西;"
|
||||
"timeout=true 表示用户没在时限内回答。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"question": {
|
||||
"type": "string",
|
||||
"description": "要问的问题",
|
||||
},
|
||||
"options": {
|
||||
"type": "array",
|
||||
"description": "选项列表",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {"type": "string", "description": "按钮上显示的文字"},
|
||||
"value": {"type": "string", "description": "返回给模型的值,留空则用 label"},
|
||||
"description": {"type": "string", "description": "选项下方的小字说明"},
|
||||
},
|
||||
"required": ["label"],
|
||||
},
|
||||
},
|
||||
"multiple": {
|
||||
"type": "boolean",
|
||||
"description": "是否允许多选,默认 false",
|
||||
},
|
||||
"allow_cancel": {
|
||||
"type": "boolean",
|
||||
"description": "是否显示「取消」按钮,默认 true",
|
||||
},
|
||||
},
|
||||
"required": ["question", "options"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _clean_options(raw) -> list:
|
||||
"""
|
||||
规整选项。
|
||||
|
||||
★ 模型经常把 options 写成裸字符串数组(`["A", "B"]`)而不是对象数组 ——
|
||||
这在 tool calling 里非常常见,直接 `.get()` 会 AttributeError。
|
||||
所以两种都收下,别让模型因为格式小错就吃一个报错。
|
||||
"""
|
||||
out = []
|
||||
for item in raw or []:
|
||||
if isinstance(item, dict):
|
||||
label = str(item.get("label") or item.get("value") or "").strip()
|
||||
if not label:
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"label": label,
|
||||
"value": str(item.get("value") or label),
|
||||
"description": str(item.get("description") or ""),
|
||||
}
|
||||
)
|
||||
elif isinstance(item, (str, int, float)):
|
||||
text = str(item).strip()
|
||||
if text:
|
||||
out.append({"label": text, "value": text, "description": ""})
|
||||
return out
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
question = str(args.get("question") or "").strip()
|
||||
if not question:
|
||||
raise ValueError("question 不能为空")
|
||||
options = _clean_options(args.get("options"))
|
||||
if not options:
|
||||
raise ValueError("options 至少要给一个选项")
|
||||
# 选项太多按钮会挤成一屏,截断并告诉模型(而不是静默丢掉)
|
||||
truncated = False
|
||||
if len(options) > 8:
|
||||
options = options[:8]
|
||||
truncated = True
|
||||
|
||||
res = call_device(
|
||||
{
|
||||
"action": "ui_dialog",
|
||||
"question": question,
|
||||
"options": options,
|
||||
"multiple": bool(args.get("multiple")),
|
||||
"allowCancel": bool(args.get("allow_cancel", True)),
|
||||
"timeoutMs": TIMEOUT_S * 1000,
|
||||
"conversationId": conversation_id(),
|
||||
}
|
||||
)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
|
||||
out = {
|
||||
"question": question,
|
||||
"multiple": bool(res.get("multiple")),
|
||||
"timeout": bool(res.get("timeout")),
|
||||
"cancelled": bool(res.get("cancelled")),
|
||||
"choice": res.get("choice") or "",
|
||||
"values": res.get("values") or [],
|
||||
}
|
||||
if truncated:
|
||||
out["note"] = "选项超过 8 个,只显示了前 8 个"
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
90
tools/end_conversation.py
Normal file
90
tools/end_conversation.py
Normal file
@@ -0,0 +1,90 @@
|
||||
"""让 AI 主动**永久结束**当前这次对话。
|
||||
|
||||
## "永久"是什么意思
|
||||
|
||||
不是"这一轮说完了",而是这次对话就此封笔:
|
||||
|
||||
· 会话被标记 `ended`(落盘,重启 App 也还在)
|
||||
· 界面上输入框变成「这次对话已结束」+ 一个「开始新对话」按钮
|
||||
· 再往里发消息会被挡住(用户想继续就开新的)
|
||||
|
||||
## 模型什么时候该用
|
||||
|
||||
· 用户要的事情已经彻底办完,且没有后续可聊的("帮我查完这趟航班" → 结束)
|
||||
· 用户自己说"就这样吧 / 不用了 / 结束"
|
||||
· 任务走进了死胡同,继续聊下去只会兜圈子
|
||||
|
||||
★ 提示词里明确要求它**先说明再结束** —— 直接封笔会让人莫名其妙。
|
||||
所以这个工具的 description 里写死了"要先在正文里说明已经结束"。
|
||||
|
||||
## 为什么要落盘而不是只改界面状态
|
||||
|
||||
界面状态一刷新就没了。用户关掉 App 再进来,会看到一个能继续输入的框,
|
||||
而模型那边以为自己已经结束了 —— 两边状态不一致是这类功能最容易出的问题。
|
||||
"""
|
||||
|
||||
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, conversation_id # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "end_conversation",
|
||||
"description": (
|
||||
"**永久结束当前这次对话**(落盘,重启 App 也生效):之后再发消息会被挡住,"
|
||||
"用户需要开一个新对话。"
|
||||
"只在事情真的办完、用户说了不用了、或者继续聊只会兜圈子时才用。"
|
||||
"★ 调用前必须先在正文里跟用户说明这次对话已经结束,别默默封笔。"
|
||||
"reason 用一句话说明为什么结束(会给用户看)。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reason": {
|
||||
"type": "string",
|
||||
"description": "为什么结束(一句话,会给用户看)",
|
||||
},
|
||||
"summary": {
|
||||
"type": "string",
|
||||
"description": "这次对话做了什么(可选,留作记录)",
|
||||
},
|
||||
},
|
||||
"required": ["reason"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
reason = str(args.get("reason") or "").strip()
|
||||
if not reason:
|
||||
raise ValueError("reason 不能为空(要告诉用户为什么结束)")
|
||||
conv = conversation_id()
|
||||
if not conv:
|
||||
# 拿不到对话 id 时**不能假装成功** —— 那样界面封了、盘上没封,
|
||||
# 用户重启后又能发消息,而模型以为自己结束了。
|
||||
raise RuntimeError("拿不到当前对话 id,无法结束对话")
|
||||
|
||||
res = call_device(
|
||||
{
|
||||
"action": "end_conversation",
|
||||
"conversationId": conv,
|
||||
"reason": reason,
|
||||
"summary": str(args.get("summary") or ""),
|
||||
}
|
||||
)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"ended": True,
|
||||
"conversationId": conv,
|
||||
"reason": reason,
|
||||
"note": "这次对话已永久结束。用户需要开新对话才能继续。",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
89
tools/show_ui.py
Normal file
89
tools/show_ui.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""让 AI 主动弹出一个 WebView 界面(自己写 HTML)。
|
||||
|
||||
## 这个工具存在的意义
|
||||
|
||||
普通的对话是一来一回的文本。有些东西**用界面表达比用文字好得多**:
|
||||
一张自己算出来的图表、一个把结果排版好的报告卡片、一个可以点的菜单、
|
||||
一段带样式的对比表。以前模型只能吐 markdown,表格一宽就乱。
|
||||
|
||||
这个工具让模型**直接写 HTML**,App 用一个全屏 WebView 渲染出来。
|
||||
|
||||
## 用法约定(也是给模型看的)
|
||||
|
||||
· `html` 里写**片段**就行(不用 <html>/<body>),会自动套一层带样式的骨架 ——
|
||||
这样模型不用每次重复写 viewport、暗色主题这些
|
||||
· 想要完整控制就传 `full_html=true`,那时 html 必须是一份完整文档
|
||||
· 界面里可以放按钮:`<button data-doubao-result="选了A">A</button>`
|
||||
—— 用户点了之后,那个 `data-doubao-result` 的值会回到模型手里
|
||||
(走 [ask_user] 那条回传通道,所以不需要模型自己写 JS)
|
||||
|
||||
## 电脑端
|
||||
|
||||
桌面版的界面在桌面窗口里,这个工具**明确返回不可用**,不假装成功。
|
||||
"""
|
||||
|
||||
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, conversation_id # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "show_ui",
|
||||
"description": (
|
||||
"在用户手机/平板上弹出一个界面,自己写 HTML 渲染(全屏 WebView)。"
|
||||
"适合:图表、排版好的报告卡片、对比表、可点的菜单、任何用文字说不清的东西。"
|
||||
"html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
|
||||
"想完全控制就传 full_html=true。"
|
||||
"界面里可以放 <button data-doubao-result=\"值\">文字</button>,"
|
||||
"用户点了之后那个值会回到你手里。"
|
||||
"调用后界面立刻显示、本工具立刻返回,用户看到之后再继续对话。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"html": {
|
||||
"type": "string",
|
||||
"description": "要渲染的 HTML(片段即可,除非 full_html=true)",
|
||||
},
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "顶部标题栏文字,可留空",
|
||||
},
|
||||
"full_html": {
|
||||
"type": "boolean",
|
||||
"description": "true 表示 html 是一份完整文档,不再套骨架。默认 false",
|
||||
},
|
||||
},
|
||||
"required": ["html"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
html = str(args.get("html") or "").strip()
|
||||
if not html:
|
||||
raise ValueError("html 不能为空")
|
||||
res = call_device(
|
||||
{
|
||||
"action": "ui_screen",
|
||||
"html": html,
|
||||
"title": str(args.get("title") or ""),
|
||||
"full_html": bool(args.get("full_html")),
|
||||
"conversationId": conversation_id(),
|
||||
}
|
||||
)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"shown": True,
|
||||
"bytes": len(html),
|
||||
"note": "界面已弹出,用户看完会自己关掉。你不需要再重复内容。",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
Reference in New Issue
Block a user