HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
fix: the container never actually ran — four defects the first boot found
richard-epsillaa12eae0b4564
diff --git a/.gitignore b/.gitignoreindex ebf627ae..f07c04ce 100644--- a/.gitignore+++ b/.gitignore@@ -18,3 +18,6 @@ dist/__pycache__/*.pyc.DS_Store++# TypeScript incremental build cache+*.tsbuildinfodiff --git a/LICENSE b/LICENSEindex 44b9c847..7ba09199 100644--- a/LICENSE+++ b/LICENSE@@ -1,6 +1,6 @@MIT License-Copyright (c) 2026 Epsilla+Copyright (c) 2026 HarnessRouterPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealdiff --git a/NOTICE b/NOTICEindex b5f57afb..fcfb8ec2 100644--- a/NOTICE+++ b/NOTICE@@ -1,5 +1,5 @@HarnessRouter-Copyright (c) 2026 Epsilla+Copyright (c) 2026 HarnessRouterThis product is licensed under the MIT License (see LICENSE).diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 813d2809..8bd74126 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -9,6 +9,12 @@ set -euo pipefailDATA_DIR="${HR_DATA_DIR:-/data}"mkdir -p "$DATA_DIR"+# Our own processes must run on the image's interpreter, never on whatever a backend puts on+# PATH. Hermes installs into its own venv and that venv's bin joins PATH below so the runner can+# spawn `hermes` — but that venv has none of the gateway's dependencies, so resolving `python3`+# through PATH would start the gateway inside it and fail on the first import.+PY=/usr/local/bin/python3+# ── configuration: self-contained defaults ────────────────────────────────────# Local storage: SQLite + files on the mounted volume. No external services.export HR_BACKING="${HR_BACKING:-local}"@@ -32,7 +38,7 @@ export HR_SANDBOX_TRUST="${HR_SANDBOX_TRUST:-owner}"# The gateway signs its own internal calls. Generated per container if not supplied, so a# default install has no shared secret and nothing to leak; it never leaves this process tree.if [ -z "${HARNESS_INTERNAL_KEY:-}" ]; then- export HARNESS_INTERNAL_KEY="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"+ export HARNESS_INTERNAL_KEY="$("$PY" -c 'import secrets; print(secrets.token_hex(32))')"fiexport GATEWAY_URL="${GATEWAY_URL:-http://127.0.0.1:8080}"@@ -51,31 +57,40 @@ export PATH="$TOOLS/bin:$PATH"export NODE_PATH="$TOOLS/lib/node_modules"export HR_BACKENDS="${HR_BACKENDS:-claude,codex,hermes}"+wanted() { [[ ",$HR_BACKENDS," == *",$1,"* ]]; }+# The executable IS the definition of "installed" — an installer that exits 0 without producing+# one is still a failed install, and reporting it as success is how a backend silently vanishes+# from the console with no explanation.+backend_bin() {+ case "$1" in+ claude) echo "$TOOLS/bin/claude" ;;+ codex) echo "$TOOLS/bin/codex" ;;+ hermes) echo "$TOOLS/venv/bin/hermes" ;;+ esac+}+install_backends() {mkdir -p "$TOOLS"- local want="$HR_BACKENDS"- if [[ ",$want," == *",claude,"* ]] && [ ! -x "$TOOLS/bin/claude" ]; then+ # -g is what creates $TOOLS/bin/<cmd>; --prefix alone just drops a node_modules tree with no+ # entry point, which npm reports as success.+ if wanted claude && [ ! -x "$(backend_bin claude)" ]; thenecho "[harnessrouter] installing Claude Code (Anthropic's terms apply)…"- npm install --prefix "$TOOLS" --global-style --no-audit --no-fund \- @anthropic-ai/claude-code >/dev/null 2>&1 \- || echo "[harnessrouter] WARN: Claude Code install failed — that backend is unavailable"+ npm install -g --prefix "$TOOLS" --no-audit --no-fund @anthropic-ai/claude-code >/dev/null 2>&1 || truefi- if [[ ",$want," == *",codex,"* ]] && [ ! -x "$TOOLS/bin/codex" ]; then+ if wanted codex && [ ! -x "$(backend_bin codex)" ]; thenecho "[harnessrouter] installing Codex (Apache-2.0)…"- npm install --prefix "$TOOLS" --global-style --no-audit --no-fund \- @openai/codex >/dev/null 2>&1 \- || echo "[harnessrouter] WARN: Codex install failed — that backend is unavailable"+ npm install -g --prefix "$TOOLS" --no-audit --no-fund @openai/codex >/dev/null 2>&1 || truefi- if [[ ",$want," == *",hermes,"* ]] && [ ! -x "$TOOLS/venv/bin/hermes" ]; then+ if wanted hermes && [ ! -x "$(backend_bin hermes)" ]; thenecho "[harnessrouter] installing Hermes (check its upstream license before use)…"- python3 -m venv "$TOOLS/venv" >/dev/null 2>&1 \- && "$TOOLS/venv/bin/pip" install --no-cache-dir -q \- "hermes-agent==0.19.0" anthropic mcp >/dev/null 2>&1 \- || echo "[harnessrouter] WARN: Hermes install failed — that backend is unavailable"+ { "$PY" -m venv "$TOOLS/venv" \+ && "$TOOLS/venv/bin/pip" install --no-cache-dir -q "hermes-agent==0.19.0" anthropic mcp; } \+ >/dev/null 2>&1 || truefi+[ -d "$TOOLS/venv/bin" ] && export PATH="$TOOLS/venv/bin:$PATH"# Hermes otherwise tries to install its own dependencies mid-turn.export HERMES_DISABLE_LAZY_INSTALLS=1@@ -87,22 +102,22 @@ pids=()cleanup() { trap - TERM INT; for p in "${pids[@]:-}"; do kill "$p" 2>/dev/null || true; done; }trap cleanup TERM INT EXIT-avail=""+avail=""; missing=""for b in claude codex hermes; do- case "$b" in- claude) [ -x "$TOOLS/bin/claude" ] && avail="$avail claude" ;;- codex) [ -x "$TOOLS/bin/codex" ] && avail="$avail codex" ;;- hermes) [ -x "$TOOLS/venv/bin/hermes" ] && avail="$avail hermes" ;;- esac+ wanted "$b" || continue+ if [ -x "$(backend_bin "$b")" ]; then avail="$avail $b"; else missing="$missing $b"; fidoneecho "[harnessrouter] data=$DATA_DIR backends available:${avail:- none}"+if [ -n "$missing" ]; then+ echo "[harnessrouter] WARN: requested but not installed:$missing — those backends cannot run"+fi# runner (loopback only)-( cd /app/runner && exec python3 -m uvicorn server:app --host 127.0.0.1 --port 8081 --log-level warning ) &+( cd /app/runner && exec "$PY" -m uvicorn server:app --host 127.0.0.1 --port 8081 --log-level warning ) &pids+=($!)# gateway (loopback only)-( cd /app/gateway && exec python3 -m uvicorn app:app --host 127.0.0.1 --port 8080 --log-level warning ) &+( cd /app/gateway && exec "$PY" -m uvicorn app:app --host 127.0.0.1 --port 8080 --log-level warning ) &pids+=($!)# Wait for the gateway before the UI starts serving, so a first page load never races adiff --git a/gateway/app.py b/gateway/app.pyindex b4417be1..309267bf 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -5,7 +5,7 @@ Responsibilities (see docs/technical/HARNESS_AS_A_SERVICE_DESIGN.md):turns into the in-sandbox runner (`{POOL}/turn?identifier=<session_id>`, Entra tokenaud `dynamicsessions.io` via the gateway's managed identity).- Credential BROKER over the existing Vault service: resolve a provider *connection*- (org-own first, Epsilla `global` pool fallback) and try an ordered fallback chain.+ (org-own first, a shared `global` pool as fallback) and try an ordered fallback chain.- Concurrency gating (global + per-tenant); session state externalized to VectorGraph(`HarnessSession` vertex) so any replica serves any session.@@ -687,7 +687,7 @@ def _vault_tenant_ok(org: str | None) -> bool:def _tenants_for(org: str | None) -> list[str]:- """Resolution order: the org's own keys first (bill to the org), then Epsilla's pool.+ """Resolution order: the org's own keys first (bill to the org), then the shared pool.Skip the org tenant if it isn't a valid vault tenant (e.g. dotted ids) -> straight to global."""return ([org] if _vault_tenant_ok(org) else []) + [GLOBAL_TENANT]diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex e22506e9..cc1270b9 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -14,7 +14,7 @@"next": "^15.1.0","react": "^19.0.0","react-dom": "^19.0.0",- "reifyui": "^0.2.0"+ "reifyui": "^0.3.0"},"devDependencies": {"@types/node": "^22",@@ -1882,9 +1882,9 @@}},"node_modules/reifyui": {- "version": "0.2.0",- "resolved": "https://registry.npmjs.org/reifyui/-/reifyui-0.2.0.tgz",- "integrity": "sha512-UZRx8Hm4zhS53vvm62r1P7+/Uxi+C+4MgYRxoG6JERFKbZYjPorilMH3kzi6A7xVRhaPfNGdCCvGzoyWV4mA+g==",+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/reifyui/-/reifyui-0.3.0.tgz",+ "integrity": "sha512-9KyyJVROvLHi4welDz5MWkqg5uFraQIZI5Wp+ftKlZvhz2T3PiaQ7eI/uayEnoBtOmJolK9lIk4moDby4rudcg==","license": "MIT","engines": {"node": ">=18"diff --git a/ui/package.json b/ui/package.jsonindex 84f0f082..c268a9cf 100644--- a/ui/package.json+++ b/ui/package.json@@ -15,7 +15,7 @@"next": "^15.1.0","react": "^19.0.0","react-dom": "^19.0.0",- "reifyui": "^0.2.0"+ "reifyui": "^0.3.0"},"devDependencies": {"@types/node": "^22",diff --git a/ui/public/favicon.svg b/ui/public/favicon.svgnew file mode 100644index 00000000..a9d7c159--- /dev/null+++ b/ui/public/favicon.svg@@ -0,0 +1,16 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="HarnessRouter">+ <rect width="32" height="32" rx="7" fill="#285AFF"/>+ <!-- One input fanning out to three backends: the router, in the smallest form that reads at 16px. -->+ <g fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round">+ <path d="M7 16h5"/>+ <path d="M12 16c4 0 4-7 8-7"/>+ <path d="M12 16h8"/>+ <path d="M12 16c4 0 4 7 8 7"/>+ </g>+ <g fill="#fff">+ <circle cx="7" cy="16" r="2.6"/>+ <circle cx="22" cy="9" r="2.3"/>+ <circle cx="22" cy="16" r="2.3"/>+ <circle cx="22" cy="23" r="2.3"/>+ </g>+</svg>diff --git a/ui/src/app/api/cloud/push/route.ts b/ui/src/app/api/cloud/push/route.tsindex d00bedbe..418268d9 100644--- a/ui/src/app/api/cloud/push/route.ts+++ b/ui/src/app/api/cloud/push/route.ts@@ -10,21 +10,16 @@// is never written to disk, never logged, and never stored server-side — if you close the tab,// it is gone. That is why the key is a parameter here rather than instance configuration.import { NextRequest } from 'next/server';+import { harnessBody, type Harness } from '@/lib/harness';const DEFAULT_CLOUD = 'https://api.harnessrouter.ai';interface PushBody {apiKey: string;cloudUrl?: string;- harnesses: Record<string, unknown>[];+ harnesses: Harness[];}-/** Fields that describe a harness's behaviour. Local-only bookkeeping (ids, timestamps,- * workspace, org) is intentionally dropped so the hosted side mints its own. */-const PORTABLE = ['name', 'base', 'defaultModel', 'systemPrompt', 'tools', 'skills',- 'mcpServers', 'maxStep', 'timeoutSeconds', 'additionalHeaders',- 'baseLabel', 'instructions'];-export const runtime = 'nodejs';export async function POST(req: NextRequest) {@@ -43,8 +38,10 @@ export async function POST(req: NextRequest) {const results: { name: string; ok: boolean; id?: string; error?: string }[] = [];for (const h of list) {- const payload: Record<string, unknown> = {};- for (const k of PORTABLE) if (h[k] !== undefined && h[k] !== null) payload[k] = h[k];+ // The same mapping the local console writes with — the hosted API takes the same body, which+ // is what makes promotion a copy rather than a translation. Local bookkeeping (id, timestamps,+ // org, workspace) isn't in it, so the hosted side mints its own.+ const payload = harnessBody(h);const name = String(payload.name || 'untitled');try {const r = await fetch(`${base}/v1/harnesses`, {diff --git a/ui/src/app/api/gw/[...path]/route.ts b/ui/src/app/api/gw/[...path]/route.tsindex 2c9ef643..2e12d230 100644--- a/ui/src/app/api/gw/[...path]/route.ts+++ b/ui/src/app/api/gw/[...path]/route.ts@@ -5,30 +5,51 @@// stay bound to the container's internal network instead of being published to the host. The// only thing published is this UI.//-// It adds NO credentials. There is nothing to add: the gateway runs with identity off, and the-// provider keys live server-side in the gateway's secret store — they never reach the browser-// and therefore never pass through here.+// It carries exactly one credential, and only ever server-side: the gateway's internal key,+// generated per container and never sent to the browser. This is the same service-to-service+// mechanism the hosted deployment uses — the gateway trusts the caller's identity headers only+// when that key is present, which is why they are set HERE and not forwarded from the browser.+// Provider keys are not involved at all: they live in the gateway's secret store and never+// travel this path.import { NextRequest } from 'next/server';+import { LOCAL_MEMBER, LOCAL_ORG } from '@/lib/identity';const GATEWAY = (process.env.GATEWAY_URL || 'http://127.0.0.1:8080').replace(/\/$/, '');+const INTERNAL_KEY = process.env.HARNESS_INTERNAL_KEY || '';// Streaming turns must not be buffered by the runtime, so this runs on Node and pipes the body.export const runtime = 'nodejs';export const dynamic = 'force-dynamic';async function proxy(req: NextRequest, path: string[]) {+ // Without the key the gateway rejects everything as unauthenticated, which looks like a bug in+ // the console rather than a missing variable. Say what is actually wrong.+ if (!INTERNAL_KEY) {+ return new Response(+ JSON.stringify({ detail: 'HARNESS_INTERNAL_KEY is not set for the console process' }),+ { status: 500, headers: { 'content-type': 'application/json' } },+ );+ }+const search = req.nextUrl.search || '';const url = `${GATEWAY}/${path.join('/')}${search}`;const headers = new Headers();// Forward only what the gateway reads. Copying blindly would drag along hop-by-hop headers// (host, connection, content-length) that break a proxied streaming response.- for (const k of ['content-type', 'accept', 'x-harness-org', 'x-harness-member',- 'x-harness-workspace', 'x-harness-workspace-default', 'x-harness-id',- 'idempotency-key']) {+ //+ // Note which headers are NOT in this list: org and member. Those are set below from server+ // constants, so a request from the browser cannot claim a different identity than the one+ // this instance has. Workspace is browser-chosen because it is a user-facing scope the+ // operator switches between, not a trust boundary.+ for (const k of ['content-type', 'accept', 'x-harness-workspace',+ 'x-harness-workspace-default', 'x-harness-id', 'idempotency-key']) {const v = req.headers.get(k);if (v) headers.set(k, v);}+ headers.set('x-harness-org', LOCAL_ORG);+ headers.set('x-harness-member', LOCAL_MEMBER);+ headers.set('x-harness-internal', INTERNAL_KEY);const method = req.method.toUpperCase();const body = method === 'GET' || method === 'HEAD' ? undefined : await req.arrayBuffer();diff --git a/ui/src/app/harnesses/[id]/page.tsx b/ui/src/app/harnesses/[id]/page.tsxindex 90a7fafc..3b0994a1 100644--- a/ui/src/app/harnesses/[id]/page.tsx+++ b/ui/src/app/harnesses/[id]/page.tsx@@ -2,6 +2,7 @@import { useEffect, useState } from 'react';import { useParams, useRouter } from 'next/navigation';+import { useDialog } from 'reifyui';import {deleteHarness, getHarness, listModels, updateHarness, type Harness, type ModelCatalog,} from '@/lib/api';@@ -9,6 +10,7 @@ import {export default function HarnessDetail() {const { id } = useParams<{ id: string }>();const router = useRouter();+ const dialog = useDialog();const [h, setH] = useState<Harness | null>(null);const [draft, setDraft] = useState<Harness | null>(null);const [catalog, setCatalog] = useState<ModelCatalog>({});@@ -32,13 +34,8 @@ export default function HarnessDetail() {const save = async () => {setSaving(true); setErr(''); setMsg('');try {- const saved = await updateHarness(id, {- name: draft.name,- defaultModel: draft.defaultModel,- systemPrompt: draft.systemPrompt,- maxStep: draft.maxStep,- timeoutSeconds: draft.timeoutSeconds,- });+ // The whole draft, not the edited subset: a write replaces the record.+ const saved = await updateHarness(id, draft);setH(saved); setDraft(saved); setMsg('Saved.');} catch (e) {setErr(String((e as Error).message || e));@@ -48,7 +45,13 @@ export default function HarnessDetail() {};const remove = async () => {- if (!window.confirm(`Delete "${draft.name}"? Its tasks are kept but it can no longer run.`)) return;+ const ok = await dialog.confirm({+ title: `Delete "${draft.name}"?`,+ message: 'Its tasks are kept, but it can no longer run.',+ destructive: true,+ confirmLabel: 'Delete',+ });+ if (!ok) return;try {await deleteHarness(id);router.push('/harnesses');diff --git a/ui/src/app/layout.tsx b/ui/src/app/layout.tsxindex a91a0ad1..9d4f231b 100644--- a/ui/src/app/layout.tsx+++ b/ui/src/app/layout.tsx@@ -2,22 +2,27 @@ import type { Metadata } from 'next';import 'reifyui/styles/themes/light.css';import 'reifyui/styles/chat.css';import 'reifyui/styles/tasks.css';+import 'reifyui/styles/dialog.css';import './globals.css';+import { Providers } from '@/components/Providers';import { Nav } from '@/components/Nav';export const metadata: Metadata = {title: 'HarnessRouter',description: 'Self-hosted harness management',+ icons: { icon: '/favicon.svg' },};export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en"><body>- <div className="shell">- <Nav />- <main className="main">{children}</main>- </div>+ <Providers>+ <div className="shell">+ <Nav />+ <main className="main">{children}</main>+ </div>+ </Providers></body></html>);diff --git a/ui/src/app/tasks/page.tsx b/ui/src/app/tasks/page.tsxindex 51075bb4..10f40ddc 100644--- a/ui/src/app/tasks/page.tsx+++ b/ui/src/app/tasks/page.tsx@@ -3,7 +3,7 @@import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'next/navigation';import {- ChatMessages, Composer, TaskList, createConversationStore, pumpResponsesStream,+ ChatMessages, Composer, TaskList, createConversationStore, pumpResponsesStream, useDialog,} from 'reifyui';import {cancelTask, deleteTask, listHarnesses, listTasks, loadTurns, streamTurn,@@ -12,6 +12,7 @@ import {function TasksInner() {const params = useSearchParams();+ const dialog = useDialog();const [harnesses, setHarnesses] = useState<Harness[]>([]);const [harnessId, setHarnessId] = useState(params.get('h') || '');const [sid, setSid] = useState<string | null>(null);@@ -74,7 +75,13 @@ function TasksInner() {};const removeTask = async (t: TaskCard) => {- if (!window.confirm('Delete this task?')) return;+ const ok = await dialog.confirm({+ title: 'Delete this task?',+ message: `"${t.title || 'Untitled task'}" and its conversation will be removed. This cannot be undone.`,+ destructive: true,+ confirmLabel: 'Delete',+ });+ if (!ok) return;try {await deleteTask(t.session_id);if (t.session_id === sid) setSid(null);diff --git a/ui/src/components/Nav.tsx b/ui/src/components/Nav.tsxindex b40c2796..23fe0dfb 100644--- a/ui/src/components/Nav.tsx+++ b/ui/src/components/Nav.tsx@@ -3,6 +3,7 @@import Link from 'next/link';import { usePathname } from 'next/navigation';import { useEffect, useState } from 'react';+import { useDialog } from 'reifyui';import {DEFAULT_WORKSPACE, currentWorkspace, listWorkspaces, saveWorkspaces, setCurrentWorkspace,type Workspace,@@ -15,20 +16,35 @@ import {* "stale list from the previous workspace" bugs. */export function Nav() {const path = usePathname();+ const dialog = useDialog();const [list, setList] = useState<Workspace[]>([DEFAULT_WORKSPACE]);const [ws, setWs] = useState(DEFAULT_WORKSPACE.id);useEffect(() => { setList(listWorkspaces()); setWs(currentWorkspace()); }, []);- const onSwitch = (id: string) => {+ const onSwitch = async (id: string) => {if (id === '__new') {- const name = window.prompt('New workspace name');+ // Keep the select showing the workspace we're actually in while the dialog is open, so a+ // cancel doesn't leave "+ New workspace…" selected.+ setWs(currentWorkspace());+ const name = await dialog.prompt({+ title: 'New workspace',+ label: 'Name',+ placeholder: 'Backend rewrite',+ help: 'A workspace scopes its own harnesses and tasks.',+ validate: (v) => {+ const t = v.trim();+ if (!t) return 'Give the workspace a name.';+ const slug = t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ if (!slug) return 'Use at least one letter or number.';+ if (listWorkspaces().some((w) => w.id === slug)) return 'A workspace with that name already exists.';+ return null;+ },+ });if (!name?.trim()) return;- const id2 = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')- || `ws-${Date.now()}`;- const next = [...listWorkspaces(), { id: id2, name: name.trim() }];- saveWorkspaces(next);- setCurrentWorkspace(id2);+ const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ saveWorkspaces([...listWorkspaces(), { id: slug, name: name.trim() }]);+ setCurrentWorkspace(slug);window.location.reload();return;}diff --git a/ui/src/components/Providers.tsx b/ui/src/components/Providers.tsxnew file mode 100644index 00000000..1d91a689--- /dev/null+++ b/ui/src/components/Providers.tsx@@ -0,0 +1,12 @@+'use client';++import { DialogHost } from 'reifyui';++/** Client-side context that has to wrap the whole tree.+ *+ * The root layout is a server component, so anything using React context lives here instead.+ * DialogHost is what lets any page `await confirm(...)` for destructive actions — deleting a+ * harness, deleting a task — without a browser popup. */+export function Providers({ children }: { children: React.ReactNode }) {+ return <DialogHost>{children}</DialogHost>;+}diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex 8925b46c..b918a65f 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -8,11 +8,10 @@// /v1 routes, the same workspace headers, the same Responses SSE shape. That is what makes// "push my harnesses to the cloud" a straight copy later rather than a translation.-/** The implicit single tenant. The gateway still scopes every record by org, so keeping a real- * value (rather than empty) means the same storage layout works if this instance is ever- * pointed at a multi-tenant backing. */-export const LOCAL_ORG = 'local';-export const LOCAL_MEMBER = 'local@localhost';+import { LOCAL_ORG } from './identity';+import { harnessBody, type Harness } from './harness';++export type { Harness };const BASE = '/api/gw';@@ -51,13 +50,14 @@ export function setCurrentWorkspace(id: string): void {try { window.localStorage.setItem(WS_KEY, id); } catch { /* private mode */ }}-/** Headers every gateway call carries: who we are, and which workspace we're scoped to. */+/** Headers every gateway call carries: which workspace we're scoped to.+ *+ * Identity is deliberately absent — the proxy pins org and member server-side, so the browser+ * cannot name a different one. */export function gwHeaders(extra: Record<string, string> = {}): Record<string, string> {const ws = currentWorkspace();return {'content-type': 'application/json',- 'x-harness-org': LOCAL_ORG,- 'x-harness-member': LOCAL_MEMBER,'x-harness-workspace': ws,...(ws === DEFAULT_WORKSPACE.id ? { 'x-harness-workspace-default': '1' } : {}),...extra,@@ -87,28 +87,17 @@ async function gw<T>(path: string, init: RequestInit = {}): Promise<T> {}// ── harnesses ─────────────────────────────────────────────────────────────────-export interface Harness {- id: string;- name: string;- base: string;- defaultModel?: string;- systemPrompt?: string;- maxStep?: number | null;- timeoutSeconds?: number | null;- createdAt?: number;- [k: string]: unknown;-}-export const listHarnesses = () =>gw<{ harnesses?: Harness[] }>(`/v1/harnesses?${qs({})}`).then((d) => d.harnesses || []);export const getHarness = (id: string) => gw<Harness>(`/v1/harnesses/${encodeURIComponent(id)}`);-export const createHarness = (body: Partial<Harness> & { name: string; base: string }) =>- gw<Harness>('/v1/harnesses', { method: 'POST', body: JSON.stringify(body) });+export const createHarness = (h: Partial<Harness> & { name: string; base: string }) =>+ gw<Harness>('/v1/harnesses', { method: 'POST', body: JSON.stringify(harnessBody(h)) });-export const updateHarness = (id: string, body: Partial<Harness>) =>- gw<Harness>(`/v1/harnesses/${encodeURIComponent(id)}`, { method: 'PUT', body: JSON.stringify(body) });+export const updateHarness = (id: string, h: Harness) =>+ gw<Harness>(`/v1/harnesses/${encodeURIComponent(id)}`,+ { method: 'PUT', body: JSON.stringify(harnessBody(h)) });export const deleteHarness = (id: string) =>gw<{ ok?: boolean }>(`/v1/harnesses/${encodeURIComponent(id)}`, { method: 'DELETE' });diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsnew file mode 100644index 00000000..608f41bd--- /dev/null+++ b/ui/src/lib/harness.ts@@ -0,0 +1,53 @@+// The harness shape, and the one place that converts it for the wire.+//+// The API is deliberately asymmetric and it matters: it RETURNS camelCase (the shape the console+// renders) but ACCEPTS snake_case, and it ignores unknown fields instead of rejecting them. Send+// the returned shape straight back and the write succeeds while quietly persisting an empty model+// and empty instructions.+//+// Shared by the console client and the server-side cloud-push route so there is exactly one+// definition of what a harness is on the wire. The local gateway and the hosted API take the same+// body, which is the whole point of the open-core split — a promotion is a copy, not a+// translation.++export interface Harness {+ id: string;+ name: string;+ base: string;+ baseLabel?: string;+ defaultModel?: string;+ systemPrompt?: string;+ mcpServers?: unknown[];+ skills?: unknown[];+ disabledTools?: string[];+ additionalHeaders?: string[];+ maxStep?: number | null;+ timeoutSeconds?: number | null;+ createdAt?: number;+ [k: string]: unknown;+}++/** Console shape -> wire body.+ *+ * Always the COMPLETE harness, never a patch: a write replaces the record, so any field left+ * out comes back empty. Editors pass the whole object they loaded with their edits applied, and+ * fields the console doesn't expose survive the round trip.+ *+ * Local bookkeeping — id, timestamps, org, workspace, member — is dropped by construction+ * rather than by a deny-list, which is also what makes this safe to push to a hosted account:+ * the destination mints its own. */+export function harnessBody(h: Partial<Harness> & { name: string; base: string }) {+ return {+ name: h.name,+ base: h.base,+ base_label: h.baseLabel || h.base,+ default_model: h.defaultModel || '',+ system_prompt: h.systemPrompt || '',+ mcp_servers: h.mcpServers || [],+ skills: h.skills || [],+ disabled_tools: h.disabledTools || [],+ additional_headers: h.additionalHeaders || [],+ max_step: h.maxStep ?? null,+ timeout_seconds: h.timeoutSeconds ?? null,+ };+}diff --git a/ui/src/lib/identity.ts b/ui/src/lib/identity.tsnew file mode 100644index 00000000..3cbff43f--- /dev/null+++ b/ui/src/lib/identity.ts@@ -0,0 +1,12 @@+// The implicit single tenant of a self-hosted instance.+//+// A self-hosted box has one operator, so there is no login and no org switching — but the+// gateway still scopes every record by org and member. Keeping real values (rather than empty+// ones) means the storage layout is identical to the hosted deployment's, which is what makes+// "push this harness to the cloud" a copy rather than a translation.+//+// Defined here rather than in lib/api.ts because both sides need them: the browser puts the org+// in query strings, and the server-side proxy pins the identity headers. One definition, so the+// two can never disagree.+export const LOCAL_ORG = 'local';+export const LOCAL_MEMBER = 'local@localhost';