Organized AI Organized AI · LLM knowledge graph

organized-gateway Wiki

// Worker-focused knowledge graph · bindings · routes · functions · D1 schema · secrets · commands

How to use this wiki (for humans and LLMs) Tighter scope than openclaw-gateway-wiki — only the Worker, no system-wide phases or trainee paths. Every binding, route, function, table, secret, and command in organized-gateway has one node. Load this when the question is "how does the Worker work" rather than "how does the gateway system work."
                              organized-gateway · NODE GRAPH

   client                        Hono app                          OPENCLAW_URL
   ──────                        ────────                          ────────────

   POST /v1/*  ───►   app.all('/v1/*')
                          │
                          ├── checkRateLimit(env, userId)  ◄──► KV  rate:{u}:{m}
                          │
                          ├── logRequest(env, entry)        ◄──► D1  requests
                          │
                          ├── (AUTH_MODE)
                          │     ├── 'openai': pass Authorization
                          │     └── 'codex' : KV oauth:{u} → X-Codex-Token
                          │
                          └── fetch(OPENCLAW_URL + path) ──────► upstream

   GET /health  ───►  liveness probe

Bindings

GATEWAY_KVKV binding

Cloudflare KV namespace. Three key shapes: rate:{user_id}:{minute} (counter, TTL 120s), oauth:{user_id} (Phase 2), tier:{user_id} (Phase 3).

DBD1 binding

D1 database organized-gateway-db. Holds the requests table + user_summary view.

OPENCLAW_URLsecret

Upstream proxy target — Tailscale bridge URL or Cloudflare Tunnel. Worker concatenates the request path onto it.

AUTH_MODEsecret

String enum: "openai" (pass-through Authorization) or "codex" (resolve OAuth from oauth:{user_id}). Selects the auth dispatch branch.

Routes

app.all('/v1/*')handler

The proxy. Sequence: extract → rate-check → log → build headers → upstream fetch → estimate tokens → log → return. Hono pattern.

app.get('/health')handler

Liveness. Returns {"status":"ok","gateway":"organized-gateway"}. No KV, no D1, no upstream — pure Worker.

Functions

hashIp(ip)function

SHA-256 → first 8 hex chars. Privacy-preserving session correlation. Stored in requests.ip_hash.

logRequest(env, entry)function

One-row INSERT into requests. Bound parameters; no SQL injection surface. Failures don't break the proxy — best-effort.

checkRateLimit(env, userId)function

Reads rate:{userId}:{minute}. Increments + returns true if < 50; returns false at cap. KV TTL 120s auto-evicts old buckets.

Schema — KV keys + D1 tables

rate:{user_id}:{minute}KV key

Per-minute integer counter. Cap 50. TTL 120 seconds — old buckets auto-evict so KV doesn't grow unbounded.

oauth:{user_id}KV key

Codex OAuth refresh token (Phase 2). Resolved on each request when AUTH_MODE=codex; missing → HTTP 401.

tier:{user_id}KV key

Customer tier (tier1 | tier2 | tier3). Phase 3. Written by Stripe webhook on checkout.

requests (table)D1 table

Append-only log. Columns: id, user_id, endpoint, status, latency_ms, tokens_est, ip_hash, created_at. Indexed on user_id + created_at.

user_summary (view)D1 view

Aggregate over requests grouped by user_id. Convenience view for dashboards and post-event review queries.

Secrets

OPENCLAW_URLsecret

Upstream proxy target. Set with echo "..." | wrangler secret put OPENCLAW_URL. Worker concatenates request pathname directly to it.

AUTH_MODEsecret

"openai" or "codex". Dispatches the auth header construction at request time.

Config files

wrangler.tomlfile

Project root config. Declares name, main, compatibility_date, account_id, [[kv_namespaces]], [[d1_databases]].

migrations/0001_init.sqlfile

Creates requests table + indexes + user_summary view. Applied via wrangler d1 execute --file during bootstrap.

worker-configuration.d.tsfile

Auto-generated TS interface for Env. Re-run wrangler types after any binding change in wrangler.toml.

scripts/bootstrap.shfile

One-shot provisioning: create KV namespace, create D1, run migrations, write generated IDs back into wrangler.toml.

Commands

bash scripts/bootstrap.shcommand

Once-per-account. Provisions KV + D1, runs migrations, writes IDs into wrangler.toml. Idempotent — safe to re-run.

wrangler secret putcommand

echo VALUE | wrangler secret put NAME --name organized-gateway. Required for both OPENCLAW_URL and AUTH_MODE.

wrangler deploycommand

wrangler deploy --name organized-gateway --config apps/organized-gateway/wrangler.toml --commit-dirty=true. Bake the dirty flag into scripts/deploy.sh.

wrangler tail organized-gatewaycommand

Live log stream. Filter with --status=error, sample with --sampling-rate=0.1. Last-resort prod debugger.

wrangler d1 executecommand

wrangler d1 execute organized-gateway-db --file=migrations/0001_init.sql for migrations; --command="…" for ad-hoc queries.

wrangler typescommand

Auto-generates worker-configuration.d.ts from wrangler.toml. Re-run on every binding change.

curl .../healthcommand

curl https://organized-gateway.<sub>.workers.dev/health. Returns {"status":"ok",…}. First check after every deploy.

watch -n5 d1 querycommand

watch -n5 'wrangler d1 execute organized-gateway-db --command "SELECT user_id, count(*) FROM requests …"'. Live trainee activity dashboard during the event.

Concepts

auth dispatchconcept

Single branch on AUTH_MODE. "openai" = pass Authorization through. "codex" = look up oauth:{user_id} in KV → forward as X-Codex-Token. Same Worker code, switched by secret.

pass-through proxyconcept

Worker doesn't transform request bodies — they're streamed verbatim to the upstream. Preserves OpenAI-compat for any client SDK that expects the standard /v1/* shape.

KV eventual consistencyconcept

Two requests at the same minute boundary can both read 49 and both write 50. Soft cap, not hard quota. Acceptable for rate limiting; not for billing enforcement.

privacy — ip_hashconcept

Raw IP never persisted. SHA-256(ip).slice(0, 8) → ip_hash. Enough to correlate one user's requests; not reversible to an IP.

tier dispatch (Phase 3)concept

Read tier:{user_id} from KV. Lookup tier-specific limit. Increment monthly_usage in D1. Over → HTTP 402.

best-effort tokens_estconcept

Worker parses upstream JSON for usage.total_tokens. Missing → 0. Don't bill against this; use it for throughput rough-cuts only.

openclaw-gateway-{guide,wiki}sibling system

System-level pair — phases 1–3, post-training paths A/B/C, HICAM event context, OpenClaw + Hermes + NoClaw services. Read alongside this Worker-focused pair.

Wrangler CLItool

Cloudflare's deploy tool. Every command in this wiki is a wrangler … invocation.

ClaudeFlaredownstream

Path C of the post-training upgrade ladder forks organized-gateway into customer-owned ExoClaw bridges + ephemeral Workers.

organized-ai-hubindex

Meta-index of every Organized AI deployment.