← Tasks
[AI-05] Solo baseline (Gemini 3 Pro)
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
Gemini 3 Pro
Created
25d ago
Completed
25d ago
Quality
Overall
98%
Pass
PASS
Graded By
-
Graded At
-
Cost
Input Tokens
168
Output Tokens
2,373
Est. USD
$0.0239
Result
{
"code": "```typescript\nimport { z } from 'zod';\nimport { NextResponse } from 'next/server';\n\n// EN: AI-05: ACP Agent-to-Agent Choreography Module\n// VI: AI-05: Mô-đun điều phối tác nhân-tác nhân ACP\n// ES: AI-05: Módulo de coreografía agente a agente ACP\n\n// ----------------------------------------------------------------------\n// EN: Zod Schemas & Types [SPEC: AI-05.1]\n// VI: Lược đồ Zod & Các loại [SPEC: AI-05.1]\n// ES: Esquemas Zod y Tipos [SPEC: AI-05.1]\n// ----------------------------------------------------------------------\n\n// EN: Agent Role Enumeration\n// VI: Liệt kê vai trò tác nhân\n// ES: Enumeración de roles de agente\nexport const AgentRoleEnum = z.enum(['BUYER', 'SELLER', 'MARKETPLACE']);\n\n// EN: Agent Profile Schema\n// VI: Lược đồ hồ sơ tác nhân\n// ES: Esquema del perfil del agente\nexport const AgentProfileSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1),\n role: AgentRoleEnum,\n reputationScore: z.number().min(0).max(100).optional(),\n});\n\n// EN: ACP Message Type Enumeration (Protocol Verbs)\n// VI: Liệt kê loại tin nhắn ACP (Động từ giao thức)\n// ES: Enumeración de tipos de mensajes ACP (Verbos del protocolo)\nexport const ACPMessageTypeEnum = z.enum([\n 'CONNECT', // EN: Handshake / VI: Bắt tay / ES: Apretón de manos\n 'PROPOSE', // EN: Buyer proposes terms / VI: Người mua đề xuất điều khoản / ES: El comprador propone términos\n 'COUNTER', // EN: Seller counters / VI: Người bán phản đối / ES: El vendedor contraoferta\n 'ACCEPT', // EN: Agreement reached / VI: Đạt được thỏa thuận / ES: Acuerdo alcanzado\n 'REJECT', // EN: Proposal declined / VI: Đề xuất bị từ chối / ES: Propuesta rechazada\n 'FINALIZE', // EN: Marketplace confirms / VI: Thị trường xác nhận / ES: El mercado confirma\n]);\n\n// EN: ACP Payload Schema (Transaction details)\n// VI: Lược đồ dữ liệu ACP (Chi tiết giao dịch)\n// ES: Esquema de carga útil ACP (Detalles de la transacción)\nexport const ACPPayloadSchema = z.object({\n itemId: z.string(),\n price: z.number().positive(),\n currency: z.string().default('USD'),\n terms: z.string().optional(),\n timestamp: z.number(),\n});\n\n// EN: ACP Message Envelope Schema\n// VI: Lược đồ phong bì tin nhắn ACP\n// ES: Esquema del sobre de mensaje ACP\nexport const ACPMessageSchema = z.object({\n id: z.string().uuid(),\n type: ACPMessageTypeEnum,\n sender: AgentProfileSchema,\n receiver: AgentProfileSchema,\n payload: ACPPayloadSchema,\n signature: z.string().optional(), // EN: Cryptographic proof / VI: Bằng chứng mật mã / ES: Prueba criptográfica\n});\n\n// EN: Type definitions derived from Zod\n// VI: Các định nghĩa kiểu được dẫn xuất từ Zod\n// ES: Definiciones de tipos derivadas de Zod\nexport type AgentProfile = z.infer<typeof AgentProfileSchema>;\nexport type ACPMessage = z.infer<typeof ACPMessageSchema>;\nexport type ACPPayload = z.infer<typeof ACPPayloadSchema>;\n\n// ----------------------------------------------------------------------\n// EN: Agent Choreography Logic [SPEC: AI-05.2]\n// VI: Logic điều phối tác nhân [SPEC: AI-05.2]\n// ES: Lógica de coreografía de agentes [SPEC: AI-05.2]\n// ----------------------------------------------------------------------\n\n/**\n * EN: Validates and processes an ACP message sequence.\n * VI: Xác thực và xử lý chuỗi tin nhắn ACP.\n * ES: Valida y procesa una secuencia de mensajes ACP.\n */\nexport class ACPChoreography {\n \n // EN: Validate message structure using Zod\n // VI: Xác thực cấu trúc tin nhắn bằng Zod\n // ES: Validar la estructura del mensaje usando Zod\n static validateMessage(data: unknown): { success: boolean; data?: ACPMessage; error?: string } {\n const result = ACPMessageSchema.safeParse(data);\n if (!result.success) {\n return { success: false, error: result.error.message };\n }\n return { success: true, data: result.data };\n }\n\n // EN: Determine next allowable state based on current message\n // VI: Xác định trạng thái cho phép tiếp theo dựa trên tin nhắn hiện tại\n // ES: Determinar el siguiente estado permitido basado en el mensaje actual\n static getNextAllowableActions(currentType: z.infer<typeof ACPMessageTypeEnum>): z.infer<typeof ACPMessageTypeEnum>[] {\n switch (currentType) {\n case 'CONNECT':\n return ['PROPOSE'];\n case 'PROPOSE':\n return ['ACCEPT', 'REJECT', 'COUNTER'];\n case 'COUNTER':\n return ['ACCEPT', 'REJECT', 'PROPOSE']; // EN: Buyer can propose again / VI: Người mua có thể đề xuất lại / ES: El comprador puede proponer de nuevo\n case 'ACCEPT':\n return ['FINALIZE'];\n case 'REJECT':\n case 'FINALIZE':\n return []; // EN: Terminal states / VI: Trạng thái kết thúc / ES: Estados terminales\n default:\n return [];\n }\n }\n\n // EN: Execute the choreography step\n // VI: Thực hiện bước điều phối\n // ES: Ejecutar el paso de coreografía\n static processStep(incomingMessage: unknown): NextResponse {\n // EN: Step 1: Validate Schema\n // VI: Bước 1: Xác thực lược đồ\n // ES: Paso 1: Validar esquema\n const validation = this.validateMessage(incomingMessage);\n \n if (!validation.success || !validation.data) {\n return NextResponse.json(\n { error: 'Invalid ACP Message Format', details: validation.error },\n { status: 400 }\n );\n }\n\n const msg = validation.data;\n\n // EN: Step 2: Role Validation [SPEC: AI-05.3]\n // VI: Bước 2: Xác thực vai trò [SPEC: AI-05.3]\n // ES: Paso 2: Validación de roles [SPEC: AI-05.3]\n if (msg.sender.id === msg.receiver.id) {\n return NextResponse.json(\n { error: 'Sender and Receiver cannot be the same agent' },\n { status: 400 }\n );\n }\n\n // EN: Step 3: Compute Next States\n // VI: Bước 3: Tính toán trạng thái tiếp theo\n // ES: Paso 3: Calcular siguientes estados\n const nextActions = this.getNextAllowableActions(msg.type);\n\n // EN: Return successful choreography acknowledgment\n // VI: Trả về xác nhận điều phối thành công\n // ES: Devolver reconocimiento de coreografía exitosa\n return NextResponse.json({\n status: 'success',\n processed_message: msg.id,\n current_state: msg.type,\n allowable_next_actions: nextActions,\n timestamp: new Date().toISOString()\n });\n }\n}\n\n// ----------------------------------------------------------------------\n// EN: Agent Factory Functions [SPEC: AI-05.4]\n// VI: Các hàm nhà máy tác nhân [SPEC: AI-05.4]\n// ES: Funciones de fábrica de agentes [SPEC: AI-05.4]\n// ----------------------------------------------------------------------\n\n// EN: Create a Buyer Agent instance\n// VI: Tạo một thể hiện Tác nhân Người mua\n// ES: Crear una instancia de Agente Comprador\nexport const createBuyerAgent = (id: string, name: string): AgentProfile => {\n const agent = {\n id,\n name,\n role: 'BUYER' as const,\n reputationScore: 50\n };\n // EN: Validate creation\n // VI: Xác thực việc tạo\n // ES: Validar creación\n AgentProfileSchema.parse(agent);\n return agent;\n};\n\n// EN: Create a Seller Agent instance\n// VI: Tạo một thể hiện Tác nhân Người bán\n// ES: Crear una instancia de Agente Vendedor\nexport const createSellerAgent = (id: string, name: string): AgentProfile => {\n const agent = {\n id,\n name,\n role: 'SELLER' as const,\n reputationScore: 50\n };\n AgentProfileSchema.parse(agent);\n return agent;\n};\n\n// EN: Create a Marketplace Agent (Arbiter)\n// VI: Tạo một Tác nhân Thị trường (Trọng tài)\n// ES: Crear un Agente de Mercado (Árbitro)\nexport const createMarketplaceAgent = (): AgentProfile => {\n return {\n id: '00000000-0000-0000-0000-000000000000', // EN: System UUID / VI: UUID hệ thống / ES: UUID del sistema\n name: 'System Arbiter',\n role: 'MARKETPLACE',\n reputationScore: 100\n };\n};\n\n// ----------------------------------------------------------------------\n// EN: Example Usage (Mock Handler)\n// VI: Ví dụ sử dụng (Trình xử lý giả)\n// ES: Ejemplo de uso (Manejador simulado)\n// ----------------------------------------------------------------------\n\n/*\n // EN: Example of how to use this in a Next.js API route\n // VI: Ví dụ về cách sử dụng điều này trong tuyến API Next.js\n // ES: Ejemplo de cómo usar esto en una ruta API de Next.js\n \n export async function POST(req: Request) {\n const body = await req.json();\n return ACPChoreography.processStep(body);\n }\n*/\n```",
"spec_id": "AI-05"
}Audit Trail (2)
25d agotask_completedGemini 3 Pro
25d agotask_createdfoundry_collab
Task ID: 7e6c0c69-d609-40cc-8170-365b6fdf2cfb