@ai-agent-forge/plugin-provider-failover 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.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @agent-forge/plugin-provider-failover
2
+
3
+ Agent Forge 出厂默认 provider 主备切换插件(显式链与 `backupProviders`、模块级熔断状态机、提交边界内的无感重放与凭据剔除),bundled 分发,宿主通过 manifest 加载并经 `api.registerStreamFnWrapper`(`priority: -100`,链最外层)挂进默认 stream 装配(D-082 批 3b,迁自内核内嵌实现 `packages/agent-forge/src/core/extensions/provider-failover.ts`)。
4
+
5
+ 配置经宿主 config 注入通道递交:`{ version: 1, failover: <settings failover 节原样> }`;无注入 = 插件 no-op。装载预检消费 `api.host.modelCatalog` 宿主服务(目录解析/provider 存在/凭据条目),配置了 failover 而宿主未提供 modelCatalog 时 fail-loud。
@@ -0,0 +1,19 @@
1
+ {
2
+ "packageFormatVersion": 1,
3
+ "id": "agent-forge.plugin.provider-failover",
4
+ "pluginVersion": "0.88.1",
5
+ "apiVersion": "1",
6
+ "minHostVersion": "0.88.0",
7
+ "platform": {
8
+ "os": [
9
+ "windows",
10
+ "macos",
11
+ "linux"
12
+ ],
13
+ "runtime": [
14
+ {
15
+ "name": "node"
16
+ }
17
+ ]
18
+ }
19
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Manifest 通道默认导出工厂(hostVersion >=0.88.0 宿主经 plugin.json 装载,
3
+ * D-082)。生产形态零参:时钟缺省 Date.now,进程日志适配 `api.logger`;配置
4
+ * 经宿主 config 注入通道递交,无 `failover` 节 = no-op。
5
+ */
6
+ declare const _default: import("@agent-forge/plugin-sdk").CapabilityPluginSyncFactory;
7
+ export default _default;
8
+ //# sourceMappingURL=entry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry.d.ts","sourceRoot":"","sources":["../src/entry.ts"],"names":[],"mappings":"AAEA;;;;GAIG;;AACH,wBAAqD","sourcesContent":["import { createProviderFailoverPluginFactory } from \"./provider-failover.ts\";\n\n/**\n * Manifest 通道默认导出工厂(hostVersion >=0.88.0 宿主经 plugin.json 装载,\n * D-082)。生产形态零参:时钟缺省 Date.now,进程日志适配 `api.logger`;配置\n * 经宿主 config 注入通道递交,无 `failover` 节 = no-op。\n */\nexport default createProviderFailoverPluginFactory();\n"]}
package/dist/entry.js ADDED
@@ -0,0 +1,8 @@
1
+ import { createProviderFailoverPluginFactory } from "./provider-failover.js";
2
+ /**
3
+ * Manifest 通道默认导出工厂(hostVersion >=0.88.0 宿主经 plugin.json 装载,
4
+ * D-082)。生产形态零参:时钟缺省 Date.now,进程日志适配 `api.logger`;配置
5
+ * 经宿主 config 注入通道递交,无 `failover` 节 = no-op。
6
+ */
7
+ export default createProviderFailoverPluginFactory();
8
+ //# sourceMappingURL=entry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry.js","sourceRoot":"","sources":["../src/entry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAE7E;;;;GAIG;AACH,eAAe,mCAAmC,EAAE,CAAC","sourcesContent":["import { createProviderFailoverPluginFactory } from \"./provider-failover.ts\";\n\n/**\n * Manifest 通道默认导出工厂(hostVersion >=0.88.0 宿主经 plugin.json 装载,\n * D-082)。生产形态零参:时钟缺省 Date.now,进程日志适配 `api.logger`;配置\n * 经宿主 config 注入通道递交,无 `failover` 节 = no-op。\n */\nexport default createProviderFailoverPluginFactory();\n"]}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * 第一方 provider 主备切换插件(设计:docs/design/供应商能力槽位与主备切换设计.md §4;
3
+ * D-082 批 3b 自内核内嵌实现逐字迁出为独立插件包)。
4
+ *
5
+ * 形态与 bootstrap-retry 同族——经公共 `api.registerStreamFnWrapper` 注册面挂进
6
+ * 宿主默认 stream 装配,`{ priority: -100 }` 固定链最外层(与装载顺序无关)——但
7
+ * 熔断状态是**模块级单例**(设计 §4.2):进程内所有会话与 subagent 共享同一份,
8
+ * 不随会话 dispose,不持久化(重启后全部 CLOSED)。
9
+ *
10
+ * 判定哲学(设计 §2):只看流终态 done/error/aborted 与"是否已向上层释放内容
11
+ * 增量"两个本地事实,不解读错误类型/错误码语义;原始 errorMessage 照透传保留,
12
+ * 只用于事件归因与 diagnostics,不参与机器判定分支。aborted 不计数、不换道、
13
+ * 状态不变。换道从第一次失败即发生;`failureThreshold` 只控制"是否继续先撞主"
14
+ * (连续 N 次后熔断打开,请求直接落备用,冷却期满后以真实请求试探回主)。
15
+ *
16
+ * 与内嵌装配的公共面差异(迁移登记,行为等价):
17
+ * - 配置不再经 SettingsManager 读取:宿主经 manifest config 通道注入
18
+ * `{ version: 1, failover: <settings failover 节原样> }`;`api.config` 无
19
+ * failover 节 = 未配置,工厂直接 return(不注册任何面)。
20
+ * - 装载预检检查面改从 `api.host.modelCatalog`(plugin-sdk `ModelCatalogV1`)
21
+ * 结构获取;配置了 failover 而宿主未注入 modelCatalog 时 fail-loud 抛错
22
+ * (与"settings 有 failover 但宿主不支持"同态,不静默降级)。
23
+ * - 插件面 `LifecycleAPI` 无 hasLifecycleEvent/dispatchLifecycle(与原内嵌第一参
24
+ * `CapabilityRuntime` 的同名方法不同构):目录 gate 以 `api.lifecycle.get` 的
25
+ * 抛错/命中等价实现(宿主未定义该事件 = 零派发);派发走公共 `api.publish`
26
+ * 事件总线(source 由运行时归属插件 manifest id;Envelope 无 phase 字段——
27
+ * 本插件的可见性事件全部是 committed 相位)。
28
+ * - 进程日志走 `api.logger`(plugin-sdk `LoggerAPI`)或工厂注入的同形 deps;
29
+ * warn 文案逐字保留。
30
+ */
31
+ import type { CapabilityPluginSyncFactory, ModelCatalogModelViewV1 } from "@agent-forge/plugin-sdk";
32
+ /** plugin.json 的 manifest id(原内嵌形态的 `agent-forge.provider-failover` 随内嵌装配退役)。 */
33
+ export declare const PROVIDER_FAILOVER_PLUGIN_ID = "agent-forge.plugin.provider-failover";
34
+ export declare const PROVIDER_FAILOVER_WRAPPER_NAME = "provider-failover";
35
+ /**
36
+ * 可见性事件的 id/version:与宿主 lifecycle-catalog.ts 的 provider.failover.*
37
+ * 常量逐字同值。插件包不可 import 宿主内部模块(D-075 §0 边界白名单),此处
38
+ * 本地声明;宿主未在 lifecycle 目录定义同名事件时 `api.lifecycle.get` 抛错,
39
+ * gate 关闭、零派发(值漂移因此被发现而不是静默错投)。
40
+ */
41
+ export declare const PROVIDER_FAILOVER_SWITCHED_EVENT_ID = "provider.failover.switched";
42
+ export declare const PROVIDER_FAILOVER_SWITCHED_EVENT_VERSION = 1;
43
+ export declare const PROVIDER_FAILOVER_RECOVERED_EVENT_ID = "provider.failover.recovered";
44
+ export declare const PROVIDER_FAILOVER_RECOVERED_EVENT_VERSION = 1;
45
+ export declare const PROVIDER_FAILOVER_PROBE_FAILED_EVENT_ID = "provider.failover.probe.failed";
46
+ export declare const PROVIDER_FAILOVER_PROBE_FAILED_EVENT_VERSION = 1;
47
+ /**
48
+ * 会话日志快照通道的 customType(设计 §4.7 Phase 3):插件经公共
49
+ * `api.session.appendEntry` 在状态转移点写入快照,footer 每帧取最后一条渲染
50
+ * 摘要行——与 goal.state / todo.state / workflow.state 同构,零新公共面。
51
+ */
52
+ export declare const PROVIDER_FAILOVER_STATE_ENTRY_TYPE = "provider.failover.state";
53
+ /** `provider.failover.state` 快照负载(footer 按最后一条渲染)。 */
54
+ export interface ProviderFailoverStateSnapshot {
55
+ readonly version: 1;
56
+ /** 主链引用 `provider/modelId`;装配期初始快照无链上下文,为空串。 */
57
+ readonly chainId: string;
58
+ readonly status: "closed" | "open" | "half-open";
59
+ /** 当前换道目标引用 `provider/modelId`(OPEN 期请求从链头重走);closed 省略。 */
60
+ readonly backupProvider?: string;
61
+ /** 下次试探时间戳 = open 时刻 + 当前冷却;closed 为 0。 */
62
+ readonly probeAtMs: number;
63
+ /** 快照写入时刻(注入时钟友好)。 */
64
+ readonly now: number;
65
+ }
66
+ interface FailoverChainDeclaration {
67
+ readonly primary: string;
68
+ readonly backups: readonly string[];
69
+ }
70
+ interface ResolvedFailoverConfig {
71
+ /** 试探失败冷却起点(也是回 CLOSED 后的重置值)。 */
72
+ readonly cooldownInitialMs: number;
73
+ readonly cooldownMaxMs: number;
74
+ readonly failureThreshold: number;
75
+ readonly backupProviders: readonly string[];
76
+ readonly chains: readonly FailoverChainDeclaration[];
77
+ }
78
+ /**
79
+ * 解析 settings `failover` 节。返回 undefined = 无 failover(未配置 / 无有效
80
+ * backupProviders 与 chains / 配置错误拒绝加载——后者附带一条警告,设计 §4.1
81
+ * "重复 primary 拒绝加载并警告")。`failover.enabled` 开关已移除(2026-10-03
82
+ * D-079):节点存在即装配,残留 `enabled` 键只警告并忽略,按其余字段正常解析。
83
+ */
84
+ export declare function parseProviderFailoverConfig(raw: unknown, warn: (message: string) => void): ResolvedFailoverConfig | undefined;
85
+ /** 测试隔离钩子:清空模块级熔断单例与预检警告去重集(仅测试使用)。 */
86
+ export declare function resetProviderFailoverStateForTests(): void;
87
+ /** 进程日志警告面(插件局部形状):工厂 deps 可注入(测试确定性),缺省适配 `api.logger`。 */
88
+ export interface ProviderFailoverHostLogger {
89
+ warn(message: string, context?: {
90
+ readonly cause?: unknown;
91
+ }): void;
92
+ }
93
+ /**
94
+ * 装载预检的宿主静态检查面(设计 §4.6)。全部为目录/凭据快照读取:不发网络
95
+ * 请求、不触发 OAuth 刷新(凭据检查与原内嵌装配的 ModelRuntime.hasConfiguredAuth
96
+ * 同构——只读"该 provider 是否有凭据条目",不做可用性探测)。与原内嵌形态的
97
+ * 类型差异:resolveModel 返回 plugin-sdk `ModelCatalogModelViewV1`(provider/
98
+ * contextWindow/maxTokens/compat/thinkingLevelMap 五字段视图)而非 `Model<Api>`,
99
+ * 即 P1 契约 `ModelCatalogV1` 的对应面。
100
+ */
101
+ export interface ProviderFailoverPreflightChecks {
102
+ /** 目录解析,与运行时换道候选解析同一面。 */
103
+ readonly resolveModel: (provider: string, modelId: string) => ModelCatalogModelViewV1 | undefined;
104
+ /** provider 在组合目录(builtin + models.json + 扩展)中存在(backupProviders 层预检)。 */
105
+ readonly hasProvider: (providerId: string) => boolean;
106
+ /** provider 有凭据条目(静态;不触发 OAuth 刷新)。 */
107
+ readonly hasConfiguredAuth: (providerId: string) => boolean;
108
+ }
109
+ export interface ProviderFailoverPluginFactoryDeps {
110
+ /** 注入时钟(测试用确定性时间);缺省 Date.now。 */
111
+ readonly now?: () => number;
112
+ /** 进程日志;缺省适配 `api.logger`(宿主未声明 logger-v1 时配置警告静默丢弃)。 */
113
+ readonly hostLogger?: ProviderFailoverHostLogger;
114
+ }
115
+ /**
116
+ * 构建 provider-failover 插件工厂(设计 §4.8 的插件包形态):
117
+ * `(api: CapabilityAPI) => void`,经公共 `loadCapabilityPlugin`/manifest 通道装载。
118
+ * deps 仅用于测试注入时钟与进程日志;生产入口(entry.ts 默认导出)零参调用。
119
+ */
120
+ export declare function createProviderFailoverPluginFactory(deps?: ProviderFailoverPluginFactoryDeps): CapabilityPluginSyncFactory;
121
+ export {};
122
+ //# sourceMappingURL=provider-failover.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-failover.d.ts","sourceRoot":"","sources":["../src/provider-failover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAaH,OAAO,KAAK,EAEX,2BAA2B,EAG3B,uBAAuB,EAGvB,MAAM,yBAAyB,CAAC;AAEjC,mHAAiF;AACjF,eAAO,MAAM,2BAA2B,yCAAyC,CAAC;AAClF,eAAO,MAAM,8BAA8B,sBAAsB,CAAC;AAElE;;;;;GAKG;AACH,eAAO,MAAM,mCAAmC,+BAA+B,CAAC;AAChF,eAAO,MAAM,wCAAwC,IAAI,CAAC;AAC1D,eAAO,MAAM,oCAAoC,gCAAgC,CAAC;AAClF,eAAO,MAAM,yCAAyC,IAAI,CAAC;AAC3D,eAAO,MAAM,uCAAuC,mCAAmC,CAAC;AACxF,eAAO,MAAM,4CAA4C,IAAI,CAAC;AAE9D;;;;GAIG;AACH,eAAO,MAAM,kCAAkC,4BAA4B,CAAC;AAE5E,kFAAsD;AACtD,MAAM,WAAW,6BAA6B;IAC7C,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;IACpB,4FAAgD;IAChD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;IACjD,wGAA4D;IAC5D,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,2EAA2C;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,oDAAsB;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB;AAcD,UAAU,wBAAwB;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAED,UAAU,sBAAsB;IAC/B,wEAAkC;IAClC,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,SAAS,wBAAwB,EAAE,CAAC;CACrD;AA8CD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAC1C,GAAG,EAAE,OAAO,EACZ,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC7B,sBAAsB,GAAG,SAAS,CAyFpC;AAsBD,uGAAuC;AACvC,wBAAgB,kCAAkC,IAAI,IAAI,CAGzD;AA4GD,gIAA4D;AAC5D,MAAM,WAAW,0BAA0B;IAC1C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;CACpE;AA0WD;;;;;;;GAOG;AACH,MAAM,WAAW,+BAA+B;IAC/C,gEAA0B;IAC1B,QAAQ,CAAC,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,uBAAuB,GAAG,SAAS,CAAC;IAClG,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,iCAAiC;IACjD,sEAAkC;IAClC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B,6GAAyD;IACzD,QAAQ,CAAC,UAAU,CAAC,EAAE,0BAA0B,CAAC;CACjD;AA8GD;;;;GAIG;AACH,wBAAgB,mCAAmC,CAClD,IAAI,GAAE,iCAAsC,GAC1C,2BAA2B,CAI7B","sourcesContent":["/**\n * 第一方 provider 主备切换插件(设计:docs/design/供应商能力槽位与主备切换设计.md §4;\n * D-082 批 3b 自内核内嵌实现逐字迁出为独立插件包)。\n *\n * 形态与 bootstrap-retry 同族——经公共 `api.registerStreamFnWrapper` 注册面挂进\n * 宿主默认 stream 装配,`{ priority: -100 }` 固定链最外层(与装载顺序无关)——但\n * 熔断状态是**模块级单例**(设计 §4.2):进程内所有会话与 subagent 共享同一份,\n * 不随会话 dispose,不持久化(重启后全部 CLOSED)。\n *\n * 判定哲学(设计 §2):只看流终态 done/error/aborted 与\"是否已向上层释放内容\n * 增量\"两个本地事实,不解读错误类型/错误码语义;原始 errorMessage 照透传保留,\n * 只用于事件归因与 diagnostics,不参与机器判定分支。aborted 不计数、不换道、\n * 状态不变。换道从第一次失败即发生;`failureThreshold` 只控制\"是否继续先撞主\"\n * (连续 N 次后熔断打开,请求直接落备用,冷却期满后以真实请求试探回主)。\n *\n * 与内嵌装配的公共面差异(迁移登记,行为等价):\n * - 配置不再经 SettingsManager 读取:宿主经 manifest config 通道注入\n * `{ version: 1, failover: <settings failover 节原样> }`;`api.config` 无\n * failover 节 = 未配置,工厂直接 return(不注册任何面)。\n * - 装载预检检查面改从 `api.host.modelCatalog`(plugin-sdk `ModelCatalogV1`)\n * 结构获取;配置了 failover 而宿主未注入 modelCatalog 时 fail-loud 抛错\n * (与\"settings 有 failover 但宿主不支持\"同态,不静默降级)。\n * - 插件面 `LifecycleAPI` 无 hasLifecycleEvent/dispatchLifecycle(与原内嵌第一参\n * `CapabilityRuntime` 的同名方法不同构):目录 gate 以 `api.lifecycle.get` 的\n * 抛错/命中等价实现(宿主未定义该事件 = 零派发);派发走公共 `api.publish`\n * 事件总线(source 由运行时归属插件 manifest id;Envelope 无 phase 字段——\n * 本插件的可见性事件全部是 committed 相位)。\n * - 进程日志走 `api.logger`(plugin-sdk `LoggerAPI`)或工厂注入的同形 deps;\n * warn 文案逐字保留。\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 {\n\tCapabilityAPI,\n\tCapabilityPluginSyncFactory,\n\tLifecycleDispatchRequest,\n\tLoggerAPI,\n\tModelCatalogModelViewV1,\n\tSessionAPI,\n\tStreamFnWrapper,\n} from \"@agent-forge/plugin-sdk\";\n\n/** plugin.json 的 manifest id(原内嵌形态的 `agent-forge.provider-failover` 随内嵌装配退役)。 */\nexport const PROVIDER_FAILOVER_PLUGIN_ID = \"agent-forge.plugin.provider-failover\";\nexport const PROVIDER_FAILOVER_WRAPPER_NAME = \"provider-failover\";\n\n/**\n * 可见性事件的 id/version:与宿主 lifecycle-catalog.ts 的 provider.failover.*\n * 常量逐字同值。插件包不可 import 宿主内部模块(D-075 §0 边界白名单),此处\n * 本地声明;宿主未在 lifecycle 目录定义同名事件时 `api.lifecycle.get` 抛错,\n * gate 关闭、零派发(值漂移因此被发现而不是静默错投)。\n */\nexport const PROVIDER_FAILOVER_SWITCHED_EVENT_ID = \"provider.failover.switched\";\nexport const PROVIDER_FAILOVER_SWITCHED_EVENT_VERSION = 1;\nexport const PROVIDER_FAILOVER_RECOVERED_EVENT_ID = \"provider.failover.recovered\";\nexport const PROVIDER_FAILOVER_RECOVERED_EVENT_VERSION = 1;\nexport const PROVIDER_FAILOVER_PROBE_FAILED_EVENT_ID = \"provider.failover.probe.failed\";\nexport const PROVIDER_FAILOVER_PROBE_FAILED_EVENT_VERSION = 1;\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 * backupProviders 与 chains / 配置错误拒绝加载——后者附带一条警告,设计 §4.1\n * \"重复 primary 拒绝加载并警告\")。`failover.enabled` 开关已移除(2026-10-03\n * D-079):节点存在即装配,残留 `enabled` 键只警告并忽略,按其余字段正常解析。\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 !== undefined) {\n\t\twarn(\"failover.enabled was removed (2026-10-03): the failover node installs whenever configured; remove the key\");\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// 熔断状态机(模块级单例,设计 §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\n/** 进程日志警告面(插件局部形状):工厂 deps 可注入(测试确定性),缺省适配 `api.logger`。 */\nexport interface ProviderFailoverHostLogger {\n\twarn(message: string, context?: { readonly cause?: unknown }): void;\n}\n\ninterface ProviderFailoverRuntimeDeps {\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?: ProviderFailoverHostLogger;\n\t/**\n\t * 事件目录 gate(`api.lifecycle.get` 命中/抛错等价原 hasLifecycleEvent):\n\t * 宿主未在 lifecycle 目录定义该事件 = 零派发。\n\t */\n\treadonly hasLifecycleEvent: (type: string, version: number) => boolean;\n\t/** 尽力派发(`api.publish` 等价面;失败只吞掉,不打断换道判定)。 */\n\treadonly dispatchLifecycleEvent: (request: LifecycleDispatchRequest) => void;\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(\"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.hasLifecycleEvent(request.type, request.version)) return;\n\t\tdeps.dispatchLifecycleEvent(request);\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\t// 事件总线 correlationId 取链引用(workflow.changed 同款领域键模式)。\n\t\t\t\t\t\tcorrelationId: chainId,\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\t// 事件总线 correlationId 取链引用(workflow.changed 同款领域键模式)。\n\t\t\t\tcorrelationId: chainId,\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\t// 事件总线 correlationId 取链引用(workflow.changed 同款领域键模式)。\n\t\tcorrelationId: chainId,\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 * 类型差异:resolveModel 返回 plugin-sdk `ModelCatalogModelViewV1`(provider/\n * contextWindow/maxTokens/compat/thinkingLevelMap 五字段视图)而非 `Model<Api>`,\n * 即 P1 契约 `ModelCatalogV1` 的对应面。\n */\nexport interface ProviderFailoverPreflightChecks {\n\t/** 目录解析,与运行时换道候选解析同一面。 */\n\treadonly resolveModel: (provider: string, modelId: string) => ModelCatalogModelViewV1 | 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 ProviderFailoverPluginFactoryDeps {\n\t/** 注入时钟(测试用确定性时间);缺省 Date.now。 */\n\treadonly now?: () => number;\n\t/** 进程日志;缺省适配 `api.logger`(宿主未声明 logger-v1 时配置警告静默丢弃)。 */\n\treadonly hostLogger?: ProviderFailoverHostLogger;\n}\n\n/** wrapper 注册优先级:低值更外层;-100 保证 failover 恒在链最外层(与装载顺序无关)。 */\nconst PROVIDER_FAILOVER_WRAPPER_PRIORITY = -100;\n\n/** 适配 `api.logger`(plugin-sdk LoggerAPI)为插件的进程日志警告面;未声明 logger-v1 时缺席。 */\nfunction hostLoggerFromApi(api: CapabilityAPI): ProviderFailoverHostLogger | undefined {\n\tconst logger: LoggerAPI | undefined = api.logger;\n\tif (logger === undefined) return undefined;\n\treturn {\n\t\twarn: (message, context) => {\n\t\t\tconst cause = context?.cause;\n\t\t\t// LoggerAPI.warn 不带 cause 形参:cause 归一为单行文本进 fields。\n\t\t\tlogger.warn(message, cause === undefined ? undefined : { cause: describeCause(cause) });\n\t\t},\n\t};\n}\n\nfunction describeCause(cause: unknown): string {\n\tif (cause instanceof Error) return cause.message === \"\" ? cause.name : `${cause.name}: ${cause.message}`;\n\treturn String(cause);\n}\n\n/**\n * 把插件装配进一个已构建的 `CapabilityAPI`(公共面;工厂与测试共用同一代码路径):\n *\n * - `api.config` 无 `failover` 节(宿主未注入)→ 直接 return,不注册任何面;\n * 残留 `failover.enabled` 键只警告并忽略(已移除,2026-10-03 D-079),节点按\n * 其余字段正常解析装配。\n * - 配置了解析后:宿主必须注入 `api.host.modelCatalog`(装载预检检查面来源),\n * 缺席 = \"settings 有 failover 但宿主不支持\"——fail-loud 抛错,不静默降级。\n * - 配置解析完成后同步执行装载预检(设计 §4.6):失败条目从候选源剔除并警告,\n * 警告经模块级去重每进程至多一次;预检不阻断其余条目与主 provider 的正常使用。\n * - 熔断状态是模块级单例:本工厂跨会话重复调用注册的是新包装器实例,但共享\n * 同一份状态(设计 §4.2)。\n */\nfunction installProviderFailoverIntoApi(api: CapabilityAPI, deps: ProviderFailoverPluginFactoryDeps): void {\n\tconst logger = deps.hostLogger ?? hostLoggerFromApi(api);\n\tconst warn =\n\t\tlogger === undefined\n\t\t\t? (_message: string) => {}\n\t\t\t: (message: string) => {\n\t\t\t\t\tlogger.warn(message);\n\t\t\t\t};\n\t// 注入契约:`{ version: 1, failover: <settings failover 节原样> }`;failover\n\t// 键缺席 = 未配置(no-op)。\n\tconst config = parseProviderFailoverConfig(api.config.failover, warn);\n\tif (config === undefined) return;\n\tconst catalog = api.host.modelCatalog;\n\tif (catalog === undefined) {\n\t\tthrow new Error(\n\t\t\t\"provider failover is configured but the host does not provide the modelCatalog capability service (api.host.modelCatalog); the plugin refuses to assemble without install-time preflight\",\n\t\t);\n\t}\n\t// P1 契约:ModelCatalogV1 的检查面(resolveModel/hasProvider/hasConfiguredAuth)\n\t// 与预检 checks 同构,直接结构绑定;契约漂移在此处显式报型。\n\tconst preflight: ProviderFailoverPreflightChecks = catalog;\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, preflight, warnPreflightOnce);\n\tconst now = deps.now ?? (() => Date.now());\n\t// deps 须在此构建——api 只在工厂内可得。\n\tconst runtimeDeps: ProviderFailoverRuntimeDeps = {\n\t\tconfig: preflighted,\n\t\tnow,\n\t\t...(api.session === undefined ? {} : { session: api.session }),\n\t\t...(logger === undefined ? {} : { hostLogger: logger }),\n\t\thasLifecycleEvent: (type, version) => {\n\t\t\ttry {\n\t\t\t\tapi.lifecycle.get(type, version);\n\t\t\t\treturn true;\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t},\n\t\tdispatchLifecycleEvent: (request) => {\n\t\t\t// LifecycleAPI 无 dispatchLifecycle(模块头差异登记):等价公共面 =\n\t\t\t// api.publish。source 由运行时归属本插件 manifest id;phase 不入\n\t\t\t// EventEnvelope(本插件的可见性事件全部是 committed 相位);所有派发点\n\t\t\t// 都带 correlationId = chainId,兜底项仅为满足 LifecycleDispatchRequest\n\t\t\t// 的可选键型。\n\t\t\tvoid api\n\t\t\t\t.publish({\n\t\t\t\t\ttype: request.type,\n\t\t\t\t\tversion: request.version,\n\t\t\t\t\tcorrelationId: request.correlationId ?? request.type,\n\t\t\t\t\tdata: request.data,\n\t\t\t\t})\n\t\t\t\t.catch(() => {\n\t\t\t\t\t// 可见性事件失败不打断换道判定(宪法 §8 的尽力通道)。\n\t\t\t\t});\n\t\t},\n\t};\n\tapi.registerStreamFnWrapper(PROVIDER_FAILOVER_WRAPPER_NAME, createFailoverWrapper(runtimeDeps), {\n\t\tpriority: PROVIDER_FAILOVER_WRAPPER_PRIORITY,\n\t});\n\t// 装配期初始快照(status closed)覆盖恢复会话里的陈旧 open 残留:熔断\n\t// 状态不持久化,新进程恒 CLOSED(设计 §4.2/§4.7)。无链上下文 → chainId 空。\n\twriteStateSnapshot(runtimeDeps, {\n\t\tversion: 1,\n\t\tchainId: \"\",\n\t\tstatus: \"closed\",\n\t\tprobeAtMs: 0,\n\t\tnow: runtimeDeps.now(),\n\t});\n}\n\n/**\n * 构建 provider-failover 插件工厂(设计 §4.8 的插件包形态):\n * `(api: CapabilityAPI) => void`,经公共 `loadCapabilityPlugin`/manifest 通道装载。\n * deps 仅用于测试注入时钟与进程日志;生产入口(entry.ts 默认导出)零参调用。\n */\nexport function createProviderFailoverPluginFactory(\n\tdeps: ProviderFailoverPluginFactoryDeps = {},\n): CapabilityPluginSyncFactory {\n\treturn (api: CapabilityAPI): void => {\n\t\tinstallProviderFailoverIntoApi(api, deps);\n\t};\n}\n"]}