dsh-mobile-plugin 0.5.30 → 0.5.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cli/pair.cjs +3 -1
- package/lib/impl.js +0 -2
- package/lib/mobile/perf-trace.js +142 -0
- package/lib/relay/pairing-payload.cjs +3 -3
- package/lib/routes/control-plane.js +10 -3
- package/lib/routes/mobile-api.js +4 -115
- package/package.json +2 -4
- package/lib/mobile/cli/acp.js +0 -231
- package/lib/mobile/cli/agents.js +0 -217
- package/lib/mobile/cli/blocks.js +0 -228
- package/lib/mobile/cli/config-prefs.js +0 -155
- package/lib/mobile/cli/icons.js +0 -138
- package/lib/mobile/cli/images.js +0 -132
- package/lib/mobile/cli/mobile.js +0 -1535
- package/lib/mobile/cli/model-prefs.js +0 -77
- package/lib/mobile/cli/model-visibility.js +0 -92
- package/lib/mobile/cli/registry.js +0 -207
- package/lib/mobile/cli/service.js +0 -1042
- package/lib/mobile/cli/usage.js +0 -133
- package/lib/mobile/services.js +0 -16
- package/lib/mobile/terminal.js +0 -574
package/lib/cli/pair.cjs
CHANGED
|
@@ -90,7 +90,9 @@ async function main(argv) {
|
|
|
90
90
|
if (args.svg) {
|
|
91
91
|
const target = path.resolve(args.svg);
|
|
92
92
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
93
|
-
|
|
93
|
+
// 静区给 4 个模块(规范值)与 512 边长:这份 SVG 多半是存下来再转给手机扫,
|
|
94
|
+
// 白边不够、边长只有 280 的时候,手机从相册里认常常读不出来。
|
|
95
|
+
fs.writeFileSync(target, await QRCode.toString(text, { type: 'svg', errorCorrectionLevel: 'M', margin: 4, width: 512 }));
|
|
94
96
|
process.stdout.write(`二维码已存成图片:${target}\n如果终端太窄扫不动,把这个文件拿下来用看图软件打开再扫。\n\n`);
|
|
95
97
|
}
|
|
96
98
|
|
package/lib/impl.js
CHANGED
|
@@ -35,7 +35,6 @@ const { resolvePort } = require('./relay/port-allocator.cjs')
|
|
|
35
35
|
const { mountTailcat, chooseTailcatTarget } = require('./tailcat/wiring.cjs') // 直连隧道:入口 + 助手会话 + 启停
|
|
36
36
|
const { mountP2P, chooseP2PTarget } = require('./p2p/wiring.cjs') // 点对点隧道:只有助手会话(连接从隧道里进来,不必开回环门)+ 落点端口的选择
|
|
37
37
|
const { createPreviewService } = require('./relay/preview.js')
|
|
38
|
-
const { mountTerminal, mountCli } = require('./mobile/services.js')
|
|
39
38
|
// 手机打开「电脑上的网页版」时用的那枚一次性登录令牌(见 mobile/host-web.js)。
|
|
40
39
|
const hostWeb = require('./mobile/host-web.js')
|
|
41
40
|
// 本机设备凭据库:/api/relay/revoke-all 必须同时吊销局域网直连的 dshc_ 凭据,
|
|
@@ -534,7 +533,6 @@ function apply(ctx) {
|
|
|
534
533
|
// 一样必须包在 ctx.effect 里,否则插件重载时重复注册会直接抛错。
|
|
535
534
|
registerUpgradeRoute: (route) => mountRoute(route, true),
|
|
536
535
|
preview,
|
|
537
|
-
terminalService: mountTerminal(ctx, { authorized, name }), cliService: mountCli(ctx, { authorized, name }),
|
|
538
536
|
phoneService: mountPhoneControl(ctx, { authorized, credentials, instanceId: state.instanceId, name }),
|
|
539
537
|
// 网页版登录令牌那条:handler 在这里造好、按依赖交给路由表,理由与 preview 一样——
|
|
540
538
|
// 它要读的是本进程的 `ctx.webServer` 与 `ctx.get('connection')`。
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 操作记录回传:手机把「调试面板 → 操作记录」导出的一段正文交给宿主,宿主原样落到本机磁盘。
|
|
5
|
+
*
|
|
6
|
+
* **数据只落在用户自己这台电脑上,不出网。** 这条路由不转发给中转、不落任何远端存储:
|
|
7
|
+
* 收到什么就写进 `$DSH_HOME/mobile-traces/` 里的一个 JSON 文件,仅此而已。检查「手机上滑得
|
|
8
|
+
* 顺不顺」要的是那条设备自己记的时间线,留在本机就够了;把它送上云反而多一份没人要的副本。
|
|
9
|
+
*
|
|
10
|
+
* 正文(`text`)按原样存,不压成一行:这份文件是给人直接打开看的,转义过的 `\n` 一整片
|
|
11
|
+
* 读不出任何东西。
|
|
12
|
+
*
|
|
13
|
+
* 同目录的 `index.jsonl` 是一份轻量目录(每条一行:文件名 / 收到时刻 / 字节数 / 设备),
|
|
14
|
+
* 方便按时间翻;它写不进去不影响这次回传本身 —— 正文已经落盘了。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const fs = require('node:fs');
|
|
18
|
+
const path = require('node:path');
|
|
19
|
+
|
|
20
|
+
const { dshHome } = require('../shared/paths');
|
|
21
|
+
const { sendJson, readJsonBody } = require('../shared/http-util');
|
|
22
|
+
|
|
23
|
+
/** 正文上限:4MB(按 UTF-8 字节数算)。一次操作记录是文本时间线,到这个量已经是"记太久"。 */
|
|
24
|
+
const MAX_TEXT_BYTES = 4 * 1024 * 1024;
|
|
25
|
+
/**
|
|
26
|
+
* 请求体上限:比正文宽一档。JSON 里换行 / 引号都要转义,4MB 正文的请求体可能大出几成;
|
|
27
|
+
* 留到 12MB 是为了「正文合法但转义撑大了」不被误判成超限,真正的判据仍是 `text` 的字节数。
|
|
28
|
+
*/
|
|
29
|
+
const MAX_BODY_BYTES = 12 * 1024 * 1024;
|
|
30
|
+
/** label 进文件名的最长长度。 */
|
|
31
|
+
const MAX_LABEL = 40;
|
|
32
|
+
/** deviceId 短码取前几位。 */
|
|
33
|
+
const DEVICE_SHORT = 8;
|
|
34
|
+
|
|
35
|
+
/** 操作记录目录:`$DSH_HOME/mobile-traces`。 */
|
|
36
|
+
function tracesDir() {
|
|
37
|
+
return path.join(dshHome(), 'mobile-traces');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 文件名安全化:只留 `[a-zA-Z0-9_-]`,其它一律变 `_`。 */
|
|
41
|
+
function safeSegment(value, fallback) {
|
|
42
|
+
const raw = typeof value === 'string' ? value : '';
|
|
43
|
+
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
44
|
+
return cleaned || fallback;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 本地时间戳,冒号换掉(`:` 在文件名里不该出现):`2026-11-08T23-47-45-123`。 */
|
|
48
|
+
function localStamp(date) {
|
|
49
|
+
const pad = (n, width = 2) => String(n).padStart(width, '0');
|
|
50
|
+
return [
|
|
51
|
+
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`,
|
|
52
|
+
`${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}-${pad(date.getMilliseconds(), 3)}`,
|
|
53
|
+
].join('T');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 这次回传要落的文件名:`<本地时间戳>-<设备短码>-<label>.json`。
|
|
58
|
+
*
|
|
59
|
+
* @param {{ receivedAt: Date, deviceId?: string, label?: string }} input
|
|
60
|
+
*/
|
|
61
|
+
function traceFileName({ receivedAt, deviceId, label }) {
|
|
62
|
+
const device = safeSegment(deviceId, 'unknown').slice(0, DEVICE_SHORT);
|
|
63
|
+
const tag = safeSegment(label, 'trace').slice(0, MAX_LABEL);
|
|
64
|
+
return `${localStamp(receivedAt)}-${device || 'unknown'}-${tag}.json`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 处理 `POST /api/mobile/v1/perf-trace`。
|
|
69
|
+
*
|
|
70
|
+
* 请求体:`{ deviceId?, label?, startedAt: number, text: string, meta? }`。
|
|
71
|
+
* 成功回 `{ ok: true, file, path }`。
|
|
72
|
+
*
|
|
73
|
+
* @param {object} _ctx 插件 ctx(这条路由用不到)
|
|
74
|
+
* @param {object} req node:http IncomingMessage(信封请求的明文已在 `req.body`)
|
|
75
|
+
* @param {object} res node:http ServerResponse
|
|
76
|
+
*/
|
|
77
|
+
async function handlePerfTrace(_ctx, req, res) {
|
|
78
|
+
const body = await readJsonBody(req, MAX_BODY_BYTES);
|
|
79
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
80
|
+
return sendJson(res, 400, { ok: false, error: '请求体不是合法 JSON(或超过 12MB 上限)' });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const text = body.text;
|
|
84
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
85
|
+
return sendJson(res, 400, { ok: false, error: 'text 必须是非空字符串' });
|
|
86
|
+
}
|
|
87
|
+
const bytes = Buffer.byteLength(text, 'utf8');
|
|
88
|
+
if (bytes > MAX_TEXT_BYTES) {
|
|
89
|
+
return sendJson(res, 413, { ok: false, error: `text 太大:${bytes} 字节,上限 ${MAX_TEXT_BYTES} 字节(4MB)` });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const startedAt = body.startedAt;
|
|
93
|
+
if (typeof startedAt !== 'number' || !Number.isFinite(startedAt)) {
|
|
94
|
+
return sendJson(res, 400, { ok: false, error: 'startedAt 必须是有限数字(毫秒时间戳)' });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const deviceId = typeof body.deviceId === 'string' ? body.deviceId : '';
|
|
98
|
+
const label = typeof body.label === 'string' ? body.label : '';
|
|
99
|
+
const meta = body.meta && typeof body.meta === 'object' ? body.meta : null;
|
|
100
|
+
|
|
101
|
+
const receivedAt = new Date();
|
|
102
|
+
const dir = tracesDir();
|
|
103
|
+
const fileName = traceFileName({ receivedAt, deviceId, label });
|
|
104
|
+
const filePath = path.join(dir, fileName);
|
|
105
|
+
|
|
106
|
+
// 收到的原文 + 几格来源信息。2 空格缩进:这份文件是给人直接翻的。
|
|
107
|
+
const payload = {
|
|
108
|
+
receivedAt: receivedAt.toISOString(),
|
|
109
|
+
deviceId,
|
|
110
|
+
label,
|
|
111
|
+
startedAt,
|
|
112
|
+
meta,
|
|
113
|
+
text,
|
|
114
|
+
};
|
|
115
|
+
const serialized = `${JSON.stringify(payload, null, 2)}\n`;
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
119
|
+
fs.writeFileSync(filePath, serialized, { encoding: 'utf8', mode: 0o600 });
|
|
120
|
+
} catch (error) {
|
|
121
|
+
const reason = error && error.message ? error.message : String(error);
|
|
122
|
+
return sendJson(res, 500, { ok: false, error: `写盘失败: ${reason}` });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// 目录索引:一条一行。它只是方便翻,写不进去不影响上面已经落好的正文。
|
|
126
|
+
try {
|
|
127
|
+
const entry = { file: fileName, receivedAt: receivedAt.toISOString(), bytes: Buffer.byteLength(serialized, 'utf8'), deviceId };
|
|
128
|
+
fs.appendFileSync(path.join(dir, 'index.jsonl'), `${JSON.stringify(entry)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
129
|
+
} catch { /* 索引可选,不影响主请求 */ }
|
|
130
|
+
|
|
131
|
+
return sendJson(res, 200, { ok: true, file: fileName, path: filePath });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = {
|
|
135
|
+
handlePerfTrace,
|
|
136
|
+
tracesDir,
|
|
137
|
+
traceFileName,
|
|
138
|
+
safeSegment,
|
|
139
|
+
MAX_TEXT_BYTES,
|
|
140
|
+
MAX_LABEL,
|
|
141
|
+
DEVICE_SHORT,
|
|
142
|
+
};
|
|
@@ -53,9 +53,9 @@ function pairingPayload(state, lanPort) {
|
|
|
53
53
|
relayUrl: relay.relayUrl,
|
|
54
54
|
relayUrls: relay.relayUrls,
|
|
55
55
|
lanUrls: urls,
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
|
|
56
|
+
// **不再带 `lanCandidates`**:它与上面 `lanUrls` 是同一个数组,App 侧从来没读过它
|
|
57
|
+
// (`parsePairingInvite` 只取 `lanUrls`)。一份地址在二维码里出现两遍,白占几十个字符、
|
|
58
|
+
// 把码点压密一档 —— 而这正是「码看着清楚却扫不出来」的成本。
|
|
59
59
|
// IPv6 直连候选(理想情况下是手机**不在同一个 Wi-Fi 里**时唯一能拨到的地址):不参与上面
|
|
60
60
|
// 那份的排序,顺序由 App 侧拿它和公网中转实测比出来;直连监听没开就没有这条通道。
|
|
61
61
|
// 用户手填的那条缀在最后当兜底(只追加、不删网卡候选),见 `withManualIpv6Candidate`。
|
|
@@ -732,18 +732,25 @@ function registerControlPlaneRoutes(deps) {
|
|
|
732
732
|
return
|
|
733
733
|
}
|
|
734
734
|
try {
|
|
735
|
+
// 静区按规范给 4 个模块:以前是 2,四个角的白边只有半个模块宽,手机在屏幕反光、
|
|
736
|
+
// 或者从截图里认的时候常常连码的边界都找不到 —— 看上去清清楚楚,就是读不出来。
|
|
737
|
+
//
|
|
738
|
+
// 位图边长按 512 生成:SVG 本身是矢量、上屏怎么缩放都清楚,但人会把码截屏、存图、
|
|
739
|
+
// 发到相册里再扫,那时候落在手里的是这张位图,280 的位图放大到屏幕上就是糊的。
|
|
735
740
|
const svg = await QRCode.toString(text, {
|
|
736
741
|
type: 'svg',
|
|
737
742
|
errorCorrectionLevel: 'M',
|
|
738
|
-
margin:
|
|
739
|
-
width:
|
|
743
|
+
margin: 4,
|
|
744
|
+
width: 512,
|
|
740
745
|
})
|
|
741
746
|
sendJson(res, 200, {
|
|
742
747
|
ok: true,
|
|
743
748
|
name: payload.name,
|
|
744
749
|
relayUrl: payload.relayUrl,
|
|
745
750
|
// 完整列表:老面板/老手机不读它,新手机拿它当候选(首项恒等于上面那条)。
|
|
746
|
-
|
|
751
|
+
// 二维码里只有一条时不写这一格(省字符),回包这里照旧给一份单元素清单 —— 这一格
|
|
752
|
+
// 的形状自始至终是数组,别让调用方为了「有没有」再分一次叉。
|
|
753
|
+
relayUrls: payload.relayUrls || (payload.relayUrl ? [payload.relayUrl] : []),
|
|
747
754
|
lanUrls: payload.lanUrls,
|
|
748
755
|
pairingCode: payload.code,
|
|
749
756
|
// 二维码里带的局域网地址用的是这个端口:首选端口被占时它与 relay.json 里
|
package/lib/routes/mobile-api.js
CHANGED
|
@@ -65,10 +65,10 @@ const { createRelayControlHandlers } = require('../mobile/relay-control.js');
|
|
|
65
65
|
const uploads = require('../mobile/uploads.js');
|
|
66
66
|
const canvasStore = require('../mobile/canvas-store.js');
|
|
67
67
|
const inboxClean = require('../mobile/inbox-clean.js');
|
|
68
|
+
const perfTrace = require('../mobile/perf-trace.js');
|
|
68
69
|
// 过程播报开关(读 / 写同一条路径,由 req.method 分派)。默认关,见那个文件头。
|
|
69
70
|
const narration = require('../mobile/narration.js');
|
|
70
71
|
const git = require('../mobile/git.js');
|
|
71
|
-
const terminal = require('../mobile/terminal.js');
|
|
72
72
|
const pairing = require('../mobile/pairing.js');
|
|
73
73
|
// 设备批量同步(docs/device-batch-sync.md):一次性入场券 + 密文收件箱。
|
|
74
74
|
const sync = require('../mobile/sync.js');
|
|
@@ -113,79 +113,8 @@ const API_VERSION = '1';
|
|
|
113
113
|
* 所以它走 route() 即包 guarded。
|
|
114
114
|
*/
|
|
115
115
|
function registerMobileRoutes(deps) {
|
|
116
|
-
const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, preview, core, pairingApproval, rotatePairing,
|
|
117
|
-
|
|
118
|
-
// 不是宿主的会话,但手机上必须像普通会话一样可用 —— 列表 / 历史 / 发送 / 停止 / 流 /
|
|
119
|
-
// 审批 / 模型全走宿主那套端点。分派发生在 `route()` 里面,下面每条注册都还是原样一行,
|
|
120
|
-
// handler 一个都没抄;`sessionId` 不在 `cli-` 前缀上的请求原样交给原 handler。
|
|
121
|
-
const cliMobile = cliService && cliService.mobile
|
|
122
|
-
const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(withCliSession(path, handler)) })
|
|
123
|
-
/**
|
|
124
|
-
* 哪些路径要过 CLI 分派。
|
|
125
|
-
*
|
|
126
|
-
* 只收「请求体是 JSON / 只读」的那批:`route()` 里的分派要先读一次 POST 的请求体才能看见
|
|
127
|
-
* sessionId,二进制那条(`/session/file`、上传分片)一读就坏,所以它们不在名单里 ——
|
|
128
|
-
* CLI 会话也没有那些东西。
|
|
129
|
-
*/
|
|
130
|
-
const CLI_SESSION_PATHS = new Set([
|
|
131
|
-
'/api/mobile/v1/session',
|
|
132
|
-
'/api/mobile/v1/session/messages',
|
|
133
|
-
'/api/mobile/v1/session/send',
|
|
134
|
-
'/api/mobile/v1/session/attachment',
|
|
135
|
-
'/api/mobile/v1/session/head',
|
|
136
|
-
'/api/mobile/v1/session/stop',
|
|
137
|
-
'/api/mobile/v1/session/rename',
|
|
138
|
-
'/api/mobile/v1/session/fork',
|
|
139
|
-
'/api/mobile/v1/session/models',
|
|
140
|
-
'/api/mobile/v1/session/select-model',
|
|
141
|
-
'/api/mobile/v1/session/model-option',
|
|
142
|
-
'/api/mobile/v1/session/model-visibility',
|
|
143
|
-
'/api/mobile/v1/session/stats',
|
|
144
|
-
'/api/mobile/v1/session/read',
|
|
145
|
-
'/api/mobile/v1/session/delivery',
|
|
146
|
-
'/api/mobile/v1/session/search',
|
|
147
|
-
'/api/mobile/v1/session/goal',
|
|
148
|
-
'/api/mobile/v1/session/queue/update',
|
|
149
|
-
'/api/mobile/v1/commands',
|
|
150
|
-
'/api/mobile/v1/skills',
|
|
151
|
-
'/api/mobile/v1/subagents',
|
|
152
|
-
'/api/mobile/v1/file-references',
|
|
153
|
-
'/api/mobile/v1/session-references',
|
|
154
|
-
'/api/mobile/v1/extension/cards',
|
|
155
|
-
// 导出:CLI 会话没有宿主日志,这条回一份空 ZIP(见 cli/mobile.js 的 handleExport)。
|
|
156
|
-
'/api/mobile/v1/session-log',
|
|
157
|
-
])
|
|
158
|
-
/**
|
|
159
|
-
* 会话级开关里那四条「属于会话自己、不属于工作区」的写:归档 / 取消归档 / 置顶 /
|
|
160
|
-
* 取消置顶。CLI 会话在宿主那本账里没有条目,原样透过去只会换一张错误卡,所以 `cli-*`
|
|
161
|
-
* 由适配层自己记(内存账,跟 CLI 会话一起没)。
|
|
162
|
-
*/
|
|
163
|
-
const CLI_SESSION_FLAGS = {
|
|
164
|
-
'/api/mobile/v1/workspace/archive-session': 'archive',
|
|
165
|
-
'/api/mobile/v1/workspace/unarchive-session': 'unarchive',
|
|
166
|
-
'/api/mobile/v1/workspace/pin-session': 'pin',
|
|
167
|
-
'/api/mobile/v1/workspace/unpin-session': 'unpin',
|
|
168
|
-
}
|
|
169
|
-
function withCliSession(path, handler) {
|
|
170
|
-
if (!cliMobile) return handler
|
|
171
|
-
if (path === '/api/mobile/v1/sessions') return cliMobile.wrapSessions(handler)
|
|
172
|
-
if (CLI_SESSION_FLAGS[path]) return cliMobile.routeFlag(CLI_SESSION_FLAGS[path], handler)
|
|
173
|
-
if (path === '/api/mobile/v1/workspace/clear-archived') return cliMobile.wrapClearArchived(handler)
|
|
174
|
-
// 后台提醒视图:CLI 会话的「在跑 / 刚完成 / 待回话」也从这里出去(注入成取值器,
|
|
175
|
-
// monitor.js 不认识 CLI 的任何细节,出口形状不变)。
|
|
176
|
-
if (path === '/api/mobile/v1/monitor') {
|
|
177
|
-
return (ctx, req, res) => handler(ctx, req, res, () => cliMobile.monitorItems())
|
|
178
|
-
}
|
|
179
|
-
if (path === '/api/mobile/v1/approval/respond') return cliMobile.wrapApprovalRespond(handler)
|
|
180
|
-
if (path === '/api/mobile/v1/session/stream') {
|
|
181
|
-
return (ctx, req, res) => {
|
|
182
|
-
const sessionId = new URL(req.url || '/', 'http://x').searchParams.get('sessionId')
|
|
183
|
-
return cliMobile.isCliSessionId(sessionId) ? cliMobile.handleStream(ctx, req, res) : handler(ctx, req, res)
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
if (CLI_SESSION_PATHS.has(path)) return cliMobile.route(path, handler)
|
|
187
|
-
return handler
|
|
188
|
-
}
|
|
116
|
+
const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, preview, core, pairingApproval, rotatePairing, phoneService } = deps;
|
|
117
|
+
const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(handler) })
|
|
189
118
|
// 中转配置那一组要**装配期已有的实例**(config store、sidecar 生命周期),不能靠模块级
|
|
190
119
|
// 单例去拿:同一进程里两份 relay.json 的真值只会打架。所以这里按装配层给的依赖建一次。
|
|
191
120
|
const relayControl = createRelayControlHandlers(deps.relayControl || {})
|
|
@@ -410,6 +339,7 @@ function registerMobileRoutes(deps) {
|
|
|
410
339
|
// 密钥时那头静默忽略——这条路由照常回 ok,「推没推成」不是 App 要操心的事。
|
|
411
340
|
// 判据(要不要收这个令牌)与配对同一把锁:guarded 已核过设备身份。
|
|
412
341
|
route('/api/mobile/v1/push-token', pushNotifyRoute.createPushTokenHandler({ pushNotify: deps.pushNotify }))
|
|
342
|
+
route('/api/mobile/v1/perf-trace', perfTrace.handlePerfTrace)
|
|
413
343
|
route('/api/mobile/v1/session', sessions.handleSession)
|
|
414
344
|
route('/api/mobile/v1/session/messages', sessions.handleMessages)
|
|
415
345
|
// 一步的过程详情:清单只带一行摘要,点开某一步才来这里取参数 / 输出 / diff / 思考全文。
|
|
@@ -439,12 +369,6 @@ function registerMobileRoutes(deps) {
|
|
|
439
369
|
route('/api/mobile/v1/session/select-model', sessions.handleSelectModel)
|
|
440
370
|
// 模型之外的附加选项(速度、输出详略……):写一条已声明的行,落地是宿主自己的设置。
|
|
441
371
|
route('/api/mobile/v1/session/model-option', sessionModelOptions.handleModelOption)
|
|
442
|
-
// CLI 模型管理页的开关(只影响显示,真值存在那台电脑上,见 cli/model-visibility.js)。
|
|
443
|
-
// 这条只对 CLI 会话有意义:宿主那套模型目录没有「跨手机一致」的要求,所以非 CLI 的
|
|
444
|
-
// sessionId 一律回 400,不做静默成功。
|
|
445
|
-
route('/api/mobile/v1/session/model-visibility', async (_ctx, _req, res) => {
|
|
446
|
-
sendJson(res, 400, { ok: false, error: { code: 'cli-only', message: '这条接口只对 CLI 会话有效' } });
|
|
447
|
-
})
|
|
448
372
|
route('/api/mobile/v1/session/stats', sessions.handleStats)
|
|
449
373
|
// 统计总览(统计页)。账本落在宿主家里(`$DSH_HOME/mobile-stats.json`),与会话日志
|
|
450
374
|
// 无关:归档只是挪位置,清理删的是日志,历史数字都还在 —— 见 mobile/stats-ledger.cjs。
|
|
@@ -749,42 +673,7 @@ function registerMobileRoutes(deps) {
|
|
|
749
673
|
//
|
|
750
674
|
// 路径字面量必须与 App 侧 apiPaths.ts 的 preview 一致:test/mobile-routes.test.cjs
|
|
751
675
|
// 就是拿这张表反向核对 App 常量表的。
|
|
752
|
-
// 远程终端(见 mobile/terminal.js):白名单 CLI + 受管伪终端。
|
|
753
|
-
//
|
|
754
|
-
// 四条普通路由里只有 `agents` / `sessions` 是读,另两条是起与收;真正的字节流走下面的
|
|
755
|
-
// 升级路由。`terminalService` 从装配层来(会话表要在插件重载时被一起收掉,不能是模块单例)。
|
|
756
|
-
if (terminalService) {
|
|
757
|
-
route('/api/mobile/v1/terminal/agents', terminalService.handleAgents)
|
|
758
|
-
route('/api/mobile/v1/terminal/session', terminalService.handleCreate)
|
|
759
|
-
route('/api/mobile/v1/terminal/close', terminalService.handleClose)
|
|
760
|
-
route('/api/mobile/v1/terminal/sessions', terminalService.handleSessions)
|
|
761
|
-
}
|
|
762
676
|
registerUpgradeRoute({ path: '/api/mobile/v1/preview', handler: preview.handleUpgrade })
|
|
763
|
-
// 终端字节流:与预览同一套升级机制(中转与局域网代理都不看路径)。
|
|
764
|
-
if (terminalService) registerUpgradeRoute({ path: '/api/mobile/v1/terminal/stream', handler: terminalService.handleUpgrade })
|
|
765
|
-
|
|
766
|
-
// CLI 对话(见 mobile/cli/service.js):同一批白名单 CLI,但走 ACP —— 手机拿到的是结构化
|
|
767
|
-
// 的消息 / 工具调用 / 审批请求,所以能像正常对话一样渲染,而不是一块终端屏幕。
|
|
768
|
-
//
|
|
769
|
-
// 与终端那组并列存在,不是替换:终端留着给「我要看原始 TUI」的那一档。`cliService` 同样
|
|
770
|
-
// 从装配层来(会话表要在插件重载时被一起收掉,不能是模块单例)。
|
|
771
|
-
if (cliService) {
|
|
772
|
-
route('/api/mobile/v1/cli/agents', cliService.handleAgents)
|
|
773
|
-
route('/api/mobile/v1/cli/session', cliService.handleCreate)
|
|
774
|
-
route('/api/mobile/v1/cli/close', cliService.handleClose)
|
|
775
|
-
route('/api/mobile/v1/cli/sessions', cliService.handleSessions)
|
|
776
|
-
// 读一份全貌 + 三个写动作。WS 是快的那条路;隧道上偶尔「握手成了、帧进不来」,这一组
|
|
777
|
-
// 是它的兜底(页面轮询 detail、发送走 HTTP),两边共用服务层同一份实现。
|
|
778
|
-
route('/api/mobile/v1/cli/detail', cliService.handleDetail)
|
|
779
|
-
route('/api/mobile/v1/cli/prompt', cliService.handlePrompt)
|
|
780
|
-
route('/api/mobile/v1/cli/permission', cliService.handlePermission)
|
|
781
|
-
route('/api/mobile/v1/cli/cancel', cliService.handleCancel)
|
|
782
|
-
route('/api/mobile/v1/cli/config', cliService.handleConfig)
|
|
783
|
-
// 「这个 CLI 以后按哪一套跑」:配置页读它、也写它。与上一条的区别是**不动正在跑的会话**,
|
|
784
|
-
// 只决定下一次开局(ACP 的配置是会话级的,所以要提前存一份,见 cli/config-prefs.js)。
|
|
785
|
-
route('/api/mobile/v1/cli/prefs', cliService.handlePrefs)
|
|
786
|
-
registerUpgradeRoute({ path: '/api/mobile/v1/cli/stream', handler: cliService.handleUpgrade })
|
|
787
|
-
}
|
|
788
677
|
|
|
789
678
|
// 「让 AI 操作手机」(见 mobile/phone/):三条状态路由与一条动作字节流的升级口。
|
|
790
679
|
//
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mobile-plugin",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.32",
|
|
4
4
|
"description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"icon": "./icon.png",
|
|
@@ -58,10 +58,8 @@
|
|
|
58
58
|
"release:check": "node scripts/preflight-release.mjs"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@agentclientprotocol/sdk": "2.4.0",
|
|
62
61
|
"qrcode": "1.5.4",
|
|
63
|
-
"ws": "8.18.0"
|
|
64
|
-
"zod": "4.6.5"
|
|
62
|
+
"ws": "8.18.0"
|
|
65
63
|
},
|
|
66
64
|
"optionalDependencies": {
|
|
67
65
|
"dsh-mobile-tailcat-darwin-arm64": "1.1.1",
|
package/lib/mobile/cli/acp.js
DELETED
|
@@ -1,231 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 一个 ACP 适配器子进程 = 一条 CLI 会话的**连接层**。
|
|
5
|
-
*
|
|
6
|
-
* 协议实现用官方库 `@agentclientprotocol/sdk`(稳定 v1 入口),不自己写 JSON-RPC:
|
|
7
|
-
* 那正是这次不做「逐家适配」的关键 —— 四家 CLI 的差别全被适配器吃掉了,这里只认一种协议。
|
|
8
|
-
*
|
|
9
|
-
* 为什么用动态 `import()`:插件这一层是 CJS(`lib/mobile/package.json`),而 SDK 是纯 ESM。
|
|
10
|
-
* 稳定入口的运行时要 zod(`dist/v1/schema/zod.gen.js` 里 `import * as z from "zod/v4"`),
|
|
11
|
-
* 所以 zod 是我们的**直接依赖**,不是可选 peer —— 靠宿主或 profile 里碰巧有一份,
|
|
12
|
-
* 装到关了自动补 peer 的环境里就是「zod 落在安装闭包之外」。
|
|
13
|
-
*
|
|
14
|
-
* `session/update` 一律走 `onNotification` 自己接,**不用** SDK 的 `ActiveSession`:后者会把
|
|
15
|
-
* 每条更新再排进一个内部队列供 `nextUpdate()` 取,我们从不取,等于给每个会话攒一个只涨不
|
|
16
|
-
* 落的数组。
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
const { spawn } = require('node:child_process');
|
|
20
|
-
const fs = require('node:fs');
|
|
21
|
-
const { Readable, Writable } = require('node:stream');
|
|
22
|
-
|
|
23
|
-
const { childEnv } = require('./agents.js');
|
|
24
|
-
const { openImage } = require('./images.js');
|
|
25
|
-
|
|
26
|
-
/** 握手超时:适配器第一次要 npx 下载,给足;再久就当它起不来了。 */
|
|
27
|
-
const START_TIMEOUT_MS = 180000;
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* 报给适配器的客户端身份。
|
|
31
|
-
*
|
|
32
|
-
* `version` **不能省**:ACP 的 `Implementation` 把它标成可选,但 opencode 那边的校验是
|
|
33
|
-
* 必填的 —— 少这一格整条 `initialize` 会回 `-32602 Invalid params`,表现就是界面上一直
|
|
34
|
-
* 「正在启动」(适配器根本没接上)。codex / claude 不挑,所以只有 opencode 会露出来。
|
|
35
|
-
*/
|
|
36
|
-
const CLIENT_INFO = { name: 'dsh-mobile', version: pluginVersion() };
|
|
37
|
-
|
|
38
|
-
function pluginVersion() {
|
|
39
|
-
try {
|
|
40
|
-
const version = require('../../package.json').version;
|
|
41
|
-
return typeof version === 'string' && version ? version : '0.0.0';
|
|
42
|
-
} catch {
|
|
43
|
-
return '0.0.0';
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
let sdkPromise = null;
|
|
48
|
-
|
|
49
|
-
function loadSdk() {
|
|
50
|
-
if (!sdkPromise) sdkPromise = import('@agentclientprotocol/sdk');
|
|
51
|
-
return sdkPromise;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function noop() {}
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* 起适配器并完成握手,返回一个会话句柄。
|
|
58
|
-
*
|
|
59
|
-
* 失败一律抛错,`message` 是要给用户看的人话(服务层把它变成一条 notice 块 + exit 帧)。
|
|
60
|
-
*/
|
|
61
|
-
async function startAgent({ spec, cwd, env, onUpdate, onPermission, onStderr, onExit }) {
|
|
62
|
-
const sdk = await loadSdk();
|
|
63
|
-
const child = spawn(spec.command, spec.args, {
|
|
64
|
-
cwd,
|
|
65
|
-
env: env || childEnv(spec.command),
|
|
66
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
let exited = false;
|
|
70
|
-
child.stdin.on('error', noop);
|
|
71
|
-
child.stdout.on('error', noop);
|
|
72
|
-
child.stderr.on('error', noop);
|
|
73
|
-
|
|
74
|
-
let stderrTail = '';
|
|
75
|
-
if (onStderr) {
|
|
76
|
-
child.stderr.on('data', (chunk) => {
|
|
77
|
-
const text = String(chunk);
|
|
78
|
-
stderrTail = (stderrTail + text).slice(-2000);
|
|
79
|
-
onStderr(text);
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
child.on('error', (error) => {
|
|
84
|
-
if (exited) return;
|
|
85
|
-
exited = true;
|
|
86
|
-
onExit?.(error && error.message ? error.message : '适配器起不来');
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
const app = sdk.client({ name: 'dsh-mobile' });
|
|
90
|
-
app.onRequest(sdk.methods.client.session.requestPermission, async (ctx) => {
|
|
91
|
-
// 适配器等这一个 promise 决定「放不放行」,所以它必须**只有一条** resolve 路径:
|
|
92
|
-
if (!onPermission) return { outcome: { outcome: 'cancelled' } };
|
|
93
|
-
return onPermission(ctx.params);
|
|
94
|
-
});
|
|
95
|
-
app.onNotification(sdk.methods.client.session.update, (ctx) => {
|
|
96
|
-
try {
|
|
97
|
-
onUpdate?.(ctx.params && ctx.params.update);
|
|
98
|
-
} catch { /* 一条更新解析失败不该掐断整条流 */ }
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
const stream = sdk.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
|
|
102
|
-
const conn = app.connect(stream);
|
|
103
|
-
|
|
104
|
-
conn.closed.then(() => {
|
|
105
|
-
if (exited) return;
|
|
106
|
-
exited = true;
|
|
107
|
-
onExit?.(stderrTail.trim().split('\n').slice(-1)[0] || '适配器退出了');
|
|
108
|
-
}, noop);
|
|
109
|
-
|
|
110
|
-
/** 握手整体超时。 */
|
|
111
|
-
const deadline = new Promise((_resolve, reject) => {
|
|
112
|
-
setTimeout(() => {
|
|
113
|
-
reject(new Error('适配器启动超时,可能卡在下载或登录上'));
|
|
114
|
-
}, START_TIMEOUT_MS).unref?.();
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
let promptCapabilities = null;
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* 收掉这条连接与它的子进程。
|
|
121
|
-
*
|
|
122
|
-
* 必须定义在握手**之前**:握手失败或超时时这里直接抛错,而那时子进程已经起来了 —— 不在这
|
|
123
|
-
* 条路径上关掉,它就成了一个没人管的孤儿进程(卡在登录界面、还在等输入)。探配置那条路会
|
|
124
|
-
* 反复进来,漏一次就是攒一个进程。
|
|
125
|
-
*/
|
|
126
|
-
function kill() {
|
|
127
|
-
try { conn.close(); } catch { /* 已经关了 */ }
|
|
128
|
-
try { child.kill('SIGTERM'); } catch { /* 已经退出 */ }
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
let session;
|
|
132
|
-
try {
|
|
133
|
-
session = await Promise.race([
|
|
134
|
-
(async () => {
|
|
135
|
-
const initialized = await conn.agent.request(sdk.methods.agent.initialize, {
|
|
136
|
-
protocolVersion: sdk.PROTOCOL_VERSION,
|
|
137
|
-
// 不认领文件系统与终端能力:四家 CLI 都有自己的文件访问,我们替它读写反而要多做
|
|
138
|
-
// 一套实现,做漏了就是一条静默失败的路。
|
|
139
|
-
clientCapabilities: { terminal: false },
|
|
140
|
-
clientInfo: CLIENT_INFO,
|
|
141
|
-
});
|
|
142
|
-
// 这家认不认图片输入:握手时它自己说。不说就按「不支持」处理 —— 硬塞 image 块过去,
|
|
143
|
-
// 有的适配器会直接回一条参数错误,把整轮提问连正文一起废掉。
|
|
144
|
-
promptCapabilities = (initialized && initialized.agentCapabilities && initialized.agentCapabilities.promptCapabilities) || null;
|
|
145
|
-
const created = await conn.agent.request(sdk.methods.agent.session.new, {
|
|
146
|
-
cwd,
|
|
147
|
-
mcpServers: [],
|
|
148
|
-
});
|
|
149
|
-
return { sessionId: created.sessionId, created };
|
|
150
|
-
})(),
|
|
151
|
-
deadline,
|
|
152
|
-
]);
|
|
153
|
-
} catch (error) {
|
|
154
|
-
kill();
|
|
155
|
-
throw error;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
return {
|
|
159
|
-
child,
|
|
160
|
-
sessionId: session.sessionId,
|
|
161
|
-
created: session.created,
|
|
162
|
-
/**
|
|
163
|
-
* 会话创建时给出的可配置项(模型 / 思考档 / 权限模式…)与模式表。
|
|
164
|
-
*
|
|
165
|
-
* ACP 把它们定成「客户端画一组下拉、选中就回一条 set」,各家 CLI 的差别全被吃掉:
|
|
166
|
-
* opencode 把模型放在 `configOptions`,claude 把模式放在 `modes`,codex 两者都给。
|
|
167
|
-
* 所以手机上的「选模型」不需要为每家写一套,照着这两张表画就行。
|
|
168
|
-
*/
|
|
169
|
-
configOptions: Array.isArray(session.created.configOptions) ? session.created.configOptions : [],
|
|
170
|
-
modes: session.created.modes ?? null,
|
|
171
|
-
/** 这家认不认图片输入(握手时它自己声明的 `promptCapabilities.image`)。 */
|
|
172
|
-
get supportsImages() { return Boolean(promptCapabilities && promptCapabilities.image); },
|
|
173
|
-
get alive() { return !exited; },
|
|
174
|
-
/**
|
|
175
|
-
* 发一轮提问;resolve 时这一轮结束(ACP 的 `session/prompt` 就是这么定的)。
|
|
176
|
-
*
|
|
177
|
-
* `images` 是已经存好的图片元数据(`{ attachmentId, mediaType }`):按 ACP 的 image 块
|
|
178
|
-
* 发过去 —— `{type:'image', data, mimeType}`,字节在这一次请求里内联(ACP 只有这一种
|
|
179
|
-
* 传法,没有「你自己去读这个路径」的入口,我们也没认领 fs 能力)。
|
|
180
|
-
*/
|
|
181
|
-
prompt(text_, images) {
|
|
182
|
-
const blocks = [];
|
|
183
|
-
for (const image of Array.isArray(images) ? images : []) {
|
|
184
|
-
const stored = openImage(image && image.attachmentId);
|
|
185
|
-
if (!stored) continue;
|
|
186
|
-
try {
|
|
187
|
-
blocks.push({
|
|
188
|
-
type: 'image',
|
|
189
|
-
data: fs.readFileSync(stored.path).toString('base64'),
|
|
190
|
-
mimeType: stored.mediaType || image.mediaType || 'image/png',
|
|
191
|
-
});
|
|
192
|
-
} catch { /* 读不出来就只丢这一张,正文照发 */ }
|
|
193
|
-
}
|
|
194
|
-
if (text_) blocks.push({ type: 'text', text: text_ });
|
|
195
|
-
if (blocks.length === 0) blocks.push({ type: 'text', text: '' });
|
|
196
|
-
return conn.agent.request(sdk.methods.agent.session.prompt, {
|
|
197
|
-
sessionId: session.sessionId,
|
|
198
|
-
prompt: blocks,
|
|
199
|
-
});
|
|
200
|
-
},
|
|
201
|
-
cancel() {
|
|
202
|
-
return conn.agent.notify(sdk.methods.agent.session.cancel, { sessionId: session.sessionId });
|
|
203
|
-
},
|
|
204
|
-
/** 改一项配置(选模型 / 换思考档)。`configId` 就是 `configOptions[].id`。 */
|
|
205
|
-
setConfigOption(configId, value) {
|
|
206
|
-
return conn.agent.request(sdk.methods.agent.session.setConfigOption, {
|
|
207
|
-
sessionId: session.sessionId,
|
|
208
|
-
configId,
|
|
209
|
-
value,
|
|
210
|
-
});
|
|
211
|
-
},
|
|
212
|
-
/** 换模式(claude 的 Manual / Accept edits / Plan 那一组)。 */
|
|
213
|
-
setMode(modeId) {
|
|
214
|
-
return conn.agent.request(sdk.methods.agent.session.setMode, {
|
|
215
|
-
sessionId: session.sessionId,
|
|
216
|
-
modeId,
|
|
217
|
-
});
|
|
218
|
-
},
|
|
219
|
-
close() {
|
|
220
|
-
// 会话收尾是尽力而为:适配器不支持 `session/close` 就直接断进程。
|
|
221
|
-
try {
|
|
222
|
-
conn.agent.request(sdk.methods.agent.session.close, { sessionId: session.sessionId }).catch(noop);
|
|
223
|
-
} catch { /* 同上 */ }
|
|
224
|
-
kill();
|
|
225
|
-
setTimeout(kill, 1500).unref?.();
|
|
226
|
-
},
|
|
227
|
-
kill,
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
module.exports = { startAgent, loadSdk, START_TIMEOUT_MS };
|