Reference

Plugins

Built-in plugins that extend the Routecraft runtime, and the full plugin API: the descriptor, the plugin context, the lifecycle and its faults, ports, hooks, steps and facets.

  1. 01
    llmPluginLanguage models.@routecraft/ai

    Configure provider keys, default models, and global LLM defaults for every agent and llm() call in the context.

  2. 02
    embeddingPluginVectors.@routecraft/ai

    Wire an embedding provider for the embedding() destination and downstream clustering with cosine().

  3. 03
    mcpPluginMCP server runtime.@routecraft/ai

    Expose mcp() capabilities over Model Context Protocol, with JWT, OAuth 2.1, and bearer-token verification built in.

  4. 04
    agentPluginAgent registry and harness.@routecraft/ai

    Register named agents, the tools they can call, and shared defaults like system prompt and principal context.

  5. 05
    acpPluginEditor protocol mount.@routecraft/ai

    Serve the Agent Client Protocol so a person can talk to this instance's agents from their editor, on the same server and behind the same wall as everything else.

  6. 06
    httpPluginHTTP routing.@routecraft/routecraft

    Expose routes over HTTP via the http() source, mounted as the catch-all surface on a named server; JWT, JWKS, or API-key auth at the plugin boundary.

  7. 07
    serversPluginNamed listeners.@routecraft/routecraft

    Declare the HTTP listeners the app binds, by name. HTTP, MCP, and custom plugins mount paths on a shared listener; a surface gets a dedicated port by declaring another named server.

  8. 08
    opsPluginHealth and readiness.@routecraft/routecraft

    Serve liveness, readiness, and operational health, mounted on a named server. Route lifecycle and circuit-breaker state are derived from events the framework already emits; indicators cover dependencies it cannot see.

  9. 09
    shellPluginshell() context defaults.@routecraft/os

    Set context-wide defaults for shell(): isolation tier, timeout, and output cap. The lowest of the three precedence layers, under the ROUTECRAFT_SHELL_ISOLATION operator override and the call site.

  10. 10
    remotesPluginRoutes of other instances.@routecraft/routecraft

    Name other running instances, and every dispatchable route they expose through the ops management API becomes a direct endpoint here, for direct(), forward(), agent tools and the local ops listing alike.

Note

Core adapter defaults (cron, direct) are set with dedicated CraftConfig fields. Each field installs the adapter's plugin for you, so you never list it in plugins. See Configuration and Merged Options.

How to write a plugin, with a worked example for each part, is on the Plugins guide. This page lists every field, member and fault.

First-class config keys

A config key installs the matching plugin with its options. Importing @routecraft/ai augments CraftConfig with keys for the AI plugins: setting llm, mcp, embedding, agent, or sessions is equivalent to listing the corresponding plugin in plugins (sessions maps to sessionsPlugin, documented under Configuration). The plugin's lifecycle and events are identical either way. A key and an explicit plugin for the same feature are two installations of one id and fail with RC1101.

Recommended for declarative configuration:

import { defineProject } from '@routecraft/routecraft'
import '@routecraft/ai' // augments CraftConfig

export default defineProject({
  llm: { providers: { openai: { apiKey: '...' } } },
  mcp: { clients: {} },
})

The factories remain available, for a plugin instance you build once and reuse, or for programmatic composition:

import { defineProject } from '@routecraft/routecraft'
import { llmPlugin, mcpPlugin } from '@routecraft/ai'

export default defineProject({
  plugins: [
    llmPlugin({ providers: { openai: { apiKey: '...' } } }),
    mcpPlugin({ clients: {} }),
  ],
})

defineProject

defineProject({ plugins, ...config }) declares a project and returns { craft, config, plugins }. craft.config.ts default-exports it, and craft start reads that export.

MemberTypeMeaning
craft()() => PreFromBuilderA route builder typed by exactly the installed plugins plus the default plugins. A step or facet of a plugin the project does not install is a compile error.
configCraftConfigThe configuration to start the application with, plugins included. Pass it to ContextBuilder.with() or testContext().with().
pluginsreadonly Plugin[]The plugins the project lists, as given.

A misspelled config key is a compile error, at the top level and inside each config block. A config key that installs a plugin with steps or a facet (deferral) types the project's routes when it is set: the package registering the key merges its plugin type into ConfigKeyPlugins, so a third-party key gets the same typing as a first-party one. The root craft() export is typed by the plugins @routecraft/routecraft ships; a route that uses an uninstalled plugin's step refuses to start with RC1111, and reading an uninstalled plugin's facet fails with the same code.

The command line reads a project and nothing else: craft.config.ts default-exports defineProject(...), and a plain object or a named craftConfig export is refused with RC1120. craft run <file> runs the file's routes in the project they were built with, or in the craft.config that extends it. A context built in code takes a plain CraftConfig, and project.config is one.

Plugin descriptor

definePlugin(descriptor) returns the descriptor unchanged, keeping its literal types.

FieldTypeMeaning
idstringDotted identity, unique per application: routecraft.deferral, acme.approvals. A duplicate is RC1101.
namespacestringThe prefix the plugin's facet, route options and events live under. Defaults to the last segment of id; unique per application (RC1102).
requiresPort[]Ports the plugin cannot run without. A missing provider is RC1104.
optionalPort[]Ports the plugin uses when present, read with lookup().
providesPort[]Ports the plugin provides in bind. Two providers of one port is RC1105.
replacesPort[]Ports whose other provider this plugin displaces. Each must also be in provides (RC1106). The displaced plugin still binds, starts and stops: replacing a port selects a provider and never removes a plugin, so a displaced plugin that owns a resource (the servers listener) keeps it, and an application that wants it gone leaves its config key out.
installsPlugin[]Plugins this one brings along, installed ahead of it and once per id, unless the application lists that id itself. Two bundles bringing different descriptors under one single id the application does not list is RC1101; repeatable descriptors under one id each install, numbered.
secretHeadersstring[]Header names that carry a secret this plugin puts on exchanges. Left out of every event snapshot, and out of the record a deferral writes, beside Authorization, Cookie, Set-Cookie, Proxy-Authorization and X-Api-Key. Matched in any letter case and at every depth of a header's value. It does not govern logs: a log line is redacted by the logger's redact paths.
repeatablebooleanSeveral installs may coexist, named id#1, id#2, ... in list order. A repeatable plugin may not provide or replace a port, or declare hooks, points, steps or a facet. It binds ahead of every other plugin that uses the ports it uses, so a reader sees every contribution, unless that order would contradict the declared dependencies.
keepsAlivebooleanThe plugin owns a lifetime past the routes (a listener, a subscription): when every route has completed, the application keeps running until stopped.
hooksHooksHooks in the chain's slots, or at a point another plugin declares.
points{ name: string }[]Moments this plugin declares and invokes from its own steps, where other plugins add hooks.
stepsRecord<string, StepFactory>Route methods this plugin adds, by name. See steps.
facet(exchange) => viewWhat ex.<namespace> reads. See facets.
tooling{ commands?, logins? }What the plugin gives the tools around an application: commands for craft, and logins for craft connect. Read without binding. See tooling.
bind(c)(c: PluginContext) => void | Promise<void>Require, provide, observe, register routes. Runs in dependency order.
start(c)(c: PluginContext) => void | Promise<void>Begin work that needs running routes. Awaited.
stop(c, info)(c: PluginContext, info: StopInfo) => void | Promise<void>Release what bind and start acquired. Reverse order.

Plugin context

bind, start and stop receive a PluginContext. A plugin never receives the CraftContext.

MemberMeaning
id, namespaceThe plugin's own id and namespace.
loggerA Logger: a child of the context's, carrying the plugin id.
require(port)The provider of a port declared in requires or optional. Throws RC1108 for an undeclared port and RC1104 when an optional port has no provider.
lookup(port)Like require, but undefined when an optional port has no provider.
provide(port, value)Provide a port declared in provides. In bind only: RC1109 for an undeclared port, RC1110 after the application froze.
observe(event, handler, options?)Subscribe to an event; { snapshots: true } asks for each event's _snapshot. Returns the unsubscribe function, for a subscription that ends before the plugin does; every subscription is released with the plugin at stop, so none needs tracking.
emit(event, details, exchange?)Emit an event. Any name the EventDetailsMap declares is accepted, the framework's included, so a plugin emits under its own names (declared by augmenting EventDetailsMap) and never poses as the framework to telemetry or audit. An event about an exchange names it by exchangeId in the details and hands the exchange itself as the third argument: no handler receives it, and a subscription made with { snapshots: true } gets a frozen copy as details._snapshot.exchange, except on route:exchange:started and route:exchange:deferred, which carry no snapshot. See snapshots.
onDispose(fn)Register a release that runs at stop, after the plugin's own stop, in reverse registration order. Every one runs even when another throws, and they run when this plugin's own bind throws after registering them.
frozenTrue once the last bind returned. A plugin that collects contributions through its port refuses later ones with RC1110.
routes.register(...definitions)Add routes. In bind only (RC1110 afterwards).
routes.list(), routes.get(id)Read-only views of registered routes: id, definition, enabled, disabledReason. The definition is read-only down the graph, at the type and at runtime: a write through it is RC1110.
routes.hooksOf(id)The hooks that apply to a route in the order they run, each as { slot, point, phase?, plugin, id }. Empty before the routes compile.
routes.canDefer(id)Whether an exchange on this route can park: it has a .defer(), a step that declares defers, or an error hook declared with mayDefer whose routes and tags select it. What a door reads to advertise a Deferred answer. False for an unknown id. Complete from start on: during bind the hooks are not placed yet, so a route that parks only through an error hook reads false.
applicationThe key of the application this plugin is bound in. What applicationState() files a value under.
continuationsReading and driving parked exchanges, below.
executionThe verbs that drive the application, below.

Execution

MemberMeaning
deliver(endpoint, body, headers?)Hand a body to the route listening on a direct() endpoint and resolve with its reply, typed unknown for the caller to narrow. RC5004 when nothing listens.
trackTask(task, { route }?)Background work the application waits for when it drains. Name the route it belongs to and that route drains it before it stops. A rejection is logged, never thrown.
capabilities()Discoverable capabilities of the enabled routes.
whenStarted()Resolves once every route signalled readiness and every start returned.
requestStop()Ask the application to stop. Returns at once; never await a stop from inside a lifecycle function.

Continuations

c.continuations is the one way a plugin reads or drives a parked exchange. It is two tiers: a read-only view, which an adapter also reaches with continuationsOf(exchange), and the acts, which only a plugin holds.

MemberTierMeaning
availableviewWhether the application has a CONTINUATIONS provider. Every other member is RC5052 without one, except verifyToken, which answers undefined.
get(id)viewThe record, with stepState, meta and the settled outcome decoded to the values the route held.
list(query)viewRecord summaries, newest first.
verifyToken(token)viewThe deferral id a token names, or undefined when this application did not mint it. Never throws.
deferredPrincipal(record)viewThe principal the exchange parked with, restored and marked as restored.
reidentificationDeviation(parked, live)viewWhy a live principal is not the parked identity, or undefined when it is.
eventScope(record)viewThe exchange fields an event about this record carries.
resume(request, { reidentified }?)actResume a parked exchange by its token on the plugin's own behalf, with no ingress door and no live principal. reidentified runs the continuation as the identity the exchange parked with, re-verified from live state by the plugin; a restored principal, or one that deviates, is RC5056.
sweep({ boot? })actRun one pass of the kernel's sweep: heal stale claims, purge settled records past retention, retire overdue ones through each route's error channel. Resolves with how many were retired.
mintToken(id, { callBinding }?)actA resume token for a record. Whoever holds it can resume the exchange, so a plugin hands it only to the party it means to.
rewriteStepState(id, rewrite)actReplace what a "this-step" site stored, by compare-and-swap.

A step never calls resume to answer a caller: it declares resumes and is handed ctx.resume, which records the principal the route verified.

Per-application state

A plugin descriptor may serve more than one application in a process, so a value a plugin's adapters need is kept per application, never in a module variable.

A value another plugin may use or replace is a port. An adapter reads it with lookupOf(exchange, PORT), which resolves the way context.lookup(PORT) does for the application the exchange runs in, replaces included, and is undefined when nothing provides it.

State private to one module is an applicationState<T>() holder:

MemberMeaning
set(application, value)Keep a value for an application. Called in bind with c.application.
get(application)Read it by key: c.application in a plugin, context.application in a source.
of(exchange)Read what the application an exchange runs in holds. What an adapter calls.

set replaces what the application held and is not tied to a lifecycle stage. The value is released with the application, because the holder keeps it weakly under the key. applicationOf(exchange) returns the key itself.

Lifecycle

FunctionRunsThe routes areUse it for
bind(c)While the application is installed, in dependency order, before any route is registeredNot registered yetRequiring and providing ports, resolving config, opening resources, observing events
start(c)After every route has startedRunningWork that drives routes or needs them able to serve
stop(c, info)During shutdown, or when an install or start failed partwayStopping, stopped, or never startedReleasing what bind opened, stopping what start began

The stages an application goes through, and the fault each one raises:

StageWhat happensFaults
1. IdentityOne plugin per id, one per namespace, one key per port name, the one port() mints.RC1101, RC1102, RC1103
2. ResolutionEvery required port resolves to exactly one provider.RC1104, RC1105, RC1106
3. OrderA topological sort over requires and optional; a repeatable plugin binds ahead of every other consumer of the ports it uses; ties keep list order. Default plugins come first.RC1107
4. BindEach plugin's bind runs in that order and must provide what it declared.RC1108, RC1109
5. FreezeNothing more is accepted: ports, routes, hooks.RC1110
6. CompileRoutes register; every hook is placed; every position and plugin step a route uses must have a provider.RC1111, RC1112, RC1113, RC1114, RC1115, RC1116
7. StartRoutes start and signal readiness, then each plugin's start.
8. StopReverse dependency order, consumers before providers; failures aggregated.

Stages 1 to 3 run before any plugin binds, so their faults leave nothing to release. Each lifecycle function is awaited before the next plugin's runs. Events plugin:binding / plugin:bound bracket bind, plugin:starting / plugin:started bracket start, and plugin:stopping / plugin:stopped bracket stop (see plugin events).

A throwing start fails context.start() with the original error, and every bound plugin is stopped in reverse order before it surfaces, including plugins whose start never ran. A failure during bind or route registration unwinds the same way: only plugins whose bind returned are stopped, and the original error surfaces unchanged even if a stop throws on the way out.

A stop that lands mid-boot waits for the lifecycle function still running before it stops that plugin, so a plugin always observes its function entered, settled, then stop. No lifecycle function runs once the stop walk has begun.

To abort a boot, throw. To stand the application down without failing the boot, call c.execution.requestStop(), which returns at once. A lifecycle function must never wait for the application's own stop: the stop waits for the function, and neither settles.

stop receives a second argument describing how far the application got:

FieldMeans
partialThis is not a fully started application: it never started (an install that failed partway, or an embedder that built and stopped without calling start()) or a start threw. Routes may not be registered and later plugins may never have bound.
startedThis plugin's own start returned. Always false for a plugin with no start, and during an install-failure unwind.

A plugin that only closes what bind opened can ignore both. A plugin that stops what start began reads started.

start is awaited, so the application is not ready until every start has resolved. Use it for startup work that finishes, and begin unbounded work (a poll loop, a subscription) there without awaiting it. A plugin descriptor may serve more than one application in a process, so per-run state is released with c.onDispose() or keyed by the PluginContext, never held in a closure slot.

Note

Waiting for a context to be ready

ctx.start() resolves when the context stops, not when it comes up: a context with an indefinite route (an HTTP server, a direct() endpoint) keeps running. Await ctx.whenStarted(), or c.execution.whenStarted() from a plugin, for readiness. It resolves once no route is still coming up and every start has finished, and rejects if a start or the config refuses. A single route failing to come up is not observable there, since the context keeps the others running.

Ports

port<T>(name) declares a port. The name is owner.capability@version in lowercase dotted segments; anything else is RC1103. Call it once at module scope and export the token: the identity is the name, so two copies of the declaring module resolve as one port; two tokens with one name but different keys in one application are RC1103. Load one build of one install per process: ports resolve across copies, but the refusal a door answers is bound in the copy that raised it, and the context warns at build when it finds more than one copy.

Adapters read a port at runtime through the context they run in, with context.require(port) or context.lookup(port).

The ports the framework ships:

TokenNameProvided by
DIRECTroutecraft.direct@1routecraft.direct
RESILIENCEroutecraft.resilience@1routecraft.resilience
CACHE_STOREroutecraft.cache-store@1routecraft.cache
AUTHORITYroutecraft.authority@1routecraft.principals
ENFORCEMENTroutecraft.enforcement@1routecraft.auth
CONTINUATIONSroutecraft.continuations@2routecraft.deferral
WEB_INGRESSroutecraft.web-ingress@1routecraft.servers
HTTProutecraft.http@1routecraft.http
OPSroutecraft.ops@1routecraft.ops
REMOTESroutecraft.remotes@1routecraft.remotes
CREDENTIALSroutecraft.credentials@1routecraft.credentials (default; see credentials)
CRON_DEFAULTSroutecraft.cron.defaults@1routecraft.cron
MAILroutecraft.mail@1routecraft.mail
CARDDAVroutecraft.carddav@1routecraft.carddav
AGENTSroutecraft.ai.agents@1routecraft.ai.agent (@routecraft/ai)
SESSION_STOREroutecraft.ai.session-store@1routecraft.ai.sessions (@routecraft/ai)
MCProutecraft.ai.mcp@1routecraft.ai.mcp (@routecraft/ai)
LLMroutecraft.ai.llm@1routecraft.ai.llm (@routecraft/ai)
EMBEDDINGroutecraft.ai.embedding@1routecraft.ai.embedding (@routecraft/ai)
SURFACESroutecraft.ai.surfaces@1routecraft.ai.surfaces (@routecraft/ai)
SHELLroutecraft.os.shell@1routecraft.os.shell (@routecraft/os)

The version in a port's name is its contract. The value a consumer reads under name@1 keeps its shape for as long as that name exists; a change of shape ships as name@2, a different port. A replaces that names a version nobody provides while another version of the port is installed is RC1119, and an unmet requires names the installed version in RC1104. RESILIENCE and ENFORCEMENT are provisional in 0.8 and outside that promise: both are due to be reshaped, so a plugin that replaces either pins the Routecraft minor it was written against.

RESILIENCE and ENFORCEMENT fill the chain's route-scope positions. The default providers are exported as resilienceProvider and enforcementProvider, so a replacement can delegate to them. CACHE_STORE is where a .cache() that names no provider keeps its entries: a CacheProvider, in memory by default. The cache's policy (the key, when, which outcomes are stored, the events) is the framework's at both scopes and no port replaces it. A step-scope wrapper (.retry() and the rest called after .from()) resolves the same provider when the exchange runs, so a replacement fills both scopes (see Slots). A plugin that replaces a port is named once at boot, at warn for AUTHORITY and ENFORCEMENT.

AUTHORITY decides who an exchange acts for and whether to trust it. It provides mint(claims), brand(principal), isAuthentic(principal), restore(record), isRestored(principal) and read(exchange). authorityOf(exchangeOrContext) returns the application's authority. Every mint and every check goes through it, so a replacement decides both sides; delegate() and the ingress mounts take the authority explicitly rather than assuming the default. defaultAuthority is exported for a replacement that decorates it.

Default plugins

Installed in every application, ahead of its own plugins:

PluginFactoryProvidesSteps and facet
routecraft.directdirectPlugin()DIRECT
routecraft.resilienceresiliencePlugin()RESILIENCE
routecraft.cachecachePlugin()CACHE_STORE
routecraft.principalsprincipalsPlugin()AUTHORITY
routecraft.authauthPlugin()ENFORCEMENTsteps authenticate, delegate; facet ex.auth
routecraft.credentialscredentialsPlugin()CREDENTIALS

An application plugin with the same id takes a default's place. A plugin that declares replaces for a default's port is selected over it while the default still binds. The deferral plugin (routecraft.deferral, installed by the deferral config key) adds the defer and resume steps and the ex.deferral facet.

Hooks

Slots

The chain around every route runs in a fixed order. Positions belong to the framework and hold one thing each; a plugin can replace what fills a position through its port, but cannot move, remove or add one. Slots sit between positions, and any number of plugins add hooks there.

In orderKindFilled by
errorslothooks; the route's own .error() runs first
beforeAuthslothooks
authorizepositionENFORCEMENT
afterAuthslothooks
parse, inputpositionsthe kernel; not replaceable
admittedslothooks
throttle, circuitBreaker, retrypositionsRESILIENCE
perAttemptslotwrappers
timeout, concurrencypositionsRESILIENCE
cacheCheckpositionthe kernel, over CACHE_STORE
the pipelinethe route's steps
cacheStorepositionthe kernel, over CACHE_STORE
exitslothooks, over completed exchanges only

SLOTS exports the slot names in order. A hook in a slot or point that does not exist is RC1112.

The resilience methods and .cache() placed after .from() are the same positions around one step. The wrapper resolves the same provider when the exchange runs, with scope: "step" and the step's label on the PositionRun ("route" and "route" at route scope), so a plugin replacing RESILIENCE fills both scopes; throttle(options, scope) takes the scope. The cache positions are the kernel's at both scopes and keep their entries in the same CACHE_STORE. A route with a step wrapped in a method no installed plugin provides refuses to start with RC1111; a .cache({ provider }) brings its own store and needs no CACHE_STORE.

Phases

PhaseMayEnforced
observereadreturning anything but undefined is RC1115
mutatereturn { headers?, body? } to change the exchange, or nothingwriting an engine-owned header (routecraft.id, routecraft.route, routecraft.operation, routecraft.split_hierarchy, routecraft.correlation_id, routecraft.causation_id, routecraft.trace.parent, routecraft.journey.joined) is RC1115. A body patch is applied as returned and never re-validated: in beforeAuth and afterAuth the route's .input() validates it afterwards, in admitted and exit it is trusted, so a hook there adds to the validated shape rather than replacing it, and a hook that must replace the body belongs in afterAuth
validatereturn nothing to allow, or refuse(reason, { kind? }) to refusereturning anything else is RC1115; a refusal fails the run with RC5068, and a door answers the caller with the kind (invalid, unauthenticated, forbidden by default, not_found, conflict, gone, rate_limited, unavailable) and the reason. A route's own .validate() step refuses the same way, by returning or throwing refuse()

A slot runs observe, then mutate, then validate. exit has no validate phase. In the error slot the phases are observe and mutate, and mutate is the deciding phase: a hook answers with a recovery body, recovery.drop(), recovery.defer(...) or recovery.rethrow(), or undefined to pass, and the first answer decides. Inside a phase, hooks run in the order the application lists the plugins. When two mutate hooks write the same header in one slot, the later wins and the framework warns once per route naming both.

perAttempt takes wrappers rather than phased hooks: { wrap(proceed, exchange, info) }. A wrapper surrounds every attempt of the route's work at route scope, inside the .retry() declared before .from() and outside .timeout(); it may time, trace or guard an attempt and may throw, but does not change the exchange. A .retry() placed after .from() is a step inside the route's work, so its attempts run inside one wrapper call. Wrappers run in plugin list order; hooks.order does not address perAttempt, which has no phases. An observe or mutate hook that throws in an exchange slot fails the exchange; in the error slot an observe hook that throws is logged and the rest of the slot still runs.

Hook fields

FieldApplies toMeaning
idallThe hook's name, addressed as pluginId/id by hooks.order and hooks.disable. Required, and stable across the plugin's releases: a hook without one is RC1117.
phaseall but perAttemptobserve, mutate or validate.
run(exchange, info)exchange slots and pointsThe hook.
run(error, exchange, info)errorThe error hook.
wrap(proceed, exchange, info)perAttemptThe wrapper.
routesallOnly these route ids. Combined with tags as alternatives.
tagsallOnly routes carrying one of these tags.
sourcesall but perAttemptOnly exchanges admitted through one of these sources, by adapterId (what sourceOf(exchange) returns, for example routecraft.adapter.argv). Must match as well as routes / tags. An empty list, or sources in perAttempt, is RC1115. A selector, never authentication: it says which door an exchange came through, not who sent it.
runsallThe run kinds the hook applies to: normal, resume, debounce, errorChannel. Defaults to normal only, except in error, which defaults to every kind. beforeAuth, afterAuth and admitted see admissions only: a normal run, and an admission resume (a park raised before the route admitted the exchange), which runs afterAuth and admitted around the authorize it re-runs. An admission resume is an admission, so those slots see it as kind normal and a hook keeping the default runs on it; the error slot, points and perAttempt see the same run as kind resume.
writesmutateThe headers the hook writes, so a conflict is reported at start rather than on the first request.
mayDefererrorThe hook may answer recovery.defer(). Makes every route it applies to deferrable, so the application refuses to start without a deferral runtime (RC5052).
inputerrorWhat a resume payload must satisfy when the hook parks with recovery.defer(request). The request carries the parking options; the schema is this field. Read back live at the resume door and validated there (RC5049); a schema that changed or disappeared under a parked exchange refuses the resume (RC5048).

info carries routeId, tags, slot and kind. An error hook's info also carries execution (1 on the first run, 2 once the exchange is a resumed continuation) and forward, which sends to a direct() endpoint under the failing exchange's principal.

An error hook that throws is reported as route:error-handler:failed with scope: "slot" and the hook's id under hook, and the slot continues to the next hook. A failure an error hook decides reaches neither context:error nor route:exchange:failed.

Points

A plugin may declare points: [{ name: 'approvals.decided' }] and run the hooks other plugins place there from its own step, with ctx.invoke(name, exchange) in a step's execute. Another plugin places a hook there under hooks.points: hooks: { points: { 'approvals.decided': { id: 'recordDecision', phase: 'observe', run } } }. Point names are dotted under the declaring plugin's namespace; two plugins declaring one point, or a point named after a slot, is RC1113.

Hooks config

The application settles conflicts in config, under hooks:

KeyTypeMeaning
orderRecord<"slot/phase", string[]>The exact order of one phase of one slot, by hook id (pluginId/id). Hooks it does not name run after the named ones, in plugin list order. Not for perAttempt, which has no phases.
disablestring[]Hooks switched off, by id. Slots only; a position is never disabled.

A name in order or disable that matches no installed hook is RC1112.

Steps

Each entry of a plugin's steps becomes a builder method of that name. The entry takes the method's arguments and returns a step built with step<In, Out>().

APIMeaning
step<In, Out>((exchange, ctx) => body)A step that replaces the body with what the function returns. The method exists only on a route whose body is assignable to In, and leaves the route at Out.
step<In, Out>(rawStep)Wraps a step written against Step directly, for one that drops or branches rather than continuing.
step(impl, { defers })The step defers the exchange and is handed ctx.defer, typed by the revival it declares (DeferHandleFor<D>). See deferring and resuming steps.
step(impl, { resumes: true })The step resumes deferred exchanges and is handed ctx.resume.
BodyA placeholder for the body at the call site. step<Body, Body> with (fn: (body: Body) => ...) in the factory's arguments gives a body-preserving method whose callback is typed at the route's current body.
StepMethods<S, This>An interface a plugin merges its method types into, under its namespace, for a method generic at the call site. The steps entry of the same name still provides the runtime. BuilderState, Retyped and SetBody are exported for writing these.
FacetTypes<S>An interface a plugin merges its facet type into, under its namespace, when the facet's type depends on the route's state.

A route that uses a plugin's step refuses to start unless the plugin is installed (RC1111). Two plugins declaring one step, or a step named after a builder method, is RC1116. So is a step named then or toJSON, which the language reads off every object.

Step identity

The continuation digest (RC5048) and the default .cache() key read one identity per step: { kind, version?, options? }.

ExportWhat it is
step(impl, { identity })identity.version marks a behaviour change the arguments and callback do not show. identity.options replaces the method's recorded arguments, so restate each one that defines the step; the callback stays in the identity. On a raw step that states [IDENTITY](), both replace what it states. The kind of a catalogue step is always <pluginId>.<stepName>.
identified(target, identity)Gives a function or object an identity. A helper that returns a closure wraps it, because guard({ roles }) returns the same source text for every roles.
IDENTITYThe registered symbol Symbol.for("routecraft.identity"). A raw step implementing [IDENTITY](): Identity states its whole identity; an adapter implementing it states its options, and its kind defaults to its adapterId.
Identity, IdentifiedStep, IdentifiedAdapterThe types of the above.
secret(value)Marks a value that configures a step without defining it. Digests as a constant, so it must not be what selects whose data comes back: use versioned(value, accountId) for a credential that does, or two accounts share one default cache key. Unrelated to what a deferral may persist.
versioned(value, id)States a value's identity by hand. id is digested and the value is not.
describeIdentity(steps) (@routecraft/testing)The digest, one short digest and kind per step, and every value the digest could not see.

Without [IDENTITY](), a raw step is identified by its operation and its adapter, and an adapter by the factory arguments tagAdapter recorded, or by its own enumerable properties.

Value in optionsDigested as
null, undefined, string, boolean, number, bigintItself
Date, URL, RegExpISO time, href, source and flags
Array, Map, SetIts members, in order
Plain objectIts own enumerable string keys, sorted
Standard SchemaIts JSON Schema rendering. A .refine() or .transform() callback is not part of a rendering, so an edit to one moves nothing: wrap such a schema in versioned(schema, id)
FunctionIts source as the runtime reports it, unless a Routecraft helper returned it, which is digested by the helper's name and arguments
A class instance, a native or bound function, a symbol, a schema with no JSON Schema rendering, a symbol-keyed or accessor property, a value that contains itself, anything nested more than five deepA placeholder. The value is reported by describeIdentity and by RC5071 on a route that defers or caches under the default key.

The digest does not cover what a function captured, what a direct() target, a named agent or a tool selected by name does, the contents of a file a step reads when it runs, or an environment variable. A wrapper's label names its events and is left out too. A core step is digested by the options it was given, so a default that changes in a release moves nothing by itself. .log() is left out of it: a log line can be added or reworded while exchanges are parked.

Deferring and resuming steps

Only the kernel parks and revives an exchange. A step asks for either by declaring it, and the kernel hands it the handle: a step result that names a deferral the kernel did not issue is refused with RC5032.

DeclarationHandleMeaning
defers: { revival: "next-step", input? }ctx.deferThe step defers, and a revival continues with the step after it. A run that returns without calling ctx.defer lets the exchange continue with no deferral. input is the schema a resume payload is validated against before the claim (RC5049).
defers: { revival: "this-step" }ctx.deferThe step may defer, and a revival runs it again with what it stored. It names its input when it defers and validates the payload itself.
resumes: truectx.resumeThe step is a resume door.
ctx.defer memberMeaning
ctx.defer({ ttl?, meta?, callBinding?, stepState?, input?, notify? })End the run deferred. The promise never resolves: return or await it, and let its rejection through a catch (isDeferSignal). A step that calls it and then returns is RC5032, and nothing is parked. stepState and input belong to a "this-step" site: step() leaves them off the type for a "next-step" declaration, and passing one anyway is RC5003. notify is awaited with the acknowledgment after the record is written; a throw is RC5067 and the record is denied.
ctx.defer.revivedSet when this run is a revival of a deferral this step raised: { deferralId, stepState, input }.
ctx.defer.refusedWhy a deferral from this position cannot be revived (inside a .split() fan-out, a .multicast() path or a .dispatch() target), when it cannot. Deferring anyway is RC5051 with this text.
ctx.defer.aside({ stepState, announce? })Store a continuation for an exchange that goes on to complete: a way to run this step again later. No acknowledgment, no token, no route:exchange:deferred. A "this-step" site only.

ctx.resume({ token, input }, { authorize?, elevate?, signal? }) resumes on behalf of the exchange's caller. The exchange, its principal and the route are the kernel's, and the resuming party recorded is the principal the route verified: a request that names resumedBy is RC5003.

An adapter of a .to() or .enrich() declares [DEFERS]: () => ({ revival: "this-step" }) and reads ctx.defer off the context it is called with. A raw step declares [DEFERS]() or [RESUMES]() the same way. Both are registered symbols.

The acts a plugin takes outside a step (c.continuations.mintToken(), resume() and rewriteStepState()) run no door policy, so the lint rule restrict-continuation-minting makes each call site an explicit exception.

Structural steps

A raw step that runs steps of its own (a branch, a fan-out, a plugin's own sub-pipeline) reports them through the NESTED_STEPS protocol, so the walks of a route's step tree see inside it: which plugins the route uses (RC1111 at start), which positions it needs, the continuation digest, and where a .defer() may land. A step that runs nested steps without reporting them hides them from every one of those, and a park inside it is RC5051.

const branch: Step<Adapter> & NestingStep = {
  operation: OperationType.PROCESS,
  adapter: { adapterId: "acme.branch", steps },
  async execute(exchange) {
    return { kind: "branch", exchange, steps };
  },
  [NESTED_STEPS]: () => [{ steps, rejoins: true }],
};

rejoins says whether the branch flows back into the main pipeline (a .choice() branch does; a .multicast() path does not), which decides whether a .defer() inside it has a continuation. A step-scope wrapper forwards the protocol to the step it wraps.

Authenticating steps

A step that establishes the exchange's principal carries the AUTHENTICATES mark, as .authenticate() does. The builder refuses a route-scope .cache() on a route that reaches a marked step (RC5003), because a cache hit would answer before the step ran with a key that never saw the identity. Both marks are registered symbols, so a step built against another build of the package is seen the same way.

Facets

A plugin's facet is readable as ex.<namespace> in route callables, typed in routes built with the project's craft(). It is computed from the exchange on every read and never stored. A facet named after an exchange field (id, headers, body, logger, context) or method is RC1114. Reading a facet in an application that does not install its plugin is RC1111.

FacetPluginLibrary equivalent
ex.auth.principalroutecraft.authprincipalOf(exchange)
ex.deferralroutecraft.deferraldeferralOf(exchange)

Code that holds a plain Exchange rather than a route's typed one (an adapter, a hook, a helper) uses the library function.

Tooling

tooling is read from the project's resolved plugin list by tools that run beside the application, the command line first among them. Nothing is bound or started, so a command or login works from the options the plugin's factory closed over.

FieldTypeMeaning
commandsRecord<string, ToolingCommand>craft <namespace> <key>. A key is one word of letters, digits, - and _ that starts with a letter or digit, and so is the namespace of a plugin that declares commands. A repeatable plugin may not declare commands (RC1117): its installs share one namespace.
logins() => CredentialLogin[]The logins the plugin's configuration declares, run by craft connect <id>. Pure: called by every tool that reads it, never by the application. Two logins with one id or one owner across the application are RC5003.

A ToolingCommand is { summary, usage?, run(args, context) }, and run resolves to { code, output?, error? }: the exit code, and what to print on standard output and standard error. Its context carries:

MemberMeaning
rootThe project root: the directory holding craft.config.ts.
loggerThe project's logger.
credentials()The project's credential store, narrowed to the owners this plugin's own logins declare. Any other owner is refused with RC5072, and a listing shows only those owners.
import { definePlugin } from '@routecraft/routecraft'

export const warehouse = definePlugin({
  id: 'acme.warehouse',
  namespace: 'warehouse',
  tooling: {
    commands: {
      whoami: {
        summary: 'Print the account the warehouse login is connected as',
        async run(_args, context) {
          const held = await (await context.credentials()).get('acme:warehouse')
          return held === undefined
            ? { code: 1, error: 'Not connected. Run craft connect warehouse.' }
            : { code: 0, output: JSON.stringify(held.value) }
        },
      },
    },
    logins: () => [
      {
        id: 'warehouse',
        owner: 'acme:warehouse',
        description: 'https://warehouse.example.com',
        async login(store, io) {
          await io.openUrl(new URL('https://warehouse.example.com/authorize'))
          const callback = await io.waitForCallback()
          await store.put('acme:warehouse', { code: callback.get('code') }, { ifVersion: null })
        },
      },
    ],
  },
})

The verbs craft keeps, and the ones it shares with a first-party plugin, are listed under plugin commands. pluginTooling(config) returns the same list for a tool of your own, and scopedCredentialStore(store, owners, plugin) the narrowed store.

A third party reaches every position a default plugin fills through replaces. It cannot be a default plugin itself: the defaults are the set @routecraft/routecraft ships.


Plugins guide

Write a plugin: ports, hooks, steps and facets with worked examples.

Configuration

Every craft.config.ts field, including the first-class keys that stand in for plugins.

Errors

RC1101 to RC1119 and RC5068, the plugin faults.

Agents and skills

Give a project a model, define an agent, and grant it capabilities as tools.

Previous
Runtime