FOUNDRY
C8 Platform
← Tasks

[AI-05] ACP choreography (Vertex 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
Vertex Flash
Created
25d ago
Completed
25d ago

Quality

Overall
79%
Pass
PASS
Graded By
-
Graded At
-

Cost

Input Tokens
168
Output Tokens
1,614
Est. USD
-

Result

{
  "code": "```typescript\n// EN: ACP agent-to-agent choreography module. // VI: Mô-đun biên đạo giao tiếp giữa các tác nhân ACP. // ES: Módulo de coreografía de agente a agente ACP.\n// SPEC: AI-05\n\nimport { z } from \"zod\";\nimport { NextResponse } from \"next/server\";\n\n// EN: Define Zod schemas for agents and messages. // VI: Định nghĩa lược đồ Zod cho các tác nhân và tin nhắn. // ES: Define esquemas Zod para agentes y mensajes.\n\nconst BuyerAgentSchema = z.object({\n  id: z.string(),\n  type: z.literal(\"buyer\"),\n  preferences: z.object({\n    productCategory: z.string(),\n    maxPrice: z.number(),\n  }),\n});\ntype BuyerAgent = z.infer<typeof BuyerAgentSchema>;\n\nconst SellerAgentSchema = z.object({\n  id: z.string(),\n  type: z.literal(\"seller\"),\n  inventory: z.array(\n    z.object({\n      productName: z.string(),\n      productCategory: z.string(),\n      price: z.number(),\n      quantity: z.number(),\n    })\n  ),\n});\ntype SellerAgent = z.infer<typeof SellerAgentSchema>;\n\nconst MarketplaceAgentSchema = z.object({\n  id: z.string(),\n  type: z.literal(\"marketplace\"),\n});\ntype MarketplaceAgent = z.infer<typeof MarketplaceAgentSchema>;\n\nconst OfferSchema = z.object({\n  productName: z.string(),\n  price: z.number(),\n  quantity: z.number(),\n  sellerId: z.string(),\n});\ntype Offer = z.infer<typeof OfferSchema>;\n\nconst BuyerRequestSchema = z.object({\n  productCategory: z.string(),\n  maxPrice: z.number(),\n  buyerId: z.string(),\n});\ntype BuyerRequest = z.infer<typeof BuyerRequestSchema>;\n\nconst ACPMessageSchema = z.union([\n  z.object({\n    type: z.literal(\"request_for_proposal\"),\n    payload: BuyerRequestSchema,\n  }),\n  z.object({\n    type: z.literal(\"proposal\"),\n    payload: OfferSchema,\n  }),\n  z.object({\n    type: z.literal(\"accept_proposal\"),\n    payload: z.object({\n      offer: OfferSchema,\n      buyerId: z.string(),\n    }),\n  }),\n  z.object({\n    type: z.literal(\"reject_proposal\"),\n    payload: z.object({\n      offer: OfferSchema,\n      buyerId: z.string(),\n      reason: z.string().optional(),\n    }),\n  }),\n]);\n\ntype ACPMessage = z.infer<typeof ACPMessageSchema>;\n\n// EN: Agent Communication Protocol (ACP) functions. // VI: Các hàm Giao thức Giao tiếp Tác nhân (ACP). // ES: Funciones del Protocolo de Comunicación de Agentes (ACP).\n\nasync function handleBuyerRequest(\n  buyerRequest: BuyerRequest,\n  sellers: SellerAgent[]\n): Promise<Offer[]> {\n  // EN: Simulate a buyer sending a request to multiple sellers. // VI: Mô phỏng người mua gửi yêu cầu đến nhiều người bán. // ES: Simula un comprador enviando una solicitud a múltiples vendedores.\n  const relevantSellers = sellers.filter((seller) =>\n    seller.inventory.some(\n      (item) =>\n        item.productCategory === buyerRequest.productCategory &&\n        item.price <= buyerRequest.maxPrice &&\n        item.quantity > 0\n    )\n  );\n\n  const offers: Offer[] = relevantSellers.map((seller) => {\n    const item = seller.inventory.find(\n      (i) =>\n        i.productCategory === buyerRequest.productCategory &&\n        i.price <= buyerRequest.maxPrice &&\n        i.quantity > 0\n    );\n    if (!item) return null as any; // Type assertion needed because of the map.\n\n    return {\n      productName: item.productName,\n      price: item.price,\n      quantity: Math.min(item.quantity, 1), // Buyer requests only one item\n      sellerId: seller.id,\n    };\n  }).filter(offer => offer !== null);\n\n  return offers;\n}\n\nasync function handleProposalAcceptance(offer: Offer, buyerId: string): Promise<string> {\n  // EN: Simulate accepting a proposal. // VI: Mô phỏng việc chấp nhận đề xuất. // ES: Simula la aceptación de una propuesta.\n  return `Proposal accepted for ${offer.productName} from seller ${offer.sellerId} by buyer ${buyerId}.`;\n}\n\nasync function handleProposalRejection(offer: Offer, buyerId: string, reason?: string): Promise<string> {\n  // EN: Simulate rejecting a proposal. // VI: Mô phỏng việc từ chối đề xuất. // ES: Simula el rechazo de una propuesta.\n  const rejectionReason = reason ? `: ${reason}` : \"\";\n  return `Proposal rejected for ${offer.productName} from seller ${offer.sellerId} by buyer ${buyerId}${rejectionReason}.`;\n}\n\n// EN: Main ACP function to handle messages. // VI: Hàm ACP chính để xử lý tin nhắn. // ES: Función ACP principal para manejar mensajes.\nasync function processACPMessage(\n  message: ACPMessage,\n  sellers: SellerAgent[]\n): Promise<NextResponse> {\n  const parseResult = ACPMessageSchema.safeParse(message);\n\n  if (!parseResult.success) {\n    console.error(\"Invalid ACP Message:\", parseResult.error);\n    return NextResponse.json({ error: \"Invalid ACP Message\" }, { status: 400 });\n  }\n\n  const validatedMessage = parseResult.data;\n\n  switch (validatedMessage.type) {\n    case \"request_for_proposal\":\n      const offers = await handleBuyerRequest(validatedMessage.payload, sellers);\n      return NextResponse.json({ offers });\n    case \"accept_proposal\":\n      const acceptanceResult = await handleProposalAcceptance(validatedMessage.payload.offer, validatedMessage.payload.buyerId);\n      return NextResponse.json({ result: acceptanceResult });\n    case \"reject_proposal\":\n      const rejectionResult = await handleProposalRejection(validatedMessage.payload.offer, validatedMessage.payload.buyerId, validatedMessage.payload.reason);\n      return NextResponse.json({ result: rejectionResult });\n    case \"proposal\":\n      return NextResponse.json({ error: \"Proposal message type not handled directly.\" }, { status: 400 }); // Proposals are sent in response to RFP\n    default:\n      return NextResponse.json({ error: \"Unknown message type\" }, { status: 400 });\n  }\n}\n\nexport {\n  BuyerAgentSchema,\n  SellerAgentSchema,\n  MarketplaceAgentSchema,\n  ACPMessageSchema,\n  BuyerAgent,\n  SellerAgent,\n  MarketplaceAgent,\n  ACPMessage,\n  processACPMessage,\n  handleBuyerRequest,\n  handleProposalAcceptance,\n  handleProposalRejection,\n};\n```",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedVertex Flash
25d agotask_createdfoundry_race
Task ID: 658138b4-9ae8-481d-9915-d1f69a313e8b