@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.
- package/README.md +1 -1
- package/docs/PRIVACY-POLICY.en.md +7 -2
- package/docs/PRIVACY-POLICY.md +7 -2
- package/docs/TERMS-OF-SERVICE.en.md +3 -2
- package/docs/TERMS-OF-SERVICE.md +3 -2
- package/lib/backup.js +30 -0
- package/lib/config.js +10 -0
- package/lib/host-plugins.js +290 -0
- package/lib/host-schedule.js +206 -0
- package/lib/host-team.js +89 -0
- package/lib/index.js +196 -3281
- package/lib/live-activity.js +351 -0
- package/lib/memory/context.js +17 -3
- package/lib/memory/decay.js +68 -4
- package/lib/memory/promises.js +116 -0
- package/lib/memory/routes.js +113 -1
- package/lib/memory/store.js +212 -13
- package/lib/memory/turn-hook.js +109 -0
- package/lib/phone-announce.js +6 -5
- package/lib/protocol.js +13 -0
- package/lib/routes/agents.js +405 -0
- package/lib/routes/app-state.js +178 -0
- package/lib/routes/backup.js +144 -0
- package/lib/routes/diagnostics.js +227 -0
- package/lib/routes/files.js +326 -0
- package/lib/routes/git.js +53 -0
- package/lib/routes/history.js +313 -0
- package/lib/routes/host-services.js +51 -0
- package/lib/routes/models.js +462 -0
- package/lib/routes/notifications.js +183 -0
- package/lib/routes/pairing.js +170 -0
- package/lib/routes/route-groups.js +20 -0
- package/lib/routes/send.js +341 -0
- package/lib/routes/sessions.js +462 -0
- package/lib/routes/toolbox.js +14 -0
- package/lib/routes/usage.js +211 -0
- package/lib/timeline.js +5 -1
- package/lib/toolbox.js +355 -0
- package/package.json +1 -1
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import { MAX_RESTORE_BODY_BYTES, applyRestore, buildBackup, decryptBackup, encryptBackup, isEncryptedBackup, passphraseProblem, planRestore } from "../backup.js";
|
|
9
|
+
import { readBody, sendError, sendJson } from "../http-util.js";
|
|
10
|
+
import { NOT_HANDLED } from "./route-groups.js";
|
|
11
|
+
|
|
12
|
+
export async function handleBackupRoutes(deps, req, res, url, rest, method, miss) {
|
|
13
|
+
const {
|
|
14
|
+
assistantPrefs, error, getMemoryStore, readJson,
|
|
15
|
+
} = deps;
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
if (rest === "/backup") {
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
let passphrase;
|
|
27
|
+
if (method === "POST") {
|
|
28
|
+
const body = await readJson(req, res);
|
|
29
|
+
if (body === undefined) return;
|
|
30
|
+
passphrase = body?.passphrase;
|
|
31
|
+
const problem = passphraseProblem(passphrase);
|
|
32
|
+
if (problem) return error(res, 400, "weak-passphrase", problem);
|
|
33
|
+
} else if (method !== "GET" && method !== "HEAD") {
|
|
34
|
+
sendError(res, 405, "method-not-allowed");
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
let store = null;
|
|
41
|
+
try {
|
|
42
|
+
store = getMemoryStore();
|
|
43
|
+
} catch (err) {
|
|
44
|
+
return error(
|
|
45
|
+
res,
|
|
46
|
+
503,
|
|
47
|
+
"memory-unavailable",
|
|
48
|
+
`记忆库打不开,无法生成完整备份:${err?.message ?? err}`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const backup = buildBackup({
|
|
52
|
+
|
|
53
|
+
store,
|
|
54
|
+
prefs: assistantPrefs,
|
|
55
|
+
});
|
|
56
|
+
sendJson(res, 200, passphrase === undefined ? backup : await encryptBackup(backup, passphrase));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (rest === "/backup/restore") {
|
|
60
|
+
if (method !== "POST") {
|
|
61
|
+
sendError(res, 405, "method-not-allowed");
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
const tooLarge = () =>
|
|
71
|
+
sendJson(
|
|
72
|
+
res,
|
|
73
|
+
413,
|
|
74
|
+
{ error: "payload-too-large", detail: "备份文件超过 32 MiB 上限 / the backup is larger than the 32 MiB limit" },
|
|
75
|
+
{ connection: "keep-alive" },
|
|
76
|
+
);
|
|
77
|
+
const declaredLength = Number(req.headers["content-length"]);
|
|
78
|
+
if (Number.isFinite(declaredLength) && declaredLength > MAX_RESTORE_BODY_BYTES) return tooLarge();
|
|
79
|
+
let raw;
|
|
80
|
+
try {
|
|
81
|
+
raw = await readBody(req, MAX_RESTORE_BODY_BYTES);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
if (err?.status === 413) return tooLarge();
|
|
84
|
+
return error(res, 400, "bad-request", "请求体读取失败 / the request body could not be read");
|
|
85
|
+
}
|
|
86
|
+
let payload;
|
|
87
|
+
try {
|
|
88
|
+
payload = JSON.parse(raw);
|
|
89
|
+
} catch {
|
|
90
|
+
return error(res, 400, "bad-request", "请求体不是合法 JSON");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
let passphrase = req.headers["x-backup-passphrase"];
|
|
95
|
+
if (payload && typeof payload === "object" && payload.format === undefined && payload.backup !== undefined) {
|
|
96
|
+
passphrase = payload.passphrase ?? passphrase;
|
|
97
|
+
payload = payload.backup;
|
|
98
|
+
}
|
|
99
|
+
if (isEncryptedBackup(payload)) {
|
|
100
|
+
try {
|
|
101
|
+
payload = await decryptBackup(payload, typeof passphrase === "string" ? passphrase : undefined);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
return error(res, 400, err?.code ?? "bad-backup", err?.message ?? "备份解不开");
|
|
104
|
+
}
|
|
105
|
+
} else if (typeof passphrase === "string" && passphrase !== "") {
|
|
106
|
+
|
|
107
|
+
return error(res, 400, "not-encrypted", "这份备份没有设口令,和输入的口令对不上 / this backup is not protected by a passphrase; check that it is the right file");
|
|
108
|
+
}
|
|
109
|
+
const dryRun = url.searchParams.get("dryRun") === "1";
|
|
110
|
+
|
|
111
|
+
let store = null;
|
|
112
|
+
try {
|
|
113
|
+
store = getMemoryStore();
|
|
114
|
+
} catch (err) {
|
|
115
|
+
|
|
116
|
+
return error(res, 503, "memory-unavailable", `记忆库打不开:${err?.message ?? err}`);
|
|
117
|
+
}
|
|
118
|
+
if (dryRun) {
|
|
119
|
+
const plan = planRestore(payload, { store, prefs: assistantPrefs });
|
|
120
|
+
if (!plan.ok) {
|
|
121
|
+
return error(res, 400, "bad-backup", plan.error ?? "备份不合法");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
sendJson(res, 200, {
|
|
125
|
+
ok: true,
|
|
126
|
+
dryRun: true,
|
|
127
|
+
backupVersion: plan.backupVersion,
|
|
128
|
+
createdAt: plan.createdAt,
|
|
129
|
+
counts: plan.counts,
|
|
130
|
+
skipped: plan.skipped.slice(0, 50),
|
|
131
|
+
assistant: plan.assistant,
|
|
132
|
+
});
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const result = applyRestore(payload, { store, prefs: assistantPrefs });
|
|
136
|
+
if (!result.ok) {
|
|
137
|
+
return error(res, 400, "bad-backup", result.error ?? "备份不合法");
|
|
138
|
+
}
|
|
139
|
+
sendJson(res, 200, { ok: true, ...result });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
miss.now = true;
|
|
143
|
+
return NOT_HANDLED;
|
|
144
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import { readdir } from "node:fs/promises";
|
|
9
|
+
import { capabilityState, hostPeerSource, jobsNeedsSessionId, readSettingsSectionStrict, wireStreamTakesControl } from "../host-compat.js";
|
|
10
|
+
import { requireGet, sendJson } from "../http-util.js";
|
|
11
|
+
import { NOT_HANDLED } from "./route-groups.js";
|
|
12
|
+
|
|
13
|
+
export async function handleDiagnosticsRoutes(deps, req, res, url, rest, method, miss) {
|
|
14
|
+
const {
|
|
15
|
+
actionEntries, apiRpc, approvalMode, authEnabled, config, ctx, eventsCapable, firstAgent, gatewayPeer,
|
|
16
|
+
lanEnabled, lanHost, lanPort, name, notifStore, pendingApprovals, pendingFrames, pendingQuestions,
|
|
17
|
+
pluginVersion, pushStatus, quietHoursConfigProblem, runtimeForm, runtimeMetrics,
|
|
18
|
+
} = deps;
|
|
19
|
+
|
|
20
|
+
if (rest === "/diagnostics") {
|
|
21
|
+
if (requireGet(method, res)) return;
|
|
22
|
+
|
|
23
|
+
const probe = (name) => {
|
|
24
|
+
try {
|
|
25
|
+
return ctx.get(name) !== undefined;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const services = {
|
|
31
|
+
webServer: !!(ctx.webServer && typeof ctx.webServer.register === "function"),
|
|
32
|
+
agents: probe("agents"),
|
|
33
|
+
sessions: probe("sessions"),
|
|
34
|
+
llm: probe("llm"),
|
|
35
|
+
permissionPresets: probe("permissionPresets"),
|
|
36
|
+
agentPresets: probe("agentPresets"),
|
|
37
|
+
workspaceRegistry: probe("workspaceRegistry"),
|
|
38
|
+
approval: probe("approval"),
|
|
39
|
+
credentials: probe("credentials"),
|
|
40
|
+
messageFeedback: probe("messageFeedback"),
|
|
41
|
+
userQuestions: probe("userQuestions"),
|
|
42
|
+
};
|
|
43
|
+
const checks = { modelsRpc: false, sessionsList: false, directories: false, workspaces: false, notifications: false, actions: false };
|
|
44
|
+
try {
|
|
45
|
+
const agents = ctx.get("agents");
|
|
46
|
+
|
|
47
|
+
const sid = firstAgent(agents)?.id;
|
|
48
|
+
if (sid) {
|
|
49
|
+
const directory = await apiRpc("session.models", { sessionId: sid });
|
|
50
|
+
checks.modelsRpc = Array.isArray(directory?.groups) && directory.groups.length > 0;
|
|
51
|
+
}
|
|
52
|
+
} catch { }
|
|
53
|
+
try {
|
|
54
|
+
checks.sessionsList = (ctx.get("sessions")?.list?.().length ?? 0) >= 0;
|
|
55
|
+
} catch { }
|
|
56
|
+
try {
|
|
57
|
+
const entries = await readdir(process.cwd(), { withFileTypes: true });
|
|
58
|
+
checks.directories = entries.some((entry) => entry.isDirectory());
|
|
59
|
+
} catch { }
|
|
60
|
+
try {
|
|
61
|
+
checks.workspaces = (ctx.get("workspaceRegistry")?.list?.().length ?? 0) > 0;
|
|
62
|
+
} catch { }
|
|
63
|
+
checks.notifications = notifStore.size >= 0;
|
|
64
|
+
checks.actions = actionEntries.size >= 0;
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
checks.pendingFrames = pendingFrames.size;
|
|
71
|
+
checks.pendingApprovals = pendingApprovals.size;
|
|
72
|
+
checks.pendingQuestions = pendingQuestions.size;
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
for (const target of config.pushUrls) {
|
|
76
|
+
const status = pushStatus.get(target.name);
|
|
77
|
+
checks[`push:${target.name}`] = status
|
|
78
|
+
? `${status.ok ? "ok" : "fail"} ${new Date(status.at).toLocaleTimeString("zh-CN", { hour12: false })}${status.ok ? "" : ` · ${status.error}`}`
|
|
79
|
+
: "idle(尚未投递)";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
checks.approvalMode = approvalMode;
|
|
84
|
+
checks.remoteEvents = eventsCapable();
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
const jobsSvc = ctx.get("jobs");
|
|
91
|
+
const settingsSvc = ctx.get("settings");
|
|
92
|
+
const gatewaySvc = ctx.get("typertGateway");
|
|
93
|
+
const presetsSvc = ctx.get("permissionPresets");
|
|
94
|
+
const workspaceSvc = ctx.get("workspaceRegistry");
|
|
95
|
+
|
|
96
|
+
let connectionSvc;
|
|
97
|
+
try {
|
|
98
|
+
connectionSvc = ctx.get("connection");
|
|
99
|
+
} catch {
|
|
100
|
+
connectionSvc = undefined;
|
|
101
|
+
}
|
|
102
|
+
const peerSource = hostPeerSource(gatewaySvc, connectionSvc);
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
const eventsPeerProbe = (() => {
|
|
107
|
+
if (!gatewaySvc) return { state: "missing" };
|
|
108
|
+
if (!wireStreamTakesControl(gatewaySvc)) return { state: "ok" };
|
|
109
|
+
if (peerSource === "operatorPeer") return { state: "ok" };
|
|
110
|
+
if (peerSource === "createPeer") {
|
|
111
|
+
|
|
112
|
+
const peer = gatewayPeer();
|
|
113
|
+
return peer && peer === deps.cachedOwnerPeer
|
|
114
|
+
? { state: "ok" }
|
|
115
|
+
: { state: "drift", reason: "gateway-peer-source-missing" };
|
|
116
|
+
}
|
|
117
|
+
return { state: "drift", reason: "gateway-peer-source-missing" };
|
|
118
|
+
})();
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
const settingsProbeNamespaces = new Set(["llm-openai-codex", "llm-pi-ai"]);
|
|
125
|
+
try {
|
|
126
|
+
for (const provider of ctx.get("llm")?.listConfigurableProviders?.() ?? []) {
|
|
127
|
+
if (typeof provider?.settingsNs === "string" && provider.settingsNs !== "") {
|
|
128
|
+
settingsProbeNamespaces.add(provider.settingsNs);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
|
|
133
|
+
}
|
|
134
|
+
const settingsReadProbe = (() => {
|
|
135
|
+
if (!settingsSvc) return { state: "missing" };
|
|
136
|
+
for (const ns of settingsProbeNamespaces) {
|
|
137
|
+
const result = readSettingsSectionStrict(settingsSvc, ns);
|
|
138
|
+
|
|
139
|
+
if (!result.ok) return { state: "drift", reason: result.reason };
|
|
140
|
+
}
|
|
141
|
+
return { state: "ok" };
|
|
142
|
+
})();
|
|
143
|
+
const hostCapabilities = {
|
|
144
|
+
"jobs.callerShape": capabilityState(jobsSvc, (s) => typeof s.list === "function" && typeof s.kill === "function"),
|
|
145
|
+
"jobs.eventsApi": capabilityState(jobsSvc, (s) => typeof s.events?.subscribe === "function" || typeof s.onJobsChanged === "function"),
|
|
146
|
+
"settings.read": settingsReadProbe.state,
|
|
147
|
+
"gateway.wireStream": capabilityState(gatewaySvc, (s) => typeof s.openWireStream === "function"),
|
|
148
|
+
"permissionPresets.apply": capabilityState(presetsSvc, (s) => Array.isArray(s.names) && typeof s.apply === "function"),
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
"permissionPresets.catalog": capabilityState(presetsSvc, (s) => s.presets !== null && typeof s.presets === "object"),
|
|
154
|
+
"workspaceRegistry.stateWrite": capabilityState(workspaceSvc, (s) => typeof s.enqueueOperation === "function" && typeof s.requireState === "function" && typeof s.setState === "function"),
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
"gateway.eventsPeer": eventsPeerProbe.state,
|
|
159
|
+
};
|
|
160
|
+
checks.hostCapabilities = hostCapabilities;
|
|
161
|
+
|
|
162
|
+
checks.hostGeneration = {
|
|
163
|
+
jobsCaller: jobsSvc ? (jobsNeedsSessionId(jobsSvc) ? "sessionId" : "agent") : "unknown",
|
|
164
|
+
settingsRead: settingsSvc ? (typeof settingsSvc.get === "function" ? "get" : typeof settingsSvc.describe === "function" ? "describe" : "unknown") : "unknown",
|
|
165
|
+
wireStreamArgs: gatewaySvc ? (wireStreamTakesControl(gatewaySvc) ? "controlArg" : "legacyArg") : "unknown",
|
|
166
|
+
|
|
167
|
+
eventsPeer: !gatewaySvc
|
|
168
|
+
? "unknown"
|
|
169
|
+
: !wireStreamTakesControl(gatewaySvc)
|
|
170
|
+
? "legacy"
|
|
171
|
+
: eventsPeerProbe.state === "ok"
|
|
172
|
+
? peerSource
|
|
173
|
+
: "none",
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
const degradedCaps = Object.entries(hostCapabilities).filter(([, state]) => state !== "ok");
|
|
177
|
+
|
|
178
|
+
const hostCapabilityReasons = {};
|
|
179
|
+
if (settingsReadProbe.reason) hostCapabilityReasons["settings.read"] = settingsReadProbe.reason;
|
|
180
|
+
|
|
181
|
+
if (eventsPeerProbe.reason) hostCapabilityReasons["gateway.eventsPeer"] = eventsPeerProbe.reason;
|
|
182
|
+
if (Object.keys(hostCapabilityReasons).length > 0) checks.hostCapabilityReasons = hostCapabilityReasons;
|
|
183
|
+
const capabilityNote = degradedCaps.length === 0
|
|
184
|
+
? ""
|
|
185
|
+
: `宿主能力非全绿:${degradedCaps.map(([name, state]) => `${name}=${state}${hostCapabilityReasons[name] ? `(${hostCapabilityReasons[name]})` : ""}`).join("、")}——对应功能会明确报错或跳过,不会静默伪装成功(ADR 0017)`;
|
|
186
|
+
const approvalNote = approvalMode === "both" && eventsCapable()
|
|
187
|
+
? "approvalMode=both:桌面 GUI 与手机同卡、先答生效($events 双端呈现,v3.1.3)"
|
|
188
|
+
: approvalMode === "both"
|
|
189
|
+
? "approvalMode=both 但 $events 通道不可用 → 按 mobile 语义降级(手机在线独占,桌面不弹);看 checks.hostCapabilities.gateway.eventsPeer 与运行日志(0.2.1+ 的进程内开流需要活 Peer;该通道本身要求宿主 0.1.2-rc.1+ / 桌面 v2.0.5+)"
|
|
190
|
+
: approvalMode === "desktop"
|
|
191
|
+
? "approvalMode=desktop:审批/问询只走桌面 GUI,手机不弹卡"
|
|
192
|
+
: "approvalMode=mobile:手机在线独占审批/问询(v3.1.2 行为),离线交桌面 GUI";
|
|
193
|
+
sendJson(res, 200, {
|
|
194
|
+
ok: true,
|
|
195
|
+
plugin: { name: "dsh-mobile-remote", version: pluginVersion() },
|
|
196
|
+
runtime: {
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
form: runtimeForm(ctx),
|
|
201
|
+
host: ctx.webServer.host,
|
|
202
|
+
port: ctx.webServer.port,
|
|
203
|
+
cwd: process.cwd(),
|
|
204
|
+
authEnabled,
|
|
205
|
+
|
|
206
|
+
lanBridge: { enabled: lanEnabled, host: lanHost, port: lanPort, listening: deps.lanBridgeListening },
|
|
207
|
+
|
|
208
|
+
metrics: runtimeMetrics(),
|
|
209
|
+
},
|
|
210
|
+
services,
|
|
211
|
+
checks,
|
|
212
|
+
notes: [
|
|
213
|
+
approvalNote,
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
"skill-catalog: 移动端新建会话已随预设装配注入技能目录(v3.1.0 起);若目录缺失请重启插件并查看本诊断",
|
|
218
|
+
|
|
219
|
+
...(capabilityNote ? [capabilityNote] : []),
|
|
220
|
+
...(quietHoursConfigProblem ? [quietHoursConfigProblem] : []),
|
|
221
|
+
],
|
|
222
|
+
});
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
miss.now = true;
|
|
226
|
+
return NOT_HANDLED;
|
|
227
|
+
}
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import { closeSync, constants as fsConstants, createReadStream, existsSync, fstatSync, lstatSync, mkdirSync, openSync, statSync } from "node:fs";
|
|
9
|
+
import { readdir } from "node:fs/promises";
|
|
10
|
+
import { basename, join, resolve, sep } from "node:path";
|
|
11
|
+
import { fileMimeOf, ifNoneMatch, normalizeServerPath, parseByteRange, requestHeaderText } from "../api-helpers.js";
|
|
12
|
+
import { guardRes, requireGet, sendJson } from "../http-util.js";
|
|
13
|
+
import { isProtectedFile, isProtectedPath, isStillAt, realPathOf, removeCreatedEntry } from "../protected-paths.js";
|
|
14
|
+
import { NOT_HANDLED } from "./route-groups.js";
|
|
15
|
+
|
|
16
|
+
export async function handleFilesRoutes(deps, req, res, url, rest, method, miss) {
|
|
17
|
+
const {
|
|
18
|
+
ctx, error, failureDetail, name, protectedPathError, readJson, writeFdFully,
|
|
19
|
+
} = deps;
|
|
20
|
+
|
|
21
|
+
if (rest === "/workspaces") {
|
|
22
|
+
if (requireGet(method, res)) return;
|
|
23
|
+
const registry = ctx.get("workspaceRegistry");
|
|
24
|
+
const workspaces = registry?.list?.() ?? [];
|
|
25
|
+
sendJson(res, 200, {
|
|
26
|
+
ok: true,
|
|
27
|
+
|
|
28
|
+
workspaces: workspaces.map((w) => ({
|
|
29
|
+
id: w.id,
|
|
30
|
+
path: w.path,
|
|
31
|
+
title: w.title,
|
|
32
|
+
sessionIds: [...(w.sessionIds ?? [])],
|
|
33
|
+
})),
|
|
34
|
+
});
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (rest === "/directories") {
|
|
39
|
+
if (method === "POST") {
|
|
40
|
+
|
|
41
|
+
const body = await readJson(req, res);
|
|
42
|
+
if (body === undefined) return;
|
|
43
|
+
const parent = typeof body.path === "string" && body.path !== "" ? normalizeServerPath(body.path) : undefined;
|
|
44
|
+
const name = typeof body.name === "string" ? body.name.trim() : "";
|
|
45
|
+
if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|]/.test(name)) return error(res, 400, "invalid-name", "文件夹名不合法");
|
|
46
|
+
|
|
47
|
+
const shown = parent ? join(parent, name) : name;
|
|
48
|
+
|
|
49
|
+
let target;
|
|
50
|
+
try {
|
|
51
|
+
target = join(realPathOf(parent ?? "."), name);
|
|
52
|
+
} catch {
|
|
53
|
+
return protectedPathError(res);
|
|
54
|
+
}
|
|
55
|
+
if (isProtectedPath(target)) return protectedPathError(res);
|
|
56
|
+
try {
|
|
57
|
+
mkdirSync(target, { recursive: false });
|
|
58
|
+
sendJson(res, 200, { ok: true, path: shown });
|
|
59
|
+
} catch (err) {
|
|
60
|
+
return error(res, 400, "mkdir-failed", failureDetail(err));
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (requireGet(method, res)) return;
|
|
65
|
+
const path = url.searchParams.get("path");
|
|
66
|
+
|
|
67
|
+
if (!path || path === "") {
|
|
68
|
+
let roots = [];
|
|
69
|
+
if (process.platform === "win32") {
|
|
70
|
+
for (let letter = 65; letter <= 90; letter++) {
|
|
71
|
+
const drive = String.fromCharCode(letter) + ":\\";
|
|
72
|
+
if (existsSync(drive)) roots.push(drive);
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
roots = ["/"];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
sendJson(res, 200, { ok: true, path: "", dirs: roots, sep });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const base = normalizeServerPath(path);
|
|
83
|
+
|
|
84
|
+
let listed;
|
|
85
|
+
try {
|
|
86
|
+
listed = realPathOf(base);
|
|
87
|
+
} catch {
|
|
88
|
+
return protectedPathError(res);
|
|
89
|
+
}
|
|
90
|
+
if (isProtectedPath(listed)) return protectedPathError(res);
|
|
91
|
+
try {
|
|
92
|
+
const entries = await readdir(listed, { withFileTypes: true });
|
|
93
|
+
const dirs = entries
|
|
94
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
95
|
+
.map((entry) => entry.name)
|
|
96
|
+
.sort((a, b) => a.localeCompare(b, "zh-CN"));
|
|
97
|
+
|
|
98
|
+
const files = entries
|
|
99
|
+
.filter((entry) => entry.isFile() && !entry.name.startsWith("."))
|
|
100
|
+
.map((entry) => entry.name)
|
|
101
|
+
.sort((a, b) => a.localeCompare(b, "zh-CN"));
|
|
102
|
+
|
|
103
|
+
const fileEntries = entries
|
|
104
|
+
.filter((entry) => entry.isFile() && !entry.name.startsWith("."))
|
|
105
|
+
.map((entry) => {
|
|
106
|
+
let size = null;
|
|
107
|
+
let mtimeMs = null;
|
|
108
|
+
try {
|
|
109
|
+
const st = statSync(join(listed, entry.name));
|
|
110
|
+
size = st.size;
|
|
111
|
+
mtimeMs = st.mtimeMs;
|
|
112
|
+
} catch {
|
|
113
|
+
|
|
114
|
+
}
|
|
115
|
+
return { name: entry.name, size, mtimeMs, mime: fileMimeOf(entry.name) };
|
|
116
|
+
})
|
|
117
|
+
.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
|
|
118
|
+
sendJson(res, 200, { ok: true, path: base, dirs, files, fileEntries });
|
|
119
|
+
} catch (err) {
|
|
120
|
+
return error(res, 400, "directory-unreadable", failureDetail(err));
|
|
121
|
+
}
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
if (rest === "/files" && (method === "GET" || method === "HEAD")) {
|
|
131
|
+
const path = url.searchParams.get("path");
|
|
132
|
+
if (!path || path === "") return error(res, 400, "bad-request", "missing path");
|
|
133
|
+
const target = resolve(normalizeServerPath(path));
|
|
134
|
+
if (isProtectedPath(target)) return protectedPathError(res);
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
let fd;
|
|
141
|
+
try {
|
|
142
|
+
fd = openSync(target, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
|
|
143
|
+
} catch (err) {
|
|
144
|
+
return error(res, 404, "file-not-found", failureDetail(err));
|
|
145
|
+
}
|
|
146
|
+
let fdOwned = true;
|
|
147
|
+
const closeFd = () => {
|
|
148
|
+
if (!fdOwned) return;
|
|
149
|
+
fdOwned = false;
|
|
150
|
+
try {
|
|
151
|
+
closeSync(fd);
|
|
152
|
+
} catch {
|
|
153
|
+
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
const st = fstatSync(fd);
|
|
158
|
+
if (isProtectedFile(st)) {
|
|
159
|
+
closeFd();
|
|
160
|
+
return protectedPathError(res);
|
|
161
|
+
}
|
|
162
|
+
if (!st.isFile()) {
|
|
163
|
+
closeFd();
|
|
164
|
+
return error(res, 400, "not-a-file", "path is not a file");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (!isStillAt(target, st)) {
|
|
168
|
+
closeFd();
|
|
169
|
+
return isProtectedPath(target) ? protectedPathError(res) : error(res, 409, "file-changed", "the file changed while it was being opened; try again");
|
|
170
|
+
}
|
|
171
|
+
const name = basename(target);
|
|
172
|
+
|
|
173
|
+
const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
|
|
174
|
+
const lastModified = new Date(st.mtimeMs).toUTCString();
|
|
175
|
+
guardRes(res);
|
|
176
|
+
if (ifNoneMatch(req, etag)) {
|
|
177
|
+
closeFd();
|
|
178
|
+
res.writeHead(304, { etag, "cache-control": "no-store", connection: "close" });
|
|
179
|
+
res.end();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const range = parseByteRange(requestHeaderText(req, "range"), st.size);
|
|
183
|
+
if (range && range.invalid) {
|
|
184
|
+
closeFd();
|
|
185
|
+
res.writeHead(416, {
|
|
186
|
+
"accept-ranges": "bytes",
|
|
187
|
+
"content-range": `bytes */${st.size}`,
|
|
188
|
+
"content-length": "0",
|
|
189
|
+
etag,
|
|
190
|
+
"cache-control": "no-store",
|
|
191
|
+
connection: "close",
|
|
192
|
+
});
|
|
193
|
+
res.end();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const start = range ? range.start : 0;
|
|
197
|
+
const end = range ? range.end : st.size - 1;
|
|
198
|
+
const length = st.size === 0 ? 0 : end - start + 1;
|
|
199
|
+
const headers = {
|
|
200
|
+
"content-type": fileMimeOf(name),
|
|
201
|
+
"content-length": String(length),
|
|
202
|
+
"content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
203
|
+
"cache-control": "no-store",
|
|
204
|
+
"accept-ranges": "bytes",
|
|
205
|
+
etag,
|
|
206
|
+
"last-modified": lastModified,
|
|
207
|
+
|
|
208
|
+
connection: "close",
|
|
209
|
+
...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
|
|
210
|
+
};
|
|
211
|
+
res.writeHead(range ? 206 : 200, headers);
|
|
212
|
+
if (method === "HEAD" || st.size === 0) {
|
|
213
|
+
closeFd();
|
|
214
|
+
res.end();
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
fdOwned = false;
|
|
218
|
+
const source = createReadStream(null, { fd, start, end, autoClose: true });
|
|
219
|
+
|
|
220
|
+
res.on("close", () => {
|
|
221
|
+
try {
|
|
222
|
+
source.destroy();
|
|
223
|
+
} catch {
|
|
224
|
+
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
source.on("error", () => {
|
|
228
|
+
try {
|
|
229
|
+
res.destroy();
|
|
230
|
+
} catch {
|
|
231
|
+
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
source.pipe(res);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
closeFd();
|
|
237
|
+
return error(res, 404, "file-not-found", failureDetail(err));
|
|
238
|
+
}
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (rest === "/files/upload" && method === "POST") {
|
|
242
|
+
|
|
243
|
+
const body = await readJson(req, res, 64 * 1024 * 1024);
|
|
244
|
+
if (body === undefined) return;
|
|
245
|
+
const name = typeof body?.name === "string" ? body.name.trim() : "";
|
|
246
|
+
|
|
247
|
+
if (name === "" || name === "." || name === ".." || /[\\/:*?"<>|\0]/.test(name) || name.length > 255) {
|
|
248
|
+
return error(res, 400, "invalid-name", "文件名不合法");
|
|
249
|
+
}
|
|
250
|
+
if (typeof body?.data !== "string" || body.data === "") return error(res, 400, "bad-request", "missing data(base64)");
|
|
251
|
+
let dir;
|
|
252
|
+
const sessionId = typeof body?.sessionId === "string" && body.sessionId !== "" ? body.sessionId : undefined;
|
|
253
|
+
if (sessionId) {
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
const agent = ctx.get("agents")?.get(sessionId);
|
|
258
|
+
if (!agent) return error(res, 404, "session-not-found");
|
|
259
|
+
dir = agent.session?.header?.cwd;
|
|
260
|
+
if (typeof dir !== "string" || dir === "") return error(res, 404, "workspace-not-found", "会话没有可用工作区");
|
|
261
|
+
} else {
|
|
262
|
+
const registry = ctx.get("workspaceRegistry");
|
|
263
|
+
dir = registry?.list?.()?.[0]?.path;
|
|
264
|
+
}
|
|
265
|
+
if (typeof dir !== "string" || dir === "") return error(res, 503, "no-workspace", "无法确定目标目录(无工作区)");
|
|
266
|
+
const target = join(resolve(normalizeServerPath(dir)), name);
|
|
267
|
+
if (isProtectedPath(target)) return protectedPathError(res);
|
|
268
|
+
try {
|
|
269
|
+
const buf = Buffer.from(body.data, "base64");
|
|
270
|
+
if (buf.length === 0) return error(res, 400, "bad-request", "empty payload");
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
try {
|
|
275
|
+
const existing = lstatSync(target);
|
|
276
|
+
if (existing.isSymbolicLink()) return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
|
|
277
|
+
if (!existing.isFile()) return error(res, 400, "not-a-file", "path is not a file");
|
|
278
|
+
} catch {
|
|
279
|
+
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
const base = fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
|
|
284
|
+
let fd;
|
|
285
|
+
let created = false;
|
|
286
|
+
try {
|
|
287
|
+
try {
|
|
288
|
+
fd = openSync(target, base | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o644);
|
|
289
|
+
created = true;
|
|
290
|
+
} catch (err) {
|
|
291
|
+
if (err?.code !== "EEXIST") throw err;
|
|
292
|
+
fd = openSync(target, base);
|
|
293
|
+
}
|
|
294
|
+
} catch (err) {
|
|
295
|
+
if (err?.code === "ELOOP" || err?.code === "EMLINK") return error(res, 400, "link-not-allowed", "目标是一个链接 / the target is a link");
|
|
296
|
+
if (err?.code === "ENXIO") return error(res, 400, "not-a-file", "path is not a file");
|
|
297
|
+
throw err;
|
|
298
|
+
}
|
|
299
|
+
let refusal;
|
|
300
|
+
let st;
|
|
301
|
+
try {
|
|
302
|
+
st = fstatSync(fd);
|
|
303
|
+
if (isProtectedFile(st)) refusal = "protected";
|
|
304
|
+
else if (!st.isFile()) refusal = "not-a-file";
|
|
305
|
+
|
|
306
|
+
else if (!isStillAt(target, st)) refusal = isProtectedPath(target) ? "protected" : "changed";
|
|
307
|
+
if (!refusal) writeFdFully(fd, buf);
|
|
308
|
+
} finally {
|
|
309
|
+
closeSync(fd);
|
|
310
|
+
}
|
|
311
|
+
if (refusal) {
|
|
312
|
+
if (created) removeCreatedEntry(target, st);
|
|
313
|
+
if (refusal === "not-a-file") return error(res, 400, "not-a-file", "path is not a file");
|
|
314
|
+
if (refusal === "changed") return error(res, 409, "file-changed", "the folder changed while the file was being written; try again");
|
|
315
|
+
return protectedPathError(res);
|
|
316
|
+
}
|
|
317
|
+
sendJson(res, 200, { ok: true, path: target, bytes: buf.length });
|
|
318
|
+
} catch (err) {
|
|
319
|
+
ctx.logger.warn(`mobile-remote: /files/upload 写入失败:${err?.message ?? err}`);
|
|
320
|
+
return error(res, 400, "write-failed", failureDetail(err));
|
|
321
|
+
}
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
miss.now = true;
|
|
325
|
+
return NOT_HANDLED;
|
|
326
|
+
}
|