dsh-mobile-plugin 0.5.31 → 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/impl.js +0 -2
- package/lib/mobile/perf-trace.js +142 -0
- package/lib/relay/pairing-payload.cjs +3 -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
|
@@ -1,1042 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 移动端「CLI 对话」:`/api/mobile/v1/cli/*` 的 handler、会话表与 WebSocket 流。
|
|
5
|
-
*
|
|
6
|
-
* 与远程终端(`mobile/terminal.js`)是同一个能力的两种呈现,边界也同一条:可执行文件只能
|
|
7
|
-
* 是 `agents.js` 那张表里的名字,工作目录只能来自这台设备已注册的工作区,没有「执行任意命令」
|
|
8
|
-
* 的路由。区别是终端把 TUI 字节原样搬给手机,这里让 CLI 以 ACP 的方式跑、把结构化事件
|
|
9
|
-
* 交给对话页 —— 手机因此能像正常对话一样看正文、看工具调用、点审批。
|
|
10
|
-
*
|
|
11
|
-
* 三个设计点:
|
|
12
|
-
*
|
|
13
|
-
* 1. **建会话立刻返回**。适配器第一次要 `npx` 下载桥包、之后还要握手,几十秒都可能;把它
|
|
14
|
-
* 压在一次 HTTP 里,App 那边的请求会先超时。所以 create 只建记录、回 `starting`,真正的
|
|
15
|
-
* 启动在后台跑,进度与失败都从 WS 帧上报(`notice` / `status` / `exit`)。
|
|
16
|
-
* 2. **块要攒批发**。流式正文每秒几十段,一段一帧等于把「出字节奏」换成「网络往返次数」。
|
|
17
|
-
* 攒 60ms 一轮,同一块的多次改动只发最后那一份。
|
|
18
|
-
* 3. **会话托管在宿主**。手机锁屏、切后台、换 Wi-Fi 都不该把 CLI 掐掉;重连时 `hello` 帧
|
|
19
|
-
* 带全量块重放,页面回到原样。
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
const { homedir } = require('node:os');
|
|
23
|
-
const { WebSocketServer } = require('ws');
|
|
24
|
-
|
|
25
|
-
const { readJsonBody, sendJson } = require('../../shared/http-util');
|
|
26
|
-
const { unwrap } = require('../envelope.js');
|
|
27
|
-
const { AGENTS, resolveAgent, childEnv, installedPackages, isInstalled } = require('./agents.js');
|
|
28
|
-
const { loadIcons } = require('./icons.js');
|
|
29
|
-
const { createUsage, applyUsageUpdate, applyPromptUsage } = require('./usage.js');
|
|
30
|
-
const { listRegistryAgents } = require('./registry.js');
|
|
31
|
-
const { preferredModel, rememberModel } = require('./model-prefs.js');
|
|
32
|
-
const { prefsOf, setValue, rememberOptions, describe } = require('./config-prefs.js');
|
|
33
|
-
const images = require('./images.js');
|
|
34
|
-
const { createBlockLog } = require('./blocks.js');
|
|
35
|
-
const { startAgent } = require('./acp.js');
|
|
36
|
-
const { createCliMobile } = require('./mobile.js');
|
|
37
|
-
|
|
38
|
-
/** 错误码 → HTTP 状态;与终端那一组同口径。 */
|
|
39
|
-
const STATUS_BY_CODE = {
|
|
40
|
-
BAD_REQUEST: 400,
|
|
41
|
-
FORBIDDEN: 403,
|
|
42
|
-
NOT_FOUND: 404,
|
|
43
|
-
UNSUPPORTED: 400,
|
|
44
|
-
AGENT_UNAVAILABLE: 404,
|
|
45
|
-
WORKSPACE_UNAVAILABLE: 502,
|
|
46
|
-
TOO_MANY_SESSIONS: 429,
|
|
47
|
-
SPAWN_FAILED: 500,
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
/** 同时活着的 CLI 会话上限:每一条都挂着一个真进程(有的还带一个 app-server)。 */
|
|
51
|
-
const MAX_SESSIONS = 4;
|
|
52
|
-
|
|
53
|
-
/** 流式块的攒批窗口。 */
|
|
54
|
-
const FLUSH_MS = 60;
|
|
55
|
-
|
|
56
|
-
/** 标题兜底截断长度(宿主没给 `session_info_update.title` 时用首条提问)。 */
|
|
57
|
-
const TITLE_MAX = 40;
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* 「探一次配置」的失败重试间隔。
|
|
61
|
-
*
|
|
62
|
-
* 探一次要起一个适配器(首次还可能要 npx 下载),不能每次进配置页都重来一遍;但也不该把
|
|
63
|
-
* 一次失败记一辈子 —— 用户多半是去装了 CLI / 登录了才回来的。
|
|
64
|
-
*/
|
|
65
|
-
const PROBE_RETRY_MS = 60 * 1000;
|
|
66
|
-
|
|
67
|
-
class CliRequestError extends Error {
|
|
68
|
-
constructor(code, message) {
|
|
69
|
-
super(message);
|
|
70
|
-
this.name = 'CliRequestError';
|
|
71
|
-
this.code = code;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function fail(code, message) {
|
|
76
|
-
return new CliRequestError(code, message);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function text(value) {
|
|
80
|
-
return typeof value === 'string' ? value.trim() : '';
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function query(req) {
|
|
84
|
-
return new URL(req.url || '/', 'http://x').searchParams;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* 「这条新会话还差哪几项没套上」—— 记着的偏好 ∩ 新会话真有的选项。
|
|
89
|
-
*
|
|
90
|
-
* 抽成纯函数是为了能脱离进程直接钉(`test/cli-config-prefs.test.cjs` 跑的就是这一份,不是
|
|
91
|
-
* 照抄一份等价实现):三条同时成立才写 —— ① 用户记过这一项 ② 新会话里有这一项 ③ 这个值还在
|
|
92
|
-
* 它的候选里。少了任何一条都跳过:CLI 升级换了档位名、或者这一版少了某个选项,硬塞过去只会
|
|
93
|
-
* 让整条会话卡在一个它不认识的值上。
|
|
94
|
-
*
|
|
95
|
-
* 模型那一项不在这里(它记在 `model-prefs` 那本账里,由 `applyPreferredModel` 负责),
|
|
96
|
-
* 免得两边各写一次、后写的那次盖掉前一次。
|
|
97
|
-
*/
|
|
98
|
-
function pendingPrefsOf(session) {
|
|
99
|
-
const recorded = prefsOf(session.agentId).values;
|
|
100
|
-
const options = Array.isArray(session.configOptions) ? session.configOptions : [];
|
|
101
|
-
const skip = new Set(['model']);
|
|
102
|
-
for (const option of options) {
|
|
103
|
-
if (option && option.category === 'model') skip.add(option.id);
|
|
104
|
-
}
|
|
105
|
-
// 模型那一项记在 `model-prefs` 那本账里(`applyPreferredModel` 负责),这里一律跳过 ——
|
|
106
|
-
// 包括 id 不叫 `model` 的那些(claude 的 `agent` 子代理、opencode 的分组模型)。
|
|
107
|
-
const out = [];
|
|
108
|
-
for (const [configId, value] of Object.entries(recorded)) {
|
|
109
|
-
if (skip.has(configId)) continue;
|
|
110
|
-
const option = options.find((item) => item && item.id === configId);
|
|
111
|
-
if (!option) continue;
|
|
112
|
-
if (String(option.currentValue) === value) continue;
|
|
113
|
-
const choices = Array.isArray(option.options) ? option.options : [];
|
|
114
|
-
if (!choices.some((item) => item && String(item.value) === value)) continue;
|
|
115
|
-
out.push([configId, value]);
|
|
116
|
-
}
|
|
117
|
-
return out;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async function bodyJson(req) {
|
|
121
|
-
const body = await readJsonBody(req, 64 * 1024);
|
|
122
|
-
if (!body || typeof body !== 'object') throw fail('BAD_REQUEST', '需要 JSON 请求体');
|
|
123
|
-
return body;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* 这一项是不是「模型」。
|
|
128
|
-
*
|
|
129
|
-
* 判据是 ACP 给的 `category`,不是 id 的字面值:codex/opencode 叫 `model`,claude 的模型
|
|
130
|
-
* 项也叫 `model`,但换一家可能就是别的名字 —— 按 id 猜就会漏掉一家,而漏掉的表现正是
|
|
131
|
-
* 「配置页勾上了、开新对话还是原来的模型」。认不出(配置页还没拿到选项表)就按 id 兜底。
|
|
132
|
-
*/
|
|
133
|
-
function isModelOption(options, configId) {
|
|
134
|
-
const list = Array.isArray(options) ? options : [];
|
|
135
|
-
const option = list.find((item) => item && item.id === configId);
|
|
136
|
-
if (option) return option.category === 'model';
|
|
137
|
-
return configId === 'model';
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* 配置页要画的「记着的那一套」。
|
|
142
|
-
*
|
|
143
|
-
* 两本账合到一处:模型记在 `model-prefs`(新会话开局由 `applyPreferredModel` 套),其余记在
|
|
144
|
-
* `config-prefs`。配置页只认一张表,所以在这里并起来 —— 不并的话,配置页里模型那一格永远
|
|
145
|
-
* 显示「跟 CLI 自己的一样」,用户选过的模型看不见。
|
|
146
|
-
*/
|
|
147
|
-
function valuesBodyOf(agentId, options) {
|
|
148
|
-
const values = { ...prefsOf(agentId).values };
|
|
149
|
-
const preferred = preferredModel(agentId);
|
|
150
|
-
if (preferred) values[preferred.configId] = preferred.value;
|
|
151
|
-
// 两本账里都不该有「模型」,但真出现过(旧版本写进去的)就别让它冒充生效值。
|
|
152
|
-
for (const key of Object.keys(values)) {
|
|
153
|
-
if (isModelOption(options, key) && !(preferred && preferred.configId === key)) delete values[key];
|
|
154
|
-
}
|
|
155
|
-
return values;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** 会话表与它的所有出口。一个宿主进程一份(装配层建、装配层关)。 */
|
|
159
|
-
function createCliService({ authorized, onLog } = {}) {
|
|
160
|
-
/** sessionId → 会话。 */
|
|
161
|
-
const sessions = new Map();
|
|
162
|
-
let seq = 0;
|
|
163
|
-
let permSeq = 0;
|
|
164
|
-
let closed = false;
|
|
165
|
-
|
|
166
|
-
const wss = new WebSocketServer({
|
|
167
|
-
noServer: true,
|
|
168
|
-
perMessageDeflate: false,
|
|
169
|
-
maxPayload: 256 * 1024,
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
const log = (message) => { try { onLog?.(message); } catch { /* 日志失败不该影响搬运 */ } };
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* 这一次的适配器清单:注册表(带缓存与兜底)那份,`agents.js` 内置四家垫底。
|
|
176
|
-
*
|
|
177
|
-
* 建会话与列清单都走它,所以「列出来的」和「点得下去的」永远是同一批 —— 两份各自算的话,
|
|
178
|
-
* 注册表刚更新那一下会出现「列表里有、点了说不认识」。
|
|
179
|
-
*/
|
|
180
|
-
let agentsPromise = null;
|
|
181
|
-
function listAgents() {
|
|
182
|
-
if (!agentsPromise) {
|
|
183
|
-
agentsPromise = listRegistryAgents(AGENTS).catch(() => AGENTS);
|
|
184
|
-
}
|
|
185
|
-
return agentsPromise;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/** agentId → `{ running, at, error, done }`:这一家探配置的状态(同时只允许一次)。 */
|
|
189
|
-
const probes = new Map();
|
|
190
|
-
|
|
191
|
-
function probeState(agentId) {
|
|
192
|
-
return probes.get(agentId) || null;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* 现去问一次这个 CLI 有哪些可调项。
|
|
197
|
-
*
|
|
198
|
-
* 为什么要这一步:选项表是 CLI 自己在握手之后给的,缓存里只有「开过对话的那几家」。用户新
|
|
199
|
-
* 装一个 CLI、想先把权限档配好再去用,正是最需要配置页的时候,而那时缓存是空的 —— 配置页
|
|
200
|
-
* 就是一句「没有可调的项」,四个配置入口点下去长得一模一样。
|
|
201
|
-
*
|
|
202
|
-
* 代价是起一次适配器(首次还要 npx 下载),所以:同一个 CLI 同时只探一次;探到手就落缓存,
|
|
203
|
-
* 之后的配置页直接读;失败记一段时间(`PROBE_RETRY_MS`),别让用户每次进来都等一轮下载。
|
|
204
|
-
* 它不进 `sessions` 那张表 —— 这是一次性的探测进程,拿到表就关,侧栏里不该多出一行。
|
|
205
|
-
*/
|
|
206
|
-
function startProbe(ctx, agentId) {
|
|
207
|
-
if (probes.has(agentId) && probes.get(agentId).running) return;
|
|
208
|
-
const entry = { running: true, at: Date.now(), error: '', done: false };
|
|
209
|
-
probes.set(agentId, entry);
|
|
210
|
-
void (async () => {
|
|
211
|
-
let handle = null;
|
|
212
|
-
try {
|
|
213
|
-
const agent = (await listAgents()).find((item) => item && item.id === agentId) || null;
|
|
214
|
-
if (!agent) throw new Error('这台电脑上没有这个 CLI');
|
|
215
|
-
const spec = resolveAgent(agent);
|
|
216
|
-
if (!spec.ok) throw new Error(spec.reason || '这个 CLI 起不来');
|
|
217
|
-
// 起在哪:配置项与目录无关,随便借一个已注册工作区(没有工作区就借家目录 —— 有些适配器
|
|
218
|
-
// 对 cwd 有要求,给个存在且可写的路径总比空串安全)。
|
|
219
|
-
const cwd = await pickProbeCwd(ctx);
|
|
220
|
-
handle = await startAgent({ spec, cwd, env: childEnv(spec.command) });
|
|
221
|
-
if (closed) return;
|
|
222
|
-
// 探到了就记下来(这家确实一项都不给时记的是空表,配置页据此说「没有可调的项」
|
|
223
|
-
// 而不是一直转圈)。
|
|
224
|
-
rememberOptions(agentId, handle.configOptions);
|
|
225
|
-
entry.error = '';
|
|
226
|
-
// 这一家**问过了**:哪怕它一项配置都不给,也不许再探第二次 —— 那等于每进一次配置页
|
|
227
|
-
// 就起一个适配器进程,而结果永远是同一张空表。
|
|
228
|
-
entry.done = true;
|
|
229
|
-
} catch (error) {
|
|
230
|
-
entry.error = error && error.message ? error.message : '问不到这个 CLI 的配置';
|
|
231
|
-
log(`cli 探配置失败(${agentId}):${entry.error}`);
|
|
232
|
-
} finally {
|
|
233
|
-
entry.running = false;
|
|
234
|
-
entry.at = Date.now();
|
|
235
|
-
try { handle?.close(); } catch { /* 已经退了 */ }
|
|
236
|
-
}
|
|
237
|
-
})();
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** 探测进程的工作目录:优先借一个已注册工作区,取不到就用家目录。 */
|
|
241
|
-
async function pickProbeCwd(ctx) {
|
|
242
|
-
try {
|
|
243
|
-
const listed = await ctx.apiProxy.workspace.list({ rpcId: 'mobile', method: 'workspace.list', payload: {} });
|
|
244
|
-
const { value } = unwrap(listed);
|
|
245
|
-
const items = Array.isArray(value) ? value : (value && Array.isArray(value.items) ? value.items : []);
|
|
246
|
-
for (const item of items) {
|
|
247
|
-
const dir = text(item && item.path);
|
|
248
|
-
if (dir) return dir;
|
|
249
|
-
}
|
|
250
|
-
} catch { /* 取不到就退到家目录 */ }
|
|
251
|
-
return homedir();
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
function send(ws, frame) {
|
|
255
|
-
if (ws.readyState !== ws.OPEN) return;
|
|
256
|
-
try { ws.send(JSON.stringify(frame)); } catch { /* 已经断了 */ }
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function broadcast(session, frame) {
|
|
260
|
-
for (const ws of session.sockets) send(ws, frame);
|
|
261
|
-
// 普通会话那套移动端接口(`cli/mobile.js`)挂在同一条广播上:它同样需要「块变了 /
|
|
262
|
-
// 状态变了 / 卡来了」这几件事,但出口是 SSE 而不是 WebSocket。失败不能影响搬运。
|
|
263
|
-
for (const sink of session.sinks) { try { sink(frame); } catch { /* 单个观众写失败不影响别人 */ } }
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
/**
|
|
267
|
-
* 挂一个非 WebSocket 的观众(`cli/mobile.js` 的 SSE)。
|
|
268
|
-
*
|
|
269
|
-
* 返回解绑函数。会话被收掉时 sinks 跟着会话对象一起没,不需要额外清理。
|
|
270
|
-
*/
|
|
271
|
-
function watch(session, sink) {
|
|
272
|
-
session.sinks.add(sink);
|
|
273
|
-
return () => { session.sinks.delete(sink); };
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
/** 攒批:同一块的多次改动只发最后那一份。 */
|
|
277
|
-
function markBlock(session, block) {
|
|
278
|
-
session.dirty.set(block.id, block);
|
|
279
|
-
if (session.timer) return;
|
|
280
|
-
session.timer = setTimeout(() => {
|
|
281
|
-
session.timer = null;
|
|
282
|
-
const pending = [...session.dirty.values()];
|
|
283
|
-
session.dirty.clear();
|
|
284
|
-
for (const item of pending) broadcast(session, { t: 'block', block: item });
|
|
285
|
-
}, FLUSH_MS);
|
|
286
|
-
session.timer.unref?.();
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function flushNow(session) {
|
|
290
|
-
if (session.timer) { clearTimeout(session.timer); session.timer = null; }
|
|
291
|
-
const pending = [...session.dirty.values()];
|
|
292
|
-
session.dirty.clear();
|
|
293
|
-
for (const item of pending) broadcast(session, { t: 'block', block: item });
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
function detailOf(session) {
|
|
297
|
-
return {
|
|
298
|
-
sessionId: session.id,
|
|
299
|
-
agent: session.agentId,
|
|
300
|
-
label: session.label,
|
|
301
|
-
workspaceId: session.workspaceId,
|
|
302
|
-
title: session.title,
|
|
303
|
-
cwd: session.cwd,
|
|
304
|
-
status: session.status,
|
|
305
|
-
updatedAt: session.updatedAt,
|
|
306
|
-
createdAt: session.createdAt,
|
|
307
|
-
// 会话的可配置项 / 模式 / 斜杠命令:手机照着这两张表画「选模型」与「模式」,
|
|
308
|
-
// 不必为每家 CLI 各写一套(见 acp.js 的 configOptions)。
|
|
309
|
-
configOptions: session.configOptions,
|
|
310
|
-
modes: session.modes,
|
|
311
|
-
commands: session.commands,
|
|
312
|
-
// 挂着的审批也要进这一份:审批原本只靠 WS 那一帧送达,帧进不来时卡片永远不出现,
|
|
313
|
-
// 而适配器那头正等着这个回答。放进详情里,轮询那条路也能把它画出来。
|
|
314
|
-
permissions: [...session.permissionFrames.values()],
|
|
315
|
-
blocks: session.blocks.list(),
|
|
316
|
-
};
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/** 只发「配置 / 命令变了」,不重发整份块(那是 `hello` 的活)。 */
|
|
320
|
-
function pushConfig(session) {
|
|
321
|
-
broadcast(session, {
|
|
322
|
-
t: 'config',
|
|
323
|
-
configOptions: session.configOptions,
|
|
324
|
-
modes: session.modes,
|
|
325
|
-
commands: session.commands,
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
function setStatus(session, status) {
|
|
330
|
-
if (session.status === status) return;
|
|
331
|
-
session.status = status;
|
|
332
|
-
session.updatedAt = Date.now();
|
|
333
|
-
broadcast(session, { t: 'status', status });
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
function setTitle(session, title) {
|
|
337
|
-
const clean = text(title);
|
|
338
|
-
if (!clean || clean === session.title) return;
|
|
339
|
-
session.title = clean;
|
|
340
|
-
session.updatedAt = Date.now();
|
|
341
|
-
broadcast(session, { t: 'title', title: clean });
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
function say(session, level, message) {
|
|
345
|
-
const block = session.blocks.notice(level, message, Date.now());
|
|
346
|
-
flushNow(session);
|
|
347
|
-
markBlock(session, block);
|
|
348
|
-
flushNow(session);
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
/** 进程没了(正常退出 / 崩溃 / 握不上手):收口块、拒掉挂着的审批、告诉每一部手机。 */
|
|
352
|
-
function finish(session, reason) {
|
|
353
|
-
if (session.finished || session.closed) return;
|
|
354
|
-
session.finished = true;
|
|
355
|
-
session.handle = null;
|
|
356
|
-
for (const [, pending] of session.permissions) {
|
|
357
|
-
try { pending({ outcome: { outcome: 'cancelled' } }); } catch { /* 已经没了 */ }
|
|
358
|
-
}
|
|
359
|
-
session.permissions.clear();
|
|
360
|
-
session.permissionFrames.clear();
|
|
361
|
-
for (const block of session.blocks.settle(Date.now())) markBlock(session, block);
|
|
362
|
-
// 同上:块先出去,再播「退出了」,否则最后一段正文会跟在收口帧后面。
|
|
363
|
-
flushNow(session);
|
|
364
|
-
session.status = 'error';
|
|
365
|
-
session.updatedAt = Date.now();
|
|
366
|
-
broadcast(session, { t: 'status', status: 'error' });
|
|
367
|
-
broadcast(session, { t: 'exit', reason: text(reason) || 'CLI 退出了' });
|
|
368
|
-
log(`cli ${session.id}: 退出(${text(reason) || '未说明'})`);
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
function onUpdate(session, update) {
|
|
372
|
-
const at = Date.now();
|
|
373
|
-
const kind = update && update.sessionUpdate;
|
|
374
|
-
// 配置类事件不进块表:它们是「这一页能做哪些设置」,画在输入条上。
|
|
375
|
-
if (kind === 'available_commands_update') {
|
|
376
|
-
const list = Array.isArray(update.availableCommands) ? update.availableCommands : [];
|
|
377
|
-
session.commands = list.map((entry) => ({
|
|
378
|
-
name: text(entry.name),
|
|
379
|
-
description: text(entry.description),
|
|
380
|
-
...(entry.input ? { hint: text(entry.input.hint) } : {}),
|
|
381
|
-
})).filter((entry) => entry.name);
|
|
382
|
-
pushConfig(session);
|
|
383
|
-
return;
|
|
384
|
-
}
|
|
385
|
-
if (kind === 'config_option_update') {
|
|
386
|
-
if (Array.isArray(update.configOptions)) session.configOptions = update.configOptions;
|
|
387
|
-
pushConfig(session);
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
if (kind === 'current_mode_update') {
|
|
391
|
-
if (session.modes && text(update.currentModeId)) session.modes = { ...session.modes, currentModeId: text(update.currentModeId) };
|
|
392
|
-
pushConfig(session);
|
|
393
|
-
return;
|
|
394
|
-
}
|
|
395
|
-
// 用量不进块表:它是一条指标,不是对话内容(见 `cli/usage.js`)。
|
|
396
|
-
if (kind === 'usage_update') {
|
|
397
|
-
if (applyUsageUpdate(session.usage, update)) session.updatedAt = at;
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
const result = session.blocks.apply(update, at);
|
|
401
|
-
if (!result) return;
|
|
402
|
-
session.updatedAt = at;
|
|
403
|
-
if (result.title) setTitle(session, result.title);
|
|
404
|
-
if (result.block) markBlock(session, result.block);
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
/** 适配器要放行:做成一条挂着的 promise,等手机上点。 */
|
|
408
|
-
function onPermission(session, params) {
|
|
409
|
-
permSeq += 1;
|
|
410
|
-
const id = `p${permSeq}`;
|
|
411
|
-
const toolCall = (params && params.toolCall) || {};
|
|
412
|
-
const options = Array.isArray(params && params.options) ? params.options : [];
|
|
413
|
-
const request = {
|
|
414
|
-
id,
|
|
415
|
-
title: text(toolCall.title) || '需要你的许可',
|
|
416
|
-
detail: toolCall.rawInput === undefined ? '' : JSON.stringify(toolCall.rawInput).slice(0, 400),
|
|
417
|
-
options: options.map((option) => ({
|
|
418
|
-
optionId: option.optionId,
|
|
419
|
-
name: text(option.name) || option.optionId,
|
|
420
|
-
kind: text(option.kind) || 'allow_once',
|
|
421
|
-
})),
|
|
422
|
-
};
|
|
423
|
-
session.permissionFrames.set(id, request);
|
|
424
|
-
broadcast(session, { t: 'permission', request });
|
|
425
|
-
return new Promise((resolve) => {
|
|
426
|
-
session.permissions.set(id, (outcome) => {
|
|
427
|
-
session.permissions.delete(id);
|
|
428
|
-
session.permissionFrames.delete(id);
|
|
429
|
-
broadcast(session, { t: 'permission-resolved', id });
|
|
430
|
-
resolve(outcome);
|
|
431
|
-
});
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
async function boot(session, spec) {
|
|
436
|
-
try {
|
|
437
|
-
const handle = await startAgent({
|
|
438
|
-
spec,
|
|
439
|
-
cwd: session.cwd,
|
|
440
|
-
env: childEnv(spec.command),
|
|
441
|
-
onUpdate: (update) => onUpdate(session, update),
|
|
442
|
-
onPermission: (params) => onPermission(session, params),
|
|
443
|
-
onExit: (reason) => finish(session, reason),
|
|
444
|
-
});
|
|
445
|
-
if (session.closed) { handle.close(); return; }
|
|
446
|
-
session.handle = handle;
|
|
447
|
-
session.finished = false;
|
|
448
|
-
session.configOptions = handle.configOptions || [];
|
|
449
|
-
session.modes = handle.modes || null;
|
|
450
|
-
// 选项表先记一份:配置页在没开这条会话时要能画出「权限档有哪几个」。
|
|
451
|
-
rememberOptions(session.agentId, session.configOptions);
|
|
452
|
-
await applyRecordedPrefs(session, handle);
|
|
453
|
-
// 套完之后再记一次:CLI 升级换了档位名时,这一步会把过期的选项表刷成新的。
|
|
454
|
-
rememberOptions(session.agentId, session.configOptions);
|
|
455
|
-
pushConfig(session);
|
|
456
|
-
setStatus(session, 'idle');
|
|
457
|
-
log(`cli ${session.id}: ${session.label} 起来了`);
|
|
458
|
-
} catch (error) {
|
|
459
|
-
if (session.closed) return;
|
|
460
|
-
// 适配器的报错是英文原文(`Invalid params` / `Authentication required` 之类),单看一眼
|
|
461
|
-
// 不知道是谁出了问题,所以前面补一句「哪个 CLI 起不来」。
|
|
462
|
-
const raw = error && error.message ? error.message : '不知道什么原因';
|
|
463
|
-
const message = `${session.label} 起不来:${raw}`;
|
|
464
|
-
say(session, 'error', message);
|
|
465
|
-
finish(session, message);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
/**
|
|
470
|
-
* 发一轮。
|
|
471
|
-
*
|
|
472
|
-
* WS 与 HTTP 两个入口都走这一份:WS 是快的那条路,HTTP 是「隧道上帧进不来」时的兜底
|
|
473
|
-
* (手机上实测过这条,见 A1-259 的坑)。所以两边都不能各写一份,不然行为会分叉。
|
|
474
|
-
*
|
|
475
|
-
* `images` 是这一发带的图(已经存好的元数据,见 `cli/images.js`):块表记一份、交给适配器
|
|
476
|
-
* 一份。**只有正文没有图**也照常走这里,与之前完全一样。
|
|
477
|
-
*/
|
|
478
|
-
function runPrompt(session, message, images) {
|
|
479
|
-
const pictures = Array.isArray(images) ? images.filter(Boolean) : [];
|
|
480
|
-
if (!message && pictures.length === 0) return { ok: false, error: '空消息' };
|
|
481
|
-
if (session.finished || !session.handle) {
|
|
482
|
-
say(session, 'error', 'CLI 还没起来,先等一下');
|
|
483
|
-
return { ok: false, error: 'CLI 还没起来' };
|
|
484
|
-
}
|
|
485
|
-
if (session.status === 'running') {
|
|
486
|
-
say(session, 'info', '上一轮还没结束,先停一下再发');
|
|
487
|
-
return { ok: false, error: '上一轮还没结束' };
|
|
488
|
-
}
|
|
489
|
-
if (pictures.length > 0 && session.handle.supportsImages === false) {
|
|
490
|
-
say(session, 'error', `${session.label} 不接受图片输入,这一发没带图`);
|
|
491
|
-
return { ok: false, error: '这个 CLI 不接受图片' };
|
|
492
|
-
}
|
|
493
|
-
markBlock(session, session.blocks.pushUser(message, Date.now(), pictures));
|
|
494
|
-
flushNow(session);
|
|
495
|
-
// 宿主还没给过标题就用首条提问兜一个 —— 侧栏那一行不能一直写着 CLI 的名字。
|
|
496
|
-
// 只发了图没写字的:标题留给适配器自己(它多半会按上下文生成一个)。
|
|
497
|
-
if (message && session.title === session.label) {
|
|
498
|
-
setTitle(session, message.length > TITLE_MAX ? `${message.slice(0, TITLE_MAX)}…` : message);
|
|
499
|
-
}
|
|
500
|
-
setStatus(session, 'running');
|
|
501
|
-
const handle = session.handle;
|
|
502
|
-
const startedAt = Date.now();
|
|
503
|
-
handle.prompt(message, pictures).then(
|
|
504
|
-
(result) => {
|
|
505
|
-
// 用量先记:`/session/stats` 就在这一轮之后被 App 拉一次,记晚了那一发读到的是上一轮。
|
|
506
|
-
applyPromptUsage(session.usage, result, Date.now() - startedAt);
|
|
507
|
-
// 顺序:先让落定的块出去,再播 idle。反过来的话最后那一段正文会落在 `turn/end`
|
|
508
|
-
// 之后,App 收到它会把已经收尾的这一轮重新认成「在跑」(见 cli/mobile.js 的 onBlock)。
|
|
509
|
-
for (const block of session.blocks.settle(Date.now())) markBlock(session, block);
|
|
510
|
-
flushNow(session);
|
|
511
|
-
if (!session.finished) setStatus(session, 'idle');
|
|
512
|
-
},
|
|
513
|
-
(error) => {
|
|
514
|
-
const reason = error && error.message ? error.message : '这一轮失败了';
|
|
515
|
-
for (const block of session.blocks.settle(Date.now())) markBlock(session, block);
|
|
516
|
-
flushNow(session);
|
|
517
|
-
say(session, 'error', reason);
|
|
518
|
-
setStatus(session, handle.alive ? 'idle' : 'error');
|
|
519
|
-
},
|
|
520
|
-
);
|
|
521
|
-
return { ok: true };
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* 把「这个 CLI 上次选的模型」套到刚起来的这条会话上。
|
|
526
|
-
*
|
|
527
|
-
* ACP 的模型是会话级配置,不套的话每次新会话都回到 CLI 自己的默认,用户每一轮都要重选一次
|
|
528
|
-
* —— 普通会话里没有这种事(宿主那边的默认模型是设备级的)。值在新会话的目录里已经不存在
|
|
529
|
-
* (CLI 升级换了名字)时不设,留在默认上,别硬塞一个它不认识的。
|
|
530
|
-
*/
|
|
531
|
-
/**
|
|
532
|
-
* 把用户在配置页定下的那一套套到这条新会话上(见 `cli/config-prefs.js`)。
|
|
533
|
-
*
|
|
534
|
-
* 顺序:先模型(`model-prefs` 那本老账),再其余各项(档位 / 权限模式 / 快速档)。逐项都是
|
|
535
|
-
* 「新会话里有这一项、且这个值还在它的选项里」才写,写不动就跳过 —— 一条过期的偏好不该让
|
|
536
|
-
* 会话建不起来,也不该把用户静默留在 CLI 的默认上还以为是自己的设置。
|
|
537
|
-
*
|
|
538
|
-
* 每一项的回包都带完整的新 `configOptions`,直接用它:手机随后那次目录请求读到的就是最终值。
|
|
539
|
-
*/
|
|
540
|
-
async function applyRecordedPrefs(session, handle) {
|
|
541
|
-
await applyPreferredModel(session, handle);
|
|
542
|
-
for (const [configId, value] of pendingPrefsOf(session)) {
|
|
543
|
-
try {
|
|
544
|
-
const updated = await handle.setConfigOption(configId, value);
|
|
545
|
-
if (updated && Array.isArray(updated.configOptions)) session.configOptions = updated.configOptions;
|
|
546
|
-
} catch {
|
|
547
|
-
// 这一项写不进去:停在 CLI 自己的默认,别连累其余几项。
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
async function applyPreferredModel(session, handle) {
|
|
553
|
-
const preferred = preferredModel(session.agentId);
|
|
554
|
-
if (!preferred) return;
|
|
555
|
-
const options = Array.isArray(session.configOptions) ? session.configOptions : [];
|
|
556
|
-
const option = options.find((item) => item && item.id === preferred.configId);
|
|
557
|
-
const values = option && Array.isArray(option.options) ? option.options : [];
|
|
558
|
-
if (!option || !values.some((item) => item && String(item.value) === preferred.value)) return;
|
|
559
|
-
if (String(option.currentValue) === preferred.value) return;
|
|
560
|
-
try {
|
|
561
|
-
const updated = await handle.setConfigOption(preferred.configId, preferred.value);
|
|
562
|
-
// 回包带着新的一整份配置项:直接用它,手机上那次目录请求就能看见已选中。
|
|
563
|
-
if (updated && Array.isArray(updated.configOptions)) session.configOptions = updated.configOptions;
|
|
564
|
-
log(`cli ${session.id}: 套上了上次选的模型(${preferred.value})`);
|
|
565
|
-
} catch {
|
|
566
|
-
// 设不动就维持 CLI 的默认:这不是失败,界面上照旧能选。
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
function answerPermission(session, id, optionId) {
|
|
571
|
-
const pending = session.permissions.get(id);
|
|
572
|
-
if (!pending || !optionId) return false;
|
|
573
|
-
pending({ outcome: { outcome: 'selected', optionId } });
|
|
574
|
-
return true;
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
function cancelTurn(session) {
|
|
578
|
-
try { session.handle?.cancel(); } catch { /* 已经没了 */ }
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
function forget(sessionId) {
|
|
582
|
-
const session = sessions.get(sessionId);
|
|
583
|
-
if (!session) return false;
|
|
584
|
-
session.closed = true;
|
|
585
|
-
sessions.delete(sessionId);
|
|
586
|
-
if (session.timer) { clearTimeout(session.timer); session.timer = null; }
|
|
587
|
-
for (const [, pending] of session.permissions) {
|
|
588
|
-
try { pending({ outcome: { outcome: 'cancelled' } }); } catch { /* 已经没了 */ }
|
|
589
|
-
}
|
|
590
|
-
session.permissions.clear();
|
|
591
|
-
try { session.handle?.close(); } catch { /* 可能已经退出 */ }
|
|
592
|
-
for (const ws of session.sockets) {
|
|
593
|
-
try { ws.close(); } catch { /* 已经关了 */ }
|
|
594
|
-
}
|
|
595
|
-
session.sockets.clear();
|
|
596
|
-
return true;
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
/**
|
|
600
|
-
* GET cli/agents:这台电脑上**装了、现在能聊**的 CLI。
|
|
601
|
-
*
|
|
602
|
-
* 清单来自官方 ACP 注册表(见 `cli/registry.js`),拉不到就退回内置的四家。建会话时按同一
|
|
603
|
-
* 份清单回头查,所以「列出来的」与「点得下去的」永远是同一批。
|
|
604
|
-
*
|
|
605
|
-
* 两条口径:
|
|
606
|
-
*
|
|
607
|
-
* 1. **注册表补进来的那些要求本机真的装了**(`isInstalled`)。注册表是「npx 能拉哪些」,
|
|
608
|
-
* 不是「这台电脑上有哪些」;照单全列,手机上就是一屏从没装过、图标还认不出来的
|
|
609
|
-
* 条目 —— 用户会以为是我们编的(2026-11-04 用户报的就是这个)。内置那四条不受此限:
|
|
610
|
-
* 它们是本仓维护的那一档,桥包由 npx 按需拉。
|
|
611
|
-
* 2. **图标跟着走**:每家一枚官方 SVG(`cli/icons.js` 本地缓存),认不出的那几家退成
|
|
612
|
-
* 首字母方块 —— 由 App 兜,插件这边只给能给的。
|
|
613
|
-
*/
|
|
614
|
-
async function handleAgents(_ctx, _req, res) {
|
|
615
|
-
const listed = await listAgents();
|
|
616
|
-
const builtin = new Set(AGENTS.map((agent) => agent.id));
|
|
617
|
-
const installed = installedPackages();
|
|
618
|
-
const kept = listed.filter((agent) => builtin.has(agent.id) || isInstalled(agent, installed));
|
|
619
|
-
const icons = await loadIcons(listed, kept.map((agent) => agent.id)).catch(() => ({}));
|
|
620
|
-
const agents = kept.map((agent) => {
|
|
621
|
-
const spec = resolveAgent(agent);
|
|
622
|
-
return {
|
|
623
|
-
id: agent.id,
|
|
624
|
-
label: agent.label,
|
|
625
|
-
available: spec.ok,
|
|
626
|
-
...(spec.ok ? {} : { reason: spec.reason }),
|
|
627
|
-
...(agent.description ? { description: agent.description } : {}),
|
|
628
|
-
...(icons[agent.id] ? { icon: icons[agent.id] } : {}),
|
|
629
|
-
};
|
|
630
|
-
});
|
|
631
|
-
sendJson(res, 200, { ok: true, agents });
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
/**
|
|
635
|
-
* POST cli/session { workspaceId, agent }
|
|
636
|
-
*
|
|
637
|
-
* 工作目录从工作区清单里取:手机只给 `workspaceId`,路径由宿主自己填 —— 与终端、Git
|
|
638
|
-
* 同一个口径,没有一条能让调用方指定任意路径的路。
|
|
639
|
-
*/
|
|
640
|
-
async function handleCreate(ctx, req, res) {
|
|
641
|
-
const body = await bodyJson(req);
|
|
642
|
-
if (closed) throw fail('UNSUPPORTED', '宿主正在关闭,稍后再试');
|
|
643
|
-
|
|
644
|
-
const workspaceId = text(body.workspaceId);
|
|
645
|
-
if (!workspaceId) throw fail('BAD_REQUEST', '需要 workspaceId');
|
|
646
|
-
|
|
647
|
-
const agent = (await listAgents()).find((item) => item && item.id === text(body.agent)) || null;
|
|
648
|
-
if (!agent) throw fail('BAD_REQUEST', '不认识这个 CLI');
|
|
649
|
-
const spec = resolveAgent(agent);
|
|
650
|
-
if (!spec.ok) throw fail('AGENT_UNAVAILABLE', spec.reason);
|
|
651
|
-
|
|
652
|
-
if (sessions.size >= MAX_SESSIONS) {
|
|
653
|
-
throw fail('TOO_MANY_SESSIONS', '同时开着的 CLI 太多了,先关掉几个');
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
const listed = await ctx.apiProxy.workspace.list({ rpcId: 'mobile', method: 'workspace.list', payload: {} });
|
|
657
|
-
const { value, error } = unwrap(listed);
|
|
658
|
-
if (error) throw fail('WORKSPACE_UNAVAILABLE', '取不到工作区清单,稍后再试');
|
|
659
|
-
const items = Array.isArray(value) ? value : (value && Array.isArray(value.items) ? value.items : []);
|
|
660
|
-
const item = items.find((entry) => entry && entry.workspaceId === workspaceId);
|
|
661
|
-
if (!item) throw fail('FORBIDDEN', '这个工作区不在这台机器上');
|
|
662
|
-
const cwd = text(item.path);
|
|
663
|
-
if (!cwd) throw fail('FORBIDDEN', '这个工作区没有对应目录');
|
|
664
|
-
|
|
665
|
-
seq += 1;
|
|
666
|
-
const id = `cli-${Date.now().toString(36)}-${seq.toString(36)}`;
|
|
667
|
-
const session = {
|
|
668
|
-
id,
|
|
669
|
-
workspaceId,
|
|
670
|
-
agentId: agent.id,
|
|
671
|
-
label: agent.label,
|
|
672
|
-
cwd,
|
|
673
|
-
title: agent.label,
|
|
674
|
-
status: 'starting',
|
|
675
|
-
createdAt: Date.now(),
|
|
676
|
-
updatedAt: Date.now(),
|
|
677
|
-
blocks: createBlockLog(),
|
|
678
|
-
configOptions: [],
|
|
679
|
-
modes: null,
|
|
680
|
-
commands: [],
|
|
681
|
-
sockets: new Set(),
|
|
682
|
-
dirty: new Map(),
|
|
683
|
-
timer: null,
|
|
684
|
-
handle: null,
|
|
685
|
-
finished: false,
|
|
686
|
-
closed: false,
|
|
687
|
-
permissions: new Map(),
|
|
688
|
-
permissionFrames: new Map(),
|
|
689
|
-
sinks: new Set(),
|
|
690
|
-
/** 用量账(上下文 / token / 耗时),见 `cli/usage.js`。 */
|
|
691
|
-
usage: createUsage(),
|
|
692
|
-
};
|
|
693
|
-
sessions.set(id, session);
|
|
694
|
-
// 新行要立刻出现在侧栏上:不然手机得等下一拍兜底轮询(推送活着时是 3 分钟)。
|
|
695
|
-
mobile.bumpList();
|
|
696
|
-
|
|
697
|
-
// 不 await:见文件头第 1 点。
|
|
698
|
-
void boot(session, spec);
|
|
699
|
-
|
|
700
|
-
sendJson(res, 200, { ok: true, session: detailOf(session) });
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
/** GET cli/sessions:宿主上还活着的会话(侧栏与页面重进都读它)。 */
|
|
704
|
-
function handleSessions(_ctx, _req, res) {
|
|
705
|
-
const list = [...sessions.values()].map((session) => {
|
|
706
|
-
const detail = detailOf(session);
|
|
707
|
-
delete detail.blocks;
|
|
708
|
-
return detail;
|
|
709
|
-
});
|
|
710
|
-
sendJson(res, 200, { ok: true, sessions: list });
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
/** 按 sessionId 取一条会话,取不到就 404。 */
|
|
714
|
-
function mustSession(id) {
|
|
715
|
-
const session = sessions.get(text(id));
|
|
716
|
-
if (!session) throw fail('NOT_FOUND', '这条会话已经不在了');
|
|
717
|
-
return session;
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
/**
|
|
721
|
-
* GET cli/session?sessionId=:一条会话的全貌(块、配置、命令、状态)。
|
|
722
|
-
*
|
|
723
|
-
* 页面靠它做兜底轮询:隧道上偶尔会出现「WS 握手成了、帧一个都没进来」的形状,只靠推送
|
|
724
|
-
* 的话界面就一直是空的、发出去的消息也看不到结果。
|
|
725
|
-
*/
|
|
726
|
-
function handleDetail(_ctx, req, res) {
|
|
727
|
-
const session = mustSession(query(req).get('sessionId'));
|
|
728
|
-
sendJson(res, 200, { ok: true, session: detailOf(session) });
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
/** POST cli/prompt { sessionId, text }:发一轮(WS 那条的 HTTP 版本)。 */
|
|
732
|
-
async function handlePrompt(_ctx, req, res) {
|
|
733
|
-
const body = await bodyJson(req);
|
|
734
|
-
const session = mustSession(body.sessionId);
|
|
735
|
-
const result = runPrompt(session, text(body.text));
|
|
736
|
-
if (!result.ok) throw fail('BAD_REQUEST', result.error);
|
|
737
|
-
sendJson(res, 200, { ok: true });
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
/** POST cli/permission { sessionId, id, optionId }:回答一条挂着的审批。 */
|
|
741
|
-
async function handlePermission(_ctx, req, res) {
|
|
742
|
-
const body = await bodyJson(req);
|
|
743
|
-
const session = mustSession(body.sessionId);
|
|
744
|
-
if (!answerPermission(session, text(body.id), text(body.optionId))) {
|
|
745
|
-
throw fail('NOT_FOUND', '这条审批已经不在了');
|
|
746
|
-
}
|
|
747
|
-
sendJson(res, 200, { ok: true });
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
/** POST cli/cancel { sessionId }:停掉这一轮(会话不杀)。 */
|
|
751
|
-
async function handleCancel(_ctx, req, res) {
|
|
752
|
-
const body = await bodyJson(req);
|
|
753
|
-
const session = mustSession(body.sessionId);
|
|
754
|
-
cancelTurn(session);
|
|
755
|
-
sendJson(res, 200, { ok: true });
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
/**
|
|
759
|
-
* POST cli/config { sessionId, configId?, value?, modeId? }
|
|
760
|
-
*
|
|
761
|
-
* 选模型 / 换思考档走 `configId + value`,换模式走 `modeId` —— 两者在 ACP 里是两条方法
|
|
762
|
-
* (`session/set_config_option` 与 `session/set_mode`),这里按传了哪个分派。
|
|
763
|
-
*/
|
|
764
|
-
async function handleConfig(_ctx, req, res) {
|
|
765
|
-
const body = await bodyJson(req);
|
|
766
|
-
const session = mustSession(body.sessionId);
|
|
767
|
-
if (!session.handle) throw fail('BAD_REQUEST', 'CLI 还没起来');
|
|
768
|
-
const modeId = text(body.modeId);
|
|
769
|
-
const configId = text(body.configId);
|
|
770
|
-
try {
|
|
771
|
-
if (modeId) await session.handle.setMode(modeId);
|
|
772
|
-
else if (configId) {
|
|
773
|
-
const updated = await session.handle.setConfigOption(configId, body.value);
|
|
774
|
-
if (updated && Array.isArray(updated.configOptions)) session.configOptions = updated.configOptions;
|
|
775
|
-
// 选过的模型要记住:下一次在这个 CLI 上开新会话时自动套上(见 applyPreferredModel)。
|
|
776
|
-
// 模型只记在 `model-prefs` 那本账里;其余每一项记进 `config-prefs.js` —— 那是「下次
|
|
777
|
-
// 开局自动套上」的唯一来源,两本账各记一份的话生效的那本必须是被写的那本。
|
|
778
|
-
const option = (session.configOptions || []).find((item) => item && item.id === configId);
|
|
779
|
-
if (option && option.category === 'model') rememberModel(session.agentId, configId, body.value);
|
|
780
|
-
else if (option) setValue(session.agentId, configId, text(body.value));
|
|
781
|
-
} else throw fail('BAD_REQUEST', '需要 configId 或 modeId');
|
|
782
|
-
} catch (error) {
|
|
783
|
-
if (error && error.code && STATUS_BY_CODE[error.code]) throw error;
|
|
784
|
-
throw fail('SPAWN_FAILED', error && error.message ? error.message : '改不了这一项');
|
|
785
|
-
}
|
|
786
|
-
sendJson(res, 200, { ok: true, session: detailOf(session) });
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
/**
|
|
790
|
-
* GET /cli/prefs?agent=:一个 CLI 的配置全貌(配置页读它)。
|
|
791
|
-
*
|
|
792
|
-
* 优先顺序:正开着的那条会话手上的表(最新)→ 记忆里那份(CLI 握过手就记下)→ **现去问一次**。
|
|
793
|
-
* 最后一档是必须的:选项表是 CLI 自己给的,一家从没在这台电脑上开过对话的 CLI(全新装的
|
|
794
|
-
* Gemini CLI 之类)记忆里一条都没有,配置页就成了一句「没有可调的项」—— 而「提前把权限配
|
|
795
|
-
* 好」正是最需要它的时候。问的那一次在后台跑(起一个适配器、拿到 `configOptions` 就关掉),
|
|
796
|
-
* 回来之前回 `pending`,App 按退避重问。
|
|
797
|
-
*
|
|
798
|
-
* `live` 说的是这份表是从跑着的会话读的;`pending` 说的是正在问。
|
|
799
|
-
*/
|
|
800
|
-
async function handlePrefs(ctx, req, res) {
|
|
801
|
-
const agentId = text(query(req).get('agent'));
|
|
802
|
-
if (!agentId) throw fail('BAD_REQUEST', '需要 agent');
|
|
803
|
-
const recorded = prefsOf(agentId);
|
|
804
|
-
// 正开着这个 CLI 的会话:拿它手上的选项表,比缓存新。
|
|
805
|
-
let options = recorded.options;
|
|
806
|
-
let live = false;
|
|
807
|
-
for (const session of sessions.values()) {
|
|
808
|
-
if (session.agentId !== agentId) continue;
|
|
809
|
-
if (session.status === 'starting') continue;
|
|
810
|
-
const described = describe(session.configOptions);
|
|
811
|
-
if (described.length === 0) continue;
|
|
812
|
-
options = described;
|
|
813
|
-
live = true;
|
|
814
|
-
break;
|
|
815
|
-
}
|
|
816
|
-
let pending = false;
|
|
817
|
-
let probeError = '';
|
|
818
|
-
// `force` 是配置页那行「重试」:探测失败之后,用户去装了 CLI / 登了录才回来,等
|
|
819
|
-
// `PROBE_RETRY_MS` 到点是不对的 —— 他这一下就是要现在再问一次。
|
|
820
|
-
const force = query(req).get('probe') === '1';
|
|
821
|
-
if (options.length === 0 && !live) {
|
|
822
|
-
const state = probeState(agentId);
|
|
823
|
-
if (state && state.running) pending = true;
|
|
824
|
-
else if (!state || force || (!state.done && (!state.error || Date.now() - state.at > PROBE_RETRY_MS))) {
|
|
825
|
-
startProbe(ctx, agentId);
|
|
826
|
-
pending = true;
|
|
827
|
-
} else if (!state.done && state.error) {
|
|
828
|
-
probeError = state.error;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
sendJson(res, 200, {
|
|
832
|
-
ok: true,
|
|
833
|
-
agent: agentId,
|
|
834
|
-
options,
|
|
835
|
-
values: valuesBodyOf(agentId, options),
|
|
836
|
-
live,
|
|
837
|
-
pending,
|
|
838
|
-
...(probeError ? { probeError } : {}),
|
|
839
|
-
});
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
/**
|
|
843
|
-
* 读写同一条 `/cli/prefs`(与过程播报那条同一个做法):GET 读,POST 写。
|
|
844
|
-
*/
|
|
845
|
-
async function handlePrefsRoute(ctx, req, res) {
|
|
846
|
-
if (req && String(req.method || 'GET').toUpperCase() === 'POST') return handleSetPref(ctx, req, res);
|
|
847
|
-
return handlePrefs(ctx, req, res);
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
/**
|
|
851
|
-
* POST /cli/prefs { agent, configId, value }:单独改一项默认配置。
|
|
852
|
-
*
|
|
853
|
-
* 与 `cli/config` 的区别:那条**改的是一条正在跑的会话**(顺带记下来),这条只改「以后新开的
|
|
854
|
-
* 那几条」。配置页在没有会话时用它,所以它也不启动任何进程。
|
|
855
|
-
*
|
|
856
|
-
* `value` 空 = 撤掉这一项,回到 CLI 自己的默认。
|
|
857
|
-
*
|
|
858
|
-
* **模型那一项记在 `model-prefs` 那本账上**:新会话开局是 `applyPreferredModel` 在读它,
|
|
859
|
-
* 记进 `config-prefs` 只会出现「配置页勾上了、开新对话却是别的」—— 两本账各记一份时,
|
|
860
|
-
* 生效的那本必须是被写的那本。
|
|
861
|
-
*/
|
|
862
|
-
async function handleSetPref(_ctx, req, res) {
|
|
863
|
-
const body = await bodyJson(req);
|
|
864
|
-
const agentId = text(body.agent);
|
|
865
|
-
const configId = text(body.configId);
|
|
866
|
-
if (!agentId || !configId) throw fail('BAD_REQUEST', '需要 agent 与 configId');
|
|
867
|
-
const value = text(body.value);
|
|
868
|
-
const options = prefsOf(agentId).options;
|
|
869
|
-
if (isModelOption(options, configId)) rememberModel(agentId, configId, value);
|
|
870
|
-
else setValue(agentId, configId, value);
|
|
871
|
-
sendJson(res, 200, { ok: true, agent: agentId, values: valuesBodyOf(agentId, options) });
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
/** POST cli/close { sessionId }:主动收掉一个会话(用户点「结束」)。 */
|
|
875
|
-
async function handleClose(_ctx, req, res) {
|
|
876
|
-
const body = await bodyJson(req);
|
|
877
|
-
const id = text(body.sessionId);
|
|
878
|
-
if (!id) throw fail('BAD_REQUEST', '需要 sessionId');
|
|
879
|
-
if (forget(id)) mobile.bumpList();
|
|
880
|
-
sendJson(res, 200, { ok: true });
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
/**
|
|
884
|
-
* WebSocket 升级:`?session=<id>`。
|
|
885
|
-
*
|
|
886
|
-
* 与终端那条同一套:凭据优先看**请求头**(连接建在 RN 侧,中转靠这些头决定转给哪台电脑),
|
|
887
|
-
* 头没有再把查询串 `cred`/`token` 折成一次普通鉴权判定。拒绝要发生在 `handleUpgrade`
|
|
888
|
-
* 之前 —— 那时 socket 还是普通 HTTP 连接。
|
|
889
|
-
*/
|
|
890
|
-
function handleUpgrade(req, socket, head) {
|
|
891
|
-
if (closed) return refuseUpgrade(socket, 503, 'Service Unavailable', 'CLI 服务已关闭');
|
|
892
|
-
|
|
893
|
-
const params = query(req);
|
|
894
|
-
const id = text(params.get('session'));
|
|
895
|
-
if (!id) return refuseUpgrade(socket, 400, 'Bad Request', '缺少 session 参数');
|
|
896
|
-
const token = text(params.get('cred')) || text(params.get('token'));
|
|
897
|
-
|
|
898
|
-
let allowed = false;
|
|
899
|
-
try {
|
|
900
|
-
allowed = Boolean(authorized && (authorized(req) || (token && authorized({
|
|
901
|
-
headers: { 'x-dsh-device-credential': token, authorization: `Bearer ${token}` },
|
|
902
|
-
}))));
|
|
903
|
-
} catch {
|
|
904
|
-
allowed = false;
|
|
905
|
-
}
|
|
906
|
-
if (!allowed) {
|
|
907
|
-
log(`cli ${id}: 凭据无效,拒绝升级`);
|
|
908
|
-
return refuseUpgrade(socket, 401, 'Unauthorized', '移动端凭据无效');
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
const session = sessions.get(id);
|
|
912
|
-
if (!session) {
|
|
913
|
-
log(`cli ${id}: 会话不在表里,拒绝升级`);
|
|
914
|
-
return refuseUpgrade(socket, 404, 'Not Found', '这条会话已经不在了');
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
wss.handleUpgrade(req, socket, head, (ws) => attach(ws, session));
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
function attach(ws, session) {
|
|
921
|
-
session.sockets.add(ws);
|
|
922
|
-
log(`cli ${session.id}: 手机接上了(第 ${session.sockets.size} 条连接)`);
|
|
923
|
-
|
|
924
|
-
// 先补全貌:页面重进 / 断线重连回来看到的仍是原来那一屏。
|
|
925
|
-
send(ws, { t: 'hello', session: detailOf(session) });
|
|
926
|
-
// 挂着的审批错过一次就再也点不到了,接上时重发一遍。
|
|
927
|
-
for (const request of session.permissionFrames.values()) send(ws, { t: 'permission', request });
|
|
928
|
-
if (session.finished) send(ws, { t: 'exit', reason: 'CLI 已经退出' });
|
|
929
|
-
|
|
930
|
-
ws.on('message', (raw) => {
|
|
931
|
-
let frame = null;
|
|
932
|
-
try { frame = JSON.parse(String(raw)); } catch { return; }
|
|
933
|
-
if (!frame || typeof frame !== 'object') return;
|
|
934
|
-
if (frame.t === 'prompt') { runPrompt(session, text(frame.text)); return; }
|
|
935
|
-
if (frame.t === 'permission') { answerPermission(session, text(frame.id), text(frame.optionId)); return; }
|
|
936
|
-
if (frame.t === 'cancel') { cancelTurn(session); }
|
|
937
|
-
});
|
|
938
|
-
|
|
939
|
-
ws.on('close', () => {
|
|
940
|
-
session.sockets.delete(ws);
|
|
941
|
-
log(`cli ${session.id}: 手机断开了(剩 ${session.sockets.size} 条连接)`);
|
|
942
|
-
});
|
|
943
|
-
ws.on('error', () => { session.sockets.delete(ws); });
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
function close() {
|
|
947
|
-
closed = true;
|
|
948
|
-
for (const id of [...sessions.keys()]) forget(id);
|
|
949
|
-
try { wss.close(); } catch { /* 已经关了 */ }
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
/** 路由包装:把领域错误翻成 HTTP 状态,与终端那一份同口径。 */
|
|
953
|
-
function wrap(handler) {
|
|
954
|
-
return async (ctx, req, res) => {
|
|
955
|
-
try {
|
|
956
|
-
await handler(ctx, req, res);
|
|
957
|
-
} catch (error) {
|
|
958
|
-
const code = error && typeof error.code === 'string' && STATUS_BY_CODE[error.code]
|
|
959
|
-
? error.code
|
|
960
|
-
: 'SPAWN_FAILED';
|
|
961
|
-
const status = STATUS_BY_CODE[code] || 500;
|
|
962
|
-
const message = error && typeof error.message === 'string' && error.message
|
|
963
|
-
? error.message
|
|
964
|
-
: 'CLI 操作失败';
|
|
965
|
-
log(`cli: ${code} ${message}`);
|
|
966
|
-
sendJson(res, status, { ok: false, error: { code, message } });
|
|
967
|
-
}
|
|
968
|
-
};
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
/**
|
|
972
|
-
* 让 `cli-*` 会话走宿主普通会话那一整套移动端接口的适配层(见 `cli/mobile.js`)。
|
|
973
|
-
*
|
|
974
|
-
* 构造在这里而不是装配层:它要读的会话表、发一轮、答审批、改标题全在这个闭包里。装配层
|
|
975
|
-
* 只负责把端点接上(`mobile-api.js` 按 sessionId 前缀分派)。
|
|
976
|
-
*/
|
|
977
|
-
const mobile = createCliMobile({
|
|
978
|
-
sessions,
|
|
979
|
-
runPrompt,
|
|
980
|
-
answerPermission,
|
|
981
|
-
cancelTurn,
|
|
982
|
-
setTitle,
|
|
983
|
-
watch,
|
|
984
|
-
// 「清空已归档」要把 CLI 这边的归档会话当场收掉(没有磁盘日志可清)。
|
|
985
|
-
forget,
|
|
986
|
-
});
|
|
987
|
-
|
|
988
|
-
return {
|
|
989
|
-
mobile,
|
|
990
|
-
handleAgents: wrap(handleAgents),
|
|
991
|
-
handleCreate: wrap(handleCreate),
|
|
992
|
-
handleSessions: wrap(handleSessions),
|
|
993
|
-
handleDetail: wrap(handleDetail),
|
|
994
|
-
handlePrompt: wrap(handlePrompt),
|
|
995
|
-
handlePermission: wrap(handlePermission),
|
|
996
|
-
handleCancel: wrap(handleCancel),
|
|
997
|
-
handleConfig: wrap(handleConfig),
|
|
998
|
-
handlePrefs: wrap(handlePrefsRoute),
|
|
999
|
-
handleClose: wrap(handleClose),
|
|
1000
|
-
handleUpgrade,
|
|
1001
|
-
close,
|
|
1002
|
-
};
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
/** 拒绝升级:这时 socket 还是一条普通 HTTP 连接,老实回一个状态码就行。 */
|
|
1006
|
-
function refuseUpgrade(socket, status, reason, text_) {
|
|
1007
|
-
if (!socket || socket.destroyed) return;
|
|
1008
|
-
const body = Buffer.from(text_, 'utf8');
|
|
1009
|
-
socket.write(
|
|
1010
|
-
`HTTP/1.1 ${status} ${reason}\r\n`
|
|
1011
|
-
+ 'Connection: close\r\n'
|
|
1012
|
-
+ 'Content-Type: text/plain; charset=utf-8\r\n'
|
|
1013
|
-
+ `Content-Length: ${body.length}\r\n\r\n`,
|
|
1014
|
-
);
|
|
1015
|
-
socket.write(body);
|
|
1016
|
-
socket.end();
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
/**
|
|
1020
|
-
* 装配层只调这一个(`impl.js` 有行数上限,装配代码不许长回来):建服务 + 挂清理。
|
|
1021
|
-
*
|
|
1022
|
-
* 清理必须挂 `ctx.effect`:插件热替换之后旧实例没人能关,适配器子进程会一直挂到宿主退出。
|
|
1023
|
-
*/
|
|
1024
|
-
function mountCli(ctx, { authorized, name } = {}) {
|
|
1025
|
-
const service = createCliService({
|
|
1026
|
-
authorized,
|
|
1027
|
-
onLog: (message) => ctx.logger?.info?.(`${name}: %s`, message),
|
|
1028
|
-
});
|
|
1029
|
-
ctx.effect(() => () => service.close(), `${name}: cli sessions`);
|
|
1030
|
-
return service;
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
module.exports = {
|
|
1034
|
-
mountCli,
|
|
1035
|
-
createCliService,
|
|
1036
|
-
pendingPrefsOf,
|
|
1037
|
-
// 配置页要画的那张表与「哪一项是模型」的判据:两条都在这里,测试直接钉这两份真函数
|
|
1038
|
-
// (照抄一份等价实现的话,实现写错测试照样绿)。
|
|
1039
|
-
isModelOption,
|
|
1040
|
-
valuesBodyOf,
|
|
1041
|
-
MAX_SESSIONS,
|
|
1042
|
-
};
|