FOUNDRY
C8 Platform
← Tasks

[AI-05] Goldilocks Inverter (prose)

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
Team Inverter (prose)
Created
25d ago
Completed
25d ago

Quality

Overall
89%
Pass
PASS
Graded By
-
Graded At
-

Cost

Input Tokens
-
Output Tokens
-
Est. USD
$0.0151

Result

{
  "code": "```typescript\n// src/lib/acp-agents.ts\n\nimport { z } from 'zod';\nimport { NextResponse } from 'next/server';\n\n// Zod Schemas for ACP Agents\n// SPEC: Section 2\n\nconst AgentBaseSchema = z.object({\n  id: z.string().uuid(), // Unique identifier for the agent\n  name: z.string(), // Name of the agent\n  role: z.enum(['buyer', 'seller', 'marketplace']), // Role of the agent\n});\n\nexport const BuyerAgentSchema = AgentBaseSchema.extend({\n  budget: z.number().positive(), // Budget for purchases\n  preferences: z.array(z.string()), // Preferences for products\n});\n\nexport const SellerAgentSchema = AgentBaseSchema.extend({\n  inventory: z.array(\n    z.object({\n      product: z.string(),\n      quantity: z.number(),\n      price: z.number().positive(), // Price of the product\n    })\n  ), // Inventory of products\n  pricingStrategy: z.string(), // Pricing strategy\n});\n\nexport const MarketplaceAgentSchema = AgentBaseSchema.extend({\n  listings: z.array(z.object({ product: z.string(), sellerId: z.string().uuid() })), // Listings of products\n  transactionFee: z.number().nonnegative(), // Transaction fee\n});\n\nexport const ACPSchema = z.object({\n  buyerAgent: BuyerAgentSchema,\n  sellerAgent: SellerAgentSchema,\n  marketplaceAgent: MarketplaceAgentSchema,\n});\n\n// Define the types based on the Zod schemas\nexport type BuyerAgent = z.infer<typeof BuyerAgentSchema>;\nexport type SellerAgent = z.infer<typeof SellerAgentSchema>;\nexport type MarketplaceAgent = z.infer<typeof MarketplaceAgentSchema>;\nexport type ACP = z.infer<typeof ACPSchema>;\n\n// Function to create a BuyerAgent\n// SPEC: Section 3\nexport function createBuyerAgent(data: z.infer<typeof BuyerAgentSchema>): BuyerAgent {\n  return data;\n}\n\n// Function to create a SellerAgent\n// SPEC: Section 3\nexport function createSellerAgent(data: z.infer<typeof SellerAgentSchema>): SellerAgent {\n  return data;\n}\n\n// Acceptance Criteria symbols\nexport const buyer_agent = BuyerAgentSchema;\nexport const seller_agent = SellerAgentSchema;\n\n// Function to perform the choreography between agents\n// SPEC: Section 3\nexport async function performChoreography(acp: unknown): Promise<NextResponse> {\n  // Validate the ACP data using Zod\n  const result = ACPSchema.safeParse(acp);\n  if (!result.success) {\n    // EN: Return an error response if the data is invalid // VI: Trả về phản hồi lỗi nếu dữ liệu không hợp lệ // ES: Devolver una respuesta de error si los datos no son válidos\n    return NextResponse.json(\n      {\n        error: result.error.issues.map(issue => ({\n          code: issue.code,\n          message: issue.message,\n          path: issue.path,\n        })),\n      },\n      { status: 400 }\n    );\n  }\n\n  const { buyerAgent, sellerAgent, marketplaceAgent } = result.data;\n\n  // Find a product that matches the buyer's preferences, respecting preference order\n  let productOfInterest = null;\n  for (const pref of buyerAgent.preferences) {\n    const found = sellerAgent.inventory.find(item => item.product === pref);\n    if (found) {\n      productOfInterest = found;\n      break;\n    }\n  }\n\n  if (!productOfInterest) {\n    // EN: Handle cases where there are no listings that match the buyer's preferences // VI: Xử lý trường hợp không có danh sách nào phù hợp với sở thích của người mua // ES: Manejar los casos en que no hay listados que coincidan con las preferencias del comprador\n    return NextResponse.json({ message: buyerAgent.preferences.length === 0 ? \"Buyer has no preferences.\" : \"No matching products found.\" }, { status: 404 });\n  }\n\n  if (productOfInterest.quantity <= 0) {\n    // EN: Handle cases where the seller's inventory is empty // VI: Xử lý các trường hợp khi kho hàng của người bán trống rỗng // ES: Manejar los casos en que el inventario del vendedor está vacío\n    return NextResponse.json({ message: \"Product out of stock.\" }, { status: 400 });\n  }\n\n  // Calculate the total cost, including transaction fee\n  const transactionFee = marketplaceAgent.transactionFee;\n  const productPrice = productOfInterest.price;\n  const totalCost = productPrice + transactionFee;\n\n  if (buyerAgent.budget < totalCost) {\n    // EN: Handle cases where the buyer's budget is insufficient to make a purchase // VI: Xử lý các trường hợp khi ngân sách của người mua không đủ để mua hàng // ES: Manejar los casos en que el presupuesto del comprador es insuficiente para realizar una compra\n    return NextResponse.json({ message: \"Insufficient budget.\" }, { status: 400 });\n  }\n\n  // Simulate the transaction\n  const remainingBudget = buyerAgent.budget - totalCost;\n  const updatedInventory = sellerAgent.inventory.map(item =>\n    item.product === productOfInterest.product ? { ...item, quantity: item.quantity - 1 } : item\n  );\n\n  const transactionId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);\n\n  // EN: Return a success response // VI: Trả về phản hồi thành công // ES: Devolver una respuesta exitosa\n  return NextResponse.json({\n    message: \"Transaction successful!\",\n    transactionId: transactionId,\n    remainingBudget: remainingBudget,\n    updatedInventory: updatedInventory,\n  });\n}\n\nexport type {\n  ACP,\n  BuyerAgent,\n  SellerAgent,\n  MarketplaceAgent,\n};\n\nexport {\n  createBuyerAgent,\n  createSellerAgent,\n};\n```",
  "spec_id": "AI-05"
}

Audit Trail (2)

25d agotask_completedTeam Inverter (prose)
25d agotask_createdfoundry_goldilocks
Task ID: 264177a6-2566-4cb6-bc54-f1f6a9c11eef