hex

module
v0.0.0-...-17a9677 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0

README

Hex

A small internal app platform: static sites, shared backend capabilities, a browser client, and a publishing CLI. The hosting gateway authenticates API and website visitors. The server authorizes each publication against the site's owners, and files are uploaded directly to storage.

This is the github.com/crazycatviking/hex monorepo: one root Go module for the server and CLI, a TypeScript browser-client package, and shared infrastructure examples and documentation.

Packages

Path Purpose
server/ Embeddable Go HTTP API framework
server/providers/ Local storage, Azure Files publishing, Azure Blob Storage, optional S3-compatible storage and publishing, PostgreSQL, in-memory and Easy Auth identity providers, the Foundry, Anthropic and OpenAI model providers, and the Key Vault credential sealer
server/dev/ Optional local provider adapter for consuming Go applications
cmd/hex-server/ Configurable reference server executable
packages/client/ @crazycatviking/hex, a dependency-free browser JS/TS client
cmd/hex/ Standalone Go CLI entry point
internal/cli/ CLI implementation and embedded skill and development assets
deploy/ Container images, NGINX configuration and composable OpenTofu deployment examples
examples/custom-server/ Example consuming executable with its own API endpoint

Develop a platform in your own repository

Build/install the CLI from this checkout with go install ./cmd/hex, or use a prebuilt executable when available. Running the CLI requires neither Go nor Node.js. Building a consuming Go server still requires Go; hex dev --binary does not. Put your Go installation's bin directory on PATH. If you previously linked the Node CLI, remove that old global npm installation/link so hex resolves to the Go executable.

See CLI build, distribution and migration, the client package, and Just release recipes for cross-platform binaries and npm distribution.

Your executable can import server/ and use server/dev for its local configuration. Start that repository with:

hex dev --package ./cmd/platform

By default, application uploads, documents and realtime are in-memory; published website assets use local files for direct NGINX serving. No service containers are started. Use hex dev --services postgres,azurite only for explicit provider integration testing. The CLI builds your server, supplies environment variables and runs NGINX. It also supports prebuilt binaries and a hex.dev.json configuration file. No .NET or cloud account is required.

You can also run your executable directly with go run . or from an IDE: the dev.Open convenience configuration needs no mode flag. The CLI only adds orchestration. See Local development and the custom-server example. The commands below run that example using the same tooling.

Run locally

Building from source requires Go 1.25+. Local website hosting also requires NGINX. Node.js is needed for npm-based app tooling, developing the browser client, and JavaScript/browser integration tests. The CLI itself has no Node.js dependency.

go install ./cmd/hex
hex dev --package ./examples/custom-server --data-dir .hex-data

The development gateway binds to 127.0.0.1:8080. NGINX serves published files directly and proxies /api/ to Go on loopback port 8081. The NGINX routing template is shared with the Azure image and embedded in the CLI. Set NGINX_BIN if NGINX is not on PATH, and optionally NGINX_MIME_TYPES if its MIME type file is in a nonstandard location. Published site directories persist under .hex-data/; default application uploads and documents are in memory and reset on restart. The launcher prints the local site directory.

In another terminal:

hex setup http://localhost:8080 --name local
hex init my-app

Open my-app in your editor. Initialization creates hex.json, skills in .agents/skills/hex/ and .claude/skills/hex/, and managed Hex instructions in AGENTS.md and .claude/rules/hex.md. Existing instructions are preserved. A plain site can put index.html and its assets directly in the project root. For a bundled app, have your coding agent install @crazycatviking/hex and build the app with your preferred tooling. See client installation for a local tarball workflow before a registry release. From the project directory:

hex capabilities
hex publish
hex sites

Open http://my-app.localhost:8080/. Each site has its own hostname and browser origin. Modern browsers resolve *.localhost to loopback; if your environment does not, add local DNS/hosts entries. hex skills refreshes the skills and Hex-managed instruction blocks, preserving other instructions.

Run hex agents install once to make Hex the default for new web apps in Claude Code, Codex and OpenCode V2, including in empty directories, and to register the MCP server in Claude Desktop, Cursor, VS Code, Windsurf and Gemini CLI when they are installed. This installs global skills, short persistent instructions and a local hex mcp serve registration. Company installers run this automatically. The harness supplies editing, dependency installation, builds and testing; Hex supplies platform discovery, configuration and publishing. See Harness setup and local MCP for every target, diagnostics and sandbox requirements.

The default hex.json contains only the site name. Publishing detects index.html in dist/, public/, or the project root, using the current default platform profile. Projects with a package.json build script need their build output before automatic publishing. Set optional directory to pin a source ("." for the root) or platform to pin a saved profile. Add descriptive metadata as needed:

{
  "name": "my-app",
  "title": "Team dashboard",
  "description": "Daily reports and shared tasks",
  "author": "Alex"
}

hex publish sends a manifest of the site's files to the platform, which checks that you own the site (the first publisher of a new name becomes its owner) and returns upload targets for changed files. Locally the files go through the server; on Azure they go straight to Azure Files through short-lived per-file SAS URLs. hex delete my-app --yes unpublishes a site you own. See Publishing for directory selection, the protocol and authentication.

hex sites calls the read-only discovery API, which enumerates site directories containing index.html and returns names, subdomain URLs, and optional metadata. The server writes title, description, author, and a UTC publishedAt to .hex-site.json alongside the site; connection settings and local paths are excluded. Existing sites without metadata remain discoverable. Set siteBaseURL when the API origin differs from the parent site domain. App uploads and database data survive unpublishing.

Connect to a company platform

For one account spanning multiple workspaces, see optional workspace directories. Direct hex setup <workspace-url> connections remain independent and unchanged.

Use hex update to install the latest verified CLI binary while preserving platform profiles. Older releases without this command need one more installation from the landing page first.

Visit the platform's main domain, such as https://hex.smartdok.dev/. Its Go-rendered portal puts personal pins first, with bounded previews of recent, shared, owned and company apps. The App library searches everything the viewer can access and offers scopes, grid/list views and finite pages; owners keep their Manage, Analytics and Copy link shortcuts. Owners share and manage their sites from Your sites. The Build & publish page offers an installer for the visitor's OS. Download it in the signed-in browser and run the displayed command: it installs the latest CLI and saves the correct platform profile automatically. Employees do not need to run hex setup or edit configuration.

Set "discoverable": false in an app's hex.json and republish to hide its listing and exclude it from catalogue statistics. Platform-admin inventory still includes it. Its URL continues to work. See portal and installers for hosting, configuration, and release prerequisites. Locally, the landing page is at http://localhost:8080/.

Agents such as Claude Code can use hex setup <url> --json and, when user sign-in is required, hex setup --file <downloaded-file> --json. Setup saves a non-secret default profile, including the platform's configured auth type, OIDC issuer, client ID and scopes. API commands, including publishing, sign in through the browser the first time and reuse the saved session; hex login and hex logout manage it, and HEX_TOKEN overrides it. See Setup and authentication handoff.

Use deployed apps from a local agent

The CLI reuses the saved sign-in to read protected pages, application records and files, and execute operations explicitly exposed by an app backend:

hex fetch --site my-app --path /
hex data list --site my-app --collection tasks
hex files list --site my-app --prefix exports/
hex actions list --site my-app
hex actions describe --site my-app create-task
hex actions run --site my-app create-task --input @task.json

Reads respect the user's existing permissions. Changes go through actions whose JSON Schema contracts are validated by both the CLI and backend. Apps declare simple create, update and delete actions in the actions section of their hex.json, which the platform performs on their own documents without server code; a consuming server can also register Go handlers in Config.Actions, as the custom-server example does for create-task. See Agent access and app actions for the full command API and registration model.

Browser API

import { createHexClient } from '@crazycatviking/hex';

const hex = createHexClient({ site: 'my-app' });
const capabilities = await hex.capabilities();

// Who is viewing, as resolved by the hosting gateway; null when the
// deployment has no identity resolver.
const identity = await hex.identity();

// What the viewer may do on this site, for showing or hiding controls. The
// platform still checks every request.
const permissions = await hex.permissions();

await hex.files.upload('notes.txt', new Blob(['Hello']));
const file = await hex.files.download('notes.txt');
const files = await hex.files.list();
await hex.files.delete('notes.txt');

const tasks = hex.db.collection<{ title: string; done: boolean }>('tasks');
const task = await tasks.create({ title: 'Ship the app', done: false }); // task.createdBy is the creator's identity ID
await tasks.set(task.id, { title: 'Ship the app', done: true });
const page = await tasks.list({ limit: 100 });

const channel = hex.realtime.connect('updates', {
  onMessage: message => console.log(message),
  onClose: () => console.log('Disconnected'),
});
await channel.ready;
await channel.send({ type: 'tasks-changed' });
channel.close();

Clients use the current origin by default. Local frontend development should proxy /api/ and WebSockets to the server rather than introduce cross-origin cookie authentication. baseURL is available for non-browser clients and tests.

Integrations, AI and automations

A platform can register integrations — typed endpoints over third-party systems such as GitHub, Slack or a CRM — that apps call through hex.integrations.call(...). Each endpoint needs a permission granted to the caller, typically through Entra ID app roles, and sensitive integrations need a platform admin to approve each site. Integrations either use a platform credential or, where the third-party system has its own per-user permissions, the caller's own connected account, which the platform's OAuth broker keeps for them. See Integrations, grants and connected accounts.

The AI capability streams model responses — text, thinking and tool calls — through hex.ai.stream(...) and hex.ai.conversation(...), with the platform's provider (Azure AI Foundry, Anthropic or OpenAI-compatible). Models can use integration endpoints as tools, run on the server with the caller's own grants. See AI.

Automations are required JavaScript modules that run on a schedule or on demand. JSON definitions in an app's hex.json or automations/ directory contain only metadata and a script reference; all workflow logic lives in JavaScript. Scripts run in isolated QuickJS WebAssembly instances and access integrations, actions, AI and the site's documents only through authorized Hex APIs. Editor types are available from @crazycatviking/hex/automations; no TypeScript transpilation is involved. Automations run as the site, with grants of their own. See Automations.

hex integrations list --site my-app
hex connections connect atlassian
hex ai ask --site my-app --model claude-opus-5-5 "Summarize open bugs" --tools azuredevops.bugs
hex automations test weekly-report

Embed the Go framework

package main

import (
    "log"
    "net/http"

    hex "github.com/crazycatviking/hex/server"
    "github.com/crazycatviking/hex/server/providers/local"
    "github.com/crazycatviking/hex/server/providers/memory"
)

func main() {
    if err := run(); err != nil {
        log.Fatal(err)
    }
}

func run() error {
    files, err := local.New("data/files")
    if err != nil {
        return err
    }
    defer func() {
        if err := files.Close(); err != nil {
            log.Printf("close file storage: %v", err)
        }
    }()

    sites, err := local.New("data/sites")
    if err != nil {
        return err
    }
    defer func() {
        if err := sites.Close(); err != nil {
            log.Printf("close site storage: %v", err)
        }
    }()

    handler := hex.New(hex.Config{
        Files:     files,
        Sites:     sites,
        Publisher: sites,
        Database:  memory.NewDatabase(),
        Realtime:  memory.NewRealtime(),
    })
    return http.ListenAndServe("127.0.0.1:8080", handler)
}

Omit a provider to disable that capability. GET /api/hex/capabilities reports which built-ins are enabled. hex.New returns an API-only http.Handler; provider credentials, connection pools and lifecycle remain under the host application's control. Mount site storage in NGINX and route each hostname to public/sites/<name>/. Set Config.SiteBaseURL for directory-derived URLs. The Go handler has no website-serving route; it receives publications only through Config.Publisher.

The interfaces are defined in server/storage.go:

  • SiteDirectory: read-only enumeration of actual site directories. The local provider reads the Azure Files share mounted by Go and NGINX, or a local development directory.
  • SitePublisher and optional DirectUploader (in server/publishing.go): writes published site files for authorized publishers. local.Store writes a local directory; azurefiles.Publisher writes Azure Files with a managed identity and signs per-file upload URLs.
  • ObjectStore: uploaded application objects, with writes, reads, prefix listing and deletion. This is separate from publishing; Azure Blob supplies app upload storage in the example.
  • Optional S3-compatible provider: consuming Go servers can explicitly wire s3.Store for ObjectStore, SitePublisher, DirectUploader, SiteDirectory and metadata reads, using separate instances/prefixes for site and file storage. It is not a reference-executable default, requires a separate object-serving gateway (no S3 mount), and does not provide atomic deployments.
  • Database: site-scoped JSON documents with keyset pagination and server-recorded creators. The PostgreSQL provider works with Azure Database for PostgreSQL or another PostgreSQL installation.
  • Realtime: subscriptions and JSON broadcasts, allowing a future distributed broker implementation without changing the browser API.
  • IdentityResolver and AccessStore (in server/identity.go and server/access.go): optional gateway-forwarded caller identity and per-site access policies. See Identity and site access control.
  • IntegrationRegistry, IntegrationStore and AutomationStore (in server/integrations.go, server/connections.go and server/automations.go): third-party integrations, approvals and connected accounts, and scheduled automations. AIProvider (in server/ai.go) answers model requests, and AIUsageStore (in server/ai_usage.go) keeps each call's usage and cost and the monthly AI budgets. The PostgreSQL and in-memory providers implement the stores.
  • AnalyticsStore (in server/analytics.go): optional platform-owned user activity, publishing lifecycle and daily nginx traffic aggregates. Platform admins use /admin; site owners get an Analytics tab. See platform analytics for independent PostgreSQL storage and traffic collection.

See the architecture and API contract for provider semantics and the hosting contract for platform independence and reference-server configuration.

Infrastructure examples

OpenTofu examples compose cloud-specific modules around the framework. The initial Azure Container Apps example defaults to authenticated site hosting and lets you select additional capabilities:

capabilities = {
  sites    = true
  files    = true
  database = "managed"
  realtime = true
}

Use database = "external" with your own PostgreSQL URL, or "none" to disable the database API. Disabling a capability also omits its managed resources in this example. The reference server has explicit provider selections so disabled capabilities do not fall back to local or in-memory services.

The infrastructure is an example to copy and adapt, not the only way to host Hex. The framework/client do not depend on Container Apps, Azure resource IDs, or Entra. A future GCP/Quick-style deployment can use the same API with GCP providers and a different authenticated hosting layer.

Verification

Use gofmt for Go, Prettier for JS/TS and project files, and tofu fmt for infrastructure. Formatting handles layout; the structure and naming principles in AGENTS.md still apply.

gofmt -w cmd internal server examples
npm run format
tofu fmt -recursive deploy/opentofu

npm run format:check checks JS/TS formatting without editing files.

go test -race ./...
go vet ./...
npm ci
npm run build
npm test
npm run test:e2e
npm run test:local

The end-to-end test requires NGINX. It starts Go and NGINX, publishes through the API, exercises change detection, discovery, application APIs and WebSockets, unpublishes, then stops Go and verifies that publishing fails cleanly. CLI tests publish against a real in-process server, filter source files, handle file/directory transitions, and upload through pre-signed Azure Files URLs to a fake share without sending credentials. Go tests cover access policies, data rules, publishing authorization, filesystem discovery, realtime, namespaces and application-upload limits. Live Azure Files publishing is not tested locally.

Initial scope

  • Sites use separate origins such as https://demo.hex.example.com/, isolating localStorage, sessionStorage and IndexedDB. App origins can use only their own data namespace, identity, capabilities and permissions; management APIs use the platform API host. User access policies are checked in addition to origin restrictions. See Subdomain hosting.
  • Sites are open to every authenticated user unless their access policy says otherwise. A policy names owners, editors and viewers, restricts URL path prefixes, and sets read/write rules per collection, file prefix and realtime channel, including creator-only documents. It covers the site's assets, APIs and discovery listing. Apps read the viewer through hex.identity() and hex.permissions().
  • Only a site's owners publish it. The first publisher of a new name becomes its owner; HEX_PUBLISHER_GROUPS limits who may claim names.
  • The in-process realtime provider requires one backend replica. Messages are transient; clients handle reconnects and refresh state themselves.
  • Documents are JSON objects, at most 1 MiB. set replaces the entire document. Lists are ordered by ID, with up to 100 results per page. There is no query language or automatic database-change feed.
  • Application file uploads through the API default to 32 MiB and are buffered in memory. Site publishing has its own limits (by default 256 MiB per file and 2 GiB per site). File and site listings are currently unpaginated.
  • Publishing replaces one site's changed files in place, uploads index.html last and deletes obsolete files on completion. It is not a transactional whole-site replacement. Concurrent publishers are not coordinated. Republish after an interrupted publication.
  • Integrations, AI and automations are frameworks: the platform registers integrations in Go and configures a model provider, and apps use them through typed endpoints. See Integrations, AI and Automations. The in-process AI token budget and integration cache are per instance.

Directories

Path Synopsis
cmd
hex command
hex-server command
examples
custom-server command
internal
automationjs
Package automationjs executes JavaScript in fresh, capability-restricted QuickJS WebAssembly instances.
Package automationjs executes JavaScript in fresh, capability-restricted QuickJS WebAssembly instances.
cli
sse
Package sse decodes the bounded server-sent events used by AI providers.
Package sse decodes the bounded server-sent events used by AI providers.
dev
providers/anthropic
Package anthropic is a Hex AI provider for the Anthropic Messages API, called over plain HTTP so the same code serves the Claude API and Claude deployments in Azure AI Foundry (whose base URL and authentication differ; the Go SDK does not support Foundry).
Package anthropic is a Hex AI provider for the Anthropic Messages API, called over plain HTTP so the same code serves the Claude API and Claude deployments in Azure AI Foundry (whose base URL and authentication differ; the Go SDK does not support Foundry).
providers/azurefiles
Package azurefiles publishes sites to an Azure Files share.
Package azurefiles publishes sites to an Azure Files share.
providers/easyauth
Package easyauth resolves request identities from the headers that Azure App Service and Container Apps built-in authentication ("Easy Auth") injects into proxied requests.
Package easyauth resolves request identities from the headers that Azure App Service and Container Apps built-in authentication ("Easy Auth") injects into proxied requests.
providers/foundry
Package foundry is a Hex AI provider for models deployed in Azure AI Foundry.
Package foundry is a Hex AI provider for models deployed in Azure AI Foundry.
providers/keyvault
Package keyvault seals connected-account tokens with envelope encryption under an Azure Key Vault key.
Package keyvault seals connected-account tokens with envelope encryption under an Azure Key Vault key.
providers/openai
Package openai is a Hex AI provider for OpenAI-compatible APIs, including the Azure OpenAI v1 API and other models in Azure AI Foundry ({endpoint}/openai/v1).
Package openai is a Hex AI provider for OpenAI-compatible APIs, including the Azure OpenAI v1 API and other models in Azure AI Foundry ({endpoint}/openai/v1).
providers/s3
Package s3 provides opt-in S3-compatible object storage and site publishing.
Package s3 provides opt-in S3-compatible object storage and site publishing.

Jump to

Keyboard shortcuts

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