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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sk33p"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
rust-version = "1.75"
license = "MIT"
Expand Down
4 changes: 2 additions & 2 deletions cloud/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -471,6 +471,6 @@ export function configFromEnv(env: Record<string, string | undefined> = 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),
}
}
50 changes: 36 additions & 14 deletions cloud/src/ask.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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<string, string | undefined>): AiFn {
const only: Record<string, string> = {}
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<string, string | undefined>, opts: { fetch?: typeof fetch } = {}): AiFn {
const pick: Record<string, string> = {}
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(/<think>[\s\S]*?<\/think>/gi, '').replace(/<think>[\s\S]*$/i, '').trim()
Expand Down
33 changes: 27 additions & 6 deletions cloud/test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
})
})
Loading