Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,29 @@ MySQL/SQL Server, mixed naming styles and singular/plural table names, columns
that look like keys with no ref, isolated tables, missing timestamps, unused
enums and wide tables. `GET /api/v1/rules` is the list.

## Ask (pay as you go)

A person asks a database question in plain words at `/ask/<personal link>` and
gets an answer grounded in the engine: the schema's summary, every review
finding and exact SQL go into the prompt, and the checker's exact output is
added to convert and review answers. 5 cents per answered question from a
prepaid balance; failures are free. Top up $5/$10/$20 through CoinPay's
hosted checkout (no subscriptions). Everything asked stays on the page,
newest first. Models: c0mpute first through `@profullstack/ai-providers`,
OpenAI/Anthropic fallback when keys are set.
## The DBA agent (Ask, pay as you go)

A DBA as a service: a database question in plain words gets an answer
grounded in the engine. The schema's summary, every review finding and exact
SQL go into the prompt, and the checker's exact output is added to convert and
review answers. 5 cents per answered question from a prepaid balance; failures
are free. Top up $5/$10/$20 through CoinPay's hosted checkout (no
subscriptions).

- **People:** the "Ask the DBA agent" button on the home page asks about the
playground's schema in place; `/ask` is the full page with every past answer.
Anyone gets a personal link there (`POST /api/signup`, 5 per IP per hour,
`SIGNUP_CREDIT_CENTS` free credit, default 0).
- **Agents:** `POST /api/ask` + `GET /api/ask/<id>` with
`Authorization: Bearer <token>`, or the MCP tools `ask_dba` / `ask_dba_result`
with the same header on the `/mcp` connection.
- **Models:** c0mpute first through `@profullstack/ai-providers`. OpenAI or
Claude is offered for a question only when its price is at least
`ASK_MIN_MARGIN` (2) x the worst-case cost of the paid call (prompt at 3
chars/token, all 2,500 output tokens, plus any paid attempt that already
failed). Rates per million tokens: `AI_COST_OPENAI_IN/OUT` (0.25/2,
gpt-5-mini) and `AI_COST_ANTHROPIC_IN/OUT` (0.10/0.50, claude-haiku-5-5);
set them when changing `AI_OPENAI_MODEL` / `AI_ANTHROPIC_MODEL`.

Operator (`ADMIN_KEY` from the vault):

Expand Down Expand Up @@ -99,8 +112,6 @@ https://dbml.db.pit.world.

- Human review marketplace: let an agent request a paid review of its schema by
a human DBA through c0mpute.com/humans. Not built.
- Optional AI review on c0mpute (off unless a free c0mpute route is available;
no paid AI providers).
- Diagram rendering (SVG) of a schema.

## Credits and license
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dbml.db",
"version": "0.2.0",
"version": "0.3.0",
"private": true,
"description": "DBML as a service for AI agents: validate, parse, review and convert database schemas over an HTTP API, MCP server and CLI.",
"type": "module",
Expand Down
6 changes: 6 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ export function llmsTxt() {
Invalid DBML answers 422 with errors carrying line and column (validate answers 200 with valid:false).
Inputs up to ${MAX_INPUT_BYTES / 1024} KiB. ${process.env.RATE_LIMIT_PER_MIN || 60} requests/minute per caller.

## DBA agent (paid, pay as you go)
A plain-words answer to a database question, grounded in the engine's exact findings and SQL. ${process.env.ASK_PRICE_CENTS || 5} cents per answer from a prepaid balance; failures are free.
Token: get a personal link at ${SITE}ask (token = the part after /ask/), top up there. Send "Authorization: Bearer <token>".
- POST /api/ask {question, schema?} -> 202 {id}; GET /api/ask/<id> -> {status: working|answered|failed, answer, error}
- MCP: ask_dba {question, schema?, wait_seconds?}, ask_dba_result {id} (same Bearer header on /mcp)

## Review rules
${RULES.map((r) => `- ${r.id} (${r.severity}): ${r.description}`).join('\n')}

Expand Down
76 changes: 66 additions & 10 deletions src/ask.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
* findings in an answer are exact, not model guesses.
*
* Models: @profullstack/ai-providers, c0mpute first, OpenAI/Anthropic
* alternating as fallback when keys are configured.
* alternating as fallback when keys are configured. A paid provider is only
* offered for a question when what the asker pays covers at least
* ASK_MIN_MARGIN (default 2) times its worst-case cost (see paidAllowed).
*/
import { createAiProviders } from '@profullstack/ai-providers';
import { fromSql, review, summarize, toSql, validate } from './dbml.js';
import { failQuestion, finishQuestion } from './store.js';
import { failQuestion, finishQuestion, startQuestion, workingQuestion } from './store.js';

export const PRICE_CENTS = () => Number(process.env.ASK_PRICE_CENTS || 5);
const MAX_QUESTION = 4000;
Expand Down Expand Up @@ -139,14 +141,41 @@ export function buildPrompt(question, facts) {
return parts.join('\n\n');
}

/** USD per million tokens, by provider; env overrides. c0mpute bills per job, logged as 0 until priced. */
function rates(provider) {
/**
* USD per million tokens, by provider; env overrides. c0mpute bills per job,
* logged as 0 until priced. Defaults: gpt-5-mini, claude-haiku-5-5 (the
* router's default fallback models).
*/
export function rates(provider) {
const env = process.env;
const d = { c0mpute: [0, 0], openai: [0.25, 2], anthropic: [1, 5] }[provider] || [0, 0];
const d = { c0mpute: [0, 0], openai: [0.25, 2], anthropic: [0.1, 0.5] }[provider] || [0, 0];
const up = String(provider || '').toUpperCase();
return [Number(env[`AI_COST_${up}_IN`] ?? d[0]), Number(env[`AI_COST_${up}_OUT`] ?? d[1])];
}

export const MAX_TOKENS = 2500;
const PAID = ['openai', 'anthropic'];

/**
* Worst-case cost in micro-USD of one call: the prompt counted at 3 chars a
* token (code tokenizes denser than prose's 4) and every allowed output token.
*/
export function worstCaseMicroUsd(provider, promptChars, maxTokens = MAX_TOKENS) {
const [rin, rout] = rates(provider);
return Math.ceil(promptChars / 3) * rin + maxTokens * rout;
}

/**
* The paid providers this question may use: price paid must be at least
* ASK_MIN_MARGIN x (paid spend so far on it + this call's worst case).
* c0mpute is always allowed.
*/
export function paidAllowed({ priceCents, promptChars, spentMicroUsd = 0, maxTokens = MAX_TOKENS }) {
const margin = Number(process.env.ASK_MIN_MARGIN || 2);
const paidMicroUsd = priceCents * 10000;
return PAID.filter((p) => margin * (spentMicroUsd + worstCaseMicroUsd(p, promptChars, maxTokens)) <= paidMicroUsd);
}

/**
* Drop a model's visible reasoning. Qwen3 can stream its thinking as plain
* text ending in </think>; keep what follows. Text that is only reasoning
Expand All @@ -166,39 +195,49 @@ export function stripThink(t) {
* (its model service exits, or the network is busy), and the router treats
* that as final for the call. The retry asks for the other live 4B model.
*/
async function answerWithRetry(question, facts, t0) {
async function answerWithRetry(question, facts, t0, priceCents) {
const budget = Number(process.env.ASK_BUDGET_MS || 170000);
const alternates = (process.env.ASK_RETRY_MODELS || 'qwen3:4b,huihui_ai/qwen3.5-abliterated:4b').split(',').map((m) => m.trim()).filter(Boolean);
const user = buildPrompt(question, facts);
const promptChars = SYSTEM.length + user.length;
// Paid spend on this question so far, counted at worst case for calls that failed.
let spent = 0;
let last;
const delay = Number(process.env.ASK_RETRY_DELAY_MS ?? 8000);
const maxAttempts = Number(process.env.ASK_MAX_ATTEMPTS || 8);
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (attempt > 0) await new Promise((res) => setTimeout(res, delay));
const left = budget - (Date.now() - t0);
if (attempt > 0 && left < 45000) break;
const only = ['c0mpute', ...paidAllowed({ priceCents, promptChars, spentMicroUsd: spent })];
let used = null;
try {
const r = await getAi(attempt > 0).streamText({
system: SYSTEM,
user,
maxTokens: 2500,
only,
maxTokens: MAX_TOKENS,
temperature: 0.2,
feature: 'ask',
timeoutMs: Math.max(30000, left),
...(attempt > 0 ? { models: { c0mpute: alternates[(attempt - 1) % alternates.length] } } : {}),
});
used = r.provider;
if (stripThink(r.text)) return r;
last = new Error('no answer text (reasoning only or empty)');
} catch (e) {
last = e;
// A paid provider may have billed before failing: count the worst case.
for (const a of e?.attempts || []) if (PAID.includes(a.provider)) spent += worstCaseMicroUsd(a.provider, promptChars);
console.error('ask attempt failed', attempt, String(e?.message || e).slice(0, 200));
}
if (used && PAID.includes(used)) spent += worstCaseMicroUsd(used, promptChars);
}
throw last || new Error('no answer');
}

/** Run one question to the end. Never throws; records the outcome. */
export async function runAsk(questionId, question, schemaText) {
export async function runAsk(questionId, question, schemaText, priceCents = PRICE_CENTS()) {
const t0 = Date.now();
let facts;
try {
Expand All @@ -208,7 +247,7 @@ export async function runAsk(questionId, question, schemaText) {
}
const exact = facts.exact.join('\n\n');
try {
const r = await answerWithRetry(question, facts, t0);
const r = await answerWithRetry(question, facts, t0, priceCents);
const text = stripThink(r.text);
const [rin, rout] = rates(r.provider);
const inTok = r.usage?.inputTokens ?? null;
Expand All @@ -221,7 +260,7 @@ export async function runAsk(questionId, question, schemaText) {
outputTokens: outTok,
costMicroUsd: Math.round((inTok || 0) * rin + (outTok || 0) * rout),
ms: Date.now() - t0,
priceCents: PRICE_CENTS(),
priceCents,
});
} catch (e) {
console.error('ask failed', questionId, String(e?.message || e).slice(0, 300));
Expand All @@ -232,3 +271,20 @@ export async function runAsk(questionId, question, schemaText) {
});
}
}

/**
* Start a question for an account: the checks every surface (page, API, MCP)
* shares. Returns {id} or {error, status}. The answer runs in the background.
*/
export function startAsk(account, question, schema) {
const q = String(question ?? '');
const s = schema == null ? '' : String(schema);
const bad = checkAskInput(q, s);
if (bad) return { error: bad, status: 400 };
const price = PRICE_CENTS();
if (account.balance_cents < price) return { error: 'Your balance is too low to ask. Please add money first. You were not charged.', status: 402 };
if (workingQuestion(account.id)) return { error: 'Still working on your last question. Please wait for it to finish.', status: 409 };
const id = startQuestion(account.id, q.trim(), s);
const done = runAsk(id, q, s, price);
return { id, done };
}
37 changes: 31 additions & 6 deletions src/askpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export function askPage({ account, questions, priceCents, notice = '', topups =
const body = `
<div class="who" role="status">You are signed in as <strong>${h(account.name)}</strong>. Balance: <strong>${dollars(account.balance_cents)}</strong>. Each question costs ${priceWords(priceCents)}.${low ? ' <span class="low">Your balance is too low to ask. Add money below.</span>' : ''}</div>
${notice ? `<div class="status good" style="display:block">${h(notice)}</div>` : ''}
<h1>Ask a database question</h1>
<h1>Ask the DBA agent</h1>
<form id="askform">
<label for="question">1. Your question</label>
<p class="hint">For example: "What is wrong with my schema?" or "Convert this to MySQL."</p>
Expand All @@ -155,17 +155,42 @@ ${topups ? `
<h2>Add money</h2>
<p class="hint">You pay on the CoinPay page, with crypto or PayPal. Your balance goes up when the payment arrives. Nothing renews by itself.</p>
<div class="money"><button type="button" data-topup="5">Add $5</button><button type="button" data-topup="10">Add $10</button><button type="button" data-topup="20">Add $20</button></div>` : ''}
<footer>Keep this page bookmarked: the link is your sign-in. If you lose it, ask Anthony for a new one. <a href="/">About dbml.db</a></footer>
<footer>Keep this page bookmarked: the link is your sign-in and the only way back to your balance and answers. <a href="/">About dbml.db</a></footer>
`;
return shell(`Ask: ${account.name}`, body, JS);
}

export function askSignedOut() {
const body = `<h1>Ask a database question</h1>
<p>To ask a question you need your personal link. It signs you in by itself, no password.</p>
<p>If you do not have it, ask Anthony to send it to you, then bookmark that page.</p>
const body = `<h1>Ask the DBA agent</h1>
<p>Ask anything about your database schema in plain words. The AI DBA agent answers from an exact check of your schema, so table names, findings and SQL are real, not guesses.</p>
<p>You need a personal link: it signs you in by itself, no password. Get one here, then bookmark the page it opens.</p>
<form id="signup">
<label for="name">Your name (optional)</label>
<textarea id="name" name="name" style="min-height:0;height:2.4em"></textarea>
<button id="signupbtn" class="ask" type="submit">Get my personal link</button>
</form>
<div id="status" class="status" aria-live="polite"></div>
<p>Already have a link? Open it again and you are back.</p>
<p><a href="/">About dbml.db</a></p>`;
return shell('Ask', body, '');
const js = `<script>
(() => {
const f = document.getElementById('signup');
const st = document.getElementById('status');
f.addEventListener('submit', async (ev) => {
ev.preventDefault();
const b = document.getElementById('signupbtn'); b.disabled = true;
try {
const r = await fetch('/api/signup', { method: 'POST', headers: { 'content-type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ name: document.getElementById('name').value }) });
const j = await r.json().catch(() => ({}));
if (r.ok && j.link) { location.href = j.link; return; }
if (j.signed_in) { location.href = '/ask'; return; }
st.className = 'status bad'; st.textContent = j.error || 'That did not work. Please try again.';
} catch (e) { st.className = 'status bad'; st.textContent = 'Could not reach the service. Please try again.'; }
b.disabled = false;
});
})();
</script>`;
return shell('Ask', body, js);
}

function shell(title, body, js) {
Expand Down
42 changes: 28 additions & 14 deletions src/askroutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*
* GET /ask/<token> personal link: signs in (cookie) and shows the page
* GET /ask the page for a signed-in browser
* POST /api/signup {name?} -> {link}: a new account and personal link (self-serve)
* GET /api/me name, balance, price, history, last schema
* POST /api/ask {question, schema} -> {id}; answered in the background
* GET /api/ask/<id> {status, answer, error, elapsed_ms}
Expand All @@ -17,7 +18,7 @@
import { timingSafeEqual, createHash } from 'node:crypto';
import { getCookie, setCookie } from 'hono/cookie';
import { CoinPay, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard';
import { checkAskInput, PRICE_CENTS, runAsk } from './ask.js';
import { PRICE_CENTS, startAsk } from './ask.js';
import { askPage, askSignedOut } from './askpage.js';
import { SITE } from './pages.js';
import {
Expand Down Expand Up @@ -73,6 +74,19 @@ function adminOk(c) {

const link = (token) => `${SITE}ask/${token}`;

/** New accounts per caller IP (first X-Forwarded-For hop) per hour. */
const signups = new Map();
function signupAllowed(c) {
const ip = (c.req.header('x-forwarded-for') || '').split(',')[0].trim() || 'local';
const now = Date.now();
const hits = (signups.get(ip) || []).filter((t) => now - t < 3600_000);
if (hits.length >= Number(process.env.SIGNUPS_PER_HOUR || 5)) return false;
hits.push(now);
signups.set(ip, hits);
if (signups.size > 10000) signups.clear();
return true;
}

export function mountAsk(app) {
app.get('/ask', (c) => {
const account = me(c);
Expand All @@ -88,6 +102,16 @@ export function mountAsk(app) {
return renderFor(c, account);
});

app.post('/api/signup', async (c) => {
if (me(c)) return c.json({ error: 'You already have an account in this browser.', signed_in: true }, 409);
if (!signupAllowed(c)) return c.json({ error: 'Too many new accounts from here. Please try again in an hour.' }, 429);
const b = await c.req.json().catch(() => ({}));
const name = String(b?.name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60) || 'dbml.db user';
const { account, token } = createAccount(name, Math.max(0, Math.trunc(Number(process.env.SIGNUP_CREDIT_CENTS || 0))));
remember(c, token);
return c.json({ link: link(token), name: account.name, balance_cents: account.balance_cents, price_cents: PRICE_CENTS() }, 201);
});

app.get('/api/me', (c) => {
const account = me(c);
if (!account) return c.json({ error: 'not signed in' }, 401);
Expand All @@ -109,19 +133,9 @@ export function mountAsk(app) {
} catch {
return c.json({ error: 'Something went wrong sending the question. Please try again.' }, 400);
}
const question = String(body?.question ?? '');
const schema = body?.schema == null ? '' : String(body.schema);
const bad = checkAskInput(question, schema);
if (bad) return c.json({ error: bad }, 400);
const price = PRICE_CENTS();
if (account.balance_cents < price) {
return c.json({ error: 'Your balance is too low to ask. Please add money below. You were not charged.' }, 402);
}
if (workingQuestion(account.id)) {
return c.json({ error: 'Still working on your last question. Please wait for it to finish.' }, 409);
}
const id = startQuestion(account.id, question.trim(), schema);
void runAsk(id, question, schema);
const r = startAsk(account, body?.question, body?.schema);
if (r.error) return c.json({ error: r.error }, r.status);
const { id } = r;
return c.json({ id, status: 'working' }, 202);
});

Expand Down
Loading
Loading