@ai-agent-forge/agent-forge 0.87.0 → 0.88.1

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 (451) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +2 -2
  3. package/bundled-plugins/agent-loop-policy/agent-forge.json +19 -0
  4. package/bundled-plugins/agent-loop-policy/dist/entry.d.ts +28 -0
  5. package/bundled-plugins/agent-loop-policy/dist/entry.d.ts.map +1 -0
  6. package/bundled-plugins/agent-loop-policy/dist/entry.js +69 -0
  7. package/bundled-plugins/agent-loop-policy/dist/entry.js.map +1 -0
  8. package/bundled-plugins/agent-loop-policy/dist/loop-guard.d.ts +199 -0
  9. package/bundled-plugins/agent-loop-policy/dist/loop-guard.d.ts.map +1 -0
  10. package/bundled-plugins/agent-loop-policy/dist/loop-guard.js +208 -0
  11. package/bundled-plugins/agent-loop-policy/dist/loop-guard.js.map +1 -0
  12. package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.d.ts +17 -0
  13. package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.d.ts.map +1 -0
  14. package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.js +18 -0
  15. package/bundled-plugins/agent-loop-policy/dist/run-loop-strategy.js.map +1 -0
  16. package/bundled-plugins/agent-loop-policy/plugin.json +7 -0
  17. package/bundled-plugins/coding-tools/agent-forge.json +19 -0
  18. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/bash.d.ts +5 -44
  19. package/bundled-plugins/coding-tools/dist/bash.d.ts.map +1 -0
  20. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/bash.js +15 -119
  21. package/bundled-plugins/coding-tools/dist/bash.js.map +1 -0
  22. package/bundled-plugins/coding-tools/dist/capability.d.ts +25 -0
  23. package/bundled-plugins/coding-tools/dist/capability.d.ts.map +1 -0
  24. package/bundled-plugins/coding-tools/dist/capability.js +98 -0
  25. package/bundled-plugins/coding-tools/dist/capability.js.map +1 -0
  26. package/bundled-plugins/coding-tools/dist/config.d.ts +8 -0
  27. package/bundled-plugins/coding-tools/dist/config.d.ts.map +1 -0
  28. package/bundled-plugins/coding-tools/dist/config.js +8 -0
  29. package/bundled-plugins/coding-tools/dist/config.js.map +1 -0
  30. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/edit.d.ts +3 -3
  31. package/bundled-plugins/coding-tools/dist/edit.d.ts.map +1 -0
  32. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/edit.js +12 -10
  33. package/bundled-plugins/coding-tools/dist/edit.js.map +1 -0
  34. package/bundled-plugins/coding-tools/dist/entry.d.ts +14 -0
  35. package/bundled-plugins/coding-tools/dist/entry.d.ts.map +1 -0
  36. package/bundled-plugins/coding-tools/dist/entry.js +23 -0
  37. package/bundled-plugins/coding-tools/dist/entry.js.map +1 -0
  38. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/find.d.ts +4 -4
  39. package/bundled-plugins/coding-tools/dist/find.d.ts.map +1 -0
  40. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/find.js +10 -8
  41. package/bundled-plugins/coding-tools/dist/find.js.map +1 -0
  42. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/grep.d.ts +3 -3
  43. package/bundled-plugins/coding-tools/dist/grep.d.ts.map +1 -0
  44. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/grep.js +10 -8
  45. package/bundled-plugins/coding-tools/dist/grep.js.map +1 -0
  46. package/bundled-plugins/coding-tools/dist/index.d.ts +17 -0
  47. package/bundled-plugins/coding-tools/dist/index.d.ts.map +1 -0
  48. package/bundled-plugins/coding-tools/dist/index.js +17 -0
  49. package/bundled-plugins/coding-tools/dist/index.js.map +1 -0
  50. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/ls.d.ts +3 -3
  51. package/bundled-plugins/coding-tools/dist/ls.d.ts.map +1 -0
  52. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/ls.js +8 -6
  53. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/ls.js.map +1 -1
  54. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/powershell.d.ts +2 -1
  55. package/bundled-plugins/coding-tools/dist/powershell.d.ts.map +1 -0
  56. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/powershell.js +6 -3
  57. package/bundled-plugins/coding-tools/dist/powershell.js.map +1 -0
  58. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/read.d.ts +3 -3
  59. package/bundled-plugins/coding-tools/dist/read.d.ts.map +1 -0
  60. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/read.js +15 -13
  61. package/bundled-plugins/coding-tools/dist/read.js.map +1 -0
  62. package/bundled-plugins/coding-tools/dist/types.d.ts +74 -0
  63. package/bundled-plugins/coding-tools/dist/types.d.ts.map +1 -0
  64. package/bundled-plugins/coding-tools/dist/types.js +28 -0
  65. package/bundled-plugins/coding-tools/dist/types.js.map +1 -0
  66. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/write.d.ts +2 -2
  67. package/bundled-plugins/coding-tools/dist/write.d.ts.map +1 -0
  68. package/{dist/core/tools → bundled-plugins/coding-tools/dist}/write.js +11 -9
  69. package/bundled-plugins/coding-tools/dist/write.js.map +1 -0
  70. package/bundled-plugins/coding-tools/plugin.json +10 -0
  71. package/bundled-plugins/compaction-policy/agent-forge.json +19 -0
  72. package/bundled-plugins/compaction-policy/dist/branch-summary-policy.d.ts +6 -0
  73. package/bundled-plugins/compaction-policy/dist/branch-summary-policy.d.ts.map +1 -0
  74. package/bundled-plugins/compaction-policy/dist/branch-summary-policy.js +19 -0
  75. package/bundled-plugins/compaction-policy/dist/branch-summary-policy.js.map +1 -0
  76. package/bundled-plugins/compaction-policy/dist/compaction-policy.d.ts +6 -0
  77. package/bundled-plugins/compaction-policy/dist/compaction-policy.d.ts.map +1 -0
  78. package/bundled-plugins/compaction-policy/dist/compaction-policy.js +38 -0
  79. package/bundled-plugins/compaction-policy/dist/compaction-policy.js.map +1 -0
  80. package/bundled-plugins/compaction-policy/dist/entry.d.ts +13 -0
  81. package/bundled-plugins/compaction-policy/dist/entry.d.ts.map +1 -0
  82. package/bundled-plugins/compaction-policy/dist/entry.js +23 -0
  83. package/bundled-plugins/compaction-policy/dist/entry.js.map +1 -0
  84. package/bundled-plugins/compaction-policy/plugin.json +10 -0
  85. package/bundled-plugins/mcp-http/dist/index.d.ts +8 -0
  86. package/bundled-plugins/mcp-http/dist/index.d.ts.map +1 -0
  87. package/bundled-plugins/mcp-http/dist/index.js +8 -0
  88. package/bundled-plugins/mcp-http/dist/index.js.map +1 -0
  89. package/bundled-plugins/mcp-http/dist/mcp-http.d.ts.map +1 -0
  90. package/{dist/plugins → bundled-plugins/mcp-http/dist}/mcp-http.js +1 -1
  91. package/bundled-plugins/mcp-http/dist/mcp-http.js.map +1 -0
  92. package/bundled-plugins/overflow-policy/agent-forge.json +19 -0
  93. package/bundled-plugins/overflow-policy/dist/entry.d.ts +16 -0
  94. package/bundled-plugins/overflow-policy/dist/entry.d.ts.map +1 -0
  95. package/bundled-plugins/overflow-policy/dist/entry.js +35 -0
  96. package/bundled-plugins/overflow-policy/dist/entry.js.map +1 -0
  97. package/bundled-plugins/overflow-policy/plugin.json +10 -0
  98. package/bundled-plugins/provider-failover/agent-forge.json +19 -0
  99. package/bundled-plugins/provider-failover/dist/entry.d.ts +8 -0
  100. package/bundled-plugins/provider-failover/dist/entry.d.ts.map +1 -0
  101. package/bundled-plugins/provider-failover/dist/entry.js +8 -0
  102. package/bundled-plugins/provider-failover/dist/entry.js.map +1 -0
  103. package/bundled-plugins/provider-failover/dist/provider-failover.d.ts +122 -0
  104. package/bundled-plugins/provider-failover/dist/provider-failover.d.ts.map +1 -0
  105. package/{dist/core/extensions → bundled-plugins/provider-failover/dist}/provider-failover.js +149 -61
  106. package/bundled-plugins/provider-failover/dist/provider-failover.js.map +1 -0
  107. package/bundled-plugins/provider-failover/plugin.json +7 -0
  108. package/bundled-plugins/retry-policy/agent-forge.json +19 -0
  109. package/bundled-plugins/retry-policy/dist/entry.d.ts +16 -0
  110. package/bundled-plugins/retry-policy/dist/entry.d.ts.map +1 -0
  111. package/bundled-plugins/retry-policy/dist/entry.js +34 -0
  112. package/bundled-plugins/retry-policy/dist/entry.js.map +1 -0
  113. package/bundled-plugins/retry-policy/plugin.json +10 -0
  114. package/dist/bundle/.build-manifest.json +105 -183
  115. package/dist/bundle/chunks/{anthropic-messages-ALDZBUKI.js → anthropic-messages-PLAKXR73.js} +1 -1
  116. package/dist/bundle/chunks/{azure-openai-responses-A2WJWZFB.js → azure-openai-responses-OUWQ2AZD.js} +1 -1
  117. package/dist/bundle/chunks/{chunk-CIX3FSBK.js → chunk-A3JYRWB6.js} +1 -1
  118. package/dist/bundle/chunks/{chunk-SQFG22WN.js → chunk-AC2FIS4G.js} +1 -1
  119. package/dist/bundle/chunks/chunk-AQLNTW2B.js +664 -0
  120. package/dist/bundle/chunks/chunk-D3ARGZFR.js +13 -0
  121. package/dist/bundle/chunks/{chunk-YJCQVXW5.js → chunk-HTEVUY7F.js} +1 -1
  122. package/dist/bundle/chunks/{chunk-Y7HXTASS.js → chunk-HV64ASMT.js} +1 -1
  123. package/dist/bundle/chunks/chunk-LZOEQITZ.js +855 -0
  124. package/dist/bundle/chunks/{chunk-7ZY7IXZD.js → chunk-TRDNDS6A.js} +1 -1
  125. package/dist/bundle/chunks/chunk-Z72JWUZ4.js +4 -0
  126. package/dist/bundle/chunks/{google-generative-ai-NIB4WONV.js → google-generative-ai-DLII6DAT.js} +1 -1
  127. package/dist/bundle/chunks/{google-vertex-DCPYUEUO.js → google-vertex-G7BZL7GM.js} +1 -1
  128. package/dist/bundle/chunks/image-resize-worker.js +3 -3
  129. package/dist/bundle/chunks/{mistral-conversations-OC6LA5XL.js → mistral-conversations-JXUK24ID.js} +1 -1
  130. package/dist/bundle/chunks/{openai-codex-responses-IO2X4Y7L.js → openai-codex-responses-5GSGFIPG.js} +1 -1
  131. package/dist/bundle/chunks/{openai-completions-XYQQHETU.js → openai-completions-EI2I6DTG.js} +1 -1
  132. package/dist/bundle/chunks/{openai-responses-DLIRN3CI.js → openai-responses-AUJQ3NWT.js} +1 -1
  133. package/dist/bundle/chunks/{pi-messages-E6RRYBO7.js → pi-messages-PWU2VJMR.js} +1 -1
  134. package/dist/bundle/chunks/virtual-modules-WF6WRHP7.js +5 -0
  135. package/dist/bundle/cli.js +1 -1
  136. package/dist/bundle/client.js +1 -1
  137. package/dist/bundle/index.js +3 -3
  138. package/dist/bundle/rpc-entry.js +1 -1
  139. package/dist/capabilities/builtin.d.ts +1 -1
  140. package/dist/capabilities/builtin.d.ts.map +1 -1
  141. package/dist/capabilities/builtin.js +5 -0
  142. package/dist/capabilities/builtin.js.map +1 -1
  143. package/dist/cli/auth-check.d.ts.map +1 -1
  144. package/dist/cli/auth-check.js +14 -2
  145. package/dist/cli/auth-check.js.map +1 -1
  146. package/dist/cli/auth-command.d.ts.map +1 -1
  147. package/dist/cli/auth-command.js +1 -1
  148. package/dist/cli/auth-command.js.map +1 -1
  149. package/dist/cli/plugin-command.d.ts.map +1 -1
  150. package/dist/cli/plugin-command.js +17 -1
  151. package/dist/cli/plugin-command.js.map +1 -1
  152. package/dist/config.d.ts +2 -3
  153. package/dist/config.d.ts.map +1 -1
  154. package/dist/config.js +5 -6
  155. package/dist/config.js.map +1 -1
  156. package/dist/core/agent-session-bash.d.ts +1 -1
  157. package/dist/core/agent-session-bash.d.ts.map +1 -1
  158. package/dist/core/agent-session-bash.js +1 -1
  159. package/dist/core/agent-session-bash.js.map +1 -1
  160. package/dist/core/agent-session-compaction.d.ts +6 -10
  161. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  162. package/dist/core/agent-session-compaction.js +21 -112
  163. package/dist/core/agent-session-compaction.js.map +1 -1
  164. package/dist/core/agent-session-internal.d.ts +1 -7
  165. package/dist/core/agent-session-internal.d.ts.map +1 -1
  166. package/dist/core/agent-session-internal.js.map +1 -1
  167. package/dist/core/agent-session-loop.d.ts +4 -3
  168. package/dist/core/agent-session-loop.d.ts.map +1 -1
  169. package/dist/core/agent-session-loop.js +9 -6
  170. package/dist/core/agent-session-loop.js.map +1 -1
  171. package/dist/core/agent-session-retry.d.ts +1 -1
  172. package/dist/core/agent-session-retry.d.ts.map +1 -1
  173. package/dist/core/agent-session-retry.js +32 -4
  174. package/dist/core/agent-session-retry.js.map +1 -1
  175. package/dist/core/agent-session-services.d.ts.map +1 -1
  176. package/dist/core/agent-session-services.js +30 -9
  177. package/dist/core/agent-session-services.js.map +1 -1
  178. package/dist/core/agent-session-tools.d.ts.map +1 -1
  179. package/dist/core/agent-session-tools.js +5 -1
  180. package/dist/core/agent-session-tools.js.map +1 -1
  181. package/dist/core/agent-session.d.ts +12 -33
  182. package/dist/core/agent-session.d.ts.map +1 -1
  183. package/dist/core/agent-session.js +61 -67
  184. package/dist/core/agent-session.js.map +1 -1
  185. package/dist/core/bash-executor.d.ts +1 -1
  186. package/dist/core/bash-executor.d.ts.map +1 -1
  187. package/dist/core/bash-executor.js.map +1 -1
  188. package/dist/core/extensions/bootstrap-agent-loop.d.ts +23 -151
  189. package/dist/core/extensions/bootstrap-agent-loop.d.ts.map +1 -1
  190. package/dist/core/extensions/bootstrap-agent-loop.js +28 -290
  191. package/dist/core/extensions/bootstrap-agent-loop.js.map +1 -1
  192. package/dist/core/extensions/capability-runtime-types.d.ts +5 -3
  193. package/dist/core/extensions/capability-runtime-types.d.ts.map +1 -1
  194. package/dist/core/extensions/capability-runtime-types.js.map +1 -1
  195. package/dist/core/extensions/capability-runtime.d.ts.map +1 -1
  196. package/dist/core/extensions/capability-runtime.js +42 -6
  197. package/dist/core/extensions/capability-runtime.js.map +1 -1
  198. package/dist/core/extensions/index.d.ts +12 -5
  199. package/dist/core/extensions/index.d.ts.map +1 -1
  200. package/dist/core/extensions/index.js +12 -5
  201. package/dist/core/extensions/index.js.map +1 -1
  202. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  203. package/dist/core/extensions/virtual-modules.js +65 -0
  204. package/dist/core/extensions/virtual-modules.js.map +1 -1
  205. package/dist/core/facade/coding-agent-facade.d.ts +1 -7
  206. package/dist/core/facade/coding-agent-facade.d.ts.map +1 -1
  207. package/dist/core/facade/coding-agent-facade.js +0 -3
  208. package/dist/core/facade/coding-agent-facade.js.map +1 -1
  209. package/dist/core/i18n/locales/zh-cn/cli.d.ts.map +1 -1
  210. package/dist/core/i18n/locales/zh-cn/cli.js +3 -1
  211. package/dist/core/i18n/locales/zh-cn/cli.js.map +1 -1
  212. package/dist/core/i18n/locales/zh-cn/core-contract-core.d.ts +1 -1
  213. package/dist/core/i18n/locales/zh-cn/core-contract-core.d.ts.map +1 -1
  214. package/dist/core/i18n/locales/zh-cn/core-contract-core.js +1 -1
  215. package/dist/core/i18n/locales/zh-cn/core-contract-core.js.map +1 -1
  216. package/dist/core/i18n/locales/zh-cn/core-contract-extensions.d.ts.map +1 -1
  217. package/dist/core/i18n/locales/zh-cn/core-contract-extensions.js +2 -4
  218. package/dist/core/i18n/locales/zh-cn/core-contract-extensions.js.map +1 -1
  219. package/dist/core/i18n/locales/zh-cn/core-errors.d.ts.map +1 -1
  220. package/dist/core/i18n/locales/zh-cn/core-errors.js +3 -1
  221. package/dist/core/i18n/locales/zh-cn/core-errors.js.map +1 -1
  222. package/dist/core/i18n/locales/zh-cn/interactive-mode.d.ts.map +1 -1
  223. package/dist/core/i18n/locales/zh-cn/interactive-mode.js +2 -0
  224. package/dist/core/i18n/locales/zh-cn/interactive-mode.js.map +1 -1
  225. package/dist/core/i18n/locales/zh-cn/tui-components-selectors.d.ts.map +1 -1
  226. package/dist/core/i18n/locales/zh-cn/tui-components-selectors.js +0 -2
  227. package/dist/core/i18n/locales/zh-cn/tui-components-selectors.js.map +1 -1
  228. package/dist/core/model-config.d.ts +0 -1
  229. package/dist/core/model-config.d.ts.map +1 -1
  230. package/dist/core/model-config.js +9 -1
  231. package/dist/core/model-config.js.map +1 -1
  232. package/dist/core/model-runtime.d.ts.map +1 -1
  233. package/dist/core/model-runtime.js +3 -3
  234. package/dist/core/model-runtime.js.map +1 -1
  235. package/dist/core/provider-composer.d.ts +2 -2
  236. package/dist/core/provider-composer.d.ts.map +1 -1
  237. package/dist/core/provider-composer.js +7 -8
  238. package/dist/core/provider-composer.js.map +1 -1
  239. package/dist/core/sdk.d.ts +18 -3
  240. package/dist/core/sdk.d.ts.map +1 -1
  241. package/dist/core/sdk.js +267 -76
  242. package/dist/core/sdk.js.map +1 -1
  243. package/dist/core/settings-manager.d.ts +9 -20
  244. package/dist/core/settings-manager.d.ts.map +1 -1
  245. package/dist/core/settings-manager.js +20 -54
  246. package/dist/core/settings-manager.js.map +1 -1
  247. package/dist/core/tools/bash-operations.d.ts +41 -0
  248. package/dist/core/tools/bash-operations.d.ts.map +1 -0
  249. package/dist/core/tools/bash-operations.js +113 -0
  250. package/dist/core/tools/bash-operations.js.map +1 -0
  251. package/dist/core/tools/index.d.ts +12 -36
  252. package/dist/core/tools/index.d.ts.map +1 -1
  253. package/dist/core/tools/index.js +1 -117
  254. package/dist/core/tools/index.js.map +1 -1
  255. package/dist/core/tools/readme-path.d.ts +3 -0
  256. package/dist/core/tools/readme-path.d.ts.map +1 -0
  257. package/dist/core/tools/readme-path.js +15 -0
  258. package/dist/core/tools/readme-path.js.map +1 -0
  259. package/dist/index.d.ts +3 -19
  260. package/dist/index.d.ts.map +1 -1
  261. package/dist/index.js +6 -39
  262. package/dist/index.js.map +1 -1
  263. package/dist/main.d.ts.map +1 -1
  264. package/dist/main.js +3 -2
  265. package/dist/main.js.map +1 -1
  266. package/dist/modes/interactive/components/footer.d.ts +0 -2
  267. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  268. package/dist/modes/interactive/components/footer.js +2 -7
  269. package/dist/modes/interactive/components/footer.js.map +1 -1
  270. package/dist/modes/interactive/components/settings-selector.d.ts +2 -6
  271. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/settings-selector.js +6 -28
  273. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  274. package/dist/modes/interactive/components/tool-execution.d.ts +0 -1
  275. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  276. package/dist/modes/interactive/components/tool-execution.js +9 -25
  277. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  278. package/dist/modes/interactive/interactive-mode.d.ts +0 -1
  279. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  280. package/dist/modes/interactive/interactive-mode.js +23 -36
  281. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  282. package/dist/modes/rpc/rpc-client.d.ts +0 -8
  283. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  284. package/dist/modes/rpc/rpc-client.js +0 -12
  285. package/dist/modes/rpc/rpc-client.js.map +1 -1
  286. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  287. package/dist/modes/rpc/rpc-mode.js +0 -9
  288. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  289. package/dist/modes/rpc/rpc-types.d.ts +0 -19
  290. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  291. package/dist/modes/rpc/rpc-types.js.map +1 -1
  292. package/dist/plugins/ecosystem/cli.d.ts.map +1 -1
  293. package/dist/plugins/ecosystem/cli.js +14 -2
  294. package/dist/plugins/ecosystem/cli.js.map +1 -1
  295. package/dist/plugins/ecosystem/node-npm-registry-source.d.ts +7 -2
  296. package/dist/plugins/ecosystem/node-npm-registry-source.d.ts.map +1 -1
  297. package/dist/plugins/ecosystem/node-npm-registry-source.js +64 -9
  298. package/dist/plugins/ecosystem/node-npm-registry-source.js.map +1 -1
  299. package/dist/plugins/ecosystem/node-plugin-acquisition-host.d.ts.map +1 -1
  300. package/dist/plugins/ecosystem/node-plugin-acquisition-host.js +6 -0
  301. package/dist/plugins/ecosystem/node-plugin-acquisition-host.js.map +1 -1
  302. package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts +9 -2
  303. package/dist/plugins/ecosystem/node-plugin-bootstrap.d.ts.map +1 -1
  304. package/dist/plugins/ecosystem/node-plugin-bootstrap.js +23 -0
  305. package/dist/plugins/ecosystem/node-plugin-bootstrap.js.map +1 -1
  306. package/dist/plugins/ecosystem/plugin-bootstrap.d.ts +9 -1
  307. package/dist/plugins/ecosystem/plugin-bootstrap.d.ts.map +1 -1
  308. package/dist/plugins/ecosystem/plugin-bootstrap.js +5 -0
  309. package/dist/plugins/ecosystem/plugin-bootstrap.js.map +1 -1
  310. package/dist/profiles/builtin-suites.d.ts +5 -1
  311. package/dist/profiles/builtin-suites.d.ts.map +1 -1
  312. package/dist/profiles/builtin-suites.js +6 -1
  313. package/dist/profiles/builtin-suites.js.map +1 -1
  314. package/dist/utils/photon.d.ts +2 -2
  315. package/dist/utils/photon.d.ts.map +1 -1
  316. package/dist/utils/photon.js +2 -2
  317. package/dist/utils/photon.js.map +1 -1
  318. package/docs/compaction.md +1 -3
  319. package/docs/docs.json +4 -0
  320. package/docs/index.md +1 -0
  321. package/docs/mcp.md +103 -0
  322. package/docs/models.md +14 -22
  323. package/docs/providers.md +0 -1
  324. package/docs/rpc.md +1 -26
  325. package/docs/sdk.md +4 -6
  326. package/docs/settings.md +9 -12
  327. package/docs/skills.md +1 -9
  328. package/docs/usage.md +1 -1
  329. package/examples/extensions/bash-spawn-hook/index.ts +7 -2
  330. package/examples/extensions/built-in-tool-renderer/index.ts +4 -2
  331. package/examples/extensions/minimal-mode/index.ts +2 -2
  332. package/examples/extensions/truncated-tool/index.ts +1 -1
  333. package/examples/extensions/with-deps/package-lock.json +2 -2
  334. package/examples/extensions/with-deps/package.json +1 -1
  335. package/examples/extensions/with-deps/plugin.json +1 -1
  336. package/examples/sdk/10-settings.ts +2 -4
  337. package/examples/sdk/12-full-control.ts +1 -2
  338. package/package.json +3 -4
  339. package/dist/bundle/chunks/chunk-6ZKDNZHA.js +0 -145
  340. package/dist/bundle/chunks/chunk-BFC2BDVJ.js +0 -13
  341. package/dist/bundle/chunks/chunk-MOHOLL3F.js +0 -1456
  342. package/dist/bundle/chunks/virtual-modules-KZ5DRH7Q.js +0 -2
  343. package/dist/core/extensions/bootstrap-branch-summary-policy.d.ts +0 -7
  344. package/dist/core/extensions/bootstrap-branch-summary-policy.d.ts.map +0 -1
  345. package/dist/core/extensions/bootstrap-branch-summary-policy.js +0 -28
  346. package/dist/core/extensions/bootstrap-branch-summary-policy.js.map +0 -1
  347. package/dist/core/extensions/bootstrap-compaction-policy.d.ts +0 -7
  348. package/dist/core/extensions/bootstrap-compaction-policy.d.ts.map +0 -1
  349. package/dist/core/extensions/bootstrap-compaction-policy.js +0 -82
  350. package/dist/core/extensions/bootstrap-compaction-policy.js.map +0 -1
  351. package/dist/core/extensions/bootstrap-overflow-policy.d.ts +0 -7
  352. package/dist/core/extensions/bootstrap-overflow-policy.d.ts.map +0 -1
  353. package/dist/core/extensions/bootstrap-overflow-policy.js +0 -30
  354. package/dist/core/extensions/bootstrap-overflow-policy.js.map +0 -1
  355. package/dist/core/extensions/bootstrap-retry-policy.d.ts +0 -7
  356. package/dist/core/extensions/bootstrap-retry-policy.d.ts.map +0 -1
  357. package/dist/core/extensions/bootstrap-retry-policy.js +0 -29
  358. package/dist/core/extensions/bootstrap-retry-policy.js.map +0 -1
  359. package/dist/core/extensions/bootstrap-tools.d.ts +0 -20
  360. package/dist/core/extensions/bootstrap-tools.d.ts.map +0 -1
  361. package/dist/core/extensions/bootstrap-tools.js +0 -36
  362. package/dist/core/extensions/bootstrap-tools.js.map +0 -1
  363. package/dist/core/extensions/microcompact.d.ts +0 -80
  364. package/dist/core/extensions/microcompact.d.ts.map +0 -1
  365. package/dist/core/extensions/microcompact.js +0 -134
  366. package/dist/core/extensions/microcompact.js.map +0 -1
  367. package/dist/core/extensions/provider-failover.d.ts +0 -106
  368. package/dist/core/extensions/provider-failover.d.ts.map +0 -1
  369. package/dist/core/extensions/provider-failover.js.map +0 -1
  370. package/dist/core/tools/bash.d.ts.map +0 -1
  371. package/dist/core/tools/bash.js.map +0 -1
  372. package/dist/core/tools/edit.d.ts.map +0 -1
  373. package/dist/core/tools/edit.js.map +0 -1
  374. package/dist/core/tools/find.d.ts.map +0 -1
  375. package/dist/core/tools/find.js.map +0 -1
  376. package/dist/core/tools/grep.d.ts.map +0 -1
  377. package/dist/core/tools/grep.js.map +0 -1
  378. package/dist/core/tools/ls.d.ts.map +0 -1
  379. package/dist/core/tools/powershell.d.ts.map +0 -1
  380. package/dist/core/tools/powershell.js.map +0 -1
  381. package/dist/core/tools/read.d.ts.map +0 -1
  382. package/dist/core/tools/read.js.map +0 -1
  383. package/dist/core/tools/write.d.ts.map +0 -1
  384. package/dist/core/tools/write.js.map +0 -1
  385. package/dist/plugins/mcp-http.d.ts.map +0 -1
  386. package/dist/plugins/mcp-http.js.map +0 -1
  387. package/dist/profile/child-facade.d.ts +0 -44
  388. package/dist/profile/child-facade.d.ts.map +0 -1
  389. package/dist/profile/child-facade.js +0 -56
  390. package/dist/profile/child-facade.js.map +0 -1
  391. package/dist/profile/dependency-wiring.d.ts +0 -48
  392. package/dist/profile/dependency-wiring.d.ts.map +0 -1
  393. package/dist/profile/dependency-wiring.js +0 -56
  394. package/dist/profile/dependency-wiring.js.map +0 -1
  395. package/dist/profile/domain-recovery.d.ts +0 -60
  396. package/dist/profile/domain-recovery.d.ts.map +0 -1
  397. package/dist/profile/domain-recovery.js +0 -94
  398. package/dist/profile/domain-recovery.js.map +0 -1
  399. package/dist/profile/first-roles.d.ts +0 -30
  400. package/dist/profile/first-roles.d.ts.map +0 -1
  401. package/dist/profile/first-roles.js +0 -83
  402. package/dist/profile/first-roles.js.map +0 -1
  403. package/dist/profile/goal-plugin.d.ts +0 -38
  404. package/dist/profile/goal-plugin.d.ts.map +0 -1
  405. package/dist/profile/goal-plugin.js +0 -132
  406. package/dist/profile/goal-plugin.js.map +0 -1
  407. package/dist/profile/plan-plugin.d.ts +0 -44
  408. package/dist/profile/plan-plugin.d.ts.map +0 -1
  409. package/dist/profile/plan-plugin.js +0 -157
  410. package/dist/profile/plan-plugin.js.map +0 -1
  411. package/dist/profile/policy-manifest.d.ts +0 -53
  412. package/dist/profile/policy-manifest.d.ts.map +0 -1
  413. package/dist/profile/policy-manifest.js +0 -53
  414. package/dist/profile/policy-manifest.js.map +0 -1
  415. package/dist/profile/role-assembly.d.ts +0 -47
  416. package/dist/profile/role-assembly.d.ts.map +0 -1
  417. package/dist/profile/role-assembly.js +0 -31
  418. package/dist/profile/role-assembly.js.map +0 -1
  419. package/dist/profile/role-catalog.d.ts +0 -43
  420. package/dist/profile/role-catalog.d.ts.map +0 -1
  421. package/dist/profile/role-catalog.js +0 -132
  422. package/dist/profile/role-catalog.js.map +0 -1
  423. package/dist/profile/role-orchestrator.d.ts +0 -123
  424. package/dist/profile/role-orchestrator.d.ts.map +0 -1
  425. package/dist/profile/role-orchestrator.js +0 -195
  426. package/dist/profile/role-orchestrator.js.map +0 -1
  427. package/dist/profile/role-runner.d.ts +0 -99
  428. package/dist/profile/role-runner.d.ts.map +0 -1
  429. package/dist/profile/role-runner.js +0 -79
  430. package/dist/profile/role-runner.js.map +0 -1
  431. package/dist/profile/root-facade.d.ts +0 -36
  432. package/dist/profile/root-facade.d.ts.map +0 -1
  433. package/dist/profile/root-facade.js +0 -49
  434. package/dist/profile/root-facade.js.map +0 -1
  435. package/dist/profile/skill-discovery-wiring.d.ts +0 -58
  436. package/dist/profile/skill-discovery-wiring.d.ts.map +0 -1
  437. package/dist/profile/skill-discovery-wiring.js +0 -80
  438. package/dist/profile/skill-discovery-wiring.js.map +0 -1
  439. package/dist/profile/state-store.d.ts +0 -62
  440. package/dist/profile/state-store.d.ts.map +0 -1
  441. package/dist/profile/state-store.js +0 -144
  442. package/dist/profile/state-store.js.map +0 -1
  443. package/dist/profile/todo-plugin.d.ts +0 -37
  444. package/dist/profile/todo-plugin.d.ts.map +0 -1
  445. package/dist/profile/todo-plugin.js +0 -137
  446. package/dist/profile/todo-plugin.js.map +0 -1
  447. package/dist/server/create-harness.d.ts +0 -26
  448. package/dist/server/create-harness.d.ts.map +0 -1
  449. package/dist/server/create-harness.js +0 -106
  450. package/dist/server/create-harness.js.map +0 -1
  451. /package/{dist/plugins → bundled-plugins/mcp-http/dist}/mcp-http.d.ts +0 -0
@@ -1,134 +0,0 @@
1
- /**
2
- * Microcompact (P1 context hygiene): before spending an LLM summarization
3
- * call, elide the BULKY OLD tool results from the LLM context — a pure local
4
- * history transform with zero model cost (the codex/ZCode "microcompact"
5
- * layer). The session file keeps every byte (append-only marker + logical
6
- * transform at context build); only the model-visible context shrinks.
7
- *
8
- * Contract: the marker is a `custom` session entry (`MICROCOMPACT_CUSTOM_TYPE`)
9
- * whose data names the elision point. The projection registered by the
10
- * bootstrap compaction policy plugin (via the PUBLIC
11
- * `api.registerEntryProjection` channel) replaces eligible tool-result
12
- * contents older than that point with a fixed placeholder, so reload and
13
- * token estimation stay consistent with live turns. The kernel applies
14
- * registered projections verbatim and knows nothing about microcompact.
15
- */
16
- import { contentText } from "@agent-forge/ai";
17
- import { estimateTokens } from "../compaction/index.js";
18
- /** Custom entry type carrying the microcompact elision point. */
19
- export const MICROCOMPACT_CUSTOM_TYPE = "microcompact.v1";
20
- /** Replacement content for an elided tool result. */
21
- export const MICROCOMPACT_ELIDED_PLACEHOLDER = "[earlier tool result elided by microcompact]";
22
- /** Tool results shorter than this are not worth eliding (noise, not bulk). */
23
- export const DEFAULT_MIN_ELIDE_CHARS = 200;
24
- /**
25
- * Minimum estimated token relief for a microcompact to fire: below this the
26
- * churn (marker entry + context transition) cannot pay for itself and the
27
- * caller falls through to full LLM compaction.
28
- */
29
- export const MIN_MICROCOMPACT_FREED_TOKENS = 2048;
30
- function isElidableToolResult(message, minChars) {
31
- if (message.role !== "toolResult")
32
- return false;
33
- // 媒体保护:含非 text part(image 等)的 tool result 不 elide——占位符替换会
34
- // 把模型可见上下文中的原图数据抹掉(会话文件虽保真,但投影按 marker 重放,
35
- // 图像不会自行回来),保持"原图常驻直到全量压缩"的现行裁决。
36
- if (Array.isArray(message.content) && message.content.some((part) => part.type !== "text")) {
37
- return false;
38
- }
39
- return contentText(message.content, "").length >= minChars;
40
- }
41
- /**
42
- * Plan one microcompact over the branch path: protect the most recent
43
- * `keepRecentTokens` (estimated) as the verbatim tail, and elide the eligible
44
- * old tool results before that cut. Returns undefined when the caller disabled
45
- * the mechanism (`options.enabled === false`), when there is nothing to elide,
46
- * or when the relief cannot reach the minimum. Deliberately does NOT reuse
47
- * `CompactionSettings`: its `enabled` is the compaction master switch — a
48
- * different gate.
49
- */
50
- export function planMicrocompact(pathEntries, options) {
51
- if (!options.enabled)
52
- return undefined;
53
- const minChars = options.minElideChars ?? DEFAULT_MIN_ELIDE_CHARS;
54
- // Protect the recent tail: walk backwards accumulating estimated tokens,
55
- // cutting before the entry that crosses the budget (same walk as
56
- // findCutPoint, but without turn-boundary subtleties — elision never
57
- // removes entries, only replaces contents, so any cut point is safe).
58
- let accumulated = 0;
59
- let cutIndex = 0;
60
- for (let i = pathEntries.length - 1; i >= 0; i--) {
61
- const entry = pathEntries[i];
62
- const messageTokens = entry.message ? estimateTokens(entry.message) : 0;
63
- if (messageTokens === 0)
64
- continue;
65
- accumulated += messageTokens;
66
- if (accumulated >= options.keepRecentTokens) {
67
- cutIndex = i;
68
- break;
69
- }
70
- }
71
- let freedTokens = 0;
72
- let elidedCount = 0;
73
- for (let i = 0; i < cutIndex; i++) {
74
- const message = pathEntries[i].message;
75
- if (!message || !isElidableToolResult(message, minChars))
76
- continue;
77
- freedTokens +=
78
- estimateTokens(message) -
79
- estimateTokens({ ...message, content: [{ type: "text", text: MICROCOMPACT_ELIDED_PLACEHOLDER }] });
80
- elidedCount += 1;
81
- }
82
- const elideBefore = pathEntries[cutIndex];
83
- if (elidedCount === 0 || freedTokens < MIN_MICROCOMPACT_FREED_TOKENS)
84
- return undefined;
85
- const elideBeforeEntryId = elideBefore?.id;
86
- if (!elideBeforeEntryId)
87
- return undefined;
88
- return { elideBeforeEntryId, freedTokens, elidedCount };
89
- }
90
- /** Resolve the marker data of the LAST microcompact marker in path order. */
91
- export function lastMicrocompactMarker(pathEntries) {
92
- let marker;
93
- for (const entry of pathEntries) {
94
- if (entry.type !== "custom" || entry.customType !== MICROCOMPACT_CUSTOM_TYPE)
95
- continue;
96
- const data = entry.data;
97
- if (typeof data?.elideBeforeEntryId === "string") {
98
- marker = {
99
- elideBeforeEntryId: data.elideBeforeEntryId,
100
- minChars: typeof data.minChars === "number" && data.minChars >= 0 ? data.minChars : DEFAULT_MIN_ELIDE_CHARS,
101
- };
102
- }
103
- }
104
- return marker;
105
- }
106
- /**
107
- * The entry projection backing microcompact: replaces the CONTENT of eligible
108
- * tool results before the marker's cut point with the fixed placeholder, and
109
- * keeps everything else verbatim. Registered through the public
110
- * `api.registerEntryProjection` channel — the same channel any third-party
111
- * context policy uses; the kernel applies it without interpretation.
112
- */
113
- export function applyMicrocompactElision(path) {
114
- const marker = lastMicrocompactMarker(path);
115
- if (marker === undefined)
116
- return path;
117
- const cutIndex = path.findIndex((entry) => entry.id === marker.elideBeforeEntryId);
118
- if (cutIndex <= 0)
119
- return path;
120
- return path.map((entry, index) => {
121
- if (index >= cutIndex || entry.type !== "message")
122
- return entry;
123
- const message = entry.message;
124
- // 与 planMicrocompact 同一判定(长度阈值 + 媒体保护):投影只 elide 规划
125
- // 时认定为可省的 tool result,否则计划与投影对同一历史给出不同结果。
126
- if (!isElidableToolResult(message, marker.minChars))
127
- return entry;
128
- return {
129
- ...entry,
130
- message: { ...message, content: [{ type: "text", text: MICROCOMPACT_ELIDED_PLACEHOLDER }] },
131
- };
132
- });
133
- }
134
- //# sourceMappingURL=microcompact.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"microcompact.js","sourceRoot":"","sources":["../../../src/core/extensions/microcompact.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAGxD,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AAC,oBAAoB,CAAC,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;YAAE,OAAO,KAAK,CAAC;QAClE,OAAO;YACN,GAAG,KAAK;YACR,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,+BAA+B,EAAE,CAAC,EAAE;SAC3F,CAAC;IAAA,CACF,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Microcompact (P1 context hygiene): before spending an LLM summarization\n * call, elide the BULKY OLD tool results from the LLM context — a pure local\n * history transform with zero model cost (the codex/ZCode \"microcompact\"\n * layer). The session file keeps every byte (append-only marker + logical\n * transform at context build); only the model-visible context shrinks.\n *\n * Contract: the marker is a `custom` session entry (`MICROCOMPACT_CUSTOM_TYPE`)\n * whose data names the elision point. The projection registered by the\n * bootstrap compaction policy plugin (via the PUBLIC\n * `api.registerEntryProjection` channel) replaces eligible tool-result\n * contents older than that point with a fixed placeholder, so reload and\n * token estimation stay consistent with live turns. The kernel applies\n * registered projections verbatim and knows nothing about microcompact.\n */\n\nimport type { AgentMessage } from \"@agent-forge/agent-core\";\nimport { contentText } from \"@agent-forge/ai\";\nimport { estimateTokens } from \"../compaction/index.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\n\n/** Custom entry type carrying the microcompact elision point. */\nexport const MICROCOMPACT_CUSTOM_TYPE = \"microcompact.v1\";\n\n/** Replacement content for an elided tool result. */\nexport const MICROCOMPACT_ELIDED_PLACEHOLDER = \"[earlier tool result elided by microcompact]\";\n\n/** Tool results shorter than this are not worth eliding (noise, not bulk). */\nexport const DEFAULT_MIN_ELIDE_CHARS = 200;\n\n/**\n * Minimum estimated token relief for a microcompact to fire: below this the\n * churn (marker entry + context transition) cannot pay for itself and the\n * caller falls through to full LLM compaction.\n */\nexport const MIN_MICROCOMPACT_FREED_TOKENS = 2048;\n\n/** Data carried by a {@link MICROCOMPACT_CUSTOM_TYPE} custom entry. */\nexport interface MicrocompactMarkerData {\n\t/** Entries strictly BEFORE this entry id (path order) are elision candidates. */\n\treadonly elideBeforeEntryId: string;\n\t/** Tool results whose serialized content is shorter are kept verbatim. */\n\treadonly minChars: number;\n}\n\nexport interface MicrocompactPlan {\n\treadonly elideBeforeEntryId: string;\n\t/** Estimated tokens freed by eliding the eligible tool results. */\n\treadonly freedTokens: number;\n\treadonly elidedCount: number;\n}\n\nfunction isElidableToolResult(\n\tmessage: AgentMessage,\n\tminChars: number,\n): message is Extract<AgentMessage, { role: \"toolResult\" }> {\n\tif (message.role !== \"toolResult\") return false;\n\t// 媒体保护:含非 text part(image 等)的 tool result 不 elide——占位符替换会\n\t// 把模型可见上下文中的原图数据抹掉(会话文件虽保真,但投影按 marker 重放,\n\t// 图像不会自行回来),保持\"原图常驻直到全量压缩\"的现行裁决。\n\tif (Array.isArray(message.content) && message.content.some((part) => part.type !== \"text\")) {\n\t\treturn false;\n\t}\n\treturn contentText(message.content, \"\").length >= minChars;\n}\n\n/** Explicit plan options: `enabled` gates THIS mechanism only (microcompact relief), not compaction. */\nexport interface MicrocompactPlanOptions {\n\t/** Whether microcompact relief may fire at all (settings switch AND session cooldown). */\n\tenabled: boolean;\n\t/** Verbatim-protected recent tail budget (estimated tokens). */\n\tkeepRecentTokens: number;\n\t/** Tool results shorter than this are not worth eliding. */\n\tminElideChars?: number;\n}\n\n/**\n * Plan one microcompact over the branch path: protect the most recent\n * `keepRecentTokens` (estimated) as the verbatim tail, and elide the eligible\n * old tool results before that cut. Returns undefined when the caller disabled\n * the mechanism (`options.enabled === false`), when there is nothing to elide,\n * or when the relief cannot reach the minimum. Deliberately does NOT reuse\n * `CompactionSettings`: its `enabled` is the compaction master switch — a\n * different gate.\n */\nexport function planMicrocompact(\n\tpathEntries: readonly { readonly id?: string; readonly type: string; readonly message?: AgentMessage }[],\n\toptions: MicrocompactPlanOptions,\n): MicrocompactPlan | undefined {\n\tif (!options.enabled) return undefined;\n\tconst minChars = options.minElideChars ?? DEFAULT_MIN_ELIDE_CHARS;\n\n\t// Protect the recent tail: walk backwards accumulating estimated tokens,\n\t// cutting before the entry that crosses the budget (same walk as\n\t// findCutPoint, but without turn-boundary subtleties — elision never\n\t// removes entries, only replaces contents, so any cut point is safe).\n\tlet accumulated = 0;\n\tlet cutIndex = 0;\n\tfor (let i = pathEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = pathEntries[i];\n\t\tconst messageTokens = entry.message ? estimateTokens(entry.message) : 0;\n\t\tif (messageTokens === 0) continue;\n\t\taccumulated += messageTokens;\n\t\tif (accumulated >= options.keepRecentTokens) {\n\t\t\tcutIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet freedTokens = 0;\n\tlet elidedCount = 0;\n\tfor (let i = 0; i < cutIndex; i++) {\n\t\tconst message = pathEntries[i].message;\n\t\tif (!message || !isElidableToolResult(message, minChars)) continue;\n\t\tfreedTokens +=\n\t\t\testimateTokens(message) -\n\t\t\testimateTokens({ ...message, content: [{ type: \"text\", text: MICROCOMPACT_ELIDED_PLACEHOLDER }] });\n\t\telidedCount += 1;\n\t}\n\n\tconst elideBefore = pathEntries[cutIndex];\n\tif (elidedCount === 0 || freedTokens < MIN_MICROCOMPACT_FREED_TOKENS) return undefined;\n\tconst elideBeforeEntryId = elideBefore?.id;\n\tif (!elideBeforeEntryId) return undefined;\n\treturn { elideBeforeEntryId, freedTokens, elidedCount };\n}\n\n/** Resolve the marker data of the LAST microcompact marker in path order. */\nexport function lastMicrocompactMarker(\n\tpathEntries: readonly { readonly type: string; readonly customType?: string; readonly data?: unknown }[],\n): MicrocompactMarkerData | undefined {\n\tlet marker: MicrocompactMarkerData | undefined;\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== MICROCOMPACT_CUSTOM_TYPE) continue;\n\t\tconst data = entry.data as Partial<MicrocompactMarkerData> | undefined;\n\t\tif (typeof data?.elideBeforeEntryId === \"string\") {\n\t\t\tmarker = {\n\t\t\t\telideBeforeEntryId: data.elideBeforeEntryId,\n\t\t\t\tminChars: typeof data.minChars === \"number\" && data.minChars >= 0 ? data.minChars : DEFAULT_MIN_ELIDE_CHARS,\n\t\t\t};\n\t\t}\n\t}\n\treturn marker;\n}\n\n/**\n * The entry projection backing microcompact: replaces the CONTENT of eligible\n * tool results before the marker's cut point with the fixed placeholder, and\n * keeps everything else verbatim. Registered through the public\n * `api.registerEntryProjection` channel — the same channel any third-party\n * context policy uses; the kernel applies it without interpretation.\n */\nexport function applyMicrocompactElision(path: SessionEntry[]): SessionEntry[] {\n\tconst marker = lastMicrocompactMarker(path);\n\tif (marker === undefined) return path;\n\tconst cutIndex = path.findIndex((entry) => entry.id === marker.elideBeforeEntryId);\n\tif (cutIndex <= 0) return path;\n\treturn path.map((entry, index) => {\n\t\tif (index >= cutIndex || entry.type !== \"message\") return entry;\n\t\tconst message = entry.message;\n\t\t// 与 planMicrocompact 同一判定(长度阈值 + 媒体保护):投影只 elide 规划\n\t\t// 时认定为可省的 tool result,否则计划与投影对同一历史给出不同结果。\n\t\tif (!isElidableToolResult(message, marker.minChars)) return entry;\n\t\treturn {\n\t\t\t...entry,\n\t\t\tmessage: { ...message, content: [{ type: \"text\", text: MICROCOMPACT_ELIDED_PLACEHOLDER }] },\n\t\t};\n\t});\n}\n"]}
@@ -1,106 +0,0 @@
1
- /**
2
- * 第一方 provider 主备切换插件(设计:docs/design/供应商能力槽位与主备切换设计.md §4)。
3
- *
4
- * 形态与 bootstrap-retry 同族——嵌入式第一方插件,策略经公共
5
- * `api.registerStreamFnWrapper` 注册面挂进宿主默认 stream 装配——但熔断状态是
6
- * **宿主模块级单例**(设计 §4.2):进程内所有会话与 subagent 共享同一份,不随
7
- * 会话 dispose,不持久化(重启后全部 CLOSED)。
8
- *
9
- * 判定哲学(设计 §2):只看流终态 done/error/aborted 与"是否已向上层释放内容
10
- * 增量"两个本地事实,不解读错误类型/错误码语义;原始 errorMessage 照透传保留,
11
- * 只用于事件归因与 diagnostics,不参与机器判定分支。aborted 不计数、不换道、
12
- * 状态不变。换道从第一次失败即发生;`failureThreshold` 只控制"是否继续先撞主"
13
- * (连续 N 次后熔断打开,请求直接落备用,冷却期满后以真实请求试探回主)。
14
- */
15
- import type { Api, Model } from "@agent-forge/ai/compat";
16
- import type { HostLogger } from "../logger.ts";
17
- import { type CapabilityPluginHandle } from "./capability-plugin.ts";
18
- import type { CapabilityRuntime } from "./capability-runtime.ts";
19
- export declare const PROVIDER_FAILOVER_PLUGIN_ID = "agent-forge.provider-failover";
20
- export declare const PROVIDER_FAILOVER_WRAPPER_NAME = "provider-failover";
21
- /**
22
- * 会话日志快照通道的 customType(设计 §4.7 Phase 3):插件经公共
23
- * `api.session.appendEntry` 在状态转移点写入快照,footer 每帧取最后一条渲染
24
- * 摘要行——与 goal.state / todo.state / workflow.state 同构,零新公共面。
25
- */
26
- export declare const PROVIDER_FAILOVER_STATE_ENTRY_TYPE = "provider.failover.state";
27
- /** `provider.failover.state` 快照负载(footer 按最后一条渲染)。 */
28
- export interface ProviderFailoverStateSnapshot {
29
- readonly version: 1;
30
- /** 主链引用 `provider/modelId`;装配期初始快照无链上下文,为空串。 */
31
- readonly chainId: string;
32
- readonly status: "closed" | "open" | "half-open";
33
- /** 当前换道目标引用 `provider/modelId`(OPEN 期请求从链头重走);closed 省略。 */
34
- readonly backupProvider?: string;
35
- /** 下次试探时间戳 = open 时刻 + 当前冷却;closed 为 0。 */
36
- readonly probeAtMs: number;
37
- /** 快照写入时刻(注入时钟友好)。 */
38
- readonly now: number;
39
- }
40
- interface FailoverChainDeclaration {
41
- readonly primary: string;
42
- readonly backups: readonly string[];
43
- }
44
- interface ResolvedFailoverConfig {
45
- /** 试探失败冷却起点(也是回 CLOSED 后的重置值)。 */
46
- readonly cooldownInitialMs: number;
47
- readonly cooldownMaxMs: number;
48
- readonly failureThreshold: number;
49
- readonly backupProviders: readonly string[];
50
- readonly chains: readonly FailoverChainDeclaration[];
51
- }
52
- /**
53
- * 解析 settings `failover` 节。返回 undefined = 无 failover(未配置 / 显式关闭 /
54
- * 配置错误拒绝加载——后者附带一条警告,设计 §4.1"重复 primary 拒绝加载并警告")。
55
- */
56
- export declare function parseProviderFailoverConfig(raw: unknown, warn: (message: string) => void): ResolvedFailoverConfig | undefined;
57
- /**
58
- * 从 SettingsManager 现有读面取合并后的 `failover` 原始节点(设计 §4.1 配置面):
59
- * `getFailoverSettings()`(Phase 1 落地)原样透传合并层对象,本层不做结构收窄
60
- * ——解析与校验全部收在本模块(见 parseProviderFailoverConfig)。
61
- */
62
- export declare function readProviderFailoverSettingsNode(settingsManager: Pick<SettingsManagerFailoverReader, "getFailoverSettings">): unknown;
63
- interface SettingsManagerFailoverReader {
64
- getFailoverSettings(): unknown;
65
- }
66
- /** 测试隔离钩子:清空模块级熔断单例与预检警告去重集(仅测试使用)。 */
67
- export declare function resetProviderFailoverStateForTests(): void;
68
- /**
69
- * 装载预检的宿主静态检查面(设计 §4.6)。全部为目录/凭据快照读取:不发网络
70
- * 请求、不触发 OAuth 刷新(凭据检查与 ModelRuntime.hasConfiguredAuth 同构——
71
- * 只读"该 provider 是否有凭据条目",不做可用性探测)。
72
- */
73
- export interface ProviderFailoverPreflightChecks {
74
- /** 目录解析,与运行时换道候选解析同一面。 */
75
- readonly resolveModel: (provider: string, modelId: string) => Model<Api> | undefined;
76
- /** provider 在组合目录(builtin + models.json + 扩展)中存在(backupProviders 层预检)。 */
77
- readonly hasProvider: (providerId: string) => boolean;
78
- /** provider 有凭据条目(静态;不触发 OAuth 刷新)。 */
79
- readonly hasConfiguredAuth: (providerId: string) => boolean;
80
- }
81
- export interface ProviderFailoverInstallOptions {
82
- /** settings `failover` 节的原始合并值(经 readProviderFailoverSettingsNode 读取)。 */
83
- readonly failoverSettings: unknown;
84
- /**
85
- * 装载预检宿主检查面(设计 §4.6):全部静态读取,零网络、零 OAuth 刷新。
86
- * 必传——预检是安装契约的一部分,宿主缺失检查面时不应静默退化为无预检。
87
- */
88
- readonly preflight: ProviderFailoverPreflightChecks;
89
- /** 注入时钟(测试用确定性时间);缺省 Date.now。 */
90
- readonly now?: () => number;
91
- /** 宿主进程日志;缺省时配置警告静默丢弃。 */
92
- readonly hostLogger?: HostLogger;
93
- }
94
- /**
95
- * 装配嵌入式 provider-failover 插件(设计 §4.8)。
96
- *
97
- * - 未配置 / `enabled: false` / 配置错误(已警告)→ 返回 undefined,不注册任何面。
98
- * - 配置解析完成后同步执行装载预检(设计 §4.6):失败条目从候选源剔除并警告,
99
- * 警告经模块级去重每进程至多一次;预检不阻断其余条目与主 provider 的正常使用。
100
- * - 宿主侧装配失败由调用方兜底(failover 是可靠性能力,装载失败不得阻断会话)。
101
- * - 熔断状态是模块级单例:本函数跨会话重复调用注册的是新包装器实例,但共享
102
- * 同一份状态(设计 §4.2)。
103
- */
104
- export declare function installProviderFailoverPlugin(runtime: CapabilityRuntime, options: ProviderFailoverInstallOptions): CapabilityPluginHandle | undefined;
105
- export {};
106
- //# sourceMappingURL=provider-failover.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider-failover.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/provider-failover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EACX,GAAG,EAMH,KAAK,EAEL,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,KAAK,sBAAsB,EAA4B,MAAM,wBAAwB,CAAC;AAC/F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAYjE,eAAO,MAAM,2BAA2B,kCAAkC,CAAC;AAC3E,eAAO,MAAM,8BAA8B,sBAAsB,CAAC;AAElE;;;;GAIG;AACH,eAAO,MAAM,kCAAkC,4BAA4B,CAAC;AAE5E,kFAAsD;AACtD,MAAM,WAAW,6BAA6B;IAC7C,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,4FAAgD;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,MAAM,KAAK,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IACrF,8GAA0E;IAC1E,QAAQ,CAAC,WAAW,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;IACtD,uEAAuC;IACvC,QAAQ,CAAC,iBAAiB,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;CAC5D;AA+HD,MAAM,WAAW,8BAA8B;IAC9C,oGAA0E;IAC1E,QAAQ,CAAC,gBAAgB,EAAE,OAAO,CAAC;IACnC;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,+BAA+B,CAAC;IACpD,sEAAkC;IAClC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,gEAA0B;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;CACjC;AAED;;;;;;;;;GASG;AACH,wBAAgB,6BAA6B,CAC5C,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,8BAA8B,GACrC,sBAAsB,GAAG,SAAS,CAyCpC","sourcesContent":["/**\n * 第一方 provider 主备切换插件(设计:docs/design/供应商能力槽位与主备切换设计.md §4)。\n *\n * 形态与 bootstrap-retry 同族——嵌入式第一方插件,策略经公共\n * `api.registerStreamFnWrapper` 注册面挂进宿主默认 stream 装配——但熔断状态是\n * **宿主模块级单例**(设计 §4.2):进程内所有会话与 subagent 共享同一份,不随\n * 会话 dispose,不持久化(重启后全部 CLOSED)。\n *\n * 判定哲学(设计 §2):只看流终态 done/error/aborted 与\"是否已向上层释放内容\n * 增量\"两个本地事实,不解读错误类型/错误码语义;原始 errorMessage 照透传保留,\n * 只用于事件归因与 diagnostics,不参与机器判定分支。aborted 不计数、不换道、\n * 状态不变。换道从第一次失败即发生;`failureThreshold` 只控制\"是否继续先撞主\"\n * (连续 N 次后熔断打开,请求直接落备用,冷却期满后以真实请求试探回主)。\n */\n\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageDiagnostic,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n} from \"@agent-forge/ai/compat\";\nimport { createAssistantMessageEventStream } from \"@agent-forge/ai/compat\";\nimport type { HostLogger } from \"../logger.ts\";\nimport { type CapabilityPluginHandle, loadCapabilityPluginSync } from \"./capability-plugin.ts\";\nimport type { CapabilityRuntime } from \"./capability-runtime.ts\";\nimport {\n\tPROVIDER_FAILOVER_PROBE_FAILED_EVENT_ID,\n\tPROVIDER_FAILOVER_PROBE_FAILED_EVENT_VERSION,\n\tPROVIDER_FAILOVER_RECOVERED_EVENT_ID,\n\tPROVIDER_FAILOVER_RECOVERED_EVENT_VERSION,\n\tPROVIDER_FAILOVER_SWITCHED_EVENT_ID,\n\tPROVIDER_FAILOVER_SWITCHED_EVENT_VERSION,\n} from \"./lifecycle-catalog.ts\";\nimport type { LifecycleDispatchRequest, SessionAPI, StreamFnWrapper } from \"./public-api.ts\";\nimport { EXPERIMENTAL_PUBLIC_API_VERSION } from \"./public-api.ts\";\n\nexport const PROVIDER_FAILOVER_PLUGIN_ID = \"agent-forge.provider-failover\";\nexport const PROVIDER_FAILOVER_WRAPPER_NAME = \"provider-failover\";\n\n/**\n * 会话日志快照通道的 customType(设计 §4.7 Phase 3):插件经公共\n * `api.session.appendEntry` 在状态转移点写入快照,footer 每帧取最后一条渲染\n * 摘要行——与 goal.state / todo.state / workflow.state 同构,零新公共面。\n */\nexport const PROVIDER_FAILOVER_STATE_ENTRY_TYPE = \"provider.failover.state\";\n\n/** `provider.failover.state` 快照负载(footer 按最后一条渲染)。 */\nexport interface ProviderFailoverStateSnapshot {\n\treadonly version: 1;\n\t/** 主链引用 `provider/modelId`;装配期初始快照无链上下文,为空串。 */\n\treadonly chainId: string;\n\treadonly status: \"closed\" | \"open\" | \"half-open\";\n\t/** 当前换道目标引用 `provider/modelId`(OPEN 期请求从链头重走);closed 省略。 */\n\treadonly backupProvider?: string;\n\t/** 下次试探时间戳 = open 时刻 + 当前冷却;closed 为 0。 */\n\treadonly probeAtMs: number;\n\t/** 快照写入时刻(注入时钟友好)。 */\n\treadonly now: number;\n}\n\n/** 链默认阈值/冷却(设计 §4.1:默认值全部可省)。 */\nconst DEFAULT_FAILURE_THRESHOLD = 2;\nconst DEFAULT_COOLDOWN_INITIAL_MS = 60_000;\nconst DEFAULT_COOLDOWN_MAX_MS = 15 * 60_000;\n/** 事件负载与 diagnostics 里的原始错误文本截断上限(只影响展示,不影响判定)。 */\nconst RAW_ERROR_MAX_LENGTH = 500;\n\n// ---------------------------------------------------------------------------\n// 配置解析(局部类型声明:settings `failover` 节不是 settings-manager 的已知面,\n// 解析与校验全部收在本模块内,宿主只递交原始节点)\n// ---------------------------------------------------------------------------\n\ninterface FailoverChainDeclaration {\n\treadonly primary: string;\n\treadonly backups: readonly string[];\n}\n\ninterface ResolvedFailoverConfig {\n\t/** 试探失败冷却起点(也是回 CLOSED 后的重置值)。 */\n\treadonly cooldownInitialMs: number;\n\treadonly cooldownMaxMs: number;\n\treadonly failureThreshold: number;\n\treadonly backupProviders: readonly string[];\n\treadonly chains: readonly FailoverChainDeclaration[];\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction parseModelReference(reference: string): { provider: string; modelId: string } | undefined {\n\tconst separator = reference.indexOf(\"/\");\n\tif (separator <= 0 || separator === reference.length - 1) return undefined;\n\treturn { provider: reference.slice(0, separator), modelId: reference.slice(separator + 1) };\n}\n\nfunction parseModelReferenceList(value: unknown, label: string, warn: (message: string) => void): string[] | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Array.isArray(value)) {\n\t\twarn(`failover ${label} must be an array of \"provider/modelId\" strings; ignoring it`);\n\t\treturn undefined;\n\t}\n\tconst references: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== \"string\" || parseModelReference(entry) === undefined) {\n\t\t\twarn(`failover ${label} contains a non-\"provider/modelId\" entry; skipping it`);\n\t\t\tcontinue;\n\t\t}\n\t\treferences.push(entry);\n\t}\n\treturn references;\n}\n\n/** `backupProviders` 是纯 provider id 列表(设计 §4.1:`[\"proxy-a\", \"proxy-b\"]`),匹配运行时做。 */\nfunction parseProviderIdList(value: unknown, warn: (message: string) => void): string[] | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Array.isArray(value)) {\n\t\twarn(\"failover.backupProviders must be an array of provider id strings; ignoring it\");\n\t\treturn undefined;\n\t}\n\tconst providerIds: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== \"string\" || entry.trim() === \"\") {\n\t\t\twarn(\"failover.backupProviders contains a non-string entry; skipping it\");\n\t\t\tcontinue;\n\t\t}\n\t\tproviderIds.push(entry);\n\t}\n\treturn providerIds;\n}\n\n/**\n * 解析 settings `failover` 节。返回 undefined = 无 failover(未配置 / 显式关闭 /\n * 配置错误拒绝加载——后者附带一条警告,设计 §4.1\"重复 primary 拒绝加载并警告\")。\n */\nexport function parseProviderFailoverConfig(\n\traw: unknown,\n\twarn: (message: string) => void,\n): ResolvedFailoverConfig | undefined {\n\tif (raw === undefined || raw === null) return undefined;\n\tif (!isPlainObject(raw)) {\n\t\twarn(\"failover settings must be an object; provider failover stays disabled\");\n\t\treturn undefined;\n\t}\n\tif (raw.enabled === false) return undefined;\n\tif (raw.enabled !== undefined && typeof raw.enabled !== \"boolean\") {\n\t\twarn(\"failover.enabled must be a boolean; provider failover stays disabled\");\n\t\treturn undefined;\n\t}\n\n\tlet failureThreshold = DEFAULT_FAILURE_THRESHOLD;\n\tif (raw.failureThreshold !== undefined) {\n\t\tif (\n\t\t\ttypeof raw.failureThreshold !== \"number\" ||\n\t\t\t!Number.isSafeInteger(raw.failureThreshold) ||\n\t\t\traw.failureThreshold < 1\n\t\t) {\n\t\t\twarn(\"failover.failureThreshold must be a positive integer; using the default (2)\");\n\t\t} else {\n\t\t\tfailureThreshold = raw.failureThreshold;\n\t\t}\n\t}\n\n\tlet cooldownInitialMs = DEFAULT_COOLDOWN_INITIAL_MS;\n\tlet cooldownMaxMs = DEFAULT_COOLDOWN_MAX_MS;\n\tif (raw.cooldown !== undefined) {\n\t\tif (!isPlainObject(raw.cooldown)) {\n\t\t\twarn(\"failover.cooldown must be an object { initialMs?, maxMs? }; using the defaults\");\n\t\t} else {\n\t\t\tconst initialMs = raw.cooldown.initialMs;\n\t\t\tconst maxMs = raw.cooldown.maxMs;\n\t\t\tif (\n\t\t\t\tinitialMs !== undefined &&\n\t\t\t\t(typeof initialMs !== \"number\" || !Number.isSafeInteger(initialMs) || initialMs < 1)\n\t\t\t) {\n\t\t\t\twarn(\"failover.cooldown.initialMs must be a positive integer; using the default (60000)\");\n\t\t\t} else if (initialMs !== undefined) {\n\t\t\t\tcooldownInitialMs = initialMs;\n\t\t\t}\n\t\t\tif (maxMs !== undefined && (typeof maxMs !== \"number\" || !Number.isSafeInteger(maxMs) || maxMs < 1)) {\n\t\t\t\twarn(\"failover.cooldown.maxMs must be a positive integer; using the default (900000)\");\n\t\t\t} else if (maxMs !== undefined) {\n\t\t\t\tcooldownMaxMs = maxMs;\n\t\t\t}\n\t\t}\n\t}\n\tif (cooldownMaxMs < cooldownInitialMs) {\n\t\twarn(\"failover.cooldown.maxMs is below initialMs; clamping maxMs to initialMs\");\n\t\tcooldownMaxMs = cooldownInitialMs;\n\t}\n\n\tconst backupProviders = parseProviderIdList(raw.backupProviders, warn) ?? [];\n\n\tconst chains: FailoverChainDeclaration[] = [];\n\tif (raw.chains !== undefined) {\n\t\tif (!Array.isArray(raw.chains)) {\n\t\t\twarn(\"failover.chains must be an array; ignoring explicit chains\");\n\t\t} else {\n\t\t\tconst seenPrimaries = new Set<string>();\n\t\t\tfor (const entry of raw.chains) {\n\t\t\t\tif (!isPlainObject(entry)) {\n\t\t\t\t\twarn(\"failover.chains entries must be objects; skipping one\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (typeof entry.primary !== \"string\" || parseModelReference(entry.primary) === undefined) {\n\t\t\t\t\twarn('failover.chains entry is missing a valid \"provider/modelId\" primary; skipping it');\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst backups = parseModelReferenceList(entry.backups, `chains[${entry.primary}].backups`, warn) ?? [];\n\t\t\t\tif (seenPrimaries.has(entry.primary)) {\n\t\t\t\t\t// 设计 §4.1:同一 primary 出现在多条显式链 → 配置错误拒绝加载。\n\t\t\t\t\twarn(\n\t\t\t\t\t\t`failover.chains declares primary \"${entry.primary}\" more than once; provider failover stays disabled`,\n\t\t\t\t\t);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tseenPrimaries.add(entry.primary);\n\t\t\t\tif (backups.length > 2) {\n\t\t\t\t\twarn(\n\t\t\t\t\t\t`failover chain \"${entry.primary}\" declares ${backups.length} backups; the worst-case retry budget grows with chain length (recommended: at most 2)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tchains.push({ primary: entry.primary, backups });\n\t\t\t}\n\t\t}\n\t}\n\n\tif (backupProviders.length === 0 && chains.length === 0) return undefined;\n\treturn { cooldownInitialMs, cooldownMaxMs, failureThreshold, backupProviders, chains };\n}\n\n/**\n * 从 SettingsManager 现有读面取合并后的 `failover` 原始节点(设计 §4.1 配置面):\n * `getFailoverSettings()`(Phase 1 落地)原样透传合并层对象,本层不做结构收窄\n * ——解析与校验全部收在本模块(见 parseProviderFailoverConfig)。\n */\nexport function readProviderFailoverSettingsNode(\n\tsettingsManager: Pick<SettingsManagerFailoverReader, \"getFailoverSettings\">,\n): unknown {\n\treturn settingsManager.getFailoverSettings();\n}\n\ninterface SettingsManagerFailoverReader {\n\tgetFailoverSettings(): unknown;\n}\n\n// ---------------------------------------------------------------------------\n// 熔断状态机(模块级单例,设计 §4.2:进程内所有会话共享,不持久化)\n// ---------------------------------------------------------------------------\n\ntype ProviderBreakerStatus = \"closed\" | \"open\" | \"half-open\";\n\ninterface ProviderBreakerState {\n\tstatus: ProviderBreakerStatus;\n\t/** CLOSED 期主连续失败计数;任一主 done 清零(设计 §4.2)。 */\n\tconsecutiveFailures: number;\n\t/** 当前冷却时长:打开时取 initialMs,每次试探失败 ×2 封顶 maxMs。 */\n\tcooldownMs: number;\n\topenedAtMs: number;\n}\n\nconst providerBreakerRegistry = new Map<string, ProviderBreakerState>();\n\n/** 预检警告去重集(设计 §4.6:每进程至多一次,与会话重复装载解耦)。 */\nconst preflightWarnedMessages = new Set<string>();\n\n/** 测试隔离钩子:清空模块级熔断单例与预检警告去重集(仅测试使用)。 */\nexport function resetProviderFailoverStateForTests(): void {\n\tproviderBreakerRegistry.clear();\n\tpreflightWarnedMessages.clear();\n}\n\nfunction getBreaker(chainId: string, config: ResolvedFailoverConfig): ProviderBreakerState {\n\tlet breaker = providerBreakerRegistry.get(chainId);\n\tif (breaker === undefined) {\n\t\tbreaker = {\n\t\t\tstatus: \"closed\",\n\t\t\tconsecutiveFailures: 0,\n\t\t\tcooldownMs: config.cooldownInitialMs,\n\t\t\topenedAtMs: 0,\n\t\t};\n\t\tproviderBreakerRegistry.set(chainId, breaker);\n\t}\n\treturn breaker;\n}\n\n// ---------------------------------------------------------------------------\n// 换道主体\n// ---------------------------------------------------------------------------\n\ninterface FailoverAttempt {\n\treadonly model: Model<Api>;\n\treadonly role: \"primary\" | \"backup\";\n}\n\ninterface AttemptFailure {\n\treadonly model: Model<Api>;\n\t/** 失败尝试的原始错误消息(照透传;诊断与事件只做展示截断)。 */\n\treadonly message: AssistantMessage;\n}\n\ntype AttemptOutcome =\n\t| { readonly outcome: \"done\"; readonly message: AssistantMessage }\n\t| { readonly outcome: \"aborted\"; readonly message: AssistantMessage }\n\t/** 已过提交边界(内容增量已释放)的 error:终态已转发,不可换道。 */\n\t| { readonly outcome: \"failed-forwarded\"; readonly message: AssistantMessage }\n\t/** 未过提交边界的 error:上层尚未看到任何事件,可安全重放。 */\n\t| { readonly outcome: \"failed-switchable\"; readonly failure: AttemptFailure };\n\nconst isCommittedDelta = (event: { type: string }): boolean =>\n\tevent.type === \"text_delta\" || event.type === \"thinking_delta\" || event.type === \"toolcall_delta\";\n\nfunction truncateRawError(text: string | undefined): string {\n\tconst value = text === undefined || text === \"\" ? \"unknown error\" : text;\n\treturn value.length > RAW_ERROR_MAX_LENGTH ? `${value.slice(0, RAW_ERROR_MAX_LENGTH)}…[truncated]` : value;\n}\n\nfunction createThrownErrorMessage(model: Model<Api>, error: unknown, nowMs: number): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: nowMs,\n\t};\n}\n\n/**\n * 换道重放的凭据剔除(设计 §4.4):apiKey/headers/env 是主 provider 的预解析\n * 凭据,照抄重放会把主的 key 发给备用 provider——剔除后由目标 provider 经\n * 宿主 auth 解析重新注入。其余 options(signal、预算、缓存策略等)原样保留。\n */\nfunction stripCredentialOptions(options: SimpleStreamOptions | undefined): SimpleStreamOptions | undefined {\n\tif (options === undefined) return undefined;\n\tconst { apiKey: _apiKey, headers: _headers, env: _env, ...rest } = options;\n\treturn rest;\n}\n\n/** 候选序列解析(设计 §4.1):显式链优先,否则 backupProviders 按声明顺序同 id 匹配。 */\nfunction resolveFailoverCandidates(\n\tmodel: Model<Api>,\n\tconfig: ResolvedFailoverConfig,\n\tresolveModel: (provider: string, modelId: string) => Model<Api> | undefined,\n): Model<Api>[] {\n\tconst reference = `${model.provider}/${model.id}`;\n\tconst chain = config.chains.find((entry) => entry.primary === reference);\n\tif (chain !== undefined) {\n\t\tconst candidates: Model<Api>[] = [];\n\t\tfor (const backup of chain.backups) {\n\t\t\tconst parsed = parseModelReference(backup);\n\t\t\tconst resolved = parsed === undefined ? undefined : resolveModel(parsed.provider, parsed.modelId);\n\t\t\tif (resolved === undefined) continue;\n\t\t\tif (resolved.provider === model.provider && resolved.id === model.id) continue;\n\t\t\tcandidates.push(resolved);\n\t\t}\n\t\treturn candidates;\n\t}\n\tconst candidates: Model<Api>[] = [];\n\tfor (const providerId of config.backupProviders) {\n\t\t// 含主 provider 自身 → 忽略该项(设计 §4.1)。\n\t\tif (providerId === model.provider) continue;\n\t\tconst resolved = resolveModel(providerId, model.id);\n\t\tif (resolved !== undefined) candidates.push(resolved);\n\t}\n\treturn candidates;\n}\n\ninterface ProviderFailoverRuntimeDeps {\n\treadonly runtime: CapabilityRuntime;\n\treadonly config: ResolvedFailoverConfig;\n\treadonly now: () => number;\n\t/**\n\t * 会话日志快照通道(宿主声明 `session` feature 时在场;最小宿主可缺席)。\n\t * 缺席只损失 footer 可见性,不影响换道判定。\n\t */\n\treadonly session?: Pick<SessionAPI, \"appendEntry\">;\n\t/** 快照写入失败的警告通道;缺省静默(与 lifecycle 事件通道同级)。 */\n\treadonly hostLogger?: HostLogger;\n}\n\n/**\n * 写一条熔断状态快照进会话日志(设计 §4.7 Phase 3)。尽力通道:失败不打断\n * 换道判定,但经进程日志警告保持失败可见。\n */\nfunction writeStateSnapshot(deps: ProviderFailoverRuntimeDeps, snapshot: ProviderFailoverStateSnapshot): void {\n\tif (deps.session === undefined) return;\n\ttry {\n\t\tdeps.session.appendEntry(PROVIDER_FAILOVER_STATE_ENTRY_TYPE, snapshot);\n\t} catch (error) {\n\t\tdeps.hostLogger?.warn(\"provider-failover\", \"failover state snapshot append failed\", { cause: error });\n\t}\n}\n\n/** OPEN 转移点(阈值打开 / 试探失败重开)共用的 open 快照。 */\nfunction writeOpenStateSnapshot(\n\tdeps: ProviderFailoverRuntimeDeps,\n\tchainId: string,\n\tbreaker: ProviderBreakerState,\n\tbackupReference: string | undefined,\n): void {\n\twriteStateSnapshot(deps, {\n\t\tversion: 1,\n\t\tchainId,\n\t\tstatus: \"open\",\n\t\t...(backupReference === undefined ? {} : { backupProvider: backupReference }),\n\t\tprobeAtMs: breaker.openedAtMs + breaker.cooldownMs,\n\t\tnow: breaker.openedAtMs,\n\t});\n}\n\nfunction dispatchFailoverEvent(deps: ProviderFailoverRuntimeDeps, request: LifecycleDispatchRequest): void {\n\ttry {\n\t\tif (!deps.runtime.hasLifecycleEvent(request.type, request.version)) return;\n\t\tvoid deps.runtime.dispatchLifecycle(request).catch(() => {\n\t\t\t// 可见性事件失败不打断换道判定(宪法 §8 的尽力通道)。\n\t\t});\n\t} catch {\n\t\t// 同上:派发入口同步抛错也不影响请求路径。\n\t}\n}\n\nfunction createFailoverWrapper(deps: ProviderFailoverRuntimeDeps): StreamFnWrapper {\n\treturn (modelArgument, contextArgument, optionsArgument, next, host) => {\n\t\tconst model = modelArgument as Model<Api>;\n\t\tconst context = contextArgument as Context;\n\t\tconst options = optionsArgument as SimpleStreamOptions | undefined;\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst resolveModel = (provider: string, modelId: string): Model<Api> | undefined =>\n\t\t\thost.resolveModel(provider, modelId) as Model<Api> | undefined;\n\t\tvoid driveFailoverStream(deps, outer, model, context, options, next, resolveModel);\n\t\treturn outer;\n\t};\n}\n\nasync function driveFailoverStream(\n\tdeps: ProviderFailoverRuntimeDeps,\n\touter: AssistantMessageEventStream,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\tnext: (model: unknown, context: unknown, options: unknown) => unknown,\n\tresolveModel: (provider: string, modelId: string) => Model<Api> | undefined,\n): Promise<void> {\n\tconst { config } = deps;\n\tconst nowMs = deps.now();\n\tconst chainId = `${model.provider}/${model.id}`;\n\tconst breaker = getBreaker(chainId, config);\n\n\t// 入场判定(设计 §4.3 判定表):CLOSED/HALF_OPEN 撞主,OPEN 且冷却未满落备用。\n\tlet attemptPrimary = true;\n\tlet isProbe = false;\n\tif (breaker.status === \"open\") {\n\t\tif (nowMs - breaker.openedAtMs >= breaker.cooldownMs) {\n\t\t\t// 冷却期满:下一个真实请求改道回主作试探(HALF_OPEN 并发放行)。\n\t\t\tbreaker.status = \"half-open\";\n\t\t\tisProbe = true;\n\t\t} else {\n\t\t\tattemptPrimary = false;\n\t\t}\n\t} else if (breaker.status === \"half-open\") {\n\t\tisProbe = true;\n\t}\n\n\tconst candidates = resolveFailoverCandidates(model, config, resolveModel);\n\t// OPEN 期请求从链头重走(设计 §4.3),快照披露的换道目标 = 链头候选。\n\tconst backupReference = candidates[0] === undefined ? undefined : `${candidates[0].provider}/${candidates[0].id}`;\n\n\tconst attempts: FailoverAttempt[] = [];\n\tif (attemptPrimary) attempts.push({ model, role: \"primary\" });\n\tfor (const candidate of candidates) attempts.push({ model: candidate, role: \"backup\" });\n\tif (attempts.length === 0) {\n\t\t// OPEN 且候选为空:无别处可去,直发主(按普通主请求计账,不作试探)。\n\t\tattempts.push({ model, role: \"primary\" });\n\t}\n\n\tconst failures: AttemptFailure[] = [];\n\tlet switchOrdinal = 0;\n\tfor (let index = 0; index < attempts.length; index++) {\n\t\tconst attempt = attempts[index];\n\t\tconst attemptOptions = attempt.role === \"backup\" ? stripCredentialOptions(options) : options;\n\t\tconst result = await runFailoverAttempt(outer, next, attempt.model, context, attemptOptions, deps.now);\n\n\t\tif (result.outcome === \"done\") {\n\t\t\tif (attempt.role === \"primary\") {\n\t\t\t\tbreaker.status = \"closed\";\n\t\t\t\tbreaker.consecutiveFailures = 0;\n\t\t\t\tbreaker.cooldownMs = config.cooldownInitialMs;\n\t\t\t\tif (isProbe) {\n\t\t\t\t\tdispatchFailoverEvent(deps, {\n\t\t\t\t\t\ttype: PROVIDER_FAILOVER_RECOVERED_EVENT_ID,\n\t\t\t\t\t\tversion: PROVIDER_FAILOVER_RECOVERED_EVENT_VERSION,\n\t\t\t\t\t\tphase: \"committed\",\n\t\t\t\t\t\tsource: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\t\t\t\t\tdata: { version: 1, chainId, provider: model.provider },\n\t\t\t\t\t});\n\t\t\t\t\t// HALF_OPEN → CLOSED 转移点:footer 摘要行随最后一条 closed 快照消失。\n\t\t\t\t\twriteStateSnapshot(deps, {\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tchainId,\n\t\t\t\t\t\tstatus: \"closed\",\n\t\t\t\t\t\tprobeAtMs: 0,\n\t\t\t\t\t\tnow: deps.now(),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// 备用成败不影响 primary 熔断状态(设计 §4.2)。\n\t\t\treturn;\n\t\t}\n\n\t\tif (result.outcome === \"aborted\") {\n\t\t\t// 用户本地取消:不计数、不换道、状态不变(设计 §2/§4.3)。\n\t\t\treturn;\n\t\t}\n\n\t\tif (result.outcome === \"failed-forwarded\") {\n\t\t\t// 已过提交边界:不可重放,交回合级重试;主失败照常计数。\n\t\t\tif (attempt.role === \"primary\") {\n\t\t\t\trecordPrimaryFailure(deps, breaker, config, chainId, result.message, isProbe, backupReference);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// failed-switchable:无可见内容,可换道重放。\n\t\tfailures.push(result.failure);\n\t\tif (attempt.role === \"primary\") {\n\t\t\trecordPrimaryFailure(deps, breaker, config, chainId, result.failure.message, isProbe, backupReference);\n\t\t}\n\n\t\tif (index + 1 < attempts.length) {\n\t\t\tswitchOrdinal += 1;\n\t\t\tconst target = attempts[index + 1];\n\t\t\tdispatchFailoverEvent(deps, {\n\t\t\t\ttype: PROVIDER_FAILOVER_SWITCHED_EVENT_ID,\n\t\t\t\tversion: PROVIDER_FAILOVER_SWITCHED_EVENT_VERSION,\n\t\t\t\tphase: \"committed\",\n\t\t\t\tsource: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\t\t\tdata: {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tchainId,\n\t\t\t\t\tfrom: `${attempt.model.provider}/${attempt.model.id}`,\n\t\t\t\t\tto: `${target.model.provider}/${target.model.id}`,\n\t\t\t\t\tattempt: switchOrdinal,\n\t\t\t\t\trawError: truncateRawError(result.failure.message.errorMessage),\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\n\t// 全链尽:报链内最后一次实际失败的原始错误 + 整链摘要进 diagnostics(设计 §4.3)。\n\tconst lastFailure = failures[failures.length - 1];\n\tif (lastFailure === undefined) {\n\t\t// 不可达(至少一次 failed-switchable 才会走到这里);保守以合成错误收尾。\n\t\tconst message = createThrownErrorMessage(model, new Error(\"provider failover exhausted the chain\"), deps.now());\n\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\touter.end();\n\t\treturn;\n\t}\n\tconst diagnostic: AssistantMessageDiagnostic = {\n\t\ttype: \"provider-failover\",\n\t\ttimestamp: deps.now(),\n\t\tdetails: {\n\t\t\tchainId,\n\t\t\tattempts: failures.map((failure) => ({\n\t\t\t\tprovider: failure.model.provider,\n\t\t\t\tmodel: failure.model.id,\n\t\t\t\terror: truncateRawError(failure.message.errorMessage),\n\t\t\t})),\n\t\t},\n\t};\n\tconst finalMessage: AssistantMessage = {\n\t\t...lastFailure.message,\n\t\tdiagnostics: [...(lastFailure.message.diagnostics ?? []), diagnostic],\n\t};\n\touter.push({ type: \"error\", reason: \"error\", error: finalMessage });\n\touter.end();\n}\n\n/**\n * 主失败计账(设计 §4.2/§4.3):CLOSED 期连续 N 次达到阈值 → OPEN(冷却取\n * initialMs);HALF_OPEN 试探失败 → OPEN 且冷却 ×2 封顶 maxMs(经 probe.failed\n * 事件可见)。backup 的成败永远不进这里。\n */\nfunction recordPrimaryFailure(\n\tdeps: ProviderFailoverRuntimeDeps,\n\tbreaker: ProviderBreakerState,\n\tconfig: ResolvedFailoverConfig,\n\tchainId: string,\n\tmessage: AssistantMessage,\n\tisProbe: boolean,\n\tbackupReference: string | undefined,\n): void {\n\tif (isProbe) {\n\t\topenAfterFailedProbe(deps, breaker, config, chainId, message, backupReference);\n\t\treturn;\n\t}\n\tbreaker.consecutiveFailures += 1;\n\tif (breaker.consecutiveFailures >= config.failureThreshold) {\n\t\tbreaker.status = \"open\";\n\t\tbreaker.cooldownMs = config.cooldownInitialMs;\n\t\tbreaker.openedAtMs = deps.now();\n\t\twriteOpenStateSnapshot(deps, chainId, breaker, backupReference);\n\t}\n}\n\n/** HALF_OPEN 试探失败:回 OPEN,冷却 ×2 封顶 maxMs,并派发 probe.failed(设计 §4.2)。 */\nfunction openAfterFailedProbe(\n\tdeps: ProviderFailoverRuntimeDeps,\n\tbreaker: ProviderBreakerState,\n\tconfig: ResolvedFailoverConfig,\n\tchainId: string,\n\tmessage: AssistantMessage,\n\tbackupReference: string | undefined,\n): void {\n\tbreaker.status = \"open\";\n\tbreaker.cooldownMs = Math.min(breaker.cooldownMs * 2, config.cooldownMaxMs);\n\tbreaker.openedAtMs = deps.now();\n\tdispatchFailoverEvent(deps, {\n\t\ttype: PROVIDER_FAILOVER_PROBE_FAILED_EVENT_ID,\n\t\tversion: PROVIDER_FAILOVER_PROBE_FAILED_EVENT_VERSION,\n\t\tphase: \"committed\",\n\t\tsource: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\tdata: {\n\t\t\tversion: 1,\n\t\t\tchainId,\n\t\t\tprovider: message.provider,\n\t\t\trawError: truncateRawError(message.errorMessage),\n\t\t\tnextCooldownMs: breaker.cooldownMs,\n\t\t},\n\t});\n\twriteOpenStateSnapshot(deps, chainId, breaker, backupReference);\n}\n\nasync function runFailoverAttempt(\n\touter: AssistantMessageEventStream,\n\tnext: (model: unknown, context: unknown, options: unknown) => unknown,\n\tattemptModel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\tnow: () => number,\n): Promise<AttemptOutcome> {\n\tlet inner: AssistantMessageEventStream;\n\ttry {\n\t\tinner = (await next(attemptModel, context, options)) as AssistantMessageEventStream;\n\t} catch (error) {\n\t\tconst message = createThrownErrorMessage(attemptModel, error, now());\n\t\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message } };\n\t}\n\n\t// 前奏事件缓冲(设计 §4.4):提交边界(首个内容增量)或正常完成前不释放,\n\t// 使\"无可见内容\"的失败可以整段丢弃后无感重放。非增量、非终态事件(start、\n\t// *_start、*_end 及未知扩展事件)一律入缓冲——保守归入前奏,重放安全性优先。\n\tconst buffered: AssistantMessageEvent[] = [];\n\tlet committed = false;\n\tconst flushBuffer = (): void => {\n\t\tfor (const event of buffered) outer.push(event);\n\t\tbuffered.length = 0;\n\t};\n\ttry {\n\t\tfor await (const event of inner) {\n\t\t\tif (event.type === \"done\") {\n\t\t\t\tflushBuffer();\n\t\t\t\touter.push(event);\n\t\t\t\touter.end();\n\t\t\t\treturn { outcome: \"done\", message: event.message };\n\t\t\t}\n\t\t\tif (event.type === \"error\") {\n\t\t\t\tif (event.reason === \"aborted\") {\n\t\t\t\t\t// 不重放的终态:丢弃缓冲只发终态,避免上层收到孤立 start。\n\t\t\t\t\touter.push(event);\n\t\t\t\t\touter.end();\n\t\t\t\t\treturn { outcome: \"aborted\", message: event.error };\n\t\t\t\t}\n\t\t\t\tif (committed) {\n\t\t\t\t\touter.push(event);\n\t\t\t\t\touter.end();\n\t\t\t\t\treturn { outcome: \"failed-forwarded\", message: event.error };\n\t\t\t\t}\n\t\t\t\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message: event.error } };\n\t\t\t}\n\t\t\tif (isCommittedDelta(event)) {\n\t\t\t\tif (!committed) {\n\t\t\t\t\tcommitted = true;\n\t\t\t\t\tflushBuffer();\n\t\t\t\t}\n\t\t\t\touter.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (committed) outer.push(event);\n\t\t\telse buffered.push(event);\n\t\t}\n\t} catch (error) {\n\t\tconst message = createThrownErrorMessage(attemptModel, error, now());\n\t\tif (committed) {\n\t\t\tconst errorEvent = { type: \"error\" as const, reason: \"error\" as const, error: message };\n\t\t\touter.push(errorEvent);\n\t\t\touter.end();\n\t\t\treturn { outcome: \"failed-forwarded\", message };\n\t\t}\n\t\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message } };\n\t}\n\n\t// 流自然结束但没有终止信号:按设计 §2 的归一哲学视作 error 终态。\n\tconst message = createThrownErrorMessage(attemptModel, new Error(\"stream ended without a terminal event\"), now());\n\tif (committed) {\n\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\touter.end();\n\t\treturn { outcome: \"failed-forwarded\", message };\n\t}\n\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message } };\n}\n\n// ---------------------------------------------------------------------------\n// 装载预检(设计 §4.6:插件安装时同步执行的静态检查,零网络请求)\n// ---------------------------------------------------------------------------\n\n/**\n * 装载预检的宿主静态检查面(设计 §4.6)。全部为目录/凭据快照读取:不发网络\n * 请求、不触发 OAuth 刷新(凭据检查与 ModelRuntime.hasConfiguredAuth 同构——\n * 只读\"该 provider 是否有凭据条目\",不做可用性探测)。\n */\nexport interface ProviderFailoverPreflightChecks {\n\t/** 目录解析,与运行时换道候选解析同一面。 */\n\treadonly resolveModel: (provider: string, modelId: string) => Model<Api> | undefined;\n\t/** provider 在组合目录(builtin + models.json + 扩展)中存在(backupProviders 层预检)。 */\n\treadonly hasProvider: (providerId: string) => boolean;\n\t/** provider 有凭据条目(静态;不触发 OAuth 刷新)。 */\n\treadonly hasConfiguredAuth: (providerId: string) => boolean;\n}\n\n/**\n * 稳定序列化(键排序、剔除 undefined):compat/thinkingLevelMap 的派生差异按\n * 值比较,不依赖对象键序。\n */\nfunction stableStringify(value: unknown): string {\n\tif (value === undefined) return \"∅\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value) ?? String(value);\n\tif (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, entryValue]) => entryValue !== undefined)\n\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n\treturn `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`).join(\",\")}}`;\n}\n\n/**\n * 显式链全量预检(设计 §4.6):每个 backup 逐一检查,失败条目从链中剔除并\n * 警告;主不可解析 → 整链跳过。contextWindow/compat/thinkingLevelMap/maxTokens\n * 差异只进警告清单、不硬拦——实施裁量:contextWindow 低于主的备用对小上下文\n * 请求仍可成功,剔除条目会静默损失兜底;只有上下文逼近主窗口的请求才必失败,\n * 该情形运行时走链内下一候选,有界。\n */\nfunction preflightExplicitChain(\n\tchain: FailoverChainDeclaration,\n\tchecks: ProviderFailoverPreflightChecks,\n\twarn: (message: string) => void,\n): FailoverChainDeclaration | undefined {\n\tconst parsedPrimary = parseModelReference(chain.primary);\n\tconst primaryModel =\n\t\tparsedPrimary === undefined ? undefined : checks.resolveModel(parsedPrimary.provider, parsedPrimary.modelId);\n\tif (parsedPrimary === undefined || primaryModel === undefined) {\n\t\twarn(`failover chain \"${chain.primary}\" primary does not resolve in the model catalog; skipping the chain`);\n\t\treturn undefined;\n\t}\n\tconst backups: string[] = [];\n\tfor (const backup of chain.backups) {\n\t\tconst parsed = parseModelReference(backup);\n\t\tconst backupModel = parsed === undefined ? undefined : checks.resolveModel(parsed.provider, parsed.modelId);\n\t\tif (parsed === undefined || backupModel === undefined) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" does not resolve in the model catalog; skipping it`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!checks.hasConfiguredAuth(backupModel.provider)) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup provider \"${backupModel.provider}\" has no configured credentials; skipping \"${backup}\"`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (backupModel.contextWindow < primaryModel.contextWindow) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" context window (${backupModel.contextWindow}) is below the primary's (${primaryModel.contextWindow}); contexts sized for the primary may fail on this backup (entry kept)`,\n\t\t\t);\n\t\t}\n\t\tif (backupModel.maxTokens !== primaryModel.maxTokens) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" maxTokens (${backupModel.maxTokens}) differs from the primary's (${primaryModel.maxTokens}); output budget may change after switching`,\n\t\t\t);\n\t\t}\n\t\tif (stableStringify(backupModel.compat) !== stableStringify(primaryModel.compat)) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" compat differs from the primary's; request derivation may change after switching`,\n\t\t\t);\n\t\t}\n\t\tif (stableStringify(backupModel.thinkingLevelMap) !== stableStringify(primaryModel.thinkingLevelMap)) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" thinkingLevelMap differs from the primary's; reasoning level mapping may change after switching`,\n\t\t\t);\n\t\t}\n\t\tbackups.push(backup);\n\t}\n\tif (backups.length === 0 && chain.backups.length > 0) {\n\t\twarn(\n\t\t\t`failover chain \"${chain.primary}\" has no usable backups left after preflight; the primary keeps no failover candidates from this chain`,\n\t\t);\n\t}\n\treturn { primary: chain.primary, backups };\n}\n\n/**\n * backupProviders 层预检(设计 §4.6):仅检 provider 存在 + 凭据条目;模型匹配\n * 留运行时(目录同 id 匹配不到时静默跳过,不算失败)。\n */\nfunction preflightBackupProviders(\n\tproviderIds: readonly string[],\n\tchecks: ProviderFailoverPreflightChecks,\n\twarn: (message: string) => void,\n): string[] {\n\tconst retained: string[] = [];\n\tfor (const providerId of providerIds) {\n\t\tif (!checks.hasProvider(providerId)) {\n\t\t\twarn(`failover.backupProviders entry \"${providerId}\" is not a known provider; skipping it`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!checks.hasConfiguredAuth(providerId)) {\n\t\t\twarn(`failover.backupProviders entry \"${providerId}\" has no configured credentials; skipping it`);\n\t\t\tcontinue;\n\t\t}\n\t\tretained.push(providerId);\n\t}\n\treturn retained;\n}\n\n/**\n * 装载预检主体:返回过滤后的派生配置(预检失败条目已从候选源剔除)。不改变\n * 运行时换道判定——过滤只发生在装载期,运行时候选解析逻辑不变。\n */\nfunction runProviderFailoverPreflight(\n\tconfig: ResolvedFailoverConfig,\n\tchecks: ProviderFailoverPreflightChecks,\n\twarn: (message: string) => void,\n): ResolvedFailoverConfig {\n\tconst backupProviders = preflightBackupProviders(config.backupProviders, checks, warn);\n\tconst chains: FailoverChainDeclaration[] = [];\n\tfor (const chain of config.chains) {\n\t\tconst preflighted = preflightExplicitChain(chain, checks, warn);\n\t\tif (preflighted !== undefined) chains.push(preflighted);\n\t}\n\treturn { ...config, backupProviders, chains };\n}\n\n// ---------------------------------------------------------------------------\n// 装配\n// ---------------------------------------------------------------------------\n\nexport interface ProviderFailoverInstallOptions {\n\t/** settings `failover` 节的原始合并值(经 readProviderFailoverSettingsNode 读取)。 */\n\treadonly failoverSettings: unknown;\n\t/**\n\t * 装载预检宿主检查面(设计 §4.6):全部静态读取,零网络、零 OAuth 刷新。\n\t * 必传——预检是安装契约的一部分,宿主缺失检查面时不应静默退化为无预检。\n\t */\n\treadonly preflight: ProviderFailoverPreflightChecks;\n\t/** 注入时钟(测试用确定性时间);缺省 Date.now。 */\n\treadonly now?: () => number;\n\t/** 宿主进程日志;缺省时配置警告静默丢弃。 */\n\treadonly hostLogger?: HostLogger;\n}\n\n/**\n * 装配嵌入式 provider-failover 插件(设计 §4.8)。\n *\n * - 未配置 / `enabled: false` / 配置错误(已警告)→ 返回 undefined,不注册任何面。\n * - 配置解析完成后同步执行装载预检(设计 §4.6):失败条目从候选源剔除并警告,\n * 警告经模块级去重每进程至多一次;预检不阻断其余条目与主 provider 的正常使用。\n * - 宿主侧装配失败由调用方兜底(failover 是可靠性能力,装载失败不得阻断会话)。\n * - 熔断状态是模块级单例:本函数跨会话重复调用注册的是新包装器实例,但共享\n * 同一份状态(设计 §4.2)。\n */\nexport function installProviderFailoverPlugin(\n\truntime: CapabilityRuntime,\n\toptions: ProviderFailoverInstallOptions,\n): CapabilityPluginHandle | undefined {\n\tconst warn =\n\t\toptions.hostLogger === undefined\n\t\t\t? (_message: string) => {}\n\t\t\t: (message: string) => {\n\t\t\t\t\toptions.hostLogger?.warn(\"provider-failover\", message);\n\t\t\t\t};\n\tconst config = parseProviderFailoverConfig(options.failoverSettings, warn);\n\tif (config === undefined) return undefined;\n\tconst warnPreflightOnce = (message: string): void => {\n\t\tif (preflightWarnedMessages.has(message)) return;\n\t\tpreflightWarnedMessages.add(message);\n\t\twarn(message);\n\t};\n\tconst preflighted = runProviderFailoverPreflight(config, options.preflight, warnPreflightOnce);\n\tconst now = options.now ?? (() => Date.now());\n\treturn loadCapabilityPluginSync(\n\t\truntime,\n\t\t{\n\t\t\tid: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\t\tversion: \"0.0.0\",\n\t\t\tapiVersion: EXPERIMENTAL_PUBLIC_API_VERSION,\n\t\t\tentry: \"<embedded:provider-failover>\",\n\t\t},\n\t\t(api) => {\n\t\t\t// 快照通道绑定本会话的公共 session 面(宿主声明 session feature 时在场):\n\t\t\t// 会话 A 触发的熔断只写进 A 的日志,footer 可见性是会话局部的(设计 §4.7\n\t\t\t// 保真度限制)。deps 须在此构建——api 只在工厂内可得。\n\t\t\tconst deps: ProviderFailoverRuntimeDeps = {\n\t\t\t\truntime,\n\t\t\t\tconfig: preflighted,\n\t\t\t\tnow,\n\t\t\t\tsession: api.session,\n\t\t\t\t...(options.hostLogger === undefined ? {} : { hostLogger: options.hostLogger }),\n\t\t\t};\n\t\t\tapi.registerStreamFnWrapper(PROVIDER_FAILOVER_WRAPPER_NAME, createFailoverWrapper(deps));\n\t\t\t// 装配期初始快照(status closed)覆盖恢复会话里的陈旧 open 残留:熔断\n\t\t\t// 状态不持久化,新进程恒 CLOSED(设计 §4.2/§4.7)。无链上下文 → chainId 空。\n\t\t\twriteStateSnapshot(deps, { version: 1, chainId: \"\", status: \"closed\", probeAtMs: 0, now: deps.now() });\n\t\t},\n\t);\n}\n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AO;QAChB,UAAU,EAAE,+BAA+B;QAC3C,KAAK,EAAE,8BAA8B;KACrC,EACD,CAAC,GAAG,EAAE,EAAE,CAAC;QACR,kGAAoD;QACpD,oGAA+C;QAC/C,8EAAkC;QAClC,MAAM,IAAI,GAAgC;YACzC,OAAO;YACP,MAAM,EAAE,WAAW;YACnB,GAAG;YACH,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,GAAG,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC;SAC/E,CAAC;QACF,GAAG,CAAC,uBAAuB,CAAC,8BAA8B,EAAE,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC;QACzF,8FAA8C;QAC9C,wGAAsD;QACtD,kBAAkB,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAAA,CACvG,CACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * 第一方 provider 主备切换插件(设计:docs/design/供应商能力槽位与主备切换设计.md §4)。\n *\n * 形态与 bootstrap-retry 同族——嵌入式第一方插件,策略经公共\n * `api.registerStreamFnWrapper` 注册面挂进宿主默认 stream 装配——但熔断状态是\n * **宿主模块级单例**(设计 §4.2):进程内所有会话与 subagent 共享同一份,不随\n * 会话 dispose,不持久化(重启后全部 CLOSED)。\n *\n * 判定哲学(设计 §2):只看流终态 done/error/aborted 与\"是否已向上层释放内容\n * 增量\"两个本地事实,不解读错误类型/错误码语义;原始 errorMessage 照透传保留,\n * 只用于事件归因与 diagnostics,不参与机器判定分支。aborted 不计数、不换道、\n * 状态不变。换道从第一次失败即发生;`failureThreshold` 只控制\"是否继续先撞主\"\n * (连续 N 次后熔断打开,请求直接落备用,冷却期满后以真实请求试探回主)。\n */\n\nimport type {\n\tApi,\n\tAssistantMessage,\n\tAssistantMessageDiagnostic,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tSimpleStreamOptions,\n} from \"@agent-forge/ai/compat\";\nimport { createAssistantMessageEventStream } from \"@agent-forge/ai/compat\";\nimport type { HostLogger } from \"../logger.ts\";\nimport { type CapabilityPluginHandle, loadCapabilityPluginSync } from \"./capability-plugin.ts\";\nimport type { CapabilityRuntime } from \"./capability-runtime.ts\";\nimport {\n\tPROVIDER_FAILOVER_PROBE_FAILED_EVENT_ID,\n\tPROVIDER_FAILOVER_PROBE_FAILED_EVENT_VERSION,\n\tPROVIDER_FAILOVER_RECOVERED_EVENT_ID,\n\tPROVIDER_FAILOVER_RECOVERED_EVENT_VERSION,\n\tPROVIDER_FAILOVER_SWITCHED_EVENT_ID,\n\tPROVIDER_FAILOVER_SWITCHED_EVENT_VERSION,\n} from \"./lifecycle-catalog.ts\";\nimport type { LifecycleDispatchRequest, SessionAPI, StreamFnWrapper } from \"./public-api.ts\";\nimport { EXPERIMENTAL_PUBLIC_API_VERSION } from \"./public-api.ts\";\n\nexport const PROVIDER_FAILOVER_PLUGIN_ID = \"agent-forge.provider-failover\";\nexport const PROVIDER_FAILOVER_WRAPPER_NAME = \"provider-failover\";\n\n/**\n * 会话日志快照通道的 customType(设计 §4.7 Phase 3):插件经公共\n * `api.session.appendEntry` 在状态转移点写入快照,footer 每帧取最后一条渲染\n * 摘要行——与 goal.state / todo.state / workflow.state 同构,零新公共面。\n */\nexport const PROVIDER_FAILOVER_STATE_ENTRY_TYPE = \"provider.failover.state\";\n\n/** `provider.failover.state` 快照负载(footer 按最后一条渲染)。 */\nexport interface ProviderFailoverStateSnapshot {\n\treadonly version: 1;\n\t/** 主链引用 `provider/modelId`;装配期初始快照无链上下文,为空串。 */\n\treadonly chainId: string;\n\treadonly status: \"closed\" | \"open\" | \"half-open\";\n\t/** 当前换道目标引用 `provider/modelId`(OPEN 期请求从链头重走);closed 省略。 */\n\treadonly backupProvider?: string;\n\t/** 下次试探时间戳 = open 时刻 + 当前冷却;closed 为 0。 */\n\treadonly probeAtMs: number;\n\t/** 快照写入时刻(注入时钟友好)。 */\n\treadonly now: number;\n}\n\n/** 链默认阈值/冷却(设计 §4.1:默认值全部可省)。 */\nconst DEFAULT_FAILURE_THRESHOLD = 2;\nconst DEFAULT_COOLDOWN_INITIAL_MS = 60_000;\nconst DEFAULT_COOLDOWN_MAX_MS = 15 * 60_000;\n/** 事件负载与 diagnostics 里的原始错误文本截断上限(只影响展示,不影响判定)。 */\nconst RAW_ERROR_MAX_LENGTH = 500;\n\n// ---------------------------------------------------------------------------\n// 配置解析(局部类型声明:settings `failover` 节不是 settings-manager 的已知面,\n// 解析与校验全部收在本模块内,宿主只递交原始节点)\n// ---------------------------------------------------------------------------\n\ninterface FailoverChainDeclaration {\n\treadonly primary: string;\n\treadonly backups: readonly string[];\n}\n\ninterface ResolvedFailoverConfig {\n\t/** 试探失败冷却起点(也是回 CLOSED 后的重置值)。 */\n\treadonly cooldownInitialMs: number;\n\treadonly cooldownMaxMs: number;\n\treadonly failureThreshold: number;\n\treadonly backupProviders: readonly string[];\n\treadonly chains: readonly FailoverChainDeclaration[];\n}\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction parseModelReference(reference: string): { provider: string; modelId: string } | undefined {\n\tconst separator = reference.indexOf(\"/\");\n\tif (separator <= 0 || separator === reference.length - 1) return undefined;\n\treturn { provider: reference.slice(0, separator), modelId: reference.slice(separator + 1) };\n}\n\nfunction parseModelReferenceList(value: unknown, label: string, warn: (message: string) => void): string[] | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Array.isArray(value)) {\n\t\twarn(`failover ${label} must be an array of \"provider/modelId\" strings; ignoring it`);\n\t\treturn undefined;\n\t}\n\tconst references: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== \"string\" || parseModelReference(entry) === undefined) {\n\t\t\twarn(`failover ${label} contains a non-\"provider/modelId\" entry; skipping it`);\n\t\t\tcontinue;\n\t\t}\n\t\treferences.push(entry);\n\t}\n\treturn references;\n}\n\n/** `backupProviders` 是纯 provider id 列表(设计 §4.1:`[\"proxy-a\", \"proxy-b\"]`),匹配运行时做。 */\nfunction parseProviderIdList(value: unknown, warn: (message: string) => void): string[] | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Array.isArray(value)) {\n\t\twarn(\"failover.backupProviders must be an array of provider id strings; ignoring it\");\n\t\treturn undefined;\n\t}\n\tconst providerIds: string[] = [];\n\tfor (const entry of value) {\n\t\tif (typeof entry !== \"string\" || entry.trim() === \"\") {\n\t\t\twarn(\"failover.backupProviders contains a non-string entry; skipping it\");\n\t\t\tcontinue;\n\t\t}\n\t\tproviderIds.push(entry);\n\t}\n\treturn providerIds;\n}\n\n/**\n * 解析 settings `failover` 节。返回 undefined = 无 failover(未配置 / 显式关闭 /\n * 配置错误拒绝加载——后者附带一条警告,设计 §4.1\"重复 primary 拒绝加载并警告\")。\n */\nexport function parseProviderFailoverConfig(\n\traw: unknown,\n\twarn: (message: string) => void,\n): ResolvedFailoverConfig | undefined {\n\tif (raw === undefined || raw === null) return undefined;\n\tif (!isPlainObject(raw)) {\n\t\twarn(\"failover settings must be an object; provider failover stays disabled\");\n\t\treturn undefined;\n\t}\n\tif (raw.enabled === false) return undefined;\n\tif (raw.enabled !== undefined && typeof raw.enabled !== \"boolean\") {\n\t\twarn(\"failover.enabled must be a boolean; provider failover stays disabled\");\n\t\treturn undefined;\n\t}\n\n\tlet failureThreshold = DEFAULT_FAILURE_THRESHOLD;\n\tif (raw.failureThreshold !== undefined) {\n\t\tif (\n\t\t\ttypeof raw.failureThreshold !== \"number\" ||\n\t\t\t!Number.isSafeInteger(raw.failureThreshold) ||\n\t\t\traw.failureThreshold < 1\n\t\t) {\n\t\t\twarn(\"failover.failureThreshold must be a positive integer; using the default (2)\");\n\t\t} else {\n\t\t\tfailureThreshold = raw.failureThreshold;\n\t\t}\n\t}\n\n\tlet cooldownInitialMs = DEFAULT_COOLDOWN_INITIAL_MS;\n\tlet cooldownMaxMs = DEFAULT_COOLDOWN_MAX_MS;\n\tif (raw.cooldown !== undefined) {\n\t\tif (!isPlainObject(raw.cooldown)) {\n\t\t\twarn(\"failover.cooldown must be an object { initialMs?, maxMs? }; using the defaults\");\n\t\t} else {\n\t\t\tconst initialMs = raw.cooldown.initialMs;\n\t\t\tconst maxMs = raw.cooldown.maxMs;\n\t\t\tif (\n\t\t\t\tinitialMs !== undefined &&\n\t\t\t\t(typeof initialMs !== \"number\" || !Number.isSafeInteger(initialMs) || initialMs < 1)\n\t\t\t) {\n\t\t\t\twarn(\"failover.cooldown.initialMs must be a positive integer; using the default (60000)\");\n\t\t\t} else if (initialMs !== undefined) {\n\t\t\t\tcooldownInitialMs = initialMs;\n\t\t\t}\n\t\t\tif (maxMs !== undefined && (typeof maxMs !== \"number\" || !Number.isSafeInteger(maxMs) || maxMs < 1)) {\n\t\t\t\twarn(\"failover.cooldown.maxMs must be a positive integer; using the default (900000)\");\n\t\t\t} else if (maxMs !== undefined) {\n\t\t\t\tcooldownMaxMs = maxMs;\n\t\t\t}\n\t\t}\n\t}\n\tif (cooldownMaxMs < cooldownInitialMs) {\n\t\twarn(\"failover.cooldown.maxMs is below initialMs; clamping maxMs to initialMs\");\n\t\tcooldownMaxMs = cooldownInitialMs;\n\t}\n\n\tconst backupProviders = parseProviderIdList(raw.backupProviders, warn) ?? [];\n\n\tconst chains: FailoverChainDeclaration[] = [];\n\tif (raw.chains !== undefined) {\n\t\tif (!Array.isArray(raw.chains)) {\n\t\t\twarn(\"failover.chains must be an array; ignoring explicit chains\");\n\t\t} else {\n\t\t\tconst seenPrimaries = new Set<string>();\n\t\t\tfor (const entry of raw.chains) {\n\t\t\t\tif (!isPlainObject(entry)) {\n\t\t\t\t\twarn(\"failover.chains entries must be objects; skipping one\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (typeof entry.primary !== \"string\" || parseModelReference(entry.primary) === undefined) {\n\t\t\t\t\twarn('failover.chains entry is missing a valid \"provider/modelId\" primary; skipping it');\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst backups = parseModelReferenceList(entry.backups, `chains[${entry.primary}].backups`, warn) ?? [];\n\t\t\t\tif (seenPrimaries.has(entry.primary)) {\n\t\t\t\t\t// 设计 §4.1:同一 primary 出现在多条显式链 → 配置错误拒绝加载。\n\t\t\t\t\twarn(\n\t\t\t\t\t\t`failover.chains declares primary \"${entry.primary}\" more than once; provider failover stays disabled`,\n\t\t\t\t\t);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tseenPrimaries.add(entry.primary);\n\t\t\t\tif (backups.length > 2) {\n\t\t\t\t\twarn(\n\t\t\t\t\t\t`failover chain \"${entry.primary}\" declares ${backups.length} backups; the worst-case retry budget grows with chain length (recommended: at most 2)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tchains.push({ primary: entry.primary, backups });\n\t\t\t}\n\t\t}\n\t}\n\n\tif (backupProviders.length === 0 && chains.length === 0) return undefined;\n\treturn { cooldownInitialMs, cooldownMaxMs, failureThreshold, backupProviders, chains };\n}\n\n/**\n * 从 SettingsManager 现有读面取合并后的 `failover` 原始节点(设计 §4.1 配置面):\n * `getFailoverSettings()`(Phase 1 落地)原样透传合并层对象,本层不做结构收窄\n * ——解析与校验全部收在本模块(见 parseProviderFailoverConfig)。\n */\nexport function readProviderFailoverSettingsNode(\n\tsettingsManager: Pick<SettingsManagerFailoverReader, \"getFailoverSettings\">,\n): unknown {\n\treturn settingsManager.getFailoverSettings();\n}\n\ninterface SettingsManagerFailoverReader {\n\tgetFailoverSettings(): unknown;\n}\n\n// ---------------------------------------------------------------------------\n// 熔断状态机(模块级单例,设计 §4.2:进程内所有会话共享,不持久化)\n// ---------------------------------------------------------------------------\n\ntype ProviderBreakerStatus = \"closed\" | \"open\" | \"half-open\";\n\ninterface ProviderBreakerState {\n\tstatus: ProviderBreakerStatus;\n\t/** CLOSED 期主连续失败计数;任一主 done 清零(设计 §4.2)。 */\n\tconsecutiveFailures: number;\n\t/** 当前冷却时长:打开时取 initialMs,每次试探失败 ×2 封顶 maxMs。 */\n\tcooldownMs: number;\n\topenedAtMs: number;\n}\n\nconst providerBreakerRegistry = new Map<string, ProviderBreakerState>();\n\n/** 预检警告去重集(设计 §4.6:每进程至多一次,与会话重复装载解耦)。 */\nconst preflightWarnedMessages = new Set<string>();\n\n/** 测试隔离钩子:清空模块级熔断单例与预检警告去重集(仅测试使用)。 */\nexport function resetProviderFailoverStateForTests(): void {\n\tproviderBreakerRegistry.clear();\n\tpreflightWarnedMessages.clear();\n}\n\nfunction getBreaker(chainId: string, config: ResolvedFailoverConfig): ProviderBreakerState {\n\tlet breaker = providerBreakerRegistry.get(chainId);\n\tif (breaker === undefined) {\n\t\tbreaker = {\n\t\t\tstatus: \"closed\",\n\t\t\tconsecutiveFailures: 0,\n\t\t\tcooldownMs: config.cooldownInitialMs,\n\t\t\topenedAtMs: 0,\n\t\t};\n\t\tproviderBreakerRegistry.set(chainId, breaker);\n\t}\n\treturn breaker;\n}\n\n// ---------------------------------------------------------------------------\n// 换道主体\n// ---------------------------------------------------------------------------\n\ninterface FailoverAttempt {\n\treadonly model: Model<Api>;\n\treadonly role: \"primary\" | \"backup\";\n}\n\ninterface AttemptFailure {\n\treadonly model: Model<Api>;\n\t/** 失败尝试的原始错误消息(照透传;诊断与事件只做展示截断)。 */\n\treadonly message: AssistantMessage;\n}\n\ntype AttemptOutcome =\n\t| { readonly outcome: \"done\"; readonly message: AssistantMessage }\n\t| { readonly outcome: \"aborted\"; readonly message: AssistantMessage }\n\t/** 已过提交边界(内容增量已释放)的 error:终态已转发,不可换道。 */\n\t| { readonly outcome: \"failed-forwarded\"; readonly message: AssistantMessage }\n\t/** 未过提交边界的 error:上层尚未看到任何事件,可安全重放。 */\n\t| { readonly outcome: \"failed-switchable\"; readonly failure: AttemptFailure };\n\nconst isCommittedDelta = (event: { type: string }): boolean =>\n\tevent.type === \"text_delta\" || event.type === \"thinking_delta\" || event.type === \"toolcall_delta\";\n\nfunction truncateRawError(text: string | undefined): string {\n\tconst value = text === undefined || text === \"\" ? \"unknown error\" : text;\n\treturn value.length > RAW_ERROR_MAX_LENGTH ? `${value.slice(0, RAW_ERROR_MAX_LENGTH)}…[truncated]` : value;\n}\n\nfunction createThrownErrorMessage(model: Model<Api>, error: unknown, nowMs: number): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: nowMs,\n\t};\n}\n\n/**\n * 换道重放的凭据剔除(设计 §4.4):apiKey/headers/env 是主 provider 的预解析\n * 凭据,照抄重放会把主的 key 发给备用 provider——剔除后由目标 provider 经\n * 宿主 auth 解析重新注入。其余 options(signal、预算、缓存策略等)原样保留。\n */\nfunction stripCredentialOptions(options: SimpleStreamOptions | undefined): SimpleStreamOptions | undefined {\n\tif (options === undefined) return undefined;\n\tconst { apiKey: _apiKey, headers: _headers, env: _env, ...rest } = options;\n\treturn rest;\n}\n\n/** 候选序列解析(设计 §4.1):显式链优先,否则 backupProviders 按声明顺序同 id 匹配。 */\nfunction resolveFailoverCandidates(\n\tmodel: Model<Api>,\n\tconfig: ResolvedFailoverConfig,\n\tresolveModel: (provider: string, modelId: string) => Model<Api> | undefined,\n): Model<Api>[] {\n\tconst reference = `${model.provider}/${model.id}`;\n\tconst chain = config.chains.find((entry) => entry.primary === reference);\n\tif (chain !== undefined) {\n\t\tconst candidates: Model<Api>[] = [];\n\t\tfor (const backup of chain.backups) {\n\t\t\tconst parsed = parseModelReference(backup);\n\t\t\tconst resolved = parsed === undefined ? undefined : resolveModel(parsed.provider, parsed.modelId);\n\t\t\tif (resolved === undefined) continue;\n\t\t\tif (resolved.provider === model.provider && resolved.id === model.id) continue;\n\t\t\tcandidates.push(resolved);\n\t\t}\n\t\treturn candidates;\n\t}\n\tconst candidates: Model<Api>[] = [];\n\tfor (const providerId of config.backupProviders) {\n\t\t// 含主 provider 自身 → 忽略该项(设计 §4.1)。\n\t\tif (providerId === model.provider) continue;\n\t\tconst resolved = resolveModel(providerId, model.id);\n\t\tif (resolved !== undefined) candidates.push(resolved);\n\t}\n\treturn candidates;\n}\n\ninterface ProviderFailoverRuntimeDeps {\n\treadonly runtime: CapabilityRuntime;\n\treadonly config: ResolvedFailoverConfig;\n\treadonly now: () => number;\n\t/**\n\t * 会话日志快照通道(宿主声明 `session` feature 时在场;最小宿主可缺席)。\n\t * 缺席只损失 footer 可见性,不影响换道判定。\n\t */\n\treadonly session?: Pick<SessionAPI, \"appendEntry\">;\n\t/** 快照写入失败的警告通道;缺省静默(与 lifecycle 事件通道同级)。 */\n\treadonly hostLogger?: HostLogger;\n}\n\n/**\n * 写一条熔断状态快照进会话日志(设计 §4.7 Phase 3)。尽力通道:失败不打断\n * 换道判定,但经进程日志警告保持失败可见。\n */\nfunction writeStateSnapshot(deps: ProviderFailoverRuntimeDeps, snapshot: ProviderFailoverStateSnapshot): void {\n\tif (deps.session === undefined) return;\n\ttry {\n\t\tdeps.session.appendEntry(PROVIDER_FAILOVER_STATE_ENTRY_TYPE, snapshot);\n\t} catch (error) {\n\t\tdeps.hostLogger?.warn(\"provider-failover\", \"failover state snapshot append failed\", { cause: error });\n\t}\n}\n\n/** OPEN 转移点(阈值打开 / 试探失败重开)共用的 open 快照。 */\nfunction writeOpenStateSnapshot(\n\tdeps: ProviderFailoverRuntimeDeps,\n\tchainId: string,\n\tbreaker: ProviderBreakerState,\n\tbackupReference: string | undefined,\n): void {\n\twriteStateSnapshot(deps, {\n\t\tversion: 1,\n\t\tchainId,\n\t\tstatus: \"open\",\n\t\t...(backupReference === undefined ? {} : { backupProvider: backupReference }),\n\t\tprobeAtMs: breaker.openedAtMs + breaker.cooldownMs,\n\t\tnow: breaker.openedAtMs,\n\t});\n}\n\nfunction dispatchFailoverEvent(deps: ProviderFailoverRuntimeDeps, request: LifecycleDispatchRequest): void {\n\ttry {\n\t\tif (!deps.runtime.hasLifecycleEvent(request.type, request.version)) return;\n\t\tvoid deps.runtime.dispatchLifecycle(request).catch(() => {\n\t\t\t// 可见性事件失败不打断换道判定(宪法 §8 的尽力通道)。\n\t\t});\n\t} catch {\n\t\t// 同上:派发入口同步抛错也不影响请求路径。\n\t}\n}\n\nfunction createFailoverWrapper(deps: ProviderFailoverRuntimeDeps): StreamFnWrapper {\n\treturn (modelArgument, contextArgument, optionsArgument, next, host) => {\n\t\tconst model = modelArgument as Model<Api>;\n\t\tconst context = contextArgument as Context;\n\t\tconst options = optionsArgument as SimpleStreamOptions | undefined;\n\t\tconst outer = createAssistantMessageEventStream();\n\t\tconst resolveModel = (provider: string, modelId: string): Model<Api> | undefined =>\n\t\t\thost.resolveModel(provider, modelId) as Model<Api> | undefined;\n\t\tvoid driveFailoverStream(deps, outer, model, context, options, next, resolveModel);\n\t\treturn outer;\n\t};\n}\n\nasync function driveFailoverStream(\n\tdeps: ProviderFailoverRuntimeDeps,\n\touter: AssistantMessageEventStream,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\tnext: (model: unknown, context: unknown, options: unknown) => unknown,\n\tresolveModel: (provider: string, modelId: string) => Model<Api> | undefined,\n): Promise<void> {\n\tconst { config } = deps;\n\tconst nowMs = deps.now();\n\tconst chainId = `${model.provider}/${model.id}`;\n\tconst breaker = getBreaker(chainId, config);\n\n\t// 入场判定(设计 §4.3 判定表):CLOSED/HALF_OPEN 撞主,OPEN 且冷却未满落备用。\n\tlet attemptPrimary = true;\n\tlet isProbe = false;\n\tif (breaker.status === \"open\") {\n\t\tif (nowMs - breaker.openedAtMs >= breaker.cooldownMs) {\n\t\t\t// 冷却期满:下一个真实请求改道回主作试探(HALF_OPEN 并发放行)。\n\t\t\tbreaker.status = \"half-open\";\n\t\t\tisProbe = true;\n\t\t} else {\n\t\t\tattemptPrimary = false;\n\t\t}\n\t} else if (breaker.status === \"half-open\") {\n\t\tisProbe = true;\n\t}\n\n\tconst candidates = resolveFailoverCandidates(model, config, resolveModel);\n\t// OPEN 期请求从链头重走(设计 §4.3),快照披露的换道目标 = 链头候选。\n\tconst backupReference = candidates[0] === undefined ? undefined : `${candidates[0].provider}/${candidates[0].id}`;\n\n\tconst attempts: FailoverAttempt[] = [];\n\tif (attemptPrimary) attempts.push({ model, role: \"primary\" });\n\tfor (const candidate of candidates) attempts.push({ model: candidate, role: \"backup\" });\n\tif (attempts.length === 0) {\n\t\t// OPEN 且候选为空:无别处可去,直发主(按普通主请求计账,不作试探)。\n\t\tattempts.push({ model, role: \"primary\" });\n\t}\n\n\tconst failures: AttemptFailure[] = [];\n\tlet switchOrdinal = 0;\n\tfor (let index = 0; index < attempts.length; index++) {\n\t\tconst attempt = attempts[index];\n\t\tconst attemptOptions = attempt.role === \"backup\" ? stripCredentialOptions(options) : options;\n\t\tconst result = await runFailoverAttempt(outer, next, attempt.model, context, attemptOptions, deps.now);\n\n\t\tif (result.outcome === \"done\") {\n\t\t\tif (attempt.role === \"primary\") {\n\t\t\t\tbreaker.status = \"closed\";\n\t\t\t\tbreaker.consecutiveFailures = 0;\n\t\t\t\tbreaker.cooldownMs = config.cooldownInitialMs;\n\t\t\t\tif (isProbe) {\n\t\t\t\t\tdispatchFailoverEvent(deps, {\n\t\t\t\t\t\ttype: PROVIDER_FAILOVER_RECOVERED_EVENT_ID,\n\t\t\t\t\t\tversion: PROVIDER_FAILOVER_RECOVERED_EVENT_VERSION,\n\t\t\t\t\t\tphase: \"committed\",\n\t\t\t\t\t\tsource: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\t\t\t\t\tdata: { version: 1, chainId, provider: model.provider },\n\t\t\t\t\t});\n\t\t\t\t\t// HALF_OPEN → CLOSED 转移点:footer 摘要行随最后一条 closed 快照消失。\n\t\t\t\t\twriteStateSnapshot(deps, {\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\tchainId,\n\t\t\t\t\t\tstatus: \"closed\",\n\t\t\t\t\t\tprobeAtMs: 0,\n\t\t\t\t\t\tnow: deps.now(),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t// 备用成败不影响 primary 熔断状态(设计 §4.2)。\n\t\t\treturn;\n\t\t}\n\n\t\tif (result.outcome === \"aborted\") {\n\t\t\t// 用户本地取消:不计数、不换道、状态不变(设计 §2/§4.3)。\n\t\t\treturn;\n\t\t}\n\n\t\tif (result.outcome === \"failed-forwarded\") {\n\t\t\t// 已过提交边界:不可重放,交回合级重试;主失败照常计数。\n\t\t\tif (attempt.role === \"primary\") {\n\t\t\t\trecordPrimaryFailure(deps, breaker, config, chainId, result.message, isProbe, backupReference);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// failed-switchable:无可见内容,可换道重放。\n\t\tfailures.push(result.failure);\n\t\tif (attempt.role === \"primary\") {\n\t\t\trecordPrimaryFailure(deps, breaker, config, chainId, result.failure.message, isProbe, backupReference);\n\t\t}\n\n\t\tif (index + 1 < attempts.length) {\n\t\t\tswitchOrdinal += 1;\n\t\t\tconst target = attempts[index + 1];\n\t\t\tdispatchFailoverEvent(deps, {\n\t\t\t\ttype: PROVIDER_FAILOVER_SWITCHED_EVENT_ID,\n\t\t\t\tversion: PROVIDER_FAILOVER_SWITCHED_EVENT_VERSION,\n\t\t\t\tphase: \"committed\",\n\t\t\t\tsource: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\t\t\tdata: {\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tchainId,\n\t\t\t\t\tfrom: `${attempt.model.provider}/${attempt.model.id}`,\n\t\t\t\t\tto: `${target.model.provider}/${target.model.id}`,\n\t\t\t\t\tattempt: switchOrdinal,\n\t\t\t\t\trawError: truncateRawError(result.failure.message.errorMessage),\n\t\t\t\t},\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\n\t// 全链尽:报链内最后一次实际失败的原始错误 + 整链摘要进 diagnostics(设计 §4.3)。\n\tconst lastFailure = failures[failures.length - 1];\n\tif (lastFailure === undefined) {\n\t\t// 不可达(至少一次 failed-switchable 才会走到这里);保守以合成错误收尾。\n\t\tconst message = createThrownErrorMessage(model, new Error(\"provider failover exhausted the chain\"), deps.now());\n\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\touter.end();\n\t\treturn;\n\t}\n\tconst diagnostic: AssistantMessageDiagnostic = {\n\t\ttype: \"provider-failover\",\n\t\ttimestamp: deps.now(),\n\t\tdetails: {\n\t\t\tchainId,\n\t\t\tattempts: failures.map((failure) => ({\n\t\t\t\tprovider: failure.model.provider,\n\t\t\t\tmodel: failure.model.id,\n\t\t\t\terror: truncateRawError(failure.message.errorMessage),\n\t\t\t})),\n\t\t},\n\t};\n\tconst finalMessage: AssistantMessage = {\n\t\t...lastFailure.message,\n\t\tdiagnostics: [...(lastFailure.message.diagnostics ?? []), diagnostic],\n\t};\n\touter.push({ type: \"error\", reason: \"error\", error: finalMessage });\n\touter.end();\n}\n\n/**\n * 主失败计账(设计 §4.2/§4.3):CLOSED 期连续 N 次达到阈值 → OPEN(冷却取\n * initialMs);HALF_OPEN 试探失败 → OPEN 且冷却 ×2 封顶 maxMs(经 probe.failed\n * 事件可见)。backup 的成败永远不进这里。\n */\nfunction recordPrimaryFailure(\n\tdeps: ProviderFailoverRuntimeDeps,\n\tbreaker: ProviderBreakerState,\n\tconfig: ResolvedFailoverConfig,\n\tchainId: string,\n\tmessage: AssistantMessage,\n\tisProbe: boolean,\n\tbackupReference: string | undefined,\n): void {\n\tif (isProbe) {\n\t\topenAfterFailedProbe(deps, breaker, config, chainId, message, backupReference);\n\t\treturn;\n\t}\n\tbreaker.consecutiveFailures += 1;\n\tif (breaker.consecutiveFailures >= config.failureThreshold) {\n\t\tbreaker.status = \"open\";\n\t\tbreaker.cooldownMs = config.cooldownInitialMs;\n\t\tbreaker.openedAtMs = deps.now();\n\t\twriteOpenStateSnapshot(deps, chainId, breaker, backupReference);\n\t}\n}\n\n/** HALF_OPEN 试探失败:回 OPEN,冷却 ×2 封顶 maxMs,并派发 probe.failed(设计 §4.2)。 */\nfunction openAfterFailedProbe(\n\tdeps: ProviderFailoverRuntimeDeps,\n\tbreaker: ProviderBreakerState,\n\tconfig: ResolvedFailoverConfig,\n\tchainId: string,\n\tmessage: AssistantMessage,\n\tbackupReference: string | undefined,\n): void {\n\tbreaker.status = \"open\";\n\tbreaker.cooldownMs = Math.min(breaker.cooldownMs * 2, config.cooldownMaxMs);\n\tbreaker.openedAtMs = deps.now();\n\tdispatchFailoverEvent(deps, {\n\t\ttype: PROVIDER_FAILOVER_PROBE_FAILED_EVENT_ID,\n\t\tversion: PROVIDER_FAILOVER_PROBE_FAILED_EVENT_VERSION,\n\t\tphase: \"committed\",\n\t\tsource: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\tdata: {\n\t\t\tversion: 1,\n\t\t\tchainId,\n\t\t\tprovider: message.provider,\n\t\t\trawError: truncateRawError(message.errorMessage),\n\t\t\tnextCooldownMs: breaker.cooldownMs,\n\t\t},\n\t});\n\twriteOpenStateSnapshot(deps, chainId, breaker, backupReference);\n}\n\nasync function runFailoverAttempt(\n\touter: AssistantMessageEventStream,\n\tnext: (model: unknown, context: unknown, options: unknown) => unknown,\n\tattemptModel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\tnow: () => number,\n): Promise<AttemptOutcome> {\n\tlet inner: AssistantMessageEventStream;\n\ttry {\n\t\tinner = (await next(attemptModel, context, options)) as AssistantMessageEventStream;\n\t} catch (error) {\n\t\tconst message = createThrownErrorMessage(attemptModel, error, now());\n\t\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message } };\n\t}\n\n\t// 前奏事件缓冲(设计 §4.4):提交边界(首个内容增量)或正常完成前不释放,\n\t// 使\"无可见内容\"的失败可以整段丢弃后无感重放。非增量、非终态事件(start、\n\t// *_start、*_end 及未知扩展事件)一律入缓冲——保守归入前奏,重放安全性优先。\n\tconst buffered: AssistantMessageEvent[] = [];\n\tlet committed = false;\n\tconst flushBuffer = (): void => {\n\t\tfor (const event of buffered) outer.push(event);\n\t\tbuffered.length = 0;\n\t};\n\ttry {\n\t\tfor await (const event of inner) {\n\t\t\tif (event.type === \"done\") {\n\t\t\t\tflushBuffer();\n\t\t\t\touter.push(event);\n\t\t\t\touter.end();\n\t\t\t\treturn { outcome: \"done\", message: event.message };\n\t\t\t}\n\t\t\tif (event.type === \"error\") {\n\t\t\t\tif (event.reason === \"aborted\") {\n\t\t\t\t\t// 不重放的终态:丢弃缓冲只发终态,避免上层收到孤立 start。\n\t\t\t\t\touter.push(event);\n\t\t\t\t\touter.end();\n\t\t\t\t\treturn { outcome: \"aborted\", message: event.error };\n\t\t\t\t}\n\t\t\t\tif (committed) {\n\t\t\t\t\touter.push(event);\n\t\t\t\t\touter.end();\n\t\t\t\t\treturn { outcome: \"failed-forwarded\", message: event.error };\n\t\t\t\t}\n\t\t\t\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message: event.error } };\n\t\t\t}\n\t\t\tif (isCommittedDelta(event)) {\n\t\t\t\tif (!committed) {\n\t\t\t\t\tcommitted = true;\n\t\t\t\t\tflushBuffer();\n\t\t\t\t}\n\t\t\t\touter.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (committed) outer.push(event);\n\t\t\telse buffered.push(event);\n\t\t}\n\t} catch (error) {\n\t\tconst message = createThrownErrorMessage(attemptModel, error, now());\n\t\tif (committed) {\n\t\t\tconst errorEvent = { type: \"error\" as const, reason: \"error\" as const, error: message };\n\t\t\touter.push(errorEvent);\n\t\t\touter.end();\n\t\t\treturn { outcome: \"failed-forwarded\", message };\n\t\t}\n\t\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message } };\n\t}\n\n\t// 流自然结束但没有终止信号:按设计 §2 的归一哲学视作 error 终态。\n\tconst message = createThrownErrorMessage(attemptModel, new Error(\"stream ended without a terminal event\"), now());\n\tif (committed) {\n\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\touter.end();\n\t\treturn { outcome: \"failed-forwarded\", message };\n\t}\n\treturn { outcome: \"failed-switchable\", failure: { model: attemptModel, message } };\n}\n\n// ---------------------------------------------------------------------------\n// 装载预检(设计 §4.6:插件安装时同步执行的静态检查,零网络请求)\n// ---------------------------------------------------------------------------\n\n/**\n * 装载预检的宿主静态检查面(设计 §4.6)。全部为目录/凭据快照读取:不发网络\n * 请求、不触发 OAuth 刷新(凭据检查与 ModelRuntime.hasConfiguredAuth 同构——\n * 只读\"该 provider 是否有凭据条目\",不做可用性探测)。\n */\nexport interface ProviderFailoverPreflightChecks {\n\t/** 目录解析,与运行时换道候选解析同一面。 */\n\treadonly resolveModel: (provider: string, modelId: string) => Model<Api> | undefined;\n\t/** provider 在组合目录(builtin + models.json + 扩展)中存在(backupProviders 层预检)。 */\n\treadonly hasProvider: (providerId: string) => boolean;\n\t/** provider 有凭据条目(静态;不触发 OAuth 刷新)。 */\n\treadonly hasConfiguredAuth: (providerId: string) => boolean;\n}\n\n/**\n * 稳定序列化(键排序、剔除 undefined):compat/thinkingLevelMap 的派生差异按\n * 值比较,不依赖对象键序。\n */\nfunction stableStringify(value: unknown): string {\n\tif (value === undefined) return \"∅\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value) ?? String(value);\n\tif (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, entryValue]) => entryValue !== undefined)\n\t\t.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n\treturn `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`).join(\",\")}}`;\n}\n\n/**\n * 显式链全量预检(设计 §4.6):每个 backup 逐一检查,失败条目从链中剔除并\n * 警告;主不可解析 → 整链跳过。contextWindow/compat/thinkingLevelMap/maxTokens\n * 差异只进警告清单、不硬拦——实施裁量:contextWindow 低于主的备用对小上下文\n * 请求仍可成功,剔除条目会静默损失兜底;只有上下文逼近主窗口的请求才必失败,\n * 该情形运行时走链内下一候选,有界。\n */\nfunction preflightExplicitChain(\n\tchain: FailoverChainDeclaration,\n\tchecks: ProviderFailoverPreflightChecks,\n\twarn: (message: string) => void,\n): FailoverChainDeclaration | undefined {\n\tconst parsedPrimary = parseModelReference(chain.primary);\n\tconst primaryModel =\n\t\tparsedPrimary === undefined ? undefined : checks.resolveModel(parsedPrimary.provider, parsedPrimary.modelId);\n\tif (parsedPrimary === undefined || primaryModel === undefined) {\n\t\twarn(`failover chain \"${chain.primary}\" primary does not resolve in the model catalog; skipping the chain`);\n\t\treturn undefined;\n\t}\n\tconst backups: string[] = [];\n\tfor (const backup of chain.backups) {\n\t\tconst parsed = parseModelReference(backup);\n\t\tconst backupModel = parsed === undefined ? undefined : checks.resolveModel(parsed.provider, parsed.modelId);\n\t\tif (parsed === undefined || backupModel === undefined) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" does not resolve in the model catalog; skipping it`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!checks.hasConfiguredAuth(backupModel.provider)) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup provider \"${backupModel.provider}\" has no configured credentials; skipping \"${backup}\"`,\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (backupModel.contextWindow < primaryModel.contextWindow) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" context window (${backupModel.contextWindow}) is below the primary's (${primaryModel.contextWindow}); contexts sized for the primary may fail on this backup (entry kept)`,\n\t\t\t);\n\t\t}\n\t\tif (backupModel.maxTokens !== primaryModel.maxTokens) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" maxTokens (${backupModel.maxTokens}) differs from the primary's (${primaryModel.maxTokens}); output budget may change after switching`,\n\t\t\t);\n\t\t}\n\t\tif (stableStringify(backupModel.compat) !== stableStringify(primaryModel.compat)) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" compat differs from the primary's; request derivation may change after switching`,\n\t\t\t);\n\t\t}\n\t\tif (stableStringify(backupModel.thinkingLevelMap) !== stableStringify(primaryModel.thinkingLevelMap)) {\n\t\t\twarn(\n\t\t\t\t`failover chain \"${chain.primary}\" backup \"${backup}\" thinkingLevelMap differs from the primary's; reasoning level mapping may change after switching`,\n\t\t\t);\n\t\t}\n\t\tbackups.push(backup);\n\t}\n\tif (backups.length === 0 && chain.backups.length > 0) {\n\t\twarn(\n\t\t\t`failover chain \"${chain.primary}\" has no usable backups left after preflight; the primary keeps no failover candidates from this chain`,\n\t\t);\n\t}\n\treturn { primary: chain.primary, backups };\n}\n\n/**\n * backupProviders 层预检(设计 §4.6):仅检 provider 存在 + 凭据条目;模型匹配\n * 留运行时(目录同 id 匹配不到时静默跳过,不算失败)。\n */\nfunction preflightBackupProviders(\n\tproviderIds: readonly string[],\n\tchecks: ProviderFailoverPreflightChecks,\n\twarn: (message: string) => void,\n): string[] {\n\tconst retained: string[] = [];\n\tfor (const providerId of providerIds) {\n\t\tif (!checks.hasProvider(providerId)) {\n\t\t\twarn(`failover.backupProviders entry \"${providerId}\" is not a known provider; skipping it`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!checks.hasConfiguredAuth(providerId)) {\n\t\t\twarn(`failover.backupProviders entry \"${providerId}\" has no configured credentials; skipping it`);\n\t\t\tcontinue;\n\t\t}\n\t\tretained.push(providerId);\n\t}\n\treturn retained;\n}\n\n/**\n * 装载预检主体:返回过滤后的派生配置(预检失败条目已从候选源剔除)。不改变\n * 运行时换道判定——过滤只发生在装载期,运行时候选解析逻辑不变。\n */\nfunction runProviderFailoverPreflight(\n\tconfig: ResolvedFailoverConfig,\n\tchecks: ProviderFailoverPreflightChecks,\n\twarn: (message: string) => void,\n): ResolvedFailoverConfig {\n\tconst backupProviders = preflightBackupProviders(config.backupProviders, checks, warn);\n\tconst chains: FailoverChainDeclaration[] = [];\n\tfor (const chain of config.chains) {\n\t\tconst preflighted = preflightExplicitChain(chain, checks, warn);\n\t\tif (preflighted !== undefined) chains.push(preflighted);\n\t}\n\treturn { ...config, backupProviders, chains };\n}\n\n// ---------------------------------------------------------------------------\n// 装配\n// ---------------------------------------------------------------------------\n\nexport interface ProviderFailoverInstallOptions {\n\t/** settings `failover` 节的原始合并值(经 readProviderFailoverSettingsNode 读取)。 */\n\treadonly failoverSettings: unknown;\n\t/**\n\t * 装载预检宿主检查面(设计 §4.6):全部静态读取,零网络、零 OAuth 刷新。\n\t * 必传——预检是安装契约的一部分,宿主缺失检查面时不应静默退化为无预检。\n\t */\n\treadonly preflight: ProviderFailoverPreflightChecks;\n\t/** 注入时钟(测试用确定性时间);缺省 Date.now。 */\n\treadonly now?: () => number;\n\t/** 宿主进程日志;缺省时配置警告静默丢弃。 */\n\treadonly hostLogger?: HostLogger;\n}\n\n/**\n * 装配嵌入式 provider-failover 插件(设计 §4.8)。\n *\n * - 未配置 / `enabled: false` / 配置错误(已警告)→ 返回 undefined,不注册任何面。\n * - 配置解析完成后同步执行装载预检(设计 §4.6):失败条目从候选源剔除并警告,\n * 警告经模块级去重每进程至多一次;预检不阻断其余条目与主 provider 的正常使用。\n * - 宿主侧装配失败由调用方兜底(failover 是可靠性能力,装载失败不得阻断会话)。\n * - 熔断状态是模块级单例:本函数跨会话重复调用注册的是新包装器实例,但共享\n * 同一份状态(设计 §4.2)。\n */\nexport function installProviderFailoverPlugin(\n\truntime: CapabilityRuntime,\n\toptions: ProviderFailoverInstallOptions,\n): CapabilityPluginHandle | undefined {\n\tconst warn =\n\t\toptions.hostLogger === undefined\n\t\t\t? (_message: string) => {}\n\t\t\t: (message: string) => {\n\t\t\t\t\toptions.hostLogger?.warn(\"provider-failover\", message);\n\t\t\t\t};\n\tconst config = parseProviderFailoverConfig(options.failoverSettings, warn);\n\tif (config === undefined) return undefined;\n\tconst warnPreflightOnce = (message: string): void => {\n\t\tif (preflightWarnedMessages.has(message)) return;\n\t\tpreflightWarnedMessages.add(message);\n\t\twarn(message);\n\t};\n\tconst preflighted = runProviderFailoverPreflight(config, options.preflight, warnPreflightOnce);\n\tconst now = options.now ?? (() => Date.now());\n\treturn loadCapabilityPluginSync(\n\t\truntime,\n\t\t{\n\t\t\tid: PROVIDER_FAILOVER_PLUGIN_ID,\n\t\t\tversion: \"0.0.0\",\n\t\t\tapiVersion: EXPERIMENTAL_PUBLIC_API_VERSION,\n\t\t\tentry: \"<embedded:provider-failover>\",\n\t\t},\n\t\t(api) => {\n\t\t\t// 快照通道绑定本会话的公共 session 面(宿主声明 session feature 时在场):\n\t\t\t// 会话 A 触发的熔断只写进 A 的日志,footer 可见性是会话局部的(设计 §4.7\n\t\t\t// 保真度限制)。deps 须在此构建——api 只在工厂内可得。\n\t\t\tconst deps: ProviderFailoverRuntimeDeps = {\n\t\t\t\truntime,\n\t\t\t\tconfig: preflighted,\n\t\t\t\tnow,\n\t\t\t\tsession: api.session,\n\t\t\t\t...(options.hostLogger === undefined ? {} : { hostLogger: options.hostLogger }),\n\t\t\t};\n\t\t\tapi.registerStreamFnWrapper(PROVIDER_FAILOVER_WRAPPER_NAME, createFailoverWrapper(deps));\n\t\t\t// 装配期初始快照(status closed)覆盖恢复会话里的陈旧 open 残留:熔断\n\t\t\t// 状态不持久化,新进程恒 CLOSED(设计 §4.2/§4.7)。无链上下文 → chainId 空。\n\t\t\twriteStateSnapshot(deps, { version: 1, chainId: \"\", status: \"closed\", probeAtMs: 0, now: deps.now() });\n\t\t},\n\t);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAGzD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAK5C,OAAO,EAIN,KAAK,WAAW,EAGhB,MAAM,sBAAsB,CAAC;AAI9B,OAAO,KAAK,EAAE,cAAc,EAA+C,MAAM,sBAAsB,CAAC;AAExG,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAkBxG,QAAA,MAAM,UAAU;;;EAGd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;;;OAOG;IACH,IAAI,EAAE,CACL,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;QACR,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;QAC/B,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;KACxB,KACG,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC;CAC1C;AAED,iEAAiE;AACjE,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,WAAW,GAA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,SAAS,EAAE,eAAe,CAAC,CA0LjF;AAYD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAEjF;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAQnG","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { constants as osConstants } from \"node:os\";\nimport type { AgentTool } from \"@agent-forge/agent-core\";\nimport { Container, Text, truncateToWidth } from \"@agent-forge/tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { t } from \"../i18n/index.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport type { ToolDefinition, ToolExecuteContext, ToolRenderResultOptions } from \"./tool-definition.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(t(\"Invalid timeout: must be a finite number of seconds\"));\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(t(\"Invalid timeout: maximum is {maxSeconds} seconds\", { maxSeconds: MAX_TIMEOUT_SECONDS }));\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect AGENT_FORGE_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to the exit code. Report signal terminations as 128 + signal number;\n\t * a null exit code is treated as a failed command.\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tt(\"Working directory does not exist: {cwd}\\nCannot execute {shellName} commands.\", {\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tshellName,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\t// A signal-killed shell has no exit code. Use the standard shell convention so\n\t\t\t\t// callers do not mistake the termination for a successful command.\n\t\t\t\tconst signalCode = child.signalCode;\n\t\t\t\treturn { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using Agent Forge's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want Agent Forge's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ToolExecuteContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.AGENT_FORGE_SESSION_ID;\n\tdelete env.AGENT_FORGE_SESSION_FILE;\n\tdelete env.AGENT_FORGE_PROVIDER;\n\tdelete env.AGENT_FORGE_MODEL;\n\tdelete env.AGENT_FORGE_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.AGENT_FORGE_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.AGENT_FORGE_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.AGENT_FORGE_PROVIDER = model.provider;\n\t\t\tenv.AGENT_FORGE_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.AGENT_FORGE_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Agent Forge session metadata as AGENT_FORGE_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\tconst seconds = ms / 1000;\n\tif (seconds < 60) return `${seconds.toFixed(1)}s`;\n\n\tconst totalSeconds = Math.floor(seconds);\n\tconst minutes = Math.floor(totalSeconds / 60);\n\tconst remainder = totalSeconds % 60;\n\tif (minutes < 60) return `${minutes}m ${remainder}s`;\n\n\treturn `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;\n}\n\nfunction formatShellCall(args: { command?: string; timeout?: number } | undefined, prompt: string): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\t// Cache the complete output: this renders on every frame for every bash result in the transcript.\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tconst hintLines: string[] = [];\n\t\t\t\t\t\tif (preview.skippedCount > 0) {\n\t\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${preview.skippedCount} earlier lines,`) +\n\t\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\t\thintLines.push(truncateToWidth(hint, width, \"...\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.cachedLines = [\"\", ...hintLines, ...preview.visualLines];\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\treturn state.cachedLines;\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?: ToolExecuteContext,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\tresolvedCommand,\n\t\t\t\tctx?.cwd || cwd,\n\t\t\t\tspawnHook,\n\t\t\t\texposeSessionEnvironment,\n\t\t\t\tctx,\n\t\t\t);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, t(\"Command aborted\")));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\tappendStatus(text, t(\"Command timed out after {seconds} seconds\", { seconds: timeoutSecs })),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode === null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, t(\"Command terminated without an exit code\")));\n\t\t\t\t}\n\t\t\t\tif (exitCode !== 0) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, t(\"Command exited with code {exitCode}\", { exitCode })));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"agent-forge-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}