Skip to main content

Crate salamandr_plugin_sdk

Crate salamandr_plugin_sdk 

Source
Expand description

Safe Rust SDK for writing Salamandr WASM extensions — see backend/internal/extwasm’s package doc comment (doc.go) for the manifest/scopes/host-function design this implements the guest side of, and abi.go for the exact alloc/dealloc/handle wire contract.

§What a plugin can do

Exactly four things, each behind a scope its manifest.toml declares and a tenant admin approves:

capabilitymodulescope
one HTTP call at a timehttp_fetchhttp_hosts
tenant-supplied config/secretsget_configconfig_keys
a small private key/value storekv_get/kv_set/kv_delete/kv_listkv
the tenant’s own helpdesk datacorecore

plus log, which needs no scope. There is no filesystem, no environment, no clock but the host’s, no sockets, and no WASI.

§Writing a plugin

Start from sdk/examples/hello-crm, a complete working plugin — this is the same code with the vendor call cut out. The crate’s README.md is the full guide (manifest schema, build, install, testing).

ⓘ
use salamandr_plugin_sdk::{plugin, ContextBlock, ContextRequest, ContextResult};

fn fetch_context(req: ContextRequest) -> ContextResult {
    let Some(email) = req.primary_email() else { return Ok(vec![]) };
    // `?` works directly on host calls — HostError converts into
    // OpError, and a host-side "not found" stays a not-found.
    let key = salamandr_plugin_sdk::get_config("api_key")?.unwrap_or_default();
    Ok(vec![ContextBlock::new("Acme CRM")
        .field("Email", email)
        .field("Key configured", if key.is_empty() { "no" } else { "yes" })])
}

plugin! {
    name: "my-plugin",
    version: env!("CARGO_PKG_VERSION"),
    // fetch_context goes in context_ops, never ops — see below.
    context_ops: {
        "fetch_context" => fetch_context,
    }
}

§ops vs context_ops

Two blocks, two wire shapes, and picking the wrong one is the single mistake in this SDK that compiles, installs and then silently misbehaves:

  • context_ops — the host decodes your answer directly into its own Go type. This is what "fetch_context" (and any "fetch_contact"-style typed convenience op) must use. Almost every community plugin uses only this block.
  • ops — the answer is wrapped in an internally-tagged Outcome ({"kind":"ok","data":…}) that only a Go caller written to unwrap it can read. It exists for first-party connectors whose own Go package decodes them (internal/ecommerce/providers/woocommerce, internal/extension/providers/hubspot). A community plugin has no such caller.

Registering fetch_context under ops is refused at install time rather than discovered in production — describe reports which block each op came from (see Registry::context_names).

§Testing without a server

testing::MockHost stands in for the host on non-wasm targets, so cargo test runs your operations natively — with your real manifest’s scopes enforced:

ⓘ
let _host = MockHost::from_manifest(include_str!("../manifest.toml"))
    .config("api_key", "test-key")
    .http(|req| Ok(HttpResponse { status: 200, body: "{}".into(), ..Default::default() }))
    .install();
assert_eq!(fetch_context(request).unwrap().len(), 1);

§Why the plugin! macro is the whole export surface

Rust exports whatever is marked #[no_mangle] extern "C", wherever that happens to be written — so a plugin hand-rolling the ABI has no structural reason its WASM export table contains only what its author meant to expose. This crate makes that mistake unreachable:

  • The only four functions a plugin built with this SDK ever exports are alloc, dealloc, handle and describe, all generated by plugin!. #[no_mangle] should not appear anywhere in a plugin’s own source.
  • An operation is reachable from Go only by appearing in that macro’s ops block. A plain Rust function is just a function. “What does this plugin expose” is answered by reading one list.
  • That same list is what the generated describe export reports, so the host verifies a manifest’s entrypoints against what the binary actually registered — at install time, not when a customer hits the missing operation.
  • Every host call is a safe, typed wrapper. An op author never touches a raw pointer or hand-encodes the wire envelope.

Re-exports§

pub use host::core_call;
pub use host::get_config;
pub use host::http_fetch;
pub use host::http_upload;
pub use host::kv_delete;
pub use host::kv_get;
pub use host::kv_list;
pub use host::kv_set;
pub use host::log;
pub use host::oauth_fetch;
pub use host::richtext_to_jira_wiki;
pub use host::richtext_to_markdown;
pub use host::self_info;
pub use host::ws_send;
pub use host::HttpRequest;
pub use host::HttpResponse;
pub use host::OAuthFetchRequest;
pub use host::SelfInfo;
pub use host::UploadRequest;
pub use persistent::PersistentConnectRequest;
pub use persistent::PersistentConnectResult;
pub use persistent::PersistentReceiveRequest;
pub use persistent::PersistentReceiveResponse;
pub use persistent::PersistentReceiveResult;

Modules§

calendar_sync
The wire contract of calendar_sync_meeting/calendar_sync_delete_meeting/ calendar_sync_free_busy/calendar_sync_ensure_watch — the four entrypoints a kind = "connector" plugin implements when it also declares scopes.calendar_sync = true (see extwasm.Scopes.CalendarSync’s manifest requirement). Register them through the same crate::Registry::connector_op/connector_ops: block crate::connector’s trio uses — a calendar-sync connector is, at the wire level, still “the host calls one of my ops and decodes the answer directly with no Outcome wrapper.”
channel
The wire contract of channel_receive/channel_send — the fixed entrypoint pair a kind = "channel" plugin must implement (see extwasm.KindChannel’s manifest requirement).
chatops
The wire contract of chatops_post_root/chatops_post_reply/ chatops_receive — the fixed entrypoint trio a kind = "chatops" plugin must implement (see extwasm.KindChatops’s manifest requirement) — plus the optional chatops_search_members/ chatops_list_channels/chatops_message_url.
code
Well-known code values a host function can set on a failed envelope. Matching on these rather than on the message text is deliberate: the human message is free to be reworded without that silently becoming a guest-visible behavior change.
connector
The wire contract of connector_create_meeting/ connector_update_meeting/connector_delete_meeting — the fixed entrypoint trio a kind = "connector" plugin must implement (see extwasm.KindConnector’s manifest requirement).
core
Typed access to the tenant’s own helpdesk data — ticket types, statuses, priorities, tags, users, organizations, teams, SLA policies, custom fields, business hours and tickets. The guest half of internal/extwasm/core.go; every function here is one host_core call with the resource/action pair filled in.
host
Safe, typed wrappers over every host function the runtime exports — the complete list of capabilities a plugin has. There is nothing else: no filesystem, no clock beyond what the host hands over, no environment, no sockets.
testing
An in-process stand-in for the Salamandr host, so a plugin’s operations can be unit-tested with cargo test — on your own machine, with a debugger and println!, rather than by uploading a .wasm to a deployment and reading someone else’s server log.

Macros§

plugin
plugin! generates the only four functions a Salamandr WASM plugin ever exports — alloc, dealloc, handle and describe — from one declarative list of operations. See this crate’s doc comment for why that list, rather than a scattering of #[no_mangle]s, is the design.

Structs§

Action
Action is one thing an agent can do from a block. Which kind it is depends on op:
ActionOutcome
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.
ActionRequest
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.
Actor
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.
ContextBlock
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.
ContextRequest
ContextRequest is what the host passes to fetch_context — mirrors adapter.go’s fetchContextInput.
Descriptor
Descriptor is what describe answers with — mirrored by extwasm.Descriptor on the Go side, which compares ops against the manifest’s entrypoints at install time.
Field
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.
FieldOption
FieldOption is one {value,label} pair — an options_op’s own answer shape, and a field’s inline options. Mirrors internal/extension’s FieldOption.
FieldSpec
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.
HostError
HostError carries both the human message and the machine code a host_* failure set (see hostfuncs.go’s envelope.Code).
PersistentConnectRequest
PersistentConnectRequest is what the host passes to persistent_connect — deliberately thin, the same reasoning ScheduledRunInput documents: this call exists so you can push a handshake frame via crate::ws_send, and occurred_at (RFC 3339) is the one useful thing to pass, because a freestanding wasm guest has no clock of its own.
PersistentReceiveRequest
PersistentReceiveRequest is what the host passes to persistent_receive. frame is None for transport = "long_poll" (your handler makes its own blocking call instead of being handed one) and Some(text) for transport = "websocket" — the raw inbound frame the host just read off the socket it holds for you.
Registry
Registry is the only path from a Go-supplied operation name to actual Rust code. A plain function in a plugin’s source is unreachable from the host until it is registered here — which is what makes “what does this plugin expose” answerable by reading one block (see the crate::plugin! macro, which builds this for you and reports the same list through describe).
TicketRef
TicketRef is what the action was run from — the way back from the vendor system to the conversation that caused the write.

Enums§

OpError
OpError is what a registered operation returns on failure. The two “sentinel” variants map to internal/extwasm’s own well-known envelope codes (see adapter.go’s CodeNotConfigured/CodeTicketTypeNotEnabled), so a plugin implementing extension.ContextProvider’s fetch_context gets the same cross-provider errors.Is behavior a native Go provider would. Everything else rides inside a successful envelope as an [Outcome] instead — see crate::Registry::op.

Constants§

ABI_VERSION
ABI_VERSION is the alloc/dealloc/handle contract’s own version, reported by describe so the host can refuse a binary built against a wire format it no longer speaks — rather than discovering the mismatch as a trap in the middle of a customer’s ticket. Bump it here and in abi.go’s ABIVersion together, or not at all.
FIELD_DATE
FIELD_DATE renders as a plain date input, whose value is always “YYYY-MM-DD”.
FIELD_MULTISELECT
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.
FIELD_NUMBER
FIELD_SELECT
FIELD_TEXT
FIELD_TEXTAREA
RICH_TEXT_FORMAT_JIRA_WIKI
RICH_TEXT_FORMAT_MARKDOWN

Type Aliases§

ActionField
ActionField is FieldSpec’s old name — kept as an alias for source compatibility with plugins written before the two schemas were unified.
ActionResult
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.
ContextResult
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.
PersistentConnectResult
PersistentConnectResult is the exact return type persistent_connect must have — a bare acknowledgement; the host discards the success payload.
PersistentReceiveResult
PersistentReceiveResult is the exact return type persistent_receive must have — the identical shape chatops_receive answers with, so a plugin implementing both transports (or migrating from one to the other) reuses the same note-building code either way.