pi-foreman 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +179 -2
- package/package.json +58 -4
- package/src/bootstrap.mjs +107 -0
- package/src/cli.mjs +504 -0
- package/src/config.mjs +819 -0
- package/src/docs.mjs +148 -0
- package/src/envs.mjs +621 -0
- package/src/harness.mjs +96 -0
- package/src/hub.mjs +117 -0
- package/src/projection.mjs +455 -0
- package/src/providers.mjs +622 -0
- package/src/server.mjs +1350 -0
- package/src/skills.mjs +340 -0
- package/src/stores.mjs +117 -0
- package/src/tasks/ask-peer.mjs +201 -0
- package/src/tasks/peer-tools.mjs +254 -0
- package/src/tasks/workspace-extension.mjs +108 -0
- package/web/dist/assets/chat-vendor-CpKl2eGN.css +1 -0
- package/web/dist/assets/chat-vendor-PY5rkhAV.js +43 -0
- package/web/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/web/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/web/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/web/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/web/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/web/dist/assets/icons-BRdrcGH3.js +2 -0
- package/web/dist/assets/index-C32JOM8D.js +35 -0
- package/web/dist/assets/index-D_7gqB73.css +1 -0
- package/web/dist/assets/react-vendor-DEAzPTfA.js +10 -0
- package/web/dist/index.html +17 -0
package/src/server.mjs
ADDED
|
@@ -0,0 +1,1350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP + 单连接 WebSocket 多路复用服务(v2)。
|
|
3
|
+
*
|
|
4
|
+
* - 单连接 WS (/api/ws):一条连接复用 envs / models / conv:<id> / login:<id> 等,
|
|
5
|
+
* 彻底解决 HTTP/1.1 同源 6 连接上限阻塞问题。
|
|
6
|
+
* - 所有数据读写经 projection.mjs DTO,所有配置/认证/reload 写操作严格限制 loopback。
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
11
|
+
import { dirname, extname, join, normalize, resolve, sep } from "node:path";
|
|
12
|
+
import { WebSocketServer } from "ws";
|
|
13
|
+
import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
|
|
14
|
+
import { Hub } from "./hub.mjs";
|
|
15
|
+
import {
|
|
16
|
+
ENV_NAME_PATTERN, ENV_WRITABLE_FIELDS, HOST_WRITABLE_FIELDS, getEnvWorkspaces, isHostTrusted,
|
|
17
|
+
listSshConfigHosts, loadConfig, normalizeWorkspaceCwd, removeEnvironment, removeHost, removeWorkspace,
|
|
18
|
+
resolveEnvTarget, resolveWorkspaceFor, setDefaultModel, setEnvironment, setHost, sshTargetForHost, upsertWorkspace,
|
|
19
|
+
} from "./config.mjs";
|
|
20
|
+
import { describeError } from "./envs.mjs";
|
|
21
|
+
import {
|
|
22
|
+
discoverRemoteWorkspaceContext, installSkillToWorkspace, invalidateAllWorkspaceCaches,
|
|
23
|
+
invalidateWorkspaceCache, listLocalSkills, removeRemoteSkill,
|
|
24
|
+
} from "./skills.mjs";
|
|
25
|
+
import {
|
|
26
|
+
entryToText, projectConversationView, projectEntries, projectEnvStatus,
|
|
27
|
+
projectExec, projectFileInfo, projectModel, projectSubmission,
|
|
28
|
+
projectUsageState, truncate,
|
|
29
|
+
} from "./projection.mjs";
|
|
30
|
+
import {
|
|
31
|
+
LoginSessionManager, listAvailableModels, listProvidersWithAuth,
|
|
32
|
+
loadPromptTemplates, reloadProviders, resolveDefaultModel,
|
|
33
|
+
} from "./providers.mjs";
|
|
34
|
+
|
|
35
|
+
const DEFAULT_PORT = 8788;
|
|
36
|
+
const DEFAULT_HOST = "127.0.0.1";
|
|
37
|
+
const WS_HEARTBEAT_MS = 25_000;
|
|
38
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
39
|
+
const MAX_EDIT_BYTES = 512 * 1024;
|
|
40
|
+
const PROBE_TIMEOUT_MS = 20_000;
|
|
41
|
+
const REMOTE_OP_TIMEOUT_MS = 45_000;
|
|
42
|
+
const DEPLOY_TIMEOUT_MS = 180_000;
|
|
43
|
+
|
|
44
|
+
const MIME = {
|
|
45
|
+
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8",
|
|
46
|
+
".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
|
|
47
|
+
".json": "application/json; charset=utf-8", ".svg": "image/svg+xml",
|
|
48
|
+
".png": "image/png", ".ico": "image/x-icon", ".woff2": "font/woff2",
|
|
49
|
+
".map": "application/json; charset=utf-8",
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** 会话标题是否还是创建时的默认值(环境名 / env:cwd / CLI 的 ask-xxx) */
|
|
53
|
+
function isDefaultTitle(rec) {
|
|
54
|
+
const t = rec.title;
|
|
55
|
+
if (!t) return true;
|
|
56
|
+
if (t === rec.env || t.startsWith(`${rec.env}:`)) return true;
|
|
57
|
+
return t.startsWith("ask-");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function startServer(deps) {
|
|
61
|
+
const {
|
|
62
|
+
cfg, dir, envs, harness, index,
|
|
63
|
+
webRoot, host = DEFAULT_HOST, port = DEFAULT_PORT,
|
|
64
|
+
remoteOpTimeoutMs = REMOTE_OP_TIMEOUT_MS,
|
|
65
|
+
deployTimeoutMs = DEPLOY_TIMEOUT_MS,
|
|
66
|
+
autoProbe = true,
|
|
67
|
+
probeIntervalMs = 30_000,
|
|
68
|
+
offlineBackoffMaxMs = 120_000,
|
|
69
|
+
} = deps;
|
|
70
|
+
|
|
71
|
+
let currentModels = typeof deps.models === "function" ? deps.models() : deps.models;
|
|
72
|
+
let extensionProviders = deps.extensionProviders ?? new Map();
|
|
73
|
+
let prompts = loadPromptTemplates();
|
|
74
|
+
|
|
75
|
+
const hub = new Hub();
|
|
76
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
77
|
+
/** @type {Set<import("ws").WebSocket>} */
|
|
78
|
+
const wsClients = new Set();
|
|
79
|
+
|
|
80
|
+
function sendWs(ws, msg) {
|
|
81
|
+
if (ws.readyState !== 1) return;
|
|
82
|
+
try { ws.send(JSON.stringify(msg)); } catch { /* closing */ }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function broadcastChannel(channel, data) {
|
|
86
|
+
for (const ws of wsClients) {
|
|
87
|
+
if (ws.__subs?.has(channel)) sendWs(ws, { type: "event", channel, data });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const loginManager = new LoginSessionManager(currentModels, {
|
|
92
|
+
onEvent: (loginId, payload) => {
|
|
93
|
+
broadcastChannel(`login:${loginId}`, payload);
|
|
94
|
+
if (payload.kind === "done") void pushProvidersAndModels();
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
async function pushProvidersAndModels() {
|
|
99
|
+
const [providers, avail] = await Promise.all([
|
|
100
|
+
listProvidersWithAuth(currentModels, extensionProviders),
|
|
101
|
+
listAvailableModels(currentModels),
|
|
102
|
+
]);
|
|
103
|
+
broadcastChannel("models", {
|
|
104
|
+
defaultModel: cfg.defaultModel,
|
|
105
|
+
providers,
|
|
106
|
+
models: avail.map(({ model, supportedThinkingLevels }) => projectModel(model, supportedThinkingLevels)),
|
|
107
|
+
at: Date.now(),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ── 环境状态:客户端在线驱动的轻量自动探测(含离线指数退避) ──────────────────
|
|
112
|
+
/** @type {Map<string, object>} */
|
|
113
|
+
const envStatus = new Map();
|
|
114
|
+
/** @type {Map<string, { failures: number, nextAt: number }>} */
|
|
115
|
+
const probeSchedule = new Map();
|
|
116
|
+
|
|
117
|
+
function hasEnvsSubscriber() {
|
|
118
|
+
for (const ws of wsClients) {
|
|
119
|
+
if (ws.readyState === 1 && ws.__subs?.has("envs")) return true;
|
|
120
|
+
}
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function triggerDueProbes(onlyUnprobed = false) {
|
|
125
|
+
if (!autoProbe) return;
|
|
126
|
+
const now = Date.now();
|
|
127
|
+
for (const name of Object.keys(cfg.environments ?? {})) {
|
|
128
|
+
if (inFlightProbes.has(name)) continue;
|
|
129
|
+
if (onlyUnprobed && envStatus.has(name)) continue;
|
|
130
|
+
if ((probeSchedule.get(name)?.nextAt ?? 0) <= now) {
|
|
131
|
+
void probeEnv(name);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function envSnapshot() {
|
|
137
|
+
return Object.keys(cfg.environments ?? {})
|
|
138
|
+
.map((name) => envStatus.get(name))
|
|
139
|
+
.filter(Boolean);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function pushEnvs() {
|
|
143
|
+
broadcastChannel("envs", { envs: envSnapshot(), at: Date.now() });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function envRowFor(name, probe) {
|
|
147
|
+
const resolved = (() => {
|
|
148
|
+
try { return resolveEnvTarget(name, cfg, dir); } catch { return null; }
|
|
149
|
+
})();
|
|
150
|
+
const e = resolved?.env ?? cfg.environments?.[name] ?? {};
|
|
151
|
+
const hostCfg = resolved?.hostCfg;
|
|
152
|
+
const label = e.container
|
|
153
|
+
? `${hostCfg?.type === "local" ? "local" : (hostCfg?.host ?? e.host)} ▸ ${e.container}`
|
|
154
|
+
: (hostCfg?.type === "local" ? name : (hostCfg?.host ?? e.host ?? name));
|
|
155
|
+
return {
|
|
156
|
+
name,
|
|
157
|
+
label,
|
|
158
|
+
host: e.host,
|
|
159
|
+
hostType: hostCfg?.type ?? "ssh",
|
|
160
|
+
runtime: resolved?.runtime ?? (e.container ? "docker" : "host"),
|
|
161
|
+
kind: resolved?.mode ?? (e.container ? "ssh-docker" : "ssh-host"),
|
|
162
|
+
cwd: e.cwd ?? null,
|
|
163
|
+
checkedAt: Date.now(),
|
|
164
|
+
...projectEnvStatus(name, probe),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const inFlightProbes = new Map();
|
|
169
|
+
function probeEnv(name) {
|
|
170
|
+
const running = inFlightProbes.get(name);
|
|
171
|
+
if (running) return running;
|
|
172
|
+
if (!cfg.environments?.[name]) return Promise.resolve(null);
|
|
173
|
+
const task = (async () => {
|
|
174
|
+
const probe = await envs
|
|
175
|
+
.probe(name, { timeoutMs: PROBE_TIMEOUT_MS, cwd: cfg.environments[name].cwd })
|
|
176
|
+
.catch((e) => ({ ok: false, error: describeError(e) }));
|
|
177
|
+
const view = envRowFor(name, probe);
|
|
178
|
+
envStatus.set(name, view);
|
|
179
|
+
if (view.ok) {
|
|
180
|
+
probeSchedule.set(name, { failures: 0, nextAt: Date.now() + probeIntervalMs });
|
|
181
|
+
} else {
|
|
182
|
+
const failures = (probeSchedule.get(name)?.failures ?? 0) + 1;
|
|
183
|
+
const delay = Math.min(offlineBackoffMaxMs, probeIntervalMs * (2 ** Math.min(failures - 1, 2)));
|
|
184
|
+
probeSchedule.set(name, { failures, nextAt: Date.now() + delay });
|
|
185
|
+
}
|
|
186
|
+
pushEnvs();
|
|
187
|
+
return view;
|
|
188
|
+
})().finally(() => inFlightProbes.delete(name));
|
|
189
|
+
inFlightProbes.set(name, task);
|
|
190
|
+
return task;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function noteEnvFailure(name, errorLike) {
|
|
194
|
+
if (!name || !cfg.environments?.[name]) return;
|
|
195
|
+
const text = describeError(errorLike);
|
|
196
|
+
if (!/pi-env|spawn_error|connection|ECONN|daemon|not trusted|host key|exited with code 255|docker/i.test(text)) return;
|
|
197
|
+
const prev = envStatus.get(name);
|
|
198
|
+
envStatus.set(name, { ...(prev ?? envRowFor(name, { ok: false })), ok: false, error: text, checkedAt: Date.now() });
|
|
199
|
+
pushEnvs();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function withTimeout(promise, ms, what) {
|
|
203
|
+
let timer;
|
|
204
|
+
const limit = ms < 1000 ? `${ms}ms` : `${Math.round(ms / 1000)}s`;
|
|
205
|
+
const timeout = new Promise((_, reject) => {
|
|
206
|
+
timer = setTimeout(
|
|
207
|
+
() => reject(new Error(`${what} 超时(${limit})—— 目标可能卡在 DNS / 跳板机 / 未响应的 sshd 上`)),
|
|
208
|
+
ms,
|
|
209
|
+
);
|
|
210
|
+
if (timer.unref) timer.unref();
|
|
211
|
+
});
|
|
212
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function hostRows(includeFields = true) {
|
|
216
|
+
return Object.entries(cfg.hosts ?? {}).map(([name, h]) => ({
|
|
217
|
+
name,
|
|
218
|
+
type: h.type,
|
|
219
|
+
label: h.type === "local" ? name : (h.host ?? name),
|
|
220
|
+
...(includeFields ? { config: h } : {}),
|
|
221
|
+
}));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function environmentRows(includeFields = true) {
|
|
225
|
+
return Object.entries(cfg.environments ?? {}).map(([name, e]) => {
|
|
226
|
+
let resolved = null;
|
|
227
|
+
try { resolved = resolveEnvTarget(name, cfg, dir); } catch { /* ignore */ }
|
|
228
|
+
const hostCfg = resolved?.hostCfg;
|
|
229
|
+
const runtime = resolved?.runtime ?? (e.container ? "docker" : "host");
|
|
230
|
+
const mode = resolved?.mode ?? (e.container ? "ssh-docker" : "ssh-host");
|
|
231
|
+
const label = e.container
|
|
232
|
+
? `${hostCfg?.type === "local" ? "local" : (hostCfg?.host ?? e.host)} ▸ ${e.container}`
|
|
233
|
+
: (hostCfg?.type === "local" ? name : (hostCfg?.host ?? e.host ?? name));
|
|
234
|
+
return {
|
|
235
|
+
name,
|
|
236
|
+
label,
|
|
237
|
+
host: e.host,
|
|
238
|
+
hostType: hostCfg?.type ?? "ssh",
|
|
239
|
+
runtime,
|
|
240
|
+
kind: mode,
|
|
241
|
+
cwd: e.cwd ?? null,
|
|
242
|
+
description: e.description ?? null,
|
|
243
|
+
fsGroup: e.fsGroup ?? null,
|
|
244
|
+
workspaces: getEnvWorkspaces(cfg, name),
|
|
245
|
+
...(includeFields ? { config: e } : {}),
|
|
246
|
+
};
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const isLoopback = (req) => {
|
|
251
|
+
const a = req.socket.remoteAddress ?? "";
|
|
252
|
+
return a === "127.0.0.1" || a === "::1" || a === "::ffff:127.0.0.1";
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const denyRemote = (res) => json(res, 403, {
|
|
256
|
+
error: "写配置、认证登录与重载只允许本机(127.0.0.1)访问。",
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
// ── WebSocket 订阅处理 ──────────────────────────────────────────────────────
|
|
260
|
+
async function subscribeWsChannel(ws, channel) {
|
|
261
|
+
if (!channel || typeof channel !== "string") return;
|
|
262
|
+
if (ws.__subs.has(channel)) return;
|
|
263
|
+
|
|
264
|
+
if (channel === "envs") {
|
|
265
|
+
ws.__subs.set(channel, () => {});
|
|
266
|
+
sendWs(ws, { type: "event", channel: "envs", data: { envs: envSnapshot(), at: Date.now(), initial: true } });
|
|
267
|
+
triggerDueProbes(false);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (channel === "models") {
|
|
272
|
+
ws.__subs.set(channel, () => {});
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const convMatch = channel.match(/^conv:(\d+)$/);
|
|
277
|
+
if (convMatch) {
|
|
278
|
+
const convId = Number(convMatch[1]);
|
|
279
|
+
const conv = await harness.conversation(convId, ctx);
|
|
280
|
+
if (!conv) {
|
|
281
|
+
sendWs(ws, { type: "event", channel, data: { error: `会话 ${convId} 不存在` } });
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const ch = hub.channel(channel, () => conv.watch(ctx), (v) => projectConversationView(v));
|
|
285
|
+
const off = ch.subscribe((dto, meta) => sendWs(ws, {
|
|
286
|
+
type: "event", channel, data: meta.error ? { error: meta.error } : dto,
|
|
287
|
+
}));
|
|
288
|
+
ws.__subs.set(channel, off);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (channel.startsWith("login:")) {
|
|
293
|
+
const loginId = channel.slice(6);
|
|
294
|
+
ws.__subs.set(channel, () => {});
|
|
295
|
+
const state = loginManager.getState(loginId);
|
|
296
|
+
if (state) sendWs(ws, { type: "event", channel, data: { kind: "state", ...state } });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ── HTTP 服务 ───────────────────────────────────────────────────────────────
|
|
301
|
+
const server = createServer(async (req, res) => {
|
|
302
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
303
|
+
const path = url.pathname;
|
|
304
|
+
try {
|
|
305
|
+
// ---- 首屏快照 ----
|
|
306
|
+
if (path === "/api/bootstrap" && req.method === "GET") {
|
|
307
|
+
const local = isLoopback(req);
|
|
308
|
+
const [providers] = await Promise.all([
|
|
309
|
+
listProvidersWithAuth(currentModels, extensionProviders),
|
|
310
|
+
]);
|
|
311
|
+
return json(res, 200, {
|
|
312
|
+
version: "0.2.0",
|
|
313
|
+
defaultModel: cfg.defaultModel,
|
|
314
|
+
localOnly: local,
|
|
315
|
+
peer: cfg.peer,
|
|
316
|
+
hosts: hostRows(local),
|
|
317
|
+
environments: environmentRows(local),
|
|
318
|
+
conversations: index.all({ includeArchived: true }).map((c) => ({
|
|
319
|
+
conversationId: c.conversationId,
|
|
320
|
+
env: c.env,
|
|
321
|
+
cwd: c.cwd,
|
|
322
|
+
title: c.title,
|
|
323
|
+
createdAt: c.createdAt,
|
|
324
|
+
...(c.archived ? { archived: true } : {}),
|
|
325
|
+
})),
|
|
326
|
+
envStatus: envSnapshot(),
|
|
327
|
+
providers,
|
|
328
|
+
prompts: prompts.map((p) => ({ name: p.name, description: p.description, body: p.body })),
|
|
329
|
+
localSkills: listLocalSkills(),
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (path === "/api/usage" && req.method === "GET") {
|
|
334
|
+
return json(res, 200, projectUsageState(await harness.usage(ctx)));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (path === "/api/prompts" && req.method === "GET") {
|
|
338
|
+
return json(res, 200, { prompts });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ---- Provider / 模型 / 认证 / 重载 ----
|
|
342
|
+
if (path === "/api/models" && req.method === "GET") {
|
|
343
|
+
const [providers, avail] = await Promise.all([
|
|
344
|
+
listProvidersWithAuth(currentModels, extensionProviders),
|
|
345
|
+
listAvailableModels(currentModels),
|
|
346
|
+
]);
|
|
347
|
+
return json(res, 200, {
|
|
348
|
+
defaultModel: cfg.defaultModel,
|
|
349
|
+
providers,
|
|
350
|
+
models: avail.map(({ model, supportedThinkingLevels }) => projectModel(model, supportedThinkingLevels)),
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (path === "/api/auth/providers" && req.method === "GET") {
|
|
355
|
+
return json(res, 200, {
|
|
356
|
+
providers: await listProvidersWithAuth(currentModels, extensionProviders),
|
|
357
|
+
localOnly: isLoopback(req),
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (path === "/api/auth/login/start" && req.method === "POST") {
|
|
362
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
363
|
+
const body = await readBody(req);
|
|
364
|
+
if (!body.providerId) return json(res, 400, { error: "providerId 必填" });
|
|
365
|
+
try {
|
|
366
|
+
const state = loginManager.start(String(body.providerId), body.authType);
|
|
367
|
+
return json(res, 200, { ok: true, ...state });
|
|
368
|
+
} catch (e) {
|
|
369
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const loginReplyMatch = path.match(/^\/api\/auth\/login\/([^/]+)\/reply$/);
|
|
374
|
+
if (loginReplyMatch && req.method === "POST") {
|
|
375
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
376
|
+
const body = await readBody(req);
|
|
377
|
+
try {
|
|
378
|
+
return json(res, 200, loginManager.reply(decodeURIComponent(loginReplyMatch[1]), body.value ?? ""));
|
|
379
|
+
} catch (e) {
|
|
380
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const loginCancelMatch = path.match(/^\/api\/auth\/login\/([^/]+)\/cancel$/);
|
|
385
|
+
if (loginCancelMatch && req.method === "POST") {
|
|
386
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
387
|
+
return json(res, 200, loginManager.cancel(decodeURIComponent(loginCancelMatch[1])));
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (path === "/api/auth/logout" && req.method === "POST") {
|
|
391
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
392
|
+
const body = await readBody(req);
|
|
393
|
+
if (!body.providerId) return json(res, 400, { error: "providerId 必填" });
|
|
394
|
+
await currentModels.logout(String(body.providerId), { signal: AbortSignal.timeout(5000) });
|
|
395
|
+
await pushProvidersAndModels();
|
|
396
|
+
return json(res, 200, { ok: true });
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (path === "/api/reload" && req.method === "POST") {
|
|
400
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
401
|
+
const freshCfg = loadConfig(dir);
|
|
402
|
+
cfg.proxy = freshCfg.proxy;
|
|
403
|
+
cfg.ssh = freshCfg.ssh;
|
|
404
|
+
cfg.defaultModel = freshCfg.defaultModel;
|
|
405
|
+
cfg.providerExtensions = freshCfg.providerExtensions;
|
|
406
|
+
cfg.peer = freshCfg.peer;
|
|
407
|
+
envs.replaceConfig(freshCfg.hosts, freshCfg.environments);
|
|
408
|
+
const reloaded = await reloadProviders(currentModels, cfg);
|
|
409
|
+
extensionProviders = reloaded.extensionProviders;
|
|
410
|
+
prompts = loadPromptTemplates();
|
|
411
|
+
invalidateAllWorkspaceCaches();
|
|
412
|
+
await pushProvidersAndModels();
|
|
413
|
+
pushEnvs();
|
|
414
|
+
return json(res, 200, {
|
|
415
|
+
ok: true,
|
|
416
|
+
discoveredExtensions: reloaded.discoveredExtensions,
|
|
417
|
+
promptsCount: prompts.length,
|
|
418
|
+
errors: reloaded.errors,
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ---- 主机(Hosts)与容器发现 ----
|
|
423
|
+
if (path === "/api/ssh/config-hosts" && req.method === "GET") {
|
|
424
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
425
|
+
return json(res, 200, {
|
|
426
|
+
ok: true,
|
|
427
|
+
configFile: cfg.ssh?.configFile ?? "~/.ssh/config",
|
|
428
|
+
hosts: listSshConfigHosts(cfg),
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (path === "/api/hosts" && req.method === "GET") {
|
|
433
|
+
return json(res, 200, { hosts: hostRows(isLoopback(req)), writable: HOST_WRITABLE_FIELDS, localOnly: isLoopback(req) });
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
if (path === "/api/hosts" && req.method === "POST") {
|
|
437
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
438
|
+
const body = await readBody(req);
|
|
439
|
+
const name = String(body.name ?? "").trim();
|
|
440
|
+
if (!name || !ENV_NAME_PATTERN.test(name)) {
|
|
441
|
+
return json(res, 400, { error: `主机名非法:必须匹配 ${ENV_NAME_PATTERN}` });
|
|
442
|
+
}
|
|
443
|
+
try {
|
|
444
|
+
const next = setHost(cfg, name, body, dir);
|
|
445
|
+
cfg.hosts = next.hosts;
|
|
446
|
+
envs.replaceConfig(next.hosts, cfg.environments);
|
|
447
|
+
return json(res, 200, { ok: true, name, hosts: hostRows(true) });
|
|
448
|
+
} catch (e) {
|
|
449
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const hostDeleteMatch = path.match(/^\/api\/hosts\/([^/]+)$/);
|
|
454
|
+
if (hostDeleteMatch && req.method === "DELETE") {
|
|
455
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
456
|
+
const name = decodeURIComponent(hostDeleteMatch[1]);
|
|
457
|
+
try {
|
|
458
|
+
const next = removeHost(cfg, name, dir);
|
|
459
|
+
cfg.hosts = next.hosts;
|
|
460
|
+
envs.replaceConfig(next.hosts, cfg.environments);
|
|
461
|
+
return json(res, 200, { ok: true, name, hosts: hostRows(true) });
|
|
462
|
+
} catch (e) {
|
|
463
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const hostTrustMatch = path.match(/^\/api\/hosts\/([^/]+)\/trust$/);
|
|
468
|
+
if (hostTrustMatch && req.method === "POST") {
|
|
469
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
470
|
+
const name = decodeURIComponent(hostTrustMatch[1]);
|
|
471
|
+
const h = cfg.hosts?.[name];
|
|
472
|
+
if (!h) return json(res, 404, { error: `未知主机: ${name}` });
|
|
473
|
+
if (h.type !== "ssh") return json(res, 400, { error: `${name} 不是 ssh 主机` });
|
|
474
|
+
const body = await readBody(req);
|
|
475
|
+
try {
|
|
476
|
+
if (body.reset === true) {
|
|
477
|
+
await withTimeout(envs.forgetTrust(name), 10_000, `重置 ${name} 的 known_hosts`);
|
|
478
|
+
if (cfg.ssh?.autoTrust !== false) {
|
|
479
|
+
for (const [envName, e] of Object.entries(cfg.environments ?? {})) {
|
|
480
|
+
if (e?.host === name) void probeEnv(envName);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return json(res, 200, { ok: true, reset: true, accepted: false });
|
|
484
|
+
}
|
|
485
|
+
const { target } = sshTargetForHost(name, cfg, dir);
|
|
486
|
+
if (!Array.isArray(body.lines) || body.lines.length === 0) {
|
|
487
|
+
if (body.force !== true && isHostTrusted(target)) {
|
|
488
|
+
return json(res, 200, { ok: true, accepted: true });
|
|
489
|
+
}
|
|
490
|
+
const scan = await withTimeout(envs.scanTrust(name), remoteOpTimeoutMs, `扫描 ${name} 的 host key`);
|
|
491
|
+
return json(res, 200, { ok: true, accepted: false, ...scan });
|
|
492
|
+
}
|
|
493
|
+
await withTimeout(envs.acceptTrust(name, body.lines.map(String)), 10_000, `写入 ${name} 的 known_hosts`);
|
|
494
|
+
for (const [envName, e] of Object.entries(cfg.environments ?? {})) {
|
|
495
|
+
if (e?.host === name) void probeEnv(envName);
|
|
496
|
+
}
|
|
497
|
+
return json(res, 200, { ok: true, accepted: true });
|
|
498
|
+
} catch (e) {
|
|
499
|
+
return json(res, 400, { error: describeError(e) });
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// ---- 环境管理 ----
|
|
504
|
+
if (path === "/api/environments" && req.method === "GET") {
|
|
505
|
+
return json(res, 200, {
|
|
506
|
+
environments: environmentRows(isLoopback(req)),
|
|
507
|
+
writable: ENV_WRITABLE_FIELDS,
|
|
508
|
+
localOnly: isLoopback(req),
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
if (path === "/api/environments/probe" && req.method === "POST") {
|
|
513
|
+
const names = Object.keys(cfg.environments ?? {});
|
|
514
|
+
await Promise.all(names.map((n) => probeEnv(n)));
|
|
515
|
+
return json(res, 200, { ok: true, envs: envSnapshot() });
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (path === "/api/environments" && req.method === "POST") {
|
|
519
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
520
|
+
const body = await readBody(req);
|
|
521
|
+
const name = String(body.name ?? "").trim();
|
|
522
|
+
if (!name) return json(res, 400, { error: "name 必填" });
|
|
523
|
+
if (!ENV_NAME_PATTERN.test(name)) {
|
|
524
|
+
return json(res, 400, { error: `环境名非法:必须匹配 ${ENV_NAME_PATTERN}` });
|
|
525
|
+
}
|
|
526
|
+
const existed = Boolean(cfg.environments?.[name]);
|
|
527
|
+
let next;
|
|
528
|
+
try {
|
|
529
|
+
next = setEnvironment(cfg, name, body, dir);
|
|
530
|
+
} catch (e) {
|
|
531
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
532
|
+
}
|
|
533
|
+
cfg.hosts = next.hosts;
|
|
534
|
+
cfg.environments = next.environments;
|
|
535
|
+
envs.replaceConfig(next.hosts, next.environments);
|
|
536
|
+
envStatus.delete(name);
|
|
537
|
+
probeSchedule.delete(name);
|
|
538
|
+
pushEnvs();
|
|
539
|
+
if (body.probe === true) void probeEnv(name);
|
|
540
|
+
return json(res, 200, { ok: true, name, created: !existed, hosts: hostRows(true), environments: environmentRows(true) });
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
const envNameMatch = path.match(/^\/api\/environments\/([^/]+)$/);
|
|
544
|
+
if (envNameMatch && req.method === "DELETE") {
|
|
545
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
546
|
+
const name = decodeURIComponent(envNameMatch[1]);
|
|
547
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
548
|
+
let next;
|
|
549
|
+
try {
|
|
550
|
+
next = removeEnvironment(cfg, name, dir);
|
|
551
|
+
} catch (e) {
|
|
552
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
553
|
+
}
|
|
554
|
+
cfg.environments = next.environments;
|
|
555
|
+
envs.replaceConfig(cfg.hosts, next.environments);
|
|
556
|
+
const orphanConversations = index.all().filter((c) => c.env === name).length;
|
|
557
|
+
envStatus.delete(name);
|
|
558
|
+
probeSchedule.delete(name);
|
|
559
|
+
pushEnvs();
|
|
560
|
+
return json(res, 200, { ok: true, name, orphanConversations, environments: environmentRows(true) });
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const envTrustMatch = path.match(/^\/api\/environments\/([^/]+)\/trust$/);
|
|
564
|
+
if (envTrustMatch && req.method === "POST") {
|
|
565
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
566
|
+
const name = decodeURIComponent(envTrustMatch[1]);
|
|
567
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
568
|
+
const resolved = resolveEnvTarget(name, cfg, dir);
|
|
569
|
+
if (resolved.hostCfg.type !== "ssh") return json(res, 400, { error: `${name} 属于 local 主机,不需要信任 host key` });
|
|
570
|
+
const body = await readBody(req);
|
|
571
|
+
try {
|
|
572
|
+
if (body.reset === true) {
|
|
573
|
+
await withTimeout(envs.forgetTrust(resolved.hostName), 10_000, `重置 ${name} 的 known_hosts`);
|
|
574
|
+
if (cfg.ssh?.autoTrust !== false) {
|
|
575
|
+
for (const [envName, e] of Object.entries(cfg.environments ?? {})) {
|
|
576
|
+
if (e?.host === resolved.hostName) void probeEnv(envName);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return json(res, 200, { ok: true, reset: true, accepted: false });
|
|
580
|
+
}
|
|
581
|
+
if (!Array.isArray(body.lines) || body.lines.length === 0) {
|
|
582
|
+
if (body.force !== true && isHostTrusted(resolved.target)) {
|
|
583
|
+
return json(res, 200, { ok: true, accepted: true });
|
|
584
|
+
}
|
|
585
|
+
const scan = await withTimeout(envs.scanTrust(resolved.hostName), remoteOpTimeoutMs, `扫描 ${name} 的 host key`);
|
|
586
|
+
return json(res, 200, { ok: true, accepted: false, ...scan });
|
|
587
|
+
}
|
|
588
|
+
await withTimeout(envs.acceptTrust(resolved.hostName, body.lines.map(String)), 10_000, `写入 ${name} 的 known_hosts`);
|
|
589
|
+
for (const [envName, e] of Object.entries(cfg.environments ?? {})) {
|
|
590
|
+
if (e?.host === resolved.hostName) void probeEnv(envName);
|
|
591
|
+
}
|
|
592
|
+
return json(res, 200, { ok: true, accepted: true });
|
|
593
|
+
} catch (e) {
|
|
594
|
+
return json(res, 400, { error: describeError(e) });
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const envDeployMatch = path.match(/^\/api\/environments\/([^/]+)\/deploy$/);
|
|
599
|
+
if (envDeployMatch && req.method === "POST") {
|
|
600
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
601
|
+
const name = decodeURIComponent(envDeployMatch[1]);
|
|
602
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
603
|
+
try {
|
|
604
|
+
const result = await withTimeout(envs.deploy(name), deployTimeoutMs, `部署 ${name} 的 daemon`);
|
|
605
|
+
void probeEnv(name);
|
|
606
|
+
return json(res, 200, { ok: true, ...result });
|
|
607
|
+
} catch (e) {
|
|
608
|
+
return json(res, 400, { error: describeError(e) });
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const envProbeMatch = path.match(/^\/api\/environments\/([^/]+)\/probe$/);
|
|
613
|
+
if (envProbeMatch && req.method === "POST") {
|
|
614
|
+
const name = decodeURIComponent(envProbeMatch[1]);
|
|
615
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
616
|
+
const view = await probeEnv(name);
|
|
617
|
+
return json(res, 200, view);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// ---- 目录与 Skills(Environment -> Workspace) ----
|
|
621
|
+
if (path === "/api/skills/local" && req.method === "GET") {
|
|
622
|
+
return json(res, 200, { skills: listLocalSkills() });
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const envWorkspacesMatch = path.match(/^\/api\/environments\/([^/]+)\/workspaces$/);
|
|
626
|
+
if (envWorkspacesMatch && req.method === "POST") {
|
|
627
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
628
|
+
const name = decodeURIComponent(envWorkspacesMatch[1]);
|
|
629
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
630
|
+
const body = await readBody(req);
|
|
631
|
+
try {
|
|
632
|
+
const next = upsertWorkspace(cfg, name, body, dir);
|
|
633
|
+
cfg.environments = next.environments;
|
|
634
|
+
envs.replaceConfig(cfg.hosts, cfg.environments);
|
|
635
|
+
invalidateAllWorkspaceCaches();
|
|
636
|
+
if (body.applyToOpen === true && (next.workspace.model || next.workspace.thinkingLevel)) {
|
|
637
|
+
const patch = {
|
|
638
|
+
...(next.workspace.model ? { model: next.workspace.model } : {}),
|
|
639
|
+
...(next.workspace.thinkingLevel ? { thinkingLevel: next.workspace.thinkingLevel } : {}),
|
|
640
|
+
};
|
|
641
|
+
for (const c of index.forEnv(name)) {
|
|
642
|
+
const convCwd = normalizeWorkspaceCwd(c.cwd || cfg.environments[name].cwd);
|
|
643
|
+
if (convCwd === next.workspace.cwd) {
|
|
644
|
+
const conv = await harness.conversation(c.conversationId, ctx);
|
|
645
|
+
if (conv) await conv.configure(patch, ctx).catch(() => {});
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return json(res, 200, {
|
|
650
|
+
ok: true,
|
|
651
|
+
workspace: next.workspace,
|
|
652
|
+
workspaces: getEnvWorkspaces(cfg, name),
|
|
653
|
+
environments: environmentRows(true),
|
|
654
|
+
});
|
|
655
|
+
} catch (e) {
|
|
656
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
if (envWorkspacesMatch && req.method === "DELETE") {
|
|
660
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
661
|
+
const name = decodeURIComponent(envWorkspacesMatch[1]);
|
|
662
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
663
|
+
const cwd = url.searchParams.get("cwd") ?? "";
|
|
664
|
+
try {
|
|
665
|
+
const next = removeWorkspace(cfg, name, cwd, dir);
|
|
666
|
+
cfg.environments = next.environments;
|
|
667
|
+
envs.replaceConfig(cfg.hosts, cfg.environments);
|
|
668
|
+
invalidateAllWorkspaceCaches();
|
|
669
|
+
return json(res, 200, {
|
|
670
|
+
ok: true,
|
|
671
|
+
workspaces: getEnvWorkspaces(cfg, name),
|
|
672
|
+
environments: environmentRows(true),
|
|
673
|
+
});
|
|
674
|
+
} catch (e) {
|
|
675
|
+
return json(res, 400, { error: String(e?.message ?? e) });
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const envWsSkillsMatch = path.match(/^\/api\/environments\/([^/]+)\/workspace-skills$/);
|
|
680
|
+
if (envWsSkillsMatch && req.method === "GET") {
|
|
681
|
+
const name = decodeURIComponent(envWsSkillsMatch[1]);
|
|
682
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
683
|
+
const cwd = url.searchParams.get("cwd") ?? cfg.environments[name].cwd ?? "/";
|
|
684
|
+
const force = url.searchParams.get("refresh") === "1";
|
|
685
|
+
let agentsMd = null;
|
|
686
|
+
let remoteSkills = [];
|
|
687
|
+
let remoteError = null;
|
|
688
|
+
try {
|
|
689
|
+
const execEnv = await withTimeout(envs.envAsync(name, cwd), remoteOpTimeoutMs, `连接 ${name}`);
|
|
690
|
+
const remote = await withTimeout(
|
|
691
|
+
discoverRemoteWorkspaceContext(execEnv, cwd, ctx, { force }),
|
|
692
|
+
remoteOpTimeoutMs,
|
|
693
|
+
`扫描 ${name}:${cwd} Skills`,
|
|
694
|
+
);
|
|
695
|
+
agentsMd = remote.agentsMd;
|
|
696
|
+
remoteSkills = remote.skills;
|
|
697
|
+
} catch (e) {
|
|
698
|
+
remoteError = describeError(e);
|
|
699
|
+
}
|
|
700
|
+
return json(res, 200, {
|
|
701
|
+
ok: true,
|
|
702
|
+
cwd: normalizeWorkspaceCwd(cwd),
|
|
703
|
+
agentsMd,
|
|
704
|
+
remoteSkills,
|
|
705
|
+
remoteError,
|
|
706
|
+
localSkills: listLocalSkills(),
|
|
707
|
+
workspace: resolveWorkspaceFor(cfg, name, cwd),
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
if (envWsSkillsMatch && req.method === "DELETE") {
|
|
711
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
712
|
+
const name = decodeURIComponent(envWsSkillsMatch[1]);
|
|
713
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
714
|
+
const cwd = url.searchParams.get("cwd") ?? cfg.environments[name].cwd ?? "/";
|
|
715
|
+
const skill = url.searchParams.get("skill") ?? "";
|
|
716
|
+
try {
|
|
717
|
+
const execEnv = await withTimeout(envs.envAsync(name, cwd), remoteOpTimeoutMs, `连接 ${name}`);
|
|
718
|
+
const result = await withTimeout(removeRemoteSkill(execEnv, cwd, skill, ctx), remoteOpTimeoutMs, `移除 Skill ${skill}`);
|
|
719
|
+
invalidateWorkspaceCache(execEnv.id, cwd);
|
|
720
|
+
return json(res, 200, result);
|
|
721
|
+
} catch (e) {
|
|
722
|
+
return json(res, 400, { error: describeError(e) });
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const envWsInstallMatch = path.match(/^\/api\/environments\/([^/]+)\/workspace-skills\/install$/);
|
|
727
|
+
if (envWsInstallMatch && req.method === "POST") {
|
|
728
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
729
|
+
const name = decodeURIComponent(envWsInstallMatch[1]);
|
|
730
|
+
if (!cfg.environments?.[name]) return json(res, 404, { error: `未知环境: ${name}` });
|
|
731
|
+
const body = await readBody(req);
|
|
732
|
+
const cwd = body.cwd ?? cfg.environments[name].cwd ?? "/";
|
|
733
|
+
try {
|
|
734
|
+
const execEnv = await withTimeout(envs.envAsync(name, cwd), remoteOpTimeoutMs, `连接 ${name}`);
|
|
735
|
+
const result = await withTimeout(
|
|
736
|
+
installSkillToWorkspace(execEnv, cwd, {
|
|
737
|
+
name: body.name,
|
|
738
|
+
fromLocal: body.fromLocal,
|
|
739
|
+
content: body.content,
|
|
740
|
+
}, ctx),
|
|
741
|
+
remoteOpTimeoutMs,
|
|
742
|
+
`安装 Skill 到 ${name}:${cwd}`,
|
|
743
|
+
);
|
|
744
|
+
invalidateWorkspaceCache(execEnv.id, cwd);
|
|
745
|
+
return json(res, 200, result);
|
|
746
|
+
} catch (e) {
|
|
747
|
+
return json(res, 400, { error: describeError(e) });
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// ---- 会话 ----
|
|
752
|
+
if (path === "/api/conversations" && req.method === "POST") {
|
|
753
|
+
const body = await readBody(req);
|
|
754
|
+
const envName = body.env;
|
|
755
|
+
if (!cfg.environments?.[envName]) return json(res, 400, { error: `未知环境: ${envName}` });
|
|
756
|
+
const cwd = body.cwd ?? cfg.environments[envName].cwd;
|
|
757
|
+
const ws = resolveWorkspaceFor(cfg, envName, cwd);
|
|
758
|
+
const requestedModel = body.model?.provider && body.model?.modelId
|
|
759
|
+
? body.model
|
|
760
|
+
: (ws?.model?.provider && ws?.model?.modelId ? ws.model : await resolveDefaultModel(currentModels, cfg));
|
|
761
|
+
const thinkingLevel = body.thinkingLevel ?? ws?.thinkingLevel;
|
|
762
|
+
const created = await deps.createConversationFn({ harness, index, ctx }, {
|
|
763
|
+
env: envName,
|
|
764
|
+
cwd,
|
|
765
|
+
model: requestedModel,
|
|
766
|
+
thinkingLevel,
|
|
767
|
+
title: body.title ?? `${envName}`,
|
|
768
|
+
});
|
|
769
|
+
void probeEnv(envName);
|
|
770
|
+
return json(res, 200, {
|
|
771
|
+
conversationId: Number(created.id),
|
|
772
|
+
env: envName,
|
|
773
|
+
cwd: cwd ?? null,
|
|
774
|
+
title: body.title ?? `${envName}`,
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
const convItemMatch = path.match(/^\/api\/conversations\/(\d+)$/);
|
|
779
|
+
if (convItemMatch && req.method === "PATCH") {
|
|
780
|
+
const convId = Number(convItemMatch[1]);
|
|
781
|
+
const body = await readBody(req);
|
|
782
|
+
const patch = {};
|
|
783
|
+
if (typeof body.title === "string") patch.title = body.title.trim();
|
|
784
|
+
if (typeof body.archived === "boolean") patch.archived = body.archived;
|
|
785
|
+
const updated = await index.patch(convId, patch);
|
|
786
|
+
if (!updated) return json(res, 404, { error: `会话 ${convId} 不存在` });
|
|
787
|
+
return json(res, 200, { ok: true, conversationId: convId, ...updated });
|
|
788
|
+
}
|
|
789
|
+
if (convItemMatch && req.method === "DELETE") {
|
|
790
|
+
const convId = Number(convItemMatch[1]);
|
|
791
|
+
const conv = await harness.conversation(convId, ctx);
|
|
792
|
+
if (conv) await conv.abort(ctx).catch(() => {});
|
|
793
|
+
const ok = await index.delete(convId);
|
|
794
|
+
if (!ok) return json(res, 404, { error: `会话 ${convId} 不存在` });
|
|
795
|
+
return json(res, 200, { ok: true, conversationId: convId });
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const entriesMatch = path.match(/^\/api\/conversations\/(\d+)\/entries$/);
|
|
799
|
+
if (entriesMatch && req.method === "GET") {
|
|
800
|
+
const convId = Number(entriesMatch[1]);
|
|
801
|
+
const conv = await harness.conversation(convId, ctx);
|
|
802
|
+
if (!conv) return json(res, 404, { error: `会话 ${convId} 不存在` });
|
|
803
|
+
const before = url.searchParams.get("before");
|
|
804
|
+
const limit = Math.min(200, Math.max(1, Number(url.searchParams.get("limit") ?? 50)));
|
|
805
|
+
const query = before ? { maxEntryId: Number(before) } : {};
|
|
806
|
+
const page = await conv.entries(query, limit, undefined, ctx);
|
|
807
|
+
const entries = projectEntries(page.items ?? []);
|
|
808
|
+
return json(res, 200, {
|
|
809
|
+
ok: true,
|
|
810
|
+
entries,
|
|
811
|
+
hasMore: Boolean(page.next),
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const msgMatch = path.match(/^\/api\/conversations\/(\d+)\/messages$/);
|
|
816
|
+
if (msgMatch && req.method === "POST") {
|
|
817
|
+
const convId = Number(msgMatch[1]);
|
|
818
|
+
const conv = await harness.conversation(convId, ctx);
|
|
819
|
+
if (!conv) return json(res, 404, { error: `会话 ${convId} 不存在` });
|
|
820
|
+
const body = await readBody(req);
|
|
821
|
+
if (!body.content || typeof body.content !== "string") return json(res, 400, { error: "content 必填" });
|
|
822
|
+
// 自动起名:标题还是默认的环境名(或 ask-xxx)时,用第一条消息的首行当标题,侧栏才可读
|
|
823
|
+
let autoTitle;
|
|
824
|
+
const rec = index.get(convId);
|
|
825
|
+
if (rec && isDefaultTitle(rec)) {
|
|
826
|
+
const first = body.content.split("\n").map((l) => l.trim()).find(Boolean);
|
|
827
|
+
if (first) {
|
|
828
|
+
autoTitle = first.length > 40 ? `${first.slice(0, 40)}…` : first;
|
|
829
|
+
await index.patch(convId, { title: autoTitle });
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
const sub = await conv.submit({ type: "input", content: body.content }, ctx);
|
|
833
|
+
return json(res, 202, { submissionId: Number(sub.id), conversationId: convId, ...(autoTitle ? { title: autoTitle } : {}) });
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
const abortMatch = path.match(/^\/api\/conversations\/(\d+)\/abort$/);
|
|
837
|
+
if (abortMatch && req.method === "POST") {
|
|
838
|
+
const convId = Number(abortMatch[1]);
|
|
839
|
+
const conv = await harness.conversation(convId, ctx);
|
|
840
|
+
if (!conv) return json(res, 404, { error: `会话 ${convId} 不存在` });
|
|
841
|
+
await conv.abort(ctx);
|
|
842
|
+
return json(res, 200, { ok: true });
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
const opMatch = path.match(/^\/api\/conversations\/(\d+)\/(compact|reset|fork|configure|exec)$/);
|
|
846
|
+
if (opMatch && req.method === "POST") {
|
|
847
|
+
const convId = Number(opMatch[1]);
|
|
848
|
+
const op = opMatch[2];
|
|
849
|
+
const conv = await harness.conversation(convId, ctx);
|
|
850
|
+
if (!conv) return json(res, 404, { error: `会话 ${convId} 不存在` });
|
|
851
|
+
const body = await readBody(req);
|
|
852
|
+
|
|
853
|
+
if (op === "compact") {
|
|
854
|
+
const taskId = await conv.compact(typeof body.instructions === "string" ? body.instructions : undefined, ctx);
|
|
855
|
+
return json(res, 202, { ok: true, taskId: Number(taskId) });
|
|
856
|
+
}
|
|
857
|
+
if (op === "reset") {
|
|
858
|
+
await conv.reset(typeof body.handoff === "string" ? body.handoff : undefined, ctx);
|
|
859
|
+
return json(res, 200, { ok: true });
|
|
860
|
+
}
|
|
861
|
+
if (op === "fork") {
|
|
862
|
+
const rec = index.get(convId);
|
|
863
|
+
let at = body.atEntryId === undefined ? undefined : Number(body.atEntryId);
|
|
864
|
+
if (at === undefined) {
|
|
865
|
+
const page = await conv.entries({}, 200, undefined, ctx);
|
|
866
|
+
const ids = (page.items ?? []).map((e) => Number(e.id)).filter(Number.isFinite);
|
|
867
|
+
if (ids.length === 0) return json(res, 400, { error: "会话还没有任何 entry,无法 fork" });
|
|
868
|
+
at = Math.max(...ids);
|
|
869
|
+
}
|
|
870
|
+
const forked = await conv.fork(at, { ownership: { kind: "ownerless" } }, ctx);
|
|
871
|
+
if (rec) {
|
|
872
|
+
await index.set(Number(forked.id), {
|
|
873
|
+
...rec,
|
|
874
|
+
title: `${rec.title ?? rec.env} (fork)`,
|
|
875
|
+
createdAt: Date.now(),
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
return json(res, 200, { ok: true, conversationId: Number(forked.id), env: rec?.env ?? null });
|
|
879
|
+
}
|
|
880
|
+
if (op === "configure") {
|
|
881
|
+
const change = {};
|
|
882
|
+
if (body.modelId !== undefined) {
|
|
883
|
+
const provider = body.provider ?? cfg.defaultModel?.provider;
|
|
884
|
+
if (!provider) return json(res, 400, { error: "切换模型需要 provider" });
|
|
885
|
+
change.model = { provider, modelId: body.modelId };
|
|
886
|
+
// 把最近选中的模型也记住为默认(loopback 下)
|
|
887
|
+
if (isLoopback(req) && body.setAsDefault) {
|
|
888
|
+
const next = setDefaultModel(cfg, change.model, dir);
|
|
889
|
+
cfg.defaultModel = next.defaultModel;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
if (body.thinkingLevel !== undefined) change.thinkingLevel = body.thinkingLevel;
|
|
893
|
+
if (body.cwd !== undefined) change.cwd = body.cwd;
|
|
894
|
+
if (body.instructions !== undefined) change.instructions = body.instructions;
|
|
895
|
+
if (body.maxTurns !== undefined) change.maxTurns = Number(body.maxTurns);
|
|
896
|
+
if (Object.keys(change).length === 0) return json(res, 400, { error: "没有任何要修改的字段" });
|
|
897
|
+
await conv.configure(change, ctx);
|
|
898
|
+
// 🔴 /cd 同步更新 DurableConvIndex,保证文件树、/exec 与面板头同步
|
|
899
|
+
if (body.cwd !== undefined) await index.patch(convId, { cwd: body.cwd });
|
|
900
|
+
return json(res, 200, { ok: true, changed: Object.keys(change) });
|
|
901
|
+
}
|
|
902
|
+
if (op === "exec") {
|
|
903
|
+
const rec = index.get(convId);
|
|
904
|
+
if (!rec || !cfg.environments?.[rec.env]) return json(res, 400, { error: "该会话没有绑定有效环境" });
|
|
905
|
+
const command = body.command;
|
|
906
|
+
if (typeof command !== "string" || !command.trim()) return json(res, 400, { error: "command 必填" });
|
|
907
|
+
const includeInContext = body.includeInContext === true;
|
|
908
|
+
const execId = typeof body.execId === "string" && body.execId.trim()
|
|
909
|
+
? body.execId.trim()
|
|
910
|
+
: `exec-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
911
|
+
const cwd = body.cwd ?? rec.cwd ?? cfg.environments[rec.env]?.cwd ?? "/";
|
|
912
|
+
const env = await envs.envAsync(rec.env, cwd);
|
|
913
|
+
const startedAt = Date.now();
|
|
914
|
+
let out = "";
|
|
915
|
+
const r = await env.exec(command, {
|
|
916
|
+
cwd,
|
|
917
|
+
onOutput: (t) => { out += t; },
|
|
918
|
+
timeout: Number(body.timeoutSec) || 60,
|
|
919
|
+
spill: { afterBytes: 2 * 1024 * 1024, afterLines: 20_000 },
|
|
920
|
+
}, ctx);
|
|
921
|
+
const durationMs = Date.now() - startedAt;
|
|
922
|
+
if (!r.ok) noteEnvFailure(rec.env, r.error ?? r);
|
|
923
|
+
const projected = projectExec(r, out, command);
|
|
924
|
+
|
|
925
|
+
const clippedTranscript = clipTail(projected.output, 128 * 1024, 4000);
|
|
926
|
+
const execData = {
|
|
927
|
+
execId,
|
|
928
|
+
command: command.trim(),
|
|
929
|
+
cwd,
|
|
930
|
+
ok: projected.ok,
|
|
931
|
+
exitCode: projected.exitCode ?? null,
|
|
932
|
+
output: clippedTranscript.text,
|
|
933
|
+
truncated: Boolean(projected.truncated || clippedTranscript.clipped),
|
|
934
|
+
...(projected.spillPath ? { spillPath: projected.spillPath } : {}),
|
|
935
|
+
...(projected.error ? { error: projected.error } : {}),
|
|
936
|
+
includeInContext,
|
|
937
|
+
at: startedAt,
|
|
938
|
+
durationMs,
|
|
939
|
+
};
|
|
940
|
+
|
|
941
|
+
const entry = includeInContext
|
|
942
|
+
? {
|
|
943
|
+
kind: "foreman.exec",
|
|
944
|
+
data: execData,
|
|
945
|
+
model: [{
|
|
946
|
+
role: "user",
|
|
947
|
+
content: formatExecForModel({ ...execData, rawOutput: projected.output }),
|
|
948
|
+
timestamp: startedAt,
|
|
949
|
+
}],
|
|
950
|
+
}
|
|
951
|
+
: {
|
|
952
|
+
kind: "foreman.exec",
|
|
953
|
+
data: execData,
|
|
954
|
+
};
|
|
955
|
+
|
|
956
|
+
const sub = await conv.submit({ type: "write", entry }, ctx);
|
|
957
|
+
const subRec = await sub.status(ctx);
|
|
958
|
+
return json(res, 200, {
|
|
959
|
+
...projected,
|
|
960
|
+
cwd,
|
|
961
|
+
durationMs,
|
|
962
|
+
at: startedAt,
|
|
963
|
+
execId,
|
|
964
|
+
includeInContext,
|
|
965
|
+
entryId: subRec.entry !== undefined ? Number(subRec.entry) : null,
|
|
966
|
+
queued: subRec.status === "queued",
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// ---- 文件系统(全部 4 种环境统一支持)----
|
|
972
|
+
const listMatch = path.match(/^\/api\/fs\/([^/]+)\/list$/);
|
|
973
|
+
if (listMatch && req.method === "GET") {
|
|
974
|
+
const envName = decodeURIComponent(listMatch[1]);
|
|
975
|
+
if (!cfg.environments?.[envName]) return json(res, 404, { error: `未知环境: ${envName}` });
|
|
976
|
+
const target = url.searchParams.get("path") ?? cfg.environments[envName].cwd ?? "/";
|
|
977
|
+
const env = await envs.envAsync(envName, target);
|
|
978
|
+
const r = await env.listDir(target, ctx);
|
|
979
|
+
if (!r.ok) {
|
|
980
|
+
noteEnvFailure(envName, r.error ?? "listDir 失败");
|
|
981
|
+
return json(res, 200, { ok: false, error: r.error?.code ?? r.error?.message ?? "listDir 失败" });
|
|
982
|
+
}
|
|
983
|
+
return json(res, 200, {
|
|
984
|
+
ok: true,
|
|
985
|
+
path: target,
|
|
986
|
+
entries: r.value.map(projectFileInfo).sort((a, b) => (b.isDir - a.isDir) || a.name.localeCompare(b.name)),
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const readMatch = path.match(/^\/api\/fs\/([^/]+)\/read$/);
|
|
991
|
+
if (readMatch && req.method === "GET") {
|
|
992
|
+
const envName = decodeURIComponent(readMatch[1]);
|
|
993
|
+
if (!cfg.environments?.[envName]) return json(res, 404, { error: `未知环境: ${envName}` });
|
|
994
|
+
const target = url.searchParams.get("path");
|
|
995
|
+
if (!target) return json(res, 400, { error: "path 必填" });
|
|
996
|
+
const cwd = cfg.environments[envName].cwd ?? "/";
|
|
997
|
+
const env = await envs.envAsync(envName, cwd);
|
|
998
|
+
|
|
999
|
+
if (url.searchParams.get("raw") === "1") {
|
|
1000
|
+
const info = await env.fileInfo(target, ctx);
|
|
1001
|
+
if (!info.ok) {
|
|
1002
|
+
noteEnvFailure(envName, info.error ?? "读取失败");
|
|
1003
|
+
return json(res, 200, { ok: false, error: info.error?.message ?? info.error?.code ?? "读取失败" });
|
|
1004
|
+
}
|
|
1005
|
+
if (info.value?.kind === "directory" || info.value?.type === "directory" || info.value?.isDir) {
|
|
1006
|
+
return json(res, 200, { ok: false, error: "不能编辑目录" });
|
|
1007
|
+
}
|
|
1008
|
+
if ((info.value?.size ?? 0) > MAX_EDIT_BYTES) {
|
|
1009
|
+
return json(res, 200, {
|
|
1010
|
+
ok: false,
|
|
1011
|
+
tooLarge: true,
|
|
1012
|
+
size: info.value.size,
|
|
1013
|
+
error: `文件超过 ${Math.round(MAX_EDIT_BYTES / 1024)} KB 编辑上限,保持只读`,
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
const binRes = await env.readBinaryFile(target, ctx);
|
|
1017
|
+
if (!binRes.ok) {
|
|
1018
|
+
noteEnvFailure(envName, binRes.error ?? "读取失败");
|
|
1019
|
+
return json(res, 200, { ok: false, error: binRes.error?.message ?? binRes.error?.code ?? "读取失败" });
|
|
1020
|
+
}
|
|
1021
|
+
const buf = Buffer.from(binRes.value);
|
|
1022
|
+
if (buf.byteLength > MAX_EDIT_BYTES) {
|
|
1023
|
+
return json(res, 200, {
|
|
1024
|
+
ok: false,
|
|
1025
|
+
tooLarge: true,
|
|
1026
|
+
size: buf.byteLength,
|
|
1027
|
+
error: `文件超过 ${Math.round(MAX_EDIT_BYTES / 1024)} KB 编辑上限,保持只读`,
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
const sampleLen = Math.min(buf.length, 8192);
|
|
1031
|
+
for (let i = 0; i < sampleLen; i++) {
|
|
1032
|
+
if (buf[i] === 0) {
|
|
1033
|
+
return json(res, 200, { ok: false, binary: true, error: "检测到二进制文件,暂不支持编辑" });
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
const sha256 = createHash("sha256").update(buf).digest("hex");
|
|
1037
|
+
return json(res, 200, {
|
|
1038
|
+
ok: true,
|
|
1039
|
+
path: target,
|
|
1040
|
+
content: buf.toString("utf8"),
|
|
1041
|
+
sha256,
|
|
1042
|
+
size: buf.byteLength,
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
const maxLines = Number(url.searchParams.get("maxLines") ?? 2000);
|
|
1047
|
+
const r = await env.readTextLines(target, { maxLines }, ctx);
|
|
1048
|
+
if (!r.ok) {
|
|
1049
|
+
noteEnvFailure(envName, r.error ?? "读取失败");
|
|
1050
|
+
return json(res, 200, { ok: false, error: r.error?.code ?? r.error?.message ?? "读取失败" });
|
|
1051
|
+
}
|
|
1052
|
+
return json(res, 200, { ok: true, path: target, lines: r.value, truncated: r.value.length >= maxLines });
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
const writeMatch = path.match(/^\/api\/fs\/([^/]+)\/write$/);
|
|
1056
|
+
if (writeMatch && req.method === "POST") {
|
|
1057
|
+
if (!isLoopback(req)) return denyRemote(res);
|
|
1058
|
+
const envName = decodeURIComponent(writeMatch[1]);
|
|
1059
|
+
if (!cfg.environments?.[envName]) return json(res, 404, { error: `未知环境: ${envName}` });
|
|
1060
|
+
const body = await readBody(req);
|
|
1061
|
+
const target = String(body.path ?? "").trim();
|
|
1062
|
+
if (!target) return json(res, 400, { error: "path 必填" });
|
|
1063
|
+
if (typeof body.content !== "string") return json(res, 400, { error: "content 必须是字符串" });
|
|
1064
|
+
const writeBuf = Buffer.from(body.content, "utf8");
|
|
1065
|
+
if (writeBuf.byteLength > MAX_EDIT_BYTES) {
|
|
1066
|
+
return json(res, 400, { error: `文件内容超过 ${Math.round(MAX_EDIT_BYTES / 1024)} KB 上限` });
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
const cwd = cfg.environments[envName].cwd ?? "/";
|
|
1070
|
+
const env = await envs.envAsync(envName, cwd);
|
|
1071
|
+
|
|
1072
|
+
if (body.createOnly === true) {
|
|
1073
|
+
const ex = await env.exists(target, ctx);
|
|
1074
|
+
if (ex.ok && ex.value) {
|
|
1075
|
+
return json(res, 409, { error: "文件已存在,请换一个路径或直接打开编辑", exists: true });
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
if (body.createParents === true || body.createOnly === true) {
|
|
1080
|
+
const parent = dirname(target);
|
|
1081
|
+
if (parent && parent !== "." && parent !== "/" && parent !== target) {
|
|
1082
|
+
const mk = await env.createDir(parent, { recursive: true }, ctx);
|
|
1083
|
+
if (!mk.ok) {
|
|
1084
|
+
noteEnvFailure(envName, mk.error ?? "创建父目录失败");
|
|
1085
|
+
return json(res, 400, { error: mk.error?.message ?? mk.error?.code ?? "创建父目录失败" });
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
if (typeof body.expectedSha256 === "string" && body.expectedSha256) {
|
|
1091
|
+
const cur = await env.readBinaryFile(target, ctx);
|
|
1092
|
+
if (cur.ok) {
|
|
1093
|
+
const curSha = createHash("sha256").update(Buffer.from(cur.value)).digest("hex");
|
|
1094
|
+
if (curSha !== body.expectedSha256) {
|
|
1095
|
+
return json(res, 409, {
|
|
1096
|
+
error: "文件在打开后已被外部修改",
|
|
1097
|
+
conflict: true,
|
|
1098
|
+
currentSha256: curSha,
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
const wr = await env.writeFile(target, body.content, ctx);
|
|
1105
|
+
if (!wr.ok) {
|
|
1106
|
+
noteEnvFailure(envName, wr.error ?? "写入失败");
|
|
1107
|
+
return json(res, 400, { error: wr.error?.message ?? wr.error?.code ?? "写入失败" });
|
|
1108
|
+
}
|
|
1109
|
+
const sha256 = createHash("sha256").update(writeBuf).digest("hex");
|
|
1110
|
+
return json(res, 200, { ok: true, path: target, sha256, size: writeBuf.byteLength });
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// ---- 主机上的容器列表(添加环境时校验容器名;只读,限本机) ----
|
|
1114
|
+
const containersMatch = path.match(/^\/api\/hosts\/([^/]+)\/containers$/);
|
|
1115
|
+
if (containersMatch && req.method === "GET") {
|
|
1116
|
+
const hostName = decodeURIComponent(containersMatch[1]);
|
|
1117
|
+
if (hostName !== "local" && !cfg.hosts?.[hostName]) return json(res, 404, { error: `未知主机: ${hostName}` });
|
|
1118
|
+
try {
|
|
1119
|
+
const containers = await envs.listContainers(hostName);
|
|
1120
|
+
return json(res, 200, { containers });
|
|
1121
|
+
} catch (e) {
|
|
1122
|
+
return json(res, 502, { error: String(e?.message ?? e) });
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// ---- git ----
|
|
1127
|
+
const gitMatch = path.match(/^\/api\/git\/([^/]+)\/(status|diff)$/);
|
|
1128
|
+
if (gitMatch && req.method === "GET") {
|
|
1129
|
+
const envName = decodeURIComponent(gitMatch[1]);
|
|
1130
|
+
const what = gitMatch[2];
|
|
1131
|
+
if (!cfg.environments?.[envName]) return json(res, 404, { error: `未知环境: ${envName}` });
|
|
1132
|
+
const cwd = url.searchParams.get("cwd") ?? cfg.environments[envName].cwd;
|
|
1133
|
+
if (!cwd) return json(res, 400, { error: "该环境没有配置 cwd" });
|
|
1134
|
+
const env = await envs.envAsync(envName, cwd);
|
|
1135
|
+
const modeParam = url.searchParams.get("mode");
|
|
1136
|
+
const mode = modeParam === "patch" || modeParam === "numstat" ? modeParam : "stat";
|
|
1137
|
+
const file = url.searchParams.get("file");
|
|
1138
|
+
const argv = what === "status"
|
|
1139
|
+
? ["git", "status", "--porcelain=v1", "-b"]
|
|
1140
|
+
: ["git", "--no-pager", "diff", "--no-color",
|
|
1141
|
+
...(mode === "patch" ? [] : mode === "numstat" ? ["--numstat"] : ["--stat"]),
|
|
1142
|
+
...(file ? ["--", file] : [])];
|
|
1143
|
+
let out = "";
|
|
1144
|
+
const r = await env.exec(argv, {
|
|
1145
|
+
cwd,
|
|
1146
|
+
onOutput: (t) => { out += t; },
|
|
1147
|
+
timeout: 30,
|
|
1148
|
+
spill: { afterBytes: 2 * 1024 * 1024, afterLines: 20_000 },
|
|
1149
|
+
}, ctx);
|
|
1150
|
+
const view = projectExec(r, out, argv);
|
|
1151
|
+
if (!r.ok) noteEnvFailure(envName, r.error ?? view.error ?? "git 失败");
|
|
1152
|
+
return json(res, 200, { ...view, output: truncate(view.output, 512 * 1024) });
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// ---- 静态资源 ----
|
|
1156
|
+
if (req.method === "GET" && webRoot) return serveStatic(res, webRoot, path);
|
|
1157
|
+
|
|
1158
|
+
json(res, 404, { error: `没有这个端点: ${req.method} ${path}` });
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
const message = String(error?.message ?? error);
|
|
1161
|
+
if (!res.headersSent) json(res, 500, { error: message });
|
|
1162
|
+
else { try { res.end(); } catch { /* 已断开 */ } }
|
|
1163
|
+
console.error(`[server] ${req.method} ${path} 失败: ${message}`);
|
|
1164
|
+
}
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1167
|
+
// WebSocket 升级与多路复用分发
|
|
1168
|
+
server.on("upgrade", (req, socket, head) => {
|
|
1169
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
1170
|
+
if (url.pathname !== "/api/ws") {
|
|
1171
|
+
socket.destroy();
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
1175
|
+
wss.emit("connection", ws, req);
|
|
1176
|
+
});
|
|
1177
|
+
});
|
|
1178
|
+
|
|
1179
|
+
wss.on("connection", (ws) => {
|
|
1180
|
+
ws.__subs = new Map();
|
|
1181
|
+
ws.__alive = true;
|
|
1182
|
+
wsClients.add(ws);
|
|
1183
|
+
sendWs(ws, { type: "connected", at: Date.now() });
|
|
1184
|
+
|
|
1185
|
+
ws.on("pong", () => { ws.__alive = true; });
|
|
1186
|
+
ws.on("message", (raw) => {
|
|
1187
|
+
let msg;
|
|
1188
|
+
try { msg = JSON.parse(String(raw)); } catch { return; }
|
|
1189
|
+
if (msg.type === "ping") {
|
|
1190
|
+
sendWs(ws, { type: "pong", at: Date.now() });
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
if (msg.type === "sub" && typeof msg.channel === "string") {
|
|
1194
|
+
void subscribeWsChannel(ws, msg.channel);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (msg.type === "unsub" && typeof msg.channel === "string") {
|
|
1198
|
+
const off = ws.__subs.get(msg.channel);
|
|
1199
|
+
if (off) {
|
|
1200
|
+
try { off(); } catch { /* ignore */ }
|
|
1201
|
+
ws.__subs.delete(msg.channel);
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
});
|
|
1205
|
+
|
|
1206
|
+
ws.on("close", () => {
|
|
1207
|
+
wsClients.delete(ws);
|
|
1208
|
+
for (const off of ws.__subs.values()) {
|
|
1209
|
+
try { off(); } catch { /* ignore */ }
|
|
1210
|
+
}
|
|
1211
|
+
ws.__subs.clear();
|
|
1212
|
+
});
|
|
1213
|
+
});
|
|
1214
|
+
|
|
1215
|
+
const wsBeat = setInterval(() => {
|
|
1216
|
+
for (const ws of wsClients) {
|
|
1217
|
+
if (ws.__alive === false) {
|
|
1218
|
+
try { ws.terminate(); } catch { /* ignore */ }
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
ws.__alive = false;
|
|
1222
|
+
try { ws.ping(); } catch { /* ignore */ }
|
|
1223
|
+
}
|
|
1224
|
+
}, WS_HEARTBEAT_MS);
|
|
1225
|
+
wsBeat.unref?.();
|
|
1226
|
+
|
|
1227
|
+
const envProbeTimer = setInterval(() => {
|
|
1228
|
+
if (hasEnvsSubscriber()) triggerDueProbes(false);
|
|
1229
|
+
}, Math.max(2000, Math.min(probeIntervalMs, 15_000)));
|
|
1230
|
+
envProbeTimer.unref?.();
|
|
1231
|
+
|
|
1232
|
+
await new Promise((listen) => server.listen(port, host, listen));
|
|
1233
|
+
const address = server.address();
|
|
1234
|
+
const origin = `http://${address.address}:${address.port}`;
|
|
1235
|
+
|
|
1236
|
+
return {
|
|
1237
|
+
server,
|
|
1238
|
+
wss,
|
|
1239
|
+
hub,
|
|
1240
|
+
origin,
|
|
1241
|
+
port: address.port,
|
|
1242
|
+
refreshEnvs: async () => {
|
|
1243
|
+
await Promise.all(Object.keys(cfg.environments ?? {}).map((n) => probeEnv(n)));
|
|
1244
|
+
return envSnapshot();
|
|
1245
|
+
},
|
|
1246
|
+
async close() {
|
|
1247
|
+
clearInterval(envProbeTimer);
|
|
1248
|
+
clearInterval(wsBeat);
|
|
1249
|
+
for (const ws of wsClients) {
|
|
1250
|
+
try { ws.close(); } catch { /* ignore */ }
|
|
1251
|
+
}
|
|
1252
|
+
wsClients.clear();
|
|
1253
|
+
await hub.closeAll();
|
|
1254
|
+
await new Promise((r) => wss.close(r));
|
|
1255
|
+
await new Promise((r) => server.close(r));
|
|
1256
|
+
},
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
function json(res, status, body) {
|
|
1261
|
+
const payload = JSON.stringify(body);
|
|
1262
|
+
res.writeHead(status, {
|
|
1263
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
1264
|
+
"Content-Length": Buffer.byteLength(payload),
|
|
1265
|
+
"Cache-Control": "no-store",
|
|
1266
|
+
});
|
|
1267
|
+
res.end(payload);
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
function readBody(req) {
|
|
1271
|
+
return new Promise((resolveBody, reject) => {
|
|
1272
|
+
let size = 0;
|
|
1273
|
+
const chunks = [];
|
|
1274
|
+
req.on("data", (c) => {
|
|
1275
|
+
size += c.length;
|
|
1276
|
+
if (size > MAX_BODY_BYTES) { reject(new Error("请求体过大")); req.destroy(); return; }
|
|
1277
|
+
chunks.push(c);
|
|
1278
|
+
});
|
|
1279
|
+
req.on("end", () => {
|
|
1280
|
+
if (chunks.length === 0) return resolveBody({});
|
|
1281
|
+
try { resolveBody(JSON.parse(Buffer.concat(chunks).toString("utf8"))); }
|
|
1282
|
+
catch (e) { reject(new Error(`请求体不是合法 JSON: ${e.message}`)); }
|
|
1283
|
+
});
|
|
1284
|
+
req.on("error", reject);
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
function serveStatic(res, root, urlPath) {
|
|
1289
|
+
const rel = urlPath === "/" ? "index.html" : urlPath.replace(/^\/+/, "");
|
|
1290
|
+
const full = resolve(root, normalize(rel));
|
|
1291
|
+
if (!full.startsWith(resolve(root) + sep) && full !== resolve(root)) {
|
|
1292
|
+
return json(res, 403, { error: "禁止访问" });
|
|
1293
|
+
}
|
|
1294
|
+
if (!existsSync(full) || !statSync(full).isFile()) {
|
|
1295
|
+
const index = join(root, "index.html");
|
|
1296
|
+
if (existsSync(index) && !urlPath.startsWith("/api/")) {
|
|
1297
|
+
res.writeHead(200, { "Content-Type": MIME[".html"], "Cache-Control": "no-store" });
|
|
1298
|
+
return res.end(readFileSync(index));
|
|
1299
|
+
}
|
|
1300
|
+
return json(res, 404, { error: `未找到 ${urlPath}` });
|
|
1301
|
+
}
|
|
1302
|
+
const type = MIME[extname(full).toLowerCase()] ?? "application/octet-stream";
|
|
1303
|
+
const isAsset = urlPath.startsWith("/assets/");
|
|
1304
|
+
res.writeHead(200, {
|
|
1305
|
+
"Content-Type": type,
|
|
1306
|
+
"Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-store",
|
|
1307
|
+
});
|
|
1308
|
+
res.end(readFileSync(full));
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
function clipTail(text, maxBytes, maxLines) {
|
|
1312
|
+
const raw = String(text ?? "");
|
|
1313
|
+
if (!raw) return { text: "", clipped: false, omittedLines: 0 };
|
|
1314
|
+
const allLines = raw.split("\n");
|
|
1315
|
+
let lines = allLines;
|
|
1316
|
+
let omittedLines = 0;
|
|
1317
|
+
let clipped = false;
|
|
1318
|
+
if (maxLines && lines.length > maxLines) {
|
|
1319
|
+
omittedLines = lines.length - maxLines;
|
|
1320
|
+
lines = lines.slice(-maxLines);
|
|
1321
|
+
clipped = true;
|
|
1322
|
+
}
|
|
1323
|
+
let out = lines.join("\n");
|
|
1324
|
+
if (maxBytes && Buffer.byteLength(out, "utf8") > maxBytes) {
|
|
1325
|
+
const buf = Buffer.from(out, "utf8");
|
|
1326
|
+
out = buf.subarray(Math.max(0, buf.length - maxBytes)).toString("utf8");
|
|
1327
|
+
const nl = out.indexOf("\n");
|
|
1328
|
+
if (nl >= 0 && nl < out.length - 1) out = out.slice(nl + 1);
|
|
1329
|
+
clipped = true;
|
|
1330
|
+
}
|
|
1331
|
+
return { text: out, clipped, omittedLines };
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
function formatExecForModel({ command, cwd, ok, exitCode, rawOutput, error, truncated }) {
|
|
1335
|
+
const clipped = clipTail(rawOutput, 24 * 1024, 250);
|
|
1336
|
+
const header = `Ran \`${command}\`${cwd ? ` (cwd: ${cwd})` : ""} — exit code ${exitCode ?? (ok ? 0 : "unknown")}`;
|
|
1337
|
+
const notes = [];
|
|
1338
|
+
if (clipped.clipped || truncated) {
|
|
1339
|
+
notes.push(
|
|
1340
|
+
clipped.omittedLines > 0
|
|
1341
|
+
? `(output truncated; showing last lines, ~${clipped.omittedLines} earlier lines omitted)`
|
|
1342
|
+
: "(output truncated to tail)",
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
if (error) notes.push(`Error: ${error}`);
|
|
1346
|
+
const body = clipped.text ? clipped.text : "(no output)";
|
|
1347
|
+
return [header, ...notes, "```", body, "```"].join("\n");
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
export { DEFAULT_PORT, DEFAULT_HOST };
|