All files / src/modules a2a.ts

41.09% Statements 60/146
78.94% Branches 15/19
36.36% Functions 4/11
41.09% Lines 60/146

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                                                                                                                                                                                                                                            1x   1x 1x 1x   1x                                         1x 1x               1x       1x       1x       1x                                                                           1x 1x                                             1x 8x   8x 5x   5x 5x 1x 1x 1x 5x 2x 1x 1x 1x 5x 1x 1x 1x 1x 5x       5x 1x 5x 5x   8x 8x   8x   7x 1x 1x 1x 1x 1x 1x     7x 5x     5x                                             5x 5x 5x 5x 5x 5x   1x 7x 8x 8x  
/**
 * AgentKits — A2A (Agent-to-Agent) Protocol Support
 *
 * Implements Google's A2A protocol basics for agent interop.
 * - Agent Card discovery
 * - Task management (create, get, cancel)
 * - Streaming via SSE
 *
 * Spec: https://google.github.io/A2A/
 *
 * Usage:
 *   import { createA2AClient, createA2AServer } from 'agentkits/a2a';
 */
 
// ── Types ──────────────────────────────────────────────────────────
 
export interface AgentSkill {
  id: string;
  name: string;
  description: string;
  tags?: string[];
  examples?: string[];
}
 
export interface AgentCard {
  name: string;
  description: string;
  url: string;
  version: string;
  capabilities: {
    streaming?: boolean;
    pushNotifications?: boolean;
    stateTransitionHistory?: boolean;
  };
  skills: AgentSkill[];
  defaultInputModes?: string[];
  defaultOutputModes?: string[];
}
 
export type TaskState = 'submitted' | 'working' | 'input-required' | 'completed' | 'canceled' | 'failed';
 
export interface TextPart {
  type: 'text';
  text: string;
}
 
export interface FilePart {
  type: 'file';
  file: { name?: string; mimeType?: string; bytes?: string; uri?: string };
}
 
export interface DataPart {
  type: 'data';
  data: Record<string, any>;
}
 
export type Part = TextPart | FilePart | DataPart;
 
export interface Message {
  role: 'user' | 'agent';
  parts: Part[];
  metadata?: Record<string, any>;
}
 
export interface Artifact {
  name?: string;
  description?: string;
  parts: Part[];
  index: number;
  append?: boolean;
  lastChunk?: boolean;
}
 
export interface Task {
  id: string;
  sessionId?: string;
  status: { state: TaskState; message?: Message; timestamp?: string };
  artifacts?: Artifact[];
  history?: Message[];
  metadata?: Record<string, any>;
}
 
export interface TaskSendParams {
  id: string;
  sessionId?: string;
  message: Message;
  historyLength?: number;
  metadata?: Record<string, any>;
}
 
export interface TaskStatusUpdateEvent {
  type: 'status';
  id: string;
  status: Task['status'];
  final: boolean;
}
 
export interface TaskArtifactUpdateEvent {
  type: 'artifact';
  id: string;
  artifact: Artifact;
}
 
export type TaskStreamEvent = TaskStatusUpdateEvent | TaskArtifactUpdateEvent;
 
// ── A2A Client ─────────────────────────────────────────────────────
 
export interface A2AClientConfig {
  /** Base URL of the A2A agent (e.g. http://localhost:8080) */
  baseUrl: string;
  /** Request timeout in ms */
  timeout?: number;
}
 
export interface A2AClient {
  /** Fetch the agent's card from /.well-known/agent.json */
  getAgentCard(): Promise<AgentCard>;
  /** Send a task (tasks/send) */
  sendTask(params: TaskSendParams): Promise<Task>;
  /** Get task status (tasks/get) */
  getTask(id: string): Promise<Task>;
  /** Cancel a task (tasks/cancel) */
  cancelTask(id: string): Promise<Task>;
  /** Stream task updates via SSE (tasks/sendSubscribe) */
  streamTask(params: TaskSendParams): AsyncIterable<TaskStreamEvent>;
}
 
interface JsonRpcResponse {
  jsonrpc: '2.0';
  id: number;
  result?: any;
  error?: { code: number; message: string; data?: any };
}
 
let _rpcId = 1;
 
export function createA2AClient(config: A2AClientConfig): A2AClient {
  const timeout = config.timeout ?? 30000;
  const baseUrl = config.baseUrl.replace(/\/$/, '');
 
  async function rpc(method: string, params: any): Promise<any> {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeout);
 
    try {
      const resp = await fetch(baseUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ jsonrpc: '2.0', id: _rpcId++, method, params }),
        signal: controller.signal,
      });
 
      if (!resp.ok) throw new Error(`A2A request failed: ${resp.status}`);
      const data: JsonRpcResponse = await resp.json() as any;
      if (data.error) throw new Error(`A2A error ${data.error.code}: ${data.error.message}`);
      return data.result;
    } finally {
      clearTimeout(timer);
    }
  }
 
  return {
    async getAgentCard(): Promise<AgentCard> {
      const resp = await fetch(`${baseUrl}/.well-known/agent.json`, {
        signal: AbortSignal.timeout(timeout),
      });
      if (!resp.ok) throw new Error(`Failed to fetch agent card: ${resp.status}`);
      return await resp.json() as AgentCard;
    },
 
    async sendTask(params: TaskSendParams): Promise<Task> {
      return rpc('tasks/send', params);
    },
 
    async getTask(id: string): Promise<Task> {
      return rpc('tasks/get', { id });
    },
 
    async cancelTask(id: string): Promise<Task> {
      return rpc('tasks/cancel', { id });
    },
 
    async *streamTask(params: TaskSendParams): AsyncIterable<TaskStreamEvent> {
      const resp = await fetch(baseUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
        body: JSON.stringify({ jsonrpc: '2.0', id: _rpcId++, method: 'tasks/sendSubscribe', params }),
      });
 
      if (!resp.ok) throw new Error(`A2A stream failed: ${resp.status}`);
      if (!resp.body) throw new Error('No response body for streaming');
 
      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
 
      try {
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() ?? '';
          let currentData = '';
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              currentData = line.slice(6);
            } else if (line === '' && currentData) {
              try {
                const msg = JSON.parse(currentData);
                if (msg.result) yield msg.result as TaskStreamEvent;
              } catch {}
              currentData = '';
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    },
  };
}
 
// ── A2A Server (Express-compatible handler) ────────────────────────
 
export interface A2AServerConfig {
  card: AgentCard;
  onTask: (params: TaskSendParams) => Promise<Task>;
  onTaskGet?: (id: string) => Promise<Task>;
  onTaskCancel?: (id: string) => Promise<Task>;
  onTaskStream?: (params: TaskSendParams) => AsyncIterable<TaskStreamEvent>;
}
 
export interface A2AHandler {
  /** Handle incoming HTTP request. Returns { status, headers, body }. */
  handle(req: { method: string; url: string; body?: any }): Promise<{
    status: number;
    headers: Record<string, string>;
    body: string | ReadableStream<Uint8Array>;
  }>;
  /** The agent card */
  card: AgentCard;
}
 
export function createA2AServer(config: A2AServerConfig): A2AHandler {
  const { card, onTask, onTaskGet, onTaskCancel, onTaskStream } = config;
 
  async function handleRpc(body: any): Promise<any> {
    const { method, params, id } = body;
 
    switch (method) {
      case 'tasks/send': {
        const result = await onTask(params);
        return { jsonrpc: '2.0', id, result };
      }
      case 'tasks/get': {
        if (!onTaskGet) return { jsonrpc: '2.0', id, error: { code: -32601, message: 'tasks/get not implemented' } };
        const result = await onTaskGet(params.id);
        return { jsonrpc: '2.0', id, result };
      }
      case 'tasks/cancel': {
        if (!onTaskCancel) return { jsonrpc: '2.0', id, error: { code: -32601, message: 'tasks/cancel not implemented' } };
        const result = await onTaskCancel(params.id);
        return { jsonrpc: '2.0', id, result };
      }
      case 'tasks/sendSubscribe': {
        if (!onTaskStream) return { jsonrpc: '2.0', id, error: { code: -32601, message: 'streaming not supported' } };
        return { _stream: true, id, params };
      }
      default:
        return { jsonrpc: '2.0', id, error: { code: -32601, message: `Unknown method: ${method}` } };
    }
  }
 
  return {
    card,
 
    async handle(req) {
      // Agent card discovery
      if (req.method === 'GET' && (req.url === '/.well-known/agent.json' || req.url?.endsWith('/agent.json'))) {
        return {
          status: 200,
          headers: { 'Content-Type': 'application/json' } as Record<string, string>,
          body: JSON.stringify(card),
        };
      }
 
      // JSON-RPC
      if (req.method === 'POST') {
        const result = await handleRpc(req.body);
 
        // Streaming response
        if (result._stream && onTaskStream) {
          const encoder = new TextEncoder();
          const stream = new ReadableStream({
            async start(controller) {
              try {
                for await (const event of onTaskStream!(result.params)) {
                  const data = JSON.stringify({ jsonrpc: '2.0', id: result.id, result: event });
                  controller.enqueue(encoder.encode(`data: ${data}\n\n`));
                  if (event.type === 'status' && event.final) break;
                }
              } finally {
                controller.close();
              }
            },
          });
 
          return {
            status: 200,
            headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' } as Record<string, string>,
            body: stream,
          };
        }
 
        return {
          status: 200,
          headers: { 'Content-Type': 'application/json' } as Record<string, string>,
          body: JSON.stringify(result),
        };
      }
 
      return { status: 404, headers: {} as Record<string, string>, body: 'Not Found' };
    },
  };
}