octopi-agent 0.90.11 → 0.98.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/agent-admin.d.ts +57 -0
  2. package/dist/agent-admin.js +96 -0
  3. package/dist/cli/args.d.ts +6 -0
  4. package/dist/cli/args.js +11 -0
  5. package/dist/cli/commands.js +13 -3
  6. package/dist/cli/daemon.d.ts +50 -0
  7. package/dist/cli/daemon.js +269 -3
  8. package/dist/cli/helpers.d.ts +20 -0
  9. package/dist/cli/helpers.js +29 -0
  10. package/dist/cli/index.js +4 -0
  11. package/dist/cli/ops.d.ts +20 -0
  12. package/dist/cli/ops.js +102 -0
  13. package/dist/cli/process-utils.d.ts +16 -3
  14. package/dist/cli/process-utils.js +32 -66
  15. package/dist/cli/webui.d.ts +21 -0
  16. package/dist/cli/webui.js +68 -13
  17. package/dist/config-audit.d.ts +8 -0
  18. package/dist/config-audit.js +25 -0
  19. package/dist/config-schema/index.d.ts +228 -8
  20. package/dist/config-schema/unknown-keys.d.ts +26 -0
  21. package/dist/config-schema/unknown-keys.js +97 -0
  22. package/dist/config-service.d.ts +59 -0
  23. package/dist/config-service.js +145 -0
  24. package/dist/config.d.ts +42 -0
  25. package/dist/config.js +119 -51
  26. package/dist/init.js +0 -2
  27. package/dist/integration/tui/app.d.ts +42 -0
  28. package/dist/integration/tui/app.js +354 -14
  29. package/dist/integration/tui/attach.d.ts +51 -0
  30. package/dist/integration/tui/attach.js +71 -0
  31. package/dist/integration/tui/components.d.ts +2 -0
  32. package/dist/integration/tui/components.js +4 -0
  33. package/dist/integration/tui/gateway-api.d.ts +56 -0
  34. package/dist/integration/tui/gateway-api.js +63 -0
  35. package/dist/integration/tui/history.d.ts +66 -0
  36. package/dist/integration/tui/history.js +133 -0
  37. package/dist/integration/tui/issues.d.ts +34 -0
  38. package/dist/integration/tui/issues.js +68 -0
  39. package/dist/integration/tui/reconnect.d.ts +23 -0
  40. package/dist/integration/tui/reconnect.js +22 -0
  41. package/dist/integration/tui/search.d.ts +30 -0
  42. package/dist/integration/tui/search.js +53 -0
  43. package/dist/role-template-store.d.ts +28 -0
  44. package/dist/role-template-store.js +51 -0
  45. package/dist/testing/scenario-runner.js +9 -2
  46. package/octopi.example.json +6 -3
  47. package/octopi.schema.json +318 -3
  48. package/package.json +5 -5
@@ -0,0 +1,57 @@
1
+ /** scaffold 选项 */
2
+ export interface ScaffoldAgentOptions {
3
+ /** 初始 AGENTS.md 全文(角色模板渲染结果);缺省用 ensureAgentDirs 默认模板 */
4
+ agentsMd?: string;
5
+ /** workspace 目录路径(`~` 由调用方展开为绝对路径);缺省用脚手架默认 */
6
+ workspace?: string;
7
+ }
8
+ export declare class AgentFileAdmin {
9
+ private readonly homeDir;
10
+ /**
11
+ * @param homeDir - OCTOPI_HOME(缺省 getOctopiHome())
12
+ */
13
+ constructor(homeDir?: string);
14
+ /**
15
+ * agent 文件态标准路径(与 octopi init 布局同源)
16
+ *
17
+ * @param agentId - agent id
18
+ * @returns home / workspace / skillDirectory 绝对路径
19
+ */
20
+ pathsOf(agentId: string): {
21
+ home: string;
22
+ workspace: string;
23
+ skillDirectory: string;
24
+ };
25
+ /**
26
+ * agent home 目录路径
27
+ *
28
+ * @param agentId - agent id
29
+ * @returns `OCTOPI_HOME/agents/<id>`
30
+ */
31
+ homeOf(agentId: string): string;
32
+ /**
33
+ * 建 agent 文件态(幂等):home / workspace / skills + AGENTS.md
34
+ *
35
+ * @param agentId - agent id
36
+ * @param opts - scaffold 选项
37
+ * @throws id 为路径穿越形态 / workspace 为相对路径时抛错(纵深防御)
38
+ */
39
+ scaffold(agentId: string, opts?: ScaffoldAgentOptions): Promise<void>;
40
+ /**
41
+ * 读 AGENTS.md(persona 全文)
42
+ *
43
+ * @param agentId - agent id
44
+ * @param home - agent 配置的 home(缺省用标准布局路径)
45
+ * @returns 文件内容;不存在返回 null
46
+ */
47
+ readPersona(agentId: string, home?: string): string | null;
48
+ /**
49
+ * 写 AGENTS.md(persona 编辑;builder 指纹缓存自动重读)
50
+ *
51
+ * @param agentId - agent id
52
+ * @param content - AGENTS.md 全文
53
+ * @param home - agent 配置的 home(缺省用标准布局路径)
54
+ * @throws home 不存在时抛错(fail-loud,防写到未 scaffold 的空洞路径)
55
+ */
56
+ writePersona(agentId: string, content: string, home?: string): void;
57
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * AgentFileAdmin — agent 文件态管理(arch/config-hot-reload.md §5.2)
3
+ *
4
+ * 新增 agent = 目录脚手架(ensureAgentDirs,幂等)+ AGENTS.md 初始内容(角色
5
+ * 模板渲染结果,给定则覆写)+ workspace 目录。persona 编辑 = 直接写 AGENTS.md
6
+ * (builder 指纹缓存 mtime/size 自动重读,天然热生效)。
7
+ *
8
+ * @module
9
+ */
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { isAbsolute, join, resolve } from 'node:path';
12
+ import { ensureAgentDirs, getOctopiHome } from './init.js';
13
+ export class AgentFileAdmin {
14
+ homeDir;
15
+ /**
16
+ * @param homeDir - OCTOPI_HOME(缺省 getOctopiHome())
17
+ */
18
+ constructor(homeDir = getOctopiHome()) {
19
+ this.homeDir = homeDir;
20
+ }
21
+ /**
22
+ * agent 文件态标准路径(与 octopi init 布局同源)
23
+ *
24
+ * @param agentId - agent id
25
+ * @returns home / workspace / skillDirectory 绝对路径
26
+ */
27
+ pathsOf(agentId) {
28
+ const home = join(this.homeDir, 'agents', agentId);
29
+ return {
30
+ home,
31
+ workspace: join(this.homeDir, 'workspace', agentId),
32
+ skillDirectory: join(home, 'skills'),
33
+ };
34
+ }
35
+ /**
36
+ * agent home 目录路径
37
+ *
38
+ * @param agentId - agent id
39
+ * @returns `OCTOPI_HOME/agents/<id>`
40
+ */
41
+ homeOf(agentId) {
42
+ return this.pathsOf(agentId).home;
43
+ }
44
+ /**
45
+ * 建 agent 文件态(幂等):home / workspace / skills + AGENTS.md
46
+ *
47
+ * @param agentId - agent id
48
+ * @param opts - scaffold 选项
49
+ * @throws id 为路径穿越形态 / workspace 为相对路径时抛错(纵深防御)
50
+ */
51
+ async scaffold(agentId, opts = {}) {
52
+ if (agentId === '.' || agentId === '..' || agentId.includes('/') || agentId.includes('\\')) {
53
+ throw new Error(`invalid agent id: ${agentId}`);
54
+ }
55
+ await ensureAgentDirs(agentId, this.homeDir);
56
+ if (opts.agentsMd !== undefined) {
57
+ // 仅在 AGENTS.md 缺失时写:重建同 id agent 不覆盖既有 persona(用户数据)
58
+ const agentsMdPath = join(this.homeOf(agentId), 'AGENTS.md');
59
+ if (!existsSync(agentsMdPath)) {
60
+ writeFileSync(agentsMdPath, opts.agentsMd, 'utf-8');
61
+ }
62
+ }
63
+ if (opts.workspace) {
64
+ if (!isAbsolute(opts.workspace)) {
65
+ throw new Error(`workspace must be absolute or ~-form: ${opts.workspace}`);
66
+ }
67
+ mkdirSync(resolve(opts.workspace), { recursive: true });
68
+ }
69
+ }
70
+ /**
71
+ * 读 AGENTS.md(persona 全文)
72
+ *
73
+ * @param agentId - agent id
74
+ * @param home - agent 配置的 home(缺省用标准布局路径)
75
+ * @returns 文件内容;不存在返回 null
76
+ */
77
+ readPersona(agentId, home) {
78
+ const path = join(home ?? this.homeOf(agentId), 'AGENTS.md');
79
+ return existsSync(path) ? readFileSync(path, 'utf-8') : null;
80
+ }
81
+ /**
82
+ * 写 AGENTS.md(persona 编辑;builder 指纹缓存自动重读)
83
+ *
84
+ * @param agentId - agent id
85
+ * @param content - AGENTS.md 全文
86
+ * @param home - agent 配置的 home(缺省用标准布局路径)
87
+ * @throws home 不存在时抛错(fail-loud,防写到未 scaffold 的空洞路径)
88
+ */
89
+ writePersona(agentId, content, home) {
90
+ const dir = home ?? this.homeOf(agentId);
91
+ if (!existsSync(dir)) {
92
+ throw new Error(`agent home not found: ${dir} (scaffold first)`);
93
+ }
94
+ writeFileSync(join(dir, 'AGENTS.md'), content, 'utf-8');
95
+ }
96
+ }
@@ -4,6 +4,8 @@
4
4
  export interface CliArgs {
5
5
  command: string;
6
6
  subcommand?: string;
7
+ /** 第三个位置参数(如 `octopi ops kill <agentId>` 的 agentId) */
8
+ target?: string;
7
9
  config?: string;
8
10
  port?: number;
9
11
  help?: boolean;
@@ -18,6 +20,10 @@ export interface CliArgs {
18
20
  restore?: boolean | string;
19
21
  /** llm-diff:目标 session id(缺省 = 最近更新的 session) */
20
22
  session?: string;
23
+ /** chat:目标 agent id(缺省 = config.agents[0]) */
24
+ agent?: string;
25
+ /** chat:启动即续接的会话 id(含历史加载) */
26
+ resume?: string;
21
27
  /** llm-diff:wire dump 根目录 */
22
28
  dir?: string;
23
29
  /** llm-diff:展示的调用条数(0 = 全部) */
package/dist/cli/args.js CHANGED
@@ -31,6 +31,8 @@ export function parseArgs(argv = process.argv.slice(2)) {
31
31
  let only;
32
32
  let restore;
33
33
  let session;
34
+ let agent;
35
+ let resume;
34
36
  let dir;
35
37
  let limit;
36
38
  let cacheDiscount;
@@ -91,6 +93,12 @@ export function parseArgs(argv = process.argv.slice(2)) {
91
93
  case '--session':
92
94
  session = requireFlagValue(argv, ++i, '--session');
93
95
  break;
96
+ case '--agent':
97
+ agent = requireFlagValue(argv, ++i, '--agent');
98
+ break;
99
+ case '--resume':
100
+ resume = requireFlagValue(argv, ++i, '--resume');
101
+ break;
94
102
  case '--dir':
95
103
  dir = requireFlagValue(argv, ++i, '--dir');
96
104
  break;
@@ -121,6 +129,7 @@ export function parseArgs(argv = process.argv.slice(2)) {
121
129
  return {
122
130
  command: positional[0] ?? 'help',
123
131
  subcommand: positional[1],
132
+ target: positional[2],
124
133
  config,
125
134
  port,
126
135
  help,
@@ -133,6 +142,8 @@ export function parseArgs(argv = process.argv.slice(2)) {
133
142
  allowDeleteLegacyDirs,
134
143
  restore,
135
144
  session,
145
+ agent,
146
+ resume,
136
147
  dir,
137
148
  limit,
138
149
  cacheDiscount,
@@ -7,7 +7,7 @@ import { loadConfig } from '../config.js';
7
7
  import { initOctopi, getOctopiHome, isInitialized, formatInitReport } from '../init.js';
8
8
  import { readPidFile, writePidFile, removePidFile, isProcessAlive } from './daemon.js';
9
9
  import { createProviderFromConfig } from '@octopi-agent/engine/config.js';
10
- import { resolveGatewayUrl } from './helpers.js';
10
+ import { resolveGatewayUrl, resolveGatewayApiKey, selectChatAgent } from './helpers.js';
11
11
  export function showHelp() {
12
12
  console.log(`
13
13
  Octopi — AI Agent Framework
@@ -30,6 +30,9 @@ Commands:
30
30
  webui restart Restart the Web UI server
31
31
  webui status Show Web UI server status
32
32
  plugin init Scaffold a new plugin project
33
+ ops kill <id> Kill switch: stop ALL execution of an agent (host-side, immediate)
34
+ ops revive <id> Release the kill switch and resume execution
35
+ ops status [id] Show kill-switch state for one or all agents
33
36
  llm-diff [session]
34
37
  Compare dumped LLM requests and locate cache-prefix breaks
35
38
  help Show this help message
@@ -47,6 +50,8 @@ Options:
47
50
  --allow-delete-legacy-dirs
48
51
  doctor: with --fix layout, rename obsolete memory/wisdom/extract dirs
49
52
  --session <id> llm-diff: target session (default: most recently updated)
53
+ --agent <id> chat: agent to chat with (default: first agent in config)
54
+ --resume <id> chat: resume an existing session (loads recent history)
50
55
  --dir <path> llm-diff: wire dump root (default: ~/.octopi/logs/llm-requests)
51
56
  --limit <n> llm-diff: number of calls to show (0 = all, default 20)
52
57
  --cache-discount <r> llm-diff: cache-hit price as a ratio of full price (default 0.1);
@@ -91,9 +96,12 @@ export async function ensureInitialized(args) {
91
96
  export async function chatCommand(args) {
92
97
  const configPath = await ensureInitialized(args);
93
98
  const config = loadConfig(configPath);
94
- const agent = config.agents[0];
99
+ const agent = selectChatAgent(config.agents, args.agent);
95
100
  if (!agent) {
96
- console.error('[Error] No agents defined in config');
101
+ const available = config.agents.map((a) => a.id).join(', ') || '(none)';
102
+ console.error(args.agent
103
+ ? `[Error] Agent "${args.agent}" not found in config; available: ${available}`
104
+ : '[Error] No agents defined in config');
97
105
  process.exit(1);
98
106
  }
99
107
  let pidFile = readPidFile();
@@ -153,6 +161,8 @@ export async function chatCommand(args) {
153
161
  const app = new TuiApp({
154
162
  agentId: agent.id,
155
163
  gatewayUrl,
164
+ apiKey: resolveGatewayApiKey(config),
165
+ resumeSessionId: args.resume,
156
166
  });
157
167
  await app.start();
158
168
  }
@@ -96,6 +96,56 @@ export declare function diagnoseStartupFailure(opts: {
96
96
  configPath?: string;
97
97
  logPath: string;
98
98
  }): string[];
99
+ /**
100
+ * 识别本次启动中 privileged 声明闸门的拒绝。
101
+ *
102
+ * gateway.log 是追加写入:只认 startMarker 之后切片里的标记,
103
+ * 否则上一次运行的同类拒绝会误触发本次启动的独立提示;
104
+ * 本次标记缺失(日志被轮转/替换)时无法界定归属,返回 null 走通用诊断。
105
+ *
106
+ * @param logPath Gateway 日志路径
107
+ * @param startMarker 本次 `serve start` 写下的 `--- octopi serve start ... ---` 行
108
+ * @returns 命中时返回 scope(elevated 启动闸门恒为 `<top>`;解析器保持 scope 无关),未命中/日志不可读返回 null
109
+ */
110
+ export declare function detectPrivilegedDeclarationFailure(logPath: string, startMarker: string): string | null;
111
+ /**
112
+ * elevated 启动声明的取值面:部署级知情声明(§8.1),只读顶层 `effectPolicy.privilegedAck`。
113
+ *
114
+ * agent 块内的 privilegedAck 是该块自己的 jail=none / escalation=full 范围级表态
115
+ * (schema refine 与 resolveEffectiveEffectPolicy 按块执法),**永不**参与 elevated
116
+ * 启动闸门——agent ack 满足不了部署声明。独立成纯函数供测试钉住这两个方向。
117
+ *
118
+ * @param config 顶层配置(只读 `effectPolicy.privilegedAck`)
119
+ * @returns 恒为 `<top>` scope 及其声明值(未声明时 `ack` 为 undefined)
120
+ */
121
+ export declare function resolveElevatedDeclarationScope(config: {
122
+ effectPolicy?: {
123
+ privilegedAck?: string;
124
+ };
125
+ }): {
126
+ name: '<top>';
127
+ ack?: string;
128
+ };
129
+ /**
130
+ * privileged 声明闸门拒绝的独立双语提示(不套「gateway 崩溃 + 日志尾巴」框架)。
131
+ *
132
+ * elevated 启动声明只认顶层(§8.1 部署级知情声明),修复指引恒指顶层 effectPolicy;
133
+ * agent 块内的 privilegedAck 只服务该块自己的 jail=none / escalation=full 范围级表态,
134
+ * 不参与 elevated 启动声明。scope 仅忠实回显断言来源供日志定位。
135
+ *
136
+ * 示例 JSON 刻意不含注释:octopi.json 是严格 JSON,用户原样粘贴必须合法。
137
+ *
138
+ * @param opts.scope 断言来源(elevated 启动闸门恒为 `<top>`)
139
+ * @param opts.configPath 实际加载的配置文件路径(指给用户修改的位置)
140
+ * @param opts.restartCommand 可复述给用户的重启动命令;缺省用中性的「重启 Octopi」
141
+ * (同一提示会被 `serve fg` 直跑路径复用,写死 `serve start` 会指错命令)
142
+ * @returns 逐行提示文本;首行含机器可读标记 `privileged_declaration_required (<scope>)`
143
+ */
144
+ export declare function renderPrivilegedDeclarationNotice(opts: {
145
+ scope: string;
146
+ configPath: string;
147
+ restartCommand?: string;
148
+ }): string[];
99
149
  /**
100
150
  * 从 `summary.tools` 配置推导 toolBindings 覆盖表(逐工具名转发,不点名硬编码)
101
151
  *
@@ -5,9 +5,10 @@ import { resolve, dirname, join } from 'node:path';
5
5
  import { spawn } from 'node:child_process';
6
6
  import { readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, openSync, closeSync, writeSync, } from 'node:fs';
7
7
  import { getOctopiHome, isInitialized, initOctopi, formatInitReport } from '../init.js';
8
- import { loadConfig, toGatewayConfig } from '../config.js';
8
+ import { loadConfig, toGatewayConfig, resolveConfigFilePath } from '../config.js';
9
9
  import { createToolSet } from '@octopi-agent/engine/harness/extension/plugin-ecosystem/tools/tool-set.js';
10
10
  import { createProviderFromConfig, createWireDumpSinkFromConfig } from '@octopi-agent/engine/config.js';
11
+ import { startLoopWatchdog } from '@octopi-agent/engine/integration/observability/loop-watchdog.js';
11
12
  import { Gateway } from '@octopi-agent/gateway/gateway/gateway.js';
12
13
  import { webuiStartCommand, webuiStopCommand } from './webui.js';
13
14
  import { delay, findPidOnPort, getProcessName, isProcessAlive, killProcess, killProcessOnPort, } from './process-utils.js';
@@ -16,6 +17,10 @@ export { findPidOnPort, isProcessAlive, killProcessOnPort };
16
17
  export function getPidPath() {
17
18
  return join(getOctopiHome(), 'gateway.pid');
18
19
  }
20
+ /** 缺省配置路径(模块级封装:`startGatewayBlocking` 内有同名 `await import` 遮蔽,函数内直接引用会 TDZ) */
21
+ function defaultConfigPath() {
22
+ return join(getOctopiHome(), 'octopi.json');
23
+ }
19
24
  export function readPidFile() {
20
25
  const pidPath = getPidPath();
21
26
  if (!existsSync(pidPath))
@@ -140,7 +145,7 @@ export async function identifyPortOccupant(port) {
140
145
  ...base,
141
146
  state: 'foreign',
142
147
  pid,
143
- processName: getProcessName(pid) ?? undefined,
148
+ processName: (await getProcessName(pid)) ?? undefined,
144
149
  };
145
150
  }
146
151
  if (pidFile && isProcessAlive(pidFile.pid) && (pidFile.port ?? port) === port) {
@@ -293,6 +298,102 @@ export function diagnoseStartupFailure(opts) {
293
298
  lines.push(`Foreground debug: octopi serve fg${configPath ? ` -c ${configPath}` : ''}`);
294
299
  return lines;
295
300
  }
301
+ /** privileged 声明闸门拒绝的机器可读标记(子进程写日志,serve start 父进程据此换独立提示呈现) */
302
+ const PRIVILEGED_DECLARATION_RE = /privileged_declaration_required \(([^)]+)\)/;
303
+ /**
304
+ * 识别本次启动中 privileged 声明闸门的拒绝。
305
+ *
306
+ * gateway.log 是追加写入:只认 startMarker 之后切片里的标记,
307
+ * 否则上一次运行的同类拒绝会误触发本次启动的独立提示;
308
+ * 本次标记缺失(日志被轮转/替换)时无法界定归属,返回 null 走通用诊断。
309
+ *
310
+ * @param logPath Gateway 日志路径
311
+ * @param startMarker 本次 `serve start` 写下的 `--- octopi serve start ... ---` 行
312
+ * @returns 命中时返回 scope(elevated 启动闸门恒为 `<top>`;解析器保持 scope 无关),未命中/日志不可读返回 null
313
+ */
314
+ export function detectPrivilegedDeclarationFailure(logPath, startMarker) {
315
+ try {
316
+ const text = readFileSync(logPath, 'utf-8');
317
+ const idx = text.lastIndexOf(startMarker);
318
+ if (idx < 0)
319
+ return null;
320
+ return PRIVILEGED_DECLARATION_RE.exec(text.slice(idx + startMarker.length))?.[1] ?? null;
321
+ }
322
+ catch {
323
+ // 日志缺失/不可读:无法识别,调用方走通用「崩溃 + 日志尾巴」呈现(呈现降级,不是安全绕过)
324
+ return null;
325
+ }
326
+ }
327
+ /**
328
+ * elevated 启动声明的取值面:部署级知情声明(§8.1),只读顶层 `effectPolicy.privilegedAck`。
329
+ *
330
+ * agent 块内的 privilegedAck 是该块自己的 jail=none / escalation=full 范围级表态
331
+ * (schema refine 与 resolveEffectiveEffectPolicy 按块执法),**永不**参与 elevated
332
+ * 启动闸门——agent ack 满足不了部署声明。独立成纯函数供测试钉住这两个方向。
333
+ *
334
+ * @param config 顶层配置(只读 `effectPolicy.privilegedAck`)
335
+ * @returns 恒为 `<top>` scope 及其声明值(未声明时 `ack` 为 undefined)
336
+ */
337
+ export function resolveElevatedDeclarationScope(config) {
338
+ return { name: '<top>', ack: config.effectPolicy?.privilegedAck };
339
+ }
340
+ /**
341
+ * privileged 声明闸门拒绝的独立双语提示(不套「gateway 崩溃 + 日志尾巴」框架)。
342
+ *
343
+ * elevated 启动声明只认顶层(§8.1 部署级知情声明),修复指引恒指顶层 effectPolicy;
344
+ * agent 块内的 privilegedAck 只服务该块自己的 jail=none / escalation=full 范围级表态,
345
+ * 不参与 elevated 启动声明。scope 仅忠实回显断言来源供日志定位。
346
+ *
347
+ * 示例 JSON 刻意不含注释:octopi.json 是严格 JSON,用户原样粘贴必须合法。
348
+ *
349
+ * @param opts.scope 断言来源(elevated 启动闸门恒为 `<top>`)
350
+ * @param opts.configPath 实际加载的配置文件路径(指给用户修改的位置)
351
+ * @param opts.restartCommand 可复述给用户的重启动命令;缺省用中性的「重启 Octopi」
352
+ * (同一提示会被 `serve fg` 直跑路径复用,写死 `serve start` 会指错命令)
353
+ * @returns 逐行提示文本;首行含机器可读标记 `privileged_declaration_required (<scope>)`
354
+ */
355
+ export function renderPrivilegedDeclarationNotice(opts) {
356
+ const { scope, configPath } = opts;
357
+ const zhRestart = opts.restartCommand
358
+ ? `保存后重新运行 '${opts.restartCommand}'。`
359
+ : '保存后重新启动 Octopi。';
360
+ const enRestart = opts.restartCommand
361
+ ? `Save the file, then re-run '${opts.restartCommand}'.`
362
+ : 'Save the file, then restart Octopi.';
363
+ return [
364
+ `⛔ privileged_declaration_required (${scope}) — 高权限启动已被拒绝 / elevated startup refused`,
365
+ '',
366
+ '【中文】',
367
+ '你正在以系统管理员(root/admin)权限启动 Octopi,这将使 Octopi 具备系统级权限。',
368
+ 'Octopi 拒绝在没有显式声明的情况下以高权限运行(不允许静默的特权部署)。',
369
+ '',
370
+ '如果你确定要以管理员身份启动,请在配置文件:',
371
+ ` ${configPath}`,
372
+ '在其中的顶层 effectPolicy 中加入 privilegedAck 字段(任意非空字符串,是「我明确知道这是特权部署」的申明)。',
373
+ '例如(已有的其他 effectPolicy 字段照旧保留;配置文件是严格 JSON,不要写注释):',
374
+ '',
375
+ ' "effectPolicy": {',
376
+ ' "privilegedAck": "windows-admin-by-design"',
377
+ ' }',
378
+ '',
379
+ `${zhRestart}如果不想以管理员权限运行,请改用普通用户权限的终端启动。`,
380
+ '',
381
+ '[EN]',
382
+ 'You are starting Octopi with elevated (root/admin) privileges, which grants it system-level access.',
383
+ 'Octopi refuses to run elevated without an explicit declaration — no silent privileged deployments.',
384
+ '',
385
+ 'If you intend to run as administrator, add a privilegedAck field (any non-empty string — an explicit',
386
+ 'acknowledgement that this is a privileged deployment) to your config file:',
387
+ ` ${configPath}`,
388
+ 'Apply it at the top-level effectPolicy. Example (keep your other effectPolicy fields; the config file is strict JSON — no comments):',
389
+ '',
390
+ ' "effectPolicy": {',
391
+ ' "privilegedAck": "windows-admin-by-design"',
392
+ ' }',
393
+ '',
394
+ `${enRestart} To run unprivileged, use a normal (non-admin) terminal.`,
395
+ ];
396
+ }
296
397
  /**
297
398
  * 按 `observability.llmRequestDump` 构造 wire dump sink(未启用时 undefined)
298
399
  *
@@ -437,6 +538,31 @@ export async function serveStartCommand(args) {
437
538
  exited.then(() => ({ kind: 'exited', pid: null })),
438
539
  ]);
439
540
  if (outcome.kind !== 'ready' || !outcome.pid) {
541
+ // privileged 声明闸门拒绝 = 独立安全提示;不套「gateway 崩溃 + 日志尾巴」框架
542
+ const privilegedScope = outcome.kind === 'exited' && !spawnError
543
+ ? detectPrivilegedDeclarationFailure(logPath, startMarker)
544
+ : null;
545
+ if (privilegedScope) {
546
+ let noticeConfigPath = configPath ?? defaultConfigPath();
547
+ try {
548
+ noticeConfigPath = resolveConfigFilePath(configPath);
549
+ }
550
+ catch {
551
+ // 极窄窗口内配置文件被移走/不可读:提示本体照常呈现,回退展示缺省路径;
552
+ // 真实的「配置找不到」错误在子进程 loadConfig 已上浮进日志,不会被这里吞掉
553
+ }
554
+ for (const line of renderPrivilegedDeclarationNotice({
555
+ scope: privilegedScope,
556
+ configPath: noticeConfigPath,
557
+ restartCommand: 'octopi serve start',
558
+ })) {
559
+ console.error(line);
560
+ }
561
+ console.error('');
562
+ console.error(`Full log: ${logPath}`);
563
+ console.error(`Foreground debug: octopi serve fg${configPath ? ` -c ${configPath}` : ''}`);
564
+ process.exit(1);
565
+ }
440
566
  if (outcome.kind === 'exited') {
441
567
  if (spawnError) {
442
568
  console.error(`❌ Failed to launch Gateway child process: ${spawnError}`);
@@ -550,6 +676,21 @@ export async function serveRestartCommand(args) {
550
676
  await delay(500);
551
677
  await serveStartCommand(args);
552
678
  }
679
+ /** 读运行中网关的特权状态(ops P4;不可达时如实返回 null,不编造) */
680
+ async function fetchPrivilegedMarker(port) {
681
+ try {
682
+ const res = await fetch(`http://127.0.0.1:${port}/api/v1/health`, {
683
+ signal: AbortSignal.timeout(2000),
684
+ });
685
+ if (!res.ok)
686
+ return null;
687
+ const body = (await res.json());
688
+ return body.data?.privileged ?? null;
689
+ }
690
+ catch {
691
+ return null;
692
+ }
693
+ }
553
694
  export async function serveStatusCommand(args = {}) {
554
695
  const pidFile = readPidFile();
555
696
  const resolved = resolveGatewayPid(args, args.config);
@@ -567,6 +708,13 @@ export async function serveStatusCommand(args = {}) {
567
708
  if (pidFile?.startedAt)
568
709
  console.log(` Started: ${pidFile.startedAt}`);
569
710
  console.log(` Port: ${resolved.port}`);
711
+ // ops P4 §8.1:CLI 常驻 PRIVILEGED 标记(与 WebUI 同源:运行中网关 /health 的 privileged 块)
712
+ if (alive) {
713
+ const privileged = await fetchPrivilegedMarker(resolved.port);
714
+ if (privileged?.active) {
715
+ console.log(` Security: ⚠️ PRIVILEGED (${privileged.reasons.join('; ')})`);
716
+ }
717
+ }
570
718
  console.log();
571
719
  if (!alive && pidFile) {
572
720
  console.log(' ⚠️ PID file is stale (no listener on port / process dead).');
@@ -622,7 +770,83 @@ export async function serveCommand(args) {
622
770
  }
623
771
  async function startGatewayBlocking(configPath, args) {
624
772
  const config = loadConfig(configPath);
773
+ // ops P3 §4.1/拍板 #5:声明了提权就必须真的拿得到——启动期探测,失败拒绝启动,
774
+ // 禁止降级静默运行(allowlist 二进制 TOCTOU 护栏一并在此兜底)。
775
+ // 覆盖面 = 顶层 + 每 agent(agent 的 effectPolicy 整体覆盖顶层,漏了就是死码)。
776
+ {
777
+ const { probeEscalationReadiness, escalationWritableRoots } = await import('@octopi-agent/engine/harness/extension/execution-environment/privileged-exec.js');
778
+ const roots = escalationWritableRoots({
779
+ workspaces: [process.cwd()],
780
+ transactionRoots: (config.effectPolicy?.transactionRoots ?? []),
781
+ });
782
+ const candidates = [
783
+ { name: '<top>', escalation: config.effectPolicy?.escalation },
784
+ ];
785
+ for (const agent of config.agents ?? []) {
786
+ if (agent.effectPolicy?.escalation) {
787
+ candidates.push({ name: agent.id ?? '<agent>', escalation: agent.effectPolicy.escalation });
788
+ }
789
+ }
790
+ for (const candidate of candidates) {
791
+ const ready = await probeEscalationReadiness(candidate.escalation, { writableRoots: roots });
792
+ if (!ready.ok) {
793
+ console.error(`✗ Escalation readiness probe failed (${candidate.name}) — refusing to start (no silent degradation):`);
794
+ console.error(` ${ready.reason}`);
795
+ process.exit(1);
796
+ }
797
+ }
798
+ // ops P4 §5 P4:root/elevated 部署语义——daemon 以高权限跑时没有 sudo,危险轴是
799
+ // 「笼不笼 × uid=0」,必须显式 privileged 声明(同 privilegedAck),拒绝静默特权态。
800
+ // ack 是部署级知情声明(进程 elevated 事实,§8.1 二级确认):只看顶层声明。
801
+ // agent 块内的 privilegedAck 服务于该块自己的 jail=none / escalation=full 范围级表态
802
+ // (schema refine 与 resolveEffectiveEffectPolicy 按块执法),与 elevated 启动声明无关。
803
+ const { isProcessElevated, assertPrivilegedDeclaration } = await import('@octopi-agent/engine/harness/extension/execution-environment/privileged-exec.js');
804
+ const elevated = await isProcessElevated();
805
+ if (elevated) {
806
+ const declaration = resolveElevatedDeclarationScope(config);
807
+ try {
808
+ assertPrivilegedDeclaration({
809
+ elevated,
810
+ privilegedAck: declaration.ack,
811
+ scope: declaration.name,
812
+ });
813
+ }
814
+ catch (err) {
815
+ // 仅闸门断言渲染独立提示(首行含机器可读标记,serve start 父进程据此换呈现);
816
+ // 其他异常原样上浮,不伪装成 privilegedAck 缺失
817
+ if (!(err instanceof Error) || !err.message.startsWith('privileged_declaration_required')) {
818
+ throw err;
819
+ }
820
+ let noticeConfigPath = configPath ?? defaultConfigPath();
821
+ try {
822
+ noticeConfigPath = resolveConfigFilePath(configPath);
823
+ }
824
+ catch {
825
+ // 极窄窗口内配置文件被移走/不可读:回退展示缺省路径;加载失败的真实错误已在 loadConfig 上浮
826
+ }
827
+ for (const line of renderPrivilegedDeclarationNotice({
828
+ scope: '<top>',
829
+ configPath: noticeConfigPath,
830
+ // 守护模式由 serve start 拉起,可复述该命令;直跑 fg 时用中性措辞避免指错命令
831
+ restartCommand: process.env.OCTOPI_DAEMON === '1' ? 'octopi serve start' : undefined,
832
+ })) {
833
+ console.error(line);
834
+ }
835
+ process.exit(1);
836
+ }
837
+ console.log('⚠ PRIVILEGED: process is elevated (root/admin) — persistent PRIVILEGED marker is now in effect.');
838
+ }
839
+ }
625
840
  const gatewayConfig = toGatewayConfig(config);
841
+ // ops P2 §4.3/§8.4:daemon 持安全字段启动锚,run 起点复核,漂移拒新 run
842
+ // (取 raw 文件切面与复核同口径;agent 改写自身配置 = 自提权面)。
843
+ // console 受控写(config-apply)经 guard.reattest 署名重锚定,见「WebUI 署名通道」。
844
+ {
845
+ const { createSecurityIntegrityGuard } = await import('@octopi-agent/engine/harness/agent/config-integrity.js');
846
+ const { resolveConfigFilePath } = await import('../config.js');
847
+ const filePath = resolveConfigFilePath(configPath);
848
+ gatewayConfig.securityIntegrity = createSecurityIntegrityGuard({ configPath: filePath });
849
+ }
626
850
  // AgentRuntime 构造参数在 toGatewayConfig 已带上;此处仅防御显式覆盖
627
851
  if (config.agentRuntime) {
628
852
  gatewayConfig.agentRuntime = {
@@ -836,7 +1060,45 @@ async function startGatewayBlocking(configPath, args) {
836
1060
  const { HttpChannelAdapter } = await import('@octopi-agent/gateway/protocols/http.js');
837
1061
  const { WebApiRouter } = await import('@octopi-agent/gateway/web/api/router.js');
838
1062
  const { resolveListenHost } = await import('@octopi-agent/engine/config.js');
839
- const webApiRouter = new WebApiRouter({ gateway, basePath: '/api/v1' });
1063
+ // 配置管理面(arch/config-hot-reload.md):FileConfigService(IO)+ provider 工厂(带 wireDump)
1064
+ const { ConfigApplyService } = await import('@octopi-agent/gateway/gateway/config-apply.js');
1065
+ const { FileConfigService } = await import('../config-service.js');
1066
+ const { AgentFileAdmin } = await import('../agent-admin.js');
1067
+ const { createConfigAuditSink } = await import('../config-audit.js');
1068
+ const { detectUnknownConfigKeys, parseConfigPath } = await import('../config-schema/unknown-keys.js');
1069
+ const { FileRoleTemplateStore } = await import('../role-template-store.js');
1070
+ const { resolveAgentDefinition, normalizeConfigRaw } = await import('../config.js');
1071
+ const configService = new FileConfigService({ configPath });
1072
+ const configApply = new ConfigApplyService({
1073
+ gateway,
1074
+ configAdmin: configService,
1075
+ providerFactory: (name, pc) => createProviderFromConfig(name, pc, { wireDump }),
1076
+ agentFiles: new AgentFileAdmin(),
1077
+ auditSink: createConfigAuditSink(),
1078
+ roleTemplates: new FileRoleTemplateStore(),
1079
+ unknownKeys: {
1080
+ detect: (raw) => detectUnknownConfigKeys(raw),
1081
+ parsePath: (path) => parseConfigPath(path),
1082
+ },
1083
+ // raw agents[] 条目 → AgentDefinition:与启动解析同规(normalizeConfigRaw 同管线)。
1084
+ // rawConfig 为写前预演的 would-be 全量 raw(fail-safe 预构造,见 config-apply)。
1085
+ agentDefFactory: (rawEntry, rawConfig) => {
1086
+ const normalized = normalizeConfigRaw(rawConfig);
1087
+ const entry = normalized.agents.find((a) => a.id === rawEntry.id);
1088
+ if (!entry) {
1089
+ throw new Error(`agent not found in normalized config: ${String(rawEntry.id)}`);
1090
+ }
1091
+ return resolveAgentDefinition(entry, normalized);
1092
+ },
1093
+ });
1094
+ // 署名归因:apiKey 闸已验明持钥方 → 审批 confirmedBy 记 credential-backed 身份;
1095
+ // 无认证部署退回客户端自报(可仿冒,KNOWN-ISSUES 已声明)
1096
+ const webApiRouter = new WebApiRouter({
1097
+ gateway,
1098
+ basePath: '/api/v1',
1099
+ configApply,
1100
+ approverIdentity: httpConfig?.apiKey ? 'owner' : undefined,
1101
+ });
840
1102
  const listenHost = resolveListenHost(listenHostConfig);
841
1103
  gateway.registerChannel(new HttpChannelAdapter({
842
1104
  port: listenPort,
@@ -851,8 +1113,12 @@ async function startGatewayBlocking(configPath, args) {
851
1113
  }),
852
1114
  }));
853
1115
  }
1116
+ // 事件循环停滞看门狗(2026-10-28 事故的自检器官):worker 侧检测停滞 + 自动栈采样,
1117
+ // 报告落 <OCTOPI_HOME>/logs/loop-watchdog.jsonl;阈值经 observability.loopWatchdog 配置
1118
+ const loopWatchdog = startLoopWatchdog(config.observability?.loopWatchdog);
854
1119
  const shutdown = async () => {
855
1120
  console.log('\n[CLI] Shutting down...');
1121
+ loopWatchdog.stop();
856
1122
  await gateway.stop();
857
1123
  removePidFile();
858
1124
  process.exit(0);