FOUNDRY
C8 Platform
← Tasks

[AI-05] ACP choreography (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
100%
Pass
PASS
Graded By
-
Graded At
-

Cost

Input Tokens
168
Output Tokens
2,072
Est. USD
$0.0209

Result

{
  "code": "```typescript\nimport { z } from 'zod';\nimport { NextResponse } from 'next/server';\n\n// EN: SPEC-AI-05: ACP (Agent Communication Protocol) Definitions\n// VI: SPEC-AI-05: Định nghĩa ACP (Giao thức Giao tiếp Tác nhân)\n// ES: SPEC-AI-05: Definiciones de ACP (Protocolo de Comunicación de Agentes)\n\n// -----------------------------------------------------------------------------\n// Zod Schemas\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 agentes\nexport const AgentRoleSchema = z.enum(['buyer', 'seller', 'marketplace']);\n\n// EN: ACP Message Types for Choreography\n// VI: Các loại tin nhắn ACP cho Vũ đạo (Choreography)\n// ES: Tipos de mensajes ACP para Coreografía\nexport const ACPMessageTypeSchema = z.enum([\n  'CONNECT',    // Handshake\n  'PROPOSE',    // Offer\n  'COUNTER',    // Counter-offer\n  'ACCEPT',     // Deal agreement\n  'REJECT',     // Deal refusal\n  'DISCONNECT'  // End session\n]);\n\n// EN: Negotiation Payload Schema\n// VI: Lược đồ dữ liệu đàm phán\n// ES: Esquema de carga útil de negociación\nexport const NegotiationPayloadSchema = z.object({\n  itemId: z.string(),\n  price: z.number().positive(),\n  currency: z.string().default('USD'),\n  quantity: z.number().int().positive().default(1),\n  terms: z.string().optional()\n});\n\n// EN: Base Agent Schema\n// VI: Lược đồ tác nhân cơ sở\n// ES: Esquema base de agente\nexport const BaseAgentSchema = z.object({\n  id: z.string().uuid(),\n  name: z.string(),\n  role: AgentRoleSchema,\n  reputationScore: z.number().min(0).max(100).default(50),\n  activeSessionId: z.string().optional()\n});\n\n// EN: Buyer Agent Schema\n// VI: Lược đồ tác nhân người mua\n// ES: Esquema de agente comprador\nexport const BuyerAgentSchema = BaseAgentSchema.extend({\n  role: z.literal('buyer'),\n  maxBudget: z.number().optional()\n});\n\n// EN: Seller Agent Schema\n// VI: Lược đồ tác nhân người bán\n// ES: Esquema de agente vendedor\nexport const SellerAgentSchema = BaseAgentSchema.extend({\n  role: z.literal('seller'),\n  minPrice: z.number().optional()\n});\n\n// EN: ACP Message Schema\n// VI: Lược đồ tin nhắn ACP\n// ES: Esquema de mensaje ACP\nexport const ACPMessageSchema = z.object({\n  id: z.string().uuid(),\n  timestamp: z.string().datetime(),\n  type: ACPMessageTypeSchema,\n  senderId: z.string(),\n  receiverId: z.string(),\n  payload: NegotiationPayloadSchema.optional(),\n  signature: z.string().optional() // For verification\n});\n\n// -----------------------------------------------------------------------------\n// Types\n// -----------------------------------------------------------------------------\n\nexport type AgentRole = z.infer<typeof AgentRoleSchema>;\nexport type ACPMessageType = z.infer<typeof ACPMessageTypeSchema>;\nexport type NegotiationPayload = z.infer<typeof NegotiationPayloadSchema>;\nexport type BuyerAgentType = z.infer<typeof BuyerAgentSchema>;\nexport type SellerAgentType = z.infer<typeof SellerAgentSchema>;\nexport type ACPMessage = z.infer<typeof ACPMessageSchema>;\n\n// -----------------------------------------------------------------------------\n// Agent Factories & Constants\n// -----------------------------------------------------------------------------\n\n// EN: Buyer Agent Factory\n// VI: Nhà máy tạo tác nhân người mua\n// ES: Fábrica de agentes compradores\nexport const buyer_agent = {\n  create: (data: unknown) => {\n    const result = BuyerAgentSchema.safeParse(data);\n    if (!result.success) {\n      throw new Error(`Invalid Buyer Agent: ${result.error.message}`);\n    }\n    return result.data;\n  }\n};\n\n// EN: Seller Agent Factory\n// VI: Nhà máy tạo tác nhân người bán\n// ES: Fábrica de agentes vendedores\nexport const seller_agent = {\n  create: (data: unknown) => {\n    const result = SellerAgentSchema.safeParse(data);\n    if (!result.success) {\n      throw new Error(`Invalid Seller Agent: ${result.error.message}`);\n    }\n    return result.data;\n  }\n};\n\n// -----------------------------------------------------------------------------\n// ACP Choreography Logic\n// -----------------------------------------------------------------------------\n\n// EN: Allowable state transitions for Agent Choreography\n// VI: Các chuyển đổi trạng thái cho phép đối với Vũ đạo Tác nhân\n// ES: Transiciones de estado permitidas para la Coreografía de Agentes\nconst VALID_TRANSITIONS: Record<ACPMessageType, ACPMessageType[]> = {\n  'CONNECT': ['PROPOSE', 'DISCONNECT'],\n  'PROPOSE': ['ACCEPT', 'REJECT', 'COUNTER', 'DISCONNECT'],\n  'COUNTER': ['ACCEPT', 'REJECT', 'COUNTER', 'DISCONNECT'],\n  'ACCEPT': ['DISCONNECT'], // Deal done\n  'REJECT': ['PROPOSE', 'DISCONNECT'], // Try again or leave\n  'DISCONNECT': [] // Terminal state\n};\n\n/**\n * EN: Agent Choreography Manager\n * VI: Quản lý Vũ đạo Tác nhân\n * ES: Gestor de Coreografía de Agentes\n * \n * SPEC-AI-05.2: State machine validation for agent negotiation.\n */\nexport class AgentChoreography {\n  \n  /**\n   * EN: Validates if the next message type is allowed based on the previous message type.\n   * VI: Xác thực xem loại tin nhắn tiếp theo có được phép dựa trên loại tin nhắn trước đó không.\n   * ES: Valida si el siguiente tipo de mensaje está permitido según el tipo de mensaje anterior.\n   */\n  static isValidTransition(lastType: ACPMessageType | null, nextType: ACPMessageType): boolean {\n    // EN: Initial state\n    // VI: Trạng thái ban đầu\n    // ES: Estado inicial\n    if (lastType === null) {\n      return nextType === 'CONNECT';\n    }\n\n    const allowed = VALID_TRANSITIONS[lastType];\n    return allowed ? allowed.includes(nextType) : false;\n  }\n\n  /**\n   * EN: Processes an ACP message and returns a standardized NextResponse.\n   * VI: Xử lý tin nhắn ACP và trả về NextResponse được chuẩn hóa.\n   * ES: Procesa un mensaje ACP y devuelve una NextResponse estandarizada.\n   */\n  static async processMessage(\n    rawMessage: unknown, \n    lastMessageType: ACPMessageType | null\n  ): Promise<NextResponse> {\n    \n    // EN: Step 1: Schema Validation\n    // VI: Bước 1: Xác thực lược đồ\n    // ES: Paso 1: Validación de esquema\n    const parseResult = ACPMessageSchema.safeParse(rawMessage);\n\n    if (!parseResult.success) {\n      return NextResponse.json(\n        { \n          success: false, \n          error: 'Invalid ACP Message Format', \n          details: parseResult.error.format() \n        },\n        { status: 400 }\n      );\n    }\n\n    const message = parseResult.data;\n\n    // EN: Step 2: Choreography Validation\n    // VI: Bước 2: Xác thực vũ đạo\n    // ES: Paso 2: Validación de coreografía\n    if (!this.isValidTransition(lastMessageType, message.type)) {\n      return NextResponse.json(\n        {\n          success: false,\n          error: 'Choreography Violation',\n          message: `Cannot transition from ${lastMessageType || 'START'} to ${message.type}`\n        },\n        { status: 409 } // Conflict\n      );\n    }\n\n    // EN: Step 3: Logic Execution (Simulation)\n    // VI: Bước 3: Thực thi logic (Mô phỏng)\n    // ES: Paso 3: Ejecución lógica (Simulación)\n    \n    // EN: In a real implementation, this would trigger LLM processing or DB updates.\n    // VI: Trong thực tế, điều này sẽ kích hoạt xử lý LLM hoặc cập nhật DB.\n    // ES: En una implementación real, esto activaría el procesamiento LLM o actualizaciones de BD.\n\n    return NextResponse.json({\n      success: true,\n      data: {\n        processedId: message.id,\n        status: 'accepted',\n        nextAllowedStates: VALID_TRANSITIONS[message.type]\n      }\n    });\n  }\n}\n\n// EN: Main ACP Module Export\n// VI: Xuất khẩu Mô-đun ACP Chính\n// ES: Exportación principal del módulo ACP\nexport const acp = {\n  AgentChoreography,\n  buyer_agent,\n  seller_agent,\n  schemas: {\n    AgentRoleSchema,\n    ACPMessageSchema,\n    NegotiationPayloadSchema\n  }\n};\n```",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedGemini 3 Pro
25d agotask_createdfoundry_race
Task ID: 51fef0a0-e199-499d-a760-7553b4bad5c5