salamandr-plugin-sdk 0.3.0

Write Salamandr helpdesk extensions in Rust: safe typed wrappers for every host capability, the fetch_context wire contract, and an in-process mock host for testing.
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! The wire contract of `fetch_context` — the one operation every plugin
//! installed through the community-extension path must implement.
//!
//! These types are a field-for-field mirror of internal/extension's
//! `ContextBlock`/`Field`/`Action` and internal/extwasm/adapter.go's
//! `fetchContextInput`. They live here because a plugin author working
//! from this crate alone has no other way to learn the shape: the host
//! decodes `fetch_context`'s answer straight into `[]extension.ContextBlock`
//! with no schema negotiation, so a guessed field name is a runtime
//! "returned data that doesn't match the expected shape" on the deployer's
//! server, not a compile error on the author's machine.
//!
//! The parity is pinned from the Go side by
//! internal/extwasm/sdkcontract_test.go, which runs the compiled
//! examples/hello-crm plugin through the real `Adapter.FetchContext` and
//! asserts every field survives the round trip.
//!
//! # What a block is
//!
//! One titled group of label/value pairs in the ticket sidebar, plus
//! optional deep links. Deliberately not a typed per-vendor struct — a
//! CRM's "deal" and an MSP's "asset" look nothing alike, and the sidebar
//! renders any provider's answer without knowing its schema.
//!
//! ```no_run
//! use salamandr_plugin_sdk::{ContextBlock, ContextRequest, ContextResult};
//!
//! fn fetch_context(req: ContextRequest) -> ContextResult {
//!     let email = match req.primary_email() {
//!         Some(e) => e,
//!         // No address to look anyone up by: an empty answer, not an
//!         // error — the sidebar simply shows nothing for this plugin.
//!         None => return Ok(vec![]),
//!     };
//!     Ok(vec![ContextBlock::new("Contact")
//!         .field("Email", email)
//!         .action("Open in CRM", format!("https://crm.example.com/?q={email}"))])
//! }
//! ```

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::error::OpError;

fn is_false(b: &bool) -> bool {
    !*b
}

/// ContextRequest is what the host passes to `fetch_context` — mirrors
/// adapter.go's `fetchContextInput`.
///
/// Every identity signal the helpdesk resolved about the ticket in front
/// of the agent, so a connector keys on whatever its own vendor can
/// actually match on. The three shapes in practice:
///
/// * **By address** (`candidate_emails`) — a CRM, an ERP, anything that
///   knows people by email. The list is "any of these is the same human",
///   in the order given.
/// * **By ticket** (`ticket_id`) — an issue tracker, which answers "what
///   is linked to *this* conversation" rather than "who is this person".
/// * **By organization** (`organization_id`) — a monitoring or RMM system,
///   which has no per-contact identity at all and works in terms of a
///   customer's estate.
///
/// The last two used to be reachable only from a connector written in Go
/// inside the product; a plugin received addresses and nothing else. They
/// are here so an SDK-written connector is not a second-class one.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ContextRequest {
    /// The ticket the agent has open. Use it to look up whatever this
    /// connector has previously linked to that ticket — through
    /// `host_kv`, or the vendor's own search.
    #[serde(default)]
    pub ticket_id: String,
    /// The human-facing ticket number and subject, worth carrying into a
    /// vendor search or a link label. Not identifiers — the number is
    /// per-tenant and the subject is free text.
    #[serde(default)]
    pub ticket_number: i64,
    #[serde(default)]
    pub subject: String,
    /// The ticket's type id, when it has one — the same value a tenant
    /// admin restricts an extension to (see `Service.SetTicketTypes`).
    /// The host has *already* applied that filter before calling, so a
    /// plugin normally ignores this; it is here for a connector that
    /// wants to answer differently per type.
    #[serde(default)]
    pub ticket_type_id: Option<String>,
    /// The Salamandr user who filed the ticket, and the organization they
    /// belong to when they belong to one. Pair either with `host_core`'s
    /// `users`/`organizations` resources to read the helpdesk's own record
    /// before deciding what to ask the vendor.
    #[serde(default)]
    pub requester_id: String,
    #[serde(default)]
    pub organization_id: Option<String>,
    /// The requester's address and any alternates, plus their
    /// organization's own domain (prefixed `@`) when it isn't a free
    /// consumer provider. Never empty in practice — but check anyway,
    /// since a ticket filed by a channel with no address at all is
    /// possible.
    #[serde(default)]
    pub candidate_emails: Vec<String>,
}

impl ContextRequest {
    /// primary_email is the requester's main address — the first entry.
    /// The alternates are worth trying only when a lookup on this one
    /// found nothing.
    pub fn primary_email(&self) -> Option<&str> {
        self.candidate_emails.first().map(String::as_str)
    }

    /// emails iterates every candidate address, primary first.
    pub fn emails(&self) -> impl Iterator<Item = &str> {
        self.candidate_emails.iter().map(String::as_str)
    }
}

/// Field is one label/value pair inside a [`ContextBlock`] — two strings,
/// never a typed value, so a plugin's JSON encoder needs no schema beyond
/// "an array of {label, value}". Format numbers, money and dates the way
/// an agent should read them; nothing downstream reformats them — with one
/// exception: a plugin has no locale to format a date *with* (a wasm guest
/// never learns who's asking), so [`FIELD_KIND_DATE`] via
/// [`ContextBlock::field_date`]/[`ContextBlock::field_date_opt`] hands the
/// frontend an RFC 3339 timestamp to render in the viewing agent's own
/// browser locale instead.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Field {
    pub label: String,
    pub value: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub kind: String,
}

pub const FIELD_KIND_DATE: &str = "date";

/// Marks Field::value as JSON-encoded TableData rather than plain text — see
/// [`ContextBlock::field_table`].
pub const FIELD_KIND_TABLE: &str = "table";

/// TableData is the shape a table field's value carries, JSON-encoded. Mirrors
/// internal/extension's TableData — see [`ContextBlock::field_table`].
#[derive(Serialize)]
struct TableData {
    columns: Vec<String>,
    rows: Vec<Vec<String>>,
}

/// Action is one thing an agent can do from a block. Which kind it is
/// depends on `op`:
///
///   - **Deep link** (`url`, no `op`) — "Open in HubSpot", "View work
///     order #4471", rendered as a plain anchor. Build it with
///     [`ContextBlock::action`].
///   - **Executable action** (`op` set) — a button that runs one of your
///     plugin's `action_ops` and *writes* to the vendor system ("Log a
///     note for the salesperson who owns this lead"). Build it with
///     [`Action::run`].
///
/// `params` is where the write's identifiers ride along: you already
/// looked the contact up to build this block, and the host never
/// interprets what you put there — it comes straight back to you in
/// [`ActionRequest::params`]. It is *not* a trust boundary: the values
/// travel through the agent's browser, so validate them as input.
///
/// Mirrors internal/extension's `Action`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Action {
    pub label: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub url: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub op: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub params: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fields: Vec<ActionField>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub confirm: String,
}

impl Action {
    /// link builds a plain deep link.
    pub fn link(label: impl Into<String>, url: impl Into<String>) -> Self {
        Self { label: label.into(), url: url.into(), ..Default::default() }
    }

    /// run builds an executable action bound to `op` — which must be
    /// registered in [`crate::plugin!`]'s `action_ops` block, or the host
    /// refuses the click.
    pub fn run(label: impl Into<String>, op: impl Into<String>) -> Self {
        Self { label: label.into(), op: op.into(), ..Default::default() }
    }

    /// param attaches one identifier the action will need when it runs.
    pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.params.insert(key.into(), value.into());
        self
    }

    /// input declares a single-line box the agent fills before running.
    pub fn input(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
        let mut f = FieldSpec::new(key, label, FIELD_TEXT);
        f.required = required;
        self.fields.push(f);
        self
    }

    /// textarea declares a multi-line box — what a note body wants.
    pub fn textarea(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
        let mut f = FieldSpec::new(key, label, FIELD_TEXTAREA);
        f.required = required;
        self.fields.push(f);
        self
    }

    /// select declares a dropdown fed by `options_op` — one of the plugin's own `read_ops`, the
    /// same allow-list every `context_op`/`action_op`'s picker already goes through.
    pub fn select(mut self, key: impl Into<String>, label: impl Into<String>, required: bool, options_op: impl Into<String>) -> Self {
        let mut f = FieldSpec::new(key, label, FIELD_SELECT);
        f.required = required;
        f.options_op = options_op.into();
        self.fields.push(f);
        self
    }

    /// multiselect is a select whose picked value is a list — see [`FieldSpec`]'s doc comment.
    pub fn multiselect(mut self, key: impl Into<String>, label: impl Into<String>, required: bool, options_op: impl Into<String>) -> Self {
        let mut f = FieldSpec::new(key, label, FIELD_MULTISELECT);
        f.required = required;
        f.options_op = options_op.into();
        self.fields.push(f);
        self
    }

    /// number declares a plain numeric input.
    pub fn number(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
        let mut f = FieldSpec::new(key, label, FIELD_NUMBER);
        f.required = required;
        self.fields.push(f);
        self
    }

    /// date declares a plain "YYYY-MM-DD" date input.
    pub fn date(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
        let mut f = FieldSpec::new(key, label, FIELD_DATE);
        f.required = required;
        self.fields.push(f);
        self
    }

    /// placeholder sets the hint on the last declared field.
    pub fn placeholder(mut self, hint: impl Into<String>) -> Self {
        if let Some(last) = self.fields.last_mut() {
            last.placeholder = hint.into();
        }
        self
    }

    /// depends_on marks the last declared field as fed by another field's current value —
    /// requires that field to also declare `options_op`, checked host-side against exactly the
    /// same rules a create_form_op answer's fields are (see [`FieldSpec::depends_on`]).
    pub fn depends_on(mut self, field_key: impl Into<String>) -> Self {
        if let Some(last) = self.fields.last_mut() {
            last.depends_on = field_key.into();
        }
        self
    }

    /// options gives the last declared field's choices inline, instead of through `options_op`.
    pub fn options(mut self, options: Vec<FieldOption>) -> Self {
        if let Some(last) = self.fields.last_mut() {
            last.options = options;
        }
        self
    }

    /// reloads_form marks the last declared field as one whose change re-fetches the whole
    /// field list — rarely useful on an action's small confirmation form, kept for parity with
    /// create_form_op's own schema.
    pub fn reloads_form(mut self) -> Self {
        if let Some(last) = self.fields.last_mut() {
            last.reloads_form = true;
        }
        self
    }

    /// rich_text_format marks the last declared field (must be a textarea) as rendered by a
    /// rich-text editor whose HTML the plugin converts itself — see [`FieldSpec::rich_text_format`].
    pub fn rich_text_format(mut self, format: impl Into<String>) -> Self {
        if let Some(last) = self.fields.last_mut() {
            last.rich_text_format = format.into();
        }
        self
    }

    /// confirm makes the UI ask first — for an action whose effect is
    /// visible to someone outside the helpdesk.
    pub fn confirm(mut self, question: impl Into<String>) -> Self {
        self.confirm = question.into();
        self
    }
}

pub const FIELD_TEXT: &str = "text";
pub const FIELD_TEXTAREA: &str = "textarea";
pub const FIELD_SELECT: &str = "select";
pub const FIELD_NUMBER: &str = "number";
/// FIELD_MULTISELECT is a select whose value is a list — GitHub's labels, Linear's labels. Its
/// options come from the same options_op every other select uses.
pub const FIELD_MULTISELECT: &str = "multiselect";
/// FIELD_DATE renders as a plain date input, whose value is always "YYYY-MM-DD".
pub const FIELD_DATE: &str = "date";

pub const RICH_TEXT_FORMAT_MARKDOWN: &str = "markdown";
pub const RICH_TEXT_FORMAT_JIRA_WIKI: &str = "jira_wiki";

/// FieldSpec is one input on a plugin-declared small form — either an executable [`Action`]'s
/// confirmation form ([`Action::fields`], built via `Action::input`/`select`/etc.) or a
/// create-record form's own schema (a `create_form_op` answer, built with `FieldSpec::text`/
/// `select`/etc. and serialized as `Vec<FieldSpec>`). Mirrors internal/extension's `FieldSpec` —
/// formerly two independently invented types (`ActionField` here, `CreateFieldSpec` on the Go
/// side) until unified.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldSpec {
    pub key: String,
    pub label: String,
    /// One of the `FIELD_*` consts above.
    pub kind: String,
    #[serde(default, skip_serializing_if = "is_false")]
    pub required: bool,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub placeholder: String,
    /// Names one of the plugin's own `read_ops` — this field's options come from calling it.
    /// Checked host-side against the manifest's declared `read_ops`; a field may declare
    /// `options_op` or inline `options`, never both.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub options_op: String,
    /// Names another field in the same form whose current value is passed to `options_op` when
    /// fetching this field's own options — a cascading dropdown. Must be acyclic and grounded in
    /// a real field in the same list; checked host-side.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub depends_on: String,
    #[serde(default, skip_serializing_if = "is_false")]
    pub numeric: bool,
    /// This field's choices, given directly instead of through `options_op` — for a plugin that
    /// already resolved them while building this very schema.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<FieldOption>,
    /// Marks a field whose change re-fetches the whole schema (create_form_op called again with
    /// every current field's value) rather than just this field's own options — for a
    /// *structural* dependency, where the set of fields itself differs per value.
    #[serde(default, skip_serializing_if = "is_false")]
    pub reloads_form: bool,
    /// Marks a textarea field rendered by a rich-text editor client-side; one of
    /// `RICH_TEXT_FORMAT_MARKDOWN`/`RICH_TEXT_FORMAT_JIRA_WIKI`. Conversion from the editor's raw
    /// HTML to the vendor's own format happens inside the plugin, via
    /// `host_richtext_to_markdown`/`host_richtext_to_jira_wiki`.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub rich_text_format: String,
}

impl FieldSpec {
    fn new(key: impl Into<String>, label: impl Into<String>, kind: &str) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            kind: kind.into(),
            required: false,
            placeholder: String::new(),
            options_op: String::new(),
            depends_on: String::new(),
            numeric: false,
            options: Vec::new(),
            reloads_form: false,
            rich_text_format: String::new(),
        }
    }

    /// text starts a create-form field — chain `.required()`/`.placeholder()`/etc.
    pub fn text(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(key, label, FIELD_TEXT)
    }
    pub fn textarea(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(key, label, FIELD_TEXTAREA)
    }
    pub fn select(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(key, label, FIELD_SELECT)
    }
    pub fn multiselect(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(key, label, FIELD_MULTISELECT)
    }
    pub fn number(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(key, label, FIELD_NUMBER)
    }
    pub fn date(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self::new(key, label, FIELD_DATE)
    }

    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }
    pub fn placeholder(mut self, hint: impl Into<String>) -> Self {
        self.placeholder = hint.into();
        self
    }
    pub fn options_op(mut self, op: impl Into<String>) -> Self {
        self.options_op = op.into();
        self
    }
    pub fn depends_on(mut self, field_key: impl Into<String>) -> Self {
        self.depends_on = field_key.into();
        self
    }
    pub fn numeric(mut self) -> Self {
        self.numeric = true;
        self
    }
    pub fn options(mut self, options: Vec<FieldOption>) -> Self {
        self.options = options;
        self
    }
    pub fn reloads_form(mut self) -> Self {
        self.reloads_form = true;
        self
    }
    pub fn rich_text_format(mut self, format: impl Into<String>) -> Self {
        self.rich_text_format = format.into();
        self
    }
}

/// ActionField is [`FieldSpec`]'s old name — kept as an alias for source compatibility with
/// plugins written before the two schemas were unified.
pub type ActionField = FieldSpec;

/// FieldOption is one {value,label} pair — an options_op's own answer shape, and a field's
/// inline `options`. Mirrors internal/extension's `FieldOption`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldOption {
    pub value: String,
    pub label: String,
}

/// Actor is who clicked — resolved by the host from the session, never
/// from anything the browser sent. Sign what you write with it: a note
/// appearing in a salesperson's CRM with no author is worse than none.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Actor {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub email: String,
}

/// TicketRef is what the action was run from — the way back from the
/// vendor system to the conversation that caused the write.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct TicketRef {
    /// The ticket's own uuid, host-resolved. Address your stored link
    /// with it (host_core's `external_links`) rather than trusting an
    /// identifier that arrived in `params`: params travel through the
    /// browser, so a write addressed by them acts on whatever record the
    /// caller named, not the one this ticket is linked to.
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub number: i64,
    #[serde(default)]
    pub subject: String,
    #[serde(default)]
    pub url: String,
}

/// ActionRequest is what an `action_ops` handler receives. `params` is
/// what you attached to the [`Action`]; `inputs` is what the agent
/// typed, keyed by [`ActionField::key`].
///
/// `occurred_at` is an RFC 3339 timestamp **supplied by the host**: a
/// plugin runs on a freestanding wasm target with no clock and no WASI,
/// so this is the only "now" that exists. Never synthesize a date.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ActionRequest {
    #[serde(default)]
    pub params: BTreeMap<String, String>,
    #[serde(default)]
    pub inputs: BTreeMap<String, String>,
    #[serde(default)]
    pub actor: Actor,
    #[serde(default)]
    pub ticket: TicketRef,
    #[serde(default)]
    pub occurred_at: String,
}

impl ActionRequest {
    /// param reads one identifier the block attached, or
    /// [`OpError::Other`] naming it when it's missing — the shape every
    /// handler starts with, since a write with no target is a bug worth
    /// refusing loudly.
    pub fn param(&self, key: &str) -> Result<&str, OpError> {
        match self.params.get(key).map(String::as_str).filter(|v| !v.is_empty()) {
            Some(v) => Ok(v),
            None => Err(OpError::Other(format!("action is missing the {key:?} parameter"))),
        }
    }

    /// opt_param reads an identifier that may legitimately be absent.
    pub fn opt_param(&self, key: &str) -> Option<&str> {
        self.params.get(key).map(String::as_str).filter(|v| !v.is_empty())
    }

    /// input reads a required form value, trimmed.
    pub fn input(&self, key: &str) -> Result<&str, OpError> {
        match self.inputs.get(key).map(|v| v.trim()).filter(|v| !v.is_empty()) {
            Some(v) => Ok(v),
            None => Err(OpError::Other(format!("{key:?} is required"))),
        }
    }

    /// opt_input reads an optional form value, trimmed.
    pub fn opt_input(&self, key: &str) -> Option<&str> {
        self.inputs.get(key).map(|v| v.trim()).filter(|v| !v.is_empty())
    }

    /// signature is the one-line "who and when" to append to whatever you
    /// write, built from the host-supplied actor, ticket and timestamp.
    /// Plain text; escape it yourself if the vendor field takes HTML.
    pub fn signature(&self) -> String {
        let who = if self.actor.name.is_empty() { self.actor.email.clone() } else { self.actor.name.clone() };
        let mut out = format!("Logged by {who}");
        if !self.actor.email.is_empty() && !self.actor.name.is_empty() {
            out.push_str(&format!(" <{}>", self.actor.email));
        }
        if self.ticket.number > 0 {
            out.push_str(&format!(" from support ticket #{}", self.ticket.number));
        }
        if !self.ticket.subject.is_empty() {
            out.push_str(&format!(" — {}", self.ticket.subject));
        }
        if !self.occurred_at.is_empty() {
            out.push_str(&format!(" · {}", self.occurred_at));
        }
        out
    }
}

/// ActionOutcome is what an action answers with: a short line the agent
/// sees and the ticket timeline records, plus an optional deep link to
/// whatever was just created. Mirrors internal/extension's `ActionResult`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ActionOutcome {
    pub message: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub url: String,
}

impl ActionOutcome {
    pub fn new(message: impl Into<String>) -> Self {
        Self { message: message.into(), url: String::new() }
    }

    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = url.into();
        self
    }
}

/// ActionResult is the exact return type an `action_ops` handler must
/// have — same reasoning as [`ContextResult`]: a signature that cannot
/// disagree with what the host decodes.
pub type ActionResult = Result<ActionOutcome, OpError>;

/// ContextBlock is one titled group of fields in the ticket sidebar. A
/// CRM plugin might answer with one block ("Contact") or several
/// ("Contact", "Open deals"); an MSP plugin one per asset. Every enabled
/// extension's blocks are concatenated into a single sidebar list, so a
/// title that names the vendor ("Acme CRM") reads better than a generic
/// one once a tenant installs two plugins.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextBlock {
    pub title: String,
    #[serde(default)]
    pub fields: Vec<Field>,
    /// Omitted from the JSON entirely when empty — matches the Go side's
    /// `json:"actions,omitempty"`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actions: Vec<Action>,
}

impl ContextBlock {
    /// new starts an empty block. Chain [`Self::field`]/[`Self::action`]
    /// onto it.
    pub fn new(title: impl Into<String>) -> Self {
        Self { title: title.into(), fields: Vec::new(), actions: Vec::new() }
    }

    /// field appends one label/value pair.
    pub fn field(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push(Field { label: label.into(), value: value.into(), kind: String::new() });
        self
    }

    /// field_opt appends the pair only when the value is present and not
    /// blank — the shape almost every vendor lookup needs, since a CRM
    /// answers with half its fields null and a sidebar row reading
    /// "Phone: —" is worse than no row.
    pub fn field_opt(self, label: impl Into<String>, value: Option<impl Into<String>>) -> Self {
        match value {
            Some(v) => {
                let v: String = v.into();
                if v.trim().is_empty() {
                    self
                } else {
                    self.field(label, v)
                }
            }
            None => self,
        }
    }

    /// field_date appends a label/value pair whose value is an RFC 3339
    /// timestamp — pass the vendor's own date string through unparsed, the
    /// frontend renders it in the viewing agent's locale.
    pub fn field_date(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push(Field { label: label.into(), value: value.into(), kind: FIELD_KIND_DATE.into() });
        self
    }

    /// field_date_opt is [`Self::field_date`] with the same present-and-not-blank
    /// guard [`Self::field_opt`] applies.
    pub fn field_date_opt(self, label: impl Into<String>, value: Option<impl Into<String>>) -> Self {
        match value {
            Some(v) => {
                let v: String = v.into();
                if v.trim().is_empty() {
                    self
                } else {
                    self.field_date(label, v)
                }
            }
            None => self,
        }
    }

    /// field_table appends a field whose value is a grid — invoice line items, payment history —
    /// rather than a single string. Rendered only in the expanded context modal, not the narrow
    /// sidebar. Unvalidated host-side: keep row/column counts sane yourself, since nothing here
    /// caps them (the frontend truncates what it displays, but the whole payload still travels).
    pub fn field_table(mut self, label: impl Into<String>, columns: Vec<String>, rows: Vec<Vec<String>>) -> Self {
        let value = serde_json::to_string(&TableData { columns, rows }).unwrap_or_default();
        self.fields.push(Field { label: label.into(), value, kind: FIELD_KIND_TABLE.into() });
        self
    }

    /// action appends a deep link.
    pub fn action(mut self, label: impl Into<String>, url: impl Into<String>) -> Self {
        self.actions.push(Action::link(label, url));
        self
    }

    /// run appends an executable action built with [`Action::run`] — the
    /// write half, e.g.
    /// `.run(Action::run("Log a note", "log_note").param("contact_id", id).textarea("body", "Note", true))`.
    pub fn run(mut self, action: Action) -> Self {
        self.actions.push(action);
        self
    }

    /// is_empty reports a block with nothing to render. Returning one is
    /// harmless but pointless — the sidebar draws the title and a blank
    /// body — so `blocks.retain(|b| !b.is_empty())` before answering.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty() && self.actions.is_empty()
    }
}

/// ContextResult is the exact return type `fetch_context` must have.
/// Spelling it out here is the point: an op whose signature is
/// `fn(ContextRequest) -> ContextResult` cannot disagree with what the
/// host decodes.
///
/// `Ok(vec![])` is the right answer for "this requester isn't in my
/// vendor's system" — an [`OpError::NotFound`] is for a lookup that
/// should have resolved and didn't. Register it in [`crate::plugin!`]'s
/// **`context_ops`** block, never `ops`.
pub type ContextResult = Result<Vec<ContextBlock>, OpError>;

#[cfg(test)]
mod tests {
    use super::*;

    // The exact JSON the Go side decodes. Field names here are the
    // contract; sdkcontract_test.go asserts the same shape from the Go
    // end against a real compiled plugin.
    #[test]
    fn block_serializes_to_the_go_wire_shape() {
        let block = ContextBlock::new("Contact")
            .field("Name", "Ada Lovelace")
            .field_opt("Phone", Some("+44 20 7946 0958"))
            .field_opt("Fax", None::<String>)
            .field_opt("Blank", Some("   "))
            .action("Open in CRM", "https://crm.example.com/1");
        let got = serde_json::to_value(&block).expect("serialize");
        let want = serde_json::json!({
            "title": "Contact",
            "fields": [
                {"label": "Name", "value": "Ada Lovelace"},
                {"label": "Phone", "value": "+44 20 7946 0958"},
            ],
            "actions": [{"label": "Open in CRM", "url": "https://crm.example.com/1"}],
        });
        assert_eq!(got, want);
    }

    #[test]
    fn a_date_field_carries_its_kind_and_a_plain_one_omits_it() {
        let block = ContextBlock::new("Issue")
            .field("Key", "PROJ-1")
            .field_date("Updated", "2026-08-15T03:52:49Z")
            .field_date_opt("Due", None::<String>);
        let got = serde_json::to_value(&block).expect("serialize");
        let want = serde_json::json!({
            "title": "Issue",
            "fields": [
                {"label": "Key", "value": "PROJ-1"},
                {"label": "Updated", "value": "2026-08-15T03:52:49Z", "kind": "date"},
            ],
        });
        assert_eq!(got, want);
    }

    #[test]
    fn empty_actions_are_omitted() {
        let got = serde_json::to_value(ContextBlock::new("Contact").field("a", "b")).expect("serialize");
        assert!(got.get("actions").is_none(), "actions must be omitted when empty, got {got}");
    }

    #[test]
    fn request_decodes_the_host_input() {
        let req: ContextRequest =
            serde_json::from_str(r#"{"ticket_type_id":"9f1c","candidate_emails":["a@x.com","b@x.com"]}"#)
                .expect("decode");
        assert_eq!(req.ticket_type_id.as_deref(), Some("9f1c"));
        assert_eq!(req.primary_email(), Some("a@x.com"));
        assert_eq!(req.emails().collect::<Vec<_>>(), vec!["a@x.com", "b@x.com"]);
    }

    // The executable half of the same contract. A deep-link action must
    // still serialize to exactly the two keys it always did, or every
    // already-installed plugin's sidebar links change shape.
    #[test]
    fn a_link_action_keeps_the_original_two_key_shape() {
        let got = serde_json::to_value(Action::link("Open in CRM", "https://crm.example.com/1")).expect("serialize");
        assert_eq!(got, serde_json::json!({"label": "Open in CRM", "url": "https://crm.example.com/1"}));
    }

    #[test]
    fn an_executable_action_serializes_to_the_go_wire_shape() {
        let action = Action::run("Log a note", "log_note")
            .param("contact_id", "701")
            .textarea("body", "Note", true)
            .placeholder("What should the salesperson know?")
            .confirm("This writes into the CRM. Continue?");
        let got = serde_json::to_value(&action).expect("serialize");
        let want = serde_json::json!({
            "label": "Log a note",
            "op": "log_note",
            "params": {"contact_id": "701"},
            "fields": [{
                "key": "body",
                "label": "Note",
                "kind": "textarea",
                "required": true,
                "placeholder": "What should the salesperson know?",
            }],
            "confirm": "This writes into the CRM. Continue?",
        });
        assert_eq!(got, want);
    }

    #[test]
    fn action_request_decodes_and_signs() {
        let req: ActionRequest = serde_json::from_str(
            r#"{"params":{"contact_id":"701"},"inputs":{"body":"  call them back  "},
                "actor":{"name":"Ada Lovelace","email":"ada@help.example"},
                "ticket":{"number":42,"subject":"Renewal question","url":"https://help.example/tickets/1"},
                "occurred_at":"2026-08-11T09:30:00Z"}"#,
        )
        .expect("decode");
        assert_eq!(req.param("contact_id").expect("param"), "701");
        assert_eq!(req.input("body").expect("input"), "call them back");
        assert!(req.opt_param("deal_id").is_none());
        assert_eq!(
            req.signature(),
            "Logged by Ada Lovelace <ada@help.example> from support ticket #42 — Renewal question · 2026-08-11T09:30:00Z"
        );
    }

    // A blank required input is refused by the plugin too, not only by
    // the host: the same op is reachable from a test harness and from a
    // future caller that doesn't validate first.
    #[test]
    fn a_blank_required_input_is_refused() {
        let req = ActionRequest { inputs: BTreeMap::from([("body".into(), "   ".into())]), ..Default::default() };
        assert!(req.input("body").is_err());
        assert!(req.opt_input("body").is_none());
    }

    // ticket_type_id is omitted (not null) when the ticket has no type —
    // see fetchContextInput's `omitempty`.
    #[test]
    fn request_decodes_without_a_ticket_type() {
        let req: ContextRequest = serde_json::from_str(r#"{"candidate_emails":[]}"#).expect("decode");
        assert!(req.ticket_type_id.is_none());
        assert_eq!(req.primary_email(), None);
    }
}