oino-core 1.0.0

Coding-agent runtime for Oino: AgentSession, extension runner, compaction, retry
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
//! Host calls made by extensions (≈ `HostServices`, extension-api.md §6), as one typed
//! operation enum. `oino-core` implements [`HostApi`]; a WASM host forwards guest imports to it.

use futures::future::BoxFuture;
use oino_ai::{JsonValue, ThinkingLevel, UserContentField};
use serde::{Deserialize, Serialize};
use tokio_util::sync::CancellationToken;

use super::api::{ArbiterRoles, CallContext, CommandSpec, FlagSpec, ShortcutSpec, ToolSpec};
use crate::agents::ChildAgent;

/// Delivery of extension messages.
#[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,
}

/// `sendMessage` draft.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomMessageDraft {
    /// Extension-defined type.
    pub custom_type: String,
    /// Content.
    #[serde(default)]
    pub content: UserContentField,
    /// Render in frontends.
    #[serde(default)]
    pub display: bool,
    /// Metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<JsonValue>,
}

/// Read-only session queries.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "query", rename_all = "kebab-case")]
pub enum SessionQuery {
    /// Header.
    Header,
    /// All entries.
    Entries,
    /// Root → leaf path.
    Branch,
    /// One entry.
    Entry {
        /// Entry id.
        id: String,
    },
    /// Tree.
    Tree,
    /// Projection at the leaf.
    Projection,
    /// Context-selected entries.
    ContextEntries,
    /// Label of an entry.
    Label {
        /// Entry id.
        id: String,
    },
    /// Session name.
    Name,
    /// Leaf id.
    Leaf,
    /// Session id.
    Id,
    /// Session file.
    File,
}

/// Every host operation an extension can perform.
#[allow(
    clippy::large_enum_variant,
    reason = "operations are built once per call and moved, never stored"
)]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum HostOp {
    /// Subscribe to event kinds.
    Subscribe(Vec<String>),
    /// Unsubscribe from event kinds.
    Unsubscribe(Vec<String>),
    /// Register (or replace own) tool.
    RegisterTool(ToolSpec),
    /// Remove own tool.
    UnregisterTool(String),
    /// Register a command; returns its invocation name.
    RegisterCommand(CommandSpec),
    /// Remove own command.
    UnregisterCommand(String),
    /// Register a shortcut.
    RegisterShortcut(ShortcutSpec),
    /// Remove a shortcut.
    UnregisterShortcut(String),
    /// Register a CLI flag.
    RegisterFlag(FlagSpec),
    /// Read a flag value.
    GetFlag(String),
    /// Register a render spec.
    RegisterRenderer(JsonValue),
    /// Register a provider (extension-api §4.4 JSON).
    RegisterProvider(JsonValue),
    /// Remove a provider.
    UnregisterProvider(String),
    /// Register a virtual model.
    RegisterVirtualModel(JsonValue),
    /// Remove a virtual model.
    UnregisterVirtualModel {
        /// Provider id.
        provider: String,
        /// Model id.
        id: String,
    },
    /// Read session data.
    SessionRead(SessionQuery),
    /// Appends an entry (`appendEntry(customType, data)`); returns the entry id.
    AppendEntry {
        /// Custom type.
        custom_type: String,
        /// Payload.
        data: Option<JsonValue>,
    },
    /// Sends a message into the session.
    SendMessage {
        /// Draft.
        message: CustomMessageDraft,
        /// Trigger a turn.
        trigger_turn: bool,
        /// Delivery mode.
        deliver_as: Option<Delivery>,
    },
    /// Sends a user message into the session.
    SendUserMessage {
        /// Content.
        content: UserContentField,
        /// Delivery mode while streaming.
        deliver_as: Option<Delivery>,
    },
    /// Sets the session name.
    SetSessionName(String),
    /// Sets the entry label.
    SetLabel {
        /// Entry id.
        entry_id: String,
        /// Label (`None` clears).
        label: Option<String>,
    },
    /// Returns the active tools.
    GetActiveTools,
    /// Returns every tool.
    GetAllTools,
    /// Sets the active tools.
    SetActiveTools(Vec<String>),
    /// Returns the registered commands.
    GetCommands,
    /// Sets the model; returns `true` when auth is configured and the model was set.
    SetModel {
        /// Provider id.
        provider: String,
        /// Model id.
        id: String,
    },
    /// `control.set-default-model`: writes the fresh-session model to core settings
    /// (`defaultProvider`/`defaultModel`/`modelThinkingLevels`) without touching this session.
    SetDefaultModel {
        /// Provider id.
        provider: String,
        /// Model id.
        id: String,
        /// Thinking level remembered for that model.
        thinking: Option<ThinkingLevel>,
    },
    /// Current model (`null` when none).
    GetModel,
    /// Returns the current thinking level.
    GetThinkingLevel,
    /// Sets the thinking level.
    SetThinkingLevel(ThinkingLevel),
    /// Returns whether the session is idle.
    IsIdle,
    /// Aborts the current turn.
    Abort,
    /// Returns whether messages are pending.
    HasPendingMessages,
    /// Returns the context usage.
    GetContextUsage,
    /// Triggers compaction.
    Compact {
        /// Custom instructions.
        custom_instructions: Option<String>,
    },
    /// Returns the current system prompt.
    GetSystemPrompt,
    /// The merged settings object.
    GetSettings,
    /// Models with configured credentials (`control.models-list`).
    GetAvailableModels,
    /// The `--models` / `enabledModels` scope (`control.scoped-models`).
    GetScopedModels,
    /// The model a virtual selection currently routes to (`control.routed-model`).
    GetRoutedModel,
    /// Session stats (`control.session-stats`).
    GetSessionStats,
    /// Project trust decision (`control.is-project-trusted`).
    IsProjectTrusted,
    /// `models.complete`: one non-session completion → `AssistantMessage`.
    ModelComplete {
        /// `provider/id` (default: the session model).
        model: Option<String>,
        /// `Context` JSON (`{messages}`).
        context: JsonValue,
        /// `StreamOptions` JSON.
        options: JsonValue,
        /// Caller cancellation.
        cancel: Option<CancellationToken>,
    },
    /// `models.summarize-default`: core's compaction summariser → `{summary, usage}`.
    SummarizeDefault {
        /// `Vec<AgentMessage>` JSON.
        messages: JsonValue,
        /// Extra focus.
        custom_instructions: Option<String>,
        /// Earlier summary to update.
        previous_summary: Option<String>,
    },
    /// Waits for idle (`ctx.waitForIdle`, command context only).
    WaitForIdle,
    /// Navigates the tree (`ctx.navigateTree`, command context only).
    NavigateTree {
        /// Target entry.
        target_id: String,
        /// Summarise the abandoned branch.
        summarize: bool,
        /// Custom instructions.
        custom_instructions: Option<String>,
        /// Replace the default prompt.
        replace_instructions: bool,
        /// Label for the summary or target.
        label: Option<String>,
    },
    /// Raise a dialog (`select`, `confirm`, …) and wait for the answer.
    UiDialog {
        /// Method.
        method: String,
        /// Fields.
        params: oino_ai::JsonObject,
        /// Caller cancel token.
        cancel: Option<CancellationToken>,
    },
    /// Fire-and-forget UI request.
    UiFire {
        /// Method.
        method: String,
        /// Fields.
        params: oino_ai::JsonObject,
    },
    /// `ctx.executeTool`: runs a callable tool nested under `parent_tool_call_id`.
    ExecuteTool {
        /// Running tool call that makes the call.
        parent_tool_call_id: String,
        /// Tool name.
        name: String,
        /// Arguments.
        args: oino_ai::JsonObject,
    },
    /// Invoke another extension's command (`command-invoke`).
    InvokeCommand {
        /// Invocation name.
        name: String,
        /// Arguments.
        args: String,
    },
    /// Declare turn arbiter roles (`registry.set-arbiter-roles`).
    SetArbiterRoles(ArbiterRoles),
    /// Nested agents of the calling session (`agents.list`).
    ListAgents,
    /// `control.run-state`: `{state, waitingOn?}`.
    GetRunState,
    /// `control.shutdown`: asks the frontend to exit when idle.
    Shutdown,
    /// `control.system-prompt-options` (command context only).
    GetSystemPromptOptions,
    /// `control.new-session` (command context only) → `{cancelled}`.
    NewSession {
        /// `parentSession` of the new header.
        parent_session: Option<std::path::PathBuf>,
    },
    /// `control.fork` (command context only) → `{cancelled, selectedText?}`.
    Fork {
        /// Entry to fork from.
        entry_id: String,
        /// Fork at the entry (`true`) or before it.
        at: bool,
    },
    /// `control.switch-session` (command context only) → `{cancelled}`.
    SwitchSession(std::path::PathBuf),
    /// `control.reload` (command context only).
    Reload,
    /// `registry.register-settings`: a ui-protocol §6.6 namespace declaration.
    RegisterSettings(JsonValue),
    /// `registry.extension-settings`: one namespace's values as the caller sees them.
    GetExtensionSettings {
        /// Namespace.
        namespace: String,
        /// Layer.
        layer: crate::extensions::settings::SettingsLayer,
    },
    /// `registry.set-extension-setting`: writes one key of an owned namespace.
    SetExtensionSetting {
        /// Namespace.
        namespace: String,
        /// Dot-path key.
        key: String,
        /// Value (`None` deletes: "use default").
        value: Option<JsonValue>,
        /// Target file.
        scope: oino_settings::SettingsScope,
    },
    /// `{namespace: values}` of every known namespace as the caller sees them (init input).
    GetAllExtensionSettings,
    /// `ui.editor-text`: the composer text last reported by the frontend
    /// (`editor_event`, ui-protocol §7.1).
    EditorText,
    /// `models.credential-for`: `{provider, headers, baseUrl?}` for a provider, or `null`.
    CredentialFor(String),
    /// `bus.publish` mirror: records sticky topics and feeds subscribed frontends
    /// (`_oino/topics`). Served by the host router, independent of any session.
    BusPublish {
        /// Topic.
        topic: String,
        /// Payload.
        data: JsonValue,
        /// Sticky.
        sticky: bool,
    },
    /// `bus.get` (hosts without their own bus): last sticky value or `null`.
    BusGet(String),
    /// `control.running-bash`: `[{toolCallId, command, startedAt, pid?}]` of the session.
    RunningBash,
    /// `host-info.get` frontends: `["desktop", "rpc", …]` attached to the session.
    GetFrontends,
}

impl HostOp {
    /// Bus operations, served by the host router independent of any session.
    #[must_use]
    pub fn is_bus_op(&self) -> bool {
        matches!(self, Self::BusPublish { .. } | Self::BusGet(_))
    }

    /// Operations served by the settings registry, independent of any session.
    #[must_use]
    pub fn is_settings_op(&self) -> bool {
        matches!(
            self,
            Self::RegisterSettings(_)
                | Self::GetExtensionSettings { .. }
                | Self::SetExtensionSetting { .. }
                | Self::GetAllExtensionSettings
                | Self::GetSettings
        )
    }
}

/// A `models.complete` / `models.stream` request.
#[derive(Clone, Debug, Default)]
pub struct ModelRequest {
    /// `provider/id`; the session model when absent.
    pub model: Option<String>,
    /// `Context` JSON.
    pub context: JsonValue,
    /// `StreamOptions` JSON (`null` = defaults).
    pub options: JsonValue,
    /// Caller cancellation.
    pub cancel: Option<CancellationToken>,
}

/// Failure of a host operation.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum HostError {
    /// The caller's session was replaced or disposed.
    #[error("{0}")]
    StaleContext(String),
    /// Session-replacing operations need a command or shortcut context.
    #[error("This operation is only available in command and shortcut contexts")]
    CommandContextRequired,
    /// Invalid input.
    #[error("{0}")]
    Invalid(String),
    /// Name already registered by another extension.
    #[error("{0}")]
    Conflict(String),
    /// The operation failed.
    #[error("{0}")]
    Failed(String),
}

/// Implemented by `oino-core`; extensions call it with their id and call context.
pub trait HostApi: Send + Sync {
    /// Performs `op` for extension `extension` in the session of `cx`.
    fn call<'a>(
        &'a self,
        extension: &'a str,
        cx: &'a CallContext,
        op: HostOp,
    ) -> BoxFuture<'a, Result<JsonValue, HostError>>;

    /// `models.stream`: streams one completion (`AssistantMessageEvent` JSON items) in the
    /// session of `cx`; same model/credential resolution as [`HostOp::ModelComplete`].
    fn model_stream<'a>(
        &'a self,
        _extension: &'a str,
        _cx: &'a CallContext,
        _request: ModelRequest,
    ) -> BoxFuture<'a, Result<futures::stream::BoxStream<'static, JsonValue>, HostError>> {
        Box::pin(async {
            Err(HostError::Failed(
                "models.stream is not supported by this host".into(),
            ))
        })
    }

    /// `control.bash-detach` / `tasks.adopt-bash`: detaches the running `bash` call
    /// `tool_call_id` of the session of `cx` into background task `task_id`.
    fn detach_bash<'a>(
        &'a self,
        _extension: &'a str,
        _cx: &'a CallContext,
        _tool_call_id: &'a str,
        _task_id: &'a str,
        _reason: &'a str,
    ) -> BoxFuture<'a, Result<crate::session::DetachedBash, HostError>> {
        Box::pin(async {
            Err(HostError::Failed(
                "bash detach is not supported by this host".into(),
            ))
        })
    }

    /// `agents.spawn`: creates a nested `AgentSession` under the session of `cx`
    /// (runtime §12). `spec` is the `AgentSpec` JSON.
    fn spawn_agent<'a>(
        &'a self,
        _extension: &'a str,
        _cx: &'a CallContext,
        _spec: JsonValue,
    ) -> BoxFuture<'a, Result<std::sync::Arc<ChildAgent>, HostError>> {
        Box::pin(async {
            Err(HostError::Failed(
                "agents is not supported by this host".into(),
            ))
        })
    }
}