oino-extension-api 1.0.1

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
//! Runtime traits: [`ExtensionRuntime`] loads packages into [`ExtensionInstance`]s, which call
//! back into [`HostServices`] (implemented by `oino-core`).

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use futures::future::BoxFuture;
use futures::stream::BoxStream;
use oino_ai::{Model, ProviderEvent};
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, ModelsOp, ModelsReply, PanelOp,
    ProviderHook, ProviderHookReply, SecretOp, SessionQuery, SessionWrite, SessionsIndexQuery,
    SettingsLayer, SettingsScope, TaskOp,
};
use crate::registry::{
    ArbiterRoles, CommandSpec, EventKind, FlagSpec, Registration, RendererSpec, ShortcutSpec,
    ToolSpec,
};
use crate::types::{CallContext, ExtensionError, ExtensionId, HostError};

/// Boxed future alias used across the contract.
pub type BoxFut<'a, T> = BoxFuture<'a, T>;

/// A process taken over from a detached `bash` tool call ([`HostServices::take_bash`]).
pub struct DetachedBash {
    /// The command line.
    pub command: String,
    /// OS process id, when known.
    pub pid: Option<u32>,
    /// Output the tool call returned before the detach marker.
    pub output_so_far: String,
    /// Temp file with the complete output so far (when the call truncated it).
    pub full_output_path: Option<String>,
    /// Further output chunks (stdout and stderr interleaved); ends with the process.
    pub output: BoxStream<'static, Vec<u8>>,
    /// Resolves with the exit code once the process ended (`None` when killed by a signal).
    pub exit: BoxFuture<'static, Option<i32>>,
    /// Cancel to kill the process tree.
    pub kill: CancellationToken,
}

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

/// Component bytes or a path to them.
#[derive(Clone, Debug)]
pub enum ComponentSource {
    /// In-memory component (bundled).
    Bytes(Arc<[u8]>),
    /// Component file on disk.
    Path(PathBuf),
}

/// A validated package ready to load.
#[derive(Clone, Debug)]
pub struct LoadedPackage {
    /// Manifest.
    pub manifest: Manifest,
    /// Component.
    pub component: ComponentSource,
    /// Package root on disk (resources), when any.
    pub root: Option<PathBuf>,
    /// Bundled with Oino (grants such as `"*"` hosts are trusted).
    pub bundled: bool,
}

/// Loads packages into instances.
pub trait ExtensionRuntime: Send + Sync {
    /// Instantiates `package`; `host` serves its imports.
    fn load(
        &self,
        package: LoadedPackage,
        host: Arc<dyn HostServices>,
    ) -> BoxFut<'_, Result<Arc<dyn ExtensionInstance>, ExtensionError>>;
}

/// One loaded extension (one component instance per process, D-principle 5).
pub trait ExtensionInstance: Send + Sync {
    /// Manifest id.
    fn id(&self) -> &ExtensionId;
    /// Manifest.
    fn manifest(&self) -> &Manifest;
    /// `init`.
    fn init(
        &self,
        input: InitInput,
        cx: CallContext,
    ) -> BoxFut<'_, Result<Registration, ExtensionError>>;
    /// `on-event`; `Ok(None)` = no result.
    fn on_event(
        &self,
        kind: EventKind,
        payload: RawJson,
        cx: CallContext,
    ) -> BoxFut<'_, Result<Option<RawJson>, ExtensionError>>;
    /// `run-tool` → `AgentToolResult` JSON.
    fn run_tool(
        &self,
        inv: ToolInvocation,
        cancel: CancellationToken,
        cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>>;
    /// `prepare-arguments`.
    ///
    /// # Errors
    ///
    /// Guest trap.
    fn prepare_arguments(&self, tool: &str, raw: RawJson) -> Result<RawJson, ExtensionError>;
    /// `prepare-loadout`.
    ///
    /// # Errors
    ///
    /// Guest trap.
    fn prepare_loadout(
        &self,
        tool: &str,
        loadout: RawJson,
    ) -> Result<Option<RawJson>, ExtensionError>;
    /// `reaches-tools` → `"all"` | `["name", …]`.
    ///
    /// # Errors
    ///
    /// Guest trap.
    fn reaches_tools(&self, tool: &str, input: RawJson) -> Result<RawJson, ExtensionError>;
    /// `run-command`.
    fn run_command(
        &self,
        name: &str,
        args: &str,
        cancel: CancellationToken,
        cx: CallContext,
    ) -> BoxFut<'_, Result<Option<RawJson>, ExtensionError>>;
    /// `complete-command`.
    fn complete_command(
        &self,
        name: &str,
        prefix: &str,
        cx: CallContext,
    ) -> BoxFut<'_, Vec<CompletionItem>>;
    /// `run-shortcut`.
    fn run_shortcut(&self, id: &str, cx: CallContext) -> BoxFut<'_, Result<(), ExtensionError>>;
    /// `handle-service`.
    fn handle_service(
        &self,
        name: &str,
        payload: RawJson,
        caller: &ExtensionId,
        cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>>;
    /// `propose-nudge`.
    fn propose_nudge(&self, cx: CallContext) -> BoxFut<'_, Option<RawJson>>;
    /// `nudge-delivered`.
    fn nudge_delivered(&self, id: &str, cx: CallContext);
    /// `wait-reason`.
    fn wait_reason(&self, cx: CallContext) -> BoxFut<'_, Option<String>>;
    /// `render` → OUS node JSON.
    fn render(&self, request: RawJson, cx: CallContext) -> Option<RawJson>;
    /// `route-model`.
    fn route_model(
        &self,
        request: RawJson,
        cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>>;
    /// `complete-input`.
    fn complete_input(&self, request: RawJson, cx: CallContext) -> BoxFut<'_, Option<RawJson>>;
    /// Provider exports, for components of world `provider-extension`.
    fn provider(&self) -> Option<&dyn ProviderInstance>;
    /// `shutdown`.
    fn shutdown(&self, reason: &str) -> BoxFut<'_, ()>;
}

/// Stream of provider events.
pub type ProviderEventStream = BoxStream<'static, Result<ProviderEvent, ExtensionError>>;

/// Provider exports (`provider.wit`).
pub trait ProviderInstance: Send + Sync {
    /// `stream`: `ProviderStreamRequest` JSON in, events out. Dropping the stream cancels.
    fn stream(&self, request: RawJson) -> BoxFut<'_, Result<ProviderEventStream, ExtensionError>>;
    /// `list-models`.
    fn list_models(
        &self,
        provider_id: &str,
        credential: Option<RawJson>,
    ) -> BoxFut<'_, Result<Vec<Model>, ExtensionError>>;
    /// `oauth-login`; the flow's `ui` dialogs run in `cx` (the session that asked).
    fn oauth_login(
        &self,
        provider_id: &str,
        cx: CallContext,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>>;
    /// `oauth-refresh`.
    fn oauth_refresh(
        &self,
        provider_id: &str,
        credential: RawJson,
    ) -> BoxFut<'_, Result<RawJson, ExtensionError>>;
}

/// A nested agent session (`agents.agent` resource).
pub trait AgentHandle: Send + Sync {
    /// Agent id.
    fn id(&self) -> String;
    /// Child session file.
    fn session_file(&self) -> Option<String>;
    /// `prompt` → disposition.
    fn prompt(
        &self,
        text: String,
        delivery: Option<String>,
    ) -> BoxFut<'_, Result<String, HostError>>;
    /// `steer`.
    fn steer(&self, text: String) -> BoxFut<'_, Result<(), HostError>>;
    /// `follow-up`.
    fn follow_up(&self, text: String) -> BoxFut<'_, Result<(), HostError>>;
    /// `abort`.
    fn abort(&self);
    /// `set-thinking` → clamped level.
    ///
    /// # Errors
    ///
    /// Invalid level.
    fn set_thinking(&self, level: &str) -> Result<String, HostError>;
    /// `last-assistant-text`.
    fn last_assistant_text(&self) -> Option<String>;
    /// `wait-idle`.
    fn wait_idle(&self) -> BoxFut<'_, Result<(), HostError>>;
    /// `usage` (`SessionStats` subset).
    fn usage(&self) -> RawJson;
    /// `events`: child `ClientEvent` JSON stream.
    fn events(&self) -> BoxStream<'static, String>;
    /// `close`.
    fn close(&self, grace: Duration) -> BoxFut<'_, ()>;
}

macro_rules! unsupported {
    ($name:literal) => {
        Err(HostError::unsupported($name))
    };
}

/// Implemented by `oino-core`: one method per WIT import that needs the runtime (grouped by
/// interface). Every method has a default that reports the capability as unsupported, so
/// hosts can grow coverage additively; `testing::RecordingHostServices` (feature `testing`) records all.
#[allow(unused_variables, reason = "default bodies ignore their arguments")]
pub trait HostServices: Send + Sync {
    // ── registry ──
    /// `registry.subscribe`.
    fn subscribe(&self, ext: &ExtensionId, events: &[EventKind]) {}
    /// `registry.unsubscribe`.
    fn unsubscribe(&self, ext: &ExtensionId, events: &[EventKind]) {}
    /// `registry.register-tool`.
    ///
    /// # Errors
    ///
    /// Conflicts, unsupported.
    fn register_tool(&self, ext: &ExtensionId, spec: ToolSpec) -> Result<(), HostError> {
        unsupported!("registry.register-tool")
    }
    /// `registry.unregister-tool`.
    fn unregister_tool(&self, ext: &ExtensionId, name: &str) {}
    /// `registry.register-command` → invocation name.
    ///
    /// # Errors
    ///
    /// Unsupported.
    fn register_command(&self, ext: &ExtensionId, spec: CommandSpec) -> Result<String, HostError> {
        unsupported!("registry.register-command")
    }
    /// `registry.unregister-command`.
    fn unregister_command(&self, ext: &ExtensionId, name: &str) {}
    /// `registry.register-shortcut`.
    ///
    /// # Errors
    ///
    /// Unsupported.
    fn register_shortcut(&self, ext: &ExtensionId, spec: ShortcutSpec) -> Result<(), HostError> {
        unsupported!("registry.register-shortcut")
    }
    /// `registry.unregister-shortcut`.
    fn unregister_shortcut(&self, ext: &ExtensionId, id: &str) {}
    /// `registry.register-flag`.
    ///
    /// # Errors
    ///
    /// Unsupported.
    fn register_flag(&self, ext: &ExtensionId, spec: FlagSpec) -> Result<(), HostError> {
        unsupported!("registry.register-flag")
    }
    /// `registry.get-flag`.
    fn get_flag(&self, ext: &ExtensionId, name: &str) -> Option<RawJson> {
        None
    }
    /// `registry.register-renderer`.
    fn register_renderer(&self, ext: &ExtensionId, spec: RendererSpec) {}
    /// `registry.register-service`.
    ///
    /// # Errors
    ///
    /// Unsupported.
    fn register_service(&self, ext: &ExtensionId, name: &str) -> Result<(), HostError> {
        unsupported!("registry.register-service")
    }
    /// `registry.set-arbiter-roles`.
    fn set_arbiter_roles(&self, ext: &ExtensionId, roles: ArbiterRoles) {}
    /// `registry.register-settings`.
    ///
    /// # Errors
    ///
    /// Unsupported, invalid namespace.
    fn register_settings(&self, ext: &ExtensionId, ns: RawJson) -> Result<(), HostError> {
        unsupported!("registry.register-settings")
    }
    /// `registry.extension-settings`: one namespace's values as `ext` sees them.
    ///
    /// # Errors
    ///
    /// Unsupported, invalid namespace.
    fn extension_settings(
        &self,
        ext: &ExtensionId,
        namespace: &str,
        layer: SettingsLayer,
    ) -> Result<RawJson, HostError> {
        unsupported!("registry.extension-settings")
    }
    /// `registry.set-extension-setting`: writes one key of a namespace `ext` registered.
    ///
    /// # Errors
    ///
    /// Unsupported, not the owner, invalid key or value, untrusted project, I/O.
    fn set_extension_setting(
        &self,
        ext: &ExtensionId,
        namespace: &str,
        key: &str,
        value: Option<RawJson>,
        scope: SettingsScope,
    ) -> Result<(), HostError> {
        unsupported!("registry.set-extension-setting")
    }
    /// `registry.register-provider`.
    ///
    /// # Errors
    ///
    /// Unsupported, invalid config.
    fn register_provider(&self, ext: &ExtensionId, cfg: RawJson) -> Result<(), HostError> {
        unsupported!("registry.register-provider")
    }
    /// `registry.unregister-provider`.
    fn unregister_provider(&self, ext: &ExtensionId, id: &str) {}
    /// `registry.register-virtual-model`.
    ///
    /// # Errors
    ///
    /// Unsupported, invalid definition.
    fn register_virtual_model(&self, ext: &ExtensionId, def: RawJson) -> Result<(), HostError> {
        unsupported!("registry.register-virtual-model")
    }
    /// `registry.unregister-virtual-model`.
    fn unregister_virtual_model(&self, ext: &ExtensionId, provider: &str, id: &str) {}

    // ── session ──
    /// Session reads.
    ///
    /// # Errors
    ///
    /// Stale context, unsupported.
    fn session_read(&self, cx: &CallContext, q: SessionQuery) -> Result<RawJson, HostError> {
        unsupported!("session reads")
    }
    /// Session writes → entry id for `append-entry`.
    fn session_write(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        w: SessionWrite,
    ) -> BoxFut<'_, Result<Option<String>, HostError>> {
        Box::pin(async { unsupported!("session writes") })
    }
    /// Sessions index.
    fn sessions_index(
        &self,
        ext: &ExtensionId,
        q: SessionsIndexQuery,
    ) -> BoxFut<'_, Result<RawJson, HostError>> {
        Box::pin(async { unsupported!("session.sessions-list") })
    }

    // ── control ──
    /// `control.*`.
    fn control(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        op: ControlOp,
    ) -> BoxFut<'_, Result<ControlReply, HostError>> {
        let name = op.name();
        Box::pin(async move { Err(HostError::unsupported(&format!("control.{name}"))) })
    }
    /// `control.tool-progress`.
    fn tool_progress(&self, cx: &CallContext, tool_call_id: &str, partial: RawJson) {}

    // ── models ──
    /// `models.*`.
    fn models(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        op: ModelsOp,
    ) -> BoxFut<'_, Result<ModelsReply, HostError>> {
        Box::pin(async { unsupported!("models") })
    }

    // ── ui ──
    /// `ui.dialog`.
    fn ui_dialog(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        req: RawJson,
        cancel: Option<CancellationToken>,
    ) -> BoxFut<'_, Result<RawJson, HostError>> {
        Box::pin(async { unsupported!("ui.dialog") })
    }
    /// `ui.fire`.
    ///
    /// # Errors
    ///
    /// Unsupported, invalid request.
    fn ui_fire(&self, ext: &ExtensionId, cx: &CallContext, req: RawJson) -> Result<(), HostError> {
        unsupported!("ui.fire")
    }
    /// Panels → panel id for `Open`.
    ///
    /// # Errors
    ///
    /// Unsupported.
    fn ui_panel(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        op: PanelOp,
    ) -> Result<Option<String>, HostError> {
        unsupported!("ui panels")
    }
    /// Editor → text for `Text`.
    ///
    /// # Errors
    ///
    /// Unsupported.
    fn ui_editor(&self, cx: &CallContext, op: EditorOp) -> Result<Option<String>, HostError> {
        unsupported!("ui editor")
    }
    /// Device integration.
    fn ui_device(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        op: DeviceOp,
    ) -> BoxFut<'_, Result<Option<RawJson>, HostError>> {
        Box::pin(async { unsupported!("ui device") })
    }

    // ── agents ──
    /// `agents.agent.spawn` (`AgentSpec` JSON).
    fn agent_spawn(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        spec: RawJson,
    ) -> BoxFut<'_, Result<Arc<dyn AgentHandle>, HostError>> {
        Box::pin(async { unsupported!("agents") })
    }
    /// `agents.list`.
    fn agents_list(&self, cx: &CallContext) -> RawJson {
        RawJson::from_json_value(&serde_json::Value::Array(Vec::new()))
    }

    // ── bash detach ──
    /// Takes the running foreground `bash` call `tool_call_id` of the calling session away
    /// from its tool call (which returns at once with a detach marker naming `task_id`) and
    /// hands the process over; the background-task service adopts it
    /// (`control.bash-detach`, `tasks.adopt-bash`).
    fn take_bash(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        tool_call_id: &str,
        task_id: &str,
        reason: &str,
    ) -> BoxFut<'_, Result<DetachedBash, HostError>> {
        Box::pin(async { unsupported!("bash detach") })
    }

    // ── tasks ──
    /// `tasks.*`.
    ///
    /// # Errors
    ///
    /// Unsupported, not found.
    fn tasks(&self, ext: &ExtensionId, cx: &CallContext, op: TaskOp) -> Result<RawJson, HostError> {
        unsupported!("tasks")
    }

    // ── bus / services / secrets ──
    /// `bus.publish`.
    fn bus_publish(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        topic: &str,
        data: RawJson,
        sticky: bool,
    ) {
    }
    /// `bus.subscribe` / `unsubscribe`.
    fn bus_subscribe(&self, ext: &ExtensionId, cx: &CallContext, pattern: &str, on: bool) {}
    /// `bus.get`.
    fn bus_get(&self, cx: &CallContext, topic: &str) -> Option<RawJson> {
        None
    }
    /// `services.call`.
    fn service_call(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        target: Option<&ExtensionId>,
        name: &str,
        payload: RawJson,
        timeout: Duration,
    ) -> BoxFut<'_, Result<RawJson, HostError>> {
        Box::pin(async { unsupported!("services.call") })
    }
    /// `services.list`.
    fn services_list(&self) -> Vec<(ExtensionId, String)> {
        Vec::new()
    }
    /// `secrets.*`.
    ///
    /// # Errors
    ///
    /// Unsupported, I/O.
    fn secret(&self, ext: &ExtensionId, op: SecretOp) -> Result<Option<String>, HostError> {
        unsupported!("secrets")
    }

    // ── provider-host ──
    /// Provider-level extension events.
    fn provider_hook(
        &self,
        ext: &ExtensionId,
        hook: ProviderHook,
    ) -> BoxFut<'_, ProviderHookReply> {
        let reply = hook.passthrough();
        Box::pin(async move { reply })
    }

    // ── host-info ──
    /// Runtime parts of host info.
    fn host_context(&self, cx: &CallContext) -> HostContextInfo {
        HostContextInfo::default()
    }

    // ── host-service ──
    /// `host-service.call`: one op of a host-provided service (`"browser"`, `"cron"`, …)
    /// in the caller's scope. The WASM host's hub serves this from its registered
    /// [`crate::host_service::HostService`]s first; an embedding host that does not use
    /// the hub implements this and [`HostServices::host_services`] instead. A name absent
    /// from both never reaches this method (the import answers `not-found`).
    fn host_service(
        &self,
        ext: &ExtensionId,
        cx: &CallContext,
        name: &str,
        op: &str,
        payload: RawJson,
        cancel: CancellationToken,
    ) -> BoxFut<'_, Result<RawJson, HostError>> {
        Box::pin(async { unsupported!("host-service.call") })
    }
    /// `host-service.list` / `host-service.available`: names this host provides (sorted;
    /// not permission-gated — discovery). Implement together with
    /// [`HostServices::host_service`].
    fn host_services(&self) -> Vec<String> {
        Vec::new()
    }

    // ── host-produced events ──
    /// Delivers an event produced by the runtime host itself (timers, process exits, tasks).
    fn deliver_event(
        &self,
        ext: &ExtensionId,
        session_id: &str,
        kind: EventKind,
        payload: RawJson,
    ) {
    }
}