Salamandr plugin SDK (Rust)
Write an extension for a Salamandr helpdesk: a small sandboxed WebAssembly binary that answers "who is this person in my system?" when an agent opens a ticket, and renders the answer in the ticket sidebar.
You do not need access to the Salamandr source to write one. You need this crate, a manifest, and the deployment's admin to install what you build.
There is a second SDK — sdk/assemblyscript — that
implements the same contract in TypeScript (AssemblyScript). Same ABI, same
manifest, same wire format; a plugin built with either is indistinguishable
to the server, and the two example plugins are run through one shared Go
contract test to keep it that way. Pick whichever language you would rather
maintain.
&&
# Cargo.toml
[]
= ["cdylib"] # not rlib — an rlib exports nothing
[]
= "0.3"
= { = "1", = ["derive"] }
= "1"
[]
= "z"
= true
= true
= "abort"
// src/lib.rs
use ;
plugin!
# -> target/wasm32-unknown-unknown/release/my_plugin.wasm
Start from sdk/examples/hello-crm instead of the snippet above — it
is a complete working plugin (vendor call, tenant secret, helpdesk data,
five tests) and is the code this README describes.
Contents
- What a plugin can do
- The manifest
fetch_context: the operation that matters- Actions: writing back
opsvscontext_opsvsaction_ops- Linking, creating, and read-only pickers
- Host capabilities
- Errors
- Testing
- Installing
- Limits and the sandbox
- Versioning
- Writing a plugin without this SDK
What a plugin can do
Four things, each behind a scope your manifest declares and a tenant admin approves:
| capability | function | scope |
|---|---|---|
| one HTTP call at a time | http_fetch |
http_hosts |
| tenant-supplied config and secrets | get_config |
config_keys |
| a small private key/value store | kv_get / kv_set / kv_delete / kv_list |
kv |
| the tenant's own helpdesk data | core::* |
core |
| upload a file the host handed you | http_upload |
http_hosts |
Plus log and self_info, which need no scope.
There is nothing else. No filesystem, no environment variables, no
sockets, no clock but the host's, no WASI — a plugin targets
wasm32-unknown-unknown, so there is no OS surface to sandbox in the
first place. This is what makes installing a third-party plugin a
reviewable decision rather than an act of faith.
The manifest
manifest.toml ships next to your .wasm and is the entire security
contract. Ask for the least that works: every line is one an admin has to
justify.
= "my-plugin" # [a-z0-9][a-z0-9_-]{1,63}
= "0.1.0"
= "issue_tracker" # crm | erp | msp | field_service | issue_tracker | tasklist | storage | custom
= "Your Name"
= "One line shown in the admin UI."
= ["fetch_context", "log_note", "link_issue", "unlink_issue",
"create_issue", "list_projects"] # every op the binary registers
# license_module = "crm" # optional: require an Enterprise license module
# read_ops: which of the entrypoints above the ticket sidebar's picker
# endpoint (GET /extension-ops/{provider}/{op}) may call directly — a
# read-only "list_projects"-style op, never a write. See "Linking,
# creating, and read-only pickers" below.
= ["list_projects"]
# link_op/unlink_op/create_op: name the entrypoints (already registered
# under `ops`, below) that back the ticket sidebar's own "link to an
# existing record" / "remove that link" / "create a new record" buttons.
# All three optional, and independent — declare only the ones your
# connector actually supports.
= "link_issue"
= "unlink_issue"
= "create_issue"
# create_form_op: names a read_ops entry (plain data, no network call)
# that answers the create form's own field list, so the ticket sidebar
# renders real inputs instead of a raw JSON body textarea. Optional, and
# only meaningful alongside create_op. Must also be listed in read_ops.
= "create_issue_form"
[]
= ["api.acme-crm.com"] # exact, or one leading "*." wildcard
# http_host_config_key: an *additional* allowed host, read from the
# named config_keys entry's own current value (its hostname) rather than
# declared as a fixed string — for a vendor whose address is genuinely
# tenant-supplied (a self-hosted instance) rather than shipped as a
# fixed API host. Optional; must name a key already listed below. See
# "A tenant-configured host" below.
= "base_url"
= ["api_key", "base_url"]
= false
= ["users:read", "tickets:read"]
Rules worth knowing before you hit them:
- Unknown fields are rejected, not ignored — a typo'd scope name fails at install rather than silently granting nothing.
entrypointsmust match what the binary registered, exactly and in both directions. Theplugin!macro generates adescribeexport the server reads, so a manifest that claims an op the binary doesn't have (or hides one it does) is refused at install.http_hostswildcards:*.acme-crm.commatcheseu.acme-crm.com, notacme-crm.comitself. Comparison is case-insensitive on the host only — never on the path.read_ops/link_op/unlink_op/create_op/create_form_opmust each name a declared entrypoint — the same "manifest can't drift from itself" check every other op-name field here gets.create_form_opadditionally must be listed inread_opsitself.- Re-installing under the same
namereplaces the extension in place and keeps its stored config, then leaves it disabled so the admin re-consents to whatever the new manifest asks for. kindis informational. It groups the extension in the admin UI and changes nothing the runtime allows.
Core scopes
core entries are <resource>:read or <resource>:write. Neither
implies the other, so a plugin that tags tickets does not thereby get to
read every ticket in the tenant.
| resource | read actions | write actions |
|---|---|---|
tickets |
get, list_by_requester, list_by_organization, messages |
add_note, create, update |
tags |
list, for_ticket |
add_to_ticket, remove_from_ticket |
users |
list, get, by_email |
upsert |
organizations |
list, get, by_domain, members |
upsert |
teams |
list, members |
— |
ticket_types |
list |
— |
ticket_statuses |
list |
— |
ticket_priorities |
list |
— |
sla_policies |
list, for_priority |
— |
custom_fields |
list |
— |
business_hours |
get |
— |
Each function in core
names the scope it needs in its own doc comment.
fetch_context: the operation that matters
Every community plugin must implement it — it is what the ticket sidebar calls, and installing without it is refused.
In — ContextRequest { ticket_type_id: Option<String>, candidate_emails: Vec<String> }.
The addresses are the requester's own plus any alternates the helpdesk
knows for the same human, primary first. That is the only identity signal
you get: a context tool never creates tickets, so there is no per-vendor
id on the ticket to look up by.
Out — Vec<ContextBlock>: a titled group of label/value pairs, plus
optional deep links.
new
.field
.field_opt // skipped when None or blank
.action
Every enabled extension's blocks are concatenated into one sidebar list, so title yours after the vendor, not "Contact".
Ok(vec![]) is the right answer for "not in my system." An Err means
I could not answer — not configured, vendor down — and lands in the
server's log. Formatting is yours: nothing downstream reformats a value,
so render money, dates and numbers the way an agent should read them.
Actions: writing back
A block can carry more than deep links. An executable action renders as a button in the expanded context view: the agent fills in the fields you declared, confirms, and the host calls your operation — which writes into the vendor's system.
Build the action where you build the block, because that is where the ids already are (the browser has no way to learn a vendor id, and re-resolving one on every click costs a round trip):
new
.field
.run
The handler's signature is fixed the way fetch_context's is:
In — ActionRequest { params, inputs, actor, ticket, occurred_at }.
params is what you attached; inputs is what the agent typed, keyed by
field. Both arrive through the agent's browser, so validate them —
req.param("contact_id")? and req.input("body")? do the usual checks.
Never let params decide which record you write to. They make the
round trip through the browser, so an id in params is a request, not a
fact: a write addressed by one reaches whatever record the caller named —
any record your credentials can touch, not the one this ticket is about.
Use req.ticket.id (host-stamped) to look your own link up through
host_core's external_links instead. params remains the right place
for display detail the write doesn't address with.
actor, ticket and occurred_at are stamped by the host and cannot be
influenced by the client; req.signature() renders them as the one-line
"who, which ticket, when" to append to whatever you write. Sign every
write — a note whose author is "the integration" leaves whoever reads it
with nobody to ask. occurred_at is also the only clock you have: a
plugin runs on a freestanding wasm target with no time source at all.
Out — ActionOutcome::new("Note logged in Acme CRM").url(deep_link).
The message is shown to the agent and recorded on the ticket's timeline.
Register actions in the macro's action_ops block:
plugin!
That block is a security boundary, not bookkeeping. The op name travels
from the browser, so the host runs only what action_ops names —
put a write in ops/context_ops instead and the click is refused; put
a read there and it never becomes clickable by accident. Actions are
staff-only, always bound to a ticket, audited, and recorded on that
ticket's timeline by the server.
ops vs context_ops vs action_ops
Three blocks in the plugin! macro. Picking wrong between the first two
is the one mistake in this SDK that compiles and installs before
misbehaving:
context_ops— the host decodes your answer directly. This is whatfetch_context(and anyfetch_contact-style typed op) must use. Almost every community plugin uses only this block.action_ops— same wire shape ascontext_ops, plus the host's permission to run the op from a button. See the section above.ops— the answer is wrapped in an internally-taggedOutcomeobject that only a purpose-written Go caller can unwrap. It exists for first-party connectors shipped inside the server. A community plugin has no such caller.
Registering fetch_context under ops is refused at install with a
message naming the fix, because describe reports which block each op
came from — and the same report is what refuses an action the binary
never registered as one.
Linking, creating, and read-only pickers
An issue-tracker-shaped connector (or anything else keyed on "which
external record is bound to this ticket") needs three more things
fetch_context/action_ops don't cover, all served by the host's
generic POST/DELETE /tickets/{id}/extension-link/{provider},
POST /tickets/{id}/extension-create/{provider} and
GET /extension-ops/{provider}/{op} routes — a community plugin gets
these for free the moment it declares them, no different from a
connector this codebase ships itself:
link_op— bind this ticket to an existing external record. The agent types one opaque identifier (an issue key, a ticket number); your op receives{ "ticket_id": "...", "external_key": "...", "linked_by": "..." }and persists whatever bridge your connector needs (external_links, thecoreresource built for exactly this — see the "Helpdesk data" example below).unlink_op— remove that binding. Receives{ "ticket_id": "..." }.create_op— make a brand-new external record and link it in one step. Receives the create-form's own JSON body (whatever fields your connector's create form asks for — there's no fixed shape, since a Jira issue and a GitHub issue don't share one) plusticket_id/linked_bymerged in. Answer the same{ key, title, status, assignee, priority, url }shape every built-in issue tracker's create op does — the sidebar renders whichever of those fields you set and ignores the rest.
All three are registered under ops (the Outcome-tagged shape), same as
any other read/write your connector performs against its own vendor —
link_op/unlink_op/create_op in the manifest just name which
already-registered ops back those three routes.
read_ops is narrower and older: a bare allow-list of ops-block
entrypoints the create-form's own pickers (a project list, a label list)
may call directly, with no ticket binding and no audit trail — a read
against the vendor, nothing more. Never list a write here.
create_form_op turns the create form itself from a raw JSON body
textarea into real inputs. It names one of your read_ops entries — plain
data, no network call needed, so write it exactly like any other read op
— whose answer is a flat array of field specs:
Each field is {key, label, kind, required?, placeholder?, options_op?, depends_on?, numeric?}.
kind is one of text/textarea/select/multiselect/number. A
select (or multiselect) field's options_op names another read_ops
entry the sidebar calls to populate it — that op must answer
{value, label} pairs, the one shape every picker (list_projects,
list_teams, ...) should converge on regardless of what your vendor's own
API calls those fields. A multiselect's value reaches your create_op
as a JSON array of the picked values, never a joined string. Set
numeric: true on a single-valued field whose value should travel as a
JSON number rather than a string — the host casts it before calling your
create_op.
The host validates this schema before the browser sees it: an
options_op outside your read_ops, a depends_on naming a field that
isn't there or that is itself dependent, a duplicate key or an unknown
kind is refused with an error naming the field. Those used to render as
a dropdown that silently stayed empty, or a field that never enabled.
Single-level cascading via depends_on: name another field in this
same schema whose current value gates a select. The sidebar disables
the dependent field and leaves it unfetched until the named field has a
value; once it does, options_op is called with one query param —
{depends_on: <that field's current value>} — and the same happens
again, with the dependent field's own value cleared, every time the
parent changes:
json!
list_issue_types then reads that param the same way any other op reads
its input:
No multi-level chains: the field a depends_on points to must not
itself have a depends_on — there is no way to express "C depends on B
depends on A" here. A dependency deeper than one level, or one where what
varies is which fields exist rather than one field's options (Redmine's
custom fields, gated by tracker), has no representation in this schema:
leave it out and keep it reachable as a plain read_ops entry instead.
Host capabilities
HTTP
let resp = http_fetch?;
Err means the call failed (no scope, bad URL, network failure, host
refused). A 4xx/5xx is a successful round trip carrying a status — what it
means is your plugin's business. resp.header("retry-after") is
case-insensitive. One call at a time; there is no concurrency inside a
plugin.
A tenant-configured host. http_hosts is a fixed list you write once
in the manifest — right for a vendor with one API host (or a small,
nameable set). It cannot work for a vendor whose address is itself
tenant-supplied: a self-hosted Redmine/GitLab/Bitbucket instance lives
wherever that tenant put it. scopes.http_host_config_key names one of
your config_keys entries whose current stored value — the same
base_url the admin already typed into your extension's config form —
also authorizes http_fetch, resolved fresh each time your plugin runs
rather than frozen at install. Nothing else changes: http_fetch still
refuses any host outside the resulting grant, redirects included. Skip
this entirely if your vendor has a fixed host; http_hosts alone is
simpler and is all a SaaS-only connector ever needs.
Knowing yourself, and uploading a file
let me = self_info?; // no scope: identity, not reach
// me.webhook_url is where deliveries for this installation arrive.
http_upload?;
self_info answers this installation's own id, name, version, kind and
public delivery URLs. It exists for the vendor that registers its own
webhook over its API (Telegram's setWebhook, a GitLab project hook): the
delivery token is minted by the host, so without this a plugin had to have
an admin copy a URL out of one field of its own settings screen and paste
it into another. No scope gates it — it discloses nothing the admin who
installed the plugin isn't already looking at.
http_upload sends one of the files on the reply a channel_send is
delivering, as multipart/form-data, without the bytes ever entering
your plugin's memory: the host streams them from its own storage into a
request you describe. It obeys the same http_hosts allow-list, redirect
re-checking and per-call request budget http_fetch does, and it accepts
only the attachment ids on the ChannelSendRequest this very call is
delivering — naming any other id is refused, which is what stops a plugin
using it to read a tenant's customer files.
Config and secrets
let Some = get_config? else ;
Values are set by the tenant admin and stored encrypted. Ok(None) means
the key was never filled in — an ordinary state for a freshly installed
extension. A key not listed in config_keys is refused even if the tenant
set it.
Key/value store
kv_set?;
let cursor = kv_get?; // Ok(None) when never set
let seen = kv_list?; // keys only, "" for all of them
kv_delete?; // deleting an absent key is fine
Per tenant, per extension, scoped to your plugin. Fine for a cursor or a
small cache; not a database — the store holds a few hundred keys per
extension, so anything you write per record you also have to delete. Use
kv_list to find what a previous run left behind (a scheduled plugin
reconciling its own state is the usual reason).
Helpdesk data
let user = user_by_email?; // Option<User>
let tickets = tickets_by_requester?; // Page<Ticket>
add_ticket_tags?; // needs tags:write
Single-row lookups answer Ok(None) when the row doesn't exist — no error
strings to match on. Lists answer a Page<T> whose has_more says
whether another page is worth asking for. A resource you didn't declare is
an Err, distinguishable from "this tenant has none".
Reads are RLS-scoped to the tenant. Writes go through the same domain services the UI uses, so a tag your plugin adds writes the same audit event an agent's would.
Errors
HostError is what a host call returns; OpError is what your operation
returns. ? converts one into the other, and a host-side "not found"
stays a not-found.
OpError |
use it for |
|---|---|
NotConfigured |
the tenant hasn't finished setting the extension up |
TicketTypeNotEnabled |
this ticket's type isn't in the extension's allow-list |
NotFound |
a lookup that should have resolved and didn't |
RateLimited { retry_after } |
the vendor rate-limited you |
Transient(msg) |
safe to retry blindly (5xx, network) |
Other(msg) |
anything else |
All of these carry across from context_ops/action_ops as typed
outcomes, so RateLimited/Transient become a real retry (and, for a
sidebar lookup, an error the agent sees) rather than folding into "nothing
found". That distinction matters more than it looks: "nothing found" is
what the sidebar shows when no record is linked yet, and it is the state
that offers an agent a Create button — so reporting a rate limit as
anything else invites a duplicate record over a link you merely failed to
read.
Testing
cargo test, no server
On non-wasm targets this crate links your plugin against an in-process mock host, so operations run natively — with your real manifest's scopes enforced:
use MockHost;
A scope you forgot to declare fails your test instead of a customer's
ticket. MockHost simulates scopes, config, kv, core and HTTP; it does
not simulate the wasm sandbox, the call timeout or the memory limit.
plugindev, the real runtime
plugindev runs your compiled .wasm under the same wazero engine,
manifest parsing, scope enforcement and install-time verification the
server uses — against a fixtures file, with no server and no database.
plugin: hello-crm 0.1.0
built with: salamandr-plugin-sdk 0.3.0 (ABI 1)
implements: fetch_context
scopes: http=api.acme-crm.com config=api_key core=users:read,tickets:read
ok: manifest and binary agree
calling fetch_context with {"candidate_emails":["ada@example.com"]}
http GET https://api.acme-crm.com/v1/contacts?email=ada%40example.com -> fixture 200
result:
[{"title":"Acme CRM","fields":[…],"actions":[…]}]
fixtures.json supplies what the host would read from a tenant's database
or the internet (sdk/examples/hello-crm/fixtures.json is a working one):
Anything unfixtured is reported as a named failure rather than a silent
empty answer. -allow-net lets unmatched calls reach the real internet;
-verify-only stops after the manifest/binary check; -op and -input
call something other than fetch_context.
Installing
An admin of the target deployment installs the pair. There is no marketplace: the trust boundary is deliberately "an admin chose to install this binary and reviewed the scopes it asks for."
These are cookie-authenticated admin calls, so they are subject to the CSRF
check every state-changing request goes through: mint a token with
GET /api/v1/auth/csrf, then echo the h4u_csrf cookie back in an
X-CSRF-Token header on each of the calls below. For scripting, an
admin-scoped API key (Authorization: Bearer …) is simpler — it is not an
ambient credential, so it is exempt from CSRF entirely.
# 1. Install (as an admin session). The extension arrives disabled.
# 2. Fill in the config the manifest declares.
# 3. Enable it — this is the admin's explicit consent to the scopes.
# Optional: restrict it to certain ticket types.
# Remove it.
GET /api/v1/extensions lists what's installed, with the scopes each one
was granted.
Limits and the sandbox
| call timeout | 5s per operation, including your HTTP call |
| memory | 256 pages (16 MB) |
| HTTP request | 256 KB, 10s timeout |
| HTTP response | 2 MB |
| log line | 4 KB |
| config key | 128 chars |
| kv key / value | 256 chars / 64 KB |
| core request | 64 KB; pages default 50, max 200 |
| core: tags per call | 20 |
| core: note body | 16 KB |
| upload (manifest + wasm) | 20 MB |
A fresh module instance is created per call: no state survives between calls, and none leaks between tenants. There is no fuel metering — a tight compute loop that never yields is bounded only by the call timeout, so don't write one.
Versioning
- Minor/patch: new wrappers, new core resources, new helpers. A plugin built against an older 0.x keeps working.
- Major: the guest ABI changed. The server refuses a binary built
against an ABI it no longer speaks (
describereports it), so rebuild against the new SDK.
Keeping entrypoints and your plugin! block in sync is checked for you;
keeping your manifest's scopes in sync with what your code calls is
checked by MockHost::from_manifest in your own tests.
Writing a plugin without this SDK
The ABI is small and this crate is not privileged. There is already a
second implementation of it in sdk/assemblyscript,
and a plugin in any other language that compiles to freestanding wasm
(TinyGo -target=wasm, C, Zig) works if it exports:
alloc(size u32) -> ptr u32
dealloc(ptr u32, size u32)
handle(op_ptr u32, op_len u32, in_ptr u32, in_len u32) -> u64 // (out_ptr<<32 | out_len)
describe() -> u64 // optional
and imports its host functions from module salamandr. Every value
crossing the boundary is a JSON envelope: {"ok":true,"data":…} or
{"ok":false,"error":"…","code":"…"}. Without describe you lose the
install-time entrypoint check and nothing else.
Rebuilding the example
sdk/examples/hello-crm/hello_crm.wasm is committed so the server's own
test suite can run the example end to end. After editing the example or
the SDK's context types: