Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

6.6 KB
Raw Blame
import { z } from 'zod'
import type { PluginErrorCode } from '../frames/plugin-protocol'
import { PLUGIN_HOST_API_MAJOR } from './plugin-host-api-major'
import { PLUGIN_HOST_API, PLUGIN_HOST_API_MINOR, PLUGIN_HOST_METHOD_NAMES } from './plugin-host-api'

type JsonSchema = z.core.JSONSchema.BaseSchema

function asSchema(node: z.core.JSONSchema._JSONSchema | undefined): JsonSchema {
  return typeof node === 'object' ? node : {}
}

/** TypeScript-like type text, so a method reads as a signature rather than a JSON Schema dump. */
function typeText(schema: JsonSchema): string {
  if (schema.const !== undefined) {
    return JSON.stringify(schema.const)
  }
  if (schema.enum) {
    return schema.enum.map((value) => JSON.stringify(value)).join(' | ')
  }
  if (schema.anyOf) {
    return schema.anyOf.map((node) => typeText(asSchema(node))).join(' | ')
  }
  if (schema.type === 'array') {
    const item = typeText(asSchema(Array.isArray(schema.items) ? undefined : schema.items))
    return item.includes(' ') && !item.startsWith('{') ? `(${item})[]` : `${item}[]`
  }
  if (schema.type === 'object' && schema.properties) {
    const required = new Set(schema.required ?? [])
    const fields = Object.entries(schema.properties).map(
      ([key, node]) => `${key}${required.has(key) ? '' : '?'}: ${typeText(asSchema(node))}`
    )
    return fields.length === 0 ? '{}' : `{ ${fields.join('; ')} }`
  }
  if (schema.type === 'object' && typeof schema.additionalProperties === 'object') {
    return `Record<string, ${typeText(schema.additionalProperties)}>`
  }
  if (schema.type === 'integer') {
    return 'number'
  }
  if (Array.isArray(schema.type)) {
    return schema.type.join(' | ')
  }
  return schema.type ?? 'JSON'
}

function signature(params: z.ZodType, result: z.ZodType): string {
  const options = { target: 'draft-2020-12', unrepresentable: 'any' } as const
  const input = z.toJSONSchema(params, { ...options, io: 'input' })
  const output = z.toJSONSchema(result, { ...options, io: 'output' })
  return `(params: ${typeText(input)}) => ${typeText(output)}`
}

// Why a Record: a new error code fails typecheck until it is documented here.
const ERROR_CODES: 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}`

/** Author reference for the host API, rendered from the typed spec table. */
export function renderPluginHostApiReference(): string {
  const specs = PLUGIN_HOST_METHOD_NAMES.map((name) => ({ name, ...PLUGIN_HOST_API[name] }))
  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',
    '',
    '| Method | Capability | Surfaces | Mutation | Since | Summary |',
    '| --- | --- | --- | --- | --- | --- |',
    ...specs.map(
      (spec) =>
        `| [\`${spec.name}\`](#${spec.name.replace('.', '').toLowerCase()}) | \`${spec.capability}\` | ${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),
      '```'
    )
  }
  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(ERROR_CODES).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`
}