octopi-agent 0.55.1 → 0.58.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.
@@ -109,7 +109,7 @@ export async function chatCommand(args) {
109
109
  }
110
110
  const channels = config.channels ?? [];
111
111
  const httpChannel = channels.find((c) => c.type === "http");
112
- const port = httpChannel?.port ?? 3000;
112
+ const port = httpChannel?.port ?? 18180;
113
113
  writePidFile({
114
114
  pid: child.pid,
115
115
  config: configPath ?? join(getOctopiHome(), 'octopi.json'),
@@ -30,10 +30,57 @@ export declare function resolveGatewayPid(args: Pick<CliArgs, 'port' | 'config'>
30
30
  port: number;
31
31
  source: 'port' | 'pidfile' | 'none';
32
32
  };
33
+ /** 端口占用者三态:空闲 / 自己的 Gateway / 其他进程 / 无法识别 */
34
+ export type PortOccupantState = 'free' | 'own-gateway' | 'foreign' | 'unknown';
35
+ export interface PortOccupant {
36
+ state: PortOccupantState;
37
+ port: number;
38
+ /** 端口监听进程 PID(探测不到时为 null) */
39
+ pid: number | null;
40
+ /** foreign 时尽力获取的进程名(如 node.exe) */
41
+ processName?: string;
42
+ /** own-gateway:进程存活但 health 尚未响应(启动中 / 卡住) */
43
+ healthy: boolean;
44
+ /** own-gateway:来自 pid 文件 */
45
+ startedAt?: string;
46
+ config?: string;
47
+ }
48
+ /**
49
+ * 识别端口占用者,供 `serve start` 决策:
50
+ *
51
+ * 1. health 是 octopi → 自己的 Gateway(幂等,不是错误)
52
+ * 2. 监听者 pid 与 pid 文件一致 → 自己的 Gateway(health 未响应 = 启动中/卡住)
53
+ * 3. 监听者是其他进程 → foreign(错误:给出占用者身份 + 出路)
54
+ * 4. 无监听者但 pid 文件进程存活且端口一致 → 自己的 Gateway(启动窗口期,防双开)
55
+ * 5. 有 HTTP 响应但拿不到 pid → unknown(警告后继续,失败由子进程日志上浮)
56
+ * 6. 其余 → free
57
+ *
58
+ * @param port 待检查的监听端口
59
+ */
60
+ export declare function identifyPortOccupant(port: number): Promise<PortOccupant>;
61
+ /** Gateway 守护进程日志路径(`OCTOPI_HOME/logs/gateway.log`) */
62
+ export declare function getGatewayLogPath(): string;
63
+ /** 读取日志尾部若干非空行 */
64
+ export declare function readLogTail(logPath: string, maxLines?: number): string[];
65
+ /**
66
+ * 把子进程日志尾部翻译成用户可执行的结论(原因 + 出路 + 证据位置)
67
+ *
68
+ * @param opts.logTail 日志尾部行(readLogTail 结果)
69
+ * @param opts.port Gateway 监听端口
70
+ * @param opts.configPath 本次使用的配置路径
71
+ * @param opts.logPath 完整日志路径
72
+ * @returns 逐行输出的诊断文本
73
+ */
74
+ export declare function diagnoseStartupFailure(opts: {
75
+ logTail: string[];
76
+ port: number;
77
+ configPath?: string;
78
+ logPath: string;
79
+ }): string[];
33
80
  export declare function createProvider(name: string, cfg: ModelProviderConfig): ModelProvider | null;
34
81
  export declare function ensureDaemonConfig(args: CliArgs): Promise<string | undefined>;
35
82
  export declare function serveStartCommand(args: CliArgs): Promise<void>;
36
- export declare function serveStopCommand(args?: Pick<CliArgs, 'port'>): Promise<void>;
83
+ export declare function serveStopCommand(args?: Pick<CliArgs, 'port' | 'config'>): Promise<void>;
37
84
  export declare function serveRestartCommand(args: CliArgs): Promise<void>;
38
85
  export declare function serveStatusCommand(args?: Pick<CliArgs, 'port' | 'config'>): Promise<void>;
39
86
  export declare function serveFgCommand(args: CliArgs): Promise<void>;
@@ -2,8 +2,8 @@
2
2
  * CLI 守护进程管理
3
3
  */
4
4
  import { resolve, dirname, join } from 'node:path';
5
- import { fork } from 'node:child_process';
6
- import { readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync } from 'node:fs';
5
+ import { spawn } from 'node:child_process';
6
+ import { readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, openSync, closeSync, writeSync, } from 'node:fs';
7
7
  import { getOctopiHome, isInitialized, initOctopi, formatInitReport } from '../init.js';
8
8
  import { loadConfig, toGatewayConfig } from '../config.js';
9
9
  import { createToolSet } from '@octopi-agent/engine/harness/extension/plugin-ecosystem/tools/tool-set.js';
@@ -11,7 +11,7 @@ import { OpenAIProvider } from '@octopi-agent/engine/integration/providers/opena
11
11
  import { AnthropicProvider } from '@octopi-agent/engine/integration/providers/anthropic.js';
12
12
  import { Gateway } from '@octopi-agent/gateway/gateway/gateway.js';
13
13
  import { webuiStartCommand, webuiStopCommand } from './webui.js';
14
- import { delay, findPidOnPort, isProcessAlive, killProcess, killProcessOnPort, } from './process-utils.js';
14
+ import { delay, findPidOnPort, getProcessName, isProcessAlive, killProcess, killProcessOnPort, } from './process-utils.js';
15
15
  // Re-export for existing importers (commands.ts / helpers.ts)
16
16
  export { findPidOnPort, isProcessAlive, killProcessOnPort };
17
17
  export function getPidPath() {
@@ -54,7 +54,7 @@ export function resolveListenPort(args, configPath) {
54
54
  return httpChannel.port;
55
55
  }
56
56
  catch { /* fall through */ }
57
- return 3000;
57
+ return 18180;
58
58
  }
59
59
  /**
60
60
  * 解析当前 Gateway 的真实 PID
@@ -75,27 +75,178 @@ export function resolveGatewayPid(args, configPath) {
75
75
  }
76
76
  return { pid: null, port, source: 'none' };
77
77
  }
78
- async function waitGatewayReady(port, timeoutMs = 20_000) {
78
+ /**
79
+ * 探测端口上的 HTTP 服务是否为 Octopi Gateway
80
+ *
81
+ * - `octopi`:`/health` 返回 200 且 body 形如 `{status:"ok"}`
82
+ * - `other`:有 HTTP 响应但不是 octopi health 形状(被别的服务占用)
83
+ * - `none`:无响应(端口空闲 / 非 HTTP 服务 / 连接被拒)
84
+ */
85
+ async function probeGatewayHealth(port) {
86
+ try {
87
+ const res = await fetch(`http://127.0.0.1:${port}/health`, {
88
+ signal: AbortSignal.timeout(800),
89
+ });
90
+ if (!res.ok)
91
+ return 'other';
92
+ const body = await res.json().catch(() => null);
93
+ if (typeof body === 'object' &&
94
+ body !== null &&
95
+ body.status === 'ok') {
96
+ return 'octopi';
97
+ }
98
+ return 'other';
99
+ }
100
+ catch {
101
+ return 'none';
102
+ }
103
+ }
104
+ /**
105
+ * 识别端口占用者,供 `serve start` 决策:
106
+ *
107
+ * 1. health 是 octopi → 自己的 Gateway(幂等,不是错误)
108
+ * 2. 监听者 pid 与 pid 文件一致 → 自己的 Gateway(health 未响应 = 启动中/卡住)
109
+ * 3. 监听者是其他进程 → foreign(错误:给出占用者身份 + 出路)
110
+ * 4. 无监听者但 pid 文件进程存活且端口一致 → 自己的 Gateway(启动窗口期,防双开)
111
+ * 5. 有 HTTP 响应但拿不到 pid → unknown(警告后继续,失败由子进程日志上浮)
112
+ * 6. 其余 → free
113
+ *
114
+ * @param port 待检查的监听端口
115
+ */
116
+ export async function identifyPortOccupant(port) {
117
+ const probe = await probeGatewayHealth(port);
118
+ const pid = findPidOnPort(port);
119
+ const pidFile = readPidFile();
120
+ const base = { port, healthy: probe === 'octopi' };
121
+ if (probe === 'octopi') {
122
+ return {
123
+ ...base,
124
+ state: 'own-gateway',
125
+ pid,
126
+ startedAt: pidFile?.startedAt,
127
+ config: pidFile?.config,
128
+ };
129
+ }
130
+ if (pid !== null) {
131
+ if (pidFile && pidFile.pid === pid && isProcessAlive(pidFile.pid)) {
132
+ return {
133
+ ...base,
134
+ state: 'own-gateway',
135
+ pid,
136
+ startedAt: pidFile.startedAt,
137
+ config: pidFile.config,
138
+ };
139
+ }
140
+ return {
141
+ ...base,
142
+ state: 'foreign',
143
+ pid,
144
+ processName: getProcessName(pid) ?? undefined,
145
+ };
146
+ }
147
+ if (pidFile && isProcessAlive(pidFile.pid) && (pidFile.port ?? port) === port) {
148
+ return {
149
+ ...base,
150
+ state: 'own-gateway',
151
+ pid: pidFile.pid,
152
+ startedAt: pidFile.startedAt,
153
+ config: pidFile.config,
154
+ };
155
+ }
156
+ if (probe === 'other') {
157
+ return { ...base, state: 'unknown', pid: null };
158
+ }
159
+ return { ...base, state: 'free', pid: null };
160
+ }
161
+ /** serve start 等待子进程就绪的超时 */
162
+ const STARTUP_TIMEOUT_MS = 20_000;
163
+ /**
164
+ * 等待子进程的 Gateway 就绪
165
+ *
166
+ * 就绪判定(任一满足):
167
+ * 1. 端口持有者 === child.pid(直连 spawn,pid 可信)
168
+ * 2. `/health` 返回 octopi 形状(端口表探测失效时兜底;pid 取端口探测值或 child.pid)
169
+ *
170
+ * 端口被外来者占据时不视为就绪——等子进程退出(race 由上层捕获)或超时,
171
+ * 由 diagnoseStartupFailure 给出结论,避免把外来实例误判为成功。
172
+ *
173
+ * @param port 监听端口
174
+ * @param childPid spawn 返回的子进程 pid
175
+ * @param timeoutMs 最长等待时间
176
+ * @returns 就绪实例 pid;超时返回 null
177
+ */
178
+ async function waitGatewayReady(port, childPid, timeoutMs = STARTUP_TIMEOUT_MS) {
79
179
  const deadline = Date.now() + timeoutMs;
80
180
  while (Date.now() < deadline) {
81
181
  const portPid = findPidOnPort(port);
82
- if (portPid && portPid !== process.pid) {
83
- return portPid;
182
+ if (portPid === childPid)
183
+ return childPid;
184
+ if ((await probeGatewayHealth(port)) === 'octopi') {
185
+ return portPid ?? childPid;
84
186
  }
85
- // health 探测兜底(端口表可能稍慢)
86
- try {
87
- const res = await fetch(`http://127.0.0.1:${port}/health`, {
88
- signal: AbortSignal.timeout(800),
89
- });
90
- if (res.ok) {
91
- return findPidOnPort(port);
92
- }
93
- }
94
- catch { /* not ready */ }
95
187
  await delay(300);
96
188
  }
97
189
  return null;
98
190
  }
191
+ /** Gateway 守护进程日志路径(`OCTOPI_HOME/logs/gateway.log`) */
192
+ export function getGatewayLogPath() {
193
+ return join(getOctopiHome(), 'logs', 'gateway.log');
194
+ }
195
+ /** 读取日志尾部若干非空行 */
196
+ export function readLogTail(logPath, maxLines = 20) {
197
+ try {
198
+ const lines = readFileSync(logPath, 'utf-8').split(/\r?\n/);
199
+ return lines.filter((l) => l.trim().length > 0).slice(-maxLines);
200
+ }
201
+ catch {
202
+ // fork 前失败 / 日志未创建 / 无读权限:降级为“空日志”,诊断走通用提示
203
+ return [];
204
+ }
205
+ }
206
+ /**
207
+ * 把子进程日志尾部翻译成用户可执行的结论(原因 + 出路 + 证据位置)
208
+ *
209
+ * @param opts.logTail 日志尾部行(readLogTail 结果)
210
+ * @param opts.port Gateway 监听端口
211
+ * @param opts.configPath 本次使用的配置路径
212
+ * @param opts.logPath 完整日志路径
213
+ * @returns 逐行输出的诊断文本
214
+ */
215
+ export function diagnoseStartupFailure(opts) {
216
+ const { logTail, port, configPath, logPath } = opts;
217
+ const tail = logTail.join('\n');
218
+ const lines = [];
219
+ if (/EADDRINUSE/i.test(tail)) {
220
+ lines.push(`Port ${port} was taken by another process after the preflight check (EADDRINUSE).`);
221
+ lines.push(` Re-run 'octopi serve start', or start on another port with --port <other>.`);
222
+ }
223
+ else if (/\bEACCES\b|\bEPERM\b/i.test(tail)) {
224
+ lines.push(`Not allowed to bind port ${port} (EACCES) — ports below 1024 may require elevated privileges.`);
225
+ }
226
+ else if (/Cannot find module|ERR_MODULE_NOT_FOUND/i.test(tail)) {
227
+ lines.push('A required module failed to load — the installation may be incomplete or out of sync.');
228
+ lines.push(' Reinstall: npm install (project) or npm install -g octopi-agent (global).');
229
+ }
230
+ else if (/Config file not found/i.test(tail)) {
231
+ lines.push(`Config file not found (searched cwd and ${configPath ?? join(getOctopiHome(), 'octopi.json')}).`);
232
+ lines.push(" Run 'octopi init' to create one, or pass -c <path>.");
233
+ }
234
+ else if (/Config validation failed/i.test(tail)) {
235
+ lines.push(`Configuration is invalid: ${configPath ?? join(getOctopiHome(), 'octopi.json')}`);
236
+ lines.push(' Fix the field reported in the log, then re-run.');
237
+ }
238
+ else if (logTail.length > 0) {
239
+ lines.push('Last lines from the Gateway log:');
240
+ for (const line of logTail)
241
+ lines.push(` ${line}`);
242
+ }
243
+ else {
244
+ lines.push('The Gateway log is empty — the child process produced no output.');
245
+ }
246
+ lines.push(`Full log: ${logPath}`);
247
+ lines.push(`Foreground debug: octopi serve fg${configPath ? ` -c ${configPath}` : ''}`);
248
+ return lines;
249
+ }
99
250
  export function createProvider(name, cfg) {
100
251
  const apiType = cfg.api === 'anthropic-messages' ? 'anthropic' : 'openai';
101
252
  const models = cfg.models.map((m) => ({
@@ -136,45 +287,123 @@ export async function ensureDaemonConfig(args) {
136
287
  }
137
288
  export async function serveStartCommand(args) {
138
289
  const configPath = await ensureDaemonConfig(args);
139
- const existing = resolveGatewayPid(args, configPath);
140
- if (existing.pid) {
141
- console.log(`⚠️ Gateway is already running (PID: ${existing.pid}, port ${existing.port})`);
142
- console.log(`\nUse 'octopi serve restart' to restart, or 'octopi serve stop' to stop.`);
143
- // Gateway 已在跑时仍尝试拉起 Web UI(restart 半失败 / 仅缺 Web UI 的场景)
290
+ const port = resolveListenPort(args, configPath);
291
+ const logPath = getGatewayLogPath();
292
+ const occupant = await identifyPortOccupant(port);
293
+ // 幂等:自己的 Gateway 已在跑 → 引导 status/restart,不报错
294
+ if (occupant.state === 'own-gateway') {
295
+ console.log(`⚠️ Gateway is already running (PID: ${occupant.pid ?? 'unknown'}, port ${port}).`);
296
+ if (occupant.healthy) {
297
+ console.log(' Health: OK');
298
+ }
299
+ else {
300
+ console.log(' Health: process alive but not responding yet (starting or stuck).');
301
+ console.log(" If it stays this way, run 'octopi serve restart'.");
302
+ }
303
+ if (occupant.startedAt)
304
+ console.log(` Started: ${occupant.startedAt}`);
305
+ if (occupant.config)
306
+ console.log(` Config: ${occupant.config}`);
307
+ console.log(`\nUse 'octopi serve status' to inspect, 'octopi serve restart' to restart, or 'octopi serve stop' to stop.`);
144
308
  await webuiStartCommand(configPath, { soft: true });
145
309
  process.exit(0);
146
310
  }
311
+ // 被无关进程占用 → 明确报错 + 三条出路,绝不静默
312
+ if (occupant.state === 'foreign') {
313
+ const who = [
314
+ occupant.processName ?? 'unknown process',
315
+ occupant.pid ? `PID ${occupant.pid}` : null,
316
+ ]
317
+ .filter(Boolean)
318
+ .join(', ');
319
+ console.error(`❌ Cannot start Gateway: port ${port} is occupied by ${who}.`);
320
+ console.error(' The occupant is not an Octopi Gateway.');
321
+ console.error('\n How to resolve:');
322
+ console.error(" 1. Stop the occupying process, then run 'octopi serve start' again");
323
+ console.error(` 2. Start on another port: octopi serve start --port ${port + 1}`);
324
+ console.error(` 3. Change the port permanently: set channels[type=http].port in ${configPath ?? 'your config'}`);
325
+ process.exit(1);
326
+ }
327
+ if (occupant.state === 'unknown') {
328
+ console.warn(`⚠️ Port ${port} has an HTTP service that could not be identified; attempting to start anyway.`);
329
+ console.warn(` If startup fails, the reason will be shown here and in ${logPath}.`);
330
+ }
331
+ // pid 文件是单槽设计:换端口启动时若旧实例仍存活,先明示再接管,避免静默变孤儿
332
+ const prevPidFile = readPidFile();
333
+ if (prevPidFile &&
334
+ isProcessAlive(prevPidFile.pid) &&
335
+ prevPidFile.port !== undefined &&
336
+ prevPidFile.port !== port) {
337
+ console.warn(`⚠️ A tracked Gateway (PID ${prevPidFile.pid}, port ${prevPidFile.port}) is still alive.`);
338
+ console.warn(` Its PID file will be replaced. To stop the old instance: octopi serve stop --port ${prevPidFile.port}`);
339
+ }
147
340
  removePidFile();
341
+ mkdirSync(dirname(logPath), { recursive: true });
342
+ const logFd = openSync(logPath, 'a');
343
+ writeSync(logFd, `\n--- octopi serve start ${new Date().toISOString()} port=${port} ---\n`);
148
344
  const cliPath = resolve(process.argv[1]);
149
345
  const childArgs = ['serve', 'fg'];
150
346
  if (configPath)
151
347
  childArgs.push('--config', configPath);
152
- if (args.port)
153
- childArgs.push('--port', String(args.port));
348
+ childArgs.push('--port', String(port));
154
349
  if (args.verbose)
155
350
  childArgs.push('--verbose');
156
- const child = fork(cliPath, childArgs, {
351
+ // 子进程 stdout/stderr 落日志:失败原因不再随 stdio:ignore 丢弃
352
+ const child = spawn(process.execPath, [cliPath, ...childArgs], {
157
353
  detached: true,
158
- stdio: 'ignore',
159
- execArgv: [],
354
+ stdio: ['ignore', logFd, logFd],
160
355
  env: { ...process.env, OCTOPI_DAEMON: '1' },
161
356
  });
357
+ closeSync(logFd);
162
358
  child.unref();
163
359
  if (!child.pid) {
164
360
  console.error('❌ Failed to start Gateway daemon');
165
361
  process.exit(1);
166
362
  }
167
- const port = resolveListenPort(args, configPath);
363
+ let childExitCode = null;
364
+ let spawnError = null;
365
+ const exited = new Promise((resolveExit) => {
366
+ child.once('exit', (code) => {
367
+ childExitCode = code;
368
+ resolveExit();
369
+ });
370
+ // spawn 本身失败(权限/资源等)只走 error 不走 exit:不挂监听会以裸栈 uncaughtException 收场
371
+ child.once('error', (err) => {
372
+ spawnError = err instanceof Error ? err.message : String(err);
373
+ resolveExit();
374
+ });
375
+ });
168
376
  console.log(`⏳ Waiting for Gateway on port ${port}...`);
169
- const realPid = await waitGatewayReady(port);
170
- if (!realPid) {
171
- console.error('❌ Gateway did not become ready within 20s');
172
- console.error(` Check logs / try: octopi serve fg -c ${configPath ?? '<config>'}`);
173
- // 尽量回收 fork 出的子进程树
174
- await killProcess(child.pid, { timeoutMs: 2000 }).catch(() => undefined);
377
+ const outcome = await Promise.race([
378
+ waitGatewayReady(port, child.pid).then((pid) => ({ kind: 'ready', pid })),
379
+ exited.then(() => ({ kind: 'exited', pid: null })),
380
+ ]);
381
+ if (outcome.kind !== 'ready' || !outcome.pid) {
382
+ if (outcome.kind === 'exited') {
383
+ if (spawnError) {
384
+ console.error(`❌ Failed to launch Gateway child process: ${spawnError}`);
385
+ }
386
+ else {
387
+ console.error(`❌ Gateway exited during startup (exit code ${childExitCode ?? 'unknown'}).`);
388
+ }
389
+ }
390
+ else {
391
+ console.error(`❌ Gateway did not become ready within ${STARTUP_TIMEOUT_MS / 1000}s.`);
392
+ // 尽量回收 spawn 出的子进程树
393
+ await killProcess(child.pid, { timeoutMs: 2000 }).catch(() => undefined);
394
+ }
395
+ for (const line of diagnoseStartupFailure({
396
+ logTail: readLogTail(logPath),
397
+ port,
398
+ configPath,
399
+ logPath,
400
+ })) {
401
+ console.error(line);
402
+ }
175
403
  process.exit(1);
176
404
  }
177
- // 以端口探测到的真实 PID 覆盖,避免 Windows fork pid 不一致
405
+ const realPid = outcome.pid;
406
+ // 以端口探测到的真实 PID 为准(与 spawn 返回的 pid 可能不一致)
178
407
  writePidFile({
179
408
  pid: realPid,
180
409
  config: configPath ?? join(getOctopiHome(), 'octopi.json'),
@@ -184,6 +413,7 @@ export async function serveStartCommand(args) {
184
413
  console.log(`✅ Gateway started (PID: ${realPid})`);
185
414
  console.log(` Config: ${configPath ?? join(getOctopiHome(), 'octopi.json')}`);
186
415
  console.log(` Port: ${port}`);
416
+ console.log(` Log: ${logPath}`);
187
417
  // Web UI 为可选:失败不拖垮 Gateway(跨平台/无 web 依赖时仍可 serve)
188
418
  await webuiStartCommand(configPath, { soft: true });
189
419
  console.log(`\nUse 'octopi serve stop' to stop, 'octopi serve status' to check.`);
@@ -202,7 +432,7 @@ export async function serveStopCommand(args = {}) {
202
432
  removePidFile();
203
433
  console.log('ℹ️ No running Gateway found (cleaned PID file if any).');
204
434
  }
205
- await webuiStopCommand();
435
+ await webuiStopCommand(args.config);
206
436
  return;
207
437
  }
208
438
  let anyStillAlive = false;
@@ -244,7 +474,7 @@ export async function serveStopCommand(args = {}) {
244
474
  console.warn(` taskkill /PID ${keepPid} /F`);
245
475
  }
246
476
  console.log(anyStillAlive ? '⚠️ Gateway not fully stopped.' : '✅ Gateway stopped.');
247
- await webuiStopCommand();
477
+ await webuiStopCommand(args.config);
248
478
  }
249
479
  export async function serveRestartCommand(args) {
250
480
  await serveStopCommand(args);
@@ -283,6 +513,12 @@ export async function serveFgCommand(args) {
283
513
  const port = resolveListenPort(args, configPath);
284
514
  const portPid = findPidOnPort(port);
285
515
  if (portPid && portPid !== process.pid) {
516
+ // 守护模式下 preflight 已做过占用者识别:静默杀进程与「失败上浮」契约冲突,
517
+ // 直接失败让父进程按日志给出结论(EADDRINUSE / 占用者信息)
518
+ if (process.env.OCTOPI_DAEMON === '1') {
519
+ console.error(`❌ Port ${port} is already occupied by PID ${portPid} (appeared after preflight).`);
520
+ process.exit(1);
521
+ }
286
522
  console.log(`⚠️ Port ${port} is occupied by PID ${portPid}. Killing...`);
287
523
  const killed = await killProcess(portPid, { timeoutMs: 3000 });
288
524
  if (!killed && findPidOnPort(port) === portPid) {
@@ -471,10 +707,12 @@ async function startGatewayBlocking(configPath, args) {
471
707
  catch (err) {
472
708
  console.warn(`[CLI] session history tools unavailable: ${err instanceof Error ? err.message : String(err)}`);
473
709
  }
710
+ const documentPort = await gateway.getDocumentPort().catch(() => null);
474
711
  const { all } = createToolSet({
475
712
  webSearch: webSearchToolCfg,
476
713
  summary: summarySupport,
477
714
  sessionHistory: sessionHistoryPort,
715
+ documentPort,
478
716
  askUser: (question, options, context) => gateway.askUser({
479
717
  sessionId: context.sessionId,
480
718
  agentId: context.agentId,
@@ -513,7 +751,7 @@ async function startGatewayBlocking(configPath, args) {
513
751
  agentSignal: mountAgentSignal,
514
752
  });
515
753
  const httpConfig = config.channels?.find((c) => c.type === 'http');
516
- const listenPort = args.port ?? httpConfig?.port ?? 3000;
754
+ const listenPort = args.port ?? httpConfig?.port ?? 18180;
517
755
  // web.host 可作 Gateway HTTP 的缺省(局域网访问两者都要放开);channels[].host 优先
518
756
  const listenHostConfig = httpConfig?.host ?? config.web?.host;
519
757
  if (httpConfig || args.port) {
@@ -25,11 +25,23 @@ export declare function findWebDir(configPath?: string, configWebDir?: string):
25
25
  export interface StartWebUiOptions {
26
26
  /** listen host(local → 127.0.0.1,lan → 0.0.0.0) */
27
27
  hostArg?: string;
28
- /** listen port(默认 5173) */
28
+ /** listen port(默认 8180) */
29
29
  port?: number;
30
+ /** 网关端口:透传给 serve-webui 动态下发 /octopi-config.js(缺省不下发) */
31
+ gatewayPort?: number;
30
32
  }
31
33
  export declare function startWebUi(distDir: string, options?: StartWebUiOptions): number | null;
32
34
  export declare function stopWebUi(pid: number): Promise<void>;
35
+ /**
36
+ * `/octopi-config.js` 响应体:把网关端口运行时下发给前端。
37
+ *
38
+ * 唯一真相源是 `octopi.json`——serve-webui 启动时读取,前端加载本脚本后
39
+ * 优先使用其中的端口,构建期兜底仅作回退。
40
+ *
41
+ * @param port 网关端口;undefined 时下发 null(前端走默认)
42
+ * @returns JavaScript 赋值语句
43
+ */
44
+ export declare function gatewayConfigScript(port?: number): string;
33
45
  export declare function getWebUiPidPath(): string;
34
46
  export declare function readWebUiPidRecord(): WebUiPidRecord | null;
35
47
  export declare function readWebUiPidFile(): number | null;
@@ -85,11 +85,27 @@ export function startWebUi(distDir, options) {
85
85
  args.push('--host', options.hostArg);
86
86
  if (options?.port)
87
87
  args.push('--port', String(options.port));
88
+ if (options?.gatewayPort)
89
+ args.push('--gateway-port', String(options.gatewayPort));
88
90
  return spawnDetached(process.execPath, args, { cwd: distDir });
89
91
  }
90
92
  export async function stopWebUi(pid) {
91
93
  await killProcess(pid, { timeoutMs: 3000 });
92
94
  }
95
+ /**
96
+ * `/octopi-config.js` 响应体:把网关端口运行时下发给前端。
97
+ *
98
+ * 唯一真相源是 `octopi.json`——serve-webui 启动时读取,前端加载本脚本后
99
+ * 优先使用其中的端口,构建期兜底仅作回退。
100
+ *
101
+ * @param port 网关端口;undefined 时下发 null(前端走默认)
102
+ * @returns JavaScript 赋值语句
103
+ */
104
+ export function gatewayConfigScript(port) {
105
+ return port !== undefined
106
+ ? `window.__OCTOPI_GATEWAY__=${JSON.stringify({ port })};\n`
107
+ : 'window.__OCTOPI_GATEWAY__=null;\n';
108
+ }
93
109
  export function getWebUiPidPath() {
94
110
  return join(getOctopiHome(), 'webui.pid');
95
111
  }
@@ -154,5 +170,5 @@ export function resolveGatewayUrl(config) {
154
170
  if (httpChannel?.port) {
155
171
  return `http://localhost:${httpChannel.port}`;
156
172
  }
157
- return 'http://localhost:3000';
173
+ return 'http://localhost:18180';
158
174
  }
@@ -18,6 +18,8 @@ export declare function isProcessAlive(pid: number): boolean;
18
18
  export declare function isSelfOrAncestorPid(pid: number): boolean;
19
19
  /** 查找监听指定 TCP 端口的进程 PID(排除自身) */
20
20
  export declare function findPidOnPort(port: number): number | null;
21
+ /** 尽力获取进程可执行名(Windows: tasklist;Unix: ps)。失败返回 null */
22
+ export declare function getProcessName(pid: number): string | null;
21
23
  /**
22
24
  * 终结进程(Windows 用 taskkill 杀进程树,避免 vite/cmd 残留子进程)
23
25
  *
@@ -129,6 +129,34 @@ export function findPidOnPort(port) {
129
129
  ? findPidOnPortWindows(port)
130
130
  : findPidOnPortUnix(port);
131
131
  }
132
+ /** 尽力获取进程可执行名(Windows: tasklist;Unix: ps)。失败返回 null */
133
+ export function getProcessName(pid) {
134
+ if (!Number.isInteger(pid) || pid <= 0)
135
+ return null;
136
+ try {
137
+ if (process.platform === 'win32') {
138
+ const out = execFileSync('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {
139
+ encoding: 'utf-8',
140
+ timeout: 5000,
141
+ stdio: 'pipe',
142
+ }).trim();
143
+ if (!out || out.startsWith('INFO'))
144
+ return null;
145
+ const name = out.split(',')[0]?.replace(/^"|"$/g, '').trim();
146
+ return name || null;
147
+ }
148
+ const out = execFileSync('ps', ['-p', String(pid), '-o', 'comm='], {
149
+ encoding: 'utf-8',
150
+ timeout: 5000,
151
+ stdio: 'pipe',
152
+ }).trim();
153
+ return out || null;
154
+ }
155
+ catch {
156
+ // 进程可能已退出或无权限查询:名字是锦上添花,缺失不阻塞主流程
157
+ return null;
158
+ }
159
+ }
132
160
  /**
133
161
  * 终结进程(Windows 用 taskkill 杀进程树,避免 vite/cmd 残留子进程)
134
162
  *
@@ -242,9 +270,37 @@ export function spawnDetached(command, args, options = {}) {
242
270
  function psQuote(value) {
243
271
  return `'${value.replace(/'/g, "''")}'`;
244
272
  }
273
+ /**
274
+ * 按 CommandLineToArgvW 规则给单个参数加双引号。
275
+ *
276
+ * `Start-Process -ArgumentList` 会把数组元素按空格拼接且不补引号,
277
+ * 不预先 quoting 的话,含空格/引号的参数(长 -e 脚本、带空格的用户路径)
278
+ * 传到子进程会被拆碎。
279
+ */
280
+ function winQuoteArg(arg) {
281
+ if (arg.length > 0 && !/[\s"]/.test(arg))
282
+ return arg;
283
+ let result = '"';
284
+ let backslashes = 0;
285
+ for (const ch of arg) {
286
+ if (ch === '\\') {
287
+ backslashes++;
288
+ continue;
289
+ }
290
+ if (ch === '"') {
291
+ result += '\\'.repeat(backslashes * 2 + 1) + '"';
292
+ backslashes = 0;
293
+ continue;
294
+ }
295
+ result += '\\'.repeat(backslashes) + ch;
296
+ backslashes = 0;
297
+ }
298
+ result += '\\'.repeat(backslashes * 2) + '"';
299
+ return result;
300
+ }
245
301
  function spawnDetachedWindows(command, args, options) {
246
302
  const cwd = typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined;
247
- const argArray = args.map(psQuote).join(', ');
303
+ const argArray = args.map((a) => psQuote(winQuoteArg(a))).join(', ');
248
304
  const workDir = cwd ? ` -WorkingDirectory ${psQuote(cwd)}` : '';
249
305
  const script = `$p = Start-Process -FilePath ${psQuote(command)} -ArgumentList @(${argArray})${workDir} -WindowStyle Hidden -PassThru; ` +
250
306
  `if ($p) { Write-Output $p.Id }`;