mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
* cli: add orca plugin install, update, uninstall and catalog list/add/rm * plugins: escape the invisible-character regex so the orcad bundle stays ASCII * plugins: split approval re-run helpers and plugin RPC binding to stay under max-lines
285 lines
10 KiB
TypeScript
285 lines
10 KiB
TypeScript
import { existsSync } from 'node:fs'
|
|
import { isAbsolute, resolve } from 'node:path'
|
|
import type { CommandHandler, HandlerContext } from '../dispatch'
|
|
import { printPluginResult, requirePluginPathArg } from '../plugin-authoring/plugin-cli-output'
|
|
import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types'
|
|
import {
|
|
approvalFingerprintOf,
|
|
approvalRerunCommand,
|
|
nextStepsOf,
|
|
pendingApprovalsOf,
|
|
perPluginApprovalCommands
|
|
} from './plugin-approval-rerun'
|
|
import { isQualifiedPluginKey } from '../../shared/plugins/manifest/plugin-manifest'
|
|
import type { PluginHostListEntry } from '../../shared/plugins/plugin-list-entry'
|
|
|
|
export type DevLoadResult = {
|
|
path: string
|
|
pluginKey: string
|
|
added: boolean
|
|
approval: 'content-only' | 'approve-flag' | 'already-approved'
|
|
plugin: PluginHostListEntry | null
|
|
}
|
|
export type LogsResult = {
|
|
pluginKey: string
|
|
lines: { ts: number; level: string; line: string }[]
|
|
/** Absent on hosts older than the `after` cursor. */
|
|
cursor?: string
|
|
}
|
|
|
|
const APPROVAL_CODES = new Set(['approval_required', 'approval_stale'])
|
|
|
|
export function stringFlag(ctx: HandlerContext, name: string): string | undefined {
|
|
const value = ctx.flags.get(name)
|
|
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
|
}
|
|
|
|
export function translatePluginRpcError(
|
|
ctx: HandlerContext,
|
|
method: string,
|
|
error: unknown
|
|
): unknown {
|
|
if (!(error instanceof RuntimeRpcFailureError)) {
|
|
return error
|
|
}
|
|
const { code, message, data } = error.response.error
|
|
if (code === 'method_not_found') {
|
|
return new RuntimeClientError(
|
|
'runtime_unsupported',
|
|
`The Orca host this command reached is too old for \`${method}\`.`,
|
|
{ nextSteps: ['Update Orca on that host, then run the command again.'] }
|
|
)
|
|
}
|
|
const fingerprint = approvalFingerprintOf(data)
|
|
const pending = pendingApprovalsOf(data)
|
|
if (APPROVAL_CODES.has(code) && fingerprint === null && pending.length > 0) {
|
|
const nextSteps = nextStepsOf(data).filter((step) => !step.startsWith('To approve '))
|
|
return new RuntimeClientError(code, message, {
|
|
...(typeof data === 'object' ? data : {}),
|
|
nextSteps: [...nextSteps, ...perPluginApprovalCommands(ctx, pending)]
|
|
})
|
|
}
|
|
if (!APPROVAL_CODES.has(code) || fingerprint === null || typeof data !== 'object') {
|
|
return error
|
|
}
|
|
const command = approvalRerunCommand(ctx.rawArgs ?? [], fingerprint)
|
|
const nextSteps = nextStepsOf(data).map((step) =>
|
|
step.startsWith('To approve, run the same command again') ? `To approve, run: ${command}` : step
|
|
)
|
|
return new RuntimeClientError(code, message, { ...data, command, nextSteps })
|
|
}
|
|
|
|
export async function callPlugins<T>(
|
|
ctx: HandlerContext,
|
|
method: string,
|
|
params?: unknown,
|
|
options?: { timeoutMs?: number }
|
|
): Promise<T> {
|
|
try {
|
|
const reply = options
|
|
? await ctx.client.call<T>(method, params, options)
|
|
: await ctx.client.call<T>(method, params)
|
|
return reply.result
|
|
} catch (error) {
|
|
throw translatePluginRpcError(ctx, method, error)
|
|
}
|
|
}
|
|
|
|
/** Development folders are paths on the Orca host, which may not be this machine. */
|
|
export function resolveHostPluginPath(ctx: HandlerContext, value: string): string {
|
|
if (process.env.ORCA_CLI_CWD) {
|
|
throw new RuntimeClientError(
|
|
'invalid_environment',
|
|
'This shell forwards orca to an Orca host on another machine, which cannot read this folder. Run the command on the machine that runs Orca, or pass --environment for an Orca server that has the folder.'
|
|
)
|
|
}
|
|
if (isAbsolute(value)) {
|
|
return value
|
|
}
|
|
if (ctx.client.isRemote) {
|
|
throw new RuntimeClientError(
|
|
'invalid_argument',
|
|
'Pass an absolute path on the Orca server; a relative path names a folder on this machine.'
|
|
)
|
|
}
|
|
return resolve(ctx.cwd, value)
|
|
}
|
|
|
|
/** A `<dir|plugin-key>` argument as host params; a folder wins, since one may be named like a key. */
|
|
export function devTargetParams(
|
|
ctx: HandlerContext,
|
|
target: string
|
|
): { pluginKey: string } | { path: string } {
|
|
const localFolder = !ctx.client.isRemote && existsSync(resolve(ctx.cwd, target))
|
|
return !localFolder && !isAbsolute(target) && isQualifiedPluginKey(target)
|
|
? { pluginKey: target }
|
|
: { path: resolveHostPluginPath(ctx, target) }
|
|
}
|
|
|
|
export function formatPluginRow(plugin: PluginHostListEntry): string {
|
|
const tags = [plugin.execution, plugin.isDev ? 'dev' : null, plugin.official ? 'official' : null]
|
|
return `${plugin.pluginKey} ${plugin.version} ${plugin.status} ${tags.filter(Boolean).join(', ')}${plugin.error ? `\n ${plugin.error}` : ''}`
|
|
}
|
|
|
|
function formatDevLoad(result: DevLoadResult): string {
|
|
const how =
|
|
result.approval === 'approve-flag'
|
|
? 'approved with --approve'
|
|
: result.approval === 'content-only'
|
|
? 'content only, no approval needed'
|
|
: 'already approved'
|
|
return [
|
|
`${result.added ? 'Loaded' : 'Reloaded'} ${result.pluginKey} from ${result.path} (${how}).`,
|
|
result.plugin ? formatPluginRow(result.plugin) : '',
|
|
'Orca reloads it (and restarts its worker) when its files change; `orca plugin logs` shows what it printed.'
|
|
]
|
|
.filter(Boolean)
|
|
.join('\n')
|
|
}
|
|
|
|
async function devLoad(ctx: HandlerContext, path: string): Promise<void> {
|
|
const result = await callPlugins<DevLoadResult>(ctx, 'plugins.devLoad', {
|
|
path,
|
|
approvalFingerprint: stringFlag(ctx, 'approve')
|
|
})
|
|
const typeFiles = await refreshDevTypes(ctx, path)
|
|
printPluginResult(
|
|
ctx,
|
|
{ ...result, typeFiles },
|
|
[formatDevLoad(result), ...typeFiles.map((file) => `Refreshed ${file}`)].join('\n')
|
|
)
|
|
}
|
|
|
|
/** Why best effort and local only: typings help the editor; a remote host's folder is not here. */
|
|
export async function refreshDevTypes(ctx: HandlerContext, path: string): Promise<string[]> {
|
|
if (ctx.client.isRemote) {
|
|
return []
|
|
}
|
|
// Lazy: the manifest schema it parses with is heavy for every other runtime command.
|
|
const types = await import('../plugin-authoring/plugin-type-files.js')
|
|
if (!(await types.pluginFolderWantsTypes(path))) {
|
|
return []
|
|
}
|
|
return types
|
|
.writePluginTypeFiles(path)
|
|
.then((files) => files.filter((file) => file.endsWith('.d.ts')))
|
|
.catch(() => [])
|
|
}
|
|
|
|
export function requirePluginKey(ctx: HandlerContext): string {
|
|
const key = stringFlag(ctx, 'plugin')
|
|
if (!key || !isQualifiedPluginKey(key)) {
|
|
throw new RuntimeClientError(
|
|
'invalid_argument',
|
|
'Pass a plugin key such as acme.dusk; `orca plugin list` shows them.'
|
|
)
|
|
}
|
|
return key
|
|
}
|
|
|
|
async function setEnabled(ctx: HandlerContext, enabled: boolean): Promise<void> {
|
|
const pluginKey = requirePluginKey(ctx)
|
|
const list = await callPlugins<PluginHostListEntry[]>(ctx, 'plugins.setEnabled', {
|
|
pluginKey,
|
|
enabled,
|
|
...(enabled ? { approvalFingerprint: stringFlag(ctx, 'approve') } : {})
|
|
})
|
|
const plugin = list.find((entry) => entry.pluginKey === pluginKey) ?? null
|
|
printPluginResult(
|
|
ctx,
|
|
{ pluginKey, enabled, plugin },
|
|
plugin ? formatPluginRow(plugin) : `${pluginKey} ${enabled ? 'enabled' : 'disabled'}`
|
|
)
|
|
}
|
|
|
|
async function setSystemEnabled(ctx: HandlerContext, enabled: boolean): Promise<void> {
|
|
const result = await callPlugins<{ enabled: boolean; plugins: PluginHostListEntry[] }>(
|
|
ctx,
|
|
'plugins.setSystemEnabled',
|
|
{ enabled }
|
|
)
|
|
const rows = result.plugins.map(formatPluginRow)
|
|
printPluginResult(
|
|
ctx,
|
|
result,
|
|
enabled
|
|
? ['Plugins are on. Only plugins approved earlier run.', ...rows].join('\n')
|
|
: 'Plugins are off. No plugin runs; installs and approvals are kept.'
|
|
)
|
|
}
|
|
|
|
export const PLUGIN_RUNTIME_HANDLERS: Record<string, CommandHandler> = {
|
|
'plugin list': async (ctx) => {
|
|
const plugins = await callPlugins<PluginHostListEntry[]>(ctx, 'plugins.list')
|
|
printPluginResult(
|
|
ctx,
|
|
{ plugins },
|
|
plugins.length === 0 ? 'No plugins.' : plugins.map(formatPluginRow).join('\n')
|
|
)
|
|
},
|
|
'plugin logs': async (ctx) => {
|
|
const result = await callPlugins<LogsResult>(ctx, 'plugins.getLogs', {
|
|
pluginKey: requirePluginKey(ctx)
|
|
})
|
|
printPluginResult(
|
|
ctx,
|
|
result,
|
|
result.lines.length === 0
|
|
? `No log lines from ${result.pluginKey}.`
|
|
: result.lines
|
|
.map((line) => `${new Date(line.ts).toISOString()} ${line.level} ${line.line}`)
|
|
.join('\n')
|
|
)
|
|
},
|
|
'plugin restart': async (ctx) => {
|
|
const result = await callPlugins<{ pluginKey: string; plugin: PluginHostListEntry | null }>(
|
|
ctx,
|
|
'plugins.restart',
|
|
{ pluginKey: requirePluginKey(ctx) }
|
|
)
|
|
printPluginResult(
|
|
ctx,
|
|
result,
|
|
`Stopped ${result.pluginKey}'s worker; its next command or event starts the current code.`
|
|
)
|
|
},
|
|
'plugin enable': (ctx) => setEnabled(ctx, true),
|
|
'plugin disable': (ctx) => setEnabled(ctx, false),
|
|
'plugin system on': (ctx) => setSystemEnabled(ctx, true),
|
|
'plugin system off': (ctx) => setSystemEnabled(ctx, false),
|
|
'plugin dev load': (ctx) =>
|
|
devLoad(ctx, resolveHostPluginPath(ctx, requirePluginPathArg(ctx, 'dir'))),
|
|
'plugin dev reload': async (ctx) => {
|
|
const dir = stringFlag(ctx, 'dir')
|
|
if (dir) {
|
|
await devLoad(ctx, resolveHostPluginPath(ctx, dir))
|
|
return
|
|
}
|
|
const plugins = await callPlugins<PluginHostListEntry[]>(ctx, 'plugins.refresh')
|
|
printPluginResult(ctx, { plugins }, `Reloaded ${plugins.length} plugin(s).`)
|
|
},
|
|
'plugin dev inspect': async (ctx) => {
|
|
const result = await callPlugins<{ pluginKey: string; opened: number }>(
|
|
ctx,
|
|
'plugins.devInspect',
|
|
{ pluginKey: requirePluginKey(ctx) }
|
|
)
|
|
printPluginResult(
|
|
ctx,
|
|
result,
|
|
result.opened === 0
|
|
? `${result.pluginKey} has no open panel or editor; open one in Orca, then run this again.`
|
|
: `Opened DevTools for ${result.opened} ${result.pluginKey} frame(s).`
|
|
)
|
|
},
|
|
'plugin dev unload': async (ctx) => {
|
|
const params = devTargetParams(ctx, requirePluginPathArg(ctx, 'target'))
|
|
const result = await callPlugins<{ path: string; pluginKey: string | null }>(
|
|
ctx,
|
|
'plugins.devUnload',
|
|
params
|
|
)
|
|
printPluginResult(ctx, result, `Unloaded ${result.pluginKey ?? 'the folder'} (${result.path}).`)
|
|
}
|
|
}
|