Agent Architecture
Understanding Hyperfold's agent system design, components, and patterns.
Overview
Hyperfold agents are autonomous software components that handle specific aspects of agentic commerce. Built on the HAC (Human-Agent Commerce) paradigm, agents combine LLM reasoning with deterministic business logic to negotiate, fulfill, and optimize commerce operations.
Key Architectural Principles
- Single Responsibility: Each agent type handles one domain (negotiation, fulfillment, etc.)
- Event-Driven: Agents respond to ACP events and system triggers
- Stateful Context: Agents maintain conversation and transaction state
- Tool-Augmented: LLM reasoning enhanced with deterministic tools
- Observable: Full tracing of decisions and actions
Core Components
Every Hyperfold agent consists of these fundamental building blocks:
// Agent architecture overview
@HyperfoldAgent({
name: "negotiator",
version: "1.0.0",
capabilities: ["negotiate", "recommend", "bundle"]
})
class NegotiatorAgent {
constructor(
private context: AgentContext,
private tools: AgentTools,
private config: AgentConfig
) {}
@OnACPEvent("search")
async handleSearch(event: SearchEvent): Promise<SearchResponse> {
const products = await this.tools.catalog.search(event.query);
return { results: products, confidence: 0.94 };
}
@OnACPEvent("quote")
async handleQuote(event: QuoteEvent): Promise<QuoteResponse> {
const pricing = await this.calculateDynamicPrice(event);
return this.formulateResponse(pricing, event.buyerContext);
}
private async calculateDynamicPrice(event: QuoteEvent) {
const customer = await this.tools.crm.getCustomer(event.customerId);
const inventory = await this.tools.inventory.check(event.productId);
return this.context.llm.reason({
prompt: "Calculate optimal price...",
context: { customer, inventory, offer: event.offerPrice }
});
}
}
Component Breakdown
| Component | Purpose |
|---|---|
| AgentContext | Session state, LLM access, logging, inter-agent communication |
| AgentTools | Business logic tools (catalog, CRM, pricing, inventory) |
| AgentConfig | Runtime configuration (limits, thresholds, feature flags) |
| Event Handlers | ACP protocol handlers decorated with @OnACPEvent |
| Internal Logic | Private methods combining tools and LLM reasoning |
Agent Lifecycle
Agents follow a defined lifecycle with hooks for initialization, operation, and cleanup:
// Agent lifecycle hooks
@HyperfoldAgent({ name: "fulfillment" })
class FulfillmentAgent {
@OnStart()
async initialize() {
await this.loadCarrierRates();
await this.syncInventory();
this.context.logger.info("Agent initialized");
}
@OnStop()
async cleanup() {
await this.flushPendingShipments();
await this.context.state.persist();
}
@OnHealthCheck()
async healthCheck(): Promise<HealthStatus> {
const providerStatus = await this.checkProviders();
return {
healthy: providerStatus.every(p => p.connected),
details: providerStatus
};
}
@OnSchedule("*/5 * * * *")
async syncInventoryLevels() {
const changes = await this.tools.inventory.sync();
if (changes.length > 0) {
await this.notifyLowStock(changes);
}
}
}
Lifecycle Stages
1. Initialization — Agent loads configuration, establishes connections to external services, and prepares internal state. The @OnStart hook runs before any events are processed.
2. Active Processing — Agent handles incoming events, executes scheduled tasks, and responds to health checks. Multiple events can be processed concurrently based on scaling configuration.
3. Graceful Shutdown — When scaling down or redeploying, agents complete in-flight requests, persist state, and release resources via the @OnStop hook.
Inter-Agent Communication
Agents collaborate through multiple communication patterns:
// 1. Direct invocation
@OnACPEvent("checkout.complete")
async handleCheckout(event: CheckoutEvent) {
const shipment = await this.context.agents.invoke("fulfillment", {
action: "create_shipment",
order: event.order
});
return { orderId: event.orderId, shipmentId: shipment.id };
}
// 2. Event-based communication
@OnACPEvent("order.created")
async handleOrder(event: OrderEvent) {
await this.context.events.publish("order.ready_for_fulfillment", {
orderId: event.orderId,
priority: event.customer.tier === "platinum" ? "high" : "normal"
});
}
// 3. Shared state access
async getCustomerContext(customerId: string) {
const negotiationHistory = await this.context.state.get(`customer:${customerId}:negotiations`);
const recommendations = await this.context.state.get(`customer:${customerId}:recommendations`);
return { negotiationHistory, recommendations };
}
// 4. Agent orchestration via workflows
@OnWorkflowStep("enrich_order")
async enrichOrder(input: WorkflowInput): Promise<WorkflowOutput> {
const enriched = await this.addCustomerInsights(input.order);
return { order: enriched, nextStep: "validate_payment" };
}
Communication Patterns
| Pattern | Use Case | Coupling |
|---|---|---|
| Direct Invocation | Synchronous request-response between agents | Tight |
| Event Publishing | Async notifications without response expectation | Loose |
| Shared State | Durable data exchange across sessions | Medium |
| Workflow Steps | Orchestrated multi-agent processes | Orchestrated |
Scaling & Deployment
Agents scale automatically based on demand:
# Agent deployment configuration (hyperfold.yaml)
agents:
negotiator:
runtime: nodejs20
memory: 512Mi
cpu: 0.5
scaling:
min_instances: 2
max_instances: 50
target_concurrency: 100
scale_up_threshold: 0.7
scale_down_threshold: 0.3
cooldown_seconds: 60
resources:
llm_provider: openai
llm_model: gpt-4-turbo
max_tokens_per_request: 4096
networking:
timeout_seconds: 30
retry_attempts: 3
circuit_breaker:
failure_threshold: 5
recovery_timeout: 30s
fulfillment:
runtime: nodejs20
memory: 256Mi
cpu: 0.25
scaling:
min_instances: 1
max_instances: 20
target_concurrency: 50
integrations:
- shipstation
- inventory_service
Scaling Considerations
Stateless by Default — Agents are designed to be stateless between requests. Session state is stored externally, allowing any instance to handle any request.
Concurrency Control — Each agent instance handles multiple concurrent requests up to the configured limit. New instances spin up when concurrency targets are exceeded.
Resource Isolation — Each agent type runs in isolated containers with dedicated resource allocations. LLM-intensive agents (negotiators) get more resources than utility agents.
Agents are deployed automatically when you run hyperfold agent deploy. Monitor scaling with Auto-Scaling.
Explore specific agent implementations: Negotiator, Fulfillment, Recommender.