octopi-agent 0.55.0

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.
Files changed (67) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +7 -0
  3. package/README.md +244 -0
  4. package/README_CN.md +241 -0
  5. package/dist/cli/args.d.ts +20 -0
  6. package/dist/cli/args.js +90 -0
  7. package/dist/cli/commands.d.ts +10 -0
  8. package/dist/cli/commands.js +253 -0
  9. package/dist/cli/daemon.d.ts +40 -0
  10. package/dist/cli/daemon.js +549 -0
  11. package/dist/cli/doctor/data.d.ts +64 -0
  12. package/dist/cli/doctor/data.js +209 -0
  13. package/dist/cli/doctor/index.d.ts +131 -0
  14. package/dist/cli/doctor/index.js +711 -0
  15. package/dist/cli/doctor/redact.d.ts +21 -0
  16. package/dist/cli/doctor/redact.js +48 -0
  17. package/dist/cli/doctor/restore.d.ts +36 -0
  18. package/dist/cli/doctor/restore.js +93 -0
  19. package/dist/cli/helpers.d.ts +38 -0
  20. package/dist/cli/helpers.js +158 -0
  21. package/dist/cli/index.d.ts +5 -0
  22. package/dist/cli/index.js +62 -0
  23. package/dist/cli/process-utils.d.ts +55 -0
  24. package/dist/cli/process-utils.js +306 -0
  25. package/dist/cli/serve-webui.d.ts +1 -0
  26. package/dist/cli/serve-webui.js +82 -0
  27. package/dist/cli/webui.d.ts +13 -0
  28. package/dist/cli/webui.js +249 -0
  29. package/dist/config-migrations.d.ts +198 -0
  30. package/dist/config-migrations.js +692 -0
  31. package/dist/config-schema/index.d.ts +1400 -0
  32. package/dist/config-schema/index.js +100 -0
  33. package/dist/config-schema/webui.d.ts +15 -0
  34. package/dist/config-schema/webui.js +15 -0
  35. package/dist/config-schema.d.ts +9 -0
  36. package/dist/config-schema.js +9 -0
  37. package/dist/config.d.ts +18 -0
  38. package/dist/config.js +136 -0
  39. package/dist/index.d.ts +24 -0
  40. package/dist/index.js +35 -0
  41. package/dist/init.d.ts +86 -0
  42. package/dist/init.js +386 -0
  43. package/dist/integration/index.d.ts +8 -0
  44. package/dist/integration/index.js +8 -0
  45. package/dist/integration/tui/app.d.ts +50 -0
  46. package/dist/integration/tui/app.js +584 -0
  47. package/dist/integration/tui/components.d.ts +82 -0
  48. package/dist/integration/tui/components.js +291 -0
  49. package/dist/integration/tui/index.d.ts +8 -0
  50. package/dist/integration/tui/index.js +8 -0
  51. package/dist/integration/tui/theme.d.ts +77 -0
  52. package/dist/integration/tui/theme.js +90 -0
  53. package/dist/testing/chaos-provider.d.ts +109 -0
  54. package/dist/testing/chaos-provider.js +211 -0
  55. package/dist/testing/index.d.ts +15 -0
  56. package/dist/testing/index.js +10 -0
  57. package/dist/testing/recording-provider.d.ts +75 -0
  58. package/dist/testing/recording-provider.js +172 -0
  59. package/dist/testing/replay-provider.d.ts +52 -0
  60. package/dist/testing/replay-provider.js +138 -0
  61. package/dist/testing/scenario-composer.d.ts +86 -0
  62. package/dist/testing/scenario-composer.js +200 -0
  63. package/dist/testing/scenario-runner.d.ts +134 -0
  64. package/dist/testing/scenario-runner.js +240 -0
  65. package/octopi.example.json +220 -0
  66. package/octopi.schema.json +2206 -0
  67. package/package.json +97 -0
@@ -0,0 +1,306 @@
1
+ /**
2
+ * CLI 跨平台进程原语
3
+ *
4
+ * Windows / macOS / Linux 共用:延时、端口探测、杀进程树、detached spawn。
5
+ * 不要在 daemon/helpers 里再手写 lsof / sleep / .bin 路径。
6
+ */
7
+ import { execFileSync, spawn } from 'node:child_process';
8
+ import { existsSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ /** Promise 化延时,替代 Unix `sleep` 命令 */
11
+ export function delay(ms) {
12
+ return new Promise((resolve) => setTimeout(resolve, ms));
13
+ }
14
+ /** 进程是否仍存活(pid 0 探测) */
15
+ export function isProcessAlive(pid) {
16
+ if (!Number.isInteger(pid) || pid <= 0)
17
+ return false;
18
+ try {
19
+ process.kill(pid, 0);
20
+ return true;
21
+ }
22
+ catch (err) {
23
+ // Windows 上对「存在但无权限」的进程会抛 EPERM:不能当成已退出
24
+ const code = err?.code;
25
+ return code === 'EPERM';
26
+ }
27
+ }
28
+ /** 进程祖先链缓存(单次 CLI 调用内足够) */
29
+ let ancestorChainCache = null;
30
+ function getAncestorPidSet() {
31
+ if (ancestorChainCache)
32
+ return ancestorChainCache;
33
+ const chain = new Set([process.pid]);
34
+ if (typeof process.ppid === 'number' && process.ppid > 0)
35
+ chain.add(process.ppid);
36
+ try {
37
+ if (process.platform === 'win32') {
38
+ const script = `$p=${process.pid}; while ($p -gt 0) { Write-Output $p; $c=Get-CimInstance Win32_Process -Filter "ProcessId=$p"; if (-not $c) { break }; $p=$c.ParentProcessId }`;
39
+ const out = execFileSync('powershell.exe', ['-NoProfile', '-Command', script], { encoding: 'utf-8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'] });
40
+ for (const line of out.split(/\r?\n/)) {
41
+ const n = parseInt(line.trim(), 10);
42
+ if (Number.isInteger(n) && n > 0)
43
+ chain.add(n);
44
+ }
45
+ }
46
+ else {
47
+ let current = process.ppid;
48
+ const seen = new Set();
49
+ while (typeof current === 'number' && current > 0 && !seen.has(current)) {
50
+ chain.add(current);
51
+ seen.add(current);
52
+ const parent = execFileSync('ps', ['-o', 'ppid=', '-p', String(current)], {
53
+ encoding: 'utf-8',
54
+ timeout: 2000,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ }).trim();
57
+ const n = parseInt(parent, 10);
58
+ if (!Number.isInteger(n) || n <= 0 || n === current)
59
+ break;
60
+ current = n;
61
+ }
62
+ }
63
+ }
64
+ catch {
65
+ // 探测失败时至少保留 self + ppid
66
+ }
67
+ ancestorChainCache = chain;
68
+ return chain;
69
+ }
70
+ /**
71
+ * pid 是否为当前进程或其祖先
72
+ *
73
+ * Windows `taskkill /T` 杀的是整棵进程树;若误把 CLI 的父进程(工具 shell)
74
+ * 当成目标,会话会被连带干掉。杀进程前必须用本函数拦截。
75
+ */
76
+ export function isSelfOrAncestorPid(pid) {
77
+ if (!Number.isInteger(pid) || pid <= 0)
78
+ return true;
79
+ return getAncestorPidSet().has(pid);
80
+ }
81
+ function findPidOnPortUnix(port) {
82
+ try {
83
+ const result = execFileSync('lsof', ['-nP', '-sTCP:LISTEN', `-iTCP:${port}`], { encoding: 'utf-8', timeout: 5000 }).trim();
84
+ if (!result)
85
+ return null;
86
+ const lines = result.split('\n').slice(1);
87
+ for (const line of lines) {
88
+ const parts = line.split(/\s+/);
89
+ const pid = parseInt(parts[1] ?? '', 10);
90
+ if (pid > 0 && pid !== process.pid)
91
+ return pid;
92
+ }
93
+ return null;
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ function findPidOnPortWindows(port) {
100
+ try {
101
+ const result = execFileSync('netstat', ['-ano'], {
102
+ encoding: 'utf-8',
103
+ timeout: 10_000,
104
+ maxBuffer: 16 * 1024 * 1024,
105
+ });
106
+ for (const line of result.split(/\r?\n/)) {
107
+ // TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 1234
108
+ // TCP [::]:3000 [::]:0 LISTENING 1234
109
+ const m = line.match(/^\s*TCP\s+\S+:(\d+)\s+\S+\s+LISTENING\s+(\d+)\s*$/i);
110
+ if (!m)
111
+ continue;
112
+ if (parseInt(m[1], 10) !== port)
113
+ continue;
114
+ const pid = parseInt(m[2], 10);
115
+ if (pid > 0 && pid !== process.pid)
116
+ return pid;
117
+ }
118
+ return null;
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ /** 查找监听指定 TCP 端口的进程 PID(排除自身) */
125
+ export function findPidOnPort(port) {
126
+ if (!Number.isInteger(port) || port <= 0)
127
+ return null;
128
+ return process.platform === 'win32'
129
+ ? findPidOnPortWindows(port)
130
+ : findPidOnPortUnix(port);
131
+ }
132
+ /**
133
+ * 终结进程(Windows 用 taskkill 杀进程树,避免 vite/cmd 残留子进程)
134
+ *
135
+ * @param pid - 目标 PID
136
+ * @param options.timeoutMs - 等待优雅退出的最长时间
137
+ * @returns 是否已确认进程退出
138
+ */
139
+ export async function killProcess(pid, options) {
140
+ const timeoutMs = options?.timeoutMs ?? 3000;
141
+ if (!Number.isInteger(pid) || pid <= 0)
142
+ return true;
143
+ // 绝不杀自己/祖先:taskkill /T 会把 agent shell 一并带走
144
+ if (isSelfOrAncestorPid(pid)) {
145
+ console.warn(`⚠️ Refusing to kill PID ${pid} (self/ancestor of current CLI process)`);
146
+ return false;
147
+ }
148
+ if (!isProcessAlive(pid))
149
+ return true;
150
+ if (process.platform === 'win32') {
151
+ // 1) 软关:taskkill 不带 /F(发 WM_CLOSE);无窗口控制台进程常失败,属预期
152
+ try {
153
+ execFileSync('taskkill', ['/PID', String(pid), '/T'], {
154
+ encoding: 'utf-8',
155
+ timeout: 5000,
156
+ stdio: 'pipe',
157
+ });
158
+ }
159
+ catch {
160
+ // already exiting / no window / access denied
161
+ }
162
+ const softDeadline = Date.now() + Math.min(timeoutMs, 3000);
163
+ while (Date.now() < softDeadline) {
164
+ if (!isProcessAlive(pid))
165
+ return true;
166
+ await delay(100);
167
+ }
168
+ // 2) 强杀进程树
169
+ try {
170
+ execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
171
+ encoding: 'utf-8',
172
+ timeout: 5000,
173
+ stdio: 'pipe',
174
+ });
175
+ }
176
+ catch {
177
+ // taskkill 对已退出/无权限进程会非零退出;以存活探测为准
178
+ }
179
+ await delay(100);
180
+ return !isProcessAlive(pid);
181
+ }
182
+ try {
183
+ process.kill(pid, 'SIGTERM');
184
+ }
185
+ catch {
186
+ return !isProcessAlive(pid);
187
+ }
188
+ const deadline = Date.now() + timeoutMs;
189
+ while (Date.now() < deadline) {
190
+ if (!isProcessAlive(pid))
191
+ return true;
192
+ await delay(200);
193
+ }
194
+ try {
195
+ process.kill(pid, 'SIGKILL');
196
+ }
197
+ catch {
198
+ // already exited
199
+ }
200
+ return !isProcessAlive(pid);
201
+ }
202
+ /** 终结占用指定端口的进程 */
203
+ export async function killProcessOnPort(port) {
204
+ const pid = findPidOnPort(port);
205
+ if (!pid || pid === process.pid)
206
+ return false;
207
+ return killProcess(pid);
208
+ }
209
+ /**
210
+ * 启动后台子进程(detached + windowsHide)
211
+ *
212
+ * Windows:优先 `powershell Start-Process`。Node `spawn({detached:true})`
213
+ * 在工具/Job Object 环境下常与父进程绑在同一 Job,父进程退出或外层清理时
214
+ * 会连带杀掉整棵 shell(表现为 CLI 一 start 会话就消失)。
215
+ *
216
+ * @returns 子进程 PID;启动失败返回 null
217
+ */
218
+ export function spawnDetached(command, args, options = {}) {
219
+ if (process.platform === 'win32') {
220
+ return spawnDetachedWindows(command, args, options);
221
+ }
222
+ try {
223
+ const child = spawn(command, args, {
224
+ detached: true,
225
+ stdio: 'ignore',
226
+ windowsHide: true,
227
+ ...options,
228
+ });
229
+ child.on('error', () => {
230
+ /* 子进程启动失败不拖垮 CLI;上层靠 pid 探测 */
231
+ });
232
+ if (child.pid) {
233
+ child.unref();
234
+ return child.pid;
235
+ }
236
+ return null;
237
+ }
238
+ catch {
239
+ return null;
240
+ }
241
+ }
242
+ function psQuote(value) {
243
+ return `'${value.replace(/'/g, "''")}'`;
244
+ }
245
+ function spawnDetachedWindows(command, args, options) {
246
+ const cwd = typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined;
247
+ const argArray = args.map(psQuote).join(', ');
248
+ const workDir = cwd ? ` -WorkingDirectory ${psQuote(cwd)}` : '';
249
+ const script = `$p = Start-Process -FilePath ${psQuote(command)} -ArgumentList @(${argArray})${workDir} -WindowStyle Hidden -PassThru; ` +
250
+ `if ($p) { Write-Output $p.Id }`;
251
+ try {
252
+ const out = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
253
+ encoding: 'utf-8',
254
+ timeout: 20_000,
255
+ stdio: ['ignore', 'pipe', 'pipe'],
256
+ windowsHide: true,
257
+ });
258
+ const lines = out.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
259
+ const pid = parseInt(lines[lines.length - 1] ?? '', 10);
260
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
261
+ }
262
+ catch {
263
+ // PowerShell Start-Process 失败时退回 Node spawn(可能仍受 Job 限制)
264
+ try {
265
+ const child = spawn(command, args, {
266
+ detached: true,
267
+ stdio: 'ignore',
268
+ windowsHide: true,
269
+ ...options,
270
+ });
271
+ child.on('error', () => undefined);
272
+ if (child.pid) {
273
+ child.unref();
274
+ return child.pid;
275
+ }
276
+ }
277
+ catch {
278
+ /* ignore */
279
+ }
280
+ return null;
281
+ }
282
+ }
283
+ /**
284
+ * 解析 Vite 可执行入口(优先直接走 node + vite.js,避开 Windows .cmd shim)
285
+ *
286
+ * @param webDir - web 项目根目录
287
+ * @param options.hostArg - 传给 Vite 的 `--host` 值(如 `localhost` / `0.0.0.0`)
288
+ * @returns { command, args } 或 null(未安装 vite)
289
+ */
290
+ export function resolveViteLaunch(webDir, options) {
291
+ const hostArgs = options?.hostArg ? ['--host', options.hostArg] : [];
292
+ const viteJs = join(webDir, 'node_modules', 'vite', 'bin', 'vite.js');
293
+ if (existsSync(viteJs)) {
294
+ return { command: process.execPath, args: [viteJs, ...hostArgs] };
295
+ }
296
+ const binName = process.platform === 'win32' ? 'vite.cmd' : 'vite';
297
+ const viteBin = join(webDir, 'node_modules', '.bin', binName);
298
+ if (existsSync(viteBin)) {
299
+ if (process.platform === 'win32') {
300
+ const comSpec = process.env.ComSpec ?? 'cmd.exe';
301
+ return { command: comSpec, args: ['/d', '/s', '/c', viteBin, ...hostArgs] };
302
+ }
303
+ return { command: viteBin, args: hostArgs };
304
+ }
305
+ return null;
306
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Static file server for prebuilt WebUI dist (product path — no Vite).
3
+ *
4
+ * Spawn: node dist/cli/serve-webui.js <distDir> [--host <host>] [--port <port>]
5
+ */
6
+ import { createServer } from 'node:http';
7
+ import { readFile, stat } from 'node:fs/promises';
8
+ import { join, normalize, extname, resolve, sep } from 'node:path';
9
+ const distArg = process.argv[2];
10
+ if (!distArg) {
11
+ console.error('usage: serve-webui <distDir> [--host host] [--port port]');
12
+ process.exit(1);
13
+ }
14
+ const distDir = resolve(distArg);
15
+ let host = '127.0.0.1';
16
+ let port = 5173;
17
+ for (let i = 3; i < process.argv.length; i++) {
18
+ if (process.argv[i] === '--host' && process.argv[i + 1])
19
+ host = process.argv[++i];
20
+ if (process.argv[i] === '--port' && process.argv[i + 1])
21
+ port = Number(process.argv[++i]);
22
+ }
23
+ const MIME = {
24
+ '.html': 'text/html; charset=utf-8',
25
+ '.js': 'text/javascript; charset=utf-8',
26
+ '.mjs': 'text/javascript; charset=utf-8',
27
+ '.css': 'text/css; charset=utf-8',
28
+ '.json': 'application/json; charset=utf-8',
29
+ '.svg': 'image/svg+xml',
30
+ '.png': 'image/png',
31
+ '.jpg': 'image/jpeg',
32
+ '.jpeg': 'image/jpeg',
33
+ '.gif': 'image/gif',
34
+ '.webp': 'image/webp',
35
+ '.ico': 'image/x-icon',
36
+ '.woff': 'font/woff',
37
+ '.woff2': 'font/woff2',
38
+ '.map': 'application/json; charset=utf-8',
39
+ };
40
+ function safeJoin(root, urlPath) {
41
+ const decoded = decodeURIComponent(urlPath.split('?')[0]);
42
+ const rel = normalize(decoded).replace(/^([/\\])+/, '');
43
+ const full = join(root, rel);
44
+ if (!full.startsWith(root + sep) && full !== root)
45
+ return null;
46
+ return full;
47
+ }
48
+ const server = createServer(async (req, res) => {
49
+ try {
50
+ let file = safeJoin(distDir, req.url || '/');
51
+ if (!file) {
52
+ res.writeHead(403).end('Forbidden');
53
+ return;
54
+ }
55
+ let st = await stat(file).catch(() => null);
56
+ if (st?.isDirectory()) {
57
+ file = join(file, 'index.html');
58
+ st = await stat(file).catch(() => null);
59
+ }
60
+ // SPA fallback
61
+ if (!st?.isFile()) {
62
+ file = join(distDir, 'index.html');
63
+ st = await stat(file).catch(() => null);
64
+ }
65
+ if (!st?.isFile()) {
66
+ res.writeHead(404).end('Not Found');
67
+ return;
68
+ }
69
+ const body = await readFile(file);
70
+ res.writeHead(200, {
71
+ 'Content-Type': MIME[extname(file).toLowerCase()] || 'application/octet-stream',
72
+ 'Cache-Control': 'no-cache',
73
+ });
74
+ res.end(body);
75
+ }
76
+ catch {
77
+ res.writeHead(500).end('Internal Server Error');
78
+ }
79
+ });
80
+ server.listen(port, host, () => {
81
+ console.log(`[serve-webui] ${distDir} → http://${host}:${port}`);
82
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * CLI Web UI 命令
3
+ */
4
+ import type { CliArgs } from './args.js';
5
+ export interface WebUiStartOptions {
6
+ /** soft: 失败只警告,不 process.exit(供 serve start 使用) */
7
+ soft?: boolean;
8
+ }
9
+ export declare function webuiStartCommand(configPath?: string, options?: WebUiStartOptions): Promise<void>;
10
+ export declare function webuiStopCommand(): Promise<void>;
11
+ export declare function webuiRestartCommand(configPath?: string): Promise<void>;
12
+ export declare function webuiStatusCommand(): Promise<void>;
13
+ export declare function webuiCommand(args: CliArgs): Promise<void>;
@@ -0,0 +1,249 @@
1
+ /**
2
+ * CLI Web UI 命令
3
+ */
4
+ import { resolve } from 'node:path';
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { networkInterfaces } from 'node:os';
7
+ import { isLanHost, resolveViteHostArg, } from '@octopi-agent/engine/config.js';
8
+ import { ensureDaemonConfig } from './daemon.js';
9
+ import { getOctopiHome } from '@octopi-agent/engine/paths.js';
10
+ import { findWebDist, startWebUi, stopWebUi, readWebUiPidRecord, writeWebUiPidFile, removeWebUiPidFile, } from './helpers.js';
11
+ import { findPidOnPort, isProcessAlive } from './process-utils.js';
12
+ /** Vite 开发服务器常见端口(用于认领未写入 pid 文件的实例) */
13
+ const VITE_DEV_PORTS = [5173, 5174, 4173];
14
+ /** 轻量读取配置中的 web.dir / web.host,避免 loadConfig 重复打日志/强校验 */
15
+ function readConfigWebSettings(configPath) {
16
+ try {
17
+ let filePath;
18
+ if (configPath) {
19
+ filePath = resolve(configPath);
20
+ }
21
+ else if (existsSync(resolve('./octopi.json'))) {
22
+ filePath = resolve('./octopi.json');
23
+ }
24
+ else {
25
+ filePath = resolve(getOctopiHome(), 'octopi.json');
26
+ }
27
+ if (!existsSync(filePath))
28
+ return {};
29
+ const raw = JSON.parse(readFileSync(filePath, 'utf-8'));
30
+ const dir = typeof raw.web?.dir === 'string' && raw.web.dir.trim() ? raw.web.dir.trim() : undefined;
31
+ const host = typeof raw.web?.host === 'string' && raw.web.host.trim()
32
+ ? raw.web.host.trim()
33
+ : undefined;
34
+ return { dir, host };
35
+ }
36
+ catch {
37
+ return {};
38
+ }
39
+ }
40
+ /** 读取配置中的 web.dir */
41
+ function readConfigWebDir(configPath) {
42
+ return readConfigWebSettings(configPath).dir;
43
+ }
44
+ /** 探测本机局域网 IPv4(用于启动提示) */
45
+ function firstLanIPv4() {
46
+ try {
47
+ const ifaces = networkInterfaces();
48
+ for (const entries of Object.values(ifaces)) {
49
+ for (const entry of entries ?? []) {
50
+ if (entry.family === 'IPv4' && !entry.internal)
51
+ return entry.address;
52
+ }
53
+ }
54
+ }
55
+ catch {
56
+ /* ignore */
57
+ }
58
+ return null;
59
+ }
60
+ /** 在常见 dev 端口上探测疑似 Vite 进程 */
61
+ function findPidOnVitePorts() {
62
+ for (const port of VITE_DEV_PORTS) {
63
+ const pid = findPidOnPort(port);
64
+ if (pid && isProcessAlive(pid))
65
+ return { pid, port };
66
+ }
67
+ return null;
68
+ }
69
+ export async function webuiStartCommand(configPath, options) {
70
+ const soft = options?.soft === true;
71
+ const existing = readWebUiPidRecord();
72
+ if (existing && isProcessAlive(existing.pid)) {
73
+ console.log(`⚠️ Web UI is already running (PID: ${existing.pid})`);
74
+ if (existing.dir)
75
+ console.log(` Directory: ${existing.dir}`);
76
+ console.log(`\nUse 'octopi webui restart' to restart.`);
77
+ return;
78
+ }
79
+ // pid 文件缺失/失效,但端口上已有实例:提示而非叠跑第二个 vite
80
+ const portHit = findPidOnVitePorts();
81
+ if (portHit) {
82
+ console.log(`⚠️ Web UI appears already running on port ${portHit.port} (PID: ${portHit.pid})`);
83
+ console.log(' Not tracked in ~/.octopi/webui.pid (started outside CLI?)');
84
+ if (soft)
85
+ return;
86
+ console.log(`\nUse 'octopi webui stop' to stop it, then start again.`);
87
+ process.exit(1);
88
+ }
89
+ removeWebUiPidFile();
90
+ const webSettings = readConfigWebSettings(configPath);
91
+ const configWebDir = webSettings.dir;
92
+ const webHost = webSettings.host;
93
+ const webDist = findWebDist(configPath, configWebDir);
94
+ if (!webDist) {
95
+ if (soft) {
96
+ console.warn('⚠️ Web UI dist not found, skipping Web UI');
97
+ console.warn(' Set "web.dir" in config, $OCTOPI_WEB_DIR, or install @octopi-agent/webui');
98
+ return;
99
+ }
100
+ console.error('❌ Web UI dist not found. Searched:');
101
+ console.error(' - $OCTOPI_WEB_DIR (if set)');
102
+ console.error(' - Config "web.dir" (if set)');
103
+ console.error(' - node_modules/@octopi-agent/webui/dist');
104
+ console.error(' - packages/webui/dist (monorepo)');
105
+ console.error(' - ~/.octopi/web/dist');
106
+ process.exit(1);
107
+ }
108
+ const listenHost = resolveViteHostArg(webHost);
109
+ const lanOpen = isLanHost(webHost);
110
+ const port = 5173;
111
+ const pid = startWebUi(webDist, { hostArg: listenHost, port });
112
+ if (!pid) {
113
+ if (soft) {
114
+ console.warn('⚠️ Failed to start Web UI static server. Gateway continues without it.');
115
+ console.warn(` Dist: ${webDist}`);
116
+ return;
117
+ }
118
+ console.error('❌ Failed to start Web UI');
119
+ console.error(` Dist: ${webDist}`);
120
+ process.exit(1);
121
+ }
122
+ writeWebUiPidFile(pid, { dir: webDist, host: webHost });
123
+ console.log(`✅ Web UI started (PID: ${pid})`);
124
+ console.log(` Dist: ${webDist}`);
125
+ if (lanOpen) {
126
+ const lanIp = firstLanIPv4();
127
+ console.log(` Access: LAN (host=${listenHost})`);
128
+ if (lanIp)
129
+ console.log(` URL: http://${lanIp}:${port}`);
130
+ console.log(' Note: Gateway 也需 channels[].host/web.host 为 "lan",局域网客户端才能连上 API');
131
+ }
132
+ else {
133
+ console.log(` Access: local only (host=${listenHost})`);
134
+ console.log(` URL: http://${listenHost === '0.0.0.0' ? '127.0.0.1' : listenHost}:${port}`);
135
+ }
136
+ console.log(`\nUse 'octopi webui stop' to stop, 'octopi webui status' to check.`);
137
+ // spawn 后父进程必须退出:Windows 上残留事件柄/Job 会让 CLI 挂住,
138
+ // 外层工具超时后 taskkill 整棵 shell(表现为执行“被杀掉”)。
139
+ if (!soft) {
140
+ process.exit(0);
141
+ }
142
+ }
143
+ export async function webuiStopCommand() {
144
+ const record = readWebUiPidRecord();
145
+ let pid = record?.pid;
146
+ let source = pid ? 'pidfile' : 'none';
147
+ if (!pid || !isProcessAlive(pid)) {
148
+ if (pid) {
149
+ console.log('ℹ️ Web UI process is not running. Cleaning up PID file.');
150
+ removeWebUiPidFile();
151
+ pid = undefined;
152
+ }
153
+ const portHit = findPidOnVitePorts();
154
+ if (portHit) {
155
+ pid = portHit.pid;
156
+ source = 'port';
157
+ console.log(`ℹ️ Adopting untracked Web UI on port ${portHit.port} (PID: ${portHit.pid})`);
158
+ }
159
+ }
160
+ if (!pid) {
161
+ console.log('ℹ️ No Web UI instance found.');
162
+ console.log(' CLI tracks ~/.octopi/webui.pid; it also probes ports 5173/5174/4173.');
163
+ console.log(' Manually started vite outside those ports must be stopped in its own terminal.');
164
+ return;
165
+ }
166
+ console.log(`🛑 Stopping Web UI (PID: ${pid})...`);
167
+ if (record?.dir)
168
+ console.log(` Directory: ${record.dir}`);
169
+ if (source === 'port')
170
+ console.log(' Source: dev port probe');
171
+ await stopWebUi(pid);
172
+ removeWebUiPidFile();
173
+ if (!isProcessAlive(pid)) {
174
+ console.log('✅ Web UI stopped.');
175
+ }
176
+ else {
177
+ console.warn(`⚠️ Web UI PID ${pid} may still be running`);
178
+ }
179
+ }
180
+ export async function webuiRestartCommand(configPath) {
181
+ await webuiStopCommand();
182
+ await new Promise((r) => setTimeout(r, 500));
183
+ await webuiStartCommand(configPath);
184
+ }
185
+ export async function webuiStatusCommand() {
186
+ const record = readWebUiPidRecord();
187
+ const pid = record?.pid;
188
+ const portHit = findPidOnVitePorts();
189
+ if (!pid) {
190
+ console.log('ℹ️ No Web UI instance found in ~/.octopi/webui.pid.');
191
+ if (portHit && isProcessAlive(portHit.pid)) {
192
+ console.log(` But port ${portHit.port} is LISTENING (PID: ${portHit.pid}) — started outside CLI?`);
193
+ }
194
+ const configWebDir = readConfigWebDir();
195
+ const webDist = findWebDist(undefined, configWebDir);
196
+ if (webDist)
197
+ console.log(` Detected Web UI dist (not started via CLI): ${webDist}`);
198
+ return;
199
+ }
200
+ const alive = isProcessAlive(pid);
201
+ console.log(`\n🌐 Web UI Status\n`);
202
+ console.log(` PID: ${pid}`);
203
+ console.log(` Status: ${alive ? '🟢 Running' : '🔴 Stopped'}`);
204
+ if (record.dir)
205
+ console.log(` Directory: ${record.dir}`);
206
+ if (record.host) {
207
+ const lanOpen = record.host === 'lan' || (record.host !== 'local' && record.host !== 'localhost' && record.host !== '127.0.0.1');
208
+ console.log(` Host: ${record.host} (${lanOpen ? 'LAN' : 'local only'})`);
209
+ }
210
+ if (record.startedAt)
211
+ console.log(` Started: ${record.startedAt}`);
212
+ if (portHit)
213
+ console.log(` Port: ${portHit.port} (PID ${portHit.pid})`);
214
+ console.log();
215
+ if (!alive) {
216
+ console.log(' ⚠️ Process is not running. PID file is stale.');
217
+ if (portHit && portHit.pid !== pid && isProcessAlive(portHit.pid)) {
218
+ console.log(` Another process holds port ${portHit.port} (PID ${portHit.pid}).`);
219
+ }
220
+ console.log(` Run 'octopi webui start' to start a new instance.\n`);
221
+ }
222
+ }
223
+ export async function webuiCommand(args) {
224
+ const configPath = await ensureDaemonConfig(args);
225
+ switch (args.subcommand) {
226
+ case 'start':
227
+ await webuiStartCommand(configPath);
228
+ break;
229
+ case 'stop':
230
+ await webuiStopCommand();
231
+ break;
232
+ case 'restart':
233
+ await webuiRestartCommand(configPath);
234
+ break;
235
+ case 'status':
236
+ await webuiStatusCommand();
237
+ break;
238
+ case undefined:
239
+ console.log('💡 Tip: Use "octopi webui start" to start Web UI.\n');
240
+ await webuiStartCommand(configPath);
241
+ break;
242
+ default:
243
+ console.error(`Unknown webui subcommand: ${args.subcommand}`);
244
+ console.error('Valid subcommands: start, stop, restart, status');
245
+ process.exit(1);
246
+ }
247
+ // 所有 webui 子命令收尾强制退出,避免 import/spawn 句柄拖住进程
248
+ process.exit(0);
249
+ }