mirror of
https://github.com/stablyai/orca.git
synced 2026-09-22 08:02:28 +00:00
* feat(plugins): Orca plugin system — kernel, content packs, panels, workers, marketplace v0 (experimental) Adds Orca's experimental plugin system behind a settings flag: a supervised kernel, declarative content packs (VM recipes, commands and keybindings, language packs), sandboxed iframe panels, forked worker hosts, and a Git-backed marketplace v0 with consent, provenance and kill-list enforcement. Theme, icon-theme and terminal-theme contributions are deferred to a follow-up pass. * fix(plugins): make unsupported marketplace listings unreachable by key findPlugin() backs preview/install/previewInstalledUpdate via requireListing(), so filtering only listPlugins() hid the catalog card while leaving the dead install path reachable one click later. * fix(plugins): fan Pi session-only status out to plugin subscribers The providerSessionOnly early-return in applyNormalizedStatus emitted to onAgentStatus (main-window fanout) but skipped enrichedStatusListeners, so plugins subscribed to agent.status.changed silently missed every Pi session_start event. Route both emit sites through one helper so a future early return cannot drop the plugin tap again. Co-authored-by: Orca <help@stably.ai> * plugins: drop dead code and hoist duplicated trust-boundary patterns Cleanup pass over the P1 diff, no behavior change: - Delete `readPluginTreeSnapshot`/`readSnapshotFile` and their types, plus the now-vestigial `directories`/`signal` plumbing in `collectFiles`. - Delete `resolveContainedPluginDirectory` (no callers). - Delete `plugin-content-load-pool.ts`; it reimplemented the existing `mapWithConcurrency`, whose index arg also removes the pairing wrapper in `buildPluginList`. - Hoist `PLUGIN_CONTENT_HASH_PATTERN` and `PLUGIN_COMMIT_PATTERN` into the install-lockfile module; 11 sites hand-rolled these identically. - Point the new reliability gate at the PR instead of gitignored docs paths, matching every other gate's link form. * fix(plugins): retry plugin state renames on Windows AV/EPERM locks Six plugin write paths (lockfile, provenance, current pointer, kill list, marketplace cache, staged install dir) did a plain rename, so an antivirus or indexer holding the target open surfaced as a failed install. The repo already retries this hazard for issue #1507, but only through a sync helper; these paths are all async. Adds one bounded async retry + atomic write used by all six, and trims a consent-provenance header that restated its own JSX. * test(plugins): cover the Windows rename retry path The retry loop shipped untested: both existing cases hit the non-retry path, and the temp-cleanup test passed identically with the `finally` removed. Mock `rename` to queue errno codes so CI can exercise locks it cannot provoke. Co-authored-by: Orca <help@stably.ai> * fix(plugins): pin bundled plugin resources to LF Windows CI checks out with autocrlf, so the byte-hashed launch tree arrived as CRLF and verify-packaged-plugin-resources rejected it — the packaged build could never pass on Windows. Reproduced locally: CRLF yields the exact CI error, LF verifies clean. Files are already LF, so nothing renormalizes. Co-authored-by: Orca <help@stably.ai> * test: guard the bundled-plugin LF pin against a CRLF checkout The byte-hash mismatch only surfaced in Windows packaging CI. Assert the .gitattributes pin and that a CRLF tree is rejected, so a regression fails on any platform instead of waiting for a packaged Windows build. Co-authored-by: Orca <help@stably.ai> * ci: trigger packaged-build check on bundled plugin resource changes The launch tree is byte-hashed during packaging, but no trigger path covered it — so the CRLF fix for that check would not have re-run the check. Add the resources, verifier and .gitattributes paths that can break packaging. Co-authored-by: Orca <help@stably.ai> * perf(plugins): rebuild the panel frame only when its baked theme values change The revision keys the panel iframe, so every bump destroys the sandboxed frame and its in-panel state. It counted root attribute mutations, but --workspace-sidebar-live-width is written every rAF of a sidebar drag, so dragging with a panel open blanked it ~60x/sec. Compare the two values the shell actually bakes in instead. Co-authored-by: Orca <help@stably.ai> * test: stop pinning a plugin name in the CRLF guard The CRLF case rewrites every launch file, so the reported mismatch is whichever plugin sorts first. P2 adds theme plugins that sort ahead of orca-navigation-shortcuts, which broke the assertion there. Co-authored-by: Orca <help@stably.ai> * style: drop stray blank lines left by the rebase resolutions Both sides of the agent-hooks and orca-runtime conflicts contributed a trailing blank, which oxfmt rejects. Whitespace only. Co-authored-by: Orca <help@stably.ai> * test(plugins): stop the startup budget failing on machine load P95 runs 16-34ms idle but exceeds the 50ms bound under full-suite parallelism, so the gate flaked. Widen it to catch an order-of-magnitude regression instead; the no-worker/no-plugin-code assertions are the real guarantee. Verified a 400ms regression still fails. Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Orca <help@stably.ai>
211 lines
7.4 KiB
TypeScript
211 lines
7.4 KiB
TypeScript
import { join } from 'node:path'
|
|
import { pathToFileURL } from 'node:url'
|
|
import {
|
|
pluginWorkerParentMessageSchema,
|
|
type PluginWorkerChildMessage
|
|
} from '../../shared/plugins/plugin-host-protocol'
|
|
import type { PluginEventName } from '../../shared/plugins/plugin-manifest'
|
|
|
|
/**
|
|
* Message-loop core of the out-of-process plugin worker. Electron-free and
|
|
* side-effect-free (send/import/exit are injected) so it unit-tests without
|
|
* forking a real child process; `plugin-host-entry.ts` wires it to the fork
|
|
* IPC channel.
|
|
*/
|
|
|
|
export type PluginHostCallError = Error & { code?: string }
|
|
|
|
/** API surface handed to a plugin's `activate(orca)` export. Everything is
|
|
* EXPERIMENTAL until pluginApi v1 freezes. */
|
|
export type PluginWorkerOrcaApi = {
|
|
/** Register the handler for a command declared in the manifest. */
|
|
commands: {
|
|
register(commandId: string, handler: (args: unknown) => unknown | Promise<unknown>): void
|
|
}
|
|
/** Handle an event the manifest subscribed to (`contributes.events`). */
|
|
events: {
|
|
on(event: PluginEventName, handler: (payload: unknown) => void | Promise<void>): void
|
|
}
|
|
/** Call a host API method (capability-gated host-side). */
|
|
host: {
|
|
call(method: string, params?: unknown): Promise<unknown>
|
|
}
|
|
/** Consented capability kinds (informational — the host re-gates). */
|
|
grantedCapabilities: readonly string[]
|
|
log(message: string): void
|
|
}
|
|
|
|
export type PluginWorkerRuntimeOptions = {
|
|
send: (message: PluginWorkerChildMessage) => void
|
|
importModule?: (specifier: string) => Promise<unknown>
|
|
exit?: (code: number) => void
|
|
}
|
|
|
|
export type PluginWorkerRuntime = {
|
|
handleMessage(raw: unknown): Promise<void>
|
|
}
|
|
|
|
function toErrorMessage(error: unknown): string {
|
|
return error instanceof Error ? (error.stack ?? error.message) : String(error)
|
|
}
|
|
|
|
export function createPluginWorkerRuntime(
|
|
options: PluginWorkerRuntimeOptions
|
|
): PluginWorkerRuntime {
|
|
const send = options.send
|
|
const importModule = options.importModule ?? ((specifier: string) => import(specifier))
|
|
const exit = options.exit ?? ((code: number) => process.exit(code))
|
|
const commandHandlers = new Map<string, (args: unknown) => unknown | Promise<unknown>>()
|
|
const eventHandlers = new Map<string, ((payload: unknown) => void | Promise<void>)[]>()
|
|
const pendingHostCalls = new Map<
|
|
number,
|
|
{ resolve: (value: unknown) => void; reject: (error: PluginHostCallError) => void }
|
|
>()
|
|
let nextHostCallId = 0
|
|
let initialized = false
|
|
let shuttingDown = false
|
|
let deactivate: (() => unknown | Promise<unknown>) | null = null
|
|
|
|
async function handleInit(input: {
|
|
pluginRoot: string
|
|
mainEntry: string
|
|
grantedCapabilities: string[]
|
|
}): Promise<void> {
|
|
if (initialized) {
|
|
send({ type: 'log', level: 'warn', message: 'ignoring duplicate init message' })
|
|
return
|
|
}
|
|
initialized = true
|
|
// Why: file URL import keeps ESM plugin entries working on Windows paths.
|
|
// Why: manifest paths accept either portable separator; split explicitly
|
|
// so a Windows-authored plugin also imports on macOS/Linux and vice versa.
|
|
const entryUrl = pathToFileURL(join(input.pluginRoot, ...input.mainEntry.split(/[\\/]/))).href
|
|
const module = (await importModule(entryUrl)) as { default?: unknown; deactivate?: unknown }
|
|
const activate = module?.default
|
|
if (typeof activate !== 'function') {
|
|
throw new Error(`plugin entry ${input.mainEntry} has no default-exported activate function`)
|
|
}
|
|
if (module.deactivate !== undefined && typeof module.deactivate !== 'function') {
|
|
throw new Error(`plugin entry ${input.mainEntry} has a non-function deactivate export`)
|
|
}
|
|
deactivate = (module.deactivate as (() => unknown | Promise<unknown>) | undefined) ?? null
|
|
const orca: PluginWorkerOrcaApi = {
|
|
commands: {
|
|
register(commandId, handler) {
|
|
commandHandlers.set(commandId, handler)
|
|
}
|
|
},
|
|
events: {
|
|
on(event, handler) {
|
|
const handlers = eventHandlers.get(event) ?? []
|
|
handlers.push(handler)
|
|
eventHandlers.set(event, handlers)
|
|
}
|
|
},
|
|
host: {
|
|
call(method, params) {
|
|
const callId = nextHostCallId++
|
|
return new Promise<unknown>((resolve, reject) => {
|
|
pendingHostCalls.set(callId, { resolve, reject })
|
|
send({ type: 'hostCall', callId, method, params })
|
|
})
|
|
}
|
|
},
|
|
grantedCapabilities: input.grantedCapabilities,
|
|
log(message) {
|
|
send({ type: 'log', level: 'info', message: String(message).slice(0, 8192) })
|
|
}
|
|
}
|
|
await activate(orca)
|
|
send({ type: 'ready', commands: [...commandHandlers.keys()] })
|
|
}
|
|
|
|
return {
|
|
async handleMessage(raw) {
|
|
const parsed = pluginWorkerParentMessageSchema.safeParse(raw)
|
|
if (!parsed.success) {
|
|
send({ type: 'log', level: 'warn', message: 'ignoring malformed parent message' })
|
|
return
|
|
}
|
|
const message = parsed.data
|
|
try {
|
|
switch (message.type) {
|
|
case 'init': {
|
|
await handleInit(message)
|
|
return
|
|
}
|
|
case 'invokeCommand': {
|
|
const handler = commandHandlers.get(message.commandId)
|
|
if (!handler) {
|
|
send({
|
|
type: 'commandResult',
|
|
callId: message.callId,
|
|
ok: false,
|
|
error: `no handler registered for command ${message.commandId}`
|
|
})
|
|
return
|
|
}
|
|
try {
|
|
const value = await handler(message.args)
|
|
send({ type: 'commandResult', callId: message.callId, ok: true, value })
|
|
} catch (error) {
|
|
send({
|
|
type: 'commandResult',
|
|
callId: message.callId,
|
|
ok: false,
|
|
error: toErrorMessage(error)
|
|
})
|
|
}
|
|
return
|
|
}
|
|
case 'deliverEvent': {
|
|
const handlers = eventHandlers.get(message.event) ?? []
|
|
for (const handler of handlers) {
|
|
try {
|
|
await handler(message.payload)
|
|
} catch (error) {
|
|
send({ type: 'log', level: 'error', message: toErrorMessage(error) })
|
|
}
|
|
}
|
|
send({ type: 'eventAck', eventId: message.eventId })
|
|
return
|
|
}
|
|
case 'hostResult': {
|
|
const pending = pendingHostCalls.get(message.callId)
|
|
if (!pending) {
|
|
return
|
|
}
|
|
pendingHostCalls.delete(message.callId)
|
|
if (message.ok) {
|
|
pending.resolve(message.value)
|
|
} else {
|
|
const error: PluginHostCallError = new Error(message.error ?? 'host call failed')
|
|
error.code = message.errorCode
|
|
pending.reject(error)
|
|
}
|
|
return
|
|
}
|
|
case 'shutdown': {
|
|
if (shuttingDown) {
|
|
return
|
|
}
|
|
shuttingDown = true
|
|
try {
|
|
await deactivate?.()
|
|
} catch (error) {
|
|
send({ type: 'log', level: 'error', message: toErrorMessage(error).slice(0, 8192) })
|
|
}
|
|
exit(0)
|
|
}
|
|
}
|
|
} catch (error) {
|
|
// Why: an init/activation failure leaves the worker useless; report
|
|
// and die so the parent surfaces the error instead of hanging on
|
|
// the ready timeout.
|
|
send({ type: 'fatal', error: toErrorMessage(error) })
|
|
exit(1)
|
|
}
|
|
}
|
|
}
|
|
}
|