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
package/README_CN.md ADDED
@@ -0,0 +1,241 @@
1
+ # Octopi 🐙
2
+
3
+ **可嵌入的 Agent 底座引擎**
4
+
5
+ > Agent 不是一个 class,是一个完整的运行时。
6
+ > 框架的价值不在于提供了多少默认实现,而在于定义了多少清晰的接口。
7
+
8
+ [English](./README.md) | [架构设计](./docs/architecture.md) | [开发规范](./docs/CONTRIBUTING.md)
9
+
10
+ ---
11
+
12
+ ## 什么是 Octopi?
13
+
14
+ Octopi 是一个可嵌入的 Agent 底座引擎,用于构建 AI 驱动的应用。它提供你的产品所需要的 Agent 运行时基础设施——就像汽车需要引擎一样,你的产品需要一个 Agent 引擎来拥有 AI 能力。
15
+
16
+ - **可嵌入** — 不是独立应用,而是产品的组件
17
+ - **4 层架构** — Loop → Core → Harness → Integration,边界清晰,层次独立
18
+ - **10 个产品域** — 治理、会话、智能体、记忆、知识、激活、运行、上下文、扩展、协作(见 [docs/domains.md](./docs/domains.md))
19
+ - **8 层上下文智能** — 智慧、人格、技能、知识、认知、记忆、运行时、信息(记忆见 [docs/memory.md](./docs/memory.md))
20
+ - **安全内置** — 注入检测、风险评估、审批流程——不可选、不可绕过
21
+ - **原生多智能体** — 从架构底层支持分布式智能
22
+
23
+ ---
24
+
25
+ ## 架构
26
+
27
+ ```
28
+ ┌──────────────────────────────────────────────────────────────┐
29
+ │ Layer 3: Integration — 外部适配 │
30
+ │ LLM Provider · 存储 · 可观测性 · Gateway · TUI · Web Runtime │
31
+ │ │
32
+ │ ┌──────────────────────────────────────────────────────────┐│
33
+ │ │ Layer 2: Harness — 10 个产品域 ││
34
+ │ │ governance · session · agent · memory · knowledge ││
35
+ │ │ activation · run · context · extension · collaboration ││
36
+ │ │ ││
37
+ │ │ ┌──────────────────────────────────────────────────────┐││
38
+ │ │ │ Layer 1: Core — 机制原语 + 接口契约 + 核心类型 │││
39
+ │ │ │ EventBus · StateMachine · Kernel ports │││
40
+ │ │ │ │││
41
+ │ │ │ ┌──────────────────────────────────────────────────┐│││
42
+ │ │ │ │ Layer 0: Loop — 纯执行循环 ││││
43
+ │ │ │ │ agentLoop · callModel · classifyError ││││
44
+ │ │ │ └──────────────────────────────────────────────────┘│││
45
+ │ │ └──────────────────────────────────────────────────────┘││
46
+ │ └──────────────────────────────────────────────────────────┘│
47
+ └──────────────────────────────────────────────────────────────┘
48
+ ```
49
+
50
+ **依赖方向:外 → 内。Core 零外层依赖。**
51
+
52
+ ### Layer 0: Loop — 纯执行循环
53
+
54
+ 引擎的核心。`agentLoop()` 是一个纯 async generator:输入消息 → 调用 LLM → 执行工具 → 输出协议事件。零状态,零外部依赖。可运行门面见 Harness 的 `Agent.run()`。
55
+
56
+ ### Layer 1: Core — Kernel 契约
57
+
58
+ 基础设施原语(EventBus、StateMachine)和 **Kernel ports**(ModelProvider、ErrorStrategy、SecurityGuard、RunGuard、ReliabilityHarness)+ 共享词汇表。**Product ports**(ToolBus、SessionStore、Observer=Telemetry)与 Domain 契约(ContextEngine、Memory、MCP…)在 Harness。Run Observatory 见 [docs/observer-domain.md](./docs/observer-domain.md)。不包含策略实现。**不 re-export Loop。**
59
+
60
+ ### Layer 2: Harness — 产品域
61
+
62
+ | 产品域 | 目录 | 问题 |
63
+ |--------|------|------|
64
+ | **Governance 治理** | `governance/` | 谁能做什么?(ACL、安全策略、HITL、凭证、账本) |
65
+ | **Session 会话** | `session/` | 连续性如何维持?(聚合、Discourse、任务、历史) |
66
+ | **Agent 智能体** | `agent/` | 它是谁、怎么配?(模板、persona、构建) |
67
+ | **Memory 记忆** | `memory/` | 它学到过什么?(Memory/Cognition/Wisdom 基质) |
68
+ | **Knowledge 知识** | `knowledge/` | 世界上写着什么?(外生语料、源、检索) |
69
+ | **Activation 激活** | `activation/` | 刺激如何变成 Run? |
70
+ | **Run 运行** | `run/` | 这一轮如何跑安全?(RunScope、可靠性、守卫、预算) |
71
+ | **Context 上下文** | `context/` | 模型看见什么?(八层装配、Token、窗口) |
72
+ | **Extension 扩展** | `extension/` | 能力如何扩展?(Plugin/Tool/Skill/MCP、沙箱) |
73
+ | **Collaboration 协作** | `collaboration/` | 多 Agent / 子系统如何协同? |
74
+
75
+ 横切/基建(不计数):`observability/`、`context/capabilities/`、`shared/`。
76
+ 数字与模块清单唯一权威:[docs/domains.yaml](./docs/domains.yaml)。
77
+
78
+ ### Layer 3: Integration — 外部适配
79
+
80
+ LLM Provider(OpenAI、Anthropic)、存储后端(JSONL、SQLite、Memory)、Telemetry 可观测性(Trace、Metrics、Exporters;配置键 `observability`)、协议(HTTP)、Gateway、TUI、Web Runtime。
81
+
82
+ ---
83
+
84
+ ## Context Intelligence — 八层智能模型
85
+
86
+ Octopi 独特的上下文智能组装方法,让 agent 通过更有效的 context 变得更聪明:
87
+
88
+ ```
89
+ 智慧(思维范式) ← 最高优先级,放在 system prompt 最前面
90
+ 人格(身份、特质)
91
+ 技能(工作流指导) ← 条件加载
92
+ 知识(外部参考资料) ← 按需检索
93
+ 认知(概念关系网络) ← 概念之间的关系
94
+ 记忆(行动命题) ← fact / method / norm(跨会话可行动洞察)
95
+ 运行时(本轮活态) ← tasks / guidance / injectedContext(system 侧)
96
+ 信息(原始消息) ← 窗口管理 + 压缩(消息窗口,非 ContextLayer)
97
+ ```
98
+
99
+ > 产品八层 = system ContextLayer(1–7,含 Runtime)+ Information(第 8 层,消息窗口)。
100
+
101
+ 这是一个**信息分馏系统**:原始信息通过逐层提炼,产出越来越高层级的理解。
102
+
103
+ **实现**:`harness/context/` 的 `ContextLayer` 契约 + `DefaultContextAssembler`。
104
+ 默认路径已接 Persona / Skill / Knowledge / Memory / Runtime;Wisdom / Cognition 待打磨。
105
+ 详见 [docs/context-layer-contracts.md](./docs/context-layer-contracts.md);Knowledge 见 [docs/knowledge.md](./docs/knowledge.md)。
106
+
107
+ ---
108
+
109
+ ## 快速开始
110
+
111
+ ```typescript
112
+ import { AgentBuilder, OpenAIProvider } from 'octopi-agent';
113
+
114
+ const { agent, runner } = await new AgentBuilder()
115
+ .model(new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY! }))
116
+ .persona('./my-agent')
117
+ .build();
118
+
119
+ for await (const event of runner.handle('session-1', userMessage)) {
120
+ if (event.type === 'llm_stream_delta') {
121
+ process.stdout.write(event.data.delta);
122
+ }
123
+ }
124
+ ```
125
+
126
+ ### MCP 集成
127
+
128
+ 注入 Integration client 工厂后连接 MCP Server:
129
+
130
+ ```typescript
131
+ import { AgentBuilder, createSdkMcpClient } from 'octopi-agent';
132
+
133
+ const { agent, runner } = await new AgentBuilder()
134
+ .model('gpt-4o')
135
+ .mcpClientFactory(createSdkMcpClient)
136
+ .mcp({
137
+ id: 'filesystem',
138
+ transport: 'stdio',
139
+ command: 'npx',
140
+ args: ['-y', '@modelcontextprotocol/server-filesystem', '/data'],
141
+ })
142
+ .build();
143
+ ```
144
+
145
+ ### Web Search(多 Provider)
146
+
147
+ 在 `octopi.json` / `~/.octopi/octopi.json` 配置后自动注册 `web_search` 工具:
148
+
149
+ ```json
150
+ {
151
+ "webSearch": {
152
+ "provider": "mimo",
153
+ "fallbacks": ["duckduckgo"],
154
+ "defaultLimit": 5,
155
+ "timeoutMs": 90000,
156
+ "providers": {
157
+ "mimo": { "api": "mimo", "apiKey": "${MIMO_API_KEY}", "model": "mimo-v2.5-pro" },
158
+ "duckduckgo": { "api": "duckduckgo" }
159
+ }
160
+ }
161
+ }
162
+ ```
163
+
164
+ 内置 provider:`duckduckgo`(免 key)、`tavily`、`brave`、`serper`、`mimo`。主 provider 失败或空结果时按 `fallbacks` 降级。
165
+
166
+ ---
167
+
168
+ ## 核心设计原则
169
+
170
+ **Agent 是运行时,不是类。** Agent 是一个完整的运行时作用域:工作区、Session 存储、工具集、模型配置、人格定义。框架提供机制,集成方提供策略。
171
+
172
+ **接口 > 实现。** 框架的价值在于接口。`ModelProvider` 让你替换 LLM 厂商;`SessionStore` 让你更换存储;`ContextEngine` 让你自由组合上下文管理。
173
+
174
+ **安全是内置的。** 注入检测、风险评估、审批流程——不是配置开关,而是内置约束。Agent 越强大,安全越不能依赖开发者自觉。
175
+
176
+ **文件即配置。** 人格、技能、智慧、操作指令——全部用 Markdown 文件定义。扩展 = 加文件。组合 = 叠加目录。
177
+
178
+ **每个领域可独立理解。** 在 vibe coding 环境中,上下文有限,你可以聚焦于单个领域而不需要理解整个系统。
179
+
180
+ ---
181
+
182
+ ## 测试
183
+
184
+ ```bash
185
+ npm test
186
+ ```
187
+
188
+ 64 个测试文件,1022 个测试。三层策略:单元测试(Mock)、录制回放、E2E 真实 API。ChaosProvider 故障注入。
189
+
190
+ ---
191
+
192
+ ## 项目结构
193
+
194
+ npm workspaces monorepo — 五个可发布包:
195
+
196
+ ```
197
+ octopi-agent 开箱套件(CLI bin: octopi)+ 配置 IO
198
+ ├─ @octopi-agent/engine Harness 十域 + 库集成
199
+ │ └─ @octopi-agent/core Loop + Kernel 契约
200
+ ├─ @octopi-agent/gateway HTTP/WS 进程面 + Web 运行时
201
+ └─ @octopi-agent/webui 预构建 Web 控制台
202
+
203
+ packages/
204
+ core/ Layer 0–1 src/loop + src/core
205
+ engine/ Layer 2–3 src/harness/** + integration 库能力 + 内置子系统
206
+ gateway/ Layer 3 gateway/、protocols/、web/**
207
+ webui/ 产品 Vite React 控制台
208
+ src/ 套件 cli/、init、config IO + 组合校验、testing/、tui/
209
+ tests/ 根目录 Vitest
210
+ docs/ 对外文档 · arch/ 内部设计
211
+ ```
212
+
213
+ | 需求 | Import |
214
+ |------|--------|
215
+ | 套件 / CLI | `octopi-agent` |
216
+ | 运行时 | `@octopi-agent/engine` |
217
+ | Kernel | `@octopi-agent/core` |
218
+ | Gateway / Web SDK | `@octopi-agent/gateway` |
219
+ | Plugin SDK | `@octopi-agent/engine/plugin-sdk/plugin-entry` |
220
+
221
+ 运行时关键配置(见 `octopi.example.json` 与 `docs/KNOWN-ISSUES.md`):
222
+ `toolIsolation`、`sessionAcl`、`agents[].workspace` / `maxSessionRights`、`summary` / `compact` / `models.level.summary`(公用能力)。
223
+
224
+ ---
225
+
226
+ ## 相关文档
227
+
228
+ - [架构设计](./docs/architecture.md) — 完整架构设计文档
229
+ - [包拆分](./arch/npm-package-split.md) — 五包拓扑(内部 handoff)
230
+ - [Plugin 系统](./docs/plugin-system.md) — Plugin 系统详细文档
231
+ - [会话任务 SessionTask](./docs/task-system.md) — 设计基准
232
+ - [领域切分](./docs/domain-split.md) — run-guard / orchestration / AsyncTask
233
+ - [开发规范](./docs/CONTRIBUTING.md) — 开发指南
234
+ - [更新日志](./CHANGELOG.md) — 版本历史
235
+ - [Web UI 设计](./packages/webui/DESIGN.md) — Playground 视觉体系与八层检查器
236
+
237
+ ---
238
+
239
+ ## 许可证
240
+
241
+ Apache-2.0 — 详见 [LICENSE](./LICENSE) 与 [NOTICE](./NOTICE)。
@@ -0,0 +1,20 @@
1
+ /**
2
+ * CLI 参数解析
3
+ */
4
+ export interface CliArgs {
5
+ command: string;
6
+ subcommand?: string;
7
+ config?: string;
8
+ port?: number;
9
+ help?: boolean;
10
+ verbose?: boolean;
11
+ fix?: boolean;
12
+ dryRun?: boolean;
13
+ json?: boolean;
14
+ yes?: boolean;
15
+ only?: string[];
16
+ allowDeleteLegacyDirs?: boolean;
17
+ /** doctor --restore [backupPath];true = 最新备份 */
18
+ restore?: boolean | string;
19
+ }
20
+ export declare function parseArgs(argv?: string[]): CliArgs;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * CLI 参数解析
3
+ */
4
+ export function parseArgs(argv = process.argv.slice(2)) {
5
+ let help = false;
6
+ let verbose = false;
7
+ let config;
8
+ let port;
9
+ let fix = false;
10
+ let dryRun = false;
11
+ let json = false;
12
+ let yes = false;
13
+ let allowDeleteLegacyDirs = false;
14
+ let only;
15
+ let restore;
16
+ const positional = [];
17
+ for (let i = 0; i < argv.length; i++) {
18
+ switch (argv[i]) {
19
+ case '--config':
20
+ case '-c':
21
+ config = argv[++i];
22
+ break;
23
+ case '--port':
24
+ case '-p':
25
+ port = parseInt(argv[++i], 10);
26
+ break;
27
+ case '--help':
28
+ case '-h':
29
+ help = true;
30
+ break;
31
+ case '--verbose':
32
+ case '-v':
33
+ verbose = true;
34
+ break;
35
+ case '--fix':
36
+ fix = true;
37
+ break;
38
+ case '--dry-run':
39
+ dryRun = true;
40
+ break;
41
+ case '--json':
42
+ json = true;
43
+ break;
44
+ case '--yes':
45
+ case '-y':
46
+ yes = true;
47
+ break;
48
+ case '--only': {
49
+ const rawOnly = argv[++i] ?? '';
50
+ only = rawOnly
51
+ .split(',')
52
+ .map((s) => s.trim())
53
+ .filter(Boolean);
54
+ break;
55
+ }
56
+ case '--allow-delete-legacy-dirs':
57
+ allowDeleteLegacyDirs = true;
58
+ break;
59
+ case '--restore': {
60
+ const next = argv[i + 1];
61
+ if (next && !next.startsWith('-')) {
62
+ restore = next;
63
+ i++;
64
+ }
65
+ else {
66
+ restore = true;
67
+ }
68
+ break;
69
+ }
70
+ default:
71
+ positional.push(argv[i]);
72
+ break;
73
+ }
74
+ }
75
+ return {
76
+ command: positional[0] ?? 'help',
77
+ subcommand: positional[1],
78
+ config,
79
+ port,
80
+ help,
81
+ verbose,
82
+ fix,
83
+ dryRun,
84
+ json,
85
+ yes,
86
+ only,
87
+ allowDeleteLegacyDirs,
88
+ restore,
89
+ };
90
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * CLI 命令实现
3
+ */
4
+ import type { CliArgs } from './args.js';
5
+ export declare function showHelp(): void;
6
+ export declare function initCommand(args: CliArgs): Promise<void>;
7
+ export declare function ensureInitialized(args: CliArgs): Promise<string | undefined>;
8
+ export declare function chatCommand(args: CliArgs): Promise<void>;
9
+ export declare function healthCommand(args: CliArgs): Promise<void>;
10
+ export declare function pluginCommand(args: CliArgs): Promise<void>;
@@ -0,0 +1,253 @@
1
+ /**
2
+ * CLI 命令实现
3
+ */
4
+ import { resolve, join } from 'node:path';
5
+ import { fork } from 'node:child_process';
6
+ import { loadConfig } from '../config.js';
7
+ import { initOctopi, getOctopiHome, isInitialized, formatInitReport } from '../init.js';
8
+ import { readPidFile, writePidFile, removePidFile, isProcessAlive, createProvider } from './daemon.js';
9
+ import { resolveGatewayUrl } from './helpers.js';
10
+ export function showHelp() {
11
+ console.log(`
12
+ Octopi — AI Agent Framework
13
+
14
+ Usage:
15
+ octopi <command> [options]
16
+
17
+ Commands:
18
+ init Initialize Octopi directory structure and config
19
+ doctor Diagnose deployment/config issues (local rules, no LLM)
20
+ serve start Start the Gateway server (background daemon)
21
+ serve stop Stop the Gateway server
22
+ serve restart Restart the Gateway server
23
+ serve status Show Gateway server status
24
+ serve fg Start the Gateway server in foreground (for debugging)
25
+ chat (or tui) Interactive TUI chat with an agent
26
+ health Check the health of configured providers
27
+ webui start Start the Web UI server
28
+ webui stop Stop the Web UI server
29
+ webui restart Restart the Web UI server
30
+ webui status Show Web UI server status
31
+ plugin init Scaffold a new plugin project
32
+ help Show this help message
33
+
34
+ Options:
35
+ --config, -c <path> Config file path (default: ~/.octopi/octopi.json)
36
+ --port, -p <port> Port override
37
+ --verbose, -v Enable verbose mode (trace all engine events to file)
38
+ --fix doctor: apply safe migrations (backs up config)
39
+ --dry-run doctor: show what --fix would do
40
+ --json doctor: machine-readable report (secrets redacted)
41
+ --yes, -y doctor: required for non-interactive --fix (apply all fixable groups)
42
+ --only <list> doctor: limit to domains/ids (config,layout,data,runtime)
43
+ --restore [path] doctor: restore octopi.json from latest (or given) backup
44
+ --allow-delete-legacy-dirs
45
+ doctor: with --fix layout, rename obsolete memory/wisdom/extract dirs
46
+ --help, -h Show this help message
47
+
48
+ Examples:
49
+ octopi init
50
+ octopi doctor
51
+ octopi doctor --fix --yes
52
+ octopi doctor --restore
53
+ octopi serve start -c ./my-config.json
54
+ octopi serve stop
55
+ octopi serve restart
56
+ octopi serve status
57
+ octopi serve fg -c ./my-config.json # foreground mode
58
+ octopi chat -c ./my-config.json
59
+ octopi health -c ./my-config.json
60
+ `);
61
+ }
62
+ export async function initCommand(args) {
63
+ const homeDir = args.config ? resolve(args.config, '..') : undefined;
64
+ const result = await initOctopi(homeDir);
65
+ console.log(formatInitReport(result));
66
+ }
67
+ export async function ensureInitialized(args) {
68
+ if (args.config)
69
+ return args.config;
70
+ // Prefer OCTOPI_HOME over cwd so a stray ./octopi.json cannot shadow workspace config
71
+ const home = getOctopiHome();
72
+ if (isInitialized(home)) {
73
+ return resolve(home, 'octopi.json');
74
+ }
75
+ if (isInitialized(process.cwd()))
76
+ return undefined;
77
+ console.log('🐙 First run detected. Initializing Octopi...\n');
78
+ const result = await initOctopi();
79
+ console.log(formatInitReport(result));
80
+ console.log('');
81
+ return result.configPath;
82
+ }
83
+ export async function chatCommand(args) {
84
+ const configPath = await ensureInitialized(args);
85
+ const config = loadConfig(configPath);
86
+ const agent = config.agents[0];
87
+ if (!agent) {
88
+ console.error('[Error] No agents defined in config');
89
+ process.exit(1);
90
+ }
91
+ let pidFile = readPidFile();
92
+ let gatewayRunning = pidFile && isProcessAlive(pidFile.pid);
93
+ if (!gatewayRunning) {
94
+ console.log('[TUI] Gateway not running, starting...');
95
+ removePidFile();
96
+ const childArgs = ['serve', 'fg'];
97
+ if (configPath)
98
+ childArgs.push('--config', configPath);
99
+ const child = fork(process.argv[1], childArgs, {
100
+ detached: true,
101
+ stdio: 'ignore',
102
+ execArgv: [],
103
+ env: { ...process.env, OCTOPI_DAEMON: '1' },
104
+ });
105
+ child.unref();
106
+ if (!child.pid) {
107
+ console.error('❌ Failed to start Gateway');
108
+ process.exit(1);
109
+ }
110
+ const channels = config.channels ?? [];
111
+ const httpChannel = channels.find((c) => c.type === "http");
112
+ const port = httpChannel?.port ?? 3000;
113
+ writePidFile({
114
+ pid: child.pid,
115
+ config: configPath ?? join(getOctopiHome(), 'octopi.json'),
116
+ port,
117
+ startedAt: new Date().toISOString(),
118
+ });
119
+ console.log('[TUI] Waiting for Gateway to start...');
120
+ const gatewayUrl = `http://localhost:${port}`;
121
+ let ready = false;
122
+ for (let i = 0; i < 30; i++) {
123
+ await new Promise((r) => setTimeout(r, 500));
124
+ try {
125
+ const res = await fetch(`${gatewayUrl}/health`, { signal: AbortSignal.timeout(1000) });
126
+ if (res.ok) {
127
+ ready = true;
128
+ break;
129
+ }
130
+ }
131
+ catch { /* not ready yet */ }
132
+ }
133
+ if (!ready) {
134
+ console.error('❌ Gateway failed to start within 15 seconds');
135
+ process.exit(1);
136
+ }
137
+ console.log(`[TUI] Gateway started (PID: ${child.pid})`);
138
+ pidFile = readPidFile();
139
+ }
140
+ else {
141
+ console.log(`[TUI] Gateway detected (PID: ${pidFile.pid})`);
142
+ }
143
+ const gatewayUrl = resolveGatewayUrl(config);
144
+ const { TuiApp } = await import('../integration/tui/app.js');
145
+ const app = new TuiApp({
146
+ agentId: agent.id,
147
+ gatewayUrl,
148
+ });
149
+ await app.start();
150
+ }
151
+ export async function healthCommand(args) {
152
+ const configPath = await ensureInitialized(args);
153
+ const config = loadConfig(configPath);
154
+ console.log('\n🏥 Health Check\n');
155
+ for (const [providerName, providerCfg] of Object.entries(config.models?.providers ?? {})) {
156
+ const provider = createProvider(providerName, providerCfg);
157
+ if (provider) {
158
+ try {
159
+ const available = await provider.isAvailable();
160
+ console.log(` ${providerName}: ${available ? '✅ OK' : '❌ FAIL'}`);
161
+ }
162
+ catch {
163
+ console.log(` ${providerName}: ❌ FAIL`);
164
+ }
165
+ }
166
+ }
167
+ console.log();
168
+ }
169
+ export async function pluginCommand(args) {
170
+ if (args.subcommand !== 'init') {
171
+ console.error('Usage: octopi plugin init <plugin-name> [--dir <path>]');
172
+ process.exit(1);
173
+ }
174
+ const rawArgs = process.argv.slice(2);
175
+ const positional = rawArgs.filter((a) => !a.startsWith('-'));
176
+ const pluginName = positional[2];
177
+ const dirIdx = rawArgs.indexOf('--dir');
178
+ const dirFlag = dirIdx >= 0 ? rawArgs[dirIdx + 1] : undefined;
179
+ if (!pluginName) {
180
+ console.error('Usage: octopi plugin init <plugin-name> [--dir <path>]');
181
+ process.exit(1);
182
+ }
183
+ const targetDir = dirFlag ?? `./plugins/${pluginName}`;
184
+ const fs = await import('node:fs');
185
+ const path = await import('node:path');
186
+ if (fs.existsSync(targetDir)) {
187
+ console.error(`Directory already exists: ${targetDir}`);
188
+ process.exit(1);
189
+ }
190
+ fs.mkdirSync(targetDir, { recursive: true });
191
+ const manifest = {
192
+ id: pluginName,
193
+ name: `${pluginName} plugin`,
194
+ version: '0.1.0',
195
+ description: 'A plugin for Octopi',
196
+ main: 'index.js',
197
+ enabledByDefault: true,
198
+ };
199
+ fs.writeFileSync(path.join(targetDir, 'octopi.plugin.json'), JSON.stringify(manifest, null, 2) + '\n');
200
+ const entryCode = `/**
201
+ * ${pluginName} plugin
202
+ */
203
+
204
+ import { definePluginEntry } from '@octopi-agent/engine/plugin-sdk/plugin-entry';
205
+
206
+ export default definePluginEntry({
207
+ id: '${pluginName}',
208
+ name: '${pluginName}',
209
+ description: 'A plugin for Octopi',
210
+
211
+ register(api) {
212
+ console.log('[${pluginName}] Registered');
213
+ },
214
+ });
215
+ `;
216
+ fs.writeFileSync(path.join(targetDir, 'index.ts'), entryCode);
217
+ const pkg = {
218
+ name: `@octopi-agent/plugin-${pluginName}`,
219
+ version: '0.1.0',
220
+ type: 'module',
221
+ main: 'index.js',
222
+ types: 'index.d.ts',
223
+ peerDependencies: {
224
+ octopi: '>=0.4.0',
225
+ },
226
+ };
227
+ fs.writeFileSync(path.join(targetDir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
228
+ const tsconfig = {
229
+ compilerOptions: {
230
+ target: 'ES2022',
231
+ module: 'ESNext',
232
+ moduleResolution: 'bundler',
233
+ declaration: true,
234
+ outDir: '.',
235
+ rootDir: '.',
236
+ strict: true,
237
+ esModuleInterop: true,
238
+ skipLibCheck: true,
239
+ },
240
+ include: ['*.ts'],
241
+ };
242
+ fs.writeFileSync(path.join(targetDir, 'tsconfig.json'), JSON.stringify(tsconfig, null, 2) + '\n');
243
+ console.log(`\n🐙 Plugin "${pluginName}" created at ${targetDir}\n`);
244
+ console.log('Files:');
245
+ console.log(` ${targetDir}/octopi.plugin.json ← Plugin manifest`);
246
+ console.log(` ${targetDir}/index.ts ← Entry point`);
247
+ console.log(` ${targetDir}/package.json ← Package config`);
248
+ console.log(` ${targetDir}/tsconfig.json ← TypeScript config`);
249
+ console.log('\nNext steps:');
250
+ console.log(` cd ${targetDir}`);
251
+ console.log(' # Edit index.ts to add your plugin logic');
252
+ console.log(' # Add plugins.loadPaths to your octopi.json config');
253
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * CLI 守护进程管理
3
+ */
4
+ import type { CliArgs } from './args.js';
5
+ import type { ModelProviderConfig } from '@octopi-agent/engine/config.js';
6
+ import type { ModelProvider } from '@octopi-agent/core/interfaces/model-provider.js';
7
+ import { findPidOnPort, isProcessAlive, killProcessOnPort } from './process-utils.js';
8
+ export { findPidOnPort, isProcessAlive, killProcessOnPort };
9
+ interface DaemonPidFile {
10
+ pid: number;
11
+ config: string;
12
+ port?: number;
13
+ startedAt: string;
14
+ }
15
+ export declare function getPidPath(): string;
16
+ export declare function readPidFile(): DaemonPidFile | null;
17
+ export declare function writePidFile(data: DaemonPidFile): void;
18
+ export declare function removePidFile(): void;
19
+ /** 从配置解析 Gateway 监听端口 */
20
+ export declare function resolveListenPort(args: Pick<CliArgs, 'port' | 'config'>, configPath?: string): number;
21
+ /**
22
+ * 解析当前 Gateway 的真实 PID
23
+ *
24
+ * 优先端口占用者(最可靠);其次 pid 文件且进程存活。
25
+ * Windows 上 fork 返回的 pid 与子进程 process.pid 可能不一致,
26
+ * 不能只信 serve start 写下的 pid。
27
+ */
28
+ export declare function resolveGatewayPid(args: Pick<CliArgs, 'port' | 'config'>, configPath?: string): {
29
+ pid: number | null;
30
+ port: number;
31
+ source: 'port' | 'pidfile' | 'none';
32
+ };
33
+ export declare function createProvider(name: string, cfg: ModelProviderConfig): ModelProvider | null;
34
+ export declare function ensureDaemonConfig(args: CliArgs): Promise<string | undefined>;
35
+ export declare function serveStartCommand(args: CliArgs): Promise<void>;
36
+ export declare function serveStopCommand(args?: Pick<CliArgs, 'port'>): Promise<void>;
37
+ export declare function serveRestartCommand(args: CliArgs): Promise<void>;
38
+ export declare function serveStatusCommand(args?: Pick<CliArgs, 'port' | 'config'>): Promise<void>;
39
+ export declare function serveFgCommand(args: CliArgs): Promise<void>;
40
+ export declare function serveCommand(args: CliArgs): Promise<void>;