Skip to content

@chamvi/core ​

The public API of @chamvi/core, taken from packages/core/src/index.ts. Contract interfaces carry an I prefix (IClock, IChannel, IAgentState, IEngine); data shapes are unprefixed types.

ts
import { Engine, defineModelAgent } from '@chamvi/core';

Test helpers live in @chamvi/test-kit.

Agents ​

ts
function defineModelAgent<S extends StateSchema = StateSchema>(def: ModelAgentDefinition<S>): ModelAgent<S>;
function defineSimpleAgent<S extends StateSchema = StateSchema, T extends ToolSet = ToolSet>(def: SimpleAgentDefinition<S, T>): SimpleAgent<S, T>;

const DEFAULT_MAX_STEPS: 20;
const DEFAULT_TIMEOUT_MS: 900_000; // 15 minutes

Throws InvalidAgentDefinitionError for an invalid name, instruction outer shape or role, duplicate subscription ids, a tool with needsApproval or a toolsContext entry naming a chamvi tool or no tool of a plain tool set (both in a plain tool set; a tools factory fails the run instead), defineModelAgent() also for run. Agent is ModelAgent | SimpleAgent | RemoteAgent, told apart (and narrowed, the definition too) by kind ('model', 'simple' or 'remote'); AgentDefinition is ModelAgentDefinition | SimpleAgentDefinition | RemoteAgentDefinition. The engine refuses an agent whose kind is none of these or disagrees with its definition (a simple agent needs a function run, a model agent has none). defineSimpleAgent() also throws for a non-function run, a tools factory or any of model, instructions, skills, output, conversation, toolsContext; its run(payload, ctx: SimpleRunContext) gets the tool context plus ctx.tools. See Agents.

A folder agent's agent.ts default-exports defineModelAgent()'s or defineSimpleAgent()'s result, named like its folder (rebuilt through the factory of its kind; one without kind, from an older core, as a model agent unless it has run); AgentRevision (@chamvi/core-kit) is the store's revision marker of a folder agent (see Agent Folders):

ts
/*
 * 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 { StandardSchemaV1 } from '@standard-schema/spec';
import type {
    AssistantModelMessage,
    InferToolOutput,
    OutputInterface,
    SystemModelMessage,
    ToolSet,
    UserModelMessage,
} from 'ai';
import type { ChannelSubscription } from '../channel/types.ts';
import type { AgentLimits } from '../limit/types.ts';
import type { ModelRef } from '../model/types.ts';
import type { RunContext } from '../run/types.ts';
import type { Budget } from '@chamvi/core-kit';
import type { StateSchema } from '../state/types.ts';
import type { SkillInput } from '../skill/types.ts';
import type { AgentTrust, ToolContext } from '../tool/types.ts';

/** The factory's argument: the same ToolContext the run's chamvi tools get. */
export type ToolFactoryContext<S extends StateSchema = StateSchema> = ToolContext<S>;

/**
 * Decides per tool name whether a run may use a tool. A refused tool is not
 * offered to the model (it is left out of `activeTools`). A call to it that
 * still arrives is a tool error, never a run failure, and its tool step
 * records `tool_not_allowed` (ToolNotAllowedError) on both paths:
 * - the model calls it anyway: the AI SDK answers the model with its
 *   unavailable-tool error (NoSuchToolError), the engine records the step
 *   as ToolNotAllowedError;
 * - a call pending on an approval (the policy changed before the resume)
 *   reaches the engine's per-call re-check, which answers the model with
 *   ToolNotAllowedError.
 * May return a promise: the engine awaits every verdict when it builds the
 * offered tools of an execution and again in the per-call re-check; a
 * rejecting policy fails the run. `now` is the engine clock's time at that
 * check (date and time policies). Should depend only on the run snapshot
 * (e.g. `run.trigger.invoker`) and `now`.
 */
export type ToolPolicy = (toolName: string, ctx: ToolPolicyContext) => boolean | Promise<boolean>;

/** What a ToolPolicy decides on. */
export type ToolPolicyContext = {
    run: RunContext;
    /** The engine clock's time at this check. */
    now: Date;
};

/** A tool call as the agent hooks see it. */
export type ToolCallInfo = {
    toolName: string;
    toolCallId: string;
    input: unknown;
};

/**
 * Gates and rewrites for every tool call of the agent's merged set (user,
 * chamvi, state and third-party tools alike), run inside the tool-call frame
 * with the execution's ToolContext (`inject` works there).
 */
export type AgentHooks = {
    /**
     * Runs before the effect lookup and returns the input to execute with
     * (`undefined` keeps it). A changed input is re-validated against the
     * tool's input schema (a failure is a ValidationError tool error) and is
     * what the effect key is computed from. A throw is a tool error
     * (ToolDeniedError for a refusal); a FatalToolError fails the run.
     */
    beforeToolExecution?(call: ToolCallInfo, ctx: ToolContext): unknown | Promise<unknown>;
    /**
     * Runs on a fresh result and on a recorded effect result alike and returns
     * the output the model sees (`undefined` keeps it). A streaming tool's
     * hook gets its final value. Not called for a tool error.
     */
    afterToolExecution?(call: ToolCallInfo & { output: unknown }, ctx: ToolContext): unknown | Promise<unknown>;
};

/** Trusted configured messages; tool-role messages are never instruction inputs. */
export type AgentInstruction = SystemModelMessage | UserModelMessage | AssistantModelMessage;

/** A string is shorthand for one system message. Arrays retain their authored order. */
export type AgentInstructions = string | readonly AgentInstruction[];

/** An agent whose runs call a language model: defineModelAgent()'s input. */
export type ModelAgentDefinition<S extends StateSchema = StateSchema> = {
    name: string;

    /** The text of the agent's MCP run tool; default: its leading system instruction. */
    description?: string;

    /** Only a simple agent has it (defineSimpleAgent()). */
    run?: never;

    /**
     * `'<provider>/<model id>'` (resolved through EngineOptions.models) or a
     * LanguageModel object; without it the agent uses EngineOptions.model.
     */
    model?: ModelRef,

    instructions: AgentInstructions,

    readonly skills?: readonly SkillInput[],

    /**
     * The channels that start the agent's runs (e.g. `cron.on('0 8 * * 1-5')`);
     * every subscription names a channel registered on the engine, ids are
     * unique per agent.
     */
    channels?: ChannelSubscription[];

    /** Shared-store execution cap across all channels; omitted or false adds no cap. */
    concurrencyMaxRuns?: number | false;

    /** Only principals granted `chamvi_agent_read` for this agent read its runs (and state). */
    private?: boolean;

    /**
     * The agent's tools: a plain `ToolSet` (the default), or a factory for
     * dynamic sets, called once per execution with the same ToolContext the
     * tools get. Tools built with `defineTool`/`defineEffectTool` receive that
     * context as `context` in `execute`.
     */
    tools?: ToolSet | ((ctx: ToolContext<S>) => ToolSet);

    trust?: AgentTrust;

    /**
     * Per tool name, a rate limit replacing the tool's own `limit`, or
     * false to turn it off. A non-empty record needs an engine with a
     * `limitService`.
     */
    limits?: AgentLimits;

    /**
     * Per tool name, the context of a tool that is not chamvi's (e.g. a
     * third-party tool with its own `contextSchema`), passed through unchanged
     * by reference to every call of every run: treat it as immutable. An entry
     * naming a chamvi tool or no tool is an InvalidAgentDefinitionError (at
     * defineModelAgent for a plain set, a failed run for a factory).
     */
    toolsContext?: Record<string, unknown>;

    /**
     * Tool hooks (see AgentHooks). AI SDK tools declaring their own
     * `needsApproval` are refused (nothing answers that request).
     */
    hooks?: AgentHooks;

    /** Filters the merged tool set (state tools included) per run, e.g. requireToolPermission(). */
    toolPolicy?: ToolPolicy;

    /** Record<collection, StandardSchemaV1>. */
    state?: S;

    budget?: Partial<Budget>;

    /**
     * Structured output (AI SDK `Output`, e.g. `Output.object({ schema })`):
     * a completed run's `output` is the parsed value instead of the text; a
     * final answer that does not parse fails the run with a ValidationError.
     */
    output?: OutputInterface;

    /**
     * Opts the agent into conversation memory (needs
     * EngineOptions.conversations); runs that come with no conversation still
     * execute as before. Omitted or false: no conversation behaviour.
     */
    conversation?: boolean | {
        /** Stable memory identity across agent renames; default is the agent name. */
        key: string;
    };
};

/**
 * What a simple agent's `run()` gets: the ToolContext its tools would get, plus
 * its own tools (wrapped like a model's calls: effect-recorded,
 * trust-classified, gated) as plain functions by name.
 */
export type SimpleRunContext<S extends StateSchema = StateSchema, T extends ToolSet = ToolSet> = ToolContext<S> & {
    tools: Record<string, (input: unknown) => Promise<unknown>> & (string extends keyof T ? unknown : {
        [K in keyof T]: (input: unknown) => Promise<InferToolOutput<T[K]>>;
    });
};

/**
 * A model-free agent, defineSimpleAgent()'s input: the engine runs `run(payload, ctx)` as a durable run
 * inside one tool-call frame, so dispatch(), waitForDispatch(), approve(),
 * ctx.channels and the agent's tools work as inside a tool call. A suspended
 * run re-runs `run()` from the start on resume (the replay rule).
 */
export type SimpleAgentDefinition<S extends StateSchema = StateSchema, T extends ToolSet = ToolSet> = {
    name: string;

    /** The run's body; its JSON-serialisable return value is the run's `output`. */
    run(payload: unknown, ctx: SimpleRunContext<S, NoInfer<T>>): unknown | Promise<unknown>;

    /** The text of the agent's MCP run tool. */
    description?: string;

    channels?: ChannelSubscription[];

    concurrencyMaxRuns?: number | false;

    /** Only principals granted `chamvi_agent_read` for this agent read its runs (and state). */
    private?: boolean;

    /** A plain set only: a factory is refused. */
    tools?: T;

    trust?: AgentTrust;

    hooks?: AgentHooks;

    toolPolicy?: ToolPolicy;

    state?: S;

    /** `timeoutMs` and the subtree budget apply; `maxSteps` and `maxTokens` do not. */
    budget?: Partial<Budget>;

    model?: never;
    instructions?: never;
    readonly skills?: never;
    output?: never;
    conversation?: never;
    toolsContext?: never;
    limits?: never;
};

/**
 * An agent whose runs another chamvi app (a peer) executes: defineRemoteAgent()'s input.
 * A run here is a stand-in that waits on the remote run.
 */
export type RemoteAgentDefinition = {
    name: string;

    /** A configured peer (EngineOptions.peers). */
    peer: string;

    /** The agent at the peer; default `name`. */
    agent?: string;

    /** Its `agent.on()` role at the peer; default `default`. */
    role?: string;

    /** The text of the agent's MCP run tool. */
    description?: string;

    channels?: ChannelSubscription[];

    /** The remote run's output, validated here (a failure is a ValidationError). */
    output?: StandardSchemaV1;

    /** The deadline of the whole remote run: 1 to APPROVAL_TIMEOUT_MAX_MS, default 24 h. */
    timeoutMs?: number;

    /** Where approvals of the remote run are announced (a channel with `out`, fixed in code). */
    approvals?: { channel: string; address: string };

    /** Only principals granted `chamvi_agent_read` for this agent read its runs. */
    private?: boolean;

    concurrencyMaxRuns?: number | false;

    run?: never;
    model?: never;
    instructions?: never;
    readonly skills?: never;
    tools?: never;
    trust?: never;
    hooks?: never;
    toolPolicy?: never;
    state?: never;
    budget?: never;
    conversation?: never;
    toolsContext?: never;
    limits?: never;
};

export type AgentDefinition<S extends StateSchema = StateSchema> = ModelAgentDefinition<S> | SimpleAgentDefinition<S> | RemoteAgentDefinition;

/** defineModelAgent()'s result: its definition with the budget defaults applied. */
export type ModelAgent<S extends StateSchema = StateSchema> = {
    readonly kind: 'model';
    readonly name: string;
    readonly definition: Required<Pick<ModelAgentDefinition<S>, 'budget'>> & ModelAgentDefinition<S>;
};

/** defineSimpleAgent()'s result: its definition with the budget defaults applied. */
export type SimpleAgent<S extends StateSchema = StateSchema, T extends ToolSet = ToolSet> = {
    readonly kind: 'simple';
    readonly name: string;
    readonly definition: Required<Pick<SimpleAgentDefinition<S, T>, 'budget'>> & SimpleAgentDefinition<S, T>;
};

/** defineRemoteAgent()'s result: its definition with `agent`, `role` and `timeoutMs` defaulted. */
export type RemoteAgent = {
    readonly kind: 'remote';
    readonly name: string;
    readonly definition: Required<Pick<RemoteAgentDefinition, 'agent' | 'role' | 'timeoutMs'>> & RemoteAgentDefinition;
};

/** A registrable agent; `kind` tells them apart and narrows the definition. */
export type Agent<S extends StateSchema = StateSchema> = ModelAgent<S> | SimpleAgent<S> | RemoteAgent;

/** The agents a permission check reads by name (an app's view of the registered agents). */
export interface IAgentRegistry {
    get(name: string): Agent | undefined;
    /** In registration order, a new array. */
    names(): string[];
}
ts
/*
 * 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.
 */

/**
 * The revision marker of a folder agent: the content hash of its folder
 * (never its code) and when that hash was recorded.
 */
export type AgentRevision = {
    agent: string;
    hash: string;
    changedAt: Date;
};

/** A stored revision marker: the marker and the row's storage id. */
export type AgentRevisionRecord = AgentRevision & {
    /** The row's storage id (a uuid), kept by every later `upsert` of the same `agent`. */
    id: string;
};

Native messages and instructions ​

Core exports the unchanged native SDK types SystemModelMessage, UserModelMessage, AssistantModelMessage, ModelMessage, UserContent, AssistantContent, TextPart, ImagePart and FilePart. App re-exports these through its normal core barrel. System content is a string; user/assistant multipart content and provider options retain their native SDK types.

AgentInstruction is the union of native system/user/assistant messages; AgentInstructions accepts a string or readonly array of that union. Tool roles and a single-object shorthand are refused. Leading system blocks use SDK instructions; all remaining configured messages stay ordered in a transient prefix. Skills runtime metadata adds a separate system block, while manual catalog metadata stays a string. Prefixes hydrate files without entering checkpoints or pending-tool replay; restored transcript system roles are rejected. See the typed instructions example.

Permissions ​

ts
function requireToolPermission(opts?: RequireToolPermissionOptions): ToolPolicy;

requireToolPermission() offers a tool when the run's invoker holds chamvi_tool_use for { agent, name } (the agent and the tool), checked with can() of @chamvi/access at the engine clock's time; runs without an invoker follow withoutInvoker (default 'deny'). An invoker's permissions are permission bindings (Permissions and authup); an entry that is not one grants nothing. See Restricting tools per invoker.

ts
/*
 * 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 { IAgentRegistry } from '../agent/types.ts';

export type RequireToolPermissionOptions = {
    /** What a run without an invoker (cron, webhook) may use. Default `'deny'`. */
    withoutInvoker?: 'allow' | 'deny';
};

/** The agents a read rule decides over, passed per call (an http app's allowlisted view). */
export type AgentScope = {
    agents: IAgentRegistry;
};

Channels ​

ts
function consoleChannel(options?: ConsoleChannelOptions): IChannel;           // out only, name 'console'
function normalizeEnvelope(raw: Record<string, unknown>): TriggerEnvelope;    // for repositories: legacy source/thread read back as channel/address
function assertTriggerKey(name: string, value: string | undefined): void;     // 255 characters, no NUL

IChannel, ChannelRequest, ChannelContext, ChannelDispatchEnvelope, DispatchResult, ChannelMessage, ChannelSendOptions, ChannelSubscription, EmitMessage, ChannelHandle, ToolChannels (ToolContext.channels) and ConsoleChannelOptions:

ts
/*
 * 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 { ApprovalDecision, ApprovalRequestInput } from '../approval/types.ts';
import type { ApprovalOption, TriggerEnvelope } from '@chamvi/core-kit';
import type { ConversationTarget } from '../conversation/types.ts';
import type { DispatchEnvelope, IEngine } from '../engine/types.ts';

/** The HTTP input of a channel: the raw web request (body unread) and the raw subpath after `/channels/<name>`. */
export type ChannelRequest = {
    request: Request;
    subpath: string;
};

/** What a channel may dispatch: the engine sets `channel` to the channel's own name. */
export type ChannelDispatchEnvelope = Omit<DispatchEnvelope, 'channel'>;

/** What `engine.dispatch()` resolves. */
export type DispatchResult = {
    runId: string;
    deduplicated: boolean;
};

export type ChannelContext = {
    engine: IEngine;
    /** engine.dispatch with `channel` set to this channel's name (a channel cannot dispatch as another). */
    dispatch(envelope: ChannelDispatchEnvelope): Promise<DispatchResult>;
    /** Trusted, registered-channel intake; the channel supplies canonical identity and accepted text. */
    dispatchConversation(envelope: ChannelDispatchEnvelope, target: ConversationTarget): Promise<DispatchResult>;
};

/** One outbound message; `key` is stable per logical message and the transport's dedupe key. */
export type ChannelMessage = {
    kind: 'message' | 'approval';
    key: string;
    runId: string;
    agent: string;
    title?: string;
    body: string;
    /** Named persistent message where supported (GitHub); omitted messages append. */
    slot?: string;
    /** Set for kind `approval`. */
    approvalId?: string;
    /** Set for kind `approval`. */
    expiresAt?: Date;
    /** Set for kind `approval` with options (without their artifacts, which stay in the inbox and API). */
    options?: Omit<ApprovalOption, 'artifacts'>[];
    /** Set (true) for kind `approval` with options of which several may be selected. */
    multiple?: boolean;
    /** Set for kind `approval` when the body is a generic notification; the request's details stay in the inbox and API. */
    generic?: true;
};

export type ChannelSendOptions = {
    signal: AbortSignal;
    /** The run's stored envelope: a transport may read the source payload, never write it. */
    trigger: TriggerEnvelope;
};

/**
 * What a channel's optional `status()` answers, in epoch milliseconds; each
 * time is absent until it happened (`runningSince` while a pass is in flight).
 */
export type ChannelStatus = {
    /** The last pass that completed without error ended. */
    lastSuccessAt?: number;
    /** The last pass that failed ended. */
    lastErrorAt?: number;
    /** The last pass ended, however it ended. */
    lastRunAt?: number;
    /** The pass in flight started. */
    runningSince?: number;
};

/**
 * Anything a run can come from or talk to. The presence of `start`, `in`
 * and `out` is the only capability; `name` follows the agent-name rules
 * and is unique per engine.
 */
export interface IChannel<TInput = ChannelRequest, TOutput = Response> {
    readonly name: string;
    /** Intake authored by external parties taints every triggered run. */
    readonly untrusted?: boolean;
    /**
     * Where `emit()` and `approve()` send when the tool names no address and
     * the run did not come from this channel (e.g. OpenClaw's `deliver.to`);
     * a non-empty string. Without it such a call needs an address.
     */
    readonly defaultAddress?: string;
    /** Background inbound (cron ticks, sockets, polling); called by engine.start() after the first recover. */
    start?(ctx: ChannelContext): Promise<void>;
    /** Called first by engine.drain() and engine.stop(): no new inbound. */
    stop?(): Promise<void>;
    /** The channel's single inbound entry; transports feed it (the http route, a socket loop, tests). */
    in?(input: TInput, ctx: ChannelContext): Promise<TOutput>;
    /** Sends a message to an address the channel defines; idempotent on `message.key`. */
    out?(message: ChannelMessage, address: string, opts: ChannelSendOptions): Promise<void>;
    /**
     * Throws (a ValidationError) when `out` would refuse `message` to
     * `address`: an approval request the channel cannot deliver fails the
     * tool call instead of leaving the run waiting. It checks only what is
     * known before sending (the rendering, the target); a delivery failure,
     * such as an offline channel, keeps the approval waiting and retried.
     */
    fits?(message: ChannelMessage, address: string): void | Promise<void>;
    /**
     * Whether `address` reaches the owner alone (a direct message): a tool
     * limit's private `detail` goes to the source of a tainted run only then.
     */
    direct?(address: string): boolean | Promise<boolean>;
    /** The status of its background work (`GET /components`); synchronous and cheap. */
    status?(): ChannelStatus;
}

/**
 * An agent's subscription to a channel (replaces the trigger definition):
 * `channel` names a channel registered on the engine, `id` is unique
 * within the agent, `options` belong to the channel.
 */
export type ChannelSubscription<P = unknown> = {
    channel: string;
    id: string;
    /** Shared-store execution cap within this agent; omitted or false adds no cap. */
    concurrencyMaxRuns?: number | false;
    options: Record<string, unknown>;
    // method signatures (bivariant): a ChannelSubscription<P> fits AgentDefinition.channels
    concurrencyKey?(payload: P): string | undefined;
    idempotencyKey?(payload: P): string | undefined;
    /** The run's address from its payload; read by the agent channel only (`agent.on()`). */
    address?(payload: P): string | undefined;
};

/** A message a tool emits; `key` overrides the content-addressed dedupe key. */
export type EmitMessage = {
    title?: string;
    body: string;
    key?: string;
    /** Named persistent message where supported (GitHub); omitted messages append. */
    slot?: string;
};

/**
 * A channel bound to the run (`ToolContext.channels`). `address` is
 * the run's source address when this is the run's source channel, else the
 * channel's `defaultAddress`.
 */
export type ChannelHandle = {
    readonly name: string;
    readonly address?: string;
    /**
     * Sends `message` through the channel's `out` to `address` (default: the
     * bound address), at most once per key; only inside a tool call.
     */
    emit(message: EmitMessage, address?: string): Promise<void>;
    /**
     * Whether the bound address reaches the owner alone: true only when the
     * channel implements `direct()` and it answers true for that address;
     * false without an address and when `direct()` throws.
     */
    direct(): Promise<boolean>;
    /** Asks the owner to approve, durably (suspends the tool call until answered). */
    approve(request: ApprovalRequestInput & { address?: string; slot?: string }): Promise<ApprovalDecision>;
};

/**
 * `ToolContext.channels`: run-bound handles on the engine's channels with
 * `out`. On the run's source channel a handle defaults to the source address.
 */
export type ToolChannels = {
    /**
     * The channel `name` (default: the run's source channel); undefined when
     * the engine has no such channel or it has no `out`.
     */
    findOne(name?: string): ChannelHandle | undefined;
    /** As findOne(), but ChannelNotFoundError instead of undefined. */
    findOneOrFail(name?: string): ChannelHandle;
    /** Every engine channel with `out`, in registration order. */
    find(): ChannelHandle[];
};

export type ConsoleChannelOptions = {
    /** Default `'console'`. */
    name?: string;
    /** Receives each line; default `console.log`. */
    write?: (line: string) => void;
};

consoleChannel() writes [chamvi] <kind>: <title or the body's first line> (agent <agent>, run <runId>, key <key>), then the body lines and, for an approval, with options select one: (or select one or more:) and one option <id>: <label> line per option, then approval <approvalId> waits until <ISO>, one write call per line. It never throws; an invalid name throws InvalidAgentDefinitionError.

The envelope (TriggerEnvelope, Invoker, from @chamvi/core-kit):

ts
/*
 * 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';
import type { Artifact } from '../artifact/types.ts';

/**
 * Who started a run (or answered an approval), as an authenticator resolved
 * it: a snapshot of identity and grants taken at dispatch, never a token.
 * Revoking a grant later does not reach a run that already holds it.
 */
export type Invoker = {
    id: string;
    /**
     * The authenticator's label: `@chamvi/http`'s staticTokens() sets
     * 'token' and authup() sets 'authup'; oidc() keeps the kind its
     * `principal` mapper returns (the docs use 'oidc'); a custom authenticator
     * or a direct dispatch may use its own (e.g. 'user').
     */
    kind: string;
    name?: string;
    /**
     * The grants, as authup permission bindings with resolved policies;
     * checked with `can()` of `@chamvi/access`. An entry that is not a
     * binding (a run stored with the older string grants) grants nothing.
     */
    bindings: readonly PermissionBinding[];
    /** authup's snapshot of the grants (plain JSON), checked together with `identity`; set for authup logins. */
    authorization?: PermissionAuthorization;
    /** What an `identity` policy evaluates; set for authup logins. */
    identity?: PermissionIdentity;
};

/**
 * The run that dispatched this one. Only the engine-internal host sets it;
 * a dispatch() envelope never carries one, so no caller forges lineage.
 */
export type DispatchParent = {
    kind: 'dispatch';
    runId: string;
    /** The parent run's agent. */
    agent: string;
    /** The dispatch role of the child agent this run was started through. */
    role: string;
    depth: number;
    /**
     * The one channel and address the dispatching code named for this run
     * (`dispatch(ctx, { source })`): its outbound gate exempts that
     * destination like a run's own source. Never from a generated dispatch tool.
     */
    source?: TriggerSource;
};

/**
 * The run of another chamvi app that started this one through a peer. Its
 * ids name runs of that app, so the run gets no `parentRunId`.
 */
export type PeerParent = {
    kind: 'peer';
    /** The peer name, taken from the credential the start arrived with, never from the request. */
    peer: string;
    /** The calling run on the peer. */
    runId: string;
    /** The stand-in run on the peer that waits on this run (the wake target). */
    standIn: string;
    /** The calling run's agent on the peer. */
    agent: string;
    /** The `agent.on()` role this run was started through. */
    role: string;
    depth: number;
    /** The name of the person behind the call, for display only; never a grant. */
    origin?: string;
};

/** Where a run came from when another run started it: a local dispatch or a peer. */
export type TriggerParent = DispatchParent | PeerParent;

/** A channel and an address on it, as `dispatch()`'s `source` names it. */
export type TriggerSource = {
    channel: string;
    address: string;
};

export type TriggerEnvelope<P = unknown> = {
    id: string;
    agent: string;
    /** The id of the agent's subscription that started the run. */
    trigger: string;
    /** The name of the channel the run came from. */
    channel: string;
    payload: P;
    idempotencyKey?: string;
    concurrencyKey?: string;
    /** Where the run came from on that channel (an issue, a thread, a caller); the channel defines it. */
    address?: string;
    /** Files the run was started with, stored as artifacts of the run; the model gets them as file parts. */
    attachments?: Artifact[];
    /**
     * Who started the run; only ever set from an authenticator (never from a
     * payload). Absent for runs a channel started without one (cron, webhooks). With an invoker the
     * idempotency key is scoped to it, so only the same invoker's dispatch
     * is deduplicated (and gets its own first run).
     */
    invoker?: Invoker;
    /** The run that started this one; set only by dispatch() or the peer intake, never from engine.dispatch(). */
    parent?: TriggerParent;
    receivedAt: Date;
};

agent.on() (dispatch roles) is in core, see Dispatch. The other subscription builders live in the channel packages: http.on() and webhook.on() in @chamvi/http, cron.on() in @chamvi/channel-cron, github.on() in @chamvi/github. See Channels & the Envelope.

Engine ​

Use IEngine for engine type annotations and Engine for construction or extension. IEngine describes every public engine member and extends IContextProvider; it is also re-exported by @chamvi/app.

ts
class Engine {
    constructor(opts: EngineOptions);

    readonly clock: IClock;
    getAgent(name: string): Agent | undefined;
    listAgents(): Agent[];
    getChannel(name: string): IChannel | undefined;
    listChannels(): IChannel[];
    putAgent(agent: Agent, options?: { revision?: string; formerRevision?: string; reload?: boolean; signal?: AbortSignal }): Promise<'added' | 'replaced' | 'unchanged'>;
    checkAgent(agent: Agent): void;
    removeAgent(name: string): Promise<boolean>;
    releaseRevision(name: string): Promise<string[] | undefined>;
    agentRevision(name: string): string | undefined;
    provide<T>(key: ContextKey<T>, value: T): void; // IContextProvider, see Context

    dispatch(envelope: DispatchEnvelope): Promise<{ runId: string; deduplicated: boolean }>;
    getRun(id: string): Promise<Run | undefined>;
    on<T extends EngineEvent['type']>(event: T, listener: (e: Extract<EngineEvent, { type: T }>) => void): () => void;

    start(options?: { channels?: boolean }): Promise<void>;
    stop(): void;
    drain(opts?: { timeoutMs?: number }): Promise<void>;
    idle(): Promise<void>;
    readonly isDraining: boolean;

    cancel(runId: string): Promise<void>;
    approve(runId: string, answer: ApprovalAnswer): Promise<void>;
    tick(): Promise<void>;
    recover(): Promise<number>;
}
MethodDescriptionGuide
store, clockThe store and clock the engine was built with (clock defaults to systemClock)
getAgent, listAgentsOne registered agent by name; all of them in registration order (a new array), read at call time
getChannel, listChannelsOne registered channel by name; all of them in registration orderChannels
putAgentRegisters an agent or replaces the one of the same name in place (a new one goes last); refuses a subscription to an unknown channel like the constructor. Replacing cancels the agent's unsettled runs created before now. With a revision (a folder's content hash) the store's marker is brought to it under the lock agents:<name> instead, cancelling once across replicas and only when a marker existed (swept before and again after the marker write; no run of the agent starts on this engine meanwhile). Each cancelled run stores agent_replaced as its error (Errors), and the sweep emits agents.cancelled. With reload: false (a process that never reloads, a job) nothing is cancelled: a missing marker is written, a different one moved only while the agent has no unsettled run, else InvalidRunStateError and the agent stays unregistered. A marker at formerRevision (the same content hashed by an earlier algorithm) counts as equal and is moved to revision without a cancel. Optional signal cancels preparation and rejects with its reason before registry mutation, retaining the previous agent, marker and runs. Once the registry operation starts, cancellation waits for consistent completion and local publication. Resolves unchanged (no event) for the same agent object at the same revisionAgent Folders
checkAgentWhat putAgent refuses before any store access (a model that does not resolve, a subscription to an unknown channel), as InvalidAgentDefinitionError; registers and writes nothingAgent Folders
removeAgentUnregisters the agent here first (no further dispatch), then under the same lock cancels its unsettled runs and deletes its marker (when it has one, unless this engine had it at another revision: a newer one registered elsewhere stays), or without a marker cancels the runs of an agent registered here; each cancelled run stores agent_removed (Errors) and the sweep emits agents.cancelled; resolves whether it was registered hereAgent Folders
releaseRevisionFor an agent held without a revision (passed in code), clears a stored revision marker of its name left by a folder or package agent of an earlier deployment, as a revision change under the lock agents:<name>: its unsettled runs are cancelled with agent_replaced and the marker deleted, so no run waits for a revision no replica holds; emits agents.cancelled. A start of @chamvi/app calls it for every agent passed in code. Nothing happens without a marker, or for an agent held at a revision or not heldAgent Folders
agentRevisionThe revision an agent was registered at; undefined for an agent without a revision
dispatchStores a queued run (and its attachments as artifacts); deduplicates by idempotencyKey under <agent>:<channel>[:<kind>:<id>]Channels
getRunReads a run from the storeRun Lifecycle
onSubscribes to run.updated, step.appended, run.delta, agents.changed or agents.cancelled (AgentRunsCancelled { name, reason: 'agent_replaced' | 'agent_removed', revision?, runIds }, the runs whose cancel went through: a run on another replica only gets a cancel request and may still complete); returns an unsubscribe functionRun Lifecycle
startRecovers, starts every channel (unless { channels: false }; a throwing start stops those already started and rejects), starts polling and starts queued runs: only runs of an agent it holds, a folder agent only at the stored revision (the others stay queued)Recovery
stopStops every channel, then polling onlyRecovery
drainStops every channel first (a throwing stop goes to onError), waits for in-flight runs (default 30 s), then marks the rest interruptedRecovery
idleResolves when nothing runs and nothing more can start
cancelCancels locally, in the store, or requests it from the owning replicaRecovery
approveAnswers the current wait point by approvalId, onceApprovals
tickDenies expired approvals and re-sends approval messages a channel has not delivered; runs every pollApprovals
recoverRequeues abandoned runs; runs on start and every pollRecovery
ts
/*
 * 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 { LanguageModel, TranscriptionModel } from 'ai';
import type { Agent } from '../agent/types.ts';
import type { IArtifactService } from '../artifact/types.ts';
import type {
    ArtifactInput,
    ConversationIdentity,
    ConversationScope,
    Invoker,
    PeerStartInput,
    Run,
    Step,
    TriggerEnvelope,
} from '@chamvi/core-kit';
import type { ChannelContext, DispatchResult, IChannel } from '../channel/types.ts';
import type { IClock } from '../clock/index.ts';
import type { IContextProvider } from '../context/types.ts';
import type { ConversationInspection, ConversationOptions, IConversationService  } from '../conversation/types.ts';
import type { IModelResolver, ModelRef, TranscriptionModelRef } from '../model/types.ts';
import type { IPeerResolver } from '../peer/types.ts';
import type { SkillInput } from '../skill/types.ts';
import type { IAgentRevisionService } from '../agent-revision/types.ts';
import type { IConnectionService } from '../connection/types.ts';
import type { ICheckpointService } from '../checkpoint/types.ts';
import type { IEffectService } from '../effect/types.ts';
import type { IIdempotencyService } from '../idempotency/types.ts';
import type { ILimitService } from '../limit/types.ts';
import type { ILockService } from '../lock/types.ts';
import type { IRunService } from '../run/types.ts';
import type { IStateService } from '../state/types.ts';
import type { IStepService } from '../step/types.ts';

/** Public engine contract; use Engine only for construction or extension. */
export interface IEngine extends IContextProvider {
    /** The rules of runs over the run repository. */
    readonly runService: IRunService;
    /** The steps of runs over the step repository. */
    readonly stepService: IStepService;
    /** The latest checkpoint of each run over the checkpoint repository. */
    readonly checkpointService: ICheckpointService;
    /** Recorded effect results over the effect repository. */
    readonly effectService: IEffectService;
    /** The files of runs over the artifact repository. */
    readonly artifactService: IArtifactService;
    /** Agent state over the key-value and document repositories. */
    readonly stateService: IStateService;
    /** The revision markers of folder agents over the agent revision repository. */
    readonly agentRevisionService: IAgentRevisionService;
    /** Leases on keys over the lock repository (keyed runs, admission, the registry, approval deliveries). */
    readonly lockService: ILockService;
    /** The idempotency keys of dispatches over the idempotency repository. */
    readonly idempotencyService: IIdempotencyService;
    /**
     * Connections over the connection repository, when the store keeps
     * them; the engine itself uses none, code that holds an engine
     * (`createHttpApp`) reads them through it.
     */
    readonly connectionService: IConnectionService | undefined;
    /**
     * The counted uses of tool limits over the limit repository, when the
     * engine has it; an agent with `limits` needs it.
     */
    readonly limitService: ILimitService | undefined;
    /**
     * Conversations over the conversation repository, when the store keeps
     * them; the conversation capability (`conversations`) needs it.
     */
    readonly conversationService: IConversationService | undefined;
    /** The configured peers remote agents run at, when the app has any. */
    readonly peers: IPeerResolver | undefined;
    readonly clock: IClock;
    readonly isDraining: boolean;

    dispatch(envelope: DispatchEnvelope): Promise<{ runId: string; deduplicated: boolean }>;
    /**
     * Starts a run a peer asked for: the peer is the one `peers.recognize()`
     * names for `envelope.invoker`, the target its `agent.on()` role
     * `fields.role`, checked like a local cross-agent dispatch (`from` entry
     * `<peer>/<parent.agent>`); a refusal writes nothing (an unknown or
     * ungranted agent: AgentNotFoundError, else ValidationError).
     */
    dispatchPeer(envelope: DispatchEnvelope, fields: PeerStartInput['peer'] & { role: string }): Promise<DispatchResult>;
    inspectConversation(identity: ConversationIdentity, query?: { limit?: number; offset?: number }): Promise<ConversationInspection | undefined>;
    resetConversation(identity: ConversationIdentity, options?: { keepNotes?: boolean }): Promise<ConversationScope>;
    deleteConversation(identity: ConversationIdentity): Promise<void>;
    pruneConversations(): Promise<void>;
    /**
     * The LanguageModel for `ref`, else the model of `agent` in the live
     * registry, else the default (EngineOptions.model): a model outside a
     * tool call (e.g. a channel's). A string goes through
     * EngineOptions.models; without a resolver, or with no model at all,
     * it is an InvalidAgentDefinitionError.
     */
    resolveModel(ref?: ModelRef, agent?: string): LanguageModel;
    /**
     * The TranscriptionModel for `ref` (e.g. a channel's voice model): an
     * object as is, a string through EngineOptions.models' `transcription()`;
     * without a resolver or transcription models it is an
     * InvalidAgentDefinitionError.
     */
    resolveTranscriptionModel(ref: TranscriptionModelRef): TranscriptionModel;
    getAgent(name: string): Agent | undefined;
    listAgents(): Agent[];
    channelContext(channel: IChannel): ChannelContext;
    getChannel(name: string): IChannel | undefined;
    listChannels(): IChannel[];
    agentRevision(name: string): string | undefined;
    putAgent(agent: Agent, options?: {
        revision?: string;
        formerRevision?: string;
        reload?: boolean;
        signal?: AbortSignal;
    }): Promise<'added' | 'replaced' | 'unchanged'>;
    removeAgent(name: string): Promise<boolean>;
    releaseRevision(name: string): Promise<string[] | undefined>;
    getRun(id: string): Promise<Run | undefined>;
    on<T extends EngineEvent['type']>(event: T, listener: (e: Extract<EngineEvent, { type: T }>) => void): () => void;
    prepare(options?: { signal?: AbortSignal; agents?: readonly Agent[] }): Promise<void>;
    start(options?: EngineStartOptions): Promise<void>;
    stop(): Promise<void>;
    recover(): Promise<number>;
    drain(options?: { timeoutMs?: number }): Promise<void>;
    idle(): Promise<void>;
    cancel(runId: string): Promise<void>;
    approve(runId: string, answer: ApprovalAnswer): Promise<void>;
    /**
     * A peer's content-free wake of stand-in `runId` waiting on the peer
     * `invoker` authenticates as (the next tick polls it at once): `marked`
     * when this call set the mark, `pending` when it was set already;
     * `undefined`, with nothing written, for any other run or invoker.
     */
    wake(runId: string, invoker: Invoker | undefined): Promise<WakeOutcome | undefined>;
    tick(): Promise<void>;
    checkAgent(agent: Agent): void;
}

/**
 * A piece of model output while it streams; never stored. `step` is the
 * checkpoint step index the step it belongs to is saved under.
 */
export type RunDelta = {
    runId: string;
    step: number;
    kind: 'text' | 'reasoning';
    text: string;
};

export type RunEvent = { type: 'run.updated'; run: Run } |
    { type: 'step.appended'; step: Step } |
    { type: 'run.delta'; delta: RunDelta };

/** An agent was added, replaced or removed on this engine; local like the run events. */
export type AgentChange = {
    type: 'agents.changed';
    name: string;
    kind: 'added' | 'replaced' | 'removed';
};

/**
 * The unsettled runs a registry change cancelled: a revision change or a
 * replaced agent without a revision (`agent_replaced`), a removal (`agent_removed`).
 * Emitted once per sweep, by the engine that swept (so once across replicas),
 * also with no run ids. `runIds` are the runs whose cancel went through,
 * which is a request for a run executing on another replica (it may still
 * complete before that replica sees it) or being drained here (it settles
 * `interrupted`).
 */
export type AgentRunsCancelled = {
    type: 'agents.cancelled';
    name: string;
    reason: 'agent_replaced' | 'agent_removed';
    /** The revision the agent was reloaded at (a folder agent's replacement only). */
    revision?: string;
    /** The runs whose cancel went through (cancelled, or a cancel requested; see above). */
    runIds: string[];
};

/** Every event Engine.on() delivers. */
export type EngineEvent = RunEvent | AgentChange | AgentRunsCancelled;

export type EngineOptions = {
    /** Runs: built on the same clock as the engine's (`clock`). */
    runService: IRunService;
    stepService: IStepService;
    checkpointService: ICheckpointService;
    effectService: IEffectService;
    artifactService: IArtifactService;
    stateService: IStateService;
    agentRevisionService: IAgentRevisionService;
    /** Leases: built on the same clock as the engine's (`clock`). */
    lockService: ILockService;
    /** Dispatch idempotency keys: built on the same clock as the engine's (`clock`). */
    idempotencyService: IIdempotencyService;
    /**
     * Connections, when the store keeps them (optional); the engine uses
     * none, it exposes the service to code that holds the engine. Its
     * fence reads the lock rows `lockService` writes.
     */
    connectionService?: IConnectionService;
    /**
     * The counted uses of tool limits (optional): an agent with non-empty
     * `limits` is refused without it; built on the engine's clock, its
     * check locks through `lockService`.
     */
    limitService?: ILimitService;
    /**
     * Conversations, when the store keeps them (optional): required by the
     * conversation capability (`conversations`), built on the engine's
     * clock.
     */
    conversationService?: IConversationService;
    agents: Agent[];
    readonly skills?: readonly SkillInput[];
    /**
     * The channels runs come from and talk to; names unique. start() starts
     * them after the first recover, drain() and stop() stop them first.
     */
    channels?: IChannel<any, any>[];
    /**
     * The default model of agents without one; a string default is checked
     * through `models` at construction.
     */
    model?: ModelRef;
    /**
     * Resolves `'<provider>/<model id>'` strings. Registration (constructor,
     * putAgent) checks every string ref through it; without it a string ref is
     * an `InvalidAgentDefinitionError`.
     */
    models?: IModelResolver;
    /**
     * The peers remote agents run at; registration (constructor, putAgent)
     * refuses a remote agent whose peer it does not have, and any remote
     * agent without it (InvalidAgentDefinitionError).
     */
    peers?: IPeerResolver;
    /**
     * The conversation capability agents with `conversation: true` need: the
     * authorizer and the limits. Persistence comes from `conversationService`.
     */
    conversations?: ConversationOptions;
    /** Default `${hostname}-${pid}`. */
    owner?: string;
    /** Default 4. */
    concurrencyMaxRuns?: number;
    /** Default 60_000, renewed every ttl/3 while running. */
    claimTtlMs?: number;
    clock?: IClock;
    /** Receives errors that have no caller to throw to. Default console.error. */
    onError?: (error: unknown, run?: Run) => void;
};

/** What a peer's wake did to a stand-in's remote wait: set the mark, or found it set. */
export type WakeOutcome = 'marked' | 'pending';

/** A run to create; `parent` is no field: only the dispatch host (dispatch()) sets the lineage. */
export type DispatchEnvelope = Omit<TriggerEnvelope, 'id' | 'receivedAt' | 'attachments' | 'parent'> &
    Partial<Pick<TriggerEnvelope, 'id' | 'receivedAt'>> & {
        /** Files to start the run with; stored as artifacts of the run before it is created. */
        attachments?: ArtifactInput[];
        /**
         * The agent object the caller's permission check saw; never stored.
         * Another registered object for the name refuses the dispatch
         * (AgentReplacedError) before any store write; a replacement while
         * the run is created cancels that run (`agent_replaced`).
         */
        checked?: Agent;
    };

/** An answer to the run's current wait point (`Engine.approve()`). */
export type ApprovalAnswer = {
    /** Must equal `run.waiting.approvalId`, else InvalidRunStateError. */
    approvalId: string;
    approved: boolean;
    reason?: string;
    /** Who answered; recorded on the wait step (\`output.approver\`). */
    approver?: Invoker;
    /**
     * The chosen option ids of a wait point with options: exactly one for a
     * single choice, at least one for a multiple choice; none on a denial.
     */
    selected?: string[];
};

export type EngineStartOptions = {
    signal?: AbortSignal;
    /** Default true; false starts no channel (a one-shot job never starts schedules or sockets). */
    channels?: boolean;
};
OptionDefault
channels[]
owner`${hostname}-${pid}`
concurrencyMaxRuns4
claimTtlMs60_000, renewed and polled every claimTtlMs / 3
clocksystemClock
onErrorlogs to console.error

Runs ​

RunContext:

ts
/*
 * 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 { EntityFindManyResult, IRunRepository } from '@chamvi/store';
import type { IFilter, IQuery } from '@rapiq/core';
import type {
    Run,
    RunStatusLiteral,
    TriggerEnvelope,
    WaitPoint,
} from '@chamvi/core-kit';
import type { ActorContext } from '../actor/types.ts';
import type { IClock } from '../clock/index.ts';
import type { AgentScope } from '../permission/types.ts';


export type RunContext = {
    runId: string;
    agent: string;
    trigger: TriggerEnvelope;
    /** Aborts on cancel, drain, a lost lease or the run timeout, and once the execution has ended. */
    signal: AbortSignal;
};

export type RunServiceContext = {
    repository: IRunRepository;
    clock: IClock;
};

export type RunFindOptions = {
    agent?: string;
    /** Only the runs of these agents (an empty list matches none; an AND with `agent`). */
    agents?: readonly string[];
    status?: RunStatusLiteral[];
    concurrencyKey?: string;
    /** Only these run ids (an empty list matches none). */
    ids?: readonly string[];
    /** Only the runs dispatched by this run (`Run.parentRunId`). */
    parentRunId?: string;
    /** Only the runs dispatched by one of these runs (an empty list matches none). */
    parentRunIds?: readonly string[];
    /** Only the runs dispatched by some run (`true`, `Run.parentRunId` set) or by none (`false`). */
    hasParent?: boolean;
    /** Only the runs whose wait point (`Run.waiting`) is of this kind. */
    waitKind?: WaitPoint['kind'];
    limit?: number;
    offset?: number;
    order?: 'asc' | 'desc';
};

/** A checked run listing (an API query, decoded): its filters, an optional agent, the page and the sorts. */
export type RunListInput = {
    filters: IFilter[];
    agent?: string;
    limit: number;
    offset: number;
    sorts: Record<string, 'ASC' | 'DESC'>;
};

export type RunUpdateOptions = {
    expectStatus?: RunStatusLiteral[];
    expectOwner?: string;
    expectWaitId?: string;
    /** Keep the stored updatedAt when the patch sets none (default: stamped with now), for derived fields such as subtreeUsage. */
    keepUpdatedAt?: boolean;
};

/**
 * The operations of `RunService`. Anything that satisfies it can stand in
 * for the service: the engine, the channels and the HTTP API take this type.
 */
export interface IRunService {
    /**
     * Insert-if-absent: false when a run with that id is stored (the stored
     * run is left as it is). `parentRunId` comes from `trigger.parent.runId`,
     * never from the caller; a parent the store does not hold is
     * RunNotFoundError and nothing is written.
     */
    create(run: Run): Promise<boolean>;

    findOne(id: string): Promise<Run | undefined>;

    findOneOrFail(id: string): Promise<Run>;

    /**
     * Throws InvalidRunStateError when `expectStatus` does not hold the
     * current status, when `expectOwner` is given and the claim is absent or
     * held by another owner (expiry is not checked: a lease is lost once
     * taken over), or when `expectWaitId` is given and the wait id (`id`,
     * else `approvalId`) differs. `updatedAt` is stamped with now unless the
     * patch sets one or `keepUpdatedAt`; `id` and `parentRunId` never
     * change; a property set to `undefined` is cleared.
     */
    update(id: string, patch: Partial<Run>, expect?: RunUpdateOptions): Promise<Run>;

    /**
     * update() with the patch derived from a copy of the locked row, after
     * the checks (`derive` may throw to abort the write): a change to a
     * nested field (`waiting`) keeps what a concurrent write stored next to it.
     */
    updateWith(id: string, derive: (run: Run) => Partial<Run>, expect?: RunUpdateOptions): Promise<Run>;

    /**
     * Ordered by createdAt, ties broken by id, both ascending (`order`
     * `asc`, the default) or both descending; `total` ignores limit and
     * offset. Without `limit`, every matching run (from `offset`).
     */
    find(options?: RunFindOptions): Promise<{ data: Run[]; total: number }>;

    /** As `find`; RepositoryNotFoundError when the selected page is empty, even with a nonzero total. */
    findOrFail(options?: RunFindOptions): Promise<{ data: Run[]; total: number }>;

    /**
     * A rapiq query over the public run fields (filters, sorts, pagination),
     * for an API listing. A top-level `waiting` filter (`eq` with `approval`
     * or `dispatch`) selects the runs whose wait point is of that kind; a
     * `waiting` condition of any other shape is a ValidationError. Ordered
     * by the query's sorts, then by `id` in the direction of the last one
     * (createdAt, then id, ascending without sorts); `meta.total` ignores
     * the pagination.
     */
    list(query: IQuery): Promise<EntityFindManyResult<Run>>;

    /** Succeeds only when the run is unleased or its lease expired (at exactly `expiresAt`). */
    claim(id: string, owner: string, ttlMs: number): Promise<boolean>;

    /** Extends the lease to now + ttlMs; only for the current, unexpired owner. */
    renewClaim(id: string, owner: string, ttlMs: number): Promise<boolean>;

    /**
     * The run for the actor: RunNotFoundError for a missing run and for one
     * of an agent the actor may not read under the private-agent rule (the
     * same error, so run ids are not probed), else 403 `chamvi_run_read`.
     */
    getOne(id: string, actor: ActorContext, options: AgentScope): Promise<Run>;

    /**
     * The runs of a checked listing the actor may list, else 403: one
     * `list()` query with the permission scope (an `agent` filter) joined
     * to the input's filters, so `total` and the page stay exact.
     */
    getMany(input: RunListInput, actor: ActorContext, options: AgentScope): Promise<EntityFindManyResult<Run>>;

    /**
     * The run the actor may cancel: 403 without `chamvi_run_cancel` for some
     * run, then for the found run's `{ agent }`; `undefined` for a missing run.
     */
    getCancelable(id: string, actor: ActorContext): Promise<Run | undefined>;

    /**
     * The run the actor may answer approvals of: RunNotFoundError for a
     * missing run (no read permission needed), 403 without
     * `chamvi_agent_approve` for its agent.
     */
    getAnswerable(id: string, actor: ActorContext, options: AgentScope): Promise<Run>;
}

The records Run, RunStatusLiteral, WaitPoint, Usage, Budget, Step and Checkpoint, from @chamvi/core-kit:

ts
/*
 * 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 { ApprovalOption } from '../approval/types.ts';
import type { AttachmentRequestBody } from '../artifact/types.ts';
import type { ConversationBinding } from '../conversation/types.ts';
import type { Invoker, TriggerEnvelope } from '../trigger/types.ts';
import type { RunStatus } from './constants.ts';

export type RunStatusLiteral = `${RunStatus}`;

export type Usage = {
    inputTokens: number;
    outputTokens: number;
};

export type RunTaint = { at: Date; source: string };

/** The approval a `waiting` run waits on, as approve() requested it. */
export type ApprovalWaitPoint = {
    kind: 'approval';
    /** The generic wait id, always equal to `approvalId` (a stored wait point without it reads back with it). */
    id: string;
    /** `<stepIndex>:<toolCallId>:<n>` of the stored checkpoint's pending call: never changes after the pause. */
    approvalId: string;
    toolName: string;
    toolCallId: string;
    title: string;
    body?: string;
    /** Safe channel notification instead of private approval arguments. */
    notification?: string;
    /** The run's artifact ids shown with the request; absent when none. */
    artifacts?: string[];
    /** The choices of the request; absent for a plain yes or no. */
    options?: ApprovalOption[];
    /** Set (true) only when several options may be selected. */
    multiple?: boolean;
    /** The channel the request is delivered through; none for the inbox and API only. */
    channel?: string;
    address?: string;
    /** The named delivery slot, if requested. */
    slot?: string;
    expiresAt: Date;
    /** Set once the approval message went out through `channel`; tick() re-sends while it is missing. */
    notifiedAt?: Date;
};

/** The dispatched runs a `waiting` run waits on to settle. */
export type DispatchWaitPoint = {
    kind: 'dispatch';
    /** `<stepIndex>:<toolCallId>:w<n>`: never changes after the pause. */
    id: string;
    toolName: string;
    toolCallId: string;
    /** The runs waited on, in the caller's order (duplicates allowed). */
    runIds: string[];
    expiresAt: Date;
};

/** An approval pending in a remote run or below it, as the last poll showed it. */
export type RemoteApproval = {
    /** The remote run that waits on the approval. */
    runId: string;
    approvalId: string;
    title: string;
    /** The owning app's own approval link. */
    url?: string;
    /** Set once the notification to the configured destination went out. */
    notifiedAt?: Date;
};

/** The run of another chamvi app a stand-in run waits on to settle. */
export type RemoteWaitPoint = {
    kind: 'remote';
    id: 'remote';
    /** The configured peer that owns the remote run. */
    peer: string;
    /** The remote agent's name on the peer. */
    agent: string;
    remoteRunId: string;
    expiresAt: Date;
    /** Set by a wake from the peer: the next tick polls at once. */
    wakeRequested?: boolean;
    /** The remote run as the last poll showed it. */
    remote?: {
        status: RunStatusLiteral;
        approval?: RemoteApproval;
    };
};

/** What a `waiting` run waits on, by `kind`. */
export type WaitPoint = ApprovalWaitPoint | DispatchWaitPoint | RemoteWaitPoint;

export type Run = {
    id: string;
    agent: string;
    status: RunStatusLiteral;
    /** First exposure to untrusted content; never cleared by execution. */
    taint?: RunTaint;
    trigger: TriggerEnvelope;
    concurrencyKey?: string;
    /** Where the run came from on its channel (`trigger.address`). */
    address?: string;
    output?: unknown;
    /**
     * Why the run failed, or why the registry cancelled it (`agent_replaced`,
     * `agent_removed`); a run cancelled on another replica keeps the reason
     * through the owner's settle, a run that completes anyway loses it.
     */
    error?: { code: string; message: string };
    usage: Usage;
    /** The sum of every descendant's usage, recomputed from the children (never incremented). */
    subtreeUsage?: Usage;
    /**
     * The run that dispatched this one (`trigger.parent.runId` of a
     * `dispatch` parent; a peer parent names another app's run and sets
     * none); set by the run service at create, never from the caller.
     */
    parentRunId?: string;
    waiting?: WaitPoint;
    claim?: { owner: string; expiresAt: Date };
    /**
     * Set by cancel() on a replica that does not execute the run: the owner
     * aborts it on its next poll, and a later execution settles it cancelled.
     */
    cancelRequested?: boolean;
    /**
     * The revision the agent was registered at when the run was created
     * (a folder agent's content hash); absent for an agent without one.
     */
    agentRevision?: string;
    /** The conversation the run belongs to; set by the trusted conversation intake only, never by dispatch(). */
    conversation?: ConversationBinding;
    createdAt: Date;
    updatedAt: Date;
    startedAt?: Date;
    finishedAt?: Date;
};

export type Budget = {
    maxSteps: number;
    maxTokens?: number;
    /**
     * Wall-clock limit per execution (not cumulative across resumes): each
     * execution of the run gets the full timeout again.
     */
    timeoutMs?: number;
    /**
     * Total tokens (input + output) of every descendant dispatched below a
     * run of this agent: at or over it, dispatch() and dispatchTo() refuse
     * (checked at dispatch time only, running children are not stopped).
     */
    maxSubtreeTokens?: number;
};

/** An invoker or approver as the API serves it: its identity only, never its grants. */
export type InvokerView = Omit<Invoker, 'bindings' | 'authorization'>;

/**
 * A run as the API serves it (REST, SSE, MCP): its invoker carries the
 * identity only, never the grants.
 */
export type RunView = Omit<Run, 'claim' | 'trigger' | 'conversation'> & {
    /** What started the run; `payload` is absent when the run was started without one. */
    trigger: Omit<TriggerEnvelope, 'invoker' | 'payload'> & { payload?: unknown; invoker?: InvokerView };
    /**
     * The run's agent is private (or not held by the app), as the server
     * checks it: `{ name: agent, private: agentPrivate }` are the attributes
     * of the agent permissions (`chamvi_agent_approve`, ...). Read when the
     * run is serialized.
     */
    agentPrivate: boolean;
};

/** `POST /agents/{name}/runs` after validation: unknown keys dropped, attachment data still base64. */
export type StartRunBody = {
    payload?: unknown;
    idempotencyKey?: string;
    /** Where the run came from on the http channel (a caller-defined thread or conversation). */
    address?: string;
    attachments?: AttachmentRequestBody[];
};
ts
/*
 * 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.
 */

export type Step = {
    runId: string;
    index: number;
    kind: 'llm' | 'tool' | 'wait';
    name?: string;
    input?: unknown;
    output?: unknown;
    error?: unknown;
    startedAt: Date;
    finishedAt: Date;
};

/** A stored step: the step and the row's id (a uuid v7 the step service assigns when it appends the step). */
export type StepRecord = Step & {
    id: string;
};
ts
/*
 * 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 { ModelMessage } from 'ai';

export type Checkpoint = {
    runId: string;
    stepIndex: number;
    messages: ModelMessage[];
    /** AI SDK finish reason of the step this checkpoint was taken after. */
    finishReason?: string;
    /** Provenance of a conversation run's recalled context (not an authorization). */
    conversation?: {
        scopeId: string;
        generation: number;
    };
    createdAt: Date;
};

/** A stored checkpoint: the checkpoint and the row's storage id (a uuid). */
export type CheckpointRecord = Checkpoint & {
    id: string;
};

The RunStatus enum (@chamvi/core-kit), whose values RunStatusLiteral is built from:

ts
/*
 * 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.
 */

export enum RunStatus {
    QUEUED = 'queued',
    RUNNING = 'running',
    WAITING = 'waiting',
    COMPLETED = 'completed',
    FAILED = 'failed',
    CANCELLED = 'cancelled',
    INTERRUPTED = 'interrupted',
}

Services and repositories ​

There is no store aggregate: RunService, StepService, CheckpointService, EffectService, ArtifactService, StateService, LockService, IdempotencyService and AgentRevisionService hold the rules of runs, steps, checkpoints, effect results, artifacts, agent state, locks, idempotency keys and agent revision markers over the ports of @chamvi/store; EngineOptions takes each (runService, stepService, checkpointService, effectService, artifactService, stateService, lockService, idempotencyService, agentRevisionService). ConnectionService holds the connection rules over IConnectionRepository; EngineOptions takes it as an optional connectionService (exposed, unused by the engine), the connection vault and config store take it. ConversationService holds the conversation rules over IConversationRepository; EngineOptions takes it as an optional conversationService, required by the conversations capability. The ports are listed on the Repository Contract page.

Artifacts ​

Artifact (metadata) and ArtifactInput (a file to store), from @chamvi/core-kit, and IRunArtifacts (the tool context's artifacts):

ts
/*
 * 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.
 */

/** Metadata of a file stored for a run (an attachment or a tool output); the bytes are read separately. */
export type Artifact = {
    id: string;
    runId: string;
    agent: string;
    mediaType: string;
    filename?: string;
    /** Byte length of the data. */
    size: number;
    createdAt: Date;
};

/**
 * A stored artifact: the metadata, and beside it the two write-only
 * properties of the row. A read never returns either.
 */
export type ArtifactRecord = Artifact & {
    /** The private write identity within the run (unique per `runId`); matched by a where, never read back. */
    key?: string;
    /** The bytes `save`/`upsert` write when set; read only through `readData`. */
    data?: Uint8Array;
};

/** A file to store: an attachment at dispatch or a tool's `artifacts.put()`. */
export type ArtifactInput = {
    /**
     * `artifacts.put()` only (a dispatch attachment takes none): a stable name
     * within the run, 1 to 255 characters without NUL. A repeated put with that
     * key replaces the artifact and keeps its id. The key is private to the
     * store and never part of an `Artifact`.
     */
    key?: string;
    /** `type/subtype`, e.g. `image/png`. */
    mediaType: string;
    filename?: string;
    data: Uint8Array;
};

/** One attachment of `POST /agents/{name}/runs` as sent. */
export type AttachmentRequestBody = {
    /** `type/subtype`, e.g. `image/png`. */
    mediaType: string;
    filename?: string;
    /** The bytes in base64. */
    data: string;
};
ts
/*
 * 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 { ToolResultPart } from 'ai';
import type { IArtifactRepository } from '@chamvi/store';
import type { Artifact, ArtifactInput } from '@chamvi/core-kit';


/**
 * The artifacts of one run, part of the tool context. Not an effect by
 * itself: put `put()` inside a `defineEffectTool` to store a file exactly once.
 */
/**
 * The file item of a tool's `toModelOutput` content for an artifact
 * (`artifactFilePart()`): its data is the artifact's marker, which the
 * engine swaps for the bytes before each model call.
 */
export type ArtifactFilePart = Extract<
    Extract<ToolResultPart['output'], { type: 'content' }>['value'][number],
    { type: 'file' }
>;

export interface IRunArtifacts {
    /**
     * Stores a file as an artifact of the run (with `key`: replacing an artifact
     * stored with that key before and keeping its id).
     * Throws ValidationError for an invalid input.
     */
    put(input: ArtifactInput): Promise<Artifact>;
    /** An artifact of this run with its bytes; undefined for an unknown id or another run's artifact. */
    get(id: string): Promise<{ artifact: Artifact; data: Uint8Array } | undefined>;
    /** The run's artifacts, by createdAt then id. */
    list(): Promise<Artifact[]>;
}

export type ArtifactServiceContext = {
    repository: IArtifactRepository;
};

/**
 * The operations of `ArtifactService`. Anything that satisfies it can stand in
 * for the service: the engine, the channels and the HTTP API take this type.
 */
export interface IArtifactService {
    /**
     * Insert-if-absent: resolves false and keeps the stored artifact
     * (metadata and bytes) when an artifact with that id, or with `key` in
     * that run, exists.
     */
    create(artifact: Artifact, data: Uint8Array, key?: string): Promise<boolean>;

    /**
     * Upsert by `(runId, key)`: an absent key inserts the artifact as
     * given; an existing one keeps its `id`, `agent` and `createdAt`,
     * replaces `mediaType`, `filename` (removed when absent), `size` and the
     * bytes. Resolves the stored metadata.
     */
    save(artifact: Artifact, data: Uint8Array, key: string): Promise<Artifact>;

    /** Metadata only. */
    findOne(id: string): Promise<Artifact | undefined>;

    /** As `findOne`; ArtifactNotFoundError when absent. */
    findOneOrFail(id: string): Promise<Artifact>;

    /** Metadata of the run's artifact stored under `key`. */
    findOneByKey(runId: string, key: string): Promise<Artifact | undefined>;

    /** The bytes, as a plain Uint8Array (no Buffer or other subclass). */
    read(id: string): Promise<Uint8Array | undefined>;

    /** Metadata of a run's artifacts, ordered by createdAt ascending, ties broken by id ascending. */
    find(runId: string): Promise<Artifact[]>;

    /** As `find`; RepositoryNotFoundError when the run has no artifact. */
    findOrFail(runId: string): Promise<Artifact[]>;
}

isArtifactMediaType(value: unknown): value is string (@chamvi/core-kit) is the media type rule dispatch and artifacts.put() apply: type/subtype (RFC 6838 restricted names) without parameters. An intake layer can check attachments with it before dispatching (@chamvi/http does).

artifactFilePart(artifact) is the file item a tool's toModelOutput returns to show an artifact of the run to the model (an image it stored with artifacts.put()): its data is the artifact's marker, so the tool step and the checkpoints keep the id while the engine hands the model the bytes before each model call.

See Files and Attachments.

Optional artifact discovery and processing tools are in @chamvi/tool-files. They use these native artifact types.

Tools ​

ts
function defineTool<I, O, S extends StateSchema = StateSchema>(
    def: Tool<I, O, ToolContext<S>> & {
        execute: ToolExecuteFunction<I, O, ToolContext<S>>;
        contextSchema?: never;
    },
): Tool<I, O, ToolContext<S>>;

function toolCallKey(ctx: Pick<ToolContext, 'run'>): string;

const toolContextSchema: StandardSchemaV1<ToolContext, ToolContext>; // vendor 'chamvi'

defineTool() is tool() with contextSchema: toolContextSchema; the engine hands the run's ToolContext to every tool carrying that schema (by reference, so a copy of the tool keeps it). Its validate returns the context unchanged and rejects a missing one, which fails the run (validation_error) with Type validation failed for tool context (<tool>): No chamvi tool context: the tool was built by another copy of @chamvi/core, or runs outside a chamvi agent. (the marker is the schema object itself, so a tool from a second copy of @chamvi/core gets no context).

toolCallKey(ctx) returns an opaque key for the active run, model step and tool call. It stays the same when that call replays and differs for calls in later steps even if a provider reuses toolCallId. Use it when run-local artifact keys must preserve earlier results. It throws InvalidRunStateError outside an active call or with another run's context. It does not record an effect or prevent computation from repeating.

ts
/*
 * 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 { IRunArtifacts } from '../artifact/types.ts';
import type { ToolChannels } from '../channel/types.ts';
import type { RunContext } from '../run/types.ts';
import type { IAgentState, StateSchema } from '../state/types.ts';

/** Run-level trust flags, evaluated on final validated input; omitted flags are false. */
export type ToolTrust<I = any, S extends StateSchema = StateSchema> = {
    /** Taint the whole run before exposing this call's potentially untrusted result or execution error. */
    taint?: boolean | ((input: I, ctx: ToolContext<S>) => boolean | Promise<boolean>);

    /** Apply the agent's approval-or-deny policy before execution if the run is already tainted. */
    guardWhenTainted?: boolean | ((input: I, ctx: ToolContext<S>) => boolean | Promise<boolean>);

    /**
     * Extra private detail of the outbound gate's approval (e.g. the commits
     * a push sends), computed on the final input when the gate asks: it goes
     * into the private approval body (inbox and API, never the source
     * channel's notification) and into the decision's binding, so a changed
     * detail on replay asks again. The tool reads `outboundApproved(ctx)` to
     * skip an approval of its own the gate already covered.
     */
    approvalDetail?: (input: I, ctx: ToolContext<S>) => string | undefined | Promise<string | undefined>;
};

export type AgentTrust = {
    /** Policy for guarded calls in tainted runs; defaults to 'approve'. */
    onTainted?: 'approve' | 'deny';
    /** Boolean overrides by tool name; false disables the corresponding tool flag. */
    tools?: Record<string, { taint?: boolean; guardWhenTainted?: boolean }>;
};

/**
 * What a chamvi tool gets as `context`: one object per execution, shared by
 * every call and the tools factory. Treat it as immutable. Engine-provided
 * values are reached with `inject(ctx, key)`, never as a field.
 */
export type ToolContext<S extends StateSchema = StateSchema> = {
    /**
     * Run-bound handles on the engine's channels with `out`: `findOne(name?)`
     * (no name: the channel the run came from), `findOneOrFail(name?)`, `find()`.
     */
    channels: ToolChannels;
    run: RunContext;
    state: IAgentState<S>;
    /**
     * The run's artifacts (its attachments and files tools stored). Not an
     * effect: put `put()` inside a `defineEffectTool` to store a file exactly once.
     */
    artifacts: IRunArtifacts;
};

See Tools and their context.

Context ​

ts
function defineContextKey<T>(name: string): ContextKey<T>;                      // a new frozen key per call; empty name -> InvalidAgentDefinitionError
function inject<T>(ctx: ToolContext, key: ContextKey<T>): T;                    // else ContextNotProvidedError ('context_not_provided')
function tryInject<T>(ctx: ToolContext, key: ContextKey<T>): T | undefined;
function injectClock(ctx: ToolContext): IClock;                               // the engine's clock inside a tool; ContextNotProvidedError on a context the engine did not pass

engine.provide(key, value) (Engine implements IContextProvider) keeps the value by reference and refuses a foreign key, undefined and a second value for one key (InvalidAgentDefinitionError naming the key). inject reads the engine's values for the ToolContext the engine built for the execution (tool execute, the tools factory, alreadyApplied, effectKey); ToolContext ({ run, state, artifacts, channels }) gains no field for a provided value, and nothing provided is stored or serialized. A missing value is a tool error in execute and the effect hooks and fails the run in the factory. See Context.

ts
/*
 * 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.
 */

declare const CONTEXT_VALUE: unique symbol;

/**
 * A typed key for a value provided on the engine; unique per
 * `defineContextKey()` call, its name is used in messages only.
 */
export type ContextKey<T> = {
    readonly name: string;
    /** Carries the value type only; never set. */
    readonly [CONTEXT_VALUE]?: T;
};

/** Holds values tools reach through `inject(ctx, key)`. */
export interface IContextProvider {
    /** Stores `value` by reference under `key`. */
    provide<T>(key: ContextKey<T>, value: T): void;
}

Models ​

ts
function resolveModel<S extends StateSchema = StateSchema>(ctx: ToolContext<S>, ref?: ModelRef): LanguageModel;
function checkAgentModel(agent: Agent, options: ModelCheckOptions): void;      // InvalidAgentDefinitionError

A ModelRef is a '<provider>/<model id>' string or an AI SDK LanguageModel object (used as is). An agent's model falls back to EngineOptions.model; the engine refuses an agent with neither, a ref of another shape, a string without EngineOptions.models (IModelResolver; pass a LanguageModel object then) and a string the resolver refuses, at construction and in putAgent (checkAgentModel is that check; a string default without a resolver is refused at construction too). Strings resolve through models.resolve() when an execution starts; the engine never hands the AI SDK a string. @chamvi/app passes both from its model settings (MODEL, chamvi.json, createApp({ model, providers })).

resolveModel(ctx, ref?) gives tool code (execute, the tools factory, the effect hooks) a model: ref, else the run's agent model from the live registry, else the default. An object is returned as is; a string needs models (resolveModel(): the model string "<ref>" needs a model resolver (EngineOptions.models).) and a ref it cannot resolve is an InvalidAgentDefinitionError too, a tool error in execute. It reads the engine's models through the context mechanism, so ToolContext keeps its shape and a hand-built context throws ContextNotProvidedError.

ts

/**
 * A model: `'<provider>/<model id>'` (split at the first `/`, resolved
 * through the engine's IModelResolver) or an AI SDK LanguageModel object,
 * used as is.
 */
export type ModelRef = string | LanguageModel;

/**
 * A transcription (speech to text) model: `'<provider>/<model id>'`
 * (resolved through IModelResolver.transcription()) or an AI SDK
 * TranscriptionModel object, used as is.
 */
export type TranscriptionModelRef = string | TranscriptionModel;

/** Turns `'<provider>/<model id>'` strings into LanguageModel (and, optionally, EmbeddingModel) objects. */
export interface IModelResolver {
    /**
     * Refuses a ref that cannot resolve (unknown provider, missing setting)
     * with InvalidAgentDefinitionError; `agent` is undefined for the app's
     * default model.
     */
    check(ref: string, agent?: string): void;
    /** The LanguageModel for `ref`; InvalidAgentDefinitionError when it cannot resolve. */
    resolve(ref: string): LanguageModel;
    /**
     * The EmbeddingModel for `ref` (`'<provider>/<model id>'`), for packages
     * that embed text; InvalidAgentDefinitionError when it cannot resolve.
     * Optional: a resolver without it hands out no embedding models.
     */
    embedding?(ref: string): EmbeddingModel;
    /**
     * The TranscriptionModel for `ref` (`'<provider>/<model id>'`), for
     * packages that transcribe audio; InvalidAgentDefinitionError when it
     * cannot resolve. Optional: a resolver without it hands out no
     * transcription models.
     */
    transcription?(ref: string): TranscriptionModel;
}

/** What checkAgentModel() reads besides the agent: the engine's default and resolver. */
export type ModelCheckOptions = {
    model?: ModelRef;
    models?: IModelResolver;
};

Effect tools ​

ts
function defineEffectTool<I, O, S extends StateSchema = StateSchema>(def: Tool<I, O, ToolContext<S>> & {
    execute: ToolExecuteFunction<I, O, ToolContext<S>>;
    contextSchema?: never;
    effectKey?: (input: I, ctx: ToolContext<S>, options: ToolExecutionOptions<ToolContext<S>>) => string;
    alreadyApplied?: (effectKey: string, input: I, ctx: ToolContext<S>) => Promise<O | undefined>;
}): EffectTool<I, O, S>;

function effectMarker(effectKey: string): string; // '<!-- chamvi:effect=<key> -->'

function wrapToolsForRun(
    tools: ToolSet,
    ctx: ToolContext,
    effects: Pick<EffectService, 'findOne' | 'save'>,
    options?: { allow?: (toolName: string) => boolean; hooks?: AgentHooks },
): ToolSet;

const EFFECT: unique symbol; // marks a tool as an effect tool

See Effect Tools & Reconciliation.

Approvals ​

ts
function approve(ctx: ToolContext, request: ApprovalRequestInput): Promise<ApprovalDecision>; // inside a tool call only

const DEFAULT_APPROVAL_TIMEOUT_MS: 86_400_000; // 24 hours
const APPROVAL_TIMEOUT_MAX_MS: 2_147_483_647;
const APPROVAL_OPTIONS_MAX: 20; // @chamvi/core-kit
const APPROVAL_OPTION_ID_PATTERN: RegExp; // /^[A-Za-z0-9@][\w.:/@+-]{0,127}$/
const APPROVAL_OPTION_LABEL_MAX_LENGTH: 200;
const APPROVAL_OPTION_DETAIL_MAX_LENGTH: 20_000;
const APPROVAL_OPTIONS_DETAIL_MAX_LENGTH: 100_000; // all details of one request
ts
/*
 * 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.
 */

/** One choice of an approval request; `detail` is shown in the UI only (e.g. a diff). */
export type ApprovalOption = {
    id: string;
    label: string;
    detail?: string;
    /**
     * Ids of this run's artifacts to show with the option (e.g. from
     * `ctx.artifacts.put()`), at most APPROVAL_ARTIFACTS_PER_OPTION_MAX,
     * unique. Not part of channel messages.
     */
    artifacts?: string[];
};

/** `POST /runs/{id}/approve`. */
export type ApproveBody = {
    /** The wait point being answered. */
    approvalId: string;
    approved: boolean;
    reason?: string;
    /** The chosen option ids of a wait point with options; none on a denial. */
    selected?: string[];
};
ts
/*
 * 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 { ToolCallFrame } from '../effect/types.ts';
import type { ApprovalRequest } from '../engine/execute/types.ts';
import type { ApprovalOption, Invoker } from '@chamvi/core-kit';

/** What a tool asks the owner to approve (`approve()`, `ChannelHandle.approve()`). */
export type ApprovalRequestInput = {
    title: string;
    body?: string;
    /**
     * Ids of this run's artifacts to show with the request (e.g. from
     * `ctx.artifacts.put()`), unique; together with the options' at most
     * APPROVAL_ARTIFACTS_MAX. Not part of channel messages.
     */
    artifacts?: string[];
    /** Choices to pick from; without them the approval is a plain yes or no. */
    options?: ApprovalOption[];
    /** Several options may be selected; default one. Needs `options`. */
    multiple?: boolean;
    /** How long the approval waits before it is denied; default 24 h. */
    timeoutMs?: number;
};

/** The owner's answer to an approval request. */
export type ApprovalDecision = {
    approved: boolean;
    reason?: string;
    /** Who answered, when known. */
    approver?: Invoker;
    /** The selected option ids in the request's option order; only on an approval of a request with options. */
    selected?: string[];
};

/** A plain approval ordinal taken before any await (internal, not exported): see reserveApproval(). */
export type ApprovalReservation = {
    frame: ToolCallFrame;
    choice: Pick<ApprovalRequest, 'options' | 'multiple' | 'artifacts'>;
    ordinal: number;
};

approve() outside a tool call, or in a streaming tool's body, throws InvalidRunStateError; a timeoutMs that is no positive integer up to APPROVAL_TIMEOUT_MAX_MS is a ValidationError, as are options outside the limits above (see Offering options). ChannelHandle.approve() is the same with the request delivered through the channel. The agent hooks (AgentHooks, ToolCallInfo) are on AgentDefinition above. See Approvals & Hooks.

Dispatch ​

ts
const agent: AgentSubscriber; // agent.on(options?): a role of the channel 'agent'
function agentChannel(): IChannel; // name 'agent', no in, no out
function dispatch(ctx: ToolContext, input: DispatchInput): Promise<DispatchResult>; // the own agent
function dispatchTo(ctx: ToolContext, input: DispatchToInput): Promise<DispatchResult>; // another agent
function waitForDispatch(ctx: ToolContext, run: string | DispatchResult, options?: DispatchWaitOptions): Promise<DispatchOutcome>;
function waitForDispatch(ctx: ToolContext, runs: Array<string | DispatchResult>, options?: DispatchWaitOptions): Promise<DispatchOutcome[]>;
function normalizeWaitPoint(raw: Record<string, unknown>): WaitPoint; // for repositories: a legacy approval gets its id
function waitIdOf(waiting: WaitPoint | undefined): string | undefined; // id, else approvalId
function dispatchTools(options: DispatchToolsOptions): ToolSet; // dispatch_<role>, dispatch_<agent>_<role>

const DEFAULT_DISPATCH_ROLE: 'default';
const DEFAULT_DISPATCH_MAX_DEPTH: 1;
const DISPATCH_DEPTH_MAX: 8; // @chamvi/core-kit
const DEFAULT_MAX_DISPATCHES_PER_RUN: 100;
const DEFAULT_DISPATCH_WAIT_TIMEOUT_MS: 86_400_000; // 24 hours

AgentSubscriptionOptions, AgentSubscriber, DispatchInput, DispatchToInput, DispatchOutcome, DispatchWaitOptions and DispatchToolsOptions (DispatchHost, DispatchRunSnapshot, DispatchWaitRecord, RoleToolInput and DispatchToolTarget are internal):

ts
/*
 * 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 { StandardSchemaV1 } from '@standard-schema/spec';
import type { FlexibleSchema } from 'ai';
import type { Agent } from '../agent/types.ts';
import type { ChannelSubscription, DispatchResult } from '../channel/types.ts';
import type { IClock } from '../clock/types.ts';
import type { DispatchEnvelope } from '../engine/types.ts';
import type { IEffectService } from '../effect/types.ts';
import type { ILockService } from '../lock/types.ts';
import type { IRunService } from '../run/types.ts';
import type { IPeerResolver } from '../peer/types.ts';
import type {
    Invoker,
    PeerParent,
    PeerStartInput,
    TriggerParent,
    TriggerSource,
} from '@chamvi/core-kit';

export type AgentSubscriptionOptions<P = unknown> = {
    /** The role (the subscription id), following the channel-name rule; default `default`. */
    role?: string;
    /** Parses the payload a tool dispatches; the parsed value is the child's payload. */
    schema?: StandardSchemaV1<unknown, P>;
    /** How many dispatches of this role one run may start (all executions together), default 100. */
    maxPerRun?: number;
    /** The other agents whose runs may dispatch to this role (agent names); the own agent always may. */
    from?: string[];
    /** The deepest a run of this role may sit in a dispatch tree (a root run has depth 0), 1 to 8, default 1. */
    maxDepth?: number;
    /** Shared-store execution cap within the agent; omitted or false adds no cap. */
    concurrencyMaxRuns?: number | false;
    /** The child's concurrency key when the call gives none. */
    concurrencyKey?(payload: P): string | undefined;
    /** The child's idempotency key when the call gives none. */
    idempotencyKey?(payload: P): string | undefined;
    /** The child's address when the call gives none; deterministic (it feeds the dispatch's dedupe key). */
    address?(payload: P): string | undefined;
    /** What the role does, for a generated dispatch tool's description. */
    description?: string;
};

/** Makes a role of the `agent` channel (subscription id = role): the opt-in for dispatch(). */
export type AgentSubscriber = {
    on<P = unknown>(options?: AgentSubscriptionOptions<P>): ChannelSubscription<P>;
};

export type DispatchInput = {
    /** The receiving `agent.on()` role; default `default`. */
    role?: string;
    /** The child run's payload (required), parsed by the role's schema. */
    payload: unknown;
    /** Dedupes across runs: a second dispatch under the same key gets the first child. */
    idempotencyKey?: string;
    concurrencyKey?: string;
    /** The child's `trigger.address` (and `Run.address`). */
    address?: string;
    /**
     * A channel and address the child may `emit()` and `approve()` to
     * without the outbound gate, as if it were the child's own source
     * (stored as `trigger.parent.source`). The exemption is only as safe as
     * the code choosing it: take the address from trusted data (an API
     * response read in code), never from model input. Generated dispatch
     * tools never set it.
     */
    source?: TriggerSource;
};

/** dispatchTo()'s input: a dispatch to the `agent.on()` role of `agent`. */
export type DispatchToInput = DispatchInput & {
    /** The receiving agent (the calling run's own agent behaves as dispatch()). */
    agent: string;
};

/** How a dispatched run ended, as waitForDispatch() reports it. */
export type DispatchOutcome = {
    runId: string;
    agent: string;
    role: string;
    /** `timeout`: the wait expired on a run another run dispatched (it keeps running), or on one whose cancel did not land within one claim TTL. */
    status: 'completed' | 'failed' | 'cancelled' | 'timeout';
    /** A completed run's output. */
    output?: unknown;
    /** A failed or cancelled run's error (a wait that expired: code `Timeout`). */
    error?: { code: string; message: string };
};

export type DispatchWaitOptions = {
    /** How long the run waits before the wait expires; 1 to APPROVAL_TIMEOUT_MAX_MS, default 24 h. */
    timeoutMs?: number;
};

/** What `dispatch-wait:<runId>:<waitId>` records (internal): the outcomes in `runIds` order, the tainted run ids. */
export type DispatchWaitRecord = {
    outcomes: DispatchOutcome[];
    tainted: string[];
};

/** The engine's copy of a run dispatch() reads (internal). */
export type DispatchRunSnapshot = {
    readonly runId: string;
    readonly agent: string;
    readonly invoker?: Invoker;
    readonly parent?: TriggerParent;
};

/** The engine side of dispatch() (internal, provided under DISPATCH_CONTEXT). */
export type DispatchHost = {
    getAgent(name: string): Agent | undefined;
    /** True for a channel registered on the engine. */
    hasChannel(name: string): boolean;
    /** The engine clock: the time a permission check of a cross-agent dispatch evaluates at. */
    clock: IClock;
    effects: Pick<IEffectService, 'findOne' | 'save'>;
    runs: Pick<IRunService, 'findOne' | 'find'>;
    /** Creates the run with `parent` as its lineage (engine.dispatch() never sets one). */
    createRun(envelope: DispatchEnvelope, parent: TriggerParent): Promise<DispatchResult>;
    /** Runs `fn` after every earlier call of the same run settled (the count and children read-check-write). */
    serial<T>(runId: string, fn: () => Promise<T>): Promise<T>;
    /** Dispatches in flight by effect key, so identical parallel calls share one. */
    inflight: Map<string, Promise<DispatchResult>>;
};

/** What a peer's start names besides the envelope: the caller's lineage, its taint and the receiving role. */
export type PeerDispatchFields = PeerStartInput['peer'] & {
    /** The receiving `agent.on()` role. */
    role: string;
};

/** The engine side of a peer's start (internal): dispatchPeer() checks, counts and creates through it. */
export type PeerDispatchHost = Pick<DispatchHost, 'getAgent' | 'clock' | 'effects' | 'serial'> & {
    peers: IPeerResolver | undefined;
    /** The store lock of the `peer-count:` read-check-write across replicas. */
    locks: Pick<ILockService, 'acquire' | 'release'>;
    /** That lock's TTL. */
    lockTtlMs: number;
    /** Creates the run with the peer lineage; `taintSource` taints it from the start. */
    createRun(envelope: DispatchEnvelope, parent: PeerParent, taintSource: string | undefined): Promise<DispatchResult>;
};

/**
 * A role schema as a generated tool's input: the AI SDK schema the model
 * sees and validates against, and how a validated input becomes the payload.
 */
export type RoleToolInput = {
    inputSchema: FlexibleSchema<unknown>;
    toPayload(input: unknown): unknown;
};

export type DispatchToolsOptions = {
    /** Roles of the calling agent: one `dispatch_<role>` tool each, calling dispatch(). */
    roles?: string[];
    /** Roles of other agents: one `dispatch_<agent>_<role>` tool each, calling dispatchTo(). */
    agents?: { agent: string; roles: string[] }[];
    /** Every generated tool waits for its child (waitForDispatch()) and returns the DispatchOutcome. */
    wait?: boolean | DispatchWaitOptions;
};

/** What a dispatchTools() placeholder stands for (internal): `agent` unset for the calling agent. */
export type DispatchToolTarget = {
    agent?: string;
    role: string;
    wait: false | DispatchWaitOptions;
};

dispatch(), dispatchTo() and waitForDispatch() run inside a tool call (or a simple agent's run()) only (InvalidRunStateError elsewhere; waitForDispatch() also in a streaming tool's body). A missing role, a caller not in from, a too deep child, the per-run limit, an invoker without chamvi_agent_run for the target, a held concurrency key and a run this run did not dispatch are ValidationError tool errors (a simple agent's run fails instead); a reached budget.maxSubtreeTokens is a BudgetExceededError tool error. dispatchTools() throws InvalidAgentDefinitionError for no role, a bad name, a name over 64 characters, a role listed twice or a bad wait. See Dispatch and Generated dispatch tools.

State ​

ts
function createAgentState<S extends StateSchema = StateSchema>(
    agent: string,
    schema: S | undefined,
    state: Pick<StateService, 'findOne' | 'set' | 'findDocuments' | 'upsertDocument' | 'deleteDocument'>,
): IAgentState<S>;

function createStateTools<S extends StateSchema>(schema: S): ToolSet; // the tools read context.state
ts
/*
 * 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 { StandardSchemaV1 } from '@standard-schema/spec';
import type { IStateDocumentRepository, IStateRepository } from '@chamvi/store';
import type { IQuery } from '@rapiq/core';
import type { ActorContext } from '../actor/types.ts';
import type { AgentScope } from '../permission/types.ts';

export type StateSchema = Record<string, StandardSchemaV1>;
export type Infer<T extends StandardSchemaV1> = StandardSchemaV1.InferOutput<T>;

export interface IAgentState<S extends StateSchema = StateSchema> {
    get<T = unknown>(key: string): Promise<T | undefined>;
    set(key: string, value: unknown): Promise<void>;
    collection<K extends keyof S & string>(name: K): {
        list(q?: { where?: Partial<Infer<S[K]>>; limit?: number }): Promise<Array<{ id: string } & Infer<S[K]>>>;
        /** Validates `doc` via the collection's Standard Schema; throws ValidationError and stores nothing on failure. */
        upsert(id: string, doc: Infer<S[K]>): Promise<void>;
        remove(id: string): Promise<void>;
    };
}

export type StateServiceContext = {
    /** The key-value port. */
    repository: IStateRepository;
    /** The document port. */
    documentRepository: IStateDocumentRepository;
};

export type StateFindOptions = { limit?: number; offset?: number };

export type StateDocumentFindOptions = { where?: Record<string, unknown>; limit?: number };

/** One key of an agent's state. */
export type StateEntryValue = { key: string; value: unknown };

/** One document of a collection: its id and the document. */
export type StateDocumentValue = { id: string; doc: unknown };

/**
 * The rapiq query of an actor listing, or a function that builds it: a
 * function runs only after the checks pass, so a caller's malformed-query
 * 400 never precedes the 403 or 404.
 */
export type StateQueryInput = IQuery | (() => IQuery);

/**
 * The operations of `StateService`. Anything that satisfies it can stand in
 * for the service: the engine, the channels and the HTTP API take this type.
 */
export interface IStateService {
    /** The value of the key; `undefined` when the agent holds none (a stored falsy value is present). */
    findOne(agent: string, key: string): Promise<unknown>;

    /** As `findOne`; RepositoryNotFoundError when the key is absent. */
    findOneOrFail(agent: string, key: string): Promise<unknown>;

    /** Stores `value` under the key, replacing a stored one; `undefined` removes the key. Resolves the stored value. */
    set(agent: string, key: string, value: unknown): Promise<unknown>;

    /**
     * One agent's entries ordered by key in code-point order; every entry
     * (from `offset`) without `limit`.
     */
    find(agent: string, options?: StateFindOptions): Promise<StateEntryValue[]>;

    /**
     * An agent's keys by a rapiq query over the entry fields (`key`,
     * `value`), for an API listing: its filters joined with the agent's,
     * its sorts, then `key` in code-point order, its pagination.
     */
    list(agent: string, query: IQuery): Promise<StateEntryValue[]>;

    /** As `find`; RepositoryNotFoundError when the selected page is empty. */
    findOrFail(agent: string, options?: StateFindOptions): Promise<StateEntryValue[]>;

    /**
     * The documents of a collection, ordered by document id in code-point
     * order; `where` matches by top-level equality (an `undefined` value
     * matches an object document lacking the key).
     */
    findDocuments(
        agent: string,
        collection: string,
        options?: StateDocumentFindOptions,
    ): Promise<StateDocumentValue[]>;

    /**
     * A collection's documents by a rapiq query, for an API listing: its
     * top-level `eq` filters as the top-level equality of `findDocuments`
     * (a field path is a document key), its limit and offset, ordered by
     * document id. Any other condition and any sort is a ValidationError.
     */
    listDocuments(agent: string, collection: string, query: IQuery): Promise<StateDocumentValue[]>;

    /** As `findDocuments`; RepositoryNotFoundError when the selected page is empty. */
    findDocumentsOrFail(
        agent: string,
        collection: string,
        options?: StateDocumentFindOptions,
    ): Promise<StateDocumentValue[]>;

    /** Stores the document, replacing a stored one of that id; `undefined` is stored as `null`. */
    upsertDocument(agent: string, collection: string, id: string, doc: unknown): Promise<StateDocumentValue>;

    /** Removes the document; a missing one is a no-op. */
    deleteDocument(agent: string, collection: string, id: string): Promise<void>;

    /**
     * The agent's keys by a rapiq query (`list`), for the actor. Each actor
     * method checks, in this order: `chamvi_state_read` (`save`:
     * `chamvi_state_write`) for `{ name }` (403), the agent in
     * `options.agents` (404), then for a private agent `chamvi_agent_read` (403).
     */
    getMany(agent: string, query: StateQueryInput, actor: ActorContext, options: AgentScope): Promise<StateEntryValue[]>;

    /** The value of the key (`findOne`), for the actor, after the checks of `getMany`. */
    getOne(agent: string, key: string, actor: ActorContext, options: AgentScope): Promise<unknown>;

    /**
     * Validates the untrusted body (`{ value }`, 400) after the checks of `getMany`, then
     * `set`s its value; resolves the validated value.
     */
    save(agent: string, key: string, data: unknown, actor: ActorContext, options: AgentScope): Promise<unknown>;

    /** A collection's documents (`listDocuments`) after the checks of `getMany`; 404 for a collection the agent does not declare. */
    getDocuments(agent: string, collection: string, query: StateQueryInput, actor: ActorContext, options: AgentScope): Promise<StateDocumentValue[]>;
}

See Agent State.

Clock ​

ts
const systemClock: IClock;
ts
/*
 * 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.
 */

export type ClockTimer = {
    clear(): void;
    /**
     * Lets the process exit while the timer is pending; a fake clock
     * leaves it out.
     */
    unref?(): void;
};

export interface IClock {
    /** Epoch milliseconds, wall time. */
    now(): number;
    setTimeout(fn: () => void, ms: number): ClockTimer;
}

now() is wall time in epoch milliseconds. A systemClock timer keeps the process alive until its unref() is called; chamvi unrefs every timer of its own except the drain deadline, the runJob() poll and the shutdown and force-exit deadlines.

Errors ​

ChamviError, InvalidAgentDefinitionError, AgentNotFoundError, ChannelNotFoundError, ContextNotProvidedError, InvalidRunStateError, RunNotFoundError, ArtifactNotFoundError, BudgetExceededError, TimeoutError, FatalToolError, IncompleteResponseError, ToolNotAllowedError, ToolDeniedError, LeaseLostError, SandboxError, ValidationError and ErrorCode:

ts
/*
 * 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.
 */

export const ErrorCode = {
    AGENT_NOT_FOUND: 'agent_not_found',
    AGENT_REMOVED: 'agent_removed',
    AGENT_REPLACED: 'agent_replaced',
    ARTIFACT_NOT_FOUND: 'artifact_not_found',
    BAD_REQUEST: 'bad_request',
    BUDGET_EXCEEDED: 'BudgetExceeded',
    CHANNEL_NOT_FOUND: 'channel_not_found',
    CONFLICT: 'conflict',
    CONNECTION_CHANGED: 'connection_changed',
    CONNECTION_HELD: 'connection_held',
    CONNECTION_NOT_CONFIGURED: 'connection_not_configured',
    CONTEXT_NOT_PROVIDED: 'context_not_provided',
    DECRYPTION_FAILED: 'decryption_failed',
    ENTITY_CONFLICT: 'entity_conflict',
    ENTITY_DEADLOCK: 'entity_deadlock',
    ENTITY_INVALID: 'entity_invalid',
    ENTITY_NOT_FOUND: 'entity_not_found',
    ENTITY_QUERY_INVALID: 'entity_query_invalid',
    ENTITY_RELATION_INVALID: 'entity_relation_invalid',
    FATAL_TOOL: 'FatalToolError',
    FORBIDDEN: 'forbidden',
    INCOMPLETE_RESPONSE: 'incomplete_response',
    INTERNAL_ERROR: 'internal_error',
    INVALID_AGENT_DEFINITION: 'invalid_agent_definition',
    INVALID_RUN_STATE: 'invalid_run_state',
    LEASE_LOST: 'lease_lost',
    NOT_FOUND: 'not_found',
    PEER_START_BUSY: 'peer_start_busy',
    REMOTE_FAILED: 'remote_failed',
    REPOSITORY_NOT_FOUND: 'repository_not_found',
    REQUEST_ENTITY_TOO_LARGE: 'request_entity_too_large',
    RUN_NOT_FOUND: 'run_not_found',
    SANDBOX: 'sandbox_error',
    SERVICE_UNAVAILABLE: 'service_unavailable',
    TIMEOUT: 'Timeout',
    TOO_MANY_REQUESTS: 'too_many_requests',
    TOOL_DENIED: 'tool_denied',
    TOOL_NOT_ALLOWED: 'tool_not_allowed',
    UNAUTHORIZED: 'unauthorized',
    UNSUPPORTED_MEDIA_TYPE: 'unsupported_media_type',
    VALIDATION: 'validation_error',
} as const;

// eslint-disable-next-line @tada5hi/type-declaration-location -- Keep the enum-like value and its same-name type contract together.
export type ErrorCode = typeof ErrorCode[keyof typeof ErrorCode];

See Errors for when each is thrown.