← Tasks
[AI-05] Solo baseline (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
83%
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 Agent) cho các agent mua/bán trong marketplace\n// ES: Módulo ACP (Protocolo de Comunicación de Agentes) para agentes comprador/vendedor del marketplace\n// SPEC: AI-05 - ACP agent-to-agent choreography\n\nimport { z } from \"zod\";\nimport { NextResponse } from \"next/server\";\n\n// ============================================================================\n// EN: Zod Schemas for Agent Types\n// VI: Zod Schemas cho các loại Agent\n// ES: Esquemas Zod para tipos de Agentes\n// SPEC: AI-05 - Agent type definitions with Zod validation\n// ============================================================================\n\n// EN: Base agent schema with common properties\n// VI: Schema agent cơ bản với các thuộc tính chung\n// ES: Esquema de agente base con propiedades comunes\nconst BaseAgentSchema = z.object({\n agentId: z.string().uuid(),\n agentType: z.enum([\"buyer_agent\", \"seller_agent\", \"marketplace_agent\"]),\n status: z.enum([\"active\", \"inactive\", \"negotiating\", \"completed\"]),\n createdAt: z.date(),\n lastActiveAt: z.date(),\n metadata: z.record(z.unknown()).optional(),\n});\n\n// EN: Buyer agent schema - represents purchasing entities\n// VI: Schema agent người mua - đại diện cho các thực thể mua hàng\n// ES: Esquema de agente comprador - representa entidades de compra\nexport const BuyerAgentSchema = BaseAgentSchema.extend({\n agentType: z.literal(\"buyer_agent\"),\n budget: z.number().positive(),\n preferences: z.object({\n categories: z.array(z.string()),\n priceRange: z.object({\n min: z.number().nonnegative(),\n max: z.number().positive(),\n }),\n qualityThreshold: z.number().min(0).max(100),\n urgency: z.enum([\"low\", \"medium\", \"high\"]),\n }),\n purchaseHistory: z.array(z.string().uuid()).default([]),\n activeNegotiations: z.array(z.string().uuid()).default([]),\n});\n\n// EN: Seller agent schema - represents selling entities\n// VI: Schema agent người bán - đại diện cho các thực thể bán hàng\n// ES: Esquema de agente vendedor - representa entidades de venta\nexport const SellerAgentSchema = BaseAgentSchema.extend({\n agentType: z.literal(\"seller_agent\"),\n inventory: z.array(\n z.object({\n productId: z.string().uuid(),\n name: z.string(),\n quantity: z.number().int().nonnegative(),\n basePrice: z.number().positive(),\n minAcceptablePrice: z.number().positive(),\n category: z.string(),\n })\n ),\n reputation: z.number().min(0).max(5),\n salesHistory: z.array(z.string().uuid()).default([]),\n activeListings: z.array(z.string().uuid()).default([]),\n negotiationStrategy: z.enum([\"aggressive\", \"moderate\", \"flexible\"]),\n});\n\n// EN: Marketplace agent schema - orchestrates buyer/seller interactions\n// VI: Schema agent marketplace - điều phối tương tác giữa người mua/bán\n// ES: Esquema de agente marketplace - orquesta interacciones comprador/vendedor\nexport const MarketplaceAgentSchema = BaseAgentSchema.extend({\n agentType: z.literal(\"marketplace_agent\"),\n managedTransactions: z.array(z.string().uuid()).default([]),\n registeredBuyers: z.array(z.string().uuid()).default([]),\n registeredSellers: z.array(z.string().uuid()).default([]),\n commissionRate: z.number().min(0).max(0.5),\n disputeQueue: z.array(z.string().uuid()).default([]),\n});\n\n// ============================================================================\n// EN: ACP Message Schemas\n// VI: Schemas tin nhắn ACP\n// ES: Esquemas de mensajes ACP\n// SPEC: AI-05 - ACP message protocol definitions\n// ============================================================================\n\n// EN: ACP message types for agent communication\n// VI: Các loại tin nhắn ACP cho giao tiếp agent\n// ES: Tipos de mensajes ACP para comunicación de agentes\nexport const ACPMessageTypeSchema = z.enum([\n \"PROPOSE\",\n \"ACCEPT\",\n \"REJECT\",\n \"COUNTER_OFFER\",\n \"QUERY\",\n \"INFORM\",\n \"REQUEST\",\n \"CONFIRM\",\n \"CANCEL\",\n \"COMPLETE\",\n]);\n\n// EN: ACP message schema for inter-agent communication\n// VI: Schema tin nhắn ACP cho giao tiếp giữa các agent\n// ES: Esquema de mensaje ACP para comunicación entre agentes\nexport const ACPMessageSchema = z.object({\n messageId: z.string().uuid(),\n conversationId: z.string().uuid(),\n messageType: ACPMessageTypeSchema,\n senderId: z.string().uuid(),\n receiverId: z.string().uuid(),\n timestamp: z.date(),\n payload: z.object({\n action: z.string(),\n data: z.record(z.unknown()),\n constraints: z.record(z.unknown()).optional(),\n }),\n replyTo: z.string().uuid().optional(),\n expiresAt: z.date().optional(),\n});\n\n// EN: Negotiation state schema\n// VI: Schema trạng thái đàm phán\n// ES: Esquema de estado de negociación\nexport const NegotiationStateSchema = z.object({\n negotiationId: z.string().uuid(),\n buyerAgentId: z.string().uuid(),\n sellerAgentId: z.string().uuid(),\n productId: z.string().uuid(),\n currentOffer: z.number().positive(),\n offerHistory: z.array(\n z.object({\n offeredBy: z.string().uuid(),\n amount: z.number().positive(),\n timestamp: z.date(),\n })\n ),\n status: z.enum([\"pending\", \"active\", \"accepted\", \"rejected\", \"expired\"]),\n roundCount: z.number().int().nonnegative(),\n maxRounds: z.number().int().positive(),\n startedAt: z.date(),\n deadline: z.date().optional(),\n});\n\n// ============================================================================\n// EN: Type Exports from Zod Schemas\n// VI: Xuất kiểu từ Zod Schemas\n// ES: Exportación de tipos desde esquemas Zod\n// ============================================================================\n\nexport type BuyerAgent = z.infer<typeof BuyerAgentSchema>;\nexport type SellerAgent = z.infer<typeof SellerAgentSchema>;\nexport type MarketplaceAgent = z.infer<typeof MarketplaceAgentSchema>;\nexport type ACPMessage = z.infer<typeof ACPMessageSchema>;\nexport type ACPMessageType = z.infer<typeof ACPMessageTypeSchema>;\nexport type NegotiationState = z.infer<typeof NegotiationStateSchema>;\n\n// ============================================================================\n// EN: Agent Choreography Class\n// VI: Lớp Điều phối Agent\n// ES: Clase de Coreografía de Agentes\n// SPEC: AI-05 - Core choreography implementation\n// ============================================================================\n\nexport class AgentChoreography {\n private buyers: Map<string, BuyerAgent> = new Map();\n private sellers: Map<string, SellerAgent> = new Map();\n private marketplace: MarketplaceAgent | null = null;\n private negotiations: Map<string, NegotiationState> = new Map();\n private messageQueue: ACPMessage[] = [];\n\n // EN: Register a buyer agent in the choreography\n // VI: Đăng ký một agent người mua trong điều phối\n // ES: Registrar un agente comprador en la coreografía\n registerBuyerAgent(agentData: unknown): {\n success: boolean;\n data?: BuyerAgent;\n error?: z.ZodError;\n } {\n const result = BuyerAgentSchema.safeParse(agentData);\n if (!result.success) {\n return { success: false, error: result.error };\n }\n this.buyers.set(result.data.agentId, result.data);\n if (this.marketplace) {\n this.marketplace.registeredBuyers.push(result.data.agentId);\n }\n return { success: true, data: result.data };\n }\n\n // EN: Register a seller agent in the choreography\n // VI: Đăng ký một agent người bán trong điều phối\n // ES: Registrar un agente vendedor en la coreografía\n registerSellerAgent(agentData: unknown): {\n success: boolean;\n data?: SellerAgent;\n error?: z.ZodError;\n } {\n const result = SellerAgentSchema.safeParse(agentData);\n if (!result.success) {\n return { success: false, error: result.error };\n }\n this.sellers.set(result.data.agentId, result.data);\n if (this.marketplace) {\n this.marketplace.registeredSellers.push(result.data.agentId);\n }\n return { success: true, data: result.data };\n }\n\n // EN: Initialize the marketplace agent\n // VI: Khởi tạo agent marketplace\n // ES: Inicializar el agente del marketplace\n initializeMarketplace(marketplaceData: unknown): {\n success: boolean;\n data?: MarketplaceAgent;\n error?: z.ZodError;\n } {\n const result = MarketplaceAgentSchema.safeParse(marketplaceData);\n if (!result.success) {\n return { success: false, error: result.error };\n }\n this.marketplace = result.data;\n return { success: true, data: result.data };\n }\n\n // EN: Create and validate an ACP message\n // VI: Tạo và xác thực tin nhắn ACP\n // ES: Crear y validar un mensaje ACP\n createMessage(messageData: unknown): {\n success: boolean;\n data?: ACPMessage;\n error?: z.ZodError;\n } {\n const result = ACPMessageSchema.safeParse(messageData);\n if (!result.success) {\n return { success: false, error: result.error };\n }\n this.messageQueue.push(result.data);\n return { success: true, data: result.data };\n }\n\n // EN: Initiate negotiation between buyer and seller\n // VI: Bắt đầu đàm phán giữa người mua và người bán\n // ES: Iniciar negociación entre comprador y vendedor\n initiateNegotiation(\n buyerId: string,\n sellerId: string,\n productId: string,\n initialOffer: number\n ): { success: boolean; data?: NegotiationState; error?: string } {\n const buyer = this.buyers.get(buyerId);\n const seller = this.sellers.get(sellerId);\n\n if (!buyer) {\n return { success: false, error: \"Buyer agent not found\" };\n }\n if (!seller) {\n return { success: false, error: \"Seller agent not found\" };\n }\n\n const product = seller.inventory.find((p) => p.productId === productId);\n if (!product) {\n return { success: false, error: \"Product not found in seller inventory\" };\n }\n\n const negotiationData = {\n negotiationId: crypto.randomUUID(),\n buyerAgentId: buyerId,\n sellerAgentId: sellerId,\n productId: productId,\n currentOffer: initialOffer,\n offerHistory: [\n {\n offeredBy: buyerId,\n amount: initialOffer,\n timestamp: new Date(),\n },\n ],\n status: \"active\" as const,\n roundCount: 1,\n maxRounds: 10,\n startedAt: new Date(),\n deadline: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours\n };\n\n const result = NegotiationStateSchema.safeParse(negotiationData);\n if (!result.success) {\n return { success: false, error: \"Invalid negotiation state\" };\n }\n\n this.negotiations.set(result.data.negotiationId, result.data);\n\n // EN: Send PROPOSE message to seller\n // VI: Gửi tin nhắn PROPOSE đến người bán\n // ES: Enviar mensaje PROPOSE al vendedor\n this.createMessage({\n messageId: crypto.randomUUID(),\n conversationId: result.data.negotiationId,\n messageType: \"PROPOSE\",\n senderId: buyerId,\n receiverId: sellerId,\n timestamp: new Date(),\n payload: {\n action: \"negotiate_price\",\n data: {\n productId,\n offeredPrice: initialOffer,\n negotiationId: result.data.negotiationId,\n },\n },\n });\n\n return { success: true, data: result.data };\n }\n\n // EN: Process counter offer from seller\n // VI: Xử lý đề xuất ngược từ người bán\n // ES: Procesar contraoferta del vendedor\n processCounterOffer(\n negotiationId: string,\n counterAmount: number\n ): { success: boolean; data?: NegotiationState; error?: string } {\n const negotiation = this.negotiations.get(negotiationId);\n if (!negotiation) {\n return { success: false, error: \"Negotiation not found\" };\n }\n\n if (negotiation.status !== \"active\") {\n return { success: false, error: \"Negotiation is not active\" };\n }\n\n if (negotiation.roundCount >= negotiation.maxRounds) {\n negotiation.status = \"expired\";\n return { success: false, error: \"Maximum negotiation rounds reached\" };\n }\n\n const seller = this.sellers.get(negotiation.sellerAgentId);\n if (!seller) {\n return { success: false, error: \"Seller agent not found\" };\n }\n\n const product = seller.inventory.find(\n (p) => p.productId === negotiation.productId\n );\n if (!product) {\n return { success: false, error: \"Product no longer available\" };\n }\n\n // EN: Check if counter offer meets minimum acceptable price\n // VI: Kiểm tra xem đề xuất ngược có đáp ứng giá tối thiểu chấp nhận được không\n // ES: Verificar si la contraoferta cumple con el precio mínimo aceptable\n if (counterAmount < product.minAcceptablePrice) {\n return {\n success: false,\n error: \"Counter offer below minimum acceptable price\",\n };\n }\n\n negotiation.currentOffer = counterAmount;\n negotiation.offerHistory.push({\n offeredBy: negotiation.sellerAgentId,\n amount: counterAmount,\n timestamp: new Date(),\n });\n negotiation.roundCount++;\n\n // EN: Send COUNTER_OFFER message to buyer\n // VI: Gửi tin nhắn COUNTER_OFFER đến người mua\n // ES: Enviar mensaje COUNTER_OFFER al comprador\n this.createMessage({\n messageId: crypto.randomUUID(),\n conversationId: negotiationId,\n messageType: \"COUNTER_OFFER\",\n senderId: negotiation.sellerAgentId,\n receiverId: negotiation.buyerAgentId,\n timestamp: new Date(),\n payload: {\n action: \"counter_negotiate\",\n data: {\n productId: negotiation.productId,\n counterPrice: counterAmount,",
"spec_id": "AI-05"
}Audit Trail (2)
25d agotask_completedOpus 4.5
25d agotask_createdfoundry_collab
Task ID: 736f88d7-97c8-4536-8766-dc88f453edfc