Files
orca/src/shared/plugins/plugin-host-api.ts
T
NeilandOrca 97e4776dfe feat(plugins): Orca plugin system — kernel, content packs, panels, workers, marketplace v0 (experimental) (#8549)
* 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>
2026-07-27 01:14:33 -07:00

270 lines
8.5 KiB
TypeScript

import { z } from 'zod'
import { PLUGIN_EVENT_NAMES } from './plugin-manifest'
import type { PluginCapabilityKind } from './plugin-capabilities'
/**
* Host API v0 — the separately-versioned public facade plugins call. Every
* method carries params AND result schemas plus capability/mutation metadata;
* handlers (bound in main) delegate to runtime services. The raw runtime-RPC
* registry is never exposed: its methods have no result schemas and evolve at
* internal velocity.
*
* This table is the single source of truth for the capability gate, the panel
* bridge action set, and the worker SDK. Electron-free by design: desktop
* main, headless serve, the relay conformance path, and tests all import it.
*
* EXPERIMENTAL: additive-only within pluginApi major 1 once frozen; no
* stability promises before then.
*/
export const PANEL_ACTION_TEXT_MAX_LENGTH = 4096
export const PLUGIN_WORKSPACE_TERMINAL_LIMIT = 50
export const PLUGIN_WORKSPACE_LABEL_MAX_LENGTH = 512
export const PLUGIN_TERMINAL_ID_MAX_LENGTH = 1024
const workspaceReadContextParams = z.object({}).strict().optional()
const workspaceReadContextResult = z
.object({
branch: z.string().max(PLUGIN_WORKSPACE_LABEL_MAX_LENGTH),
displayName: z.string().max(PLUGIN_WORKSPACE_LABEL_MAX_LENGTH),
/** Terminals of the focused worktree, so callers can address a specific
* terminal id — the API has no "active terminal" write target. */
terminals: z
.array(
z
.object({
id: z.string().min(1).max(PLUGIN_TERMINAL_ID_MAX_LENGTH)
})
.strict()
)
.max(PLUGIN_WORKSPACE_TERMINAL_LIMIT)
})
.strict()
.nullable()
const terminalSendTextParams = z.object({
/** Explicit target. Never "the active terminal": a focus change must not
* redirect a delayed plugin write into another pane (design-doc rule). */
terminalId: z.string().min(1).max(PLUGIN_TERMINAL_ID_MAX_LENGTH),
text: z.string().min(1).max(PANEL_ACTION_TEXT_MAX_LENGTH),
enter: z.boolean().default(false)
})
const terminalSendTextResult = z.object({ accepted: z.boolean() })
const notificationsShowParams = z.object({
title: z.string().min(1).max(120),
body: z.string().max(1000).optional()
})
const notificationsShowResult = z.object({ delivered: z.boolean() })
const RESERVED_STORAGE_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
const storageKeySchema = z
.string()
.min(1)
.max(256)
.refine((key) => !RESERVED_STORAGE_KEYS.has(key), 'reserved storage key')
const pluginJsonValueSchema = z.json()
/** Caps keep per-plugin storage an honest key-value store, not a database. */
export const PLUGIN_STORAGE_VALUE_MAX_BYTES = 256 * 1024
export const PLUGIN_STORAGE_TOTAL_MAX_BYTES = 5 * 1024 * 1024
export const PLUGIN_STORAGE_KEY_LIMIT = 1024
const storageGetParams = z.object({ key: storageKeySchema })
const storageGetResult = z.object({ value: pluginJsonValueSchema })
const storageSetParams = z.object({ key: storageKeySchema, value: pluginJsonValueSchema })
const storageSetResult = z.object({ ok: z.literal(true) })
const storageDeleteParams = z.object({ key: storageKeySchema })
const storageDeleteResult = z.object({ ok: z.literal(true) })
const storageKeysParams = z.object({}).strict().optional()
const storageKeysResult = z.object({ keys: z.array(z.string()).max(PLUGIN_STORAGE_KEY_LIMIT) })
const secretsGetParams = z.object({ key: storageKeySchema })
const secretsGetResult = z.object({ value: z.string().nullable() })
const secretsSetParams = z.object({ key: storageKeySchema, value: z.string().max(64 * 1024) })
const secretsSetResult = z.object({ ok: z.literal(true) })
const secretsDeleteParams = z.object({ key: storageKeySchema })
const secretsDeleteResult = z.object({ ok: z.literal(true) })
const settingsGetParams = z.object({}).strict().optional()
const settingsGetResult = z.object({ settings: z.record(z.string(), pluginJsonValueSchema) })
const settingsSetParams = z.object({ key: storageKeySchema, value: pluginJsonValueSchema })
const settingsSetResult = z.object({ ok: z.literal(true) })
const eventsSubscribeParams = z.object({
events: z.array(z.enum(PLUGIN_EVENT_NAMES)).min(1).max(PLUGIN_EVENT_NAMES.length)
})
const eventsSubscribeResult = z.object({ subscribed: z.array(z.enum(PLUGIN_EVENT_NAMES)) })
export type PluginHostMethodSpec = {
name: string
/** pluginApi minor the method appeared in (`1.0` for the v0 set). */
since: string
/** Machine-readable resource boundary enforced by the host binding. */
scope: 'active-worktree' | 'explicit-terminal' | 'plugin-private' | 'desktop' | 'host-events'
stability: 'experimental'
capability: PluginCapabilityKind
/** Mutations are audit-logged with actor `plugin:<id>`. */
mutation: boolean
/** Whether sandboxed panels may call this over the postMessage bridge.
* Workers can call every method. */
panel: boolean
params: z.ZodTypeAny
result: z.ZodTypeAny
}
const spec = <P extends z.ZodTypeAny, R extends z.ZodTypeAny>(
entry: Omit<PluginHostMethodSpec, 'params' | 'result' | 'stability'> & {
params: P
result: R
}
): PluginHostMethodSpec => ({ ...entry, stability: 'experimental' })
export const PLUGIN_HOST_API_V0: readonly PluginHostMethodSpec[] = [
spec({
name: 'workspace.readContext',
since: '1.0',
scope: 'active-worktree',
capability: 'workspace:read',
mutation: false,
panel: true,
params: workspaceReadContextParams,
result: workspaceReadContextResult
}),
spec({
name: 'terminal.sendText',
since: '1.0',
scope: 'explicit-terminal',
capability: 'terminal:send',
mutation: true,
panel: true,
params: terminalSendTextParams,
result: terminalSendTextResult
}),
spec({
name: 'notifications.show',
since: '1.0',
scope: 'desktop',
capability: 'notifications:show',
mutation: true,
panel: true,
params: notificationsShowParams,
result: notificationsShowResult
}),
spec({
name: 'storage.get',
since: '1.0',
scope: 'plugin-private',
capability: 'storage',
mutation: false,
panel: false,
params: storageGetParams,
result: storageGetResult
}),
spec({
name: 'storage.set',
since: '1.0',
scope: 'plugin-private',
capability: 'storage',
mutation: true,
panel: false,
params: storageSetParams,
result: storageSetResult
}),
spec({
name: 'storage.delete',
since: '1.0',
scope: 'plugin-private',
capability: 'storage',
mutation: true,
panel: false,
params: storageDeleteParams,
result: storageDeleteResult
}),
spec({
name: 'storage.keys',
since: '1.0',
scope: 'plugin-private',
capability: 'storage',
mutation: false,
panel: false,
params: storageKeysParams,
result: storageKeysResult
}),
spec({
name: 'secrets.get',
since: '1.0',
scope: 'plugin-private',
capability: 'secrets',
mutation: false,
panel: false,
params: secretsGetParams,
result: secretsGetResult
}),
spec({
name: 'secrets.set',
since: '1.0',
scope: 'plugin-private',
capability: 'secrets',
mutation: true,
panel: false,
params: secretsSetParams,
result: secretsSetResult
}),
spec({
name: 'secrets.delete',
since: '1.0',
scope: 'plugin-private',
capability: 'secrets',
mutation: true,
panel: false,
params: secretsDeleteParams,
result: secretsDeleteResult
}),
spec({
name: 'settings.get',
since: '1.0',
scope: 'plugin-private',
capability: 'settings:own',
mutation: false,
panel: false,
params: settingsGetParams,
result: settingsGetResult
}),
spec({
name: 'settings.set',
since: '1.0',
scope: 'plugin-private',
capability: 'settings:own',
mutation: true,
panel: false,
params: settingsSetParams,
result: settingsSetResult
}),
spec({
name: 'events.subscribe',
since: '1.0',
scope: 'host-events',
capability: 'events:subscribe',
mutation: false,
panel: false,
params: eventsSubscribeParams,
result: eventsSubscribeResult
})
]
const SPEC_BY_NAME = new Map(PLUGIN_HOST_API_V0.map((entry) => [entry.name, entry]))
export function getPluginHostMethodSpec(name: string): PluginHostMethodSpec | null {
return SPEC_BY_NAME.get(name) ?? null
}
/** Actions sandboxed panels may request over the postMessage bridge. Derived
* from the spec table so the panel surface can never drift from the gate. */
export const PLUGIN_PANEL_ACTIONS = PLUGIN_HOST_API_V0.filter((entry) => entry.panel).map(
(entry) => entry.name
)
export function isPluginPanelAction(action: string): boolean {
return PLUGIN_PANEL_ACTIONS.includes(action)
}