standard-plugin-sdk 0.1.1

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
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
//! The account interfaces shared by UI and daemon plugins, and the viewer
//! interfaces of UI plugins.
//!
//! Each interface is a zero-sized handle returned by a function of the same
//! name ([`values()`], [`events()`], ...) and by the matching method of the
//! plugin's context. Every call is checked against the manifest's grants; a
//! call they do not cover returns [`Error::GrantDenied`] naming the grant.
//! Payloads are JSON: typed values go through `serde`.

use alloc::string::String;
use alloc::vec::Vec;

use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::error::{Error, Result};
use crate::host;

/// A JSON document as the host passes it: a value, a live message, an
/// event payload, a call's request or response.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Json(pub String);

impl Json {
    /// Serializes `value`.
    pub fn from_value<T: Serialize + ?Sized>(value: &T) -> Result<Self> {
        serde_json::to_string(value).map(Self).map_err(Error::json)
    }

    /// Deserializes the document.
    pub fn parse<T: DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_str(&self.0).map_err(Error::json)
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

/// Where an event or call is delivered.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Target {
    /// Every listener on the account.
    All,
    /// Every viewer.
    Viewers,
    /// Every daemon.
    Daemons,
    /// The daemon on one machine, by machine id.
    Machine(String),
    /// The singleton daemon instance of the plugin.
    Singleton,
}

/// Durable key-value state on the account. Keys under the plugin's own id
/// (`<id>.<rest>`) need no grant; others need `values.read:<prefix>` /
/// `values.write:<prefix>`.
pub mod values {
    use super::*;

    #[derive(Clone, Copy, Debug, Default)]
    pub struct Values;

    impl Values {
        pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
            match host::values_get(key)? {
                Some(json) => Json(json).parse().map(Some),
                None => Ok(None),
            }
        }

        pub fn get_json(&self, key: &str) -> Result<Option<Json>> {
            Ok(host::values_get(key)?.map(Json))
        }

        pub fn set<T: Serialize + ?Sized>(&self, key: &str, value: &T) -> Result<()> {
            host::values_set(key, &Json::from_value(value)?.0)
        }

        pub fn delete(&self, key: &str) -> Result<()> {
            host::values_delete(key)
        }

        /// The keys under `prefix`.
        pub fn keys(&self, prefix: &str) -> Result<Vec<String>> {
            host::values_keys(prefix)
        }

        /// Asks for [`crate::Event::ValueChanged`] for keys under `prefix`.
        pub fn watch(&self, prefix: &str) -> Result<()> {
            host::values_watch(prefix)
        }
    }
}

/// The unstored latest-value channel: a publisher replaces the value, a
/// subscriber sees the newest one ([`crate::Event::Live`]). The own
/// namespace needs no grant; others need `live.publish:<prefix>` /
/// `live.subscribe:<prefix>`.
pub mod live {
    use super::*;

    #[derive(Clone, Copy, Debug, Default)]
    pub struct Live;

    impl Live {
        pub fn publish<T: Serialize + ?Sized>(&self, key: &str, payload: &T) -> Result<()> {
            host::live_publish(key, &Json::from_value(payload)?.0)
        }

        /// Withdraws the latest value of `key`: subscribers hear
        /// [`crate::Event::LiveDeleted`] (a pane that closed, a machine
        /// that has nothing to report), and later subscribers see nothing.
        pub fn delete(&self, key: &str) -> Result<()> {
            host::live_delete(key)
        }

        pub fn subscribe(&self, prefix: &str) -> Result<()> {
            host::live_subscribe(prefix)
        }

        pub fn unsubscribe(&self, prefix: &str) -> Result<()> {
            host::live_unsubscribe(prefix)
        }
    }
}

/// Named, unstored messages between plugins ([`crate::Event::Plugin`]).
/// The plugin's own namespace (`<id>.*`) needs no grant; `global.*`,
/// another plugin's namespace and `system.*` need `events.emit:<ns>` or
/// `events.on:<ns>`. Nothing may emit into `system.*`.
pub mod events {
    use super::*;

    #[derive(Clone, Copy, Debug, Default)]
    pub struct Events;

    impl Events {
        pub fn emit<T: Serialize + ?Sized>(
            &self,
            name: &str,
            payload: &T,
            to: Target,
        ) -> Result<()> {
            host::events_emit(name, &Json::from_value(payload)?.0, &to)
        }

        /// Listens to events whose names match `pattern` (`git.*`).
        pub fn on(&self, pattern: &str) -> Result<()> {
            host::events_on(pattern)
        }

        pub fn off(&self, pattern: &str) -> Result<()> {
            host::events_off(pattern)
        }
    }
}

/// Request and response to the plugin's companion daemon. Grant:
/// `call:<plugin id>`.
///
/// A UI plugin prefers [`Calls::send`] and [`Calls::call_async`]: neither
/// blocks, so `event` and `frame` stay within their budgets while the
/// companion works. [`Calls::call`] waits (10 s at most unless told
/// otherwise, 30 s at most ever) and, in a browser without JSPI, answers
/// [`Error::Unavailable`]. At most 32 sends and async calls of one plugin
/// are in flight at once; past that they answer [`Error::RateLimited`].
pub mod calls {
    use super::*;

    /// Identifies a [`Calls::call_async`] in its
    /// [`Event::CallResult`](crate::Event::CallResult).
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct CallId(pub u64);

    #[derive(Clone, Copy, Debug, Default)]
    pub struct Calls;

    impl Calls {
        /// Calls `method` with a typed request and waits for the typed
        /// response, 10 s at most.
        pub fn call<Req: Serialize + ?Sized, Resp: DeserializeOwned>(
            &self,
            method: &str,
            request: &Req,
            to: Target,
        ) -> Result<Resp> {
            self.call_json(method, &Json::from_value(request)?, to)?
                .parse()
        }

        pub fn call_json(&self, method: &str, request: &Json, to: Target) -> Result<Json> {
            host::call(method, &request.0, &to, None).map(Json)
        }

        /// [`Calls::call_json`] waiting at most `timeout_ms` (30 s at most).
        pub fn call_json_timeout(
            &self,
            method: &str,
            request: &Json,
            to: Target,
            timeout_ms: u32,
        ) -> Result<Json> {
            host::call(method, &request.0, &to, Some(timeout_ms)).map(Json)
        }

        /// Sends `method` and returns at once; nothing answers. For commands
        /// whose outcome arrives another way (a value, a live message).
        pub fn send<Req: Serialize + ?Sized>(
            &self,
            method: &str,
            request: &Req,
            to: Target,
        ) -> Result<()> {
            host::call_send(method, &Json::from_value(request)?.0, &to)
        }

        /// Starts a call and returns at once; its answer arrives as
        /// [`Event::CallResult`](crate::Event::CallResult) with the id
        /// returned here, after 10 s at most.
        pub fn call_async<Req: Serialize + ?Sized>(
            &self,
            method: &str,
            request: &Req,
            to: Target,
        ) -> Result<CallId> {
            host::call_async(method, &Json::from_value(request)?.0, &to, None).map(CallId)
        }

        /// [`Calls::call_async`] answered within `timeout_ms` (30 s at most).
        pub fn call_async_timeout<Req: Serialize + ?Sized>(
            &self,
            method: &str,
            request: &Req,
            to: Target,
            timeout_ms: u32,
        ) -> Result<CallId> {
            host::call_async(method, &Json::from_value(request)?.0, &to, Some(timeout_ms))
                .map(CallId)
        }
    }
}

/// The plugin's configuration document, as the account stores it. No grant.
pub mod config {
    use super::*;

    /// The configuration, deserialized.
    pub fn get<T: DeserializeOwned>() -> Result<T> {
        Json(host::config()).parse()
    }

    /// The configuration document as the host passed it.
    pub fn json() -> Json {
        Json(host::config())
    }
}

/// The plugin's own report of how it is doing: shown beside its runtime
/// state in the Plugins view (a UI plugin's, in that viewer) and by
/// `standard plugin health` (a daemon plugin's, per machine). Each report
/// replaces the last; a plugin that never reports is `ok`. No grant.
pub mod health {
    use super::*;

    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    pub enum Health {
        #[default]
        Ok,
        /// Working, with a problem the user may want to know about.
        Degraded,
        /// Not doing its job until something changes.
        Failed,
    }

    /// Reports `health` with a short message (200 characters are kept).
    pub fn set(health: Health, message: &str) {
        host::health_set(health, message);
    }

    pub fn ok() {
        set(Health::Ok, "");
    }

    pub fn degraded(message: &str) {
        set(Health::Degraded, message);
    }

    pub fn failed(message: &str) {
        set(Health::Failed, message);
    }
}

/// Named secrets the user entered for this plugin. Grant: `secret:<NAME>`.
pub mod secrets {
    use super::*;

    pub fn get(name: &str) -> Result<Option<String>> {
        host::secret(name)
    }
}

/// Read-only account state. Grant: `account.read`. Never what is inside a
/// pane: no screen, scrollback, input or output exists in this API.
pub mod account {
    use super::*;

    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct Machine {
        pub id: String,
        pub name: String,
        pub online: bool,
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct Project {
        pub id: String,
        pub name: String,
        pub machine: String,
        pub path: String,
    }

    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    pub enum AgentStatus {
        #[default]
        None,
        Working,
        Idle,
        WaitingForInput,
    }

    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    pub struct Pane {
        pub id: String,
        /// The pane's generation: 1 at creation, advanced by every restart
        /// and restore; 0 while unknown. `<id>@<generation>` names one run
        /// of the pane.
        pub generation: u64,
        pub machine: String,
        pub project: Option<String>,
        pub title: String,
        /// The pane's current directory when the host knows it, else its
        /// project root. A new directory arrives as a `changed` pane.
        pub cwd: String,
        pub cols: u32,
        pub rows: u32,
        /// The foreground program name, when known.
        pub program: Option<String>,
        /// The agent the pane runs, when one is detected.
        pub agent: Option<String>,
        pub agent_status: AgentStatus,
    }

    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    pub struct AccountState {
        pub machines: Vec<Machine>,
        pub projects: Vec<Project>,
        pub panes: Vec<Pane>,
    }

    pub fn state() -> Result<AccountState> {
        host::account_state()
    }

    /// Asks for [`crate::Event::AccountChanged`] on every change.
    pub fn watch() -> Result<()> {
        host::account_watch()
    }
}

/// Exactly-once effects across the viewers that run a UI plugin.
///
/// Every viewer on the account runs its own instance of a UI plugin, so an
/// effect written naively happens once per open viewer. Claim a key first;
/// only the instance whose claim succeeds performs the effect. Keys live in
/// the plugin's own namespace. No grant.
pub mod claims {
    use super::*;

    #[derive(Clone, Copy, Debug, Default)]
    pub struct Claims;

    impl Claims {
        /// Claims `key` for `ttl_ms`: true when this plugin session holds it
        /// (renewed if it already did); another viewer, even on this machine,
        /// or another daemon of a fleet plugin gets false; the claim expires
        /// after `ttl_ms` unless renewed. Both worlds.
        pub fn claim(&self, key: &str, ttl_ms: u32) -> Result<bool> {
            host::claim(key, ttl_ms)
        }

        pub fn release(&self, key: &str) -> Result<()> {
            host::release(key)
        }

        /// Runs `effect` only in the instance that wins the claim on `key`.
        /// Returns whether it ran.
        pub fn once(&self, key: &str, ttl_ms: u32, effect: impl FnOnce()) -> Result<bool> {
            let won = self.claim(key, ttl_ms)?;
            if won {
                effect();
            }
            Ok(won)
        }
    }
}

/// Opens web pages in the user's browser. UI plugins only. Grant:
/// `url.open:<host>` (`*.<domain>` for its subdomains, `*` for any host).
pub mod url {
    use super::*;

    /// Opens an `https://` URL in the user's browser, on the machine the
    /// viewer runs on (a new tab in a browser viewer). Only as a direct
    /// result of user input: while handling a key, paste, pointer press or
    /// command, or within a second after one, and once per input;
    /// `Error::Invalid` otherwise or for a URL that is not plain https,
    /// `Error::GrantDenied { grant: "url.open:<host>" }` for a host no
    /// grant names.
    pub fn open(url: &str) -> Result<()> {
        host::url_open(url)
    }
}

/// Viewer-local state. UI plugins only; no grant.
pub mod view {
    use super::*;

    /// The viewer's theme colours as `0xRRGGBB`.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct Theme {
        pub fg: u32,
        pub bg: u32,
        /// Text receded toward the background: "grayed out".
        pub recede_fg: u32,
        pub recede_bg: u32,
        pub accent: u32,
        /// The terminal's 16 ANSI colours as the viewer resolved them.
        pub palette: [u32; 16],
    }

    /// The xterm defaults of the 16 ANSI colours.
    pub const XTERM_PALETTE: [u32; 16] = [
        0x000000, 0xcd0000, 0x00cd00, 0xcdcd00, 0x0000ee, 0xcd00cd, 0x00cdcd, 0xe5e5e5, 0x7f7f7f,
        0xff0000, 0x00ff00, 0xffff00, 0x5c5cff, 0xff00ff, 0x00ffff, 0xffffff,
    ];

    /// How far a fully grayed-out colour recedes toward the background,
    /// in percent: the viewer's own rule.
    pub const GRAYED_OUT_PERCENT: u16 = 55;

    impl Default for Theme {
        fn default() -> Self {
            Self {
                fg: 0xd0d0d0,
                bg: 0x000000,
                recede_fg: 0x808080,
                recede_bg: 0x101010,
                accent: 0x5fafff,
                palette: XTERM_PALETTE,
            }
        }
    }

    impl Theme {
        /// `rgb` receded `percent` of the way toward this theme's
        /// background: how the viewer grays things out, keeping the
        /// colour's hue on light, dark and tinted themes alike (never a
        /// fixed gray). [`GRAYED_OUT_PERCENT`] is fully grayed out.
        pub fn recede(&self, rgb: u32, percent: u16) -> u32 {
            crate::colour::recede(rgb, self.bg, percent)
        }

        /// ANSI colour `index` (0 to 15) as this viewer shows it.
        pub fn ansi(&self, index: u8) -> u32 {
            self.palette[usize::from(index & 15)]
        }
    }

    /// Whether this viewer is the one the user is controlling. Several
    /// viewers can show the same account at once; only the driving one
    /// should act on the user's behalf.
    pub fn is_driving() -> bool {
        host::is_driving()
    }

    pub fn theme() -> Theme {
        host::theme()
    }

    /// The focused pane's id, when one is focused.
    pub fn focused_pane() -> Option<String> {
        host::focused_pane()
    }

    /// A pane and its generation.
    #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
    pub struct PaneRef {
        pub id: String,
        /// 0 while the viewer does not know it.
        pub generation: u64,
    }

    impl PaneRef {
        /// `<id>@<generation>`: a key for this run of the pane, so state
        /// kept for a pane that restarted is not shown for its next run.
        pub fn key(&self) -> String {
            alloc::format!("{}@{}", self.id, self.generation)
        }
    }

    /// The pane an instance surface (`<surface>@<pane>`, a `pane.footer`
    /// or `pane.header` instance) belongs to, with its generation now.
    pub fn surface_pane(surface: &str) -> Option<PaneRef> {
        host::surface_pane(surface)
    }

    /// The machine an instance surface (`<surface>@<machine>`, a
    /// `machine.after` instance) belongs to.
    pub fn surface_machine(surface: &str) -> Option<String> {
        host::surface_machine(surface)
    }

    /// The project an instance surface (`<surface>@<project>`, a
    /// `project.after` instance) belongs to.
    pub fn surface_project(surface: &str) -> Option<String> {
        host::surface_project(surface)
    }

    /// The identity tint (`0xRRGGBB`) of what an instance surface belongs
    /// to: a machine row's machine, a project row's project, a pane
    /// footer's project (else its machine), as the viewer paints it.
    pub fn surface_tint(surface: &str) -> Option<u32> {
        host::surface_tint(surface)
    }

    /// The identity tint of a machine or project, by id.
    pub fn identity_tint(id: &str) -> Option<u32> {
        host::identity_tint(id)
    }

    /// The machine this viewer runs on, by the account's machine id; `None`
    /// in a viewer that is not an enrolled machine (a browser).
    pub fn machine_id() -> Option<String> {
        host::machine_id()
    }

    /// This viewer instance: shared by every plugin of one running viewer,
    /// different in every other viewer and after a restart. A key such as
    /// `<plugin>.seen.<instance>` is this viewer's own.
    pub fn instance_id() -> String {
        host::instance_id()
    }

    /// The wall clock where the viewer runs, in milliseconds since the Unix
    /// epoch: for dates, countdowns and "updated 3 min ago". Animation keeps
    /// to [`Frame::now_ms`](crate::Frame::now_ms).
    pub fn wall_ms() -> u64 {
        host::wall_ms()
    }

    /// The viewer's local offset from UTC right now, in minutes east
    /// (UTC+2 is 120). It follows daylight saving: read it when you format
    /// a time, not once at activation.
    pub fn utc_offset_minutes() -> i32 {
        host::utc_offset_minutes()
    }

    /// The viewer's IANA time zone (`Europe/Berlin`), when known.
    pub fn time_zone() -> Option<String> {
        host::time_zone()
    }

    /// The viewer's local wall-clock time in milliseconds since the Unix
    /// epoch shifted by the offset: `local_ms() / 86_400_000` is the local
    /// day number, and the remainder the time of day.
    pub fn local_ms() -> i64 {
        host::wall_ms() as i64 + i64::from(host::utc_offset_minutes()) * 60_000
    }
}

/// What this viewer can show. UI plugins only; no grant. Changes arrive as
/// [`crate::Event::CapabilitiesChanged`].
pub mod capabilities {
    use super::*;

    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    pub struct Capabilities {
        /// Whether the graphics model paints as real graphics here. Without
        /// it the viewer shows a pixels surface as half-block cells.
        pub graphics: bool,
        /// Whether graphics go through the kitty graphics protocol. The
        /// viewer's only raster layer is kitty's, so this equals
        /// `graphics` today.
        pub kitty: bool,
        /// The paced frame rate the viewer runs at right now.
        pub frame_rate: u32,
        /// The pixel size of one cell (zero when unknown).
        pub cell_px: (u32, u32),
        /// Device pixels per surface pixel: 2 while the viewer has halved
        /// this plugin's pixel resolution because its frames ran long.
        pub pixel_scale: u32,
    }

    pub fn get() -> Capabilities {
        host::capabilities()
    }
}

pub fn values() -> values::Values {
    values::Values
}

pub fn live() -> live::Live {
    live::Live
}

pub fn events() -> events::Events {
    events::Events
}

pub fn calls() -> calls::Calls {
    calls::Calls
}

pub fn claims() -> claims::Claims {
    claims::Claims
}