An open-source, faster Devin alternative
TypeScript
add benchmark script, cache edge auth + org policy per isolate to relieve per-request D1 under burst
Brian Reardona8e27fa70dc2
diff --git a/benchmarks/tti/.gitignore b/benchmarks/tti/.gitignorenew file mode 100644index 00000000..10b0ae89--- /dev/null+++ b/benchmarks/tti/.gitignore@@ -0,0 +1,3 @@+node_modules/+*.json.out+results*.jsondiff --git a/benchmarks/tti/README.md b/benchmarks/tti/README.mdnew file mode 100644index 00000000..f70f8c4c--- /dev/null+++ b/benchmarks/tti/README.md@@ -0,0 +1,42 @@+# OpenComputer sandbox TTI benchmark++Standalone replica of the public [ComputeSDK sandbox TTI benchmark](https://github.com/computesdk/benchmarks)+(runs Fridays 00:00 UTC). Measures **Time-to-Interactive**: wall-clock from+`sandbox.create()` through the first `runCommand('node -v')` succeeding (destroy+excluded), using the **same `@computesdk/opencomputer` adapter the leaderboard uses**+— so these numbers preview what we'll post on Friday.++## Run++```bash+npm install+OPENCOMPUTER_API_KEY=osb_xxx node bench.mjs # all 3 modes, PROD, 100 iters+OPENCOMPUTER_API_KEY=osb_xxx node bench.mjs --mode sequential --iterations 20+```++Defaults to **prod** (`https://app.opencomputer.dev`). Point elsewhere with+`OPENCOMPUTER_API_URL` (e.g. dev `https://app2.opensandbox.ai`).++## Config (env var, `--flag` overrides)++| var | flag | default | notes |+|---|---|---|---|+| `OPENCOMPUTER_API_URL` | `--api-url` | `https://app.opencomputer.dev` | prod |+| `OPENCOMPUTER_API_KEY` | `--api-key` | — | **required**; needs concurrency ≥ `CONCURRENCY` for staggered/burst |+| `MODE` | `--mode` | `all` | `sequential` \| `staggered` \| `burst` \| `all` |+| `ITERATIONS` | `--iterations` | `100` | |+| `CONCURRENCY` | `--concurrency` | `100` | staggered/burst; sequential is always 1 |+| `STAGGER_DELAY_MS` | `--stagger-delay-ms` | `200` | staggered only |+| `JSON_OUT` | `--json` | — | also write raw results to a JSON file |++## Modes (identical to the leaderboard)++- **sequential** — one at a time (concurrency 1) — isolated cold-start.+- **staggered** — ramp, 200ms between starts (concurrency 100).+- **burst** — all at once (concurrency 100) — peak-demand.++## Scoring (ported verbatim)++Stats trim bottom+top 5% of successful runs, then `median / P95 / P99`.+`score = (0.60·median + 0.25·P95 + 0.15·P99) × success-rate`, each metric scored+`100 × (1 − v/10000ms)` (≥10s ⇒ 0).diff --git a/benchmarks/tti/bench.mjs b/benchmarks/tti/bench.mjsnew file mode 100644index 00000000..f8a501cf--- /dev/null+++ b/benchmarks/tti/bench.mjs@@ -0,0 +1,245 @@+#!/usr/bin/env node+/**+ * OpenComputer sandbox TTI benchmark — a standalone replica of the public+ * ComputeSDK leaderboard's "Sandbox TTI" benchmark+ * (github.com/computesdk/benchmarks, runs Fridays 00:00 UTC).+ *+ * It measures Time-to-Interactive: wall-clock from `sandbox.create()` through+ * the first `runCommand('node -v')` succeeding (destroy excluded), using the+ * SAME @computesdk/opencomputer adapter the leaderboard uses — so the numbers+ * here are what we should expect to post on Friday.+ *+ * Three modes, matching the leaderboard exactly:+ * sequential — one at a time (concurrency 1)+ * staggered — ramp, 200ms between starts (concurrency 100)+ * burst — all at once (concurrency 100)+ *+ * Stats + composite score are ported verbatim from the leaderboard:+ * - trim bottom+top 5% of SUCCESSFUL runs, then median / P95 / P99+ * - metricScore(v) = max(0, 100 * (1 - v/10000ms)) (10s ceiling -> 0)+ * - timingScore = 0.60*median + 0.25*P95 + 0.15*P99 (all metricScore'd)+ * - compositeScore = round(timingScore * successRate * 100) / 100+ *+ * Config (env var, with --flag override). Defaults to PROD:+ * OPENCOMPUTER_API_URL default https://app.opencomputer.dev+ * OPENCOMPUTER_API_KEY required+ * MODE / --mode sequential|staggered|burst|all (default all)+ * ITERATIONS / --iterations default 100+ * CONCURRENCY/ --concurrency default 100 (staggered/burst; sequential is always 1)+ * STAGGER_DELAY_MS / --stagger-delay-ms default 200 (staggered only)+ * JSON_OUT / --json <path> also write raw results as JSON+ *+ * Usage:+ * OPENCOMPUTER_API_KEY=osb_xxx node bench.mjs # all modes, prod, 100 iters+ * OPENCOMPUTER_API_KEY=osb_xxx node bench.mjs --mode sequential --iterations 20+ */+import { opencomputer } from '@computesdk/opencomputer';++// ---- config ---------------------------------------------------------------++function flag(name, envName, def) {+ const i = process.argv.indexOf(`--${name}`);+ if (i !== -1 && process.argv[i + 1] !== undefined) return process.argv[i + 1];+ if (envName && process.env[envName] !== undefined && process.env[envName] !== '') return process.env[envName];+ return def;+}++const API_URL = flag('api-url', 'OPENCOMPUTER_API_URL', 'https://app.opencomputer.dev');+const API_KEY = flag('api-key', 'OPENCOMPUTER_API_KEY', '');+const MODE = String(flag('mode', 'MODE', 'all')).toLowerCase();+const ITERATIONS = parseInt(flag('iterations', 'ITERATIONS', '100'), 10);+const CONCURRENCY = parseInt(flag('concurrency', 'CONCURRENCY', '100'), 10);+const STAGGER_DELAY_MS = parseInt(flag('stagger-delay-ms', 'STAGGER_DELAY_MS', '200'), 10);+const JSON_OUT = flag('json', 'JSON_OUT', '');++// Per-op timeouts, matching the leaderboard's tti-task.ts.+const CREATE_TIMEOUT_MS = 120_000;+const COMMAND_TIMEOUT_MS = 30_000;+const DESTROY_TIMEOUT_MS = 15_000;+const KEEP_ALIVE_MS = 600_000; // sandboxOptions.timeout on the leaderboard++if (!API_KEY) {+ console.error('ERROR: OPENCOMPUTER_API_KEY is required (env var or --api-key).');+ process.exit(2);+}++// ---- helpers --------------------------------------------------------------++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++function withTimeout(promise, ms, label) {+ let t;+ const timeout = new Promise((_, reject) => {+ t = setTimeout(() => reject(new Error(`${label} (>${ms}ms)`)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(t));+}++/** One TTI iteration: create -> node -v (exit 0) -> destroy (untimed). */+async function ttiTask() {+ const compute = opencomputer({ apiKey: API_KEY, apiUrl: API_URL });+ const start = performance.now();+ const sandbox = await withTimeout(+ compute.sandbox.create({ timeout: KEEP_ALIVE_MS }),+ CREATE_TIMEOUT_MS,+ 'create timed out',+ );+ try {+ const res = await withTimeout(sandbox.runCommand('node -v'), COMMAND_TIMEOUT_MS, 'command timed out');+ if (res.exitCode !== 0) {+ throw new Error(`node -v exit ${res.exitCode}: ${res.stderr || 'unknown'}`);+ }+ return performance.now() - start;+ } finally {+ await withTimeout(sandbox.destroy(), DESTROY_TIMEOUT_MS, 'destroy timed out').catch(() => {});+ }+}++/**+ * Run `iterations` TTI tasks with at most `concurrency` in flight, launching+ * successive tasks `staggerDelayMs` apart. sequential = {conc 1, delay 0},+ * staggered = {conc 100, delay 200}, burst = {conc 100, delay 0}.+ */+async function runMode(label, { iterations, concurrency, staggerDelayMs }) {+ process.stdout.write(+ `\n== ${label}: iterations=${iterations} concurrency=${concurrency} staggerDelayMs=${staggerDelayMs} ==\n`,+ );+ const oks = []; // ttiMs of successes+ let done = 0;+ let fails = 0;+ let active = 0;+ const queue = [];++ const runOne = async (i) => {+ active++;+ try {+ const ttiMs = await ttiTask();+ oks.push(ttiMs);+ process.stdout.write(` [${++done + fails}/${iterations}] ok ${(ttiMs / 1000).toFixed(2)}s\n`);+ } catch (err) {+ fails++;+ process.stdout.write(` [${done + fails}/${iterations}] FAIL ${err?.message || err}\n`);+ } finally {+ active--;+ }+ };++ // Dispatcher: respects the concurrency cap and the stagger between starts.+ for (let i = 0; i < iterations; i++) {+ while (active >= concurrency) await sleep(5);+ queue.push(runOne(i));+ if (staggerDelayMs > 0 && i < iterations - 1) await sleep(staggerDelayMs);+ }+ await Promise.all(queue);++ return summarize(label, { iterations, oks, fails });+}++// ---- stats + scoring (ported verbatim from the leaderboard) ---------------++function percentile(sorted, p) {+ if (sorted.length === 0) return 0;+ const idx = Math.max(0, Math.ceil((p / 100) * sorted.length) - 1);+ return sorted[Math.min(idx, sorted.length - 1)];+}++/** Trim bottom+top `trimPercent`, then compute stats on the remainder. */+function computeStats(values, trimPercent = 0.05) {+ if (values.length === 0) return { min: 0, max: 0, mean: 0, median: 0, p95: 0, p99: 0, n: 0 };+ const sorted = [...values].sort((a, b) => a - b);+ const trimCount = Math.floor(sorted.length * trimPercent);+ const trimmed =+ trimCount > 0 && sorted.length - 2 * trimCount > 0+ ? sorted.slice(trimCount, sorted.length - trimCount)+ : sorted;+ const mid = Math.floor(trimmed.length / 2);+ const median = trimmed.length % 2 === 0 ? (trimmed[mid - 1] + trimmed[mid]) / 2 : trimmed[mid];+ const mean = trimmed.reduce((a, b) => a + b, 0) / trimmed.length;+ return {+ n: trimmed.length,+ min: trimmed[0],+ max: trimmed[trimmed.length - 1],+ mean,+ median,+ p95: percentile(trimmed, 95),+ p99: percentile(trimmed, 99),+ };+}++const CEILING_MS = 10_000;+const scoreMetric = (v) => Math.max(0, 100 * (1 - v / CEILING_MS));++function compositeScore(stats, successRate) {+ if (successRate === 0) return 0;+ const timingScore =+ 0.6 * scoreMetric(stats.median) + 0.25 * scoreMetric(stats.p95) + 0.15 * scoreMetric(stats.p99);+ return Math.round(timingScore * successRate * 100) / 100;+}++function summarize(mode, { iterations, oks, fails }) {+ const successRate = iterations > 0 ? oks.length / iterations : 0;+ const stats = computeStats(oks);+ const score = compositeScore(stats, successRate);+ return { mode, iterations, successes: oks.length, failures: fails, successRate, stats, score, raw: oks };+}++function fmt(ms) {+ return ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`;+}++function printSummary(results) {+ console.log(`\n${'='.repeat(78)}`);+ console.log(`OpenComputer TTI benchmark — ${API_URL}`);+ console.log('='.repeat(78));+ const head = ['mode', 'ok/n', 'succ%', 'min', 'median', 'P95', 'P99', 'max', 'mean', 'score'];+ const rows = results.map((r) => [+ r.mode,+ `${r.successes}/${r.iterations}`,+ `${(r.successRate * 100).toFixed(0)}%`,+ fmt(r.stats.min),+ fmt(r.stats.median),+ fmt(r.stats.p95),+ fmt(r.stats.p99),+ fmt(r.stats.max),+ fmt(r.stats.mean),+ r.score.toFixed(2),+ ]);+ const widths = head.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));+ const line = (cells) => cells.map((c, i) => c.padEnd(widths[i])).join(' ');+ console.log(line(head));+ console.log(widths.map((w) => '-'.repeat(w)).join(' '));+ for (const row of rows) console.log(line(row));+ console.log('');+ console.log('score = 0.60·median + 0.25·P95 + 0.15·P99 (each vs 10s ceiling) × success-rate;');+ console.log('stats trim bottom+top 5% of successful runs (leaderboard methodology).');+}++// ---- main -----------------------------------------------------------------++const MODES = {+ sequential: { iterations: ITERATIONS, concurrency: 1, staggerDelayMs: 0 },+ staggered: { iterations: ITERATIONS, concurrency: CONCURRENCY, staggerDelayMs: STAGGER_DELAY_MS },+ burst: { iterations: ITERATIONS, concurrency: CONCURRENCY, staggerDelayMs: 0 },+};++const toRun = MODE === 'all' ? ['sequential', 'staggered', 'burst'] : [MODE];+for (const m of toRun) {+ if (!MODES[m]) {+ console.error(`ERROR: unknown mode "${m}" (want sequential|staggered|burst|all)`);+ process.exit(2);+ }+}++console.log(`OpenComputer TTI bench → ${API_URL} (key ${API_KEY.slice(0, 6)}…) modes=[${toRun.join(', ')}]`);++const results = [];+for (const m of toRun) {+ results.push(await runMode(m, MODES[m]));+}+printSummary(results);++if (JSON_OUT) {+ const fs = await import('node:fs');+ fs.writeFileSync(JSON_OUT, JSON.stringify({ apiUrl: API_URL, results }, null, 2));+ console.log(`\nwrote raw results → ${JSON_OUT}`);+}diff --git a/benchmarks/tti/diag.mjs b/benchmarks/tti/diag.mjsnew file mode 100644index 00000000..c21311bc--- /dev/null+++ b/benchmarks/tti/diag.mjs@@ -0,0 +1,70 @@+#!/usr/bin/env node+/**+ * Burst diagnostic: same workload as bench.mjs (create -> node -v -> destroy)+ * but times each PHASE separately, so we can see where the ~8s under+ * 100-concurrency actually goes (provisioning vs first-command exec).+ *+ * OPENCOMPUTER_API_KEY=osb_xxx node diag.mjs [--iterations 100] [--concurrency 100]+ */+import { opencomputer } from '@computesdk/opencomputer';++const flag = (n, e, d) => {+ const i = process.argv.indexOf(`--${n}`);+ if (i !== -1 && process.argv[i + 1] !== undefined) return process.argv[i + 1];+ return process.env[e] ?? d;+};+const API_URL = flag('api-url', 'OPENCOMPUTER_API_URL', 'https://app.opencomputer.dev');+const API_KEY = flag('api-key', 'OPENCOMPUTER_API_KEY', '');+const ITER = parseInt(flag('iterations', 'ITERATIONS', '100'), 10);+const CONC = parseInt(flag('concurrency', 'CONCURRENCY', '100'), 10);+if (!API_KEY) { console.error('OPENCOMPUTER_API_KEY required'); process.exit(2); }++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const now = () => performance.now();++async function one() {+ const compute = opencomputer({ apiKey: API_KEY, apiUrl: API_URL });+ const t0 = now();+ const sandbox = await compute.sandbox.create({ timeout: 600_000 });+ const t1 = now();+ let cmdOk = false;+ try {+ const r = await sandbox.runCommand('node -v');+ cmdOk = r.exitCode === 0;+ } catch { /* record as fail */ }+ const t2 = now();+ sandbox.destroy().catch(() => {});+ return { createMs: t1 - t0, execMs: t2 - t1, ok: cmdOk };+}++function stats(a) {+ if (!a.length) return { n: 0 };+ const s = [...a].sort((x, y) => x - y);+ const pct = (q) => s[Math.min(s.length - 1, Math.ceil(q * s.length) - 1)];+ return { n: s.length, min: s[0], med: pct(0.5), p95: pct(0.95), p99: pct(0.99), max: s[s.length - 1] };+}+const f = (ms) => (ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`);+const row = (label, st) =>+ console.log(` ${label.padEnd(8)} n=${st.n} min=${f(st.min)} med=${f(st.med)} p95=${f(st.p95)} p99=${f(st.p99)} max=${f(st.max)}`);++console.log(`burst diag → ${API_URL} iterations=${ITER} concurrency=${CONC}\n`);+const results = [];+let active = 0;+const q = [];+for (let i = 0; i < ITER; i++) {+ while (active >= CONC) await sleep(5);+ active++;+ q.push(+ one()+ .then((r) => results.push(r))+ .catch((e) => results.push({ createMs: NaN, execMs: NaN, ok: false, err: String(e?.message || e) }))+ .finally(() => active--),+ );+}+await Promise.all(q);++const ok = results.filter((r) => r.ok);+console.log(`success ${ok.length}/${results.length}\n`);+row('create', stats(results.map((r) => r.createMs).filter((x) => !isNaN(x))));+row('exec', stats(ok.map((r) => r.execMs)));+row('total', stats(ok.map((r) => r.createMs + r.execMs)));diff --git a/benchmarks/tti/package-lock.json b/benchmarks/tti/package-lock.jsonnew file mode 100644index 00000000..c62be639--- /dev/null+++ b/benchmarks/tti/package-lock.json@@ -0,0 +1,74 @@+{+ "name": "opencomputer-tti-bench",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "opencomputer-tti-bench",+ "dependencies": {+ "@computesdk/opencomputer": "^1.0.1",+ "computesdk": "^4.1.4"+ }+ },+ "node_modules/@computesdk/cmd": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/@computesdk/cmd/-/cmd-0.4.1.tgz",+ "integrity": "sha512-hhcYrwMnOpRSwWma3gkUeAVsDFG56nURwSaQx8vCepv0IuUv39bK4mMkgszolnUQrVjBDdW7b3lV+l5B2S8fRA==",+ "license": "MIT"+ },+ "node_modules/@computesdk/opencomputer": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@computesdk/opencomputer/-/opencomputer-1.0.1.tgz",+ "integrity": "sha512-430gMhj2kFbxZZvcCINJFgTBroG60VIOa67CQuGK5vbTwK3babHdOLiND5JK6P60m5QNwWw1jnPaq4PQLWHfnA==",+ "license": "MIT",+ "dependencies": {+ "@computesdk/provider": "2.1.4",+ "@opencomputer/sdk": "^0.12.4",+ "computesdk": "4.1.4"+ }+ },+ "node_modules/@computesdk/provider": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@computesdk/provider/-/provider-2.1.4.tgz",+ "integrity": "sha512-abTZS8kpif4QpLZ7Jzo6hmlje2b3YB4VRC8hVkrb/tKXwt0QcU7Nao7tM1phRru0HxVrfHycb/vZtdJSlNFGeA==",+ "license": "MIT",+ "dependencies": {+ "@computesdk/cmd": "0.4.1",+ "computesdk": "4.1.4",+ "daemond": "0.1.4"+ }+ },+ "node_modules/@opencomputer/sdk": {+ "version": "0.12.4",+ "resolved": "https://registry.npmjs.org/@opencomputer/sdk/-/sdk-0.12.4.tgz",+ "integrity": "sha512-/BpMJMHxskkSI2GUri27xej9eXMrjlvu85NxIz/luiEKJ6lJKFF3w6uTY0IweZlB50SqIt7/dsC5ksZFXkyPzA==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/computesdk": {+ "version": "4.1.4",+ "resolved": "https://registry.npmjs.org/computesdk/-/computesdk-4.1.4.tgz",+ "integrity": "sha512-PRBMwJ2yRTMvVc+8mC8wM2EKI96kco1Dk9/kSAOsABlv7YP+h9v5qbqVIQQ6xKr46KL81MLpIOKf0dVZbIEafg==",+ "license": "MIT",+ "dependencies": {+ "@computesdk/cmd": "0.4.1",+ "daemond": "0.1.4"+ }+ },+ "node_modules/daemond": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/daemond/-/daemond-0.1.4.tgz",+ "integrity": "sha512-xiLScBiwYGGPmxfcAb24aH+FkmR/ZSd+PxOvigGpKda6OsDjE2Gj6/4oAX2N3hMWoL4atti1hYyF9dLV3FFM0A==",+ "license": "MIT",+ "os": [+ "linux",+ "darwin"+ ],+ "engines": {+ "node": ">=18.0.0"+ }+ }+ }+}diff --git a/benchmarks/tti/package.json b/benchmarks/tti/package.jsonnew file mode 100644index 00000000..0f246b68--- /dev/null+++ b/benchmarks/tti/package.json@@ -0,0 +1,16 @@+{+ "name": "opencomputer-tti-bench",+ "private": true,+ "type": "module",+ "description": "Standalone replica of the ComputeSDK sandbox TTI benchmark (create -> `node -v` -> destroy) run against OpenComputer. Defaults to prod; driven by env vars. Uses the same @computesdk/opencomputer adapter the public leaderboard runs on Fridays.",+ "scripts": {+ "bench": "node bench.mjs",+ "bench:sequential": "node bench.mjs --mode sequential",+ "bench:staggered": "node bench.mjs --mode staggered",+ "bench:burst": "node bench.mjs --mode burst"+ },+ "dependencies": {+ "@computesdk/opencomputer": "^1.0.1",+ "computesdk": "^4.1.4"+ }+}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex a3cc23c2..b654ca27 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -193,6 +193,38 @@ function stripApiKeyQueryParam(target: string): string {// WebSocket Upgrade requests, also accept ?api_key= because browser WS APIs// cannot set custom headers. Session-JWT auth (browser flows) is a TODO;// SDK/test traffic uses the API key.+// --- Per-isolate auth + org-policy caches (burst D1 relief) ------------------+// Every request authenticates with a D1 SELECT on api_keys, create additionally+// reads the org policy (D1 SELECT on orgs), and auth fired a same-row last_used+// write per request. A burst from ONE key => hundreds of concurrent D1 ops that+// serialize on D1's single writer, stalling requests at the edge while the+// backend sits idle. Cache the (stable) key->org auth and the org policy+// per-isolate for a few seconds so a burst collapses to a handful of D1 reads,+// and throttle the last_used bump. Isolates recycle so entries are naturally+// bounded; CACHE_MAX guards pathological key cardinality.+const AUTH_TTL_MS = 60_000;+const ORG_POLICY_TTL_MS = 5_000; // short: bounds is_halted / cap staleness+const LAST_USED_BUMP_MS = 60_000; // at most once/min/key/isolate+const CACHE_MAX = 10_000;++interface AuthEntry {+ caller: Caller;+ expiresAt: number | null;+ cachedAtMs: number;+ lastBumpMs: number;+}+const authCache = new Map<string, AuthEntry>();+const orgPolicyCache = new Map<string, { policy: OrgPolicy | null; cachedAtMs: number }>();++function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number): void {+ if (nowMs - entry.lastBumpMs < LAST_USED_BUMP_MS) return;+ entry.lastBumpMs = nowMs;+ env.OPENCOMPUTER_DB.prepare("UPDATE api_keys SET last_used = ?1 WHERE key_hash = ?2")+ .bind(Math.floor(nowMs / 1000), hash)+ .run()+ .catch(() => {});+}+async function authenticate(req: Request, env: Env): Promise<Caller | null> {const apiKey = apiKeyFromRequest(req);if (!apiKey) return null;@@ -208,19 +240,30 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {return verifyProvisionToken(env.OC_PROVISION_SECRET, apiKey);}const hash = await hashAPIKey(apiKey);+ const nowMs = Date.now();+ const nowSec = Math.floor(nowMs / 1000);++ const cached = authCache.get(hash);+ if (cached && nowMs - cached.cachedAtMs < AUTH_TTL_MS) {+ if (cached.expiresAt && cached.expiresAt < nowSec) return null;+ bumpLastUsed(env, hash, cached, nowMs);+ return cached.caller;+ }+const row = await env.OPENCOMPUTER_DB.prepare("SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",).bind(hash).first<{ org_id: string; created_by: string | null; expires_at: number | null }>();- if (!row) return null;- if (row.expires_at && row.expires_at < Math.floor(Date.now() / 1000)) return null;- // best-effort last_used bump- env.OPENCOMPUTER_DB.prepare("UPDATE api_keys SET last_used = ?1 WHERE key_hash = ?2")- .bind(Math.floor(Date.now() / 1000), hash)- .run()- .catch(() => {});- return { orgID: row.org_id, userID: row.created_by };+ if (!row) return null; // never cache negatives — a freshly-created key must work at once+ if (row.expires_at && row.expires_at < nowSec) return null;++ const caller: Caller = { orgID: row.org_id, userID: row.created_by };+ if (authCache.size >= CACHE_MAX) authCache.clear();+ const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };+ authCache.set(hash, entry);+ bumpLastUsed(env, hash, entry, nowMs);+ return caller;}interface CellRow {@@ -426,11 +469,17 @@ interface OrgPolicy {// loadOrgPolicy reads an org's routing + policy fields from D1. Returns null// when the org doesn't exist (callers 401).async function loadOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | null> {- return await env.OPENCOMPUTER_DB.prepare(+ const nowMs = Date.now();+ const cached = orgPolicyCache.get(orgID);+ if (cached && nowMs - cached.cachedAtMs < ORG_POLICY_TTL_MS) return cached.policy;+ const policy = await env.OPENCOMPUTER_DB.prepare("SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider FROM orgs WHERE id = ?1",).bind(orgID).first<OrgPolicy>();+ if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();+ orgPolicyCache.set(orgID, { policy, cachedAtMs: nowMs });+ return policy;}// enforceCreatePolicy applies every org-level gate for creating or forking a