From d8daeb3e8d85d867680857cffe8e95462a486fe0 Mon Sep 17 00:00:00 2001 From: Philip Date: Sun, 1 Nov 2026 00:44:41 -0400 Subject: [PATCH] docs: bring the README, SDK and template docs up to date The README now covers the Workflows plug-in, how rh runs a plug-in, the install and approval flow, the permissions and their Landlock confinement, web panels and their bridge messages, and the plug-in creator's tools and templates, with each bundled plug-in's settings, permissions and routes. Add a README for the TypeScript SDK and the Rust crate documenting their public API, and bring the creator GUIDE in line with the SDK's http routes and the runtime's permission rules. --- README.md | 242 +++++++++++++++++++++++++++------ packages/plugin-sdk/README.md | 110 +++++++++++++++ rust/rivethub-plugin/README.md | 96 +++++++++++++ templates/javascript/GUIDE.md | 79 +++++++---- 4 files changed, 456 insertions(+), 71 deletions(-) create mode 100644 packages/plugin-sdk/README.md create mode 100644 rust/rivethub-plugin/README.md diff --git a/README.md b/README.md index 67b5f9f..f3220be 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,23 @@ # rivethub-plugins -Plug-ins for RivetHub, and the SDKs and templates for writing them. A plug-in is a program that runs in its own process on -one node and reaches the runtime only over its published contract (row B17 and notes 50 to 60 of the -[rivethub-runtime](https://github.com/philbert440/rivethub-runtime) CONTRACT): rh starts it, proxies clients to its -views, delivers its events and offers its tools to agents through `rh mcp`. A plug-in that proves valuable for everyone -gets promoted into the platform, with its domain moving into a runtime context and its payloads into the contract. +Plug-ins for RivetHub, and the SDKs and templates for writing them. A plug-in is a program that runs in its own process +on one node and reaches the runtime only over its published contract: row B17 and notes 50 to 60, 71 and 91 of +`docs/CONTRACT.md` in [rivethub-runtime](https://github.com/philbert440/rivethub-runtime). rh starts it, proxies clients +to its views, delivers its events, runs its jobs and offers its tools to agents through `rh mcp`. ## Layout - `packages/contract`: `@rivethub/contract`, the runtime's schemas and the types generated from them. -- `packages/plugin-sdk`: `@rivethub/plugin-sdk`, for plug-ins in TypeScript, with the `rivethub-plugin-dev` harness. -- `rust/rivethub-plugin`: the `rivethub-plugin` crate, for plug-ins in Rust, in a Cargo workspace of its own. +- `packages/plugin-sdk`: `@rivethub/plugin-sdk`, for plug-ins in TypeScript or JavaScript, with the + `rivethub-plugin-dev` harness. Its [README](packages/plugin-sdk/README.md) documents the API. +- `rust/rivethub-plugin`: the `rivethub-plugin` crate, for plug-ins in Rust, in a Cargo workspace of its own. Its + [README](rust/rivethub-plugin/README.md) documents the API. - `templates/typescript`, `templates/rust`: a checklist plug-in in each language to start from: a page with a form and a list (and a canvas board in TypeScript), an `add_item` agent tool and a `session.placed` subscription. -- `templates/javascript`: the same checklist with its canvas board, in JavaScript that Node runs as it is, and a - `GUIDE.md` for an agent building from it. It is the template rh's plug-in creator scaffolds from. -- `plugins/voice`: speech to text and text to speech for the composer, on `http/transcribe` and `http/speak`, through - the STT and TTS servers named in its settings. It replaces rh's `/api/voice` routes. -- `plugins/files`: the Files page's and the workflow editor's file calls on `http/list`, `http/download`, `http/upload`, - `http/mkdir`, `http/rename` and `http/delete`, with the queries, bodies and errors of rh's `/api/files` routes, which it - replaces. Every path stays inside the folder its `root` setting names, links included. +- `templates/javascript`: the same checklist with its canvas board, in JavaScript that Node runs as it is, and + [`GUIDE.md`](templates/javascript/GUIDE.md), the field-by-field guide an agent builds from. It is the template rh's + plug-in creator scaffolds from. +- `plugins/voice`, `plugins/files`, `plugins/workflows`: the plug-ins described under [The plug-ins](#the-plug-ins). ## The contract @@ -31,17 +29,44 @@ gets promoted into the platform, with its domain moving into a runtime context a - `rust/rivethub-plugin/src/contract.rs`, the plug-in types (the manifest, views, canvas, events, jobs, tools, the plug-in API and `GatewayError`) as Rust, from the accepted schema. -To move to a newer runtime, set `ref` in `contract.json` to a commit on the runtime's `main`, run `npm run contract`, and +To move to a newer runtime, set `ref` in `contract.json` to the runtime commit's full sha, run `npm run contract`, and commit the schema and type diff in its own PR. If a plug-in needs something the contract doesn't offer, propose the change to the runtime first. -## Writing a plug-in +## How a plug-in runs -A plug-in is a directory holding `rivethub-plugin.json` and the program its `run.command` starts. Both SDKs answer what rh -asks on the plug-in socket (`GET /health`, views, actions, canvas events, tools, events and jobs), drop an event -delivery they have already handled (by `seq`), pass `settings.changed` and the starting settings to the settings -handler, and call rh on the plug-in API socket with the per-start token: the plug-in's own record, `viewsChanged`, -`notify`, and any route its permissions name. +A plug-in is a directory holding `rivethub-plugin.json`, its manifest, and the program its `run.command` starts. The +manifest names the plug-in (`id`: 2 to 24 of `a-z`, `0-9` and single hyphens), what it asks for (`permissions`), its +`settings` fields, its agent `tools`, its `contributes` (`pages`, `topicCards`, `sessionActions`), its `jobs` and the +`events` it subscribes to; `GUIDE.md` lists every field. rh refuses an unknown field or an invalid value, naming its +path. + +rh starts `run.command` in the plug-in directory with `PATH`, `HOME`, `USER`, `LANG`, `LC_ALL` and `TZ` from its own +environment, `run.env`, and `RIVETHUB_PLUGIN_ID`, `RIVETHUB_PLUGIN_NODE`, `RIVETHUB_PLUGIN_DATA` (its data folder), +`RIVETHUB_PLUGIN_SOCKET`, `RIVETHUB_API_SOCKET`, `RIVETHUB_PLUGIN_TOKEN` and `TMPDIR`. The plug-in serves HTTP/1.1 on +the unix socket `RIVETHUB_PLUGIN_SOCKET`: `GET /health` (it is ready once this answers 2xx within `run.readyTimeoutMs`, +default 10000), `POST /views/{view}`, `/actions/{action}`, `/canvas/{canvas}/events`, `/tools/{tool}`, `/events` and +`/jobs/{job}`, `GET /panel/{path}` and any method on `/http/{path}`, as far as its manifest needs them. A process that +exits or is not ready in time is started again after 1 s, doubling to 60 s. + +Clients reach it through rh as `/api/plugins/{id}/{views,actions,canvas,tools,panel,http}/…`; rh adds +`x-rivethub-user`, `x-rivethub-node` and `x-rivethub-request-id` and drops the caller's credentials. rh parses every +view, action, canvas and tool answer as its contract type and answers the client `502` `plugin_invalid_response`, +naming the field, for one that does not parse. It waits 30 s for those answers, 120 s for a tool and 60 s for the first +byte of a `panel` or `http` answer, which it streams. Agents get each tool as `-` from `rh mcp`. + +The plug-in calls rh on `RIVETHUB_API_SOCKET` with `Authorization: Bearer `, a token minted at +each start: `GET /api/plugin/self` (its record, settings and data folder), `POST /api/plugin/views/changed` (clients +showing those views fetch them again; apps never poll), `POST /api/plugin/notify`, and the routes its permissions open. + +rh keeps each plug-in's `/plugins//`: `data/` (kept across reloads and disables), `run/` (its socket and +`TMPDIR`) and `logs/plugin.log`, which holds its stdout and stderr and rh's own `host` lines (start, exit, every answer +it refused). + +## Writing one + +Both SDKs answer what rh asks on the plug-in socket, drop an event delivery they have already handled (by `seq`), pass +the starting settings and every `settings.changed` to a settings handler, and call rh on the API socket. ```ts await serve({ @@ -49,6 +74,7 @@ await serve({ actions: { add: ({ values }) => [{ type: 'refresh' }] }, tools: { add_item: ({ title }) => `Added ${String(title)}` }, events: { 'session.placed': ({ sessionId }) => {} }, + http: { report: (request) => new Response('ok') }, }) ``` @@ -61,27 +87,160 @@ Plugin::new(state) .await ``` -The TypeScript SDK also serves the `http/` routes: `http: { speak: (request) => response }` gets each -`/http/speak/…` call as a web `Request`, body unread, and streams the `Response` it returns back through rh. +Only the TypeScript SDK serves `http/` routes; neither serves `panel/` yet. On Linux rh confines the process with +Landlock (see [Permissions](#permissions)), so it can read only its own directory, the program it runs and the system +folders. A TypeScript plug-in therefore runs a bundle (`npm run build -w ` writes `dist/plugin.js` with +esbuild), a JavaScript one carries the SDK's sources in its own `sdk/` folder, and a Rust one runs its release binary +(`cargo build --release`, `run.command` `["target/release/"]`). + +`rivethub-plugin-dev ` starts a plug-in the way rh does, standing in for its `/api/plugin` routes, and reads +commands from stdin (`view main`, `action add {"values":{"title":"x"}}`, `canvas board {"event":{…}}`, `tool add_item +{"title":"x"}`, `event session.placed {…}`, `job `), printing each answer. Any other rh route answers `501`, and +`http` routes have no command. `npm run dev` in `templates/typescript` builds and runs it this way. + +## Installing on a node + +Only the node's owner manages plug-ins: + +- `POST /api/plugins` `{"path": ""}` registers the directory in place, disabled, with every + permission it asks for pending. Nothing is copied, so edits to the directory take effect at the next reload. +- `POST /api/plugins/{id}/enable` `{"approve": []}` (`{}` when none are pending) grants them + and starts the process. +- `POST /api/plugins/{id}/reload` reads the manifest again and restarts an enabled plug-in. Fewer permissions narrow the + grant at once; more stop it in `awaitingApproval` until an enable approves them. +- `POST …/disable` stops it and keeps its grants, settings and data; `DELETE /api/plugins/{id}` removes it and its + `/plugins//` (`?keepData=true` keeps that), never the source directory. +- `GET …/logs?tail=` reads its log; `GET` and `PUT …/settings` `{"values": {…}}` read and change its settings (`null` + resets a key to the manifest's `value`) and deliver `settings.changed`; `POST …/jobs/{job}/run` runs a job. + +Every authenticated user of the node can list plug-ins and use their views, actions, canvases, panels and tools. + +## Permissions + +A plug-in asks for permissions in its manifest. Approving is the `enable` call: it must name exactly the pending +permissions (`409` `permissions_unapproved` otherwise), and an enable that grants one the plug-in does not hold yet must +come from a paired device's certificate mapped to the owner; a bearer token, a node or agent certificate or a loopback +caller gets `403` `device_certificate_required`. So an agent can install and reload a plug-in, and a person approves it +from the RivetHub app on a paired device. + +| Permission | What it opens on the API socket (`GET` means `GET` or `HEAD`) | +| --- | --- | +| `memory.read` | `GET /api/memory/*`, `GET /api/wiki*`, `POST /api/memory/tool/{memory_search,memory_browse,memory_stats,memory_get_full}`; the `summary.written` event | +| `memory.write` | `POST /api/capture`, `POST /api/memory/tool/memory_append`, written as agent `plugin:` | +| `sessions.read` | `GET /api/harness-sessions*`, `/api/harnesses/*`, `/api/catalog`; the `session.*` events | +| `sessions.control` | other methods on `/api/harness-sessions*`, `POST /api/sessions/{session}/messages` | +| `topics.read` | `GET /api/topics*`, `/api/sessions/history`, `/api/sessions/suggestions`, `/api/sessions/{session}/placement` | +| `topics.write` | other methods on `/api/topics*`, `/api/sessions/{session}/placement` and `/api/sessions/{session}/history` | +| `tasks.read` | `GET /api/tasks*`; the `task.done` event | +| `tasks.delegate` | `POST /api/tasks` | +| `agents.read` | `GET /api/agents*` | +| `notifications.send` | `POST /api/plugin/notify` | + +Any other route answers `403` `permission_required`. On Linux the process is confined with Landlock: it reads its +install directory, the program it runs (and the `lib` folder beside that program's `bin` folder), `/usr`, `/bin`, +`/sbin`, `/lib*`, `/etc`, `/proc`, `/sys` and the `/dev` null, zero and random devices; writes only its `data/` and +`run/` folders and `/dev/null`; connects only to the API socket; and opens no TCP connection. The host permissions widen +that: `host.files.read` and `host.files.write` read and write any file the node's user can, `host.network` allows TCP +except to rh's own ports, and `host.exec` records that it runs other programs, which inherit its confinement. A node +whose kernel lacks full Landlock refuses to enable a plug-in that asks for a `host.*` permission (`409` +`sandbox_unavailable`). + +## Web panels + +A view can hold a `webPanel` block `{id, entry, height?, params?}` for what blocks and canvases cannot draw. The client +loads `GET /panel/{entry}` in a web view at an origin of its own for each plug-in and node, serving `/http/…` from the +plug-in's `http/` route and every other path from `panel/` through the proxy with its own credentials, so the page holds +no token and reaches only its plug-in. Scripts run only from files on those routes, never inline; the page cannot +navigate away, open pop-ups or download. + +The page talks to the client with `parent.postMessage(message, '*')` and receives the client's messages as `message` +events, telling them apart by `type`: + +- the client sends `{type: 'init', theme, params?, context, plugin, node}` once the page has loaded and + `{type: 'theme', theme}` when the theme changes, `theme` being `{scheme, colors, fontFamily, fontMono, fontSize, + radius}`, and sets the same as CSS variables: `--rh-color-` with the colour role in kebab case + (`--rh-color-surface-container-high`), `--rh-font-family`, `--rh-font-mono`, `--rh-font-size`, `--rh-radius` and + `color-scheme`; +- the page sends `{type: 'ready'}`, `{type: 'resize', height}` and `{type: 'action', action}`, which runs any view + action as a button would. + +`PanelMessage` and `PanelHostMessage` in `@rivethub/contract` (under `Accepted` and `Sent`) type them. RivetHub desktop +drops a message over 256 KiB or one that does not parse, and keeps `resize` heights between 48 and 2400. A panel has +no permissions of its own: it can do what its plug-in's routes do. Neither SDK serves `panel/` yet. + +## Creator mode + +rh's plug-in creator (note 71) lets an agent build a plug-in on its own node with four tools that `rh mcp` lists under +the reserved id `plugins`: + +- `plugins-templates` `{}` lists the node's templates, or says that a person has to install them; +- `plugins-scaffold` `{template, id, name, description}` copies a template into a new `/workshop//`, sets + the manifest's `id`, `name` and `description`, and answers the folder; +- `plugins-install` `{id}` checks that folder's manifest, installs or reloads it, waits for it to start and asks each + page for its view, reporting every answer rh refuses; +- `plugins-status` `{id?, lines?}` answers its state, permissions, last exit and last log lines (40 by default, at most + 200), or without an id the node's plug-ins. + +The tools never enable a plug-in or grant a permission; their answers tell the agent when a person has to act. rh +carries no templates and fetches none: it reads `/plugin-templates/`, one real folder per template. `npm run +templates:install` copies `templates/javascript` there with an `sdk/` folder holding the SDK's sources (`index.ts`, +`plugin.ts`, `rivethub.ts`, `serve.ts`, `types.ts`), which Node 22.18 and later runs without a build. `` is the +first argument (`npm run templates:install -- `), else `RIVETHUB_STATE_DIR`, else `~/.rivethub`. Run it again +after pulling a newer SDK; it replaces the template, and plug-ins already scaffolded keep the SDK they were made with. + +## The plug-ins + +Build the TypeScript ones with `npm ci` and `npm run build -w plugins/`, then install the directory as above. + +### Voice + +`plugins/voice`: speech to text and text to speech for the composer, through OpenAI-compatible servers. It asks for +`host.network` and has three settings: `sttUrl`, a transcription endpoint that takes a multipart `file` and answers +`{text}`; `ttsUrl`, a speech endpoint that takes `{input, response_format, instructions?, voice?}`; and `instructions`, +sent with each speech request that brings none. Both URLs must be `http` or `https` with a host. + +- `POST /api/plugins/voice/http/transcribe`: the body is the audio, at most 15 MiB (its content type is passed on when + it is one the plug-in knows, else `audio/wav`); answers `{text}`. +- `POST /api/plugins/voice/http/speak`: the body is `{input, instructions?, voice?}`, at most 64 KiB, `input` at most + 4096 UTF-8 bytes; answers the audio, asked for as `wav`, streamed, at most 30 MiB. + +Errors are `{error}`: `400` for a bad body, `413` for audio over the limit, `501` when the URL is unset or invalid, +and `502` when the server fails or answers something else. Through rh's proxy a server has 60 s to start answering. +These are the bodies, limits and errors of rh's deprecated `/api/voice/transcribe` and `/api/voice/speak`. + +### Files + +`plugins/files`: the Files page's and the workflow editor's file calls, under one folder. It asks for +`host.files.read` and `host.files.write`; its one setting, `root`, is that absolute folder. Paths are relative to it, +and a path with `..`, a leading `/` or `~`, or a backslash, or a link that leads outside it, is `403`. + +| Route under `/api/plugins/files/http/` | Query | Answer | +| --- | --- | --- | +| `GET list` | `path` | `{path, root, entries: [{name, type, size, mtime}]}`, `type` `dir` or `file`, folders first | +| `GET download` | `path` | the file, at most 1 GiB: common image, text, JSON, CSV, PDF, audio and video types inline, the rest as an attachment | +| `POST upload` | `dir`, `name`, `overwrite=1` | the body is the file, at most 1 GiB; answers `{ok: true, path}` | +| `POST mkdir` | `dir`, `name` | `{ok: true, path}` | +| `POST rename` | `from`, `to` | `{ok: true, path}` | +| `DELETE delete` | `path`, `recursive=1` | `{ok: true, path}` | -On Linux rh confines a plug-in with Landlock to its own directory, its data and run folders and the program it runs, so -a TypeScript plug-in runs a bundle (`npm run build` writes `dist/plugin.js` with esbuild) rather than sources that -import from outside its directory, and a Rust plug-in runs its release binary. +An upload is written to a hidden part file that `list` never shows and moved into place whole; it refuses to replace a +file without `overwrite=1`, and through rh's proxy it must finish within 60 s, since the answer comes once the file is +written. Errors are `{error}`: `403`, `404`, `405` for the wrong method, `409` for a name that exists or a folder that +is not empty, `413`, `422` for a bad name or a missing argument, and `503` when `root` is unset ("files browser disabled +on this node") or missing. These are the queries, bodies and errors of rh's deprecated `/api/files/*`. -`rivethub-plugin-dev ` starts a plug-in the way rh does, standing in for its own `/api/plugin` routes, and reads -commands from stdin (`view main`, `action add {"values":{"title":"x"}}`, `tool add_item {"title":"x"}`, -`event session.placed {...}`, `job `), printing each answer. To run one on a node, `POST /api/plugins` with -`{"path": ""}` and enable it from a paired device. +### Workflows -## Templates on a node +`plugins/workflows`: define an ordered list of agent steps and run them, each step getting the previous step's result. +It is JavaScript that Node runs as it is (`node plugin.js`, no build), with its own copy of the SDK's sources in `sdk/`, +taken before the SDK gained `http` routes. It asks for `tasks.delegate` and `tasks.read`, has no settings, and adds a +Workflows page (views `main`, `editor`, `history` and `run`). -rh's plug-in creator (note 70 of the runtime's CONTRACT) lets an agent on a node scaffold a plug-in from a template, -edit it, install it and read its log through `rh mcp`. rh carries no templates; it reads them from the node's -`/plugin-templates/` (`~/.rivethub/plugin-templates/` unless the state folder moved), one folder each, and never -fetches one. `npm run templates:install` writes the templates that need no build there: the `javascript` folder with -`sdk/`, the SDK's own TypeScript sources, which Node 22.18 and later runs without a build. Pass another state folder as -`npm run templates:install -- `. Run it again after pulling a newer SDK; plug-ins already scaffolded keep the -SDK they were made with. +A workflow is a name and steps, each an agent name and a prompt. A run delegates each step in order with +`POST /api/tasks` (the prompt, plus the previous result marked as data; a 10-minute budget; `delegate_task` excluded), +waits on `GET /api/tasks/{id}/wait`, and stops at the first step that does not complete. Workflows, runs and each +step's status and result are kept in `workflows.db` (`node:sqlite`) in its data folder, a workflow runs once at a +time, and runs left unfinished resume when the plug-in starts. ## Rules @@ -92,6 +251,7 @@ SDK they were made with. ## Checks -`npm run check` runs what CI runs: Biome lint and format, `tsc` in strict mode, the tests, the contract freshness check, -the privacy scan, and `npm run rust` (rustfmt, Clippy with warnings as errors, and the tests, for the crate and the Rust -template). Run it before every push. +`npm run check` runs what CI runs: Biome lint and format, `tsc` in strict mode, the tests, the contract freshness check +(which fetches the pinned schemas), the privacy scan, and `npm run rust` (rustfmt and Clippy with warnings as errors +for the crate and the Rust template, and the crate's tests). Run it before every push. On a pull request CI also scans +its title and body for private data and checks every commit's author and message. diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md new file mode 100644 index 0000000..0439550 --- /dev/null +++ b/packages/plugin-sdk/README.md @@ -0,0 +1,110 @@ +# @rivethub/plugin-sdk + +Write RivetHub plug-ins in TypeScript or JavaScript. `serve` answers what rh asks on the plug-in socket, `connect` calls +rh on the plug-in API socket, and `rivethub-plugin-dev` runs a plug-in without rh. The package is private to this +repository (a workspace, not on npm) and ships its TypeScript sources: a bundler such as esbuild builds them into a +plug-in, and Node 22.18 or later runs them as they are, as the `javascript` template and `plugins/workflows` do. + +```ts +import { connect, Refusal, serve } from '@rivethub/plugin-sdk' + +const rh = connect() + +await serve({ + views: { main: () => ({ title: 'Checklist', blocks: [] }) }, + actions: { + add: ({ values }) => { + if (!values?.title) throw new Refusal('Give the item a title', { title: 'Required' }) + return [{ type: 'refresh' }] + }, + }, + tools: { add_item: ({ title }) => `Added ${String(title)}` }, + events: { 'session.placed': () => rh.viewsChanged(['main']) }, + http: { export: () => new Response('id,title\n', { headers: { 'content-type': 'text/csv' } }) }, + settings: (values) => console.log('settings', values), +}) +``` + +## Exports + +| Export | What it is | +| --- | --- | +| `serve(plugin, env?)` | Listens on `RIVETHUB_PLUGIN_SOCKET` and answers rh with the `Plugin`'s handlers. Resolves to the Node `Server` once it listens. | +| `Plugin` | The handler tables `serve` takes (below). Every key is optional. | +| `Refusal` | `new Refusal(message, fields?)`: thrown from an action, it answers `422 {message, fields}` and the form shows each field's message beside it. | +| `connect(env?)` | A `RivetHub` client for `RIVETHUB_API_SOCKET` with `RIVETHUB_PLUGIN_TOKEN`. | +| `RivetHub` | The client class; `new RivetHub(socket, token)` builds one by hand. | +| `RivetHubError` | What a client call rejects with when rh answers outside 2xx: `status`, and `code` and `detail` from rh's `GatewayError`; `message` is its `error`, then `: detail` when there is one. | +| `pluginEnv(env?)` | `PluginEnv` `{id, node, dataDir, socket, apiSocket, token}` from the `RIVETHUB_*` variables; throws naming the first one missing. | +| `router(plugin)` | The routing `serve` uses, as `(method, path, text) => Promise` (`Reply` is `{status, body?}`), for tests without a socket. It does not serve `http`. | +| `EventHandlers`, `EventKind`, `EventOf` | The `events` table's type, the subscribable kinds (every `PluginEvent` type but `settings.changed`) and one kind's event. | +| Contract types | `Accepted` and `Sent` (every `@rivethub/contract` type), and by name: `PluginManifest`, `View`, `ViewBlock`, `ViewInline`, `ViewButton`, `ViewField`, `ViewAction`, `ViewValue`, `CanvasScene`, `CanvasItem`, `CanvasShape`, `CanvasOp`, `CanvasResponse`, `PluginToolResult`, `PluginJobResult`, `PluginNotify` (what a plug-in answers or sends) and `ViewRequest`, `ViewActionRequest`, `CanvasEventRequest`, `CanvasEvent`, `PluginToolCall`, `PluginEventDelivery`, `PluginEvent`, `PluginJobRequest`, `PluginSelf`, `GatewayError`, `Settings` (what it receives). | + +## The `Plugin` handlers + +| Key | Handler | rh calls | Answer | +| --- | --- | --- | --- | +| `views` | `(request: ViewRequest) => View` | `POST /views/{view}` | the view | +| `actions` | `(request: ViewActionRequest) => ViewAction[]` | `POST /actions/{action}` | `{actions}`; a thrown `Refusal` is `422`, any other error `500` | +| `canvas` | `(request: CanvasEventRequest) => CanvasResponse` | `POST /canvas/{canvas}/events` | `{ops?, actions?}` | +| `tools` | `(args, call: PluginToolCall) => string \| PluginToolResult` | `POST /tools/{tool}` | a string becomes `{text}`; a thrown error becomes `{text: message, isError: true}` | +| `events` | `(event: EventOf, delivery: PluginEventDelivery) => void`, keyed by kind | `POST /events` | `204` | +| `jobs` | `(request: PluginJobRequest) => string \| undefined` | `POST /jobs/{job}` | `{outcome: 'succeeded', message?}`; a thrown error is `{outcome: 'failed', message}` | +| `http` | `(request: Request) => Response` | any method on `/http/{name}/…` | the `Response`, streamed | +| `settings` | `(values: Settings) => void` | at start and on `settings.changed` | | + +Every handler may be async. A view, canvas or event handler that throws answers `500` with the message; rh logs it, and +retries an event. A name the table lacks is the plug-in's own `404`, a request body that is not JSON is `400`, and +`GET /health` answers `200 ok`. + +Events: `serve` remembers the last `seq` it handled and answers a repeated delivery `204` without calling the handler. A +delivery whose handler throws is not counted, so rh's retry runs it again. `settings.changed` never reaches `events`: it +goes to `settings`, which `serve` also calls once before it listens, with `PluginSelf.settings` from +`GET /api/plugin/self`. Without a `settings` handler that call is skipped. + +`http`: a request whose path starts `/http/{name}` goes to `http[name]` as a web `Request` with rh's headers (among them +`x-rivethub-user`, `x-rivethub-node` and `x-rivethub-request-id`), the query, and the body unread, so a handler can +stream an upload. Clients reach it as `/api/plugins/{id}/http/{name}/…`, and rh waits 60 s for the first byte. A handler +that throws answers `500` with the message as text. rh passes the status, headers (less hop-by-hop headers and +`Set-Cookie`) and body through, adding `Content-Security-Policy: sandbox allow-scripts allow-forms allow-popups +allow-downloads` and `X-Content-Type-Options: nosniff`. The SDK serves no `/panel/` route, so a `webPanel` block cannot +be answered with it yet. + +## Calling rh + +`connect()` reads the environment rh starts the plug-in with; the token changes at every start and only works on the +API socket. + +| Method | Route | Needs | +| --- | --- | --- | +| `self(): Promise` | `GET /api/plugin/self`: id, node, version, granted permissions, settings (secrets included) and `dataDir` | nothing | +| `viewsChanged(views: string[])` | `POST /api/plugin/views/changed`: every client showing one of those views fetches it again | nothing | +| `notify(notice: PluginNotify)` | `POST /api/plugin/notify` `{title, text?, tone?, action?}`: a notification in every app | `notifications.send` | +| `request(method, path, body?)` | any route a granted permission opens, as the node's owner, with its usual body; resolves to the parsed JSON, or `undefined` for an empty answer | the route's permission | + +A route outside the granted permissions rejects with a `RivetHubError` of status `403` and code `permission_required`, +naming the missing permission in `detail` (none for a route no permission opens); a missing or stale token is `401`. + +## `rivethub-plugin-dev` + +`rivethub-plugin-dev [dir]` (default `.`) reads `dir/rivethub-plugin.json`, starts `run.command` in `dir` with the +environment rh gives it (`PATH`, `HOME`, `USER`, `LANG`, `LC_ALL`, `TZ`, `run.env`, the `RIVETHUB_*` variables and +`TMPDIR`), waits up to `run.readyTimeoutMs` (default 10000) for `GET /health`, then reads one command per line from +stdin and prints the plug-in's status and answer: + +``` +view [{"params":{},"context":{}}] +action [{"values":{},"params":{}}] +canvas {"event":{"type":"activated","item":""}} +tool [arguments] +event [fields] +job +``` + +`event` wraps the fields as a delivery with the next `seq` (so `event settings.changed {"values":{"on":true}}` reaches +the settings handler), and `job` sends a `manual` run. The harness stands in for rh's API socket: `GET /api/plugin/self` +answers node `dev`, every permission the manifest asks for, and each setting's manifest `value`; `POST +/api/plugin/views/changed` and `/notify` are printed as `rh ← …` and answered `204`; any other route answers `501` with +code `not_in_dev_harness`. It has no command for `http` routes, applies no Landlock confinement, and deletes its +temporary data folder when stdin closes or the plug-in exits. A workspace in this repository has it on `PATH` in npm +scripts (`npm run dev` in `templates/typescript`); elsewhere run `node /src/dev.ts `. diff --git a/rust/rivethub-plugin/README.md b/rust/rivethub-plugin/README.md new file mode 100644 index 0000000..4cd6ce8 --- /dev/null +++ b/rust/rivethub-plugin/README.md @@ -0,0 +1,96 @@ +# rivethub-plugin + +Write RivetHub plug-ins in Rust. `Plugin` answers what rh asks on the plug-in socket and `RivetHub` calls rh on the +plug-in API socket. The crate is not published (`publish = false`); the Rust template depends on it by path: +`rivethub-plugin = { path = "../../rust/rivethub-plugin" }`. It needs a Tokio runtime (the template uses +`#[tokio::main]` with `rt-multi-thread` and `macros`). + +```rust +use rivethub_plugin::contract::{View, ViewAction, ViewActionRefusal, ViewValue}; +use rivethub_plugin::{Env, Error, Plugin}; + +#[tokio::main] +async fn main() -> Result<(), Error> { + let env = Env::from_env()?; + Plugin::new(env.rivethub()) + .view("main", |_, _| async move { + Ok(View { title: "Checklist".into(), ..View::default() }) + }) + .action("add", |_, request| async move { + match request.values.get("title") { + Some(ViewValue::Text(title)) if !title.trim().is_empty() => Ok(vec![ViewAction::Refresh]), + _ => Err(ViewActionRefusal::new("Give the item a title").field("title", "Required").into()), + } + }) + .tool("add_item", |rh, call| async move { + let title: String = call.parse::()?["title"].as_str().unwrap_or_default().into(); + rh.views_changed(["main"]).await?; + Ok(format!("Added {title}")) + }) + .serve() + .await +} +``` + +## `Plugin` + +`Plugin::new(state)` keeps `state` in an `Arc` (`S: Send + Sync + 'static`) and hands it to every handler. Each +builder method registers an async handler `Fn(Arc, Input) -> impl Future>`: + +| Method | Input | Output | rh calls | +| --- | --- | --- | --- | +| `.view(name, handler)` | `ViewRequest` | `View` | `POST /views/{name}` | +| `.action(name, handler)` | `ViewActionRequest` | `Vec` | `POST /actions/{name}` | +| `.canvas(name, handler)` | `CanvasEventRequest` | `CanvasResponse` | `POST /canvas/{name}/events` | +| `.tool(name, handler)` | `PluginToolCall` | `String` | `POST /tools/{name}` | +| `.job(name, handler)` | `PluginJobRequest` | `Option` | `POST /jobs/{name}` | +| `.events(handler)` | `PluginEventDelivery` | `()` | `POST /events`, every kind | +| `.settings(handler)` | `BTreeMap` | `()` | at start and on `settings.changed` | + +`.serve().await` reads the environment with `Env::from_env`, calls the settings handler once with +`PluginSelf.settings` when there is one, binds `RIVETHUB_PLUGIN_SOCKET` and answers until the process ends. +`plugin.handle(&method, path, body).await` answers one request without a socket and returns a `Reply` `{status, json, +body}`, for tests. + +What an `Err` becomes: from an action, `Error::Refused(refusal)` answers `422 {message, fields}` and anything else +`500`; from a tool, `{text: , isError: true}`; from a job, `{outcome: "failed", message}`; from a view, +canvas, event or settings handler, `500` with the message. `GET /health` answers `200 ok`, an unregistered name `404`, +and a body that does not parse as its input `400`. + +Events: one handler takes every kind, so match on `delivery.event` (`PluginEvent::SessionPlaced { .. }` and the rest). A +repeated `seq` is answered `204` without calling it, and a delivery whose handler fails is not counted, so rh's retry +runs it again. `settings.changed` goes to the settings handler when there is one, else to the events handler. + +The crate serves no `http/` or `panel/` routes; the TypeScript SDK serves `http/`. + +## Calling rh + +`Env::from_env()` reads `RIVETHUB_PLUGIN_ID`, `RIVETHUB_PLUGIN_NODE`, `RIVETHUB_PLUGIN_DATA`, `RIVETHUB_PLUGIN_SOCKET`, +`RIVETHUB_API_SOCKET` and `RIVETHUB_PLUGIN_TOKEN` into `Env` `{id, node, data_dir, socket, api_socket, token}`, or +fails with `Error::Missing(name)`. `env.rivethub()` (or `RivetHub::new(socket, token)`) gives the client: + +| Method | Route | +| --- | --- | +| `own() -> PluginSelf` | `GET /api/plugin/self`: id, node, version, granted permissions, settings (secrets included), data folder | +| `views_changed(views)` | `POST /api/plugin/views/changed`: every client showing one of those views fetches it again | +| `notify(&PluginNotify)` | `POST /api/plugin/notify` (`notifications.send`) | +| `get::(path)`, `post::(path, &body)`, `request::(method, path, Option<&B>)` | any route a granted permission opens, as the node's owner | + +An answer outside 2xx is `Error::RivetHub { status, error }` with rh's `GatewayError` (`error`, `detail`, `code`, …); a +route outside the granted permissions is `403` with code `permission_required`. An empty answer is read as JSON `null`, +so ask for `()`, an `Option` or `serde_json::Value` from a route that answers nothing. + +## Errors and helpers + +`Error` is `Refused(ViewActionRefusal)`, `Failed(String)` (`Error::failed(message)`), `Missing(&'static str)`, +`RivetHub { status, error }`, `Io`, `Json` and `Http`, with `From` for `ViewActionRefusal`, `std::io::Error`, +`serde_json::Error` and `hyper::Error`, so `?` works on each. `ViewActionRefusal::new(message).field(key, message)` +builds a refusal, and `call.parse::()` reads a tool call's arguments as any `Deserialize` type. The crate also +re-exports `Method` and `StatusCode` from hyper. + +`rivethub_plugin::contract` holds the plug-in types generated from the runtime's accepted schema by `npm run contract` +(the manifest, views, canvas, events, jobs, tools, the plug-in API bodies and `GatewayError`). Never write them by +hand. + +Run a built plug-in without rh with the TypeScript SDK's harness: `cargo build --release`, then +`rivethub-plugin-dev ` (see `packages/plugin-sdk`). diff --git a/templates/javascript/GUIDE.md b/templates/javascript/GUIDE.md index b881403..af7ea98 100644 --- a/templates/javascript/GUIDE.md +++ b/templates/javascript/GUIDE.md @@ -18,32 +18,35 @@ canvas board, an `add_item` agent tool and a `session.placed` subscription). Rew You can install and reload. You cannot turn a plug-in on or grant it permissions: a person does that in the RivetHub app (Settings › Plug-ins › the plug-in › Turn on, or Approve and turn on when it asks for permissions), from a device paired with this node. A new plug-in stays off until they do. Once it is on, every reload restarts it with your changes, -unless the manifest asks for a permission it does not hold yet: then it waits, off, for the person to approve again. -When an answer says a person has to act, tell them exactly that. +unless the manifest asks for a permission it does not hold yet: then it stops until the person approves the new ones. +Dropping a permission from the manifest takes effect at the next reload. When an answer says a person has to act, tell +them exactly that. ## Files - `sdk/` is `@rivethub/plugin-sdk`, as TypeScript sources that Node runs directly. Import from `./sdk/index.ts`, read `sdk/plugin.ts` and `sdk/rivethub.ts` for its API, and do not edit it. -- `plugin.js` calls `serve({ views, actions, canvas, tools, events, jobs, settings })`; every key is optional. +- `plugin.js` calls `serve({ views, actions, canvas, tools, events, jobs, http, settings })`; every key is optional. - Keep state in `pluginEnv().dataDir` (a folder rh keeps across reloads), as `checklist.js` does with one JSON file. - The process runs as `node plugin.js` (Node 22.18 or later) with this folder as its working directory. Use Node's - built-in modules. Anything else must live inside this folder: on Linux rh confines the process to it, its data folder - and the program it runs. + built-in modules. Anything else must live inside this folder: on Linux rh lets the process read only this folder, the + program it runs and the system folders (`/usr`, `/etc`, `/proc` and the like), and write only its data folder and + `TMPDIR`. It cannot write to this folder. ## The manifest -`manifest` 1; `id` (2 to 24 of `a-z`, `0-9` and single hyphens; it must stay the folder's name); `name`; `version`; -`description`; `icon` (a Material Symbols name, as every icon here); `run.command` (`["node", "plugin.js"]`); -`permissions`; `settings` (fields as in a form, drawn in Settings, read with `rh.self()` and the `settings` handler); -`tools` (`{name, title?, description, inputSchema, hints?}`, offered to agents as `-`; `name` uses `a-z`, -`0-9` and single underscores); `contributes.pages` (`{id, title, icon?, view}`: a sidebar entry opening that view), -`contributes.topicCards` (`{id, title, view}`: a card in a topic, its view gets `context.topicId`) and -`contributes.sessionActions` (`{id, title, icon?, action}`: a session menu entry, `context.sessionId`); `jobs` (`{id, -title, schedule?, timeoutMs?}`, `schedule` a five-field cron in the node's time); `events` (`session.started`, -`session.idle`, `session.ended`, `session.placed` need `sessions.read`; `summary.written` needs `memory.read`; -`task.done` needs `tasks.read`). Unknown fields are refused. Remove what you do not use, the example's `sessions.read` -and `session.placed` among them, so the person is not asked to approve it. +`manifest` 1; `id` (2 to 24 of `a-z`, `0-9` and single hyphens, starting with a letter, never `plugins`; it must stay +the folder's name); `name`; `version`; `description`; `icon` (a Material Symbols name, as every icon here); +`run.command` (`["node", "plugin.js"]`), `run.env` (no `RIVETHUB_` names) and `run.readyTimeoutMs` (default 10000); +`permissions`; `settings` (fields as in a form, any input but `file`, drawn in Settings, read with `rh.self()` and the +`settings` handler); `tools` (`{name, title?, description, inputSchema, hints?}`, offered to agents as `-`; +`name` uses `a-z`, `0-9` and single underscores); `contributes.pages` (`{id, title, icon?, view}`: a sidebar entry +opening that view), `contributes.topicCards` (`{id, title, view}`: a card in a topic, its view gets `context.topicId`) +and `contributes.sessionActions` (`{id, title, icon?, action}`: a session menu entry, `context.sessionId`); `jobs` +(`{id, title, schedule?, timeoutMs?}`, `schedule` a five-field cron in the node's time, `timeoutMs` default 600000); +`events` (`session.started`, `session.idle`, `session.ended`, `session.placed` need `sessions.read`; `summary.written` +needs `memory.read`; `task.done` needs `tasks.read`). Unknown fields are refused. Remove what you do not use, the +example's `sessions.read` and `session.placed` among them, so the person is not asked to approve it. ## Views @@ -56,8 +59,10 @@ ratio?}`; `tabs` `{tabs: [{id, title, badge?, blocks}], selected?}`; `text` `{te (0 to 1), label?}`; `notice` `{tone, title?, text, actions?}`; `list` `{items: [{id, title, subtitle?, icon?, trailing?: [inline], action?, menu?: [button]}], empty?}`; `table` `{columns: [{title, align?, sortable?}], rows: [{id, cells: [inline], action?, menu?}], empty?}`; `breadcrumbs` `{items: [{label, action?}]}`; `actions` `{buttons}`; `form` `{id, -fields, buttons}`; `canvas` (below). `empty` is `{title, text?, button?}`. Do not use `image`, `webPanel` or the -`download` action: they need routes this SDK does not serve. +fields, buttons}`; `canvas` (below); `image` `{path, alt}`. `empty` is `{title, text?, button?}`. `image` and the +`download` action take a path under this plug-in's `http/` route (below): `chart/today.png` is `GET +/http/chart/today.png`, answered by the `chart` handler. Do not use `webPanel`: it needs a `panel/` route this SDK does +not serve. Inlines (`type`): `text` `{text, tone?, icon?, monospace?}`, `badge` `{text, tone}`, `time` `{at: epoch ms, style?: relative|absolute}`, `duration` `{ms}`, `bytes` `{value}`. Tones: `neutral`, `info`, `success`, `warning`, `danger`. @@ -71,7 +76,8 @@ Actions (`type`): `call` `{action, params?}` runs your action handler with `{par the form's when the button is in a form) and shows the actions it returns; throw `new Refusal(message, {field: message})` to show errors beside fields. `navigate` `{view, params?, replace?}`, `dialog` `{view, params?}`, `back`, `refresh`, `toast` `{text, tone?}`, `copy` `{text}`, `openSession` `{sessionId}`, `openTopic` `{topicId}`, `openUrl` -`{url}`. An action handler cannot answer with another `call`. +`{url}` (`http` or `https`), `download` `{path, filename?}`. An action handler cannot answer with another `call`. rh +waits 30 s for a view, action or canvas answer. Apps never poll. A page shows what its view answered when it was opened; when your state changes on its own (a timer, an event, an agent's tool call), call `await rh.viewsChanged(['main'])` (with `const rh = connect()`) and every app @@ -92,19 +98,32 @@ fill?, stroke?}` and `icon` `{x, y, name, size?, color?}`. Colours are theme rol context}`, `event.type` one of `selected`, `moved` `{items: [{id, x, y}]}`, `connected`, `deleted` `{items}`, `activated` `{item}` and `menu`. Answer `{ops?: [{type: 'upsert', item} | {type: 'remove', ids}], actions?}`. -## Tools, events, jobs and settings +## Tools, events, jobs, http and settings -`tools.(arguments, call)` returns text (or `{text, isError}`); a thrown error becomes an error result. `events` -handlers get `(event, delivery)`, at least once and in order. `jobs.(request)` returns an optional message; a thrown -error fails the run. `settings(values)` gets the starting values and every change. +`tools.(arguments, call)` returns text (or `{text, isError}`) within 120 s; a thrown error becomes an error +result. `events` handlers get `(event, delivery)`, at least once and in order; the SDK drops a repeated `delivery.seq`, +and `delivery.missed` counts events lost before this one, so reconcile through the API when it is above 0. A handler +that throws is retried. `jobs.(request)` returns an optional message; a thrown error fails the run. A `schedule` +runs a job at each tick, and the node's owner can run one at any time (`request.trigger` is `schedule` or `manual`). +`http.(request)` gets every request to `/http//…` as a web `Request` (any method, the query, the body +unread) and returns a `Response`, which rh streams to the app; apps reach it as `/api/plugins//http//…` +and rh waits 60 s for its first byte. `settings(values)` gets the starting values and every change. ## Permissions Ask only for what the plug-in uses; each is shown to the person when they approve. `rh.request(method, path, body)` -reaches the routes a permission opens, as the node's owner: `memory.read` (`GET /api/memory/*`, `GET /api/wiki*`), -`memory.write` (`POST /api/capture`), `sessions.read` (`GET /api/harness-sessions*`), `sessions.control`, -`topics.read` (`GET /api/topics*`), `topics.write`, `tasks.read` (`GET /api/tasks*`), `tasks.delegate` (`POST -/api/tasks`), `agents.read` (`GET /api/agents*`) and `notifications.send` (`rh.notify({title, text?, tone?, -action?})`, a notification in every app). Without a host permission the process opens no network connection, reads -and writes only its folders and runs no other program; `host.network`, `host.files.read`, `host.files.write` and -`host.exec` widen that and need the person's approval like the rest. Any other route answers 403. +reaches the routes a permission opens, as the node's owner, with their usual bodies (`GET` here means `GET` or `HEAD`, +anything else a write): `memory.read` (`GET /api/memory/*` and `/api/wiki*`; `POST +/api/memory/tool/memory_search`, `memory_browse`, `memory_stats` and `memory_get_full`), `memory.write` (`POST +/api/capture`, `POST /api/memory/tool/memory_append`; what it writes is filed as agent `plugin:`), +`sessions.read` (`GET /api/harness-sessions*`, `/api/harnesses/*` and `/api/catalog`), `sessions.control` (writes to +`/api/harness-sessions*` and `POST /api/sessions//messages`), `topics.read` (`GET /api/topics*`, +`/api/sessions/history`, `/api/sessions/suggestions` and `/api/sessions//placement`), `topics.write` (writes +to `/api/topics*`, `/api/sessions//placement` and `/api/sessions//history`), `tasks.read` (`GET +/api/tasks*`), `tasks.delegate` (`POST /api/tasks`), `agents.read` (`GET /api/agents*`) and `notifications.send` +(`rh.notify({title, text?, tone?, action?})`, a notification in every app). Any other route answers 403 with code +`permission_required`. Without a host permission the process opens no TCP connection and reads and writes only what +the Files list above names. `host.network` allows TCP (but not rh's own ports), `host.files.read` reads and +`host.files.write` writes any file the node's user can, and `host.exec` tells the person it runs other programs (they +run under the same confinement). Each needs the person's approval like the rest, and a node whose kernel cannot fully +confine the process refuses to turn on a plug-in that asks for one.