Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add Cerebras as an API-based AI provider (#2701)
[._.]/ Adam Eivyec65a5a8b3ab
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0b1a89789e..f5e64aa3c2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,8 @@- **The Brain daily log now saves itself.** Your entry is saved automatically as you type (about a second and a half after you pause, and at least every ten seconds during a long uninterrupted writing run), when you click away from the editor, when you switch tabs or navigate away, and when you background the tab or app — so a closed laptop or a backgrounded phone no longer loses the day. The toolbar shows the current state (`Unsaved…` / `Saving…` / `Saved`) in place of a toast on every autosave; the Save button and ⌘S still work and still confirm with a toast. Autosave never reverts what you're typing mid-save, never writes one day's text into another when you change dates, keeps debouncing instead of retrying per keystroke when the server is unreachable, and deliberately stands down when a dictated voice segment arrives while you have unsaved edits (the toolbar says "Autosave paused — save to keep your edits") — a full-content save would otherwise drop the segment.+- [issue-2701] **Cerebras is now available as an AI provider.** Add your API key on the AI Providers page and PortOS can route AI-backed work through Cerebras's OpenAI-compatible endpoint (very high tokens/sec). Ships disabled with no key, so nothing calls it until you opt in; hit "Refresh models" after adding your key to pull the live model list. Existing installs pick the provider up automatically on restart. Cost estimates on /devtools/usage are also now accurate for `gpt-oss-120b` — it was previously billed at OpenAI GPT-5.4's rates, roughly 10x its real price.+## Changed- Daily log entries now re-embed into the Chief-of-Staff memory index once you settle (coalesced per day, ~30s after your last edit) instead of on every single save. Autosave means a day's entry is now written every couple of seconds while you type; re-embedding per save would have meant an embedding call per typing pause — and, once a day's log grows past the embedding size budget, an unrequested AI summarization call each time too. Search results are unchanged; the index simply updates when you pause rather than mid-sentence, which also produces a better vector than embedding a half-typed sentence a hundred times. Journals now use the same debounced, coalesced re-embed path every other Brain record type already used.diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex c7d4642ed9..1552fdb724 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -248,6 +248,23 @@"enabled": false,"envVars": {}},+ "cerebras": {+ "id": "cerebras",+ "name": "Cerebras",+ "type": "api",+ "endpoint": "https://api.cerebras.ai/v1",+ "apiKey": "",+ "models": ["gpt-oss-120b"],+ "defaultModel": "gpt-oss-120b",+ "lightModel": "gpt-oss-120b",+ "mediumModel": "gpt-oss-120b",+ "heavyModel": "gpt-oss-120b",+ "fallbackProvider": null,+ "timeout": 300000,+ "enabled": false,+ "envVars": {},+ "secretEnvVars": []+ },"grok": {"id": "grok","name": "xAI Grok",diff --git a/scripts/migrations/195-cerebras-provider.js b/scripts/migrations/195-cerebras-provider.jsnew file mode 100644index 0000000000..59f627c561--- /dev/null+++ b/scripts/migrations/195-cerebras-provider.js@@ -0,0 +1,91 @@+/**+ * Ship the Cerebras API provider to existing installs.+ *+ * Background: issue-2701. Cerebras exposes an OpenAI-compatible chat API+ * (https://api.cerebras.ai/v1) authenticated with a plain API key, so the+ * toolkit's generic `executeApiRun` drives it with no runner changes — the+ * provider is pure configuration. `api.cerebras.ai` is allowlisted in+ * aiToolkit/internal/endpointGuard.js so the key may be attached outbound.+ *+ * `setup-data.js` merges *missing* provider entries from data.reference, but+ * only when an install re-runs setup. This migration delivers the provider on a+ * plain server restart too, and is the canonical path for deployed installs to+ * pick it up. Purely additive: a brand-new id, so there's no rename or+ * pinned-id rewrite — an existing `cerebras` key is left untouched (idempotent),+ * which also preserves a user's stored apiKey and refreshed model list.+ *+ * Seeded with only `gpt-oss-120b`: as of 2026-07-16 it is Cerebras's sole+ * *production* model — the rest of the catalog (`zai-glm-4.7`, `gemma-4-31b`)+ * is flagged preview and documented as removable "on short notice", so pinning+ * a preview id into a shipped seed would strand installs on a dead model. All+ * four tiers therefore point at the one production model (same shape as the+ * grok-cli/grok-tui single-model entries); "Refresh models" repopulates the+ * live list from GET /v1/models once the user adds a key. `enabled: false`+ * keeps the provider inert until then (no cold-bootstrap LLM calls).+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. Frozen here as the+ * historical record this migration installs; later default changes ride their+ * own migrations rather than mutating this one.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const PROVIDERS_REL_PATH = 'data/providers.json';++const CEREBRAS_API = {+ id: 'cerebras',+ name: 'Cerebras',+ type: 'api',+ endpoint: 'https://api.cerebras.ai/v1',+ apiKey: '',+ models: ['gpt-oss-120b'],+ defaultModel: 'gpt-oss-120b',+ lightModel: 'gpt-oss-120b',+ mediumModel: 'gpt-oss-120b',+ heavyModel: 'gpt-oss-120b',+ fallbackProvider: null,+ timeout: 300000,+ enabled: false,+ envVars: {},+ secretEnvVars: [],+};++export default {+ async up({ rootDir }) {+ const providersPath = join(rootDir, PROVIDERS_REL_PATH);+ const raw = await readFile(providersPath, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Cerebras from data.reference)`);+ return;+ }++ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);+ return;+ }++ if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);+ return;+ }++ if (config.providers[CEREBRAS_API.id]) {+ console.log(`✅ ${PROVIDERS_REL_PATH}: Cerebras provider already present — no change`);+ return;+ }++ // structuredClone fully detaches the frozen shipped def (nested arrays/+ // objects included) so a later mutation of the install can't corrupt it.+ config.providers[CEREBRAS_API.id] = structuredClone(CEREBRAS_API);+ console.log(`📝 ${PROVIDERS_REL_PATH}: added ${CEREBRAS_API.id} provider`);+ await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);+ },+};diff --git a/scripts/migrations/195-cerebras-provider.test.js b/scripts/migrations/195-cerebras-provider.test.jsnew file mode 100644index 0000000000..a532eff902--- /dev/null+++ b/scripts/migrations/195-cerebras-provider.test.js@@ -0,0 +1,127 @@+/**+ * Test for migration 195 — add the Cerebras API provider to existing installs.+ * Picked up by server/vitest.config.js's `../scripts/**\/*.test.js` glob.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './195-cerebras-provider.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 195 — Cerebras provider', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-195-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('adds the Cerebras API provider to an existing install', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);++ const api = out.providers.cerebras;+ expect(api.type).toBe('api');+ expect(api.endpoint).toBe('https://api.cerebras.ai/v1');+ expect(api.defaultModel).toBe('gpt-oss-120b');+ expect(api.models).toEqual(['gpt-oss-120b']);+ // ships inert — no key, disabled, so nothing calls the provider unprompted+ expect(api.apiKey).toBe('');+ expect(api.enabled).toBe(false);++ // unrelated providers + active provider untouched+ expect(out.providers['claude-code']).toBeDefined();+ expect(out.activeProvider).toBe('claude-code');+ });++ it('does not overwrite a user-customized cerebras entry', async () => {+ writeJson(providersPath, {+ providers: {+ cerebras: {+ id: 'cerebras',+ type: 'api',+ endpoint: 'https://api.cerebras.ai/v1',+ enabled: true,+ apiKey: 'csk-secret',+ defaultModel: 'zai-glm-4.7',+ models: ['zai-glm-4.7', 'gpt-oss-120b'],+ },+ },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ // stored key, enablement, and a refreshed model list all survive+ expect(out.providers.cerebras.enabled).toBe(true);+ expect(out.providers.cerebras.apiKey).toBe('csk-secret');+ expect(out.providers.cerebras.defaultModel).toBe('zai-glm-4.7');+ expect(out.providers.cerebras.models).toEqual(['zai-glm-4.7', 'gpt-oss-120b']);+ });++ it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {+ writeJson(providersPath, { providers: {} });+ await migration.up({ rootDir });+ const first = readJson(providersPath);+ first.providers.cerebras.models.push('mutated');++ // A second install run must still ship the pristine model list.+ const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-195-b-'));+ mkdirSync(join(rootDir2, 'data'), { recursive: true });+ const providersPath2 = join(rootDir2, 'data/providers.json');+ writeJson(providersPath2, { providers: {} });+ await migration.up({ rootDir: rootDir2 });+ expect(readJson(providersPath2).providers.cerebras.models).not.toContain('mutated');+ rmSync(rootDir2, { recursive: true, force: true });+ });++ it('is idempotent — a second run makes no changes', async () => {+ writeJson(providersPath, {+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });+ const afterFirst = readFileSync(providersPath, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);+ });++ it('is a no-op when data/providers.json does not exist (fresh install)', async () => {+ await migration.up({ rootDir });+ expect(existsSync(providersPath)).toBe(false);+ });++ it('does not modify the file on invalid JSON', async () => {+ writeFileSync(providersPath, '{ not valid json');+ const before = readFileSync(providersPath, 'utf-8');++ await migration.up({ rootDir });++ expect(readFileSync(providersPath, 'utf-8')).toBe(before);+ });++ it('does not modify the file when the providers map is missing', async () => {+ writeJson(providersPath, { activeProvider: 'claude-code' });+ const before = readFileSync(providersPath, 'utf-8');++ await migration.up({ rootDir });++ expect(readFileSync(providersPath, 'utf-8')).toBe(before);+ });+});diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex f7f9d03b8d..3fe7d34c45 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -237,6 +237,23 @@"envVars": {},"secretEnvVars": []},+ "cerebras": {+ "id": "cerebras",+ "name": "Cerebras",+ "type": "api",+ "endpoint": "https://api.cerebras.ai/v1",+ "apiKey": "",+ "models": ["gpt-oss-120b"],+ "defaultModel": "gpt-oss-120b",+ "lightModel": "gpt-oss-120b",+ "mediumModel": "gpt-oss-120b",+ "heavyModel": "gpt-oss-120b",+ "fallbackProvider": null,+ "timeout": 300000,+ "enabled": false,+ "envVars": {},+ "secretEnvVars": []+ },"lmstudio": {"id": "lmstudio","name": "LM Studio",diff --git a/server/lib/aiToolkit/internal/endpointGuard.js b/server/lib/aiToolkit/internal/endpointGuard.jsindex d8f5e86010..ca059d9034 100644--- a/server/lib/aiToolkit/internal/endpointGuard.js+++ b/server/lib/aiToolkit/internal/endpointGuard.js@@ -62,6 +62,7 @@ const ALLOWED_PROVIDER_HOSTS = new Set(['api.cohere.ai','api.cohere.com','api.fireworks.ai',+ 'api.cerebras.ai',]);const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;diff --git a/server/lib/aiToolkit/internal/endpointGuard.test.js b/server/lib/aiToolkit/internal/endpointGuard.test.jsindex a1ffa8aff5..77aecd55f1 100644--- a/server/lib/aiToolkit/internal/endpointGuard.test.js+++ b/server/lib/aiToolkit/internal/endpointGuard.test.js@@ -119,6 +119,9 @@ describe('endpointGuard — assertSecretEndpoint', () => {it('does not throw for an allowlisted host with a secret', () => {expect(() => assertSecretEndpoint('https://api.openai.com/v1', { hasSecret: true })).not.toThrow();});+ it('does not throw for the Cerebras host with a secret', () => {+ expect(() => assertSecretEndpoint('https://api.cerebras.ai/v1', { hasSecret: true })).not.toThrow();+ });it('does not throw for loopback with a secret', () => {expect(() => assertSecretEndpoint('http://127.0.0.1:1234/v1', { hasSecret: true })).not.toThrow();});diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex c5b04cd934..f529766ad1 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -12,6 +12,7 @@* - https://developers.openai.com/api/docs/pricing* - https://docs.x.ai/docs/pricing* - https://ai.google.dev/gemini-api/docs/pricing+ * - https://inference-docs.cerebras.ai/models/openai-oss** Model ids arrive in many shapes (full ids, CLI sentinels like `opus`, the* `*-configured-default` sentinels from providerModels.js, Bedrock-prefixed@@ -56,6 +57,10 @@ const EXACT_RATES = {'gemini-2.5-pro': [1.25, 10.0],'gemini-2.5-flash': [0.3, 2.5],'gemini-2.5-flash-lite': [0.1, 0.4],+ // Cerebras — open-weights models on an OpenAI-compatible host. Listed exactly+ // (not via the `/gpt/i` family rule) because that rule would otherwise bill+ // `gpt-oss-120b` at OpenAI GPT-5.4's $2.50/$15.00 — off by ~10-20x.+ 'gpt-oss-120b': [0.35, 0.75],};// Exact keys sorted longest-first for the substring pass in@@ -79,6 +84,10 @@ const FAMILY_RULES = [{ test: /sonnet/i, rateModel: 'claude-sonnet-4-5' },{ test: /haiku/i, rateModel: 'claude-haiku-4-5' },{ test: /codex/i, rateModel: 'gpt-5.3-codex' },+ // `gpt-oss-*` is open-weights and hosted cheaply everywhere — it must win over+ // the proprietary `/gpt/i` rule below, which would bill it at ~10-20x. Sizes+ // other than the exact-listed 120b land here.+ { test: /gpt-oss/i, rateModel: 'gpt-oss-120b' },{ test: /gpt/i, rateModel: 'gpt-5.4' },{ test: /grok-build/i, rateModel: 'grok-build-0.1' },{ test: /grok-4\.20/i, rateModel: 'grok-4.3' },@@ -92,6 +101,10 @@ const PROVIDER_DEFAULT_RULES = [{ test: /codex|openai/i, rateModel: 'gpt-5.3-codex' },{ test: /grok|xai/i, rateModel: 'grok-4.5' },{ test: /antigravity|agy|gemini|google/i, rateModel: 'gemini-3.1-pro-preview' },+ // Cerebras hosts a small, uniformly cheap catalog; its flagship's rates are a+ // far better estimate for an unrecognized id (e.g. a preview model picked up+ // by "Refresh models") than the generic $3/$15 fallback.+ { test: /cerebras/i, rateModel: 'gpt-oss-120b' },];// Legacy blended estimate (the old flat usage.js rate) — the last resort for adiff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.jsindex dfc8d21778..5ce9f3c331 100644--- a/server/lib/modelPricing.test.js+++ b/server/lib/modelPricing.test.js@@ -33,6 +33,24 @@ describe('resolveModelRates', () => {expect(resolveModelRates('codex', 'gpt-5.6-terra-2026-06-01')).toMatchObject({ rateModel: 'gpt-5.6-terra', matched: 'family' });});+ it('prices Cerebras gpt-oss-120b at its own rates, not OpenAI GPT rates', () => {+ expect(resolveModelRates('cerebras', 'gpt-oss-120b')).toMatchObject({+ rateModel: 'gpt-oss-120b', inputPer1M: 0.35, outputPer1M: 0.75, matched: 'exact',+ });+ });++ it('keeps other gpt-oss sizes on open-weights rates rather than the proprietary /gpt/ rule', () => {+ expect(resolveModelRates('cerebras', 'gpt-oss-20b')).toMatchObject({ rateModel: 'gpt-oss-120b', matched: 'family' });+ });++ it('still resolves proprietary OpenAI ids through the gpt family rule', () => {+ expect(resolveModelRates('codex', 'gpt-4.1')).toMatchObject({ rateModel: 'gpt-5.4', matched: 'family' });+ });++ it('estimates an unrecognized Cerebras model at the Cerebras flagship rate', () => {+ expect(resolveModelRates('cerebras', 'zai-glm-4.7')).toMatchObject({ rateModel: 'gpt-oss-120b', matched: 'providerDefault' });+ });+it('falls back to a provider default when the model is unknown', () => {const r = resolveModelRates('claude-code', 'my-custom-alias');expect(r).toMatchObject({ rateModel: 'claude-sonnet-4-5', matched: 'providerDefault' });