Skip to content
This repository was archived by the owner on Nov 19, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ gets promoted into the platform, with its domain moving into a runtime context a
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.

## The contract

Expand Down Expand Up @@ -56,6 +61,9 @@ 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.

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.
Expand Down
29 changes: 28 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
},
"workspaces": [
"packages/*",
"templates/typescript"
"templates/typescript",
"plugins/*"
],
"scripts": {
"check": "npm run lint && npm run typecheck && npm test && npm run contract:check && npm run privacy && npm run rust",
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-sdk/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface Plugin {
>
events?: EventHandlers
jobs?: Record<string, (request: PluginJobRequest) => Awaitable<string | undefined>>
http?: Record<string, (request: Request) => Awaitable<Response>>
settings?: (values: Settings) => Awaitable<void>
}

Expand Down
46 changes: 45 additions & 1 deletion packages/plugin-sdk/src/serve.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { createServer, type Server, type ServerResponse } from 'node:http'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
import { type Plugin, type Reply, router } from './plugin.ts'
import { connect, pluginEnv } from './rivethub.ts'

type HttpHandler = NonNullable<Plugin['http']>[string]

function write(response: ServerResponse, reply: Reply): void {
if (reply.body === undefined) {
response.writeHead(reply.status).end()
Expand All @@ -12,11 +17,50 @@ function write(response: ServerResponse, reply: Reply): void {
}
}

function httpHandler(plugin: Plugin, url: string): HttpHandler | undefined {
const [kind, name] = new URL(url, 'http://plugin').pathname.split('/').filter(Boolean)
if (kind !== 'http' || name === undefined || plugin.http === undefined) return undefined
return Object.hasOwn(plugin.http, name) ? plugin.http[name] : undefined
}

function webRequest(incoming: IncomingMessage): Request {
const headers = new Headers()
const raw = incoming.rawHeaders
for (let index = 0; index + 1 < raw.length; index += 2) headers.append(raw[index] ?? '', raw[index + 1] ?? '')
const method = incoming.method ?? 'GET'
const body = method === 'GET' || method === 'HEAD' ? null : (Readable.toWeb(incoming) as ReadableStream<Uint8Array>)
return new Request(new URL(incoming.url ?? '/', 'http://plugin'), { method, headers, body, duplex: 'half' })
}

async function relay(handler: HttpHandler, incoming: IncomingMessage, response: ServerResponse): Promise<void> {
let answer: Response
try {
answer = await handler(webRequest(incoming))
} catch (error) {
answer = new Response(error instanceof Error ? error.message : String(error), {
status: 500,
headers: { 'content-type': 'text/plain; charset=utf-8' },
})
}
const headers = Object.fromEntries(answer.headers)
if (!incoming.complete) headers.connection = 'close'
response.writeHead(answer.status, headers)
if (answer.body === null) {
response.end()
return
}
await pipeline(Readable.fromWeb(answer.body as NodeReadableStream<Uint8Array>), response).catch((error: unknown) =>
response.destroy(error instanceof Error ? error : undefined),
)
}

export async function serve(plugin: Plugin, env: NodeJS.ProcessEnv = process.env): Promise<Server> {
const { socket } = pluginEnv(env)
if (plugin.settings !== undefined) await plugin.settings((await connect(env).self()).settings)
const route = router(plugin)
const server = createServer(async (request, response) => {
const handler = httpHandler(plugin, request.url ?? '/')
if (handler !== undefined) return relay(handler, request, response)
const chunks: Buffer[] = []
for await (const chunk of request) chunks.push(chunk as Buffer)
write(response, await route(request.method ?? 'GET', request.url ?? '/', Buffer.concat(chunks).toString('utf8')))
Expand Down
15 changes: 15 additions & 0 deletions plugins/files/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "files",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"build": "esbuild src/plugin.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/plugin.js"
},
"dependencies": {
"@rivethub/plugin-sdk": "0.7.0"
},
"devDependencies": {
"esbuild": "0.28.2"
}
}
19 changes: 19 additions & 0 deletions plugins/files/rivethub-plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"manifest": 1,
"id": "files",
"name": "Files",
"version": "0.1.0",
"description": "Browse, upload, rename and delete files under one folder of this node, for the Files page and the workflow editor.",
"icon": "folder",
"run": { "command": ["node", "dist/plugin.js"] },
"permissions": ["host.files.read", "host.files.write"],
"settings": [
{
"key": "root",
"label": "Files root",
"input": { "type": "text" },
"help": "The absolute folder the Files page and the workflow editor work in. Nothing outside it is reachable, through links either.",
"placeholder": "/srv/shared"
}
]
}
95 changes: 95 additions & 0 deletions plugins/files/src/fence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import type { Stats } from 'node:fs'
import { lstat, realpath, stat } from 'node:fs/promises'
import { isAbsolute, join, relative, sep } from 'node:path'

export class FilesError extends Error {
readonly status: number

constructor(status: number, message: string) {
super(message)
this.status = status
}
}

export const escaped = (): FilesError => new FilesError(403, 'path escapes the files root')

export const failed = (what: string, error: unknown): FilesError =>
new FilesError(500, `${what} failed: ${error instanceof Error ? error.message : String(error)}`)

export const code = (error: unknown): string | undefined =>
error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined

export type Follow = 'target' | 'entry'
export type Final = 'mustExist' | 'mayBeNew'
export type Located = { absolute: string; relative: string }
export type Failures = { missing: FilesError; what: string }

export function inside(root: string, path: string): boolean {
const rest = relative(root, path)
return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest))
}

export async function openRoot(configured: string): Promise<string> {
const unavailable = new FilesError(503, `files root not available: ${configured}`)
if (!isAbsolute(configured)) throw unavailable
try {
const root = await realpath(configured)
if ((await stat(root)).isDirectory()) return root
} catch (error) {
console.error(`[files] files root ${configured} is not available: ${String(error)}`)
}
throw unavailable
}

function segments(raw: string): string[] {
if (raw.includes('\0') || raw.includes('\\') || raw.startsWith('/') || raw.startsWith('~')) throw escaped()
const parts = raw.split('/').filter((part) => part !== '' && part !== '.')
if (parts.includes('..')) throw escaped()
return parts
}

async function linked(path: string, root: string, on: Failures): Promise<string> {
try {
const target = await realpath(path)
if (inside(root, target)) return target
} catch (error) {
if (code(error) === 'ENOENT') throw on.missing
throw failed(on.what, error)
}
throw escaped()
}

export async function locate(root: string, raw: string, follow: Follow, final: Final, on: Failures): Promise<Located> {
const parts = segments(raw)
let current = root
for (const [index, part] of parts.entries()) {
const last = index + 1 === parts.length
const next = join(current, part)
let found: Stats
try {
found = await lstat(next)
} catch (error) {
if (code(error) === 'ENOENT' && last && final === 'mayBeNew') {
current = next
continue
}
if (code(error) === 'ENOENT' || code(error) === 'ENOTDIR') throw on.missing
throw failed(on.what, error)
}
current = found.isSymbolicLink() && !(last && follow === 'entry') ? await linked(next, root, on) : next
}
if (!inside(root, current)) throw escaped()
return { absolute: current, relative: parts.join('/') }
}

export async function shown(path: string, root: string): Promise<Stats> {
const own = await lstat(path)
if (!own.isSymbolicLink()) return own
try {
const target = await realpath(path)
return inside(root, target) ? await stat(target) : own
} catch (error) {
if (code(error) === 'ENOENT') return own
throw error
}
}
Loading
Loading