API Reference

HBForge v4.1.1 API Reference

50 modules. Zero dependencies. All exports, types, and usage examples.

# HBForge is internal — zero external dependencies
import { createAMP } from "@hyperbridge/forge/amp";
import { AIG, AIGBuilder } from "@hyperbridge/forge/aig";
import { verifyPoO } from "@hyperbridge/forge/poo";
import { Vault } from "@hyperbridge/forge/vault";
amp @hyperbridge/forge/amp Web7 Core

Agent Mesh Protocol — the on-wire format for all agent interactions. Creates, signs, and verifies AMP envelopes. Implements all 7 protocol verbs and 4 settlement rails.

function createAMP(config: AMPConfig): AMPClient
Creates an AMP client bound to a DID and private key. Returns a client with methods for all 7 verbs.
class AMPClient
Methods: .discover(skill, constraints) · .negotiate(agentDid, terms) · .delegate(to, intent, settle) · .execute(delegationId, result) · .settle(outcomeId) · .attest(outcomeId, sig) · .revoke(delegationId, reason)
function signEnvelope(envelope: AMPEnvelope, privateKey: Uint8Array): AMPEnvelope
Signs an AMP envelope with ed25519. Returns envelope with auth field set to hex-encoded signature.
function verifyEnvelope(envelope: AMPEnvelope, registry: DIDRegistry): boolean
Verifies the envelope signature against the sender's DID public key. Returns false for forged or expired envelopes.
type AMPEnvelope
Fields: v · kind · id · parent · from · to · intent · settle · require · auth · nonce · ts · payload
Example
import { createAMP } from "@hyperbridge/forge/amp";

const amp = createAMP({ did: "did:w7:alice", privateKey: myKey });

const result = await amp.delegate({
  to: "did:w7:skill/tax-filing",
  intent: { action: "file_quarterly", params: { quarter: "2026-Q1" } },
  settle: { rail: "amp-escrow", amount: "50 USD" }
});
aig @hyperbridge/forge/aig Web7 Core

Accountable Intelligence Graph — a tamper-evident DAG of signed events. Tracks the full lineage from Intent → Delegation → Inference → Outcome. Computes Merkle roots for L0 commitment.

class AIG
Methods: .addNode(node) · .addEdge(fromId, toId, type) · .walk(rootId) · .lineage(outcomeId) · .merkleRoot() · .merkleProof(nodeId) · .anchor() · .toDot()
class AIGBuilder
Fluent DSL: .intent(envelope) · .delegation(envelope) · .inference(envelope) · .outcome(envelope) · .build()
type AIGNode
Fields: id · kind · envelope · signature · timestamp · children
Example
import { AIGBuilder } from "@hyperbridge/forge/aig";

const graph = new AIGBuilder()
  .intent(intentEnvelope)
  .delegation(delegationEnvelope)
  .inference(inferenceEnvelope)
  .outcome(outcomeEnvelope)
  .build();

const root = graph.merkleRoot();
// anchor to L0: graph.anchor()
poo @hyperbridge/forge/poo Web7 Core

Proof-of-Outcome — the 8-check verification predicate. Verifies agent authorisation, model identity, ZK-ML inference, policy compliance, and stake adequacy. Any failed check triggers slashing logic.

async function verifyPoO(intent: AMPEnvelope, outcome: AMPEnvelope, opts?: PoOOptions): Promise<PoOResult>
Runs all 8 checks: principalSig · delegationSig · agentSig · zkml · policy · stake · sla · attestors. Returns scored result with pass/fail per check.
async function verifyBatch(pairs: Array<{intent, outcome}>): Promise<PoOResult[]>
Parallel batch verification. Useful for settling multiple agent outcomes in one pass.
function settlementValue(result: PoOResult, maxAmount: number): number
Calculates payout amount based on PoO score and configured settlement rail. Returns 0 on hard failure.
const CHECKS: Record<CheckName, { weight: number, required: boolean }>
8 checks with weights: principalSig(25) · delegationSig(20) · agentSig(15) · zkml(15) · policy(10) · stake(5) · sla(5) · attestors(5)
Example
import { verifyPoO, CHECKS } from "@hyperbridge/forge/poo";

const result = await verifyPoO(intentEnv, outcomeEnv);

if (result.pass) {
  const payout = settlementValue(result, 50); // USD
  await releaseEscrow(delegationId, payout);
} else {
  await slashReputation(result.agentDid, result.failedChecks);
}
vault @hyperbridge/forge/vault Web7 Core

AES-256-GCM encryption, secret leases, and env loading. Uses Web Crypto API natively on Vercel/Cloudflare with a Node.js crypto fallback for Docker deployments. Namespace-isolated per agent.

class Vault
Methods: .encrypt(data) · .decrypt(ciphertext) · .setSecret(key, value, ttl?) · .getSecret(key) · .rotateKey() · .namespace(ns)
class EnvVault
Loads .env file, encrypts all values, exposes via .get(key). Supports per-deployment key rotation without re-deploying app.
class Secret
A leased secret with TTL, access count, and auto-expiry. .value · .expiresAt · .renew() · .revoke()
reputation @hyperbridge/forge/reputation Web7 Core

Reputation-as-Collateral ledger. Non-transferable, domain-scoped, slashable. 6-month half-life decay. 6 slash triggers with configurable distribution ratios.

class ReputationRegistry
Methods: .getScore(agentDid, domain) · .recordOutcome(agentDid, outcomeValue, domain) · .slash(agentDid, rule, domain) · .gate(minScore)
function computeScore(record: ReputationRecord): number
Applies age-decay formula: outcome_value × principal_stake × domain_match × 0.5^(months/6)
const SLASH_RULES
badZkml: 100% · signatureForger: 100% · policyViolation: 50% · missedSla: 20% · failedAttestation: 25% · unavailability: 10%
function reputationGate(registry: ReputationRegistry, minScore: number, domain: string): Middleware
Express/Forge HTTP middleware. Rejects requests from agents below the minimum reputation score for the given domain.
settlement @hyperbridge/forge/settlement Web7 Core

Implements the 4 AMP settlement rails: escrow (milestone), outcome (binary), subscription (recurring), and split (multi-agent revenue share). All rails are PoO-triggered.

class EscrowLedger
.lockFunds(delegationId, amount) · .releaseMilestone(milestoneId) · .forfeit(delegationId, reason) · .dispute(delegationId) · .balance(delegationId)
class SubscriptionRail
Manages recurring payment schedules. .subscribe(agentDid, plan) · .cancel(subscriptionId) · .pauseBilling(subscriptionId) · .nextBillingDate(subscriptionId)
class SplitRail
Distributes payment to multiple agents by percentage. .define(splits: {did, pct}[]) · .execute(totalAmount) · .audit()
const RAILS
AMP_ESCROW · AMP_OUTCOME · AMP_SUBSCRIPTION · AMP_SPLIT
identity @hyperbridge/forge/identity Web7 Core

DID registry, Verifiable Credentials, RBAC, and sessions. Implements the did:w7 method for all entity types. Mock ed25519 in v0.1; hardware-backed in production.

class DIDRegistry
.create(slug) · .resolve(did) · .sign(did, data) · .verify(did, data, sig) · .update(did, patch, sig) · .deactivate(did, sig) · .importPublic(did, pubKeyHex)
class VCIssuer
Issues signed W3C Verifiable Credentials. .issue(subject, claims, expiry?) · .verify(vc) · .revoke(vcId)
class RBAC
.defineRole(name, permissions[]) · .assign(did, role) · .can(did, permission) · .middleware(permission)
class SessionStore
Session management with DID binding. .create(did, scope) · .validate(token) · .revoke(token) · .extend(token, ttl)
cron @hyperbridge/forge/cron Application

Full cron expression parser and scheduler. Handles all cron features including ranges, steps, and lists. Distributed lock support for multi-instance deployments.

function parseCron(expr: string): CronExpression
Parses 5-field cron expression. Supports *, ranges (1-5), steps (*/15), lists (1,3,5), and named (@daily).
function nextDate(expr: string, from?: Date): Date
Returns the next Date matching the cron expression after the given date (defaults to now).
class CronScheduler
.add(name, expr, fn, opts?) · .remove(name) · .start() · .stop() · .status(). Opts: timeout, concurrency, distributedLock
const NAMED
@hourly · @daily · @weekly · @monthly · @yearly · @midnight
Example
import { CronScheduler, NAMED } from "@hyperbridge/forge/cron";

const scheduler = new CronScheduler();

scheduler.add("daily-report", NAMED.daily, async () => {
  await generateDailyReport();
}, { timeout: 30_000 });

scheduler.start();
events @hyperbridge/forge/events Application

Type-safe event bus with wildcard patterns, middleware, dead-letter queue, and event store for replay/snapshot. Used internally by AMP to emit lifecycle events.

class EventBus
.on(pattern, handler) · .emit(event) · .off(pattern, handler) · .use(middleware) · .waitFor(pattern, timeout?) · .deadLetter(handler)
matchPattern(pattern: string, eventName: string): boolean
Supports * (single segment) and ** (multi-segment) wildcards. "user.*" matches "user.created" but not "user.profile.updated".
class EventStore
Append-only event log with snapshot support. .record(event) · .rebuild(fromSnapshot?) · .snapshot() · .replay(fromSeq)
const bus: EventBus
Global singleton event bus. Import and use directly for app-wide events.
vigil @hyperbridge/forge/vigil Data & Media

Security observability: rate limiting (sliding window), threat scoring (rule-based), IP blocklist, and NDJSON audit logging. Used by the Vigil security app and all production services.

class RateLimiter
Sliding window rate limiter. .check(key, limit, windowMs) · .block(key, durationMs) · .middleware(opts)
class ThreatScorer
Rule-based threat scoring. .addRule(name, weight, fn) · .score(request) · .middleware(threshold)
class AuditLog
Tamper-evident append-only log. .record(event) · .export('ndjson') · .query(filters)
addCommonRules(scorer: ThreatScorer): void
Adds pre-built rules: SQL injection detection, XSS patterns, path traversal, bot user-agent detection.
geo @hyperbridge/forge/geo Data & Media

Geographic utilities: Haversine distance, bearing, geohash encoding/decoding/neighbors, BBox, and a grid-based SpatialIndex for proximity queries.

haversine(a: Point, b: Point, unit?: 'km'|'mi'|'m'): number
Great-circle distance between two lat/lng points using the Haversine formula.
geohashEncode(lat: number, lng: number, precision?: number): string
Encodes lat/lng to geohash string (BASE32). Default precision 9 (~±2.4m accuracy).
class SpatialIndex
Grid-based spatial index for fast proximity queries. .insert(id, point) · .nearest(point, k?) · .withinRadius(point, radiusKm)
store @hyperbridge/forge/store Application

Reactive state management with signals, computed values, time-travel undo/redo, and pluggable persistence. Works server-side for agent state and client-side for UI state.

atom<T>(initial: T): Signal<T>
Creates a reactive atom. Read: atom.value. Write: atom.set(newValue). Subscribe: atom.subscribe(fn).
molecule<T>(atoms, derive): Computed<T>
Derived computed value from one or more atoms. Memoized — only recomputes when dependencies change.
class Store
Full store with deep path get/set, undo/redo history, persistence adapter, and Slice namespacing. .get(path) · .set(path, value) · .undo() · .redo()
deploy @hyperbridge/forge/deploy Application

Deployment orchestration: canary releases, blue-green switches, pre-deploy HTTP checks, and a release manager with automated rollback.

class CanaryController
.setWeight(pct) · .autoEvaluate(errorThreshold, latencyThreshold) · .promote() · .rollback()
class BlueGreenController
.deploy(env: 'blue'|'green') · .switch() · .status() · .rollback()
class PreDeployChecks
.addHttpCheck(url, expectedStatus) · .addCustomCheck(name, fn) · .run() — all checks must pass before deploy proceeds.
evolve @hyperbridge/forge/evolve Self-Evolution

Self-learning meta-layer for Web7 agents. Monitors PoO outcomes, mines AIG patterns, proposes new modules, wraps external APIs as AMP skills, and discovers new conformance test vectors — all autonomously. See RFC-0006 for the normative spec.

class AgentLearner(agentDid, opts?)
.learn(record) — ingest an outcome record. .reflect() — run reflection cycle, returns ImprovementProposal[]. .getScore() — current average PoO score. .proposals() — all accumulated proposals. .history() — reflection cycle history from agent memory.
class PatternMiner(opts?)
.mine(aigNodes) — analyse AIG intent nodes from aig.walk() or aig.lineage(). .results() — all patterns above minFrequency. .highValue() — patterns with successRate ≥ 0.80 and count ≥ 5. .lowValue() — failing patterns to route to specialist agents.
class ModuleProposer()
.fromPatterns(patterns) — generate module stubs from PatternMiner results. .stubs() — returns ModuleStub[] with import path, frequency, success rate, and full JS stub. .toRFC() — emit Markdown RFC body for all proposed modules.
class ProtocolAdaptor(agentDid)
.fromOpenAPI(spec) — parse an OpenAPI 3.x document. .toAMPSkills() — returns AMPSkill[] ready for registerSkill() in Prime. Each operation becomes one skill with a live HTTP handler. .skillCount() — number of operations found.
class ConformanceEvolver()
.observe(pooResult) — feed production PoO results. .newVectors() — all auto-discovered test vectors. .mature(minEvidence?) — vectors with enough evidence to add to the conformance suite (default: ≥ 3). .failureRate() — overall PoO failure rate observed.
function getEvolveRuntime(): EvolveRuntime
Singleton accessor. Wires all five components together. .agent(did) · .observe(poo) · .mine(nodes) · .adapt(did, openApiSpec) · .report()
Example — full reflection cycle
import { getEvolveRuntime } from "@hyperbridge/forge/evolve";
import { getAIG, verifyPoO } from "@hyperbridge/forge/amp";

const runtime = getEvolveRuntime();
const learner = runtime.agent("did:w7:skill/tax-agent");

// After each outcome:
learner.learn({ outcomeId: outcome.id, action: intent.intent.action,
                ok: poo.ok, score: poo.score });

// Periodic reflection (every 100 outcomes or 1h):
const proposals = learner.reflect();
// proposals[0] → { type: "workflow", suggestion: "Action 'file_quarterly' ..." }

// Mine the AIG for new module candidates:
runtime.mine(getAIG().walk());
console.log(runtime.report());
// { patterns: 12, highValuePatterns: 3, moduleProposals: 3, ... }