Files
archived-orca/src/shared/plugins/workers/plugin-host-api-reference-doc.ts
T
Neil 255b5c22c1 feat(plugins): host API 1.8 — create workspaces, resume agents, automations (#41528)
* feat(plugins): proposed tier for host methods not yet frozen

A method spec may set `proposed: true`: only development plugins may call
it (others get not_permitted), and the minor, frame/worker method lists,
typings and skill references omit it. The reference renders such methods
in a separate Proposed section; dev workers' host.has answers for them.

* feat(plugins): param capabilities, host confirmations, automation provenance

- PluginHostMethodSpec.paramCapabilities: a passed param can require a
  second capability; executePluginHostCall and the mock host refuse it with
  capability_denied before any audit or effect, and the reference shows it.
- confirmPluginAction generalizes the external-open prompt into a host-owned
  confirmation, exposed as PluginHostServices.confirm (desktop only; absent
  in headless serve). It re-checks the plugin's approval after the answer.
- Automations record createdBy { kind: 'plugin', pluginKey, name }, set by
  the runtime from the in-process plugin caller (RpcContext.plugin), never
  from params; the Automations detail shows "Created by <plugin>".

* feat(plugins): workspace:create, automation:read and automation:write capabilities

New closed-enum kinds (older Orcas refuse such manifests with the engines
message), worker-only, with consent copy that names what each allows;
release floor PLUGIN_HOST_API_1_8_SINCE (1.4.259) joins
PLUGIN_SCHEMA_NEWEST_SINCE. agent:launch copy now says it also resumes.

* feat(plugins): host API 1.8 methods: workspace.create, agent.resume, automation.*

- workspace.create (workspace:create; agent also needs agent:launch): a
  worktree in a Git project, as orca worktree create does; with agent, the
  CLI's agent.launch create-worktree path, so the agent starts after setup.
  Setup is skipped or follows the project's settings; never run, an
  approved hash or a startup command.
- agent.resume (agent:launch): terminal.ensureAgentSession by session id;
  started is false when a terminal already ran it. agents.list rows and
  agent.status.changed carry sessionId.
- automation.list/create/update/delete (automation:read/write): create
  forwards only name, prompt, agent, target, schedule, time zone and
  enabled; update/delete of automations another plugin or the person made
  ask the person first and report cancelled or consent-unavailable.

* test(plugins): host API 1.8 coverage; regenerate plugin artifacts

Covers param capabilities (host and mock host), workspace.create payloads
and refusals, agent.resume keys and adoption, sessionId on agents.list,
automation projection, forbidden create fields, confirmation outcomes,
runtime-set provenance and capability access growth. Regenerates the
reference, schemas, typings, declarative runtime and skill references.

* fix(plugins): host API 1.8 review fixes

- Confirmations spend the frame dialog budget, allow one question per
  plugin at a time and pause after a refusal (rate_limited); a worker's
  question shows in the focused window, else the first visible one.
- Changing what an automation with extra agent settings runs (prompt,
  schedule, resuming) asks first even for its creator, showing the prompt.
- Removing, disabling or blocking a plugin pauses its automations and ends
  its ownership (createdBy.endedAt), so neither re-enabling nor a reinstall
  under the key resumes or edits them silently; the remove dialog says so.
- workspace.create and agent.resume record the terminals they return as
  the plugin's own; a launch that fails after its worktree exists names it.
- Setup-decision refusals are told by the runtime's error class (kept as
  the in-process RPC error's cause); generated names see every worktree
  of the project; resume transcripts match the workspace and host.
- Created by shows the plugin id beside its name.

* fix(plugins): end automation ownership only on uninstall, disable or block

- The ownership sweep no longer reads discovery: only an uninstall
  (announced by the removal path), the disabled list, the kill list or
  the plugin-system switch end it, and only once the service is ready,
  so an unreadable plugins folder pauses nothing. An install under the
  same key after a removal keeps what it creates.
- A new time zone on an automation with extra agent settings asks first.
- A failed launch names only a new worktree made from the requested name.
- Settings' plugins-off state and the CLI's plugin system off and plugin
  disable say that plugin-created automations are paused and stay so.

* fix(plugins): address host API 1.8 review threads

- Confirmations close when the worker's call ends, freeing the plugin's
  turn; they name the automation (short id, project, workspace,
  schedule), show any new prompt, and are refused as `changed` when the
  automation was edited while the person was asked.
- automation.create takes hostId (through the project's setup on that
  host) and a creationKey scoped to the plugin; the runtime rechecks the
  plugin's approval right before the write.
- agent.resume records only terminals it started; both it and
  workspace.create recheck approval before recording.
- automation.list never cuts a schedule (null when too long) or fails on
  an id too long to show.
- The Automations detail says when a creator plugin was removed or
  disabled.
2026-11-12 05:28:13 -08:00

169 lines
10 KiB
TypeScript

import type { z } from 'zod'
import { PLUGIN_EVENT_PAYLOAD_SCHEMAS, PLUGIN_EVENT_SUMMARIES } from '../events/plugin-events'
import type { PluginErrorCode } from '../frames/plugin-protocol'
import { PLUGIN_EVENT_NAMES } from '../manifest/plugin-manifest'
import { PLUGIN_HOOK_NAMES } from '../contributions/plugin-hook-contribution'
import { PLUGIN_HOOK_DEFAULT_DEADLINE_MS, PLUGIN_HOOK_SPECS } from '../events/plugin-hook-payloads'
import { PLUGIN_HOST_API_MAJOR } from './plugin-host-api-major'
import {
PLUGIN_HOST_API,
PLUGIN_HOST_API_MINOR,
PLUGIN_HOST_METHOD_NAMES,
PLUGIN_STABLE_HOST_METHOD_NAMES,
type PluginHostMethodSpec
} from './plugin-host-api'
import { REFERENCE_TYPE_TEXT, zodTypeText } from './plugin-schema-type-text'
function signature(params: z.ZodType, result: z.ZodType): string {
const input = zodTypeText(params, 'input', REFERENCE_TYPE_TEXT)
// Why parse: a top-level `.optional()` is lost in the type text, yet the call may omit params.
const omittable = params.safeParse(undefined).success
return `(params${omittable ? '?' : ''}: ${input}) => ${zodTypeText(result, 'output', REFERENCE_TYPE_TEXT)}`
}
// Why a Record: a new error code fails typecheck until it is documented here.
export const PLUGIN_HOST_ERROR_CODE_MEANINGS: Record<PluginErrorCode, string> = {
invalid_request: 'the call itself is malformed',
invalid_params:
'params do not match the method, including a field this Orca does not know; the message names it',
unknown_method: 'the method does not exist in this Orca',
capability_denied: 'the manifest does not declare the capability',
consent_required: 'the plugin is disabled or the user has not approved this version',
not_permitted:
'the method or document is not available here, e.g. a worker-only method from a panel',
rate_limited: 'calls arrive faster than the budget; `retryAfterMs` says when to try again',
unavailable: 'the service behind the method is not running yet',
action_failed: 'the method ran and failed',
cancelled: 'the caller aborted the call through its `signal`',
timeout: 'Orca gave up waiting',
conflict:
'the call was made against a stale version, e.g. an editor edit after an outside change',
too_large: 'the message is larger than Orca accepts'
}
const version = (minor: number): string => `${PLUGIN_HOST_API_MAJOR}.${minor}`
/** `workspace:create` (+`agent:launch` for `agent`): a passed param can need a second capability. */
function capabilityCell(spec: PluginHostMethodSpec): string {
const base = spec.capability === null ? 'none' : `\`${spec.capability}\``
const extra = Object.entries(spec.paramCapabilities ?? {}).map(
([param, kind]) => ` (+\`${kind}\` for \`${param}\`)`
)
return `${base}${extra.join('')}`
}
/** Author reference for the host API, rendered from the typed spec table. */
export function renderPluginHostApiReference(): string {
const specs = PLUGIN_STABLE_HOST_METHOD_NAMES.map((name) => ({
name,
...PLUGIN_HOST_API[name]
}))
const proposed = PLUGIN_HOST_METHOD_NAMES.filter((name) => PLUGIN_HOST_API[name].proposed)
const lines = [
'# Orca plugin host API reference',
'',
'<!-- Generated by `pnpm generate:plugin-schemas` from src/shared/plugins. Do not edit. -->',
'',
`Host API ${version(PLUGIN_HOST_API_MINOR)} (\`"pluginApi": ${PLUGIN_HOST_API_MAJOR}\`). Workers call a method with \`await orca.host.call(name, params)\`; panels and custom editors call the same methods through \`window.orca.host.call(name, params)\`. Each method lists the surfaces allowed to call it; any other surface gets \`not_permitted\`. \`orca.host.has(name)\` answers synchronously whether this Orca offers a method on the current surface, and \`orca.api\` is \`{ major, minor }\`. See [Plugin authoring](./plugin-authoring.md) for the frame API.`,
'',
'Every call is checked against the capabilities the user approved, and params are validated before Orca runs anything: params are strict, so a field this Orca does not know is refused with `invalid_params` instead of being dropped. Mutations are recorded in the audit log as `plugin:<publisher>.<id>`.',
'',
'Methods whose capability is `none` need no capability but still need the plugin enabled and approved. `shell.openExternal` and `files.saveAs` also need transient user activation (a click or key press in the calling frame, within a few seconds), are rate-limited, and run only in the desktop app; frames also reach them as `orca.shell.openExternal(url)` and `orca.files.saveAs({ suggestedName, mimeType, data })`, which resolves with `{ status: "saved" }`, or `{ status: "cancelled" }` when the person cancels the dialog. Saved files carry the OS mark for downloaded files.',
'',
'## Methods',
'',
'| Method | Capability | Surfaces | Mutation | Since | Summary |',
'| --- | --- | --- | --- | --- | --- |',
...specs.map(
(spec) =>
`| [\`${spec.name}\`](#${spec.name.replace('.', '').toLowerCase()}) | ${capabilityCell(spec)} | ${spec.surfaces.join(', ')} | ${spec.mutation ? 'yes' : 'no'} | ${version(spec.since)}${spec.deprecatedSince === undefined ? '' : ` (deprecated ${version(spec.deprecatedSince)})`} | ${spec.summary} |`
)
]
for (const spec of specs) {
lines.push(
'',
`### \`${spec.name}\``,
'',
spec.summary,
'',
'```ts',
signature(spec.params, spec.result),
'```'
)
}
if (proposed.length > 0) {
lines.push(
'',
'## Proposed',
'',
'Methods still being designed. Only development plugins (`orca plugin dev`) may call them; any other plugin gets `not_permitted`. They are not frozen: they may change or disappear in any release, they count toward no `api.minor`, and `orca/host` typings omit them.'
)
for (const name of proposed) {
const spec = PLUGIN_HOST_API[name]
lines.push(
'',
`### \`${name}\``,
'',
`${spec.summary} Capability: ${capabilityCell(spec)}; surfaces: ${spec.surfaces.join(', ')}.`,
'',
'```ts',
signature(spec.params, spec.result),
'```'
)
}
}
lines.push(
'',
'## Events',
'',
"A worker receives the events its manifest lists in `contributes.events` through `orca.events.on(event, handler)`, which returns `{ dispose() }`. Each needs `main`, the `trusted-worker` profile and its domain's capability (`workspace:read` or `agent:read`; editor events need none). `orca plugin types` writes the payloads as `PluginEvents` in `orca/host`.",
'',
'| Event | Payload | Summary |',
'| --- | --- | --- |',
...PLUGIN_EVENT_NAMES.map(
(name) =>
`| \`${name}\` | \`${zodTypeText(PLUGIN_EVENT_PAYLOAD_SCHEMAS[name], 'output', REFERENCE_TYPE_TEXT).replaceAll('|', '\\|')}\` | ${PLUGIN_EVENT_SUMMARIES[name]} |`
)
)
const typeCell = (schema: z.ZodType | null): string =>
schema === null
? 'none'
: `\`${zodTypeText(schema, 'output', REFERENCE_TYPE_TEXT).replaceAll('|', '\\|')}\``
lines.push(
'',
'## Hooks',
'',
`A worker changes or stops what Orca is about to do with \`orca.hooks.on(hook, (event, next) => ...)\`, which returns \`{ dispose() }\`. Each hook must be listed in \`contributes.hooks\` (\`main\` and the \`trusted-worker\` profile; no capability). Return \`next(event)\` to go on, with the fields the hook allows changed; return a result such as \`{ deny: reason }\` to stop; return nothing to pass. Plugins run one after another (installed plugins by key, then development folders), then Orca acts on what is left. Orca starts the workers of plugins that list hooks (or status bar items) as soon as they are enabled and keeps them running until they are disabled. A handler that takes longer than ${PLUGIN_HOOK_DEFAULT_DEADLINE_MS / 1000} s, a worker that does not start within the worker ready timeout, a throw, a crash or a disabled plugin counts as having passed, and \`orca plugin logs\` shows the hook, the plugin and how long it took. A guard that must fail closed sets \`"onError": "deny"\` on its \`contributes.hooks\` entry; then those failures refuse the action, naming the plugin. Decide before any other awaited call: an awaited host call ahead of your \`{ deny }\` can fail or time out and let the action through.`,
'',
"Hooks run in the workers of the Orca that handles the request, before it acts: for an SSH or WSL terminal or workspace, that is the desktop, before the work is sent to its host. A paired client reaching a remote Orca server is decided by that server's plugins. `orca plugin types` writes the events as `PluginHooks` in `orca/host`; `orca/testing` `mountWorker(...).hooks.fire(hook, event)` returns what the chain decided.",
'',
'| Hook | Event | Stop result | `next` may change | Summary |',
'| --- | --- | --- | --- | --- |',
...PLUGIN_HOOK_NAMES.map((name) => {
const spec = PLUGIN_HOOK_SPECS[name]
const mutable = spec.mutable.map((key) => `\`${key}\``).join(', ') || 'nothing'
return `| \`${name}\` | ${typeCell(spec.payload)} | ${typeCell(spec.result)} | ${mutable} | ${spec.summary} |`
})
)
lines.push(
'',
'## Errors',
'',
'A failed call rejects with an `Error` carrying `code`, `message`, `retryable` and, for `rate_limited`, `retryAfterMs`. Treat a code not listed here as `action_failed`:',
'',
...Object.entries(PLUGIN_HOST_ERROR_CODE_MEANINGS).map(
([code, meaning]) => `- \`${code}\`: ${meaning}.`
),
'',
'## Stability and deprecation',
'',
'Plugins are in Alpha: the manifest v2 format and catalog format are stable contracts; items listed as experimental in [Plugin authoring](./plugin-authoring.md#stability) may change.',
'',
`- **Host API ${PLUGIN_HOST_API_MAJOR} is frozen.** Within \`pluginApi\` ${PLUGIN_HOST_API_MAJOR}, methods, params and results only grow: a new method or a new optional param arrives with a higher \`Since\` minor, and nothing listed here is removed, renamed or narrowed.`,
'- **Deprecation.** A method to be retired is marked deprecated in this table and keeps working for the rest of the major.',
'- **New majors.** A breaking change ships as a new `pluginApi` major beside the old one. Orca refuses a manifest whose `pluginApi` names a major it does not implement, with "update Orca", instead of loading it against the wrong API.',
'- **Detect, do not assume.** Check `orca.host.has(name)` or `orca.api.minor` before calling a method newer than the oldest Orca you support; a call that slips through fails with `unknown_method`.'
)
return `${lines.join('\n')}\n`
}