@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
252 lines • 12.6 kB
TypeScript
import { type OkpJwk } from '../crypto-kit/index.js';
import { type TenantTokenSource, type TenantVerifierInput, type VerifiedTenant } from './tenant_auth.js';
/**
* The Redis channel the federated console talks to another app over: the console publishes a
* command on `<prefix>-agent-console`, every instance of the owning app hears it, the one that wins
* `SET <prefix>-agent-console-claim:<id> NX PX` runs it, and the answer comes back on
* `<prefix>-agent-console-reply`. Same design as `@adonis-agora/config`'s and
* `@adonis-agora/durable`'s console commands, on channels of its own (`-agent-`), so all of them can
* share an app's prefix. Ported from `@adonis-agora/config`'s channel (only {@link CONSOLE_TOPIC}
* and the names differ).
*
* Redis is not a trust boundary: anyone who can publish there could otherwise approve a pending tool
* call as any approver or rewrite prices. Every command is authenticated (one of three modes, see
* {@link RedisConsoleChannel}), refused when older than a minute, claimed once (a replay reuses the
* id and loses the claim), and every answer is MACed so a forged one is ignored.
*/
/** This package's part of the channel names. */
export declare const CONSOLE_TOPIC = "agent";
/** One command sent to the owning app. Arguments and answer are plain JSON. */
export interface AgentConsoleCommand {
id: string;
verb: string;
args: unknown[];
/** Who acted in the console, recorded by the owning app as the deciding actor. */
actor?: string;
/**
* What the console's `authorize` granted that viewer. Only narrows: in token mode the token's
* capabilities cap it, and a command without it is never taken to mean "everything".
*/
capabilities?: string[];
/** The console that sent it (its `appLabel`), for the owning app's log. */
via?: string;
/** When it was sent (ms since the epoch): a command older than a minute is refused. */
ts?: number;
/** Shared-secret mode: HMAC of every field above (set by {@link RedisConsoleChannel}). */
mac?: string;
/**
* Token mode: who the owning app verified the console as (its token's partition and
* capabilities). Set by the channel after verification, never taken from the wire.
*/
verified?: Pick<VerifiedTenant, 'partition' | 'capabilities' | 'clientId' | 'audienceBound'>;
}
/** The owning app's answer to a {@link AgentConsoleCommand}. */
export type AgentConsoleReply = ({
id: string;
ok: true;
data: unknown;
} | {
id: string;
ok: false;
error: {
message: string;
code?: string;
status?: number;
};
}) & {
mac?: string;
};
/** A shared secret: a string, or a Secret-like object (`env.get('X')` in AdonisJS). */
export type ChannelSecret = string | {
release(): string;
};
/** The owning app refused the console's token (the console drops its cached token). */
export declare const UNAUTHORIZED_CONSOLE = "federated-console-unauthorized";
/**
* How a sealed command is encrypted: to the app's command key derived from its `APP_KEY`, or with
* a key of `@adonis-agora/crypto` (the Hub's, or the app's own). Either way only the owning app
* opens it, and the AAD binds it to this channel and this command id.
*/
export interface ConsoleSealer {
/** Whether `sealed` is this sealer's ciphertext (so the app knows which one opens it). */
owns(sealed: string): boolean;
seal(plaintext: string, aad: string): Promise<string>;
open(sealed: string, aad: string): Promise<string>;
}
/** The `encrypt`/`decrypt` pair `@adonis-agora/crypto` exposes (`crypto.client`, `serviceCipher`). */
export interface ConsoleCipher {
encrypt(input: {
key: string;
plaintext: string;
aad?: string;
context?: string;
}): Promise<{
ciphertext: string;
}>;
decrypt(input: {
key: string;
ciphertext: string;
aad?: string;
context?: string;
}): Promise<{
plaintext: string;
}>;
}
/**
* A cipher, or a function returning one: `config/agent.ts` is read before `@adonis-agora/crypto` is
* ready, so `() => crypto.client!` (or `() => serviceCipher(crypto.service, 'app')`) defers it to
* the first command.
*/
export type ConsoleCipherSource = ConsoleCipher | (() => ConsoleCipher | Promise<ConsoleCipher>);
/**
* The `@adonis-agora/crypto` key console commands are sealed with, unless another is named. Every
* Agora lib names its key `console-<lib>` (an app opens its own `console-*` keys with no grant).
*/
export declare const CONSOLE_CRYPTO_KEY = "console-agent";
/** `crypto` on either side: a cipher, the key (default `console-agent`), and an optional `owns`. */
export interface ConsoleCryptoOptions {
cipher: ConsoleCipherSource;
key?: string | undefined;
/**
* Whether a ciphertext is this cipher's, so the app knows which mode opens a command. Default: the
* `@adonis-agora/crypto` format (`agora:ct1:<key>:`). Set it for a cipher of your own (a KMS, Vault
* transit, an HSM) whose ciphertext looks different.
*/
owns?: ((ciphertext: string) => boolean) | undefined;
}
/** Seals with an `@adonis-agora/crypto` key: whoever may `encrypt` with it sends, the app opens. */
export declare function cryptoConsoleSealer(options: ConsoleCryptoOptions): ConsoleSealer;
/** Seals to the app's X25519 command key: the console side (the app's public key, configured). */
export declare function appKeySealerTo(recipient: OkpJwk | (() => Promise<OkpJwk>)): ConsoleSealer;
/** Opens with the app's X25519 command key pair (derived from its `APP_KEY`): the app side. */
export declare function appKeySealer(keys: {
publicKey: OkpJwk;
privateKey: OkpJwk;
}): ConsoleSealer;
/** How one channel authenticates: what it sends with, and every way it accepts commands. */
export interface ConsoleChannelAuthOptions {
/** Shared-secret mode: the same value on the console and on the app (16+ characters). */
secret?: ChannelSecret | undefined;
/**
* Sealed mode with `@adonis-agora/crypto`, both sides: the cipher (`crypto.client`, or
* `serviceCipher(crypto.service, partition)` where crypto is embedded) and the key
* (`console-agent` by default). The console needs `encrypt` on it, the app `decrypt`.
*/
crypto?: ConsoleCryptoOptions | undefined;
/** Console side: the token each command carries (`authkitTenantToken(...)`). */
token?: TenantTokenSource | undefined;
/**
* Console side, crypto mode: the token is optional (the app accepts crypto alone). When minting
* it fails, the command is sent without it, this is called with the reason, and minting is
* retried after 5 minutes. Without it (or without crypto), a failed mint fails the command.
*/
onTokenSkipped?: ((reason: string, error?: unknown) => void) | undefined;
/**
* Console side, without `crypto`: the app's command public key (`node ace agent:console-key` on
* that app prints it). Configured, never read from Redis.
*/
recipient?: OkpJwk | (() => Promise<OkpJwk>) | undefined;
/** App side, without `crypto`: this app's command key pair (derived from its `APP_KEY`). */
keys?: {
publicKey: OkpJwk;
privateKey: OkpJwk;
} | undefined;
/** App side: verifies the console's token (`authkitTenantVerifier(...)`). */
verifyTenant?: TenantVerifierInput | undefined;
/**
* App side, crypto mode with `verifyTenant`: accept a sealed command that carries no token (one
* that carries a token must still pass it). Set for a fallback verifier (authkit's app-call one);
* an explicit `crypto` + `verifyTenant` keeps the token mandatory. Token-only mode always requires it.
*/
tokenOptional?: boolean | undefined;
/** App side: this app's partition, handed to `verifyTenant` as the app the command is for. */
app?: string | undefined;
}
/** An `ioredis` client: pub/sub needs a dedicated connection, made with `duplicate()`. */
export interface IoredisLike {
publish(channel: string, message: string): Promise<unknown>;
set?(key: string, value: string, px: 'PX', ms: number, nx: 'NX'): Promise<unknown>;
duplicate(): IoredisSubscriberLike;
}
export interface IoredisSubscriberLike {
subscribe(...channels: string[]): unknown;
on(event: 'message', listener: (channel: string, message: string) => void): unknown;
disconnect?(): void;
}
/** An `@adonisjs/redis` connection: it keeps its own subscriber and hands each payload over. */
export interface AdonisRedisLike {
publish(channel: string, message: string): Promise<unknown>;
set?(key: string, value: string, px: 'PX', ms: number, nx: 'NX'): Promise<unknown>;
subscribe(channel: string, handler: (message: string) => void): unknown;
unsubscribe?(channel: string): unknown;
}
export type RedisLike = IoredisLike | AdonisRedisLike;
/** How long a command waits for its answer by default. */
export declare const AGENT_CONSOLE_TIMEOUT_MS = 15000;
/** A command the owning app refused or failed, or that nobody answered. */
export declare class AgentConsoleChannelError extends Error {
readonly code: string;
/** Set when this app refused an incoming command: the uniform reason the app logs. */
readonly reason: string | undefined;
constructor(message: string, code: string, reason?: string);
}
/**
* An incoming command this app refused, with the uniform reason every Agora lib logs: `not JSON`,
* `no command id`, `did not open with this app's key`, `bad signature`, `stale`, `token refused`,
* `capabilities-required`, or `mode not accepted here (…)`.
*/
export declare function refusedCommand(reason: string): AgentConsoleChannelError;
/** Token mode: the console's app-call token could not be minted (no grant, authkit down). */
export declare const TOKEN_UNAVAILABLE = "federated-console-token-unavailable";
/** Nobody listens on the app's channel, or nobody answered in time. */
export declare const APP_UNREACHABLE = "federated-app-unreachable";
/** The channel has no authentication, or a command arrived without valid authentication. */
export declare const UNSIGNED_CHANNEL = "federated-channel-unsigned";
export declare class RedisConsoleChannel {
#private;
readonly prefix: string;
/**
* Redis is not a trust boundary, so a channel neither sends nor answers commands without one of:
*
* - `crypto` — commands sealed with an `@adonis-agora/crypto` key (the console may encrypt with it,
* the app decrypt), optionally with a `token` the app checks with `verifyTenant`;
* - a `token` sealed to the app's command key (`recipient` / `keys`, from its `APP_KEY`), checked
* with `verifyTenant` (authkit, typically);
* - `secret` — shared by the console and the app (the same value on both sides).
*/
constructor(options: {
client: RedisLike;
prefix: string;
} & ConsoleChannelAuthOptions);
/** Whether this channel can send commands (crypto, a token and the app's key, or a secret). */
get signed(): boolean;
get commandChannel(): string;
get replyChannel(): string;
/**
* Send `command` to the owning app and wait for its answer. Rejects at once when the channel has
* no authentication or no instance listens (`PUBLISH` reached nobody), and after `timeoutMs` when
* nobody answers. An answer without this command's MAC is ignored.
*/
send(command: AgentConsoleCommand, options?: {
timeoutMs?: number | undefined;
}): Promise<AgentConsoleReply>;
/**
* Answer the commands other apps' consoles send this app. Every instance subscribes; the one that
* wins `SET <prefix>-agent-console-claim:<id> NX` runs the command and publishes the answer, so a
* command runs once however many processes the app has. Throws when the channel has no
* authentication, or when the client cannot run that `SET`: a command never runs without both.
*/
answer(handler: (command: AgentConsoleCommand) => Promise<unknown>, options?: {
onError?: (error: unknown) => void;
}): Promise<void>;
/** Stop listening and fail the commands still waiting for an answer. */
close(): Promise<void>;
}
/**
* The Redis client for `connection` (an `@adonisjs/redis` connection name; omit for its default),
* resolved through the container's `redis` binding.
*/
export declare function resolveRedisConnection(container: {
make(binding: string): Promise<unknown>;
}, connection: string | undefined): Promise<RedisLike>;
//# sourceMappingURL=redis_channel.d.ts.map