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
518 changes: 518 additions & 0 deletions plugins/workflows/plugin.js

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions plugins/workflows/rivethub-plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"manifest": 1,
"id": "workflows",
"name": "Workflows",
"version": "0.1.0",
"description": "Define an ordered list of agent steps and run them, passing each step's result to the next.",
"icon": "account_tree",
"run": {
"command": ["node", "plugin.js"]
},
"permissions": ["tasks.delegate", "tasks.read"],
"contributes": {
"pages": [
{
"id": "workflows",
"title": "Workflows",
"icon": "account_tree",
"view": "main"
}
]
}
}
4 changes: 4 additions & 0 deletions plugins/workflows/sdk/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { type EventHandlers, type EventKind, type EventOf, type Plugin, Refusal, type Reply, router } from './plugin.ts'
export { connect, type PluginEnv, pluginEnv, RivetHub, RivetHubError } from './rivethub.ts'
export { serve } from './serve.ts'
export type * from './types.ts'
142 changes: 142 additions & 0 deletions plugins/workflows/sdk/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import type {
CanvasEventRequest,
CanvasResponse,
PluginEvent,
PluginEventDelivery,
PluginJobRequest,
PluginJobResult,
PluginToolCall,
PluginToolResult,
Settings,
View,
ViewAction,
ViewActionRequest,
ViewRequest,
} from './types.ts'

type Awaitable<T> = T | Promise<T>

export type EventKind = Exclude<PluginEvent['type'], 'settings.changed'>
export type EventOf<K extends PluginEvent['type']> = Extract<PluginEvent, { type: K }>
export type EventHandlers = {
[K in EventKind]?: (event: EventOf<K>, delivery: PluginEventDelivery) => Awaitable<void>
}

export interface Plugin {
views?: Record<string, (request: ViewRequest) => Awaitable<View>>
actions?: Record<string, (request: ViewActionRequest) => Awaitable<ViewAction[]>>
canvas?: Record<string, (request: CanvasEventRequest) => Awaitable<CanvasResponse>>
tools?: Record<
string,
(args: PluginToolCall['arguments'], call: PluginToolCall) => Awaitable<string | PluginToolResult>
>
events?: EventHandlers
jobs?: Record<string, (request: PluginJobRequest) => Awaitable<string | undefined>>
settings?: (values: Settings) => Awaitable<void>
}

export class Refusal extends Error {
readonly fields: Record<string, string>

constructor(message: string, fields: Record<string, string> = {}) {
super(message)
this.fields = fields
}
}

export type Reply = { status: number; body?: unknown }

const named = <T>(table: Record<string, T> | undefined, name: string | undefined): T | undefined =>
table !== undefined && name !== undefined && Object.hasOwn(table, name) ? table[name] : undefined

const failure = (error: unknown): string => (error instanceof Error ? error.message : String(error))

const missing: Reply = { status: 404, body: 'not found' }

export function router(plugin: Plugin): (method: string, path: string, text: string) => Promise<Reply> {
let seen = 0

async function event(delivery: PluginEventDelivery): Promise<Reply> {
if (delivery.seq <= seen) return { status: 204 }
const { event } = delivery
if (event.type === 'settings.changed') {
await plugin.settings?.(event.values)
} else {
const handler = plugin.events?.[event.type] as
| ((event: PluginEvent, delivery: PluginEventDelivery) => Awaitable<void>)
| undefined
await handler?.(event, delivery)
}
seen = delivery.seq
return { status: 204 }
}

async function action(name: string | undefined, request: ViewActionRequest): Promise<Reply> {
const handler = named(plugin.actions, name)
if (handler === undefined) return missing
try {
return { status: 200, body: { actions: await handler(request) } }
} catch (error) {
if (error instanceof Refusal) return { status: 422, body: { message: error.message, fields: error.fields } }
throw error
}
}

async function tool(name: string | undefined, call: PluginToolCall): Promise<Reply> {
const handler = named(plugin.tools, name)
if (handler === undefined) return missing
try {
const result = await handler(call.arguments, call)
return { status: 200, body: typeof result === 'string' ? { text: result } : result }
} catch (error) {
return { status: 200, body: { text: failure(error), isError: true } satisfies PluginToolResult }
}
}

async function job(name: string | undefined, request: PluginJobRequest): Promise<Reply> {
const handler = named(plugin.jobs, name)
if (handler === undefined) return missing
let result: PluginJobResult
try {
const message = await handler(request)
result = message === undefined ? { outcome: 'succeeded' } : { outcome: 'succeeded', message }
} catch (error) {
result = { outcome: 'failed', message: failure(error) }
}
return { status: 200, body: result }
}

async function answer(segments: string[], body: unknown): Promise<Reply> {
const [kind, name, tail] = segments
if (kind === 'views' && segments.length === 2) {
const handler = named(plugin.views, name)
return handler === undefined ? missing : { status: 200, body: await handler(body as ViewRequest) }
}
if (kind === 'canvas' && tail === 'events' && segments.length === 3) {
const handler = named(plugin.canvas, name)
return handler === undefined ? missing : { status: 200, body: await handler(body as CanvasEventRequest) }
}
if (kind === 'actions' && segments.length === 2) return action(name, body as ViewActionRequest)
if (kind === 'tools' && segments.length === 2) return tool(name, body as PluginToolCall)
if (kind === 'jobs' && segments.length === 2) return job(name, body as PluginJobRequest)
if (kind === 'events' && segments.length === 1) return event(body as PluginEventDelivery)
return missing
}

return async (method, path, text) => {
const segments = new URL(path, 'http://plugin').pathname.split('/').filter(Boolean)
if (method === 'GET' && segments.length === 1 && segments[0] === 'health') return { status: 200, body: 'ok' }
if (method !== 'POST') return missing
let body: unknown
try {
body = JSON.parse(text)
} catch (error) {
return { status: 400, body: failure(error) }
}
try {
return await answer(segments, body)
} catch (error) {
return { status: 500, body: failure(error) }
}
}
}
98 changes: 98 additions & 0 deletions plugins/workflows/sdk/rivethub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { request as send } from 'node:http'
import type { Accepted, GatewayError, PluginNotify, PluginSelf } from './types.ts'

export type PluginEnv = {
id: string
node: string
dataDir: string
socket: string
apiSocket: string
token: string
}

export function pluginEnv(env: NodeJS.ProcessEnv = process.env): PluginEnv {
const read = (name: string): string => {
const value = env[name]
if (value === undefined || value === '') {
throw new Error(`${name} is not set: run the plug-in from rh or rivethub-plugin-dev`)
}
return value
}
return {
id: read('RIVETHUB_PLUGIN_ID'),
node: read('RIVETHUB_PLUGIN_NODE'),
dataDir: read('RIVETHUB_PLUGIN_DATA'),
socket: read('RIVETHUB_PLUGIN_SOCKET'),
apiSocket: read('RIVETHUB_API_SOCKET'),
token: read('RIVETHUB_PLUGIN_TOKEN'),
}
}

export class RivetHubError extends Error {
readonly status: number
readonly code: string | undefined
readonly detail: string | undefined

constructor(status: number, body: GatewayError) {
super(body.detail ? `${body.error}: ${body.detail}` : body.error)
this.status = status
this.code = body.code ?? undefined
this.detail = body.detail ?? undefined
}
}

function gatewayError(status: number, text: string): GatewayError {
try {
const body = JSON.parse(text) as Partial<GatewayError>
if (typeof body.error === 'string') return body as GatewayError
} catch {}
return { error: text || `rh answered ${status}` }
}

export class RivetHub {
readonly #socket: string
readonly #token: string

constructor(socket: string, token: string) {
this.#socket = socket
this.#token = token
}

self(): Promise<PluginSelf> {
return this.request('GET', '/api/plugin/self')
}

async viewsChanged(views: string[]): Promise<void> {
await this.request('POST', '/api/plugin/views/changed', { views } satisfies Accepted.PluginViewsChanged)
}

async notify(notice: PluginNotify): Promise<void> {
await this.request('POST', '/api/plugin/notify', notice)
}

request<T>(method: string, path: string, body?: unknown): Promise<T> {
const payload = body === undefined ? undefined : JSON.stringify(body)
const headers: Record<string, string> = { authorization: `Bearer ${this.#token}` }
if (payload !== undefined) headers['content-type'] = 'application/json'
return new Promise((resolve, reject) => {
const outgoing = send({ socketPath: this.#socket, path, method, headers }, (response) => {
const chunks: Buffer[] = []
response.on('data', (chunk: Buffer) => chunks.push(chunk))
response.on('error', reject)
response.on('end', () => {
const status = response.statusCode ?? 0
const text = Buffer.concat(chunks).toString('utf8')
if (status < 200 || status > 299) reject(new RivetHubError(status, gatewayError(status, text)))
else resolve((text === '' ? undefined : JSON.parse(text)) as T)
})
})
outgoing.on('error', reject)
outgoing.end(payload)
})
}
}

export function connect(env: NodeJS.ProcessEnv = process.env): RivetHub {
const { apiSocket, token } = pluginEnv(env)
return new RivetHub(apiSocket, token)
}
29 changes: 29 additions & 0 deletions plugins/workflows/sdk/serve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createServer, type Server, type ServerResponse } from 'node:http'
import { type Plugin, type Reply, router } from './plugin.ts'
import { connect, pluginEnv } from './rivethub.ts'

function write(response: ServerResponse, reply: Reply): void {
if (reply.body === undefined) {
response.writeHead(reply.status).end()
} else if (typeof reply.body === 'string') {
response.writeHead(reply.status, { 'content-type': 'text/plain; charset=utf-8' }).end(reply.body)
} else {
response.writeHead(reply.status, { 'content-type': 'application/json' }).end(JSON.stringify(reply.body))
}
}

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 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')))
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(socket, resolve)
})
return server
}
32 changes: 32 additions & 0 deletions plugins/workflows/sdk/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Accepted, Sent } from '@rivethub/contract'

export type { Accepted, Sent }

export type PluginManifest = Accepted.PluginManifest
export type View = Accepted.View
export type ViewBlock = Accepted.ViewBlock
export type ViewInline = Accepted.ViewInline
export type ViewButton = Accepted.ViewButton
export type ViewField = Accepted.ViewField
export type ViewAction = Accepted.ViewAction
export type ViewValue = Accepted.ViewValue
export type CanvasScene = Accepted.CanvasScene
export type CanvasItem = Accepted.CanvasItem
export type CanvasShape = Accepted.CanvasShape
export type CanvasOp = Accepted.CanvasOp
export type CanvasResponse = Accepted.CanvasResponse
export type PluginToolResult = Accepted.PluginToolResult
export type PluginJobResult = Accepted.PluginJobResult
export type PluginNotify = Accepted.PluginNotify

export type ViewRequest = Sent.ViewRequest
export type ViewActionRequest = Sent.ViewActionRequest
export type CanvasEventRequest = Sent.CanvasEventRequest
export type CanvasEvent = Sent.CanvasEvent
export type PluginToolCall = Sent.PluginToolCall
export type PluginEventDelivery = Sent.PluginEventDelivery
export type PluginEvent = Sent.PluginEvent
export type PluginJobRequest = Sent.PluginJobRequest
export type PluginSelf = Sent.PluginSelf
export type GatewayError = Sent.GatewayError
export type Settings = PluginSelf['settings']
Loading
Loading