DecidrHolon Design Kit

Technologies and APIs

Meter and gate

Micro-dollar spend metering, worst-case holds, pause files, and public-mode session and rate controls.

JavaScript
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 (openMeter and checkLedger): spend ledger path inside HOLON_CONSOLE_DATA, budgetMicro (default 3,000,000 micro-dollars = $3.00/day, plus HOLON_AGENTS_MAX_USD when Explore is enabled locally), callCap (4,000 calls/day), requireExisting (set from the .init marker file), and a paused() check testing <HOLON_CONSOLE_DATA>/PAUSE. Reference: server.mjs Reference: meter.mjs
  • Gate (makeGate): access key (minimum 24 characters; read from HOLON_CONSOLE_KEY_FILE, or generated at 24 random bytes base64url with mode 0600 if absent), a per-process 32-byte random HMAC secret, secure (true in public mode), days (7), and optional publicOrigin. Reference: public.mjs Reference: server.mjs

Outputs

  • Meter handle: hold(amount) persists a hold and returns { id, day, amount } or null; settle(hold, actual) commits the real charge (or the full hold if actual is 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 signed Set-Cookie value; session(req) validates signature and expiry and returns the session ID or null. Helpers sameOriginJson, clientAddress, addressKey, and makeLimiter enforce 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

SQL
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) checks t.calls >= callCap and t.spent + held + amount > budgetMicro and saves the hold to console_holds. Because a byte-level token is at least one UTF-8 byte, bounds use UTF-8 byte lengths plus FRAMING_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. In server.mjs, REPLY_MODEL pins prices: { input: 2, output: 10, cached: 0.1 } micro-dollars per token and maxOutputTokens: 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 through pausedReserve. Reference: server.mjs
  • Atomic settlement and crash recovery: settle() adds the charge to console_spend and deletes the hold inside one SQL transaction. If that transaction fails, the rollback keeps the hold on disk and flips broken = true, blocking all future holds for the process. On startup, any rows left in console_holds from an earlier crash are charged in full to console_spend before traffic is served. Reference: meter.mjs
  • Refusing to start with a lost ledger: checkLedger maintains a mode-0600 <ledgerPath>.init marker. Once that marker exists, startup throws if the ledger file is missing (refusing to start with a fresh budget), and openMeter (requireExisting: true) throws if the console_spend table is absent so an emptied file cannot reset the day's budget. Reference: server.mjs Reference: meter.mjs
  • Pause file: placing a file named PAUSE in HOLON_CONSOLE_DATA stops every model call immediately, including subsequent calls inside an in-flight flow (checked in server.mjs, meteredDecisions, meteredTalk, and pausedReserve). Reference: server.mjs Reference: meter.mjs
Meter settingDefault valueScope
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
callCap4,000 callsDaily model call ceiling
FRAMING_TOKENS1,024 tokens (* 4 bytes)Worst-case request framing buffer
maxOutputTokens300 tokens (fallback 1,000 in talkBound)Reply model output cap
Decisions timeout10,000 msPer-call network ceiling
Reply timeout15,000 msPer-call network ceiling

Public gate and session cookies (public.mjs)

  • Key link and cookie format: GET /?k=<key> checks the query string (length 1..255) with timingSafeEqual over SHA-256 digests. On match, issue() creates an 18-byte base64url session ID, sets exp = now + 7 days, signs ${sid}.${exp} with HMAC-SHA256 using the in-memory 32-byte secret, and sets hk=<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: 10 wrong keys from one hashed address within 10 minutes lock that address out of GET /?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 valid Origin header whose host matches req.headers.host (or whose full origin equals HOLON_PUBLIC_ORIGIN) and a Content-Type matching /^application\/json(\s*;|$)/i. Reference: public.mjs
  • Hashed client address: clientAddress(req) trusts the tunnel's connecting-IP header (under 64 characters) only when the socket address is loopback (127.0.0.1, ::1, or ::ffff:127.0.0.1), otherwise using req.socket.remoteAddress. addressKey(addr, salt) computes the first 16 hex characters of SHA-256("${salt}:${addr}") with an 8-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 timeoutValueEnforcement point
sessionMessages20 per 10 min (600,000 ms)POST /api/say in public mode (429)
addressMessages40 per 10 min (600,000 ms)POST /api/say in public mode (429)
dayMessages500 per 24 h (86,400,000 ms)POST /api/say in public mode (429)
sessionProfile1 per 10 min (600,000 ms)POST /api/profile-checks in public mode (429)
dayProfile12 per 24 h (86,400,000 ms)POST /api/profile-checks in public mode (429)
badKeys10 per 10 min (600,000 ms)GET /?k= in public mode (404 lockout)
Per-session concurrency1 flow at a time (s.busy)admitAndRun (429 one_at_a_time)
addressConcurrent2 concurrent flows per hashed addressadmitAndRun (429 address_concurrent)
concurrent4 concurrent flows across all sessionsadmitAndRun (503 concurrent)
sessions300 active sessions in memorysessionFor (evicts oldest idle, else 503)
sseSession / sseTotal3 per session / 60 totalReserved constants in LIMITS
bodyBytes4,096 bytesreadJson (413)
BODY_MS5,000 msreadJson (408)
HTTP server timeoutsHeaders 10,000 ms, request 60,000 ms, keep-alive 5,000 mshttp.createServer in server.mjs
Limiter sweepEvery 500 hits, drops keys idle >= 24 hmakeLimiter in public.mjs

See also