OpenHive

Example

Simple agent implementation

This guide shows how to build a complete H.I.V.E. Protocol agent. The example demonstrates an approach optimized for simplicity and fast implementation.

Complete Agent

const express = require("express");
const crypto = require("crypto");

// Agent setup
const AGENT_ID = "hive:agentid:" + crypto.randomBytes(8).toString("hex");
const PORT = 3000;

// Generate keys (save these in production!)
const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519", {
  publicKeyEncoding: { type: "spki", format: "pem" },
  privateKeyEncoding: { type: "pkcs8", format: "pem" },
});

// Capabilities
const capabilities = [
  {
    id: "text-processing",
    input: { text: "string", operation: "string" },
    output: { result: "string" },
  },
  {
    id: "math-calculation",
    input: { expression: "string" },
    output: { result: "number" },
  },
];

const app = express();
app.use(express.json());

// Helper functions
function signMessage(message) {
  return crypto
    .sign(null, Buffer.from(JSON.stringify(message)), privateKey)
    .toString("base64");
}

function processTask(capability, data) {
  if (capability === "text-processing") {
    const { text, operation } = data;
    switch (operation) {
      case "uppercase":
        return { result: text.toUpperCase() };
      case "lowercase":
        return { result: text.toLowerCase() };
      case "reverse":
        return { result: text.split("").reverse().join("") };
      default:
        throw new Error(`Unknown operation: ${operation}`);
    }
  }
  if (capability === "math-calculation") {
    return { result: Function(`"use strict"; return (${data.expression})`)() };
  }
  throw new Error(`Unknown capability: ${capability}`);
}

// Endpoints
app.post("/tasks", (req, res) => {
  try {
    const { from, type, data } = req.body;
    if (type !== "task_request") throw new Error("Invalid message type");

    const result = processTask(data.capability, data);
    const response = {
      from: AGENT_ID,
      to: from,
      type: "task_result",
      data: { task_id: data.task_id, status: "completed", result },
    };
    res.json({ ...response, sig: signMessage(response) });
  } catch (error) {
    const errorResponse = {
      from: AGENT_ID,
      to: req.body.from,
      type: "task_error",
      data: { error: "processing_failed", message: error.message },
    };
    res.status(500).json({ ...errorResponse, sig: signMessage(errorResponse) });
  }
});

app.get("/capabilities", (req, res) => res.json({ capabilities }));
app.get("/status", (req, res) =>
  res.json({
    agent_id: AGENT_ID,
    status: "online",
    capabilities: capabilities.map((c) => c.id),
  })
);

app.listen(PORT, () =>
  console.log(`🚀 Agent running at http://localhost:${PORT}`)
);

Test Client

const crypto = require("crypto");

const { privateKey: clientPrivateKey } = crypto.generateKeyPairSync("ed25519", {
  privateKeyEncoding: { type: "pkcs8", format: "pem" },
});
const CLIENT_ID =
  "hive:agentid:client-" + crypto.randomBytes(4).toString("hex");

function signMessage(message) {
  return crypto
    .sign(null, Buffer.from(JSON.stringify(message)), clientPrivateKey)
    .toString("base64");
}

async function testAgent() {
  const taskRequest = {
    from: CLIENT_ID,
    to: "hive:agentid:agent",
    type: "task_request",
    data: {
      task_id: "test-" + Date.now(),
      capability: "text-processing",
      text: "Hello!",
      operation: "uppercase",
    },
  };

  const response = await fetch("http://localhost:3000/tasks", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...taskRequest, sig: signMessage(taskRequest) }),
  });

  const result = await response.json();
  console.log("✅ Result:", result.data.result.result);
}

testAgent();

Running

# Terminal 1
npm install express
node simple-agent.js

# Terminal 2
node test-client.js

Production Enhancements

// 1. Secure keys
const privateKey = process.env.AGENT_PRIVATE_KEY;

// 2. Input validation
function validateInput(capability, data) {
  const cap = capabilities.find((c) => c.id === capability);
  return (
    cap &&
    Object.keys(cap.input).every(
      (field) => typeof data[field] === cap.input[field]
    )
  );
}

// 3. Rate limiting
const rateLimit = require("express-rate-limit");
app.use("/tasks", rateLimit({ windowMs: 60000, max: 100 }));

// 4. HTTPS
const https = require("https");
https.createServer(tlsOptions, app).listen(443);

Perfect Starting Point: This agent demonstrates all essential H.I.V.E. features. Start here and add complexity only when needed.

Security: Add proper key management, input validation, and HTTPS for production use.