2026-11-27 16:22 UTC

BYOBrain documents a game SDK for optional local AI

state: expiredheat: lowuncertainty: mediumrelevance: mediumlocal-llm game-development on-device-aipathmap

What is this?

BYOBrain is presented in developer documentation as a web SDK for connecting games to AI through a player-mounted browser extension or web iframe. The documentation describes chat requests with priority levels, streaming, cancellation, and connection-state callbacks, and advises developers to keep games playable with scripted fallbacks when AI is slow or unavailable. The linked documentation is available, but the supplied evidence does not independently verify the implementation or how widely it is used. There is also a source mismatch: the Hacker News post is titled “I made an open-web protocol for local LLM storage sharing” and is attributed to pathmap, while its linked page is titled “BYOBrain Web SDK - Developer Documentation” and is associated with a different apparent name. The relationship between those claims and authors is unclear.

Why it matters

The interesting idea is not simply adding NPC dialogue, but treating variable-speed, player-local inference as an optional game capability rather than something gameplay must wait on. If the documented interface works as described, priorities, cancellation, pre-generation and scripted fallbacks could make local AI more practical in games while limiting dependence on network access or remote inference. Evidence here establishes a published integration guide, not performance, adoption, or a confirmed release history.

Current assessment

The linked BYOBrain documentation gives a concrete integration pattern: mount a connection UI, send chat requests, assign high/normal/low priorities, stream output, and cancel pending generation. Its guide recommends timeouts, scripted fallbacks, validating generated text, and pre-cooking ambient dialogue so gameplay does not block on inference. The documentation says the SDK detects an extension or falls back to a web iframe, but the supplied evidence does not establish where inference runs in each mode, what models or devices are supported, or whether priority preemption and cancellation behave as described in practice. These are documentation claims, not independently demonstrated results. The Hacker News title suggests a local-LLM storage-sharing protocol, which is not what the linked SDK guide primarily describes; the discrepancy and differing apparent authorship remain unresolved. No supplied evidence establishes adoption, benchmarks, or commercial impact.

Measured heat

now 0 pts/hpeak 0 pts/hcomments 0/hpeers p14momentum: steady2 platformsage 337h
points/hour across evidence · reading as of 2026-11-23 02:22:21.694677+11:00 · deterministic, not a model opinion

How the heat travelled

11-08 15:23 (minted)⭐ origin echo-reconstructedThe linked project page is the primary artifact found; no upstream tweet, paper, or other source was referenced. It describes “Bring Your Ow
Joshua D. D. (joshuadd79) on other (echo) · attributed from hn.story.50413739 · published time unknown
—
11-08 14:38first on hacker news · published · lag ?I made an open-web protocol for local LLM storage sharing
pathmap
—
11-08 14:38amplified on hacker news 👑hn.story.50413739
pathmap
peak 2 · 0 comments · 104% of case engagement
11-08 15:20our radar first saw it · lag ?discovery anchor: hn.story.50413739—

Evidence (2) — ⭐ canonical anchor

sourceobjectauthorscorecomments
🟧 hnI made an open-web protocol for local LLM storage sharing
Retrieved article excerpt

Open article · Retrieved 2026-11-08T15:21:03.873537+00:00

# Building with BYOBrain

A guide to building resilient, non-blocking games powered by local AI.

Because Bring Your Own Brain (BYOB) runs on the **player's local hardware** (via browser extension or web fallback), inference speeds can vary wildly from high-end GPUs to integrated mobile chips. Designing for BYOB requires a shift in mindset: the game must never wait for the AI.

#### The Golden Rules of BYOB Design

**1. Fallback is King:** Your game must be 100% playable without AI. If the model is slow, offline, or produces gibberish, the game should instantly fall back to standard scripted lines.

**2. The Player Always Wins:** Player actions (closing a menu, walking away, starting combat) must immediately interrupt and cancel any background AI generation to save GPU compute.

**3. Never Block the Event Loop:** The game state should continue ticking while the AI thinks. Wrap requests in timeouts.

## 1. Basic Setup & Mounting

Load the V2 SDK script and instantiate the brain. You can mount the connection UI anywhere in your DOM. The SDK automatically detects if the user has the high-performance BYOB Extension installed, or safely falls back to the web iframe.

```
<!-- Load the SDK -->
<script src="https://bringyourownbrain.org/byob-web-sdk-v2.js"></script>

<!-- Container for the connect button -->
<div id="connector-slot"></div>

<script>
const brain = new BringYourOwnBrainWeb({
    container: document.getElementById('connector-slot'),
    width: '210px',
    height: '40px',
    onState: (state, msg) => {
        if (state === 'ready') console.log('Brain connected!');
    }
});
brain.mount(); // Renders the iframe
</script>
```

## 2. The Non-Blocking Request Pattern

Do not just `await brain.chat()`. Instead, wrap requests with a `Promise.race` timeout so your game doesn't hang if the user's GPU is overloaded.

```
/**
 * Safe, cancellable wrapper for AI requests.
 * @param {Array} msgs - Messages array
 * @param {Object} opts - BYOB options (priority, max_tokens, etc)
 * @param {Number} timeoutMs - Max time to wait before bailing
 */
function askBrainSafe(msgs, opts, timeoutMs = 8000) {
    const result = { cancel: () => {}, promise: null };
    
    try {
        // 1. Initiate request
        const p = brain.chat(msgs, opts);
        
        // 2. Expose the native cancel method
        result.cancel = () => { try { p.cancel(); } catch(e){} };
        
        // 3. Setup Race Condition for Timeout
        let timer;
        const to = new Promise((_, reject) => {
            timer = setTimeout(() => {
                result.cancel(); // kill generation
                reject(new Error('timeout'));
            }, timeoutMs);
        });

        // 4. Return the raced promise
        result.promise = Promise.race([p, to]).finally(() => clearTimeout(timer));
    } catch(e) {
        result.promise = Promise.reject(e);
    }
    
    return result;
}
```

## 3. Priorities & Compute Management

The BYOB engine supports a queue system based on priority. Sending a `high` priority task instantly preempts and pauses lower priority tasks.

- high **Direct Player Interaction:** The player clicked a character and is waiting for a response. Maximize tokens/speed.
- normal **Reactions:** The player bumped into an NPC or triggered a quick event.
- low **Ambient Chatter:** Background bots talking to each other. Will be dropped automatically if a high priority task comes in.

```
// The player is waiting for this:
const reply = brain.chat(messages, { 
    priority: 'high', 
    max_tokens: 40,
    temperature: 0.8
});

// A background NPC is just thinking:
const ambient = brain.chat(messages, { 
    priority: 'low', 
    max_tokens: 20 
});
```

## 4. Cancellation (Stop the GPU)

If an NPC is talking or generating text, and the player walks away or attacks them, **you must cancel the promise**. This frees up the user's hardware immediately.

```
let currentAiTask = null;

function chatWithNPC(npc, text) {
    // If they were already generating something else, kill it!
    if (currentAiTask) {
        currentAiTask.cancel(); 
    }

    currentAiTask = askBrainSafe([...], { priority: 'high' }, 5000);

    currentAiTask.promise
        .then(reply => npc.say(reply))
        .catch(err => {
            // Handle timeout or manual cancellation gracefully
            if (err.cancelled) return; 
            npc.say("I lost my train of thought..."); // Fallback!
        })
        .finally(() => currentAiTask = null);
}

// When the player triggers combat:
function startCombat() {
    if (currentAiTask) currentAiTask.cancel();
}
```

## 5. Pre-cooking & Caching (The Ambient Secret)

Don't generate ambient idle lines on the fly. When the game engine detects the player is idle, use `low` priority to "pre-cook" lines and store them in an array. When an NPC needs to speak idly, pop a line from the array instantly.

```
// Run this inside your game tick/loop:
function ambientTick() {
    // Only generate if we aren't busy and the player hasn't done anything recently
    if (isAiBusy || playerIsActive) return;

    const idleNPCs = getNPCsWithEmptyCache();
    if (idleNPCs.length > 0) {
        const target = idleNPCs[0];
        
        // Generate a line in the background
        const task = askBrainSafe(
            [{role: 'system', content: 'Generate a short idle thought.'}], 
            { priority: 'low' }, 
            12000 // give it plenty of time
        );

        task.promise.then(line => {
            if (validateLine(line)) {
                target.dialogueCache.push(line); // Store for later!
            }
        }).catch(() => { /* quietly fail */ });
    }
}

// When the NPC actually needs to speak on screen:
function npcIdleSpeak(npc) {
    if (npc.dialogueCache.length > 0) {
        npc.say(npc.dialogueCache.shift()); // Instant delivery!
    } else {
        npc.say(npc.defaultScriptedLines[0]); // Scripted fallback
    }
}
```

## 6. Data Validation

Local AI models hallucinate. They might spit out Markdown, empty brackets, or system prompts. **Never pipe AI text directly to your UI without cleaning it first.** If validation fails, throw it away and use a scripted line.

```
function cleanAiText(raw) {
    // Remove HTML tags, markdown artifacts, and trim
    let s = String(raw || '').replace(/<[^>]*>/g, '').trim();
    
    // Remove common AI prefix bugs (e.g., "Bot Name: ")
    s = s.replace(/^(NPC|Bot|Assistant)\s*:\s*/i, '');
    
    return s;
}

function isValidLine(s) {
    if (!s || s.length < 2 || s.length > 200) return false;
    
    // Catch common model breakages
    if (/\[error|
```

## API Reference Overview

#### `new BringYourOwnBrainWeb(options)`

Creates the SDK instance.

- `container`: DOM element to mount the iframe button in.
- `width` / `height`: CSS strings for the iframe dimensions.
- `onState(state, message)`: Callback triggered on state changes (`'idle'`, `'ready'`, `'error'`).

#### `brain.chat(messages, options) -> Promise`

Sends a chat completion request to the connected model.

- `messages`: Array of objects `[{role: 'system', content: '...'}, {role: 'user', content: '...'}]`
- `options.priority`: `'high'`, `'normal'`, or `'low'`.
- `options.max_tokens`: Integer limit for the response.
- `options.temperature`: Float between 0.0 and 2.0.
- `options.onChunk(text)`: Callback for streaming tokens in real-time.

**Returns:** A Promise that resolves to a string. The Promise object has an attached `.cancel()` method to abort the request.

#### `brain.open()`

Programmatically opens the BYOB hub connection modal without requiring a click inside the iframe. Best used alongside custom UI.
pathmap20
🟧 echo.other ⭐The linked project page is the primary artifact found; no upstream tweet, paper, or other source was referenced. It describes “Bring Your OwJoshua D. D. (joshuadd79)——

Interpretation history

Decision trace