← Tasks
[AI-05] Solo baseline (Swiss HF) (retry 1) (retry 2) (retry 3)
completedcode_genP0
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
Cloud Lu → Claude Sonnet
Created
1d ago
Completed
1d ago
Quality
Overall
81%
Pass
PASS
Graded By
-
Graded At
-
Cost
Input Tokens
-
Output Tokens
-
Est. USD
-
Result
{
"cost": {
"input_tokens": 177,
"estimated_usd": 0.077736,
"output_tokens": 5147
},
"model": "claude-sonnet-4-20250514",
"status": "success",
"transport": "anthropic_api",
"latency_ms": 62200,
"response_text": "I'll implement the ACP agent-to-agent choreography module for buyer/seller marketplace interactions.\n\n```typescript\n// src/lib/acp-agents.ts\n// EN: Agent Communication Protocol for buyer/seller marketplace choreography\n// VI: Giao thức truyền thông tác nhân cho điều phối thị trường mua/bán\n// ES: Protocolo de comunicación de agentes para coreografía de mercado comprador/vendedor\n\nimport { z } from 'zod'\n\n// SPEC: M4.AI-05 - ACP agent choreography schema validation\n// EN: Message types and protocol definitions\n// VI: Định nghĩa loại tin nhắn và giao thức\n// ES: Definiciones de tipos de mensajes y protocolo\n\nconst MessageSchema = z.object({\n id: z.string(),\n type: z.enum(['inquiry', 'quote', 'negotiate', 'accept', 'reject', 'confirm']),\n sender: z.string(),\n receiver: z.string(),\n payload: z.record(z.any()),\n timestamp: z.number(),\n})\n\nconst ProductSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: z.string(),\n price: z.number(),\n quantity: z.number().optional(),\n})\n\nconst AgentStateSchema = z.object({\n id: z.string(),\n type: z.enum(['buyer', 'seller']),\n status: z.enum(['idle', 'negotiating', 'busy', 'offline']),\n preferences: z.record(z.any()),\n})\n\ntype Message = z.infer<typeof MessageSchema>\ntype Product = z.infer<typeof ProductSchema>\ntype AgentState = z.infer<typeof AgentStateSchema>\n\n// SPEC: M4.AI-05 - Core ACP implementation\n// EN: Agent Communication Protocol base class\n// VI: Lớp cơ sở giao thức truyền thông tác nhân\n// ES: Clase base del protocolo de comunicación de agentes\n\nexport class acp {\n private messageQueue: Message[] = []\n private agents: Map<string, AgentState> = new Map()\n\n // EN: Register agent in the ACP network\n // VI: Đăng ký tác nhân trong mạng ACP\n // ES: Registrar agente en la red ACP\n registerAgent(agent: AgentState): boolean {\n const validation = AgentStateSchema.safeParse(agent)\n if (!validation.success) {\n console.error('Invalid agent state:', validation.error)\n return false\n }\n\n this.agents.set(agent.id, agent)\n return true\n }\n\n // EN: Send message between agents with protocol validation\n // VI: Gửi tin nhắn giữa các tác nhân với xác thực giao thức\n // ES: Enviar mensaje entre agentes con validación de protocolo\n sendMessage(message: Message): boolean {\n const validation = MessageSchema.safeParse(message)\n if (!validation.success) {\n console.error('Invalid message format:', validation.error)\n return false\n }\n\n // EN: Check if sender and receiver exist\n // VI: Kiểm tra người gửi và người nhận có tồn tại\n // ES: Verificar si el remitente y receptor existen\n if (!this.agents.has(message.sender) || !this.agents.has(message.receiver)) {\n console.error('Agent not found in network')\n return false\n }\n\n this.messageQueue.push(message)\n return true\n }\n\n // EN: Get pending messages for specific agent\n // VI: Lấy tin nhắn đang chờ cho tác nhân cụ thể\n // ES: Obtener mensajes pendientes para agente específico\n getMessages(agentId: string): Message[] {\n return this.messageQueue.filter(msg => msg.receiver === agentId)\n }\n\n // EN: Remove processed messages from queue\n // VI: Xóa tin nhắn đã xử lý khỏi hàng đợi\n // ES: Eliminar mensajes procesados de la cola\n acknowledgeMessage(messageId: string): void {\n this.messageQueue = this.messageQueue.filter(msg => msg.id !== messageId)\n }\n}\n\n// SPEC: M4.AI-05 - Buyer agent implementation\n// EN: Buyer agent with marketplace choreography logic\n// VI: Tác nhân mua hàng với logic điều phối thị trường\n// ES: Agente comprador con lógica de coreografía de mercado\n\nexport class buyer_agent {\n private state: AgentState\n private acp: acp\n private budget: number\n private requirements: Product[]\n\n constructor(id: string, acpInstance: acp, budget: number = 1000) {\n this.state = {\n id,\n type: 'buyer',\n status: 'idle',\n preferences: { budget, maxNegotiationRounds: 3 }\n }\n this.acp = acpInstance\n this.budget = budget\n this.requirements = []\n \n // EN: Register with ACP network\n // VI: Đăng ký với mạng ACP\n // ES: Registrarse en la red ACP\n this.acp.registerAgent(this.state)\n }\n\n // EN: Send product inquiry to seller agent\n // VI: Gửi yêu cầu sản phẩm đến tác nhân bán hàng\n // ES: Enviar consulta de producto al agente vendedor\n sendInquiry(sellerId: string, product: Partial<Product>): string {\n const messageId = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`\n \n const message: Message = {\n id: messageId,\n type: 'inquiry',\n sender: this.state.id,\n receiver: sellerId,\n payload: { \n product,\n budget: this.budget,\n urgency: 'normal'\n },\n timestamp: Date.now()\n }\n\n const success = this.acp.sendMessage(message)\n if (success) {\n this.state.status = 'negotiating'\n console.log(`Buyer ${this.state.id} sent inquiry for ${product.name}`)\n }\n \n return messageId\n }\n\n // EN: Process incoming messages and respond according to choreography\n // VI: Xử lý tin nhắn đến và phản hồi theo điều phối\n // ES: Procesar mensajes entrantes y responder según coreografía\n processMessages(): void {\n const messages = this.acp.getMessages(this.state.id)\n \n messages.forEach(message => {\n switch (message.type) {\n case 'quote':\n this.handleQuote(message)\n break\n case 'negotiate':\n this.handleNegotiation(message)\n break\n case 'confirm':\n this.handleConfirmation(message)\n break\n }\n \n this.acp.acknowledgeMessage(message.id)\n })\n }\n\n private handleQuote(message: Message): void {\n const { price, product } = message.payload\n \n if (price <= this.budget) {\n // EN: Accept quote if within budget\n // VI: Chấp nhận báo giá nếu trong ngân sách\n // ES: Aceptar cotización si está dentro del presupuesto\n this.sendResponse(message.sender, 'accept', { \n originalMessageId: message.id,\n agreedPrice: price,\n product \n })\n } else {\n // EN: Negotiate if price exceeds budget\n // VI: Thương lượng nếu giá vượt ngân sách\n // ES: Negociar si el precio excede el presupuesto\n const counterOffer = Math.min(price * 0.8, this.budget)\n this.sendResponse(message.sender, 'negotiate', { \n originalMessageId: message.id,\n counterPrice: counterOffer,\n reason: 'budget_constraint'\n })\n }\n }\n\n private handleNegotiation(message: Message): void {\n // EN: Handle seller's counter-negotiation\n // VI: Xử lý thương lượng phản hồi của người bán\n // ES: Manejar contra-negociación del vendedor\n const { counterPrice } = message.payload\n \n if (counterPrice <= this.budget) {\n this.sendResponse(message.sender, 'accept', {\n originalMessageId: message.id,\n finalPrice: counterPrice\n })\n } else {\n this.sendResponse(message.sender, 'reject', {\n originalMessageId: message.id,\n reason: 'price_too_high'\n })\n }\n }\n\n private handleConfirmation(message: Message): void {\n console.log(`Purchase confirmed by seller: ${JSON.stringify(message.payload)}`)\n this.state.status = 'idle'\n }\n\n private sendResponse(receiverId: string, type: Message['type'], payload: any): void {\n const responseMessage: Message = {\n id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n type,\n sender: this.state.id,\n receiver: receiverId,\n payload,\n timestamp: Date.now()\n }\n \n this.acp.sendMessage(responseMessage)\n }\n}\n\n// SPEC: M4.AI-05 - Seller agent implementation\n// EN: Seller agent with marketplace choreography logic\n// VI: Tác nhân bán hàng với logic điều phối thị trường\n// ES: Agente vendedor con lógica de coreografía de mercado\n\nexport class seller_agent {\n private state: AgentState\n private acp: acp\n private inventory: Product[]\n private minProfitMargin: number\n\n constructor(id: string, acpInstance: acp, inventory: Product[] = [], minProfit: number = 0.1) {\n this.state = {\n id,\n type: 'seller',\n status: 'idle',\n preferences: { minProfitMargin: minProfit, autoAcceptThreshold: 0.95 }\n }\n this.acp = acpInstance\n this.inventory = inventory\n this.minProfitMargin = minProfit\n \n // EN: Register with ACP network\n // VI: Đăng ký với mạng ACP\n // ES: Registrarse en la red ACP\n this.acp.registerAgent(this.state)\n }\n\n // EN: Add products to inventory\n // VI: Thêm sản phẩm vào kho\n // ES: Agregar productos al inventario\n addProduct(product: Product): boolean {\n const validation = ProductSchema.safeParse(product)\n if (!validation.success) {\n console.error('Invalid product:', validation.error)\n return false\n }\n \n this.inventory.push(product)\n return true\n }\n\n // EN: Process incoming buyer inquiries and negotiations\n // VI: Xử lý yêu cầu và thương lượng từ người mua\n // ES: Procesar consultas y negociaciones de compradores entrantes\n processMessages(): void {\n const messages = this.acp.getMessages(this.state.id)\n \n messages.forEach(message => {\n switch (message.type) {\n case 'inquiry':\n this.handleInquiry(message)\n break\n case 'negotiate':\n this.handleNegotiation(message)\n break\n case 'accept':\n this.handleAcceptance(message)\n break\n case 'reject':\n this.handleRejection(message)\n break\n }\n \n this.acp.acknowledgeMessage(message.id)\n })\n }\n\n private handleInquiry(message: Message): void {\n const { product: inquiredProduct, budget } = message.payload\n \n // EN: Find matching product in inventory\n // VI: Tìm sản phẩm phù hợp trong kho\n // ES: Encontrar producto coincidente en inventario\n const availableProduct = this.inventory.find(p => \n p.name.toLowerCase().includes(inquiredProduct.name?.toLowerCase() || '') ||\n p.category === inquiredProduct.category\n )\n\n if (availableProduct) {\n this.sendQuote(message.sender, availableProduct, message.id)\n this.state.status = 'negotiating'\n } else {\n this.sendResponse(message.sender, 'reject', {\n originalMessageId: message.id,\n reason: 'product_not_available'\n })\n }\n }\n\n private handleNegotiation(message: Message): void {\n const { counterPrice, originalMessageId } = message.payload\n const minAcceptablePrice = this.calculateMinPrice(counterPrice)\n \n if (counterPrice >= minAcceptablePrice) {\n // EN: Accept counter-offer if it meets minimum profit\n // VI: Chấp nhận đề nghị nếu đạt lợi nhuận tối thiểu\n // ES: Aceptar contraoferta si cumple con el beneficio mínimo\n this.sendResponse(message.sender, 'accept', {\n originalMessageId,\n finalPrice: counterPrice,\n agreedTerms: 'standard'\n })\n } else {\n // EN: Make counter-counter offer\n // VI: Đưa ra đề nghị phản hồi\n // ES: Hacer contraoferta\n const counterCounterPrice = (counterPrice + minAcceptablePrice) / 2\n this.sendResponse(message.sender, 'negotiate', {\n originalMessageId,\n counterPrice: counterCounterPrice,\n reason: 'below_minimum_profit'\n })\n }\n }\n\n private handleAcceptance(message: Message): void {\n const { finalPrice, product } = message.payload\n \n // EN: Confirm transaction and update inventory\n // VI: Xác nhận giao dịch và cập nhật kho\n // ES: Confirmar transacción y actualizar inventario\n this.sendResponse(message.sender, 'confirm', {\n transactionId: `tx_${Date.now()}`,\n finalPrice,\n product,\n deliveryEstimate: '3-5 business days'\n })\n \n this.state.status = 'idle'\n console.log(`Sale completed: ${product?.name || 'product'} for $${finalPrice}`)\n }\n\n private handleRejection(message: Message): void {\n console.log(`Buyer rejected offer: ${message.payload.reason}`)\n this.state.status = 'idle'\n }\n\n private sendQuote(buyerId: string, product: Product, originalMessageId: string): void {\n const quoteMessage: Message = {\n id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n type: 'quote',\n sender: this.state.id,\n receiver: buyerId,\n payload: {\n originalMessageId,\n product,\n price: product.price,\n availability: product.quantity || 1,\n validUntil: Date.now() + (24 * 60 * 60 * 1000) // 24 hours\n },\n timestamp: Date.now()\n }\n \n this.acp.sendMessage(quoteMessage)\n }\n\n private sendResponse(receiverId: string, type: Message['type'], payload: any): void {\n const responseMessage: Message = {\n id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n type,\n sender: this.state.id,\n receiver: receiverId,\n payload,\n timestamp: Date.now()\n }\n \n this.acp.sendMessage(responseMessage)\n }\n\n private calculateMinPrice(offeredPrice: number): number {\n // EN: Calculate minimum acceptable price based on profit margin\n // VI: Tính giá tối thiểu có thể chấp nhận dựa trên tỷ suất lợi nhuận\n // ES: Calcular precio mínimo aceptable basado en margen de beneficio\n return offeredPrice * (1 - this.minProfitMargin)\n }\n}\n\n// SPEC: M4.AI-05 - Agent choreography orchestrator\n// EN: Choreography manager for coordinating agent interactions\n// VI: Trình quản lý điều phối cho phối hợp tương tác tác nhân\n// ES: Gestor de coreografía para coordinar interacciones de agentes\n\nexport const agent_choreography = {\n // EN: Initialize marketplace with ACP and sample agents\n // VI: Khởi tạo thị trường với ACP và tác nhân mẫu\n // ES: Inicializar mercado con ACP y agentes de muestra\n initializeMarketplace(): { acp: acp, buyers: buyer_agent[], sellers: seller_agent[] } {\n const acpInstance = new acp()\n \n // EN: Create sample sellers with inventory\n // VI: Tạo người bán mẫu với kho hàng\n // ES: Crear vendedores de muestra con inventario\n const seller1 = new seller_agent('seller_001', acpInstance, [\n { id: 'laptop_001', name: 'Gaming Laptop', category: 'electronics', price: 1200 },\n { id: 'phone_001', name: 'Smartphone', category: 'electronics', price: 800 }\n ])\n\n const seller2 = new seller_agent('seller_002', acpInstance, [\n { id: 'book_001', name: 'Programming Guide', category: 'books', price: 45 },\n { id: 'desk_001', name: 'Office Desk', category: 'furniture', price: 300 }\n ])\n\n // EN: Create sample buyers with different budgets\n // VI: Tạo người mua mẫu với ngân sách khác nhau\n // ES: Crear compradores de muestra con diferentes presupuestos\n const buyer1 = new buyer_agent('buyer_001', acpInstance, 1000)\n const buyer2 = new buyer_agent('buyer_002', acpInstance, 500)\n\n return {\n acp: acpInstance,\n buyers: [buyer1, buyer2],\n sellers: [seller1, seller2]\n }\n },\n\n // EN: Execute choreography simulation step\n // VI: Thực hiện bước mô phỏng điều phối\n // ES: Ejecutar paso de simulación de coreografía\n simulateMarketActivity(marketplace: ReturnType<typeof agent_choreography.initializeMarketplace>): void {\n const { buyers, sellers } = marketplace\n\n // EN: Process all pending messages for all agents\n // VI: Xử lý tất cả tin nhắn đang chờ cho tất cả tác nhân\n // ES: Procesar todos los mensajes pendientes para todos los agentes\n [...buyers, ...sellers].forEach(agent => {\n agent.processMessages()\n })\n\n console.log('Market activity simulation step completed')\n }\n}\n```\n\nThis implementation provides a complete ACP (Agent Communication Protocol) module with:\n\n**Core Features:**\n- `acp`: Base communication protocol with message queuing and agent registration\n- `buyer_agent`: Intelligent buyer with budget constraints and negotiation logic\n- `seller_agent`: Seller with inventory management and profit optimization\n- `agent_choreography`: Orchestrator for coordinating marketplace interactions\n\n**Key Choreography Elements:**\n- Message-based communication with validation\n- Multi-step negotiation flows (inquiry → quote → negotiate → accept/reject → confirm)\n- State management for agents during negotiations\n- Inventory and budget constraint handling\n- Automatic response generation based on business rules\n\nThe module follows all specified conventions with trilingual comments, Zod validation, and proper error handling."
}Task ID: 40f61a66-f0d3-4487-893f-c741030b6a47