QiForge plugin API

Reference for OraclePlugin, the abstract class every plugin extends: required and optional fields, every hook signature, the Workers runtime's metering and turn-gating hooks, defineOraclePlugin and error handling.

This page is the reference for OraclePlugin, the abstract class every QiForge plugin extends. Use it when you write a plugin and need the exact signature of a field or hook, or how the runtime handles a hook that throws.

OraclePlugin declares three required fields (name, version, manifest) and a set of optional hooks the runtime invokes during boot and per request.

import { OraclePlugin } from '@ixo/oracle-runtime';

For a stateless plugin you can skip the class and use the defineOraclePlugin POJO helper instead. Both produce the same internal representation.

OraclePlugin (abstract class)

export abstract class OraclePlugin {
  abstract readonly name: string;
  abstract readonly version: string;
  abstract readonly manifest: PluginManifest;

  readonly dependsOn?: string[];
  readonly softDependsOn?: string[];
  readonly configSchema?: z.ZodObject<any>;

  autoDetect?(env: NodeJS.ProcessEnv): boolean;
  readonly autoDetectHint?: string;

  getTools?(ctx: PluginContext): PluginTool[] | Promise<PluginTool[]>;
  getRequestTools?(rtCtx: RuntimeContext): PluginTool[] | Promise<PluginTool[]>;

  getSubAgents?(ctx: PluginContext): PluginSubAgent[];
  getRequestSubAgents?(rtCtx: RuntimeContext): PluginSubAgent[] | Promise<PluginSubAgent[]>;

  getMiddlewares?(ctx: PluginContext): AgentMiddleware[];

  getSharedState?(): Record<string, (state: any, runCtx: RuntimeContext) => unknown>;

  getNestModules?(ctx?: PluginContext): Array<Type | DynamicModule>;
  getAuthExcludedRoutes?(): AuthExcludedRoute[];
}

Required fields

name
  • Type: string
  • Convention: kebab-case unique identifier.

Used by features, dependsOn, softDependsOn, the app.plugins.status() report, the meta-tools. Boot fails on collision with another plugin's name.

version
  • Type: string

Plugin version. Surfaced in the app.plugins.status() report. Not used for compatibility checking in v1.

manifest
  • Type: PluginManifest

The agent's structured interface to the plugin. See Manifest schema.

Optional fields

dependsOn
  • Type: string[]

Hard dependencies. Boot fails if any listed plugin is not loaded. Used to topologically order plugins.

softDependsOn
  • Type: string[]

Soft dependencies. Your plugin loads either way; the runtime logs one line per missing soft dep at boot. Branch at runtime via ctx.availablePlugins.has(...).

configSchema
  • Type: z.ZodObject<any>

Plugin-owned env vars. Merged with every other plugin's schema and the base Tier-0 schema at boot, then process.env is validated against the result.

autoDetectHint
  • Type: string

Human-readable explanation of what autoDetect checks (e.g. 'REDIS_URL'). Surfaced in boot logs when the plugin is skipped.

Hooks

autoDetect(env)
autoDetect?(env: NodeJS.ProcessEnv): boolean;

Predicate the loader runs when the plugin is left at 'auto' (or has no explicit features entry). Return false to skip the plugin. Plugins without autoDetect are on-by-default.

getTools(ctx)
getTools?(ctx: PluginContext): PluginTool[] | Promise<PluginTool[]>;

Boot-time tools. Called once per request build and cached. Use when registration depends only on config and identity.

getRequestTools(rtCtx)
getRequestTools?(rtCtx: RuntimeContext): PluginTool[] | Promise<PluginTool[]>;

Per-request tools. Called fresh on every agent build with the full RuntimeContext. Outputs are merged with getTools.

getSubAgents(ctx)
getSubAgents?(ctx: PluginContext): PluginSubAgent[];

Sub-agents the runtime auto-wraps as tools. Same call lifecycle as getTools.

getRequestSubAgents(rtCtx)
getRequestSubAgents?(rtCtx: RuntimeContext): PluginSubAgent[] | Promise<PluginSubAgent[]>;

Per-request sub-agents. Merged with getSubAgents.

getMiddlewares(ctx)
getMiddlewares?(ctx: PluginContext): AgentMiddleware[];

LangChain AgentMiddleware instances appended to the stack after the framework's own middleware. Plugin middleware runs last, in topological dependency order across plugins.

The framework's four always-on middlewares, in order, are:

  1. capability-gate: gates on-demand tools by the thread's loadedPlugins.
  2. tool-validation: turns schema errors into recoverable ToolMessages.
  3. tool-repetition-guard: blocks identical repeated tool calls.
  4. tool-retry: retries a failed tool call once.

Two more are conditional, added only when the matching createOracleApp({ hooks }) field is set: page-context (when hooks.getRoomTitle is provided) and safety-guardrail (when hooks.safetyModel is provided). Both run before your plugin middleware.

getSharedState()
getSharedState?(): Record<string, (state: any, runCtx: RuntimeContext) => unknown>;

Read-only accessors this plugin exposes for other plugins to consume via ctx.shared.<key>. Key collisions across plugins fail boot.

getNestModules(ctx)
getNestModules?(ctx?: PluginContext): Array<Type | DynamicModule>;

NestJS modules spread into RuntimeAppModule.imports. Full DI access to Tier-0 services. Use for long-lived services and HTTP controllers.

ctx is optional. Older plugins that omit the argument still work.

getAuthExcludedRoutes()
getAuthExcludedRoutes?(): AuthExcludedRoute[];

Routes contributed by this plugin's controllers that must not pass through AuthHeaderMiddleware. Returns AuthExcludedRoute[] ({ path, method? }). path matches the same way as NestJS MiddlewareConsumer.exclude(...). Use the full path the controller mounts at.

Metering and turn-gating hooks (Workers runtime)

The Cloudflare Workers runtime (@ixo/oracle-runtime-workers 0.58.0 and later) has four hooks for a plugin that meters what a person's use of the oracle costs and refuses turns it will not pay for: a credits plugin, a quota or a suspension. The Node.js runtime (@ixo/oracle-runtime) does not have them. The types are exported from @ixo/oracle-runtime-workers. For a worked plugin, see Meter usage and charge for it.

import type {
  ModelCallReport,
  RuntimeContext,
  TurnGateContext,
  TurnGatePolicy,
  TurnGateResult,
  TurnModelUsage,
} from '@ixo/oracle-runtime-workers';

abstract class OraclePlugin {
  // … the fields and hooks above, plus:
  gateTurn?(ctx: TurnGateContext): TurnGateResult | undefined | Promise<TurnGateResult | undefined>;
  readonly turnGate?: TurnGatePolicy;
  onModelCall?(call: ModelCallReport, ctx: RuntimeContext): void | Promise<void>;
  onTurnUsage?(usage: TurnModelUsage, ctx: RuntimeContext): void | Promise<void>;
  onWake?(ctx: RuntimeContext): void | Promise<void>;
}
HookWhen it runsWhat it gets
gateTurn(ctx)Before every turn starts, on every entryTurnGateContext: who, which entry, ctx.kv, ctx.ucan
onModelCall(call, ctx)After every model call the runtime makes for the person, once per callModelCallReport: purpose, payer, tokens, provider cost, ids
onTurnUsage(usage, ctx)Once per turn attempt, after each of its calls went through onModelCallTurnModelUsage: the attempt's calls and totals
onWake(ctx)When a wake the plugin asked for with ctx.requestWake(at) comes dueThe person's RuntimeContext, with no run

The runtime's own description of these hooks is docs/usage-metering.md in the QiForge repository.

gateTurn(ctx)

gateTurn decides whether a turn may start at all. It runs after authentication and before anything of the turn exists: no run is recorded, no message is stored or mirrored, no file is read, no model is called and no stream is opened. A refused turn leaves nothing to clean up.

ctx.trigger says how the turn started:

triggerThe turn
portalPOST /messages/:sessionId, streamed or not
matrixA message in the person's direct room or one of its threads
matrix-groupA message in a Matrix group room
taskA scheduled task run, a Topic deliverable run, or the approved run of a before-action task
channelA message from the IXO Channels gateway, such as WhatsApp
channel-noticeThe gateway's delivery notice for a blocked file
channel-eventA channel event (permission_answered, identity_check_updated)

The other TurnGateContext fields:

FieldWhat it holds
userdid, matrixUserId and ucanDelegation: the token the Portal sent, or else the delegation the person deposited for this oracle (raw is empty when there is none)
sessionrequestId and client (portal, matrix or channel), plus id, roomId, roomKind (direct or group), taskRunId and channel (provider, bindingId, bindingRevision) when they apply. id is absent on a channel message that opens the binding's first session
modelThe model the request named, when it named one. A byo: id asks for the person's own provider
hasAttachmentsWhether the turn carries files. They are read only after the gate allows the turn
configThe merged, validated environment, as in RuntimeContext.config
kvThe person's durable plugin rows, as in RuntimeContext.kv
ucanThe UCAN helpers bound to this person, as in RuntimeContext.ucan
hasByoCredentials()Whether the person has a bring-your-own model provider connected. It reads the room's secrets index through a 60-second cache. It does not say the turn will use that provider: per call, ModelCallReport.paidBy is the authority
loggerThe plugin logger
signalAborted when the gate's time limit passes or the request goes away
backgroundKeeps un-awaited work alive after the gate returns

Return one of these:

gateTurn is on every turn's path, so keep it cheap. Answer from ctx.kv. A network call is the plugin's choice and counts against its time limit. Nothing on the gate's path makes a network call unless the plugin does.

Several gates compose. Every plugin with gateTurn is asked at the same time, and the answer is the first refusal in plugin order, whichever gate finishes first. Once it is known, the later gates' ctx.signal is aborted, so a gate must not assume earlier gates allowed the turn. Without a refusal, one gate answering platformModels: 'deny' restricts the turn.

These are not new turns and are not gated: a poll of an existing channel request, re-joining a run (GET /runs/:id), a queued run that starts later (it was gated when it was submitted), a run resumed after a reset, and the empty-reply retry inside a channel turn.

turnGate

readonly turnGate?: { onFailure?: 'open' | 'closed'; timeoutMs?: number };

timeoutMs bounds each call of gateTurn: 1,000 ms by default, at most 10,000 ms. ctx.signal aborts at the limit.

A gate that throws, times out or returns something that is not a valid TurnGateResult has failed. With onFailure: 'open' (the default) the turn runs. With onFailure: 'closed' the turn is refused with status 503 and code turn_gate_unavailable. Either way the runtime logs one [turn-gate] warning with the plugin, trigger, request id, failure and policy. Refusals are logged as [turn-gate] refused with the plugin, trigger, request id, status, code and time taken. No user id is logged.

The refusal

interface TurnRefusal {
  status: number;
  message: string;
  code?: string;
  details?: {
    retryAfterSeconds?: number;
    action?: { label: string; url: string };
    [key: string]: unknown;
  };
}
FieldRules
statusAn integer from 400 to 599. It is answered as given when it is 402 (payment needed), 403 (not allowed), 429 (too many) or 503 (try again shortly). Any other status is answered as 403 and logged
message1 to 2,000 characters. It is shown to the person as is, on every surface: plain text, complete on its own, short, with no URL inside. Put a link in details.action
codeOptional. Matches [a-z][a-z0-9_]{0,63}. Keep it stable: clients choose how to present a refusal by its code, and the Matrix and channel gateways throttle repeated notices per code
detailsOptional JSON, at most 4 KiB serialised
details.retryAfterSeconds"Try again in about N seconds": a number from 1 to 86,400, rounded up to a whole number. Shown on every surface
details.actionOne call to action. url must be https:; label is 1 to 40 characters after trimming. Shown on every surface

An invalid retryAfterSeconds or action is removed from the refusal and logged. The refusal still stands. Other details keys reach the Portal only, as sent.

How a refusal reaches the person

EntryWhat the runtime does
portalAnswers the HTTP request with the refusal's status and the JSON body below, the x-request-id header, and Retry-After when details.retryAfterSeconds is set. No SSE stream is opened
matrix, matrix-groupThe Matrix gateway posts one m.notice in the message's thread. Its body is message, then <label>: <url> on its own line when there is an action. Its formatted_body has the action as a link. In a group room the notice starts with a mention of the refused person (m.mentions.user_ids and a matrix.to pill); a direct room has no mention
taskThe run is skipped. Its ledger row is failed with the detail refused before it started (<status> <code>): <message>, the task's lastResult is Skipped: <message>, and the schedule moves to its next occurrence with no backoff and no failure counted. A task the refusal ends (a one-shot, or a schedule with no next occurrence) posts one notice in its room, with the action as a link. A recurring task that moves on posts nothing
channel, channel-notice, channel-eventAnswers the IXO Channels gateway with the refusal's status and a turn_refused body (below). The gateway sends message to the person as one reply, with the action as a link button where the channel has one (for example WhatsApp), or else as <label>: <url> text. Nothing is recorded, so the same request id may be resent

Matrix sends at most one notice per room, person and code in 10 minutes. A refused message inside that window gets no reply, and a turn that runs for that person in that room clears the window. The channel gateway keeps the same rule per binding, sender and reason.

The Portal body (TurnRefusalBody):

{
  "statusCode": 402,
  "message": "You're out of IXO credits. Top up to keep chatting.",
  "code": "insufficient_credits",
  "details": {
    "retryAfterSeconds": 60,
    "action": { "label": "Top up credits", "url": "https://portal.qi.space/wallet?topup=1" }
  },
  "requestId": "<request-id>",
  "refused": true
}

refused: true marks a turn that a plugin's gate refused, whatever its status and code. It is never an authentication failure: a client must not renew credentials, or ask the person for their PIN, on a 403 that carries it, and shows message instead. Only a gate refusal carries the marker, so a client needs no list of plugin codes. @ixo/oracles-client-sdk 1.10.0 and later surfaces such an answer at once, without renewing. See Errors.

The channel body keeps its own shape. code: "turn_refused" is its marker, reason is the plugin's code, and reason, retryAfterSeconds and action are omitted when the refusal has none:

{
  "code": "turn_refused",
  "reason": "insufficient_credits",
  "message": "You're out of IXO credits. Top up to keep chatting.",
  "retryAfterSeconds": 60,
  "action": { "label": "Top up credits", "url": "https://portal.qi.space/wallet?topup=1" }
}

Allow a turn on the person's own provider only

{ allow: true, platformModels: 'deny' } lets the turn run, but nothing of it may use the platform's model key (the oracle's OpenRouter or Nebius key, and its Decision provider). Use it for a person who may use their own provider but not the platform's, for example when they are out of credits. The restriction is stored with the run, so a queued or resumed attempt keeps it.

Part of the turnUnder platformModels: 'deny'
The turn as a wholeRuns only when it would run on the person's provider. When it would not (no provider connected, the request names a platform model, the credential could not be read), it fails before any model is called, with PlatformModelsDeniedError
main, summarizer, sub-agents, plugin ctx.llm, the safety modelRun on the person's provider when it serves the role. A role it does not serve (for example vision on DeepSeek) gets a model whose every call fails with PlatformModelsDeniedError
A bring-your-own model the provider refusesNo platform fallback: the provider's error ends the call
Session titleNot generated. A later turn without the restriction titles the session
Attachments, view_attachment, memory document ingestPlain-text files are still read. Nothing is sent to the extraction model: the model is told it could not read each such file
Capability routerNo Decision: nothing is preloaded, and the model loads capabilities with load_capability
Channel conversation routingNo Decision: the message stays in the current conversation
ctx.decisions, an event turn's handleChannelEventctx.decisions rejects with DecisionProviderUnavailableError; an event turn's plugin ctx.llm is denied
Group-room summaryNot a turn, so not affected

A model a plugin builds itself without ctx.llm is not covered: the runtime cannot see it.

onModelCall(call, ctx)

Every model call the runtime makes for a person ends in one ModelCallReport, delivered once to each plugin's onModelCall, after the call ended or failed. The hook runs in the background and never delays the turn. A hook that throws is logged and ignored. Do not call a model inside it: such a call is not reported.

FieldMeaning
purposeWhat the call was for (next table)
paidByplatform (the oracle's key) or user (the person's own provider: do not charge for it)
callIdUnique per call attempt and reported once: the idempotency key of a charge. A retried or fallback attempt is a new call with its own id
startedAt, durationMsStart time in epoch milliseconds, and duration
role, requestedModel, servedModel, provider, generationIdThe model role and models. servedModel and provider are as the provider reported them
promptTokens, cachedTokens, cacheWriteTokens, outputTokens, reasoningTokensToken counts, as reported
costUsdThe provider-reported cost only (OpenRouter returns it on every response). The runtime never computes a price: it is absent for Nebius, bring-your-own and Decision calls, and for calls that failed before usage arrived. Price those yourself; the runtime exports fetchOpenRouterPrices for list prices
usageEstimatedtrue when the token counts are an estimate (below)
fallback, modelFallback, providerFallbackWhether an OpenRouter model or provider fallback answered
ok, finishReason, errorKind, errorStatus, errorCodeThe outcome

The report holds no message content, tool arguments or user ids.

purposeThe call
replyThe main agent's model, task runs, the empty-reply retry
summarizationHistory compaction
subagentA plugin sub-agent's model
pluginA plugin's ctx.llm call in a tool, middleware, request hook or handleChannelEvent
attachmentReading a file into text: the turn's attachments, view_attachment, memory document ingest
titleThe session title written after the turn
routingThe capability router's Decision, and channel conversation routing
decisionA plugin's ctx.decisions evaluation
safetyThe host's safetyModel hook model
group-summaryA Matrix group room's summary, run in the latest speaker's object
otherA model handed out without a known use, such as a host getRoomTitle hook's model

The full list is exported as MODEL_CALL_PURPOSES.

ctx is the turn's (ctx.session.requestId, ctx.session.runId, ctx.user.did, ctx.user.ucanDelegation, ctx.kv, ctx.background). For a call outside a turn (a group-room summary, channel routing before a run exists), ctx.user is the person the object serves and ctx.session.requestId is the channel request's id or an id of the call's own.

A streamed platform call that failed or was aborted after output started, before the provider's usage arrived, carries an estimate: usageEstimated: true, prompt and output tokens counted as characters divided by 4 (tool schemas are not counted), and no costUsd. Price it from the model's list price. A stream that failed before any output carries no tokens.

These calls are not reported: a model a plugin builds without ctx.llm; a call made inside onModelCall or channelFailureReply; the OpenAI client's own retries inside one call (one report, with the final attempt's usage); the refused attempt of a bring-your-own model that the platform then answered (one report, the platform's); and a streamed call whose consumer stops reading without an error.

onTurnUsage(usage, ctx)

onTurnUsage runs in the background once per attempt of a turn, after the attempt ended and every call it made has been through every plugin's onModelCall, the session title included. It waits at most 60 seconds for slow onModelCall hooks, then reports without them and logs it.

interface TurnModelUsage {
  requestId: string;
  runId: string;
  sessionId: string;
  status: 'finished' | 'failed' | 'aborted' | 'interrupted';
  calls: readonly ModelCallReport[]; // in the order they ended
  platformCostUsd: number;           // sum of costUsd over platform-paid calls that reported one
  unpricedPlatformCalls: number;     // platform-paid calls with no costUsd
}

It fires for every attempt that built the agent, and for an attempt that ended earlier but made calls (for example an event turn a plugin decided with ctx.llm). It does not fire for an attempt that made no call and never built the agent, such as a refused turn.

Every call whose ctx.session.runId is set is in exactly one onTurnUsage, so a plugin may meter in-turn calls from onTurnUsage alone and use onModelCall only for calls without a run. The exception: an attempt the object stops in the middle (a deploy, an eviction, a reset) gets no report. Its calls reached onModelCall only, and the run resumes as a new attempt with its own report.

onWake(ctx) and ctx.requestWake(at)

ctx.requestWake(at) asks the host to wake the person's object no earlier than about at (epoch milliseconds) and call every plugin's onWake then, without a request from the person. Use it to retry work the person left pending, such as an unsent usage event. It is present on the Workers runtime when some plugin defines onWake, and can be called from any hook.

  • Several requests keep the earliest. A wake fires once, so onWake asks again for the next one.
  • onWake(ctx) runs in the object's housekeeping alarm. ctx.user is the person the object serves, with their deposited delegation when there is one. ctx.session.id is empty and there is no run.
  • Each onWake call may take at most 30 seconds. After that it is left running and the alarm moves on. A hook that throws is logged and ignored.
  • A pending wake does not keep an idle object alive. When the person has been away long enough for the object to evict its working copy (5 days without a request), the wake is dropped. The plugin's next hook for that person, at their next turn, is where pending work resumes.
  • Each wake may open the person's database, so ask for wakes sparingly: back off, do not poll.

defineOraclePlugin

For plugins without constructor args, the POJO form:

import { defineOraclePlugin } from '@ixo/oracle-runtime';

export default defineOraclePlugin({
  name: 'hello',
  version: '0.1.0',
  manifest: { /* ... */ },
  getTools(ctx) { /* ... */ },
});

defineOraclePlugin is an identity function: it returns its argument with type-checking applied. The resulting object is interchangeable with a class instance for everything the runtime does.

Error handling

If a hook throws at request build time, the runtime logs the error with the plugin name and skips that plugin's contribution for that request. The rest of the agent build continues. Same Promise.allSettled semantics for sub-agent init.

Boot-time errors in autoDetect, configSchema validation, or manifest validation fail boot loudly.