oino-extension-api 1.1.0

Contracts between oino-core and extension runtimes: instances, host services, manifests, permissions
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! Test doubles (feature `testing`): [`RecordingHostServices`] records every host call and
//! keeps a small in-memory session, bus and secret store; [`FakeExtensionRuntime`] produces
//! [`FakeInstance`]s scripted with Rust closures.

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;

use futures::channel::oneshot;
use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;

use crate::guest::{CompletionItem, InitInput, ToolInvocation};
use crate::json::RawJson;
use crate::manifest::Manifest;
use crate::ops::{
    ControlOp, ControlReply, DeviceOp, EditorOp, HostContextInfo, PanelOp, SecretOp, SessionQuery,
    SessionWrite, SettingsLayer, SettingsScope,
};
use crate::registry::{
    ArbiterRoles, CommandSpec, EventKind, FlagSpec, Registration, RendererSpec, ShortcutSpec,
    ToolSpec,
};
use crate::runtime::{
    BoxFut, ExtensionInstance, ExtensionRuntime, HostServices, LoadedPackage, ProviderInstance,
};
use crate::types::{CallContext, ExtensionError, ExtensionId, HostError};

fn guard<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(PoisonError::into_inner)
}

/// One recorded host call.
#[derive(Clone, Debug, PartialEq)]
pub struct HostCall {
    /// Method (`register_tool`, `session_write`, `deliver_event`, …).
    pub method: String,
    /// Calling extension, when known.
    pub ext: Option<String>,
    /// Arguments as JSON.
    pub detail: Value,
}

/// Records calls; answers with simple in-memory behaviour.
#[derive(Default)]
pub struct RecordingHostServices {
    calls: Mutex<Vec<HostCall>>,
    entries: Mutex<Vec<Value>>,
    sticky: Mutex<BTreeMap<String, RawJson>>,
    secrets: Mutex<HashMap<String, String>>,
    dialog_answers: Mutex<VecDeque<RawJson>>,
    dialog_waiters: Mutex<VecDeque<oneshot::Sender<RawJson>>>,
    flags: Mutex<HashMap<String, RawJson>>,
    editor: Mutex<String>,
    panels: Mutex<u32>,
    /// Extension settings layers: `(scope, namespace)` → values object.
    ext_settings: Mutex<BTreeMap<(String, String), Value>>,
}

/// Sets dot path `key` in `target` (`None` removes it).
fn set_dotted(target: &mut Value, key: &str, value: Option<Value>) {
    if !target.is_object() {
        *target = json!({});
    }
    let segments: Vec<&str> = key.split('.').collect();
    let Some((last, parents)) = segments.split_last() else {
        return;
    };
    let mut cursor = target;
    for segment in parents {
        let Value::Object(map) = cursor else { return };
        let next = map
            .entry((*segment).to_owned())
            .or_insert_with(|| json!({}));
        if !next.is_object() {
            *next = json!({});
        }
        cursor = next;
    }
    if let Value::Object(map) = cursor {
        match value {
            Some(v) => {
                map.insert((*last).to_owned(), v);
            }
            None => {
                map.remove(*last);
            }
        }
    }
}

fn merge_values(base: &mut Value, over: &Value) {
    match (base, over) {
        (Value::Object(b), Value::Object(o)) => {
            for (k, v) in o {
                merge_values(b.entry(k.clone()).or_insert(Value::Null), v);
            }
        }
        (b, o) => *b = o.clone(),
    }
}

impl std::fmt::Debug for RecordingHostServices {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RecordingHostServices")
            .field("calls", &guard(&self.calls).len())
            .finish_non_exhaustive()
    }
}

impl RecordingHostServices {
    /// A new recorder.
    #[must_use]
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    fn record(&self, method: &str, ext: Option<&ExtensionId>, detail: Value) {
        guard(&self.calls).push(HostCall {
            method: method.to_owned(),
            ext: ext.map(ToString::to_string),
            detail,
        });
    }

    /// Every call so far.
    #[must_use]
    pub fn calls(&self) -> Vec<HostCall> {
        guard(&self.calls).clone()
    }

    /// Calls of one method.
    #[must_use]
    pub fn calls_named(&self, method: &str) -> Vec<HostCall> {
        guard(&self.calls)
            .iter()
            .filter(|c| c.method == method)
            .cloned()
            .collect()
    }

    /// Custom entries appended so far (`{type:"custom", customType, data, id}`).
    #[must_use]
    pub fn entries(&self) -> Vec<Value> {
        guard(&self.entries).clone()
    }

    /// Seeds entries as if a previous process had appended them before dying (restart
    /// tests: the session file is durable, the guest state is not).
    pub fn seed_entries(&self, entries: Vec<Value>) {
        guard(&self.entries).extend(entries);
    }

    /// Queues an answer for the next `ui.dialog`.
    pub fn queue_dialog_answer(&self, answer: Value) {
        guard(&self.dialog_answers).push_back(RawJson::from(answer));
    }

    /// Answers the oldest pending dialog; returns false when none is waiting.
    pub fn answer_pending_dialog(&self, answer: Value) -> bool {
        let waiter = guard(&self.dialog_waiters).pop_front();
        waiter.is_some_and(|tx| tx.send(RawJson::from(answer)).is_ok())
    }

    /// Number of dialogs currently waiting for an answer.
    #[must_use]
    pub fn pending_dialogs(&self) -> usize {
        guard(&self.dialog_waiters).len()
    }

    /// Values stored by `set-extension-setting` in one scope (`{}` when none).
    #[must_use]
    pub fn extension_setting_layer(&self, scope: SettingsScope, namespace: &str) -> Value {
        guard(&self.ext_settings)
            .get(&(scope_name(scope).to_owned(), namespace.to_owned()))
            .cloned()
            .unwrap_or_else(|| json!({}))
    }

    /// Presets one key of an extension settings layer (as if a user had edited it).
    pub fn preset_extension_setting(
        &self,
        scope: SettingsScope,
        namespace: &str,
        key: &str,
        value: Value,
    ) {
        let mut all = guard(&self.ext_settings);
        let layer = all
            .entry((scope_name(scope).to_owned(), namespace.to_owned()))
            .or_insert_with(|| json!({}));
        set_dotted(layer, key, Some(value));
    }

    /// Sets a CLI flag value.
    pub fn set_flag(&self, name: &str, value: Value) {
        guard(&self.flags).insert(name.to_owned(), RawJson::from(value));
    }
}

fn scope_name(scope: SettingsScope) -> &'static str {
    match scope {
        SettingsScope::Global => "global",
        SettingsScope::Project => "project",
    }
}

fn to_json<T: serde::Serialize>(v: &T) -> Value {
    serde_json::to_value(v).unwrap_or(Value::Null)
}

impl HostServices for RecordingHostServices {
    fn subscribe(&self, ext: &ExtensionId, events: &[EventKind]) {
        self.record("subscribe", Some(ext), to_json(&events));
    }
    fn unsubscribe(&self, ext: &ExtensionId, events: &[EventKind]) {
        self.record("unsubscribe", Some(ext), to_json(&events));
    }
    fn register_tool(&self, ext: &ExtensionId, spec: ToolSpec) -> Result<(), HostError> {
        self.record("register_tool", Some(ext), to_json(&spec));
        Ok(())
    }
    fn unregister_tool(&self, ext: &ExtensionId, name: &str) {
        self.record("unregister_tool", Some(ext), json!(name));
    }
    fn register_command(&self, ext: &ExtensionId, spec: CommandSpec) -> Result<String, HostError> {
        let name = spec.name.clone();
        self.record("register_command", Some(ext), to_json(&spec));
        Ok(name)
    }
    fn unregister_command(&self, ext: &ExtensionId, name: &str) {
        self.record("unregister_command", Some(ext), json!(name));
    }
    fn register_shortcut(&self, ext: &ExtensionId, spec: ShortcutSpec) -> Result<(), HostError> {
        self.record("register_shortcut", Some(ext), to_json(&spec));
        Ok(())
    }
    fn unregister_shortcut(&self, ext: &ExtensionId, id: &str) {
        self.record("unregister_shortcut", Some(ext), json!(id));
    }
    fn register_flag(&self, ext: &ExtensionId, spec: FlagSpec) -> Result<(), HostError> {
        self.record("register_flag", Some(ext), to_json(&spec));
        Ok(())
    }
    fn get_flag(&self, ext: &ExtensionId, name: &str) -> Option<RawJson> {
        self.record("get_flag", Some(ext), json!(name));
        guard(&self.flags).get(name).cloned()
    }
    fn register_renderer(&self, ext: &ExtensionId, spec: RendererSpec) {
        self.record("register_renderer", Some(ext), to_json(&spec));
    }
    fn register_service(&self, ext: &ExtensionId, name: &str) -> Result<(), HostError> {
        self.record("register_service", Some(ext), json!(name));
        Ok(())
    }
    fn set_arbiter_roles(&self, ext: &ExtensionId, roles: ArbiterRoles) {
        self.record("set_arbiter_roles", Some(ext), to_json(&roles));
    }
    fn register_settings(&self, ext: &ExtensionId, ns: RawJson) -> Result<(), HostError> {
        self.record("register_settings", Some(ext), ns.to_value());
        Ok(())
    }
    fn extension_settings(
        &self,
        ext: &ExtensionId,
        namespace: &str,
        layer: SettingsLayer,
    ) -> Result<RawJson, HostError> {
        self.record(
            "extension_settings",
            Some(ext),
            json!({"namespace": namespace, "layer": layer}),
        );
        let all = guard(&self.ext_settings);
        let get = |scope: SettingsScope| {
            all.get(&(scope_name(scope).to_owned(), namespace.to_owned()))
                .cloned()
                .unwrap_or_else(|| json!({}))
        };
        let value = match layer {
            SettingsLayer::Effective => {
                let mut v = get(SettingsScope::Global);
                merge_values(&mut v, &get(SettingsScope::Project));
                v
            }
            SettingsLayer::Global => get(SettingsScope::Global),
            SettingsLayer::Project => get(SettingsScope::Project),
        };
        Ok(RawJson::from(value))
    }
    fn set_extension_setting(
        &self,
        ext: &ExtensionId,
        namespace: &str,
        key: &str,
        value: Option<RawJson>,
        scope: SettingsScope,
    ) -> Result<(), HostError> {
        let value = value.map(|v| v.to_value());
        self.record(
            "set_extension_setting",
            Some(ext),
            json!({"namespace": namespace, "key": key, "value": value, "scope": scope}),
        );
        let mut all = guard(&self.ext_settings);
        let layer = all
            .entry((scope_name(scope).to_owned(), namespace.to_owned()))
            .or_insert_with(|| json!({}));
        set_dotted(layer, key, value.filter(|v| !v.is_null()));
        Ok(())
    }
    fn register_provider(&self, ext: &ExtensionId, cfg: RawJson) -> Result<(), HostError> {
        self.record("register_provider", Some(ext), cfg.to_value());
        Ok(())
    }
    fn unregister_provider(&self, ext: &ExtensionId, id: &str) {
        self.record("unregister_provider", Some(ext), json!(id));
    }
    fn register_virtual_model(&self, ext: &ExtensionId, def: RawJson) -> Result<(), HostError> {
        self.record("register_virtual_model", Some(ext), def.to_value());
        Ok(())
    }
    fn unregister_virtual_model(&self, ext: &ExtensionId, provider: &str, id: &str) {
        self.record("unregister_virtual_model", Some(ext), json!([provider, id]));
    }

    fn session_read(&self, cx: &CallContext, q: SessionQuery) -> Result<RawJson, HostError> {
        self.record("session_read", None, to_json(&q));
        let value = match q {
            SessionQuery::SessionId => json!(cx.session_id),
            SessionQuery::Entries | SessionQuery::Branch { .. } | SessionQuery::ContextEntries => {
                Value::Array(self.entries())
            }
            SessionQuery::Entry { id } => self
                .entries()
                .into_iter()
                .find(|e| e["id"] == id.as_str())
                .unwrap_or(Value::Null),
            SessionQuery::Header => json!({"type": "session", "version": 3, "id": cx.session_id}),
            _ => Value::Null,
        };
        Ok(RawJson::from(value))
    }

    fn session_write(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        w: SessionWrite,
    ) -> BoxFut<'_, Result<Option<String>, HostError>> {
        let detail = match &w {
            SessionWrite::SetSessionName(n) => json!({"setSessionName": n}),
            SessionWrite::SetLabel { id, label } => json!({"setLabel": [id, label]}),
            SessionWrite::AppendEntry { custom_type, data } => {
                json!({"appendEntry": custom_type, "data": data.as_ref().map(RawJson::to_value)})
            }
            SessionWrite::SendMessage { message, options } => {
                json!({"sendMessage": message.to_value(), "options": to_json(options)})
            }
            SessionWrite::SendUserMessage { content, options } => {
                json!({"sendUserMessage": content.to_value(), "options": to_json(options)})
            }
        };
        self.record("session_write", Some(ext), detail);
        let id = if let SessionWrite::AppendEntry { custom_type, data } = w {
            let mut entries = guard(&self.entries);
            let id = format!("{:08x}", entries.len() + 1);
            entries.push(json!({
                "type": "custom", "id": id, "customType": custom_type,
                "data": data.as_ref().map_or(Value::Null, RawJson::to_value),
            }));
            Some(id)
        } else {
            None
        };
        Box::pin(async move { Ok(id) })
    }

    fn control(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        op: ControlOp,
    ) -> BoxFut<'_, Result<ControlReply, HostError>> {
        self.record("control", Some(ext), json!(op.name()));
        let reply = match op {
            ControlOp::IsIdle | ControlOp::IsProjectTrusted | ControlOp::SetModel { .. } => {
                ControlReply::Bool(true)
            }
            ControlOp::HasPendingMessages => ControlReply::Bool(false),
            ControlOp::ThinkingLevel => ControlReply::String("off".into()),
            ControlOp::SystemPrompt => ControlReply::String(String::new()),
            ControlOp::ActiveTools => ControlReply::Strings(Vec::new()),
            ControlOp::Model | ControlOp::RoutedModel => ControlReply::MaybeJson(None),
            ControlOp::Abort | ControlOp::Shutdown | ControlOp::SetActiveTools(_) => {
                ControlReply::Unit
            }
            _ => ControlReply::Json(RawJson::null()),
        };
        Box::pin(async move { Ok(reply) })
    }

    fn tool_progress(&self, _cx: &CallContext, tool_call_id: &str, partial: RawJson) {
        self.record(
            "tool_progress",
            None,
            json!({"toolCallId": tool_call_id, "partial": partial.to_value()}),
        );
    }

    fn ui_dialog(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        req: RawJson,
        cancel: Option<CancellationToken>,
    ) -> BoxFut<'_, Result<RawJson, HostError>> {
        self.record("ui_dialog", Some(ext), req.to_value());
        let queued = guard(&self.dialog_answers).pop_front();
        let waiter = if queued.is_none() {
            let (tx, rx) = oneshot::channel();
            guard(&self.dialog_waiters).push_back(tx);
            Some(rx)
        } else {
            None
        };
        Box::pin(async move {
            if let Some(answer) = queued {
                return Ok(answer);
            }
            let Some(rx) = waiter else {
                return Err(HostError::Cancelled);
            };
            let cancelled = async {
                match cancel {
                    Some(token) => token.cancelled().await,
                    None => std::future::pending().await,
                }
            };
            futures::pin_mut!(cancelled);
            match futures::future::select(rx, cancelled).await {
                futures::future::Either::Left((Ok(answer), _)) => Ok(answer),
                futures::future::Either::Left((Err(_), _)) | futures::future::Either::Right(_) => {
                    Err(HostError::Cancelled)
                }
            }
        })
    }

    fn ui_fire(&self, ext: &ExtensionId, _cx: &CallContext, req: RawJson) -> Result<(), HostError> {
        self.record("ui_fire", Some(ext), req.to_value());
        Ok(())
    }

    fn ui_panel(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        op: PanelOp,
    ) -> Result<Option<String>, HostError> {
        let (detail, id) = match op {
            PanelOp::Open(spec) => {
                let mut n = guard(&self.panels);
                *n += 1;
                (json!({"open": spec.to_value()}), Some(format!("panel-{n}")))
            }
            PanelOp::Update { panel_id, spec } => {
                (json!({"update": panel_id, "spec": spec.to_value()}), None)
            }
            PanelOp::Close(id) => (json!({"close": id}), None),
        };
        self.record("ui_panel", Some(ext), detail);
        Ok(id)
    }

    fn ui_editor(&self, _cx: &CallContext, op: EditorOp) -> Result<Option<String>, HostError> {
        self.record("ui_editor", None, json!(format!("{op:?}")));
        let mut editor = guard(&self.editor);
        Ok(match op {
            EditorOp::Text => Some(editor.clone()),
            EditorOp::Set(t) => {
                *editor = t;
                None
            }
            EditorOp::Insert(t) => {
                editor.push_str(&t);
                None
            }
        })
    }

    fn ui_device(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        op: DeviceOp,
    ) -> BoxFut<'_, Result<Option<RawJson>, HostError>> {
        self.record("ui_device", Some(ext), json!(format!("{op:?}")));
        Box::pin(async { Ok(None) })
    }

    fn bus_publish(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        topic: &str,
        data: RawJson,
        sticky: bool,
    ) {
        self.record(
            "bus_publish",
            Some(ext),
            json!({"topic": topic, "data": data.to_value(), "sticky": sticky}),
        );
        if sticky {
            guard(&self.sticky).insert(topic.to_owned(), data);
        }
    }
    fn bus_subscribe(&self, ext: &ExtensionId, _cx: &CallContext, pattern: &str, on: bool) {
        self.record(
            "bus_subscribe",
            Some(ext),
            json!({"pattern": pattern, "on": on}),
        );
    }
    fn bus_get(&self, _cx: &CallContext, topic: &str) -> Option<RawJson> {
        guard(&self.sticky).get(topic).cloned()
    }

    fn secret(&self, ext: &ExtensionId, op: SecretOp) -> Result<Option<String>, HostError> {
        let mut secrets = guard(&self.secrets);
        let key = |n: &str| format!("{ext}/{n}");
        self.record(
            "secret",
            Some(ext),
            json!(format!("{op:?}").split('(').next()),
        );
        Ok(match op {
            SecretOp::Get(name) => secrets.get(&key(&name)).cloned(),
            SecretOp::Set { name, value } => {
                secrets.insert(key(&name), value);
                None
            }
            SecretOp::Delete(name) => secrets.remove(&key(&name)),
        })
    }

    fn host_context(&self, _cx: &CallContext) -> HostContextInfo {
        HostContextInfo {
            frontends: vec!["rpc".into()],
            frontend_focused: true,
            workspace: None,
        }
    }

    fn deliver_event(
        &self,
        ext: &ExtensionId,
        session_id: &str,
        kind: EventKind,
        payload: RawJson,
    ) {
        self.record(
            "deliver_event",
            Some(ext),
            json!({"sessionId": session_id, "kind": kind.wire(), "payload": payload.to_value()}),
        );
    }

    fn service_call(
        &self,
        ext: &ExtensionId,
        _cx: &CallContext,
        target: Option<&ExtensionId>,
        name: &str,
        payload: RawJson,
        _timeout: Duration,
    ) -> BoxFut<'_, Result<RawJson, HostError>> {
        self.record("service_call", Some(ext), json!({"target": target.map(ToString::to_string), "name": name, "payload": payload.to_value()}));
        Box::pin(async { Err(HostError::NotFound("service".into())) })
    }
}

type EventFn =
    dyn Fn(EventKind, &RawJson, &CallContext) -> Result<Option<RawJson>, String> + Send + Sync;
type ToolFn = dyn Fn(&ToolInvocation, &CallContext) -> Result<RawJson, String> + Send + Sync;
type CommandFn = dyn Fn(&str, &str) -> Result<Option<RawJson>, String> + Send + Sync;

/// A scripted instance.
pub struct FakeInstance {
    manifest: Manifest,
    registration: Registration,
    on_event: Option<Box<EventFn>>,
    run_tool: Option<Box<ToolFn>>,
    run_command: Option<Box<CommandFn>>,
}

impl std::fmt::Debug for FakeInstance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FakeInstance")
            .field("id", &self.manifest.id)
            .finish_non_exhaustive()
    }
}

impl FakeInstance {
    /// An instance with `manifest` that registers `registration` at init.
    #[must_use]
    pub fn new(manifest: Manifest, registration: Registration) -> Self {
        Self {
            manifest,
            registration,
            on_event: None,
            run_tool: None,
            run_command: None,
        }
    }

    /// Event handler.
    #[must_use]
    pub fn on_event(
        mut self,
        f: impl Fn(EventKind, &RawJson, &CallContext) -> Result<Option<RawJson>, String>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.on_event = Some(Box::new(f));
        self
    }

    /// Tool handler.
    #[must_use]
    pub fn run_tool(
        mut self,
        f: impl Fn(&ToolInvocation, &CallContext) -> Result<RawJson, String> + Send + Sync + 'static,
    ) -> Self {
        self.run_tool = Some(Box::new(f));
        self
    }

    /// Command handler.
    #[must_use]
    pub fn run_command(
        mut self,
        f: impl Fn(&str, &str) -> Result<Option<RawJson>, String> + Send + Sync + 'static,
    ) -> Self {
        self.run_command = Some(Box::new(f));
        self
    }

    fn err(&self, call: &str, message: String) -> ExtensionError {
        ExtensionError::new(self.manifest.id.as_str(), call, message)
    }
}

impl ExtensionInstance for FakeInstance {
    fn id(&self) -> &ExtensionId {
        &self.manifest.id
    }
    fn manifest(&self) -> &Manifest {
        &self.manifest
    }
    fn init(
        &self,
        _input: InitInput,
        _cx: CallContext,
    ) -> BoxFut<'_, Result<Registration, ExtensionError>> {
        let reg = self.registration.clone();
        Box::pin(async move { Ok(reg) })
    }
    fn on_event(
        &self,
        kind: EventKind,
        payload: RawJson,
        cx: CallContext,
    ) -> BoxFut<'_, Result<Option<RawJson>, ExtensionError>> {
        let result = self
            .on_event
            .as_ref()
            .map_or(Ok(None), |f| f(kind, &payload, &cx));
        Box::pin(async move { result.map_err(|m| self.err("on-event", m)) })
    }
    fn run_tool(
        &self,
        inv: ToolInvocation,
        _cancel: CancellationToken,
        cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>> {
        let result = self
            .run_tool
            .as_ref()
            .map_or_else(|| Err("no tools".to_owned()), |f| f(&inv, &cx));
        Box::pin(async move { result.map_err(|m| self.err("run-tool", m)) })
    }
    fn prepare_arguments(&self, _tool: &str, raw: RawJson) -> Result<RawJson, ExtensionError> {
        Ok(raw)
    }
    fn prepare_loadout(
        &self,
        _tool: &str,
        _loadout: RawJson,
    ) -> Result<Option<RawJson>, ExtensionError> {
        Ok(None)
    }
    fn reaches_tools(&self, _tool: &str, _input: RawJson) -> Result<RawJson, ExtensionError> {
        Ok(RawJson::from_json_value(&json!([])))
    }
    fn run_command(
        &self,
        name: &str,
        args: &str,
        _cancel: CancellationToken,
        _cx: CallContext,
    ) -> BoxFut<'_, Result<Option<RawJson>, ExtensionError>> {
        let result = self
            .run_command
            .as_ref()
            .map_or(Ok(None), |f| f(name, args));
        Box::pin(async move { result.map_err(|m| self.err("run-command", m)) })
    }
    fn complete_command(
        &self,
        _name: &str,
        _prefix: &str,
        _cx: CallContext,
    ) -> BoxFut<'_, Vec<CompletionItem>> {
        Box::pin(async { Vec::new() })
    }
    fn run_shortcut(&self, _id: &str, _cx: CallContext) -> BoxFut<'_, Result<(), ExtensionError>> {
        Box::pin(async { Ok(()) })
    }
    fn handle_service(
        &self,
        name: &str,
        _payload: RawJson,
        _caller: &ExtensionId,
        _cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>> {
        let err = self.err("handle-service", format!("unknown service {name}"));
        Box::pin(async move { Err(err) })
    }
    fn propose_nudge(&self, _cx: CallContext) -> BoxFut<'_, Option<RawJson>> {
        Box::pin(async { None })
    }
    fn nudge_delivered(&self, _id: &str, _cx: CallContext) {}
    fn wait_reason(&self, _cx: CallContext) -> BoxFut<'_, Option<String>> {
        Box::pin(async { None })
    }
    fn render(&self, _request: RawJson, _cx: CallContext) -> Option<RawJson> {
        None
    }
    fn route_model(
        &self,
        _request: RawJson,
        _cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>> {
        let err = self.err("route-model", "not a router".into());
        Box::pin(async move { Err(err) })
    }
    fn complete_input(&self, _request: RawJson, _cx: CallContext) -> BoxFut<'_, Option<RawJson>> {
        Box::pin(async { None })
    }
    fn provider(&self) -> Option<&dyn ProviderInstance> {
        None
    }
    fn shutdown(&self, _reason: &str) -> BoxFut<'_, ()> {
        Box::pin(async {})
    }
}

type Factory = dyn Fn(&LoadedPackage) -> FakeInstance + Send + Sync;

/// Runtime producing [`FakeInstance`]s from a factory.
pub struct FakeExtensionRuntime {
    factory: Box<Factory>,
}

impl std::fmt::Debug for FakeExtensionRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("FakeExtensionRuntime")
    }
}

impl FakeExtensionRuntime {
    /// A runtime calling `factory` per loaded package.
    #[must_use]
    pub fn new(factory: impl Fn(&LoadedPackage) -> FakeInstance + Send + Sync + 'static) -> Self {
        Self {
            factory: Box::new(factory),
        }
    }
}

impl ExtensionRuntime for FakeExtensionRuntime {
    fn load(
        &self,
        package: LoadedPackage,
        _host: Arc<dyn HostServices>,
    ) -> BoxFut<'_, Result<Arc<dyn ExtensionInstance>, ExtensionError>> {
        let instance: Arc<dyn ExtensionInstance> = Arc::new((self.factory)(&package));
        Box::pin(async move { Ok(instance) })
    }
}