/** * Core Agent Types and Utilities * DO NOT MODIFY THIS FILE - You may break the agent functionality * * This module provides types and utilities for AI agents. * The actual agent implementation is in core-base-agent.ts. * * @example * ```typescript * // In agents.ts * import type { AgentDefinition } from './core-agent'; * * const supportAgent: AgentDefinition = { * name: 'support-assistant', * description: 'Helps users with common questions', * systemPrompt: 'You are a helpful support assistant...', * integrations: ['slack', 'github'], * entities: ['ticket', 'user'], * }; * * export const APP_AGENTS: AgentDefinition[] = [supportAgent]; * ``` */ import { z } from 'zod'; import type { Env } from './core-utils'; import type { IntegrationClient } from './core-integrations'; import type { ExecutionLimits } from './task-delegation/types'; /** * Agent state persisted across conversations */ export interface AgentState { /** Conversation history */ messages: AgentMessage[]; /** Custom memory data */ memory: Record; /** Session metadata */ sessionId: string; /** User identifier for per-user memory */ userId?: string; /** Last activity timestamp */ lastActivityAt: number; } /** * Message in agent conversation */ export interface AgentMessage { id: string; role: 'user' | 'assistant' | 'system' | 'tool'; content: string; timestamp: number; toolCalls?: Array<{ id: string; name: string; arguments: Record; }>; toolResults?: Array<{ id: string; result: unknown; }>; } /** * Memory strategy for agents * - session: Memory resets when conversation ends * - user: Memory persists per user across conversations * - shared: Memory is shared across all users */ export type MemoryStrategy = 'session' | 'user' | 'shared'; /** * Agent definition schema */ export interface AgentDefinition { /** Unique agent name (kebab-case, e.g., 'support-assistant') */ name: string; /** Human-readable description */ description: string; /** System prompt defining agent behavior */ systemPrompt: string; /** Agent type for UI hints */ type?: 'conversational' | 'task'; /** Integration IDs the agent can access */ integrations?: string[]; /** Entity names the agent can read/write */ entities?: string[]; /** * Endpoints on OTHER apps in this workspace that the agent may call, as * `'::'` — e.g. `'labcrm:GET:/v1/portal/catalog'`. * `` is the target app's slug; `` is the path exactly as registered, * `:param` placeholders included. * * Declared explicitly, like `entities` and `integrations`: an agent can only * call what the app author listed, never an arbitrary endpoint. */ appEndpoints?: string[]; /** Memory strategy */ memoryStrategy?: MemoryStrategy; /** Custom tools for this agent */ customTools?: AgentToolDefinition[]; /** Default task instruction for task agents. Can be overridden per execution. */ prompt?: string; /** Cost/time limits for task agent sandbox execution. Optional overrides. */ executionLimits?: ExecutionLimits; } /** A parsed `'::'` agent endpoint reference. */ export interface AppEndpointRef { app: string; method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; path: string; } /** * Parse `'labcrm:GET:/v1/portal/invite/:token'`. * * Split on the first two colons only: the path itself contains colons for its * `:param` segments, so a naive split would mangle every parameterized endpoint. * Returns null for anything malformed rather than throwing, so one bad entry in an * agent definition costs that one tool instead of the whole agent. */ export declare function parseAppEndpointRef(ref: string): AppEndpointRef | null; /** * Stable, model-friendly tool name for an endpoint reference, e.g. * `call_labcrm_get_v1_portal_invite`. Param segments are dropped so the name * stays readable; the full path is in the tool description. */ export declare function appEndpointToolName(ref: AppEndpointRef): string; /** * Custom tool definition for agents */ export interface AgentToolDefinition { name: string; description: string; parameters: z.ZodObject; execute: (args: Record, context: AgentToolContext) => Promise; } /** * Context passed to tool execution */ export interface AgentToolContext { env: Env; agentName: string; integrationClient: IntegrationClient; state: AgentState; } /** * Initial state for new agent instances */ export declare const INITIAL_AGENT_STATE: AgentState; /** * Agent registry - maps agent names to their definitions */ export type AgentRegistry = Record; /** * Create an agent registry from an array of definitions. * * NOTE: This function is defensive against undefined/null inputs because it's called * at module-level in core-base-agent.ts. During Vite HMR, when files are being rewritten, * there's a race condition where APP_AGENTS may be undefined momentarily. Without * this guard, the worker crashes with "definitions is not iterable", which triggers * cascading HMR failures and eventually causes "@cloudflare/vite-plugin" to lose its * miniflare instance ("Expected `miniflare` to be defined" error). */ export declare function createAgentRegistry(definitions?: AgentDefinition[] | null): AgentRegistry; /** * Workspace agent registration request */ export interface RegisterAgentRequest { appId: string; appName: string; agentName: string; description: string; type: 'conversational' | 'task'; integrations: string[]; entities: string[]; tools?: AgentToolMeta[]; systemPrompt?: string; prompt?: string; executionLimits?: ExecutionLimits; } /** * Tool metadata for API responses (JSON-serializable, no Zod) */ export interface AgentToolMeta { name: string; description: string; source: 'entity' | 'integration' | 'custom'; sourceId?: string; parameters: { type: 'object'; properties: Record; required?: string[]; }; } /** * Tool definition with Zod schema (for buildTools) */ export interface AgentToolDef { name: string; description: string; source: 'entity' | 'integration' | 'custom'; sourceId?: string; parameters: z.ZodObject; } /** Zod schema for entity list tool */ export declare const entityListSchema: z.ZodObject<{ limit: z.ZodOptional; cursor: z.ZodOptional; }, "strip", z.ZodTypeAny, { cursor?: string | undefined; limit?: number | undefined; }, { cursor?: string | undefined; limit?: number | undefined; }>; /** Zod schema for entity get tool */ export declare const entityGetSchema: z.ZodObject<{ id: z.ZodString; }, "strip", z.ZodTypeAny, { id: string; }, { id: string; }>; /** * Get tool definitions for entity access */ export declare function getEntityToolDefs(entities: string[]): AgentToolDef[]; /** Zod schema for integration API tool */ export declare const integrationApiSchema: z.ZodObject<{ method: z.ZodDefault>; endpoint: z.ZodString; data: z.ZodOptional>; headers: z.ZodOptional>; }, "strip", z.ZodTypeAny, { endpoint: string; method: "POST" | "GET" | "PUT" | "PATCH" | "DELETE"; data?: Record | undefined; headers?: Record | undefined; }, { endpoint: string; data?: Record | undefined; method?: "POST" | "GET" | "PUT" | "PATCH" | "DELETE" | undefined; headers?: Record | undefined; }>; /** * Get tool definitions for integration access */ export declare function getIntegrationToolDefs(integrations: string[]): AgentToolDef[]; /** * Get tool definitions from custom tools (extracts metadata from AgentToolDefinition) */ export declare function getCustomToolDefs(customTools: AgentToolDefinition[]): AgentToolDef[]; /** * Get all tool definitions for an agent */ export declare function getAgentToolDefs(agent: AgentDefinition): AgentToolDef[]; /** * Convert tool definition to JSON-serializable metadata */ export declare function toolDefToMeta(def: AgentToolDef): AgentToolMeta; /** * Get all tool metadata for an agent (JSON-serializable) * Use this for API responses and workspace registration */ export declare function getAgentToolMeta(agent: AgentDefinition): AgentToolMeta[]; /** * Tool availability status at runtime */ export interface AgentToolStatus { name: string; source: 'entity' | 'integration' | 'custom'; sourceId?: string; available: boolean; reason?: string; } /** * Integration connection status */ export interface IntegrationStatus { id: string; connected: boolean; reason?: string; } /** * Agent runtime status - actual availability of capabilities */ export interface AgentRuntimeStatus { /** Agent name */ name: string; /** Whether agent definition was found */ initialized: boolean; /** Integration connection status */ integrations: IntegrationStatus[]; /** Tool availability status */ tools: AgentToolStatus[]; /** AI proxy configured */ aiProxyConfigured: boolean; /** Timestamp of status check */ checkedAt: number; } import type { Hono } from 'hono'; /** * Mount agent routes on the Hono app * Provides REST API for AI agent interactions */ export declare function agentRoutes(app: Hono<{ Bindings: Env; }>): void;