@octopi-agent/engine 0.90.11 → 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 (169) 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/context.d.ts +6 -1
  21. package/dist/config-schema/context.js +8 -0
  22. package/dist/config-schema/engine.d.ts +106 -4
  23. package/dist/config-schema/governance.d.ts +43 -1
  24. package/dist/config-schema/governance.js +157 -0
  25. package/dist/config-schema/models.d.ts +5 -2
  26. package/dist/config-schema/models.js +4 -1
  27. package/dist/config-schema/observability.d.ts +9 -0
  28. package/dist/config-schema/observability.js +29 -0
  29. package/dist/config-schema/run.d.ts +3 -0
  30. package/dist/config-schema/run.js +14 -0
  31. package/dist/config.d.ts +29 -4
  32. package/dist/config.js +15 -4
  33. package/dist/harness/activation/dispatcher.d.ts +8 -2
  34. package/dist/harness/activation/dispatcher.js +33 -5
  35. package/dist/harness/activation/inbox.d.ts +87 -0
  36. package/dist/harness/activation/inbox.js +169 -0
  37. package/dist/harness/activation/runtime.d.ts +9 -8
  38. package/dist/harness/activation/runtime.js +100 -8
  39. package/dist/harness/activation/types.d.ts +19 -0
  40. package/dist/harness/activation/types.js +2 -0
  41. package/dist/harness/agent/builder.d.ts +15 -1
  42. package/dist/harness/agent/builder.js +31 -10
  43. package/dist/harness/agent/config-bridge.d.ts +5 -0
  44. package/dist/harness/agent/config-bridge.js +3 -0
  45. package/dist/harness/agent/config-integrity.d.ts +72 -0
  46. package/dist/harness/agent/config-integrity.js +146 -0
  47. package/dist/harness/agent/wire-agent-builder.js +2 -1
  48. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  49. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  50. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  51. package/dist/harness/collaboration/delegation/service.js +2 -3
  52. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  53. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  54. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  55. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  56. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  57. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  58. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  59. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  60. package/dist/harness/context/capabilities/compact/index.js +2 -1
  61. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  62. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  63. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  64. package/dist/harness/context/constitution/default-agents.md +11 -10
  65. package/dist/harness/context/default-context-engine.d.ts +34 -4
  66. package/dist/harness/context/default-context-engine.js +194 -49
  67. package/dist/harness/context/hybrid-compressor.js +6 -0
  68. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  69. package/dist/harness/context/llm-summarizer.js +69 -91
  70. package/dist/harness/context/message-selector.js +4 -3
  71. package/dist/harness/context/summarize.d.ts +2 -0
  72. package/dist/harness/context/summarize.js +7 -2
  73. package/dist/harness/context/truncate-compressor.js +7 -0
  74. package/dist/harness/context/turn-envelope.d.ts +3 -2
  75. package/dist/harness/context/turn-envelope.js +3 -2
  76. package/dist/harness/context/types.d.ts +33 -1
  77. package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
  78. package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
  79. package/dist/harness/extension/execution-environment/effect-policy.d.ts +127 -8
  80. package/dist/harness/extension/execution-environment/effect-policy.js +244 -19
  81. package/dist/harness/extension/execution-environment/index.d.ts +4 -2
  82. package/dist/harness/extension/execution-environment/index.js +2 -1
  83. package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
  84. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  85. package/dist/harness/extension/execution-environment/ops-audit.d.ts +200 -0
  86. package/dist/harness/extension/execution-environment/ops-audit.js +338 -0
  87. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  88. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  89. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  90. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  91. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  92. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  93. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  94. package/dist/harness/extension/execution-environment/sandbox.js +228 -21
  95. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  96. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  97. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  98. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  99. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -0
  100. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
  101. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
  102. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
  103. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +53 -2
  104. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
  105. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  106. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  107. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  108. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  109. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  110. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  111. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  112. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  113. package/dist/harness/governance/security/temp-path.js +13 -2
  114. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  115. package/dist/harness/index.d.ts +2 -0
  116. package/dist/harness/index.js +2 -0
  117. package/dist/harness/knowledge/fts.js +1 -2
  118. package/dist/harness/knowledge/index-store.js +59 -9
  119. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  120. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  121. package/dist/harness/observability/observer/hub.js +8 -0
  122. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  123. package/dist/harness/observability/observer/types.d.ts +4 -0
  124. package/dist/harness/run/agent/agent.d.ts +7 -0
  125. package/dist/harness/run/agent/agent.js +23 -1
  126. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  127. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  128. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  129. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  130. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  131. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  132. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  133. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  134. package/dist/harness/run/reliability/run-agent.js +231 -33
  135. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  136. package/dist/harness/run/run-scope.d.ts +31 -0
  137. package/dist/harness/run/runner.d.ts +116 -2
  138. package/dist/harness/run/runner.js +547 -41
  139. package/dist/harness/session/attachments/llm-intent.js +2 -1
  140. package/dist/harness/session/tasks/render.d.ts +4 -1
  141. package/dist/harness/session/tasks/render.js +10 -7
  142. package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
  143. package/dist/harness/shared/events/agent-event-map.js +5 -0
  144. package/dist/index.d.ts +3 -3
  145. package/dist/index.js +2 -2
  146. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  147. package/dist/integration/index.d.ts +2 -0
  148. package/dist/integration/index.js +1 -0
  149. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  150. package/dist/integration/observability/loop-watchdog.js +177 -0
  151. package/dist/integration/observability/metrics.d.ts +3 -0
  152. package/dist/integration/observability/metrics.js +18 -7
  153. package/dist/integration/providers/anthropic.d.ts +23 -0
  154. package/dist/integration/providers/anthropic.js +97 -12
  155. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  156. package/dist/integration/providers/fetch-timeout.js +51 -0
  157. package/dist/integration/providers/openai.d.ts +10 -0
  158. package/dist/integration/providers/openai.js +58 -11
  159. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  160. package/dist/integration/providers/provider-diagnostics.js +89 -0
  161. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  162. package/dist/integration/providers/timeout-coherence.js +68 -0
  163. package/dist/integration/providers/wire-dump.d.ts +62 -0
  164. package/dist/integration/providers/wire-dump.js +111 -2
  165. package/dist/integration/storage/jsonl.js +4 -1
  166. package/dist/subsystems/cognition-steward/conceptualize/handler.js +1 -1
  167. package/dist/subsystems/memory-steward/backfill/handler.js +1 -1
  168. package/dist/subsystems/wisdom-steward/formation/handler.js +1 -1
  169. package/package.json +3 -2
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 模型调用错误的重试上限(单一事实源)
3
+ *
4
+ * 为什么集中在一处:生产链路由 `AgentBuilder` 注入 `DefaultErrorStrategy`,
5
+ * `runAgentWithReliability` 的兜底分支只在未注入时生效。两处各写一套数字,
6
+ * 很容易出现「改了一处、线上还是旧策略」的漂移。
7
+ *
8
+ * ## 为什么 timeout 保持 3 次(2026-10-27 修正)
9
+ *
10
+ * 曾经把它降到 1 次,理由是「一次 timeout 已耗掉整个 watchdog 窗口,再赌 3 轮就是
11
+ * 52 分钟黑屏」。那是把**症状**当成了**病因**:52 分钟来自「单次尝试耗时过长」
12
+ * 叠加「全程零反馈」,不是来自重试次数。砍次数只是让最坏时长变小,代价是
13
+ * 削弱了上游抖动时的自愈能力——这正是「让系统看起来好了」而不是修好了。
14
+ *
15
+ * 真正的修复在别处:
16
+ * - 单次尝试有界:回退链单节点预算(`fallbackAttemptTtftMs`)使有备选时 90s 即切换
17
+ * - 重试过程可见:`engine.model_retry` 事件 + WebUI 角标,用户知道在第几次、还要等多久
18
+ * - 重试过程可中止:退避等待响应 abort,用户不必等满整个序列
19
+ *
20
+ * 三者俱备后,3 次重试是安全的:用户全程看得到、随时能停。
21
+ *
22
+ * @module harness/run/reliability/model-error-policy
23
+ */
24
+ /** 各错误原因的最大重试次数(不含首次尝试) */
25
+ export const MODEL_ERROR_MAX_ATTEMPTS = {
26
+ rate_limit: 3,
27
+ timeout: 3,
28
+ network: 3,
29
+ server: 2,
30
+ // 内容过滤拒答多为阈值型误杀(同请求重试常过);给 2 次原样重试,
31
+ // 仍被拦则如实收口(不教模型换说法绕过审核)
32
+ content_filter: 2,
33
+ };
34
+ /**
35
+ * 查询某错误原因允许的重试次数
36
+ *
37
+ * @param reason - `classifyError` 给出的错误原因
38
+ * @returns 最大重试次数;不可重试的原因返回 0
39
+ */
40
+ export function maxAttemptsFor(reason) {
41
+ return MODEL_ERROR_MAX_ATTEMPTS[reason] ?? 0;
42
+ }
@@ -11,6 +11,28 @@
11
11
  *
12
12
  * @module
13
13
  */
14
+ /**
15
+ * 判定错误是否属于「取消/中止」而非「节点故障」
16
+ *
17
+ * 两类来源:(1) 调用方主动 abort(用户停止、run 取消);
18
+ * (2) 回退链的单节点预算耗尽 —— 它 abort 的是子 signal,节点本身可能只是慢。
19
+ * 二者都不应累计熔断失败数,否则健康节点会被连续 5 次「慢」直接熔断。
20
+ *
21
+ * @param err - provider 抛出的错误
22
+ * @param signal - 该次请求的 signal
23
+ * @returns 是否为取消类
24
+ */
25
+ function isCancellationLike(err, signal) {
26
+ if (signal?.aborted)
27
+ return true;
28
+ if (typeof err !== 'object' || err === null)
29
+ return false;
30
+ const name = err.name;
31
+ if (name === 'AbortError')
32
+ return true;
33
+ const message = err.message;
34
+ return typeof message === 'string' && /abort/i.test(message);
35
+ }
14
36
  /**
15
37
  * 用熔断器包装 ModelProvider
16
38
  *
@@ -35,7 +57,10 @@ export function wrapProviderWithCircuitBreaker(provider, cb) {
35
57
  return result;
36
58
  }
37
59
  catch (err) {
38
- cb.recordFailure();
60
+ // abort / 预算类错误不计入熔断:节点只是「慢」或「被取消」,
61
+ // 把它当故障会误伤健康节点(连续 5 次即熔断,随后只剩 unknown 错误)。
62
+ if (!isCancellationLike(err, request.signal))
63
+ cb.recordFailure();
39
64
  throw err;
40
65
  }
41
66
  };
@@ -50,7 +75,9 @@ export function wrapProviderWithCircuitBreaker(provider, cb) {
50
75
  cb.recordSuccess();
51
76
  }
52
77
  catch (err) {
53
- cb.recordFailure();
78
+ // 同 chat:取消/预算类错误不是节点故障
79
+ if (!isCancellationLike(err, request.signal))
80
+ cb.recordFailure();
54
81
  throw err;
55
82
  }
56
83
  };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 内容过滤拒答守卫 — ModelProvider 装饰器
3
+ *
4
+ * 把「正文=罐头拒答」的 200 内联返回转成 ContentFilterError(content_filter 模型错误),
5
+ * 复用既有 onError/重试链路:阈值型误杀原样重试常过;重试耗尽走既有诚实收口
6
+ * (stopReason=llm_error + 「模型调用失败…可继续对话重试」),拒答语永远不会落成
7
+ * 助手回答。
8
+ *
9
+ * 流式路径按前缀扣发罐头正文:正常回答仅在「累计正文仍是拒答签名前缀」的短暂窗口内
10
+ * 缓冲,一旦脱离签名前缀立即冲刷透传;reasoning / tool_call 块不经缓冲(有工具调用的
11
+ * 响应不是拒答,遇 tool_call 即转全透传)。
12
+ */
13
+ import type { ModelProvider } from '@octopi-agent/core/interfaces/model-provider.js';
14
+ /**
15
+ * 为 ModelProvider 套上内容过滤拒答守卫。
16
+ *
17
+ * @param model - 被包装的 provider(可与 FallbackProvider 等装饰器叠放)
18
+ * @returns 守卫后的 provider(接口同构,方法逐个显式委托——展开抄不到原型方法)
19
+ */
20
+ export declare function guardRefusalProvider(model: ModelProvider): ModelProvider;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * 内容过滤拒答守卫 — ModelProvider 装饰器
3
+ *
4
+ * 把「正文=罐头拒答」的 200 内联返回转成 ContentFilterError(content_filter 模型错误),
5
+ * 复用既有 onError/重试链路:阈值型误杀原样重试常过;重试耗尽走既有诚实收口
6
+ * (stopReason=llm_error + 「模型调用失败…可继续对话重试」),拒答语永远不会落成
7
+ * 助手回答。
8
+ *
9
+ * 流式路径按前缀扣发罐头正文:正常回答仅在「累计正文仍是拒答签名前缀」的短暂窗口内
10
+ * 缓冲,一旦脱离签名前缀立即冲刷透传;reasoning / tool_call 块不经缓冲(有工具调用的
11
+ * 响应不是拒答,遇 tool_call 即转全透传)。
12
+ */
13
+ import { ContentFilterError, isCannedRefusalText, isCannedRefusalPrefix, } from '@octopi-agent/core/loop/canned-refusal.js';
14
+ /**
15
+ * 响应级拒答判定:正文恰为罐头拒答且无工具调用时抛 ContentFilterError。
16
+ *
17
+ * @param response - 同步调用响应
18
+ * @throws {ContentFilterError} 正文为罐头拒答时
19
+ */
20
+ function assertNotCannedRefusal(response) {
21
+ if (response.toolCalls?.length)
22
+ return; // 有工具调用的响应不是拒答
23
+ if (response.content && isCannedRefusalText(response.content)) {
24
+ throw new ContentFilterError(response.content);
25
+ }
26
+ }
27
+ /**
28
+ * 流式守卫:内容块按前缀扣发,落定为罐头拒答时抛 ContentFilterError。
29
+ *
30
+ * @param model - 被包装的 provider
31
+ * @param request - LLM 请求
32
+ * @returns 受守卫的流(正常内容照常流出,仅拒答前缀窗口内缓冲)
33
+ * @throws {ContentFilterError} 流的最终正文为罐头拒答时
34
+ */
35
+ async function* guardedStream(model, request) {
36
+ let contentBuf = '';
37
+ let sawToolCall = false;
38
+ for await (const chunk of model.stream(request)) {
39
+ if (chunk.type === 'tool_call') {
40
+ sawToolCall = true;
41
+ if (contentBuf) {
42
+ yield { type: 'content', content: contentBuf };
43
+ contentBuf = '';
44
+ }
45
+ yield chunk;
46
+ continue;
47
+ }
48
+ if (chunk.type === 'content' && !sawToolCall) {
49
+ contentBuf += chunk.content ?? '';
50
+ if (isCannedRefusalPrefix(contentBuf))
51
+ continue; // 疑似罐头:继续扣发
52
+ yield { type: 'content', content: contentBuf };
53
+ contentBuf = '';
54
+ continue;
55
+ }
56
+ if (chunk.type === 'done') {
57
+ if (!sawToolCall && contentBuf && isCannedRefusalText(contentBuf)) {
58
+ throw new ContentFilterError(contentBuf);
59
+ }
60
+ if (contentBuf) {
61
+ yield { type: 'content', content: contentBuf };
62
+ contentBuf = '';
63
+ }
64
+ yield chunk;
65
+ continue;
66
+ }
67
+ yield chunk;
68
+ }
69
+ // 流异常结束(无 done):非罐头的残留正文不丢输出
70
+ if (contentBuf && !isCannedRefusalText(contentBuf)) {
71
+ yield { type: 'content', content: contentBuf };
72
+ }
73
+ }
74
+ /**
75
+ * 为 ModelProvider 套上内容过滤拒答守卫。
76
+ *
77
+ * @param model - 被包装的 provider(可与 FallbackProvider 等装饰器叠放)
78
+ * @returns 守卫后的 provider(接口同构,方法逐个显式委托——展开抄不到原型方法)
79
+ */
80
+ export function guardRefusalProvider(model) {
81
+ return {
82
+ name: model.name,
83
+ defaultModel: model.defaultModel,
84
+ ...(model.models ? { models: model.models } : {}),
85
+ getModelInfo: (modelName) => model.getModelInfo(modelName),
86
+ getModelInfos: () => model.getModelInfos(),
87
+ isAvailable: () => model.isAvailable(),
88
+ ...(model.dispose
89
+ ? {
90
+ dispose: () => {
91
+ model.dispose?.();
92
+ },
93
+ }
94
+ : {}),
95
+ chat: async (request) => {
96
+ const response = await model.chat(request);
97
+ assertNotCannedRefusal(response);
98
+ return response;
99
+ },
100
+ stream: (request) => guardedStream(model, request),
101
+ };
102
+ }
@@ -18,6 +18,8 @@
18
18
  import { getTextContent } from '@octopi-agent/core/types.js';
19
19
  import { classifyError } from '@octopi-agent/core/loop/error-classifier.js';
20
20
  import { agentLoop } from '@octopi-agent/core/loop/agent-loop.js';
21
+ import { maxAttemptsFor } from './model-error-policy.js';
22
+ import { guardRefusalProvider } from './refusal-guard.js';
21
23
  import { recordToolCall, detectNoProgressLoop, } from '../concurrency/tool-loop-detection.js';
22
24
  import { severityToAction } from '@octopi-agent/core/security-guard.js';
23
25
  import { RunMetricsCollector } from './run-metrics-collector.js';
@@ -62,6 +64,78 @@ function estimateCost(snapshot, pricing) {
62
64
  const outputCost = (snapshot.outputTokens / 1_000_000) * defaultPricing.outputPer1M;
63
65
  return inputCost + cachedCost + outputCost;
64
66
  }
67
+ /**
68
+ * 入队一条「模型调用即将重试」通知
69
+ *
70
+ * onError 不是 generator,无法直接 yield;与 SecurityGuard 同策略入队,
71
+ * 由主循环在下一个事件边界推出。
72
+ *
73
+ * @param state - Run 状态(承载待推队列)
74
+ * @param error - 分类后的错误
75
+ * @param attempt - 本次尝试序号(从 0 起)
76
+ * @param delayMs - 重试前等待时长
77
+ */
78
+ /**
79
+ * 入队一条「模型调用即将重试」通知,并登记待执行的退避等待
80
+ *
81
+ * onError 不是 generator,无法直接 yield;与 SecurityGuard 同策略入队,
82
+ * 由主循环在下一个事件边界推出。
83
+ *
84
+ * **等待不在这里执行**(2026-10-27 评审修正):若在此 `await sleep(delayMs)`,
85
+ * generator 会卡在 onError 内,外层 for-await 没有任何事件可排空,
86
+ * 通知要等睡眠结束才送达——`rate_limit` 带 `Retry-After` 时用户在整个等待期仍是零反馈。
87
+ * 因此把退避时长登记到 state,由排空处在 `yield` 之后再 sleep。
88
+ *
89
+ * @param state - reliability 运行态
90
+ * @param error - 已分类错误
91
+ * @param attempt - 本次尝试序号(从 0 起)
92
+ * @param delayMs - 重试前需等待的时长
93
+ * @param maxAttempts - 该原因的允许重试次数(由调用方给出,避免表外原因显示 0)
94
+ */
95
+ function pushRetryNotice(state, error, attempt, delayMs, maxAttempts) {
96
+ state.pendingModelRetryEvents.push({
97
+ type: 'model_retry',
98
+ timestamp: Date.now(),
99
+ data: {
100
+ attempt: attempt + 1,
101
+ maxAttempts,
102
+ reason: error.reason,
103
+ delayMs,
104
+ error: (error.message || '').slice(0, 500),
105
+ },
106
+ });
107
+ // 多条通知合并成一次等待:取最大退避,避免退避时长被叠加放大
108
+ state.pendingRetryDelayMs = Math.max(state.pendingRetryDelayMs, delayMs);
109
+ }
110
+ /**
111
+ * 可被 abort 打断的等待
112
+ *
113
+ * `rate_limit` 的 `Retry-After` 可达数十秒;若用裸 `setTimeout`,
114
+ * 用户按下停止后仍要等满整个退避窗口才能生效。
115
+ *
116
+ * @param ms - 等待时长
117
+ * @param signal - 运行中止信号(可选)
118
+ * @returns 到时或被中止时 resolve(不 reject:中止由循环自身处理)
119
+ */
120
+ async function sleepUnlessAborted(ms, signal) {
121
+ if (ms <= 0)
122
+ return;
123
+ if (!signal) {
124
+ await new Promise((resolve) => setTimeout(resolve, ms));
125
+ return;
126
+ }
127
+ if (signal.aborted)
128
+ return;
129
+ await new Promise((resolve) => {
130
+ const done = () => {
131
+ clearTimeout(timer);
132
+ signal.removeEventListener('abort', done);
133
+ resolve();
134
+ };
135
+ const timer = setTimeout(done, ms);
136
+ signal.addEventListener('abort', done, { once: true });
137
+ });
138
+ }
65
139
  function createInitialState(checkpointInterval = 15) {
66
140
  return {
67
141
  planningOnlyAttempts: 0,
@@ -83,6 +157,8 @@ function createInitialState(checkpointInterval = 15) {
83
157
  modelErrorAttempt: 0,
84
158
  pendingBudgetHardYield: false,
85
159
  pendingSecurityEvents: [],
160
+ pendingRetryDelayMs: 0,
161
+ pendingModelRetryEvents: [],
86
162
  wrapUp: false,
87
163
  advisoryTriggered: new Set(),
88
164
  };
@@ -183,6 +259,9 @@ export async function* runAgentWithReliability(context, config, harness, signal)
183
259
  const originalBeforeToolCall = config.beforeToolCall;
184
260
  const wrappedConfig = {
185
261
  ...config,
262
+ // 内容过滤拒答守卫:把「200 内联罐头拒答」转成 content_filter 模型错误,
263
+ // 复用 onError/重试链路(阈值型误杀原样重试常过;耗尽走诚实收口)
264
+ model: guardRefusalProvider(config.model),
186
265
  // getFollowUpMessages:返回 reliability 层注入的 steer 消息
187
266
  getFollowUpMessages: async () => {
188
267
  const msgs = [...pendingFollowUps];
@@ -195,6 +274,38 @@ export async function* runAgentWithReliability(context, config, harness, signal)
195
274
  },
196
275
  // beforeToolCall:Budget hard 闸 + wrap-up 控制 + SecurityGuard 检查 + 原始回调
197
276
  beforeToolCall: async (ctx, signal) => {
277
+ // ops P5 kill switch:宿主侧急停,先于一切执行(不依赖 LLM/agent 合作,agent 无法解除)
278
+ {
279
+ const scope = getRunScope();
280
+ const killPaths = scope?.toolRuntime?.killSwitchPaths;
281
+ if (killPaths && killPaths.length > 0) {
282
+ const { checkKillSwitch } = await import('../../extension/execution-environment/kill-switch.js');
283
+ const killState = checkKillSwitch(killPaths);
284
+ if (killState.engaged) {
285
+ const reason = `kill_switch_active: agent execution is halted by the host sentinel (${killState.path})`;
286
+ state.pendingSecurityEvents.push({
287
+ type: 'security_blocked',
288
+ timestamp: Date.now(),
289
+ data: {
290
+ sessionId: scope?.sessionId,
291
+ agentId: scope?.agentId,
292
+ reason,
293
+ toolName: ctx.toolCall.name,
294
+ action: 'reject',
295
+ severity: 'high',
296
+ violations: [
297
+ {
298
+ type: 'unauthorized_tool',
299
+ severity: 'high',
300
+ description: reason,
301
+ },
302
+ ],
303
+ },
304
+ });
305
+ return { block: true, reason, terminate: true };
306
+ }
307
+ }
308
+ }
198
309
  // Budget hard:阻止本批工具继续执行(turn_end 在工具之前 yield)
199
310
  if (budget && !state.budgetStop) {
200
311
  const hard = budget.checkHardOnly();
@@ -274,6 +385,27 @@ export async function* runAgentWithReliability(context, config, harness, signal)
274
385
  sessionRights,
275
386
  ])) {
276
387
  const reason = `tool_rights_denied: "${ctx.toolCall.name}" is not permitted for this session participant`;
388
+ // ops P5/§8.6:提权请求者缺权 → **确认闸门之前**拒绝并留痕(not_authorized,
389
+ // 无弹窗)。工具 handler 根本不会执行——确认 ≠ 请求者可信。
390
+ if (ctx.toolCall.name === 'priv_exec') {
391
+ scope?.toolRuntime?.recordOpsEvent?.({
392
+ event: 'ops.escalation.denied',
393
+ data: {
394
+ argv: [
395
+ String(ctx.toolCall.arguments?.cmd ?? ''),
396
+ ...(ctx.toolCall.arguments?.args ?? []),
397
+ ],
398
+ why: 'not_authorized',
399
+ toolName: ctx.toolCall.name,
400
+ origin: {
401
+ sessionId: scope?.sessionId,
402
+ agentId: scope?.agentId,
403
+ runId: scope?.runId ?? null,
404
+ participants: scope?.toolRuntime?.sessionParticipants ?? [],
405
+ },
406
+ },
407
+ });
408
+ }
277
409
  state.pendingSecurityEvents.push({
278
410
  type: 'security_blocked',
279
411
  timestamp: Date.now(),
@@ -353,24 +485,10 @@ export async function* runAgentWithReliability(context, config, harness, signal)
353
485
  afterToolCall: async (ctx, signal) => {
354
486
  // SecurityGuard 检查工具输出(字符串直扫;结构化结果序列化后扫,防 MCP/对象结果绕过)
355
487
  if (harness.security && ctx.result.content != null) {
356
- const raw = ctx.result.content;
357
- const scanText = typeof raw === 'string'
358
- ? raw
359
- : (() => {
360
- try {
361
- return JSON.stringify(raw);
362
- }
363
- catch {
364
- return String(raw);
365
- }
366
- })();
367
488
  // 超大 payload 截断扫描,避免序列化字符串拖垮 checkToolOutput
368
- const outputCheck = harness.security.checkToolOutput(scanText.length > 100_000 ? scanText.slice(0, 100_000) : scanText);
489
+ const outputCheck = harness.security.checkToolOutput(truncateForOutputScan(toolOutputScanText(ctx.result.content)));
369
490
  if (!outputCheck.isClean) {
370
- const action = severityToAction(outputCheck.violations.reduce((worst, v) => {
371
- const order = { critical: 4, high: 3, medium: 2, low: 1 };
372
- return order[v.severity] > order[worst.severity] ? v : worst;
373
- }, outputCheck.violations[0]).severity);
491
+ const action = severityToAction(worstOutputViolation(outputCheck.violations).severity);
374
492
  // 输出侧无「事前确认」语义:confirm/high 一律拦截该输出
375
493
  if (action === 'block' || action === 'reject' || action === 'confirm') {
376
494
  const reason = outputCheck.violations
@@ -392,6 +510,28 @@ export async function* runAgentWithReliability(context, config, harness, signal)
392
510
  }
393
511
  return undefined;
394
512
  },
513
+ // onToolUpdate:部分输出经 SecurityGuard 出口扫描后转发(展示通道)。
514
+ // 与 afterToolCall 同一判定口径(共享助手)——否则恶意工具可借部分输出绕过出口扫描;
515
+ // 违规部分扣发,最终结果仍走 afterToolCall 裁决。
516
+ onToolUpdate: config.onToolUpdate
517
+ ? (params) => {
518
+ const partial = params.partial;
519
+ if (harness.security && partial.content != null) {
520
+ const outputCheck = harness.security.checkToolOutput(truncateForOutputScan(toolOutputScanText(partial.content)));
521
+ if (!outputCheck.isClean)
522
+ return;
523
+ }
524
+ config.onToolUpdate({
525
+ toolCall: params.toolCall,
526
+ partial: {
527
+ ...partial,
528
+ content: typeof partial.content === 'string'
529
+ ? capPartialTail(partial.content)
530
+ : partial.content,
531
+ },
532
+ });
533
+ }
534
+ : undefined,
395
535
  // onTurnComplete:可靠性副作用(注入 steer 指令,不控制停止)
396
536
  onTurnComplete: async (ctx) => {
397
537
  // 一轮成功走到这里:重置模型错误 attempt
@@ -658,27 +798,23 @@ export async function* runAgentWithReliability(context, config, harness, signal)
658
798
  if (harness.errorStrategy) {
659
799
  const action = harness.errorStrategy.onModelError(classified, attempt);
660
800
  if (action.action === 'retry') {
661
- if (action.delayMs > 0) {
662
- await new Promise(resolve => setTimeout(resolve, action.delayMs));
663
- }
801
+ const delayMs = action.delayMs ?? 0;
802
+ // maxAttempts 取「本次实际允许的重试次数」;自定义 strategy 对表外原因也重试时,
803
+ // 至少报 1(而不是 0),避免 UI 显示「第 1 次 / 共 0 次」
804
+ pushRetryNotice(state, classified, attempt, delayMs, Math.max(1, maxAttemptsFor(classified.reason)));
664
805
  return 'retry';
665
806
  }
666
807
  return 'abort';
667
808
  }
668
- // 默认:重试 rate_limit / timeout / network / server(最多 3 次,避免无界重试)
669
- // network 含对端断连(undici terminated / socket hang up),重试常可自愈
670
- if (classified.reason === 'rate_limit' ||
671
- classified.reason === 'timeout' ||
672
- classified.reason === 'network' ||
673
- classified.reason === 'server') {
674
- if (attempt < 3) {
675
- const delayMs = classified.retryAfterMs ?? (attempt + 1) * 1000;
676
- if (delayMs > 0) {
677
- await new Promise(resolve => setTimeout(resolve, delayMs));
678
- }
679
- return 'retry';
680
- }
681
- return 'abort';
809
+ // 默认:按错误原因分级重试(次数上限见 MODEL_ERROR_MAX_ATTEMPTS)
810
+ // network 含对端断连(undici terminated / socket hang up),重试常可自愈;
811
+ // timeout 只给 1 次——一次失败已经耗掉整个 watchdog 窗口(流 300s + 同步兜底 300s),
812
+ // 原样再来 3 轮正是 2026-10-27 那次 52 分钟黑屏的成因。
813
+ const maxAttempts = maxAttemptsFor(classified.reason);
814
+ if (attempt < maxAttempts) {
815
+ const delayMs = classified.retryAfterMs ?? (attempt + 1) * 1000;
816
+ pushRetryNotice(state, classified, attempt, delayMs, maxAttempts);
817
+ return 'retry';
682
818
  }
683
819
  return 'abort';
684
820
  },
@@ -690,6 +826,18 @@ export async function* runAgentWithReliability(context, config, harness, signal)
690
826
  const sec = state.pendingSecurityEvents.shift();
691
827
  yield sec;
692
828
  }
829
+ // 模型重试通知(onError 入队,此处推出:重试窗口必须对用户可见)
830
+ while (state.pendingModelRetryEvents.length > 0) {
831
+ const retry = state.pendingModelRetryEvents.shift();
832
+ yield retry;
833
+ }
834
+ // 退避等待放在通知 yield 之后:消费方已看到「即将重试 + 等多久」,
835
+ // 而 agentLoop 此刻挂在 turn_end 之后未继续,下一次调用不会提前发起。
836
+ if (state.pendingRetryDelayMs > 0) {
837
+ const waitMs = state.pendingRetryDelayMs;
838
+ state.pendingRetryDelayMs = 0;
839
+ await sleepUnlessAborted(waitMs, signal);
840
+ }
693
841
  // Observer:run 结束前附带 RunMetricsCollector 快照(P1 Guard 面板)
694
842
  if (event.type === 'agent_end') {
695
843
  const scope = getRunScope();
@@ -1026,3 +1174,53 @@ function executeRecoveryActions(actions, messages) {
1026
1174
  }
1027
1175
  }
1028
1176
  }
1177
+ /**
1178
+ * 工具输出扫描文本:字符串直扫;结构化结果序列化后扫(防 MCP/对象结果绕过)。
1179
+ *
1180
+ * @param content - 工具输出内容
1181
+ * @returns 扫描文本
1182
+ */
1183
+ function toolOutputScanText(content) {
1184
+ if (typeof content === 'string')
1185
+ return content;
1186
+ try {
1187
+ return JSON.stringify(content);
1188
+ }
1189
+ catch {
1190
+ return String(content);
1191
+ }
1192
+ }
1193
+ /**
1194
+ * 超大 payload 截断扫描,避免序列化字符串拖垮 checkToolOutput。
1195
+ *
1196
+ * @param text - 扫描文本
1197
+ * @returns 截断后的扫描文本(前 100k)
1198
+ */
1199
+ function truncateForOutputScan(text) {
1200
+ return text.length > 100_000 ? text.slice(0, 100_000) : text;
1201
+ }
1202
+ /**
1203
+ * 最重违规(afterToolCall 与部分输出扣发共用同一裁决口径)。
1204
+ *
1205
+ * @param violations - 违规列表(非空;调用方已判 isClean=false)
1206
+ * @returns 最重违规
1207
+ */
1208
+ function worstOutputViolation(violations) {
1209
+ const order = {
1210
+ critical: 4,
1211
+ high: 3,
1212
+ medium: 2,
1213
+ low: 1,
1214
+ };
1215
+ return violations.reduce((worst, v) => (order[v.severity] > order[worst.severity] ? v : worst), violations[0]);
1216
+ }
1217
+ /**
1218
+ * 部分输出载荷截断(保留尾部 4KB:流式输出的最新片段才有展示价值)。
1219
+ *
1220
+ * @param text - 部分输出文本
1221
+ * @param maxChars - 上限(缺省 4096)
1222
+ * @returns 尾部截断结果
1223
+ */
1224
+ function capPartialTail(text, maxChars = 4096) {
1225
+ return text.length > maxChars ? text.slice(text.length - maxChars) : text;
1226
+ }
@@ -366,10 +366,10 @@ ${summaryText}${taskLine}${recoveryLine}${signalsLine}
366
366
 
367
367
  只回复一个词(OK/CONCERN/STOP),如果需要可以加冒号说明原因。`;
368
368
  try {
369
+ // 不指定温度:由模型配置(ModelInfo.temperature)或服务端默认决定
369
370
  const response = await this.model.chat({
370
371
  messages: [{ role: 'user', content: prompt }],
371
372
  model: this.config.llmModel || undefined,
372
- temperature: 0,
373
373
  });
374
374
  const text = response.content.trim().toUpperCase();
375
375
  if (text.startsWith('STOP')) {
@@ -36,14 +36,45 @@ export interface RunToolRuntime {
36
36
  requireCredentialBindings?: boolean;
37
37
  /** D7 require jail */
38
38
  requireJail?: boolean;
39
+ /** 授权无笼(effectPolicy.jail=none):跳过 jail 包裹,注记 disabled_by_config */
40
+ disableJail?: boolean;
39
41
  /** jail $HOME write (project/host) */
40
42
  homeWrite?: boolean;
41
43
  /** Run-level securityDegraded hook */
42
44
  noteSecurityDegraded?: (reason: string) => void;
45
+ /** ops 审计回传(ops P2):动作/越权写入 → 统一审计账本 */
46
+ recordOpsEvent?: (record: {
47
+ event: string;
48
+ data: Record<string, unknown>;
49
+ }) => void;
43
50
  /** L2 级别 */
44
51
  pathContainment?: "strict" | "soft" | "none";
45
52
  confirmEffect?: import("@octopi-agent/core/types/tools.js").ToolExecutionContext["confirmEffect"];
46
53
  effectChannel?: "engine" | "host-gate";
54
+ /** 提权策略(ops P3/P4,resolved):priv_exec 匹配面(allowlist 全等 / full 全量) */
55
+ escalation?: {
56
+ policy: "none" | "allowlist" | "full";
57
+ via: "sudo" | "direct";
58
+ allow: Array<{
59
+ cmd: string;
60
+ args?: string[];
61
+ confirm?: boolean;
62
+ }>;
63
+ };
64
+ /** 危险命令减速带 resolved(§6):full 档 pre-exec 闸 + 确认超时(超时一律 deny) */
65
+ dangerousCommands?: {
66
+ policy: "confirm" | "deny" | "off";
67
+ timeoutMs: number;
68
+ };
69
+ /** 会话参与者身份(SEC-2 / ops P5):提权审计 requester 入账 */
70
+ sessionParticipants?: Array<{
71
+ agentId: string;
72
+ roleId: string;
73
+ }>;
74
+ /** kill switch 哨兵路径(ops P5):beforeToolCall 逐工具闸的检查面 */
75
+ killSwitchPaths?: string[];
76
+ /** 特权部署标记(§5 P4/§8.1):jail=none / full 档 / root 进程——UI 常驻 `PRIVILEGED` 数据源 */
77
+ privileged?: boolean;
47
78
  /** L1 processLimits(false = 不强制 timeoutMs 看门狗) */
48
79
  processLimits?: boolean;
49
80
  /** shell 工具策略(gateEffect;deny=拒绝 shell) */