mirror of
https://github.com/stablyai/orca.git
synced 2026-10-26 00:03:55 +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>
213 lines
7.2 KiB
TypeScript
213 lines
7.2 KiB
TypeScript
import { createHash } from 'node:crypto'
|
|
import { createReadStream } from 'node:fs'
|
|
import { mkdir, rm } from 'node:fs/promises'
|
|
import { dirname, join } from 'node:path'
|
|
import { z } from 'zod'
|
|
import { PLUGIN_COMMIT_PATTERN } from '../../shared/plugins/plugin-install-lockfile'
|
|
import {
|
|
pluginMarketplaceGitSourceSchema,
|
|
pluginMarketplaceSchema,
|
|
type PluginMarketplace,
|
|
type PluginMarketplaceGitSource
|
|
} from '../../shared/plugins/plugin-marketplace'
|
|
import { writePluginFileAtomically } from './plugin-atomic-file-write'
|
|
|
|
export const PLUGIN_MARKETPLACE_SOURCE_LIMIT = 64
|
|
export const PLUGIN_MARKETPLACE_SOURCE_ID_PATTERN = /^[0-9a-f]{32}$/
|
|
|
|
const sourceIdSchema = z.string().regex(PLUGIN_MARKETPLACE_SOURCE_ID_PATTERN)
|
|
const registeredSourceSchema = z.strictObject({
|
|
id: sourceIdSchema,
|
|
source: pluginMarketplaceGitSourceSchema,
|
|
addedAt: z.number().finite().nonnegative()
|
|
})
|
|
const sourceFileSchema = z.strictObject({
|
|
schemaVersion: z.literal(1),
|
|
sources: z.array(registeredSourceSchema).max(PLUGIN_MARKETPLACE_SOURCE_LIMIT)
|
|
})
|
|
const cachedSnapshotSchema = z.strictObject({
|
|
schemaVersion: z.literal(1),
|
|
sourceId: sourceIdSchema,
|
|
source: pluginMarketplaceGitSourceSchema,
|
|
marketplaceCommit: z.string().regex(PLUGIN_COMMIT_PATTERN),
|
|
fetchedAt: z.number().finite().nonnegative(),
|
|
marketplace: pluginMarketplaceSchema
|
|
})
|
|
|
|
export type PluginMarketplaceRegisteredSource = z.infer<typeof registeredSourceSchema>
|
|
export type PluginMarketplaceCachedSnapshot = z.infer<typeof cachedSnapshotSchema>
|
|
|
|
const SOURCE_FILE_MAX_BYTES = 2 * 1024 * 1024
|
|
const SNAPSHOT_FILE_MAX_BYTES = 16 * 1024 * 1024
|
|
|
|
export function marketplaceSourceId(source: PluginMarketplaceGitSource): string {
|
|
const parsed = pluginMarketplaceGitSourceSchema.parse(source)
|
|
return createHash('sha256')
|
|
.update(`orca-plugin-marketplace-source-v1\0${parsed.url}\0${parsed.ref}`)
|
|
.digest('hex')
|
|
.slice(0, 32)
|
|
}
|
|
|
|
export class PluginMarketplaceStore {
|
|
private readonly sourcesPath: string
|
|
private readonly snapshotDirectory: string
|
|
private sources: PluginMarketplaceRegisteredSource[] | null = null
|
|
private writeChain: Promise<void> = Promise.resolve()
|
|
|
|
constructor(pluginsDataDir: string) {
|
|
const root = join(pluginsDataDir, 'marketplaces')
|
|
this.sourcesPath = join(root, 'sources.json')
|
|
this.snapshotDirectory = join(root, 'snapshots')
|
|
}
|
|
|
|
async listSources(): Promise<readonly PluginMarketplaceRegisteredSource[]> {
|
|
await this.loadSources()
|
|
return this.sources!
|
|
}
|
|
|
|
async addSource(
|
|
source: PluginMarketplaceGitSource,
|
|
addedAt = Date.now()
|
|
): Promise<PluginMarketplaceRegisteredSource> {
|
|
const parsedSource = pluginMarketplaceGitSourceSchema.parse(source)
|
|
const registration = registeredSourceSchema.parse({
|
|
id: marketplaceSourceId(parsedSource),
|
|
source: parsedSource,
|
|
addedAt
|
|
})
|
|
await this.mutateSources((sources) => {
|
|
if (sources.some((candidate) => candidate.id === registration.id)) {
|
|
return [...sources]
|
|
}
|
|
if (sources.length >= PLUGIN_MARKETPLACE_SOURCE_LIMIT) {
|
|
throw new Error(`marketplace source limit (${PLUGIN_MARKETPLACE_SOURCE_LIMIT}) reached`)
|
|
}
|
|
return [...sources, registration]
|
|
})
|
|
return this.sources!.find((candidate) => candidate.id === registration.id)!
|
|
}
|
|
|
|
async removeSource(sourceId: string): Promise<boolean> {
|
|
const parsedId = sourceIdSchema.parse(sourceId)
|
|
let removed = false
|
|
await this.mutateSources((sources) => {
|
|
const next = sources.filter((source) => source.id !== parsedId)
|
|
removed = next.length !== sources.length
|
|
return next
|
|
})
|
|
if (removed) {
|
|
await rm(this.snapshotPath(parsedId), { force: true })
|
|
}
|
|
return removed
|
|
}
|
|
|
|
async writeSnapshot(input: {
|
|
source: PluginMarketplaceRegisteredSource
|
|
marketplaceCommit: string
|
|
fetchedAt?: number
|
|
marketplace: PluginMarketplace
|
|
}): Promise<PluginMarketplaceCachedSnapshot> {
|
|
const snapshot = cachedSnapshotSchema.parse({
|
|
schemaVersion: 1,
|
|
sourceId: input.source.id,
|
|
source: input.source.source,
|
|
marketplaceCommit: input.marketplaceCommit,
|
|
fetchedAt: input.fetchedAt ?? Date.now(),
|
|
marketplace: input.marketplace
|
|
})
|
|
await writeAtomicJson(this.snapshotPath(input.source.id), snapshot)
|
|
return snapshot
|
|
}
|
|
|
|
async readSnapshot(sourceId: string): Promise<PluginMarketplaceCachedSnapshot | null> {
|
|
const parsedId = sourceIdSchema.parse(sourceId)
|
|
try {
|
|
const raw = JSON.parse(
|
|
await readBoundedText(this.snapshotPath(parsedId), SNAPSHOT_FILE_MAX_BYTES)
|
|
)
|
|
const parsed = cachedSnapshotSchema.parse(raw)
|
|
if (parsed.sourceId !== parsedId) {
|
|
throw new Error('marketplace snapshot source identity does not match its cache path')
|
|
}
|
|
return parsed
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
|
return null
|
|
}
|
|
throw new Error(
|
|
`marketplace snapshot is invalid: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
}
|
|
}
|
|
|
|
private async loadSources(): Promise<void> {
|
|
if (this.sources !== null) {
|
|
return
|
|
}
|
|
try {
|
|
const parsed = sourceFileSchema.parse(
|
|
JSON.parse(await readBoundedText(this.sourcesPath, SOURCE_FILE_MAX_BYTES))
|
|
)
|
|
const ids = new Set<string>()
|
|
for (const source of parsed.sources) {
|
|
if (source.id !== marketplaceSourceId(source.source) || ids.has(source.id)) {
|
|
throw new Error('marketplace source identity is inconsistent or duplicated')
|
|
}
|
|
ids.add(source.id)
|
|
}
|
|
this.sources = parsed.sources
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
|
this.sources = []
|
|
return
|
|
}
|
|
throw new Error(
|
|
`marketplace sources are invalid: ${error instanceof Error ? error.message : String(error)}`
|
|
)
|
|
}
|
|
}
|
|
|
|
private async mutateSources(
|
|
mutation: (
|
|
sources: readonly PluginMarketplaceRegisteredSource[]
|
|
) => PluginMarketplaceRegisteredSource[]
|
|
): Promise<void> {
|
|
const update = this.writeChain
|
|
.catch(() => undefined)
|
|
.then(async () => {
|
|
await this.loadSources()
|
|
const next = sourceFileSchema.parse({
|
|
schemaVersion: 1,
|
|
sources: mutation(this.sources!)
|
|
}).sources
|
|
await writeAtomicJson(this.sourcesPath, { schemaVersion: 1, sources: next })
|
|
this.sources = next
|
|
})
|
|
this.writeChain = update
|
|
await update
|
|
}
|
|
|
|
private snapshotPath(sourceId: string): string {
|
|
return join(this.snapshotDirectory, `${sourceId}.json`)
|
|
}
|
|
}
|
|
|
|
async function readBoundedText(path: string, limit: number): Promise<string> {
|
|
const chunks: Buffer[] = []
|
|
let totalBytes = 0
|
|
for await (const chunk of createReadStream(path)) {
|
|
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
totalBytes += bytes.byteLength
|
|
if (totalBytes > limit) {
|
|
throw new Error(`file exceeds its ${limit}-byte limit`)
|
|
}
|
|
chunks.push(bytes)
|
|
}
|
|
return Buffer.concat(chunks, totalBytes).toString('utf8')
|
|
}
|
|
|
|
async function writeAtomicJson(path: string, value: unknown): Promise<void> {
|
|
await mkdir(dirname(path), { recursive: true })
|
|
await writePluginFileAtomically(path, `${JSON.stringify(value, null, 2)}\n`)
|
|
}
|