← Tasks
[AI-05] ACP agent-to-agent choreography (retry 1)
completedcode_genP2
Description
## AI-05: ACP agent-to-agent choreography
Section: AI Features | Milestone: M4 | Owner: Cowork Lu
### Failing Tests
- **acp_agents** (grep): Pattern `agent.*choreography|acp|buyer.*agent|seller.*agent` in `src/**/*.ts*` (need 1+ matches)
### Acceptance Criteria
- File matching `src/**/*.ts*` must contain pattern `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()
- (supabase as any) with eslint-disable
- NextResponse.json() responses
- Error format: { error: 'message' }
### Reference Files (passing siblings in this section)
- AI-01: Photo categorization (Gemini Vision)
- AI-02: Vietnamese voice listing (Web Speech API)
- AI-03: Vietnamese voice search (vi-VN)
- AI-04: MCP tool exposure (6 marketplace tools)
### Dependencies
- AI-04: PASS
Assignee
-
Claimed By
Cloud Lu → G3 Flash
Created
1d ago
Completed
1d ago
Quality
Overall
96%
Pass
PASS
Graded By
-
Graded At
-
Cost
Input Tokens
-
Output Tokens
-
Est. USD
-
Result
{
"cost": {
"input_tokens": 283,
"estimated_usd": 0.003925,
"output_tokens": 1261
},
"model": "gemini-3-flash-preview",
"status": "success",
"transport": "gemini_api",
"latency_ms": 11706,
"response_text": "To fulfill the requirements for **AI-05: ACP agent-to-agent choreography**, I will create a new API route that implements the logic for communication between a buyer agent and a seller agent using the Agent Communication Protocol (ACP).\n\nThis implementation includes Zod validation, trilingual comments, Supabase integration (with the required casting), and the specific patterns required by the test suite.\n\n```typescript\n// src/app/api/ai/choreography/route.ts\n\nimport { NextRequest, NextResponse } from 'next/server';\nimport { z } from 'zod';\nimport { createClient } from '@supabase/supabase-js';\n\n// SPEC: AI-05 Agent-to-Agent Choreography\n// EN: Schema for ACP (Agent Communication Protocol) message validation.\n// VI: Sơ đồ xác thực thông điệp ACP (Giao thức truyền thông tác nhân).\n// ES: Esquema para la validación de mensajes ACP (Protocolo de comunicación de agentes).\nconst acpChoreographySchema = z.object({\n sender: z.enum(['buyer_agent', 'seller_agent']),\n receiver: z.enum(['buyer_agent', 'seller_agent']),\n action: z.string(),\n payload: z.record(z.any()),\n conversationId: z.string().uuid(),\n});\n\n/**\n * EN: Handles the agent-to-agent choreography for the marketplace.\n * VI: Xử lý điều phối giữa các tác nhân (agent-to-agent choreography) cho thị trường.\n * ES: Maneja la coreografía de agente a agente para el mercado.\n */\nexport async function POST(req: NextRequest) {\n try {\n const body = await req.json();\n \n // EN: Validate the ACP request structure.\n // VI: Xác thực cấu trúc yêu cầu ACP.\n // ES: Validar la estructura de la solicitud ACP.\n const result = acpChoreographySchema.safeParse(body);\n\n if (!result.success) {\n return NextResponse.json(\n { error: 'Invalid ACP message format' },\n { status: 400 }\n );\n }\n\n const { sender, receiver, action, payload, conversationId } = result.data;\n\n // EN: Initialize Supabase client with required bypass for choreography logging.\n // VI: Khởi tạo client Supabase với ép kiểu cần thiết để ghi nhật ký điều phối.\n // ES: Inicializar el cliente Supabase con la omisión necesaria para el registro de coreografía.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n const supabase = createClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!\n ) as any;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // EN: Log the agent interaction to the database for audit trailing.\n // VI: Ghi lại tương tác của tác nhân vào cơ sở dữ liệu để theo dõi kiểm tra.\n // ES: Registrar la interacción del agente en la base de datos para el seguimiento de auditoría.\n const { error: dbError } = await supabase\n .from('agent_logs')\n .insert([\n {\n conversation_id: conversationId,\n sender_type: sender,\n receiver_type: receiver,\n action_performed: action,\n metadata: payload,\n protocol: 'acp',\n },\n ]);\n\n if (dbError) {\n console.error('Choreography log error:', dbError);\n return NextResponse.json({ error: 'Failed to log agent interaction' }, { status: 500 });\n }\n\n // EN: Simulate logic for buyer agent negotiating with seller agent.\n // VI: Mô phỏng logic cho tác nhân người mua thương lượng với tác nhân người bán.\n // ES: Simular la lógica para el agente comprador negociando con el agente vendedor.\n let responseMessage = '';\n if (sender === 'buyer_agent' && receiver === 'seller_agent') {\n responseMessage = `ACP: Seller agent received ${action} from buyer agent.`;\n } else {\n responseMessage = `ACP: Buyer agent received ${action} from seller agent.`;\n }\n\n return NextResponse.json({\n success: true,\n message: responseMessage,\n choreographyStatus: 'active',\n });\n } catch (error) {\n // EN: Standard error format as per codebase conventions.\n // VI: Định dạng lỗi tiêu chuẩn theo quy ước mã nguồn.\n // ES: Formato de error estándar según las convenciones de la base de código.\n return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });\n }\n}\n```\n\n### Key Features Implemented:\n1. **Pattern Matching**: Includes `acp`, `agent.*choreography`, `buyer.*agent`, and `seller.*agent` to satisfy the grep test.\n2. **ACP Schema**: Uses `zod` at the module level with `.safeParse()` for validating the Agent Communication Protocol messages.\n3. **Supabase Integration**: Uses the required `(supabase as any)` casting with `eslint-disable` comments.\n4. **Trilingual Comments**: Every major block includes EN, VI, and ES descriptions.\n5. **SPEC Reference**: Includes `// SPEC: AI-05 Agent-to-Agent Choreography`.\n6. **Response Format**: Uses `NextResponse.json()` and the mandatory `{ error: 'message' }` format for failures."
}Task ID: c0f2af9b-fefb-4056-a4f9-542c2b413b3b