← Tasks
[AI-05] Goldilocks Cost Zero (prose) (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
83%
Pass
PASS
Graded By
-
Graded At
-
Cost
Input Tokens
-
Output Tokens
-
Est. USD
-
Result
{
"cost": {
"input_tokens": 179,
"estimated_usd": 0.051312,
"output_tokens": 3385
},
"model": "claude-sonnet-4-20250514",
"status": "success",
"transport": "anthropic_api",
"latency_ms": 38235,
"response_text": "```typescript\n// src/lib/acp-agents.ts\n// AI-05: ACP agent-to-agent choreography for marketplace\n// EN: Agent Communication Protocol for buyer/seller interactions\n// VI: Giao thức giao tiếp Agent cho tương tác mua/bán\n// ES: Protocolo de Comunicación de Agentes para interacciones comprador/vendedor\n\nimport { z } from 'zod'\n\n// EN: Message schemas for ACP protocol validation\n// VI: Schemas tin nhắn để xác thực giao thức ACP\n// ES: Esquemas de mensajes para validación de protocolo ACP\nconst MessageSchema = z.object({\n id: z.string(),\n sender: z.string(),\n receiver: z.string(),\n type: z.enum(['INQUIRY', 'PROPOSAL', 'ACCEPTANCE', 'REJECTION', 'COMPLETION']),\n payload: z.record(z.any()),\n timestamp: z.number()\n})\n\nconst ChoreographyStateSchema = z.object({\n phase: z.enum(['DISCOVERY', 'NEGOTIATION', 'AGREEMENT', 'EXECUTION', 'COMPLETED']),\n participants: z.array(z.string()),\n messages: z.array(MessageSchema),\n metadata: z.record(z.any())\n})\n\ntype Message = z.infer<typeof MessageSchema>\ntype ChoreographyState = z.infer<typeof ChoreographyStateSchema>\n\n// EN: ACP protocol implementation for agent communication\n// VI: Triển khai giao thức ACP cho giao tiếp agent\n// ES: Implementación de protocolo ACP para comunicación de agentes\nexport class ACP {\n private choreographies: Map<string, ChoreographyState> = new Map()\n\n // EN: Create new choreography between agents\n // VI: Tạo choreography mới giữa các agent\n // ES: Crear nueva coreografía entre agentes\n createChoreography(id: string, participants: string[]): ChoreographyState {\n const choreography: ChoreographyState = {\n phase: 'DISCOVERY',\n participants,\n messages: [],\n metadata: { createdAt: Date.now() }\n }\n\n this.choreographies.set(id, choreography)\n return choreography\n }\n\n // EN: Send message between agents in choreography\n // VI: Gửi tin nhắn giữa các agent trong choreography\n // ES: Enviar mensaje entre agentes en coreografía\n sendMessage(choreographyId: string, message: Partial<Message>): boolean {\n const parseResult = MessageSchema.safeParse({\n ...message,\n timestamp: Date.now()\n })\n\n if (!parseResult.success) {\n return false\n }\n\n const choreography = this.choreographies.get(choreographyId)\n if (!choreography) {\n return false\n }\n\n choreography.messages.push(parseResult.data)\n this.updatePhase(choreographyId, parseResult.data)\n return true\n }\n\n // EN: Update choreography phase based on message type\n // VI: Cập nhật giai đoạn choreography dựa trên loại tin nhắn\n // ES: Actualizar fase de coreografía basada en tipo de mensaje\n private updatePhase(choreographyId: string, message: Message): void {\n const choreography = this.choreographies.get(choreographyId)\n if (!choreography) return\n\n switch (message.type) {\n case 'INQUIRY':\n choreography.phase = 'DISCOVERY'\n break\n case 'PROPOSAL':\n choreography.phase = 'NEGOTIATION'\n break\n case 'ACCEPTANCE':\n choreography.phase = 'AGREEMENT'\n break\n case 'COMPLETION':\n choreography.phase = 'COMPLETED'\n break\n }\n }\n\n // EN: Get choreography state\n // VI: Lấy trạng thái choreography\n // ES: Obtener estado de coreografía\n getChoreography(id: string): ChoreographyState | undefined {\n return this.choreographies.get(id)\n }\n}\n\n// EN: Buyer agent implementation for marketplace\n// VI: Triển khai agent mua hàng cho marketplace\n// ES: Implementación de agente comprador para marketplace\nexport class BuyerAgent {\n constructor(\n private id: string,\n private acp: ACP\n ) {}\n\n // EN: Initiate purchase inquiry with seller\n // VI: Bắt đầu yêu cầu mua hàng với người bán\n // ES: Iniciar consulta de compra con vendedor\n initiateInquiry(sellerId: string, productId: string, requirements: Record<string, any>): string {\n const choreographyId = `${this.id}-${sellerId}-${Date.now()}`\n \n this.acp.createChoreography(choreographyId, [this.id, sellerId])\n \n this.acp.sendMessage(choreographyId, {\n id: `msg-${Date.now()}`,\n sender: this.id,\n receiver: sellerId,\n type: 'INQUIRY',\n payload: {\n productId,\n requirements,\n action: 'purchase_inquiry'\n }\n })\n\n return choreographyId\n }\n\n // EN: Accept seller's proposal\n // VI: Chấp nhận đề xuất của người bán\n // ES: Aceptar propuesta del vendedor\n acceptProposal(choreographyId: string, sellerId: string, terms: Record<string, any>): boolean {\n return this.acp.sendMessage(choreographyId, {\n id: `msg-${Date.now()}`,\n sender: this.id,\n receiver: sellerId,\n type: 'ACCEPTANCE',\n payload: {\n terms,\n action: 'accept_proposal'\n }\n })\n }\n\n // EN: Reject seller's proposal\n // VI: Từ chối đề xuất của người bán\n // ES: Rechazar propuesta del vendedor\n rejectProposal(choreographyId: string, sellerId: string, reason: string): boolean {\n return this.acp.sendMessage(choreographyId, {\n id: `msg-${Date.now()}`,\n sender: this.id,\n receiver: sellerId,\n type: 'REJECTION',\n payload: {\n reason,\n action: 'reject_proposal'\n }\n })\n }\n\n // EN: Complete transaction\n // VI: Hoàn thành giao dịch\n // ES: Completar transacción\n completeTransaction(choreographyId: string, sellerId: string): boolean {\n return this.acp.sendMessage(choreographyId, {\n id: `msg-${Date.now()}`,\n sender: this.id,\n receiver: sellerId,\n type: 'COMPLETION',\n payload: {\n action: 'transaction_complete',\n completedAt: Date.now()\n }\n })\n }\n}\n\n// EN: Seller agent implementation for marketplace\n// VI: Triển khai agent bán hàng cho marketplace\n// ES: Implementación de agente vendedor para marketplace\nexport class SellerAgent {\n constructor(\n private id: string,\n private acp: ACP,\n private inventory: Map<string, any> = new Map()\n ) {}\n\n // EN: Process buyer inquiry and send proposal\n // VI: Xử lý yêu cầu của người mua và gửi đề xuất\n // ES: Procesar consulta del comprador y enviar propuesta\n processInquiry(choreographyId: string, buyerId: string, inquiry: Record<string, any>): boolean {\n const { productId, requirements } = inquiry\n \n // EN: Check inventory and generate proposal\n // VI: Kiểm tra kho hàng và tạo đề xuất\n // ES: Verificar inventario y generar propuesta\n const product = this.inventory.get(productId)\n if (!product) {\n return this.acp.sendMessage(choreographyId, {\n id: `msg-${Date.now()}`,\n sender: this.id,\n receiver: buyerId,\n type: 'REJECTION',\n payload: {\n reason: 'Product not available',\n action: 'product_unavailable'\n }\n })\n }\n\n // EN: Send proposal with pricing and terms\n // VI: Gửi đề xuất với giá cả và điều khoản\n // ES: Enviar propuesta con precios y términos\n return this.acp.sendMessage(choreographyId, {\n id: `msg-${Date.now()}`,\n sender: this.id,\n receiver: buyerId,\n type: 'PROPOSAL',\n payload: {\n productId,\n price: product.price,\n availability: product.stock,\n terms: {\n delivery: '7-14 days',\n warranty: '1 year',\n paymentOptions: ['credit_card', 'crypto']\n },\n action: 'send_proposal'\n }\n })\n }\n\n // EN: Add product to inventory\n // VI: Thêm sản phẩm vào kho hàng\n // ES: Agregar producto al inventario\n addProduct(productId: string, details: Record<string, any>): void {\n this.inventory.set(productId, details)\n }\n\n // EN: Update product availability after sale\n // VI: Cập nhật tình trạng sản phẩm sau khi bán\n // ES: Actualizar disponibilidad del producto después de la venta\n updateInventory(productId: string, quantity: number): boolean {\n const product = this.inventory.get(productId)\n if (!product || product.stock < quantity) {\n return false\n }\n\n product.stock -= quantity\n this.inventory.set(productId, product)\n return true\n }\n\n // EN: Get current inventory status\n // VI: Lấy trạng thái kho hàng hiện tại\n // ES: Obtener estado actual del inventario\n getInventory(): Record<string, any> {\n return Object.fromEntries(this.inventory)\n }\n}\n\n// EN: Agent choreography orchestrator for complex interactions\n// VI: Điều phối choreography agent cho tương tác phức tạp\n// ES: Orquestador de coreografía de agentes para interacciones complejas\nexport const agent_choreography = {\n // EN: Create coordinated agent interaction\n // VI: Tạo tương tác agent được điều phối\n // ES: Crear interacción de agentes coordinada\n createMarketplaceInteraction: (buyerId: string, sellerId: string, productId: string) => {\n const acp = new ACP()\n const buyer = new BuyerAgent(buyerId, acp)\n const seller = new SellerAgent(sellerId, acp)\n\n // EN: Setup initial product inventory\n // VI: Thiết lập kho hàng sản phẩm ban đầu\n // ES: Configurar inventario inicial de productos\n seller.addProduct(productId, {\n name: 'Sample Product',\n price: 99.99,\n stock: 10,\n category: 'electronics'\n })\n\n return { acp, buyer, seller }\n },\n\n // EN: Execute full purchase choreography\n // VI: Thực hiện choreography mua hàng đầy đủ\n // ES: Ejecutar coreografía completa de compra\n executePurchaseFlow: async (buyerId: string, sellerId: string, productId: string) => {\n const { acp, buyer, seller } = agent_choreography.createMarketplaceInteraction(\n buyerId, sellerId, productId\n )\n\n // EN: Step 1: Buyer initiates inquiry\n // VI: Bước 1: Người mua bắt đầu yêu cầu\n // ES: Paso 1: Comprador inicia consulta\n const choreographyId = buyer.initiateInquiry(sellerId, productId, {\n quantity: 1,\n maxPrice: 100\n })\n\n // EN: Step 2: Seller processes inquiry\n // VI: Bước 2: Người bán xử lý yêu cầu\n // ES: Paso 2: Vendedor procesa consulta\n const choreography = acp.getChoreography(choreographyId)\n if (choreography && choreography.messages.length > 0) {\n const inquiry = choreography.messages[0]\n seller.processInquiry(choreographyId, buyerId, inquiry.payload)\n }\n\n return { choreographyId, acp }\n }\n}\n\n// EN: Export ACP instance for global use\n// VI: Xuất instance ACP để sử dụng toàn cục\n// ES: Exportar instancia ACP para uso global\nexport const acp = new ACP()\nexport const buyer_agent = (id: string) => new BuyerAgent(id, acp)\nexport const seller_agent = (id: string) => new SellerAgent(id, acp)\n```"
}Task ID: 3ed56d1a-2b0f-4743-b374-3600d95531f5