# Plugins

Source: https://iskue.com/docs/plugins/

> Extend Iskue with sandboxed JavaScript plugins: the plugin registry, the marketplace and catalogue sources, hooks and event facts, the six script actions, background execution and the sandbox budgets.

Iskue's plugin system has three parts. The **registry** is a set of instance-wide extension records an administrator installs, enables, configures and uninstalls. Each record may carry a **sandboxed JavaScript** that runs in a locked-down GraalJS context whenever a ticket event fires. The **marketplace** installs plugins from catalogues — a built-in one that works offline, and any catalogue sources you add — instead of pasting scripts by hand. Scripts observe events, write log lines and request a small, fixed set of effects: add a label, assign, transition, comment and set a custom field.

> **Note:** **Java plugins** in the Jira Data Center model — with their own REST endpoints, a panel on the work item page, workflow rules, TQL functions, their own tables and a versioned Java API — are available as an **alpha** (plugin API 0.3) on the **Java plugins (alpha)** tab of Administration → Plugins; uploading them is off unless the instance sets `APP_PLUGINS_UPLOAD_ENABLED=true`. See [Plugin development](https://iskue.com/docs/plugin-development/). This page covers script plugins.

> **Note:** Plugins are an **ENTERPRISE** edition feature. With a licence installed, every request under `/api/v1/admin/plugins` (the marketplace included) on a lower edition is rejected with HTTP 403 and the body `{"message":"This feature requires the ENTERPRISE edition"}`. An instance with **no licence installed is unrestricted** — development and evaluation setups keep every feature.

## The plugin registry

Each installed plugin is a row with a stable `pluginKey`, display metadata (`name`, `description`, `version`), an `enabled` flag, a free-form JSON `config` object, an optional `script`, and — for plugins installed from a catalogue — where it came from. Two execution models hang off the same row: **built-in handlers** — trusted code shipped with the application, activated by installing a row whose key matches the handler — and **scripts**, attached by an administrator or installed from the marketplace. One built-in handler ships today: `event-logger`, which logs each ticket change, comment and SLA breach while installed and enabled; its `level` config key (`"info"` or `"debug"`, default `info`) controls the log level for ticket changes.

Nothing runs unless its registry row is both **installed and enabled**. Disabling a plugin stops its built-in handler and its script immediately; uninstalling removes the row entirely.

## Managing plugins

Open **Administration → Plugins** (`/admin/plugins`, ADMIN role). The **Installed** tab lists installed plugins with their key, version and enabled state, and offers per-plugin actions: **Enable/Disable**, **Configure** (edit the JSON config, seeded from the plugin's declared defaults), **Script** (edit the sandboxed script) and **Uninstall**. An install form registers a plugin by hand; built-in handler keys not yet installed appear as one-click shortcuts. The **Marketplace** tab is described below.

- `pluginKey` must match `[a-z0-9][a-z0-9.\-]{1,99}` — lowercase letters, digits, dots and hyphens, 2–100 characters. It is the stable identity and cannot be changed after install.
- `name` is required (up to 200 characters); `description` (1000) and `version` (40) are optional.
- The **Configure** panel edits the row's JSON config; it must parse as a JSON object.
- The **Script** panel edits the sandboxed JavaScript (at most 20,000 characters); saving an empty script clears it.

> **Note:** Every install, update and uninstall — by hand or from the marketplace — is recorded in the configuration audit trail under the `PLUGIN` category.

### REST API

| Method and path | Purpose |
| --- | --- |
| `GET /api/v1/admin/plugins` | List installed plugins (includes config and script) |
| `GET /api/v1/admin/plugins/available` | Keys of the built-in handlers this build ships |
| `POST /api/v1/admin/plugins` | Install (register) a plugin by hand |
| `PATCH /api/v1/admin/plugins/{pluginKey}` | Toggle `enabled`, replace `config`, and/or set `script` |
| `DELETE /api/v1/admin/plugins/{pluginKey}` | Uninstall |
| `GET /api/v1/admin/plugins/marketplace/catalog` | Every catalogue entry with its source, install state and available update |
| `POST /api/v1/admin/plugins/marketplace/catalog/{sourceId}/{pluginId}/install` | Install a catalogue entry (starts disabled) |
| `POST /api/v1/admin/plugins/marketplace/catalog/{sourceId}/{pluginId}/update` | Update an installed plugin to the catalogue's newer version |
| `GET`, `POST /api/v1/admin/plugins/marketplace/sources`; `PATCH`, `DELETE …/sources/{id}` | List, add, enable / disable and remove catalogue sources |

All three fields of the PATCH body are optional: omit a field (or send `null`) to leave it unchanged. A **blank** `script` clears the stored script; anything else replaces it.

*PATCH /api/v1/admin/plugins/{pluginKey} — request body*

```json
{
  "enabled": true,
  "config": { "runAsEmail": "triage-bot@example.com" },
  "script": "function onComment(event, config) {\n  if (event.body.toLowerCase().includes('urgent')) actions.addLabel('triage-urgent');\n}"
}
```

## Marketplace

**Administration → Plugins → Marketplace** installs plugins from catalogues. The **built-in catalogue** ships with Iskue and works offline. It carries two plugins: **Time in status** (on every status change, the time spent in the status just left is added to a text field, one line per status, totals accumulating across visits) and **Date of first response** (the date-time of the first comment by someone other than the reporter, recorded once in a date-time field, optionally with a label) — the counterparts of the CHART marketplace fields for Jira.

- Each card shows the version, author, description and the **permissions** the plugin declares, with one action: **Install**, **Update to x.y.z** when the catalogue has a newer version, or *Installed*. The tab counts how many installed plugins have an update.
- A search box filters by name, author or permission.
- Installed plugins **start disabled**, like any fresh install: enable and configure them on the Installed tab.
- Every download is verified against the **SHA-256** digest the catalogue publishes before it is installed; a mismatch is refused with a clear message.

### Catalogue sources

Administrators add **catalogue sources**: the HTTPS address of a catalogue document, which anyone can publish. Sources can be enabled, disabled or removed. They are re-read every 10 minutes with a 10-second timeout and a 1 MB size cap; a source that cannot be read keeps its last good catalogue and shows the error on its own row, never on the page.

*Catalogue format*

```json
{
  "name": "Acme plugins",
  "plugins": [
    {
      "id": "acme.hello",
      "name": "Hello",
      "version": "1.2.0",
      "description": "Adds a label to urgent comments.",
      "author": "Acme",
      "homepage": "https://acme.example/plugins/hello",
      "permissions": ["add a label"],
      "sha256": "<hex SHA-256 of the file at url>",
      "url": "https://acme.example/plugins/hello-1.2.0.js"
    }
  ]
}
```

`id` becomes the plugin key (same rules as above) and must be unique within the catalogue; `version`, `sha256` (64 hex characters) and an `https:` `url` are required, the rest is optional. `url` points at the plugin's JavaScript source (at most 20,000 characters) and `sha256` is its digest. Versions compare numerically by dotted segment (`1.10` is newer than `1.9`; `2.0-beta` precedes `2.0`). A catalogue holds at most 500 entries.

## Writing a plugin script

On every hook event, the runtime evaluates the whole script top to bottom in a **fresh context**, then — if the script defined a function with the hook's name — calls it as `hook(event, config)`. A script that does not define the current hook is a no-op for that event, so define only the hooks you care about. Four globals exist: `event` and `config` (read-only maps), `log(message)`, and `actions`. Nothing survives between invocations: top-level variables are re-initialised every time.

*A script may implement any subset of the three hooks*

```text
function onComment(event, config) {
  if (event.isFirstResponse) {
    actions.setField('First response', event.firstResponseAtLocal);
  }
  if (event.body.toLowerCase().includes('urgent')) {
    actions.addLabel('triage-urgent');
    actions.assign(config.oncallEmail);
  }
}

function onTicketEvent(event, config) {
  if (event.kind === 'STATUS_CHANGED' && event.status === 'Waiting for customer'
      && event.secondsInPreviousStatus > 86400) {
    actions.comment('Spent more than a day in ' + event.previousStatus + '.');
  }
}

function onSlaBreach(event, config) {
  log('SLA breached on ' + event.ticketKey);
  actions.transition('Escalated');
}
```

### Hooks and event payloads

| Hook | Fires | Event fields |
| --- | --- | --- |
| `onTicketEvent` | After a ticket change commits | `kind`, `ticketKey`, `actorId` (string UUID, or null for system / anonymous changes) |
| `onComment` | After a comment is added (internal user, or customer via portal or inbound email) and the change commits | `kind` (always `COMMENTED`), `ticketKey`, `authorId` (null for customer-authored comments), `body`, `visibility` (`PUBLIC` or `INTERNAL`) |
| `onSlaBreach` | When a ticket breaches its response or resolution SLA | `kind` (always `SLA_BREACHED`), `ticketKey` |

Besides those, **every** hook's `event` carries the work item's facts: `title`, `priority`, `status`, `statusCategory`, `statusSince`, `createdAt`, `reporterId`, `assigneeId`, `now`, `nowLocal` and `fields` (current custom-field values by field name). A status change adds `previousStatus`, `previousStatusEnteredAt` and `secondsInPreviousStatus`. A comment adds `isFirstResponse`, `firstResponseAt`, `firstResponseAtLocal` and `secondsToFirstResponse` — the first comment by someone other than the reporter, portal contacts excluded.

`event.kind` in `onTicketEvent` is one of `CREATED`, `UPDATED`, `STATUS_CHANGED`, `ASSIGNED`, `COMMENTED`, `LABEL_ADDED`. A new comment fires **both** `onTicketEvent` (with kind `COMMENTED`) and `onComment`; only the latter carries the comment body and visibility. **Editing** an existing comment also fires `onTicketEvent` with kind `COMMENTED` (but not `onComment`), so use `onComment` when you need exactly one call per new comment. Plugins are instance-wide — every enabled script runs for events from **all projects** — so branch on `event.ticketKey` (the project key is its prefix) if a script should act on some projects only.

`config` is the plugin row's JSON config, passed to every hook. Use it for tunable values — team e-mails, label names, keyword lists — so behaviour can be changed from the Configure panel without editing the script.

## What scripts can do

Scripts never touch application services directly — they collect actions through the `actions.*` surface, and after the script returns a separate applier performs them. That applier is the plugin runtime's only write path into the application, so a script's power is exactly the actions below, no more.

| Function | Effect |
| --- | --- |
| `log(message)` | Writes one line to the application log at INFO, prefixed `[plugin <pluginKey>]`. |
| `actions.addLabel(name)` | Attaches a label to the event's ticket, created in the project if missing (matched case-insensitively; idempotent). |
| `actions.assign(email)` | Assigns the ticket to a project member by e-mail; `null` or an empty value unassigns. |
| `actions.transition("Status name")` | Moves the ticket to a status by name or id — only along a transition the workflow allows. |
| `actions.comment(text)` | Adds an internal note. Requires the plugin's `runAsEmail` config entry; refused without it. |
| `actions.setField("Field name", value)` | Sets a custom field of the ticket's project by name, creating it (TEXT, or DATETIME when the value looks like `yyyy-MM-ddTHH:mm`) if the project lacks it. An empty value clears the field. |

- Set the plugin's **`runAsEmail`** config entry to the user these changes are attributed to in the history and in notifications.
- Messages, names and values are trimmed and truncated to about 200 characters (197 plus an ellipsis); label names are additionally capped at **60** characters, so a longer `addLabel` fails at apply time (logged as a warning).
- At most **10 actions** are collected per invocation; further calls are silently dropped.
- For an SLA-breach event that cannot be resolved to a concrete ticket, collected actions are discarded rather than applied.

> **Note:** A plugin's own changes **never trigger plugins again**: while its actions are applied, the resulting events are not fed back to the plugins, so a script that comments on every change cannot loop.

> **Warning:** Scripts cannot call external services, create tickets, keep state between runs or schedule work. If a process needs more than the six functions above, it belongs in an automation rule — or in a [Java plugin](https://iskue.com/docs/plugin-development/) (alpha).

## Background execution

Hooks are dispatched **after the triggering transaction commits**, on a small background pool (two workers, a queue of 500), so a slow plugin never slows down the request that triggered it — a label a script adds appears a moment later. When the queue is full, the invocation is skipped with a warning in the log.

## Sandbox and isolation

Scripts run in a GraalJS polyglot context (community edition, interpreted on a stock JDK) with all host access disabled. The sandbox is **deny-by-default**: the only capabilities a script has are the four injected globals, and the only inputs are immutable copies of the event and config maps.

- **No host classes** — the `Java`, `java` and `Polyglot` interop namespaces do not exist.
- **No filesystem, network, process or thread access** — `fetch`, `require` and `process` are undefined; there is no IO surface of any kind.
- **Fresh context per invocation** — scripts are stateless and cannot leak data between events or between plugins.
- **Read-only inputs** — `event` and `config` are immutable copies.

### Execution budgets

Independent guards bound a runaway script. A **statement limit** cancels interpreted loops outright. A **wall-clock watchdog** bounds total time and catches work the statement counter cannot see. A **memory budget** cancels a script whose thread allocates too much, and strings and typed arrays are capped so one giant allocation fails fast. Any guard tripping fails that one invocation; the next event starts clean.

| Limit | Value | On breach |
| --- | --- | --- |
| Statements per invocation | 100,000 | Invocation cancelled: "script exceeded its statement limit" |
| Wall-clock time per invocation | 5,000 ms | Context closed: "script exceeded its 5000ms time limit" |
| Memory allocated per invocation | 256 MB | Invocation cancelled |
| String length / typed-array length | 10 million characters / elements | RangeError inside the script |
| Actions per invocation | 10 | Further `actions.*` calls silently ignored |
| Script size | 20,000 characters | Rejected at save time |

## Error handling and logging

Every plugin invocation is isolated: a syntax error, thrown exception, sandbox violation or budget breach is caught, logged and swallowed. A failing script can never roll back or break the operation that triggered it, and never prevents other plugins from running.

- Failures surface with safe, self-describing messages: `script error: …`, `script exceeded its statement limit (possible infinite loop)`, `script exceeded its 5000ms time limit (possible infinite loop or heavy computation)` and `script rejected: …`. Cause chains from plugin code are deliberately discarded.
- Failures are logged at WARN as `Script plugin '<pluginKey>' failed handling <hook> on <ticketKey>: <message>`.
- `log()` output appears at INFO as `[plugin <pluginKey>] <message>`.

To verify the runtime end to end, install **Time in status** from the marketplace, enable it, and move a ticket between two statuses: the *Time in status* field appears on the ticket a moment later.
