Meter and gate
Micro-dollar spend metering, worst-case holds, pause files, and public-mode session and rate controls.
export const COOKIE = 'hk';
export const SESSION_DAYS = 7;
export const LIMITS = Object.freeze({
sessionMessages: { n: 20, ms: 10 * 60_000 },
addressMessages: { n: 40, ms: 10 * 60_000 },
dayMessages: { n: 500, ms: 24 * 3_600_000 },
sessionProfile: { n: 1, ms: 10 * 60_000 },
dayProfile: { n: 12, ms: 24 * 3_600_000 },
badKeys: { n: 10, ms: 10 * 60_000 },
concurrent: 4,
addressConcurrent: 2,
sseSession: 3,
sseTotal: 60,
sessions: 300,
bodyBytes: 4_096,
});
export const SECURITY_HEADERS = Object.freeze({
'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
'x-frame-options': 'DENY',
'x-content-type-options': 'nosniff',
'referrer-policy': 'no-referrer',
'permissions-policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=()',
'cross-origin-opener-policy': 'same-origin',
'cross-origin-resource-policy': 'same-origin',
'x-robots-tag': 'noindex, nofollow, noarchive',
'cache-control': 'no-store',
});Overview
Two deterministic safeguards sit around every model call in the reference console: the spend meter (meter.mjs) bounds daily cost and call counts in micro-dollars, and the public gate (public.mjs) controls access, session isolation, request origins, headers, and rate limits when HOLON_CONSOLE_PUBLIC=1. Reference: meter.mjs Reference: public.mjs
Both safeguards fail closed. A missing or wiped ledger refuses to start the process, a failed ledger update disables further holds for the rest of the run, a PAUSE file halts every model call immediately, and any unauthenticated request in public mode receives 404 Not found. Reference: server.mjs Reference: meter.mjs Reference: public.mjs
Inputs
- Meter (
openMeterandcheckLedger): spend ledger path insideHOLON_CONSOLE_DATA,budgetMicro(default3,000,000micro-dollars =$3.00/day, plusHOLON_AGENTS_MAX_USDwhen Explore is enabled locally),callCap(4,000calls/day),requireExisting(set from the.initmarker file), and apaused()check testing<HOLON_CONSOLE_DATA>/PAUSE. Reference: server.mjs Reference: meter.mjs - Gate (
makeGate): accesskey(minimum24characters; read fromHOLON_CONSOLE_KEY_FILE, or generated at24random bytes base64url with mode0600if absent), a per-process32-byte random HMACsecret,secure(truein public mode),days(7), and optionalpublicOrigin. Reference: public.mjs Reference: server.mjs
Outputs
- Meter handle:
hold(amount)persists a hold and returns{ id, day, amount }ornull;settle(hold, actual)commits the real charge (or the full hold ifactualis missing or invalid) and drops the hold atomically;today()returns{ spent, calls, held, budget };broken()reports whether a persistence error locked spending. Reference: meter.mjs - Gate handle:
keyOk(given)performs a constant-time SHA-256 comparison;issue()mints a signedSet-Cookievalue;session(req)validates signature and expiry and returns the session ID ornull. HelperssameOriginJson,clientAddress,addressKey, andmakeLimiterenforce origin, privacy, and sliding-window caps. Reference: public.mjs
Topics
Spend meter (meter.mjs)
The meter stores daily totals and active holds in two tables inside the local append-only store (day is UTC YYYY-MM-DD): Reference: meter.mjs
CREATE TABLE IF NOT EXISTS console_spend (
day TEXT PRIMARY KEY, spent INTEGER NOT NULL, calls INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS console_holds (
id TEXT PRIMARY KEY, day TEXT NOT NULL, amount INTEGER NOT NULL, at TEXT NOT NULL
);- Worst-case holds before every call: before any external request leaves the process,
meter.hold(bound)checkst.calls >= callCapandt.spent + held + amount > budgetMicroand saves the hold toconsole_holds. Because a byte-level token is at least one UTF-8 byte, bounds use UTF-8 byte lengths plusFRAMING_TOKENS * 4(FRAMING_TOKENS = 1,024) rather than loose character estimates: Reference: meter.mjs- Decisions bound:
(bytes(input) + bytes(questions) + FRAMING_TOKENS * 4) * DECISIONS_PRICES.input(output is free). Reference: meter.mjs - Reply bound:
(bytes(instructions) + bytes(input) + bytes(schema) + FRAMING_TOKENS * 4) * client.prices.input + (client.maxOutputTokens ?? 1_000) * client.prices.output. Inserver.mjs,REPLY_MODELpinsprices: { input: 2, output: 10, cached: 0.1 }micro-dollars per token andmaxOutputTokens: 300. Reference: meter.mjs Reference: server.mjs - Explore reserve (local only): reserves and settles the full per-run cap (
HOLON_AGENTS_MAX_USD, default$2) up front throughpausedReserve. Reference: server.mjs
- Decisions bound:
- Atomic settlement and crash recovery:
settle()adds the charge toconsole_spendand deletes the hold inside one SQL transaction. If that transaction fails, the rollback keeps the hold on disk and flipsbroken = true, blocking all future holds for the process. On startup, any rows left inconsole_holdsfrom an earlier crash are charged in full toconsole_spendbefore traffic is served. Reference: meter.mjs - Refusing to start with a lost ledger:
checkLedgermaintains a mode-0600<ledgerPath>.initmarker. Once that marker exists, startup throws if the ledger file is missing (refusing to start with a fresh budget), andopenMeter(requireExisting: true) throws if theconsole_spendtable is absent so an emptied file cannot reset the day's budget. Reference: server.mjs Reference: meter.mjs - Pause file: placing a file named
PAUSEinHOLON_CONSOLE_DATAstops every model call immediately, including subsequent calls inside an in-flight flow (checked inserver.mjs,meteredDecisions,meteredTalk, andpausedReserve). Reference: server.mjs Reference: meter.mjs
| Meter setting | Default value | Scope |
|---|---|---|
HOLON_CONSOLE_DAY_USD | $3 (3,000,000 micro-USD) | Daily budget (UTC day) |
HOLON_AGENTS_MAX_USD | $2 (added locally when HOLON_AGENTS=on) | Explore per-run cap |
callCap | 4,000 calls | Daily model call ceiling |
FRAMING_TOKENS | 1,024 tokens (* 4 bytes) | Worst-case request framing buffer |
maxOutputTokens | 300 tokens (fallback 1,000 in talkBound) | Reply model output cap |
| Decisions timeout | 10,000 ms | Per-call network ceiling |
| Reply timeout | 15,000 ms | Per-call network ceiling |
Public gate and session cookies (public.mjs)
- Key link and cookie format:
GET /?k=<key>checks the query string (length1..255) withtimingSafeEqualover SHA-256 digests. On match,issue()creates an18-byte base64url session ID, setsexp = now + 7 days, signs${sid}.${exp}with HMAC-SHA256 using the in-memory32-byte secret, and setshk=<sid>.<exp>.<sig>; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800; Secure. Because the signing secret is never persisted, all sessions end on server restart. Reference: public.mjs - Lockout after wrong keys:
10wrong keys from one hashed address within10minutes lock that address out ofGET /?k=(404) until earlier attempts age out of the sliding window. Reference: server.mjs Reference: public.mjs - Same-origin JSON guard:
sameOriginJson(req, publicOrigin)requires a validOriginheader whose host matchesreq.headers.host(or whose full origin equalsHOLON_PUBLIC_ORIGIN) and aContent-Typematching/^application\/json(\s*;|$)/i. Reference: public.mjs - Hashed client address:
clientAddress(req)trusts the tunnel's connecting-IP header (under64characters) only when the socket address is loopback (127.0.0.1,::1, or::ffff:127.0.0.1), otherwise usingreq.socket.remoteAddress.addressKey(addr, salt)computes the first16hex characters ofSHA-256("${salt}:${addr}")with an8-byte per-process random salt, so raw IP addresses never appear in logs or limit buckets. Reference: public.mjs Reference: server.mjs
Complete limits and timeouts table
| Limit or timeout | Value | Enforcement point |
|---|---|---|
sessionMessages | 20 per 10 min (600,000 ms) | POST /api/say in public mode (429) |
addressMessages | 40 per 10 min (600,000 ms) | POST /api/say in public mode (429) |
dayMessages | 500 per 24 h (86,400,000 ms) | POST /api/say in public mode (429) |
sessionProfile | 1 per 10 min (600,000 ms) | POST /api/profile-checks in public mode (429) |
dayProfile | 12 per 24 h (86,400,000 ms) | POST /api/profile-checks in public mode (429) |
badKeys | 10 per 10 min (600,000 ms) | GET /?k= in public mode (404 lockout) |
| Per-session concurrency | 1 flow at a time (s.busy) | admitAndRun (429 one_at_a_time) |
addressConcurrent | 2 concurrent flows per hashed address | admitAndRun (429 address_concurrent) |
concurrent | 4 concurrent flows across all sessions | admitAndRun (503 concurrent) |
sessions | 300 active sessions in memory | sessionFor (evicts oldest idle, else 503) |
sseSession / sseTotal | 3 per session / 60 total | Reserved constants in LIMITS |
bodyBytes | 4,096 bytes | readJson (413) |
BODY_MS | 5,000 ms | readJson (408) |
| HTTP server timeouts | Headers 10,000 ms, request 60,000 ms, keep-alive 5,000 ms | http.createServer in server.mjs |
| Limiter sweep | Every 500 hits, drops keys idle >= 24 h | makeLimiter in public.mjs |