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,549 @@
1
+ /**
2
+ * CLI 守护进程管理
3
+ */
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';
7
+ import { getOctopiHome, isInitialized, initOctopi, formatInitReport } from '../init.js';
8
+ import { loadConfig, toGatewayConfig } from '../config.js';
9
+ import { createToolSet } from '@octopi-agent/engine/harness/extension/plugin-ecosystem/tools/tool-set.js';
10
+ import { OpenAIProvider } from '@octopi-agent/engine/integration/providers/openai.js';
11
+ import { AnthropicProvider } from '@octopi-agent/engine/integration/providers/anthropic.js';
12
+ import { Gateway } from '@octopi-agent/gateway/gateway/gateway.js';
13
+ import { webuiStartCommand, webuiStopCommand } from './webui.js';
14
+ import { delay, findPidOnPort, isProcessAlive, killProcess, killProcessOnPort, } from './process-utils.js';
15
+ // Re-export for existing importers (commands.ts / helpers.ts)
16
+ export { findPidOnPort, isProcessAlive, killProcessOnPort };
17
+ export function getPidPath() {
18
+ return join(getOctopiHome(), 'gateway.pid');
19
+ }
20
+ export function readPidFile() {
21
+ const pidPath = getPidPath();
22
+ if (!existsSync(pidPath))
23
+ return null;
24
+ try {
25
+ return JSON.parse(readFileSync(pidPath, 'utf-8'));
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ export function writePidFile(data) {
32
+ const pidPath = getPidPath();
33
+ mkdirSync(dirname(pidPath), { recursive: true });
34
+ writeFileSync(pidPath, JSON.stringify(data, null, 2));
35
+ }
36
+ export function removePidFile() {
37
+ const pidPath = getPidPath();
38
+ if (existsSync(pidPath)) {
39
+ try {
40
+ unlinkSync(pidPath);
41
+ }
42
+ catch { /* ignore */ }
43
+ }
44
+ }
45
+ /** 从配置解析 Gateway 监听端口 */
46
+ export function resolveListenPort(args, configPath) {
47
+ if (args.port)
48
+ return args.port;
49
+ const path = configPath ?? args.config;
50
+ try {
51
+ const config = loadConfig(path);
52
+ const httpChannel = config.channels?.find((c) => c.type === 'http');
53
+ if (httpChannel?.port)
54
+ return httpChannel.port;
55
+ }
56
+ catch { /* fall through */ }
57
+ return 3000;
58
+ }
59
+ /**
60
+ * 解析当前 Gateway 的真实 PID
61
+ *
62
+ * 优先端口占用者(最可靠);其次 pid 文件且进程存活。
63
+ * Windows 上 fork 返回的 pid 与子进程 process.pid 可能不一致,
64
+ * 不能只信 serve start 写下的 pid。
65
+ */
66
+ export function resolveGatewayPid(args, configPath) {
67
+ const port = resolveListenPort(args, configPath);
68
+ const portPid = findPidOnPort(port);
69
+ if (portPid && portPid !== process.pid) {
70
+ return { pid: portPid, port, source: 'port' };
71
+ }
72
+ const pidFile = readPidFile();
73
+ if (pidFile && isProcessAlive(pidFile.pid) && pidFile.pid !== process.pid) {
74
+ return { pid: pidFile.pid, port: pidFile.port ?? port, source: 'pidfile' };
75
+ }
76
+ return { pid: null, port, source: 'none' };
77
+ }
78
+ async function waitGatewayReady(port, timeoutMs = 20_000) {
79
+ const deadline = Date.now() + timeoutMs;
80
+ while (Date.now() < deadline) {
81
+ const portPid = findPidOnPort(port);
82
+ if (portPid && portPid !== process.pid) {
83
+ return portPid;
84
+ }
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
+ await delay(300);
96
+ }
97
+ return null;
98
+ }
99
+ export function createProvider(name, cfg) {
100
+ const apiType = cfg.api === 'anthropic-messages' ? 'anthropic' : 'openai';
101
+ const models = cfg.models.map((m) => ({
102
+ name: m.name ?? m.id,
103
+ contextWindow: m.contextWindow,
104
+ maxOutputTokens: m.maxTokens,
105
+ }));
106
+ if (apiType === 'anthropic') {
107
+ return new AnthropicProvider({
108
+ name,
109
+ apiKey: cfg.apiKey,
110
+ baseUrl: cfg.baseUrl,
111
+ models,
112
+ timeoutMs: cfg.timeoutSeconds ? cfg.timeoutSeconds * 1000 : undefined,
113
+ });
114
+ }
115
+ return new OpenAIProvider({
116
+ name,
117
+ apiKey: cfg.apiKey,
118
+ baseUrl: cfg.baseUrl,
119
+ models,
120
+ timeoutMs: cfg.timeoutSeconds ? cfg.timeoutSeconds * 1000 : undefined,
121
+ });
122
+ }
123
+ export async function ensureDaemonConfig(args) {
124
+ if (args.config)
125
+ return args.config;
126
+ const home = getOctopiHome();
127
+ if (isInitialized(home))
128
+ return resolve(home, 'octopi.json');
129
+ if (isInitialized(process.cwd()))
130
+ return undefined;
131
+ console.log('🐙 First run detected. Initializing Octopi...\n');
132
+ const result = await initOctopi();
133
+ console.log(formatInitReport(result));
134
+ console.log('');
135
+ return result.configPath;
136
+ }
137
+ export async function serveStartCommand(args) {
138
+ 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 的场景)
144
+ await webuiStartCommand(configPath, { soft: true });
145
+ process.exit(0);
146
+ }
147
+ removePidFile();
148
+ const cliPath = resolve(process.argv[1]);
149
+ const childArgs = ['serve', 'fg'];
150
+ if (configPath)
151
+ childArgs.push('--config', configPath);
152
+ if (args.port)
153
+ childArgs.push('--port', String(args.port));
154
+ if (args.verbose)
155
+ childArgs.push('--verbose');
156
+ const child = fork(cliPath, childArgs, {
157
+ detached: true,
158
+ stdio: 'ignore',
159
+ execArgv: [],
160
+ env: { ...process.env, OCTOPI_DAEMON: '1' },
161
+ });
162
+ child.unref();
163
+ if (!child.pid) {
164
+ console.error('❌ Failed to start Gateway daemon');
165
+ process.exit(1);
166
+ }
167
+ const port = resolveListenPort(args, configPath);
168
+ 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);
175
+ process.exit(1);
176
+ }
177
+ // 以端口探测到的真实 PID 覆盖,避免 Windows fork pid 不一致
178
+ writePidFile({
179
+ pid: realPid,
180
+ config: configPath ?? join(getOctopiHome(), 'octopi.json'),
181
+ port,
182
+ startedAt: new Date().toISOString(),
183
+ });
184
+ console.log(`✅ Gateway started (PID: ${realPid})`);
185
+ console.log(` Config: ${configPath ?? join(getOctopiHome(), 'octopi.json')}`);
186
+ console.log(` Port: ${port}`);
187
+ // Web UI 为可选:失败不拖垮 Gateway(跨平台/无 web 依赖时仍可 serve)
188
+ await webuiStartCommand(configPath, { soft: true });
189
+ console.log(`\nUse 'octopi serve stop' to stop, 'octopi serve status' to check.`);
190
+ process.exit(0);
191
+ }
192
+ export async function serveStopCommand(args = {}) {
193
+ const resolved = resolveGatewayPid(args);
194
+ const pidFile = readPidFile();
195
+ const targets = new Set();
196
+ if (resolved.pid)
197
+ targets.add(resolved.pid);
198
+ if (pidFile && isProcessAlive(pidFile.pid))
199
+ targets.add(pidFile.pid);
200
+ if (targets.size === 0) {
201
+ if (pidFile || resolved.source === 'none') {
202
+ removePidFile();
203
+ console.log('ℹ️ No running Gateway found (cleaned PID file if any).');
204
+ }
205
+ await webuiStopCommand();
206
+ return;
207
+ }
208
+ let anyStillAlive = false;
209
+ for (const pid of targets) {
210
+ console.log(`🛑 Stopping Gateway (PID: ${pid})...`);
211
+ const stopped = await killProcess(pid, { timeoutMs: 3000 });
212
+ if (!stopped || isProcessAlive(pid)) {
213
+ anyStillAlive = true;
214
+ console.warn(`⚠️ Gateway PID ${pid} may still be running (permission denied or still exiting)`);
215
+ }
216
+ }
217
+ // 端口清理兜底(killProcess 内部会拒绝杀 self/ancestor)
218
+ const portPid = findPidOnPort(resolved.port);
219
+ if (portPid && portPid !== process.pid) {
220
+ console.log(`🛑 Freeing port ${resolved.port} (PID: ${portPid})...`);
221
+ await killProcess(portPid, { timeoutMs: 3000 });
222
+ }
223
+ const portStillHeld = findPidOnPort(resolved.port);
224
+ if (portStillHeld && portStillHeld !== process.pid) {
225
+ anyStillAlive = true;
226
+ console.warn(`⚠️ Port ${resolved.port} still held by PID ${portStillHeld}`);
227
+ }
228
+ if (!anyStillAlive) {
229
+ removePidFile();
230
+ }
231
+ else if (portStillHeld || resolved.pid || pidFile?.pid) {
232
+ // 保留 pid 文件,避免下次 status/start 误判“没有实例”
233
+ const keepPid = portStillHeld ?? resolved.pid ?? pidFile?.pid;
234
+ if (keepPid && keepPid > 0) {
235
+ writePidFile({
236
+ pid: keepPid,
237
+ config: pidFile?.config ?? join(getOctopiHome(), 'octopi.json'),
238
+ port: resolved.port,
239
+ startedAt: pidFile?.startedAt ?? new Date().toISOString(),
240
+ });
241
+ }
242
+ console.warn('⚠️ Gateway stop incomplete — process still alive.');
243
+ console.warn(' If it was started from an elevated shell, stop it from an elevated terminal:');
244
+ console.warn(` taskkill /PID ${keepPid} /F`);
245
+ }
246
+ console.log(anyStillAlive ? '⚠️ Gateway not fully stopped.' : '✅ Gateway stopped.');
247
+ await webuiStopCommand();
248
+ }
249
+ export async function serveRestartCommand(args) {
250
+ await serveStopCommand(args);
251
+ await delay(500);
252
+ await serveStartCommand(args);
253
+ }
254
+ export async function serveStatusCommand(args = {}) {
255
+ const pidFile = readPidFile();
256
+ const resolved = resolveGatewayPid(args, args.config);
257
+ if (!pidFile && !resolved.pid) {
258
+ console.log('ℹ️ No Gateway instance found.');
259
+ return;
260
+ }
261
+ const alive = resolved.pid !== null;
262
+ console.log(`\n🐙 Gateway Status\n`);
263
+ console.log(` PID: ${resolved.pid ?? pidFile?.pid ?? '—'}`);
264
+ console.log(` Status: ${alive ? '🟢 Running' : '🔴 Stopped'}`);
265
+ console.log(` Source: ${resolved.source}`);
266
+ if (pidFile?.config)
267
+ console.log(` Config: ${pidFile.config}`);
268
+ if (pidFile?.startedAt)
269
+ console.log(` Started: ${pidFile.startedAt}`);
270
+ console.log(` Port: ${resolved.port}`);
271
+ console.log();
272
+ if (!alive && pidFile) {
273
+ console.log(' ⚠️ PID file is stale (no listener on port / process dead).');
274
+ console.log(` Run 'octopi serve start' to start a new instance.\n`);
275
+ }
276
+ if (alive && pidFile && pidFile.pid !== resolved.pid) {
277
+ console.log(` ℹ️ PID file (${pidFile.pid}) differs from live process (${resolved.pid}).`);
278
+ console.log(` Status/stop use the live process.\n`);
279
+ }
280
+ }
281
+ export async function serveFgCommand(args) {
282
+ const configPath = await ensureDaemonConfig(args);
283
+ const port = resolveListenPort(args, configPath);
284
+ const portPid = findPidOnPort(port);
285
+ if (portPid && portPid !== process.pid) {
286
+ console.log(`⚠️ Port ${port} is occupied by PID ${portPid}. Killing...`);
287
+ const killed = await killProcess(portPid, { timeoutMs: 3000 });
288
+ if (!killed && findPidOnPort(port) === portPid) {
289
+ console.error(`❌ Port ${port} still held by PID ${portPid} (likely elevated/foreign process).`);
290
+ console.error(' Stop that process first, or use a different --port.');
291
+ process.exit(1);
292
+ }
293
+ await delay(500);
294
+ }
295
+ await startGatewayBlocking(configPath, args);
296
+ }
297
+ export async function serveCommand(args) {
298
+ switch (args.subcommand) {
299
+ case 'start':
300
+ return serveStartCommand(args);
301
+ case 'stop':
302
+ return serveStopCommand(args);
303
+ case 'restart':
304
+ return serveRestartCommand(args);
305
+ case 'status':
306
+ return serveStatusCommand(args);
307
+ case 'fg':
308
+ return serveFgCommand(args);
309
+ case undefined:
310
+ console.log('💡 Tip: Use "octopi serve start" for background mode.\n');
311
+ return serveFgCommand(args);
312
+ default:
313
+ console.error(`Unknown serve subcommand: ${args.subcommand}`);
314
+ console.error('Valid subcommands: start, stop, restart, status, fg');
315
+ process.exit(1);
316
+ }
317
+ }
318
+ async function startGatewayBlocking(configPath, args) {
319
+ const config = loadConfig(configPath);
320
+ const gatewayConfig = toGatewayConfig(config);
321
+ // AgentRuntime 构造参数在 toGatewayConfig 已带上;此处仅防御显式覆盖
322
+ if (config.agentRuntime) {
323
+ gatewayConfig.agentRuntime = {
324
+ ...gatewayConfig.agentRuntime,
325
+ coalesceWindowMs: config.agentRuntime.coalesceWindowMs,
326
+ coalesceBufferLimit: config.agentRuntime.coalesceBufferLimit,
327
+ expectedMaxConcurrentRuns: config.agentRuntime.expectedMaxConcurrentRuns,
328
+ };
329
+ }
330
+ if (args.port)
331
+ gatewayConfig.port = args.port;
332
+ if (args.verbose && !gatewayConfig.trace) {
333
+ const os = await import('node:os');
334
+ const path = await import('node:path');
335
+ gatewayConfig.trace = {
336
+ outputDir: path.join(os.homedir(), '.octopi', 'traces'),
337
+ level: 'DEBUG',
338
+ };
339
+ console.log('[CLI] Verbose mode: tracing enabled');
340
+ }
341
+ // 与 Gateway 共享 SessionStore(history 检索与运行时同一真相源)
342
+ const { getOctopiHome } = await import('@octopi-agent/engine/paths.js');
343
+ const { join: joinPath } = await import('node:path');
344
+ const { JsonlSessionStore } = await import('@octopi-agent/engine/integration/storage/jsonl.js');
345
+ const home = getOctopiHome();
346
+ let sessionIndex;
347
+ // 先建无 index 的 store 供新鲜度校验;再挂投影
348
+ const storeForRebuild = new JsonlSessionStore({
349
+ sessionsDir: joinPath(home, 'sessions'),
350
+ });
351
+ try {
352
+ const { createSqliteSessionIndex, ensureSessionIndexFresh } = await import('@octopi-agent/engine/integration/storage/session-index.js');
353
+ sessionIndex = await createSqliteSessionIndex({
354
+ dbPath: joinPath(home, 'sessions.index.db'),
355
+ });
356
+ await sessionIndex.ensureSchema();
357
+ // 存量/首次启用:投影数与权威 list 对齐,避免空索引误杀 search
358
+ const fresh = await ensureSessionIndexFresh(sessionIndex, storeForRebuild);
359
+ if (fresh.rebuilt) {
360
+ console.log(`[CLI] session index rebuilt from sessions/ (${fresh.sessions} sessions)`);
361
+ }
362
+ }
363
+ catch (err) {
364
+ sessionIndex = undefined;
365
+ console.warn(`[CLI] session index unavailable (scan-only search): ${err instanceof Error ? err.message : String(err)}`);
366
+ }
367
+ const gatewayStoreForHistory = new JsonlSessionStore({
368
+ sessionsDir: joinPath(home, 'sessions'),
369
+ index: sessionIndex,
370
+ });
371
+ const gateway = new Gateway(gatewayConfig, gatewayStoreForHistory);
372
+ for (const [providerName, providerCfg] of Object.entries(config.models?.providers ?? {})) {
373
+ const provider = createProvider(providerName, providerCfg);
374
+ if (provider) {
375
+ gateway.registerProvider(provider);
376
+ console.log(`[CLI] Registered provider: ${providerName} (${providerCfg.api})`);
377
+ }
378
+ }
379
+ // memory 工具不在 Gateway 全局注册:AgentBuilder.build() 按各 agent 的 MemoryStore
380
+ //(SqliteMemoryStore(agent.db))创建 memory_store/search,与七层 MemoryLayer / memory.steward.* 同实例。
381
+ // SessionTaskService 随 AgentBuilder/Gateway 的 SessionStore 自动接线;不再单独建 TaskTracker。
382
+ let webSearchToolCfg;
383
+ if (config.webSearch?.providers && Object.keys(config.webSearch.providers).length > 0) {
384
+ const { resolveWebSearchProviders, createWebSearchWithFallback } = await import('@octopi-agent/engine/integration/web-search/factory.js');
385
+ const resolved = resolveWebSearchProviders(config.webSearch);
386
+ if (resolved.primary) {
387
+ webSearchToolCfg = {
388
+ provider: createWebSearchWithFallback(resolved.primary, resolved.fallbacks),
389
+ defaultLimit: resolved.defaultLimit,
390
+ timeoutMs: resolved.timeoutMs,
391
+ };
392
+ console.log(`[CLI] Web search enabled: primary=${resolved.primary.id} (api=${resolved.primaryApi}), ` +
393
+ `fallbacks=[${resolved.fallbacks.map((f) => f.id).join(', ')}]`);
394
+ }
395
+ }
396
+ // 公用能力 SummaryPort(http_request / file_read L2);无可用 provider 时仅 L1
397
+ let summarySupport;
398
+ try {
399
+ const { createSummaryPort, createToolSummarySupport, createMemorySummaryCache } = await import('@octopi-agent/engine/harness/context/capabilities/summary/index.js');
400
+ const providerMap = new Map();
401
+ let fallback;
402
+ for (const [providerName, providerCfg] of Object.entries(config.models?.providers ?? {})) {
403
+ const provider = createProvider(providerName, providerCfg);
404
+ if (provider) {
405
+ providerMap.set(providerName, provider);
406
+ fallback = fallback ?? provider;
407
+ }
408
+ }
409
+ if (fallback) {
410
+ const summaryCfg = config.summary;
411
+ const toolsCfg = summaryCfg?.tools;
412
+ let cache;
413
+ let cacheEnabled = false;
414
+ if (summaryCfg?.cache?.enabled) {
415
+ cache = createMemorySummaryCache({
416
+ maxEntries: summaryCfg.cache.maxEntries,
417
+ defaultTtlMs: summaryCfg.cache.ttlMs,
418
+ });
419
+ cacheEnabled = true;
420
+ }
421
+ const policyOverrides = summaryCfg?.policies;
422
+ const portOptions = {
423
+ providers: providerMap,
424
+ levelMap: config.models?.level,
425
+ fallbackProvider: fallback,
426
+ legacySummaryModel: config.contextEngine?.summaryModel,
427
+ model: summaryCfg?.model,
428
+ modelLevel: summaryCfg?.modelLevel,
429
+ gate: summaryCfg?.gate,
430
+ defaultInputBudgetTokens: summaryCfg?.defaultInputBudgetTokens,
431
+ safetyMarginTokens: summaryCfg?.safetyMarginTokens,
432
+ oversizedStrategy: summaryCfg?.oversizedStrategy,
433
+ policyOverrides,
434
+ cache,
435
+ cacheEnabled,
436
+ cacheTtlMs: summaryCfg?.cache?.ttlMs,
437
+ maxReturnCharsDefault: toolsCfg?.maxReturnChars,
438
+ toolBindings: {
439
+ http_request: toolsCfg?.http_request,
440
+ file_read: toolsCfg?.file_read,
441
+ },
442
+ };
443
+ const port = createSummaryPort(portOptions);
444
+ // 根因修复:配置与 tools 共用同一 binding 解析表(toolBindings),不再 binding:undefined
445
+ summarySupport = createToolSummarySupport(port, portOptions);
446
+ console.log('[CLI] Summary capability: SummaryPort wired into builtin tools');
447
+ }
448
+ }
449
+ catch (err) {
450
+ console.warn(`[CLI] Summary capability wiring failed (L1-only tools): ${err instanceof Error ? err.message : String(err)}`);
451
+ }
452
+ // 全局工具:CLI 级 builtin(shell/file/http/web_search 等)。
453
+ // memory_store/memory_search **不在**全局注册:由 AgentBuilder 在 agent build 时
454
+ // 按各 agent 的 MemoryStore(SqliteMemoryStore(agent.db))注入,与 MemoryLayer 同实例。
455
+ // session_search / session_read:Information 历史检索,绑 Gateway 同一 SessionStore。
456
+ let sessionHistoryPort;
457
+ try {
458
+ const { createSessionHistoryPort } = await import('@octopi-agent/engine/harness/session/history/index.js');
459
+ const { SessionAclService } = await import('@octopi-agent/engine/harness/governance/session-acl/service.js');
460
+ sessionHistoryPort = createSessionHistoryPort({
461
+ store: gatewayStoreForHistory,
462
+ sessionAcl: new SessionAclService(gatewayConfig.sessionAcl),
463
+ archiveDir: joinPath(home, 'archives'),
464
+ historyScope: 'participated',
465
+ index: sessionIndex,
466
+ // E6 agent.max:与 Runner agentMaxSessionRights 同源(宿主可按 agent 收紧)
467
+ resolveAgentMax: () => undefined,
468
+ });
469
+ console.log('[CLI] session_search/session_read: SessionHistoryPort @ OCTOPI_HOME/sessions');
470
+ }
471
+ catch (err) {
472
+ console.warn(`[CLI] session history tools unavailable: ${err instanceof Error ? err.message : String(err)}`);
473
+ }
474
+ const { all } = createToolSet({
475
+ webSearch: webSearchToolCfg,
476
+ summary: summarySupport,
477
+ sessionHistory: sessionHistoryPort,
478
+ askUser: (question, options, context) => gateway.askUser({
479
+ sessionId: context.sessionId,
480
+ agentId: context.agentId,
481
+ question,
482
+ options,
483
+ }),
484
+ });
485
+ for (const tool of all)
486
+ gateway.registerTool(tool);
487
+ console.log(`[CLI] Registered ${all.length} global tools: ${all.map(t => t.definition.name).join(', ')}`);
488
+ console.log('[CLI] memory_store/memory_search: agent-scoped (AgentBuilder + memoryStore), not global');
489
+ // ── 子系统发现(启动可见;Agent 首次 build 时按 allow/deny 实际注册) ──
490
+ try {
491
+ const { discoverSubsystemSpecs } = await import('@octopi-agent/engine/harness/agent/builder.js');
492
+ const { specs, errors } = await discoverSubsystemSpecs();
493
+ if (specs.length > 0) {
494
+ console.log(`[CLI] subsystems discovered: ${specs.map((s) => s.id).join(', ')}`);
495
+ }
496
+ else {
497
+ console.log('[CLI] subsystems discovered: (none)');
498
+ }
499
+ for (const err of errors) {
500
+ console.warn(`[CLI] subsystem load error at ${err.path}: ${err.error}`);
501
+ }
502
+ }
503
+ catch (err) {
504
+ console.warn(`[CLI] subsystem discovery failed: ${err instanceof Error ? err.message : String(err)}`);
505
+ }
506
+ // ── Agent Runtime:按配置块挂载 Source(无 enabled 总开关;不写 schedule/escalate 即不挂)──
507
+ const arCfg = config.agentRuntime;
508
+ // agentSignal:显式 true,或 escalate 已配置可用 defaultAgentId 时默认挂
509
+ const mountAgentSignal = arCfg?.agentSignal === true || !!arCfg?.escalate?.defaultAgentId;
510
+ await gateway.configureAgentRuntime({
511
+ schedule: arCfg?.schedule,
512
+ escalate: arCfg?.escalate,
513
+ agentSignal: mountAgentSignal,
514
+ });
515
+ const httpConfig = config.channels?.find((c) => c.type === 'http');
516
+ const listenPort = args.port ?? httpConfig?.port ?? 3000;
517
+ // web.host 可作 Gateway HTTP 的缺省(局域网访问两者都要放开);channels[].host 优先
518
+ const listenHostConfig = httpConfig?.host ?? config.web?.host;
519
+ if (httpConfig || args.port) {
520
+ const { HttpChannelAdapter } = await import('@octopi-agent/gateway/protocols/http.js');
521
+ const { WebApiRouter } = await import('@octopi-agent/gateway/web/api/router.js');
522
+ const { resolveListenHost } = await import('@octopi-agent/engine/config.js');
523
+ const webApiRouter = new WebApiRouter({ gateway, basePath: '/api/v1' });
524
+ const listenHost = resolveListenHost(listenHostConfig);
525
+ gateway.registerChannel(new HttpChannelAdapter({
526
+ port: listenPort,
527
+ host: listenHost,
528
+ path: httpConfig?.path ?? '/messages',
529
+ apiKey: httpConfig?.apiKey,
530
+ corsOrigins: httpConfig?.corsOrigins,
531
+ onRequest: (req, res) => webApiRouter.handle(req, res),
532
+ }));
533
+ }
534
+ const shutdown = async () => {
535
+ console.log('\n[CLI] Shutting down...');
536
+ await gateway.stop();
537
+ removePidFile();
538
+ process.exit(0);
539
+ };
540
+ process.on('SIGINT', shutdown);
541
+ process.on('SIGTERM', shutdown);
542
+ writePidFile({
543
+ pid: process.pid,
544
+ config: configPath ?? join(getOctopiHome(), 'octopi.json'),
545
+ port: httpConfig || args.port ? listenPort : undefined,
546
+ startedAt: new Date().toISOString(),
547
+ });
548
+ await gateway.start();
549
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * doctor 数据层:agent.db 迁移检查 + session.store 废弃检测
3
+ *
4
+ * 本地确定性;node:sqlite / agent.db 不可用时只报告,不拖垮 doctor。
5
+ *
6
+ * @module
7
+ */
8
+ export interface DataFixResult {
9
+ findings: Array<{
10
+ id: string;
11
+ domain: 'data' | 'config';
12
+ severity: 'error' | 'warn' | 'info' | 'ok';
13
+ message: string;
14
+ hint?: string;
15
+ fixable: boolean;
16
+ group?: 'data' | 'config';
17
+ }>;
18
+ notes: string[];
19
+ }
20
+ export interface AgentDataTarget {
21
+ id: string;
22
+ home: string;
23
+ }
24
+ /**
25
+ * 从配置 raw 解析 agent 数据目录目标
26
+ *
27
+ * @param home - OCTOPI_HOME
28
+ * @param raw - 配置对象
29
+ * @returns agent id + home 列表
30
+ */
31
+ export declare function resolveAgentDataTargets(home: string, raw: Record<string, unknown> | null): AgentDataTarget[];
32
+ /**
33
+ * 检测废弃 session.store.dataDir 与真实会话落点对照(不迁移数据)
34
+ *
35
+ * @param raw - 未展开配置
36
+ * @param targets - agent home
37
+ * @param configDir - 配置文件所在目录(dataDir 相对基准)
38
+ * @returns findings
39
+ */
40
+ export declare function checkDeprecatedSessionStore(raw: Record<string, unknown> | null, targets: AgentDataTarget[], configDir: string): DataFixResult['findings'];
41
+ /**
42
+ * 检测数据层问题(不修改磁盘)
43
+ *
44
+ * @param targets - agent home 列表
45
+ * @returns findings
46
+ */
47
+ export declare function detectDataLayer(targets: AgentDataTarget[]): DataFixResult['findings'];
48
+ /**
49
+ * 打开 agent.db 触发既有 schema migrate(幂等)
50
+ *
51
+ * @param target - agent home
52
+ * @returns 说明;失败时 throw 由调用方转 finding
53
+ */
54
+ export declare function migrateAgentDatabase(target: AgentDataTarget): Promise<string>;
55
+ /**
56
+ * 应用数据层修复
57
+ *
58
+ * @param targets - agent home 列表
59
+ * @param options - dryRun 时只描述将做什么
60
+ * @returns findings + notes
61
+ */
62
+ export declare function applyDataLayerFixes(targets: AgentDataTarget[], options?: {
63
+ dryRun?: boolean;
64
+ }): Promise<DataFixResult>;