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
//! Host operation enums: one variant per WIT function of the interfaces that
//! [`crate::HostServices`] serves (same names in `UpperCamelCase`, same parameters).

use std::fmt;

use futures::stream::BoxStream;
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;

use crate::json::RawJson;

// ── session ──────────────────────────────────────────────────────────────

/// `session.delivery`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Delivery {
    /// Steering queue.
    Steer,
    /// Follow-up queue.
    FollowUp,
    /// With the next user prompt.
    NextTurn,
}

/// `session.provenance` (the embedding harness provenance).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Provenance {
    /// Source (extension or subsystem).
    pub source: String,
    /// Title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Synopsis.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub synopsis: Option<String>,
    /// Severity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub severity: Option<String>,
}

/// `session.send-options`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SendOptions {
    /// Trigger a turn when idle.
    pub trigger_turn: bool,
    /// Delivery while streaming.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deliver_as: Option<Delivery>,
    /// Provenance.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<Provenance>,
}

/// `session.user-message-options`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserMessageOptions {
    /// Delivery while streaming.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deliver_as: Option<Delivery>,
    /// Expand prompt templates.
    pub expand_prompt_templates: bool,
    /// Provenance.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<Provenance>,
}

/// `session.sessions-scope`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SessionsScope {
    /// Sessions of the current cwd.
    Cwd,
    /// All sessions.
    All,
}

/// Session reads; results are `oino_session` JSON.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "kebab-case")]
pub enum SessionQuery {
    /// `header` → `SessionHeader`.
    Header,
    /// `session-id` → string.
    SessionId,
    /// `session-file` → string | null.
    SessionFile,
    /// `leaf-id` → string | null.
    LeafId,
    /// `entry` → `SessionEntry` | null.
    Entry {
        /// Entry id.
        id: String,
    },
    /// `entries` → all entries in file order.
    Entries,
    /// `branch` → root → `from` (default leaf).
    Branch {
        /// Branch tip.
        from: Option<String>,
    },
    /// `context-entries`.
    ContextEntries,
    /// `projection`.
    Projection,
    /// `tree`.
    Tree,
    /// `label` → string | null.
    Label {
        /// Entry id.
        id: String,
    },
    /// `session-name` → string | null.
    SessionName,
}

/// Session writes.
#[derive(Clone, Debug, PartialEq)]
pub enum SessionWrite {
    /// `set-session-name`.
    SetSessionName(Option<String>),
    /// `set-label`.
    SetLabel {
        /// Entry id.
        id: String,
        /// Label (`None` clears).
        label: Option<String>,
    },
    /// `append-entry` → entry id.
    AppendEntry {
        /// Custom type.
        custom_type: String,
        /// Data.
        data: Option<RawJson>,
    },
    /// `send-message`: `{customType, content, display, details?}`.
    SendMessage {
        /// Message JSON.
        message: RawJson,
        /// Options.
        options: SendOptions,
    },
    /// `send-user-message`: `UserContentField`.
    SendUserMessage {
        /// Content JSON.
        content: RawJson,
        /// Options.
        options: UserMessageOptions,
    },
}

/// Sessions index (C7).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SessionsIndexQuery {
    /// `sessions-list` → `Vec<SessionInfo>`.
    List(SessionsScope),
    /// `session-read` → `{header, entries}`.
    Read {
        /// Session file path.
        path: String,
    },
}

// ── control ──────────────────────────────────────────────────────────────

/// `control` operations (except `tool-progress`, which is fire-and-forget).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ControlOp {
    /// `model` → `Model` | null.
    Model,
    /// `routed-model`.
    RoutedModel,
    /// `set-model` → bool.
    SetModel {
        /// Provider id.
        provider: String,
        /// Model id.
        id: String,
    },
    /// `set-default-model` → bool: persists the fresh-session model in core settings.
    SetDefaultModel {
        /// Provider id.
        provider: String,
        /// Model id.
        id: String,
        /// Thinking level to remember for that model.
        thinking: Option<String>,
    },
    /// `thinking-level` → string.
    ThinkingLevel,
    /// `set-thinking-level` → clamped level.
    SetThinkingLevel(String),
    /// `models-list` → `Vec<Model>`.
    ModelsList,
    /// `scoped-models`.
    ScopedModels,
    /// `run-state`.
    RunState,
    /// `is-idle` → bool.
    IsIdle,
    /// `has-pending-messages` → bool.
    HasPendingMessages,
    /// `context-usage`.
    ContextUsage,
    /// `session-stats`.
    SessionStats,
    /// `system-prompt` → string.
    SystemPrompt,
    /// `is-project-trusted` → bool.
    IsProjectTrusted,
    /// `get-settings`.
    GetSettings,
    /// `abort`.
    Abort,
    /// `compact` → `CompactionResult`.
    Compact {
        /// Custom instructions.
        custom_instructions: Option<String>,
    },
    /// `shutdown`.
    Shutdown,
    /// `system-prompt-options` (command context).
    SystemPromptOptions,
    /// `wait-for-idle` (command context).
    WaitForIdle,
    /// `new-session` → cancelled? (command context).
    NewSession {
        /// Parent session file.
        parent_session: Option<String>,
    },
    /// `fork` → `{cancelled, selectedText?}` (command context).
    Fork {
        /// Entry id.
        entry_id: String,
        /// Fork at (true) or before (false) the entry.
        at: bool,
    },
    /// `switch-session` → cancelled? (command context).
    SwitchSession {
        /// Session file.
        path: String,
    },
    /// `navigate-tree` (command context).
    NavigateTree {
        /// Target entry.
        target_id: String,
        /// `NavigateTreeOptions` JSON.
        options: RawJson,
    },
    /// `reload` (command context).
    Reload,
    /// `active-tools` → names.
    ActiveTools,
    /// `set-active-tools`.
    SetActiveTools(Vec<String>),
    /// `all-tools` → `Vec<ToolInfo>`.
    AllTools,
    /// `commands-list` → `Vec<SlashCommandInfo>`.
    CommandsList,
    /// `command-invoke` → optional JSON.
    CommandInvoke {
        /// Invocation name.
        name: String,
        /// Arguments.
        args: String,
    },
    /// `execute-tool` → `AgentToolCallOutcome` (tool-call context).
    ExecuteTool {
        /// Tool name.
        name: String,
        /// Arguments JSON.
        args: RawJson,
        /// Caller cancellation.
        cancel: Option<CancellationToken>,
    },
    /// `bash-detach` → task id.
    BashDetach {
        /// Running bash tool call.
        tool_call_id: String,
        /// Reason.
        reason: String,
    },
    /// `running-bash`.
    RunningBash,
}

impl ControlOp {
    /// WIT function name (for errors and permission messages).
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Model => "model",
            Self::RoutedModel => "routed-model",
            Self::SetModel { .. } => "set-model",
            Self::SetDefaultModel { .. } => "set-default-model",
            Self::ThinkingLevel => "thinking-level",
            Self::SetThinkingLevel(_) => "set-thinking-level",
            Self::ModelsList => "models-list",
            Self::ScopedModels => "scoped-models",
            Self::RunState => "run-state",
            Self::IsIdle => "is-idle",
            Self::HasPendingMessages => "has-pending-messages",
            Self::ContextUsage => "context-usage",
            Self::SessionStats => "session-stats",
            Self::SystemPrompt => "system-prompt",
            Self::IsProjectTrusted => "is-project-trusted",
            Self::GetSettings => "get-settings",
            Self::Abort => "abort",
            Self::Compact { .. } => "compact",
            Self::Shutdown => "shutdown",
            Self::SystemPromptOptions => "system-prompt-options",
            Self::WaitForIdle => "wait-for-idle",
            Self::NewSession { .. } => "new-session",
            Self::Fork { .. } => "fork",
            Self::SwitchSession { .. } => "switch-session",
            Self::NavigateTree { .. } => "navigate-tree",
            Self::Reload => "reload",
            Self::ActiveTools => "active-tools",
            Self::SetActiveTools(_) => "set-active-tools",
            Self::AllTools => "all-tools",
            Self::CommandsList => "commands-list",
            Self::CommandInvoke { .. } => "command-invoke",
            Self::ExecuteTool { .. } => "execute-tool",
            Self::BashDetach { .. } => "bash-detach",
            Self::RunningBash => "running-bash",
        }
    }

    /// Requires manifest permission `sessionControl`.
    #[must_use]
    pub fn needs_session_control(&self) -> bool {
        matches!(
            self,
            Self::SetModel { .. }
                | Self::SetDefaultModel { .. }
                | Self::SetThinkingLevel(_)
                | Self::Abort
                | Self::Compact { .. }
                | Self::Shutdown
                | Self::SetActiveTools(_)
                | Self::NewSession { .. }
                | Self::Fork { .. }
                | Self::SwitchSession { .. }
                | Self::NavigateTree { .. }
                | Self::Reload
        )
    }

    /// Only valid in command/shortcut contexts.
    #[must_use]
    pub fn needs_command_context(&self) -> bool {
        matches!(
            self,
            Self::SystemPromptOptions
                | Self::WaitForIdle
                | Self::NewSession { .. }
                | Self::Fork { .. }
                | Self::SwitchSession { .. }
                | Self::NavigateTree { .. }
                | Self::Reload
        )
    }
}

/// Result of a [`ControlOp`].
#[derive(Clone, Debug, PartialEq)]
pub enum ControlReply {
    /// No value.
    Unit,
    /// Boolean.
    Bool(bool),
    /// String.
    String(String),
    /// String list.
    Strings(Vec<String>),
    /// JSON value.
    Json(RawJson),
    /// Optional JSON value.
    MaybeJson(Option<RawJson>),
}

// ── models ───────────────────────────────────────────────────────────────

/// `models.credential`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Credential {
    /// Headers to add.
    pub headers: Vec<(String, String)>,
    /// Base URL override.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    /// Provider id.
    pub provider: String,
}

/// `models` operations (permission `models.complete`, `credentials`).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ModelsOp {
    /// `complete` → `AssistantMessage`.
    Complete {
        /// `CompletionRequest` JSON.
        request: RawJson,
        /// Caller cancellation.
        cancel: Option<CancellationToken>,
    },
    /// `stream` → `AssistantMessageEvent` JSON items.
    Stream {
        /// `CompletionRequest` JSON.
        request: RawJson,
    },
    /// `summarize-default` → `{summary, usage?}`.
    SummarizeDefault {
        /// `Vec<AgentMessage>` JSON.
        messages: RawJson,
        /// Custom instructions.
        custom_instructions: Option<String>,
        /// Summary of the earlier messages: the call then updates it.
        previous_summary: Option<String>,
    },
    /// `credential-for`.
    CredentialFor(String),
    /// `classify`.
    Classify(RawJson),
    /// `generate-image`.
    GenerateImage(RawJson),
}

/// Result of a [`ModelsOp`].
pub enum ModelsReply {
    /// JSON value.
    Json(RawJson),
    /// Stream of JSON items.
    Stream(BoxStream<'static, String>),
    /// Credential (none when unavailable).
    Credential(Option<Credential>),
}

impl fmt::Debug for ModelsReply {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Json(json) => f.debug_tuple("Json").field(json).finish(),
            Self::Stream(_) => f.write_str("Stream(..)"),
            Self::Credential(c) => f.debug_tuple("Credential").field(c).finish(),
        }
    }
}

// ── ui ───────────────────────────────────────────────────────────────────

/// Panel operations (ui-protocol §5).
#[derive(Clone, Debug, PartialEq)]
pub enum PanelOp {
    /// `panel-open` → panel id.
    Open(RawJson),
    /// `panel-update`.
    Update {
        /// Panel id.
        panel_id: String,
        /// Spec.
        spec: RawJson,
    },
    /// `panel-close`.
    Close(String),
}

/// Editor operations (ui-protocol §7).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EditorOp {
    /// `editor-text` → text.
    Text,
    /// `editor-set`.
    Set(String),
    /// `editor-insert`.
    Insert(String),
}

/// Device integration (permissions `osNotify`, `clipboard.*`, `openUrl`, `editExternally`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviceOp {
    /// `os-notify`.
    OsNotify {
        /// Title.
        title: String,
        /// Body.
        body: String,
        /// Urgency (`low`|`normal`|`critical`).
        urgency: String,
        /// URL opened on click.
        action_url: Option<String>,
    },
    /// `clipboard-write-text`.
    ClipboardWriteText(String),
    /// `clipboard-read-image` → `ImageContent` | none.
    ClipboardReadImage,
    /// `open-url`.
    OpenUrl(String),
    /// `edit-externally` → edited text | none.
    EditExternally {
        /// Initial text.
        text: String,
        /// File extension hint.
        extension_hint: Option<String>,
    },
}

// ── tasks / secrets ──────────────────────────────────────────────────────

/// `tasks` operations (C12).
#[derive(Clone, Debug, PartialEq)]
pub enum TaskOp {
    /// `start` (`TaskSpec` JSON) → task id.
    Start(RawJson),
    /// `adopt-bash` → task id.
    AdoptBash {
        /// Running bash tool call.
        tool_call_id: String,
        /// Reason.
        reason: String,
    },
    /// `list` → `Vec<TaskInfo>`.
    List,
    /// `get` → `TaskInfo` | null.
    Get(String),
    /// `logs` → text.
    Logs {
        /// Task id.
        id: String,
        /// Max bytes.
        max_bytes: u32,
        /// From the end.
        tail: bool,
    },
    /// `kill`.
    Kill(String),
    /// `clear-finished`.
    ClearFinished,
}

/// `secrets` operations (namespaced to the calling extension).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SecretOp {
    /// `get`.
    Get(String),
    /// `set`.
    Set {
        /// Name.
        name: String,
        /// Value.
        value: String,
    },
    /// `delete`.
    Delete(String),
}

// ── settings ─────────────────────────────────────────────────────────────

/// Settings file a write targets (`registry.settings-scope`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SettingsScope {
    /// `<agent>/settings.json` (and the secret store for secret fields).
    Global,
    /// `<cwd>/.oino/settings.json` (trusted projects only).
    Project,
}

/// Values a settings read returns (`registry.settings-layer`).
#[derive(
    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "lowercase")]
pub enum SettingsLayer {
    /// `defaults ⊕ global ⊕ project`.
    #[default]
    Effective,
    /// The global file's values.
    Global,
    /// The project file's values.
    Project,
}

// ── provider-host ────────────────────────────────────────────────────────

/// `provider-host` calls made by provider components.
#[derive(Clone, Debug, PartialEq)]
pub enum ProviderHook {
    /// `before-request`: dispatch `before_provider_headers` then `before_provider_request`.
    BeforeRequest {
        /// `requestId` from the stream request.
        request_id: String,
        /// Wire payload.
        payload: RawJson,
        /// Request headers.
        headers: Vec<(String, String)>,
    },
    /// `after-response` (`after_provider_response`).
    AfterResponse {
        /// Request id.
        request_id: String,
        /// HTTP status.
        status: u16,
        /// Response headers.
        headers: Vec<(String, String)>,
    },
    /// `stream-event` (`provider_stream_event`).
    StreamEvent {
        /// Request id.
        request_id: String,
        /// Raw event JSON.
        data: RawJson,
    },
}

/// Reply to a [`ProviderHook`].
#[derive(Clone, Debug, PartialEq)]
pub enum ProviderHookReply {
    /// Possibly replaced payload and headers.
    BeforeRequest {
        /// Payload.
        payload: RawJson,
        /// Headers.
        headers: Vec<(String, String)>,
    },
    /// Acknowledged.
    Done,
}

impl ProviderHook {
    /// The pass-through reply (no extension changed anything).
    #[must_use]
    pub fn passthrough(&self) -> ProviderHookReply {
        match self {
            Self::BeforeRequest {
                payload, headers, ..
            } => ProviderHookReply::BeforeRequest {
                payload: payload.clone(),
                headers: headers.clone(),
            },
            Self::AfterResponse { .. } | Self::StreamEvent { .. } => ProviderHookReply::Done,
        }
    }
}

// ── host-info ────────────────────────────────────────────────────────────

/// `host-info.workspace-info` (D10).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceInfo {
    /// `wsid`: first 16 hex chars of sha256(canonical project root).
    pub id: String,
    /// Canonical project root.
    pub root: String,
    /// Git root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_root: Option<String>,
    /// Git branch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_branch: Option<String>,
    /// cwd.
    pub cwd: String,
}

/// Host information that needs the runtime.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HostContextInfo {
    /// Attached frontends (`tui`, `desktop`, `mobile`, `rpc`, `acp`).
    pub frontends: Vec<String>,
    /// A frontend currently has focus.
    pub frontend_focused: bool,
    /// Workspace override (`None` = computed by the host from the call cwd).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<WorkspaceInfo>,
}