// ============================================================================= // Dynamic loader for seller offerings. // Offerings are stored per-agent: src/seller/offerings/// // ============================================================================= import * as fs from "fs"; import * as path from "path"; import { fileURLToPath } from "url"; import type { OfferingHandlers } from "./offeringTypes.js"; import { CANONICAL_CATALOG, getEffectiveCanonicalOffering, getCanonicalOfferingNamesForAgent, } from "../offerings/canonical-catalog.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); /** The parsed offering.json config. */ export interface OfferingConfig { name: string; description: string; jobFee: number; jobFeeType: "fixed" | "percentage"; requiredFunds: boolean; } export interface LoadedOffering { config: OfferingConfig; handlers: OfferingHandlers; } const REQUIRED_FIELDS = [ "name", "description", "jobFee", "jobFeeType", "requiredFunds", ] as const; function resolveOfferingsRoot(agentDirName: string): string { return path.resolve(__dirname, "..", "offerings", agentDirName); } /** * Load a named offering from `src/seller/offerings///`. * Expects `offering.json` and `handlers.ts` in that directory. */ export async function loadOffering( offeringName: string, agentDirName: string, ): Promise { const offeringsRoot = resolveOfferingsRoot(agentDirName); const offeringDir = path.resolve(offeringsRoot, offeringName); const relativePath = path.relative(offeringsRoot, offeringDir); if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) { throw new Error( `Invalid offering name: path traversal detected ("${offeringName}")`, ); } // offering.json const configPath = path.join(offeringDir, "offering.json"); if (!fs.existsSync(configPath)) { throw new Error(`offering.json not found: ${configPath}`); } const parsedConfig = JSON.parse( fs.readFileSync(configPath, "utf-8"), ) as OfferingConfig; const effectiveCanonical = getEffectiveCanonicalOffering(offeringName); const config: OfferingConfig = effectiveCanonical ? { ...parsedConfig, name: effectiveCanonical.name, jobFee: effectiveCanonical.jobFee, jobFeeType: effectiveCanonical.jobFeeType, requiredFunds: effectiveCanonical.requiredFunds, } : parsedConfig; // handlers.ts (dynamically imported) const handlersPath = path.join(offeringDir, "handlers.ts"); if (!fs.existsSync(handlersPath)) { throw new Error(`handlers.ts not found: ${handlersPath}`); } const handlers = (await import(handlersPath)) as OfferingHandlers; if (typeof handlers.executeJob !== "function") { throw new Error( `handlers.ts in "${offeringName}" must export an executeJob function`, ); } return { config, handlers }; } /** * List all available offering names for a given agent. */ export function listOfferings( agentDirName: string, logger: Pick = console, ): string[] { const offeringsRoot = resolveOfferingsRoot(agentDirName); if (!fs.existsSync(offeringsRoot)) return []; return fs .readdirSync(offeringsRoot, { withFileTypes: true }) .filter((d) => d.isDirectory()) .filter((d) => !d.name.startsWith("_")) .flatMap((d) => { const offeringDir = path.join(offeringsRoot, d.name); const missingFiles = [ !fs.existsSync(path.join(offeringDir, "offering.json")) ? "offering.json" : null, !fs.existsSync(path.join(offeringDir, "handlers.ts")) ? "handlers.ts" : null, ].filter((value): value is string => value !== null); if (missingFiles.length > 0) { logger.warn( `[seller] Skipping incomplete offering "${d.name}": missing ${missingFiles.join(", ")}`, ); return []; } return [d]; }) .map((d) => d.name); } function loadOfferingConfigJson( agentDirName: string, offeringName: string, ): Record { const offeringsRoot = resolveOfferingsRoot(agentDirName); const offeringDir = path.join(offeringsRoot, offeringName); const offeringJsonPath = path.join(offeringDir, "offering.json"); if (!fs.existsSync(offeringJsonPath)) { throw new Error(`${offeringName}: offering.json not found`); } const raw = fs.readFileSync(offeringJsonPath, "utf-8"); const parsed = JSON.parse(raw); if (!parsed || typeof parsed !== "object") { throw new Error(`${offeringName}: offering.json must be a JSON object`); } return parsed as Record; } function normalizeFeeToCents(value: unknown): number | undefined { if (typeof value !== "number" || !Number.isFinite(value)) { return undefined; } return Math.round(value * 100); } /** * Fail-fast preflight for the active seller directory. * * Startup must refuse to run unless the active agent directory contains * exactly the canonical offerings with canonical pricing + required fields. */ export function assertCanonicalOfferingsOrThrow( agentDirName: string, offerings: string[], logger: Pick = console, ): void { const errors: string[] = []; const discovered = new Set(offerings); const expectedOfferings = getCanonicalOfferingNamesForAgent(agentDirName); const missing = expectedOfferings.filter((name) => !discovered.has(name)); if (missing.length > 0) { errors.push(`Missing canonical offerings: ${missing.join(", ")}`); } const extra = offerings.filter((name) => !expectedOfferings.includes(name)); if (extra.length > 0) { errors.push(`Unexpected offering directories: ${extra.join(", ")}`); } for (const offeringName of expectedOfferings) { if (!discovered.has(offeringName)) { continue; } let config: Record; try { config = loadOfferingConfigJson(agentDirName, offeringName); } catch (err) { errors.push(err instanceof Error ? err.message : String(err)); continue; } const canonical = CANONICAL_CATALOG[offeringName]; for (const field of REQUIRED_FIELDS) { if (config[field] === undefined || config[field] === null) { errors.push(`${offeringName}: missing required field "${field}"`); } } if (config.name !== canonical.name) { errors.push( `${offeringName}: name mismatch (got "${String(config.name)}", expected "${canonical.name}")`, ); } const actualFeeCents = normalizeFeeToCents(config.jobFee); const expectedFeeCents = normalizeFeeToCents(canonical.jobFee); if (actualFeeCents === undefined || expectedFeeCents === undefined) { errors.push(`${offeringName}: invalid numeric jobFee`); } else if (actualFeeCents !== expectedFeeCents) { errors.push( `${offeringName}: jobFee mismatch (got ${String(config.jobFee)}, expected ${canonical.jobFee})`, ); } if (config.jobFeeType !== canonical.jobFeeType) { errors.push( `${offeringName}: jobFeeType mismatch (got "${String(config.jobFeeType)}", expected "${canonical.jobFeeType}")`, ); } if (config.requiredFunds !== canonical.requiredFunds) { errors.push( `${offeringName}: requiredFunds mismatch (got ${String(config.requiredFunds)}, expected ${String(canonical.requiredFunds)})`, ); } const handlersPath = path.join( resolveOfferingsRoot(agentDirName), offeringName, "handlers.ts", ); if (!fs.existsSync(handlersPath)) { errors.push(`${offeringName}: handlers.ts not found`); } } if (errors.length > 0) { const summary = [ `Canonical offering preflight failed for agent dir "${agentDirName}"`, `Expected canonical offerings: ${expectedOfferings.length}`, ...errors.map((error) => `- ${error}`), ].join("\n"); logger.error(`[seller] ${summary}`); throw new Error(summary); } logger.log( `[seller] Canonical offering preflight passed for "${agentDirName}" (${expectedOfferings.length}/${expectedOfferings.length})`, ); } export function logOfferingsStatus( agentDirName: string, offerings: string[], logger: Pick = console, ): void { if (offerings.length === 0) { logger.warn( `[seller] WARNING: No offerings discovered for agent dir "${agentDirName}"`, ); } logger.log( `[seller] Available offerings: ${offerings.length > 0 ? offerings.join(", ") : "(none)"}`, ); }