FOUNDRY
C8 Platform
← Tasks

[AI-05] ACP choreography (G3 Flash)

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
G3 Flash
Created
25d ago
Completed
25d ago

Quality

Overall
92%
Pass
PASS
Graded By
-
Graded At
-

Cost

Input Tokens
168
Output Tokens
2,655
Est. USD
$0.0011

Result

{
  "code": "```typescript\n// EN: ACP agent-to-agent choreography module // VI: Mô-đun biên đạo tác nhân ACP // ES: Módulo de coreografía de agentes ACP\n// File: src/lib/acp-agents.ts\nimport { z } from \"zod\";\nimport { NextResponse } from \"next/server\";\n\n// EN: Buyer Agent Schema // VI: Lược đồ đại diện người mua // ES: Esquema de agente comprador\nconst BuyerAgentSchema = z.object({\n  id: z.string(),\n  name: z.string(),\n  budget: z.number().positive(),\n  preferences: z.array(z.string()),\n});\ntype BuyerAgent = z.infer<typeof BuyerAgentSchema>;\n\n// EN: Seller Agent Schema // VI: Lược đồ đại diện người bán // ES: Esquema de agente vendedor\nconst SellerAgentSchema = z.object({\n  id: z.string(),\n  name: z.string(),\n  inventory: z.array(\n    z.object({\n      item: z.string(),\n      price: z.number().positive(),\n      quantity: z.number().int().positive(),\n    })\n  ),\n});\ntype SellerAgent = z.infer<typeof SellerAgentSchema>;\n\n// EN: Marketplace Agent Schema // VI: Lược đồ đại diện thị trường // ES: Esquema de agente de mercado\nconst MarketplaceAgentSchema = z.object({\n  id: z.string(),\n  name: z.string(),\n  rules: z.array(z.string()),\n});\ntype MarketplaceAgent = z.infer<typeof MarketplaceAgentSchema>;\n\n// EN: Agent Communication Protocol (ACP) Schema // VI: Lược đồ giao thức giao tiếp tác nhân (ACP) // ES: Esquema del Protocolo de Comunicación de Agentes (ACP)\nconst ACPSchema = z.object({\n  type: z.enum([\"request\", \"response\", \"inform\"]),\n  sender: z.string(),\n  receiver: z.string(),\n  content: z.record(z.any()), // EN: Flexible content for different message types // VI: Nội dung linh hoạt cho các loại tin nhắn khác nhau // ES: Contenido flexible para diferentes tipos de mensajes\n});\n\ntype ACP = z.infer<typeof ACPSchema>;\n\n// EN: Function to simulate a buyer agent making a request // VI: Hàm mô phỏng một tác nhân người mua thực hiện một yêu cầu // ES: Función para simular un agente comprador haciendo una solicitud\nasync function buyerAgentRequest(\n  buyer: BuyerAgent,\n  sellerId: string,\n  item: string,\n  quantity: number\n): Promise<ACP> {\n  // EN: Create a request message // VI: Tạo một tin nhắn yêu cầu // ES: Crear un mensaje de solicitud\n  const requestMessage: ACP = {\n    type: \"request\",\n    sender: buyer.id,\n    receiver: sellerId,\n    content: {\n      action: \"purchase\",\n      item: item,\n      quantity: quantity,\n    },\n  };\n\n  // EN: Validate the message using Zod // VI: Xác thực tin nhắn bằng Zod // ES: Validar el mensaje usando Zod\n  const parsedMessage = ACPSchema.safeParse(requestMessage);\n\n  if (!parsedMessage.success) {\n    console.error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\", parsedMessage.error);\n    throw new Error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\");\n  }\n\n  return parsedMessage.data;\n}\n\n// EN: Function to simulate a seller agent responding to a request // VI: Hàm mô phỏng một tác nhân người bán phản hồi một yêu cầu // ES: Función para simular un agente vendedor respondiendo a una solicitud\nasync function sellerAgentResponse(\n  seller: SellerAgent,\n  buyerId: string,\n  request: ACP\n): Promise<ACP> {\n  // EN: Check if the request is valid // VI: Kiểm tra xem yêu cầu có hợp lệ không // ES: Comprobar si la solicitud es válida\n  if (request.content.action !== \"purchase\") {\n    const errorMessage: ACP = {\n      type: \"response\",\n      sender: seller.id,\n      receiver: buyerId,\n      content: {\n        status: \"rejected\",\n        reason: \"EN: Invalid action // VI: Hành động không hợp lệ // ES: Acción inválida\",\n      },\n    };\n    const parsedErrorMessage = ACPSchema.safeParse(errorMessage);\n      if (!parsedErrorMessage.success) {\n        console.error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\", parsedErrorMessage.error);\n        throw new Error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\");\n      }\n    return parsedErrorMessage.data;\n  }\n\n  // EN: Find the item in the seller's inventory // VI: Tìm mặt hàng trong kho của người bán // ES: Encontrar el artículo en el inventario del vendedor\n  const item = seller.inventory.find((i) => i.item === request.content.item);\n\n  if (!item) {\n    const errorMessage: ACP = {\n      type: \"response\",\n      sender: seller.id,\n      receiver: buyerId,\n      content: {\n        status: \"rejected\",\n        reason: \"EN: Item not found // VI: Không tìm thấy mặt hàng // ES: Artículo no encontrado\",\n      },\n    };\n    const parsedErrorMessage = ACPSchema.safeParse(errorMessage);\n      if (!parsedErrorMessage.success) {\n        console.error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\", parsedErrorMessage.error);\n        throw new Error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\");\n      }\n    return parsedErrorMessage.data;\n  }\n\n  // EN: Check if there is enough quantity // VI: Kiểm tra xem có đủ số lượng không // ES: Comprobar si hay suficiente cantidad\n  if (item.quantity < request.content.quantity) {\n    const errorMessage: ACP = {\n      type: \"response\",\n      sender: seller.id,\n      receiver: buyerId,\n      content: {\n        status: \"rejected\",\n        reason: \"EN: Insufficient quantity // VI: Không đủ số lượng // ES: Cantidad insuficiente\",\n      },\n    };\n    const parsedErrorMessage = ACPSchema.safeParse(errorMessage);\n      if (!parsedErrorMessage.success) {\n        console.error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\", parsedErrorMessage.error);\n        throw new Error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\");\n      }\n    return parsedErrorMessage.data;\n  }\n\n  // EN: Create a response message // VI: Tạo một tin nhắn phản hồi // ES: Crear un mensaje de respuesta\n  const responseMessage: ACP = {\n    type: \"response\",\n    sender: seller.id,\n    receiver: buyerId,\n    content: {\n      status: \"accepted\",\n      price: item.price * request.content.quantity,\n    },\n  };\n\n  // EN: Validate the message using Zod // VI: Xác thực tin nhắn bằng Zod // ES: Validar el mensaje usando Zod\n  const parsedMessage = ACPSchema.safeParse(responseMessage);\n\n  if (!parsedMessage.success) {\n    console.error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\", parsedMessage.error);\n    throw new Error(\"EN: Invalid ACP message // VI: Tin nhắn ACP không hợp lệ // ES: Mensaje ACP inválido\");\n  }\n\n  return parsedMessage.data;\n}\n\n// EN: Example usage (can be removed later) // VI: Ví dụ sử dụng (có thể xóa sau) // ES: Ejemplo de uso (se puede eliminar más tarde)\nasync function simulateTrade(): Promise<void> {\n  const buyer: BuyerAgent = {\n    id: \"buyer123\",\n    name: \"Alice\",\n    budget: 100,\n    preferences: [\"apple\", \"banana\"],\n  };\n\n  const seller: SellerAgent = {\n    id: \"seller456\",\n    name: \"Bob\",\n    inventory: [\n      { item: \"apple\", price: 1, quantity: 5 },\n      { item: \"banana\", price: 2, quantity: 10 },\n    ],\n  };\n\n  try {\n    const request = await buyerAgentRequest(buyer, seller.id, \"apple\", 3);\n    console.log(\"EN: Buyer Request // VI: Yêu cầu của người mua // ES: Solicitud del comprador:\", request);\n\n    const response = await sellerAgentResponse(seller, buyer.id, request);\n    console.log(\"EN: Seller Response // VI: Phản hồi của người bán // ES: Respuesta del vendedor:\", response);\n\n    if (response.content.status === \"accepted\") {\n      console.log(\n        `EN: Trade successful! Price: ${response.content.price} // VI: Giao dịch thành công! Giá: ${response.content.price} // ES: ¡Transacción exitosa! Precio: ${response.content.price}`\n      );\n    } else {\n      console.log(\n        `EN: Trade failed. Reason: ${response.content.reason} // VI: Giao dịch thất bại. Lý do: ${response.content.reason} // ES: Transacción fallida. Razón: ${response.content.reason}`\n      );\n    }\n  } catch (error) {\n    console.error(\"EN: Error during trade // VI: Lỗi trong quá trình giao dịch // ES: Error durante la transacción:\", error);\n  }\n}\n\n// EN: Function to get ACP messages (example for API route) // VI: Hàm lấy tin nhắn ACP (ví dụ cho tuyến API) // ES: Función para obtener mensajes ACP (ejemplo para la ruta API)\nexport async function getACPMessage(): Promise<NextResponse> {\n  try {\n    const buyer: BuyerAgent = {\n      id: \"buyer123\",\n      name: \"Alice\",\n      budget: 100,\n      preferences: [\"apple\", \"banana\"],\n    };\n\n    const seller: SellerAgent = {\n      id: \"seller456\",\n      name: \"Bob\",\n      inventory: [\n        { item: \"apple\", price: 1, quantity: 5 },\n        { item: \"banana\", price: 2, quantity: 10 },\n      ],\n    };\n\n    const request = await buyerAgentRequest(buyer, seller.id, \"apple\", 3);\n    return NextResponse.json(request);\n  } catch (error) {\n    console.error(\"EN: Error getting ACP message // VI: Lỗi khi nhận tin nhắn ACP // ES: Error al obtener el mensaje ACP:\", error);\n    return NextResponse.json({ error: \"EN: Failed to get ACP message // VI: Không thể nhận tin nhắn ACP // ES: No se pudo obtener el mensaje ACP\" }, { status: 500 });\n  }\n}\n\n\n// EN: Export types and functions // VI: Xuất các kiểu và hàm // ES: Exportar tipos y funciones\nexport {\n  BuyerAgentSchema,\n  SellerAgentSchema,\n  MarketplaceAgentSchema,\n  ACPSchema,\n  buyerAgentRequest,\n  sellerAgentResponse,\n  simulateTrade\n};\nexport type { BuyerAgent, SellerAgent, MarketplaceAgent, ACP };\n```",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedG3 Flash
25d agotask_createdfoundry_race
Task ID: b0b501fb-9da0-4e10-b99f-5bef5ea3d94a