All files / src/trpc/routers conversation.ts

0.89% Statements 1/112
0% Branches 0/62
6.25% Functions 1/16
0.93% Lines 1/107

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                        11x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
/**
 * Conversation Router — inter-agent communication procedures
 */
 
import { TRPCError } from '@trpc/server';
import { tracked, type TrackedEnvelope } from '@trpc/server';
import { z } from 'zod';
import type { ProcedureBuilder } from '../trpc.js';
import { requireConversationRepository, requireAgentManager, requireTaskRepository } from './_helpers.js';
import type { ConversationCreatedEvent, ConversationAnsweredEvent } from '../../events/types.js';
 
export function conversationProcedures(publicProcedure: ProcedureBuilder) {
  return {
    createConversation: publicProcedure
      .input(z.object({
        fromAgentId: z.string().min(1),
        toAgentId: z.string().min(1).optional(),
        phaseId: z.string().min(1).optional(),
        taskId: z.string().min(1).optional(),
        question: z.string().min(1),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requireConversationRepository(ctx);
        const agentManager = requireAgentManager(ctx);
 
        let toAgentId = input.toAgentId;
 
        // Resolve target agent from taskId
        if (!toAgentId && input.taskId) {
          const agents = await agentManager.list();
          const match = agents.find(a => a.taskId === input.taskId && a.status === 'running');
          if (!match) {
            throw new TRPCError({
              code: 'NOT_FOUND',
              message: `No running agent found for task '${input.taskId}'`,
            });
          }
          toAgentId = match.id;
        }
 
        // Resolve target agent from phaseId
        if (!toAgentId && input.phaseId) {
          const taskRepo = requireTaskRepository(ctx);
          const tasks = await taskRepo.findByPhaseId(input.phaseId);
          const taskIds = new Set(tasks.map(t => t.id));
          const agents = await agentManager.list();
          const match = agents.find(a => a.taskId && taskIds.has(a.taskId) && a.status === 'running');
          if (!match) {
            throw new TRPCError({
              code: 'NOT_FOUND',
              message: `No running agent found for phase '${input.phaseId}'`,
            });
          }
          toAgentId = match.id;
        }
 
        if (!toAgentId) {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: 'Must provide toAgentId, taskId, or phaseId to identify target agent',
          });
        }
 
        const conversation = await repo.create({
          fromAgentId: input.fromAgentId,
          toAgentId,
          initiativeId: null,
          phaseId: input.phaseId ?? null,
          taskId: input.taskId ?? null,
          question: input.question,
        });
 
        ctx.eventBus.emit({
          type: 'conversation:created' as const,
          timestamp: new Date(),
          payload: {
            conversationId: conversation.id,
            fromAgentId: input.fromAgentId,
            toAgentId,
          },
        });
 
        return conversation;
      }),
 
    getPendingConversations: publicProcedure
      .input(z.object({
        agentId: z.string().min(1),
      }))
      .query(async ({ ctx, input }) => {
        const repo = requireConversationRepository(ctx);
        return repo.findPendingForAgent(input.agentId);
      }),
 
    getConversation: publicProcedure
      .input(z.object({
        id: z.string().min(1),
      }))
      .query(async ({ ctx, input }) => {
        const repo = requireConversationRepository(ctx);
        return repo.findById(input.id);
      }),
 
    answerConversation: publicProcedure
      .input(z.object({
        id: z.string().min(1),
        answer: z.string().min(1),
      }))
      .mutation(async ({ ctx, input }) => {
        const repo = requireConversationRepository(ctx);
        const existing = await repo.findById(input.id);
        if (!existing) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Conversation '${input.id}' not found`,
          });
        }
        if (existing.status === 'answered') {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: `Conversation '${input.id}' is already answered`,
          });
        }
 
        const updated = await repo.answer(input.id, input.answer);
 
        ctx.eventBus.emit({
          type: 'conversation:answered' as const,
          timestamp: new Date(),
          payload: {
            conversationId: input.id,
            fromAgentId: existing.fromAgentId,
            toAgentId: existing.toAgentId,
          },
        });
 
        return updated;
      }),
 
    onPendingConversation: publicProcedure
      .input(z.object({ agentId: z.string().min(1) }))
      .subscription(async function* (opts): AsyncGenerator<TrackedEnvelope<{
        conversationId: string;
        fromAgentId: string;
        question: string;
        phaseId: string | null;
        taskId: string | null;
      }>> {
        const { agentId } = opts.input;
        const signal = opts.signal ?? new AbortController().signal;
        const eventBus = opts.ctx.eventBus;
        const repo = requireConversationRepository(opts.ctx);
 
        // First yield any already-pending conversations
        const existing = await repo.findPendingForAgent(agentId);
        let eventCounter = 0;
        for (const conv of existing) {
          yield tracked(`conv-${eventCounter++}`, {
            conversationId: conv.id,
            fromAgentId: conv.fromAgentId,
            question: conv.question,
            phaseId: conv.phaseId,
            taskId: conv.taskId,
          });
        }
 
        // Then listen for new conversation:created events
        const queue: string[] = []; // conversation IDs
        let resolve: (() => void) | null = null;
 
        const handler = (event: ConversationCreatedEvent) => {
          if (event.payload.toAgentId !== agentId) return;
          queue.push(event.payload.conversationId);
          if (resolve) {
            const r = resolve;
            resolve = null;
            r();
          }
        };
 
        eventBus.on('conversation:created', handler);
 
        const cleanup = () => {
          eventBus.off('conversation:created', handler);
          if (resolve) {
            const r = resolve;
            resolve = null;
            r();
          }
        };
 
        signal.addEventListener('abort', cleanup, { once: true });
 
        try {
          while (!signal.aborted) {
            while (queue.length > 0) {
              const convId = queue.shift()!;
              const conv = await repo.findById(convId);
              if (conv && conv.status === 'pending') {
                yield tracked(`conv-${eventCounter++}`, {
                  conversationId: conv.id,
                  fromAgentId: conv.fromAgentId,
                  question: conv.question,
                  phaseId: conv.phaseId,
                  taskId: conv.taskId,
                });
              }
            }
 
            if (!signal.aborted) {
              await new Promise<void>((r) => {
                resolve = r;
              });
            }
          }
        } finally {
          cleanup();
        }
      }),
 
    onConversationAnswer: publicProcedure
      .input(z.object({ conversationId: z.string().min(1) }))
      .subscription(async function* (opts): AsyncGenerator<TrackedEnvelope<{ answer: string }>> {
        const { conversationId } = opts.input;
        const signal = opts.signal ?? new AbortController().signal;
        const eventBus = opts.ctx.eventBus;
        const repo = requireConversationRepository(opts.ctx);
 
        // Check if already answered
        const existing = await repo.findById(conversationId);
        if (existing && existing.status === 'answered' && existing.answer) {
          yield tracked('answer-0', { answer: existing.answer });
          return;
        }
 
        // Listen for conversation:answered events matching this ID
        let answered = false;
        let resolve: (() => void) | null = null;
 
        const handler = (event: ConversationAnsweredEvent) => {
          if (event.payload.conversationId !== conversationId) return;
          answered = true;
          if (resolve) {
            const r = resolve;
            resolve = null;
            r();
          }
        };
 
        eventBus.on('conversation:answered', handler);
 
        const cleanup = () => {
          eventBus.off('conversation:answered', handler);
          if (resolve) {
            const r = resolve;
            resolve = null;
            r();
          }
        };
 
        signal.addEventListener('abort', cleanup, { once: true });
 
        try {
          while (!signal.aborted && !answered) {
            await new Promise<void>((r) => {
              resolve = r;
            });
          }
 
          if (answered) {
            const conv = await repo.findById(conversationId);
            if (conv && conv.answer) {
              yield tracked('answer-0', { answer: conv.answer });
            }
          }
        } finally {
          cleanup();
        }
      }),
  };
}