diff --git a/Cargo.lock b/Cargo.lock index cbe06b5..e0edbea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -794,7 +794,7 @@ dependencies = [ [[package]] name = "sk33p" -version = "0.3.0" +version = "0.4.0" dependencies = [ "aes-gcm", "argon2", diff --git a/Cargo.toml b/Cargo.toml index 8f1541a..fede1f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sk33p" -version = "0.3.0" +version = "0.4.0" edition = "2021" rust-version = "1.75" license = "MIT" diff --git a/cloud/src/app.ts b/cloud/src/app.ts index 444521c..462b580 100644 --- a/cloud/src/app.ts +++ b/cloud/src/app.ts @@ -13,7 +13,7 @@ import { CoinPay, CoinPayError, readWebhook, verifyWebhook } from '@profullstack import { descriptorResponse } from '@profullstack/footer' import { runTool, safeName, withExt, ToolError, FORMATS, type FileIn } from './engine.ts' import { Store, type Key, type Plan } from './store.ts' -import { ask, c0mputeAi, type AiFn } from './ask.ts' +import { ask, houseAi, type AiFn } from './ask.ts' import { docsMarkdown, docsPage, homePage, keyPage, llmsTxt, messagePage, upgradePage } from './page.ts' export type Limits = { calls: number; maxBytes: number } @@ -471,6 +471,6 @@ export function configFromEnv(env: Record = process. sandbox: env.SANDBOX !== '0', coinpay, mintsPerIp: n('MINTS_PER_IP', 5), - ai: env.ASK_DISABLED === '1' ? null : c0mputeAi(env), + ai: env.ASK_DISABLED === '1' ? null : houseAi(env), } } diff --git a/cloud/src/ask.ts b/cloud/src/ask.ts index 74eaf39..666befc 100644 --- a/cloud/src/ask.ts +++ b/cloud/src/ask.ts @@ -1,9 +1,10 @@ /** * Ask: a plain-language question about a sheet in, one checked formula out. * - * The model runs on the c0mpute network only. The router is built from the - * C0MPUTE_* variables alone with the paid fallback off, so OpenAI and - * Anthropic are never constructed, whatever else is in the environment. + * House rule (2026-11-30): c0mpute first, then OpenAI / Anthropic (alternating, + * via @profullstack/ai-providers) when c0mpute fails or times out. The fallback + * exists only when a paid key is configured and AI_PAID_FALLBACK is not "off"; + * without one the router can reach c0mpute and nothing else. * * Every formula is run through the engine before it is returned: if it fails * or evaluates to an error value, the model gets the error and one more try. @@ -31,22 +32,43 @@ Rules: Answer with JSON only, no prose and no code fences: {"formula": "=...", "explanation": "what it does, at most 140 characters"}` -/** A router that can only ever reach c0mpute. */ -export function c0mputeAi(env: Record): AiFn { - const only: Record = {} - for (const [k, v] of Object.entries(env)) if (k.startsWith('C0MPUTE_') && v) only[k] = v - only.C0MPUTE_MODELS ||= DEFAULT_MODELS - only.C0MPUTE_TIMEOUT_MS ||= '120000' - only.AI_PAID_FALLBACK = 'off' - const router = createAiProviders({ env: only, paidFallback: false }) - const timeoutMs = Number(only.C0MPUTE_TIMEOUT_MS) || 120_000 +const PAID_KEYS = /^(OPENAI_API_KEY|ANTHROPIC_API_KEY|AI_OPENAI_MODEL|AI_ANTHROPIC_MODEL)$/ + +/** + * c0mpute first; OpenAI then Anthropic only when a key is configured. With a + * fallback, c0mpute gets a shorter timeout (default 45 s) so a waiting user is + * actually helped by it; without one, c0mpute gets the full 120 s. + */ +export function houseAi(env: Record, opts: { fetch?: typeof fetch } = {}): AiFn { + const pick: Record = {} + for (const [k, v] of Object.entries(env)) if (v && (k.startsWith('C0MPUTE_') || PAID_KEYS.test(k))) pick[k] = v + const paid = !/^(0|false|no|off)$/i.test(env.AI_PAID_FALLBACK ?? '') && Boolean(pick.OPENAI_API_KEY || pick.ANTHROPIC_API_KEY) + if (!paid) { + delete pick.OPENAI_API_KEY + delete pick.ANTHROPIC_API_KEY + } + pick.C0MPUTE_MODELS ||= DEFAULT_MODELS + const c0Timeout = Number(pick.C0MPUTE_TIMEOUT_MS) || (paid ? 45_000 : 120_000) + pick.C0MPUTE_TIMEOUT_MS = String(c0Timeout) + pick.AI_PAID_FALLBACK = paid ? 'on' : 'off' + const f = opts.fetch ? { fetch: opts.fetch } : {} + const router = createAiProviders({ + env: pick, + paidFallback: paid, + c0mpute: { timeoutMs: c0Timeout, ...f }, + openai: { timeoutMs: 60_000, ...f }, + anthropic: { timeoutMs: 60_000, ...f }, + }) return async ({ system, user }) => { - const r = await router.generateText({ system, user, json: true, maxTokens: 1500, temperature: 0.2, feature: 'sk33p-ask', timeoutMs, only: ['c0mpute'] } as any) - if (r.provider !== 'c0mpute') throw new Error(`refusing an answer from ${r.provider}`) + const r = await router.generateText({ system, user, json: true, maxTokens: 1500, temperature: 0.2, feature: 'sk33p-ask', ...(paid ? {} : { only: ['c0mpute'] }) } as any) + if (!paid && r.provider !== 'c0mpute') throw new Error(`refusing an answer from ${r.provider}`) return { text: r.text, model: r.model, provider: r.provider } } } +/** @deprecated name kept for callers; same as houseAi. */ +export const c0mputeAi = houseAi + /** Pull {formula, explanation} out of what a small model wrote. */ export function parseAnswer(text: string): { formula: string; explanation: string } { const cleaned = text.replace(/[\s\S]*?<\/think>/gi, '').replace(/[\s\S]*$/i, '').trim() diff --git a/cloud/test/app.test.ts b/cloud/test/app.test.ts index ab2b9dc..91d88a5 100644 --- a/cloud/test/app.test.ts +++ b/cloud/test/app.test.ts @@ -3,7 +3,7 @@ import { signWebhook } from '@profullstack/coinpay-onboard' import { createApp, configFromEnv, callTool, DEFAULT_LIMITS, type Config } from '../src/app.ts' import { EXAMPLES } from '../src/page.ts' import { Store } from '../src/store.ts' -import { contextCells, parseAnswer, type AiFn, type AiRequest } from '../src/ask.ts' +import { contextCells, houseAi, parseAnswer, type AiFn, type AiRequest } from '../src/ask.ts' // SK33P_BIN must point at a built sk33p (e.g. a release binary). const BIN = process.env.SK33P_BIN ?? 'sk33p' @@ -311,12 +311,33 @@ describe('ask', () => { expect(contextCells(CONTEXT)).toEqual({ A1: 'Item', B1: 'Cost', A2: 'Desk', B2: '100', A3: 'Lamp', B3: '50' }) }) - test('the production router can only reach c0mpute', async () => { - const cfg = configFromEnv({ SK33P_BIN: BIN, OPENAI_API_KEY: 'sk-not-used', ANTHROPIC_API_KEY: 'sk-ant-not-used', C0MPUTE_DISABLED: '1' }) - expect(cfg.ai).toBeFunction() - // With c0mpute switched off nothing else is tried: the paid keys are never wired in. - await expect(cfg.ai!({ system: 's', user: 'u' })).rejects.toThrow() + test('house rule: c0mpute only unless a paid fallback key is configured', async () => { + // No paid key, or AI_PAID_FALLBACK=off: with c0mpute switched off nothing else is tried. + for (const env of [{ C0MPUTE_DISABLED: '1' }, { C0MPUTE_DISABLED: '1', OPENAI_API_KEY: 'sk-x', AI_PAID_FALLBACK: 'off' }]) { + const ai = houseAi(env) + await expect(ai({ system: 's', user: 'u' })).rejects.toThrow() + } const src = await Bun.file(new URL('../src/ask.ts', import.meta.url)).text() expect(src).not.toMatch(/from ['"](openai|@anthropic-ai\/sdk)['"]/) }) + + test('house rule: falls back to OpenAI when c0mpute is unavailable and a key is set', async () => { + const calls: string[] = [] + const answer = '{"formula":"=SUM(B2:B3)","explanation":"total"}' + const fakeFetch = (async (url: string) => { + calls.push(String(url)) + const body = { + id: 'x', object: 'chat.completion', model: 'gpt-test', + choices: [{ index: 0, message: { role: 'assistant', content: answer }, finish_reason: 'stop' }], + output_text: answer, output: [{ type: 'message', content: [{ type: 'output_text', text: answer }] }], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2, input_tokens: 1, output_tokens: 1 }, + } + return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }) + }) as unknown as typeof fetch + const ai = houseAi({ C0MPUTE_DISABLED: '1', OPENAI_API_KEY: 'sk-test' }, { fetch: fakeFetch }) + const r = await ai({ system: 's', user: 'u' }) + expect(r.provider).toBe('openai') + expect(r.text).toContain('=SUM(B2:B3)') + expect(calls.some((u) => u.includes('openai'))).toBe(true) + }) })