FOUNDRY
C8 Platform
← Tasks

[AI-05] ACP choreography (Opus 4.5)

completedcode_genP3

Description

## AI-05: ACP agent-to-agent choreography Section: AI Features | Milestone: M4 ### Requirements Implement an ACP (Agent Communication Protocol) module for buyer/seller marketplace agents. ### Acceptance Criteria - File src/lib/acp-agents.ts must contain: agent choreography, acp, buyer_agent, seller_agent ### Codebase Conventions - Trilingual comments: // EN: ... // VI: ... // ES: ... - SPEC section refs in comments - Zod at module level with .safeParse() - NextResponse.json() responses Write
Assignee
-
Claimed By
Opus 4.5
Created
25d ago
Completed
25d ago

Quality

Overall
86%
Pass
PASS
Graded By
-
Graded At
-

Cost

Input Tokens
196
Output Tokens
4,096
Est. USD
$0.3101

Result

{
  "code": "```typescript\n// src/lib/acp-agents.ts\n// EN: ACP (Agent Communication Protocol) module for buyer/seller marketplace agents\n// VI: Module ACP (Giao thức Giao tiếp Đại lý) cho các đại lý mua/bán trên thị trường\n// ES: Módulo ACP (Protocolo de Comunicación de Agentes) para agentes compradores/vendedores del mercado\n\n// SPEC: AI-05 - ACP agent-to-agent choreography\n// Section: AI Features | Milestone: M4\n\nimport { z } from \"zod\";\n\n// EN: Agent role enumeration for marketplace participants\n// VI: Liệt kê vai trò đại lý cho những người tham gia thị trường\n// ES: Enumeración de roles de agentes para participantes del mercado\nexport const AgentRoleSchema = z.enum([\n  \"buyer_agent\",\n  \"seller_agent\",\n  \"marketplace_agent\",\n]);\n\nexport type AgentRole = z.infer<typeof AgentRoleSchema>;\n\n// EN: Message types supported by ACP protocol\n// VI: Các loại tin nhắn được hỗ trợ bởi giao thức ACP\n// ES: Tipos de mensajes soportados por el protocolo ACP\nexport const ACPMessageTypeSchema = z.enum([\n  \"REQUEST_QUOTE\",\n  \"QUOTE_RESPONSE\",\n  \"NEGOTIATE_PRICE\",\n  \"ACCEPT_OFFER\",\n  \"REJECT_OFFER\",\n  \"COUNTER_OFFER\",\n  \"CONFIRM_TRANSACTION\",\n  \"CANCEL_TRANSACTION\",\n  \"REGISTER_AGENT\",\n  \"DEREGISTER_AGENT\",\n  \"HEARTBEAT\",\n  \"ACK\",\n]);\n\nexport type ACPMessageType = z.infer<typeof ACPMessageTypeSchema>;\n\n// EN: Base agent schema with common properties\n// VI: Schema đại lý cơ bản với các thuộc tính chung\n// ES: Esquema base de agente con propiedades comunes\nexport const BaseAgentSchema = z.object({\n  id: z.string().uuid(),\n  role: AgentRoleSchema,\n  name: z.string().min(1).max(100),\n  status: z.enum([\"active\", \"inactive\", \"busy\", \"offline\"]),\n  capabilities: z.array(z.string()),\n  metadata: z.record(z.string(), z.unknown()).optional(),\n  createdAt: z.date(),\n  lastActiveAt: z.date(),\n});\n\nexport type BaseAgent = z.infer<typeof BaseAgentSchema>;\n\n// EN: Buyer agent with purchasing preferences and budget\n// VI: Đại lý mua với sở thích mua và ngân sách\n// ES: Agente comprador con preferencias de compra y presupuesto\nexport const BuyerAgentSchema = BaseAgentSchema.extend({\n  role: z.literal(\"buyer_agent\"),\n  budget: z.number().positive(),\n  currency: z.string().length(3),\n  preferences: z.object({\n    categories: z.array(z.string()),\n    maxPricePerItem: z.number().positive().optional(),\n    preferredSellers: z.array(z.string().uuid()).optional(),\n    autoNegotiate: z.boolean().default(true),\n    maxNegotiationRounds: z.number().int().min(1).max(10).default(3),\n  }),\n  purchaseHistory: z\n    .array(\n      z.object({\n        transactionId: z.string().uuid(),\n        sellerId: z.string().uuid(),\n        amount: z.number().positive(),\n        timestamp: z.date(),\n      })\n    )\n    .optional(),\n});\n\nexport type BuyerAgent = z.infer<typeof BuyerAgentSchema>;\n\n// EN: Seller agent with inventory and pricing strategies\n// VI: Đại lý bán với kho hàng và chiến lược giá\n// ES: Agente vendedor con inventario y estrategias de precios\nexport const SellerAgentSchema = BaseAgentSchema.extend({\n  role: z.literal(\"seller_agent\"),\n  inventory: z.array(\n    z.object({\n      itemId: z.string().uuid(),\n      name: z.string(),\n      quantity: z.number().int().nonnegative(),\n      basePrice: z.number().positive(),\n      minPrice: z.number().positive(),\n      category: z.string(),\n    })\n  ),\n  pricingStrategy: z.enum([\n    \"fixed\",\n    \"dynamic\",\n    \"auction\",\n    \"negotiable\",\n  ]),\n  rating: z.number().min(0).max(5).optional(),\n  salesHistory: z\n    .array(\n      z.object({\n        transactionId: z.string().uuid(),\n        buyerId: z.string().uuid(),\n        itemId: z.string().uuid(),\n        finalPrice: z.number().positive(),\n        timestamp: z.date(),\n      })\n    )\n    .optional(),\n});\n\nexport type SellerAgent = z.infer<typeof SellerAgentSchema>;\n\n// EN: Marketplace agent for orchestrating transactions\n// VI: Đại lý thị trường để điều phối các giao dịch\n// ES: Agente del mercado para orquestar transacciones\nexport const MarketplaceAgentSchema = BaseAgentSchema.extend({\n  role: z.literal(\"marketplace_agent\"),\n  registeredBuyers: z.array(z.string().uuid()),\n  registeredSellers: z.array(z.string().uuid()),\n  activeTransactions: z.array(z.string().uuid()),\n  commissionRate: z.number().min(0).max(1),\n  rules: z.object({\n    maxTransactionValue: z.number().positive(),\n    allowNegotiation: z.boolean(),\n    escrowRequired: z.boolean(),\n    disputeResolutionEnabled: z.boolean(),\n  }),\n});\n\nexport type MarketplaceAgent = z.infer<typeof MarketplaceAgentSchema>;\n\n// EN: ACP message schema for agent communication\n// VI: Schema tin nhắn ACP cho giao tiếp đại lý\n// ES: Esquema de mensaje ACP para comunicación de agentes\nexport const ACPMessageSchema = z.object({\n  messageId: z.string().uuid(),\n  type: ACPMessageTypeSchema,\n  senderId: z.string().uuid(),\n  receiverId: z.string().uuid(),\n  conversationId: z.string().uuid(),\n  timestamp: z.date(),\n  payload: z.record(z.string(), z.unknown()),\n  signature: z.string().optional(),\n  ttl: z.number().int().positive().optional(),\n  priority: z.enum([\"low\", \"normal\", \"high\", \"urgent\"]).default(\"normal\"),\n});\n\nexport type ACPMessage = z.infer<typeof ACPMessageSchema>;\n\n// EN: Quote request payload schema\n// VI: Schema payload yêu cầu báo giá\n// ES: Esquema de carga útil de solicitud de cotización\nexport const QuoteRequestPayloadSchema = z.object({\n  itemId: z.string().uuid(),\n  quantity: z.number().int().positive(),\n  desiredPrice: z.number().positive().optional(),\n  deliveryRequirements: z.string().optional(),\n});\n\nexport type QuoteRequestPayload = z.infer<typeof QuoteRequestPayloadSchema>;\n\n// EN: Quote response payload schema\n// VI: Schema payload phản hồi báo giá\n// ES: Esquema de carga útil de respuesta de cotización\nexport const QuoteResponsePayloadSchema = z.object({\n  itemId: z.string().uuid(),\n  quantity: z.number().int().positive(),\n  unitPrice: z.number().positive(),\n  totalPrice: z.number().positive(),\n  validUntil: z.date(),\n  terms: z.string().optional(),\n});\n\nexport type QuoteResponsePayload = z.infer<typeof QuoteResponsePayloadSchema>;\n\n// EN: Negotiation payload schema\n// VI: Schema payload đàm phán\n// ES: Esquema de carga útil de negociación\nexport const NegotiationPayloadSchema = z.object({\n  originalQuoteId: z.string().uuid(),\n  proposedPrice: z.number().positive(),\n  round: z.number().int().positive(),\n  justification: z.string().optional(),\n});\n\nexport type NegotiationPayload = z.infer<typeof NegotiationPayloadSchema>;\n\n// EN: Transaction confirmation payload schema\n// VI: Schema payload xác nhận giao dịch\n// ES: Esquema de carga útil de confirmación de transacción\nexport const TransactionConfirmationPayloadSchema = z.object({\n  transactionId: z.string().uuid(),\n  buyerId: z.string().uuid(),\n  sellerId: z.string().uuid(),\n  itemId: z.string().uuid(),\n  quantity: z.number().int().positive(),\n  finalPrice: z.number().positive(),\n  escrowId: z.string().uuid().optional(),\n});\n\nexport type TransactionConfirmationPayload = z.infer<\n  typeof TransactionConfirmationPayloadSchema\n>;\n\n// EN: Agent choreography state machine states\n// VI: Các trạng thái máy trạng thái điều phối đại lý\n// ES: Estados de la máquina de estados de coreografía de agentes\nexport const ChoreographyStateSchema = z.enum([\n  \"IDLE\",\n  \"QUOTE_REQUESTED\",\n  \"QUOTE_RECEIVED\",\n  \"NEGOTIATING\",\n  \"OFFER_ACCEPTED\",\n  \"OFFER_REJECTED\",\n  \"TRANSACTION_PENDING\",\n  \"TRANSACTION_CONFIRMED\",\n  \"TRANSACTION_CANCELLED\",\n  \"ERROR\",\n]);\n\nexport type ChoreographyState = z.infer<typeof ChoreographyStateSchema>;\n\n// EN: Choreography session tracking\n// VI: Theo dõi phiên điều phối\n// ES: Seguimiento de sesión de coreografía\nexport const ChoreographySessionSchema = z.object({\n  sessionId: z.string().uuid(),\n  conversationId: z.string().uuid(),\n  buyerId: z.string().uuid(),\n  sellerId: z.string().uuid(),\n  marketplaceId: z.string().uuid().optional(),\n  currentState: ChoreographyStateSchema,\n  stateHistory: z.array(\n    z.object({\n      state: ChoreographyStateSchema,\n      timestamp: z.date(),\n      triggeredBy: z.string().uuid(),\n    })\n  ),\n  messages: z.array(ACPMessageSchema),\n  startedAt: z.date(),\n  updatedAt: z.date(),\n  completedAt: z.date().optional(),\n});\n\nexport type ChoreographySession = z.infer<typeof ChoreographySessionSchema>;\n\n// EN: ACP Protocol class for agent communication choreography\n// VI: Lớp Giao thức ACP cho điều phối giao tiếp đại lý\n// ES: Clase de Protocolo ACP para coreografía de comunicación de agentes\nexport class ACPProtocol {\n  private sessions: Map<string, ChoreographySession> = new Map();\n  private agents: Map<string, BuyerAgent | SellerAgent | MarketplaceAgent> =\n    new Map();\n\n  // EN: Register an agent with the protocol\n  // VI: Đăng ký một đại lý với giao thức\n  // ES: Registrar un agente con el protocolo\n  registerAgent(\n    agent: BuyerAgent | SellerAgent | MarketplaceAgent\n  ): { success: boolean; error?: string } {\n    // SPEC: AI-05 - Agent registration validation\n    const validation = BaseAgentSchema.safeParse(agent);\n    if (!validation.success) {\n      return {\n        success: false,\n        error: `Invalid agent data: ${validation.error.message}`,\n      };\n    }\n\n    this.agents.set(agent.id, agent);\n    return { success: true };\n  }\n\n  // EN: Create a new choreography session between buyer and seller\n  // VI: Tạo một phiên điều phối mới giữa người mua và người bán\n  // ES: Crear una nueva sesión de coreografía entre comprador y vendedor\n  createSession(\n    buyerId: string,\n    sellerId: string,\n    marketplaceId?: string\n  ): { success: boolean; session?: ChoreographySession; error?: string } {\n    const buyer = this.agents.get(buyerId);\n    const seller = this.agents.get(sellerId);\n\n    if (!buyer || buyer.role !== \"buyer_agent\") {\n      return { success: false, error: \"Invalid buyer agent\" };\n    }\n\n    if (!seller || seller.role !== \"seller_agent\") {\n      return { success: false, error: \"Invalid seller agent\" };\n    }\n\n    const sessionId = crypto.randomUUID();\n    const conversationId = crypto.randomUUID();\n    const now = new Date();\n\n    const session: ChoreographySession = {\n      sessionId,\n      conversationId,\n      buyerId,\n      sellerId,\n      marketplaceId,\n      currentState: \"IDLE\",\n      stateHistory: [\n        {\n          state: \"IDLE\",\n          timestamp: now,\n          triggeredBy: buyerId,\n        },\n      ],\n      messages: [],\n      startedAt: now,\n      updatedAt: now,\n    };\n\n    // SPEC: AI-05 - Session validation\n    const validation = ChoreographySessionSchema.safeParse(session);\n    if (!validation.success) {\n      return {\n        success: false,\n        error: `Session creation failed: ${validation.error.message}`,\n      };\n    }\n\n    this.sessions.set(sessionId, session);\n    return { success: true, session };\n  }\n\n  // EN: Process incoming ACP message and update choreography state\n  // VI: Xử lý tin nhắn ACP đến và cập nhật trạng thái điều phối\n  // ES: Procesar mensaje ACP entrante y actualizar estado de coreografía\n  processMessage(\n    sessionId: string,\n    message: ACPMessage\n  ): {\n    success: boolean;\n    newState?: ChoreographyState;\n    response?: ACPMessage;\n    error?: string;\n  } {\n    // SPEC: AI-05 - Message validation with Zod\n    const messageValidation = ACPMessageSchema.safeParse(message);\n    if (!messageValidation.success) {\n      return {\n        success: false,\n        error: `Invalid message: ${messageValidation.error.message}`,\n      };\n    }\n\n    const session = this.sessions.get(sessionId);\n    if (!session) {\n      return { success: false, error: \"Session not found\" };\n    }\n\n    const stateTransition = this.getStateTransition(\n      session.currentState,\n      message.type\n    );\n    if (!stateTransition.valid) {\n      return {\n        success: false,\n        error: `Invalid state transition from ${session.currentState} with message type ${message.type}`,\n      };\n    }\n\n    // EN: Update session state\n    // VI: Cập nhật trạng thái phiên\n    // ES: Actualizar estado de sesión\n    const now = new Date();\n    session.currentState = stateTransition.newState;\n    session.stateHistory.push({\n      state: stateTransition.newState,\n      timestamp: now,\n      triggeredBy: message.senderId,\n    });\n    session.messages.push(message);\n    session.updatedAt = now;\n\n    if (\n      stateTransition.newState === \"TRANSACTION_CONFIRMED\" ||\n      stateTransition.newState === \"TRANSACTION_CANCELLED\"\n    ) {\n      session.completedAt = now;\n    }\n\n    this.sessions.set(sessionId, session);\n\n    // EN: Generate automatic response if needed\n    // VI: Tạo phản hồi tự động nếu cần\n    // ES: Generar respuesta automática si es necesario\n    const autoResponse = this.generateAutoResponse(session, message);\n\n    return {\n      success: true,\n      newState: stateTransition.newState,\n      response: autoResponse,",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedOpus 4.5
25d agotask_createdfoundry_race
Task ID: ed085f81-1f8a-45f7-8c50-e71a75c4453b