AI BAST Agent Library
Agent LibraryWorkshopsAcademyGet an agent runningGet started

Under the hood

Longer engineering notes, kept as written. These assume more background than the notes above.

Several AI Agents, One Repository: How We Keep Them From Overwriting Each Other

This library is now changed by more than one AI agent at the same time, next to the people who maintain it. One agent records narration, another builds an API for the guide, a third works on the installers. The first problem was not quality. It was collisions: two agents editing the same file, one rebuilding a generated file the other had just changed, a fix quietly undone by a later push.

We did not invent a new process. Large open-source projects solved this years ago for hundreds of human contributors: every change lives on its own topic branch, branches meet only in one integration branch, and everything is tested there. AI agents are simply very fast contributors, so the same rules apply, written down plainly enough for an agent to follow.

The rules

  1. One worktree per change. Each agent works in its own git worktree, on its own branch, one pull request each. Two agents never share a folder. Worktrees live in a lasting place, not a temporary folder a restart can clear.
  2. Staging is the only place work meets. Changes arrive by pull request with a merge commit after checks pass. No direct pushes, no force-pushes. Rebase onto staging before starting and again right before pushing.
  3. Look before touching shared files. List the open pull requests and check them for the same files. If another one touches it, keep the change small and rebase after it merges. Prefer adding a new module over editing a shared builder.
  4. Generated files are rebuilt, never merged by hand. After a rebase, rerun the build and commit its output. A hand-merged generated file is a silent bug.
  5. Small pull requests, one concern, evidence as counts. "384 of 384 scenarios played" instead of "works". Anything not exercised is called unverified.
  6. Test together, report rather than revert. After every merge, rerun the live checks. If one change breaks another, report it on the pull request that caused it. An agent never reverts another agent's work on its own, and never weakens a check to get green.
  7. Never in any branch: secrets, customer data, or content from outside the repository's own sources.

What it looked like in practice

On the day we adopted it, three pull requests were open against staging at once. Two of them changed the same generated catalog file. Neither agent hand-merged it: the rule told the second one to rebuild the file after the first merged. Each pull request reported its tests before and after the change, so a pre-existing failure was visible as pre-existing instead of being blamed on the newest arrival.

Why write it down for agents

An agent follows what it can read. A rule that lives only in a maintainer's head gets rediscovered by every new session, usually after the collision. The standard is a short file in the repository, linked from the instructions every agent reads first, with a seven-step checklist at the end. Read it in docs/MULTI-AGENT-DEVELOPMENT.md and use it in your own repositories.

You Don't Need a MITM Proxy to Reverse-Engineer an AI Agent Protocol — Just Read the SDK

A recent Lighthouse Newsletter piece put GitHub Copilot's Electron traffic behind mitmproxy to figure out what the client actually does at runtime, versus what its source merely allows. It's a legitimate technique — Electron apps are opaque black boxes when the vendor doesn't ship source. But it made us ask a narrower question: for Microsoft's new Copilot Studio "agentic loop" harness — the CLI-authored agent runtime behind pac copilot, the Copilot Studio plugin, and third-party streaming-chat playgrounds — do you actually need to intercept traffic at all?

The answer, it turns out, is no. The entire wire protocol is sitting in a published npm package. No certificate pinning to defeat, no proxy to stand up — just npm pack and a text editor.

Two things converged

First, Microsoft open-sourced microsoft/copilot-studio-plugin (the target of aka.ms/CopilotStudioPlugin), the successor to skills-for-copilot-studio. It's an experimental CLI-agent authoring plugin, and its scripts/src/chat-with-agent.js is a complete, commented reference client for talking to a CLI/agentic-loop agent.

Second, a community write-up — "Streaming Responses in Copilot Studio" — documented, from the outside, the exact gotchas you hit building a live progressive-response chat UI against this runtime: bubbles that explode into 150+ fragments, a "cold" observable with only one subscriber slot, auto-scroll that stalls on in-place updates, and a Direct Line opt-in you have to know to ask for.

Both are describing the same underlying wire protocol from two different vantage points — one from the client SDK's source, one from empirical black-box discovery. We pulled the actual SDK apart to confirm it.

Finding the real source of truth

Neither copilot-studio-plugin nor pac implements the wire protocol itself. Both depend on @microsoft/agents-copilotstudio-client, a public npm package. One npm pack @microsoft/agents-copilotstudio-client later, its compiled dist/src/copilotStudioClient.js lays out the entire mechanism in ~500 lines:

const eventSource = createEventSource({
  url,
  headers: {
    Authorization: `Bearer ${token}`,
    'User-Agent': UserAgentHelper.getProductInfo(),
    'Content-Type': 'application/json',
    Accept: 'text/event-stream'
  },
  body: body ? JSON.stringify(body) : undefined,
  method,
});

for await (const { data, event } of eventSource) {
  if (data && event === 'activity') {
    const activity = Activity.fromJson(data);
    const streamingEntity = activity.entities?.find(
      e => e.type === 'streaminfo' && e.streamType === 'streaming'
    );
    // ...accumulate by streamId + streamSequence, yield activity
  } else if (event === 'end') {
    break; // stream complete
  }
}

That's the whole transport: Server-Sent Events carrying Bot Framework Activity objects, Accept: text/event-stream, an event: activity per chunk and a terminal event: end.

The streamId/streamSequence trick — confirmed, not guessed

The playground's biggest "gotcha" was that every interim chunk arrives as a Typing activity with its own unique activity id, while all chunks belonging to one answer share a streamId. Their fix was to stamp id = streamId so Web Chat groups chunks into one growing bubble instead of 150 stacked ones.

Reading the SDK source shows this isn't an incidental workaround — it's exactly what the SDK itself does internally, one layer down, for its own text accumulation:

if (id && sequence) {
  if (streamMap.has(id)) {
    streamMap.get(id).push({ text, sequence });
  } else {
    streamMap.set(id, [{ text, sequence }]);
  }
  activity.text = streamMap.get(id)
    .sort((a, b) => a.sequence - b.sequence)
    .map(item => item.text)
    .join('');
}

The SDK also carries a legacy fallback most consumers wouldn't discover without exactly the kind of empirical, "old style vs. new style" debugging the playground describes: if entities[].type === "streaminfo" is absent, it checks activity.channelData.streamType === "streaming" instead. Two protocol generations, same client, quietly reconciled.

The lesson: before reaching for a MITM proxy, check whether the client is already public. Microsoft ships the actual protocol implementation as an npm package consumed by pac, the Copilot Studio plugin, and any Direct-to-Engine integration. Reading compiled, sourcemapped JS you can npm pack is strictly easier — and more authoritative — than reconstructing behavior from captured traffic. Traffic capture is for verifying the parts nobody ships source for. When they do ship it, read that first.

What we mapped end-to-end

  • Endpoint shape: CLI/agentic-loop agents (recognizer CLIAgentRecognizer / CLICopilotRecognizer) are served at https://<env>.<n>.environment.<cloud-suffix>/copilotstudio/agenticruntime/3p/dataverse-backed/authenticated/bots/<schemaName>?api-version=1, with per-cloud host suffixes and a 30/2 vs. 31/1 environment-GUID split depending on cloud (Prod/FirstRelease vs. everything else).
  • Auth: MSAL device-code, public client, scope CopilotStudio.Copilots.Invoke, token cached through the OS keychain with a plaintext-file fallback when native modules can't load.
  • Conversation lifecycle: startConversationStreaming() opens the SSE stream and optionally emits a start event; a response header can seed the conversation id if the body didn't; an island-experimental-url header can hot-swap the connect URL mid-flow.
  • Activity taxonomy: informative (reasoning steps like "Generating plan…"), streaming (cumulative text chunks — the playground saw 150+ per answer), final (the concluded message activity).

Why this matters beyond one SDK

The instinct to reach straight for a proxy is understandable — it's the general-purpose tool that works regardless of whether source is available. But for any agent platform built by a vendor that also publishes its client libraries, static analysis of that published client is faster, gives you sourcemaps and comments instead of raw bytes on the wire, and tells you the intended contract rather than one observed session's incidental behavior. MITM is still the right tool for closed clients like Claude Desktop or ChatGPT Desktop's Electron shell. It's the wrong first step when the vendor already shipped you the protocol in node_modules.

How a Background Thread Silently Ate Your Login

We shipped an account switcher in v0.5.4. It worked great — unless you first signed in with a GitHub account that didn't have Copilot access. When you switched to the right account, the UI stayed stuck on "Waiting for authorization..." forever. The fix was a six-line architectural change, but the bug exposed a pattern worth documenting.

The setup: two callers, one resource

The brainstem's device code login flow has two consumers. A background thread (_bg_poll_loop) polls GitHub so the token gets captured even if the browser disconnects. And the client polls POST /login/poll every 5 seconds so the UI updates when auth completes.

Both callers invoked the same function: poll_device_code(). That function, on success, saves the token and clears the _pending_login state. Whoever gets there first wins the token. The loser finds _pending_login empty, returns None, and tells the client {"status": "pending"}. Forever.

Background thread Client poll (/login/poll) │ │ ├── poll_device_code() ────┐ │ │ ✓ got token │ │ │ ✓ cleared state ───────┤ │ │ │ ├── poll_device_code() │ │ │ ✗ state empty → None │ │ │ returns {"pending"} │ │ │ │ │ ├── ...forever ▼ ▼ ▼

Why it only showed up on account switch

On a normal first login, the race exists but is harmless — either caller reports success and the UI dismisses. On an account switch, the first (wrong) account goes through the full device code flow successfully at the GitHub level. GitHub grants a token. But the Copilot token exchange fails because the account has no Copilot license. The background thread catches this error silently, and the client is left polling an empty _pending_login dict.

The second login attempt (correct account) hits the same race. If the background thread wins — which it reliably does because it's already polling at the right interval — the client never sees the result.

The fix: single-writer pattern

The solution is to stop having two callers compete for the same resource. We introduced a shared _login_result dict. The background thread is now the sole caller of poll_device_code(). When it gets a result — success or failure — it writes to _login_result.

The /login/poll endpoint no longer calls poll_device_code() at all. It just reads _login_result. Python's GIL makes dict assignment atomic, so no locks are needed.

_login_result = {}  # Written by bg thread only

def _bg_poll_loop():
    token = poll_device_code()
    if token:
        try:
            get_copilot_token()
            _login_result = {"status": "ok", ...}
        except NO_COPILOT_ACCESS:
            _login_result = {"status": "error", ...}

@app.route("/login/poll")
def login_poll():
    if _login_result:          # bg thread wrote something
        return jsonify(_login_result)
    if not _pending_login:     # no flow in progress
        return jsonify({"status": "expired"})
    return jsonify({"status": "pending"})  # still waiting
Pattern: When a background thread and a request handler both need the result of the same operation, don't let them race to call it. Have one writer and N readers. The writer owns the function call; the readers check a shared result.

Bonus fixes

  • NO_COPILOT_ACCESS surfaces to the UI. Previously swallowed — the user saw "Authenticated!" then got errors on first chat. Now the login overlay shows "username doesn't have Copilot access" with "Switch account" and "Sign up for Copilot" links.
  • Client poll has a timeout. 180 attempts at 5-second intervals (15 minutes, matching GitHub's device code expiry). No more infinite loops.
  • Stale Copilot cache cleared on new flow. Starting a fresh device code now wipes .copilot_session and the in-memory cache, so a previous account's session can't bleed through.

The lesson

Background threads that "help" by doing the same work as a request handler create races that only show up under specific timing. The thread was added to capture tokens when the browser disconnects — a real need. But it should have been the only writer from day one, with the HTTP endpoint as a passive reader. Adding a background optimization to an existing request path requires rethinking ownership, not just adding another caller.

Why We Killed Remote Agents (For Now)

The brainstem shipped with a feature that felt magical: paste a GitHub repo URL, toggle agents on, and they'd hot-load into your running server. No restart, no file copying. It worked by fetching manifest.json from the repo, downloading individual *_agent.py files, shimming their imports, and injecting them into the running Python process.

We removed all of it in v0.1.0. Here's why.

The complexity cost

Remote agent loading touched almost every layer of the system. It required URL normalization (handling github.com/, owner/repo, GitHub Pages URLs), manifest fetching (with three fallback strategies), file downloads, sys.path manipulation, sys.modules shimming, auto-pip-install on import failures, persistent config in .repos.json, restore-on-startup logic, and four HTTP endpoints for the UI to manage it all.

That's a lot of surface area for a feature whose primary value — making agents available — can be solved by just dropping a .py file into a folder.

The statelessness argument

The brainstem is designed to deploy as an Azure Function. Azure Functions are stateless by design — each invocation starts clean. Caching agents in memory and hot-loading from remote repos assumes a long-lived process. That assumption breaks in production.

By making agent loading stateless (fresh discovery every call, no cache, no remote state), we made the brainstem behave identically whether it's running locally on Flask or deployed as a serverless function. Same code path everywhere.

Design principle: If it works differently in dev vs prod, it's a bug in the architecture, not a feature.

What stays

The import shims (_register_shims) still exist. They're valuable for a different reason: agents written for the Azure deployment import utils.azure_file_storage, and the shims redirect those imports to local_storage.py so the same agent code runs locally without modification. That's a portability feature, not a remote-loading feature.

The auto-pip-install logic also stays. If a local agent imports beautifulsoup4 and it's not installed, the brainstem installs it and retries. That makes onboarding frictionless — drop in an agent, the brainstem figures out the deps.

The path forward

Remote agents will likely return, but as a first-class packaging system rather than a runtime hot-loader. Think: brainstem install github.com/org/agents that clones the repo into your local agents folder, resolves dependencies, and you're done. Install-time, not runtime. Explicit, not magic.

agents/ ├── hello_agent.py ← local, loads automatically ├── my_custom_agent.py ← local, loads automatically ├── context_memory_agent.py ← local, loads automatically └── experimental/ └── converter_agent.py ← excluded from auto-discovery

Version Tracking with a Plain Text File

The brainstem installs via a one-liner: curl ... | bash. That same one-liner should also handle upgrades. The question is: how does the installer know whether to upgrade?

The approach

A single file — rapp_brainstem/VERSION — contains the semver string. That's it. No package registry, no GitHub releases API, no git describe parsing.

$ cat rapp_brainstem/VERSION
0.1.0

The installer does two things:

  • Reads the local VERSION file from ~/.brainstem/src/rapp_brainstem/VERSION
  • Fetches the remote VERSION from the raw GitHub URL

If they match, print "Already up to date" and exit. If remote is newer, proceed with the full install flow (git pull, pip install, CLI wrapper update). The comparison is a simple semver walk — split on dots, compare integers left to right.

Why not git-based detection?

We could compare commit SHAs or use git fetch + git rev-list to detect ahead/behind. But the installer runs before cloning on a fresh install. We need a mechanism that works with a single HTTP request against a raw file URL, even when there's no local git repo yet.

Why not GitHub Releases API?

The GitHub API requires authentication for higher rate limits and adds a JSON parsing dependency. A raw file on GitHub Pages is cacheable, fast, and works with a bare curl. The VERSION file is also readable by Python (brainstem.py reads it at startup), the shell installers, and humans — one file serves every consumer.

Bump process: Edit rapp_brainstem/VERSION, commit, push. The next time any user runs the one-liner, they get the update. That's the whole release process.

Exposed in the API

The version is available at GET /version and included in the GET /health response. The startup banner prints it too. Everything reads from the same VERSION file — there's exactly one place to update.

$ curl -s localhost:7071/health | python3 -m json.tool
{
    "status": "ok",
    "version": "0.1.0",
    "model": "gpt-4o",
    "agents": ["HelloAgent", "ContextMemoryAgent"],
    "copilot": "✓",
    ...
}