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
71%
Pass
PASS
Graded By
-
Graded At
-

Cost

Input Tokens
168
Output Tokens
1,735
Est. USD
$0.0007

Result

{
  "code": "```typescript\n// src/lib/acp-agents.ts\n\n// EN: This module implements ACP agent-to-agent choreography for a marketplace. // VI: Mô-đun này triển khai sự biên đạo tác nhân-tới-tác nhân ACP cho một thị trường. // ES: Este módulo implementa la coreografía agente a agente de ACP para un mercado.\n\nimport { z } from \"zod\";\nimport { NextResponse } from \"next/server\";\n\n// SPEC: Define Zod schemas for agent message types.\n// EN: Define Zod schemas for agent message types. // VI: Xác định lược đồ Zod cho các loại tin nhắn tác nhân. // ES: Definir esquemas Zod para los tipos de mensajes de agente.\n\n// Buyer Agent Schema\nconst BuyerAgentSchema = z.object({\n  agentType: z.literal(\"buyer\"),\n  agentId: z.string(),\n  desiredProduct: z.string(),\n  maxPrice: z.number(),\n});\ntype BuyerAgent = z.infer<typeof BuyerAgentSchema>;\n\n// Seller Agent Schema\nconst SellerAgentSchema = z.object({\n  agentType: z.literal(\"seller\"),\n  agentId: z.string(),\n  productOffered: z.string(),\n  price: z.number(),\n  quantityAvailable: z.number(),\n});\ntype SellerAgent = z.infer<typeof SellerAgentSchema>;\n\n// Marketplace Agent Schema\nconst MarketplaceAgentSchema = z.object({\n  agentType: z.literal(\"marketplace\"),\n  agentId: z.string(),\n});\ntype MarketplaceAgent = z.infer<typeof MarketplaceAgentSchema>;\n\n// ACP Message Schema (Example)\nconst ACPMessageSchema = z.object({\n  sender: z.string(),\n  receiver: z.string(),\n  type: z.string(),\n  payload: z.record(z.any()),\n});\ntype ACPMessage = z.infer<typeof ACPMessageSchema>;\n\n// SPEC: Implement agent choreography logic.\n// EN: Implement agent choreography logic. // VI: Triển khai logic biên đạo tác nhân. // ES: Implementar la lógica de coreografía del agente.\n\n// Example: Buyer Agent initiating a purchase\nasync function buyerAgentInitiatePurchase(\n  buyer: BuyerAgent,\n  marketplace: MarketplaceAgent\n): Promise<NextResponse> {\n  // EN: Buyer sends a purchase request to the marketplace. // VI: Người mua gửi yêu cầu mua hàng đến thị trường. // ES: El comprador envía una solicitud de compra al mercado.\n  const message: ACPMessage = {\n    sender: buyer.agentId,\n    receiver: marketplace.agentId,\n    type: \"purchase_request\",\n    payload: {\n      desiredProduct: buyer.desiredProduct,\n      maxPrice: buyer.maxPrice,\n    },\n  };\n\n  // In a real implementation, this would be sent over a network.\n  console.log(\"Buyer sent message:\", message);\n\n  return NextResponse.json({ status: \"purchase_request_sent\", message });\n}\n\n// Example: Marketplace Agent processing a purchase request\nasync function marketplaceAgentProcessPurchaseRequest(\n  marketplace: MarketplaceAgent,\n  message: ACPMessage,\n  sellers: SellerAgent[]\n): Promise<NextResponse> {\n  // EN: Marketplace receives a purchase request and finds matching sellers. // VI: Thị trường nhận được yêu cầu mua hàng và tìm người bán phù hợp. // ES: El mercado recibe una solicitud de compra y encuentra vendedores coincidentes.\n  if (message.type !== \"purchase_request\") {\n    return NextResponse.json(\n      { error: \"Invalid message type\" },\n      { status: 400 }\n    );\n  }\n\n  const buyerId = message.sender;\n  const desiredProduct = message.payload.desiredProduct;\n  const maxPrice = message.payload.maxPrice;\n\n  const matchingSellers = sellers.filter(\n    (seller) =>\n      seller.productOffered === desiredProduct && seller.price <= maxPrice && seller.quantityAvailable > 0\n  );\n\n  if (matchingSellers.length === 0) {\n    // EN: No sellers found. // VI: Không tìm thấy người bán. // ES: No se encontraron vendedores.\n    return NextResponse.json({ status: \"no_sellers_found\" });\n  }\n\n  // EN: Select the best seller (e.g., lowest price). // VI: Chọn người bán tốt nhất (ví dụ: giá thấp nhất). // ES: Seleccionar el mejor vendedor (por ejemplo, el precio más bajo).\n  const bestSeller = matchingSellers.sort((a, b) => a.price - b.price)[0];\n\n  // EN: Send purchase order to the seller. // VI: Gửi đơn đặt hàng cho người bán. // ES: Enviar orden de compra al vendedor.\n  const purchaseOrder: ACPMessage = {\n    sender: marketplace.agentId,\n    receiver: bestSeller.agentId,\n    type: \"purchase_order\",\n    payload: {\n      buyerId: buyerId,\n      productId: bestSeller.productOffered,\n      quantity: 1, // Assuming buyer wants to buy 1 unit.\n      price: bestSeller.price,\n    },\n  };\n\n  console.log(\"Marketplace sent message:\", purchaseOrder);\n\n  return NextResponse.json({ status: \"purchase_order_sent\", purchaseOrder });\n}\n\n// Example: Seller Agent processing a purchase order\nasync function sellerAgentProcessPurchaseOrder(\n  seller: SellerAgent,\n  message: ACPMessage\n): Promise<NextResponse> {\n  // EN: Seller receives a purchase order. // VI: Người bán nhận được đơn đặt hàng. // ES: El vendedor recibe una orden de compra.\n  if (message.type !== \"purchase_order\") {\n    return NextResponse.json(\n      { error: \"Invalid message type\" },\n      { status: 400 }\n    );\n  }\n\n  const buyerId = message.payload.buyerId;\n  const productId = message.payload.productId;\n  const quantity = message.payload.quantity;\n  const price = message.payload.price;\n\n  if (seller.productOffered !== productId || seller.quantityAvailable < quantity) {\n    // EN: Insufficient stock or incorrect product. // VI: Không đủ hàng hoặc sản phẩm không chính xác. // ES: Stock insuficiente o producto incorrecto.\n    return NextResponse.json({ status: \"insufficient_stock\" });\n  }\n\n  // EN: Process the order. // VI: Xử lý đơn hàng. // ES: Procesar la orden.\n  seller.quantityAvailable -= quantity;\n\n  // EN: Send confirmation to the marketplace. // VI: Gửi xác nhận đến thị trường. // ES: Enviar confirmación al mercado.\n  const confirmationMessage: ACPMessage = {\n    sender: seller.agentId,\n    receiver: \"marketplace\", // Replace with actual marketplace agent ID if needed\n    type: \"order_confirmation\",\n    payload: {\n      buyerId: buyerId,\n      productId: productId,\n      quantity: quantity,\n      price: price,\n    },\n  };\n\n  console.log(\"Seller sent message:\", confirmationMessage);\n\n  return NextResponse.json({ status: \"order_confirmed\", confirmationMessage, seller });\n}\n\n// SPEC: Export agent types and choreography functions.\n// EN: Export agent types and choreography functions. // VI: Xuất các loại tác nhân và các hàm biên đạo. // ES: Exportar los tipos de agentes y las funciones de coreografía.\n\nexport {\n  BuyerAgentSchema,\n  SellerAgentSchema,\n  MarketplaceAgentSchema,\n  buyerAgentInitiatePurchase,\n  marketplaceAgentProcessPurchaseRequest,\n  sellerAgentProcessPurchaseOrder,\n};\n\nexport type { BuyerAgent, SellerAgent, MarketplaceAgent, ACPMessage };\n```",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedG3 Flash
25d agotask_createdfoundry_race
Task ID: 462bcff9-b773-478b-8aa2-8494c3dd7493