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:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Agent architecture overview
@HyperfoldAgent({
name: "negotiator",
version: "1.0.0",
capabilities: ["negotiate", "recommend", "bundle"]
})
class NegotiatorAgent {
// Context injection - agent state, tools, config
constructor(
private context: AgentContext,
private tools: AgentTools,
private config: AgentConfig
) {}
// Event handlers - respond to ACP events
@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);
}
// Internal logic with LLM reasoning
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

ComponentPurpose
AgentContextSession state, LLM access, logging, inter-agent communication
AgentToolsBusiness logic tools (catalog, CRM, pricing, inventory)
AgentConfigRuntime configuration (limits, thresholds, feature flags)
Event HandlersACP protocol handlers decorated with @OnACPEvent
Internal LogicPrivate methods combining tools and LLM reasoning

Agent Lifecycle

Agents follow a defined lifecycle with hooks for initialization, operation, and cleanup:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Agent lifecycle hooks
@HyperfoldAgent({ name: "fulfillment" })
class FulfillmentAgent {
// Called when agent instance starts
@OnStart()
async initialize() {
await this.loadCarrierRates();
await this.syncInventory();
this.context.logger.info("Agent initialized");
}
// Called before shutdown
@OnStop()
async cleanup() {
await this.flushPendingShipments();
await this.context.state.persist();
}
// Health check endpoint
@OnHealthCheck()
async healthCheck(): Promise<HealthStatus> {
const providerStatus = await this.checkProviders();
return {
healthy: providerStatus.every(p => p.connected),
details: providerStatus
};
}
// Periodic tasks
@OnSchedule("*/5 * * * *") // Every 5 minutes
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:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Inter-agent communication patterns
// 1. Direct invocation
@OnACPEvent("checkout.complete")
async handleCheckout(event: CheckoutEvent) {
// Invoke fulfillment agent directly
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) {
// Publish event for other agents to consume
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) {
// Access shared state written by other agents
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> {
// Part of multi-agent workflow
const enriched = await this.addCustomerInsights(input.order);
return { order: enriched, nextStep: "validate_payment" };
}

Communication Patterns

PatternUse CaseCoupling
Direct InvocationSynchronous request-response between agentsTight
Event PublishingAsync notifications without response expectationLoose
Shared StateDurable data exchange across sessionsMedium
Workflow StepsOrchestrated multi-agent processesOrchestrated

Scaling & Deployment

Agents scale automatically based on demand:

yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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
# Connect to external systems
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.