@octopi-agent/engine 0.86.38 → 0.97.15

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 (218) hide show
  1. package/dist/config-admin/agent-presets.d.ts +70 -0
  2. package/dist/config-admin/agent-presets.js +243 -0
  3. package/dist/config-admin/discover.d.ts +30 -0
  4. package/dist/config-admin/discover.js +48 -0
  5. package/dist/config-admin/env.d.ts +22 -0
  6. package/dist/config-admin/env.js +41 -0
  7. package/dist/config-admin/index.d.ts +20 -0
  8. package/dist/config-admin/index.js +15 -0
  9. package/dist/config-admin/model-presets.d.ts +75 -0
  10. package/dist/config-admin/model-presets.js +249 -0
  11. package/dist/config-admin/name-guard.d.ts +14 -0
  12. package/dist/config-admin/name-guard.js +24 -0
  13. package/dist/config-admin/patch.d.ts +56 -0
  14. package/dist/config-admin/patch.js +201 -0
  15. package/dist/config-admin/port.d.ts +68 -0
  16. package/dist/config-admin/port.js +21 -0
  17. package/dist/config-admin/redact.d.ts +39 -0
  18. package/dist/config-admin/redact.js +42 -0
  19. package/dist/config-schema/agent.d.ts +43 -1
  20. package/dist/config-schema/agent.js +12 -5
  21. package/dist/config-schema/context.d.ts +7 -2
  22. package/dist/config-schema/context.js +8 -0
  23. package/dist/config-schema/engine.d.ts +110 -8
  24. package/dist/config-schema/governance.d.ts +43 -1
  25. package/dist/config-schema/governance.js +160 -2
  26. package/dist/config-schema/models.d.ts +7 -4
  27. package/dist/config-schema/models.js +4 -1
  28. package/dist/config-schema/observability.d.ts +9 -0
  29. package/dist/config-schema/observability.js +29 -0
  30. package/dist/config-schema/run.d.ts +3 -0
  31. package/dist/config-schema/run.js +14 -0
  32. package/dist/config-schema/shared.d.ts +3 -0
  33. package/dist/config-schema/shared.js +12 -0
  34. package/dist/config-schema/substrate.d.ts +1 -1
  35. package/dist/config.d.ts +60 -13
  36. package/dist/config.js +81 -78
  37. package/dist/harness/activation/dispatcher.d.ts +8 -2
  38. package/dist/harness/activation/dispatcher.js +33 -5
  39. package/dist/harness/activation/inbox.d.ts +87 -0
  40. package/dist/harness/activation/inbox.js +169 -0
  41. package/dist/harness/activation/runtime.d.ts +9 -8
  42. package/dist/harness/activation/runtime.js +100 -8
  43. package/dist/harness/activation/types.d.ts +19 -0
  44. package/dist/harness/activation/types.js +2 -0
  45. package/dist/harness/agent/builder.d.ts +18 -3
  46. package/dist/harness/agent/builder.js +42 -17
  47. package/dist/harness/agent/config-bridge.d.ts +5 -0
  48. package/dist/harness/agent/config-bridge.js +7 -1
  49. package/dist/harness/agent/config-integrity.d.ts +72 -0
  50. package/dist/harness/agent/config-integrity.js +146 -0
  51. package/dist/harness/agent/tool-purpose.d.ts +9 -1
  52. package/dist/harness/agent/tool-purpose.js +11 -2
  53. package/dist/harness/agent/wire-agent-builder.js +11 -3
  54. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.d.ts +11 -1
  55. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +11 -1
  56. package/dist/harness/collaboration/autonomous-subsystem/loader.d.ts +13 -0
  57. package/dist/harness/collaboration/autonomous-subsystem/loader.js +16 -1
  58. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +4 -0
  59. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +3 -1
  60. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  61. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  62. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  63. package/dist/harness/collaboration/delegation/service.js +2 -3
  64. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  65. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  66. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  67. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  68. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  69. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  70. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  71. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  72. package/dist/harness/context/capabilities/compact/index.js +2 -1
  73. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  74. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  75. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  76. package/dist/harness/context/constitution/default-agents.md +11 -10
  77. package/dist/harness/context/default-context-engine.d.ts +34 -4
  78. package/dist/harness/context/default-context-engine.js +198 -53
  79. package/dist/harness/context/hybrid-compressor.js +6 -0
  80. package/dist/harness/context/layer-types.d.ts +36 -0
  81. package/dist/harness/context/layer-types.js +38 -0
  82. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  83. package/dist/harness/context/llm-summarizer.js +69 -91
  84. package/dist/harness/context/message-selector.js +4 -3
  85. package/dist/harness/context/root-instructions.js +1 -1
  86. package/dist/harness/context/summarize.d.ts +2 -0
  87. package/dist/harness/context/summarize.js +7 -2
  88. package/dist/harness/context/system-prompt-assembler.js +10 -4
  89. package/dist/harness/context/tool-result-aging.js +2 -2
  90. package/dist/harness/context/truncate-compressor.js +7 -0
  91. package/dist/harness/context/turn-envelope.d.ts +4 -3
  92. package/dist/harness/context/turn-envelope.js +4 -3
  93. package/dist/harness/context/types.d.ts +33 -1
  94. package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
  95. package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
  96. package/dist/harness/extension/execution-environment/effect-policy.d.ts +133 -4
  97. package/dist/harness/extension/execution-environment/effect-policy.js +263 -14
  98. package/dist/harness/extension/execution-environment/index.d.ts +4 -2
  99. package/dist/harness/extension/execution-environment/index.js +2 -1
  100. package/dist/harness/extension/execution-environment/isolation.js +5 -1
  101. package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
  102. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  103. package/dist/harness/extension/execution-environment/ops-audit.d.ts +200 -0
  104. package/dist/harness/extension/execution-environment/ops-audit.js +338 -0
  105. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  106. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  107. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  108. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  109. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  110. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  111. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  112. package/dist/harness/extension/execution-environment/sandbox.js +264 -29
  113. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  114. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  115. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  116. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  117. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.d.ts +6 -0
  118. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +50 -0
  119. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
  120. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
  121. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
  122. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +53 -2
  123. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +10 -17
  124. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.d.ts +31 -0
  125. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.js +104 -0
  126. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.d.ts +111 -0
  127. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.js +197 -0
  128. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.d.ts +8 -8
  129. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +9 -100
  130. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +6 -0
  131. package/dist/harness/extension/plugin-ecosystem/tools/index.js +4 -0
  132. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  133. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  134. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  135. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  136. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  137. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  138. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  139. package/dist/harness/governance/security/temp-path.js +13 -2
  140. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  141. package/dist/harness/index.d.ts +4 -0
  142. package/dist/harness/index.js +3 -0
  143. package/dist/harness/knowledge/file-identity.d.ts +8 -0
  144. package/dist/harness/knowledge/file-identity.js +26 -1
  145. package/dist/harness/knowledge/fts.js +1 -2
  146. package/dist/harness/knowledge/grounding.js +5 -5
  147. package/dist/harness/knowledge/index-store.d.ts +31 -4
  148. package/dist/harness/knowledge/index-store.js +180 -48
  149. package/dist/harness/knowledge/ingest.d.ts +115 -115
  150. package/dist/harness/knowledge/ingest.js +150 -150
  151. package/dist/harness/knowledge/knowledge-serve-child.js +1 -1
  152. package/dist/harness/knowledge/purge.js +4 -1
  153. package/dist/harness/memory/backfill-coverage.js +3 -1
  154. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  155. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  156. package/dist/harness/observability/observer/hub.js +38 -1
  157. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  158. package/dist/harness/observability/observer/types.d.ts +27 -0
  159. package/dist/harness/run/agent/agent.d.ts +7 -0
  160. package/dist/harness/run/agent/agent.js +23 -1
  161. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  162. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  163. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  164. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  165. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  166. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  167. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  168. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  169. package/dist/harness/run/reliability/run-agent.js +231 -33
  170. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  171. package/dist/harness/run/run-scope.d.ts +31 -0
  172. package/dist/harness/run/runner.d.ts +132 -2
  173. package/dist/harness/run/runner.js +679 -60
  174. package/dist/harness/session/attachments/llm-intent.js +2 -1
  175. package/dist/harness/session/history/port.js +15 -5
  176. package/dist/harness/session/in-memory-store.d.ts +5 -0
  177. package/dist/harness/session/in-memory-store.js +33 -2
  178. package/dist/harness/session/tasks/render.d.ts +4 -1
  179. package/dist/harness/session/tasks/render.js +10 -7
  180. package/dist/harness/session/title.js +25 -9
  181. package/dist/harness/shared/events/agent-event-map.d.ts +92 -0
  182. package/dist/harness/shared/events/agent-event-map.js +7 -0
  183. package/dist/index.d.ts +6 -4
  184. package/dist/index.js +4 -3
  185. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  186. package/dist/integration/index.d.ts +2 -0
  187. package/dist/integration/index.js +1 -0
  188. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  189. package/dist/integration/observability/loop-watchdog.js +177 -0
  190. package/dist/integration/observability/metrics.d.ts +3 -0
  191. package/dist/integration/observability/metrics.js +18 -7
  192. package/dist/integration/observability/run-telemetry.d.ts +8 -0
  193. package/dist/integration/observability/run-telemetry.js +31 -8
  194. package/dist/integration/observability/trace-collector.js +26 -4
  195. package/dist/integration/observability/trace-events.d.ts +1 -0
  196. package/dist/integration/observability/trace-events.js +2 -0
  197. package/dist/integration/observability/trace-logger.js +27 -17
  198. package/dist/integration/providers/anthropic.d.ts +23 -0
  199. package/dist/integration/providers/anthropic.js +97 -12
  200. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  201. package/dist/integration/providers/fetch-timeout.js +51 -0
  202. package/dist/integration/providers/openai.d.ts +10 -0
  203. package/dist/integration/providers/openai.js +58 -11
  204. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  205. package/dist/integration/providers/provider-diagnostics.js +89 -0
  206. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  207. package/dist/integration/providers/timeout-coherence.js +68 -0
  208. package/dist/integration/providers/wire-dump.d.ts +62 -0
  209. package/dist/integration/providers/wire-dump.js +111 -2
  210. package/dist/integration/storage/jsonl.d.ts +19 -1
  211. package/dist/integration/storage/jsonl.js +100 -4
  212. package/dist/paths.d.ts +19 -0
  213. package/dist/paths.js +38 -1
  214. package/dist/subsystems/cognition-steward/conceptualize/handler.js +1 -1
  215. package/dist/subsystems/memory-steward/backfill/handler.js +1 -1
  216. package/dist/subsystems/safety-guard/config.yaml +3 -1
  217. package/dist/subsystems/wisdom-steward/formation/handler.js +1 -1
  218. package/package.json +3 -2
@@ -0,0 +1,350 @@
1
+ /**
2
+ * priv_exec 工具 — 白名单提权执行(ops P3,§5 P3 / §8)
3
+ *
4
+ * 独立 privileged 通道:引擎侧 execFile 执行完整 argv,不经 shell、不包 jail、
5
+ * env 消毒、**cwd 钉住**(规则显式或 `/`,绝不取 agent 的 cwd)、超时真树杀。
6
+ * shell 工具保持原牢笼语义不动(原则 6:提权不与牢笼抢轴)。
7
+ *
8
+ * 安全闸门(全 fail-closed):
9
+ * 1. **匹配面**(effect-policy `matchEscalationRule`):`allowlist` 档 cmd 绝对路径 +
10
+ * args 逐项全等;`full` 档(P4,需 privilegedAck + jail=none + mode=host)无
11
+ * allowlist 面,但 `via: sudo` 仍必须显式 `sudo -n` 形态(裸跑 = 非特权通道假象)。
12
+ * 未命中/形态非法 → 拒绝 + `ops.escalation.denied` 留痕(不留痕的拒绝等于没拒)。
13
+ * 2. **确认闸门**:规则 `confirm: true`(allowlist)或 §6 危险分类命中(full 档)走
14
+ * HitlDecision 单模型(§8.2),缓存 key 含**完整 argv 全等**(§5 P3:防一次批准
15
+ * 放行整类);特权通道把 `approve_always` 降格为 `approve_session`。
16
+ * **确认超时一律 deny**(T1 硬约束,outcome 不可配)。
17
+ * 3. **请求者授权**(§8.6 拍板):由 SEC-2 `toolRights.deny('priv_exec')` 表达——
18
+ * 缺权参与者在 toolRights 层即拒,连确认闸都到不了。
19
+ * 4. **审计**(§7):`ops.escalation.requested` → `ops.privileged.exec` / `denied`。
20
+ *
21
+ * `full` 档的 §6 分类是**减速带不是安全边界**(只拦事故不拦攻击):未命中自动放行,
22
+ * 不做「未知即危险」;真正的边界是 privilegedAck + 常驻 PRIVILEGED 标记 + 审计。
23
+ */
24
+ import { isAbsolute } from 'node:path';
25
+ import { matchEscalationRule } from '../../execution-environment/effect-policy.js';
26
+ import { classifyDangerousArgv } from '../../execution-environment/dangerous-commands.js';
27
+ import { runPrivilegedExec, } from '../../execution-environment/privileged-exec.js';
28
+ import { resolveHitlOutcome, } from '../../../governance/human-in-the-loop/decision-cache.js';
29
+ /**
30
+ * 确认闸计时(T1 硬约束:超时 = 拒绝,outcome 不可配)。
31
+ * 超时后宿主再批也无效(decision 已按 deny 定案)——宁可重请求,不可放马后炮。
32
+ *
33
+ * @param ask - 宿主确认回调(可携带拒绝来源/归因标注)
34
+ * @param timeoutMs - 确认窗毫秒
35
+ * @param abortSignal - run 中止信号(中止即收闸,不再空等确认窗走完)
36
+ * @returns 决策 + 来源标注(审计 why: confirm_timeout / confirm_denied / channel_error / aborted 可分辨)
37
+ */
38
+ async function askWithTimeout(ask, timeoutMs, abortSignal) {
39
+ let timer;
40
+ let onAbort;
41
+ const timeout = new Promise((res) => {
42
+ timer = setTimeout(() => res({ decision: 'deny', timedOut: true }), timeoutMs);
43
+ timer.unref?.();
44
+ });
45
+ const aborted = new Promise((res) => {
46
+ if (!abortSignal)
47
+ return;
48
+ onAbort = () => res({ decision: 'deny', denyReason: 'aborted' });
49
+ if (abortSignal.aborted)
50
+ onAbort();
51
+ else
52
+ abortSignal.addEventListener('abort', onAbort, { once: true });
53
+ });
54
+ try {
55
+ return await Promise.race([
56
+ ask().then((result) => ({ ...result, timedOut: result.timedOut ?? false })),
57
+ timeout,
58
+ aborted,
59
+ ]);
60
+ }
61
+ finally {
62
+ if (timer)
63
+ clearTimeout(timer);
64
+ if (onAbort)
65
+ abortSignal?.removeEventListener('abort', onAbort);
66
+ }
67
+ }
68
+ /**
69
+ * 创建 priv_exec 工具
70
+ *
71
+ * 参数:
72
+ * - cmd (string, required):可执行文件**绝对路径**(与规则逐字相同)
73
+ * - args (string[], optional):argv 尾部(与规则逐项全等)
74
+ *
75
+ * 返回:ruleId / exitCode / stdout / stderr / durationMs / confirmDecision。
76
+ *
77
+ * @param options - 可注入 HITL 缓存
78
+ * @returns 注册好的提权工具
79
+ */
80
+ export function createPrivExecTool(options) {
81
+ return {
82
+ definition: {
83
+ name: 'priv_exec',
84
+ // exec 标签:reduced 工具面(untrusted 降级)剥掉提权通道(降能力不降墙)
85
+ capabilities: ['exec'],
86
+ description: 'Execute a privileged command through the engine-side privileged channel. ' +
87
+ 'Under effectPolicy.escalation.policy=allowlist the argv must match an allow rule exactly (absolute cmd + identical args); ' +
88
+ 'under policy=full any absolute argv is accepted (via:sudo must spell `sudo -n <target…>`). ' +
89
+ 'Runs without a shell or jail; env scrubbed; cwd pinned by the rule (default /); timeout + tree-kill. ' +
90
+ 'Refused argv is audited (ops.escalation.denied). Rules with confirm:true — and any argv hitting the ' +
91
+ 'dangerous-command table under full — pass a HITL gate keyed on the full argv; confirm timeout is deny. ' +
92
+ 'This is the only privilege-escalation channel.',
93
+ parameters: {
94
+ cmd: {
95
+ type: 'string',
96
+ required: true,
97
+ description: 'Absolute path of the executable, exactly as configured in the allow rule',
98
+ },
99
+ args: {
100
+ type: 'array',
101
+ items: { type: 'string', description: 'argument' },
102
+ description: 'Arguments after cmd — must match the rule element-by-element (no prefix/regex matching)',
103
+ },
104
+ },
105
+ // 不设工具总线看门狗(同 ask_user 先例):真实时限全部内部强制——确认窗
106
+ // (dangerousCommands.timeoutMs,超时=拒绝)+ 执行超时(runPrivilegedExec 120s
107
+ // 树杀)。总线看门狗曾把 escalation_confirm_timeout 顶成 tool_timeout(错误语义
108
+ // 失真、诱导盲重试),且其阈值必须随配置漂移才成立——两处都错,故整块去掉。
109
+ },
110
+ handler: async (args, context) => {
111
+ const cmd = args.cmd;
112
+ const rawArgs = args.args;
113
+ const origin = {
114
+ sessionId: context?.sessionId,
115
+ agentId: context?.agentId,
116
+ runId: context?.runId ?? null,
117
+ // ops P5「参与者身份入账」:请求者是谁(SEC-2 角色绑定)——确认 ≠ 请求者可信
118
+ participants: context?.sessionParticipants ?? [],
119
+ };
120
+ // 参数形态非法也必须留痕(拒了没记 = 盲区)
121
+ const invalid = (() => {
122
+ if (typeof cmd !== 'string' || cmd === '')
123
+ return 'cmd must be a non-empty string';
124
+ if (rawArgs !== undefined && (!Array.isArray(rawArgs) || rawArgs.some((a) => typeof a !== 'string'))) {
125
+ return 'args must be an array of strings';
126
+ }
127
+ return null;
128
+ })();
129
+ if (invalid) {
130
+ context?.recordOpsEvent?.({
131
+ event: 'ops.escalation.denied',
132
+ data: { argv: [String(cmd), ...(Array.isArray(rawArgs) ? rawArgs.map(String) : [])], why: 'invalid_args', origin },
133
+ });
134
+ throw new Error(`priv_exec: ${invalid}`);
135
+ }
136
+ const argvTail = rawArgs ?? [];
137
+ // invalid 守卫已保证 cmd 为非空 string(TS 无法穿透闭包收窄,String() 为恒等转换)
138
+ const cmdStr = String(cmd);
139
+ const argv = [cmdStr, ...argvTail];
140
+ const escalation = context?.escalation;
141
+ if (!escalation || escalation.policy === 'none') {
142
+ context?.recordOpsEvent?.({
143
+ event: 'ops.escalation.denied',
144
+ data: { argv, why: 'policy_none', origin },
145
+ });
146
+ throw new Error('priv_exec disabled: effectPolicy.escalation.policy=none (enable allowlist/full to use priv_exec)');
147
+ }
148
+ // 匹配面:allowlist = cmd+args 全等;full(P4)= 全量档,仅校验形态(绝对路径 + sudo 显式形态)
149
+ let ruleId;
150
+ let ruleConfirm = false;
151
+ let ruleCwd;
152
+ if (escalation.policy === 'full') {
153
+ if (!isAbsolute(cmdStr)) {
154
+ context?.recordOpsEvent?.({
155
+ event: 'ops.escalation.denied',
156
+ data: { argv, why: 'invalid_args', origin },
157
+ });
158
+ throw new Error('priv_exec: cmd must be an absolute path (PATH resolution = replaceable binary)');
159
+ }
160
+ if (escalation.via === 'sudo') {
161
+ // full 档仍必须显式 `sudo -n <target…>` 形态:裸跑 = 非特权通道假象(与 allowlist 形态规则同构)
162
+ const base = cmdStr.replace(/\\/g, '/').split('/').pop()?.toLowerCase() ?? '';
163
+ const spellsSudo = base === 'sudo' || base === 'doas';
164
+ if (!spellsSudo || argvTail[0] !== '-n') {
165
+ context?.recordOpsEvent?.({
166
+ event: 'ops.escalation.denied',
167
+ data: { argv, why: 'invalid_args', origin },
168
+ });
169
+ throw new Error('priv_exec: full policy via=sudo must spell `sudo -n <target…>` explicitly (cmd = /usr/bin/sudo, args[0] = "-n")');
170
+ }
171
+ }
172
+ ruleId = 'full';
173
+ }
174
+ else {
175
+ const match = matchEscalationRule(escalation, cmdStr, argvTail);
176
+ if (!match) {
177
+ // 未命中即拒绝并留痕:拒绝必须可查(§7),否则注入探测就成了盲区
178
+ context?.recordOpsEvent?.({
179
+ event: 'ops.escalation.denied',
180
+ data: { argv, why: 'not_allowlisted', origin },
181
+ });
182
+ throw new Error('escalation_not_allowlisted: no allow rule matches this argv exactly (cmd absolute path + args element-by-element)');
183
+ }
184
+ ruleId = match.ruleId;
185
+ ruleConfirm = match.rule.confirm === true;
186
+ ruleCwd = match.rule.cwd;
187
+ }
188
+ // §6 危险分类(full 档 pre-exec 闸):命中走确认/deny,未命中放行(不做「未知即危险」)。
189
+ // allowlist 档由规则 confirm 显式表态,不叠加分类——规则作者已逐条裁决。
190
+ let dangerousPattern;
191
+ let needsConfirm = ruleConfirm;
192
+ if (escalation.policy === 'full') {
193
+ const verdict = classifyDangerousArgv(argv);
194
+ if (verdict.dangerous) {
195
+ dangerousPattern = verdict.pattern;
196
+ const gatePolicy = context?.dangerousCommands?.policy ?? 'confirm';
197
+ if (gatePolicy === 'deny') {
198
+ context?.recordOpsEvent?.({
199
+ event: 'ops.escalation.denied',
200
+ data: { ruleId, argv, why: 'dangerous_denied', dangerous: dangerousPattern, origin },
201
+ });
202
+ throw new Error(`escalation_dangerous_denied: ${JSON.stringify(argv)} hit \`${dangerousPattern}\` (dangerousCommands.policy=deny)`);
203
+ }
204
+ if (gatePolicy === 'confirm')
205
+ needsConfirm = true;
206
+ // 'off':分类关闭——命中仍入审计(留痕不设闸),但不拦
207
+ }
208
+ }
209
+ context?.recordOpsEvent?.({
210
+ event: 'ops.escalation.requested',
211
+ data: {
212
+ ruleId,
213
+ argv,
214
+ via: escalation.via,
215
+ decision: 'pending',
216
+ requester: origin,
217
+ ...(dangerousPattern !== undefined ? { dangerous: dangerousPattern } : {}),
218
+ },
219
+ });
220
+ let confirmDecision = 'auto';
221
+ // P5 确认人入账:谁批的、经哪条通道(宿主归因;未知如实缺省,不编造)
222
+ let confirmedBy;
223
+ let confirmChannel;
224
+ if (needsConfirm) {
225
+ // 确认超时一律 deny(T1 硬约束,outcome 不可配);超时/人工拒绝/通道故障在审计里可分辨
226
+ const confirmTimeoutMs = context?.dangerousCommands?.timeoutMs ?? 120_000;
227
+ const outcome = await resolveHitlOutcome({
228
+ // 缓存 key 含完整 argv 全等(§5 P3):一次 approve_session 只覆盖这一条命令
229
+ key: `priv:${JSON.stringify(argv)}`,
230
+ channel: 'effect',
231
+ // session/always 缓存需要归属(缺归属 = 退化 one-shot)
232
+ sessionId: context?.sessionId,
233
+ agentId: context?.agentId,
234
+ cache: options?.cache,
235
+ ask: () => askWithTimeout(async () => {
236
+ const confirmEffect = context?.confirmEffect;
237
+ // 无确认通道 ≠ 人工拒绝:如实标注来源,fail-closed
238
+ if (!confirmEffect) {
239
+ return {
240
+ decision: 'deny',
241
+ denyReason: 'no_channel',
242
+ denyDetail: 'confirmEffect hook absent',
243
+ };
244
+ }
245
+ const raw = await confirmEffect({
246
+ kind: 'shell',
247
+ // 无歧义渲染:argv 数组的 JSON 形式(join(' ') 无法区分 args 边界与换行注入)
248
+ command: JSON.stringify(argv),
249
+ cwd: ruleCwd ?? '/',
250
+ // 宿主卡片生命周期据此排在确认窗之后(严格晚 settle,防误标 confirm_denied)
251
+ timeoutMs: confirmTimeoutMs,
252
+ });
253
+ // 裸 HitlDecision 或 ConfirmOutcome(带归因/来源)都合法
254
+ const normalized = typeof raw === 'string' ? { decision: raw } : raw;
255
+ // 特权通道保守语义:approve_always 永久放行特权 argv 过宽 → 降格 session 级
256
+ const decision = normalized.decision === 'approve_always' ? 'approve_session' : normalized.decision;
257
+ return {
258
+ decision,
259
+ ...(normalized.approver !== undefined ? { approver: normalized.approver } : {}),
260
+ ...(normalized.channel !== undefined ? { channel: normalized.channel } : {}),
261
+ // 宿主标注的拒绝来源:timeout 归超时语义;其余(如 no_session_scope)
262
+ // 归通道故障——任何非人工来源都不得冒充人工拒绝
263
+ ...(decision === 'deny' && normalized.reason === 'timeout'
264
+ ? { timedOut: true }
265
+ : {}),
266
+ ...(decision === 'deny' &&
267
+ normalized.reason !== undefined &&
268
+ normalized.reason !== 'timeout'
269
+ ? { denyReason: 'channel_error', denyDetail: normalized.reason }
270
+ : {}),
271
+ };
272
+ }, confirmTimeoutMs, context?.abortSignal),
273
+ });
274
+ if (outcome.approver !== undefined)
275
+ confirmedBy = outcome.approver;
276
+ if (outcome.channel !== undefined)
277
+ confirmChannel = outcome.channel;
278
+ if (!outcome.allowed) {
279
+ const why = outcome.timedOut
280
+ ? 'confirm_timeout'
281
+ : outcome.denyReason === 'aborted' || outcome.denyReason === 'cancelled'
282
+ ? 'aborted'
283
+ : outcome.denyReason !== undefined
284
+ ? 'channel_error'
285
+ : 'confirm_denied';
286
+ context?.recordOpsEvent?.({
287
+ event: 'ops.escalation.denied',
288
+ data: {
289
+ ruleId,
290
+ argv,
291
+ why,
292
+ ...(outcome.denyDetail !== undefined ? { reason: outcome.denyDetail } : {}),
293
+ ...(dangerousPattern !== undefined ? { dangerous: dangerousPattern } : {}),
294
+ origin,
295
+ },
296
+ });
297
+ const argvText = JSON.stringify(argv);
298
+ throw new Error(outcome.timedOut
299
+ ? `escalation_confirm_timeout: no decision within ${confirmTimeoutMs}ms — timeout is deny (not configurable). A human approval request is still pending on the confirm channel; do NOT retry this call until a human decides: ${argvText}`
300
+ : why === 'aborted'
301
+ ? `priv_exec_aborted: run aborted while awaiting confirmation — nothing was executed: ${argvText}`
302
+ : why === 'channel_error'
303
+ ? `escalation_confirm_unavailable: confirm channel unavailable (${outcome.denyReason}${outcome.denyDetail ? `: ${outcome.denyDetail}` : ''}) — fail-closed deny, no human decision was reached: ${argvText}`
304
+ : `escalation_confirm_denied: a human rejected this argv — do NOT retry this call on your own: ${argvText}`);
305
+ }
306
+ confirmDecision = 'approved';
307
+ }
308
+ const result = await runPrivilegedExec({
309
+ cmd: cmdStr,
310
+ args: argvTail,
311
+ via: escalation.via,
312
+ // cwd 钉住:规则显式或 `/`——agent 的 cwd 无权决定特权进程在哪解析相对路径
313
+ cwd: ruleCwd ?? '/',
314
+ timeoutMs: 120_000,
315
+ // run 中止即时树杀(不等执行超时兜底)
316
+ abortSignal: context?.abortSignal,
317
+ });
318
+ context?.recordOpsEvent?.({
319
+ event: 'ops.privileged.exec',
320
+ data: {
321
+ ruleId,
322
+ argv,
323
+ via: escalation.via,
324
+ confirmDecision,
325
+ executed: result.executed,
326
+ exitCode: result.exitCode,
327
+ durationMs: result.durationMs,
328
+ timedOut: result.timedOut,
329
+ ...(dangerousPattern !== undefined ? { dangerous: dangerousPattern } : {}),
330
+ ...(confirmedBy !== undefined ? { confirmedBy } : {}),
331
+ ...(confirmChannel !== undefined ? { confirmChannel } : {}),
332
+ origin,
333
+ },
334
+ });
335
+ if (!result.executed) {
336
+ // 「未执行」≠「执行失败」:spawn 都没起来,业务结果不冒充执行
337
+ throw new Error(`priv_exec_spawn_failed: ${result.stderr}`);
338
+ }
339
+ return {
340
+ ruleId,
341
+ exitCode: result.exitCode,
342
+ stdout: result.stdout,
343
+ stderr: result.stderr,
344
+ durationMs: result.durationMs,
345
+ timedOut: result.timedOut,
346
+ confirmDecision,
347
+ };
348
+ },
349
+ };
350
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * process_list 工具 — 只读进程诊断(ops P1)
3
+ *
4
+ * 引擎侧枚举(procfs / ps / powershell),不经 shell 工具:
5
+ * macOS 牢笼拒 exec setuid 的 `ps`,Linux 牢笼在新 pidns 里看不到宿主进程,
6
+ * 「看进程」只能由牢笼外的引擎进程自己做。零权限放松——不杀进程、不改状态。
7
+ *
8
+ * 能力标签为 `host-read`(宿主内省,超出 workspace 信息面):
9
+ * reduced 工具面(untrusted 降级)**剥掉**本工具——argv 是凭证泄漏面
10
+ * (`--token=…`、内联脚本),且引擎侧数据源会绕过牢笼「看不到宿主进程」的边界。
11
+ */
12
+ import type { RegisteredTool } from '@octopi-agent/core/types.js';
13
+ /**
14
+ * 创建 process_list 工具
15
+ *
16
+ * 参数:
17
+ * - pid (number, optional): 查单个 pid —— 返回该进程条目 + 祖先链(远祖在前,自身为链尾)+ 可执行映像;不可与其余参数同用
18
+ * - pids (number[], optional): 只列出这些 pid
19
+ * - nameContains (string, optional): 命令行子串过滤(大小写不敏感)
20
+ * - sort ('rss' | 'pid', optional): 排序键,缺省 'rss' 降序(重的在前)
21
+ * - limit (number, optional): 返回上限,缺省 200;截断时 `truncated` 为 true
22
+ *
23
+ * 返回:进程条目(pid/ppid/command/rssBytes/cpuTimeMs/threads)+ matched/total/truncated
24
+ * + source + complete + notes。complete=false 表示来源降级/不全(如牢笼内 ps 被拒、
25
+ * 表行被跳过),此时进程表不可当作「机器上只有这些」。
26
+ * pid 模式另有 chainComplete:祖先链是否每一环都解析到了(与 complete 相互独立)。
27
+ *
28
+ * @returns 注册好的只读工具
29
+ */
30
+ export declare function createProcessListTool(): RegisteredTool;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * process_list 工具 — 只读进程诊断(ops P1)
3
+ *
4
+ * 引擎侧枚举(procfs / ps / powershell),不经 shell 工具:
5
+ * macOS 牢笼拒 exec setuid 的 `ps`,Linux 牢笼在新 pidns 里看不到宿主进程,
6
+ * 「看进程」只能由牢笼外的引擎进程自己做。零权限放松——不杀进程、不改状态。
7
+ *
8
+ * 能力标签为 `host-read`(宿主内省,超出 workspace 信息面):
9
+ * reduced 工具面(untrusted 降级)**剥掉**本工具——argv 是凭证泄漏面
10
+ * (`--token=…`、内联脚本),且引擎侧数据源会绕过牢笼「看不到宿主进程」的边界。
11
+ */
12
+ import { getAncestorPidChain, listProcesses, resolveProcessImage, selectProcesses, } from '../../execution-environment/process-info.js';
13
+ function entryToJson(entry) {
14
+ return {
15
+ pid: entry.pid,
16
+ ppid: entry.ppid,
17
+ command: entry.command,
18
+ rssBytes: entry.rssBytes,
19
+ cpuTimeMs: entry.cpuTimeMs,
20
+ threads: entry.threads,
21
+ };
22
+ }
23
+ /**
24
+ * 创建 process_list 工具
25
+ *
26
+ * 参数:
27
+ * - pid (number, optional): 查单个 pid —— 返回该进程条目 + 祖先链(远祖在前,自身为链尾)+ 可执行映像;不可与其余参数同用
28
+ * - pids (number[], optional): 只列出这些 pid
29
+ * - nameContains (string, optional): 命令行子串过滤(大小写不敏感)
30
+ * - sort ('rss' | 'pid', optional): 排序键,缺省 'rss' 降序(重的在前)
31
+ * - limit (number, optional): 返回上限,缺省 200;截断时 `truncated` 为 true
32
+ *
33
+ * 返回:进程条目(pid/ppid/command/rssBytes/cpuTimeMs/threads)+ matched/total/truncated
34
+ * + source + complete + notes。complete=false 表示来源降级/不全(如牢笼内 ps 被拒、
35
+ * 表行被跳过),此时进程表不可当作「机器上只有这些」。
36
+ * pid 模式另有 chainComplete:祖先链是否每一环都解析到了(与 complete 相互独立)。
37
+ *
38
+ * @returns 注册好的只读工具
39
+ */
40
+ export function createProcessListTool() {
41
+ return {
42
+ definition: {
43
+ name: 'process_list',
44
+ capabilities: ['host-read'],
45
+ description: 'List running processes (read-only host diagnostics; engine-side procfs/ps read, works even where a jailed shell cannot run `ps`). ' +
46
+ 'Fields per entry: pid, ppid, command, rssBytes, cpuTimeMs (cumulative CPU time — no percentage without sampling), threads. ' +
47
+ 'Pass `pid` to inspect one process: returns its entry, its ancestor chain (root-first, ending with the pid itself) and executable image. ' +
48
+ 'Check `complete`: false means the source was degraded/unreadable or dropped unparseable lines and the list is partial or empty — never read it as "nothing is running". ' +
49
+ '`chainComplete` (pid mode) reports whether every ancestor link resolved.',
50
+ parameters: {
51
+ pid: {
52
+ type: 'number',
53
+ minimum: 1,
54
+ description: 'Inspect a single pid: returns that entry plus its ancestor chain and image. Cannot be combined with any other parameter.',
55
+ },
56
+ pids: {
57
+ type: 'array',
58
+ items: { type: 'number', minimum: 1, description: 'pid' },
59
+ description: 'Restrict the listing to these pids (composes with nameContains/sort/limit)',
60
+ },
61
+ nameContains: {
62
+ type: 'string',
63
+ description: 'Case-insensitive substring filter on the command line',
64
+ },
65
+ sort: {
66
+ type: 'string',
67
+ enum: ['rss', 'pid'],
68
+ description: "Sort key: 'rss' (default; heaviest first) or 'pid' (ascending)",
69
+ },
70
+ limit: {
71
+ type: 'number',
72
+ minimum: 1,
73
+ description: 'Maximum entries to return (default 200); `truncated` reports the cut',
74
+ },
75
+ },
76
+ timeoutMs: 60_000,
77
+ },
78
+ handler: async (args) => {
79
+ const pid = args.pid;
80
+ const pids = args.pids;
81
+ const nameContains = args.nameContains;
82
+ const sort = args.sort;
83
+ const limit = args.limit;
84
+ if (pid !== undefined && (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0)) {
85
+ throw new Error(`process_list: pid must be a positive integer, got ${JSON.stringify(pid)}`);
86
+ }
87
+ if (pid !== undefined && (pids !== undefined || nameContains !== undefined || sort !== undefined || limit !== undefined)) {
88
+ throw new Error('process_list: pid cannot be combined with pids/nameContains/sort/limit');
89
+ }
90
+ if (pids !== undefined &&
91
+ (!Array.isArray(pids) || pids.some((p) => typeof p !== 'number' || !Number.isInteger(p) || p <= 0))) {
92
+ throw new Error('process_list: pids must be an array of positive integers');
93
+ }
94
+ if (nameContains !== undefined && (typeof nameContains !== 'string' || nameContains === '')) {
95
+ throw new Error('process_list: nameContains must be a non-empty string');
96
+ }
97
+ if (sort !== undefined && sort !== 'rss' && sort !== 'pid') {
98
+ throw new Error(`process_list: sort must be 'rss' or 'pid', got ${JSON.stringify(sort)}`);
99
+ }
100
+ if (limit !== undefined && (typeof limit !== 'number' || !Number.isInteger(limit) || limit <= 0)) {
101
+ throw new Error(`process_list: limit must be a positive integer, got ${JSON.stringify(limit)}`);
102
+ }
103
+ const listed = await listProcesses();
104
+ if (pid !== undefined) {
105
+ const built = await getAncestorPidChain(pid, listed);
106
+ const found = listed.processes.find((p) => p.pid === pid) ?? null;
107
+ return {
108
+ process: found ? entryToJson(found) : null,
109
+ image: await resolveProcessImage(pid),
110
+ ancestors: built.chain.map((ancestorPid) => ({
111
+ pid: ancestorPid,
112
+ command: listed.processes.find((p) => p.pid === ancestorPid)?.command ?? null,
113
+ })),
114
+ chainComplete: built.complete,
115
+ source: listed.source,
116
+ complete: listed.complete,
117
+ notes: found ? listed.notes : [...listed.notes, `pid ${pid} not present in this enumeration`],
118
+ };
119
+ }
120
+ const selected = selectProcesses(listed.processes, {
121
+ pids: pids,
122
+ nameContains: nameContains,
123
+ sort: sort === 'pid' ? 'pid' : 'rss',
124
+ limit: limit === undefined ? 200 : limit,
125
+ });
126
+ return {
127
+ processes: selected.selected.map(entryToJson),
128
+ matched: selected.matched,
129
+ total: selected.total,
130
+ truncated: selected.truncated,
131
+ source: listed.source,
132
+ complete: listed.complete,
133
+ notes: listed.notes,
134
+ };
135
+ },
136
+ };
137
+ }
@@ -15,6 +15,32 @@ import type { HitlDecision } from '@octopi-agent/core/types/tools.js';
15
15
  export type HitlChannel = 'high_risk' | 'effect';
16
16
  /** Cached scope of a remembered approval */
17
17
  export type HitlCacheScope = 'session' | 'always';
18
+ /** 非人工拒绝来源(人工决策不带此标注);用于错误面与审计如实归因 */
19
+ export type HitlDenyReason = 'no_channel' | 'channel_error' | 'aborted' | 'cancelled';
20
+ /** ask 回调结果:裸决策或带来源/归因标注(同 key 并发合流共享) */
21
+ export interface HitlAskResult {
22
+ decision: HitlDecision;
23
+ /** 确认窗到期(超时=拒绝,T1 硬约束) */
24
+ timedOut?: boolean;
25
+ /** 非人工拒绝来源 */
26
+ denyReason?: HitlDenyReason;
27
+ /** 拒绝来源细节(如宿主 reason 原文) */
28
+ denyDetail?: string;
29
+ /** 确认人署名(随 channel 判读可信度) */
30
+ approver?: string;
31
+ /** 确认通道 */
32
+ channel?: string;
33
+ }
34
+ /** HITL 决策结果(同 key 并发合流共享同一结果对象,杜绝各说各话) */
35
+ export interface HitlOutcome {
36
+ allowed: boolean;
37
+ decision: HitlDecision;
38
+ timedOut: boolean;
39
+ denyReason?: HitlDenyReason;
40
+ denyDetail?: string;
41
+ approver?: string;
42
+ channel?: string;
43
+ }
18
44
  /**
19
45
  * In-memory HITL approval cache.
20
46
  *
@@ -73,16 +99,25 @@ export declare class HitlDecisionCache {
73
99
  clear(): void;
74
100
  /**
75
101
  * Resolve through cache + host hook with in-flight de-dup.
76
- * Concurrent callers for the same key share one `ask()`.
102
+ * Concurrent callers for the same key share one `ask()` and one outcome object
103
+ * (decision + timedOut + attribution — 合流者不得各自编造拒绝来源).
77
104
  */
78
105
  resolve(options: {
79
106
  channel: HitlChannel;
80
107
  key: string;
81
108
  sessionId?: string;
82
109
  agentId?: string;
83
- ask: () => Promise<HitlDecision>;
110
+ ask: () => Promise<HitlDecision | HitlAskResult>;
84
111
  }): Promise<boolean>;
85
- private resolveUncached;
112
+ /** 同 {@link resolve},但回传完整结果(timedOut / 拒绝来源 / 归因),供错误面与审计口径一致。 */
113
+ resolveOutcome(options: {
114
+ channel: HitlChannel;
115
+ key: string;
116
+ sessionId?: string;
117
+ agentId?: string;
118
+ ask: () => Promise<HitlDecision | HitlAskResult>;
119
+ }): Promise<HitlOutcome>;
120
+ private resolveOutcomeUncached;
86
121
  }
87
122
  /** Process-wide default cache (keys include sessionId / agentId). */
88
123
  export declare const defaultHitlCache: HitlDecisionCache;
@@ -101,5 +136,20 @@ export declare function resolveHitlDecision(options: {
101
136
  key: string;
102
137
  sessionId?: string;
103
138
  agentId?: string;
104
- ask: () => Promise<HitlDecision>;
139
+ ask: () => Promise<HitlDecision | HitlAskResult>;
105
140
  }): Promise<boolean>;
141
+ /**
142
+ * 同 {@link resolveHitlDecision},但回传完整结果(timedOut / 拒绝来源 / 归因)——
143
+ * 供调用方把错误面标注得与审计一致:超时 ≠ 人工拒绝 ≠ 通道故障,三者不得混为一谈。
144
+ *
145
+ * @param options - 同 resolveHitlDecision
146
+ * @returns 完整决策结果(同 key 并发合流共享同一对象)
147
+ */
148
+ export declare function resolveHitlOutcome(options: {
149
+ cache?: HitlDecisionCache;
150
+ channel: HitlChannel;
151
+ key: string;
152
+ sessionId?: string;
153
+ agentId?: string;
154
+ ask: () => Promise<HitlDecision | HitlAskResult>;
155
+ }): Promise<HitlOutcome>;