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

Cost

Input Tokens
168
Output Tokens
2,763
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-tác nhân ACP // ES: Módulo de coreografía agente a agente ACP\n// File: src/lib/acp-agents.ts\n// SPEC: AI-05\n\nimport { z } from \"zod\";\nimport { NextResponse } from \"next/server\";\n\n// EN: Buyer Agent Schema // VI: Lược đồ Đại lý 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 lý 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 lý Thị trường // ES: Esquema de Agente del 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 Đại lý (ACP) // ES: Esquema de 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: Allows any content // VI: Cho phép bất kỳ nội dung nào // ES: Permite cualquier contenido\n});\ntype ACP = z.infer<typeof ACPSchema>;\n\n// EN: Function to simulate buyer agent behavior // VI: Hàm mô phỏng hành vi của đại lý người mua // ES: Función para simular el comportamiento del agente comprador\nasync function buyerAgent(\n  buyer: BuyerAgent,\n  marketplace: MarketplaceAgent,\n  sellers: SellerAgent[]\n): Promise<NextResponse> {\n  const buyerResult = BuyerAgentSchema.safeParse(buyer);\n  if (!buyerResult.success) {\n    console.error(\"EN: Buyer agent validation failed // VI: Xác thực đại lý người mua không thành công // ES: Falló la validación del agente comprador\", buyerResult.error);\n    return NextResponse.json({ error: buyerResult.error.message }, { status: 400 });\n  }\n\n  const marketplaceResult = MarketplaceAgentSchema.safeParse(marketplace);\n    if (!marketplaceResult.success) {\n    console.error(\"EN: Marketplace agent validation failed // VI: Xác thực đại lý thị trường không thành công // ES: Falló la validación del agente del mercado\", marketplaceResult.error);\n    return NextResponse.json({ error: marketplaceResult.error.message }, { status: 400 });\n  }\n\n  const offers = sellers.map(seller => {\n    const sellerResult = SellerAgentSchema.safeParse(seller);\n    if (!sellerResult.success) {\n        console.error(\"EN: Seller agent validation failed // VI: Xác thực đại lý người bán không thành công // ES: Falló la validación del agente vendedor\", sellerResult.error);\n        return null;\n    }\n    const relevantItems = seller.inventory.filter((item) =>\n      buyer.preferences.includes(item.item)\n    );\n\n    if (relevantItems.length === 0) {\n      return null;\n    }\n\n    const acpMessage: ACP = {\n      type: \"request\",\n      sender: buyer.id,\n      receiver: seller.id,\n      content: {\n        itemsOfInterest: relevantItems.map(item => item.item),\n        quantityDesired: 1, // EN: Assuming buyer wants 1 of each // VI: Giả sử người mua muốn 1 cái cho mỗi loại // ES: Asumiendo que el comprador quiere 1 de cada uno\n      },\n    };\n    return { sellerId: seller.id, acpMessage };\n  }).filter(offer => offer !== null);\n\n  if (offers.length === 0) {\n    return NextResponse.json({ message: \"EN: No offers found // VI: Không tìm thấy ưu đãi nào // ES: No se encontraron ofertas\" });\n  }\n\n  // EN: Simulate buyer choosing the best offer (simplistic) // VI: Mô phỏng người mua chọn ưu đãi tốt nhất (đơn giản) // ES: Simular que el comprador elige la mejor oferta (simplista)\n  const bestOffer = offers[0];\n  if (!bestOffer) {\n    return NextResponse.json({ message: \"EN: No suitable offers // VI: Không có ưu đãi phù hợp // ES: No hay ofertas adecuadas\" });\n  }\n\n  const purchaseACP: ACP = {\n    type: \"inform\",\n    sender: buyer.id,\n    receiver: bestOffer.sellerId,\n    content: {\n      action: \"purchase\",\n      items: bestOffer.acpMessage.content.itemsOfInterest,\n      quantity: bestOffer.acpMessage.content.quantityDesired,\n    },\n  };\n\n  return NextResponse.json({\n    message: \"EN: Purchase initiated // VI: Đã bắt đầu mua hàng // ES: Compra iniciada\",\n    acp: purchaseACP,\n  });\n}\n\n// EN: Function to simulate seller agent behavior // VI: Hàm mô phỏng hành vi của đại lý người bán // ES: Función para simular el comportamiento del agente vendedor\nasync function sellerAgent(\n  seller: SellerAgent,\n  acpMessage: ACP\n): Promise<NextResponse> {\n  const sellerResult = SellerAgentSchema.safeParse(seller);\n  if (!sellerResult.success) {\n    console.error(\"EN: Seller agent validation failed // VI: Xác thực đại lý người bán không thành công // ES: Falló la validación del agente vendedor\", sellerResult.error);\n    return NextResponse.json({ error: sellerResult.error.message }, { status: 400 });\n  }\n\n  const acpResult = ACPSchema.safeParse(acpMessage);\n  if (!acpResult.success) {\n    console.error(\"EN: ACP message validation failed // VI: Xác thực tin nhắn ACP không thành công // ES: Falló la validación del mensaje ACP\", acpResult.error);\n    return NextResponse.json({ error: acpResult.error.message }, { status: 400 });\n  }\n\n  if (acpMessage.type === \"request\") {\n    const itemsOfInterest = acpMessage.content.itemsOfInterest as string[];\n    const quantityDesired = acpMessage.content.quantityDesired as number;\n\n    const availableItems = seller.inventory.filter((item) =>\n      itemsOfInterest.includes(item.item) && item.quantity >= quantityDesired\n    );\n\n    if (availableItems.length === itemsOfInterest.length) {\n      const totalPrice = availableItems.reduce((sum, item) => sum + item.price * quantityDesired, 0);\n\n      const responseACP: ACP = {\n        type: \"response\",\n        sender: seller.id,\n        receiver: acpMessage.sender,\n        content: {\n          status: \"available\",\n          items: availableItems.map(item => item.item),\n          quantity: quantityDesired,\n          totalPrice: totalPrice,\n        },\n      };\n      return NextResponse.json({ message: \"EN: Items available // VI: Các mặt hàng có sẵn // ES: Artículos disponibles\", acp: responseACP });\n    } else {\n      const responseACP: ACP = {\n        type: \"response\",\n        sender: seller.id,\n        receiver: acpMessage.sender,\n        content: {\n          status: \"unavailable\",\n          message: \"EN: Some items are unavailable or insufficient quantity // VI: Một số mặt hàng không có sẵn hoặc số lượng không đủ // ES: Algunos artículos no están disponibles o la cantidad es insuficiente\",\n        },\n      };\n      return NextResponse.json({ message: \"EN: Items unavailable // VI: Các mặt hàng không có sẵn // ES: Artículos no disponibles\", acp: responseACP });\n    }\n  } else if (acpMessage.type === \"inform\" && acpMessage.content.action === \"purchase\") {\n    const itemsToPurchase = acpMessage.content.items as string[];\n    const quantityToPurchase = acpMessage.content.quantity as number;\n\n    // EN: Simulate updating inventory (simplistic) // VI: Mô phỏng cập nhật kho (đơn giản) // ES: Simular la actualización del inventario (simplista)\n    seller.inventory.forEach((item) => {\n      if (itemsToPurchase.includes(item.item)) {\n        item.quantity -= quantityToPurchase;\n      }\n    });\n\n    return NextResponse.json({\n      message: \"EN: Purchase confirmed, inventory updated // VI: Đã xác nhận mua hàng, đã cập nhật kho // ES: Compra confirmada, inventario actualizado\",\n      updatedInventory: seller.inventory,\n    });\n  } else {\n    return NextResponse.json({ message: \"EN: Unknown ACP message type // VI: Loại tin nhắn ACP không xác định // ES: Tipo de mensaje ACP desconocido\" }, { status: 400 });\n  }\n}\n\n// EN: Example Usage (not for export) // VI: Ví dụ sử dụng (không dành cho xuất) // ES: Ejemplo de uso (no para exportar)\nasync function exampleUsage() {\n  const buyer: BuyerAgent = {\n    id: \"buyer123\",\n    name: \"Alice\",\n    budget: 100,\n    preferences: [\"apple\", \"banana\"],\n  };\n\n  const seller1: SellerAgent = {\n    id: \"seller456\",\n    name: \"Bob's Fruits\",\n    inventory: [\n      { item: \"apple\", price: 1, quantity: 10 },\n      { item: \"banana\", price: 0.5, quantity: 20 },\n      { item: \"orange\", price: 0.75, quantity: 15 },\n    ],\n  };\n\n    const seller2: SellerAgent = {\n    id: \"seller789\",\n    name: \"Charlie's Market\",\n    inventory: [\n      { item: \"apple\", price: 1.2, quantity: 5 },\n      { item: \"grape\", price: 2, quantity: 10 },\n      { item: \"banana\", price: 0.6, quantity: 25 },\n    ],\n  };\n\n  const marketplace: MarketplaceAgent = {\n    id: \"market001\",\n    name: \"FruitMarket\",\n    rules: [\"price comparison\", \"quality check\"],\n  };\n\n  const buyerResponse = await buyerAgent(buyer, marketplace, [seller1, seller2]);\n  console.log(\"EN: Buyer Response: // VI: Phản hồi của người mua: // ES: Respuesta del comprador:\", buyerResponse);\n\n  if (buyerResponse.status === 200) {\n    const buyerData = await buyerResponse.json();\n    if (buyerData.acp) {\n        const sellerResponse = await sellerAgent(seller1, buyerData.acp);\n        console.log(\"EN: Seller Response: // VI: Phản hồi của người bán: // ES: Respuesta del vendedor:\", sellerResponse);\n    }\n  }\n\n}\n\n//exampleUsage(); // EN: Uncomment to run the example // VI: Bỏ ghi chú để chạy ví dụ // ES: Descomentar para ejecutar el ejemplo\n\nexport { buyerAgent, sellerAgent, BuyerAgentSchema, SellerAgentSchema, MarketplaceAgentSchema, ACPSchema };\n```",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedG3 Flash
25d agotask_createdfoundry_race
Task ID: 80e96c4c-5589-4953-8ffb-b89760b03ed2