@gpu-agent/hub (0.1.2)

Published 2026-10-23 18:41:13 -07:00 by donny

Installation

@gpu-agent:registry=https://gitea.dev.blueoceanswim.com/api/packages/donny/npm/
npm install @gpu-agent/hub@0.1.2
"@gpu-agent/hub": "0.1.2"

About this package

The agent hub core: framework-free, no DB; an app mounts it on its own websocket route and gives it store callbacks (gpu-agent docs/DESIGN.md §5.1).

@gpu-agent/hub

The agent hub core of the generic GPU agent (donny/gpu-agent docs/DESIGN.md §5.1): the server side of every agent connection on the worker protocol v2 (@gpu-agent/wire). Framework-free, no database, no file system: an app mounts it on its own websocket route and gives it two small interfaces. Depends on @gpu-agent/wire, zod and node:crypto only, so it runs under Bun and Node.

# .npmrc of the consuming repo
@gpu-agent:registry=https://gitea.dev.blueoceanswim.com/api/packages/donny/npm/
//gitea.dev.blueoceanswim.com/api/packages/donny/npm/:_authToken=${GITEA_NPM_TOKEN}
bun add @gpu-agent/hub@<version>      # pulls @gpu-agent/wire

Create and mount

import { createHub, hashToken, type AgentSocket } from "@gpu-agent/hub";

const hub = createHub({ store, files, log, options: { logs: true } });
hub.start(); // liveness: pings every 10 s, offline after 30 s of silence, token re-check every 10 s

With hono/bun (as ImageLab's agent-hub/routes.ts does today):

app.get("/agent", upgradeWebSocket((c) => {
  let conn: ReturnType<typeof hub.connect>;
  return {
    onOpen: (_ev, ws) => {
      const socket: AgentSocket = {
        send: (d) => ws.send(d),
        close: (code, reason) => ws.close(code, reason),
        ping: () => ws.raw?.ping(),
        remote: c.req.header("x-forwarded-for"),
      };
      conn = hub.connect(socket);
    },
    onMessage: (ev) => conn.onMessage(ev.data),
    onClose: (ev) => conn.onClose(ev.code, ev.reason),
  };
}));

With @hono/node-ws the shape is the same (ws.raw is the ws socket; ws.raw.ping()).

HubStore: tokens, status, capabilities (DESIGN §5 Q7)

The hub keeps only live state. Rows stay in the app's database, behind callbacks:

const store: HubStore = {
  verifyToken: async (token) => {                 // the app hashes and compares
    const row = await db.workerByTokenHash(hashToken(token));
    return row ? { workerId: row.id, name: row.name } : null;
  },
  tokenStillValid: async (workerId, tokenHash) => db.tokenValid(workerId, tokenHash), // every 10 s; false -> 4401
  onStatus: (workerId, online, at) => db.setStatus(workerId, online, at),
  onCapabilities: (workerId, caps) => db.saveCapabilities(workerId, caps),
};

hashToken(token) is sha256 hex of the token; generateWorkerToken() makes a 64-hex token.

HubFiles: job inputs and outputs

const files: HubFiles = {
  // one window of one input, for the agent's `input.fetch {offset, length}`; null = not there
  read: async (key, offset, length) => {
    const f = await storage.stat(key);
    return f ? { mime: f.mime, size: f.size, bytes: storage.stream(key, offset, length) } : null;
  },
  // one output, chunk by chunk, in order; the hub verifies size and the agent's sha256 before end()
  write: (info) => {
    const w = storage.openWrite(`outputs/${info.jobId}/${info.index}`);
    return { chunk: (b) => w.write(b), end: () => w.finish(), abort: () => w.discard() };
  },
};

What end() returns comes back to the job's sink as output.stored.

Jobs

hub.dispatch(workerId, { jobId, engine: "comfy", slot: "gpu0", graph, inputs, priority: "interactive", maxWaitS: 30 }, {
  queued: ({ position, waitingOn }) => {},   // waits in the agent's local queue (§4.2)
  started: ({ slot }) => {},
  progress: ({ value, max, nodeId, stage, fraction }) => {},
  output: ({ index, mime, size, sha256, name, role, stored }) => {},   // after it is stored and verified
  done: ({ outputs, durationMs, manifest, meta }) => {},
  error: ({ error, retryable }) => {},       // `worker_lost` (retryable) when the agent drops
});
hub.cancel(workerId, jobId);                 // also removes a job waiting in the local queue; no answer in cancelTimeoutMs (30 s) → error `cancelled`
hub.signal(workerId, jobId, "pull");         // job.signal into a running job

A blender job carries jobType, input and scripts instead of graph.

Workers, control, events

hub.workers();      // online workers: capabilities (v2 shape, slots + engine blocks) and the last heartbeat's slot view (§4.5)
hub.worker(id);     // one worker, online or not
await hub.control(workerId, { type: "control.restart", engineId: "comfy0", hard: true });   // -> control.result
await hub.control(workerId, { type: "control.drain", on: true });
hub.on("worker.online" | "worker.offline" | "capabilities" | "heartbeat" | "log", (e) => {});

Extensions (DESIGN §2.4)

App features ride on the core. The hub lists them in welcome.features (to agents whose build has agentExtension), routes their message types, and tells them when a worker goes away:

hub.extend("llm", {
  agentExtension: "imagelab",
  messages: [llmChunkSchema, llmDoneSchema, llmErrorSchema],   // from wire's defineMessage
  onMessage: (ctx, msg) => { /* ctx.workerId, ctx.send(...) */ },
  onWorkerLost: (workerId) => {},
});
hub.sendTo(workerId, llmRequest);                 // any extension message
await hub.request(workerId, controlInstallModel); // any request answered by control.result

Protocol

Protocol 2 only. A v1 hello is closed with 4426 upgrade required; ImageLab's v1 adapter lives in the ImageLab server during its migration (DESIGN §10). Close codes: 4401 unauthorized, 4408 timeout, 4409 superseded, 4426 upgrade required, 4000 shutdown.

Tests

MemoryStore, MemoryFiles, FakeAgent, FakeSocket, recordingSink and hubFixture are exported, so an app can drive a hub in its own tests without a network.

Releases

Bump version in packages/hub/package.json, commit to main, tag hub-v<version> (.gitea/workflows/publish.yml). The published package depends on the @gpu-agent/wire version in the workspace at that commit.

Dependencies

Dependencies

ID Version
@gpu-agent/wire 0.1.1
zod ^4.6.7
Details
npm
2026-10-23 18:41:13 -07:00
626
UNLICENSED
latest
23 KiB
Assets (1)
hub-0.1.2.tgz 23 KiB
Versions (3) View all
0.1.2 2026-10-23
0.1.1 2026-10-23
0.1.0 2026-10-23