@octopi-agent/engine 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 (246) 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 +45 -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 +110 -4
  23. package/dist/config-schema/governance.d.ts +45 -1
  24. package/dist/config-schema/governance.js +187 -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 +26 -1
  42. package/dist/harness/agent/builder.js +85 -37
  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 +138 -0
  46. package/dist/harness/agent/config-integrity.js +235 -0
  47. package/dist/harness/agent/wire-agent-builder.js +7 -1
  48. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  49. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  50. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  51. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  52. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  53. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  54. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  55. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  56. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  57. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  58. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  59. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  60. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  61. package/dist/harness/collaboration/delegation/service.js +2 -3
  62. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  63. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  64. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  65. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  66. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  67. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  68. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  69. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  70. package/dist/harness/context/capabilities/compact/index.js +2 -1
  71. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  72. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  73. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  74. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  75. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  76. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  77. package/dist/harness/context/constitution/default-agents.md +11 -10
  78. package/dist/harness/context/default-context-engine.d.ts +34 -4
  79. package/dist/harness/context/default-context-engine.js +194 -49
  80. package/dist/harness/context/hybrid-compressor.js +6 -0
  81. package/dist/harness/context/layers.d.ts +2 -4
  82. package/dist/harness/context/layers.js +9 -11
  83. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  84. package/dist/harness/context/llm-summarizer.js +69 -91
  85. package/dist/harness/context/message-selector.js +4 -3
  86. package/dist/harness/context/summarize.d.ts +3 -1
  87. package/dist/harness/context/summarize.js +9 -4
  88. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  89. package/dist/harness/context/system-prompt-assembler.js +1 -0
  90. package/dist/harness/context/truncate-compressor.js +7 -0
  91. package/dist/harness/context/turn-envelope.d.ts +3 -2
  92. package/dist/harness/context/turn-envelope.js +3 -2
  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 +149 -8
  97. package/dist/harness/extension/execution-environment/effect-policy.js +274 -19
  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/kill-switch.d.ts +34 -0
  101. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  102. package/dist/harness/extension/execution-environment/ops-audit.d.ts +204 -0
  103. package/dist/harness/extension/execution-environment/ops-audit.js +337 -0
  104. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  105. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  106. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  107. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  108. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  109. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  110. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  111. package/dist/harness/extension/execution-environment/sandbox.js +228 -21
  112. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  113. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  114. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  115. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  116. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  117. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  118. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -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 +70 -26
  123. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  124. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  125. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  126. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  127. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  128. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
  129. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  130. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  131. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  132. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  133. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  134. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  135. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  136. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  137. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  138. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  139. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  140. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  141. package/dist/harness/governance/security/default-security-guard.js +9 -0
  142. package/dist/harness/governance/security/index.d.ts +1 -0
  143. package/dist/harness/governance/security/index.js +2 -0
  144. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  145. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  146. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  147. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  148. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  149. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  150. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  151. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  152. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  153. package/dist/harness/governance/security/shell-parser.js +37 -496
  154. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  155. package/dist/harness/governance/security/temp-path.js +13 -2
  156. package/dist/harness/governance/security/vendor/README.md +24 -0
  157. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  158. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  159. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  160. package/dist/harness/index.d.ts +2 -0
  161. package/dist/harness/index.js +2 -0
  162. package/dist/harness/knowledge/fts.js +1 -2
  163. package/dist/harness/knowledge/index-store.js +59 -9
  164. package/dist/harness/memory/index.d.ts +6 -2
  165. package/dist/harness/memory/index.js +4 -1
  166. package/dist/harness/memory/memory-events.d.ts +25 -0
  167. package/dist/harness/memory/memory-events.js +38 -0
  168. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  169. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  170. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  171. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  172. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  173. package/dist/harness/memory/steward-policy.d.ts +3 -0
  174. package/dist/harness/memory/steward-policy.js +1 -1
  175. package/dist/harness/memory/types.d.ts +41 -3
  176. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  177. package/dist/harness/memory/wisdom-attribution.js +287 -0
  178. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  179. package/dist/harness/memory/wisdom-events.js +61 -0
  180. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  181. package/dist/harness/memory/wisdom-formation.js +55 -21
  182. package/dist/harness/memory/wisdom.d.ts +7 -2
  183. package/dist/harness/memory/wisdom.js +40 -2
  184. package/dist/harness/observability/observer/hub.js +8 -0
  185. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  186. package/dist/harness/observability/observer/types.d.ts +4 -0
  187. package/dist/harness/run/agent/agent.d.ts +7 -0
  188. package/dist/harness/run/agent/agent.js +23 -1
  189. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  190. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  191. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  192. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  193. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  194. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  195. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  196. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  197. package/dist/harness/run/reliability/run-agent.js +231 -33
  198. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  199. package/dist/harness/run/run-scope.d.ts +35 -0
  200. package/dist/harness/run/runner.d.ts +141 -2
  201. package/dist/harness/run/runner.js +592 -42
  202. package/dist/harness/session/attachments/llm-intent.js +2 -1
  203. package/dist/harness/session/tasks/render.d.ts +4 -1
  204. package/dist/harness/session/tasks/render.js +10 -7
  205. package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
  206. package/dist/harness/shared/events/agent-event-map.js +5 -0
  207. package/dist/harness/shared/paths/glob.d.ts +52 -0
  208. package/dist/harness/shared/paths/glob.js +218 -0
  209. package/dist/harness/shared/paths/index.d.ts +84 -0
  210. package/dist/harness/shared/paths/index.js +179 -0
  211. package/dist/index.d.ts +3 -3
  212. package/dist/index.js +2 -2
  213. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  214. package/dist/integration/index.d.ts +2 -0
  215. package/dist/integration/index.js +1 -0
  216. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  217. package/dist/integration/observability/loop-watchdog.js +177 -0
  218. package/dist/integration/observability/metrics.d.ts +3 -0
  219. package/dist/integration/observability/metrics.js +18 -7
  220. package/dist/integration/providers/anthropic.d.ts +23 -0
  221. package/dist/integration/providers/anthropic.js +97 -12
  222. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  223. package/dist/integration/providers/fetch-timeout.js +51 -0
  224. package/dist/integration/providers/openai.d.ts +10 -0
  225. package/dist/integration/providers/openai.js +58 -11
  226. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  227. package/dist/integration/providers/provider-diagnostics.js +89 -0
  228. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  229. package/dist/integration/providers/timeout-coherence.js +68 -0
  230. package/dist/integration/providers/wire-dump.d.ts +62 -0
  231. package/dist/integration/providers/wire-dump.js +111 -2
  232. package/dist/integration/storage/jsonl.js +4 -1
  233. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  234. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  235. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  236. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  237. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  238. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  239. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  240. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  241. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  242. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  243. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  244. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  245. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  246. package/package.json +8 -2
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Path containment primitives — shared by tool execution and effect auditing
3
+ *
4
+ * Containment is a cross-cutting mechanism, not a policy owned by one domain:
5
+ * the tools domain decides *what* may be touched (`pathRoots`, `containment`),
6
+ * while the execution-environment domain decides *what gets recorded*. Both
7
+ * need the same answer to "is this path under that root", and both need it in
8
+ * real coordinates — a purely lexical comparison lets a symlink inside a root
9
+ * reach outside it.
10
+ *
11
+ * These helpers live in `shared/` so that no domain has to import another
12
+ * domain's internals to get correct containment. They are foundation code:
13
+ * no policy defaults, no product decisions.
14
+ */
15
+ import { lstatSync, realpathSync } from 'node:fs';
16
+ import { basename, dirname, join, resolve, sep } from 'node:path';
17
+ /**
18
+ * Resolve a path that may not exist yet to its real location.
19
+ *
20
+ * `realpathSync` throws for a missing target, but creating a new file is a
21
+ * normal operation. Walk up to the deepest existing ancestor, resolve that,
22
+ * and re-append the remaining segments. `resolve()` already folded `..`, so the
23
+ * appended tail cannot introduce a new escape.
24
+ *
25
+ * A missing segment that *does* exist as a directory entry is not treated as
26
+ * "about to be created": that is a dangling symlink or a link loop, and letting
27
+ * it through would allow the following open/write to follow it out of the root.
28
+ * `lstatSync` does not follow the final component, which separates the cases.
29
+ *
30
+ * @param abs - absolute, lexically normalized path
31
+ * @returns real path, or null when it cannot be resolved safely
32
+ */
33
+ export function realpathAllowMissing(abs) {
34
+ let current = abs;
35
+ const tail = [];
36
+ for (;;) {
37
+ try {
38
+ const real = realpathSync(current);
39
+ return tail.length ? join(real, ...tail) : real;
40
+ }
41
+ catch (error) {
42
+ const code = error.code;
43
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
44
+ return null;
45
+ if (existsLstat(current))
46
+ return null;
47
+ const parent = dirname(current);
48
+ if (parent === current)
49
+ return null;
50
+ tail.unshift(basename(current));
51
+ current = parent;
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Whether anything exists at this path, without following a final symlink.
57
+ *
58
+ * @param path - absolute path
59
+ * @returns true when an entry exists (including a dangling link)
60
+ */
61
+ function existsLstat(path) {
62
+ try {
63
+ lstatSync(path);
64
+ return true;
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ /**
71
+ * Containment over already-normalized paths (no filesystem access).
72
+ *
73
+ * Use this only when both sides are already real paths; otherwise prefer
74
+ * {@link isPathUnderRoots}, which resolves them first.
75
+ *
76
+ * Windows drive letters are compared case-insensitively, matching how the
77
+ * effect policy treats volume names.
78
+ *
79
+ * @param absPath - path already resolved to its real form
80
+ * @param roots - roots already resolved to their real form
81
+ * @returns whether the path is one of the roots or under one
82
+ */
83
+ export function lexicalUnderRoots(absPath, roots) {
84
+ const win = process.platform === 'win32';
85
+ const norm = (s) => (win ? s.toLowerCase() : s);
86
+ const target = norm(absPath);
87
+ return roots.some((root) => {
88
+ const r = norm(root);
89
+ return target === r || target.startsWith(r.endsWith(sep) ? r : r + sep);
90
+ });
91
+ }
92
+ /**
93
+ * Whether a path falls under any of the given roots, in real coordinates.
94
+ *
95
+ * Both sides are resolved: comparing a resolved target against an unresolved
96
+ * root would wrongly deny legitimate paths whenever the root is itself an alias
97
+ * (macOS `/var` → `/private/var`, a symlinked `$HOME`). A path that cannot be
98
+ * resolved falls back to its lexical form, so this only ever answers "is it
99
+ * inside", never "is it safe to operate on" — callers that need the resolved
100
+ * path must use their own resolution step.
101
+ *
102
+ * @param absPath - path to test
103
+ * @param roots - allowed roots
104
+ * @returns true when the path is one of the roots or under one
105
+ */
106
+ export function isPathUnderRoots(absPath, roots) {
107
+ const lexical = roots.map((root) => resolve(root));
108
+ const target = resolve(absPath);
109
+ const real = (s) => realpathAllowMissing(s) ?? s;
110
+ const realTarget = realpathAllowMissing(target);
111
+ if (realTarget !== null) {
112
+ // Compare in real coordinates: a resolved target against an unresolved root
113
+ // would deny legitimate paths whenever the root is itself an alias.
114
+ return lexicalUnderRoots(realTarget, lexical.map(real));
115
+ }
116
+ // The target exists but cannot be resolved (dangling symlink or link loop).
117
+ // Comparing a lexical target against resolved roots would mix coordinate
118
+ // systems and report an in-root link as outside. Stay lexical on both sides.
119
+ // This answers containment only; callers that act on the path must take
120
+ // realpathAllowMissing's null and refuse, which is what containPath does.
121
+ return lexicalUnderRoots(target, lexical);
122
+ }
123
+ /**
124
+ * Whether the final path component is a symbolic link, without following it.
125
+ *
126
+ * `lstat` inspects the entry itself, so a dangling link still reports `true` —
127
+ * which is what a write guard needs: an unresolvable link is exactly the case
128
+ * where a later open would follow it somewhere unintended.
129
+ *
130
+ * @param path - path to inspect
131
+ * @returns true when the entry exists and is a symlink
132
+ */
133
+ export function isFinalSymlink(path) {
134
+ try {
135
+ return lstatSync(path).isSymbolicLink();
136
+ }
137
+ catch {
138
+ // ENOENT / ENOTDIR: nothing at that name, so nothing to follow.
139
+ return false;
140
+ }
141
+ }
142
+ /**
143
+ * Read a file refusing to traverse a symlink at the final component.
144
+ *
145
+ * Resolving containment already returns a real path, so normally the final
146
+ * component is not a link. If it is one at open time, something replaced it
147
+ * between the containment check and this open; `O_NOFOLLOW` makes the kernel
148
+ * refuse instead of following it (`ELOOP`).
149
+ *
150
+ * @param path - absolute path, normally already resolved
151
+ * @param encoding - text encoding
152
+ * @returns file contents
153
+ */
154
+ export async function readFileNoFollow(path, encoding) {
155
+ const { open, constants } = await import('node:fs/promises');
156
+ // O_NOFOLLOW is POSIX-only. On Windows it is absent, and `0 | undefined` is
157
+ // `0` — which would silently mean "follow the link", the opposite of intent.
158
+ // Fall back to an lstat pre-check there: it keeps refusing dangling links
159
+ // (the common planted case) at the cost of a narrower TOCTOU window.
160
+ if (constants.O_NOFOLLOW === undefined) {
161
+ if (isFinalSymlink(path)) {
162
+ throw new Error(`path_forbidden: "${path}" final component is a symlink (no O_NOFOLLOW on this platform)`);
163
+ }
164
+ const handle = await open(path, 'r');
165
+ try {
166
+ return await handle.readFile({ encoding });
167
+ }
168
+ finally {
169
+ await handle.close();
170
+ }
171
+ }
172
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
173
+ try {
174
+ return await handle.readFile({ encoding });
175
+ }
176
+ finally {
177
+ await handle.close();
178
+ }
179
+ }
package/dist/index.d.ts CHANGED
@@ -26,7 +26,7 @@ export type { ContextEngine, ContextEngineInfo, AssembleParams, AssembleResult,
26
26
  export { setRunTelemetryFactory, getRunTelemetryFactory } from './harness/observability/run-telemetry.js';
27
27
  export type { RunTelemetry, RunTelemetryFactory } from './harness/observability/run-telemetry.js';
28
28
  export { createRunTelemetry } from './integration/observability/run-telemetry.js';
29
- export { AgentBuilder, createAgent, isSubsystemAllowed, discoverSubsystemSpecs } from './harness/agent/builder.js';
29
+ export { AgentBuilder, createAgent, DefaultErrorStrategy, isSubsystemAllowed, discoverSubsystemSpecs } from './harness/agent/builder.js';
30
30
  export type { AgentTraceOptions } from './harness/agent/builder.js';
31
31
  export type { AgentBuildOptions, AgentBuildResult, AgentBuildCoreResult } from './harness/agent/builder.js';
32
32
  export type { ChannelAdapter, ChannelMessage, ChannelReply } from './harness/extension/plugin-ecosystem/channel-types.js';
@@ -40,11 +40,11 @@ export { TurnFileUndoLog, commitSessionFileUndo, discardSessionFileUndo, resolve
40
40
  export { TurnMemoryJournal, JournaledMemoryStore, createMemoryRestorer, discardMemoryUndo, } from './harness/extension/execution-environment/memory-undo.js';
41
41
  export type { MemoryUndoEntry, MemoryEffectRestorer, DiscardMemoryEffectsResult, } from './harness/extension/execution-environment/memory-undo.js';
42
42
  export type { MemoryEffectJournal, MemoryEffectDomain } from '@octopi-agent/core/types/tools.js';
43
- export { resolveEffectiveEffectPolicy, requiresJail, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
43
+ export { resolveEffectiveEffectPolicy, requiresJail, buildOpsJailState, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
44
44
  export { ProcessSandbox, createProcessSandbox, assessL4ProcessMinimum, probeProcessIsolation, scrubEnv, killProcessTree, supervisedSpawnProfile, } from './harness/extension/execution-environment/index.js';
45
45
  export type { ProcessIsolationProfile, IsolationBackend, L4ProcessAssessment, } from './harness/extension/execution-environment/process-isolation.js';
46
46
  export { runWithToolLimits, resolveToolTimeoutMs, ToolTimeoutError, } from './harness/extension/execution-environment/resource-limits.js';
47
- export type { EffectIntent, ConfirmEffect, ConfirmEffectDecision, UntrustedAdmission, ToolSurface, SecurityDegradation, SessionEffectOverrides, } from './harness/extension/execution-environment/effect-policy.js';
47
+ export type { EffectIntent, ConfirmEffect, ConfirmEffectDecision, UntrustedAdmission, JailIntent, OnJailUnavailable, OpsJailState, ToolSurface, SecurityDegradation, SessionEffectOverrides, } from './harness/extension/execution-environment/effect-policy.js';
48
48
  export type { EffectRunMode, EffectPolicyConfig, EffectiveEffectPolicy, PathContainment, ShellEscapePolicy, } from './harness/extension/execution-environment/effect-policy.js';
49
49
  export { scanOrphanSessionUndo, } from './harness/extension/execution-environment/undo-log.js';
50
50
  export type { SessionUndoPaths, FileUndoEntry, DiscardFileEffectsResult, DiscardConflictReason, EditResendResult, NotReversedEffects, NotReversedReason, UndoLimitConfig, OrphanUndoDir, } from './harness/extension/execution-environment/undo-log.js';
package/dist/index.js CHANGED
@@ -21,13 +21,13 @@ import { createRunTelemetry } from './integration/observability/run-telemetry.js
21
21
  setRunTelemetryFactory(createRunTelemetry);
22
22
  export { setRunTelemetryFactory, getRunTelemetryFactory } from './harness/observability/run-telemetry.js';
23
23
  export { createRunTelemetry } from './integration/observability/run-telemetry.js';
24
- export { AgentBuilder, createAgent, isSubsystemAllowed, discoverSubsystemSpecs } from './harness/agent/builder.js';
24
+ export { AgentBuilder, createAgent, DefaultErrorStrategy, isSubsystemAllowed, discoverSubsystemSpecs } from './harness/agent/builder.js';
25
25
  export { Agent } from './harness/run/agent/index.js';
26
26
  export { SessionAwareRunner } from './harness/run/runner.js';
27
27
  export { DEFAULT_TOOL_ISOLATION, resolveToolIsolationCwd, } from './harness/extension/execution-environment/isolation.js';
28
28
  export { TurnFileUndoLog, commitSessionFileUndo, discardSessionFileUndo, resolveSessionUndoPaths, resolveSessionUndoOnClose, createUnconfiguredFileEffects, createUnconfiguredMemoryEffects, } from './harness/extension/execution-environment/undo-log.js';
29
29
  export { TurnMemoryJournal, JournaledMemoryStore, createMemoryRestorer, discardMemoryUndo, } from './harness/extension/execution-environment/memory-undo.js';
30
- export { resolveEffectiveEffectPolicy, requiresJail, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
30
+ export { resolveEffectiveEffectPolicy, requiresJail, buildOpsJailState, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
31
31
  export { ProcessSandbox, createProcessSandbox, assessL4ProcessMinimum, probeProcessIsolation, scrubEnv, killProcessTree, supervisedSpawnProfile, } from './harness/extension/execution-environment/index.js';
32
32
  export { runWithToolLimits, resolveToolTimeoutMs, ToolTimeoutError, } from './harness/extension/execution-environment/resource-limits.js';
33
33
  export { scanOrphanSessionUndo, } from './harness/extension/execution-environment/undo-log.js';
@@ -50,9 +50,27 @@ export async function dispatchChannelMessage(options) {
50
50
  const { runtime, msg, resolveAgentId, resolveSessionId, onEvent } = options;
51
51
  const agentId = resolveAgentId(msg);
52
52
  if (!agentId) {
53
+ // 回执契约 = 恒发一次(liveness);no_agent 的实际结果由上层 error/静默路径处理
54
+ msg.delivery = 'run';
55
+ msg.onDelivery?.('run');
53
56
  return { status: 'skipped', reason: 'no_agent' };
54
57
  }
55
58
  const sessionId = resolveSessionId(msg);
56
59
  const trigger = channelMessageToTrigger(msg, agentId, sessionId);
57
- return runtime.dispatch(trigger, onEvent ? { onEvent } : undefined);
60
+ // 单一入口:dispatch 内部 offer;活跃 Run 接收即回执(早于 Run 结束)。
61
+ // 拒绝/早退路径(runtime_stopped 等)也要回执一次(liveness),错误走 error 通道。
62
+ let delivered = false;
63
+ const result = await runtime.dispatch(trigger, {
64
+ ...(onEvent ? { onEvent } : {}),
65
+ onDelivery: (delivery) => {
66
+ delivered = true;
67
+ msg.delivery = delivery;
68
+ msg.onDelivery?.(delivery);
69
+ },
70
+ });
71
+ if (!delivered) {
72
+ msg.delivery = 'run';
73
+ msg.onDelivery?.('run');
74
+ }
75
+ return result;
58
76
  }
@@ -12,6 +12,8 @@ export type { SessionIndexBackend, SessionIndexSink, SessionIndexPrefilterQuery,
12
12
  export { NoopObserver } from './observability/noop-observer.js';
13
13
  export { LogObserver } from './observability/log-observer.js';
14
14
  export { createRunTelemetry } from './observability/run-telemetry.js';
15
+ export { startLoopWatchdog } from './observability/loop-watchdog.js';
16
+ export type { LoopWatchdog, LoopWatchdogOptions } from './observability/loop-watchdog.js';
15
17
  export { SdkMcpClient, createSdkMcpClient } from './mcp/index.js';
16
18
  export { createDuckDuckGoProvider, createTavilyProvider, createBraveProvider, createSerperProvider, createMimoProvider, createWebSearchProviderFromSlot, resolveWebSearchProviders, createWebSearchWithFallback, } from './web-search/index.js';
17
19
  export type { WebSearchConfig, WebSearchProviderSlotConfig, ResolvedWebSearchProviders, } from './web-search/index.js';
@@ -12,6 +12,7 @@ export { createSqliteSessionIndex, rebuildSessionIndexFromStore, ensureSessionIn
12
12
  export { NoopObserver } from './observability/noop-observer.js';
13
13
  export { LogObserver } from './observability/log-observer.js';
14
14
  export { createRunTelemetry } from './observability/run-telemetry.js';
15
+ export { startLoopWatchdog } from './observability/loop-watchdog.js';
15
16
  // ── MCP ──
16
17
  export { SdkMcpClient, createSdkMcpClient } from './mcp/index.js';
17
18
  // ── Web Search ──
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 事件循环停滞看门狗(宿主自检器官)
3
+ *
4
+ * 背景(2026-10-28 事故):网关事件循环被同步阻塞整体冻结约 4.5 小时——两个 run 的
5
+ * turn 同时停摆、HTTP accept 停止、SIGTERM handler 无法运行,最终被 `serve restart`
6
+ * 的 SIGKILL 升级收尾。事后缺一份阻塞现场的栈采样,确切阻塞点永久失考。
7
+ *
8
+ * 机制:独立 worker 线程(不随主循环冻结)定期 ping 主线程;主线程 message handler
9
+ * 回 pong 以证明事件循环存活。主循环冻结 → pong 静默超阈值 → worker 判定停滞:
10
+ * 写 JSONL 报告 +(macOS)自动 `sample <pid>` 抓主线程栈。检测与取证全部发生在
11
+ * worker 侧,不依赖已被冻结的事件循环。
12
+ *
13
+ * 第二道闸:进程 RSS 越过 `footprintThresholdMb` 即同样落报告 + 采栈。停滞检测
14
+ * 只能证明「已经僵死」,内存失控则可能在冻死前给出一段可干预的窗口——2026-10-30
15
+ * 网关膨胀到 30.5G 的进程在采样完成后几分钟就被系统收走。
16
+ *
17
+ * 设计约束:
18
+ * - 观测 fail-open:看门狗自身的任何失败不得影响宿主(写盘/采样失败静默吞掉)。
19
+ * - worker unref:不阻止进程退出;宿主应显式 `stop()` 收尾。
20
+ * - 复发 runbook:报告文件给出停滞起点(lastPongAt),`.sample-*.txt` 给出阻塞栈;
21
+ * 若自动采样失败,在杀进程前手动执行 `sample <pid> 5 -f /tmp/octopi-hang.txt`。
22
+ *
23
+ * @module integration/observability/loop-watchdog
24
+ */
25
+ /** 看门狗配置 */
26
+ export interface LoopWatchdogOptions {
27
+ /** 显式关闭(缺省开启;关闭态返回 no-op 句柄) */
28
+ enabled?: boolean;
29
+ /** 心跳间隔(毫秒,缺省 5_000) */
30
+ intervalMs?: number;
31
+ /** 主循环静默多久判停滞(毫秒,缺省 30_000) */
32
+ stallThresholdMs?: number;
33
+ /** 报告落盘路径(JSONL,每行一个事件;缺省 `<OCTOPI_HOME>/logs/loop-watchdog.jsonl`) */
34
+ reportFile?: string;
35
+ /** 停滞时自动 `sample` 抓主线程栈(macOS 专属;缺省 true,测试关闭) */
36
+ captureSample?: boolean;
37
+ /**
38
+ * 进程 RSS 阈值(MB,缺省 4096;传 0 关闭)
39
+ *
40
+ * 越过阈值即写 `footprint` 事件并采栈——不必等事件循环冻死。用于在内存
41
+ * 失控的早期抓住现场(滞回:跌回阈值的 80% 以下才复位,避免阈值附近反复采样)。
42
+ */
43
+ footprintThresholdMb?: number;
44
+ }
45
+ /** 看门狗句柄 */
46
+ export interface LoopWatchdog {
47
+ /** 停止看门狗并回收 worker */
48
+ stop(): void;
49
+ }
50
+ /**
51
+ * 启动事件循环停滞看门狗
52
+ *
53
+ * @param options - 心跳间隔 / 停滞阈值 / 报告路径 / 是否自动栈采样
54
+ * @returns 看门狗句柄(`stop()` 回收 worker)
55
+ */
56
+ export declare function startLoopWatchdog(options?: LoopWatchdogOptions): LoopWatchdog;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * 事件循环停滞看门狗(宿主自检器官)
3
+ *
4
+ * 背景(2026-10-28 事故):网关事件循环被同步阻塞整体冻结约 4.5 小时——两个 run 的
5
+ * turn 同时停摆、HTTP accept 停止、SIGTERM handler 无法运行,最终被 `serve restart`
6
+ * 的 SIGKILL 升级收尾。事后缺一份阻塞现场的栈采样,确切阻塞点永久失考。
7
+ *
8
+ * 机制:独立 worker 线程(不随主循环冻结)定期 ping 主线程;主线程 message handler
9
+ * 回 pong 以证明事件循环存活。主循环冻结 → pong 静默超阈值 → worker 判定停滞:
10
+ * 写 JSONL 报告 +(macOS)自动 `sample <pid>` 抓主线程栈。检测与取证全部发生在
11
+ * worker 侧,不依赖已被冻结的事件循环。
12
+ *
13
+ * 第二道闸:进程 RSS 越过 `footprintThresholdMb` 即同样落报告 + 采栈。停滞检测
14
+ * 只能证明「已经僵死」,内存失控则可能在冻死前给出一段可干预的窗口——2026-10-30
15
+ * 网关膨胀到 30.5G 的进程在采样完成后几分钟就被系统收走。
16
+ *
17
+ * 设计约束:
18
+ * - 观测 fail-open:看门狗自身的任何失败不得影响宿主(写盘/采样失败静默吞掉)。
19
+ * - worker unref:不阻止进程退出;宿主应显式 `stop()` 收尾。
20
+ * - 复发 runbook:报告文件给出停滞起点(lastPongAt),`.sample-*.txt` 给出阻塞栈;
21
+ * 若自动采样失败,在杀进程前手动执行 `sample <pid> 5 -f /tmp/octopi-hang.txt`。
22
+ *
23
+ * @module integration/observability/loop-watchdog
24
+ */
25
+ import { Worker } from 'node:worker_threads';
26
+ import { join } from 'node:path';
27
+ import { getOctopiHome } from '../../paths.js';
28
+ /**
29
+ * worker 侧脚本(eval 载入;此处为字符串以规避 dist/源码双态下的模块解析差异)
30
+ *
31
+ * 职责:心跳 ping、停滞判定、报告落盘、栈采样。不得引用 worker_threads 之外的
32
+ * 外部模块形态(eval worker 无 ESM import,只能 require)。
33
+ */
34
+ const WORKER_SRC = `
35
+ const { parentPort, workerData } = require('node:worker_threads');
36
+ const { appendFileSync, mkdirSync } = require('node:fs');
37
+ const { dirname } = require('node:path');
38
+ const { spawnSync } = require('node:child_process');
39
+
40
+ let lastPongAt = Date.now();
41
+ let stalledSince = undefined;
42
+ let footprintLatched = false;
43
+
44
+ const writeReport = (record) => {
45
+ try {
46
+ mkdirSync(dirname(workerData.reportFile), { recursive: true });
47
+ appendFileSync(workerData.reportFile, JSON.stringify(record) + '\\n');
48
+ } catch {
49
+ // 观测 fail-open:报告写盘失败不得影响 worker 自身的监测
50
+ }
51
+ };
52
+
53
+ const captureStack = (tag) => {
54
+ if (!workerData.captureSample || process.platform !== 'darwin') return;
55
+ const sampleFile = workerData.sampleFile.replace('{{ts}}', tag + '-' + Date.now());
56
+ try {
57
+ const r = spawnSync('sample', [String(process.pid), '3', '-f', sampleFile], {
58
+ timeout: 15000,
59
+ stdio: 'ignore',
60
+ });
61
+ // spawnSync 失败不抛(ENOENT 等走返回值):必须按返回值如实留痕,
62
+ // 否则「宣称采样成功」会把运维引向不存在的文件
63
+ if (r.error == null && r.status === 0) {
64
+ console.error('[LoopWatchdog] stack sample written: ' + sampleFile);
65
+ } else {
66
+ console.error('[LoopWatchdog] stack sample FAILED (' + (r.error ? r.error.message : 'exit ' + r.status) + '); run manually: sample ' + process.pid + ' 5 -f /tmp/octopi-hang.txt');
67
+ }
68
+ } catch (err) {
69
+ console.error('[LoopWatchdog] stack sample FAILED: ' + String(err) + '; run manually: sample ' + process.pid + ' 5 -f /tmp/octopi-hang.txt');
70
+ }
71
+ };
72
+
73
+ parentPort.on('message', (msg) => {
74
+ if (msg && msg.type === 'pong') {
75
+ lastPongAt = Date.now();
76
+ if (stalledSince !== undefined) {
77
+ writeReport({
78
+ event: 'recovered',
79
+ detectedAt: new Date().toISOString(),
80
+ stalledForMs: Date.now() - stalledSince,
81
+ });
82
+ console.error('[LoopWatchdog] event loop recovered after ' + (Date.now() - stalledSince) + 'ms stall');
83
+ stalledSince = undefined;
84
+ }
85
+ }
86
+ });
87
+
88
+ setInterval(() => {
89
+ parentPort.postMessage({ type: 'ping' });
90
+ const silentForMs = Date.now() - lastPongAt;
91
+ if (stalledSince === undefined && silentForMs >= workerData.stallThresholdMs) {
92
+ stalledSince = lastPongAt;
93
+ writeReport({
94
+ event: 'stall',
95
+ detectedAt: new Date().toISOString(),
96
+ silentForMs,
97
+ lastPongAt,
98
+ pid: process.pid,
99
+ });
100
+ console.error('[LoopWatchdog] event loop stalled: no heartbeat for ' + silentForMs + 'ms (pid ' + process.pid + ')');
101
+ captureStack('stall');
102
+ }
103
+
104
+ // 内存足迹阈值:在撑爆前留出干预窗口。
105
+ // 2026-10-30 事故里 footprint 涨到 30.5G 时主线程已被原生 h2 扩容循环吃满,
106
+ // 等到心跳消失再采样只是事后取证——进程几分钟后就被系统收走,无从止损。
107
+ // 滞回(跌回 80% 以下才复位)避免在阈值附近反复采样。
108
+ const thresholdMb = workerData.footprintThresholdMb;
109
+ if (thresholdMb > 0) {
110
+ const rssMb = Math.round(process.memoryUsage().rss / 1048576);
111
+ if (!footprintLatched && rssMb >= thresholdMb) {
112
+ footprintLatched = true;
113
+ writeReport({
114
+ event: 'footprint',
115
+ detectedAt: new Date().toISOString(),
116
+ rssMb,
117
+ thresholdMb,
118
+ pid: process.pid,
119
+ });
120
+ console.error('[LoopWatchdog] footprint ' + rssMb + 'MB >= threshold ' + thresholdMb + 'MB (pid ' + process.pid + ')');
121
+ captureStack('footprint');
122
+ } else if (footprintLatched && rssMb < thresholdMb * 0.8) {
123
+ footprintLatched = false;
124
+ writeReport({
125
+ event: 'footprint_recovered',
126
+ detectedAt: new Date().toISOString(),
127
+ rssMb,
128
+ thresholdMb,
129
+ });
130
+ console.error('[LoopWatchdog] footprint back under threshold: ' + rssMb + 'MB');
131
+ }
132
+ }
133
+ }, workerData.intervalMs);
134
+ `;
135
+ /**
136
+ * 启动事件循环停滞看门狗
137
+ *
138
+ * @param options - 心跳间隔 / 停滞阈值 / 报告路径 / 是否自动栈采样
139
+ * @returns 看门狗句柄(`stop()` 回收 worker)
140
+ */
141
+ export function startLoopWatchdog(options = {}) {
142
+ if (options.enabled === false) {
143
+ return { stop: () => { } };
144
+ }
145
+ const reportFile = options.reportFile ?? join(getOctopiHome(), 'logs', 'loop-watchdog.jsonl');
146
+ const worker = new Worker(WORKER_SRC, {
147
+ eval: true,
148
+ workerData: {
149
+ intervalMs: options.intervalMs ?? 5_000,
150
+ stallThresholdMs: options.stallThresholdMs ?? 30_000,
151
+ reportFile,
152
+ captureSample: options.captureSample ?? true,
153
+ sampleFile: `${reportFile}.sample-{{ts}}.txt`,
154
+ footprintThresholdMb: options.footprintThresholdMb ?? 4096,
155
+ },
156
+ });
157
+ // 心跳应答(主循环冻结时此 handler 不再被调度——正是停滞信号)
158
+ worker.on('message', (msg) => {
159
+ if (msg?.type === 'ping') {
160
+ worker.postMessage({ type: 'pong' });
161
+ }
162
+ });
163
+ worker.on('error', (err) => {
164
+ // 观测 fail-open:worker 自身崩溃不得影响宿主;但必须留痕——否则自检能力
165
+ // 整个进程生命周期无声缺席(eval worker 启动失败/平台差异)
166
+ console.warn(`[LoopWatchdog] worker error, stall detection disabled: ${String(err)}`);
167
+ });
168
+ // 不阻止进程退出
169
+ worker.unref();
170
+ return {
171
+ stop: () => {
172
+ worker.terminate().catch(() => {
173
+ // 关停竞态(worker 已退出)无害
174
+ });
175
+ },
176
+ };
177
+ }
@@ -50,6 +50,8 @@ export interface MetricsSnapshot {
50
50
  sessionsActive: number;
51
51
  /** 总 turn 数 */
52
52
  turnsTotal: number;
53
+ /** 以失败告终的 turn 数(turn.end 带 error;含重试中失败尝试,失败不再是指标盲区) */
54
+ failedTurns: number;
53
55
  /** 空回复数 */
54
56
  emptyResponses: number;
55
57
  /** 重试次数 */
@@ -84,6 +86,7 @@ export declare class MetricsAggregator {
84
86
  private _toolErrors;
85
87
  private _sessionsActive;
86
88
  private _turnsTotal;
89
+ private _failedTurns;
87
90
  private _emptyResponses;
88
91
  private _retriesTotal;
89
92
  private _snapshots;
@@ -63,6 +63,7 @@ export class MetricsAggregator {
63
63
  // Session 指标
64
64
  _sessionsActive = new Set();
65
65
  _turnsTotal = 0;
66
+ _failedTurns = 0;
66
67
  _emptyResponses = 0;
67
68
  _retriesTotal = 0;
68
69
  // 快照历史
@@ -123,14 +124,22 @@ export class MetricsAggregator {
123
124
  break;
124
125
  }
125
126
  // ── Turn ──
126
- case 'turn.start':
127
- this._turnsTotal++;
128
- break;
129
- case 'turn.end':
130
- if (!event.data?.content || event.data.content.length === 0) {
131
- this._emptyResponses++;
127
+ // 只计完整结束的 turn:重试中失败尝试的 turn_end(error) 不是用户语义上的轮次,
128
+ // 否则 turnsTotal 会把失败尝试计成 turn、与 llmCalls 倒挂;失败调用的空输出
129
+ // 也不是「空响应」。
130
+ case 'turn.end': {
131
+ const failed = Boolean(event.data?.error);
132
+ if (!failed) {
133
+ this._turnsTotal++;
134
+ if (!event.data?.content || event.data.content.length === 0) {
135
+ this._emptyResponses++;
136
+ }
137
+ }
138
+ else {
139
+ this._failedTurns++;
132
140
  }
133
141
  break;
142
+ }
134
143
  // ── 重试 ──
135
144
  case 'retry':
136
145
  this._retriesTotal++;
@@ -162,6 +171,7 @@ export class MetricsAggregator {
162
171
  toolErrors: Object.fromEntries(this._toolErrors),
163
172
  sessionsActive: this._sessionsActive.size,
164
173
  turnsTotal: this._turnsTotal,
174
+ failedTurns: this._failedTurns,
165
175
  emptyResponses: this._emptyResponses,
166
176
  retriesTotal: this._retriesTotal,
167
177
  estimatedCostUsd: Math.round(estimatedCostUsd * 10000) / 10000,
@@ -188,6 +198,7 @@ export class MetricsAggregator {
188
198
  this._toolErrors.clear();
189
199
  this._sessionsActive.clear();
190
200
  this._turnsTotal = 0;
201
+ this._failedTurns = 0;
191
202
  this._emptyResponses = 0;
192
203
  this._retriesTotal = 0;
193
204
  this._snapshots = [];
@@ -211,7 +222,7 @@ export function formatMetricsSnapshot(snap) {
211
222
  lines.push(`${'─'.repeat(50)}`);
212
223
  lines.push(`Uptime: ${(snap.uptimeMs / 1000).toFixed(0)}s`);
213
224
  lines.push(`Sessions: ${snap.sessionsActive} active`);
214
- lines.push(`Turns: ${snap.turnsTotal}`);
225
+ lines.push(`Turns: ${snap.turnsTotal} (${snap.failedTurns} failed)`);
215
226
  lines.push(`Empty replies: ${snap.emptyResponses}`);
216
227
  lines.push(`Retries: ${snap.retriesTotal}`);
217
228
  lines.push('');
@@ -49,6 +49,10 @@ export declare class AnthropicProvider implements ModelProvider {
49
49
  private baseUrl;
50
50
  private version;
51
51
  private timeoutMs;
52
+ /** 与 timeoutMs 对齐的 fetch dispatcher(transport 不得在配置值之下提前掐断) */
53
+ private dispatcher;
54
+ /** HTTP transport(可注入替换供测试;默认 undici fetch,错误形态与内置 fetch 一致) */
55
+ private fetch;
52
56
  readonly defaultModel: string;
53
57
  constructor(config: AnthropicProviderConfig);
54
58
  /**
@@ -72,6 +76,12 @@ export declare class AnthropicProvider implements ModelProvider {
72
76
  * 检查 provider 是否可用
73
77
  */
74
78
  isAvailable(): Promise<boolean>;
79
+ /**
80
+ * 释放 transport 资源(keep-alive dispatcher 的连接池)
81
+ *
82
+ * 热更替换(gateway.registerProvider)或宿主显式收口时调用;重复调用安全。
83
+ */
84
+ dispose(): Promise<void>;
75
85
  /**
76
86
  * 构造实际发送的请求体(wire dump 观测用)
77
87
  *
@@ -86,6 +96,19 @@ export declare class AnthropicProvider implements ModelProvider {
86
96
  * OpenAI 格式 → Anthropic 格式
87
97
  */
88
98
  private toAnthropicRequest;
99
+ /**
100
+ * 将消息列表转换为 Anthropic 消息列表(含 tool_result 聚合)
101
+ *
102
+ * Anthropic 协议要求:一个 assistant 回合发出的全部 `tool_use`,其 `tool_result`
103
+ * 必须位于**紧随其后的同一条 user 消息**内。引擎里并行工具调用的结果是一条 tool
104
+ * 消息携带多个 `toolResults`,而历史中相邻的 tool 消息也可能出现;逐条转换会产出
105
+ * 多条连续 user 消息,导致前面的 tool_use 无配对结果而被拒(火山等严格端点只回
106
+ * 通用 InvalidParameter,不指出 param)。
107
+ *
108
+ * @param messages - 非 system 消息列表
109
+ * @returns Anthropic 消息列表(连续 tool 消息已聚合为一条 user 消息)
110
+ */
111
+ private toAnthropicMessages;
89
112
  /**
90
113
  * 将 OpenAI 消息格式转换为 Anthropic 消息格式
91
114
  */