@dsh-mobile/mobile-remote 3.4.1-beta.2 → 3.5.0-beta.1

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.
@@ -0,0 +1,405 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+ import { scopeTarget } from "@deepseek-ai/dsh-scope";
9
+ import { requestAbort } from "../api-helpers.js";
10
+ import { firstRootAgent, jobsCallerFor } from "../host-compat.js";
11
+ import { requireGet, requirePost, sendJson } from "../http-util.js";
12
+ import { isEndpointUnavailable, rpcError } from "../rpc-adapter.js";
13
+ import { NOT_HANDLED } from "./route-groups.js";
14
+
15
+ export async function handleAgentsRoutes(deps, req, res, url, rest, method, miss) {
16
+ const {
17
+ actionEntries, apiRpc, bodyError, ctx, error, failureDetail, jobViews, listPersistedSubagents,
18
+ localDesktopGate, readJson, resolveSessionTitles, resumeDormantAgent, sessionTitleOf, shortSessionId,
19
+ todosView,
20
+ } = deps;
21
+ const actionMatch = /^\/actions\/([^/]+)\/invoke$/.exec(rest); if (actionMatch && method === "POST") {
22
+ let id;
23
+ try {
24
+
25
+ id = decodeURIComponent(actionMatch[1]);
26
+ } catch (err) {
27
+ return bodyError(err, res);
28
+ }
29
+ const entry = actionEntries.get(id);
30
+ if (!entry) return error(res, 404, "action-not-found");
31
+ const body = await readJson(req, res);
32
+ if (body === undefined) return;
33
+ try {
34
+ await entry.handler(body?.args ?? {});
35
+ } catch (err) {
36
+ ctx.logger.warn(`mobile-remote: /actions/${id} 执行失败:${err?.message ?? err}`);
37
+ return error(res, 500, "action-failed", failureDetail(err));
38
+ }
39
+ sendJson(res, 200, { ok: true, accepted: true });
40
+ return;
41
+ }
42
+
43
+
44
+ if (rest === "/jobs") {
45
+ if (requireGet(method, res)) return;
46
+ const jobs = ctx.get("jobs");
47
+ if (!jobs) return error(res, 503, "jobs-unavailable");
48
+ const sessionId = url.searchParams.get("sessionId");
49
+ const agents = ctx.get("agents");
50
+ const agent = sessionId && agents ? agents.get(sessionId) : undefined;
51
+ if (sessionId && !agent) return error(res, 404, "session-not-found");
52
+ const views = jobViews(jobs.list(jobsCallerFor(jobs, agent, sessionId ?? undefined)));
53
+ sendJson(res, 200, { ok: true, sessionId: sessionId ?? null, jobs: views });
54
+ return;
55
+ }
56
+
57
+ if (rest === "/todos") {
58
+ if (requireGet(method, res)) return;
59
+ const sessionId = url.searchParams.get("sessionId");
60
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
61
+ const agents = ctx.get("agents");
62
+ const session = agents?.get?.(sessionId)?.session;
63
+
64
+ const todos = session ? todosView(session) : null;
65
+ sendJson(res, 200, { ok: true, sessionId, todos });
66
+ return;
67
+ }
68
+ if (rest === "/jobs/kill") {
69
+ if (requirePost(method, res)) return;
70
+ const body = await readJson(req, res);
71
+ if (body === undefined) return;
72
+ const jobs = ctx.get("jobs");
73
+ if (!jobs) return error(res, 503, "jobs-unavailable");
74
+ const jobId = typeof body.jobId === "string" ? body.jobId : "";
75
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
76
+ if (!jobId) return error(res, 400, "jobId-required");
77
+ const agents = ctx.get("agents");
78
+ const agent = sessionId && agents ? agents.get(sessionId) : undefined;
79
+ try {
80
+ await jobs.kill(jobId, jobsCallerFor(jobs, agent, sessionId), "mobile-remote: user cancelled");
81
+ sendJson(res, 200, { ok: true });
82
+ } catch (err) {
83
+ return error(res, 400, "job-kill-failed", err?.message ?? String(err));
84
+ }
85
+ return;
86
+ }
87
+ if (rest === "/subagents") {
88
+ if (requireGet(method, res)) return;
89
+ const parentSessionId = url.searchParams.get("parentSessionId");
90
+ if (!parentSessionId) return error(res, 400, "parentSessionId-required");
91
+ const agents = ctx.get("agents");
92
+ const sessions = ctx.get("sessions");
93
+ const subagentsSvc = ctx.get("subagents");
94
+ const agent = agents?.get(parentSessionId);
95
+
96
+ const signal = requestAbort(res);
97
+ const parent = sessions?.get?.(parentSessionId);
98
+ const hasCatalog = typeof subagentsSvc?.listChildren === "function";
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+ let catalogRows = null;
114
+ let catalogDegraded = false;
115
+ if (hasCatalog) {
116
+ try {
117
+ const rows = await subagentsSvc.listChildren(parentSessionId);
118
+ if (Array.isArray(rows)) catalogRows = rows;
119
+ } catch {
120
+ catalogRows = null;
121
+ }
122
+ }
123
+ if (catalogRows === null) {
124
+ const persisted = await listPersistedSubagents(parentSessionId, signal);
125
+
126
+
127
+ if (signal.aborted) return;
128
+ if (persisted?.timedOut) return error(res, 504, "subagents-timeout");
129
+ if (persisted === null) {
130
+
131
+ } else if (!persisted.parentExists) {
132
+ return error(res, 404, "session-not-found");
133
+ } else {
134
+
135
+
136
+ catalogRows = persisted.entries.map((entry) => ({
137
+ id: entry.id,
138
+ title: entry.title,
139
+ createdAt: entry.createdAt,
140
+ }));
141
+ catalogDegraded = true;
142
+ }
143
+ }
144
+ if (catalogRows === null && (agent || parent)) {
145
+ catalogRows = (sessions?.list?.() ?? [])
146
+ .map((session) => ({ session, header: session?.header ?? {} }))
147
+ .filter(({ header }) => header.origin === "subagent" && header.parentSession === parentSessionId)
148
+ .map(({ session, header }) => ({ id: session?.id ?? header.id, createdAt: header.createdAt }));
149
+ catalogDegraded = true;
150
+ }
151
+ if (catalogRows === null) return error(res, 404, "session-not-found");
152
+
153
+ const rows = catalogRows.map((row) => {
154
+ const id = typeof row?.id === "string" && row.id !== "" ? row.id : "";
155
+ const live = agents?.get?.(id);
156
+ const session = sessions?.get?.(id);
157
+ const createdAt = typeof row?.createdAt === "number"
158
+ ? row.createdAt
159
+ : (typeof session?.header?.createdAt === "number" ? session.header.createdAt : undefined);
160
+
161
+
162
+
163
+
164
+ const label = typeof row?.label === "string" && row.label !== "" ? row.label : undefined;
165
+ const rowTitle = typeof row?.title === "string" && row.title !== "" ? row.title : undefined;
166
+ const liveTitle = sessionTitleOf(session);
167
+ return { id, live, createdAt, label, rowTitle, liveTitle, mode: row?.mode };
168
+ }).filter((row) => row.id !== "");
169
+
170
+
171
+
172
+
173
+ const needPersistedTitle = rows.filter((row) => !row.label && !row.rowTitle && !row.liveTitle).map((row) => row.id);
174
+ const persistedTitleMap = needPersistedTitle.length > 0
175
+ ? await resolveSessionTitles(needPersistedTitle, signal)
176
+ : new Map();
177
+ if (signal.aborted) return;
178
+ const entries = rows
179
+ .map((row) => ({
180
+ id: row.id,
181
+
182
+
183
+
184
+
185
+ kind: row.mode === "unknown" ? "diagnostic" : "child",
186
+
187
+ status: row.mode === "unknown"
188
+ ? "unsupported"
189
+ : (typeof row.live?.status === "string" && row.live.status !== ""
190
+ ? (row.live.status === "running" ? "running" : "inactive")
191
+ : "inactive"),
192
+ title: row.label ?? row.rowTitle ?? row.liveTitle ?? persistedTitleMap.get(row.id) ?? shortSessionId(row.id),
193
+ ...(row.createdAt === undefined ? {} : { createdAt: row.createdAt }),
194
+ }))
195
+ .sort((a, b) => {
196
+ const ta = typeof a.createdAt === "number" ? a.createdAt : Number.NEGATIVE_INFINITY;
197
+ const tb = typeof b.createdAt === "number" ? b.createdAt : Number.NEGATIVE_INFINITY;
198
+ if (ta !== tb) return tb - ta;
199
+ return String(a.id).localeCompare(String(b.id));
200
+ });
201
+ sendJson(res, 200, {
202
+ ok: true,
203
+ parentAvailable: !!agent,
204
+
205
+ ...(catalogDegraded ? { catalogDegraded: true } : {}),
206
+ subagents: entries,
207
+ });
208
+ return;
209
+ }
210
+ if (rest === "/subagents/interrupt") {
211
+ if (requirePost(method, res)) return;
212
+ const body = await readJson(req, res);
213
+ if (body === undefined) return;
214
+ const parentSessionId = typeof body.parentSessionId === "string" ? body.parentSessionId : "";
215
+ const childSessionId = typeof body.childSessionId === "string" ? body.childSessionId : "";
216
+ if (!parentSessionId || !childSessionId) return error(res, 400, "parentSessionId-and-childSessionId-required");
217
+ try {
218
+
219
+
220
+ try {
221
+ await apiRpc("subagent.interrupt", { parentSessionId, childSessionId, mode: "continuable" });
222
+ } catch (err) {
223
+ if (!isEndpointUnavailable(err)) throw err;
224
+ await apiRpc("subagent.interruptByParent", { parentSessionId, childSessionId, mode: "continuable" });
225
+ }
226
+ sendJson(res, 200, { ok: true });
227
+ } catch (err) {
228
+ return error(res, ...rpcError(err, "subagent-interrupt-failed"));
229
+ }
230
+ return;
231
+ }
232
+ if (rest === "/commands") {
233
+
234
+
235
+
236
+ const agents = ctx.get("agents");
237
+ const commands = ctx.get("commands");
238
+ if (method === "GET" || method === "HEAD") {
239
+ const sessionId = url.searchParams.get("sessionId");
240
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
241
+ let agent = agents ? agents.get(sessionId) : undefined;
242
+ if (!commands) {
243
+
244
+
245
+ sendJson(res, 200, { ok: true, commands: [], unavailable: true });
246
+ return;
247
+ }
248
+
249
+
250
+ if (!agent) agent = (await resumeDormantAgent(sessionId))?.agent;
251
+
252
+ if (!agent) return error(res, 404, "session-not-found", `session not found: ${sessionId}`);
253
+ try {
254
+ const list = commands.list(agent);
255
+ sendJson(res, 200, {
256
+ ok: true,
257
+ commands: (list ?? []).map((c) => ({
258
+ name: c.name,
259
+ description: c.description,
260
+ ...(c.input ? { input: c.input } : {}),
261
+ })),
262
+ });
263
+ } catch (err) {
264
+ return error(res, 400, "commands-list-failed", err?.message ?? String(err));
265
+ }
266
+ return;
267
+ }
268
+ if (method === "POST") {
269
+ const body = await readJson(req, res);
270
+ if (body === undefined) return;
271
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
272
+ const line = typeof body.line === "string" ? body.line : "";
273
+ if (!sessionId) return error(res, 400, "missing-sessionId");
274
+ if (!line || !line.startsWith("/")) return error(res, 400, "bad-request", "line must start with /");
275
+ let agent = sessionId && agents ? agents.get(sessionId) : undefined;
276
+ if (!commands) return error(res, 503, "commands-unavailable", "commands service not available in this DSH");
277
+
278
+ if (!agent) agent = (await resumeDormantAgent(sessionId))?.agent;
279
+
280
+ if (!agent) return error(res, 404, "session-not-found", `session not found: ${sessionId}`);
281
+ try {
282
+
283
+
284
+
285
+
286
+
287
+ const result = await commands.execute(agent, line, [], AbortSignal.timeout(180000));
288
+
289
+
290
+ if (result === undefined) {
291
+ return error(res, 404, "command-not-found", `unknown or malformed command: ${line}`);
292
+ }
293
+ sendJson(res, 200, { ok: true, result });
294
+ } catch (err) {
295
+ return error(res, ...rpcError(err, "commands-execute-failed"));
296
+ }
297
+ return;
298
+ }
299
+ return error(res, 405, "method-not-allowed");
300
+ }
301
+ if (rest === "/goal") {
302
+ const agents = ctx.get("agents");
303
+ if (method === "GET" || method === "HEAD") {
304
+ const sessionId = url.searchParams.get("sessionId");
305
+
306
+ if (!sessionId) return error(res, 400, "bad-request", "missing sessionId");
307
+ const agent = agents ? agents.get(sessionId) : undefined;
308
+ const goals = ctx.get("goals");
309
+ if (!goals || !agent) return error(res, 503, "goal-unavailable");
310
+ try {
311
+ const current = await goals.get(agent);
312
+ sendJson(res, 200, { ok: true, goal: current ?? null });
313
+ } catch (err) {
314
+ return error(res, 400, "goal-get-failed", err?.message ?? String(err));
315
+ }
316
+ return;
317
+ }
318
+ if (method === "POST") {
319
+ const body = await readJson(req, res);
320
+ if (body === undefined) return;
321
+ const action = typeof body.action === "string" ? body.action : "";
322
+ const goals = ctx.get("goals");
323
+ const sessionId = typeof body.sessionId === "string" ? body.sessionId : "";
324
+ const agent = sessionId && agents ? agents.get(sessionId) : undefined;
325
+ if (!sessionId || !agent) return error(res, 400, "sessionId-required");
326
+ if (!goals) return error(res, 503, "goal-unavailable");
327
+ try {
328
+
329
+ const current = await goals.get(agent);
330
+ switch (action) {
331
+ case "create": {
332
+ const objective = typeof body.objective === "string" ? body.objective : "";
333
+ if (!objective) return error(res, 400, "objective-required");
334
+
335
+ const rounds = body.maxGoalRounds;
336
+ if (rounds !== undefined && (!Number.isInteger(rounds) || rounds < 1 || rounds > 10000)) {
337
+ return error(res, 400, "maxGoalRounds-invalid", "maxGoalRounds must be an integer 1-10000");
338
+ }
339
+ await apiRpc("goal.create", {
340
+ sessionId,
341
+ objective,
342
+ ...(rounds === undefined ? {} : { maxGoalRounds: rounds }),
343
+ });
344
+ break;
345
+ }
346
+ case "pause":
347
+ case "resume":
348
+ case "complete": {
349
+ if (!current) return error(res, 400, "no-active-goal");
350
+ await apiRpc(`goal.${action}`, {
351
+ sessionId,
352
+ ref: { id: current.id, revision: current.revision },
353
+ });
354
+ break;
355
+ }
356
+ default:
357
+ return error(res, 400, "bad-action");
358
+ }
359
+ sendJson(res, 200, { ok: true });
360
+ } catch (err) {
361
+ return error(res, ...rpcError(err, "goal-failed"));
362
+ }
363
+ return;
364
+ }
365
+ return error(res, 405, "method-not-allowed");
366
+ }
367
+
368
+
369
+
370
+
371
+
372
+ if (rest === "/dev/approval-test") {
373
+ if (requirePost(method, res)) return;
374
+
375
+
376
+
377
+
378
+
379
+ const gate = localDesktopGate(req, { relayGuard: false });
380
+ if (!gate.ok) return error(res, 403, gate.code, gate.detail);
381
+ const body = await readJson(req, res);
382
+ if (body === undefined) return;
383
+ const agents = ctx.get("agents");
384
+ if (!agents) return error(res, 503, "agents-unavailable");
385
+ const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
386
+ const agent = (sessionId ? agents.get(sessionId) : undefined) ?? firstRootAgent(agents);
387
+ if (!agent) return error(res, 404, "no-live-agent");
388
+ const synthetic = {
389
+ agent,
390
+ toolName: "write",
391
+ callId: `dev-${Date.now().toString(36)}`,
392
+ reason: "合成测试:验证手机审批卡链路(等待手机批准/拒绝)",
393
+ };
394
+ const outcome = await ctx.waterfall(
395
+ scopeTarget(agent, agent),
396
+ "approval/request",
397
+ synthetic,
398
+ () => Promise.resolve("unavailable"),
399
+ );
400
+ sendJson(res, 200, { ok: true, synthetic: true, outcome });
401
+ return;
402
+ }
403
+ miss.now = true;
404
+ return NOT_HANDLED;
405
+ }
@@ -0,0 +1,178 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+ import { FILE_RANGE_CAPABILITIES } from "../api-helpers.js";
9
+ import { readBody, requireGet, requirePost, sendError, sendJson } from "../http-util.js";
10
+ import { protocolInfo } from "../protocol.js";
11
+ import { EVENT_TIMELINE_CAPABILITIES } from "../timeline.js";
12
+ import { turnOutlineCapabilityOf } from "../turn-outline.js";
13
+ import { NOT_HANDLED } from "./route-groups.js";
14
+
15
+ export async function handleAppStateRoutes(deps, req, res, url, rest, method, miss) {
16
+ const {
17
+ agentSessionId, assistantPrefs, authEnabled, basePath, config, ctx, error, handleMemory, handlePersona,
18
+ handleReminders, ipv4Addresses, lanNoiseUrls, lanPort, liveActivity, noteUserActivity, phoneActions, pluginVersion,
19
+ privateFirst, proactive, proactiveIdleMs, readJson, sessionTitleOf, shortSessionId,
20
+ } = deps;
21
+ if (rest === "/bootstrap") {
22
+ if (requireGet(method, res)) return;
23
+ const agents = ctx.get("agents");
24
+ const sessions = ctx.get("sessions");
25
+
26
+ const agentList = agents
27
+ ? agents.list().map((agent) => {
28
+
29
+
30
+
31
+ const sid = agentSessionId(agent);
32
+ const s = sessions?.get(sid);
33
+ return {
34
+ id: agent.id,
35
+ sessionId: sid,
36
+ status: agent.status,
37
+ hasPending: agent.inbox?.hasPending ?? false,
38
+ title: sessionTitleOf(s) ?? shortSessionId(sid),
39
+ };
40
+ })
41
+ : [];
42
+ const sessionList = sessions
43
+ ? sessions.list().map((session) => ({ id: session.id, createdAt: session.header.createdAt, cwd: session.header.cwd, title: sessionTitleOf(session) ?? shortSessionId(session.id) }))
44
+ : [];
45
+
46
+
47
+ const urls = deps.lanBridgeListening
48
+ ? [...privateFirst(ipv4Addresses()).map((ip) => `http://${ip}:${lanPort}`), `http://127.0.0.1:${ctx.webServer.port}`]
49
+ : [...privateFirst(ipv4Addresses()), "127.0.0.1"].map((ip) => `http://${ip}:${ctx.webServer.port}`);
50
+ sendJson(res, 200, {
51
+ ok: true,
52
+ auth: { enabled: authEnabled },
53
+ server: { port: ctx.webServer.port, urls, path: basePath },
54
+ plugin: { name: "dsh-mobile-remote", version: pluginVersion() },
55
+
56
+ ...protocolInfo(phoneActions.features()),
57
+ capabilities: {
58
+ eventTimeline: EVENT_TIMELINE_CAPABILITIES,
59
+
60
+
61
+ turnOutline: turnOutlineCapabilityOf(ctx),
62
+
63
+ fileRange: FILE_RANGE_CAPABILITIES,
64
+
65
+
66
+ ...(lanNoiseUrls().length > 0 ? { lanNoise: { version: 1, urls: lanNoiseUrls() } } : {}),
67
+
68
+ hold: {
69
+ version: 1,
70
+ onlineMs: Math.max(0, Number(config.pendingTimeoutMs ?? 120_000) || 0),
71
+ offlineMs: Math.max(0, Number(config.offlineHoldMs ?? 300_000) || 0),
72
+ },
73
+ },
74
+ agents: agentList,
75
+ sessions: sessionList,
76
+ });
77
+ return;
78
+ }
79
+
80
+ if (rest === "/phone-action-result" && await phoneActions.handle(req, res, method)) return;
81
+ if (rest === "/live-activity/token" && await liveActivity.handle(req, res, method)) return;
82
+
83
+ if (rest === "/persona" || rest.startsWith("/persona/")) {
84
+ if (await handlePersona(req, res, rest, method)) return;
85
+ }
86
+
87
+
88
+
89
+
90
+
91
+
92
+ if (rest === "/presence") {
93
+ if (requirePost(method, res)) return;
94
+ const body = await readJson(req, res);
95
+ if (body === undefined) return;
96
+ if (body?.state === "background") {
97
+
98
+ deps.presenceState = "background";
99
+ sendJson(res, 200, { ok: true });
100
+ return;
101
+ }
102
+ if (body?.state !== "foreground") return error(res, 400, "bad-request", "state must be \"foreground\" or \"background\"");
103
+ const wasBackground = deps.presenceState === "background";
104
+ deps.presenceState = "foreground";
105
+ const t = Date.now();
106
+ const idleMs = proactiveIdleMs();
107
+ const awayMs = Number.isFinite(body.awayMs) && body.awayMs >= 0 ? body.awayMs : null;
108
+ const wasAway = (awayMs === null || awayMs >= idleMs) && t - deps.lastTypedAt >= idleMs;
109
+ if (wasAway) {
110
+ deps.returned = { at: t, since: Math.max(deps.lastTypedAt, awayMs === null ? 0 : t - awayMs, deps.newsCursor) };
111
+ if (config.proactive?.enabled) setImmediate(() => void proactive.tick());
112
+ } else if (wasBackground && config.proactive?.enabled) {
113
+ setImmediate(() => void proactive.tick());
114
+ }
115
+ noteUserActivity();
116
+ sendJson(res, 200, { ok: true, returned: wasAway });
117
+ return;
118
+ }
119
+
120
+
121
+ if (rest === "/reminders" || rest.startsWith("/reminders/")) {
122
+ if (await handleReminders(req, res, rest, method)) return;
123
+ }
124
+
125
+
126
+ if (rest === "/memory" || rest.startsWith("/memory/")) {
127
+ await handleMemory(req, res, url, rest, method);
128
+ return;
129
+ }
130
+
131
+
132
+
133
+
134
+
135
+
136
+ if (rest === "/assistant") {
137
+ if (method === "GET") {
138
+ sendJson(res, 200, { ok: true, ...assistantPrefs.get() });
139
+ return;
140
+ }
141
+ if (method === "PATCH" || method === "POST") {
142
+ let body;
143
+ try {
144
+
145
+
146
+ body = JSON.parse(await readBody(req));
147
+ } catch {
148
+ return error(res, 400, "bad-request", "请求体不是合法 JSON");
149
+ }
150
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
151
+ return error(res, 400, "bad-request", "请求体必须是对象");
152
+ }
153
+ try {
154
+ const { changed, ...next } = assistantPrefs.set({
155
+ mode: body.mode,
156
+ persona: body.persona,
157
+
158
+
159
+ quietHours: body.quietHours,
160
+
161
+ breakReminder: body.breakReminder,
162
+
163
+ personaCard: body.personaCard,
164
+ });
165
+ if (changed) noteUserActivity();
166
+ sendJson(res, 200, { ok: true, ...next });
167
+ } catch (err) {
168
+
169
+ error(res, 400, "bad-request", err?.message ?? "invalid value");
170
+ }
171
+ return;
172
+ }
173
+ sendError(res, 405, "method-not-allowed");
174
+ return;
175
+ }
176
+ miss.now = true;
177
+ return NOT_HANDLED;
178
+ }