flockd

module
v0.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: Apache-2.0

README ΒΆ

⬑ Teraflock β€” flockd

Turn idle GPUs into an inference mesh. flockd is the open-source node daemon for Teraflock: install it on a Mac, a gaming PC, or a homelab box, and your idle silicon serves open-weight LLM inference β€” earning credits you can spend on the network's OpenAI-compatible API or redeem for cash.

  • πŸ–₯ One binary, three OSes. Go daemon + CLI/TUI. llama.cpp (Metal, CUDA, ROCm, Vulkan, CPU) runs as a supervised subprocess.
  • πŸ›‘ Your machine comes first. Serves only when idle (configurable), never on battery by default, thermal guards, and instant-yield: touch the keyboard and in-flight work drains or cancels within 2 seconds. Guaranteed by tests, not vibes.
  • πŸ” Nothing to hide. Apache-2.0, no request persistence, one outbound mTLS connection, hash-verified models and runtimes. Read docs/privacy.md for exactly what the daemon can and cannot see β€” including the honest part about what node operators could theoretically observe.
  • πŸ’° Earnings you can watch tick. tera dashboard (terminal) and a built-in web dashboard at localhost:7777.

Status: beta, hosted mesh live. Nodes enroll against the hosted coordinator at tunnel.teraflock.ai and serve traffic that arrives at api.teraflock.ai (see the roadmap below). Standalone mode still works without an account.

Install

macOS / Linux:

brew install teraflock/tap/tera                   # macOS (cask)
curl -fsSL https://teraflock.ai/install.sh | sh   # Linux, or anything else

We publish a Homebrew cask, which Homebrew supports only on macOS β€” on Linux use install.sh, or the .deb / .rpm on the release.

Windows: grab the zip from the latest release (winget install Teraflock.tera coming later). On Windows tera up registers a per-user Task Scheduler logon task named flockd (no admin prompt; logs go to %USERPROFILE%\.teraflock\flockd.log), hardware detection is real β€” RAM, CPU name, NVIDIA GPUs with VRAM via nvidia-smi (cuda12), other adapters listed on the CPU lane β€” and the battery guard works; a Windows llama-server build is still in progress (epic), so until then set runtime.llama_server_path to a local build or use --standalone with the mock runtime.

Beta note: binaries are checksummed but not yet code-signed/notarized. Joining the mesh needs an invite from teraflock.ai β€” then tera login, tera up, tera dashboard.

Build from source today:

git clone https://github.com/teraflock/proto ../proto   # sibling checkout (see Development)
go build ./cmd/flockd ./cmd/tera

Quickstart (standalone, no account needed)

Run the daemon with the in-process fake coordinator and the deterministic mock model β€” the whole serving path (governor, tunnel, telemetry, API) is real:

flockd --standalone --runtime=mock

Point any OpenAI SDK at it:

export OPENAI_BASE_URL=http://localhost:7777/v1
export OPENAI_API_KEY=anything   # loopback is keyless by default

Python:

from openai import OpenAI
client = OpenAI()  # reads OPENAI_BASE_URL / OPENAI_API_KEY

stream = client.chat.completions.create(
    model="mock-8b-instruct",
    messages=[{"role": "user", "content": "hello, mesh"}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)

Node:

import OpenAI from "openai";
const client = new OpenAI();

const stream = await client.chat.completions.create({
  model: "mock-8b-instruct",
  messages: [{ role: "user", content: "hello, mesh" }],
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

/v1/completions and /v1/embeddings work too. To serve a real model, point the daemon at a llama-server binary and a model catalog:

# ~/.teraflock/config.toml
[runtime]
kind = "llamacpp"
llama_server_path = "/opt/homebrew/bin/llama-server"

[models]
manifest_path = "/path/to/catalog.yaml"   # teraflock/models format; artifact_url
                                          # may be a local file:///... (C:/... on Windows)
default = "llama-3.1-8b-instruct-q4_k_m"

Downloads land in <data_dir>/models/: a single-file model as <id>.gguf; a sharded model (catalog parts) or one with a vision projector (mmproj) in its own <id>/ directory under the upstream file names (<name>-00001-of-0000N.gguf ... and mmproj-*.gguf), because llama-server discovers the sibling shards from the name of part 1, which it is given as -m, and takes the projector via --mmproj. Every file is verified against its own pinned sha256 as it arrives; shards download one at a time, resume individually, and a finished shard is never fetched twice. models.json next to them is the daemon's index.

Then watch it work:

tera dashboard        # gorgeous terminal dashboard: tok/s sparkline, earnings ticker
tera dashboard --web  # browser dashboard (prints the auth token to paste)
tera status           # one-shot status
tera logs -f          # follow the daemon's log ring (same source as the dashboards)
tera chat             # streaming REPL against the node's own model (SSH boxes, headless nodes)
echo "hi" | tera chat -m <id>   # one-shot: answers once and exits (scriptable)
tera limits --serve idle-only   # resource policy
tera models pull <id>           # download a catalog model (progress bar, resumes)
tera models load <id>           # load / unload / default β€” the daemon does the work
scripts/smoke.sh      # the whole Phase 0 exit criterion as a script

Use it from your agent tooling

tera mcp is a local MCP server over stdio: Claude Code, Claude Desktop and Cursor can chat with the models on this node and manage them, through the same loopback API and token as the CLI. No port is opened; the client spawns tera as you.

claude mcp add --scope user teraflock -- tera mcp   # Claude Code
tera mcp --describe                                 # the 6 tools + 3 resources

Config for Claude Desktop and Cursor, the macOS PATH gotcha, and troubleshooting: docs/mcp.md. Tools that speak the OpenAI API instead need only OPENAI_BASE_URL=http://127.0.0.1:7777/v1 (above).

Joining the mesh

The hosted mesh is live: a node dials out to tunnel.teraflock.ai:443 over mTLS and serves requests that arrive at api.teraflock.ai. Onboarding runs in cohorts from the waitlist; once you have an invite link open:

tera login                     # browser handoff: claims this node to your account
tera login --claim-code CODE   # headless boxes: paste the one-shot claim code instead
tera up                        # install + start the service (launchd / systemd --user / Windows logon task)
tera dashboard                 # watch it serve

Linux, headless / over SSH: the service is a systemd --user unit, which systemd stops when your last session ends. tera up runs loginctl enable-linger for you so the node survives logout; if that needs a password (polkit), tera up still succeeds and prints the hint β€” run sudo loginctl enable-linger $USER once. tera down never disables lingering.

tera login stores the claim code (plus, for the browser flow, the PKCE verifier that makes the code redeemable from this machine only); on first start the daemon exchanges it for a 30-day client certificate from the mesh CA (rotated automatically in its last 7 days) and then holds one outbound session to the coordinator. The defaults already point at the hosted coordinator, the published runtime manifest and the model catalog, so a fresh install needs no config file. The coordinator may ask the node to download and serve catalog models that fit the budget you set with tera limits β€” every such placement is reported in tera dashboard and the activity feed, and mesh_managed = false turns it off.

Residential ISP terms

Many residential internet plans have terms that restrict running "servers" or "commercial" services on the connection. Read yours before you enroll. What a Teraflock node actually does on the network:

  • It opens one outbound, client-initiated mTLS connection to tunnel.teraflock.ai:443 and does all of its work over it. It never listens on a public port, never needs port forwarding, and is not reachable from the internet β€” the only listener is the loopback dashboard on localhost:7777.
  • The traffic is tokens, not media. A completion token is a few bytes, so a node serving flat out for an hour moves on the order of tens of megabytes, not gigabytes; while idle the tunnel exchanges a keepalive ping about every 20 seconds. The one large transfer is the one-time model download (a few GB to tens of GB per model, from the teraflock-downloads S3 bucket, and only while on AC power by default).
  • We have not yet published measured per-day totals from a production node; when we have them, they will go here.

Whether that fits your plan is between you and your ISP: you are responsible for complying with your own ISP's terms of service, and Teraflock does not represent that any particular ISP permits it. This is a description of the daemon's behaviour, not legal advice.

Resource governance promises

The whole project dies if the daemon ever makes your machine feel slow, so these are hard rules, enforced by the governor and its test suite:

promise mechanism
never serve while you're using the machine serve = idle-only (default), input-idle detection; a locked screen counts as idle immediately (macOS, Linux)
get out of the way fast instant-yield: in-flight requests drain-or-cancel within yield_grace (2s default)
never drain your battery serve_on_battery = false by default
never cook your laptop max_temp_celsius pause threshold (Linux thermal zones; no temperature source on macOS or Windows yet, so it is inert there)
you set the schedule serve = scheduled + windows like 22:00-08:00
clean exit tera uninstall --purge removes everything

Hardware support

Detection runs once at boot (internal/hardware) and picks the accelerator the runtime artifact is fetched for. Nothing here needs cgo or a vendor SDK: the daemon reads sysfs / shells out to the vendor tool.

platform GPU detection accel
macOS (Apple Silicon) system_profiler; unified memory counts as VRAM metal
macOS (Intel + discrete) system_profiler metal
Linux, NVIDIA nvidia-smi CSV cuda12
Linux, AMD sysfs (/sys/class/drm/card*/device, amdgpu driver) for id/VRAM, pci.ids for the retail name, rocm-smi (optional) to enrich rocm
Linux, any GPU with a Vulkan driver libvulkan.so.1 + a hardware ICD in /usr/share/vulkan/icd.d (RADV/AMDVLK, NVIDIA, ANV; lavapipe does not count) vulkan (secondary lane)
Linux, no usable GPU β€” cpu-avx2 (amd64) / cpu
Windows, NVIDIA nvidia-smi CSV cuda12
Windows, other adapters Win32_VideoController (listed; no VRAM/accel until a Windows Vulkan lane exists) cpu-avx2

The accel column is what the profile reports; the build that actually runs is the first lane of the preference chain cuda12 > rocm > vulkan > cpu-avx2/cpu that the pinned runtime manifest publishes (hardware.AccelPreference). An AMD box with Mesa's RADV therefore serves on vulkan until a ROCm build ships, and tera status / GET /api/v1/status (runtime_accel) show which lane is live. The daemon logs runtime accel selected accel=… reason=… on the first model load.

AMD notes: a mixed NVIDIA+AMD box serves on CUDA (NVIDIA is probed first); APUs whose VRAM carveout is under 2 GB are logged at debug and the node is placed as CPU-only; an AMD card with no amdgpu driver bound is logged and skipped. Whether a matching runtime build is published is a separate question (tera up preflight says so before installing the service); ROCm/Vulkan lanes are tracked in teraflock/runtimes.

Architecture

OpenAI SDKs ──▢ localhost:7777/v1 ─┐
tera CLI/TUI ─▢ /api/v1 ───────────┼─▢ engine ─▢ governor ─▢ runtime (llama-server subprocess / mock)
web dashboard β–Ά / (go:embed) β”€β”€β”€β”€β”€β”€β”˜        β–²
coordinator ◀── mTLS tunnel (outbound only) β”˜   (in-process fake coordinator in --standalone)

More in docs/architecture.md. Protocol contracts live in teraflock/proto (flock.tunnel.v1, flock.types.v1).

Development

flockd expects the proto repo as a sibling checkout (there's a replace github.com/teraflock/proto => ../proto in go.mod):

teraflock/
β”œβ”€β”€ proto/    git clone https://github.com/teraflock/proto
└── flockd/    this repo
go build ./... && go vet ./... && go test ./...   # everything
scripts/smoke.sh                                  # end-to-end standalone check
cd web && npm install && npm run build            # rebuild the dashboard

Note: web/dist/ is committed on purpose so go build works from a fresh clone without Node installed (it's embedded via go:embed). Rebuild it when you touch web/src.

make build|test|lint|smoke is the canonical interface (make build regenerates the management API from api/openapi.yaml first β€” never edit internal/localapi/gen/ by hand); a justfile mirrors the same verbs. make lint installs and runs the lint policy CI gates on: revive with the strict revive.toml (a verbatim copy of control-plane's canonical one β€” change it there first), staticcheck, bodyclose + noctx, and govulncheck.

Release signing

Tags are released by the release job in .github/workflows/ci.yml (goreleaser). Three signing legs are wired and each keys on its own secrets, so a tag publishes unsigned until the keys exist and signed the moment they do β€” no config change in this repo:

leg tool (runs on the Linux job) needs
macOS Developer ID + notarization of flockd/tera rcodesign APPLE_CERTIFICATE (base64 .p12), APPLE_CERTIFICATE_PASSWORD, APPLE_API_KEY_ID, APPLE_API_ISSUER, APPLE_API_KEY (base64 .p8)
Windows Authenticode on flockd.exe/tera.exe jsign + Azure Trusted Signing secrets AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET; variables AZURE_SIGNING_ENDPOINT, AZURE_SIGNING_ACCOUNT, AZURE_SIGNING_PROFILE
cosign bundle over checksums.txt cosign variable COSIGN_MODE=keyless or COSIGN_MODE=kms + COSIGN_KMS_KEY (+ AWS_ROLE_TO_ASSUME)

The SIGNING_REQUIRED variable turns "skip when missing" into "fail when missing": true requires every leg, macos,cosign a subset. Secrets that are present are always used, and a signing or notarization failure always fails the job, so a published release is never half-signed; the release notes state what was signed and how to verify it. Policy and scripts: scripts/release/ (lib.sh is the contract). Contributors without keys build the same way as before:

goreleaser check
goreleaser release --snapshot --skip=publish,sign

Roadmap

  • Phase 0 β€” single-node vertical slice. Hardware detection, supervised runtime, model manager, governor with instant-yield, OpenAI endpoint on localhost, TUI + web dashboards, fake coordinator. Exit criterion met: OPENAI_BASE_URL=http://localhost:7777/v1 works with the OpenAI SDKs (scripts/smoke.sh).
  • Phase 1 β€” mesh MVP. Hosted coordinator (tunnel.teraflock.ai), enrollment with one-shot claim codes + mTLS and cert rotation, heterogeneous nodes behind the hosted gateway (api.teraflock.ai), coordinator-driven model placement under the operator's budget. Still open: QUIC transport (the tunnel is gRPC over H2/TLS).
  • Phase 2 β€” money. Double-entry ledger, prepaid credits, earnings accrual + 7-day escrow, slashing.
  • Phase 3 β€” trust (partial). Canary duplication, timing envelopes, reputation and slashing are live. The daemon answers fingerprint challenges, but real expected-output sets are not generated yet, so fingerprint verification is not active on the hosted mesh.
  • Phase 4 β€” product (partial). Batch API and the hosted console (app.teraflock.com) shipped; redemption moves credits but the payout leg is a stub; signed auto-update is open (binaries are checksummed, not signed).

What's implemented vs stubbed, in detail: docs/HANDOFF.md.

License

Apache-2.0. The daemon runs on machines we don't control; you deserve to read every line of what it does.

Directories ΒΆ

Path Synopsis
cmd
flockd command
Command flockd is the Teraflock node daemon: hardware detection, model management, a supervised llama.cpp runtime, resource governance, the loopback OpenAI-compatible API, and the coordinator tunnel (in-process fake coordinator in --standalone / Phase 0 mode).
Command flockd is the Teraflock node daemon: hardware detection, model management, a supervised llama.cpp runtime, resource governance, the loopback OpenAI-compatible API, and the coordinator tunnel (in-process fake coordinator in --standalone / Phase 0 mode).
tera command
Command tera is the operator CLI/TUI for the Teraflock node daemon.
Command tera is the operator CLI/TUI for the Teraflock node daemon.
internal
activity
Package activity is the daemon's short operator-facing history: what happened to the model store and the runtimes, by whom (the mesh, the operator, or the daemon's own housekeeping), and why.
Package activity is the daemon's short operator-facing history: what happened to the model store and the runtimes, by whom (the mesh, the operator, or the daemon's own housekeeping), and why.
assign
Package assign executes the coordinator's ModelAssignment pushes on the operator's terms (SPEC Β§4.1, Β§4.4; plan 05).
Package assign executes the coordinator's ModelAssignment pushes on the operator's terms (SPEC Β§4.1, Β§4.4; plan 05).
browser
Package browser opens URLs in the operator's default browser.
Package browser opens URLs in the operator's default browser.
clock
Package clock abstracts time for deterministic tests (governor yield latency, backoff, rolling stats).
Package clock abstracts time for deterministic tests (governor yield latency, backoff, rolling stats).
config
Package config loads flockd configuration from defaults, an optional TOML file, and FLOCKD_-prefixed environment variables (koanf).
Package config loads flockd configuration from defaults, an optional TOML file, and FLOCKD_-prefixed environment variables (koanf).
engine
Package engine routes completion requests to loaded runtime Instances, applying governor admission and telemetry accounting.
Package engine routes completion requests to loaded runtime Instances, applying governor admission and telemetry accounting.
enroll
Package enroll manages node identity (Ed25519 keypair that never leaves the device), CSR generation, the Enroll RPC, credential storage, and the `tera login` PKCE-style browser handoff (SPEC Β§4.1, Β§6).
Package enroll manages node identity (Ed25519 keypair that never leaves the device), CSR generation, the Enroll RPC, credential storage, and the `tera login` PKCE-style browser handoff (SPEC Β§4.1, Β§6).
events
Package events is the daemon's in-process event bus: governor state changes, model download progress, and model lifecycle changes fan out to SSE subscribers (web dash, desktop app, TUI).
Package events is the daemon's in-process event bus: governor state changes, model download progress, and model lifecycle changes fan out to SSE subscribers (web dash, desktop app, TUI).
governor
Package governor is the resource-governance policy engine (SPEC Β§4.1, Β§10).
Package governor is the resource-governance policy engine (SPEC Β§4.1, Β§10).
hardware
Package hardware detects the node's compute capability and produces the typesv1.CapabilityProfile sent at enrollment and in heartbeats.
Package hardware detects the node's compute capability and produces the typesv1.CapabilityProfile sent at enrollment and in heartbeats.
localapi
Package localapi is the daemon's loopback HTTP surface on localhost:7777: the OpenAI-compatible /v1 endpoints (Phase 0 exit criterion) and the management /api/v1 REST+SSE API that the CLI, TUI and embedded web dashboard all consume (SPEC Β§A1.2: one source of truth).
Package localapi is the daemon's loopback HTTP surface on localhost:7777: the OpenAI-compatible /v1 endpoints (Phase 0 exit criterion) and the management /api/v1 REST+SSE API that the CLI, TUI and embedded web dashboard all consume (SPEC Β§A1.2: one source of truth).
localapi/client
Package client is the loopback client of the daemon's local API on localhost:7777 β€” the one client the tera CLI, the TUI, `tera mcp` and any Go tooling share (SPEC Β§A1.2: CLI, TUI and web dash are all clients of one API).
Package client is the loopback client of the daemon's local API on localhost:7777 β€” the one client the tera CLI, the TUI, `tera mcp` and any Go tooling share (SPEC Β§A1.2: CLI, TUI and web dash are all clients of one API).
localapi/client/clienttest
Package clienttest stands up a real localapi.Server on an httptest listener β€” the generated router, the mock runtime, a governor with fake signal sources, the event hub and the log ring β€” so client, CLI, TUI and `tera mcp` tests talk to the actual API contract rather than a hand-rolled fake that could drift from it.
Package clienttest stands up a real localapi.Server on an httptest listener β€” the generated router, the mock runtime, a governor with fake signal sources, the event hub and the log ring β€” so client, CLI, TUI and `tera mcp` tests talk to the actual API contract rather than a hand-rolled fake that could drift from it.
localapi/gen
Package gen provides primitives to interact with the openapi HTTP API.
Package gen provides primitives to interact with the openapi HTTP API.
logging
Package logging provides slog setup plus an in-memory ring buffer handler backing GET /api/v1/logs.
Package logging provides slog setup plus an in-memory ring buffer handler backing GET /api/v1/logs.
memory
Package memory is the daemon's model-memory accounting: the budget loaded models may use, the footprint estimate for a model before it is loaded, and the measured physical footprint of a running runtime process.
Package memory is the daemon's model-memory accounting: the budget loaded models may use, the footprint estimate for a model before it is loaded, and the measured physical footprint of a running runtime process.
modelops
Package modelops is the daemon's on-demand model operations service: catalog browsing, operator-triggered downloads (with cancel), and runtime load/unload/default switching.
Package modelops is the daemon's on-demand model operations service: catalog browsing, operator-triggered downloads (with cancel), and runtime load/unload/default switching.
models
Package models manages the local model cache: catalog manifests (teraflock/models format), resumable GGUF downloads with SHA256 verification, and LRU eviction under the operator's disk budget.
Package models manages the local model cache: catalog manifests (teraflock/models format), resumable GGUF downloads with SHA256 verification, and LRU eviction under the operator's disk budget.
runtime
Package runtime defines the inference Runtime interface (SPEC Β§A1.3) and its adapters.
Package runtime defines the inference Runtime interface (SPEC Β§A1.3) and its adapters.
runtime/llamacpp
Package llamacpp adapts a supervised llama-server subprocess to the runtime.Runtime interface (SPEC Β§A1.3: subprocess, never cgo).
Package llamacpp adapts a supervised llama-server subprocess to the runtime.Runtime interface (SPEC Β§A1.3: subprocess, never cgo).
svc
Package svc installs and controls flockd as a per-user OS service: launchd LaunchAgent (macOS), systemd --user unit (Linux) and a Task Scheduler logon task (Windows).
Package svc installs and controls flockd as a per-user OS service: launchd LaunchAgent (macOS), systemd --user unit (Linux) and a Task Scheduler logon task (Windows).
telemetry
Package telemetry assembles heartbeats and keeps rolling performance stats (tok/s, request counters) shared by the tunnel, local API and TUI.
Package telemetry assembles heartbeats and keeps rolling performance stats (tok/s, request counters) shared by the tunnel, local API and TUI.
tunnel
Package tunnel implements the node side of flock.tunnel.v1.TunnelService: the persistent, node-initiated session over which the coordinator pushes dispatches, challenges and model assignments (SPEC Β§3: nodes dial out, never listen).
Package tunnel implements the node side of flock.tunnel.v1.TunnelService: the persistent, node-initiated session over which the coordinator pushes dispatches, challenges and model assignments (SPEC Β§3: nodes dial out, never listen).
tunnel/fakecoord
Package fakecoord is an in-process fake coordinator implementing flock.tunnel.v1.TunnelService over bufconn (SPEC Β§A2.2 key seam).
Package fakecoord is an in-process fake coordinator implementing flock.tunnel.v1.TunnelService over bufconn (SPEC Β§A2.2 key seam).
update
Package update checks for a newer flockd release.
Package update checks for a newer flockd release.
Package web embeds the built local dashboard (web/dist) into the daemon binary.
Package web embeds the built local dashboard (web/dist) into the daemon binary.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL