zerolaunch-plugin-host 0.2.0

ZeroLaunch third-party plugin host — subprocess management and RemotePluginAdapter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! RemoteComponent — 远程插件组件的统一承载结构。
//!
//! 一个逻辑组件对应一个 `RemoteComponent` 实例,同时实现 `Configurable`、
//! `DataSource`、`ActionExecutor`、`Plugin` 四个 trait,消除原先多 adapter
//! 之间对 `RemoteConfigurableAdapter` 的机械委托。

use async_trait::async_trait;
use parking_lot::RwLock;
use std::sync::Arc;
use std::time::Duration;
use zerolaunch_plugin_api::config::{
    ComponentCore, ComponentType, ConfigActionDef, ConfigError, Configurable, SettingDefinition,
};
use zerolaunch_plugin_api::{
    ActionExecutor, CachedCandidateData, CandidateId, DataSource, ExecutionContext, ExecutionError,
    KeywordInjector, KeywordInputSource, KeywordOptimizer, PanelInteraction, Plugin, PluginContext,
    PluginError, PluginHandle, PluginMetadata, Query, QueryResponse, ResultAction, ScoreBooster,
    ScoredCandidate, SearchCandidate, SearchEngine, TargetType,
};

use crate::client::JsonRpcClient;
use zerolaunch_plugin_protocol::messages::*;
use zerolaunch_plugin_protocol::methods::plugin as plugin_methods;
use zerolaunch_plugin_protocol::{codes, ProtocolError};

/// 远程插件组件的种类与专属数据。
///
/// 判断字段归属的标准:
/// - 只有某个种类需要 → 放入对应 variant;
/// - 所有种类都需要(如 Configurable 相关的缓存)→ 保留在 `RemoteComponent` struct 层面。
#[derive(Debug)]
pub enum RemoteComponentKind {
    DataSource,
    ActionExecutor {
        target_types: Vec<TargetType>,
        result_actions: Vec<ResultAction>,
    },
    /// 搜索引擎 —— 参与搜索管道(与内置引擎互斥,仅允许一个启用)。
    SearchEngine,
    Plugin {
        /// 插件级元数据 —— 与 `PluginRegistration.metadata` 共享同一 `Arc`(唯一源),
        /// 由 build_components 一次性构造后不可变。
        metadata: Arc<PluginMetadata>,
        /// 交互策略缓存:discover 拉初始值,查询/设置变更时经 RPC 刷新
        /// (PanelInteraction 是插件级语义——仅 Plugin 组件持有;
        /// 内置插件在每次会话推送时同步求值,远端以此对齐)。
        interaction_policy: RwLock<PanelInteraction>,
    },
    /// 分数增强器 —— 引擎打分后追加分数修正(多个可同时启用)。
    ScoreBooster,
    /// 关键词优化器 —— 候选管道中扩展关键词。
    /// 优化属性(input_source / priority)为声明属性,经 keyword_optimizer_info
    /// RPC 拉取缓存(discover 初始值),设置变更时经 RPC 刷新。
    KeywordOptimizer {
        info: RwLock<KeywordOptimizerInfo>,
    },
    /// 关键词注入器 —— 基于候选项完整上下文注入额外关键词。
    KeywordInjector,
}

pub struct RemoteComponent {
    /// 身份核心。内置插件与远程插件共享同一身份模型。
    pub core: ComponentCore,

    // ── 通信 ──
    pub client: Arc<JsonRpcClient>,

    // ── 私有缓存 ──
    cached_settings: RwLock<serde_json::Value>,
    cached_schema: RwLock<Vec<SettingDefinition>>,
    /// 配置动作缓存。`config_actions()` 是 `Configurable` trait 的通用方法,
    /// 所有组件类型均可能使用,因此放在 struct 层面而非 kind variant 内部。
    cached_actions: RwLock<Vec<ConfigActionDef>>,
    /// 默认启用状态:discover 时经 RPC 拉取(与内置 `default_enabled()` 语义一致)。
    cached_default_enabled: RwLock<bool>,

    // ── 种类与专属数据 ──
    pub kind: RemoteComponentKind,
}

/// Helper: convert a ProtocolError to a ConfigError.
fn to_config_error(e: ProtocolError) -> ConfigError {
    ConfigError::ApplyFailed(e.to_string())
}
impl std::fmt::Debug for RemoteComponent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteComponent")
            .field("core", &self.core)
            .field("cached_settings", &self.cached_settings.read())
            .field("cached_schema", &self.cached_schema.read())
            .field("cached_actions", &self.cached_actions.read())
            .field("kind", &self.kind)
            .finish()
    }
}

impl RemoteComponent {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        component_id: String,
        component_name: String,
        component_description: String,
        component_type: ComponentType,
        priority: u32,
        client: Arc<JsonRpcClient>,
        schema: Vec<SettingDefinition>,
        settings: serde_json::Value,
        actions: Vec<ConfigActionDef>,
        default_enabled: bool,
        kind: RemoteComponentKind,
    ) -> Self {
        Self {
            core: ComponentCore::new(
                component_id,
                component_name,
                component_description,
                component_type,
                priority,
            ),
            client,
            cached_settings: RwLock::new(settings),
            cached_schema: RwLock::new(schema),
            cached_actions: RwLock::new(actions),
            cached_default_enabled: RwLock::new(default_enabled),
            kind,
        }
    }

    /// 将自身转换为 `DataSource` trait object,仅在 kind 为 DataSource 时成功。
    pub fn as_data_source(self: Arc<Self>) -> Option<Arc<dyn DataSource>> {
        matches!(self.kind, RemoteComponentKind::DataSource).then(|| self as Arc<dyn DataSource>)
    }

    /// 将自身转换为 `ActionExecutor` trait object,仅在 kind 为 ActionExecutor 时成功。
    pub fn as_action_executor(self: Arc<Self>) -> Option<Arc<dyn ActionExecutor>> {
        matches!(self.kind, RemoteComponentKind::ActionExecutor { .. })
            .then(|| self as Arc<dyn ActionExecutor>)
    }

    /// 将自身转换为 `Plugin` trait object,仅在 kind 为 Plugin 时成功。
    pub fn as_plugin(self: Arc<Self>) -> Option<Arc<dyn Plugin>> {
        matches!(self.kind, RemoteComponentKind::Plugin { .. }).then(|| self as Arc<dyn Plugin>)
    }
    /// 将自身转换为 `SearchEngine` trait object,仅在 kind 为 SearchEngine 时成功。
    pub fn as_search_engine(self: Arc<Self>) -> Option<Arc<dyn SearchEngine>> {
        matches!(self.kind, RemoteComponentKind::SearchEngine)
            .then(|| self as Arc<dyn SearchEngine>)
    }

    /// 将自身转换为 `ScoreBooster` trait object,仅在 kind 为 ScoreBooster 时成功。
    pub fn as_score_booster(self: Arc<Self>) -> Option<Arc<dyn ScoreBooster>> {
        matches!(self.kind, RemoteComponentKind::ScoreBooster)
            .then(|| self as Arc<dyn ScoreBooster>)
    }

    /// 将自身转换为 `KeywordOptimizer` trait object,仅在 kind 为 KeywordOptimizer 时成功。
    pub fn as_keyword_optimizer(self: Arc<Self>) -> Option<Arc<dyn KeywordOptimizer>> {
        matches!(self.kind, RemoteComponentKind::KeywordOptimizer { .. })
            .then(|| self as Arc<dyn KeywordOptimizer>)
    }

    /// 将自身转换为 `KeywordInjector` trait object,仅在 kind 为 KeywordInjector 时成功。
    pub fn as_keyword_injector(self: Arc<Self>) -> Option<Arc<dyn KeywordInjector>> {
        matches!(self.kind, RemoteComponentKind::KeywordInjector)
            .then(|| self as Arc<dyn KeywordInjector>)
    }

    pub fn is_data_source(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::DataSource)
    }

    pub fn is_action_executor(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::ActionExecutor { .. })
    }

    pub fn is_plugin(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::Plugin { .. })
    }
    /// 是否为搜索引擎组件。
    pub fn is_search_engine(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::SearchEngine)
    }

    /// 是否为分数增强器组件。
    pub fn is_score_booster(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::ScoreBooster)
    }

    /// 是否为关键词优化器组件。
    pub fn is_keyword_optimizer(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::KeywordOptimizer { .. })
    }

    /// 是否为关键词注入器组件。
    pub fn is_keyword_injector(&self) -> bool {
        matches!(self.kind, RemoteComponentKind::KeywordInjector)
    }
}
#[async_trait]
impl Configurable for RemoteComponent {
    fn core(&self) -> &ComponentCore {
        &self.core
    }

    fn setting_schema(&self) -> Vec<SettingDefinition> {
        self.cached_schema.read().clone()
    }

    fn get_settings(&self) -> serde_json::Value {
        self.cached_settings.read().clone()
    }

    fn config_actions(&self) -> Vec<ConfigActionDef> {
        self.cached_actions.read().clone()
    }

    /// 默认启用状态来自插件自声明(discover 时经 RPC 拉取),与内置组件一致。
    fn default_enabled(&self) -> bool {
        *self.cached_default_enabled.read()
    }

    async fn apply_settings(&self, settings: serde_json::Value) -> Result<(), ConfigError> {
        let client = self.client.clone();
        let component_id = self.core.component_id().to_string();
        let settings_clone = settings.clone();
        client
            .call::<_, serde_json::Value>(
                plugin_methods::APPLY_SETTINGS,
                ApplySettingsParams {
                    component_id,
                    settings: settings_clone,
                },
                Duration::from_secs(5),
            )
            .await
            .map_err(to_config_error)?;
        *self.cached_settings.write() = settings;
        // 设置变更可能改变交互策略(如 on-enter 模式开关):
        // 应用成功后立即刷新策略缓存,避免 reemit_current_session 推送旧策略
        // (内置插件每次推送同步求值,远端以此对齐)。
        self.refresh_interaction_policy().await;
        if self.is_keyword_optimizer() {
            self.refresh_keyword_optimizer_info().await;
        }
        Ok(())
    }

    async fn validate_settings(&self, settings: &serde_json::Value) -> Result<(), ConfigError> {
        // 1. 宿主侧 Schema 校验(key 合法性、类型、对象结构、数值/数组约束等)
        //    宿主 Schema 是最终权威,插件校验只能补充不能取代。
        let contribution = self.settings_contribution()?;
        contribution
            .validate_values(settings)
            .map_err(ConfigError::ValidationFailed)?;

        // 2. 插件侧业务校验(通过 RPC 委托远程插件)
        let client = self.client.clone();
        let component_id = self.core.component_id().to_string();
        let settings_clone = settings.clone();
        let result: ValidateSettingsResult = client
            .call(
                plugin_methods::VALIDATE_SETTINGS,
                ValidateSettingsParams {
                    component_id,
                    settings: settings_clone,
                },
                Duration::from_secs(5),
            )
            .await
            .map_err(to_config_error)?;
        if let Some(error) = result.error {
            return Err(ConfigError::ValidationFailed(error));
        }
        Ok(())
    }

    async fn execute_config_action(
        &self,
        action: &str,
        params: &serde_json::Value,
    ) -> Result<serde_json::Value, String> {
        let client = self.client.clone();
        let component_id = self.core.component_id().to_string();
        let action = action.to_string();
        let params = params.clone();
        let result: Result<serde_json::Value, ProtocolError> = client
            .call::<_, serde_json::Value>(
                plugin_methods::EXECUTE_CONFIG_ACTION,
                ExecuteConfigActionParams {
                    component_id,
                    action,
                    params,
                },
                Duration::from_secs(10),
            )
            .await;
        result.map_err(|e| e.to_string())
    }
}

#[async_trait]
impl DataSource for RemoteComponent {
    async fn fetch_candidates(&self) -> CachedCandidateData {
        assert!(
            matches!(self.kind, RemoteComponentKind::DataSource),
            "RemoteComponent {} is not a DataSource but fetch_candidates() was called",
            self.core.component_id()
        );

        let result: Result<FetchCandidatesResult, _> = self
            .client
            .call(
                plugin_methods::FETCH_CANDIDATES,
                FetchCandidatesParams {
                    component_id: self.core.component_id().to_string(),
                },
                Duration::from_secs(30),
            )
            .await;

        match result {
            Ok(data) => {
                let mut cache = CachedCandidateData::new();
                for candidate in data.candidates {
                    cache.add_candidate(candidate);
                }
                cache
            }
            Err(e) => {
                tracing::warn!(
                    "DataSource {} fetch_candidates failed: {}",
                    self.core.component_id(),
                    e
                );
                CachedCandidateData::new()
            }
        }
    }
}

#[async_trait]
impl ActionExecutor for RemoteComponent {
    fn supported_target_types(&self) -> Vec<TargetType> {
        match &self.kind {
            RemoteComponentKind::ActionExecutor { target_types, .. } => target_types.clone(),
            _ => panic!(
                "RemoteComponent {} is not an ActionExecutor but supported_target_types() was called",
                self.core.component_id()
            ),
        }
    }

    fn supported_actions(&self) -> Vec<ResultAction> {
        match &self.kind {
            RemoteComponentKind::ActionExecutor { result_actions, .. } => result_actions.clone(),
            _ => panic!(
                "RemoteComponent {} is not an ActionExecutor but supported_actions() was called",
                self.core.component_id()
            ),
        }
    }

    async fn execute(&self, ctx: &ExecutionContext, action_id: &str) -> Result<(), ExecutionError> {
        assert!(
            matches!(self.kind, RemoteComponentKind::ActionExecutor { .. }),
            "RemoteComponent {} is not an ActionExecutor but execute() was called",
            self.core.component_id()
        );

        // 完整执行上下文原样透传(与进程内 ActionExecutor 一致),
        // 不再重建伪 PluginContext(旧实现丢弃 target 等字段并伪造 trace_id)。
        let result: Result<ExecutorExecuteResult, _> = self
            .client
            .call(
                plugin_methods::EXECUTOR_EXECUTE,
                ExecutorExecuteParams {
                    component_id: self.core.component_id().to_string(),
                    execution_ctx: ctx.clone(),
                    action_id: action_id.to_string(),
                },
                Duration::from_secs(30),
            )
            .await;

        match result {
            Ok(r) => {
                if let Some(error) = r.error {
                    Err(ExecutionError::Failed(error))
                } else {
                    Ok(())
                }
            }
            Err(e) => Err(ExecutionError::Failed(e.to_string())),
        }
    }
}

#[async_trait]
impl Plugin for RemoteComponent {
    async fn init(
        &self,
        ctx: &PluginContext,
        _handle: Option<Arc<PluginHandle>>,
    ) -> Result<(), PluginError> {
        assert!(
            matches!(self.kind, RemoteComponentKind::Plugin { .. }),
            "RemoteComponent {} is not a Plugin but init() was called",
            self.core.component_id()
        );
        // 远端进程无宿主句柄(跨进程不可序列化),init 语义为通知插件进程完成初始化;
        // 平台能力由插件侧经 host() 的 host/* RPC 访问。
        // METHOD_NOT_FOUND(旧 SDK 插件无 init 方法)= 无初始化需求,静默完成
        // (与引入 init RPC 前的 no-op 行为一致);其他错误向上传播。
        let metadata = match &self.kind {
            RemoteComponentKind::Plugin { metadata, .. } => metadata,
            _ => unreachable!("kind 已在上面断言为 Plugin"),
        };
        let result: Result<serde_json::Value, _> = self
            .client
            .call(
                plugin_methods::INIT,
                InitParams {
                    plugin_id: metadata.id.clone(),
                    ctx: ctx.clone(),
                },
                Duration::from_secs(10),
            )
            .await;
        match result {
            Ok(_) => Ok(()),
            Err(zerolaunch_plugin_protocol::ProtocolError::Rpc { code, .. })
                if code == codes::METHOD_NOT_FOUND =>
            {
                Ok(())
            }
            Err(e) => Err(PluginError::InitFailed(e.to_string())),
        }
    }

    /// 交互策略:返回查询时刷新的缓存值(与内置每次查询同步求值语义对齐)。
    /// 仅 Plugin 组件有策略(kind 已断言为 Plugin)。
    fn interaction_policy(&self) -> PanelInteraction {
        match &self.kind {
            RemoteComponentKind::Plugin {
                interaction_policy, ..
            } => interaction_policy.read().clone(),
            _ => panic!(
                "RemoteComponent {} is not a Plugin but interaction_policy() was called",
                self.core.component_id()
            ),
        }
    }

    async fn query(
        &self,
        ctx: &PluginContext,
        query: &Query,
    ) -> Result<QueryResponse, PluginError> {
        let metadata = match &self.kind {
            RemoteComponentKind::Plugin { metadata, .. } => metadata,
            _ => panic!(
                "RemoteComponent {} is not a Plugin but query() was called",
                self.core.component_id()
            ),
        };

        // 每次查询先刷新交互策略缓存(内置插件在会话推送时同步求值,远端以此对齐)。
        self.refresh_interaction_policy().await;

        self.client
            .call::<_, QueryResponse>(
                plugin_methods::QUERY,
                QueryParams {
                    plugin_id: metadata.id.clone(),
                    ctx: ctx.clone(),
                    query: query.clone(),
                },
                Duration::from_secs(30),
            )
            .await
            .map_err(|e| PluginError::QueryFailed(e.to_string()))
    }

    async fn execute_action(
        &self,
        ctx: &PluginContext,
        action_id: &str,
        payload: serde_json::Value,
    ) -> Result<(), PluginError> {
        let metadata = match &self.kind {
            RemoteComponentKind::Plugin { metadata, .. } => metadata,
            _ => panic!(
                "RemoteComponent {} is not a Plugin but execute_action() was called",
                self.core.component_id()
            ),
        };

        self.client
            .call::<_, serde_json::Value>(
                plugin_methods::EXECUTE_ACTION,
                ExecuteActionParams {
                    plugin_id: metadata.id.clone(),
                    ctx: ctx.clone(),
                    action_id: action_id.to_string(),
                    payload,
                },
                Duration::from_secs(30),
            )
            .await
            .map_err(|e| PluginError::ActionFailed(e.to_string()))?;
        Ok(())
    }
}

impl RemoteComponent {
    /// 经 RPC 刷新交互策略缓存(宿主在会话推送时同步读取)。
    /// 策略为插件级语义:非 Plugin 组件(DataSource/Executor)无策略,直接跳过。
    /// 失败静默:策略保持上次值(新协议方法,老 SDK 插件可能回 METHOD_NOT_FOUND)。
    async fn refresh_interaction_policy(&self) {
        let RemoteComponentKind::Plugin {
            interaction_policy, ..
        } = &self.kind
        else {
            return;
        };
        let result: Result<PanelInteraction, _> = self
            .client
            .call(
                plugin_methods::INTERACTION_POLICY,
                InteractionPolicyParams {
                    component_id: self.core.component_id().to_string(),
                },
                Duration::from_secs(5),
            )
            .await;
        if let Ok(policy) = result {
            *interaction_policy.write() = policy;
        }
    }
    /// 经 RPC 刷新优化器属性缓存(input_source / priority 为声明字段)。
    /// 仅 KeywordOptimizer 组件有属性;失败静默保持上次值。
    async fn refresh_keyword_optimizer_info(&self) {
        let RemoteComponentKind::KeywordOptimizer { info } = &self.kind else {
            return;
        };
        let result: Result<KeywordOptimizerInfo, _> = self
            .client
            .call(
                plugin_methods::KEYWORD_OPTIMIZER_INFO,
                KeywordOptimizerInfoParams {
                    component_id: self.core.component_id().to_string(),
                },
                Duration::from_secs(5),
            )
            .await;
        match result {
            Ok(meta) => *info.write() = meta,
            Err(e) => {
                // 刷新失败保留上次值(候选管道按旧属性排序),告警便于诊断,不阻断设置流程。
                tracing::warn!(
                    "KeywordOptimizer {} 属性刷新失败: {}",
                    self.core.component_id(),
                    e
                );
            }
        }
    }
}
#[async_trait]
impl SearchEngine for RemoteComponent {
    async fn calculate_scores(
        &self,
        candidates: &CachedCandidateData,
        query: &str,
    ) -> Vec<ScoredCandidate> {
        assert!(
            matches!(self.kind, RemoteComponentKind::SearchEngine),
            "RemoteComponent {} is not a SearchEngine but calculate_scores() was called",
            self.core.component_id()
        );
        let result: Result<Vec<ScoredCandidate>, _> = self
            .client
            .call(
                plugin_methods::CALCULATE_SCORES,
                CalculateScoresParams {
                    component_id: self.core.component_id().to_string(),
                    candidates: candidates.to_data(),
                    query: query.to_string(),
                },
                Duration::from_secs(5),
            )
            .await;
        match result {
            Ok(scored) => scored,
            Err(e) => {
                // 远端引擎故障:本次查询退化为空结果(插件禁用即恢复),不静默回退本地引擎。
                tracing::error!(
                    "SearchEngine {} calculate_scores failed: {}",
                    self.core.component_id(),
                    e
                );
                Vec::new()
            }
        }
    }
}

#[async_trait]
impl ScoreBooster for RemoteComponent {
    async fn record(&self, candidate_id: CandidateId, data: &CachedCandidateData, query: &str) {
        assert!(
            matches!(self.kind, RemoteComponentKind::ScoreBooster),
            "RemoteComponent {} is not a ScoreBooster but record() was called",
            self.core.component_id()
        );
        let result: Result<serde_json::Value, _> = self
            .client
            .call(
                plugin_methods::BOOSTER_RECORD,
                BoosterRecordParams {
                    component_id: self.core.component_id().to_string(),
                    candidate_id,
                    candidates: data.to_data(),
                    query: query.to_string(),
                },
                Duration::from_secs(2),
            )
            .await;
        if let Err(e) = result {
            tracing::warn!(
                "ScoreBooster {} record failed: {}",
                self.core.component_id(),
                e
            );
        }
    }

    async fn boost(
        &self,
        candidates: &mut Vec<ScoredCandidate>,
        data: &CachedCandidateData,
        query: &str,
    ) {
        assert!(
            matches!(self.kind, RemoteComponentKind::ScoreBooster),
            "RemoteComponent {} is not a ScoreBooster but boost() was called",
            self.core.component_id()
        );
        let result: Result<Vec<ScoredCandidate>, _> = self
            .client
            .call(
                plugin_methods::BOOSTER_BOOST,
                BoosterBoostParams {
                    component_id: self.core.component_id().to_string(),
                    candidates: data.to_data(),
                    scored: candidates.clone(),
                    query: query.to_string(),
                },
                Duration::from_secs(5),
            )
            .await;
        match result {
            Ok(scored) => *candidates = scored,
            Err(e) => {
                // 增强失败:保留引擎原分数(无增强,结果不劣于无该组件)。
                tracing::warn!(
                    "ScoreBooster {} boost failed: {}",
                    self.core.component_id(),
                    e
                );
            }
        }
    }
}

#[async_trait]
impl KeywordOptimizer for RemoteComponent {
    async fn optimize(&self, keyword: &str) -> Vec<String> {
        assert!(
            matches!(self.kind, RemoteComponentKind::KeywordOptimizer { .. }),
            "RemoteComponent {} is not a KeywordOptimizer but optimize() was called",
            self.core.component_id()
        );
        let result: Result<Vec<String>, _> = self
            .client
            .call(
                plugin_methods::KEYWORD_OPTIMIZE,
                KeywordOptimizeParams {
                    component_id: self.core.component_id().to_string(),
                    keyword: keyword.to_string(),
                    input_source: self.input_source(),
                },
                Duration::from_secs(10),
            )
            .await;
        match result {
            Ok(keywords) => keywords,
            Err(e) => {
                // 优化失败:跳过该组件(召回略降,候选仍可搜索)。
                tracing::warn!(
                    "KeywordOptimizer {} optimize failed: {}",
                    self.core.component_id(),
                    e
                );
                Vec::new()
            }
        }
    }

    fn input_source(&self) -> KeywordInputSource {
        match &self.kind {
            RemoteComponentKind::KeywordOptimizer { info } => info.read().input_source.clone(),
            _ => panic!(
                "RemoteComponent {} is not a KeywordOptimizer but input_source() was called",
                self.core.component_id()
            ),
        }
    }

    fn get_priority(&self) -> u32 {
        match &self.kind {
            RemoteComponentKind::KeywordOptimizer { info } => info.read().priority,
            _ => panic!(
                "RemoteComponent {} is not a KeywordOptimizer but get_priority() was called",
                self.core.component_id()
            ),
        }
    }
}

#[async_trait]
impl KeywordInjector for RemoteComponent {
    async fn inject_keywords(&self, candidate: &SearchCandidate) -> Vec<String> {
        assert!(
            matches!(self.kind, RemoteComponentKind::KeywordInjector),
            "RemoteComponent {} is not a KeywordInjector but inject_keywords() was called",
            self.core.component_id()
        );
        let result: Result<Vec<String>, _> = self
            .client
            .call(
                plugin_methods::KEYWORD_INJECT,
                KeywordInjectParams {
                    component_id: self.core.component_id().to_string(),
                    candidate: candidate.clone(),
                },
                Duration::from_secs(10),
            )
            .await;
        match result {
            Ok(keywords) => keywords,
            Err(e) => {
                // 注入失败:跳过该组件(召回略降,候选仍可搜索)。
                tracing::warn!(
                    "KeywordInjector {} inject_keywords failed: {}",
                    self.core.component_id(),
                    e
                );
                Vec::new()
            }
        }
    }
}