UNPKG

@adonis-agora/agent

Version:

Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.

344 lines • 17.8 kB
import { type A2aActionPolicy, type A2aParkedAction, type A2aTurnOutcome, type A2aTurnService } from '../a2a/turn.js'; import type { Actor } from '../types.js'; import type { PoppyPrincipal } from './auth.js'; import { type PoppyOperationsService } from './operations.js'; import { type PoppyAuthor, type PoppyEvent, type PoppyEventMessage, type PoppyMessageAddons, type PoppyRequestBody, type PoppySendBody, type PoppyState } from './protocol.js'; import { type PoppyConversationRecord, type PoppyStore } from './store.js'; /** What the hooks are told about a conversation. */ export interface PoppyHookContext { conversationId: string; conversation: PoppyConversationRecord; /** Who the conversation's turns run as (its latest request); `null` before any. */ actor: Actor | null; } /** * What {@link PoppyHandoffHooks.request} decided: * - `'queued'` — someone will join: call {@link PoppyConversations.humanJoined} when they do, or * {@link PoppyConversations.handoffUnavailable} if nobody can. Meanwhile `handoff` is `pending` * and the Company Agent keeps answering (§8.9). * - `'joined'` — a person took it now. * - `{ unavailable }` — nobody can; the text is what the Company Agent says (§8.9). */ export type PoppyHandoffDecision = 'queued' | 'joined' | { unavailable: string; }; /** * How the app brings a person in (§8.9). Without these, a handoff is answered by the Company Agent * saying no one is available — the conversation stays with the agent. */ export interface PoppyHandoffHooks { /** A person was asked for — by the Personal Agent (`requested`) or by the app (`company`). */ request(ctx: PoppyHookContext & { by: 'requested' | 'company'; }): PoppyHandoffDecision | Promise<PoppyHandoffDecision>; /** * A message from the Personal Agent for the person handling the conversation — the agent does * not answer those. When a person joins, the messages the agent had not taken up yet come here * too. Route them to your support tool. */ message?(ctx: PoppyHookContext & { message: PoppyEventMessage; }): void | Promise<void>; /** * The Personal Agent withdrew its request while a person was being found (§8.9). Return `false` * to keep looking (a help desk that cannot withdraw a routed request); anything else stops, and * `handoff` goes back to `none`. Without this hook, the Company stops looking. */ withdraw?(ctx: PoppyHookContext): boolean | undefined | Promise<boolean | undefined>; /** The conversation closed while a person was handling it or being found (§8.12). */ cancel?(ctx: PoppyHookContext): void | Promise<void>; } /** Notified when the Personal Agent opens or closes a Direct Conversation (§8.10). */ export interface PoppyDirectHooks { opened?(ctx: PoppyHookContext & { parentId: string; }): void | Promise<void>; closed?(ctx: PoppyHookContext & { parentId: string; }): void | Promise<void>; } /** What the Company Agent says on its own — and what it is told when it must speak first. */ export interface PoppyTexts { /** A handoff with no one to take it (§8.9). */ handoffUnavailable: string; /** A turn that failed before saying anything. */ failed: string; /** Asked in a Direct Conversation alongside an `authorization` event (§8.11). */ signIn: string; /** An action that ran — `{title}` is the app's confirmation title (default {@link formatPoppyAction}). */ actionSucceeded: string; /** An approved action that did not run. `{title}`, `{error}`. */ actionFailed: string; /** An action the policy refused. `{title}`. */ actionRejected: string; /** * Given to the Company Agent — never shown — when the User accepts its `user_requested` event and * opens a Direct Conversation (§8.10), so it speaks first. `{reason}` is the event's reason. */ userJoined: string; /** * What the Company Agent reads for an action held for approval (Operations extension) — the * tool's answer; the action did not run. */ operationHeld: string; /** A message that carries an operation, when nothing else was said. `{summary}`. */ operationRequired: string; /** A message that carries a declined approval. `{summary}`, `{reason}`. */ operationDeclined: string; /** * Given to the Company Agent — never shown — when an approval lets it perform a held action: * `{summary}`, `{tool}`, `{input}` (JSON). */ operationApproved: string; /** An approval of an operation this conversation never asked for. `{operation}`. */ operationUnknown: string; /** An approved action that is still being performed. `{summary}`. */ operationPerforming: string; } export declare const DEFAULT_POPPY_TEXTS: PoppyTexts; /** * Conversations with the Operations extension (version 3): an action that waits for approval is * not performed — the Company Agent's message carries the operation, and the action runs once the * Personal Agent sends its approval in a later message. Used only when the request declares * `"operations";v="3"`; the operations service stores and verifies them. */ export interface PoppyOperationsOptions { /** The operations service. Default: the one in `Symbol.for('@adonis-agora/poppy:operations')`. */ service?: PoppyOperationsService; /** Which actions are operations. Default: every action that waits for approval. */ requires?: (action: A2aParkedAction & { conversation: PoppyConversationRecord; }) => boolean | Promise<boolean>; /** * The operation's words and terms. Default: the tool's confirmation as `summary` (its name and * input without one), `{ tool, input }` as `terms`. */ describe?: (action: A2aParkedAction & { conversation: PoppyConversationRecord; }) => PoppyOperationTerms | Promise<PoppyOperationTerms>; /** How long an approval may take, in ms. Default 15 minutes. */ expiresInMs?: number; } /** What {@link PoppyOperationsOptions.describe} answers. */ export interface PoppyOperationTerms { summary?: string; terms?: Record<string, unknown>; expiresAt?: Date | string; } /** What the Company Agent's reply carries besides text and data: links, disclosures. */ export type PoppyReplyAddons = (ctx: PoppyHookContext & { text: string; data?: Record<string, unknown>; }) => PoppyMessageAddons | undefined | Promise<PoppyMessageAddons | undefined>; /** An action of the turn, as the reply's `data.actions` carries it. */ export type PoppyActionOutcome = A2aTurnOutcome; /** * Words an action for the reply's text (§8: the message must make sense without `data`). Return * `null` to leave it out. Default {@link formatPoppyAction}. */ export type PoppyActionFormatter = (action: PoppyActionOutcome, texts: PoppyTexts) => string | null | undefined; /** * Default wording: the status line from `texts` with the confirmation title (a question like * "Log this dose?" loses its `?`), then the confirmation detail. */ export declare function formatPoppyAction(action: PoppyActionOutcome, texts: PoppyTexts): string; /** The versions a conversation started in, and those of a request on it (§8.2). */ export interface PoppyVersionCheck { conversation: PoppyConversationRecord; started: { protocolVersion: string; extensions: Record<string, string>; }; request: { protocolVersion: string; extensions: Record<string, string>; }; /** `read` for `GET …/events`; `write` for every POST on the conversation. */ kind: 'read' | 'write'; } export interface PoppyConversationsOptions { store: PoppyStore; /** What runs a turn — `AgentService`, or an app's adapter (the A2A surface's contract). */ service: A2aTurnService & { drive?(runId: string): Promise<void>; }; /** The roles a tool declares, for matching the token's scopes. */ toolRoles: (toolName: string) => string[] | undefined; /** The registered agent that answers. Omitted → the agent provider's default. */ agentName?: string; /** What happens to `action` calls that park for approval. Default `'approve-delegated'`. */ actions?: A2aActionPolicy; /** Give up on a turn after this many ms. Default 120 000. */ timeoutMs?: number; /** Drive a durable run left pending, in this process (see `AgentService.drive`). Default `true`. */ drive?: boolean; /** Map a principal without an actor to the app's actor. Default: `poppy:<hash>`. */ actorFor?: (principal: PoppyPrincipal, defaults: Actor) => Actor | Promise<Actor>; /** Words each action of a reply. Default {@link formatPoppyAction}. */ formatAction?: PoppyActionFormatter; handoff?: PoppyHandoffHooks; direct?: PoppyDirectHooks; texts?: Partial<PoppyTexts>; /** * Whether a request in other versions than the conversation started in continues it (§8.2); * `false` answers `version_mismatch`. Default: when the protocol versions are compatible. */ continueVersion?: (check: PoppyVersionCheck) => boolean | Promise<boolean>; /** Keep events this long, then prune them (a cursor there is `cursor_expired`). Default: forever. */ retentionMs?: number; /** How often a waiting read looks for events another replica appended. Default 1000 ms. */ pollMs?: number; /** Logs what fails outside a request (a turn, a hook). */ onError?: (error: unknown, context: string) => void; /** * The Operations extension. Default: on when an operations service is installed in * `Symbol.for('@adonis-agora/poppy:operations')`; `false` turns it off. */ operations?: boolean | PoppyOperationsOptions; /** Links and disclosures for each reply of the Company Agent (Links and Disclosures extensions). */ replyAddons?: PoppyReplyAddons; } /** What a read answers (§8.5): the events, and the state when the Company responds (§8.7). */ export interface PoppyReadResult extends PoppyState { conversation_id: string; events: PoppyEvent[]; cursor: string | null; has_more: boolean; } /** What an accepted POST answers (§8.3): only the conversation's ID. */ export interface PoppyAccepted { status: 201 | 202; body: { conversation_id: string; }; } /** What a stream yields: a stored event, a provisional piece of text, or `working` (§8.6). */ export type PoppyStreamItem = { kind: 'event'; event: PoppyEvent; } | { kind: 'delta'; messageId: string; text: string; } | { kind: 'working'; working: boolean; }; /** The actor of a principal the resolver gave none: stable per (Personal Agent, its User). */ export declare function poppyActorId(clientId: string, userId: string): string; /** * Poppy conversations (§8) over the agent runtime: the state, the event log and the turns. * HTTP-free — `createPoppyHandler` puts the protocol's requests on it, and the app drives the * Company side through it (a person joining, their messages, `user_requested`). * * A conversation is an agent thread owned by the principal's actor. Every request is accepted * first, then acted on (§8.3): a user message is appended to the event log, and the log is the turn * queue — a pump per conversation (one replica at a time, by lease) answers the messages after * `turnSeq` in one turn, streams its text as `text-delta`, then appends the reply as a `message` * event. `working` is true from a message's acceptance until its reply is written. A replica that * finds a conversation `working` with no pump picks it up, so a reply survives the process that * started it. * * @experimental Implements Personal Agent Protocol 1.0 (https://personalagentprotocol.org/docs/1.0/spec). * The surface may still change between minor releases of this package while it settles. */ export declare class PoppyConversations { #private; private readonly options; constructor(options: PoppyConversationsOptions); /** * The actor a principal's turns run as: the resolver's (`toActor`), else the app's `actorFor`, * else — signed in — the ACCOUNT, `{ id: accountId }`, the way a PACT delegation runs as the * account; signed out, `poppy:<hash>` (stable per Personal Agent and User, never an account). * It ALWAYS carries `personal_agent` (what puts it behind `personalAgentGate`) and one * `scope:<id>` role per account scope of a signed-in token — the roles a PACT delegation gives, * so a tool written for personal agents gates both surfaces alike. */ actorOf(principal: PoppyPrincipal): Promise<Actor>; /** Whether conversations ask for approval with operations (a service is there, and not turned off). */ get operationsEnabled(): boolean; /** * `POST {endpoint}` — start a conversation with its first message, or a Direct Conversation * (§8.3, §8.10). Answers `201 { conversation_id }`; a retried request (same ID, path and body) * answers the conversation it already started. */ start(principal: PoppyPrincipal, body: PoppySendBody): Promise<PoppyAccepted & { conversationId: string; }>; /** `POST {endpoint}/{id}/messages` — another message (§8.3). Answers `202 { conversation_id }`. */ send(principal: PoppyPrincipal, conversationId: string, body: PoppySendBody): Promise<PoppyAccepted>; /** `GET {endpoint}/{id}/events` without streaming — read (and wait for) events (§8.5). */ read(principal: PoppyPrincipal, conversationId: string, options: { cursor?: string; waitMs?: number; }): Promise<PoppyReadResult>; /** * A read of a conversation already checked — also what a POST with `wait` answers (§8.3). Holds * up to `waitMs` until there is an event, or until `working` turns false (§8.5). */ readOwned(conversation: PoppyConversationRecord, options: { cursor?: string; waitMs?: number; }): Promise<PoppyReadResult>; /** Check a conversation is the principal's (and its versions continue it), for a caller that reads it afterwards. */ owned(principal: PoppyPrincipal, conversationId: string, kind?: 'read' | 'write'): Promise<PoppyConversationRecord>; /** * `GET {endpoint}/{id}/events` as SSE (§8.6): `working` first, the events after `cursor`, then new * ones as they come, with `text-delta` pieces of a reply being written in this process and * `working` again on each change. Ends when `signal` aborts, or once the conversation is closed * and every event was sent. */ stream(conversation: PoppyConversationRecord, cursor: string | undefined, signal: AbortSignal): AsyncGenerator<PoppyStreamItem>; /** `POST {endpoint}/{id}/handoff` — ask for a person at the Company (§8.9). Answers `202`. */ requestHandoff(principal: PoppyPrincipal, conversationId: string, body: PoppyRequestBody): Promise<PoppyAccepted>; /** `POST {endpoint}/{id}/handoff/cancel` — withdraw a request for a person (§8.9). Answers `202`. */ cancelHandoff(principal: PoppyPrincipal, conversationId: string, body: PoppyRequestBody): Promise<PoppyAccepted>; /** * `POST {endpoint}/{id}/close` — close the conversation (§8.12). Answers `202`, also on a * conversation already closed. A close does not wait its turn. */ closeByAgent(principal: PoppyPrincipal, conversationId: string, body: PoppyRequestBody): Promise<PoppyAccepted>; /** Look a conversation up — for the app's own routing (a support tool, an admin page). */ get(conversationId: string): Promise<PoppyConversationRecord | null>; /** * Close a conversation (§8.12): its open Direct Conversation first; a pending handoff stops, and * a `state` event says `closed`. Requests not acted on yet are dropped. Nothing it started is * undone. Idempotent. */ close(conversationId: string): Promise<PoppyState>; /** The Company Agent hands off to a person on its own (§8.9) — e.g. from one of your tools. */ handoff(conversationId: string): Promise<PoppyState>; /** * A person at the Company joined: `handoff` none, `responder` human (§8.7, §8.9). The messages * the agent had not taken up yet go to the `handoff.message` hook. */ humanJoined(conversationId: string): Promise<PoppyState>; /** The person left: the Company Agent answers again. */ humanLeft(conversationId: string): Promise<PoppyState>; /** * No one could take a pending handoff: the Company Agent says why, and `handoff` goes back to * `none` with the agent (§8.9). */ handoffUnavailable(conversationId: string, reason?: string): Promise<PoppyState>; /** * Add a Company message — a person's (`author.type: 'human'`, while they handle the conversation) or * an automated one. Answers the message's id. */ postMessage(conversationId: string, message: { text?: string; data?: Record<string, unknown>; author: PoppyAuthor; /** Pages the message refers to (Links extension). */ links?: PoppyMessageAddons['links']; /** Notices that matter whatever else it says (Disclosures extension). */ disclosures?: PoppyMessageAddons['disclosures']; }): Promise<string>; /** * Ask to talk with the User directly (§8.10): a `user_requested` event. Only the Personal Agent * opens the Direct Conversation, once the User agrees. Answers the event's ID. */ requestUser(conversationId: string, reason: string): Promise<string>; /** Stop pumping and waiting in this process (shutdown). */ shutdown(): void; } //# sourceMappingURL=conversations.d.ts.map