yapi-core 0.4.1

Coding agent core: sessions, compaction, settings, resources, built-in tools, system prompt, packages, extension runner and MCP. An internal library of yapi, with no stable API.
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
//! What extensions show, as pi's `ExtensionUIContext`: dialogs,
//! notifications, footer statuses, widgets, the editor and custom components.

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

use futures_util::future::BoxFuture;
use serde_json::Value;
use tokio_util::sync::CancellationToken;

/// How a notification is shown.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotifyKind {
    /// A status message.
    #[default]
    Info,
    /// A warning.
    Warning,
    /// An error.
    Error,
}

impl NotifyKind {
    /// pi's name for the kind.
    pub fn as_str(self) -> &'static str {
        match self {
            NotifyKind::Info => "info",
            NotifyKind::Warning => "warning",
            NotifyKind::Error => "error",
        }
    }
}

/// What extensions see of the terminal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TerminalState {
    /// Its size in columns and rows.
    pub size: (usize, usize),
    /// The prompt editor, or an extension's editor in its place, has the
    /// keyboard, rather than a selector, a dialog or an extension component,
    /// as pi-tui's `focusedComponent` tells.
    pub editor_focused: bool,
}

/// pi's `ExtensionUIDialogOptions`: when a dialog closes on its own.
#[derive(Clone, Debug, Default)]
pub struct DialogOptions {
    /// Closes the dialog as cancelled after this long. Interactive dialogs
    /// count down in their title.
    pub timeout: Option<Duration>,
    /// Closes the dialog as cancelled once cancelled.
    pub cancel: Option<CancellationToken>,
}

/// pi's `WidgetPlacement`: where a widget goes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Placement {
    /// Above the editor.
    #[default]
    AboveEditor,
    /// Below the editor.
    BelowEditor,
}

/// pi's `WorkingIndicatorOptions`: the animation shown while the agent works.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WorkingIndicator {
    /// Frames drawn as given, escape sequences included. `None` keeps the
    /// default spinner frames, and an empty list hides the indicator.
    pub frames: Option<Vec<String>>,
    /// Milliseconds per frame, or `None` for the default.
    pub interval_ms: Option<u64>,
}

/// What a widget shows.
#[derive(Clone, Debug)]
pub enum Widget {
    /// Lines of text with escape sequences.
    Lines(Vec<String>),
    /// A component the extension renders.
    Component(RemoteComponent),
}

/// The extension runtime side of components: renders them and delivers
/// input to them.
pub trait ComponentHost: Send + Sync {
    /// The lines of component `handle` at `width` columns: text with escape
    /// sequences, and pi-tui's cursor marker where a focused component wants
    /// the cursor. Empty once the component is gone.
    fn render(&self, handle: u32, width: u16) -> BoxFuture<'static, Vec<String>>;

    /// Delivers raw terminal input to component `handle`.
    fn input(&self, handle: u32, data: &str);

    /// Delivers pi-tui's `TuiMouseEvent` `event` to component `handle`,
    /// after the input delivered before it. Resolves to whether the
    /// component took it, as pi-tui's `dispatchMouseEvent` decides.
    fn mouse(&self, handle: u32, event: &Value) -> BoxFuture<'static, bool>;

    /// Sends `op` to editor component `handle`, after the input delivered
    /// before it: `{"op": "setText", "text"}`, `{"op": "addToHistory",
    /// "text"}`, `{"op": "insertTextAtCursor", "text", "apart"}`, or
    /// `{"op": "configure", "border", "paddingX", "autocompleteMaxVisible",
    /// "focused", "rows"}`. `apart` sets the text apart from the words
    /// around the cursor, and `border` is a thinking level or `bashMode`.
    fn editor_op(&self, handle: u32, op: &Value);

    /// Runs the runtime's `onTerminalInput` listeners over raw input `keys`,
    /// in order. Answers the keys left to handle, as the listeners
    /// transformed them, without those they consumed or emptied.
    fn terminal_input(&self, keys: Vec<String>) -> BoxFuture<'static, Vec<String>>;

    /// The suggestions of the runtime's autocomplete providers for pi's
    /// provider arguments `request`, as for [`ExtensionUi::suggestions`],
    /// with what applying each item gives: `{"prefix", "items", "applied":
    /// [{"lines", "cursorLine", "cursorCol"}]}`, or `Null`.
    fn suggestions(&self, request: Value) -> BoxFuture<'static, Value>;
}

/// A pi-tui component that lives in an extension runtime.
#[derive(Clone)]
pub struct RemoteComponent {
    runtime: u64,
    handle: u32,
    host: Arc<dyn ComponentHost>,
}

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

impl RemoteComponent {
    /// Component `handle` of `host`, the runtime numbered `runtime`.
    pub fn new(runtime: u64, handle: u32, host: Arc<dyn ComponentHost>) -> RemoteComponent {
        RemoteComponent {
            runtime,
            handle,
            host,
        }
    }

    /// What identifies it across runtimes: the runtime's number and its
    /// handle there.
    pub fn key(&self) -> (u64, u32) {
        (self.runtime, self.handle)
    }

    /// Its lines at `width` columns (see [`ComponentHost::render`]).
    pub fn render(&self, width: u16) -> BoxFuture<'static, Vec<String>> {
        self.host.render(self.handle, width)
    }

    /// Delivers raw terminal input.
    pub fn input(&self, data: &str) {
        self.host.input(self.handle, data);
    }

    /// Delivers a mouse event (see [`ComponentHost::mouse`]).
    pub fn mouse(&self, event: &Value) -> BoxFuture<'static, bool> {
        self.host.mouse(self.handle, event)
    }

    /// Sends an operation to the editor it is, as
    /// [`ComponentHost::editor_op`] describes.
    pub fn editor_op(&self, op: &Value) {
        self.host.editor_op(self.handle, op);
    }
}

/// The options of pi's `custom`: how a custom component is shown.
#[derive(Clone, Debug, Default)]
pub struct CustomOptions {
    /// Over the screen instead of in the editor's place.
    pub overlay: bool,
    /// pi's `OverlayOptions`: anchor, size and margins.
    pub overlay_options: Value,
}

/// pi's `ExtensionUIContext` as a mode implements it. Dialogs a mode cannot
/// show resolve as cancelled. Everything else does nothing by default.
pub trait ExtensionUi: Send + Sync {
    /// Whether a person can answer dialogs.
    fn has_ui(&self) -> bool;

    /// pi's `ctx.shutdown()`: the mode exits once the agent is idle.
    fn shutdown(&self) {}

    /// Shows a message.
    fn notify(&self, message: &str, kind: NotifyKind);

    /// Shows a message that names no kind. Hosts show it as information,
    /// and RPC forwards it without a kind, as pi does.
    fn notify_untyped(&self, message: &str) {
        self.notify(message, NotifyKind::Info);
    }

    /// Asks to pick one of `options`, resolving to `None` when cancelled.
    fn select(
        &self,
        _title: &str,
        _options: Vec<String>,
        _dialog: DialogOptions,
    ) -> BoxFuture<'static, Option<String>> {
        Box::pin(async { None })
    }

    /// Asks for a line of text, resolving to `None` when cancelled.
    fn input(
        &self,
        _title: &str,
        _placeholder: Option<&str>,
        _dialog: DialogOptions,
    ) -> BoxFuture<'static, Option<String>> {
        Box::pin(async { None })
    }

    /// Asks a yes or no question, resolving to `false` when cancelled.
    fn confirm(
        &self,
        _title: &str,
        _message: &str,
        _dialog: DialogOptions,
    ) -> BoxFuture<'static, bool> {
        Box::pin(async { false })
    }

    /// Asks for multi-line text starting from `prefill`, resolving to `None`
    /// when cancelled.
    fn editor(&self, _title: &str, _prefill: Option<&str>) -> BoxFuture<'static, Option<String>> {
        Box::pin(async { None })
    }

    /// Sets the footer status `key`, or clears it.
    fn set_status(&self, _key: &str, _text: Option<&str>) {}

    /// Sets widget `key`, or removes it. Without a placement it goes above
    /// the editor.
    fn set_widget(&self, _key: &str, _widget: Option<Widget>, _placement: Option<Placement>) {}

    /// Replaces the footer, or restores the built-in one.
    fn set_footer(&self, _component: Option<RemoteComponent>) {}

    /// Replaces the startup header, or restores the built-in one.
    fn set_header(&self, _component: Option<RemoteComponent>) {}

    /// Sets the terminal title.
    fn set_title(&self, _title: &str) {}

    /// Completions an extension computed in the background are ready. The
    /// editor asks for its suggestions again.
    fn refresh_completions(&self) {}

    /// Sets the message shown while the agent works, or restores the default.
    fn set_working_message(&self, _message: Option<&str>) {}

    /// Shows or hides the indicator shown while the agent works.
    fn set_working_visible(&self, _visible: bool) {}

    /// Sets the animation shown while the agent works, or restores the
    /// default spinner.
    fn set_working_indicator(&self, _indicator: Option<WorkingIndicator>) {}

    /// Sets the label of hidden thinking blocks, or restores the default.
    fn set_hidden_thinking_label(&self, _label: Option<&str>) {}

    /// Replaces the editor's text.
    fn set_editor_text(&self, _text: &str) {}

    /// Pastes into the editor as a terminal paste would.
    fn paste_to_editor(&self, text: &str) {
        self.set_editor_text(text);
    }

    /// The editor's text.
    fn editor_text(&self) -> String {
        String::new()
    }

    /// Whether [`ExtensionUi::custom`] and component widgets are shown.
    fn shows_components(&self) -> bool {
        false
    }

    /// Replaces the editor with `editor`, or restores the built-in one.
    /// `embeds_status` when the editor shows the working status in its top
    /// border.
    fn set_editor(&self, _editor: Option<RemoteComponent>, _embeds_status: bool) {}

    /// The extension's editor now holds `text`, paste markers expanded.
    fn editor_changed(&self, _text: &str) {}

    /// The extension's editor submitted `text`.
    fn editor_submit(&self, _text: &str) {}

    /// The extension's editor asks for app action `action`, a key binding id
    /// such as `app.interrupt`.
    fn editor_action(&self, _action: &str) {}

    /// Starts passing raw input through the `onTerminalInput` listeners of
    /// extension runtime `runtime`, which `listeners` runs, or stops with
    /// `None`. Runtimes' listeners see input in the order they started.
    fn set_terminal_input(&self, _runtime: u64, _listeners: Option<Arc<dyn ComponentHost>>) {}

    /// Completes through the providers composed with
    /// `addAutocompleteProvider`, which `providers` runs. `triggers` open
    /// completion too. They replace the providers of the runtime that set
    /// them before.
    fn set_autocomplete(&self, _providers: Arc<dyn ComponentHost>, _triggers: Vec<String>) {}

    /// What the built-in provider suggests for pi's provider arguments
    /// `request`, `{"lines", "cursorLine", "cursorCol", "force"}` with
    /// UTF-16 columns: pi's `AutocompleteSuggestions`, or `Null`.
    fn suggestions(&self, _request: Value) -> BoxFuture<'static, Value> {
        Box::pin(async { Value::Null })
    }

    /// The built-in provider's `applyCompletion` for `{"lines",
    /// "cursorLine", "cursorCol", "item", "prefix"}`: `{"lines",
    /// "cursorLine", "cursorCol"}`.
    fn apply_completion(&self, _request: &Value) -> Value {
        Value::Null
    }

    /// Whether raw input `data` is an extension shortcut, which then runs.
    fn editor_shortcut(&self, _data: &str) -> bool {
        false
    }

    /// The key bindings components match keys against: `{"kitty",
    /// "bindings": {id: [key]}, "actions": [id]}`, where `actions` are the
    /// app actions an extension's editor can ask for. `Null` keeps pi-tui's
    /// defaults.
    fn keybindings(&self) -> Value {
        Value::Null
    }

    /// Shows `component` with keyboard focus until [`ExtensionUi::close`].
    fn custom(&self, _component: RemoteComponent, _options: CustomOptions) {}

    /// Removes the custom component `component`.
    fn close(&self, _component: RemoteComponent) {}

    /// Removes the editor, widgets, footer and header that extension runtime
    /// `runtime` showed, which it lost when it restarted. The built-in
    /// editor, footer and header return.
    fn drop_components(&self, _runtime: u64) {}

    /// Shows a screen of the `/mcp` manager with keyboard focus, opening the
    /// manager. [`McpScreen::Close`] closes it. Without the TUI the screen
    /// is dropped, which closes its menu.
    ///
    /// [`McpScreen::Close`]: crate::mcp::extension::McpScreen::Close
    fn mcp_manager(&self, _screen: crate::mcp::extension::McpScreen) {}

    /// Components changed and need rendering.
    fn request_render(&self) {}

    /// An extension registered transcript renderers or a Markdown
    /// transformer after its session started. What draws next uses them.
    fn renderers_changed(&self) {}

    /// Whether tool output is expanded.
    fn tools_expanded(&self) -> bool {
        false
    }

    /// Expands or collapses tool output.
    fn set_tools_expanded(&self, _expanded: bool) {}

    /// The terminal's state, kept current as it changes, or `None` without a
    /// terminal, as in print, JSON and RPC modes.
    fn terminal(&self) -> Option<tokio::sync::watch::Receiver<TerminalState>> {
        None
    }

    /// What custom footers read: `{"gitBranch", "statuses": [[key, text]],
    /// "providers"}`.
    fn footer_data(&self) -> Value {
        Value::Null
    }

    /// The theme as escape sequences, and the colors they come from:
    /// `{"name", "mode", "fg": {token: sequence}, "bg": {token: sequence},
    /// "dim": [token], "colors": {token: color}}`. `Null` leaves text
    /// unstyled.
    fn theme(&self) -> Value {
        Value::Null
    }

    /// The theme called `name`, as [`ExtensionUi::theme`] describes it, or
    /// `Null` when there is none.
    fn get_theme(&self, _name: &str) -> Value {
        Value::Null
    }

    /// pi's `getAllThemes`: the themes [`ExtensionUi::set_theme`] can switch
    /// to, as `[{"name", "path"}]` with no `path` for a theme without a file.
    /// Empty without a UI that switches themes, as in pi's RPC mode.
    fn all_themes(&self) -> Value {
        Value::Array(Vec::new())
    }

    /// Switches to `theme`: a theme name, which is saved as `/settings`
    /// saves it, or a theme document `{"name", "appearance", "colors"}`,
    /// which is not saved. The error says why it could not.
    fn set_theme(&self, _theme: &Value) -> Result<(), String> {
        Err("UI not available".into())
    }

    /// A handler of extension `path` failed on `event`, with the error's
    /// stack when the runtime gave one. By default it reports as print mode
    /// does.
    fn extension_error(&self, path: &str, _event: &str, error: &str, _stack: Option<&str>) {
        use std::io::Write as _;
        let _ = writeln!(std::io::stderr(), "Extension error ({path}): {error}");
    }
}

/// The UI of print and JSON modes: nothing is shown.
pub struct NoUi;

impl ExtensionUi for NoUi {
    fn has_ui(&self) -> bool {
        false
    }

    fn notify(&self, _message: &str, _kind: NotifyKind) {}
}