@chamvi/http
REST, SSE, MCP, the http, mcp and webhook channels and the /channels/<name> mount for chamvi agents, on routup. The public API of packages/http/src/index.ts.
npm install @chamvi/http @chamvi/core --save@chamvi/core is a peer dependency. See HTTP API & MCP for the behaviour.
createHttpApp
function createHttpApp(options: HttpAppOptions): App; // routup AppThe services, the agents and the clock come from engine (engine.runService, engine.stateService, ..., engine.listAgents(), engine.clock). The agents are read from the engine on every request, so an agent registered, replaced or removed at runtime gets (or loses) its routes, webhook subscriptions, GET /agents entry, schedules and MCP run_<agent> tool at once; a run_<agent> definition is built once per agent object, and one that fails for an agent registered after construction goes to onError and that tool is left out. agents narrows the served agents to the named ones, checked at construction: the others, also agents registered later, get no routes or MCP tools in this app (a mounted channel serves every agent subscribing to it), and a named agent removed from the engine answers 404. agentIssues lists agents that failed to load as GET /agents issues. HttpRouteContext.agents is read from the engine on every access. Throws InvalidAgentDefinitionError for a name in agents the engine lacks or that is given twice, an empty auth array and an invalid routes entry (a path that is not static, a duplicate method and path, a first segment of a built-in route such as agents, runs or channels, or the metrics path, all compared case-sensitively, as routup matches).
export type CorsOptions = CorsPluginOptions;
/** Without the library's `trustProxy`: chamvi keys by `getRequestIP()`, so `HttpAppOptions.trustProxy` is the one proxy setting. */
export type RateLimitOptions = Omit<RateLimitPluginOptions, 'trustProxy'>;
/** A mounted channel's independent per-client HTTP request limit. */
export type ChannelRateLimitOptions = {
max: number;
/** Positive timer-safe milliseconds. Default: 60,000. */
windowMs?: number;
};
export type PrometheusOptions = PrometheusPluginOptions;
/** routup's trust-proxy input: a predicate, CIDRs, `'loopback'`, a hop count or a boolean. */
export type TrustProxyInput = NonNullable<AppOptionsInput['trustProxy']>;
export type McpOptions = {
name?: string;
version?: string;
maxWaitSeconds?: number;
};
export type HttpAppOptions = {
/** Its services (`runService`, `stepService`, `artifactService`, `stateService`, `connectionService`), agents and `clock` serve every route. */
engine: IEngine;
/**
* Names of the engine's agents to serve (routes, MCP tools, extra
* routes), checked at construction; the others, also agents registered
* later, are unknown to this app. A named agent removed from the engine
* answers 404. Default: every agent the engine holds, at request time.
*/
agents?: string[];
/**
* Agents that failed to load (e.g. from an agents folder), read per
* `GET /agents` and listed as its `issues`. Default: none.
*/
agentIssues?: () => readonly AgentIssue[];
/** One authenticator or a chain; the first principal wins. */
auth: Authenticator | Authenticator[];
/** Prefix of every route, e.g. `/api`. Default: none. */
basePath?: string;
/** Which proxies `getRequestIP` trusts (and so the rate-limit key). Default: none. */
trustProxy?: TrustProxyInput;
/**
* Adds an `auth` metric (the authenticator chain) to the `Server-Timing`
* response header. Default: false, as timings tell a client how long
* authentication took.
*/
serverTiming?: boolean;
/** Fails `/readyz` once shutting down; the app ends its streams on shutdown. */
shutdown?: IShutdown;
/** Bytes a request body may have. Default: 1 MiB. */
bodyLimit?: number;
stream?: {
/** How often a stream polls the store for runs executing elsewhere. Default: 2 s. */
pollMs?: number;
/**
* Open SSE run streams plus waiting MCP `run_<agent>` calls, per app
* (a positive integer). Over it a stream answers 503 with
* `Retry-After`, an MCP call answers without waiting. Default: 1000.
*/
maxOpen?: number;
};
mcp?: false | McpOptions;
/**
* The OpenAPI document of the REST API at `GET <basePath>/openapi.json`
* and a Swagger UI over it at `<basePath>/docs` (`ui: false` serves the
* document only), both unauthenticated; false serves neither. A missing
* or unreadable document (a build without its last step) mounts neither
* and is reported once to `onError`. Default: both.
*/
openapi?: false | OpenApiOptions;
/** CORS is off unless given. */
cors?: false | CorsOptions;
rateLimit?: false | Partial<RateLimitOptions>;
/**
* Policies for mounted POST /channels/<name> paths (including subpaths).
* An omitted name shares the general limit; false exempts the channel;
* an explicit policy replaces it with a separate per-channel/client bucket,
* also when rateLimit is false. Authentication and body limits are unchanged.
*/
channelRateLimits?: Record<string, false | ChannelRateLimitOptions>;
metrics?: false | Partial<PrometheusOptions>;
/** How long `/readyz` waits for the store. Default: 2 s. */
readyTimeoutMs?: number;
/** Receives 5xx causes and background failures. Default: `console.error`. */
onError?: (error: unknown) => void;
/** Extra routes other packages contribute (e.g. the dashboard), served under `basePath`. */
routes?: HttpRoute[];
/**
* Controller instances an app contributes: objects whose class carries
* `@DController` of `@routup/decorators`, mounted after the built-in
* controllers and served under `basePath`. Each base path must be a
* static path outside the built-in routes and the metrics path, listed
* once per controller, with no extra route at or under it and not at or
* under an extra prefix route (any method), and each method path one
* routup parses; a breach throws InvalidAgentDefinitionError at
* construction. A repeated route is answered by the first. A method is not
* authenticated unless it uses `ForceLoggedInMiddleware` (or a body
* middleware) or its service authorizes. Default: none.
*/
controllers?: object[];
/**
* Channels to serve at `POST /channels/<name>` and below (e.g. the
* webhook and GitHub channels), unauthenticated: each checks its own
* credentials. Each needs an `in` and must be the object the engine holds
* under its name, else InvalidAgentDefinitionError. Default: none.
*/
channels?: IChannel[];
/**
* The connection handles to serve at `/connections` (status, the
* widgets such as a pairing QR, live events, reset), read per request.
* Default: none, the list is empty.
*/
connections?: () => readonly IConnectionHandle[];
/**
* The configurable connection types (`/connection-types`, the declared
* connections listed at `/connections`), read per request. Default: none.
*/
connectionTypes?: () => readonly IConnectionTypeProvider[];
/**
* Where connection settings and secrets are saved; it needs an engine
* with a connection service (`engine.connectionService`, the stored
* rows), else InvalidAgentDefinitionError. Absent (a store without
* connections): connections are read-only, no save or create is
* accepted.
*/
connectionConfigs?: IConnectionConfigStore;
/** The separately built pages `GET /ui-pages` lists, read per request. Default: none. */
uiPages?: () => readonly UiPage[];
/**
* The background jobs `GET /components` lists before the engine's
* channels with a `status()`, read per request. Default: none.
*/
components?: () => readonly HttpComponent[];
};channels lists the channels mounted at POST /channels/<name> (each needs an in and must be the object the engine holds under its name, else InvalidAgentDefinitionError). connections returns the connection handles (IConnectionHandle of @chamvi/core: name, type, status(), widgets(), subscribe(), actions.reset?) served at /connections; it is called per request, and @chamvi/app passes every AppToken.CONNECTIONS contribution. routes takes extra routes from other packages, such as the dashboard of @chamvi/ui:
export type HttpRouteMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export type HttpRouteRequest = {
/** URL, method, headers and signal; without the body, which only readBody() reads. */
request: Request;
/**
* Runs the app's authenticators over the request, once per request (every
* call, and a built-in route's check, shares the result): 401 with
* `WWW-Authenticate: Bearer` without a principal, 403 when `permission`
* is given and not granted: for the resource `attributes` when given,
* else for some resource (a binding whose policies need the missing
* attributes passes). A route that never calls it stays unauthenticated.
*/
authorize(permission?: string, attributes?: Record<string, unknown>): Promise<Principal>;
/**
* The raw body, at most `bodyLimit` bytes: 413 above it (content-length
* refused unread, else drained like readJsonBody); with a non-empty body,
* 415 for a missing or non-JSON media type and 400 for a malformed one;
* an empty body is a 0-length array.
* Memoized: every call answers the same bytes (or the same error).
*/
readBody(): Promise<Uint8Array>;
/**
* The path below the route's `path`: `''` for `path` itself, else the raw
* (still percent-encoded, case kept) rest starting with `/`, e.g.
* `/assets/app-1a2b.js`; never the query. Only a `prefix` route sees more than `''`.
*/
subpath: string;
};
export type HttpRouteResult = {
status: number;
/** Set on the response; a `content-type` here wins over the body's default. */
headers?: Record<string, string>;
/**
* A `Uint8Array` is sent as is (`application/octet-stream` unless
* `headers` names a `content-type`); objects, arrays, numbers and booleans
* as JSON, a string as `text/plain`; `undefined` or `null` answer an empty body.
*/
body?: unknown;
};
export type HttpRouteContext = {
engine: IEngine;
/** The agents the app serves, read from the engine on every access. */
agents: readonly Agent[];
clock: IClock;
onError: (error: unknown) => void;
/** The app's `basePath` (`''` by default), e.g. to build absolute links. */
basePath: string;
};
export type HttpRoute = {
method: HttpRouteMethod;
/** Static path under basePath (no ':' '*' '{'), e.g. '/ui'; also its metrics label. */
path: string;
/** false: skipped by the app's rate limiter (callers that never retry, e.g. webhook senders). Default: limited. */
rateLimit?: false;
/**
* true: the route also serves every path below `path/` (same method),
* handing the rest as `request.subpath`; labelled `<path>/*` in metrics.
*/
prefix?: true;
/**
* Not authenticated by the app's authenticators unless the handler calls
* `request.authorize()`. Thrown chamvi and @ebec/http errors render like any route's.
*/
handler: (request: HttpRouteRequest, ctx: HttpRouteContext) => Promise<HttpRouteResult>;
};The app's authenticators do not guard an extra route. A handler that needs them calls request.authorize(permission?): it resolves the caller's Principal (the authenticator chain runs once per request), answers 401 with WWW-Authenticate: Bearer without one and 403 when the principal lacks permission.
Channel HTTP request limits
channelRateLimits?: Record<string, false | ChannelRateLimitOptions> selects the HTTP intake policy for each mounted channel, without changing run execution capacity:
- An omitted entry inherits the general
rateLimitbucket (default 300 requests per 60 seconds per client IP), shared with REST and other unconfigured channels. { max, windowMs? }replaces that bucket for the channel with its own per-client bucket, separate from REST and other configured channels.windowMsdefaults to 60,000. Explicit channel limits also work when the generalrateLimitisfalse.falseremoves request limiting only for that channel's mountedPOST /channels/<name>and subpaths. It does not disable authentication, signatures or body-size checks. Other methods and unknown channel paths do not gain the exemption.
The keys must exactly name mounted input channels. max must be a positive safe integer; windowMs a positive integer no greater than 2,147,483,647. Invalid policies throw InvalidAgentDefinitionError before serving. Buckets are local to this HTTP app, not coordinated through the run store. Refusals remain JSON 429 responses with Retry-After and rate-limit headers.
The same options pass through httpModule() in @chamvi/app. See GitHub intake behind an ingress for finite and disabled examples. trustProxy defaults to trusting no forwarded headers; restrict it to known proxy source addresses or CIDRs, never blindly trust arbitrary client headers.
OpenAPI document
Every app serves the OpenAPI 3.2 document of its REST API at GET <basePath>/openapi.json and a Swagger UI over it at <basePath>/docs. The document describes the built-in REST routes: MCP, the /channels/<name> mount and extra routes are not in it, and an app's controllers only when the app contributes their document (openapi.documents, see OpenAPI document). It is generated from the controllers when @chamvi/http is built (dist/swagger.json in the published package), never at runtime; its servers entry is the app's basePath. A missing or unreadable document serves neither path and is reported once to onError; a UI that cannot be mounted leaves only /docs unserved, reported the same way; the API still starts.
openapi: { ui: false }serves the document without the UI;openapi: falseserves neither. With@chamvi/app, pass it throughhttpModule({ openapi: false }); there is no environment variable for it.- Both are unauthenticated, rate-limited like every other route and labelled
/openapi.json,/docsand/docs/*in the metrics. Turn them off, or keep them off the public ingress, if the shape of the API should not be public. - The UI answers
GETandHEADfor its page (<basePath>/docs,/docs/,/docs/index.html,docsin lower case only) and the files the page loads (its generatedswagger-initializer.jswith the document,index.css, the Swagger UI bundle, styles and icons), everything else under/docswith the JSON 404. The page has no inline script or style and loads nothing from another origin: the page and every file it serves (not the JSON 404 answers) carry a Content-Security-Policy of same-origin files only (default-src 'none',worker-src 'none',frame-ancestors 'none'),x-content-type-options: nosniff,referrer-policy: no-referrer,x-frame-options: DENY,cross-origin-resource-policy: same-originandcache-control: no-cache. docsandopenapi.jsonare reserved first path segments: an extra route there is refused at construction, also withopenapi: false.- The UI's npm dependency
swagger-ui-distinstalls@scarf/scarf, whose install script reports install analytics. SetSCARF_ANALYTICS=falsein the environment that runsnpm install(an image build stage, CI), or"scarfSettings": { "enabled": false }in the app'spackage.json, to turn it off.
Channels
function httpChannel(options?: HttpChannelOptions): IChannel; // name 'http': REST runs; no in, no out
function mcpChannel(options?: HttpChannelOptions): IChannel; // name 'mcp': MCP run_<agent> runs; no in, no out
// HttpChannelOptions { untrusted?: boolean }: true taints every run the channel starts (default trusted)
function webhookChannel(options: WebhookChannelOptions): WebhookChannel; // in at /channels/<name>/<agent><path>; on() bound to its name
function readRequestBody(request: Request, options: ReadRequestBodyOptions): Promise<Uint8Array>; // for a channel's in: 413 above options.limit
const http: HttpSubscriber; // http.on({ schema? }): id 'http', at most one per agent
const webhook: WebhookSubscriber; // webhook.on(path, options?): id 'webhook:<path>'
const HTTP_CHANNEL_NAME: 'http';
const MCP_CHANNEL_NAME: 'mcp';
const WEBHOOK_CHANNEL_NAME: 'webhook';/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { ChannelRequest, IChannel } from '@chamvi/core';
import type { Authenticator } from '../auth/types.ts';
import type { WebhookSubscriber } from '../subscriptions/types.ts';
/** Options of `httpChannel()` and `mcpChannel()`. */
export type HttpChannelOptions = {
/**
* Taint every run started through this channel (`channel:<name>`), so
* classified outbound tools need approval; default false (the caller is
* an authenticated principal). Set it when principals relay content you
* do not trust.
*/
untrusted?: boolean;
};
export type WebhookChannelOptions = {
/** The channel name; default `webhook`. A second instance needs its own. */
name?: string;
/**
* Who may deliver: the first principal wins (as the http app's `auth`),
* and it needs `chamvi_agent_run` for the agent. Required, since the http app never
* authenticates channel routes.
*/
auth: Authenticator | Authenticator[];
/** Bytes a delivery may have (413 above). Default: 1 MiB, the http app's default. */
bodyLimit?: number;
};
/** A webhook channel: `in` only, with `on()` bound to its name. */
export type WebhookChannel = IChannel<ChannelRequest, Response> & WebhookSubscriber;
/** A webhook delivery's target, parsed from the subpath; internal. */
export type WebhookTarget = {
agent: string;
/** Starts with `/`, the decoded segments joined with `/`. */
path: string;
};/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { ChannelSubscription } from '@chamvi/core';
import type { StandardSchemaV1 } from '@standard-schema/spec';
export type HttpSubscriptionOptions = {
/** Shared-store execution cap for REST, UI and MCP starts; omitted or false adds no cap. */
concurrencyMaxRuns?: number | false;
/** Validates the payload of a REST, UI or MCP start. */
schema?: StandardSchemaV1;
};
/** Makes the `http` subscription (id `http`, at most one per agent). */
export type HttpSubscriber = {
on(options?: HttpSubscriptionOptions): ChannelSubscription;
};
export type WebhookSubscriptionOptions = {
/** Shared-store execution cap within the agent; omitted or false adds no cap. */
concurrencyMaxRuns?: number | false;
/** Validates the delivered payload. */
schema?: StandardSchemaV1;
/** The run's idempotency key when the delivery has no `Idempotency-Key` header. */
idempotencyKey?: (payload: unknown) => string | undefined;
concurrencyKey?: (payload: unknown) => string | undefined;
};
/** Makes webhook subscriptions for one channel name. */
export type WebhookSubscriber = {
/** `path` starts with `/`; the subscription id is `webhook:<path>`. */
on(path: string, options?: WebhookSubscriptionOptions): ChannelSubscription;
};httpChannel({ untrusted: true }) and mcpChannel({ untrusted: true }) opt the REST and MCP intake into the run-taint boundary, for callers that relay text written by others (an OpenClaw MCP principal forwarding chat messages): every run they start is tainted (channel:http/channel:mcp), so outbound tools wait for approval. Both default to trusted, since the caller is an authenticated principal. In an @chamvi/app app, configure the built-in http module: httpModule({ untrusted: { mcp: true } }) (or http: true) in createApp({ modules }).
The engine refuses an http.on() subscription unless it holds httpChannel() (REST and MCP keep separate idempotency scopes through the two channel names), and a webhook.on() one unless it holds the webhook channel. webhook.on() throws InvalidAgentDefinitionError for a path that does not start with /. See Channels.
Authenticators
type Authenticator = (request: Request) => Promise<Principal | undefined>;
function staticTokens(options: StaticTokensOptions): Authenticator;
function authup(options: AuthupOptions): Authenticator;
function oidc(options: OidcOptions): Authenticator;An authenticator resolves undefined for a request it does not recognize and throws a 401 for credentials it rejects. staticTokens throws InvalidAgentDefinitionError for an empty tokens array, a token value shorter than 16 characters, a missing id or a value given twice; oidc for an empty issuers list, an issuer without audience or a missing principal.
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { PermissionAuthorization, PermissionBinding, PermissionIdentity } from '@chamvi/access';
export type Principal = {
id: string;
kind: 'token' | 'authup' | 'oidc' | (string & {});
/** Granted permissions: authup bindings with resolved policy trees (plain data). */
bindings: readonly PermissionBinding[];
/** authup's snapshot of the identity's grants; set by `authup()`, which leaves `bindings` empty. */
authorization?: PermissionAuthorization;
/** What an `identity` policy evaluates; set by `authup()`. */
identity?: PermissionIdentity;
claims?: Record<string, unknown>;
};
/**
* Resolves `undefined` when the request carries no credentials it
* recognizes, throws `UnauthorizedError` for credentials it rejects.
*/
export type Authenticator = (request: Request) => Promise<Principal | undefined>;/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { ITokenVerifier } from '@authup/server-adapter-kit';
import type { IClock } from '@chamvi/core';
export type AuthupOptions = {
/** An authup `TokenVerifier` (remote mode for grants) or any `ITokenVerifier`. */
verifier: ITokenVerifier;
/** RFC 8705: the client certificate's SHA-256 thumbprint, for certificate-bound tokens. */
certificateThumbprintByRequest?: (request: Request) => string | undefined | Promise<string | undefined>;
/**
* Reads authup's `GET /authorization` body (needs `permission_read` with a realm scope of `ownOrNull` or wider).
* Called once, again once the copy is older than `catalogMaxAgeMs`,
* when a grant names a definition or policy the copy lacks, and after a
* failed read (a body that is not a catalog counts as one).
*/
catalog: () => Promise<unknown>;
/** How long a read catalog is used before it is read again, so policy edits in authup apply. Default: 60 000. */
catalogMaxAgeMs?: number;
/** The clock the catalog's age is measured on. Default: `systemClock`. */
clock?: IClock;
/** The realm chamvi's resources belong to (the realm id of chamvi's authup client). Called per request with grants; cache it. */
realm: () => Promise<string>;
/**
* The owner client id (#282). Set, every permission name is checked only
* as a definition of this client in `realm`; global and realm-owned
* definitions grant nothing. Called per login with grants; cache it.
*/
client?: () => Promise<string>;
/** Receives catalog, realm, client and snapshot failures; the login then grants nothing. Default: `console.error`. */
onError?: (error: unknown) => void;
};Permissions
function assertMcpRunTool(agent: Agent): void; // throws InvalidAgentDefinitionError like createHttpAppassertMcpRunTool builds the agent's run_<agent> MCP tool definition and throws what createHttpApp would throw for it (a tool name above 64 characters, a payload schema MCP cannot compile); the app runs it on every folder agent before registering it. createHttpApp reports a folder agent's failure (one the engine holds at a revision) to onError and skips its tool instead of throwing.
The routes check Permission names of @chamvi/access with can(principal, name, { attributes, now }) (one resource) and canSome(principal, name, { now }) (a collection), now from the engine clock. The names and their attributes are in Permissions and authup.
createShutdown
function createShutdown(options: ShutdownOptions): IShutdown;
const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS: 30_000;
const DEFAULT_SHUTDOWN_CLOSE_TIMEOUT_MS: 5_000;/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { IEngine } from '@chamvi/core';
export interface IShutdown {
/** True from the first `shutdown()` call on; `/readyz` then fails. */
readonly shuttingDown: boolean;
/**
* Runs `fn` during the shutdown, in the order added, after readiness
* failed and before the server closes; returns an unsubscribe.
*/
onShutdown(fn: () => void | Promise<void>): () => void;
/** Idempotent: every call returns the same promise. */
shutdown(): Promise<void>;
}
export type ShutdownOptions = {
/** Drained on shutdown; its `clock` times the delays. */
engine: IEngine;
/** srvx `Server` (pass `gracefulShutdown: false` to `serve`). */
server?: { close(closeActiveConnections?: boolean): Promise<void> };
/** Time for load balancers to see the failing readiness. Default 0. */
readinessDelayMs?: number;
/**
* Default 30 s. A function is called when the drain begins, so the drain
* can get what remains of a budget earlier shutdown work shared.
*/
drainTimeoutMs?: number | (() => number);
/** Wait for open connections after the drain, then close them. Default 5 s. */
closeTimeoutMs?: number;
/** Default `console.error`. */
onError?: (error: unknown) => void;
};Wire types
type InvokerView = Omit<Invoker, 'bindings'>;
type RunView = Omit<Run, 'claim' | 'trigger' | 'conversation'> & {
trigger: Omit<TriggerEnvelope, 'invoker'> & { invoker?: InvokerView };
agentPrivate: boolean; // the agent's `private` as the server checks it (an agent the app does not hold: true)
};
type RunSummary = Pick<Run, 'id' | 'agent' | 'status' | 'createdAt' | 'finishedAt' | 'error'>;
type RunToolResult = {
runId: string;
status: RunStatusLiteral;
deduplicated: boolean;
output?: unknown;
error?: { code: string; message: string };
waiting?: RunToolApprovalWait | RunToolDispatchWait | RunToolRemoteWait;
};
type RunToolApprovalWait = { // the run, or a descendant it waits on, waits on an approval
kind: 'approval';
runId: string; // the run to answer with approve_run
agent: string;
toolName: string;
title: string;
body?: string;
artifacts?: string[];
options?: ApprovalOption[]; // the choices to answer with approve_run's selected
multiple?: boolean; // true when several options may be selected
expiresAt: string;
};
type RunToolDispatchWait = { // the run waits on the runs it dispatched (get_run only: run_<agent> keeps waiting)
kind: 'dispatch';
toolName: string;
runIds: string[];
expiresAt: string;
};
type RunToolRemoteWait = { // a remote agent's stand-in (runId, agent) waits on its run at a peer
kind: 'remote';
runId: string;
agent: string;
peer: string;
remoteAgent: string; // the agent's name at the peer
remoteRunId: string;
expiresAt: string;
approval?: { runId: string; approvalId: string; title: string; url?: string }; // pending at the peer, answered there (url), never with approve_run
};
type ApproveBody = { // POST /runs/:id/approve; approve_run takes the same fields plus runId
approvalId: string;
approved: boolean;
reason?: string;
selected?: string[]; // the chosen option ids of a wait point with options, none on a denial
};GET /runs takes filter[parent]=<run id> (once, else 400 filter[parent] takes one run id.) next to filter[agent], filter[status], filter[waiting] (approval or dispatch, once, else 400 filter[waiting] takes approval or dispatch.; the wait point's kind) and filter[createdAt] (an inclusive gte/lte bound per ISO 8601 instant, see HTTP): the runs whose parentRunId it is, under the same read rule (an agent-scoped reader adds filter[agent]). Runs carry parentRunId and subtreeUsage when set; POST /runs/:id/approve answers a run waiting on dispatched runs with 409 invalid_run_state, and approve_run refuses it.
selected follows engine.approve()'s rules (see Approvals and HTTP): a selection that does not fit the wait point is 400 validation_error.
GET /agents answers { data: AgentSummary[], issues: AgentIssue[] }, GET /schedules { data: ScheduleSummary[] }:
/*
* Copyright (c) 2026.
* Author Peter Placzek (tada5hi)
* For the full copyright and license information,
* view the LICENSE file that was distributed with this source code.
*/
import type { Budget } from '../run/types.ts';
/** What a cron tick does while a run of the same subscription is active (as `@chamvi/channel-cron` defines it). */
export type ScheduleOverlap = 'skip' | 'queue-one' | 'allow';
/** An agent as `GET /agents` lists it. */
export type AgentSummary = {
name: string;
/**
* The agent's `kind`: `simple` for a simple agent (defineSimpleAgent()),
* `remote` for one a peer runs (defineRemoteAgent()), else `model`.
*/
kind: 'model' | 'simple' | 'remote';
/**
* The agent's subscriptions: the channel name and the subscription id;
* `hook` is the ready-made path of a subscription to a webhook channel
* this app mounts.
*/
channels: Array<{
channel: string;
id: string;
hook?: string;
}>;
budget: Budget;
/** Declared state collections. */
state: string[];
/** A private agent: reading its runs and state needs `chamvi_agent_read` for it. */
private: boolean;
/** A remote agent only: the peer that runs it and the agent's name there. */
remote?: {
peer: string;
agent: string;
};
};
/** An agent that failed to load, as `GET /agents` lists it next to the agents. */
export type AgentIssue = {
agent: string;
message: string;
at: Date;
};
/** A cron subscription as `GET /schedules` lists it (definitions only, not scheduler health). */
export type ScheduleSummary = {
agent: string;
/** The cron channel's name. */
channel: string;
/** The subscription id. */
trigger: string;
expression: string;
timezone?: string;
overlap: ScheduleOverlap;
/** ISO time of the next fire after now. */
nextAt: string;
};