@hjd-hitsz/claudex-web 4.1.3 → 4.1.4

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.
@@ -19,6 +19,7 @@ export function createCodexAdapter({
19
19
  version,
20
20
  send,
21
21
  broadcast,
22
+ readSubagentSettings = async () => backend,
22
23
  }) {
23
24
  config = { ...config, upstreamUrl: backend.url, codexHome: backend.dataDir };
24
25
  const questions = new Map();
@@ -51,14 +52,16 @@ export function createCodexAdapter({
51
52
  },
52
53
  });
53
54
  const nativeCall = transport.call;
54
- const sessionParams = (method, params) =>
55
+ const sessionParams = async (method, params) =>
55
56
  subagentModelParams(
56
57
  method,
57
58
  referenceToolParams(method, params, config),
58
- backend,
59
+ ["thread/start", "thread/resume", "thread/fork"].includes(method)
60
+ ? await readSubagentSettings()
61
+ : backend,
59
62
  );
60
- transport.call = (method, params, options) =>
61
- nativeCall(method, sessionParams(method, params), options);
63
+ transport.call = async (method, params, options) =>
64
+ nativeCall(method, await sessionParams(method, params), options);
62
65
  const threadNaming = createThreadNaming({
63
66
  call: transport.call,
64
67
  generate: (params) =>
@@ -138,13 +141,13 @@ export function createCodexAdapter({
138
141
  readTokenUsage: (thread) => readCodexTokenUsage(thread, transport.call),
139
142
  workspaceOwner: "backend",
140
143
  state,
141
- receive(client, message) {
144
+ async receive(client, message) {
142
145
  if (!message.method) return receive(client, message);
143
146
  const { providerId, ...params } = message.params || {};
144
147
  if (providerId) throw new Error("Codex 使用现有账户与模型配置");
145
148
  return receive(client, {
146
149
  ...message,
147
- params: sessionParams(message.method, params),
150
+ params: await sessionParams(message.method, params),
148
151
  });
149
152
  },
150
153
  connect: transport.connect,
@@ -9,7 +9,6 @@ export const loadedThreadMethods = new Set([
9
9
  "turn/start",
10
10
  "thread/compact/start",
11
11
  "review/start",
12
- "thread/goal/get",
13
12
  "thread/goal/set",
14
13
  "thread/goal/clear",
15
14
  "thread/backgroundTerminals/list",
@@ -1,6 +1,7 @@
1
1
  import { resolve, join } from "node:path";
2
2
  import { createStorage } from "./storage.mjs";
3
3
  import { validateNetworkProxy } from "./network-proxy.mjs";
4
+ import { subagentSettings } from "../../../shared/subagent-settings.mjs";
4
5
 
5
6
  export function validateBackend(input, config) {
6
7
  if (!["codex", "claude"].includes(input.id) || input.id !== input.type)
@@ -152,6 +153,11 @@ export function createBackendConfiguration(config) {
152
153
  ...storage,
153
154
  read,
154
155
  save,
156
+ async readSubagentSettings(id) {
157
+ return subagentSettings(
158
+ (await storage.read()).backends.find((b) => b.id === id) || {},
159
+ );
160
+ },
155
161
  async readProviders() {
156
162
  return (await storage.read()).providers;
157
163
  },
@@ -15,6 +15,8 @@ import {
15
15
  validateBackend,
16
16
  } from "./configuration.mjs";
17
17
  import { createProviders } from "./providers.mjs";
18
+ import { isSubagentSettings } from "../../../shared/subagent-settings.mjs";
19
+ import { validateSubagentSettings } from "./subagent-settings.mjs";
18
20
  import { createCodexAdapter } from "./codex/adapter.mjs";
19
21
  import { createClaudeWorkerAdapter } from "./claude/worker-client.mjs";
20
22
  import { mapResult, mapState, nativeParams } from "./identity-mapping.mjs";
@@ -122,6 +124,8 @@ export function createBackendManager({
122
124
  config,
123
125
  version,
124
126
  providers,
127
+ readSubagentSettings: () =>
128
+ configuration.readSubagentSettings(backend.id),
125
129
  send(client, message) {
126
130
  client.deliver(message);
127
131
  },
@@ -291,18 +295,7 @@ export function createBackendManager({
291
295
  validateBackend(params, config);
292
296
  const old = instances.get(params.id);
293
297
  const next = validateBackend({ ...old?.backend, ...params }, config);
294
- if (next.subagentProviderId && next.subagentProviderId !== "@native") {
295
- const provider = await providers.get("claude", next.subagentProviderId);
296
- if (!provider.models.includes(next.subagentModel))
297
- throw new Error("子代理模型不在所选供应商的模型列表中");
298
- if (
299
- next.subagentEffort &&
300
- !provider.modelCapabilities?.[
301
- next.subagentModel
302
- ]?.supportedEffortLevels?.includes(next.subagentEffort)
303
- )
304
- throw new Error("子代理模型不支持所选思考强度");
305
- }
298
+ await validateSubagentSettings(next, providers);
306
299
  if (
307
300
  params.hiddenModels !== undefined &&
308
301
  Object.keys(params).every((key) =>
@@ -317,6 +310,11 @@ export function createBackendManager({
317
310
  emitState();
318
311
  return { backends: publicBackends() };
319
312
  }
313
+ if (!prepare && isSubagentSettings(params)) {
314
+ old.backend = await configuration.save(params);
315
+ emitState();
316
+ return { backends: publicBackends() };
317
+ }
320
318
  const snapshot = old?.adapter?.state().params;
321
319
  if (hasBackendWork(snapshot))
322
320
  throw new Error("请等待此后端的任务结束后修改配置。");
@@ -324,11 +322,12 @@ export function createBackendManager({
324
322
  try {
325
323
  await old?.adapter?.shutdown?.();
326
324
  if (prepare) await prepare();
325
+ if (closed) return { backends: publicBackends() };
327
326
  const backend = await configuration.save(params);
328
327
  old?.adapter?.close();
329
328
  await install(backend);
330
329
  } catch (error) {
331
- if (old) {
330
+ if (old && !closed) {
332
331
  old.changing = false;
333
332
  if (!old.adapter?.ready) {
334
333
  old.adapter?.close();
@@ -477,6 +476,7 @@ export function createBackendManager({
477
476
  ready: initialized,
478
477
  activeTurns: params.activeTurns,
479
478
  compactions: params.compactions,
479
+ installingBackends: [...installationJobs.keys()],
480
480
  tokenUsageReconciliation: usageReconciliation.snapshot(),
481
481
  },
482
482
  };
@@ -0,0 +1,14 @@
1
+ export async function validateSubagentSettings(backend, providers) {
2
+ if (!backend.subagentProviderId || backend.subagentProviderId === "@native")
3
+ return;
4
+ const provider = await providers.get("claude", backend.subagentProviderId);
5
+ if (!provider.models.includes(backend.subagentModel))
6
+ throw new Error("子代理模型不在所选供应商的模型列表中");
7
+ if (
8
+ backend.subagentEffort &&
9
+ !provider.modelCapabilities?.[
10
+ backend.subagentModel
11
+ ]?.supportedEffortLevels?.includes(backend.subagentEffort)
12
+ )
13
+ throw new Error("子代理模型不支持所选思考强度");
14
+ }
@@ -0,0 +1,69 @@
1
+ import { spawn } from "node:child_process";
2
+ import { open, readFile } from "node:fs/promises";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+
5
+ export async function processIdentity(pid) {
6
+ try {
7
+ const stat = await readFile(`/proc/${pid}/stat`, "utf8");
8
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
9
+ if (["Z", "X"].includes(fields[0])) return null;
10
+ return {
11
+ pid,
12
+ startTime: fields[19],
13
+ bootId: (
14
+ await readFile("/proc/sys/kernel/random/boot_id", "utf8")
15
+ ).trim(),
16
+ };
17
+ } catch (error) {
18
+ if (["ENOENT", "ESRCH"].includes(error.code)) return null;
19
+ throw error;
20
+ }
21
+ }
22
+
23
+ export async function processAlive(expected) {
24
+ if (!expected) return false;
25
+ const actual = await processIdentity(expected.pid);
26
+ return Boolean(
27
+ actual &&
28
+ actual.startTime === expected.startTime &&
29
+ actual.bootId === expected.bootId,
30
+ );
31
+ }
32
+
33
+ export async function stopProcess(expected, { timeout = 30000 } = {}) {
34
+ if (!(await processAlive(expected))) return;
35
+ process.kill(expected.pid, "SIGTERM");
36
+ const deadline = Date.now() + timeout;
37
+ while (Date.now() < deadline) {
38
+ if (!(await processAlive(expected))) return;
39
+ await delay(100);
40
+ }
41
+ if (!(await processAlive(expected))) return;
42
+ console.warn("网页进程未在退出期限内结束,终止所属进程后继续重启。");
43
+ process.kill(expected.pid, "SIGKILL");
44
+ for (let attempt = 0; attempt < 30; attempt++) {
45
+ if (!(await processAlive(expected))) return;
46
+ await delay(100);
47
+ }
48
+ throw new Error("网页进程尚未退出,已保留当前安装,请查看维护日志后重试。");
49
+ }
50
+
51
+ export async function spawnDetached(command, args, { env, cwd, logFile }) {
52
+ const log = await open(logFile, "a", 0o600);
53
+ try {
54
+ const child = spawn(command, args, {
55
+ detached: true,
56
+ stdio: ["ignore", log.fd, log.fd],
57
+ env,
58
+ cwd,
59
+ });
60
+ await new Promise((resolve, reject) => {
61
+ child.once("spawn", resolve);
62
+ child.once("error", reject);
63
+ });
64
+ child.unref();
65
+ return await processIdentity(child.pid);
66
+ } finally {
67
+ await log.close();
68
+ }
69
+ }
@@ -1,12 +1,19 @@
1
1
  import { X509Certificate } from "node:crypto";
2
- // 此入口复制到配置目录后由独立 systemd 单元执行,更新期间保持可运行。
2
+ // 此入口及进程辅助模块复制到配置目录,安装替换和网页退出后继续运行。
3
3
  import { execFile } from "node:child_process";
4
4
  import { promisify } from "node:util";
5
5
  import { mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
6
6
  import { delimiter, dirname, join } from "node:path";
7
7
  import https from "node:https";
8
+ import {
9
+ processAlive,
10
+ processIdentity,
11
+ spawnDetached,
12
+ stopProcess,
13
+ } from "./service-maintenance-process.mjs";
8
14
  const execute = promisify(execFile);
9
15
  const job = JSON.parse(await readFile(process.argv[2], "utf8"));
16
+ if (job.process) job.task.worker = await processIdentity(process.pid);
10
17
  const environment = {
11
18
  ...process.env,
12
19
  ...job.environment,
@@ -57,11 +64,43 @@ const health = async () => {
57
64
  };
58
65
  let stage,
59
66
  backup,
67
+ replacement,
68
+ stopped = false,
60
69
  replaced = false;
70
+ const restart = async () => {
71
+ if (job.process) {
72
+ await stopProcess(replacement || job.process.identity);
73
+ stopped = true;
74
+ replacement = await spawnDetached(
75
+ job.process.command,
76
+ job.process.args,
77
+ job.process,
78
+ );
79
+ if (!replacement) throw new Error("网页进程启动失败,请查看维护日志。");
80
+ } else
81
+ await execute("systemctl", ["--user", "restart", "claudex-web.service"], {
82
+ timeout: 90000,
83
+ });
84
+ };
85
+ const waitHealthy = async (target) => {
86
+ for (let attempt = 0; attempt < 60; attempt++) {
87
+ if (job.process && !(await processAlive(replacement)))
88
+ throw new Error("网页进程启动后退出,请查看维护日志。");
89
+ const status = await health();
90
+ if (status?.version?.version === target) return;
91
+ await new Promise((resolve) => setTimeout(resolve, 1000));
92
+ }
93
+ throw new Error("服务启动检查超时,请查看维护日志。");
94
+ };
95
+ let previousVersion;
61
96
  try {
97
+ await save(job.task.state);
62
98
  // 留出 HTTP 确认响应和浏览器开始轮询的时间。
63
99
  await new Promise((resolve) => setTimeout(resolve, 1500));
64
100
  if (job.action === "update") {
101
+ previousVersion = JSON.parse(
102
+ await readFile(join(job.root, "package.json"), "utf8"),
103
+ ).version;
65
104
  stage = await mkdtemp(join(job.prefix, ".claudex-update-"));
66
105
  await execute(
67
106
  "npm",
@@ -83,6 +122,11 @@ try {
83
122
  if (manifest.version !== job.task.target)
84
123
  throw new Error("安装包版本校验失败");
85
124
  await readFile(join(installed, "client/dist/index.html"));
125
+ // 普通进程先退出再替换,关闭期间仍可读取原安装的按需模块。
126
+ if (job.process) {
127
+ await stopProcess(job.process.identity);
128
+ stopped = true;
129
+ }
86
130
  backup = job.root + ".maintenance-backup";
87
131
  await rename(job.root, backup);
88
132
  try {
@@ -95,34 +139,25 @@ try {
95
139
  }
96
140
  }
97
141
  await save("restarting");
98
- await execute("systemctl", ["--user", "restart", "claudex-web.service"], {
99
- timeout: 90000,
100
- });
101
- let healthy = false;
102
- for (let attempt = 0; attempt < 60; attempt++) {
103
- const status = await health();
104
- if (status?.version?.version === job.task.target) {
105
- healthy = true;
106
- break;
107
- }
108
- await new Promise((resolve) => setTimeout(resolve, 1000));
109
- }
110
- if (!healthy)
111
- throw new Error(
112
- "服务启动检查超时,请查看 journalctl --user -u claudex-web.service",
113
- );
142
+ await restart();
143
+ await waitHealthy(job.task.target);
114
144
  await save("completed");
115
145
  replaced = false;
116
146
  if (backup) await rm(backup, { recursive: true, force: true });
117
147
  } catch (error) {
118
- if (replaced) {
119
- await rm(job.root, { recursive: true, force: true });
120
- await rename(backup, job.root);
121
- await execute("systemctl", [
122
- "--user",
123
- "restart",
124
- "claudex-web.service",
125
- ]).catch(() => {});
148
+ try {
149
+ if (replaced) {
150
+ if (job.process) await stopProcess(replacement);
151
+ await rm(job.root, { recursive: true, force: true });
152
+ await rename(backup, job.root);
153
+ await restart();
154
+ await waitHealthy(previousVersion);
155
+ } else if (stopped && job.process && !(await processAlive(replacement))) {
156
+ await restart();
157
+ await waitHealthy(previousVersion || job.task.target);
158
+ }
159
+ } catch (failure) {
160
+ error.message += `;恢复原服务失败:${failure.message}`;
126
161
  }
127
162
  await save("failed", error.message);
128
163
  process.exitCode = 1;
@@ -11,6 +11,11 @@ import {
11
11
  import { constants } from "node:fs";
12
12
  import { delimiter, dirname, join, resolve } from "node:path";
13
13
  import { fileURLToPath } from "node:url";
14
+ import {
15
+ processAlive,
16
+ processIdentity,
17
+ spawnDetached,
18
+ } from "./service-maintenance-process.mjs";
14
19
 
15
20
  const execute = promisify(execFile);
16
21
  const root = fileURLToPath(new URL("../../", import.meta.url));
@@ -20,6 +25,7 @@ export function createServiceMaintenance({
20
25
  version,
21
26
  isBusy = () => false,
22
27
  run = execute,
28
+ launch = spawnDetached,
23
29
  fetchVersion = async () => {
24
30
  const response = await fetch(
25
31
  `https://registry.npmjs.org/${packageName}/latest`,
@@ -73,12 +79,16 @@ export function createServiceMaintenance({
73
79
  Date.now() - Date.parse(task.startedAt) > 30000
74
80
  ) {
75
81
  try {
76
- await run("systemctl", [
77
- "--user",
78
- "is-active",
79
- "--quiet",
80
- "claudex-web-maintenance.service",
81
- ]);
82
+ if (task.mode === "process") {
83
+ if (!(await processAlive(task.worker)))
84
+ throw new Error("维护进程已退出");
85
+ } else
86
+ await run("systemctl", [
87
+ "--user",
88
+ "is-active",
89
+ "--quiet",
90
+ "claudex-web-maintenance.service",
91
+ ]);
82
92
  } catch {
83
93
  task = {
84
94
  ...task,
@@ -94,13 +104,17 @@ export function createServiceMaintenance({
94
104
  if (task?.state === "failed") switching = false;
95
105
  let managed = false;
96
106
  try {
97
- const { stdout } = await run("systemctl", [
98
- "--user",
99
- "show",
100
- "claudex-web.service",
101
- "--property=MainPID",
102
- "--value",
103
- ]);
107
+ const { stdout } = await run(
108
+ "systemctl",
109
+ [
110
+ "--user",
111
+ "show",
112
+ "claudex-web.service",
113
+ "--property=MainPID",
114
+ "--value",
115
+ ],
116
+ { timeout: 5000 },
117
+ );
104
118
  managed = Number(stdout.trim()) === process.pid;
105
119
  } catch {
106
120
  /* 服务管理能力由当前进程归属决定。 */
@@ -127,10 +141,6 @@ export function createServiceMaintenance({
127
141
  if (["updating", "restarting"].includes(current.task?.state))
128
142
  return current;
129
143
  if (isBusy()) throw new Error("任务仍在运行,请结束后重试。");
130
- if (!current.managed)
131
- throw new Error(
132
- "请通过 claudex-web service install 安装并启动 systemd 用户服务后重试",
133
- );
134
144
  if (action === "update") {
135
145
  await check();
136
146
  if (error) throw new Error(error);
@@ -147,8 +157,13 @@ export function createServiceMaintenance({
147
157
  new URL("./service-maintenance-worker.mjs", import.meta.url),
148
158
  join(directory, "worker.mjs"),
149
159
  );
160
+ await copyFile(
161
+ new URL("./service-maintenance-process.mjs", import.meta.url),
162
+ join(directory, "service-maintenance-process.mjs"),
163
+ );
150
164
  const task = {
151
165
  action,
166
+ mode: current.managed ? "systemd" : "process",
152
167
  state: action === "update" ? "updating" : "restarting",
153
168
  target: action === "update" ? latest : version.version,
154
169
  startedAt: new Date().toISOString(),
@@ -162,6 +177,16 @@ export function createServiceMaintenance({
162
177
  statusFile,
163
178
  port: config.port,
164
179
  cert: config.tlsCert || join(config.configDir, "tls/certificate.pem"),
180
+ process: current.managed
181
+ ? null
182
+ : {
183
+ identity: await processIdentity(process.pid),
184
+ command: process.execPath,
185
+ args: [...process.execArgv, ...process.argv.slice(1)],
186
+ cwd: process.cwd(),
187
+ env: process.env,
188
+ logFile: join(directory, "web.log"),
189
+ },
165
190
  // 独立用户单元使用管理器的环境,npm 须沿用网页服务的安装与网络环境。
166
191
  environment: Object.fromEntries(
167
192
  Object.entries({
@@ -200,16 +225,30 @@ export function createServiceMaintenance({
200
225
  }
201
226
  switching = true;
202
227
  try {
203
- await run("systemd-run", [
204
- "--user",
205
- "--collect",
206
- "--unit=claudex-web-maintenance",
207
- "--property=Type=exec",
208
- "--",
209
- process.execPath,
210
- join(directory, "worker.mjs"),
211
- join(directory, "job.json"),
212
- ]);
228
+ if (current.managed)
229
+ await run("systemd-run", [
230
+ "--user",
231
+ "--collect",
232
+ "--unit=claudex-web-maintenance",
233
+ "--property=Type=exec",
234
+ "--",
235
+ process.execPath,
236
+ join(directory, "worker.mjs"),
237
+ join(directory, "job.json"),
238
+ ]);
239
+ else {
240
+ const worker = await launch(
241
+ process.execPath,
242
+ [join(directory, "worker.mjs"), join(directory, "job.json")],
243
+ {
244
+ cwd: directory,
245
+ env: process.env,
246
+ logFile: join(directory, "worker.log"),
247
+ },
248
+ );
249
+ if (!worker)
250
+ throw new Error("维护进程启动失败,请查看维护日志后重试。");
251
+ }
213
252
  } catch (failure) {
214
253
  switching = false;
215
254
  await writeFile(
@@ -3,6 +3,8 @@ import { isCompacting } from "./compaction-state.mjs";
3
3
  // 后端快照包含原生执行与网页占用;停止前仍须在执行方原子复核。
4
4
  export function hasBackendWork(state = {}) {
5
5
  return Boolean(
6
+ state.installingBackends?.length ||
7
+ state.backends?.some((backend) => backend.installation?.installing) ||
6
8
  Object.keys(state.activeTurns || {}).length ||
7
9
  Object.keys(state.backgroundTasks || {}).length ||
8
10
  Object.keys(state.queuedInputs || {}).length ||
@@ -0,0 +1,18 @@
1
+ const fields = ["subagentModel", "subagentProviderId", "subagentEffort"];
2
+
3
+ export function subagentSettings(backend) {
4
+ return Object.fromEntries(fields.map((key) => [key, backend[key] || ""]));
5
+ }
6
+
7
+ export function isSubagentSettings(input) {
8
+ return (
9
+ fields.some((key) => Object.hasOwn(input, key)) &&
10
+ Object.keys(input).every((key) => ["id", "type", ...fields].includes(key))
11
+ );
12
+ }
13
+
14
+ export function executionBackend(backend) {
15
+ return Object.fromEntries(
16
+ Object.entries(backend).filter(([key]) => !fields.includes(key)),
17
+ );
18
+ }