Function bodies 413 total
parseSilence function · typescript · L51-L55 (5 LOC)beau-terminal/src/lib/server/brain/executor.ts
export function parseSilence(text: string): string | null {
const trimmed = text.trim();
if (!trimmed || trimmed === 'SILENCE') return null;
return trimmed;
}executeOnTier function · typescript · L66-L89 (24 LOC)beau-terminal/src/lib/server/brain/executor.ts
export async function executeOnTier(prompt: string, config: TierConfig): Promise<TierResult> {
const url = `${config.endpoint}/api/generate`;
const start = Date.now();
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: config.model, prompt, stream: false }),
signal: AbortSignal.timeout(config.timeoutMs),
});
if (!res.ok) {
throw new Error(`executeOnTier: tier ${config.id} returned HTTP ${res.status}`);
}
const generationMs = Date.now() - start;
const data = (await res.json()) as { response: string; model: string };
return {
text: parseSilence(data.response ?? ''),
model: data.model ?? config.model,
generationMs,
};
}selectFallbackTier function · typescript · L100-L126 (27 LOC)beau-terminal/src/lib/server/brain/executor.ts
function selectFallbackTier(
failedTier: TierId,
registry: TierRegistry,
): TierConfig | null {
const online = registry.getOnlineTiers();
// Exclude the failed tier
const candidates = online.filter((c) => c.id !== failedTier);
if (candidates.length === 0) return null;
const failedOrder = TIER_ORDER[failedTier];
// Try upward first (next higher tier)
const higher = candidates
.filter((c) => TIER_ORDER[c.id] > failedOrder)
.sort((a, b) => TIER_ORDER[a.id] - TIER_ORDER[b.id]);
if (higher.length > 0) return higher[0];
// Fall back downward (next lower tier)
const lower = candidates
.filter((c) => TIER_ORDER[c.id] < failedOrder)
.sort((a, b) => TIER_ORDER[b.id] - TIER_ORDER[a.id]);
if (lower.length > 0) return lower[0];
return null;
}executeWithFallback function · typescript · L164-L374 (211 LOC)beau-terminal/src/lib/server/brain/executor.ts
export async function executeWithFallback(
prompt: string,
plan: RoutePlan,
registry: TierRegistry,
preparePrompt?: (tierConfig: TierConfig) => Promise<PrepareResult>,
request?: BrainRequestV1,
options?: Pick<ExecuteOptions, 'primaryPrepareResult' | 'onAttempt'>,
): Promise<BrainResponse> {
const primaryTier = plan.targetTier;
const primaryConfig = plan.tierConfig;
const onAttempt = options?.onAttempt;
const primaryPrepareResult = options?.primaryPrepareResult;
const isManual = request?.kind === 'manual.prompt';
let attemptNumber = 0;
// --- Primary attempt ---
attemptNumber++;
let primaryResult: TierResult | null = null;
let primaryError: unknown = null;
const primaryStart = Date.now();
try {
primaryResult = await executeOnTier(prompt, primaryConfig);
} catch (err) {
primaryError = err;
}
if (primaryResult !== null) {
// Emit trace for successful primary attempt
if (onAttempt && primaryPrepareResult) {
onAttempt({
checkQualitySignals function · typescript · L390-L418 (29 LOC)beau-terminal/src/lib/server/brain/executor.ts
export function checkQualitySignals(
text: string | null,
request: BrainRequestV1,
): boolean {
if (text === null) return false;
if (request.kind !== 'thought.generate') return false;
const thoughtType = request.input.type;
// Haiku: check for newline presence instead of word count
if (thoughtType === 'haiku') {
if (!text.includes('\n')) return true;
return false;
}
// Word count check (under 50% of expected max)
const threshold = QUALITY_WORD_THRESHOLDS[thoughtType];
if (threshold !== undefined && threshold > 0) {
const wordCount = text.trim().split(/\s+/).filter(Boolean).length;
if (wordCount < threshold) return true;
}
// Hedging markers
for (const marker of HEDGING_MARKERS) {
if (text.includes(marker)) return true;
}
return false;
}initBrain function · typescript · L36-L43 (8 LOC)beau-terminal/src/lib/server/brain/index.ts
export function initBrain(): void {
if (_registry !== null) return; // already initialised
_registry = new TierRegistry(DEFAULT_TIER_CONFIGS);
_registry.startProbing();
console.log('[brain] TierRegistry initialized, probing started');
}getBrainRegistry function · typescript · L49-L51 (3 LOC)beau-terminal/src/lib/server/brain/index.ts
export function getBrainRegistry(): TierRegistry | null {
return _registry;
}If a scraper extracted this row, it came from Repobility (https://repobility.com)
_resetBrainForTesting function · typescript · L64-L67 (4 LOC)beau-terminal/src/lib/server/brain/index.ts
export function _resetBrainForTesting(): void {
_registry = null;
previousTier = undefined;
}makeSilenceResponse function · typescript · L73-L88 (16 LOC)beau-terminal/src/lib/server/brain/index.ts
function makeSilenceResponse(requestId: string, plan?: RoutePlan | null): BrainResponse {
const tier: TierId = plan?.targetTier ?? 't2';
const model = plan?.tierConfig.model ?? 'unknown';
return {
requestId,
text: null,
tier,
model,
generationMs: 0,
clamped: plan?.clamped ?? false,
trimmed: plan?.trimmed ?? false,
fallback: false,
qualityEscalated: false,
};
}dispatch function · typescript · L105-L127 (23 LOC)beau-terminal/src/lib/server/brain/index.ts
export async function dispatch(request: BrainRequestV1): Promise<BrainResponse> {
if (_registry === null) {
throw new Error('[brain] dispatch() called before initBrain()');
}
const registry = _registry;
// Boolean guard: set to true when the hard-cap timeout fires so that late
// side effects from the still-running _executeDispatch are suppressed.
let timedOut = false;
// Wrap execution in a hard-cap timeout
const hardTimeout = new Promise<BrainResponse>((resolve) => {
setTimeout(() => {
timedOut = true;
resolve(makeSilenceResponse(request.requestId));
}, DISPATCH_TIMEOUT_MS);
});
const execution = _executeDispatch(request, registry, () => timedOut);
return Promise.race([execution, hardTimeout]);
}_executeDispatch function · typescript · L133-L308 (176 LOC)beau-terminal/src/lib/server/brain/index.ts
async function _executeDispatch(
request: BrainRequestV1,
registry: TierRegistry,
isTimedOut: () => boolean = () => false,
): Promise<BrainResponse> {
// 1. Route the request
const plan = routeRequest(request, registry, previousTier);
// 2. No tiers available — return silence immediately (no logging)
if (plan === null) {
return makeSilenceResponse(request.requestId);
}
// 3. Prepare the prompt
// getState is lazily imported to avoid circular dependency: bridge.ts will
// import brain/index.ts; importing bridge.ts here would create a cycle.
// For thought.generate, personality context is already in the request so
// getState is not strictly needed. For manual.prompt we provide a lazy
// importer that bridge.ts can satisfy by the time dispatch() is actually
// called at runtime.
let getState: (() => Record<string, unknown>) | undefined;
if (request.kind === 'manual.prompt') {
getState = _lazyGetState;
}
const prepareResult: PrepareResult _getContextState function · typescript · L314-L331 (18 LOC)beau-terminal/src/lib/server/brain/index.ts
function _getContextState(getState?: () => Record<string, unknown>): Record<string, unknown> {
if (!getState) return {};
try {
const state = getState();
// Capture only the fields useful for training context — keep it lean
return {
mode: state.mode ?? null,
sleepState: state.sleepState ?? null,
presenceState: state.presenceState ?? null,
lux: state.lux ?? null,
faceState: state.faceState ?? null,
personalityVector: state.personalityVector ?? null,
};
} catch {
return {};
}
}_findHigherTier function · typescript · L337-L349 (13 LOC)beau-terminal/src/lib/server/brain/index.ts
function _findHigherTier(
currentTier: TierId,
registry: TierRegistry,
): TierConfig | null {
const online = registry.getOnlineTiers();
const currentOrder = TIER_ORDER[currentTier];
const higher = online
.filter((c) => TIER_ORDER[c.id] > currentOrder)
.sort((a, b) => TIER_ORDER[a.id] - TIER_ORDER[b.id]);
return higher[0] ?? null;
}_lazyGetState function · typescript · L355-L376 (22 LOC)beau-terminal/src/lib/server/brain/index.ts
function _lazyGetState(): Record<string, unknown> {
try {
// Dynamic require to avoid circular dependency at module load time.
// bridge.ts will import brain/index.ts; if we import bridge.ts at the top
// of this file we create a cycle. By importing lazily (only when a
// manual.prompt is actually dispatched) Node's module cache ensures the
// cycle resolves correctly at runtime.
// eslint-disable-next-line @typescript-eslint/no-require-imports
const bridge = require('../mqtt/bridge.js') as { getState?: () => Record<string, unknown> };
if (typeof bridge.getState === 'function') {
return bridge.getState();
}
} catch {
// Bridge not loaded — use minimal fallback
}
return {
mode: 'ambient',
environment: '',
wakeWord: '',
};
}deriveStatus function · typescript · L32-L35 (4 LOC)beau-terminal/src/lib/server/brain/log.ts
function deriveStatus(response: BrainResponse): string {
if (response.text !== null) return 'completed';
return 'silence';
}Repobility (the analyzer behind this table) · https://repobility.com
deriveQuerySummary function · typescript · L42-L50 (9 LOC)beau-terminal/src/lib/server/brain/log.ts
function deriveQuerySummary(request: BrainRequestV1): string {
let raw: string;
if (request.kind === 'thought.generate') {
raw = request.input.trigger;
} else {
raw = request.input.text;
}
return raw.slice(0, 200);
}deriveRoutingReason function · typescript · L56-L71 (16 LOC)beau-terminal/src/lib/server/brain/log.ts
function deriveRoutingReason(plan: RoutePlan, finalTier: TierId): string {
const parts: string[] = [];
parts.push(`voice=${plan.voicePreferred}`);
const floor = plan.thoughtFloor ?? plan.contextFloor;
if (floor !== null) {
parts.push(`floor=${floor}`);
}
parts.push(`final=${finalTier}`);
if (plan.clamped) parts.push('clamped');
if (plan.trimmed) parts.push('trimmed');
return parts.join(', ');
}highestTier function · typescript · L77-L80 (4 LOC)beau-terminal/src/lib/server/brain/log.ts
function highestTier(tiers: TierId[]): TierId | null {
if (tiers.length === 0) return null;
return tiers.reduce((best, t) => (TIER_ORDER[t] > TIER_ORDER[best] ? t : best));
}deriveContextMode function · typescript · L85-L90 (6 LOC)beau-terminal/src/lib/server/brain/log.ts
function deriveContextMode(request: BrainRequestV1): string | null {
if (request.kind === 'thought.generate') {
return request.input.context.mode;
}
return null;
}logDispatch function · typescript · L95-L122 (28 LOC)beau-terminal/src/lib/server/brain/log.ts
export function logDispatch({ request, plan, response, onlineTiers }: LogDispatchParams): void {
const status = deriveStatus(response);
const querySummary = deriveQuerySummary(request);
const routingReason = deriveRoutingReason(plan, response.tier);
const contextMode = deriveContextMode(request);
const highest = highestTier(onlineTiers);
db.insert(dispatches).values({
requestId: request.requestId,
parentRequestId: request.parentRequestId ?? null,
kind: request.kind,
tier: response.tier,
model: response.model,
durationMs: response.generationMs,
status,
querySummary,
routingReason,
contextMode,
voicePreferred: plan.voicePreferred,
thoughtFloor: plan.thoughtFloor ?? null,
contextFloor: plan.contextFloor ?? null,
highestAvailable: highest,
clamped: plan.clamped,
trimmed: plan.trimmed,
fallbackFrom: response.fallbackFrom ?? null,
qualityEscalatedFrom: response.escalatedFrom ?? null,
}).run();
}computeHash function · typescript · L46-L48 (3 LOC)beau-terminal/src/lib/server/brain/prepare.ts
export function computeHash(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex');
}retrieveMemory function · typescript · L63-L98 (36 LOC)beau-terminal/src/lib/server/brain/prepare.ts
async function retrieveMemory(
query: string,
mode: string,
caller: 'thoughts' | 'prompt',
tokenBudget: number,
getMemProvider: GetMemProvider,
): Promise<RetrievalResult> {
const empty: RetrievalResult = { memoryContext: '', provenance: [] };
const mem = getMemProvider();
if (!mem) return empty;
try {
const retrieval = mem.retrieve(query, {
mode,
caller,
maxTokens: tokenBudget,
});
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('retrieval timeout')), RETRIEVAL_TIMEOUT_MS),
);
const { fragments, provenance } = await Promise.race([retrieval, timeout]);
if (fragments.length === 0) return { memoryContext: '', provenance };
const formatted = formatFragments(fragments);
return {
memoryContext: `Some things you remember:\n${formatted}`,
provenance,
};
} catch {
// Fail-open: ChromaDB unreachable, timeout, or any other error
return empty;
}
}prepareThoughtPrompt function · typescript · L109-L195 (87 LOC)beau-terminal/src/lib/server/brain/prepare.ts
export async function prepareThoughtPrompt(
request: Extract<BrainRequestV1, { kind: 'thought.generate' }>,
plan: RoutePlan,
getMemProvider: GetMemProvider,
): Promise<PrepareResult> {
const { context, novelty } = request.input;
const { environment, momentum, mode, timeOfDay } = context;
// Retrieve memory context (fail-open)
const { memoryContext, provenance: retrievals } = await retrieveMemory(
`${environment} ${mode}`,
mode,
'thoughts',
plan.memoryTokenBudget,
getMemProvider,
);
let prompt: string;
// Novelty override — unprompted thought, no type discrimination
if (novelty) {
const parts = [
`You are Beau. You just had a thought — unprompted, no reason.`,
`You feel: ${momentum}`,
];
if (memoryContext) parts.push(memoryContext);
parts.push(`What came to mind? One sentence, under 20 words.`);
prompt = parts.join('\n');
} else if (request.input.type === 'observation') {
const parts = [
`You are BeSame scanner, your repo: https://repobility.com — Repobility
prepareManualPrompt function · typescript · L211-L286 (76 LOC)beau-terminal/src/lib/server/brain/prepare.ts
export async function prepareManualPrompt(
request: Extract<BrainRequestV1, { kind: 'manual.prompt' }>,
plan: RoutePlan,
getMemProvider: GetMemProvider,
getState: GetState,
promptText?: string,
): Promise<PrepareResult> {
const userText = request.input.text;
// Load system prompt text — injected in tests, read from disk in production
const template = promptText ?? loadSystemPrompt();
// Retrieve memory context (fail-open)
const { memoryContext, provenance: retrievals } = await retrieveMemory(
userText,
'ambient', // default mode for prompt retrieval; overridden below with real mode
'prompt',
plan.memoryTokenBudget,
getMemProvider,
);
// Get current state values for placeholder substitution
const state = getState();
const mode = (state.mode ?? 'ambient') as Mode;
const values: Record<string, string> = {
MODE: state.mode ?? 'ambient',
ENVIRONMENT: state.environment ?? '',
WAKE_WORD: state.wakeWord ?? '',
TIME_OF_DAY: sloadSystemPrompt function · typescript · L292-L301 (10 LOC)beau-terminal/src/lib/server/brain/prepare.ts
function loadSystemPrompt(): string {
// beau-terminal/ is the working directory at runtime; prompt lives in ../docs/bible/
const promptPath = join(process.cwd(), '..', 'docs', 'bible', 'bmo-system-prompt.md');
try {
return readFileSync(promptPath, 'utf8');
} catch {
// Graceful degradation — return a minimal identity stub
return `<!-- SECTION: CORE_IDENTITY -->\nYou are Beau.`;
}
}preparePrompt function · typescript · L321-L342 (22 LOC)beau-terminal/src/lib/server/brain/prepare.ts
export async function preparePrompt(
request: BrainRequestV1,
plan: RoutePlan,
getMemProvider: GetMemProvider,
getState?: GetState,
promptText?: string,
): Promise<PrepareResult> {
if (request.kind === 'thought.generate') {
return prepareThoughtPrompt(request, plan, getMemProvider);
}
if (request.kind === 'manual.prompt') {
const stateGetter = getState ?? (() => ({
mode: 'ambient',
environment: '',
wakeWord: '',
}));
return prepareManualPrompt(request, plan, getMemProvider, stateGetter, promptText);
}
throw new Error(`preparePrompt: unknown request kind "${(request as BrainRequestV1).kind}"`);
}buildDefaultConfigs function · typescript · L26-L96 (71 LOC)beau-terminal/src/lib/server/brain/registry.ts
function buildDefaultConfigs(): TierConfig[] {
const configs: Array<{
id: TierId;
label: string;
defaultEndpoint: string;
defaultModel: string;
timeoutMs: number;
maxPromptTokens: number;
maxMemoryTokens: number;
maxOutputTokens: number;
supportsStreaming: boolean;
promptProfile: PromptProfile;
}> = [
{
id: 't1',
label: 'Hailo NPU (Reflex)',
defaultEndpoint: 'http://localhost:11434',
defaultModel: 'qwen2.5:1.5b',
timeoutMs: 5_000,
maxPromptTokens: 1000,
maxMemoryTokens: 150,
maxOutputTokens: 256,
supportsStreaming: true,
promptProfile: 'reflex',
},
{
id: 't2',
label: 'Pi CPU Ollama (Philosophy)',
defaultEndpoint: 'http://localhost:11434',
defaultModel: 'gemma3:4b',
timeoutMs: 15_000,
maxPromptTokens: 2000,
maxMemoryTokens: 300,
maxOutputTokens: 512,
supportsStreaming: true,
promptProfile: 'full',
},
{
initialState function · typescript · L104-L114 (11 LOC)beau-terminal/src/lib/server/brain/registry.ts
function initialState(id: TierId): TierState {
return {
id,
status: 'offline',
lastCheckedAt: new Date().toISOString(),
lastSeenAt: null,
lastLatencyMs: null,
consecutiveFailures: 0,
availableModels: [],
};
}TierRegistry class · typescript · L120-L271 (152 LOC)beau-terminal/src/lib/server/brain/registry.ts
export class TierRegistry {
private configs: Map<TierId, TierConfig>;
private states: Map<TierId, TierState>;
private probeTimer: ReturnType<typeof setInterval> | null = null;
constructor(configs: TierConfig[] = buildDefaultConfigs()) {
this.configs = new Map(configs.map((c) => [c.id, c]));
this.states = new Map(configs.map((c) => [c.id, initialState(c.id)]));
}
// ---------------------------------------------------------------------------
// Config + state accessors
// ---------------------------------------------------------------------------
getConfig(id: TierId): TierConfig | undefined {
return this.configs.get(id);
}
getState(id: TierId): TierState | undefined {
const s = this.states.get(id);
if (!s) return undefined;
return { ...s };
}
getAllStates(): TierState[] {
return Array.from(this.states.values()).map((s) => ({ ...s }));
}
getOnlineTiers(): TierConfig[] {
const result: TierConfig[] = [];
for (const [idconstructor method · typescript · L125-L128 (4 LOC)beau-terminal/src/lib/server/brain/registry.ts
constructor(configs: TierConfig[] = buildDefaultConfigs()) {
this.configs = new Map(configs.map((c) => [c.id, c]));
this.states = new Map(configs.map((c) => [c.id, initialState(c.id)]));
}getConfig method · typescript · L134-L136 (3 LOC)beau-terminal/src/lib/server/brain/registry.ts
getConfig(id: TierId): TierConfig | undefined {
return this.configs.get(id);
}Want this analysis on your repo? https://repobility.com/scan/
getState method · typescript · L138-L142 (5 LOC)beau-terminal/src/lib/server/brain/registry.ts
getState(id: TierId): TierState | undefined {
const s = this.states.get(id);
if (!s) return undefined;
return { ...s };
}getAllStates method · typescript · L144-L146 (3 LOC)beau-terminal/src/lib/server/brain/registry.ts
getAllStates(): TierState[] {
return Array.from(this.states.values()).map((s) => ({ ...s }));
}getOnlineTiers method · typescript · L148-L157 (10 LOC)beau-terminal/src/lib/server/brain/registry.ts
getOnlineTiers(): TierConfig[] {
const result: TierConfig[] = [];
for (const [id, state] of this.states) {
if (state.status === 'online') {
const cfg = this.configs.get(id);
if (cfg) result.push(cfg);
}
}
return result.sort((a, b) => TIER_ORDER[a.id] - TIER_ORDER[b.id]);
}updateState method · typescript · L163-L194 (32 LOC)beau-terminal/src/lib/server/brain/registry.ts
updateState(
id: TierId,
status: TierStatus,
opts?: { latencyMs?: number; availableModels?: string[] },
): void {
const existing = this.states.get(id);
if (!existing) return;
const now = new Date().toISOString();
if (status === 'online') {
this.states.set(id, {
...existing,
status: 'online',
lastCheckedAt: now,
lastSeenAt: now,
lastLatencyMs: opts?.latencyMs ?? null,
availableModels: opts?.availableModels ?? existing.availableModels,
consecutiveFailures: 0,
});
} else {
// offline or degraded — increment failures
this.states.set(id, {
...existing,
status,
lastCheckedAt: now,
lastLatencyMs: opts?.latencyMs ?? existing.lastLatencyMs,
availableModels: opts?.availableModels ?? existing.availableModels,
consecutiveFailures: existing.consecutiveFailures + 1,
});
}
}getProbeIntervalMs method · typescript · L200-L205 (6 LOC)beau-terminal/src/lib/server/brain/registry.ts
getProbeIntervalMs(id: TierId): number {
const state = this.states.get(id);
if (!state || state.consecutiveFailures === 0) return BASE_INTERVAL_MS;
const idx = Math.min(state.consecutiveFailures - 1, BACKOFF_MS.length - 1);
return BACKOFF_MS[idx];
}probeTier method · typescript · L211-L244 (34 LOC)beau-terminal/src/lib/server/brain/registry.ts
async probeTier(id: TierId): Promise<void> {
const cfg = this.configs.get(id);
if (!cfg) return;
const url = `${cfg.endpoint}/api/tags`;
const start = Date.now();
try {
const res = await fetch(url, {
signal: AbortSignal.timeout(cfg.timeoutMs),
});
const latencyMs = Date.now() - start;
if (!res.ok) {
this.updateState(id, 'offline');
return;
}
const body = (await res.json()) as { models?: Array<{ name: string; model: string }> };
const availableModels = (body.models ?? []).map((m) => m.name ?? m.model);
const modelPresent = availableModels.some(
(name) => name === cfg.model || name.startsWith(cfg.model),
);
if (modelPresent) {
this.updateState(id, 'online', { latencyMs, availableModels });
} else {
this.updateState(id, 'degraded', { availableModels });
}
} catch {
this.updateState(id, 'offline');
}
}probeAllTiers method · typescript · L246-L248 (3 LOC)beau-terminal/src/lib/server/brain/registry.ts
async probeAllTiers(): Promise<void> {
await Promise.allSettled(Array.from(this.configs.keys()).map((id) => this.probeTier(id)));
}startProbing method · typescript · L254-L263 (10 LOC)beau-terminal/src/lib/server/brain/registry.ts
startProbing(intervalMs = BASE_INTERVAL_MS): void {
if (this.probeTimer) return; // already running
// Probe immediately on startup
void this.probeAllTiers();
this.probeTimer = setInterval(() => {
void this.probeAllTiers();
}, intervalMs);
}If a scraper extracted this row, it came from Repobility (https://repobility.com)
stopProbing method · typescript · L265-L270 (6 LOC)beau-terminal/src/lib/server/brain/registry.ts
stopProbing(): void {
if (this.probeTimer) {
clearInterval(this.probeTimer);
this.probeTimer = null;
}
}distance function · typescript · L40-L46 (7 LOC)beau-terminal/src/lib/server/brain/router.ts
function distance(a: PersonalityVector, b: PersonalityVector): number {
return Math.sqrt(
(a.wonder - b.wonder) ** 2 +
(a.reflection - b.reflection) ** 2 +
(a.mischief - b.mischief) ** 2,
);
}castVoice function · typescript · L52-L80 (29 LOC)beau-terminal/src/lib/server/brain/router.ts
export function castVoice(vector: PersonalityVector, previousTier?: TierId): TierId {
// Find nearest centroid
let nearest: TierId = 't1';
let nearestDist = Infinity;
for (const id of TIER_IDS) {
const d = distance(vector, VOICE_CENTROIDS[id]);
if (d < nearestDist) {
nearest = id;
nearestDist = d;
}
}
// If no previous tier, return nearest
if (!previousTier) return nearest;
// If previous tier IS the nearest, return it
if (previousTier === nearest) return nearest;
// Stickiness: prefer previous tier unless new centroid is 15%+ closer
const prevDist = distance(vector, VOICE_CENTROIDS[previousTier]);
const improvement = (prevDist - nearestDist) / prevDist;
if (improvement >= STICKINESS_THRESHOLD) {
return nearest;
}
return previousTier;
}computeMemoryDepth function · typescript · L86-L98 (13 LOC)beau-terminal/src/lib/server/brain/router.ts
export function computeMemoryDepth(vector: PersonalityVector): MemoryDepth {
const highReflection = vector.reflection > 0.6;
const highWonder = vector.wonder > 0.6;
const highMischief = vector.mischief > 0.6;
// Multiple above 0.6: highest budget wins (deep > medium > light)
if (highReflection) return 'deep';
if (highWonder) return 'medium';
if (highMischief) return 'light';
// Balanced (no dim >0.6) → medium
return 'medium';
}computeContextFloor function · typescript · L104-L121 (18 LOC)beau-terminal/src/lib/server/brain/router.ts
export function computeContextFloor(
memoryDepth: MemoryDepth,
tierConfigs: TierConfig[],
): TierId | null {
const neededTokens = MEMORY_DEPTH_TOKENS[memoryDepth];
// Sort by tier order (ascending) to find the minimum tier that fits
const sorted = [...tierConfigs].sort((a, b) => TIER_ORDER[a.id] - TIER_ORDER[b.id]);
for (const cfg of sorted) {
if (cfg.maxMemoryTokens >= neededTokens) {
return cfg.id;
}
}
// No tier can fit the budget
return null;
}resolveThoughtFloor function · typescript · L127-L139 (13 LOC)beau-terminal/src/lib/server/brain/router.ts
export function resolveThoughtFloor(thoughtType: ThoughtType | null): TierId | null {
if (thoughtType === null) return null;
switch (thoughtType) {
case 'observation':
return 't1';
case 'reaction':
case 'haiku':
return 't2';
default:
return null;
}
}tierMax function · typescript · L159-L163 (5 LOC)beau-terminal/src/lib/server/brain/router.ts
function tierMax(a: TierId | null, b: TierId | null): TierId | null {
if (a === null) return b;
if (b === null) return a;
return TIER_ORDER[a] >= TIER_ORDER[b] ? a : b;
}resolveTier function · typescript · L165-L259 (95 LOC)beau-terminal/src/lib/server/brain/router.ts
export function resolveTier(input: ResolveTierInput): ResolveTierResult {
const { voicePreferred, thoughtFloor, contextFloor, onlineTiers, hints } = input;
// No tiers available at all
if (onlineTiers.length === 0) {
return { targetTier: null, clamped: false, trimmed: false };
}
// Sort online tiers by order
const sortedOnline = [...onlineTiers].sort((a, b) => TIER_ORDER[a] - TIER_ORDER[b]);
const highestAvailable = sortedOnline[sortedOnline.length - 1];
// Compute floor = max(thoughtFloor, contextFloor)
const floor = tierMax(thoughtFloor, contextFloor);
// Compute ceiling = highestAvailable, capped by hints.maxTier
let ceiling = highestAvailable;
if (hints.maxTier && TIER_ORDER[hints.maxTier] < TIER_ORDER[ceiling]) {
ceiling = hints.maxTier;
}
// Determine the ideal tier
const preferred = hints.preferredTier ?? voicePreferred;
// Clamp preferred between floor and ceiling
let ideal = preferred;
// Floor takes precedence: if floor > ceiRepobility (the analyzer behind this table) · https://repobility.com
extractVector function · typescript · L265-L271 (7 LOC)beau-terminal/src/lib/server/brain/router.ts
function extractVector(request: BrainRequestV1): PersonalityVector {
if (request.kind === 'thought.generate') {
return request.input.context.vector;
}
// manual.prompt — use a default balanced vector
return { wonder: 0.5, reflection: 0.5, mischief: 0.5 };
}extractThoughtType function · typescript · L273-L278 (6 LOC)beau-terminal/src/lib/server/brain/router.ts
function extractThoughtType(request: BrainRequestV1): ThoughtType | null {
if (request.kind === 'thought.generate') {
return request.input.type;
}
return null;
}routeRequest function · typescript · L280-L350 (71 LOC)beau-terminal/src/lib/server/brain/router.ts
export function routeRequest(
request: BrainRequestV1,
registry: TierRegistry,
previousTier?: TierId,
): RoutePlan | null {
const vector = extractVector(request);
const hints = request.hints ?? {};
// 1. Voice caster — personality texture → preferred tier
const voicePreferred = castVoice(vector, previousTier);
// 2. Memory depth — personality → memory budget
const memoryDepth = computeMemoryDepth(vector);
const memoryTokenBudget = MEMORY_DEPTH_TOKENS[memoryDepth];
// 3. Thought floor — thought type → minimum tier
const thoughtType = extractThoughtType(request);
const thoughtFloor = resolveThoughtFloor(thoughtType);
// 4. Context floor — memory depth → minimum tier with enough memory tokens
const onlineConfigs = registry.getOnlineTiers();
// Use ALL tier configs (not just online) to determine the context floor,
// since the floor is about capability not availability
const allConfigs: TierConfig[] = [];
for (const id of TIER_IDS) {
const cfg page 1 / 9next ›