<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.billmongan.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.billmongan.com/" rel="alternate" type="text/html" /><updated>2026-11-06T18:57:34+00:00</updated><id>https://www.billmongan.com/feed.xml</id><title type="html">William M. Mongan, Ph.D.</title><subtitle>Homepage of Dr. Bill Mongan</subtitle><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><entry><title type="html">Giving Every Student Their Own VM: Jetstream2 Classroom Provisioning with OpenStack</title><link href="https://www.billmongan.com/posts/2026/10/jetstream2-classroom-vms/" rel="alternate" type="text/html" title="Giving Every Student Their Own VM: Jetstream2 Classroom Provisioning with OpenStack" /><published>2026-10-19T00:00:00+00:00</published><updated>2026-10-19T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/10/jetstream2-classroom-vms</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/10/jetstream2-classroom-vms/"><![CDATA[<p>This term, every student in my class has their own Linux VM on <a href="https://jetstream-cloud.org/">Jetstream2</a>, an NSF-funded research cloud available through the ACCESS program. Educational use is free. I use the VMs to run agentic coding tools such as OpenCode inside Docker, so students do not have to install anything on their laptops and I do not pay for cloud machines myself.</p>

<p>This post covers how I got an account, requested an allocation, exchanged credits for compute, and obtained the OpenStack credentials. It then shows the commands behind my provisioning script: creating a machine with my key, adding a student’s key, and installing OpenCode. I have left out the full script. Every command below works for one machine, and a loop runs it for the whole class.</p>

<h2 id="create-an-access-account">Create an ACCESS account</h2>

<p>Jetstream2 sign-in goes through <a href="https://account.access-ci.org/">ACCESS</a>. Register there, preferably with your institutional identity, and note your ACCESS username. The allocation request asks for it, and support tickets use your <code class="language-plaintext highlighter-rouge">@access-ci.org</code> identity.</p>

<h2 id="request-an-allocation">Request an allocation</h2>

<p>Sign in at <a href="https://allocations.access-ci.org/">allocations.access-ci.org</a> and start a new request. For a class, choose the <strong>Explore</strong> tier and the <strong>Classroom / Training</strong> grant type. Explore decisions usually arrive within about two business days, while larger tiers can take weeks.</p>

<p>The request asks for the following:</p>

<ul>
  <li>A title and public overview describing the course and what students do on the VMs</li>
  <li>Fields of science (I chose Computer Science as primary and AI as secondary)</li>
  <li>Credits (the initial Explore award is 200,000, and you can request more later with a progress report)</li>
  <li>Personnel (I listed myself as both PI and Allocation Manager)</li>
  <li>A syllabus and a short CV</li>
</ul>

<p>An Explore project lasts 12 months. Unspent credits expire when it ends.</p>

<h2 id="exchange-credits-for-jetstream2-time">Exchange credits for Jetstream2 time</h2>

<p>An approved allocation holds generic ACCESS credits, not Jetstream2 time, so you must exchange them for a specific resource before you can launch anything.</p>

<p>Open the approved project and go to <strong>Credits + Resources</strong>. Choose <strong>Add a resource to your exchange</strong> and select <strong>Indiana Jetstream2 CPU</strong>. On Jetstream2, one ACCESS credit equals one service unit (SU). I sized my request with this formula:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>SUs = (number of VMs) x (SUs per hour) x 24 x (days remaining) x 1.10
</code></pre></div></div>

<p>My VMs use the <code class="language-plaintext highlighter-rouge">m3.quad</code> flavor, which has 4 vCPUs, 15 GB of RAM, and costs 4 SUs per hour. The 1.10 is a 10% cushion. The exchange also asks for a short justification. Describing the class, the VM size, and the software students run was enough. The resource provider then approves the exchange.</p>

<p>Four budgeting facts matter:</p>

<ul>
  <li>A running VM uses 100% of its rate, whether or not anyone is logged in.</li>
  <li>A stopped VM still uses 50%.</li>
  <li>A shelved VM uses no compute SUs, so shelve a VM when you want to pause it.</li>
  <li>Hosted LLM inference uses no SUs, so you need GPU time only if students serve their own models.</li>
</ul>

<h2 id="get-the-credentials-openrcsh-and-cloudsyaml">Get the credentials: <code class="language-plaintext highlighter-rouge">openrc.sh</code> and <code class="language-plaintext highlighter-rouge">clouds.yaml</code></h2>

<p>First add the allocation in <a href="https://jetstream2.exosphere.app/">Exosphere</a> so you can see it. The command line needs an <strong>application credential tied to the allocation</strong>, which you create in Horizon. Do not use the “OpenStack RC File” option in Horizon’s user menu, because Jetstream2 documents that it does not work.</p>

<ol>
  <li>Sign in to <a href="https://js2.jetstream-cloud.org/project/">Horizon</a> with ACCESS CILogon.</li>
  <li>Use the project selector at the top left to choose the allocation that holds your CPU exchange. This is easy to miss.</li>
  <li>Open <strong>Identity → Application Credentials</strong> and click <strong>Create Application Credential</strong>.</li>
  <li>Enter a descriptive name, a strong secret, and an <strong>explicit expiration date</strong> after the term ends. A blank expiration defaults to today, and authentication then fails tomorrow.</li>
  <li>Download both files from the confirmation dialog: the openrc file (a shell script) and <code class="language-plaintext highlighter-rouge">clouds.yaml</code>. Horizon cannot show the secret again, so if you lose the files, create a new credential.</li>
</ol>

<p>Store both files where only you can read them:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">chmod </span>600 ~/jetstream/openrc-myproject.sh

<span class="nb">mkdir</span> <span class="nt">-p</span> ~/.config/openstack
<span class="nb">mv</span> ~/Downloads/clouds.yaml ~/.config/openstack/clouds.yaml
<span class="nb">chmod </span>600 ~/.config/openstack/clouds.yaml
</code></pre></div></div>

<p>Both files contain the credential secret, so treat them like passwords. Keep them on your admin machine. Never put them in a git repository or on a student VM.</p>

<p>Use one file or the other, not both. To use the openrc file, <strong>source</strong> it. Running it as <code class="language-plaintext highlighter-rouge">./openrc.sh</code> sets the variables in a child process that exits immediately, which is the most common mistake:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">source</span> ~/jetstream/openrc-myproject.sh
</code></pre></div></div>

<p>To use <code class="language-plaintext highlighter-rouge">clouds.yaml</code>, name the cloud with the top-level key from your downloaded file:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">export </span><span class="nv">OS_CLOUD</span><span class="o">=</span>openstack
</code></pre></div></div>

<p>Open a fresh terminal when you switch between the two. Then install the client and confirm that you are authenticated:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt <span class="nb">install</span> <span class="nt">-y</span> python3-openstackclient openssh-client

openstack token issue <span class="o">&gt;</span>/dev/null <span class="o">&amp;&amp;</span> <span class="nb">echo</span> <span class="s2">"authenticated"</span>
openstack flavor list                  <span class="c"># should list m3.* flavors</span>
openstack image list | <span class="nb">grep</span> <span class="nt">-i</span> ubuntu  <span class="c"># find the exact image name</span>
</code></pre></div></div>

<h2 id="check-your-quotas">Check your quotas</h2>

<p>Each VM boots from its own volume and, in my setup, gets its own public floating IP. A new project’s default quotas may be lower than your class size:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openstack quota show <span class="nt">--usage</span>
</code></pre></div></div>

<p>My instance quota was sufficient, but the volume and floating IP quotas were each 10. That would have stopped provisioning partway through a class of 22. To raise a quota, open an ACCESS help desk ticket with Issue set to <em>Allocation Question</em>, Resource set to <em>Jetstream2</em>, and Keyword set to <em>Quota</em>. Give the exact numbers you need and the reason. If a script stops at a quota limit, rerun it after the increase and it resumes where it stopped.</p>

<h2 id="provision-one-machine">Provision one machine</h2>

<p>My script wraps the OpenStack commands below and adds a preview mode, a CSV of results, and safe reruns. Here are the commands underneath it.</p>

<h3 id="create-a-vm-with-your-key">Create a VM with your key</h3>

<p>Register your public key as an OpenStack keypair. I used the key I already had, <code class="language-plaintext highlighter-rouge">~/.ssh/id_rsa.pub</code>. According to the <a href="https://docs.openstack.org/python-openstackclient/pike/cli/command-objects/keypair.html"><code class="language-plaintext highlighter-rouge">openstack keypair create</code> documentation</a>, <code class="language-plaintext highlighter-rouge">--public-key</code> names the public key file to add, so the command uploads that key to OpenStack under a name you choose. Without <code class="language-plaintext highlighter-rouge">--public-key</code>, it creates a private key instead, which it prints to the console unless you pass <code class="language-plaintext highlighter-rouge">--private-key</code> with a filename. That is not what we want here. At first boot, cloud-init installs the key for the <code class="language-plaintext highlighter-rouge">ubuntu</code> user:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openstack keypair create <span class="nt">--public-key</span> ~/.ssh/id_rsa.pub class-admin-key

openstack server create vm01 <span class="se">\</span>
  <span class="nt">--flavor</span> m3.quad <span class="se">\</span>
  <span class="nt">--image</span> Featured-Ubuntu24 <span class="se">\</span>
  <span class="nt">--boot-from-volume</span> 40 <span class="se">\</span>
  <span class="nt">--key-name</span> class-admin-key <span class="se">\</span>
  <span class="nt">--security-group</span> class-ssh <span class="se">\</span>
  <span class="nt">--network</span> auto_allocated_network <span class="se">\</span>
  <span class="nt">--wait</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">class-ssh</code> security group allows inbound SSH on port 22. I also pass cloud-init user data that disables SSH password and keyboard-interactive login, so the VMs accept key logins only.</p>

<p>Next, give the VM a public address:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">FIP</span><span class="o">=</span><span class="si">$(</span>openstack floating ip create public <span class="nt">-f</span> value <span class="nt">-c</span> floating_ip_address<span class="si">)</span>
openstack server add floating ip vm01 <span class="s2">"</span><span class="nv">$FIP</span><span class="s2">"</span>
</code></pre></div></div>

<h3 id="trust-the-host-key-on-first-contact">Trust the host key on first contact</h3>

<p>Every SSH step below uses <code class="language-plaintext highlighter-rouge">StrictHostKeyChecking=accept-new</code>. This option records an unknown VM’s host key on first contact and refuses to connect if the key later changes:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh <span class="nt">-o</span> <span class="nv">StrictHostKeyChecking</span><span class="o">=</span>accept-new <span class="nt">-i</span> ~/.ssh/id_rsa ubuntu@<span class="s2">"</span><span class="nv">$FIP</span><span class="s2">"</span> <span class="nb">true</span>
</code></pre></div></div>

<p>This is trust on first use, so the first connection is the one that matters. To verify a key independently, compare the fingerprints that cloud-init prints to the console log with the fingerprint you recorded locally:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openstack console log show vm01 <span class="se">\</span>
  | <span class="nb">sed</span> <span class="nt">-n</span> <span class="s1">'/BEGIN SSH HOST KEY FINGERPRINTS/,/END SSH HOST KEY FINGERPRINTS/p'</span>
ssh-keygen <span class="nt">-lF</span> <span class="s2">"</span><span class="nv">$FIP</span><span class="s2">"</span>
</code></pre></div></div>

<p>Jetstream2 may give a new VM a floating IP that an older VM used, for example after you delete and rebuild the class. SSH then stops with <code class="language-plaintext highlighter-rouge">REMOTE HOST IDENTIFICATION HAS CHANGED</code>. That refusal is correct. Confirm that you rebuilt the VM, remove the stale entry with <code class="language-plaintext highlighter-rouge">ssh-keygen -R "$FIP"</code>, and connect again. A <code class="language-plaintext highlighter-rouge">Host</code> block in <code class="language-plaintext highlighter-rouge">~/.ssh/config</code> does not change this behavior, because OpenSSH uses the first value it finds for each option and the command-line option wins.</p>

<h3 id="add-a-students-key">Add a student’s key</h3>

<p>Each student generates a key pair on their own computer and sends me only the <code class="language-plaintext highlighter-rouge">.pub</code> file:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh-keygen <span class="nt">-t</span> ed25519 <span class="nt">-f</span> ~/.ssh/class_vm   <span class="c"># the student runs this</span>
</code></pre></div></div>

<p>I append that public key to the <code class="language-plaintext highlighter-rouge">ubuntu</code> account’s <code class="language-plaintext highlighter-rouge">authorized_keys</code> on the student’s VM, next to my own. Only the public key travels:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh <span class="nt">-o</span> <span class="nv">StrictHostKeyChecking</span><span class="o">=</span>accept-new <span class="nt">-i</span> ~/.ssh/id_rsa ubuntu@<span class="s2">"</span><span class="nv">$FIP</span><span class="s2">"</span> <span class="se">\</span>
  <span class="s1">'cat &gt;&gt; ~/.ssh/authorized_keys'</span> &lt; student-keys/alice.pub
</code></pre></div></div>

<p>The real script first checks whether the key is already present, so running it twice adds nothing. Afterward, the student and I both log in as <code class="language-plaintext highlighter-rouge">ubuntu</code>. The student can reach only their own VM, and I can reach all of them.</p>

<h3 id="install-docker-and-opencode">Install Docker and OpenCode</h3>

<p>This step installs Docker, adds <code class="language-plaintext highlighter-rouge">ubuntu</code> to the <code class="language-plaintext highlighter-rouge">docker</code> group, and pulls the OpenCode image:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh <span class="nt">-o</span> <span class="nv">StrictHostKeyChecking</span><span class="o">=</span>accept-new <span class="nt">-i</span> ~/.ssh/id_rsa ubuntu@<span class="s2">"</span><span class="nv">$FIP</span><span class="s2">"</span> <span class="s1">'
  sudo apt-get update &amp;&amp;
  sudo apt-get install -y docker.io &amp;&amp;
  sudo usermod -aG docker ubuntu &amp;&amp;
  sudo docker pull ghcr.io/anomalyco/opencode:latest
'</span>
</code></pre></div></div>

<p>A small launcher script in <code class="language-plaintext highlighter-rouge">/usr/local/bin/opencode</code> runs the container interactively. It mounts a directory in the student’s home as the container’s home, and it mounts OpenCode’s config and data directories inside that. If a nested mountpoint does not exist, Docker creates it as <code class="language-plaintext highlighter-rouge">root</code>, and OpenCode, which runs as <code class="language-plaintext highlighter-rouge">ubuntu</code>, then fails with <code class="language-plaintext highlighter-rouge">EACCES: permission denied, mkdir '/opencode-home/.local/state'</code>. The launcher avoids this by creating every mountpoint as the invoking user before it starts the container:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/.opencode-container-home <span class="se">\</span>
         ~/.config/opencode ~/.local/share/opencode

docker run <span class="nt">-it</span> <span class="nt">--rm</span> <span class="nt">-u</span> <span class="s2">"</span><span class="si">$(</span><span class="nb">id</span> <span class="nt">-u</span><span class="si">)</span><span class="s2">:</span><span class="si">$(</span><span class="nb">id</span> <span class="nt">-g</span><span class="si">)</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-v</span> ~/.opencode-container-home:/opencode-home <span class="se">\</span>
  <span class="nt">-v</span> ~/.config/opencode:/opencode-home/.config/opencode <span class="se">\</span>
  <span class="nt">-v</span> ~/.local/share/opencode:/opencode-home/.local/share/opencode <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$PWD</span><span class="s2">"</span>:/workspace <span class="nt">-w</span> /workspace <span class="se">\</span>
  ghcr.io/anomalyco/opencode:latest
</code></pre></div></div>

<p>The VMs also get <a href="https://herdr.dev/">herdr</a>, a terminal multiplexer for coding agents. Its sidebar shows whether each agent is working, blocked, or idle. I install it with herdr’s official installer, which verifies the release checksum, and then register its OpenCode integration as the <code class="language-plaintext highlighter-rouge">ubuntu</code> user:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-fsSL</span> https://herdr.dev/install.sh | <span class="nb">sudo </span>sh   <span class="c"># check herdr.dev for the current installer URL</span>
herdr integration <span class="nb">install </span>opencode
</code></pre></div></div>

<p>The integration writes herdr’s OpenCode plugin files into <code class="language-plaintext highlighter-rouge">~/.config/opencode</code>. The launcher already mounts that directory into the container, so OpenCode loads the plugin. The plugin reports to herdr only when <code class="language-plaintext highlighter-rouge">HERDR_ENV</code>, <code class="language-plaintext highlighter-rouge">HERDR_SOCKET_PATH</code>, and <code class="language-plaintext highlighter-rouge">HERDR_PANE_ID</code> are set and the herdr socket is reachable. When a student starts <code class="language-plaintext highlighter-rouge">opencode</code> inside a herdr pane, the launcher forwards those variables and mounts the socket’s directory (normally <code class="language-plaintext highlighter-rouge">~/.config/herdr</code>) at the same path. Outside herdr, the launcher passes nothing extra.</p>

<p>The launcher excerpt above is simplified. Since the image uses the <code class="language-plaintext highlighter-rouge">:latest</code> tag, VMs set up at different times can end up with different OpenCode builds. Pin a tag or digest if every student needs the same version.</p>

<p>Students log out and back in once so the Docker group change takes effect. They then run <code class="language-plaintext highlighter-rouge">opencode</code> and use <code class="language-plaintext highlighter-rouge">/connect</code> to configure a model provider. I put no model credentials on the VMs.</p>

<h2 id="do-it-in-a-loop">Do it in a loop</h2>

<p>None of these commands is specific to one machine, so the class is a loop. The script generates the names and pairs them with the sorted list of student key files:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for </span>i <span class="k">in</span> <span class="si">$(</span><span class="nb">seq</span> <span class="nt">-w</span> 1 22<span class="si">)</span><span class="p">;</span> <span class="k">do
  </span>openstack server create <span class="s2">"vm</span><span class="nv">$i</span><span class="s2">"</span> <span class="se">\</span>
    <span class="nt">--flavor</span> m3.quad <span class="nt">--image</span> Featured-Ubuntu24 <span class="se">\</span>
    <span class="nt">--boot-from-volume</span> 40 <span class="nt">--key-name</span> class-admin-key <span class="se">\</span>
    <span class="nt">--security-group</span> class-ssh <span class="nt">--network</span> auto_allocated_network <span class="nt">--wait</span>
  <span class="c"># then: floating IP, student key $i, Docker and OpenCode</span>
<span class="k">done</span>
</code></pre></div></div>

<p>For each stage, I preview first, then run on one VM, then run on all of them.</p>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="agentic" /><category term="jetstream2" /><category term="openstack" /><category term="teaching" /><category term="opencode" /><category term="docker" /><summary type="html"><![CDATA[This term, every student in my class has their own Linux VM on Jetstream2, an NSF-funded research cloud available through the ACCESS program. Educational use is free. I use the VMs to run agentic coding tools such as OpenCode inside Docker, so students do not have to install anything on their laptops and I do not pay for cloud machines myself.]]></summary></entry><entry><title type="html">A Herdr Docker Devbox: Running Several Coding Agents in One Container with Approval-Based Host Access</title><link href="https://www.billmongan.com/posts/2026/10/herdr-docker-devbox/" rel="alternate" type="text/html" title="A Herdr Docker Devbox: Running Several Coding Agents in One Container with Approval-Based Host Access" /><published>2026-10-17T00:00:00+00:00</published><updated>2026-10-17T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/10/herdr-docker-devbox</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/10/herdr-docker-devbox/"><![CDATA[<p>Coding agents are useful because they can read your files and run commands. That also makes them risky to run on a machine with real data on it. A model can misread an instruction, or a file it opens can contain instructions of its own, and an agent running as you can do anything you can do. I run several agents at once, and each one wants access to the same drives. I’d like them to cooperate without all of them being able to see everything.</p>

<p>This post describes a setup I built to deal with that. Everything runs in a single Docker container. Seven agents (Claude Code, Codex, Antigravity, Grok, OpenCode, pi, and Qwen Code) each get their own Linux user, their own home directory, and a terminal tab managed by <a href="https://herdr.dev/">Herdr</a>. None of them can see my Windows drives. When one needs a file, it asks a small broker program, and the request sits there until I approve it, either on a web page or by typing a six-digit code into Claude from my phone. Every file in the project is at the bottom of this post, so you can build it yourself.</p>

<p>This is experimental. I built it for my own setup, so it may not be appropriate or secure enough for general use, and it has had limited testing. Please don’t rely on it in production; read it as a reference for the decisions and tradeoffs I made for my use case.</p>

<p>I’ll go through it in the order I’d want it explained to me: first the ideas you need (containers, users, permissions, sandboxes), then how to build and run it, then how each piece works and why I made the choices I did. If you already know Docker and Linux permissions, skip ahead to “Protecting the host drives.”</p>

<p>If you’ve read my <a href="/posts/2026/10/herdr-multiagent-mcpproxy/">earlier post on Herdr and per-agent MCP credentials</a>, this is a different approach to a related problem. That post fenced agents apart on a server by giving each its own credentials. This one puts them in a container and puts a human approval step between them and the host.</p>

<h2 id="what-were-building">What we’re building</h2>

<p>Everything runs in one Docker container. The host drives are mounted inside a folder that only root can open, so the agents never touch them directly. When an agent needs something on the host, it runs a command called <code class="language-plaintext highlighter-rouge">hostctl</code>, which talks to a broker running as root. The broker records the request and waits. You approve or deny it, either on a web page or from the Claude session with a one-time code. Everything the agents need to keep (sign-ins, settings, passwords) lives in a Docker volume, so rebuilding the image doesn’t make you sign in to everything again.</p>

<h2 id="background-youll-need">Background you’ll need</h2>

<p>These are the pieces I’ll keep referring to, explained for someone who has never run Docker. Skip any you already know.</p>

<h3 id="containers-images-and-volumes">Containers, images, and volumes</h3>

<p>An <em>image</em> is a frozen recipe-plus-ingredients for a small Linux system: the operating system files, the programs installed on top of it, and the command to run at startup. A <em>container</em> is a running copy of an image. It looks like its own computer, with its own file system and its own process list, but it shares the host’s kernel. That sharing is why containers start in a second instead of a minute, and it is also why container isolation is weaker than a virtual machine’s. A bug in the kernel affects both.</p>

<p>A container’s file system is thrown away when the container is removed. A <em>volume</em> is storage that Docker keeps separately, so it survives. We’ll keep all the important state in one volume. A <em>bind mount</em> is a different thing: it makes a folder from the host appear inside the container. We’ll use bind mounts to show the Windows drives to the container, and then immediately hide them from the agents.</p>

<h3 id="users-uids-and-file-permissions">Users, UIDs, and file permissions</h3>

<p>Linux decides who may read a file by looking at the numeric ID of the user running the program (the UID) and the permission bits on the file. A file with mode <code class="language-plaintext highlighter-rouge">0600</code> can be read and written by its owner and nobody else. A folder with mode <code class="language-plaintext highlighter-rouge">0700</code> can only be entered by its owner. Root (UID 0) can ignore these rules.</p>

<p>If every agent ran as the same user, they could all read each other’s files, including each other’s login tokens. Instead, each agent gets its own UID (21001 through 21007), and its own home directory, which is private to it. A different agent running as a different UID simply gets “permission denied” when it tries to look inside. And because none of them is root, none of them can open the folder where the Windows drives are mounted.</p>

<h3 id="capabilities-and-no_new_privs">Capabilities and <code class="language-plaintext highlighter-rouge">no_new_privs</code></h3>

<p>Root’s power is divided on modern Linux into pieces called <em>capabilities</em>, such as “may mount file systems” or “may change file ownership.” The launcher that starts each agent drops to the agent’s UID, confirms that every capability set is empty, and sets a flag called <code class="language-plaintext highlighter-rouge">no_new_privs</code>. That flag tells the kernel that this process and anything it starts can never gain privileges, even by running a setuid program. The container itself is also started with <code class="language-plaintext highlighter-rouge">--security-opt no-new-privileges=true</code>.</p>

<h3 id="unix-sockets-and-peer-credentials">Unix sockets and peer credentials</h3>

<p>A <em>Unix socket</em> is a file-shaped doorway that two programs on the same machine can use to talk. It has a useful property: when a program connects, the kernel can tell the listener the UID of the connecting process, and the connecting process cannot lie about it. The broker uses this. When a request arrives on the socket, the broker asks the kernel who is on the other end, so an agent can’t pretend to be a different agent, and can’t claim to be you.</p>

<h3 id="namespaces-seccomp-and-bubblewrap">Namespaces, seccomp, and bubblewrap</h3>

<p>We’ll spend a whole section on these later, because the container needs a special setting for one of the agents. For now: a <em>namespace</em> gives a process its own private view of some part of the system (its own set of mounts, process IDs, network, or user IDs). <em>Seccomp</em> is a filter that decides which system calls a process may make. <em>Bubblewrap</em> is a small program that uses namespaces to build a sandbox around another program. Codex uses it on Linux.</p>

<h2 id="what-you-need-before-you-start">What you need before you start</h2>

<ul>
  <li>A Windows machine with WSL2 and an Ubuntu distribution, or a Linux machine. The scripts assume WSL, where your Windows drives appear under <code class="language-plaintext highlighter-rouge">/mnt</code>, such as <code class="language-plaintext highlighter-rouge">/mnt/c</code>.</li>
  <li>Docker, reachable from inside WSL (Docker Desktop with WSL integration turned on, or Docker Engine installed in the distribution). Check with <code class="language-plaintext highlighter-rouge">docker info</code>.</li>
  <li>Python 3 and <code class="language-plaintext highlighter-rouge">bash</code> in WSL, plus the <code class="language-plaintext highlighter-rouge">mountpoint</code> command (part of <code class="language-plaintext highlighter-rouge">util-linux</code>, normally already there).</li>
  <li>An authenticator app on your phone, such as the one you already use for your accounts. You’ll add one entry to it.</li>
  <li>Accounts for whichever agents you plan to use. You don’t have to use all seven. Each agent signs in on its own the first time you open it.</li>
  <li>Optionally, an <a href="https://openwebui.com/">Open WebUI</a> server with an API key, if you want OpenCode, pi, and Qwen Code to use your own models by default.</li>
</ul>

<p>The project is set up for one host drive, C, which is all I needed. To add more, extend the same places: the <code class="language-plaintext highlighter-rouge">for drive in c</code> loop and the <code class="language-plaintext highlighter-rouge">--mount</code> line in <code class="language-plaintext highlighter-rouge">run.sh</code>, the <code class="language-plaintext highlighter-rouge">mkdir</code> line in the Dockerfile that creates <code class="language-plaintext highlighter-rouge">/host-private/c</code>, and the drive lists in <code class="language-plaintext highlighter-rouge">devbox.py</code> (search for <code class="language-plaintext highlighter-rouge">('c',)</code>). The startup check then requires every drive you list. You can also set <code class="language-plaintext highlighter-rouge">"require_mounts": false</code> in a config override, described later, if you’d rather it not check.</p>

<h2 id="building-it">Building it</h2>

<p>Make a folder, and save the files from the appendix at the bottom of this post into it. You need six: <code class="language-plaintext highlighter-rouge">Dockerfile</code>, <code class="language-plaintext highlighter-rouge">build.sh</code>, <code class="language-plaintext highlighter-rouge">run.sh</code>, <code class="language-plaintext highlighter-rouge">attach.sh</code>, <code class="language-plaintext highlighter-rouge">prepare-seccomp.py</code>, and <code class="language-plaintext highlighter-rouge">totp_generate.sh</code>. Then:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd</span> ~/herdr-devbox
<span class="nb">chmod</span> +x build.sh run.sh attach.sh totp_generate.sh
bash build.sh
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">build.sh</code> does three things. First it runs <code class="language-plaintext highlighter-rouge">prepare-seccomp.py</code>, which creates the seccomp profile file the container will use. I explain what that profile is later; the short version is that it’s Docker’s standard profile with six extra permissions that bubblewrap needs. The script downloads Docker’s upstream profile once and keeps a copy named <code class="language-plaintext highlighter-rouge">default.json</code> next to itself, so later builds don’t need the network for that. If <code class="language-plaintext highlighter-rouge">herdr-seccomp.json</code> already exists, the script leaves it alone, which means you can hand-edit that file and it won’t be overwritten.</p>

<p>Second, <code class="language-plaintext highlighter-rouge">build.sh</code> runs <code class="language-plaintext highlighter-rouge">docker build</code>. That installs the operating system packages, Node.js, the seven agents (at the versions the Dockerfile specifies), Herdr, and the <code class="language-plaintext highlighter-rouge">pi-openai-compat</code> extension, and then writes the application itself into the image. The application is one Python program, <code class="language-plaintext highlighter-rouge">devbox.py</code>, embedded in the Dockerfile as a here-document so the whole project stays a single file you can read top to bottom.</p>

<p>Third, it runs the project’s self-test inside the freshly built image. The build itself also runs the tests, so a failing test stops you from ending up with a broken image.</p>

<p>The agent versions are set by <code class="language-plaintext highlighter-rouge">ARG</code> lines near the top of the Dockerfile. Agent CLIs change quickly, and I’d like a rebuild next month to give me the same system. To upgrade one agent, change its version number and rebuild.</p>

<h2 id="running-it">Running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bash run.sh
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">run.sh</code> is interactive, and it’s worth knowing what each prompt means.</p>

<p><strong>Open WebUI settings.</strong> If you gave it an endpoint before, it shows the saved URL and model (never the key) and asks whether to change them. If you answer yes, or if it’s your first run, it asks for the Open WebUI URL and your API key, then fetches the list of models from the server and lets you pick the default by number. That fetch runs in a throwaway container so the key never appears on a command line. If the list can’t be fetched, you type the model ID instead. These settings are stored in the state volume, in a folder only root can read.</p>

<p><strong>Saved passwords.</strong> There are three secrets the project generates: the dashboard password, the OpenCode web password, and the approval (TOTP) secret. After the first run they’re saved in the volume. On later runs, <code class="language-plaintext highlighter-rouge">run.sh</code> asks about each one: <code class="language-plaintext highlighter-rouge">A saved dashboard password exists. Overwrite it? [y/N]</code>. Answer no and the saved one stays. Answer yes and you can type a new one or press Enter to generate a random one. This is how you keep the same authenticator entry on your phone from run to run, and from build to build.</p>

<p><strong>Existing container.</strong> If a container with the same name is already running, <code class="language-plaintext highlighter-rouge">run.sh</code> tells you that recreating it stops anything it’s doing, and makes you type the word <code class="language-plaintext highlighter-rouge">recreate</code> to confirm. Your state volume is not touched.</p>

<p>When it finishes, it prints the approval secret and a URI for your authenticator app, plus the dashboard password and the OpenCode web password. Add the approval secret to your authenticator app as a new entry (most apps accept the base32 string by typing it in, or the <code class="language-plaintext highlighter-rouge">otpauth://</code> link). If you don’t have an app handy, <code class="language-plaintext highlighter-rouge">bash totp_generate.sh</code> asks for the secret and prints the current code, which is also handy for checking that you entered it correctly.</p>

<p>Open <code class="language-plaintext highlighter-rouge">http://127.0.0.1:8090</code> in a browser, sign in with the dashboard password, and you’ll see the approval page. To get into the terminals, run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bash attach.sh
</code></pre></div></div>

<p>That attaches Herdr to the running container. You’ll see one workspace per agent. Detach with Ctrl+B, then Q; the container keeps running. You can also reach the very same Herdr session in the browser at <code class="language-plaintext highlighter-rouge">http://127.0.0.1:8090/terminal/</code>, which is what makes it possible to work from a different computer.</p>

<p>The first time you open each agent’s tab, run <code class="language-plaintext highlighter-rouge">agent-login</code> and follow its sign-in prompts, then <code class="language-plaintext highlighter-rouge">agent-start</code> to launch it. Claude and Antigravity start with their own remote-control feature on, so once Claude is signed in you can connect to it from the Claude app on your phone. The sign-ins land in each agent’s private home inside the volume, so you only do this once.</p>

<h2 id="the-agents-and-why-each-one-has-its-own-user">The agents, and why each one has its own user</h2>

<table>
  <thead>
    <tr>
      <th>Agent</th>
      <th>UID</th>
      <th>How it starts</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>claude (the lead)</td>
      <td>21001</td>
      <td><code class="language-plaintext highlighter-rouge">claude --remote-control</code></td>
    </tr>
    <tr>
      <td>codex</td>
      <td>21002</td>
      <td><code class="language-plaintext highlighter-rouge">codex</code>, with approvals on request</td>
    </tr>
    <tr>
      <td>agy (Antigravity)</td>
      <td>21003</td>
      <td><code class="language-plaintext highlighter-rouge">agy --remote-control</code></td>
    </tr>
    <tr>
      <td>grok</td>
      <td>21004</td>
      <td><code class="language-plaintext highlighter-rouge">grok</code></td>
    </tr>
    <tr>
      <td>opencode</td>
      <td>21005</td>
      <td><code class="language-plaintext highlighter-rouge">opencode attach http://127.0.0.1:4096</code></td>
    </tr>
    <tr>
      <td>pi</td>
      <td>21006</td>
      <td><code class="language-plaintext highlighter-rouge">pi</code></td>
    </tr>
    <tr>
      <td>qwen</td>
      <td>21007</td>
      <td><code class="language-plaintext highlighter-rouge">qwen</code></td>
    </tr>
  </tbody>
</table>

<p>Herdr itself recognizes these agents and shows whether each is idle, working, or waiting for you. That’s what makes a tab-per-agent layout manageable. I looked at which of the agents from my own install script Herdr officially supports before adding them. CodeWhale, DeepSeek’s <code class="language-plaintext highlighter-rouge">dsh</code>, and Mistral Vibe aren’t on its list, so I left them out, and I chose not to include Gemini CLI, which Herdr only tracks with less testing. If you want those, you can add them by following how <code class="language-plaintext highlighter-rouge">pi</code> and <code class="language-plaintext highlighter-rouge">qwen</code> appear in the Dockerfile: a user, a home directory, a launch command, and a login hint.</p>

<p>Claude is the “lead.” That role matters in two places: only Claude can relay your approvals from the Claude session, and only Claude can send a task to the other agents. I picked Claude because it’s the one I keep a remote-control connection to from my phone. The lead is just a name in a few lists, so you can make a different agent the lead.</p>

<p>None of the launch commands turns off an agent’s own safety prompts. I did not use any “yolo” or skip-permissions flag. Pi is an exception only because it has no per-tool approvals at all by design; its protection here comes from running as its own user. One other thing I learned while checking: pi’s <code class="language-plaintext highlighter-rouge">-a</code> flag looks like it might mean “ask for approval,” but in pi it means “trust project-local files for this run,” which does the opposite of what I wanted. So pi starts with no flags.</p>

<p>All agents run from their own folder, <code class="language-plaintext highlighter-rouge">/state/agents/&lt;name&gt;/workspace</code>, which is also where each one’s private notes and rules files live.</p>

<h2 id="protecting-the-host-drives">Protecting the host drives</h2>

<p>Here is one request, followed from start to finish.</p>

<p>When the container starts, the host drives are bind-mounted under <code class="language-plaintext highlighter-rouge">/host-private</code>, one folder per drive, such as <code class="language-plaintext highlighter-rouge">/host-private/c</code>. The parent folder, <code class="language-plaintext highlighter-rouge">/host-private</code>, is owned by root with mode <code class="language-plaintext highlighter-rouge">0700</code>. That means only root can even walk into it. No agent is root, so no agent can look at a single file on those drives. This is a plain file permission, not a clever trick, and the self-test checks it by starting a process as each agent’s UID and confirming that it gets “permission denied.”</p>

<p>When an agent needs to modify files on the host, it runs <code class="language-plaintext highlighter-rouge">hostctl</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>hostctl list c Users
hostctl <span class="nb">read </span>c projects/example.txt
hostctl search c projects <span class="s2">"literal text"</span>
hostctl write c projects/example.txt <span class="nt">--file</span> ./proposed.txt
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">hostctl</code> is a tiny client. It sends a JSON message over the Unix socket to the broker, which is a root-owned part of the same Python program. The broker:</p>

<ol>
  <li>Asks the kernel which UID is on the other end, and turns that into an agent name. The message itself can’t claim to be someone else.</li>
  <li>Checks that the drive is one of the allowed ones and that the path is a plain relative path. It refuses <code class="language-plaintext highlighter-rouge">..</code>, absolute paths, backslashes, colons, control characters, and Windows device names like <code class="language-plaintext highlighter-rouge">CON</code> and <code class="language-plaintext highlighter-rouge">NUL</code>.</li>
  <li>Creates a request record, saves it in memory with a random ID and a timeout (ten minutes by default), writes an entry to a SQLite audit log, and tells the agent the request is pending.</li>
</ol>

<p>At this point the broker has not touched the file, not even to read it or check that it exists. The self-test checks for this, because it’s an easy rule to break by accident.</p>

<p>The agent’s <code class="language-plaintext highlighter-rouge">hostctl</code> command now waits, polling once a second. When you approve the request, the broker finally does the work. Reading a file opens it without following symbolic links, walks the path one folder at a time with no link-following, and refuses to cross onto a different file system than the drive. A symbolic link is a file that points somewhere else, and an agent that could plant one could try to trick the broker into reading <code class="language-plaintext highlighter-rouge">/etc/passwd</code>; these precautions are about that attack. The broker also compares the file’s identity before and after the read, and rejects the result if the file changed underneath it.</p>

<h3 id="writes">Writes</h3>

<p>A write is the riskiest operation, so it has more care. When you approve a write, the broker:</p>

<ol>
  <li>Reads the current version of the file and remembers its identity (inode, size, modification time, hash).</li>
  <li>Saves the old bytes as a backup in <code class="language-plaintext highlighter-rouge">/state/backups</code>, named after the request ID.</li>
  <li>Writes the new content to a temporary file in the same folder and flushes it to disk.</li>
  <li>Checks the file’s identity again. If it changed since step 1, the write is cancelled.</li>
  <li>Renames the temporary file over the original, and reads it back to confirm it matches what was requested.</li>
</ol>

<p>The agent never sees the old contents. The web page also has an optional “show diff first” button, which reads the current file and shows you the difference before you decide. A write is one approval, with that diff as an extra step you can use if you want to look.</p>

<p>The rename in step 5 is the best you can do portably, but it can’t be made perfectly safe against another program editing the same file at the same instant, particularly on Windows drives and network shares. The recheck in step 4 narrows the window; it doesn’t close it.</p>

<h3 id="limits">Limits</h3>

<p>By default there are no limits on file size, number of search results, or number of files searched in one request. I wanted large projects to just work. If you’d rather cap them, there are four settings (<code class="language-plaintext highlighter-rouge">max_file_bytes</code>, <code class="language-plaintext highlighter-rouge">max_entries</code>, <code class="language-plaintext highlighter-rouge">search_max_files</code>, <code class="language-plaintext highlighter-rouge">search_max_bytes</code>), where <code class="language-plaintext highlighter-rouge">0</code> means unlimited and any positive number is a cap. Keep in mind that “unlimited” means the broker loads a whole file into memory when you approve a read of it.</p>

<h2 id="approving-requests-via-a-web-frontend-or-via-an-agent-with-a-totp-code">Approving Requests via a web frontend or via an agent with a TOTP code</h2>

<p>You can approve through either route, and whichever you use first wins. A second decision on the same request gets a “no longer pending” error.</p>

<h3 id="route-one-the-web-page">Route one: the web page</h3>

<p>The dashboard shows each pending request with the agent, the operation, the path, and for writes the SHA-256 hash of the proposed content. You press Approve or Deny. The page is protected by a password, and every button carries a token (CSRF protection) so another website can’t make your browser press it for you. Sessions last twelve hours.</p>

<p>The dashboard binds to <code class="language-plaintext highlighter-rouge">127.0.0.1</code> only, so it’s reachable from the machine itself and from nowhere else. We’ll come back to remote access.</p>

<h3 id="route-two-from-the-claude-session">Route two: from the Claude session</h3>

<p>I wanted to approve things from my phone, where I connect to the Claude instance in the container through Claude’s remote control, not to the dashboard. That needs a way for approval to happen inside the Claude conversation without an agent being able to approve its own requests.</p>

<p>Here is how it works. The lead agent, Claude, gets four extra <code class="language-plaintext highlighter-rouge">hostctl</code> commands:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>hostctl pending                 <span class="c"># list what is waiting</span>
hostctl approve ID CODE         <span class="c"># approve one request</span>
hostctl preview ID CODE         <span class="c"># show the diff for a write first (optional)</span>
hostctl deny ID                 <span class="c"># deny, no code needed</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">CODE</code> is a six-digit one-time code from your authenticator app. You type it into the conversation, Claude runs the command, and the broker checks the code. Three things stop this from being a hole:</p>

<ul>
  <li>The broker accepts these commands only from Claude’s UID, which it checks through the socket, as before. Any other agent gets a 403 error.</li>
  <li>Each code works exactly once. The broker remembers the last time-slot it accepted, so a code that was used can’t be replayed.</li>
  <li>Five wrong codes in a row lock approvals for five minutes.</li>
</ul>

<p>There is also a second gate in Claude Code itself. The container has a managed settings file at <code class="language-plaintext highlighter-rouge">/etc/claude-code/managed-settings.json</code>, owned by root so no agent can edit it. It makes Claude Code ask me before running <code class="language-plaintext highlighter-rouge">hostctl approve</code> or <code class="language-plaintext highlighter-rouge">hostctl preview</code>. So an approval takes both a tap on my phone and a valid code.</p>

<h3 id="how-the-one-time-code-works">How the one-time code works</h3>

<p>If you’ve used an authenticator app, you’ve used TOTP (time-based one-time passwords, <a href="https://www.rfc-editor.org/rfc/rfc6238">RFC 6238</a>). The app and the broker share a secret, a random string stored in both places. Every thirty seconds, each side independently computes the same six digits from the secret and the current time. Nothing is sent over a network, which is why it works without a connection.</p>

<p>The computation is small enough to show in full. Here it is in Python, as it appears in <code class="language-plaintext highlighter-rouge">totp_generate.sh</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">base64</span><span class="p">,</span> <span class="n">hashlib</span><span class="p">,</span> <span class="n">hmac</span><span class="p">,</span> <span class="n">struct</span><span class="p">,</span> <span class="n">time</span>

<span class="k">def</span> <span class="nf">code</span><span class="p">(</span><span class="n">secret_base32</span><span class="p">,</span> <span class="n">counter</span><span class="p">):</span>
    <span class="n">key</span> <span class="o">=</span> <span class="n">base64</span><span class="p">.</span><span class="n">b32decode</span><span class="p">(</span><span class="n">secret_base32</span><span class="p">)</span>
    <span class="n">digest</span> <span class="o">=</span> <span class="n">hmac</span><span class="p">.</span><span class="n">new</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">struct</span><span class="p">.</span><span class="n">pack</span><span class="p">(</span><span class="s">'&gt;Q'</span><span class="p">,</span> <span class="n">counter</span><span class="p">),</span> <span class="n">hashlib</span><span class="p">.</span><span class="n">sha1</span><span class="p">).</span><span class="n">digest</span><span class="p">()</span>
    <span class="n">offset</span> <span class="o">=</span> <span class="n">digest</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">&amp;</span> <span class="mi">15</span>
    <span class="n">number</span> <span class="o">=</span> <span class="n">struct</span><span class="p">.</span><span class="n">unpack</span><span class="p">(</span><span class="s">'&gt;I'</span><span class="p">,</span> <span class="n">digest</span><span class="p">[</span><span class="n">offset</span><span class="p">:</span><span class="n">offset</span> <span class="o">+</span> <span class="mi">4</span><span class="p">])[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&amp;</span> <span class="mh">0x7fffffff</span>
    <span class="k">return</span> <span class="s">'%06d'</span> <span class="o">%</span> <span class="p">(</span><span class="n">number</span> <span class="o">%</span> <span class="mi">1000000</span><span class="p">)</span>

<span class="k">print</span><span class="p">(</span><span class="n">code</span><span class="p">(</span><span class="s">'JBSWY3DPEHPK3PXP'</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="n">time</span><span class="p">.</span><span class="n">time</span><span class="p">()</span> <span class="o">//</span> <span class="mi">30</span><span class="p">)))</span>   <span class="c1"># JBSWY3DPEHPK3PXP is a well-known example secret, don't use it in production!
</span></code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">int(time.time() // 30)</code> is the “counter”: it increases by one every thirty seconds. The code runs HMAC-SHA1 on that counter using the secret as the key, takes four bytes from a spot chosen by the last byte of the result (“dynamic truncation”), and keeps the last six decimal digits. The broker accepts the code for the previous, current, or next time slot to allow for clocks that are slightly off, and then refuses to ever accept an earlier or equal slot again.</p>

<p>The secret is stored at <code class="language-plaintext highlighter-rouge">/state/secrets/approval-totp</code>, inside a folder only root can open. That’s also why the agents can’t read it. <code class="language-plaintext highlighter-rouge">run.sh</code> prints it on every start so you can always get it again, and you can read it later with <code class="language-plaintext highlighter-rouge">docker exec herdr-devbox cat /state/secrets/approval-totp</code>.</p>

<h3 id="the-trust-model-stated-plainly">The trust model, stated plainly</h3>

<p>The code you type into the Claude conversation is visible to Claude. Because it’s single-use and expires in about thirty seconds, a leaked code is not much good to anyone, and the Claude Code prompt is a second gate. But this route is weaker than the web page, where the secret never goes near an agent. I use it because being able to approve from my phone is worth that to me. If an agent were truly hostile, the web route is the one that holds up; the phone route holds up against mistakes and against an agent trying to approve its own requests without your knowledge, which are the cases I care about most.</p>

<h3 id="telling-claude-a-request-is-waiting">Telling Claude a request is waiting</h3>

<p>Approving from Claude only helps if Claude knows there is something to approve. When a request is created, the broker sends a short message into Claude’s terminal pane using Herdr’s <code class="language-plaintext highlighter-rouge">agent prompt</code> command. The message contains only the request ID, which agent asked, the operation, the drive and path (or the search text), and for writes the hash of the content. It never contains file contents or a diff. It also tells Claude what to do: show me the request, ask me for the current code, then run <code class="language-plaintext highlighter-rouge">hostctl approve</code>.</p>

<p>A few details keep this from becoming a problem. Paths and search text come from agents, so control characters are replaced and long text is cut off before it goes into the message; an agent can’t smuggle terminal escape codes or fake instructions into Claude’s prompt that way. Messages are batched, so one agent making fifty requests produces one notification rather than fifty. If the notification fails, the request still goes through; the broker logs the error and moves on. And when a request gets decided on the web page, or times out, Claude gets a one-line note so it doesn’t ask me about something already closed.</p>

<h3 id="approving-workflows">Approving Workflows</h3>

<p>Each agent has its own “may I run this command?” prompt, which became tedious: I’d approve running <code class="language-plaintext highlighter-rouge">hostctl read</code>, and then approve the read itself. Since the broker is the real gate, I told each agent to run <code class="language-plaintext highlighter-rouge">hostctl list</code>, <code class="language-plaintext highlighter-rouge">read</code>, <code class="language-plaintext highlighter-rouge">search</code>, <code class="language-plaintext highlighter-rouge">write</code>, and <code class="language-plaintext highlighter-rouge">pending</code> without asking. The devbox writes that into each agent’s own configuration at every start, using whatever mechanism that agent has (Claude’s managed settings, Codex’s rules files, Qwen’s and Antigravity’s settings, Grok’s config file, and OpenCode’s permission block). The commands that relay your decision, <code class="language-plaintext highlighter-rouge">approve</code>, <code class="language-plaintext highlighter-rouge">preview</code>, and <code class="language-plaintext highlighter-rouge">deny</code>, are deliberately left out, so those still ask. The files are merged, not overwritten, so settings you’ve added yourself survive, and a file that can’t be parsed is left alone with a logged warning.</p>

<h2 id="agents-working-together">Agents working together</h2>

<p>Claude, as the lead, can also look at and talk to the other agents, using <code class="language-plaintext highlighter-rouge">teamctl</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>teamctl status                      <span class="c"># which agents are idle, working, or blocked</span>
teamctl prompt codex <span class="s2">"write tests for the parser in my workspace"</span>
teamctl <span class="nb">read </span>codex                  <span class="c"># last 100 lines of codex's terminal</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">status</code> shows names and states only. <code class="language-plaintext highlighter-rouge">prompt</code> types a task into another agent’s terminal, and Claude Code asks me before running it, since the broker doesn’t gate it. <code class="language-plaintext highlighter-rouge">read</code> shows what is on another agent’s screen, which could include something sensitive, so it goes through the broker like a file read: it creates a request, and I approve it on the web page or with a code in the Claude session, the same as a host file. Nothing is read until I do.</p>

<p>To be clear about what this separates: Agents can’t read each other’s files, but if I ask Claude to relay something one agent saw to another, I’ve handed it over myself. Approving a read puts that content into the requesting agent’s context, and it can mention it to anyone it talks to. The approval step controls new access, not what happens after.</p>

<h2 id="bubblewrap-and-why-the-container-needs-a-custom-seccomp-profile">Bubblewrap, and why the container needs a custom seccomp profile</h2>

<p>This was the part I had to learn the most about to get right.</p>

<h3 id="what-bubblewrap-does">What bubblewrap does</h3>

<p><a href="https://github.com/containers/bubblewrap">Bubblewrap</a> (<code class="language-plaintext highlighter-rouge">bwrap</code>) is a small command that runs a program inside a sandbox, without needing root. It builds that sandbox out of Linux namespaces. A namespace gives a process a private view of one kind of system resource:</p>

<ul>
  <li>A <em>mount namespace</em> gives it its own set of mounted file systems. Bubblewrap uses this to show a program a tiny made-up file system: perhaps a read-only copy of <code class="language-plaintext highlighter-rouge">/usr</code>, a scratch <code class="language-plaintext highlighter-rouge">/tmp</code>, and one writable project folder, and nothing else.</li>
  <li>A <em>PID namespace</em> gives it its own process numbering, so it can’t see or signal other processes.</li>
  <li>A <em>network namespace</em> can cut off network access, or give it a private network.</li>
  <li>A <em>user namespace</em> is the clever one. Inside it, a process can appear to be root and have capabilities such as “may mount,” but only over things that belong to that namespace. That’s how an ordinary user can create the other namespaces without being a real administrator.</li>
  <li>IPC and UTS namespaces isolate shared-memory objects and the hostname.</li>
</ul>

<p>Codex uses bubblewrap on Linux to sandbox the commands it runs. This limits what the model’s commands can touch. It also means that Codex needs to be able to create those namespaces inside our container. In this setup Codex is the only agent whose sandbox depends on bubblewrap, so it is the only one that needs the wider seccomp profile. I didn’t turn on sandboxing for the others because the container, the separate UIDs, and the broker already keep them away from the host drives and from each other. Some of them could use it, though. Claude Code has an optional sandbox mode that, on Linux, relies on bubblewrap and <code class="language-plaintext highlighter-rouge">socat</code> (a relay that passes network traffic between the sandbox and a filtering proxy). Neither <code class="language-plaintext highlighter-rouge">bwrap</code> nor <code class="language-plaintext highlighter-rouge">socat</code> is in this image’s package list, so enabling that mode would mean installing both and accepting the same widened profile. I haven’t tried it, so check each agent’s current documentation before relying on this.</p>

<h3 id="configuring-a-custom-seccomp-policy">Configuring a Custom Seccomp Policy</h3>

<p>Docker, by default, applies a <em>seccomp profile</em> to every container. Seccomp is a kernel feature that filters the system calls a process may make. Docker’s default profile allows most of what normal programs need and blocks a number of calls that create namespaces or mount file systems, unless the container has the <code class="language-plaintext highlighter-rouge">SYS_ADMIN</code> capability. Those blocks are there because namespaces and mounts have historically been a rich source of kernel bugs, and a container that can create them has more of the kernel exposed to it.</p>

<p>So by default, bubblewrap inside a container fails with an error along the lines of “Creating new namespace failed: Operation not permitted.” The usual fixes are to run the container with <code class="language-plaintext highlighter-rouge">--privileged</code> or add <code class="language-plaintext highlighter-rouge">SYS_ADMIN</code>, both of which hand the container far more power than I want to give a box full of coding agents.</p>

<h3 id="composing-the-seccomp-configuration">Composing the seccomp Configuration</h3>

<p><code class="language-plaintext highlighter-rouge">prepare-seccomp.py</code> takes Docker’s own default profile (the <a href="https://github.com/moby/profiles/blob/main/seccomp/default.json"><code class="language-plaintext highlighter-rouge">default.json</code> in the Moby profiles repository</a>, which it downloads), keeps all of its rules, and adds exceptions for only the system calls bubblewrap needs:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">clone</code> is allowed when the flags don’t ask for a new cgroup namespace. The profile checks the first argument against a bit mask.</li>
  <li><code class="language-plaintext highlighter-rouge">unshare</code> is allowed only when the flags request some combination of user, mount, PID, network, IPC, and UTS namespaces (plus a System V semaphore flag), and nothing else.</li>
  <li><code class="language-plaintext highlighter-rouge">mount</code>, <code class="language-plaintext highlighter-rouge">umount2</code>, <code class="language-plaintext highlighter-rouge">pivot_root</code>, and <code class="language-plaintext highlighter-rouge">setns</code> are allowed outright.</li>
</ul>

<p>In the script this is a few lines that append rules to the profile’s list of syscalls. The interesting ones use <code class="language-plaintext highlighter-rouge">SCMP_CMP_MASKED_EQ</code>, which compares an argument after masking off some bits:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">rules</span><span class="p">.</span><span class="n">append</span><span class="p">({</span><span class="s">'names'</span><span class="p">:</span> <span class="p">[</span><span class="s">'clone'</span><span class="p">],</span> <span class="s">'action'</span><span class="p">:</span> <span class="s">'SCMP_ACT_ALLOW'</span><span class="p">,</span>
              <span class="s">'args'</span><span class="p">:</span> <span class="p">[{</span><span class="s">'index'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s">'value'</span><span class="p">:</span> <span class="mh">0x02000000</span><span class="p">,</span> <span class="s">'valueTwo'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
                        <span class="s">'op'</span><span class="p">:</span> <span class="s">'SCMP_CMP_MASKED_EQ'</span><span class="p">}]})</span>
</code></pre></div></div>

<p>That reads as: allow <code class="language-plaintext highlighter-rouge">clone</code> when the cgroup-namespace bit in argument 0 is zero. For <code class="language-plaintext highlighter-rouge">unshare</code>, the mask is everything except the permitted flags, and the comparison is to zero, so any flag outside the allowed set makes the call fail. I left <code class="language-plaintext highlighter-rouge">clone3</code>, the newer version of <code class="language-plaintext highlighter-rouge">clone</code>, at Docker’s default. It passes its flags through a pointer, which a seccomp filter can’t inspect, so there’s no safe way to filter it by flags.</p>

<p>The script also refuses to continue if the upstream profile already contains an explicit deny for one of these calls, because that would mean my assumptions about the profile are wrong and it deserves a human look.</p>

<h3 id="my-tradeoff">My Tradeoff</h3>

<p>This does widen the kernel surface exposed to every process in the container, not just Codex. A user namespace inside the container gives processes a kind of local “root” inside their own namespace, and the kernel code that handles that has had bugs. Several other protections still apply: the agents have no real capabilities, the container runs with <code class="language-plaintext highlighter-rouge">no-new-privileges</code>, and the kernel still checks capability and ownership rules for these calls. But I wouldn’t call the result a security certification, and neither does the script; it says to test the profile in a disposable container before pointing it at drives you care about. If you don’t use Codex, you can skip the custom profile and run with Docker’s default instead, but Codex’s bubblewrap sandbox then can’t create its namespaces. You can also change how Codex launches with <code class="language-plaintext highlighter-rouge">launch_commands</code> in the config.</p>

<h2 id="open-webui-as-the-default-model-provider">Open WebUI as the default model provider</h2>

<p>I run my own <a href="https://openwebui.com/">Open WebUI</a> server for open-weight models, and I wanted OpenCode, pi, and Qwen Code all to use it by default without my configuring each one by hand. When <code class="language-plaintext highlighter-rouge">run.sh</code> has your URL, key, and default model, the devbox writes the right settings into all three at each start:</p>

<ul>
  <li>OpenCode gets an <code class="language-plaintext highlighter-rouge">openwebui</code> provider and a default model of <code class="language-plaintext highlighter-rouge">openwebui/&lt;your model&gt;</code>.</li>
  <li>pi gets the provider through the <code class="language-plaintext highlighter-rouge">pi-openai-compat</code> extension, and a default provider and model in its settings.</li>
  <li>Qwen Code gets an OpenAI-compatible provider entry, the key in its <code class="language-plaintext highlighter-rouge">env</code> section, and the default model.</li>
</ul>

<p>For the URL, you can give the site’s address (the devbox appends <code class="language-plaintext highlighter-rouge">/api</code>), or a URL already ending in <code class="language-plaintext highlighter-rouge">/api</code> or <code class="language-plaintext highlighter-rouge">/v1</code> which is used as typed.</p>

<p>Two model-discovery plugins mean you aren’t limited to the single model you picked: <a href="https://github.com/BillJr99/opencode-auto-models">opencode-auto-models</a>, which asks the endpoint for its model list and adds all of them, and <a href="https://www.npmjs.com/package/@billjr99/pi-openai-compat">pi-openai-compat</a> for pi. The pi extension is installed into the image at build time. The OpenCode plugin is added to its configuration at a specific git commit, and OpenCode downloads it with <code class="language-plaintext highlighter-rouge">git</code> the first time it starts. That first start needs network access, and the result is cached in the volume after that. The menu in <code class="language-plaintext highlighter-rouge">run.sh</code> therefore only chooses what each agent starts on. Every model on the server is available from inside the agents.</p>

<p>If you add another provider to OpenCode, or log in to something with <code class="language-plaintext highlighter-rouge">/connect</code>, or add a provider to pi with <code class="language-plaintext highlighter-rouge">/compat-login</code>, it stays. Each configuration file is merged, not replaced: the devbox sets only the keys it owns (the permission rules, the Open WebUI provider’s address and key, and the default model if you haven’t chosen another one) and leaves the rest of the file alone. If you set a different default model yourself, the devbox respects that.</p>

<h2 id="persisting-agent-state">Persisting Agent State</h2>

<p>Agent state and configuration lives in the Docker volume named <code class="language-plaintext highlighter-rouge">herdr-devbox-state</code>, mounted at <code class="language-plaintext highlighter-rouge">/state</code>:</p>

<table>
  <thead>
    <tr>
      <th>What</th>
      <th>Where</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Each agent’s home: sign-ins, history, config</td>
      <td><code class="language-plaintext highlighter-rouge">/state/agents/&lt;name&gt;/</code></td>
    </tr>
    <tr>
      <td>Approval secret</td>
      <td><code class="language-plaintext highlighter-rouge">/state/secrets/approval-totp</code></td>
    </tr>
    <tr>
      <td>OpenCode web password</td>
      <td><code class="language-plaintext highlighter-rouge">/state/secrets/opencode-password</code></td>
    </tr>
    <tr>
      <td>Dashboard password</td>
      <td><code class="language-plaintext highlighter-rouge">/state/admin-password</code></td>
    </tr>
    <tr>
      <td>Saved Open WebUI settings</td>
      <td><code class="language-plaintext highlighter-rouge">/state/secrets/openwebui.json</code></td>
    </tr>
    <tr>
      <td>Backups of overwritten host files</td>
      <td><code class="language-plaintext highlighter-rouge">/state/backups/</code></td>
    </tr>
    <tr>
      <td>Audit log of every request and decision</td>
      <td><code class="language-plaintext highlighter-rouge">/state/audit.sqlite3</code></td>
    </tr>
  </tbody>
</table>

<p>The <code class="language-plaintext highlighter-rouge">secrets</code> folder, and the password files, are readable only by root. The state folder as a whole is set so other users can pass through it but not list it, so each agent can reach its own home and nothing else. This is why rebuilding the image or recreating the container doesn’t sign you out of anything. Only <code class="language-plaintext highlighter-rouge">docker volume rm herdr-devbox-state</code> throws it all away.</p>

<p>The audit log is worth a look now and then. Each row has the time, request ID, agent, operation, drive, path, and what happened to it (requested, approved via web or via the Claude session, denied, expired, failed).</p>

<h2 id="configuration">Configuration</h2>

<p>Defaults are in a JSON block inside the Dockerfile. To change them, write a JSON file containing just the keys you want to override, make it owned by root, and point <code class="language-plaintext highlighter-rouge">DEVBOX_CONFIG</code> at it. The loader refuses keys it doesn’t know, which catches typos.</p>

<table>
  <thead>
    <tr>
      <th>Key</th>
      <th>Default</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">max_file_bytes</code>, <code class="language-plaintext highlighter-rouge">max_entries</code>, <code class="language-plaintext highlighter-rouge">search_max_files</code>, <code class="language-plaintext highlighter-rouge">search_max_bytes</code></td>
      <td><code class="language-plaintext highlighter-rouge">0</code></td>
      <td>Limits; <code class="language-plaintext highlighter-rouge">0</code> is unlimited</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">approval_timeout_seconds</code></td>
      <td><code class="language-plaintext highlighter-rouge">600</code></td>
      <td>How long a request waits</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">notify_interval_seconds</code></td>
      <td><code class="language-plaintext highlighter-rouge">5</code></td>
      <td>Minimum gap between messages to Claude</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">web_port</code></td>
      <td><code class="language-plaintext highlighter-rouge">8090</code></td>
      <td>Dashboard port inside the container</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">require_mounts</code></td>
      <td><code class="language-plaintext highlighter-rouge">true</code></td>
      <td>Refuse to start unless the drives are mounted</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">launch_commands</code></td>
      <td>Codex only</td>
      <td>Per-agent launch command overrides</td>
    </tr>
  </tbody>
</table>

<p><code class="language-plaintext highlighter-rouge">run.sh</code> also reads a few environment variables, including <code class="language-plaintext highlighter-rouge">DEVBOX_IMAGE</code>, <code class="language-plaintext highlighter-rouge">DEVBOX_CONTAINER</code>, and <code class="language-plaintext highlighter-rouge">DEVBOX_VOLUME</code> if you want different names, and <code class="language-plaintext highlighter-rouge">DEVBOX_TOTP_SECRET</code>, <code class="language-plaintext highlighter-rouge">DEVBOX_ADMIN_PASSWORD</code>, and <code class="language-plaintext highlighter-rouge">DEVBOX_OPENCODE_PASSWORD</code> if you’d rather supply the secrets yourself than have them generated. Values given that way replace what’s saved, without a prompt. Be aware that anything passed to a container with <code class="language-plaintext highlighter-rouge">-e</code> can be seen by someone who can run <code class="language-plaintext highlighter-rouge">docker inspect</code> on the host.</p>

<h2 id="reaching-it-from-somewhere-else">Reaching it from somewhere else</h2>

<p>By default, <code class="language-plaintext highlighter-rouge">run.sh</code> publishes the dashboard and the OpenCode web port on <code class="language-plaintext highlighter-rouge">127.0.0.1</code>, which means only the host itself can connect. If you want to reach them from your phone or another computer on a trusted network, set <code class="language-plaintext highlighter-rouge">DEVBOX_BIND</code> to the address you want, such as your VPN interface’s address, before running <code class="language-plaintext highlighter-rouge">run.sh</code>. On Windows with WSL2, you may also need to open the Windows firewall for the port, and arrange for the traffic to reach WSL. The dashboard is plain HTTP and the <code class="language-plaintext highlighter-rouge">/terminal/</code> page is a complete shell into the container, so only bind it to something you trust. A safer habit is an SSH tunnel from the other machine:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh <span class="nt">-N</span> <span class="nt">-L</span> 8090:127.0.0.1:8090 you@your-docker-host
</code></pre></div></div>

<p>Then open <code class="language-plaintext highlighter-rouge">http://localhost:8090</code> on that machine. For my own use, the Claude remote-control route needs none of this; it works through Anthropic’s service, so approving from the phone doesn’t require exposing the dashboard.</p>

<h2 id="testing">Testing</h2>

<p>The project has a self-test, <code class="language-plaintext highlighter-rouge">docker run --rm herdr-devbox self-test</code>, and the build runs it too. About sixty checks cover the things I’d be most upset to get wrong:</p>

<ul>
  <li>Each agent’s UID gets “permission denied” reading the drives, the passwords, and the secrets.</li>
  <li>A request does no file work before approval; denied and expired requests return nothing.</li>
  <li>Path tricks (<code class="language-plaintext highlighter-rouge">..</code>, absolute paths, colons, backslashes, device names, symbolic links in the middle of a path) are refused.</li>
  <li>Replaying an approval fails. A forged agent name in a message is ignored.</li>
  <li>Writes need an unchanged file, keep a backup, and fail if the file changed.</li>
  <li>The one-time codes: a wrong code is refused, a used code can’t be reused, five failures lock approvals, and only the lead can relay.</li>
  <li>Notifications to Claude contain no file contents, strip control characters, batch, and don’t break a request if they fail.</li>
  <li>The merged configuration files keep what you added, don’t override a default you chose, and leave unparseable files alone.</li>
  <li>The three saved secrets persist, can be replaced, and stay out of the agents’ reach.</li>
</ul>

<p>A couple of those checks need real separate UIDs, so they only run inside the built image (on a plain host, the suite skips them, and the build fails if they get skipped there).</p>

<p>One story from while I was building it: I used HTML comment markers (<code class="language-plaintext highlighter-rouge">&lt;!-- --&gt;</code>) to fence off the section of each agent’s configuration file that the devbox manages. That’s fine for the Markdown rules files, but Grok’s configuration is a TOML file, where that syntax is an error, and Grok refused to start. The fix was to use <code class="language-plaintext highlighter-rouge">#</code> comments in TOML files and to remove the old block on the next start. It is a good example of why the self-test now parses every configuration file it generates.</p>

<h2 id="limits-of-this-design">Limits of this design</h2>

<p>Nothing here is perfect isolation. These are the edges as I know them.</p>

<ul>
  <li>Containers share the host’s kernel. A kernel bug could cross the boundary, and the widened seccomp profile exposes a bit more of the kernel to every process in the container.</li>
  <li>The root broker and controller are trusted. A bug in <code class="language-plaintext highlighter-rouge">devbox.py</code> is a bug in the security boundary, which is the reason the whole thing is a single file you can read.</li>
  <li>Approving content hands it to the agent. After that, the agent can use it however it likes, including repeating it to other agents.</li>
  <li>The phone route puts a one-time code in front of Claude. It’s good against mistakes and unattended approvals, and weaker than the web page against a determined hostile agent.</li>
  <li>Windows drive and network-share behavior (permissions, symbolic links, atomic renames) varies. Test with files you can afford to lose before trusting it with anything else.</li>
  <li>API keys in the Open WebUI integration are stored in the agents’ own private configuration files, in the volume. They’re protected from other agents, not from someone with access to the Docker host.</li>
  <li>I built this against the agent versions set in the Dockerfile. Agent CLIs change quickly, and the configuration formats the devbox writes are the first thing a new release is likely to break.</li>
</ul>

<h2 id="troubleshooting">Troubleshooting</h2>

<p><strong><code class="language-plaintext highlighter-rouge">run.sh</code> says a drive isn’t mounted.</strong> The script checks that each host drive is a real mount point under <code class="language-plaintext highlighter-rouge">/mnt</code> in WSL. Run <code class="language-plaintext highlighter-rouge">findmnt -M /mnt/c</code> (or the drive it named). If a drive isn’t mounted in WSL, mount it first, or remove that drive from the lists described earlier.</p>

<p><strong>Bubblewrap or Codex says it can’t create a namespace.</strong> Make sure the container started with the custom profile: <code class="language-plaintext highlighter-rouge">docker inspect herdr-devbox</code> should show the <code class="language-plaintext highlighter-rouge">seccomp=</code> path to your <code class="language-plaintext highlighter-rouge">herdr-seccomp.json</code> under the security options.</p>

<p><strong>An approved read didn’t leave a file behind.</strong> <code class="language-plaintext highlighter-rouge">hostctl read</code> prints the file’s bytes to the agent’s output. It doesn’t copy anything into the workspace. If you want a local copy, redirect the output: <code class="language-plaintext highlighter-rouge">hostctl read d notes.txt &gt; notes.txt</code>.</p>

<p><strong>You lost the approval secret.</strong> <code class="language-plaintext highlighter-rouge">docker exec herdr-devbox cat /state/secrets/approval-totp</code>, or run <code class="language-plaintext highlighter-rouge">run.sh</code> and say yes to overwriting if you want a new one (then re-add it to your authenticator app).</p>

<p><strong>OpenCode shows only one model.</strong> The model-discovery plugin is downloaded the first time OpenCode starts, so it needs network access and <code class="language-plaintext highlighter-rouge">git</code>. Check the OpenCode tab for errors, and restart it after the first start has finished downloading.</p>

<p><strong>You edited a configuration file and the devbox complained.</strong> Files the devbox merges into must be valid JSON (or TOML for Grok). If one can’t be parsed, the devbox leaves it alone and logs a warning, which is safe, but it means its own settings aren’t applied to that file until you fix it.</p>

<h2 id="next-steps">Next Steps</h2>

<p>The same shape works for other things. The broker pattern (an untrusted client asks, a trusted process checks and waits for a person, then acts) fits any capability you’d like an agent to use but not hold, such as a deploy key or a database connection. The one-time-code idea is also reusable: it’s about forty lines, and it lets a person authorize something from a device that has no direct access to the machine.</p>

<p>A last word of caution: this is experimental and shouldn’t be relied on in production. I built it for my own use case, so it may not be appropriate or secure enough for general-purpose use. Treat it as a reference for the decisions and tradeoffs I made, and test it with files you can afford to lose.</p>

<h2 id="references">References</h2>

<ul>
  <li><a href="https://herdr.dev/docs/install/">Herdr documentation</a> and its <a href="https://herdr.dev/docs/agents/">list of supported agents</a></li>
  <li><a href="https://docs.docker.com/engine/security/seccomp/">Docker’s default seccomp profile</a> and the <a href="https://github.com/moby/profiles">Moby profile source</a></li>
  <li><a href="https://github.com/containers/bubblewrap">Bubblewrap</a></li>
  <li><a href="https://man7.org/linux/man-pages/man7/namespaces.7.html">Linux namespaces</a> and <a href="https://man7.org/linux/man-pages/man7/user_namespaces.7.html">user namespaces</a></li>
  <li><a href="https://www.rfc-editor.org/rfc/rfc6238">RFC 6238: TOTP</a> and <a href="https://www.rfc-editor.org/rfc/rfc4226">RFC 4226: HOTP</a></li>
  <li><a href="https://code.claude.com/docs/en/remote-control">Claude Code remote control</a> and <a href="https://code.claude.com/docs/en/settings">managed settings</a></li>
  <li><a href="https://learn.chatgpt.com/docs/agent-configuration/rules">Codex rules</a></li>
  <li><a href="https://github.com/BillJr99/opencode-auto-models">opencode-auto-models</a> and <a href="https://www.npmjs.com/package/@billjr99/pi-openai-compat">pi-openai-compat</a></li>
  <li><a href="https://openwebui.com/">Open WebUI</a></li>
</ul>

<h2 id="the-files">The files</h2>

<p>Save each of these in one folder using the name in its heading. Two other files appear when you build: <code class="language-plaintext highlighter-rouge">default.json</code> is Docker’s upstream seccomp profile, which <code class="language-plaintext highlighter-rouge">prepare-seccomp.py</code> downloads and keeps, and <code class="language-plaintext highlighter-rouge">herdr-seccomp.json</code> is the profile it generates from that. Neither needs to be typed in. A few lines in the Dockerfile say “Bill” (in the rules text the agents are given and in the messages to Claude); change those to your name.</p>

<h3 id="dockerfile"><code class="language-plaintext highlighter-rouge">Dockerfile</code></h3>

<p>The image and the whole application: the broker, launcher, self-tests, and default configuration are embedded here.</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># syntax=docker/dockerfile:1.7</span>
<span class="c"># Single-file HerdR devbox, 2026-10-16.</span>
<span class="c"># Authoring checks: payload syntax + 19 portable handler/filesystem tests passed.</span>
<span class="c"># Six real UID/socket integration checks need Docker and run during image build.</span>
<span class="c"># The authoring environment had no Docker daemon; full image and provider logins</span>
<span class="c"># have not been exercised here. Validate WSL/share semantics on your host.</span>
<span class="c"># No local COPY sources, Compose file, privileged mode, or Docker socket required.</span>
<span class="c">#</span>
<span class="c"># BUILD:</span>
<span class="c">#   docker build --pull -t herdr-devbox .</span>
<span class="c"># CHECK (synthetic fixtures only, no host mounts):</span>
<span class="c">#   docker run --rm herdr-devbox self-test</span>
<span class="c"># RUN from WSL, after confirming /mnt/c is the actual drive mount:</span>
<span class="c">#   findmnt -M /mnt/c</span>
<span class="c">#   docker run -it --name herdr-devbox \</span>
<span class="c">#     --security-opt no-new-privileges=true \</span>
<span class="c">#     --mount type=volume,src=herdr-devbox-state,dst=/state \</span>
<span class="c">#     --mount type=bind,src=/mnt/c,dst=/host-private/c \</span>
<span class="c">#     --add-host=host.docker.internal:host-gateway \</span>
<span class="c">#     -p 127.0.0.1:8090:8090 -p 127.0.0.1:4096:4096 \</span>
<span class="c">#     -e OPENWEBUI_URL=https://YOUR-WEBUI-HOST \</span>
<span class="c">#     -e OPENWEBUI_MODEL=YOUR-EXACT-MODEL-ID \</span>
<span class="c">#     -e OPENWEBUI_API_KEY herdr-devbox</span>
<span class="c"># Set OPENWEBUI_API_KEY in your shell before running; do not put the key here.</span>
<span class="c"># Alternatively use OPENWEBUI_API_KEY_FILE with a read-only secret mounted below</span>
<span class="c"># /host-private/secrets, which remains inaccessible to agents.</span>
<span class="c"># OPENWEBUI_URL may be the WebUI origin, an /api base, or a full chat-completions</span>
<span class="c"># URL. For a custom prefix use its complete API base, ending in /api or /v1.</span>
<span class="c"># All Open WebUI settings are runtime inputs, never build arguments.</span>
<span class="c">#</span>
<span class="c"># Open http://localhost:8090 and use the password printed at startup.</span>
<span class="c"># /terminal/ is a live, authenticated view of this exact HerdR session.</span>
<span class="c"># Native Claude and agy remote control is enabled on interactive launch; complete</span>
<span class="c"># eligible subscription sign-in and workspace trust yourself in each pane.</span>
<span class="c"># Codex's managed remote-control server is enabled after login; pair from the</span>
<span class="c"># Codex shell with: codex remote-control pair</span>
<span class="c"># Grok Build 1.0.62 has no documented native remote-control switch; its exact</span>
<span class="c"># live session is remotely controllable through the common browser terminal.</span>
<span class="c"># Pi and Qwen Code are also supported by HerdR and run under their own UIDs with no yolo</span>
<span class="c"># flags. Pi has no per-tool approval prompts by design (its containment is the UID boundary</span>
<span class="c"># here, plus project-trust prompts: never launch it with -a, which auto-trusts project files).</span>
<span class="c"># Not added: CodeWhale, DeepSeek dsh and Mistral Vibe (not HerdR-supported), Gemini CLI.</span>
<span class="c"># OpenCode uses one authenticated web backend plus an attached HerdR TUI.</span>
<span class="c"># Its username/password are printed at startup; access via localhost:4096.</span>
<span class="c">#</span>
<span class="c"># Close the browser tab to detach. Ctrl+B, Q detaches the local HerdR client;</span>
<span class="c"># in foreground mode detaching stops the container. Use docker run -d instead</span>
<span class="c"># of -it for an always-on browser-only session. Stop with docker stop herdr-devbox.</span>
<span class="c"># Resume an existing stopped container: docker start -ai herdr-devbox</span>
<span class="c"># Attach to a running background instance:</span>
<span class="c">#   docker exec -it herdr-devbox /usr/local/bin/devbox attach</span>
<span class="c"># Retrieve generated UI passwords: docker logs herdr-devbox</span>
<span class="c"># Credentials, local workspaces, backups, audit, and CLI history persist in /state.</span>
<span class="c"># Active jobs end on container stop. Native conversation resume is available in</span>
<span class="c"># each CLI; exact automatic conversation restoration is not claimed.</span>
<span class="c">#</span>
<span class="c"># On another computer, forward the private dashboard through SSH:</span>
<span class="c">#   ssh -N -L 8090:127.0.0.1:8090 USER@DOCKER-HOST</span>
<span class="c"># Then open http://localhost:8090 there. No public web port is needed.</span>
<span class="c">#</span>
<span class="c"># PERMISSIONS:</span>
<span class="c"># Each agent has a distinct UID. /host-private is root-owned 0700, protecting</span>
<span class="c"># mounted drives without changing permissions on Windows files. No agent runs</span>
<span class="c"># as root. The root controller and approval broker are trusted processes.</span>
<span class="c"># hostctl requests list/read/search/write, checking the socket peer's kernel UID.</span>
<span class="c"># Every operation needs a separate human approval; write preview and final write</span>
<span class="c"># are separate decisions. No raw host file descriptor or direct mount is granted.</span>
<span class="c"># This mediates NEW host operations. Already approved content can remain in an</span>
<span class="c"># agent's workspace/model context. Separate identities cannot enforce semantic</span>
<span class="c"># non-disclosure if cooperating agents are deliberately given the same data.</span>
<span class="c"># Broker writes recheck file hashes and preserve the old bytes; there is no</span>
<span class="c"># portable atomic compare-and-swap guarantee against simultaneous host writers.</span>
<span class="c"># DrvFS junctions/SMB durability require validation on your actual WSL/share setup.</span>
<span class="c"># Do not expose separate unauthenticated host filesystem/Docker APIs to agents.</span>
<span class="c">#</span>
<span class="c"># Optional root-owned JSON configuration override: DEVBOX_CONFIG=/path/config.json.</span>
<span class="c"># max_file_bytes, max_entries, search_max_files and search_max_bytes default to 0,</span>
<span class="c"># which means unlimited; set a positive number in the override to restore a cap.</span>
<span class="c"># Runtime knobs and default launch commands are in embedded defaults.json below.</span>
<span class="c"># Agent commands are not allowed to modify broker policy or approve requests.</span>
<span class="c"># Build uses pinned agent releases and verified HerdR/agy payload checksums.</span>
<span class="c"># Base-image tags and Ubuntu security packages remain updateable.</span>

<span class="k">FROM</span><span class="w"> </span><span class="s">node:24-bookworm-slim</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">node_runtime</span>
<span class="k">FROM</span><span class="s"> ubuntu:24.04</span>
<span class="k">ENV</span><span class="s"> DEBIAN_FRONTEND=noninteractive TZ=America/New_York LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8</span>
<span class="k">SHELL</span><span class="s"> ["/bin/bash", "-o", "pipefail", "-c"]</span>
<span class="k">RUN </span>apt-get update <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>    ca-certificates curl git openssh-client locales tzdata <span class="se">\
</span>    python3 python3-aiohttp python3-venv python3-pip <span class="se">\
</span>    util-linux procps ripgrep jq unzip xz-utils ttyd tini <span class="se">\
</span>    libatomic1 libstdc++6 libgcc-s1 build-essential <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">sed</span> <span class="nt">-i</span> <span class="s1">'s/^# *en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/'</span> /etc/locale.gen <span class="se">\
</span>    <span class="o">&amp;&amp;</span> locale-gen en_US.UTF-8 <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
<span class="k">COPY</span><span class="s"> --from=node_runtime /usr/local/ /usr/local/</span>
<span class="k">ARG</span><span class="s"> CLAUDE_VERSION=2.1.302</span>
<span class="k">ARG</span><span class="s"> CODEX_VERSION=0.163.0</span>
<span class="k">ARG</span><span class="s"> GROK_VERSION=1.0.62</span>
<span class="k">ARG</span><span class="s"> OPENCODE_VERSION=1.19.3</span>
<span class="k">ARG</span><span class="s"> PI_VERSION=1.3.0</span>
<span class="k">ARG</span><span class="s"> QWEN_VERSION=0.25.2</span>
<span class="c"># pi-openai-compat publishes on every push to main, so a version is pinned. The opencode plugin</span>
<span class="c"># is pinned by commit in devbox.py (OPENCODE_PLUGIN) and installed by opencode on first start.</span>
<span class="k">ARG</span><span class="s"> PI_OPENAI_COMPAT_VERSION=1.1.35</span>
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">--global</span> <span class="nt">--omit</span><span class="o">=</span>dev <span class="se">\
</span>    <span class="s2">"@anthropic-ai/claude-code@</span><span class="k">${</span><span class="nv">CLAUDE_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="s2">"@openai/codex@</span><span class="k">${</span><span class="nv">CODEX_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="s2">"@xai-official/grok@</span><span class="k">${</span><span class="nv">GROK_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="s2">"opencode-ai@</span><span class="k">${</span><span class="nv">OPENCODE_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="o">&amp;&amp;</span> npm cache clean <span class="nt">--force</span>
<span class="c"># Pi is installed without lifecycle scripts; Qwen Code needs none either.</span>
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">--global</span> <span class="nt">--omit</span><span class="o">=</span>dev <span class="nt">--ignore-scripts</span> <span class="se">\
</span>    <span class="s2">"@earendil-works/pi-coding-agent@</span><span class="k">${</span><span class="nv">PI_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="s2">"@qwen-code/qwen-code@</span><span class="k">${</span><span class="nv">QWEN_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="o">&amp;&amp;</span> npm cache clean <span class="nt">--force</span>
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">--global</span> <span class="nt">--omit</span><span class="o">=</span>dev <span class="nt">--ignore-scripts</span> <span class="se">\
</span>    <span class="s2">"@billjr99/pi-openai-compat@</span><span class="k">${</span><span class="nv">PI_OPENAI_COMPAT_VERSION</span><span class="k">}</span><span class="s2">"</span> <span class="se">\
</span>    <span class="o">&amp;&amp;</span> npm cache clean <span class="nt">--force</span> <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">test</span> <span class="nt">-f</span> /usr/local/lib/node_modules/@billjr99/pi-openai-compat/index.ts
<span class="k">RUN </span><span class="nb">install</span> <span class="nt">-d</span> <span class="nt">-m</span> 0755 /opt/devbox /state /run/devbox <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">install</span> <span class="nt">-d</span> <span class="nt">-m</span> 0700 /host-private /host-private/secrets <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">mkdir</span> /host-private/c <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="k">for </span>pair <span class="k">in </span>claude:21001 codex:21002 agy:21003 grok:21004 opencode:21005 pi:21006 qwen:21007<span class="p">;</span> <span class="k">do</span> <span class="se">\
</span>        <span class="nv">agent_name</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">pair</span><span class="p">%</span>:<span class="p">*</span><span class="k">}</span><span class="s2">"</span><span class="p">;</span> <span class="nv">agent_uid</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">pair</span><span class="p">#*</span>:<span class="k">}</span><span class="s2">"</span><span class="p">;</span> <span class="se">\
</span>        groupadd <span class="nt">--gid</span> <span class="s2">"</span><span class="nv">$agent_uid</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$agent_name</span><span class="s2">"</span><span class="p">;</span> <span class="se">\
</span>        useradd <span class="nt">--uid</span> <span class="s2">"</span><span class="nv">$agent_uid</span><span class="s2">"</span> <span class="nt">--gid</span> <span class="s2">"</span><span class="nv">$agent_uid</span><span class="s2">"</span> <span class="nt">--no-create-home</span> <span class="se">\
</span>          <span class="nt">--home-dir</span> <span class="s2">"/state/agents/</span><span class="nv">$agent_name</span><span class="s2">"</span> <span class="nt">--shell</span> /bin/bash <span class="s2">"</span><span class="nv">$agent_name</span><span class="s2">"</span><span class="p">;</span> <span class="se">\
</span>    <span class="k">done</span>
<span class="k">RUN </span>python3 - <span class="o">&lt;&lt;</span><span class="sh">'</span><span class="no">INSTALL_NATIVE</span><span class="sh">'</span>
import hashlib, io, json, pathlib, platform, tarfile, traceback, urllib.request
arch = platform.machine()
platforms = {
 'x86_64': {
  'herdr': ('https://github.com/herdrdev/herdr/releases/download/v0.9.5/herdr-linux-x86_64',
            '14d9e8bc8b4a9e0118d77c32266f76d461f09b40342eb23752960bd89f59929d'),
  'agy': ('https://storage.googleapis.com/antigravity-public/antigravity-cli/1.4.0-5281842794987520/linux-x64/cli_linux_x64.tar.gz',
          '6c4b298c2a69b6bd0f58567031cc56d8097a32be54c4b633aa80ad395871b389618ab3860d4ba0a12599831b8226b51b03e258ee2ec7fae105a45b8e0fce2188')},
 'aarch64': {
  'herdr': ('https://github.com/herdrdev/herdr/releases/download/v0.9.5/herdr-linux-aarch64',
            '17d7536f2da50859523680ef279dffcac8e4a235f4e46fe8da6c2ec44141897c'),
  'agy': ('https://storage.googleapis.com/antigravity-public/antigravity-cli/1.4.0-5281842794987520/linux-arm/cli_linux_arm64.tar.gz',
          '64dfb2a9665ebd19b6e9d687c094673b61ca9f5ffdebc81391cea8e3858773e1c88154f088e8a8691208561d946a7aea9acbec7a3bdca9e5d8a48fa197b0a308')}
}
if arch not in platforms:
 raise SystemExit('Supported architectures: x86_64 and aarch64')
for name, (url, expected) in platforms[arch].items():
 try:
  for attempt in range(3):
   try:
    req = urllib.request.Request(url, headers={'User-Agent': 'herdr-devbox-build'})
    with urllib.request.urlopen(req, timeout=180) as response:
     payload = response.read()
    break
   except Exception as e:
    print('[download]', e); traceback.print_exc()
    if attempt == 2: raise
  algorithm = 'sha512' if name == 'agy' else 'sha256'
  if hashlib.new(algorithm, payload).hexdigest() != expected:
   raise ValueError(name + ' checksum mismatch')
  if name == 'agy':
   with tarfile.open(fileobj=io.BytesIO(payload), mode='r:gz') as archive:
    member = archive.getmember('antigravity')
    if not member.isfile(): raise ValueError('Unexpected agy archive member')
    payload = archive.extractfile(member).read()
  path = pathlib.Path('/usr/local/bin') / name
  path.write_bytes(payload); path.chmod(0o755)
 except Exception as e:
  print('[native installation]', e); traceback.print_exc(); raise
INSTALL_NATIVE

<span class="k">COPY</span><span class="s"> &lt;&lt;'DEVBOX_PY' /opt/devbox/devbox.py</span>
<span class="c">#!/usr/bin/python3</span>
"""One-container HerdR workstation. All mutable policy lives in JSON."""
import argparse
import asyncio
import base64
import ctypes
import difflib
import hashlib
import hmac
import html
import http.cookies
import json
import os
import pathlib
import re
import resource
import secrets
import signal
import socket
import sqlite3
import stat
import struct
import subprocess
import sys
import tempfile
import time
import traceback
<span class="k">from</span><span class="s"> aiohttp import web, ClientSession, UnixConnector, WSMsgType</span>

HERE = pathlib.Path(__file__).resolve().parent
AGENTS = {name: 21001 + i for i, name in enumerate(
    ('claude', 'codex', 'agy', 'grok', 'opencode', 'pi', 'qwen'))}
UIDS = {v: k for k, v in AGENTS.items()}
STATE = pathlib.Path(os.environ.get('DEVBOX_STATE', '/state'))
<span class="k">RUN </span><span class="o">=</span> pathlib.Path<span class="o">(</span>os.environ.get<span class="o">(</span><span class="s1">'DEVBOX_RUN'</span>, <span class="s1">'/run/devbox'</span><span class="o">))</span>
DRIVES = pathlib.Path(os.environ.get('DEVBOX_DRIVES', '/host-private'))
CFG = {}
CHILDREN = []


def error(where, exc):
    print(f'[{where}] {exc}', file=sys.stderr, flush=True)
    traceback.print_exc()


def load_config():
    cfg = json.loads((HERE / 'defaults.json').read_text())
    # Cached Open WebUI settings live in the root-only secrets directory of the state volume.
    try:
        saved = json.loads((STATE / 'secrets/openwebui.json').read_text())
    except (OSError, ValueError):
        saved = {}
    for key in ('openwebui_url', 'openwebui_model'):
        if saved.get(key):
            cfg[key] = saved[key]
    override = os.environ.get('DEVBOX_CONFIG')
    if override:
        extra = json.loads(pathlib.Path(override).read_text())
        for key, value in extra.items():
            if key not in cfg:
                raise ValueError(f'Unknown configuration key: {key}')
            cfg[key] = value
    envmap = {'OPENWEBUI_URL': 'openwebui_url', 'OPENWEBUI_MODEL': 'openwebui_model',
              'DEVBOX_TOTP_SECRET': 'approval_totp_secret'}
    for env, key in envmap.items():
        if env in os.environ:
            cfg[key] = os.environ[env]
    cfg['openwebui_key'] = os.environ.get('OPENWEBUI_API_KEY') or saved.get('openwebui_key', '')
    keyfile = os.environ.get('OPENWEBUI_API_KEY_FILE')
    if keyfile:
        cfg['openwebui_key'] = pathlib.Path(keyfile).read_text().strip()
    if bool(cfg['openwebui_url']) != bool(cfg['openwebui_model']):
        raise ValueError('Set OPENWEBUI_URL and OPENWEBUI_MODEL together')
    return cfg


def cap(key):
    """Configured numeric limit; 0 means unlimited."""
    return CFG[key] or float('inf')


def client_limit():
    """aiohttp request body cap derived from the file limit (0 = unlimited)."""
    return CFG['max_file_bytes'] * 2 if CFG['max_file_bytes'] else 1 &lt;&lt; 62


MANAGED_BEGIN = '&lt;!-- devbox-managed:begin --&gt;'
MANAGED_END = '&lt;!-- devbox-managed:end --&gt;'
TOML_BEGIN = '# devbox-managed:begin'
TOML_END = '# devbox-managed:end'


def write_managed(path, body, uid=0, begin=MANAGED_BEGIN, end_marker=MANAGED_END):
    """Refresh the devbox block between markers; keep user text outside it. Never follows symlinks."""
    block = begin + '\n' + body.rstrip('\n') + '\n' + end_marker + '\n'
    existing = ''
    try:
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    except FileNotFoundError:
        pass
    else:
        with os.fdopen(fd, 'r', errors='replace') as f:
            if not stat.S_ISREG(os.fstat(f.fileno()).st_mode):
                raise ValueError(f'Refusing non-regular rules file: {path}')
            existing = f.read()
    start = existing.find(begin)
    end = existing.find(end_marker, start + 1) if start &gt;= 0 else -1
    if start &gt;= 0 and end &gt;= 0:
        tail = existing[end + len(end_marker):].lstrip('\n')
        text = existing[:start] + block + (('\n' + tail) if tail else '')
    elif existing.strip():
        text = block + '\n' + existing  <span class="c"># Pre-marker file: keep its content below the managed block.</span>
    else:
        text = block
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, 'w') as f:
        f.write(text)
        os.fchown(f.fileno(), uid, uid)
        os.fchmod(f.fileno(), 0o600)


# hostctl subcommands that only create broker requests; the broker's own approval gates them.
# approve/preview/deny (the human's decision relay) are deliberately not pre-allowed anywhere.
HOSTCTL_FREE = ('list', 'read', 'search', 'write', 'pending')


def write_owned(path, text, uid):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, 'w') as f:
        f.write(text)
        os.fchown(f.fileno(), uid, uid)
        os.fchmod(f.fileno(), 0o600)


def read_text_nofollow(path):
    try:
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    except FileNotFoundError:
        return None
    with os.fdopen(fd, 'r', errors='replace') as f:
        if not stat.S_ISREG(os.fstat(f.fileno()).st_mode):
            raise ValueError(f'Refusing non-regular file: {path}')
        return f.read()


def merge_allow(path, entries, uid):
    """Add entries to permissions.allow in a JSON settings file, keeping everything else."""
    text = read_text_nofollow(path)
    try:
        doc = json.loads(text) if text and text.strip() else {}
        perms = doc.setdefault('permissions', {})
        allow = perms.setdefault('allow', [])
        if not isinstance(doc, dict) or not isinstance(perms, dict) or not isinstance(allow, list):
            raise ValueError('unexpected structure')
    except ValueError as e:
        error('permissions merge skipped for ' + str(path), e)  # Never clobber a file we cannot parse.
        return
    for entry in entries:
        if entry not in allow:
            allow.append(entry)
    write_owned(path, json.dumps(doc, indent=2) + '\n', uid)


def refresh_agent_permissions(name, home, uid):
    """Pre-allow the broker-gated hostctl subcommands in each agent's own permission system."""
    free = HOSTCTL_FREE
    if name == 'codex':
        rules = home / '.codex/rules'
        private_dir(rules, uid)
        write_owned(rules / 'devbox.rules', ''.join(
            'prefix_rule(pattern = ["hostctl", "%s"], decision = "allow", '
            'justification = "Host request gated by the devbox broker")\n' % sub
            for sub in free), uid)
    elif name == 'qwen':
        merge_allow(home / '.qwen/settings.json', ['run_shell_command(hostctl %s)' % sub for sub in free], uid)
    elif name == 'agy':
        directory = home / '.gemini/antigravity-cli'
        private_dir(directory, uid)
        merge_allow(directory / 'settings.json', ['command(hostctl %s)' % sub for sub in free], uid)
    elif name == 'grok':
        body = '[permission]\nrules = [\n' + ''.join(
            '  { action = "allow", tool = "bash", pattern = "hostctl %s *" },\n'
            '  { action = "allow", tool = "bash", pattern = "hostctl %s" },\n' % (sub, sub)
            for sub in free) + ']'
        path = home / '.grok/config.toml'
        existing = read_text_nofollow(path) or ''
        # Earlier builds wrote HTML-comment markers, which are invalid TOML; drop that block.
        legacy = re.sub(re.escape(MANAGED_BEGIN) + '.*?' + re.escape(MANAGED_END) + r'\n?', '', existing, flags=re.S)
        if legacy != existing:
            write_owned(path, legacy, uid)
            existing = legacy
        outside = re.sub(re.escape(TOML_BEGIN) + '.*?' + re.escape(TOML_END), '', existing, flags=re.S)
        if re.search(r'^\s*\[permission\]', outside, re.M):
            error('grok permissions', ValueError('config.toml already has its own [permission] table; '
                                                 'add hostctl allow rules there manually'))
        else:
            write_managed(path, body, uid, TOML_BEGIN, TOML_END)
    # claude: root-owned managed settings (Dockerfile). opencode: generated config below. pi: has no prompts.


# Same spec `opencode plugin github:BillJr99/opencode-auto-models<span class="c">#&lt;commit&gt;` writes to the config</span>
<span class="c"># (opencode 1.19.3 uses the plugin array); opencode fetches it with git on first start.</span>
OPENCODE_PLUGIN = 'github:BillJr99/opencode-auto-models<span class="c">#9950ce159afc9e9ffb4d7ca8752eb6847588e42c'</span>
PI_PLUGIN_DIR = '/usr/local/lib/node_modules/@billjr99/pi-openai-compat'
OPENWEBUI_ENV_KEY = 'OPENWEBUI_API_KEY'


def openwebui_base(url):
    """API base for an Open WebUI origin, /api base, or full chat-completions URL."""
    base = url.rstrip('/')
    if base.endswith('/chat/completions'):
        base = base[:-len('/chat/completions')]
    elif not base.endswith(('/api', '/v1')):
        base += '/api'
    from urllib.parse import urlsplit
    u = urlsplit(base)
    if u.scheme not in ('http', 'https') or not u.hostname or u.username:
        raise ValueError('Open WebUI URL must be an HTTP(S) endpoint without embedded credentials')
    return base


def load_json_object(path):
    """Parsed JSON object (empty if the file is absent), or None if it cannot be safely merged."""
    text = read_text_nofollow(path)
    try:
        doc = json.loads(text) if text and text.strip() else {}
    except ValueError as e:
        error('config merge skipped (fix or remove ' + str(path) + ')', e)
        return None
    if not isinstance(doc, dict):
        error('config merge skipped (' + str(path) + ')', ValueError('top level is not an object'))
        return None
    return doc


def dict_of(value):
    return value if isinstance(value, dict) else {}


def refresh_pi_config(home, uid):
    """Install the pi-openai-compat extension and register Open WebUI as its default provider."""
    agent_dir = home / '.pi/agent'
    private_dir(home / '.pi', uid)
    private_dir(agent_dir, uid)
    settings = load_json_object(agent_dir / 'settings.json')
    if settings is not None:
        packages = settings.get('packages') if isinstance(settings.get('packages'), list) else []
        if PI_PLUGIN_DIR not in packages:
            packages.append(PI_PLUGIN_DIR)
        settings['packages'] = packages
        if CFG['openwebui_url'] and settings.get('defaultProvider') in (None, '', 'compat-openwebui'):
            settings['defaultProvider'] = 'compat-openwebui'
            settings['defaultModel'] = CFG['openwebui_model']
        write_owned(agent_dir / 'settings.json', json.dumps(settings, indent=2) + '\n', uid)
    if not CFG['openwebui_url']:
        return
    private_dir(home / '.config', uid)
    private_dir(home / '.config/pi-openai-compat', uid)
    path = home / '.config/pi-openai-compat/config.json'
    doc = load_json_object(path)
    if doc is None:
        return
    providers = dict_of(doc.get('providers'))
    mine = dict_of(providers.get('openwebui'))
    cached = [m for m in mine.get('cachedModels', []) if isinstance(m, dict) and m.get('id')]
    if CFG['openwebui_model'] not in [m['id'] for m in cached]:
        cached.insert(0, {'id': CFG['openwebui_model']})
    providers['openwebui'] = {**mine, 'displayName': 'Open WebUI', 'baseUrl': openwebui_base(CFG['openwebui_url']),
                              'apiKey': CFG['openwebui_key'] or None, 'cachedModels': cached}
    doc['providers'] = providers
    doc.setdefault('previousModel', None)
    write_owned(path, json.dumps(doc, indent=2) + '\n', uid)


def refresh_qwen_config(home, uid):
    """Register Open WebUI as an OpenAI-compatible provider in Qwen Code and make it the default."""
    if not CFG['openwebui_url']:
        return
    path = home / '.qwen/settings.json'
    doc = load_json_object(path)
    if doc is None:
        return
    base, model = openwebui_base(CFG['openwebui_url']), CFG['openwebui_model']
    env = dict_of(doc.get('env'))
    env[OPENWEBUI_ENV_KEY] = CFG['openwebui_key']
    doc['env'] = env
    providers = dict_of(doc.get('modelProviders'))
    entries = [e for e in providers.get('openai', []) if isinstance(e, dict)]
    ours = [e for e in entries if e.get('envKey') == OPENWEBUI_ENV_KEY]
    for entry in ours:
        entry['baseUrl'] = base
    if model not in [e.get('id') for e in ours]:
        entries.insert(0, {'id': model, 'name': model + ' (Open WebUI)', 'envKey': OPENWEBUI_ENV_KEY, 'baseUrl': base})
    providers['openai'] = entries
    doc['modelProviders'] = providers
    auth = dict_of(dict_of(doc.get('security')).get('auth'))
    chosen = dict_of(doc.get('model')).get('name')
    ours_ids = {e.get('id') for e in entries if e.get('envKey') == OPENWEBUI_ENV_KEY}
    if not auth.get('selectedType') or (auth.get('selectedType') == 'openai' and chosen in (None, '', *ours_ids)):
        doc['security'] = {**dict_of(doc.get('security')), 'auth': {**auth, 'selectedType': 'openai'}}
        doc['model'] = {**dict_of(doc.get('model')), 'name': model}
    write_owned(path, json.dumps(doc, indent=2) + '\n', uid)


def fetch_openwebui_models(url, key):
    """Model IDs reported by GET &lt;base&gt;/models (used by run.sh's default-model picker)."""
    import urllib.request
    req = urllib.request.Request(openwebui_base(url) + '/models',
                                 headers={'Authorization': 'Bearer ' + key, 'User-Agent': 'herdr-devbox'})
    with urllib.request.urlopen(req, timeout=15) as response:
        payload = json.loads(response.read(8 * 1024 * 1024))
    items = payload.get('data', payload) if isinstance(payload, dict) else payload
    return sorted({m['id'] for m in items if isinstance(m, dict) and m.get('id')})


def refresh_opencode_config(path):
    """Merge devbox-owned settings into OpenCode's config without clobbering user additions.

    Owned by the devbox: the permission policy, the Open WebUI provider's endpoint and key, and
    the default model (kept only while it is unset or already an openwebui/ model). Providers,
    models, and every other key you add are preserved; so is anything /connect or /models saves
    elsewhere (auth.json and state live outside this file)."""
    uid = AGENTS['opencode']
    text = read_text_nofollow(path)
    try:
        doc = json.loads(text) if text and text.strip() else {}
        if not isinstance(doc, dict):
            raise ValueError('top level is not an object')
    except ValueError as e:
        error('opencode config merge skipped (fix or remove ' + str(path) + ')', e)
        return
    doc['$schema'] = 'https://opencode.ai/config.json'
    plugins = doc.get('plugin') if isinstance(doc.get('plugin'), list) else []
    plugins = [x for x in plugins if not str(x).startswith('github:BillJr99/opencode-auto-models')]
    plugins.append(OPENCODE_PLUGIN)  # Replaces an older pin of the same plugin.
    doc['plugin'] = plugins
    doc['permission'] = {'*': 'ask', 'bash': {'*': 'ask', **{'hostctl %s*' % sub: 'allow' for sub in HOSTCTL_FREE}}}
    if doc.get('enabled_providers') == ['openwebui']:
        del doc['enabled_providers']  # Legacy devbox allowlist that hid every other provider.
    if CFG['openwebui_url']:
        base = openwebui_base(CFG['openwebui_url'])
        providers = doc.get('provider') if isinstance(doc.get('provider'), dict) else {}
        mine = providers.get('openwebui') if isinstance(providers.get('openwebui'), dict) else {}
        options = mine.get('options') if isinstance(mine.get('options'), dict) else {}
        models = mine.get('models') if isinstance(mine.get('models'), dict) else {}
        models.setdefault(CFG['openwebui_model'], {'name': CFG['openwebui_model']})
        providers['openwebui'] = {**mine, 'npm': '@ai-sdk/openai-compatible', 'name': 'Open WebUI',
                                  'options': {**options, 'baseURL': base, 'apiKey': CFG['openwebui_key']},
                                  'models': models}
        doc['provider'] = providers
        if not doc.get('model') or str(doc['model']).startswith('openwebui/'):
            doc['model'] = 'openwebui/' + CFG['openwebui_model']
    write_owned(path, json.dumps(doc, indent=2) + '\n', uid)


def clean(text, limit=200):
    """Printable, single-line, bounded rendition of untrusted text for notifications."""
    text = re.sub(r'[\x00-\x1f\x7f-\x9f\u2028\u2029]', '?', str(text))
    return text if len(text) &lt;= limit else text[:limit] + '...'


SECRET_SOURCES = {}


def persist_secret(path, explicit_env, regen_env, size):
    """Keep a generated password in the root-only state volume across runs and rebuilds.

    Precedence: an explicit value in explicit_env replaces the saved one; regen_env=1 makes a new
    random one; otherwise the saved value is reused; otherwise one is generated."""
    explicit = os.environ.get(explicit_env, '')
    saved = (read_text_nofollow(path) or '').strip()
    if explicit:
        if len(explicit) &lt; 12 or re.search(r'[\s\x00-\x1f\x7f]', explicit):
            raise ValueError(f'{explicit_env} must be at least 12 characters with no whitespace')
        value, source = explicit, 'configured (replaced any saved password)'
    elif saved and os.environ.get(regen_env) != '1':
        value, source = saved, 'saved from a previous run'
    else:
        value, source = secrets.token_urlsafe(size), 'newly generated'
    if value != saved:
        fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
        with os.fdopen(fd, 'w') as f:
            f.write(value)
    SECRET_SOURCES[path.name] = source


def totp_code(secret, counter):
    """RFC 6238 six-digit code (HMAC-SHA1, 30-second step) for a base32 secret."""
    digest = hmac.new(base64.b32decode(secret, casefold=True), struct.pack('&gt;Q', counter), 'sha1').digest()
    offset = digest[-1] &amp; 15
    return '%06d' % ((struct.unpack('&gt;I', digest[offset:offset + 4])[0] &amp; 0x7fffffff) % 1000000)


def private_dir(path, uid=0):
    path.mkdir(parents=True, exist_ok=True)
    if path.is_symlink() or not path.is_dir():
        raise ValueError(f'Unsafe state directory: {path}')
    os.chown(path, uid, uid)
    path.chmod(0o700)


def write_new(path, content, uid=0, mode=0o600):
    if path.exists() or path.is_symlink():
        return
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
    with os.fdopen(fd, 'w') as f:
        f.write(content)
        os.fchown(f.fileno(), uid, uid)


def drop_privileges(name):
    """Drop groups, UID, capabilities through UID transition, and future escalation."""
    uid = AGENTS[name]
    if os.geteuid() != 0:
        raise PermissionError('The trusted launcher must start as root')
    for fd in (0, 1, 2):
        if os.isatty(fd):
            os.fchown(fd, uid, uid)
            os.fchmod(fd, 0o600)
    os.setgroups([])
    os.setgid(uid)
    os.setuid(uid)
    libc = ctypes.CDLL(None, use_errno=True)
    if libc.prctl(38, 1, 0, 0, 0) != 0:  # PR_SET_NO_NEW_PRIVS
        raise OSError(ctypes.get_errno(), 'PR_SET_NO_NEW_PRIVS')
    if libc.prctl(4, 0, 0, 0, 0) != 0:  # PR_SET_DUMPABLE
        raise OSError(ctypes.get_errno(), 'PR_SET_DUMPABLE')
    status = pathlib.Path('/proc/self/status').read_text()
    for field in ('CapEff', 'CapPrm', 'CapAmb'):
        value = re.search(r'^' + field + r':\s*([0-9a-f]+)', status, re.M)
        if value and int(value.group(1), 16):
            raise PermissionError('Agent retained Linux capabilities: ' + field)
    # Only descriptors attached to this agent's terminal may survive exec.
    os.closerange(3, 1048576)
    os.umask(0o077)


def agent_env(name):
    home = STATE / 'agents' / name
    env = {
        'HOME': str(home), 'USER': name, 'LOGNAME': name,
        'PATH': '/usr/local/bin:/usr/bin:/bin', 'SHELL': '/bin/bash',
        'TERM': os.environ.get('TERM', 'xterm-256color'), 'COLORTERM': 'truecolor',
        'LANG': 'en_US.UTF-8', 'LC_ALL': 'en_US.UTF-8', 'TZ': 'America/New_York',
        'BROWSER': '/usr/local/bin/print-browser-url', 'DEVBOX_AGENT': name,
        'DEVBOX_RUN': str(RUN), 'DEVBOX_STATE': str(STATE),
        'XDG_CONFIG_HOME': str(home / '.config'),
        'XDG_CACHE_HOME': str(home / '.cache'),
        'XDG_DATA_HOME': str(home / '.local/share'),
        'HERDR_AGENT': 'antigravity-cli' if name == 'agy' else name,
    }
    # These IDs convey context only. The protected HerdR socket is not inherited.
    for key in ('HERDR_PANE_ID', 'HERDR_WORKSPACE_ID', 'HERDR_TAB_ID', 'HERDR_ENV'):
        if key in os.environ:
            env[key] = os.environ[key]
    if name == 'opencode':
        env['OPENCODE_SERVER_PASSWORD'] = (STATE / 'secrets/opencode-password').read_text().strip()
    return env


def as_agent(name, command):
    env = agent_env(name)
    work = STATE / 'agents' / name / 'workspace'
    os.chdir(work)
    drop_privileges(name)
    os.execvpe(command[0], command, env)


def pane():
    name = os.environ.get('DEVBOX_AGENT', 'claude')
    if name not in AGENTS:
        raise ValueError('Invalid pane agent')
    env = agent_env(name)
    os.chdir(STATE / 'agents' / name / 'workspace')
    drop_privileges(name)
    os.execve('/bin/bash', ['bash', '--rcfile', str(HERE / 'agent.bashrc'), '-i'], env)


def native_start(name):
    commands = {
        'claude': ['claude', '--remote-control'],
        'codex': ['codex'],
        'agy': ['agy', '--remote-control'],
        'grok': ['grok'],
        'opencode': ['opencode', 'attach', 'http://127.0.0.1:4096'],
        'pi': ['pi'],
        'qwen': ['qwen'],
    }
    # Runtime JSON makes command overrides explicit and auditable by the operator.
    cfg = json.loads((STATE / 'public.json').read_text())
    command = cfg['launch_commands'].get(name, commands[name])
    result = subprocess.run(command, check=False)
    print(f'[{name}] Agent exited ({result.returncode}). Use agent-start to reopen it.')
    return result.returncode


def canonical(drive, path):
    if drive not in ('c',):
        raise ValueError('Drive must be c')
    if not isinstance(path, str) or len(path) &gt; 4096:
        raise ValueError('Invalid path')
    if '\\' in path or ':' in path or '\x00' in path or path.startswith('/'):
        raise ValueError('Use a relative POSIX path without colon or backslash')
    parts = path.split('/') if path not in ('', '.') else []
    if any(p in ('', '.', '..') or p.endswith((' ', '.')) for p in parts):
        raise ValueError('Unsafe path component')
    if any(re.fullmatch(r'(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])',
                        p.split('.')[0].upper()) for p in parts):
        raise ValueError('Windows device names are not supported')
    if any(ord(c) &lt; 32 for c in path):
        raise ValueError('Control character in path')
    return parts


def open_dir(drive, parts):
    """Walk beneath an approved drive with no symlink traversal or mount crossings."""
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
    fd = os.open(DRIVES / drive, flags)
    device = os.fstat(fd).st_dev
    try:
        for part in parts:
            nextfd = os.open(part, flags, dir_fd=fd)
            os.close(fd)
            fd = nextfd
            if os.fstat(fd).st_dev != device:
                raise PermissionError('Cross-filesystem traversal refused')
        return fd
    except Exception:
        os.close(fd)
        raise


def read_file(drive, path):
    parts = canonical(drive, path)
    if not parts:
        raise ValueError('A file path is required')
    parent = open_dir(drive, parts[:-1])
    fd = None
    try:
        fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK |
                     os.O_CLOEXEC, dir_fd=parent)
        before = os.fstat(fd)
        if not stat.S_ISREG(before.st_mode) or before.st_dev != os.fstat(parent).st_dev:
            raise PermissionError('Only regular files on the selected drive are supported')
        limit = cap('max_file_bytes')
        if before.st_size &gt; limit:
            raise ValueError(f'File exceeds the configured {limit}-byte limit')
        chunks = []
        remaining = limit + 1
        while remaining:
            b = os.read(fd, min(65536, remaining))
            if not b:
                break
            chunks.append(b)
            remaining -= len(b)
        data = b''.join(chunks)
        after = os.fstat(fd)
        stamp = lambda s: (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns)
        if len(data) &gt; limit or stamp(before) != stamp(after):
            raise ValueError('File changed during read or exceeded the size limit')
        return data, {'sha256': hashlib.sha256(data).hexdigest(),
                      'stamp': list(stamp(after)), 'mode': stat.S_IMODE(after.st_mode),
                      'links': after.st_nlink}
    finally:
        if fd is not None:
            os.close(fd)
        os.close(parent)


def snapshot(drive, path):
    try:
        return read_file(drive, path)
    except FileNotFoundError:
        # The parent must already exist; this does not authorize mkdir.
        parts = canonical(drive, path)
        parent = open_dir(drive, parts[:-1])
        os.close(parent)
        return b'', {'sha256': None, 'stamp': None, 'mode': 0o644, 'links': 0}


def approved_write(request):
    drive, path = request['drive'], request['path']
    expected = request.get('preview_version')
    old, version = snapshot(drive, path)
    if expected is None:
        # One approval covers preview and write: pin the version read right now.
        expected = version
    elif version != expected:
        raise ValueError('File changed after preview; submit a new request')
    if version['links'] &gt; 1:
        raise ValueError('Replacing multiply linked files is refused')
    parts = canonical(drive, path)
    parent = open_dir(drive, parts[:-1])
    temp = '.devbox-' + secrets.token_hex(16)
    data = base64.b64decode(request['content_b64'], validate=True)
    try:
        if version['sha256'] is not None:
            backup = STATE / 'backups' / request['id']
            write_new(backup, base64.b64encode(old).decode())
        fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
                     version['mode'], dir_fd=parent)
        with os.fdopen(fd, 'wb') as f:
            f.write(data)
            f.flush()
            os.fsync(f.fileno())
        # Recheck immediately before replacing the destination. Host-side writers are
        <span class="c"># not locked by this process; ordinary filesystems cannot guarantee CAS here.</span>
        _, current = snapshot(drive, path)
        if current != expected:
            raise ValueError('Concurrent edit detected; replacement refused')
        os.replace(temp, parts[-1], src_dir_fd=parent, dst_dir_fd=parent)
        durability_warning = None
        try:
            os.fsync(parent)
        except OSError as e:
            error('write directory fsync', e)
            durability_warning = str(e)
        actual, _ = read_file(drive, path)
        if actual != data:
            raise IOError('Write verification failed; inspect host file and backup')
        return {'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data),
                'backup_id': request['id'] if version['sha256'] else None,
                'durability_warning': durability_warning}
    finally:
        try:
            os.unlink(temp, dir_fd=parent)
        except FileNotFoundError:
            pass
        os.close(parent)


def execute(request):
    op, drive, path = request['op'], request.get('drive'), request.get('path')
    if op == 'read':
        data, version = read_file(drive, path)
        return {'content_b64': base64.b64encode(data).decode(), **version}
    if op == 'list':
        fd = open_dir(drive, canonical(drive, path))
        try:
            result = []
            with os.scandir(fd) as entries:
                for item in entries:
                    if len(result) &gt;= cap('max_entries'):
                        return {'entries': result, 'truncated': True}
                    result.append({'name': item.name,
                                   'directory': item.is_dir(follow_symlinks=False),
                                   'symlink': item.is_symlink()})
            return {'entries': result, 'truncated': False}
        finally:
            os.close(fd)
    if op == 'search':
        # Search is one explicitly bounded operation within the approved subtree.
        needle = request['query']
        queue = [path]
        results, examined, size = [], 0, 0
        while queue and examined &lt; cap('search_max_files'):
            folder = queue.pop()
            fd = open_dir(drive, canonical(drive, folder))
            try:
                with os.scandir(fd) as entries:
                    for entry in entries:
                        examined += 1
                        if examined &gt; cap('search_max_files'):
                            break
                        sub = '/'.join(p for p in (folder if folder != '.' else '', entry.name) if p)
                        if entry.is_symlink():
                            continue
                        if entry.is_dir(follow_symlinks=False):
                            canonical(drive, sub)
                            queue.append(sub)
                        elif entry.is_file(follow_symlinks=False):
                            data, _ = read_file(drive, sub)
                            size += len(data)
                            if size &gt; cap('search_max_bytes'):
                                return {'matches': results, 'truncated': True}
                            for number, line in enumerate(data.decode('utf-8', 'replace').splitlines(), 1):
                                if needle in line:
                                    results.append({'path': sub, 'line': number, 'text': line[:1000]})
                                    if len(results) &gt;= cap('max_entries'):
                                        return {'matches': results, 'truncated': True}
            finally:
                os.close(fd)
        return {'matches': results, 'truncated': bool(queue) or examined &gt;= cap('search_max_files')}
    if op == 'write':
        return approved_write(request)
    if op == 'team-read':
        return {'text': herdr('agent', 'read', PANES[request['target']], '--lines', '100', raw=True)}
    raise ValueError('Unknown operation')


PANES = {}


def herdr(*args, raw=False):
    completed = subprocess.run(herdr_command(*args), check=True, capture_output=True,
                               text=True, timeout=20, env=controller_env())
    if raw:
        return completed.stdout
    parsed = json.loads(completed.stdout)
    if parsed.get('ok') is False or parsed.get('error'):
        raise RuntimeError(parsed)
    return parsed.get('result', parsed)


def herdr_command(*args):
    session = (RUN / 'private/session').read_text().strip()
    return ['herdr', '--session', session, *args]


class Broker:
    def __init__(self):
        self.requests = {}
        self.sessions = {}
        self.lock = asyncio.Lock()
        self.db = sqlite3.connect(STATE / 'audit.sqlite3')
        self.db.execute('CREATE TABLE IF NOT EXISTS audit (time REAL, request_id TEXT, agent TEXT, operation TEXT, drive TEXT, path TEXT, decision TEXT)')
        self.password = (STATE / 'admin-password').read_text().strip()
        # Approval-code secret, kept in the root-only state volume so it survives restarts and
        <span class="c"># rebuilds. Precedence: an explicit secret (DEVBOX_TOTP_SECRET / approval_totp_secret)</span>
        <span class="c"># replaces the saved one; DEVBOX_TOTP_REGENERATE=1 makes a new one; otherwise the saved</span>
        <span class="c"># secret is reused; otherwise a new one is generated.</span>
        saved_path = STATE / 'secrets/approval-totp'
        configured = (CFG.get('approval_totp_secret') or '').replace(' ', '').upper()
        saved = ''
        try:
            saved = (read_text_nofollow(saved_path) or '').strip()
            if saved:
                totp_code(saved, 0)
        except Exception as e:
            error('saved TOTP secret unusable; generating a new one', e)
            saved = ''
        if configured:
            totp_code(configured, 0)  # Fails fast on an invalid base32 secret.
            self.totp_source = 'configured (replaced any saved secret)'
        elif saved and os.environ.get('DEVBOX_TOTP_REGENERATE') != '1':
            configured, self.totp_source = saved, 'saved from a previous run'
        else:
            configured = base64.b32encode(secrets.token_bytes(20)).decode()
            self.totp_source = 'newly generated'
        if configured != saved:
            fd = os.open(saved_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
            with os.fdopen(fd, 'w') as f:
                f.write(configured)
        self.totp_secret = configured
        self.totp_last = 0
        self.totp_failures = 0
        self.totp_locked_until = 0
        self.notify_queue = []
        self.notify_task = None
        self.notify_last = 0.0

    def notify(self, line):
        """Queue a one-line note for Claude's pane. Batched and rate limited; never raises."""
        try:
            if 'claude' not in PANES:
                return
            self.notify_queue.append(line)
            if self.notify_task is None or self.notify_task.done():
                self.notify_task = asyncio.get_running_loop().create_task(self.flush_notifications())
        except Exception as e:
            error('notify', e)

    async def flush_notifications(self):
        while self.notify_queue:
            wait = self.notify_last + CFG['notify_interval_seconds'] - time.monotonic()
            if wait &gt; 0:
                await asyncio.sleep(wait)
            batch, self.notify_queue = self.notify_queue[:6], self.notify_queue[6:]
            more = ('\n...and %d more events; run hostctl pending.' % len(self.notify_queue)
                    if self.notify_queue else '')
            self.notify_queue = []  # Anything beyond one batch is summarized by hostctl pending.
            message = ('[devbox] Host approval activity. Show Bill any new request, ask him for the '
                       'current six-digit authenticator code, then run hostctl approve ID CODE, '
                       'hostctl preview ID CODE, or hostctl deny ID. Do not ask about closed requests.\n' +
                       '\n'.join(batch) + more)
            self.notify_last = time.monotonic()
            try:
                await asyncio.to_thread(herdr, 'agent', 'prompt', PANES['claude'], message)
            except Exception as e:
                error('claude notification', e)

    async def drain_notifications(self):
        while self.notify_task is not None and not self.notify_task.done():
            await asyncio.wait([self.notify_task])

    def request_line(self, r):
        where = ('target ' + clean(r['target'], 40) if 'target' in r else
                 clean(r.get('drive', '')) + ':' + json.dumps(clean(r.get('path', ''))))
        if 'query' in r:
            where += ' query=' + json.dumps(clean(r['query'], 80))
        if 'payload_sha256' in r:
            where += ' sha256=' + r['payload_sha256']
        return 'NEW id=%s agent=%s op=%s %s' % (r['id'], r['agent'], r['op'], where)

    def totp_uri(self):
        return ('otpauth://totp/HerdR%20devbox:approvals?secret=' + self.totp_secret +
                '&amp;issuer=HerdR%20devbox')

    def check_totp(self, code):
        """Single-use authenticator code; five failures lock approvals for five minutes."""
        now = time.time()
        if now &lt; self.totp_locked_until:
            raise web.HTTPTooManyRequests(text='Approval codes are locked after repeated failures')
        counter = int(now // 30)
        matched = None
        for c in (counter - 1, counter, counter + 1):
            if (isinstance(code, str) and re.fullmatch(r'\d{6}', code) and c &gt; self.totp_last
                    and hmac.compare_digest(totp_code(self.totp_secret, c), code)):
                matched = c
        if matched is None:
            self.totp_failures += 1
            if self.totp_failures &gt;= 5:
                self.totp_failures = 0
                self.totp_locked_until = now + 300
            raise web.HTTPForbidden(text='Invalid, expired or reused approval code')
        self.totp_last = matched
        self.totp_failures = 0

    def audit(self, r, decision):
        self.db.execute('INSERT INTO audit VALUES (?,?,?,?,?,?,?)',
                        (time.time(), r['id'], r['agent'], r['op'], r.get('drive'), r.get('path'), decision))
        self.db.commit()

    def peer(self, request):
        sock = request.transport.get_extra_info('socket')
        if not sock or sock.family != socket.AF_UNIX:
            raise web.HTTPForbidden(text='Local agent socket required')
        _, uid, _ = struct.unpack('3i', sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
        if uid not in UIDS:
            raise web.HTTPForbidden(text='Unknown agent UID')
        return UIDS[uid]

    def expire(self, r):
        if r['status'] == 'pending' and time.time() &gt; r['expires']:
            r['status'] = 'expired'
            self.audit(r, 'expired')
            self.notify('CLOSED id=%s expired' % r['id'])

    async def rpc(self, request):
        agent = self.peer(request)
        data = await request.json()
        action = data.get('action')
        if action == 'get':
            r = self.requests.get(data.get('id'))
            if not r or r['agent'] != agent:
                raise web.HTTPNotFound()
            self.expire(r)
            return web.json_response({k: r[k] for k in ('id', 'status', 'result') if k in r})
        if action in ('pending', 'rc-decide'):
            if agent != 'claude':
                raise web.HTTPForbidden(text='Only the lead may relay approvals')
            if action == 'pending':
                out = []
                for r in self.requests.values():
                    self.expire(r)
                    if r['status'] == 'pending':
                        out.append({k: r[k] for k in ('id', 'agent', 'op', 'drive', 'path', 'query',
                                                      'target', 'payload_sha256', 'diff') if k in r}
                                   | {'preview_authorized': 'preview_version' in r})
                return web.json_response({'pending': out})
            choice = data.get('decision')
            if choice not in ('preview', 'approve', 'deny'):
                raise ValueError('Decision must be preview, approve or deny')
            if choice != 'deny':
                self.check_totp(data.get('code'))
            async with self.lock:
                r = self.requests.get(data.get('id'))
                if not r:
                    raise web.HTTPNotFound()
                self.expire(r)
                if r['status'] != 'pending':
                    raise web.HTTPConflict(text='Request is no longer pending')
                await self.apply_decision(r, choice, 'claude-rc')
                return web.json_response({k: r[k] for k in ('id', 'status', 'result', 'error', 'diff') if k in r})
        if action == 'team-status' or action == 'team-prompt':
            if agent != 'claude':
                raise web.HTTPForbidden(text='Only the lead may coordinate')
            if action == 'team-status':
                listing = herdr('agent', 'list')
                # Only names and state are exposed without a content-transfer approval.
                text = json.dumps(listing)
                return web.json_response({'panes': PANES, 'states':
                    re.findall(r'"(?:state|status)"\s*:\s*"(idle|working|blocked|done|unknown)"', text)})
            target = data.get('target')
            prompt = data.get('prompt', '')
            if target not in PANES or target == 'claude' or not isinstance(prompt, str) or len(prompt) &gt; 12000:
                raise ValueError('Invalid target or prompt')
            # The official agent-prompt interface refuses known blocked approval UIs.
            result = herdr('agent', 'prompt', PANES[target], prompt)
            return web.json_response({'result': result})
        if action != 'create':
            raise ValueError('Unknown action')
        if sum(r['status'] == 'pending' and r['agent'] == agent for r in self.requests.values()) &gt;= 8:
            raise web.HTTPTooManyRequests(text='At most eight pending requests per agent')
        op = data.get('op')
        r = {'id': secrets.token_hex(16), 'agent': agent, 'op': op, 'status': 'pending',
             'expires': time.time() + CFG['approval_timeout_seconds']}
        if op == 'team-read':
            if agent != 'claude' or data.get('target') not in PANES or data['target'] == 'claude':
                raise ValueError('Invalid team-read request')
            r['target'] = data['target']
        else:
            if op not in ('list', 'read', 'write', 'search'):
                raise ValueError('Unsupported host operation')
            canonical(data.get('drive'), data.get('path'))  # No host I/O before approval.
            r.update(drive=data['drive'], path=data['path'])
            if op == 'search':
                if not isinstance(data.get('query'), str) or not 1 &lt;= len(data['query']) &lt;= 200:
                    raise ValueError('Supply a literal search string, 1-200 characters')
                r['query'] = data['query']
            if op == 'write':
                content = base64.b64decode(data['content_b64'], validate=True)
                if len(content) &gt; cap('max_file_bytes'):
                    raise ValueError('Write exceeds configured byte limit')
                r['content_b64'] = base64.b64encode(content).decode()
                r['payload_sha256'] = hashlib.sha256(content).hexdigest()
        self.requests[r['id']] = r
        self.audit(r, 'requested')
        self.notify(self.request_line(r))
        return web.json_response({'id': r['id'], 'status': r['status']})

    def session(self, request):
        sid = request.cookies.get('devbox_session', '')
        found = self.sessions.get(sid)
        if not found or found['expires'] &lt; time.time():
            raise web.HTTPFound('/login')
        return found

    def page(self, body):
        return web.Response(text='&lt;!doctype html&gt;&lt;html&gt;&lt;meta charset="utf-8"&gt;'
            '&lt;meta name="viewport" content="width=device-width,initial-scale=1"&gt;'
            '&lt;title&gt;HerdR devbox&lt;/title&gt;&lt;style&gt;body{font:16px system-ui;max-width:1000px;'
            'margin:2rem auto;padding:0 1rem;background:#f5f5f1;color:#16221e}'
            'article{background:white;border:1px solid <span class="c">#ccd4cc;padding:1rem;margin:1rem 0}'</span>
            'pre{white-space:pre-wrap;overflow-wrap:anywhere}button{padding:.7rem;margin:.3rem}'
            'input{padding:.7rem}a{color:#075a45}&lt;/style&gt;' + body + '&lt;/html&gt;',
            content_type='text/html', headers={'Cache-Control': 'no-store',
            'X-Frame-Options': 'DENY', 'Referrer-Policy': 'no-referrer',
            'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'"})

    async def login(self, request):
        if request.method == 'POST':
            form = await request.post()
            if not secrets.compare_digest(form.get('password', ''), self.password):
                await asyncio.sleep(1)
                raise web.HTTPForbidden(text='Incorrect password')
            sid = secrets.token_urlsafe(32)
            self.sessions[sid] = {'csrf': secrets.token_urlsafe(32), 'expires': time.time() + 43200}
            response = web.HTTPFound('/')
            response.set_cookie('devbox_session', sid, httponly=True, samesite='Strict', max_age=43200)
            return response
        return self.page('&lt;h1&gt;HerdR devbox&lt;/h1&gt;&lt;p&gt;Use the password printed by docker run.&lt;/p&gt;'
            '&lt;form method="post"&gt;&lt;input type="password" name="password" required '
            'autocomplete="current-password"&gt;&lt;button&gt;Sign in&lt;/button&gt;&lt;/form&gt;')

    async def dashboard(self, request):
        session = self.session(request)
        esc = html.escape
        out = ['&lt;h1&gt;HerdR devbox&lt;/h1&gt;&lt;p&gt;&lt;a href="/terminal/"&gt;Open live HerdR terminal&lt;/a&gt; · '
               '&lt;a href="/"&gt;Refresh requests&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Approvals apply once, to the named agent '
               'and exact operation. Reads may enter that agent’s model context. '
               'Searches inspect the displayed subtree within the limits below (0 means unlimited).&lt;/p&gt;',
               '&lt;pre&gt;' + esc(json.dumps({k: CFG[k] for k in ('max_file_bytes', 'max_entries',
               'search_max_files', 'search_max_bytes', 'approval_timeout_seconds')}, indent=2)) + '&lt;/pre&gt;']
        for r in list(self.requests.values())[-60:][::-1]:
            self.expire(r)
            out.append('&lt;article&gt;&lt;h2&gt;' + esc(r['agent'] + ': ' + r['op']) + '&lt;/h2&gt;&lt;pre&gt;' +
                       esc(json.dumps({k: r[k] for k in ('id', 'drive', 'path', 'query', 'target',
                           'status', 'expires', 'payload_sha256') if k in r}, indent=2)) + '&lt;/pre&gt;')
            if r['op'] == 'write':
                if 'diff' in r:
                    out.append('&lt;p&gt;Current content was inspected for this preview. '
                               'Final approval replaces only the previewed version.&lt;/p&gt;&lt;pre&gt;' + esc(r['diff']) + '&lt;/pre&gt;')
                else:
                    content = base64.b64decode(r['content_b64'])
                    out.append('&lt;p&gt;Proposed replacement bytes, UTF-8 preview:&lt;/p&gt;&lt;pre&gt;' +
                               esc(content.decode('utf-8', 'replace')) + '&lt;/pre&gt;')
            if r['status'] == 'pending':
                out.append('&lt;form method="post" action="/decide"&gt;'
                    '&lt;input type="hidden" name="csrf" value="' + session['csrf'] + '"&gt;'
                    '&lt;input type="hidden" name="id" value="' + r['id'] + '"&gt;')
                if r['op'] == 'write' and 'preview_version' not in r:
                    out.append('&lt;button name="decision" value="preview"&gt;Show diff against current file first (optional)&lt;/button&gt;')
                    out.append('&lt;button name="decision" value="approve"&gt;Approve write (reads current file for backup, then replaces it)&lt;/button&gt;')
                else:
                    out.append('&lt;button name="decision" value="approve"&gt;Approve this operation once&lt;/button&gt;')
                out.append('&lt;button name="decision" value="deny"&gt;Deny&lt;/button&gt;&lt;/form&gt;')
            if r.get('error'):
                out.append('&lt;pre&gt;' + esc(r['error']) + '&lt;/pre&gt;')
            out.append('&lt;/article&gt;')
        return self.page(''.join(out))

    async def apply_decision(self, r, choice, channel):
        """Apply one human decision; the caller holds the lock and checked r is pending."""
        try:
            if choice == 'deny':
                r['status'] = 'denied'
                self.audit(r, 'denied via ' + channel)
            elif choice == 'preview' and r['op'] == 'write':
                self.audit(r, 'human-authorized-preview via ' + channel)
                old, version = await asyncio.to_thread(snapshot, r['drive'], r['path'])
                new = base64.b64decode(r['content_b64'])
                diff = ''.join(difflib.unified_diff(old.decode('utf-8', 'replace').splitlines(True),
                    new.decode('utf-8', 'replace').splitlines(True), fromfile='current', tofile='proposed'))
                r['preview_version'] = version
                r['diff'] = diff or '(No text difference; inspect payload hash and byte count.)'
            elif choice == 'approve':
                self.audit(r, 'approved via ' + channel)
                r['status'] = 'executing'  # Consume before any filesystem operation.
                r['result'] = await asyncio.to_thread(execute, dict(r))
                r['status'] = 'completed'
                self.audit(r, 'completed')
            else:
                raise ValueError('Unknown decision')
        except Exception as e:
            error('approved operation', e)
            r['status'] = 'failed'
            r['error'] = str(e)
            r['result'] = {'error': str(e)}
            self.audit(r, 'failed')

    async def decide(self, request):
        session = self.session(request)
        form = await request.post()
        if not secrets.compare_digest(form.get('csrf', ''), session['csrf']):
            raise web.HTTPForbidden(text='Invalid CSRF token')
        async with self.lock:
            r = self.requests.get(form.get('id'))
            if not r:
                raise web.HTTPNotFound()
            self.expire(r)
            if r['status'] != 'pending':
                raise web.HTTPConflict(text='Request is no longer pending')
            await self.apply_decision(r, form.get('decision'), 'web')
            if r['status'] != 'pending':
                self.notify('CLOSED id=%s %s on the web dashboard' % (r['id'], r['status']))
        raise web.HTTPFound('/')

    async def terminal(self, request):
        self.session(request)
        if request.headers.get('Upgrade', '').lower() == 'websocket':
            # A same-site cookie alone does not prevent cross-site WebSocket use.
            origin = request.headers.get('Origin', '')
            if origin != f'{request.scheme}://{request.host}':
                raise web.HTTPForbidden(text='WebSocket origin mismatch')
        connector = UnixConnector(path=str(RUN / 'private/ttyd.sock'))
        async with ClientSession(connector=connector) as client:
            url = 'http://localhost' + str(request.rel_url)
            if request.headers.get('Upgrade', '').lower() != 'websocket':
                async with client.get(url, allow_redirects=False) as upstream:
                    headers = {k: v for k, v in upstream.headers.items()
                               if k.lower() in ('content-type', 'location', 'etag', 'cache-control')}
                    return web.Response(body=await upstream.read(), status=upstream.status, headers=headers)
            protocols = tuple(p.strip() for p in request.headers.get('Sec-WebSocket-Protocol', '').split(',') if p.strip())
            async with client.ws_connect(url, protocols=protocols, max_msg_size=16 * 1024 * 1024) as upstream:
                ws = web.WebSocketResponse(protocols=protocols, max_msg_size=16 * 1024 * 1024)
                await ws.prepare(request)

                async def relay(source, destination):
                    async for msg in source:
                        if msg.type == WSMsgType.BINARY:
                            await destination.send_bytes(msg.data)
                        elif msg.type == WSMsgType.TEXT:
                            await destination.send_str(msg.data)
                        else:
                            break
                    await destination.close()

                tasks = [asyncio.create_task(relay(ws, upstream)), asyncio.create_task(relay(upstream, ws))]
                try:
                    await asyncio.gather(*tasks)
                finally:
                    for task in tasks:
                        task.cancel()
                return ws


@web.middleware
async def errors(request, handler):
    try:
        return await handler(request)
    except web.HTTPException:
        raise
    except Exception as e:
        error('request', e)
        return web.json_response({'error': str(e)}, status=400)


async def run_broker(broker):
    local = web.Application(middlewares=[errors], client_max_size=client_limit())
    local.router.add_post('/rpc', broker.rpc)
    runner = web.AppRunner(local, access_log=None)
    await runner.setup()
    sockpath = RUN / 'agent.sock'
    if sockpath.exists():
        sockpath.unlink()
    await web.UnixSite(runner, str(sockpath)).start()
    sockpath.chmod(0o666)  # Peer UID, not pathname secrecy, authenticates agents.
    app = web.Application(middlewares=[errors], client_max_size=client_limit())
    app.router.add_route('*', '/login', broker.login)
    app.router.add_get('/', broker.dashboard)
    app.router.add_post('/decide', broker.decide)
    app.router.add_get('/terminal/{path:.*}', broker.terminal)
    ui = web.AppRunner(app, access_log=None)
    await ui.setup()
    await web.TCPSite(ui, '0.0.0.0', CFG['web_port']).start()
    return runner, ui


async def call_rpc(data):
    async with ClientSession(connector=UnixConnector(path=str(RUN / 'agent.sock'))) as client:
        async with client.post('http://localhost/rpc', json=data) as response:
            text = await response.text()
            if response.status != 200:
                raise RuntimeError(text)
            return json.loads(text)


async def client_request(args):
    if args.mode == 'team':
        if args.op == 'status':
            print(json.dumps(await call_rpc({'action': 'team-status'}), indent=2))
            return
        if args.op == 'prompt':
            print(json.dumps(await call_rpc({'action': 'team-prompt', 'target': args.target,
                                            'prompt': args.prompt}), indent=2))
            return
        data = {'action': 'create', 'op': 'team-read', 'target': args.target}
    elif args.op in ('pending', 'preview', 'approve', 'deny'):
        # Lead-only relay of the human's decision; approve/preview need a fresh authenticator code.
        if args.op == 'pending':
            payload = {'action': 'pending'}
        else:
            payload = {'action': 'rc-decide', 'id': args.id, 'decision': args.op,
                       'code': getattr(args, 'code', None)}
        print(json.dumps(await call_rpc(payload), indent=2))
        return
    else:
        data = {'action': 'create', 'op': args.op, 'drive': args.drive.lower(), 'path': args.path}
        if args.op == 'write':
            raw = pathlib.Path(args.file).read_bytes()
            data['content_b64'] = base64.b64encode(raw).decode()
        if args.op == 'search':
            data['query'] = args.query
    result = await call_rpc(data)
    print('Awaiting human approval in the devbox dashboard. Request: ' + result['id'], file=sys.stderr)
    while result['status'] in ('pending', 'executing'):
        await asyncio.sleep(1)
        result = await call_rpc({'action': 'get', 'id': result['id']})
    if result['status'] != 'completed':
        raise RuntimeError(json.dumps(result))
    value = result.get('result', {})
    if args.mode == 'host' and args.op == 'read':
        sys.stdout.buffer.write(base64.b64decode(value['content_b64']))
    else:
        print(json.dumps(value, indent=2))


def cli(mode, argv):
    parser = argparse.ArgumentParser(prog='hostctl' if mode == 'host' else 'teamctl')
    sub = parser.add_subparsers(dest='op', required=True)
    if mode == 'host':
        sub.add_parser('pending', help='Claude only: list pending requests')
        for op in ('preview', 'approve', 'deny'):
            p = sub.add_parser(op, help='Claude only: relay the human decision' +
                               ('' if op == 'deny' else ' with the human-typed authenticator code'))
            p.add_argument('id')
            if op != 'deny':
                p.add_argument('code', help='Six-digit code typed by the human; never reuse or guess')
        for op in ('list', 'read', 'search', 'write'):
            p = sub.add_parser(op)
            p.add_argument('drive', choices=('c',))
            p.add_argument('path')
            if op == 'search':
                p.add_argument('query')
            if op == 'write':
                p.add_argument('--file', required=True, help='Local file containing proposed replacement bytes')
    else:
        sub.add_parser('status')
        p = sub.add_parser('prompt')
        p.add_argument('target', choices=tuple(n for n in AGENTS if n != 'claude'))
        p.add_argument('prompt')
        p = sub.add_parser('read')
        p.add_argument('target', choices=tuple(n for n in AGENTS if n != 'claude'))
    args = parser.parse_args(argv)
    args.mode = mode
    asyncio.run(client_request(args))


def controller_env():
    return {'HOME': str(STATE / 'controller'), 'PATH': '/usr/local/bin:/usr/bin:/bin',
            'TERM': os.environ.get('TERM', 'xterm-256color'), 'LANG': 'en_US.UTF-8',
            'HERDR_CONFIG_PATH': str(STATE / 'controller/config.toml'),
            'XDG_RUNTIME_DIR': str(RUN / 'private'),
            'DEVBOX_STATE': str(STATE), 'DEVBOX_RUN': str(RUN),
            'DEVBOX_AGENT': 'claude'}


def initialize():
    private_dir(STATE)
    # Other users may reach their own private homes and public configuration only.
    STATE.chmod(0o711)
    private_dir(STATE / 'agents')
    (STATE / 'agents').chmod(0o711)
    for name, uid in AGENTS.items():
        home = STATE / 'agents' / name
        private_dir(home, uid)
        for tail in ('workspace', '.config', '.cache', '.local', '.local/share', '.claude', '.codex', '.grok', '.gemini', '.pi', '.qwen'):
            private_dir(home / tail, uid)
        rules = (
            '# Devbox operating rules\nYou are ' + name + '. Claude is the lead. '
            'Host drives are inaccessible directly. Use hostctl and wait for Bill’s approval.\n'
            'hostctl list c Users\nhostctl read d projects/example.txt\n'
            'hostctl search x project "literal text"\n'
            'hostctl write d projects/example.txt --file ./proposed.txt\n'
            'Every host operation requires its own approval. Never approve a peer’s request. '
            'Claude is notified automatically when a request arrives (a line starting [devbox]). '
            'Only Claude may relay the human\'s decision: run hostctl pending, show Bill the request, '
            'and ask him to type the current six-digit authenticator code; then run hostctl approve ID CODE '
            '(or preview/deny). Never guess, reuse, or invent a code, and never approve on your own initiative. '
            'Agent-private local files may be used without a host request. '
            'Do not share host-derived contents with peers without Bill’s permission.\n'
            'Claude may use teamctl status, teamctl prompt TARGET "task", '
            'and teamctl read TARGET. Reading peer terminal output requires human approval.\n'
            'The common authenticated browser terminal controls these exact live sessions.\n')
        for filename in ('AGENTS.md', 'CLAUDE.md', 'GEMINI.md', 'QWEN.md'):
            write_managed(home / 'workspace' / filename, rules, uid)
        write_new(home / '.claude/settings.json', json.dumps({'permissions': {'defaultMode': 'default'}}), uid)
        refresh_agent_permissions(name, home, uid)
    private_dir(STATE / 'controller')
    private_dir(STATE / 'backups')
    private_dir(STATE / 'secrets')
    if CFG['openwebui_url']:
        cache = STATE / 'secrets/openwebui.json'
        if cache.is_symlink():
            raise ValueError('Refusing symlink for cached Open WebUI settings')
        fd = os.open(cache, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
        with os.fdopen(fd, 'w') as f:
            json.dump({k: CFG[k] for k in ('openwebui_url', 'openwebui_model', 'openwebui_key')}, f)
    persist_secret(STATE / 'secrets/opencode-password', 'DEVBOX_OPENCODE_PASSWORD', 'DEVBOX_OPENCODE_REGENERATE', 32)
    persist_secret(STATE / 'admin-password', 'DEVBOX_ADMIN_PASSWORD', 'DEVBOX_ADMIN_REGENERATE', 28)
    public = {k: v for k, v in CFG.items() if k not in ('openwebui_key', 'approval_totp_secret')}
    # This generated file is a projection of runtime JSON, not mutable operator settings.
    (STATE / 'public.json').write_text(json.dumps(public, indent=2))
    (STATE / 'public.json').chmod(0o644)
    RUN.mkdir(parents=True, exist_ok=True)
    RUN.chmod(0o755)
    private_dir(RUN / 'private')
    if not DRIVES.is_dir() or DRIVES.is_symlink():
        raise ValueError('Missing protected drive mount parent')
    if DRIVES.stat().st_uid != 0 or stat.S_IMODE(DRIVES.stat().st_mode) != 0o700:
        raise PermissionError('Drive mount parent must be root-owned mode 0700')
    if CFG['require_mounts']:
        for name in ('c',):
            if not os.path.ismount(DRIVES / name):
                raise ValueError(f'{name}: is not a mounted drive; startup refused')
    config = ('onboarding = false\n[terminal]\ndefault_shell = "/usr/local/bin/devbox-pane"\n'
              'shell_mode = "non_login"\nnew_cwd = "/state"\n[update]\nversion_check = false\n'
              'manifest_check = false\n[session]\nresume_agents_on_restore = false\n'
              '[ui]\nconfirm_close = true\n[ui.sound]\nenabled = false\n')
    # Reset only generated controller configuration. No user home is mounted here.
    (STATE / 'controller/config.toml').write_text(config.replace('new_cwd = "/state"',
                                                       'new_cwd = ' + json.dumps(str(STATE))))
    home = STATE / 'agents/opencode'
    opath = home / '.config/opencode'
    private_dir(opath, AGENTS['opencode'])
    refresh_opencode_config(opath / 'opencode.json')
    refresh_pi_config(STATE / 'agents/pi', AGENTS['pi'])
    refresh_qwen_config(STATE / 'agents/qwen', AGENTS['qwen'])


def spawn_agent_service(name, command, logfile):
    f = open(logfile, 'ab', buffering=0)
    proc = subprocess.Popen([sys.executable, __file__, 'as-agent', name, *command],
                            stdout=f, stderr=f, env={**controller_env()}, start_new_session=True)
    f.close()
    CHILDREN.append(proc)
    return proc


async def workstation():
    global PANES
    initialize()
    # A fresh generated layout avoids restoring stale privileged controller shells.
    (RUN / 'private/session').write_text('devbox-' + secrets.token_hex(6))
    broker = Broker()
    await run_broker(broker)
    opencode = spawn_agent_service('opencode', ['opencode', 'web', '--hostname', '0.0.0.0',
                                               '--port', '4096'], STATE / 'controller/opencode.log')
    for _ in range(100):
        try:
            reader, writer = await asyncio.open_connection('127.0.0.1', 4096)
            writer.close()
            await writer.wait_closed()
            break
        except OSError:
            if opencode.poll() is not None:
                raise RuntimeError('OpenCode backend exited; inspect controller/opencode.log')
            await asyncio.sleep(.1)
    else:
        raise RuntimeError('OpenCode backend did not become ready')
    log = open(STATE / 'controller/herdr.log', 'ab', buffering=0)
    server = subprocess.Popen(herdr_command('server'), env=controller_env(), stdout=log,
                               stderr=log, start_new_session=True)
    CHILDREN.append(server)
    for _ in range(100):
        try:
            await asyncio.to_thread(herdr, 'workspace', 'list')
            break
        except Exception:
            if server.poll() is not None:
                raise RuntimeError('HerdR server exited; inspect /state/controller/herdr.log')
            await asyncio.sleep(.1)
    else:
        raise RuntimeError('Timed out waiting for HerdR server')
    # Rebuild the generated layout on each container start, without touching agent homes.
    listing = herdr('workspace', 'list')
    existing = listing if isinstance(listing, list) else listing.get('workspaces', [])
    old_ids = [x['workspace_id'] for x in existing]
    for name in AGENTS:
        result = herdr('workspace', 'create', '--cwd', str(STATE), '--label',
                       name + (' (lead)' if name == 'claude' else ''), '--env',
                       'DEVBOX_AGENT=' + name, '--env', 'HERDR_AGENT=' +
                       ('antigravity-cli' if name == 'agy' else name), '--no-focus')
        PANES[name] = result['root_pane']['pane_id']
        if name == 'claude':
            lead_workspace = result['workspace']['workspace_id']
    for workspace_id in old_ids:
        herdr('workspace', 'close', workspace_id)
    herdr('workspace', 'focus', lead_workspace)
    # Native Codex relay uses the account's managed server. Authentication can be
    <span class="c"># completed in the TUI; a bounded retry loop enables it afterward.</span>
    relay_task = asyncio.create_task(codex_relay())
    ttylog = open(STATE / 'controller/ttyd.log', 'ab', buffering=0)
    stale_tty = RUN / 'private/ttyd.sock'
    if stale_tty.exists():
        stale_tty.unlink()
    ttyd = subprocess.Popen(['ttyd', '-W', '-i', str(RUN / 'private/ttyd.sock'),
                             '-b', '/terminal', *herdr_command()], env=controller_env(),
                            stdout=ttylog, stderr=ttylog, start_new_session=True)
    CHILDREN.append(ttyd)
    print(f'\nApproval dashboard and remote HerdR: http://localhost:{CFG["web_port"]}', flush=True)
    print('Dashboard password (%s): %s' % (SECRET_SOURCES.get('admin-password', 'saved'), broker.password), flush=True)
    print('Claude-session approval authenticator secret (%s): %s' % (broker.totp_source, broker.totp_secret), flush=True)
    print('Authenticator URI: ' + broker.totp_uri(), flush=True)
    print('OpenCode web: http://localhost:4096  user: opencode  password (%s): %s' % (
          SECRET_SOURCES.get('opencode-password', 'saved'),
          (STATE / 'secrets/opencode-password').read_text()), flush=True)
    print('Claude/agy native remote control starts in their panes after login. '
          'All seven are also remotely controllable through the protected HerdR web terminal.', flush=True)
    print('First login: complete trust and sign-in in each pane. '
          'agent-login and agent-start are available in every agent shell.', flush=True)
    foreground = None
    if sys.stdin.isatty() and os.environ.get('DEVBOX_HEADLESS') != '1':
        foreground = subprocess.Popen(herdr_command(), env=controller_env())
    stop = asyncio.Event()
    loop = asyncio.get_running_loop()
    for sig in (signal.SIGTERM, signal.SIGINT):
        loop.add_signal_handler(sig, stop.set)
    try:
        while not stop.is_set():
            if foreground and foreground.poll() is not None:
                break
            for proc, label in ((server, 'HerdR'), (ttyd, 'ttyd'), (opencode, 'OpenCode')):
                if proc.poll() is not None:
                    raise RuntimeError(label + ' service exited; inspect controller logs')
            try:
                await asyncio.wait_for(stop.wait(), timeout=1)
            except asyncio.TimeoutError:
                pass
    finally:
        relay_task.cancel()
        if foreground and foreground.poll() is None:
            foreground.terminate()
        for proc in reversed(CHILDREN):
            if proc.poll() is None:
                os.killpg(proc.pid, signal.SIGTERM)
        await asyncio.sleep(.3)


async def codex_relay():
    while True:
        log = STATE / 'controller/codex-remote.log'
        proc = spawn_agent_service('codex', ['codex', 'remote-control', 'start', '--json'], log)
        while proc.poll() is None:
            await asyncio.sleep(2)
        if proc.returncode == 0:
            return
        await asyncio.sleep(30)


def main():
    global CFG
    os.umask(0o077)
    mode = sys.argv[1] if len(sys.argv) &gt; 1 else 'start'
    if mode == 'pane':
        pane()
    elif mode == 'as-agent':
        as_agent(sys.argv[2], sys.argv[3:])
    elif mode == 'agent-start':
        return native_start(os.environ['DEVBOX_AGENT'])
    elif mode in ('host', 'team'):
        cli(mode, sys.argv[2:])
    elif mode == 'self-test':
        import selftest
        return selftest.run()
    elif mode == 'attach':
        os.execvpe('herdr', herdr_command(), controller_env())
    elif mode == 'secret-exists':
        # Used by run.sh: exit 0 if the named saved secret exists. Never prints it.
        path = {'totp': STATE / 'secrets/approval-totp', 'admin': STATE / 'admin-password',
                'opencode': STATE / 'secrets/opencode-password'}[sys.argv[2]]
        return 0 if path.is_file() and path.stat().st_size else 1
    elif mode == 'openwebui-models':
        # Used by run.sh's default-model picker. URL/key come from the environment (just typed)
        # or, when unset, from the cache; the key never appears on a command line.
        try:
            cached = json.loads((STATE / 'secrets/openwebui.json').read_text())
        except (OSError, ValueError):
            cached = {}
        url = os.environ.get('OPENWEBUI_URL') or cached.get('openwebui_url', '')
        key = os.environ.get('OPENWEBUI_API_KEY') or cached.get('openwebui_key', '')
        try:
            print('\n'.join(fetch_openwebui_models(url, key)))
        except Exception as e:
            print('[openwebui-models] ' + str(e), file=sys.stderr)
            return 1
    elif mode == 'openwebui-show':
        # Used by run.sh: prints the cached endpoint (never the key) so you can keep or change it.
        try:
            saved = json.loads((STATE / 'secrets/openwebui.json').read_text())
            print(saved['openwebui_url'])
            print(saved['openwebui_model'])
            print('key' if saved.get('openwebui_key') else 'nokey')
        except (OSError, ValueError, KeyError):
            return 1
    elif mode == 'versions':
        print((HERE / 'versions.txt').read_text())
    elif mode == 'start':
        CFG = load_config()
        resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
        ctypes.CDLL(None).prctl(4, 0, 0, 0, 0)
        asyncio.run(workstation())
    else:
        raise ValueError('Modes: start, attach, self-test, versions')
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception as e:
        error('devbox', e)
        sys.exit(1)


DEVBOX_PY

<span class="k">COPY</span><span class="s"> &lt;&lt;'SELFTEST_PY' /opt/devbox/selftest.py</span>
"""Synthetic security tests. Never mount real drives when running these."""
import asyncio
import base64
import hashlib
import json
import os
<span class="k">from</span><span class="s"> pathlib import Path</span>
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import unittest
import types
import struct
<span class="k">from</span><span class="s"> unittest.mock import patch</span>
<span class="k">from</span><span class="s"> aiohttp import ClientSession, CookieJar, web</span>
import devbox as d


class SecurityTests(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        if os.geteuid() != 0:
            self.skipTest('UID-boundary tests require container root')
        self.temp = tempfile.TemporaryDirectory(prefix='devbox-selftest-')
        self.root = Path(self.temp.name)
        self.root.chmod(0o755)
        d.STATE, d.RUN, d.DRIVES = [self.root / n for n in ('state', 'run', 'host-private')]
        d.DRIVES.mkdir(mode=0o700)
        for drive in ('c',):
            (d.DRIVES / drive).mkdir()
        (d.DRIVES / 'c/secret.txt').write_text('PRIVATE HOST CONTENT\n')
        d.PANES = {}
        d.CFG = d.load_config()
        d.CFG['require_mounts'] = False
        d.CFG['web_port'] = 0
        <span class="c"># Some hosted workspaces map only UID 0. Run filesystem/protocol tests there,</span>
        <span class="c"># but explicitly skip checks that require actual distinct kernel UIDs.</span>
        self.uid_isolation = any(int(line.split()[0]) &lt;= 21007 &lt; int(line.split()[0]) + int(line.split()[2])
                                 for line in Path('/proc/self/uid_map').read_text().splitlines())
        self.old_uids = d.UIDS.copy()
        if self.uid_isolation:
            d.initialize()
        else:
            with patch('os.chown'), patch('os.fchown'):
                d.initialize()
            d.UIDS = {0: 'claude'}
        self.broker = d.Broker()
        self.runners = ()
        self.client = None
        if self.uid_isolation:
            self.runners = await d.run_broker(self.broker)
            site = next(iter(self.runners[1]._sites))
            self.url = 'http://127.0.0.1:' + str(site._server.sockets[0].getsockname()[1])
            self.client = ClientSession(cookie_jar=CookieJar(unsafe=True))
            response = await self.client.post(self.url + '/login', data={'password': self.broker.password}, allow_redirects=False)
            self.assertEqual(response.status, 302)
            response.release()
        else:
            response = await self.broker.login(self.fake_request(method='POST', payload={'password': self.broker.password}))
            self.assertEqual(response.status, 302)
        self.csrf = next(iter(self.broker.sessions.values()))['csrf']

    async def asyncTearDown(self):
        if hasattr(self, 'client'):
            if self.client:
                await self.client.close()
            for runner in self.runners:
                await runner.cleanup()
            self.broker.db.close()
            d.UIDS = self.old_uids
            d.PANES = {}
            self.temp.cleanup()

    async def rpc(self, data, uid=21001):
        # A real process connects after setuid. A supplied JSON agent name has no authority.
        if not self.uid_isolation:
            try:
                response = await self.broker.rpc(self.fake_request(payload=data, uid=0))
                return response.status, json.loads(response.text)
            except web.HTTPException as e:
                return e.status, e.text
            except Exception as e:
                return 400, {'error': str(e)}
        code = '''
import os,socket,sys,json,ctypes
if int(sys.argv[1]) != os.getuid():
 os.setgroups([]);os.setgid(int(sys.argv[1]));os.setuid(int(sys.argv[1]))
ctypes.CDLL(None).prctl(38,1,0,0,0)
s=socket.socket(socket.AF_UNIX);s.connect(sys.argv[2])
b=sys.argv[3].encode()
s.sendall(b'POST /rpc HTTP/1.1\\r\\nHost: local\\r\\nContent-Type: application/json\\r\\nConnection: close\\r\\nContent-Length: '+str(len(b)).encode()+b'\\r\\n\\r\\n'+b)
f=s.makefile('rb');sys.stdout.buffer.write(f.read())
'''
        proc = await asyncio.create_subprocess_exec(sys.executable, '-c', code, str(uid),
            str(d.RUN / 'agent.sock'), json.dumps(data), stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        out, err = await asyncio.wait_for(proc.communicate(), 10)
        self.assertEqual(proc.returncode, 0, err.decode())
        head, body = out.split(b'\r\n\r\n', 1)
        status = int(head.split()[1])
        try:
            return status, json.loads(body)
        except json.JSONDecodeError:
            return status, body.decode()

    async def new(self, op='read', **kw):
        data = {'action': 'create', 'op': op, 'drive': 'c', 'path': 'secret.txt', **kw}
        status, response = await self.rpc(data)
        self.assertEqual(status, 200, response)
        return response['id']

    async def decide(self, rid, decision, csrf=None):
        if not self.uid_isolation:
            try:
                await self.broker.decide(self.fake_request(payload={
                    'csrf': self.csrf if csrf is None else csrf, 'id': rid, 'decision': decision}))
            except web.HTTPException as e:
                return e.status
        response = await self.client.post(self.url + '/decide', data={
            'csrf': self.csrf if csrf is None else csrf, 'id': rid, 'decision': decision},
            allow_redirects=False)
        status = response.status
        await response.read()
        return status

    def fake_request(self, method='GET', payload=None, uid=0, authenticated=True):
        async def value():
            return payload
        sock = types.SimpleNamespace(family=socket.AF_UNIX,
            getsockopt=lambda *args: struct.pack('3i', 1, uid, uid))
        sid = next(iter(self.broker.sessions), '') if authenticated else ''
        return types.SimpleNamespace(method=method, json=value, post=value,
            cookies={'devbox_session': sid}, headers={},
            transport=types.SimpleNamespace(get_extra_info=lambda key: sock))

    def code(self, offset=0):
        return d.totp_code(self.broker.totp_secret, int(time.time() // 30) + offset)

    async def test_rc_approval_requires_valid_single_use_code(self):
        rid = await self.new()
        status, _ = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': '000000'})
        self.assertEqual(status, 403)
        self.assertEqual(self.broker.requests[rid]['status'], 'pending')
        code = self.code()
        status, result = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': code})
        self.assertEqual(status, 200, result)
        self.assertEqual(self.broker.requests[rid]['status'], 'completed')
        rid2 = await self.new()
        status, _ = await self.rpc({'action': 'rc-decide', 'id': rid2, 'decision': 'approve', 'code': code})
        self.assertEqual(status, 403)
        self.assertEqual(self.broker.requests[rid2]['status'], 'pending')

    async def test_rc_lockout_after_failures(self):
        rid = await self.new()
        for _ in range(5):
            await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': '123456'})
        status, _ = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': self.code()})
        self.assertEqual(status, 429)

    async def test_rc_deny_needs_no_code_and_web_conflicts_after(self):
        rid = await self.new()
        status, _ = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'deny'})
        self.assertEqual(status, 200)
        self.assertEqual(await self.decide(rid, 'approve'), 409)

    async def test_rc_pending_lists_requests_and_peer_is_refused(self):
        rid = await self.new()
        status, result = await self.rpc({'action': 'pending'})
        self.assertEqual(status, 200)
        self.assertIn(rid, [x['id'] for x in result['pending']])
        self.assertNotIn('PRIVATE HOST', json.dumps(result))
        if self.uid_isolation:
            status, _ = await self.rpc({'action': 'pending'}, uid=d.AGENTS['codex'])
            self.assertEqual(status, 403)
            status, _ = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'deny'}, uid=d.AGENTS['codex'])
            self.assertEqual(status, 403)

    async def test_openwebui_cache_is_private_and_reused(self):
        cache = d.STATE / 'secrets/openwebui.json'
        self.assertFalse(cache.exists())
        d.CFG.update(openwebui_url='https://w.example.org', openwebui_model='m', openwebui_key='sekrit')
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        self.assertEqual(oct(cache.stat().st_mode &amp; 0o777), '0o600')
        self.assertNotIn('sekrit', (d.STATE / 'public.json').read_text())
        with patch.dict(os.environ, {}, clear=False):
            for k in ('OPENWEBUI_URL', 'OPENWEBUI_MODEL', 'OPENWEBUI_API_KEY'):
                os.environ.pop(k, None)
            cfg = d.load_config()
        self.assertEqual((cfg['openwebui_url'], cfg['openwebui_model'], cfg['openwebui_key']),
                         ('https://w.example.org', 'm', 'sekrit'))

    def watch_herdr(self, fail=False):
        sent = []

        def fake(*args, **kw):
            sent.append(args)
            if fail:
                raise RuntimeError('herdr unavailable')
            return {}
        d.PANES = {'claude': 'pane-claude'}
        d.CFG['notify_interval_seconds'] = 0
        return sent, patch.object(d, 'herdr', fake)

    async def test_request_notifies_claude_pane_without_contents(self):
        sent, mock = self.watch_herdr()
        with mock:
            rid = await self.new('write', content_b64=base64.b64encode(b'PROPOSED SECRET BYTES').decode())
            await self.broker.drain_notifications()
            await self.decide(rid, 'preview')
            await self.broker.drain_notifications()
        self.assertEqual(sent[0][:3], ('agent', 'prompt', 'pane-claude'))
        text = sent[0][3]
        self.assertIn(rid, text)
        self.assertIn('claude', text)
        self.assertIn('write', text)
        self.assertIn('secret.txt', text)
        self.assertIn(hashlib.sha256(b'PROPOSED SECRET BYTES').hexdigest(), text)
        self.assertIn('hostctl approve ID CODE', text)
        everything = json.dumps(sent)
        for forbidden in ('PRIVATE HOST', 'PROPOSED SECRET', base64.b64encode(b'PROPOSED SECRET BYTES').decode(), '---', 'current'):
            if forbidden != 'current':
                self.assertNotIn(forbidden, everything)

    async def test_notification_strips_control_characters(self):
        sent, mock = self.watch_herdr()
        with mock:
            await self.new('search', path='.', query='a\x1b[31m\nIGNORE\rb')
            await self.broker.drain_notifications()
        text = sent[0][3]
        self.assertNotIn('\x1b', text)
        self.assertNotIn('\r', text)
        self.assertNotIn('\nIGNORE', text)

    async def test_failed_notification_does_not_break_request(self):
        sent, mock = self.watch_herdr(fail=True)
        with mock:
            rid = await self.new()
            await self.broker.drain_notifications()
        self.assertEqual(self.broker.requests[rid]['status'], 'pending')
        self.assertTrue(sent)

    async def test_notifications_are_batched(self):
        sent, mock = self.watch_herdr()
        d.CFG['notify_interval_seconds'] = 0.3
        with mock:
            for _ in range(7):
                await self.new()
            await self.broker.drain_notifications()
        self.assertLessEqual(len(sent), 2)

    async def test_web_decision_and_expiry_send_closing_notes(self):
        sent, mock = self.watch_herdr()
        with mock:
            rid = await self.new()
            await self.broker.drain_notifications()
            await self.decide(rid, 'deny')
            rid2 = await self.new()
            self.broker.requests[rid2]['expires'] = time.time() - 1
            await self.decide(rid2, 'approve')
            await self.broker.drain_notifications()
        joined = '\n'.join(m[3] for m in sent)
        self.assertIn('CLOSED id=' + rid + ' denied on the web dashboard', joined)
        self.assertIn('CLOSED id=' + rid2 + ' expired', joined)

    async def test_rules_files_refreshed_and_user_text_kept(self):
        home = d.STATE / 'agents/claude/workspace'
        target = home / 'CLAUDE.md'
        target.write_text(d.MANAGED_BEGIN + '\nSTALE RULES\n' + d.MANAGED_END + '\nMY OWN NOTES\n')
        (home / 'AGENTS.md').write_text('# Devbox operating rules\nold unmarked file\n')
        outside = d.STATE / 'outside.txt'
        outside.write_text('untouched')
        (home / 'QWEN.md').unlink()
        (home / 'QWEN.md').symlink_to(outside)
        with patch('os.chown'), patch('os.fchown'):
            with self.assertRaises(OSError):
                d.initialize()
        self.assertEqual(outside.read_text(), 'untouched')
        (home / 'QWEN.md').unlink()
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        text = target.read_text()
        self.assertNotIn('STALE RULES', text)
        self.assertIn('hostctl approve ID CODE', text)
        self.assertIn('MY OWN NOTES', text)
        self.assertEqual(text.count(d.MANAGED_BEGIN), 1)
        self.assertEqual(oct(target.stat().st_mode &amp; 0o777), '0o600')
        old = (home / 'AGENTS.md').read_text()
        self.assertIn('old unmarked file', old)
        self.assertIn(d.MANAGED_BEGIN, old)

    async def test_hostctl_preallowed_but_decisions_still_prompt(self):
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        agents = d.STATE / 'agents'
        rules = (agents / 'codex/.codex/rules/devbox.rules').read_text()
        self.assertIn('pattern = ["hostctl", "read"]', rules)
        self.assertNotIn('approve', rules)
        qwen = json.loads((agents / 'qwen/.qwen/settings.json').read_text())
        self.assertIn('run_shell_command(hostctl write)', qwen['permissions']['allow'])
        agy = json.loads((agents / 'agy/.gemini/antigravity-cli/settings.json').read_text())
        self.assertIn('command(hostctl search)', agy['permissions']['allow'])
        self.assertNotIn('hostctl approve', json.dumps(agy))
        grok = (agents / 'grok/.grok/config.toml').read_text()
        self.assertIn('pattern = "hostctl read *"', grok)
        self.assertNotIn('approve', grok)
        opencode = json.loads((agents / 'opencode/.config/opencode/opencode.json').read_text())
        self.assertEqual(opencode['permission']['bash']['hostctl read*'], 'allow')
        self.assertEqual(opencode['permission']['bash']['*'], 'ask')

    async def test_permission_merge_preserves_existing_settings_and_is_idempotent(self):
        path = d.STATE / 'agents/qwen/.qwen/settings.json'
        path.write_text(json.dumps({'auth': {'type': 'oauth'}, 'permissions': {'allow': ['run_shell_command(ls)']}}))
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
            d.initialize()
        doc = json.loads(path.read_text())
        self.assertEqual(doc['auth'], {'type': 'oauth'})
        self.assertIn('run_shell_command(ls)', doc['permissions']['allow'])
        self.assertEqual(doc['permissions']['allow'].count('run_shell_command(hostctl read)'), 1)
        path.write_text('{not json')
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        self.assertEqual(path.read_text(), '{not json')

    async def test_grok_config_is_valid_toml_and_legacy_block_repaired(self):
        import tomllib
        path = d.STATE / 'agents/grok/.grok/config.toml'
        path.write_text(d.MANAGED_BEGIN + '\n[permission]\nrules = []\n' + d.MANAGED_END + '\n[ui]\nremember_tool_approvals = true\n')
        for _ in range(2):
            with patch('os.chown'), patch('os.fchown'):
                d.initialize()
            doc = tomllib.loads(path.read_text())
            self.assertEqual(doc['ui'], {'remember_tool_approvals': True})
            rules = doc['permission']['rules']
            self.assertIn({'action': 'allow', 'tool': 'bash', 'pattern': 'hostctl read *'}, rules)
            self.assertNotIn('approve', json.dumps(rules))
            self.assertNotIn('&lt;!--', path.read_text())
            self.assertEqual(path.read_text().count(d.TOML_BEGIN), 1)

    async def test_every_generated_config_parses(self):
        import tomllib
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        for rel in ('grok/.grok/config.toml',):
            tomllib.loads((d.STATE / 'agents' / rel).read_text())
        for rel in ('qwen/.qwen/settings.json', 'agy/.gemini/antigravity-cli/settings.json',
                    'opencode/.config/opencode/opencode.json', 'claude/.claude/settings.json'):
            json.loads((d.STATE / 'agents' / rel).read_text())

    async def test_opencode_config_merges_and_keeps_user_providers(self):
        path = d.STATE / 'agents/opencode/.config/opencode/opencode.json'
        d.CFG.update(openwebui_url='https://w.example.org', openwebui_model='m1', openwebui_key='k1')
        path.write_text(json.dumps({
            'enabled_providers': ['openwebui'], 'model': 'openwebui/old',
            'provider': {'anthropic': {'options': {'apiKey': 'user-key'}},
                         'openwebui': {'models': {'extra': {'name': 'Extra'}}, 'options': {'timeout': 5}}},
            'theme': 'tokyonight', 'permission': 'allow'}))
        for _ in range(2):
            with patch('os.chown'), patch('os.fchown'):
                d.initialize()
            doc = json.loads(path.read_text())
            self.assertNotIn('enabled_providers', doc)
            self.assertEqual(doc['theme'], 'tokyonight')
            self.assertEqual(doc['provider']['anthropic'], {'options': {'apiKey': 'user-key'}})
            self.assertEqual(doc['model'], 'openwebui/m1')  # an openwebui/ default follows the configured model
            ow = doc['provider']['openwebui']
            self.assertEqual(set(ow['models']), {'extra', 'm1'})
            self.assertEqual(ow['options'], {'timeout': 5, 'baseURL': 'https://w.example.org/api', 'apiKey': 'k1'})
            self.assertEqual(doc['permission']['bash']['*'], 'ask')
            self.assertEqual(doc['permission']['*'], 'ask')

    async def test_opencode_default_model_rules(self):
        path = d.STATE / 'agents/opencode/.config/opencode/opencode.json'
        d.CFG.update(openwebui_url='https://w.example.org', openwebui_model='m1', openwebui_key='k1')
        path.unlink(missing_ok=True)
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        self.assertEqual(json.loads(path.read_text())['model'], 'openwebui/m1')
        doc = json.loads(path.read_text())
        doc['model'] = 'anthropic/claude'
        doc['enabled_providers'] = ['anthropic', 'openwebui']
        path.write_text(json.dumps(doc))
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        doc = json.loads(path.read_text())
        self.assertEqual(doc['model'], 'anthropic/claude')
        self.assertEqual(doc['enabled_providers'], ['anthropic', 'openwebui'])

    async def test_opencode_unparseable_config_is_left_alone(self):
        path = d.STATE / 'agents/opencode/.config/opencode/opencode.json'
        path.write_text('// comment\n{"theme": "x"}')
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        self.assertEqual(path.read_text(), '// comment\n{"theme": "x"}')

    def init_with_openwebui(self, url='https://w.example.org', model='m1', key='k1'):
        d.CFG.update(openwebui_url=url, openwebui_model=model, openwebui_key=key)
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()

    async def test_openwebui_base_normalization(self):
        self.assertEqual(d.openwebui_base('https://h'), 'https://h/api')
        self.assertEqual(d.openwebui_base('https://h/api/'), 'https://h/api')
        self.assertEqual(d.openwebui_base('https://h/api/v1'), 'https://h/api/v1')
        self.assertEqual(d.openwebui_base('https://h/api/chat/completions'), 'https://h/api')
        with self.assertRaises(ValueError):
            d.openwebui_base('https://user:pw@h')
        with self.assertRaises(ValueError):
            d.openwebui_base('ftp://h')

    async def test_opencode_plugin_entry_pinned_and_user_plugins_kept(self):
        path = d.STATE / 'agents/opencode/.config/opencode/opencode.json'
        path.write_text(json.dumps({'plugin': ['my-plugin', 'github:BillJr99/opencode-auto-models']}))
        self.init_with_openwebui()
        self.init_with_openwebui()
        plugins = json.loads(path.read_text())['plugin']
        self.assertEqual(plugins, ['my-plugin', d.OPENCODE_PLUGIN])
        self.assertRegex(d.OPENCODE_PLUGIN, r'^github:BillJr99/opencode-auto-models<span class="c">#[0-9a-f]{40}$')</span>

    async def test_pi_configured_for_openwebui_and_user_additions_persist(self):
        home = d.STATE / 'agents/pi'
        (home / '.pi/agent').mkdir(parents=True, exist_ok=True)
        (home / '.pi/agent/settings.json').write_text(json.dumps({'theme': 'dark', 'packages': ['npm:other']}))
        cfg_dir = home / '.config/pi-openai-compat'
        cfg_dir.mkdir(parents=True, exist_ok=True)
        (cfg_dir / 'config.json').write_text(json.dumps({'previousModel': None, 'providers': {
            'openrouter': {'displayName': 'OpenRouter', 'baseUrl': 'https://openrouter.ai/api/v1', 'apiKey': 'or-key',
                           'cachedModels': [{'id': 'x/y'}]},
            'openwebui': {'cachedModels': [{'id': 'discovered', 'contextWindow': 1}]}}}))
        self.init_with_openwebui()
        self.init_with_openwebui(model='m2', key='k2')
        settings = json.loads((home / '.pi/agent/settings.json').read_text())
        self.assertEqual(settings['theme'], 'dark')
        self.assertEqual(settings['packages'], ['npm:other', d.PI_PLUGIN_DIR])
        self.assertEqual((settings['defaultProvider'], settings['defaultModel']), ('compat-openwebui', 'm2'))
        doc = json.loads((cfg_dir / 'config.json').read_text())
        self.assertEqual(doc['providers']['openrouter']['apiKey'], 'or-key')
        ow = doc['providers']['openwebui']
        self.assertEqual((ow['baseUrl'], ow['apiKey']), ('https://w.example.org/api', 'k2'))
        self.assertEqual([m['id'] for m in ow['cachedModels']], ['m2', 'm1', 'discovered'])
        self.assertEqual(ow['cachedModels'][-1]['contextWindow'], 1)

    async def test_pi_default_not_overridden_when_user_chose_another_provider(self):
        home = d.STATE / 'agents/pi'
        (home / '.pi/agent').mkdir(parents=True, exist_ok=True)
        (home / '.pi/agent/settings.json').write_text(json.dumps({'defaultProvider': 'anthropic', 'defaultModel': 'claude'}))
        self.init_with_openwebui()
        settings = json.loads((home / '.pi/agent/settings.json').read_text())
        self.assertEqual((settings['defaultProvider'], settings['defaultModel']), ('anthropic', 'claude'))

    async def test_qwen_configured_for_openwebui_and_user_additions_persist(self):
        path = d.STATE / 'agents/qwen/.qwen/settings.json'
        path.write_text(json.dumps({
            'env': {'OTHER_KEY': 'o'},
            'modelProviders': {'openai': [
                {'id': 'gpt-x', 'name': 'GPT X', 'envKey': 'OTHER_KEY', 'baseUrl': 'https://api.openai.com/v1'},
                {'id': 'extra-ow', 'name': 'Extra', 'envKey': 'OPENWEBUI_API_KEY', 'baseUrl': 'https://old/api'}]},
            'ui': {'theme': 'dark'}}))
        self.init_with_openwebui()
        self.init_with_openwebui(model='m2', key='k2')
        doc = json.loads(path.read_text())
        self.assertEqual(doc['ui'], {'theme': 'dark'})
        self.assertEqual(doc['env'], {'OTHER_KEY': 'o', 'OPENWEBUI_API_KEY': 'k2'})
        entries = {e['id']: e for e in doc['modelProviders']['openai']}
        self.assertEqual(set(entries), {'m1', 'm2', 'gpt-x', 'extra-ow'})  # earlier Open WebUI models are kept
        self.assertEqual(entries['extra-ow']['baseUrl'], 'https://w.example.org/api')
        self.assertEqual(entries['gpt-x']['baseUrl'], 'https://api.openai.com/v1')
        self.assertEqual(entries['m2']['envKey'], 'OPENWEBUI_API_KEY')
        self.assertEqual(doc['security']['auth']['selectedType'], 'openai')
        self.assertEqual(doc['model']['name'], 'm2')
        self.assertIn('run_shell_command(hostctl read)', doc['permissions']['allow'])

    async def test_qwen_user_chosen_auth_and_model_respected(self):
        path = d.STATE / 'agents/qwen/.qwen/settings.json'
        path.write_text(json.dumps({'security': {'auth': {'selectedType': 'qwen-oauth'}}, 'model': {'name': 'coder'}}))
        self.init_with_openwebui()
        doc = json.loads(path.read_text())
        self.assertEqual(doc['security']['auth']['selectedType'], 'qwen-oauth')
        self.assertEqual(doc['model']['name'], 'coder')
        self.assertIn('modelProviders', doc)

    async def test_no_openwebui_means_no_provider_changes(self):
        d.CFG.update(openwebui_url='', openwebui_model='', openwebui_key='')
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        home = d.STATE / 'agents'
        self.assertFalse((home / 'pi/.config/pi-openai-compat/config.json').exists())
        self.assertNotIn('modelProviders', json.loads((home / 'qwen/.qwen/settings.json').read_text()))
        self.assertIn(d.PI_PLUGIN_DIR, json.loads((home / 'pi/.pi/agent/settings.json').read_text())['packages'])

    async def test_fetch_openwebui_models(self):
        import http.server
        import threading
        seen = {}

        class Handler(http.server.BaseHTTPRequestHandler):
            def do_GET(self):
                seen['path'], seen['auth'] = self.path, self.headers.get('Authorization')
                body = json.dumps({'data': [{'id': 'b'}, {'id': 'a'}, {'id': 'a'}]}).encode()
                self.send_response(200)
                self.send_header('Content-Length', str(len(body)))
                self.end_headers()
                self.wfile.write(body)

            def log_message(self, *args):
                pass
        server = http.server.HTTPServer(('127.0.0.1', 0), Handler)
        threading.Thread(target=server.serve_forever, daemon=True).start()
        try:
            models = await asyncio.to_thread(d.fetch_openwebui_models, 'http://127.0.0.1:%d' % server.server_port, 'sekret')
        finally:
            server.shutdown()
        self.assertEqual(models, ['a', 'b'])
        self.assertEqual((seen['path'], seen['auth']), ('/api/models', 'Bearer sekret'))

    async def test_grok_existing_permission_table_is_not_clobbered(self):
        path = d.STATE / 'agents/grok/.grok/config.toml'
        path.write_text('[permission]\nrules = []\n')
        with patch('os.chown'), patch('os.fchown'):
            d.initialize()
        self.assertEqual(path.read_text(), '[permission]\nrules = []\n')

    async def test_team_read_approved_through_claude_session(self):
        calls = []

        def fake(*args, **kw):
            calls.append(args)
            return 'PEER TERMINAL TEXT' if args[:2] == ('agent', 'read') else {}
        d.PANES = {'claude': 'pane-claude', 'codex': 'pane-codex'}
        d.CFG['notify_interval_seconds'] = 0
        with patch.object(d, 'herdr', fake):
            status, created = await self.rpc({'action': 'create', 'op': 'team-read', 'target': 'codex'})
            self.assertEqual(status, 200, created)
            rid = created['id']
            await self.broker.drain_notifications()
            prompts = [c for c in calls if c[:2] == ('agent', 'prompt')]
            self.assertIn('target codex', prompts[0][3])
            self.assertNotIn('PEER TERMINAL TEXT', prompts[0][3])
            # Nothing is read before approval, and the pending list shows the target only.
            self.assertFalse([c for c in calls if c[:2] == ('agent', 'read')])
            status, listing = await self.rpc({'action': 'pending'})
            entry = next(x for x in listing['pending'] if x['id'] == rid)
            self.assertEqual((entry['op'], entry['target']), ('team-read', 'codex'))
            self.assertNotIn('PEER TERMINAL TEXT', json.dumps(listing))
            # A wrong code reads nothing; a valid single-use code returns the peer text once.
            status, _ = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': '000000'})
            self.assertEqual(status, 403)
            self.assertFalse([c for c in calls if c[:2] == ('agent', 'read')])
            code = self.code()
            status, result = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': code})
            self.assertEqual(status, 200, result)
            self.assertEqual(result['status'], 'completed')
            self.assertEqual(result['result']['text'], 'PEER TERMINAL TEXT')
            reads = [c for c in calls if c[:2] == ('agent', 'read')]
            self.assertEqual(len(reads), 1)
            self.assertEqual(reads[0][2], 'pane-codex')
            status, again = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': code})
            self.assertIn(status, (403, 409))
            self.assertEqual(len([c for c in calls if c[:2] == ('agent', 'read')]), 1)
        self.assertIn('claude-rc', [row[0].split(' via ')[-1] for row in self.broker.db.execute(
            "SELECT decision FROM audit WHERE request_id=? AND decision LIKE 'approved via%'", (rid,))])

    async def test_team_read_rules(self):
        d.PANES = {'claude': 'pane-claude', 'codex': 'pane-codex'}
        for target in ('claude', 'nobody', None):
            status, _ = await self.rpc({'action': 'create', 'op': 'team-read', 'target': target})
            self.assertEqual(status, 400, target)
        if self.uid_isolation:
            status, _ = await self.rpc({'action': 'create', 'op': 'team-read', 'target': 'claude'},
                                       uid=d.AGENTS['codex'])
            self.assertEqual(status, 400)
            status, created = await self.rpc({'action': 'create', 'op': 'team-read', 'target': 'codex'})
            self.assertEqual(status, 200)
            status, _ = await self.rpc({'action': 'rc-decide', 'id': created['id'], 'decision': 'deny'},
                                       uid=d.AGENTS['codex'])
            self.assertEqual(status, 403)

    async def test_totp_secret_persists_and_precedence(self):
        path = d.STATE / 'secrets/approval-totp'
        first = path.read_text()
        self.assertEqual(oct(path.stat().st_mode &amp; 0o777), '0o600')
        self.assertEqual(oct(path.parent.stat().st_mode &amp; 0o777), '0o700')
        self.assertEqual(self.broker.totp_source, 'newly generated')
        self.assertEqual(d.Broker().totp_secret, first)            # reused across runs
        self.assertEqual(d.Broker().totp_source, 'saved from a previous run')
        with patch.dict(os.environ, {'DEVBOX_TOTP_REGENERATE': '1'}):
            regenerated = d.Broker()
        self.assertNotEqual(regenerated.totp_secret, first)
        self.assertEqual(path.read_text(), regenerated.totp_secret)
        d.CFG['approval_totp_secret'] = 'jbsw y3dp ehpk 3pxp'      # spaces/case tolerated
        explicit = d.Broker()
        self.assertEqual(explicit.totp_secret, 'JBSWY3DPEHPK3PXP')
        self.assertEqual(path.read_text(), 'JBSWY3DPEHPK3PXP')
        d.CFG['approval_totp_secret'] = ''
        self.assertEqual(d.Broker().totp_secret, 'JBSWY3DPEHPK3PXP')  # explicit value now saved
        path.write_text('not base32 !!')
        self.assertNotEqual(d.Broker().totp_secret, 'not base32 !!')

    async def test_passwords_persist_across_runs_and_can_be_replaced(self):
        for name, path, explicit, regen in (
                ('admin', d.STATE / 'admin-password', 'DEVBOX_ADMIN_PASSWORD', 'DEVBOX_ADMIN_REGENERATE'),
                ('opencode', d.STATE / 'secrets/opencode-password', 'DEVBOX_OPENCODE_PASSWORD',
                 'DEVBOX_OPENCODE_REGENERATE')):
            first = path.read_text()
            self.assertEqual(oct(path.stat().st_mode &amp; 0o777), '0o600', name)
            with patch('os.chown'), patch('os.fchown'):
                d.initialize()
            self.assertEqual(path.read_text(), first, name)
            self.assertEqual(d.SECRET_SOURCES[path.name], 'saved from a previous run')
            with patch.dict(os.environ, {regen: '1'}), patch('os.chown'), patch('os.fchown'):
                d.initialize()
            self.assertNotEqual(path.read_text(), first, name)
            self.assertEqual(d.SECRET_SOURCES[path.name], 'newly generated')
            with patch.dict(os.environ, {explicit: 'my-own-password-123'}), patch('os.chown'), patch('os.fchown'):
                d.initialize()
            self.assertEqual(path.read_text(), 'my-own-password-123', name)
            with patch.dict(os.environ, {explicit: 'short'}), patch('os.chown'), patch('os.fchown'):
                with self.assertRaises(ValueError):
                    d.initialize()
            with patch('os.chown'), patch('os.fchown'):
                d.initialize()
            self.assertEqual(path.read_text(), 'my-own-password-123', name)  # explicit value is now the saved one

    async def test_opencode_password_reaches_only_the_opencode_agent_env(self):
        (d.STATE / 'secrets/opencode-password').write_text('pw-for-opencode-xyz')
        self.assertEqual(d.agent_env('opencode')['OPENCODE_SERVER_PASSWORD'], 'pw-for-opencode-xyz')
        self.assertNotIn('OPENCODE_SERVER_PASSWORD', d.agent_env('codex'))

    async def test_totp_secret_unreadable_by_agents(self):
        if not self.uid_isolation:
            self.skipTest('Distinct UIDs unavailable in this host workspace')
        code = 'import os,sys;os.setgroups([]);os.setgid(21001);os.setuid(21001);open(sys.argv[1]).read()'
        proc = await asyncio.create_subprocess_exec(sys.executable, '-c', code,
            str(d.STATE / 'secrets/approval-totp'), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        out, err = await proc.communicate()
        self.assertNotEqual(proc.returncode, 0)
        self.assertIn(b'PermissionError', err)

    async def test_totp_secret_is_not_in_public_config(self):
        self.assertNotIn(self.broker.totp_secret, (d.STATE / 'public.json').read_text())

    async def test_totp_matches_rfc6238_vector(self):
        import base64 as b
        secret = b.b32encode(b'12345678901234567890').decode()
        self.assertEqual(d.totp_code(secret, 59 // 30), '287082')

    async def test_all_agent_uids_cannot_read_directly(self):
        if not self.uid_isolation:
            self.skipTest('Host maps only UID 0; run this check inside the built image')
        for name, uid in d.AGENTS.items():
            code = 'import os,sys;os.setgroups([]);os.setgid(int(sys.argv[1]));os.setuid(int(sys.argv[1]));open(sys.argv[2]).read()'
            proc = await asyncio.create_subprocess_exec(sys.executable, '-c', code, str(uid),
                str(d.DRIVES / 'c/secret.txt'), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
            _, err = await proc.communicate()
            self.assertNotEqual(proc.returncode, 0, name)
            self.assertIn(b'PermissionError', err)

    async def test_pending_read_has_no_host_contents(self):
        rid = await self.new()
        status, result = await self.rpc({'action': 'get', 'id': rid})
        self.assertEqual(status, 200)
        self.assertEqual(result['status'], 'pending')
        self.assertNotIn('result', result)
        self.assertNotIn('PRIVATE HOST', json.dumps(self.broker.requests[rid]))

    async def test_no_file_io_before_approval(self):
        rid = await self.new(path='does-not-exist.txt')
        self.assertEqual(self.broker.requests[rid]['status'], 'pending')

    async def test_approval_returns_exact_bytes(self):
        rid = await self.new()
        self.assertEqual(await self.decide(rid, 'approve'), 302)
        status, result = await self.rpc({'action': 'get', 'id': rid})
        self.assertEqual(status, 200)
        self.assertEqual(base64.b64decode(result['result']['content_b64']), b'PRIVATE HOST CONTENT\n')

    async def test_denial_returns_no_contents(self):
        rid = await self.new()
        await self.decide(rid, 'deny')
        _, result = await self.rpc({'action': 'get', 'id': rid})
        self.assertEqual(result['status'], 'denied')
        self.assertNotIn('result', result)

    async def test_uid_spoofing_ignored(self):
        rid = await self.new(agent='codex', uid=0)
        self.assertEqual(self.broker.requests[rid]['agent'], 'claude')

    async def test_peer_cannot_collect_approved_read(self):
        if not self.uid_isolation:
            self.skipTest('Distinct UIDs unavailable in this host workspace')
        rid = await self.new()
        await self.decide(rid, 'approve')
        status, _ = await self.rpc({'action': 'get', 'id': rid}, uid=d.AGENTS['codex'])
        self.assertEqual(status, 404)

    async def test_root_is_not_an_agent(self):
        if not self.uid_isolation:
            self.skipTest('Distinct UIDs unavailable in this host workspace')
        status, _ = await self.rpc({'action': 'create', 'op': 'read', 'drive': 'c', 'path': 'secret.txt'}, uid=0)
        self.assertEqual(status, 403)

    async def test_traversal_rejected(self):
        for path in ('../admin-password', '/etc/passwd', 'a/../b', 'a\\b', 'foo:stream', 'a//b', 'a./b'):
            with self.assertRaises(ValueError):
                d.canonical('c', path)

    async def test_symlink_rejected_after_approval(self):
        (d.DRIVES / 'c/link').symlink_to('/etc/passwd')
        rid = await self.new(path='link')
        await self.decide(rid, 'approve')
        self.assertEqual(self.broker.requests[rid]['status'], 'failed')

    async def test_intermediate_symlink_rejected(self):
        (d.DRIVES / 'c/link').symlink_to('/etc', target_is_directory=True)
        rid = await self.new(path='link/passwd')
        await self.decide(rid, 'approve')
        self.assertEqual(self.broker.requests[rid]['status'], 'failed')

    async def test_csrf_rejected(self):
        rid = await self.new()
        self.assertEqual(await self.decide(rid, 'approve', csrf='invalid'), 403)
        self.assertEqual(self.broker.requests[rid]['status'], 'pending')

    async def test_unauthenticated_ui_redirects(self):
        if not self.uid_isolation:
            for method in (self.broker.dashboard, self.broker.terminal):
                with self.assertRaises(web.HTTPFound):
                    await method(self.fake_request(authenticated=False))
            return
        async with ClientSession() as client:
            async with client.get(self.url + '/', allow_redirects=False) as response:
                self.assertEqual(response.status, 302)
            async with client.get(self.url + '/terminal/', allow_redirects=False) as response:
                self.assertEqual(response.status, 302)

    async def test_replay_rejected(self):
        rid = await self.new()
        await self.decide(rid, 'approve')
        self.assertEqual(await self.decide(rid, 'approve'), 409)

    async def test_expiry(self):
        rid = await self.new()
        self.broker.requests[rid]['expires'] = time.time() - 1
        self.assertEqual(await self.decide(rid, 'approve'), 409)
        self.assertEqual(self.broker.requests[rid]['status'], 'expired')

    async def test_write_single_approval_backs_up_and_writes(self):
        rid = await self.new('write', content_b64=base64.b64encode(b'new\n').decode())
        await self.decide(rid, 'approve')
        self.assertEqual(self.broker.requests[rid]['status'], 'completed')
        self.assertEqual((d.DRIVES / 'c/secret.txt').read_text(), 'new\n')
        self.assertEqual(base64.b64decode((d.STATE / 'backups' / rid).read_text()), b'PRIVATE HOST CONTENT\n')
        self.assertNotIn('PRIVATE HOST', json.dumps((await self.rpc({'action': 'get', 'id': rid}))[1]))

    async def test_rc_write_needs_only_one_code(self):
        rid = await self.new('write', content_b64=base64.b64encode(b'new\n').decode())
        status, result = await self.rpc({'action': 'rc-decide', 'id': rid, 'decision': 'approve', 'code': self.code()})
        self.assertEqual(status, 200, result)
        self.assertEqual((d.DRIVES / 'c/secret.txt').read_text(), 'new\n')

    async def test_preview_does_not_disclose_old_file_to_agent(self):
        rid = await self.new('write', content_b64=base64.b64encode(b'new\n').decode())
        await self.decide(rid, 'preview')
        _, result = await self.rpc({'action': 'get', 'id': rid})
        self.assertEqual(result['status'], 'pending')
        self.assertNotIn('PRIVATE HOST', json.dumps(result))

    async def test_approved_write_and_backup(self):
        rid = await self.new('write', content_b64=base64.b64encode(b'new\n').decode())
        await self.decide(rid, 'preview')
        await self.decide(rid, 'approve')
        self.assertEqual(self.broker.requests[rid]['status'], 'completed')
        self.assertEqual((d.DRIVES / 'c/secret.txt').read_text(), 'new\n')
        self.assertEqual(base64.b64decode((d.STATE / 'backups' / rid).read_text()), b'PRIVATE HOST CONTENT\n')

    async def test_stale_write_rejected(self):
        rid = await self.new('write', content_b64=base64.b64encode(b'new\n').decode())
        await self.decide(rid, 'preview')
        (d.DRIVES / 'c/secret.txt').write_text('concurrent change\n')
        await self.decide(rid, 'approve')
        self.assertEqual(self.broker.requests[rid]['status'], 'failed')
        self.assertEqual((d.DRIVES / 'c/secret.txt').read_text(), 'concurrent change\n')

    async def test_new_file_write(self):
        rid = await self.new('write', path='new.txt', content_b64=base64.b64encode(b'new\n').decode())
        await self.decide(rid, 'preview')
        await self.decide(rid, 'approve')
        self.assertEqual((d.DRIVES / 'c/new.txt').read_text(), 'new\n')

    async def test_literal_search(self):
        rid = await self.new('search', path='.', query='PRIVATE')
        await self.decide(rid, 'approve')
        result = self.broker.requests[rid]['result']
        self.assertEqual(result['matches'][0]['path'], 'secret.txt')

    async def test_listing(self):
        rid = await self.new('list', path='.')
        await self.decide(rid, 'approve')
        self.assertEqual(self.broker.requests[rid]['result']['entries'][0]['name'], 'secret.txt')

    async def test_agent_cannot_access_admin_password(self):
        if not self.uid_isolation:
            self.skipTest('Distinct UIDs unavailable in this host workspace')
        code = 'import os,sys;os.setgroups([]);os.setgid(21001);os.setuid(21001);open(sys.argv[1]).read()'
        proc = await asyncio.create_subprocess_exec(sys.executable, '-c', code,
            str(d.STATE / 'admin-password'), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        out, err = await proc.communicate()
        self.assertNotEqual(proc.returncode, 0)
        self.assertNotIn(self.broker.password.encode(), out)
        self.assertIn(b'PermissionError', err)

    async def test_launcher_drops_uid_and_capabilities(self):
        if not self.uid_isolation:
            self.skipTest('Distinct UIDs unavailable in this host workspace')
        command = ['sh', '-c', 'id -u; sed -n "/^CapEff:/p; /^NoNewPrivs:/p" /proc/self/status']
        env = {**os.environ, 'DEVBOX_STATE': str(d.STATE), 'DEVBOX_RUN': str(d.RUN)}
        proc = await asyncio.create_subprocess_exec(sys.executable, str(d.HERE / 'devbox.py'),
            'as-agent', 'claude', *command, env=env,
            stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        out, err = await proc.communicate()
        self.assertEqual(proc.returncode, 0, err.decode())
        text = out.decode()
        self.assertIn('21001', text)
        self.assertRegex(text, r'CapEff:\s*0+\b')
        self.assertRegex(text, r'NoNewPrivs:\s*1')

    async def test_authenticated_terminal_http_and_websocket_proxy(self):
        if not self.uid_isolation:
            self.skipTest('Unix sockets unavailable in this host workspace')
        async def backend(request):
            if request.path.endswith('/ws'):
                ws = web.WebSocketResponse()
                await ws.prepare(request)
                async for message in ws:
                    if message.type == d.WSMsgType.TEXT:
                        await ws.send_str(message.data)
                    else:
                        break
                return ws
            return web.Response(text='Terminal backend fixture')
        app = web.Application()
        app.router.add_get('/terminal/{tail:.*}', backend)
        runner = web.AppRunner(app)
        await runner.setup()
        await web.UnixSite(runner, str(d.RUN / 'private/ttyd.sock')).start()
        try:
            async with self.client.get(self.url + '/terminal/') as response:
                self.assertEqual(await response.text(), 'Terminal backend fixture')
            async with self.client.ws_connect(self.url + '/terminal/ws', headers={'Origin': self.url}) as ws:
                await ws.send_str('live terminal echo')
                result = await asyncio.wait_for(ws.receive(), 3)
                self.assertEqual(result.data, 'live terminal echo')
        finally:
            await runner.cleanup()


class LimitTests(unittest.TestCase):
    """Limits default to unlimited (0); a positive value still caps."""

    def setUp(self):
        self.temp = tempfile.TemporaryDirectory(prefix='devbox-limits-')
        self.old = d.DRIVES, d.CFG
        d.DRIVES = Path(self.temp.name)
        (d.DRIVES / 'c').mkdir()
        (d.DRIVES / 'c/big.bin').write_bytes(b'x' * 6000000)
        d.CFG = d.load_config()

    def tearDown(self):
        d.DRIVES, d.CFG = self.old
        self.temp.cleanup()

    def test_defaults_are_unlimited(self):
        for key in ('max_file_bytes', 'max_entries', 'search_max_files', 'search_max_bytes'):
            self.assertEqual(d.CFG[key], 0, key)

    def test_large_read_allowed_by_default(self):
        data, _ = d.read_file('c', 'big.bin')
        self.assertEqual(len(data), 6000000)

    def test_configured_cap_still_applies(self):
        d.CFG['max_file_bytes'] = 1000
        with self.assertRaises(ValueError):
            d.read_file('c', 'big.bin')

    def test_search_without_file_cap(self):
        for i in range(300):
            (d.DRIVES / 'c' / f'f{i}.txt').write_text('needle\n')
        result = d.execute({'op': 'search', 'drive': 'c', 'path': '.', 'query': 'needle'})
        self.assertEqual(len(result['matches']), 300)
        self.assertFalse(result['truncated'])


def run():
    if Path('/proc/self/uid_map').read_text().split() == ['0', '0', '1']:
        print('Portable handler/filesystem mode: this host maps only UID 0. '
              'Real process-identity and socket integration checks require docker run IMAGE self-test.', flush=True)
    suite = unittest.TestSuite([unittest.defaultTestLoader.loadTestsFromTestCase(SecurityTests),
                                unittest.defaultTestLoader.loadTestsFromTestCase(LimitTests)])
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    if result.skipped and os.environ.get('DEVBOX_PORTABLE_TESTS') != '1':
        print('FAIL: full UID isolation tests were skipped. Use a Docker host with mapped agent UIDs.', file=sys.stderr)
        return 1
    return 0 if result.wasSuccessful() else 1


if __name__ == '__main__':
    sys.exit(run())


SELFTEST_PY

<span class="k">COPY</span><span class="s"> &lt;&lt;'DEFAULTS_JSON' /opt/devbox/defaults.json</span>
{
  "max_file_bytes": 0,
  "max_entries": 0,
  "search_max_files": 0,
  "search_max_bytes": 0,
  "approval_timeout_seconds": 600,
  "notify_interval_seconds": 5,
  "web_port": 8090,
  "require_mounts": true,
  "approval_totp_secret": "",
  "openwebui_url": "",
  "openwebui_model": "",
  "launch_commands": {
    "codex": [
      "codex",
      "--ask-for-approval", "on-request",
      "-c", "default_permissions=\"host-broker\"",
      "-c", "permissions.host-broker.extends=\":workspace\"",
      "-c", "features.network_proxy=true",
      "-c", "permissions.host-broker.network.enabled=true",
      "-c", "permissions.host-broker.network.unix_sockets={\"/run/devbox/agent.sock\"=\"allow\"}"
    ]
  }
}

DEFAULTS_JSON

<span class="k">COPY</span><span class="s"> &lt;&lt;'AGENT_BASHRC' /opt/devbox/agent.bashrc</span>
export PS1='\[\e[32m\]${DEVBOX_AGENT}@devbox\[\e[0m\]:\w\$ '
agent-start() {
  /usr/bin/python3 /opt/devbox/devbox.py agent-start
}
agent-login() {
  case "$DEVBOX_AGENT" in
    claude) claude auth login ;;
    codex) codex login --device-auth ;;
    grok) grok login --device-auth ;;
    agy) agy ;;
    opencode) printf '%s\n' 'OpenCode uses the Open WebUI runtime settings. Run agent-start.' ;;
    pi) printf '%s\n' 'Run agent-start, then /login inside Pi.' ;;
    qwen) printf '%s\n' 'Run agent-start, then complete /auth inside Qwen Code.' ;;
  esac
}
printf '\n%s\n' "Agent: $DEVBOX_AGENT. Host access: hostctl --help. Login: agent-login. Reopen: agent-start."
printf '%s\n' 'Host operations wait for your approval at the browser dashboard.'
agent-start


AGENT_BASHRC

<span class="k">RUN </span><span class="o">&lt;&lt;</span><span class="sh">'</span><span class="no">WRAPPERS</span><span class="sh">'</span>
set -eu
cat &gt; /usr/local/bin/devbox &lt;&lt;'SH'
#!/bin/sh
exec /usr/bin/python3 /opt/devbox/devbox.py "$@"
SH
cat &gt; /usr/local/bin/devbox-pane &lt;&lt;'SH'
#!/bin/sh
exec /usr/bin/python3 /opt/devbox/devbox.py pane
SH
cat &gt; /usr/local/bin/hostctl &lt;&lt;'SH'
#!/bin/sh
exec /usr/bin/python3 /opt/devbox/devbox.py host "$@"
SH
cat &gt; /usr/local/bin/teamctl &lt;&lt;'SH'
#!/bin/sh
exec /usr/bin/python3 /opt/devbox/devbox.py team "$@"
SH
cat &gt; /usr/local/bin/print-browser-url &lt;&lt;'SH'
#!/bin/sh
printf '\nOpen this URL in your host browser:\n'
printf '%s\n' "$@"
SH
chmod 0755 /usr/local/bin/devbox /usr/local/bin/devbox-pane \
    /usr/local/bin/hostctl /usr/local/bin/teamctl /usr/local/bin/print-browser-url
<span class="c"># Root-owned managed policy: Claude Code must always ask before relaying an approval.</span>
install -d -m 0755 /etc/claude-code
cat &gt; /etc/claude-code/managed-settings.json &lt;&lt;'JSON'
{"permissions": {"defaultMode": "default",
 "allow": [
  "Bash(hostctl list *)", "Bash(hostctl read *)", "Bash(hostctl search *)",
  "Bash(hostctl write *)", "Bash(hostctl pending)", "Bash(hostctl pending *)",
  "Bash(teamctl status)", "Bash(teamctl read *)"],
 "ask": [
  "Bash(hostctl approve *)", "Bash(hostctl preview *)",
  "Bash(devbox host approve *)", "Bash(devbox host preview *)",
  "Bash(*devbox.py host approve*)", "Bash(*devbox.py host preview*)"]}}
JSON
chmod 0644 /etc/claude-code/managed-settings.json
python3 -m py_compile /opt/devbox/devbox.py /opt/devbox/selftest.py
bash -n /opt/devbox/agent.bashrc
{
    node --version
    herdr --version
    claude --version
    codex --version
    agy --version
    grok --version
    opencode --version
    pi --version
    qwen --version
    ttyd --version
} &gt; /opt/devbox/versions.txt
<span class="c"># Full tests run inside the build; skips fail unless explicitly enabled for local development.</span>
python3 /opt/devbox/devbox.py self-test
WRAPPERS
<span class="k">WORKDIR</span><span class="s"> /state</span>
<span class="k">EXPOSE</span><span class="s"> 8090 4096</span>
<span class="k">STOPSIGNAL</span><span class="s"> SIGTERM</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["/usr/bin/tini", "-s", "--", "/usr/local/bin/devbox"]</span>
<span class="k">CMD</span><span class="s"> ["start"]</span>
</code></pre></div></div>

<h3 id="buildsh"><code class="language-plaintext highlighter-rouge">build.sh</code></h3>

<p>Prepares the seccomp profile, builds the image, and runs the self-test.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env bash</span>
<span class="nb">set</span> <span class="nt">-Eeuo</span> pipefail

<span class="nv">script_dir</span><span class="o">=</span><span class="s2">"</span><span class="si">$(</span><span class="nb">cd</span> <span class="nt">--</span> <span class="s2">"</span><span class="si">$(</span><span class="nb">dirname</span> <span class="nt">--</span> <span class="s2">"</span><span class="k">${</span><span class="nv">BASH_SOURCE</span><span class="p">[0]</span><span class="k">}</span><span class="s2">"</span><span class="si">)</span><span class="s2">"</span> <span class="o">&amp;&amp;</span> <span class="nb">pwd</span><span class="si">)</span><span class="s2">"</span>
<span class="nv">image</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">DEVBOX_IMAGE</span><span class="k">:-</span><span class="nv">herdr</span><span class="p">-devbox</span><span class="k">}</span><span class="s2">"</span>

python3 <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">/prepare-seccomp.py"</span>

<span class="nb">command</span> <span class="nt">-v</span> docker <span class="o">&gt;</span>/dev/null 2&gt;&amp;1 <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'Docker is not installed or is not on PATH.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>
<span class="o">[[</span> <span class="nt">-f</span> <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">/Dockerfile"</span> <span class="o">]]</span> <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'Place build.sh beside Dockerfile.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>
docker info <span class="o">&gt;</span>/dev/null

docker build <span class="nt">--pull</span> <span class="nt">--tag</span> <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="nt">--file</span> <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">/Dockerfile"</span> <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">"</span>
docker run <span class="nt">--rm</span> <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> self-test
<span class="nb">printf</span> <span class="s1">'\nFile/search limits default to unlimited (0); override via DEVBOX_CONFIG.'</span>
<span class="nb">printf</span> <span class="s1">'\nBuilt and checked %s. Start it with: bash %q/run.sh\n'</span> <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">"</span>
</code></pre></div></div>

<h3 id="runsh"><code class="language-plaintext highlighter-rouge">run.sh</code></h3>

<p>Asks for settings, starts the container, and prints the secrets.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env bash</span>
<span class="nb">set</span> <span class="nt">-Eeuo</span> pipefail

<span class="nv">image</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">DEVBOX_IMAGE</span><span class="k">:-</span><span class="nv">herdr</span><span class="p">-devbox</span><span class="k">}</span><span class="s2">"</span>
<span class="nv">container</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">DEVBOX_CONTAINER</span><span class="k">:-</span><span class="nv">herdr</span><span class="p">-devbox</span><span class="k">}</span><span class="s2">"</span>
<span class="nv">state_volume</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">DEVBOX_VOLUME</span><span class="k">:-</span><span class="nv">herdr</span><span class="p">-devbox-state</span><span class="k">}</span><span class="s2">"</span>

<span class="nv">script_dir</span><span class="o">=</span><span class="s2">"</span><span class="si">$(</span><span class="nb">cd</span> <span class="nt">--</span> <span class="s2">"</span><span class="si">$(</span><span class="nb">dirname</span> <span class="nt">--</span> <span class="s2">"</span><span class="k">${</span><span class="nv">BASH_SOURCE</span><span class="p">[0]</span><span class="k">}</span><span class="s2">"</span><span class="si">)</span><span class="s2">"</span> <span class="o">&amp;&amp;</span> <span class="nb">pwd</span><span class="si">)</span><span class="s2">"</span>

<span class="k">if</span> <span class="o">[[</span> <span class="o">!</span> <span class="nt">-r</span> <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">/herdr-seccomp.json"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">printf</span> <span class="s1">'Missing seccomp profile: %s/herdr-seccomp.json\n'</span> <span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">"</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="k">fi

</span><span class="nb">command</span> <span class="nt">-v</span> docker <span class="o">&gt;</span>/dev/null 2&gt;&amp;1 <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'Docker is not installed or is not on PATH.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>
<span class="nb">command</span> <span class="nt">-v</span> mountpoint <span class="o">&gt;</span>/dev/null 2&gt;&amp;1 <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'Run this script in WSL with the mountpoint utility installed.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>
docker info <span class="o">&gt;</span>/dev/null
docker image inspect <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="o">&gt;</span>/dev/null 2&gt;&amp;1 <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'Image %s was not found. Run bash build.sh first.\n'</span> <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>

<span class="k">for </span>drive <span class="k">in </span>c<span class="p">;</span> <span class="k">do
  if</span> <span class="o">!</span> mountpoint <span class="nt">-q</span> <span class="s2">"/mnt/</span><span class="nv">$drive</span><span class="s2">"</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">printf</span> <span class="s1">'Missing drive mount: /mnt/%s. Mount the actual drive/share in WSL first.\n'</span> <span class="s2">"</span><span class="nv">$drive</span><span class="s2">"</span> <span class="o">&gt;</span>&amp;2
    <span class="nb">exit </span>1
  <span class="k">fi
done</span>

<span class="c"># Prevent inherited shell tracing from revealing the API key during expansion.</span>
<span class="nb">set</span> +x
<span class="nb">trap</span> <span class="s1">'unset OPENWEBUI_API_KEY'</span> EXIT

<span class="c"># Open WebUI settings are cached inside the state volume (/state/secrets, root-only, so no</span>
<span class="c"># agent can read them). Later starts only ask whether to change them.</span>
<span class="nv">OPENWEBUI_URL</span><span class="o">=</span><span class="s1">''</span>
<span class="nv">OPENWEBUI_MODEL</span><span class="o">=</span><span class="s1">''</span>
<span class="nv">OPENWEBUI_API_KEY</span><span class="o">=</span><span class="s1">''</span>
<span class="nv">cached</span><span class="o">=()</span>

devbox_py<span class="o">()</span> <span class="o">{</span>
  <span class="c"># Runs a devbox.py helper against the state volume; names passed via -e keep the key off the command line.</span>
  docker run <span class="nt">--rm</span> <span class="nt">--entrypoint</span> /usr/bin/python3 <span class="nt">--security-opt</span> no-new-privileges<span class="o">=</span><span class="nb">true</span> <span class="se">\</span>
    <span class="nt">--mount</span> <span class="s2">"type=volume,src=</span><span class="nv">$state_volume</span><span class="s2">,dst=/state"</span> <span class="s2">"</span><span class="nv">$@</span><span class="s2">"</span>
<span class="o">}</span>

<span class="c"># Lists the endpoint's models (the OpenCode and Pi plugins expose all of them; this only picks</span>
<span class="c"># the startup default). Uses what you just typed, or the cached URL/key for whatever you left unset.</span>
pick_model<span class="o">()</span> <span class="o">{</span>
  <span class="nb">local </span><span class="nv">env_args</span><span class="o">=()</span> <span class="nv">models</span><span class="o">=()</span> choice i
  <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_URL</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="o">{</span> <span class="nb">export </span>OPENWEBUI_URL<span class="p">;</span> env_args+<span class="o">=(</span><span class="nt">-e</span> OPENWEBUI_URL<span class="o">)</span><span class="p">;</span> <span class="o">}</span>
  <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_API_KEY</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="o">{</span> <span class="nb">export </span>OPENWEBUI_API_KEY<span class="p">;</span> env_args+<span class="o">=(</span><span class="nt">-e</span> OPENWEBUI_API_KEY<span class="o">)</span><span class="p">;</span> <span class="o">}</span>
  <span class="k">if</span> <span class="o">!</span> <span class="nb">mapfile</span> <span class="nt">-t</span> models &lt; &lt;<span class="o">(</span>devbox_py <span class="s2">"</span><span class="k">${</span><span class="nv">env_args</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> /opt/devbox/devbox.py openwebui-models 2&gt;/dev/null<span class="o">)</span> <span class="se">\</span>
      <span class="o">||</span> <span class="o">((</span><span class="k">${#</span><span class="nv">models</span><span class="p">[@]</span><span class="k">}</span> <span class="o">==</span> 0<span class="o">))</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">printf</span> <span class="s1">'Could not list models from the endpoint; enter the model ID by hand.\n'</span> <span class="o">&gt;</span>&amp;2
    <span class="k">return </span>1
  <span class="k">fi
  </span><span class="nb">printf</span> <span class="s1">'\nModels available on the endpoint (%d):\n'</span> <span class="s2">"</span><span class="k">${#</span><span class="nv">models</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span>
  <span class="k">for </span>i <span class="k">in</span> <span class="s2">"</span><span class="k">${</span><span class="p">!models[@]</span><span class="k">}</span><span class="s2">"</span><span class="p">;</span> <span class="k">do</span>
    <span class="o">((</span>i &lt; 40<span class="o">))</span> <span class="o">&amp;&amp;</span> <span class="nb">printf</span> <span class="s1">'  %2d) %s\n'</span> <span class="s2">"</span><span class="k">$((</span>i <span class="o">+</span> <span class="m">1</span><span class="k">))</span><span class="s2">"</span> <span class="s2">"</span><span class="k">${</span><span class="nv">models</span><span class="p">[i]</span><span class="k">}</span><span class="s2">"</span>
  <span class="k">done</span>
  <span class="o">((</span><span class="k">${#</span><span class="nv">models</span><span class="p">[@]</span><span class="k">}</span> <span class="o">&gt;</span> 40<span class="o">))</span> <span class="o">&amp;&amp;</span> <span class="nb">printf</span> <span class="s1">'  ... and %d more (type an ID to use one of them)\n'</span> <span class="s2">"</span><span class="k">$((${#</span><span class="nv">models</span><span class="p">[@]</span><span class="k">}</span> <span class="o">-</span> <span class="m">40</span><span class="k">))</span><span class="s2">"</span>
  <span class="k">while </span><span class="nb">true</span><span class="p">;</span> <span class="k">do
    </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s2">"Default model [number or exact ID</span><span class="k">${</span><span class="nv">OPENWEBUI_MODEL</span>:+,<span class="p"> Enter keeps </span><span class="nv">$OPENWEBUI_MODEL</span><span class="k">}</span><span class="s2">]: "</span> choice
    <span class="k">if</span> <span class="o">[[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="nv">$choice</span><span class="s2">"</span> <span class="o">&amp;&amp;</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_MODEL</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
      return </span>0
    <span class="k">elif</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$choice</span><span class="s2">"</span> <span class="o">=</span>~ ^[0-9]+<span class="nv">$ </span><span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="o">((</span>choice <span class="o">&gt;=</span> 1 <span class="o">&amp;&amp;</span> choice &lt;<span class="o">=</span> <span class="k">${#</span><span class="nv">models</span><span class="p">[@]</span><span class="k">}</span><span class="o">))</span><span class="p">;</span> <span class="k">then
      </span><span class="nv">OPENWEBUI_MODEL</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">models</span><span class="p">[choice - 1]</span><span class="k">}</span><span class="s2">"</span>
      <span class="k">return </span>0
    <span class="k">elif</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$choice</span><span class="s2">"</span> <span class="o">=</span>~ <span class="o">[</span>^[:space:]] <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="nb">printf</span> <span class="s1">'%s\n'</span> <span class="s2">"</span><span class="k">${</span><span class="nv">models</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> | <span class="nb">grep</span> <span class="nt">-qxF</span> <span class="nt">--</span> <span class="s2">"</span><span class="nv">$choice</span><span class="s2">"</span><span class="p">;</span> <span class="k">then
      </span><span class="nv">OPENWEBUI_MODEL</span><span class="o">=</span><span class="s2">"</span><span class="nv">$choice</span><span class="s2">"</span>
      <span class="k">return </span>0
    <span class="k">fi
    </span><span class="nb">printf</span> <span class="s1">'Choose a listed number or an exact model ID.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="k">done</span>
<span class="o">}</span>

<span class="k">if </span><span class="nb">mapfile</span> <span class="nt">-t</span> cached &lt; &lt;<span class="o">(</span>devbox_py <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> /opt/devbox/devbox.py openwebui-show 2&gt;/dev/null<span class="o">)</span> <span class="o">&amp;&amp;</span> <span class="o">((</span><span class="k">${#</span><span class="nv">cached</span><span class="p">[@]</span><span class="k">}</span> <span class="o">==</span> 3<span class="o">))</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">printf</span> <span class="s1">'Saved Open WebUI settings:\n  URL:   %s\n  Model: %s\n  Key:   (saved, hidden)\n'</span> <span class="s2">"</span><span class="k">${</span><span class="nv">cached</span><span class="p">[0]</span><span class="k">}</span><span class="s2">"</span> <span class="s2">"</span><span class="k">${</span><span class="nv">cached</span><span class="p">[1]</span><span class="k">}</span><span class="s2">"</span>
  <span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s1">'Change them? [y/N]: '</span> change
  <span class="k">if</span> <span class="o">[[</span> <span class="o">!</span> <span class="s2">"</span><span class="nv">$change</span><span class="s2">"</span> <span class="o">=</span>~ ^[Yy] <span class="o">]]</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s1">'Pick a different default model from the endpoint? [y/N]: '</span> repick
    <span class="k">if</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$repick</span><span class="s2">"</span> <span class="o">=</span>~ ^[Yy] <span class="o">]]</span><span class="p">;</span> <span class="k">then
      </span><span class="nv">OPENWEBUI_MODEL</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">cached</span><span class="p">[1]</span><span class="k">}</span><span class="s2">"</span>
      pick_model <span class="o">||</span> <span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s1">'Model ID: '</span> OPENWEBUI_MODEL
    <span class="k">fi
    </span><span class="nv">cached</span><span class="o">=(</span>keep<span class="o">)</span>
  <span class="k">fi
else
  </span><span class="nv">cached</span><span class="o">=()</span>
<span class="k">fi

if</span> <span class="o">[[</span> <span class="s2">"</span><span class="k">${</span><span class="nv">cached</span><span class="p">[0]</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">!=</span> keep <span class="o">]]</span><span class="p">;</span> <span class="k">then
  while </span><span class="nb">true</span><span class="p">;</span> <span class="k">do
    </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s2">"Open WebUI URL (for example https://webui.example.org) [</span><span class="k">${</span><span class="nv">cached</span><span class="p">[0]</span><span class="k">:-}</span><span class="s2">]: "</span> OPENWEBUI_URL
    <span class="nv">OPENWEBUI_URL</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">OPENWEBUI_URL</span><span class="k">:-${</span><span class="nv">cached</span><span class="p">[0]</span><span class="k">:-}}</span><span class="s2">"</span>
    <span class="o">[[</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_URL</span><span class="s2">"</span> <span class="o">=</span>~ ^https?://[^[:space:]]+<span class="nv">$ </span><span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="nb">break
    printf</span> <span class="s1">'Enter a complete http:// or https:// URL without spaces.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="k">done
  while </span><span class="nb">true</span><span class="p">;</span> <span class="k">do
    </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-s</span> <span class="nt">-p</span> <span class="s1">'Open WebUI API key (hidden; Enter keeps the saved key if there is one): '</span> OPENWEBUI_API_KEY
    <span class="nb">printf</span> <span class="s1">'\n'</span>
    <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_API_KEY</span><span class="s2">"</span> <span class="o">||</span> <span class="s2">"</span><span class="k">${</span><span class="nv">cached</span><span class="p">[2]</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">==</span> key <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="nb">break
    printf</span> <span class="s1">'The API key cannot be empty.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="k">done
  </span><span class="nv">OPENWEBUI_MODEL</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">cached</span><span class="p">[1]</span><span class="k">:-}</span><span class="s2">"</span>
  <span class="k">if</span> <span class="o">!</span> pick_model<span class="p">;</span> <span class="k">then
    while </span><span class="nb">true</span><span class="p">;</span> <span class="k">do
      </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s2">"Open WebUI model ID (exact identifier) [</span><span class="k">${</span><span class="nv">cached</span><span class="p">[1]</span><span class="k">:-}</span><span class="s2">]: "</span> OPENWEBUI_MODEL
      <span class="nv">OPENWEBUI_MODEL</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">OPENWEBUI_MODEL</span><span class="k">:-${</span><span class="nv">cached</span><span class="p">[1]</span><span class="k">:-}}</span><span class="s2">"</span>
      <span class="o">[[</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_MODEL</span><span class="s2">"</span> <span class="o">=</span>~ <span class="o">[</span>^[:space:]] <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="nb">break
      printf</span> <span class="s1">'The model ID cannot be empty.\n'</span> <span class="o">&gt;</span>&amp;2
    <span class="k">done
  fi
fi</span>
<span class="c"># Only values you entered are passed; anything left unset is loaded from the cached volume copy.</span>
<span class="nv">openwebui_args</span><span class="o">=()</span>
<span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_URL</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="o">{</span> <span class="nb">export </span>OPENWEBUI_URL<span class="p">;</span> openwebui_args+<span class="o">=(</span><span class="nt">-e</span> OPENWEBUI_URL<span class="o">)</span><span class="p">;</span> <span class="o">}</span>
<span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_MODEL</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="o">{</span> <span class="nb">export </span>OPENWEBUI_MODEL<span class="p">;</span> openwebui_args+<span class="o">=(</span><span class="nt">-e</span> OPENWEBUI_MODEL<span class="o">)</span><span class="p">;</span> <span class="o">}</span>
<span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$OPENWEBUI_API_KEY</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="o">{</span> <span class="nb">export </span>OPENWEBUI_API_KEY<span class="p">;</span> openwebui_args+<span class="o">=(</span><span class="nt">-e</span> OPENWEBUI_API_KEY<span class="o">)</span><span class="p">;</span> <span class="o">}</span>
<span class="nb">bind</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">DEVBOX_BIND</span><span class="k">:-</span><span class="nv">127</span><span class="p">.0.0.1</span><span class="k">}</span><span class="s2">"</span>
<span class="c"># Optional: DEVBOX_TOTP_SECRET (base32) fixes the Claude-session approval authenticator secret.</span>
<span class="nv">totp_args</span><span class="o">=()</span>
<span class="k">if</span> <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="k">${</span><span class="nv">DEVBOX_TOTP_SECRET</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">printf</span> <span class="s1">'\nUsing DEVBOX_TOTP_SECRET from your environment; it replaces any saved approval secret.\n'</span>
  <span class="nv">totp_args</span><span class="o">=(</span><span class="nt">-e</span> DEVBOX_TOTP_SECRET<span class="o">)</span>
<span class="k">elif </span>devbox_py <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> /opt/devbox/devbox.py secret-exists totp 2&gt;/dev/null<span class="p">;</span> <span class="k">then</span>
  <span class="c"># The saved secret lives in the root-only state volume, so it survives restarts and rebuilds.</span>
  <span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s1">$'</span><span class="se">\n</span><span class="s1">A saved approval (TOTP) secret exists. Overwrite it? [y/N]: '</span> overwrite
  <span class="k">if</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$overwrite</span><span class="s2">"</span> <span class="o">=</span>~ ^[Yy] <span class="o">]]</span><span class="p">;</span> <span class="k">then
    while </span><span class="nb">true</span><span class="p">;</span> <span class="k">do
      </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-s</span> <span class="nt">-p</span> <span class="s1">'New base32 secret (Enter generates a random one): '</span> DEVBOX_TOTP_SECRET
      <span class="nb">printf</span> <span class="s1">'\n'</span>
      <span class="k">if</span> <span class="o">[[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="nv">$DEVBOX_TOTP_SECRET</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
        </span><span class="nv">totp_args</span><span class="o">=(</span><span class="nt">-e</span> <span class="nv">DEVBOX_TOTP_REGENERATE</span><span class="o">=</span>1<span class="o">)</span>
        <span class="nb">break
      </span><span class="k">elif</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$DEVBOX_TOTP_SECRET</span><span class="s2">"</span> <span class="o">=</span>~ ^[A-Za-z2-7<span class="se">\ </span><span class="o">]{</span>16,<span class="o">}</span><span class="nv">$ </span><span class="o">]]</span><span class="p">;</span> <span class="k">then
        </span><span class="nb">export </span>DEVBOX_TOTP_SECRET
        <span class="nv">totp_args</span><span class="o">=(</span><span class="nt">-e</span> DEVBOX_TOTP_SECRET<span class="o">)</span>
        <span class="nb">break
      </span><span class="k">fi
      </span><span class="nb">printf</span> <span class="s1">'Enter at least 16 base32 characters (A-Z, 2-7), or press Enter to generate one.\n'</span> <span class="o">&gt;</span>&amp;2
    <span class="k">done
  else
    </span><span class="nb">printf</span> <span class="s1">'Keeping the saved approval secret.\n'</span>
  <span class="k">fi
fi</span>

<span class="c"># Dashboard and OpenCode passwords are saved in the state volume the same way. Ask before replacing.</span>
<span class="nv">password_args</span><span class="o">=()</span>
ask_password<span class="o">()</span> <span class="o">{</span>  <span class="c"># label, secret-name, explicit env var, regenerate env var</span>
  <span class="nb">local </span><span class="nv">label</span><span class="o">=</span><span class="s2">"</span><span class="nv">$1</span><span class="s2">"</span> <span class="nv">name</span><span class="o">=</span><span class="s2">"</span><span class="nv">$2</span><span class="s2">"</span> <span class="nv">explicit</span><span class="o">=</span><span class="s2">"</span><span class="nv">$3</span><span class="s2">"</span> <span class="nv">regen</span><span class="o">=</span><span class="s2">"</span><span class="nv">$4</span><span class="s2">"</span> overwrite value
  <span class="k">if</span> <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="k">${</span><span class="p">!explicit</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">printf</span> <span class="s1">'\nUsing %s from your environment; it replaces the saved %s password.\n'</span> <span class="s2">"</span><span class="nv">$explicit</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$label</span><span class="s2">"</span>
    <span class="nb">export</span> <span class="s2">"</span><span class="nv">$explicit</span><span class="s2">"</span>
    password_args+<span class="o">=(</span><span class="nt">-e</span> <span class="s2">"</span><span class="nv">$explicit</span><span class="s2">"</span><span class="o">)</span>
  <span class="k">elif </span>devbox_py <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> /opt/devbox/devbox.py secret-exists <span class="s2">"</span><span class="nv">$name</span><span class="s2">"</span> 2&gt;/dev/null<span class="p">;</span> <span class="k">then
    </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s2">"A saved </span><span class="nv">$label</span><span class="s2"> password exists. Overwrite it? [y/N]: "</span> overwrite
    <span class="k">if</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$overwrite</span><span class="s2">"</span> <span class="o">=</span>~ ^[Yy] <span class="o">]]</span><span class="p">;</span> <span class="k">then
      while </span><span class="nb">true</span><span class="p">;</span> <span class="k">do
        </span><span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-s</span> <span class="nt">-p</span> <span class="s2">"New </span><span class="nv">$label</span><span class="s2"> password (at least 12 characters, no spaces; Enter generates one): "</span> value
        <span class="nb">printf</span> <span class="s1">'\n'</span>
        <span class="k">if</span> <span class="o">[[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="nv">$value</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
          </span>password_args+<span class="o">=(</span><span class="nt">-e</span> <span class="s2">"</span><span class="nv">$regen</span><span class="s2">=1"</span><span class="o">)</span>
          <span class="nb">break
        </span><span class="k">elif</span> <span class="o">[[</span> <span class="k">${#</span><span class="nv">value</span><span class="k">}</span> <span class="nt">-ge</span> 12 <span class="o">&amp;&amp;</span> <span class="o">!</span> <span class="s2">"</span><span class="nv">$value</span><span class="s2">"</span> <span class="o">=</span>~ <span class="o">[[</span>:space:]] <span class="o">]]</span><span class="p">;</span> <span class="k">then
          </span><span class="nb">printf</span> <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$explicit</span><span class="s2">"</span> <span class="s1">'%s'</span> <span class="s2">"</span><span class="nv">$value</span><span class="s2">"</span>
          <span class="nb">export</span> <span class="s2">"</span><span class="nv">$explicit</span><span class="s2">"</span>
          password_args+<span class="o">=(</span><span class="nt">-e</span> <span class="s2">"</span><span class="nv">$explicit</span><span class="s2">"</span><span class="o">)</span>
          <span class="nb">break
        </span><span class="k">fi
        </span><span class="nb">printf</span> <span class="s1">'Use at least 12 characters with no spaces, or press Enter to generate one.\n'</span> <span class="o">&gt;</span>&amp;2
      <span class="k">done
    else
      </span><span class="nb">printf</span> <span class="s1">'Keeping the saved %s password.\n'</span> <span class="s2">"</span><span class="nv">$label</span><span class="s2">"</span>
    <span class="k">fi
  fi</span>
<span class="o">}</span>
ask_password <span class="s1">'dashboard'</span> admin DEVBOX_ADMIN_PASSWORD DEVBOX_ADMIN_REGENERATE
ask_password <span class="s1">'OpenCode'</span> opencode DEVBOX_OPENCODE_PASSWORD DEVBOX_OPENCODE_REGENERATE

<span class="nb">printf</span> <span class="s1">'\nImage: %s\nContainer: %s\n'</span> <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span>

<span class="k">if </span>docker container inspect <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="o">&gt;</span>/dev/null 2&gt;&amp;1<span class="p">;</span> <span class="k">then
  </span><span class="nb">printf</span> <span class="s1">'\nContainer %s already exists.\n'</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span>
  <span class="nb">printf</span> <span class="s1">'Recreating it stops its active jobs and removes its container filesystem.\n'</span>
  <span class="nb">printf</span> <span class="s1">'Agent state in named volume %s is preserved.\n'</span> <span class="s2">"</span><span class="nv">$state_volume</span><span class="s2">"</span>
  <span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-p</span> <span class="s2">"Type recreate to stop and remove </span><span class="nv">$container</span><span class="s2">, then apply these settings: "</span> answer
  <span class="k">if</span> <span class="o">[[</span> <span class="s2">"</span><span class="nv">$answer</span><span class="s2">"</span> <span class="o">!=</span> recreate <span class="o">]]</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">printf</span> <span class="s1">'Cancelled. The existing container was left untouched.\n'</span>
    <span class="nb">exit </span>0
  <span class="k">fi
  </span>docker stop <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="o">&gt;</span>/dev/null
  docker <span class="nb">rm</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="o">&gt;</span>/dev/null
<span class="k">fi

</span><span class="nb">printf</span> <span class="s1">'\nDashboard: http://%s:8090 (bind address from DEVBOX_BIND)\n'</span> <span class="s2">"</span><span class="nv">$bind</span><span class="s2">"</span>
<span class="nb">printf</span> <span class="s1">'The devbox will print the dashboard password when startup completes.\n\n'</span>

<span class="c"># Passing variable names keeps the key out of Docker command-line arguments.</span>
<span class="c"># Docker receives it from this process environment. The devbox persists its</span>
<span class="c"># generated OpenCode configuration in the private state volume.</span>
docker run <span class="nt">-d</span> <span class="nt">--restart</span> unless-stopped <span class="nt">--name</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">--security-opt</span> no-new-privileges<span class="o">=</span><span class="nb">true</span> <span class="se">\</span>
  <span class="nt">--security-opt</span> <span class="nv">seccomp</span><span class="o">=</span><span class="s2">"</span><span class="nv">$script_dir</span><span class="s2">/herdr-seccomp.json"</span> <span class="se">\</span>
  <span class="nt">--mount</span> <span class="s2">"type=volume,src=</span><span class="nv">$state_volume</span><span class="s2">,dst=/state"</span> <span class="se">\</span>
  <span class="nt">--mount</span> <span class="nb">type</span><span class="o">=</span><span class="nb">bind</span>,src<span class="o">=</span>/mnt/c,dst<span class="o">=</span>/host-private/c <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$bind</span><span class="s2">:8090:8090"</span> <span class="se">\</span>
  <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$bind</span><span class="s2">:4096:4096"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">openwebui_args</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">totp_args</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">password_args</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span>

<span class="k">for </span>_ <span class="k">in</span> <span class="si">$(</span><span class="nb">seq </span>1 60<span class="si">)</span><span class="p">;</span> <span class="k">do
  </span>docker <span class="nb">exec</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="nb">test</span> <span class="nt">-s</span> /state/secrets/approval-totp 2&gt;/dev/null <span class="o">&amp;&amp;</span> <span class="nb">break
  sleep </span>1
<span class="k">done</span>
<span class="c"># Always show the approval secret, wherever it came from; fall back to reading the volume directly.</span>
<span class="nv">totp_secret</span><span class="o">=</span><span class="s2">"</span><span class="si">$(</span>docker <span class="nb">exec</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="nb">cat</span> /state/secrets/approval-totp 2&gt;/dev/null <span class="o">||</span>
  devbox_py <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="nt">-c</span> <span class="s2">"print(open('/state/secrets/approval-totp').read().strip())"</span> 2&gt;/dev/null <span class="o">||</span> <span class="nb">true</span><span class="si">)</span><span class="s2">"</span>
<span class="nb">printf</span> <span class="s1">'\nClaude approval authenticator secret (base32):\n%s\n'</span> <span class="s2">"</span><span class="k">${</span><span class="nv">totp_secret</span><span class="k">:-</span><span class="p">(unavailable</span>:<span class="p"> run docker logs </span><span class="nv">$container</span><span class="p">)</span><span class="k">}</span><span class="s2">"</span>
<span class="k">if</span> <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$totp_secret</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">printf</span> <span class="s1">'\nURI: otpauth://totp/HerdR%%20devbox:approvals?secret=%s&amp;issuer=HerdR%%20devbox\n'</span> <span class="s2">"</span><span class="nv">$totp_secret</span><span class="s2">"</span>
<span class="k">fi
</span>show_secret<span class="o">()</span> <span class="o">{</span>  <span class="c"># path inside the volume; falls back to reading the volume directly</span>
  docker <span class="nb">exec</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span> <span class="nb">cat</span> <span class="s2">"</span><span class="nv">$1</span><span class="s2">"</span> 2&gt;/dev/null <span class="o">||</span>
    devbox_py <span class="s2">"</span><span class="nv">$image</span><span class="s2">"</span> <span class="nt">-c</span> <span class="s2">"import sys;print(open(sys.argv[1]).read().strip())"</span> <span class="s2">"</span><span class="nv">$1</span><span class="s2">"</span> 2&gt;/dev/null <span class="o">||</span>
    <span class="nb">printf</span> <span class="s1">'(unavailable: see docker logs %s)'</span> <span class="s2">"</span><span class="nv">$container</span><span class="s2">"</span>
<span class="o">}</span>
<span class="nb">printf</span> <span class="s1">'\nHerdr Admin (http://localhost:8090) password: %s\n'</span> <span class="s2">"</span><span class="si">$(</span>show_secret /state/admin-password<span class="si">)</span><span class="s2">"</span>
<span class="nb">printf</span> <span class="s1">'\nOpencode (http://localhost:4096, username opencode) password: %s\n'</span> <span class="s2">"</span><span class="si">$(</span>show_secret /state/secrets/opencode-password<span class="si">)</span><span class="s2">"</span>
</code></pre></div></div>

<h3 id="attachsh"><code class="language-plaintext highlighter-rouge">attach.sh</code></h3>

<p>Attaches Herdr to the running container.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/bin/bash</span>
<span class="nb">echo</span> <span class="s2">"Detach with Ctrl+B, then Q. The background container keeps running."</span>
docker <span class="nb">exec</span> <span class="nt">-it</span> herdr-devbox /usr/local/bin/devbox attach
</code></pre></div></div>

<h3 id="prepare-seccomppy"><code class="language-plaintext highlighter-rouge">prepare-seccomp.py</code></h3>

<p>Creates the seccomp profile that lets bubblewrap work.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#!/usr/bin/env python3
</span><span class="s">"""Create a candidate Docker profile for Bubblewrap; never overwrite a file.

Start from Moby's published default, retain its default-deny policy and all
existing rules, then allow six namespace and mount syscalls. This broadens
kernel exposure for every process in the container, not only Codex. Kernel
namespace ownership and capability checks still apply. Validate in a disposable
container before using it with host mounts. This is not a security certification.
"""</span>
<span class="kn">import</span> <span class="nn">argparse</span>
<span class="kn">import</span> <span class="nn">hashlib</span>
<span class="kn">import</span> <span class="nn">json</span>
<span class="kn">from</span> <span class="nn">pathlib</span> <span class="kn">import</span> <span class="n">Path</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">traceback</span>
<span class="kn">import</span> <span class="nn">urllib.request</span>

<span class="n">HERE</span> <span class="o">=</span> <span class="n">Path</span><span class="p">(</span><span class="n">__file__</span><span class="p">).</span><span class="n">resolve</span><span class="p">().</span><span class="n">parent</span>


<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="p">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="n">__doc__</span><span class="p">)</span>
    <span class="n">parser</span><span class="p">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">'--base'</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">Path</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">'Use an existing upstream default JSON instead of the cached or downloaded one'</span><span class="p">)</span>
    <span class="n">parser</span><span class="p">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">'--output'</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">Path</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">HERE</span> <span class="o">/</span> <span class="s">'herdr-seccomp.json'</span><span class="p">)</span>
    <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="p">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">args</span><span class="p">.</span><span class="n">output</span><span class="p">.</span><span class="n">exists</span><span class="p">():</span>
        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'Skipping, file exists: </span><span class="si">{</span><span class="n">args</span><span class="p">.</span><span class="n">output</span><span class="si">}</span><span class="s">'</span><span class="p">)</span>
        <span class="nb">exit</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">url</span> <span class="o">=</span> <span class="s">'https://raw.githubusercontent.com/moby/profiles/main/seccomp/default.json'</span>
    <span class="n">cache</span> <span class="o">=</span> <span class="n">HERE</span> <span class="o">/</span> <span class="s">'default.json'</span>
    <span class="k">if</span> <span class="n">args</span><span class="p">.</span><span class="n">base</span><span class="p">:</span>
        <span class="n">raw</span> <span class="o">=</span> <span class="n">args</span><span class="p">.</span><span class="n">base</span><span class="p">.</span><span class="n">read_bytes</span><span class="p">()</span>
        <span class="n">source</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">args</span><span class="p">.</span><span class="n">base</span><span class="p">)</span>
    <span class="k">elif</span> <span class="n">cache</span><span class="p">.</span><span class="n">exists</span><span class="p">():</span>
        <span class="n">raw</span> <span class="o">=</span> <span class="n">cache</span><span class="p">.</span><span class="n">read_bytes</span><span class="p">()</span>
        <span class="n">source</span> <span class="o">=</span> <span class="sa">f</span><span class="s">'</span><span class="si">{</span><span class="n">cache</span><span class="si">}</span><span class="s"> (cached)'</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">with</span> <span class="n">urllib</span><span class="p">.</span><span class="n">request</span><span class="p">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
            <span class="n">raw</span> <span class="o">=</span> <span class="n">response</span><span class="p">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1024</span> <span class="o">*</span> <span class="mi">1024</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">raw</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1024</span> <span class="o">*</span> <span class="mi">1024</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">'Upstream profile exceeds 1 MiB'</span><span class="p">)</span>
        <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">raw</span><span class="p">)</span>  <span class="c1"># Validate before caching so a bad download is never reused.
</span>        <span class="k">with</span> <span class="n">cache</span><span class="p">.</span><span class="nb">open</span><span class="p">(</span><span class="s">'xb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">saved</span><span class="p">:</span>
            <span class="n">saved</span><span class="p">.</span><span class="n">write</span><span class="p">(</span><span class="n">raw</span><span class="p">)</span>
        <span class="n">source</span> <span class="o">=</span> <span class="sa">f</span><span class="s">'</span><span class="si">{</span><span class="n">url</span><span class="si">}</span><span class="s"> (downloaded, saved to </span><span class="si">{</span><span class="n">cache</span><span class="si">}</span><span class="s">)'</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">raw</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1024</span> <span class="o">*</span> <span class="mi">1024</span><span class="p">:</span>
        <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">'Upstream profile exceeds 1 MiB'</span><span class="p">)</span>
    <span class="n">profile</span> <span class="o">=</span> <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">raw</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">profile</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">'defaultAction'</span><span class="p">)</span> <span class="o">!=</span> <span class="s">'SCMP_ACT_ERRNO'</span><span class="p">:</span>
        <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">'Expected an upstream default-deny profile'</span><span class="p">)</span>
    <span class="n">rules</span> <span class="o">=</span> <span class="n">profile</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">'syscalls'</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">rules</span><span class="p">,</span> <span class="nb">list</span><span class="p">)</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">rules</span><span class="p">:</span>
        <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">'Missing upstream syscall rules'</span><span class="p">)</span>
    <span class="n">changed</span> <span class="o">=</span> <span class="p">{</span><span class="s">'clone'</span><span class="p">,</span> <span class="s">'unshare'</span><span class="p">,</span> <span class="s">'mount'</span><span class="p">,</span> <span class="s">'umount2'</span><span class="p">,</span> <span class="s">'pivot_root'</span><span class="p">,</span> <span class="s">'setns'</span><span class="p">}</span>
    <span class="k">for</span> <span class="n">rule</span> <span class="ow">in</span> <span class="n">rules</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">changed</span><span class="p">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">rule</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">'names'</span><span class="p">,</span> <span class="p">[]))</span> <span class="ow">and</span> <span class="n">rule</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">'action'</span><span class="p">)</span> <span class="o">!=</span> <span class="s">'SCMP_ACT_ALLOW'</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">'Upstream has a conflicting explicit deny rule; review it manually'</span><span class="p">)</span>
    <span class="c1"># clone3 stays at the upstream policy. The legacy clone interface permits
</span>    <span class="c1"># argument filtering; clone3 passes flags through a pointer, which ordinary
</span>    <span class="c1"># seccomp filters cannot inspect. This candidate targets x86_64/ARM64 only.
</span>    <span class="c1"># Preserve existing clone rules, adding namespace creation except cgroups.
</span>    <span class="n">rules</span><span class="p">.</span><span class="n">append</span><span class="p">({</span><span class="s">'names'</span><span class="p">:</span> <span class="p">[</span><span class="s">'clone'</span><span class="p">],</span> <span class="s">'action'</span><span class="p">:</span> <span class="s">'SCMP_ACT_ALLOW'</span><span class="p">,</span>
                  <span class="s">'args'</span><span class="p">:</span> <span class="p">[{</span><span class="s">'index'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s">'value'</span><span class="p">:</span> <span class="mh">0x02000000</span><span class="p">,</span> <span class="s">'valueTwo'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
                            <span class="s">'op'</span><span class="p">:</span> <span class="s">'SCMP_CMP_MASKED_EQ'</span><span class="p">}]})</span>
    <span class="c1"># Permit user, mount, PID, network, IPC, UTS and SYSVSEM unshare flags.
</span>    <span class="n">permitted</span> <span class="o">=</span> <span class="mh">0x10000000</span> <span class="o">|</span> <span class="mh">0x00020000</span> <span class="o">|</span> <span class="mh">0x20000000</span> <span class="o">|</span> <span class="mh">0x40000000</span> <span class="o">|</span> <span class="mh">0x08000000</span> <span class="o">|</span> <span class="mh">0x04000000</span> <span class="o">|</span> <span class="mh">0x00040000</span>
    <span class="n">rules</span><span class="p">.</span><span class="n">append</span><span class="p">({</span><span class="s">'names'</span><span class="p">:</span> <span class="p">[</span><span class="s">'unshare'</span><span class="p">],</span> <span class="s">'action'</span><span class="p">:</span> <span class="s">'SCMP_ACT_ALLOW'</span><span class="p">,</span>
                  <span class="s">'args'</span><span class="p">:</span> <span class="p">[{</span><span class="s">'index'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s">'value'</span><span class="p">:</span> <span class="p">((</span><span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="mi">64</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">^</span> <span class="n">permitted</span><span class="p">,</span>
                            <span class="s">'valueTwo'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s">'op'</span><span class="p">:</span> <span class="s">'SCMP_CMP_MASKED_EQ'</span><span class="p">}]})</span>
    <span class="n">rules</span><span class="p">.</span><span class="n">append</span><span class="p">({</span><span class="s">'names'</span><span class="p">:</span> <span class="p">[</span><span class="s">'mount'</span><span class="p">,</span> <span class="s">'umount2'</span><span class="p">,</span> <span class="s">'pivot_root'</span><span class="p">,</span> <span class="s">'setns'</span><span class="p">],</span>
                  <span class="s">'action'</span><span class="p">:</span> <span class="s">'SCMP_ACT_ALLOW'</span><span class="p">})</span>
    <span class="k">with</span> <span class="n">args</span><span class="p">.</span><span class="n">output</span><span class="p">.</span><span class="nb">open</span><span class="p">(</span><span class="s">'x'</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s">'utf-8'</span><span class="p">)</span> <span class="k">as</span> <span class="n">output</span><span class="p">:</span>
        <span class="n">json</span><span class="p">.</span><span class="n">dump</span><span class="p">(</span><span class="n">profile</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">indent</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
        <span class="n">output</span><span class="p">.</span><span class="n">write</span><span class="p">(</span><span class="s">'</span><span class="se">\n</span><span class="s">'</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'Created candidate: </span><span class="si">{</span><span class="n">args</span><span class="p">.</span><span class="n">output</span><span class="p">.</span><span class="n">resolve</span><span class="p">()</span><span class="si">}</span><span class="s">'</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'Base SHA256: </span><span class="si">{</span><span class="n">hashlib</span><span class="p">.</span><span class="n">sha256</span><span class="p">(</span><span class="n">raw</span><span class="p">).</span><span class="n">hexdigest</span><span class="p">()</span><span class="si">}</span><span class="s">'</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Base: '</span> <span class="o">+</span> <span class="n">source</span><span class="p">)</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Added permissions: '</span> <span class="o">+</span> <span class="s">', '</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">changed</span><span class="p">)))</span>
    <span class="k">print</span><span class="p">(</span><span class="s">'Test in a disposable container before using with host mounts.'</span><span class="p">)</span>


<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">'__main__'</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">main</span><span class="p">()</span>
    <span class="k">except</span> <span class="nb">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'[prepare-seccomp.main] </span><span class="si">{</span><span class="n">e</span><span class="si">}</span><span class="s">'</span><span class="p">,</span> <span class="nb">file</span><span class="o">=</span><span class="n">sys</span><span class="p">.</span><span class="n">stderr</span><span class="p">)</span>
        <span class="n">traceback</span><span class="p">.</span><span class="n">print_exc</span><span class="p">()</span>
        <span class="n">sys</span><span class="p">.</span><span class="nb">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="totp_generatesh"><code class="language-plaintext highlighter-rouge">totp_generate.sh</code></h3>

<p>Computes the current approval code from the secret.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env bash</span>
<span class="c"># Prompt for the devbox approval TOTP secret (base32 or a pasted otpauth:// URI) and print</span>
<span class="c"># the current six-digit code. Retrieve the secret with:</span>
<span class="c">#   docker exec herdr-devbox cat /state/secrets/approval-totp</span>
<span class="c"># Usage: bash totp_generate.sh [--watch]   (--watch refreshes until Ctrl+C)</span>
<span class="nb">set</span> <span class="nt">-Eeuo</span> pipefail
<span class="nb">set</span> +x

<span class="nb">command</span> <span class="nt">-v</span> python3 <span class="o">&gt;</span>/dev/null 2&gt;&amp;1 <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'python3 is required.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>

<span class="nv">watch</span><span class="o">=</span>0
<span class="o">[[</span> <span class="s2">"</span><span class="k">${</span><span class="nv">1</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">==</span> <span class="s2">"--watch"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="nv">watch</span><span class="o">=</span>1

<span class="nb">read</span> <span class="nt">-r</span> <span class="nt">-s</span> <span class="nt">-p</span> <span class="s1">'TOTP secret (hidden, base32 or otpauth:// URI): '</span> TOTP_SECRET
<span class="nb">printf</span> <span class="s1">'\n'</span>
<span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="nv">$TOTP_SECRET</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">||</span> <span class="o">{</span>
  <span class="nb">printf</span> <span class="s1">'The secret cannot be empty.\n'</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">exit </span>1
<span class="o">}</span>
<span class="nb">export </span>TOTP_SECRET <span class="nv">TOTP_WATCH</span><span class="o">=</span><span class="s2">"</span><span class="nv">$watch</span><span class="s2">"</span>
<span class="nb">trap</span> <span class="s1">'unset TOTP_SECRET'</span> EXIT

<span class="c"># The secret travels in the environment, not on the command line.</span>
python3 <span class="nt">-I</span> - <span class="o">&lt;&lt;</span><span class="sh">'</span><span class="no">PY</span><span class="sh">'
import base64, hashlib, hmac, os, re, struct, sys, time
from urllib.parse import parse_qs, urlsplit

raw = os.environ['TOTP_SECRET'].strip()
if raw.lower().startswith('otpauth://'):
    values = parse_qs(urlsplit(raw).query).get('secret')
    if not values:
        sys.exit('The otpauth URI has no secret parameter.')
    raw = values[0]
secret = re.sub(r'[</span><span class="se">\s</span><span class="sh">-]', '', raw).upper()
try:
    key = base64.b32decode(secret + '=' * (-len(secret) % 8))
except Exception:
    sys.exit('That is not a valid base32 secret.')


def code(counter):
    digest = hmac.new(key, struct.pack('&gt;Q', counter), hashlib.sha1).digest()
    offset = digest[-1] &amp; 15
    return '%06d' % ((struct.unpack('&gt;I', digest[offset:offset + 4])[0] &amp; 0x7fffffff) % 1000000)


def show(end):
    now = time.time()
    print('Code: %s   (valid for about %ds)' % (code(int(now // 30)), 30 - int(now % 30)), end=end, flush=True)


if os.environ.get('TOTP_WATCH') == '1':
    try:
        last = None
        while True:
            counter = int(time.time() // 30)
            if counter != last:
                last = counter
                print()
                show('')
            time.sleep(0.5)
    except KeyboardInterrupt:
        print()
else:
    show('</span><span class="se">\n</span><span class="sh">')
</span><span class="no">PY
</span></code></pre></div></div>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="agentic" /><category term="herdr" /><category term="docker" /><category term="security" /><category term="sandboxing" /><category term="opencode" /><summary type="html"><![CDATA[Coding agents are useful because they can read your files and run commands. That also makes them risky to run on a machine with real data on it. A model can misread an instruction, or a file it opens can contain instructions of its own, and an agent running as you can do anything you can do. I run several agents at once, and each one wants access to the same drives. I’d like them to cooperate without all of them being able to see everything.]]></summary></entry><entry><title type="html">Herding Agents: Multi-Agent Coordination with Herdr and Per-Agent MCP Credentials</title><link href="https://www.billmongan.com/posts/2026/10/herdr-multiagent-mcpproxy/" rel="alternate" type="text/html" title="Herding Agents: Multi-Agent Coordination with Herdr and Per-Agent MCP Credentials" /><published>2026-10-04T00:00:00+00:00</published><updated>2026-10-04T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/10/herdr-multiagent-mcpproxy</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/10/herdr-multiagent-mcpproxy/"><![CDATA[<p>I now run nine coding agents side by side on a small always-on Ubuntu server: Claude Code, Codex, Antigravity, Grok Build, Hermes, GitHub Copilot, two separate copies of OpenCode, and pi. <a href="https://herdr.dev/">Herdr</a> keeps them organized, one labelled tab per agent, and brings them back after a reboot. Most of them share one <a href="/posts/2026/05/mcpproxy/">mcpproxy</a> instance for tools. One of those tools talks to a service that needs a personal API key, and only one agent ever holds that key: a deliberately fenced-in OpenCode. The other agents can see the tool, but they can’t authenticate to the service behind it. When they need that service, they hand the task to that OpenCode through Herdr.</p>

<p>The second OpenCode and pi are the general-purpose half of the setup. Neither holds that key or any other private credential. Both get their models from llmproxy, a small OpenAI-compatible router I run in Docker on the same machine, and both fill in their model lists automatically from it.</p>

<p>This post walks through the whole build from a bare server: installing and signing in to each agent, wiring them into Herdr, running a second, fully isolated OpenCode and pi against llmproxy, making the setup survive a reboot, adding mobile access, running mcpproxy, and finally scoping an MCP credential to a single agent by sending it as a request header instead of storing it in the proxy. Everything here is generic. Substitute your own user, paths, endpoints, and keys, and never paste real credentials into a config file you might share or commit.</p>

<h2 id="the-server">The server</h2>

<p>Any modern x86-64 Linux box with a reasonable amount of RAM will do. Mine is a small mini PC running Ubuntu Server with about 14 GiB of usable memory and some swap. The agents themselves are light, since the models run remotely; most of the memory goes to the Docker services described later.</p>

<p>Start with the basics:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt update
<span class="nb">sudo </span>apt <span class="nb">install</span> <span class="nt">-y</span> curl git ca-certificates build-essential jq tmux openssl
</code></pre></div></div>

<p>Run everything below as your ordinary user, and use <code class="language-plaintext highlighter-rouge">sudo</code> only where shown. I also recommend running each installation step separately and stopping at the first error, rather than pasting a long block and hoping.</p>

<h2 id="installing-herdr-and-the-agents">Installing Herdr and the agents</h2>

<p>Every tool in this section ships a native installer, usually a one-line shell command published on the vendor’s own site or in its official documentation. I’m not reproducing those commands here. Get each one from the vendor’s install page (the references at the end link to the documentation), read the script before piping it to a shell, and install one tool at a time. Native installers mean most of these don’t need a system-wide Node.js, and they generally drop binaries into <code class="language-plaintext highlighter-rouge">~/.local/bin</code> or a tool-specific directory under your home.</p>

<p>Here is what I installed, and what to know about each one.</p>

<p><strong>Herdr</strong> is the terminal multiplexer that knows about agents. Install it first so the integrations step later has something to talk to. HerdrGo, the mobile companion, needs Herdr 0.8.2 or newer.</p>

<p><strong>Claude Code</strong> (Anthropic) installs with a native installer from Anthropic’s setup docs. Its mobile Remote Control feature needs a claude.ai subscription login; API-key authentication doesn’t support it.</p>

<p><strong>Codex</strong> (OpenAI) has a native installer linked from its GitHub repository and OpenAI’s docs. You sign in with a ChatGPT account or an API key.</p>

<p><strong>Antigravity CLI</strong> (Google) installs the <code class="language-plaintext highlighter-rouge">agy</code> command. Its documentation describes a sign-in flow that works over SSH by printing a URL and code to open on another device.</p>

<p><strong>Grok Build</strong> (xAI) installs the <code class="language-plaintext highlighter-rouge">grok</code> command, usually under <code class="language-plaintext highlighter-rouge">~/.grok/bin</code>.</p>

<p><strong>Hermes Agent</strong> (Nous Research) installs <code class="language-plaintext highlighter-rouge">hermes</code> and manages its own runtime dependencies. Its installer may walk you through choosing a model provider and an optional messaging integration. Pick the provider you intend to use; messaging is optional if you only want the terminal agent.</p>

<p><strong>GitHub Copilot CLI</strong> installs <code class="language-plaintext highlighter-rouge">copilot</code> and signs in with your GitHub account.</p>

<p><strong>OpenCode</strong> is the open, provider-agnostic agent in the group. Instead of a vendor subscription, I connect it to an OpenAI-compatible endpoint of my choosing. I use OpenCode V2, which installs under <code class="language-plaintext highlighter-rouge">~/.opencode/bin</code>. One install serves two tabs: a scoped copy that ends up holding the credential later in this post, and a general-purpose copy that runs with its own separate configuration.</p>

<p><strong>pi</strong> is a small, extensible coding agent. I install the standalone Linux release from its GitHub releases page and check the archive against the release’s <code class="language-plaintext highlighter-rouge">SHA256SUMS</code> before unpacking it. The binary doesn’t need Node.js to run, but <code class="language-plaintext highlighter-rouge">pi install npm:...</code> shells out to <code class="language-plaintext highlighter-rouge">npm</code> to fetch packages. I add an npm extension below, so install Node.js and npm first. Ubuntu’s own packages are enough (they gave me Node 22 and npm 9):</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>apt <span class="nb">install</span> <span class="nt">-y</span> nodejs npm
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/.local/share/pi-standalone/VERSION
<span class="nb">sha256sum</span> <span class="nt">-c</span> <span class="nt">--ignore-missing</span> SHA256SUMS      <span class="c"># in the download directory</span>
<span class="nb">tar </span>xzf pi-linux-x64.tar.gz <span class="nt">-C</span> ~/.local/share/pi-standalone/VERSION
<span class="nb">ln</span> <span class="nt">-s</span> ~/.local/share/pi-standalone/VERSION/pi/pi ~/.local/bin/pi
pi <span class="nt">--version</span>
</code></pre></div></div>

<p>pi also has an official install script that manages its own runtime and updates; either route works.</p>

<p>After installing, make the PATH change permanent instead of exporting it in one shell. Adjust the directories to wherever your installers actually put things:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">line</span><span class="o">=</span><span class="s1">'export PATH="$HOME/.opencode/bin:$HOME/.local/bin:$HOME/.grok/bin:$PATH"'</span>
<span class="nb">grep</span> <span class="nt">-qxF</span> <span class="s2">"</span><span class="nv">$line</span><span class="s2">"</span> ~/.bashrc <span class="o">||</span> <span class="nb">printf</span> <span class="s1">'\n%s\n'</span> <span class="s2">"</span><span class="nv">$line</span><span class="s2">"</span> <span class="o">&gt;&gt;</span> ~/.bashrc
<span class="nb">source</span> ~/.bashrc
</code></pre></div></div>

<p>Then confirm that everything resolves:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>herdr <span class="nt">--version</span>
claude <span class="nt">--version</span>
codex <span class="nt">--version</span>
agy <span class="nt">--version</span>
grok <span class="nt">--version</span>
copilot <span class="nt">--version</span>
opencode <span class="nt">--version</span>
pi <span class="nt">--version</span>
hermes <span class="nt">--help</span>
</code></pre></div></div>

<h3 id="a-cpu-quirk-with-antigravity">A CPU quirk with Antigravity</h3>

<p>On my machine, <code class="language-plaintext highlighter-rouge">agy --version</code> aborted immediately with <code class="language-plaintext highlighter-rouge">CRNGT failed</code> from inside BoringCrypto. The cause is the CPU’s hardware random number instruction (RDRAND), which BoringSSL checks and rejects on some processors. Masking that instruction through an OpenSSL capability variable fixed it:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">OPENSSL_ia32cap</span><span class="o">=</span><span class="s1">'~0x4000000000000000'</span> agy <span class="nt">--version</span>
</code></pre></div></div>

<p>A shell function would work interactively, but systemd services and Herdr’s own launches don’t read your <code class="language-plaintext highlighter-rouge">.bashrc</code> functions. A small wrapper script earlier on the PATH is more dependable, and it leaves the installer-managed binary alone:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.local/agy-compat/bin"</span>
<span class="nb">cat</span> <span class="o">&gt;</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.local/agy-compat/bin/agy"</span> <span class="o">&lt;&lt;</span><span class="sh">'</span><span class="no">EOF</span><span class="sh">'
#!/bin/sh
exec env OPENSSL_ia32cap='~0x4000000000000000' "</span><span class="nv">$HOME</span><span class="sh">/.local/bin/agy" "</span><span class="nv">$@</span><span class="sh">"
</span><span class="no">EOF
</span><span class="nb">chmod </span>755 <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.local/agy-compat/bin/agy"</span>

<span class="nv">line</span><span class="o">=</span><span class="s1">'export PATH="$HOME/.local/agy-compat/bin:$PATH"'</span>
<span class="nb">grep</span> <span class="nt">-qxF</span> <span class="s2">"</span><span class="nv">$line</span><span class="s2">"</span> ~/.bashrc <span class="o">||</span> <span class="nb">printf</span> <span class="s1">'\n%s\n'</span> <span class="s2">"</span><span class="nv">$line</span><span class="s2">"</span> <span class="o">&gt;&gt;</span> ~/.bashrc
</code></pre></div></div>

<p>If you don’t see the error, skip this. If you do, remember that the same directory has to appear in the PATH of the systemd service later.</p>

<h2 id="signing-in-to-each-agent">Signing in to each agent</h2>

<p>Launch each agent once by itself, complete its sign-in, and exit before moving to the next. Several of them print a URL or device code for you to open on a phone or laptop, which works fine over SSH.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>claude
codex
agy
grok
hermes
copilot
</code></pre></div></div>

<p>If Hermes still needs a model provider afterwards, <code class="language-plaintext highlighter-rouge">hermes setup</code> (or just <code class="language-plaintext highlighter-rouge">hermes model</code>) reopens that step. OpenCode is the exception here: it gets a configuration file instead of an interactive login, which I cover in its own section below.</p>

<h2 id="herdr-integrations">Herdr integrations</h2>

<p>First launch creates each agent’s configuration directory, and Herdr’s integrations need those directories to exist. Once they do, install an integration for each agent:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>herdr integration <span class="nb">install </span>claude
herdr integration <span class="nb">install </span>codex
herdr integration <span class="nb">install </span>antigravity-cli
herdr integration <span class="nb">install </span>grok
herdr integration <span class="nb">install </span>hermes
herdr integration <span class="nb">install </span>copilot
<span class="nb">mkdir</span> <span class="nt">-p</span> ~/.config/opencode
herdr integration <span class="nb">install </span>opencode
herdr integration <span class="nb">install </span>pi
herdr integration status
</code></pre></div></div>

<p>Note that Antigravity’s integration identifier is <code class="language-plaintext highlighter-rouge">antigravity-cli</code>, not <code class="language-plaintext highlighter-rouge">agy</code>. pi’s integration is an extension under <code class="language-plaintext highlighter-rouge">~/.pi/agent/extensions</code>, which pi loads automatically. Integrations add hooks or plugins to each agent’s own configuration so Herdr can report the agent’s status and session identity. If you’ve already customized an agent’s settings, look at what the integration changes before applying it.</p>

<h2 id="one-tab-per-agent-one-directory-per-agent">One tab per agent, one directory per agent</h2>

<p>Start Herdr once to finish its onboarding, then detach with Ctrl+B followed by Q:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>herdr
</code></pre></div></div>

<p>From an ordinary shell, create a labelled tab for each agent and start the agent in it. Each agent gets its own working directory under <code class="language-plaintext highlighter-rouge">~/agents/&lt;name&gt;</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">(</span>
  <span class="nb">set</span> <span class="nt">-e</span>
  <span class="k">for </span>agent <span class="k">in </span>claude codex agy grok hermes copilot opencode-scoped opencode pi<span class="p">;</span> <span class="k">do
    </span><span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/</span><span class="nv">$agent</span><span class="s2">"</span>
    <span class="nv">response</span><span class="o">=</span><span class="si">$(</span>herdr tab create <span class="se">\</span>
      <span class="nt">--cwd</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/</span><span class="nv">$agent</span><span class="s2">"</span> <span class="nt">--label</span> <span class="s2">"</span><span class="nv">$agent</span><span class="s2">"</span> <span class="nt">--no-focus</span><span class="si">)</span>
    <span class="nv">pane</span><span class="o">=</span><span class="si">$(</span><span class="nb">printf</span> <span class="s1">'%s'</span> <span class="s2">"</span><span class="nv">$response</span><span class="s2">"</span> | jq <span class="nt">-er</span> <span class="s1">'.result.root_pane.pane_id'</span><span class="si">)</span>
    herdr pane run <span class="s2">"</span><span class="nv">$pane</span><span class="s2">"</span> <span class="s2">"</span><span class="k">${</span><span class="nv">agent</span><span class="p">%-scoped</span><span class="k">}</span><span class="s2">"</span>
  <span class="k">done</span>
<span class="o">)</span>
</code></pre></div></div>

<p>Run that loop exactly once. Rerunning it creates duplicate tabs, and the startup launcher described below depends on each label being unique. The label is what tells the two OpenCodes apart: <code class="language-plaintext highlighter-rouge">opencode-scoped</code> is the one that will hold the private environment file, and plain <code class="language-plaintext highlighter-rouge">opencode</code> is the general-purpose copy (a short label leaves more room in the tab bar). Both start here as ordinary OpenCode sessions. Once each is configured below, exit it and start it again with the same command the launcher uses.</p>

<p>If you’re adding the new tabs to an existing setup instead, create only the missing ones with <code class="language-plaintext highlighter-rouge">herdr tab create</code>, and rename an existing tab with <code class="language-plaintext highlighter-rouge">herdr tab rename &lt;tab-id&gt; &lt;label&gt;</code> rather than closing and recreating it.</p>

<p>Separate directories matter more than I expected. Most of these CLIs decide what “resume the latest conversation” means relative to the current directory, and several ask you to trust a workspace before they’ll touch it. One directory per agent keeps those histories and trust decisions apart, and keeps one agent’s scratch files out of another’s way.</p>

<p>A few Herdr keys cover most daily use:</p>

<table>
  <thead>
    <tr>
      <th>Action</th>
      <th>Keys or command</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>New tab</td>
      <td>Ctrl+B, then C</td>
    </tr>
    <tr>
      <td>Next / previous tab</td>
      <td>Ctrl+B, then N / P</td>
    </tr>
    <tr>
      <td>Split right / down</td>
      <td>Ctrl+B, then V / minus</td>
    </tr>
    <tr>
      <td>Detach, leaving everything running</td>
      <td>Ctrl+B, then Q</td>
    </tr>
    <tr>
      <td>Reattach</td>
      <td><code class="language-plaintext highlighter-rouge">herdr</code></td>
    </tr>
    <tr>
      <td>See which agents are running or blocked</td>
      <td><code class="language-plaintext highlighter-rouge">herdr agent list</code></td>
    </tr>
  </tbody>
</table>

<p>Send each agent a short prompt after setting it up so it has a conversation on record to resume later, and detach rather than exiting the agents.</p>

<h2 id="configuring-opencode-for-an-openai-compatible-provider">Configuring OpenCode for an OpenAI-compatible provider</h2>

<p>This section configures the scoped copy, the one in the <code class="language-plaintext highlighter-rouge">opencode-scoped</code> tab. OpenCode’s configuration is global, at <code class="language-plaintext highlighter-rouge">~/.config/opencode/opencode.jsonc</code>, even though I launch it from its own workspace directory. I point it at an OpenAI-compatible endpoint. The API key stays in an environment file, and the config only refers to it by name:</p>

<div class="language-jsonc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"$schema"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://opencode.ai/config.json"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"model"</span><span class="p">:</span><span class="w"> </span><span class="s2">"myprovider/coder"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"providers"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"myprovider"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"My Provider"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"env"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"MYPROVIDER_API_KEY"</span><span class="p">],</span><span class="w">
      </span><span class="nl">"package"</span><span class="p">:</span><span class="w"> </span><span class="s2">"@opencode/ai/providers/openai-compatible"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"settings"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"baseURL"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://llm.example.com/api/v1"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"apiKey"</span><span class="p">:</span><span class="w"> </span><span class="s2">"{env:MYPROVIDER_API_KEY}"</span><span class="w">
      </span><span class="p">},</span><span class="w">
      </span><span class="nl">"models"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"coder"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
          </span><span class="nl">"modelID"</span><span class="p">:</span><span class="w"> </span><span class="s2">"UPSTREAM_MODEL_ID"</span><span class="p">,</span><span class="w">
          </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Coding Model"</span><span class="p">,</span><span class="w">
          </span><span class="nl">"capabilities"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"tools"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w"> </span><span class="nl">"input"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"text"</span><span class="p">],</span><span class="w"> </span><span class="nl">"output"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"text"</span><span class="p">]</span><span class="w"> </span><span class="p">}</span><span class="w">
        </span><span class="p">}</span><span class="w">
      </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The endpoint and model ID aren’t secrets, so I pin them literally in the file. If you also keep copies of them in an environment file for scripts, change both places together whenever the endpoint or model changes, then restart OpenCode.</p>

<p>The environment file is private to OpenCode, created with mode <code class="language-plaintext highlighter-rouge">0600</code>, and never committed anywhere:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">umask </span>077
<span class="nb">mkdir</span> <span class="nt">-p</span> ~/.config/opencode
<span class="nb">touch</span> ~/.config/opencode/service.env
<span class="nb">chmod </span>600 ~/.config/opencode/service.env
nano ~/.config/opencode/service.env
</code></pre></div></div>

<p>For now it holds <code class="language-plaintext highlighter-rouge">MYPROVIDER_API_KEY=...</code>. It gains a second key in the credential-scoping section. A quick test that sources the file the same way Herdr will, without printing the key:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd</span> ~/agents/opencode-scoped
/bin/bash <span class="nt">-c</span> <span class="s1">'
  set -a; source "$HOME/.config/opencode/service.env"; set +a
  test -n "$MYPROVIDER_API_KEY" &amp;&amp; echo "MYPROVIDER_API_KEY=set" || echo "MYPROVIDER_API_KEY=MISSING"
  exec opencode run --standalone "Reply with exactly: PROVIDER_OK"
'</span>
</code></pre></div></div>

<p>If the model answers <code class="language-plaintext highlighter-rouge">PROVIDER_OK</code>, the provider path works.</p>

<h2 id="a-second-general-purpose-opencode-on-llmproxy">A second, general-purpose OpenCode on llmproxy</h2>

<p>I wanted an OpenCode I could point at any model without dragging along the scoped copy’s private environment, MCP connection, or credentials. Running a second copy from the same binary is easy. Keeping it from reading the first copy’s configuration took one more step.</p>

<p>OpenCode always loads its global config from <code class="language-plaintext highlighter-rouge">~/.config/opencode</code>. Pointing <code class="language-plaintext highlighter-rouge">OPENCODE_CONFIG_DIR</code> somewhere else only adds a source on top of it (<code class="language-plaintext highlighter-rouge">opencode debug config</code> lists every source it loaded), so the scoped copy’s provider and MCP headers would still show up. What does work is giving the second copy its own XDG base directories. OpenCode then keeps its config, its stored credentials and session database, its state, and its plugin and model caches under a separate root, and never sees the first copy’s files:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">root</span><span class="o">=</span><span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.local/opencode-general"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$root</span><span class="s2">"</span>/<span class="o">{</span>config,data,state,cache<span class="o">}</span>/opencode
<span class="nb">chmod </span>700 <span class="s2">"</span><span class="nv">$root</span><span class="s2">"</span>
</code></pre></div></div>

<p>The second copy needs a few more things in its own config directory:</p>

<ul>
  <li>Its own copy of Herdr’s OpenCode integration files. <code class="language-plaintext highlighter-rouge">herdr integration install opencode</code> always writes to <code class="language-plaintext highlighter-rouge">~/.config/opencode</code>, so I copy the files it installed there (<code class="language-plaintext highlighter-rouge">plugins/</code>, <code class="language-plaintext highlighter-rouge">herdr-opencode/</code>, <code class="language-plaintext highlighter-rouge">herdr-tui-session.js</code>, <code class="language-plaintext highlighter-rouge">tui.jsonc</code>, and <code class="language-plaintext highlighter-rouge">cli.json</code>) into <code class="language-plaintext highlighter-rouge">$root/config/opencode/</code>. Without them, Herdr can’t report this tab’s state. Re-copy them after a Herdr update changes the integration.</li>
  <li>An <code class="language-plaintext highlighter-rouge">opencode.jsonc</code> with llmproxy as the only provider:</li>
</ul>

<div class="language-jsonc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"$schema"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://opencode.ai/config.json"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"model"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy/default"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"providers"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"llmproxy"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy (local)"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"package"</span><span class="p">:</span><span class="w"> </span><span class="s2">"@opencode/ai/providers/openai-compatible"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"settings"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"baseURL"</span><span class="p">:</span><span class="w"> </span><span class="s2">"http://127.0.0.1:8080/v1"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"apiKey"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy-no-key-required"</span><span class="w">
      </span><span class="p">},</span><span class="w">
      </span><span class="nl">"models"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"default"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
          </span><span class="nl">"modelID"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy/flagship__free"</span><span class="p">,</span><span class="w">
          </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy flagship free (default)"</span><span class="p">,</span><span class="w">
          </span><span class="nl">"capabilities"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"tools"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w"> </span><span class="nl">"input"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"text"</span><span class="p">],</span><span class="w"> </span><span class="nl">"output"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"text"</span><span class="p">]</span><span class="w"> </span><span class="p">}</span><span class="w">
        </span><span class="p">}</span><span class="w">
      </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>My llmproxy listens only on loopback and doesn’t ask clients for a key, so the <code class="language-plaintext highlighter-rouge">apiKey</code> is just a placeholder that llmproxy ignores. The <code class="language-plaintext highlighter-rouge">default</code> entry gives this copy a fixed starting model: llmproxy’s free flagship route. There’s no <code class="language-plaintext highlighter-rouge">mcp</code> block, so this copy has no tools beyond its own.</p>

<p>Listing several thousand models by hand isn’t practical, so I let a plugin do it. <a href="https://github.com/BillJr99/opencode-auto-models">opencode-auto-models</a> calls the provider’s <code class="language-plaintext highlighter-rouge">GET /v1/models</code> at startup and adds every model it reports, keeping manual entries like <code class="language-plaintext highlighter-rouge">default</code> as overrides. Install it with the same environment the tab uses, so it lands in the second copy’s config:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd</span> ~/agents/opencode
<span class="nb">env </span><span class="nv">XDG_CONFIG_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/config"</span> <span class="nv">XDG_DATA_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/data"</span>     <span class="nv">XDG_STATE_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/state"</span> <span class="nv">XDG_CACHE_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/cache"</span>     opencode plugin add github:BillJr99/opencode-auto-models
</code></pre></div></div>

<p>The plugin caches the model list and refreshes it in the background, so a model added to llmproxy shows up on the next start. The discovered models appear a moment after OpenCode starts, which is fine in the interactive tab. A one-shot <code class="language-plaintext highlighter-rouge">opencode run --model ...</code> that names a discovered model immediately can still report it as unavailable, so I test with the default model:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd</span> ~/agents/opencode
<span class="nb">env </span><span class="nv">XDG_CONFIG_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/config"</span> <span class="nv">XDG_DATA_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/data"</span>     <span class="nv">XDG_STATE_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/state"</span> <span class="nv">XDG_CACHE_HOME</span><span class="o">=</span><span class="s2">"</span><span class="nv">$root</span><span class="s2">/cache"</span>     opencode run <span class="nt">--standalone</span> <span class="s2">"Reply with exactly: LLMPROXY_OK"</span>
</code></pre></div></div>

<p>One side effect of moving <code class="language-plaintext highlighter-rouge">XDG_CONFIG_HOME</code>: other tools that OpenCode runs look there too. GitHub CLI is the one I noticed, since it keeps its login under <code class="language-plaintext highlighter-rouge">~/.config/gh</code>. Setting <code class="language-plaintext highlighter-rouge">GH_CONFIG_DIR="$HOME/.config/gh"</code> in the same launch command keeps <code class="language-plaintext highlighter-rouge">gh</code> signed in. Git still reads <code class="language-plaintext highlighter-rouge">~/.gitconfig</code>, so it’s unaffected.</p>

<h2 id="pi-on-llmproxy">pi on llmproxy</h2>

<p>pi gets the same treatment through an extension, which is why it needs npm. <a href="https://www.npmjs.com/package/@billjr99/pi-openai-compat">pi-openai-compat</a> registers OpenAI-compatible endpoints as pi providers, fetches their model lists, and puts the models in pi’s own <code class="language-plaintext highlighter-rouge">/model</code> picker. It has an llmproxy template built in:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pi <span class="nb">install </span>npm:@billjr99/pi-openai-compat
</code></pre></div></div>

<p>Inside pi, <code class="language-plaintext highlighter-rouge">/compat-login</code> walks through choosing llmproxy and fetching its models. You can also write the extension’s config directly, which is what I did. With an empty <code class="language-plaintext highlighter-rouge">cachedModels</code> list, the extension fetches the catalog on the next session start, and a <code class="language-plaintext highlighter-rouge">null</code> key sends no <code class="language-plaintext highlighter-rouge">Authorization</code> header at all. Keep the base URL spelled exactly as the extension’s llmproxy template has it, <code class="language-plaintext highlighter-rouge">http://localhost:8080/v1</code>; a different spelling of the same address gets a one-time notice that the provider is out of date. In <code class="language-plaintext highlighter-rouge">~/.config/pi-openai-compat/config.json</code>, mode <code class="language-plaintext highlighter-rouge">0600</code>:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"previousModel"</span><span class="p">:</span><span class="w"> </span><span class="kc">null</span><span class="p">,</span><span class="w">
  </span><span class="nl">"providers"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"llmproxy"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"displayName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy (local)"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"baseUrl"</span><span class="p">:</span><span class="w"> </span><span class="s2">"http://localhost:8080/v1"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"apiKey"</span><span class="p">:</span><span class="w"> </span><span class="kc">null</span><span class="p">,</span><span class="w">
      </span><span class="nl">"cachedModels"</span><span class="p">:</span><span class="w"> </span><span class="p">[]</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The default model goes in pi’s own settings, <code class="language-plaintext highlighter-rouge">~/.pi/agent/settings.json</code>, so pi starts on the same free flagship route as the general OpenCode. The extension registers each provider under a <code class="language-plaintext highlighter-rouge">compat-</code> prefix, so the provider name here is <code class="language-plaintext highlighter-rouge">compat-llmproxy</code>, not <code class="language-plaintext highlighter-rouge">llmproxy</code>. <code class="language-plaintext highlighter-rouge">pi install</code> adds the <code class="language-plaintext highlighter-rouge">packages</code> entry itself:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"defaultProvider"</span><span class="p">:</span><span class="w"> </span><span class="s2">"compat-llmproxy"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"defaultModel"</span><span class="p">:</span><span class="w"> </span><span class="s2">"llmproxy/flagship__free"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"packages"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"npm:@billjr99/pi-openai-compat"</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>There’s one ordering catch. Until the extension has a cached model list, it registers the provider only when a session starts, which is too late for <code class="language-plaintext highlighter-rouge">pi --list-models</code> or print mode. Start pi once interactively to fill the cache. After that, both work from the command line:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd</span> ~/agents/pi
pi <span class="nt">--list-models</span> flagship__free
pi <span class="nt">--no-session</span> <span class="nt">-p</span> <span class="s2">"Reply with exactly: PI_OK"</span>
</code></pre></div></div>

<p>In the pi tab, the startup notice reads <code class="language-plaintext highlighter-rouge">OpenAI-compat: llmproxy (local) available in /model</code>, and the footer shows <code class="language-plaintext highlighter-rouge">llmproxy/flagship__free</code>. <code class="language-plaintext highlighter-rouge">/compat-refresh</code> refetches the list later, and <code class="language-plaintext highlighter-rouge">/model</code> shows everything llmproxy offers.</p>

<h2 id="mobile-access">Mobile access</h2>

<p>I wanted to check on agents from my phone, and there are two layers to that.</p>

<p><a href="https://github.com/herdr-go/herdr-go">HerdrGo</a> is a Herdr plugin plus an Android app. It gives a terminal view of every agent, including those with no remote-control feature of their own. Install it as the same user that runs Herdr:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>loginctl enable-linger <span class="s2">"</span><span class="si">$(</span><span class="nb">id</span> <span class="nt">-un</span><span class="si">)</span><span class="s2">"</span>
herdr plugin <span class="nb">install </span>herdr-go/herdr-go
herdr plugin action invoke herdrgo.setup
herdr plugin action invoke herdrgo.status
herdr plugin action invoke herdrgo.pair    <span class="c"># shows the pairing QR again</span>
</code></pre></div></div>

<p>Install the app from the project’s releases page and scan the QR code. Treat that QR code like a password, because it contains the network credential for the bridge. Its default transport doesn’t need any router port forwarding.</p>

<p>Several agents also have their own remote-control modes, which give you the vendor’s mobile interface instead of a raw terminal:</p>

<table>
  <thead>
    <tr>
      <th>Agent</th>
      <th>Turn it on</th>
      <th>Where you use it</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Claude Code</td>
      <td><code class="language-plaintext highlighter-rouge">/remote-control</code>, or enable it for all sessions in <code class="language-plaintext highlighter-rouge">/config</code></td>
      <td>Claude mobile app or claude.ai/code</td>
    </tr>
    <tr>
      <td>Codex</td>
      <td><code class="language-plaintext highlighter-rouge">codex remote-control start</code>, then <code class="language-plaintext highlighter-rouge">codex remote-control pair</code> (experimental)</td>
      <td>ChatGPT app, where supported</td>
    </tr>
    <tr>
      <td>Antigravity</td>
      <td><code class="language-plaintext highlighter-rouge">/remote-control on</code>, or launch with <code class="language-plaintext highlighter-rouge">--remote-control</code></td>
      <td>Printed URL in a mobile browser</td>
    </tr>
    <tr>
      <td>Copilot</td>
      <td><code class="language-plaintext highlighter-rouge">/remote on</code>, or launch with <code class="language-plaintext highlighter-rouge">--remote</code></td>
      <td>GitHub Mobile, under Copilot agent sessions</td>
    </tr>
    <tr>
      <td>Hermes</td>
      <td>Its separate web dashboard and API gateway services</td>
      <td>Browser or an OpenAI-compatible client</td>
    </tr>
    <tr>
      <td>Grok Build, OpenCode</td>
      <td>No native option that I’ve confirmed</td>
      <td>HerdrGo</td>
    </tr>
  </tbody>
</table>

<p>None of these require permission-bypass flags. A remote connection and a conversation are separate things, too: resuming a conversation after a reboot doesn’t automatically restore its remote link, so you may need to re-enable it.</p>

<p>Hermes’s dashboard and API gateway run as their own processes, separate from the terminal agent in Herdr. If you bind the dashboard to anything other than localhost, Hermes requires you to configure authentication, and I’d keep both on a trusted LAN or VPN rather than exposing them to the internet.</p>

<h2 id="starting-everything-at-boot">Starting everything at boot</h2>

<p>Herdr can restore agents on its own, but I wanted a simpler rule: try to resume the latest conversation, and if that command fails, start fresh once. That takes three pieces.</p>

<h3 id="turn-off-herdrs-native-relaunch">Turn off Herdr’s native relaunch</h3>

<p>In <code class="language-plaintext highlighter-rouge">~/.config/herdr/config.toml</code>, inside the existing <code class="language-plaintext highlighter-rouge">[session]</code> table:</p>

<div class="language-toml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">[session]</span>
<span class="py">resume_agents_on_restore</span> <span class="p">=</span> <span class="kc">false</span>
</code></pre></div></div>

<p>The integrations stay installed and keep reporting status. Herdr just no longer launches the agents itself during restore, so it won’t compete with the launcher.</p>

<h3 id="a-user-service-that-hosts-herdr">A user service that hosts Herdr</h3>

<p>A systemd user service starts a Herdr client inside a tmux server on its own socket, so it doesn’t collide with any tmux sessions you run by hand. Lingering (enabled in the HerdrGo step above) lets user services run without a login. Create <code class="language-plaintext highlighter-rouge">~/.config/systemd/user/herdr-autostart.service</code>, adjusting the PATH to match your install locations:</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">[Unit]</span>
<span class="py">Description</span><span class="p">=</span><span class="s">Herdr boot session and agent restoration</span>

<span class="nn">[Service]</span>
<span class="py">Type</span><span class="p">=</span><span class="s">oneshot</span>
<span class="py">RemainAfterExit</span><span class="p">=</span><span class="s">yes</span>
<span class="py">WorkingDirectory</span><span class="p">=</span><span class="s">%h</span>
<span class="py">Environment</span><span class="p">=</span><span class="s">"PATH=%h/.local/agy-compat/bin:%h/.local/bin:%h/.grok/bin:/usr/local/bin:/usr/bin:/bin"</span>
<span class="py">ExecStart</span><span class="p">=</span><span class="s">/usr/bin/tmux -L herdr-autostart new-session -d -s agents -x 160 -y 48 %h/.local/bin/herdr</span>
<span class="py">ExecStop</span><span class="p">=</span><span class="s">/usr/bin/tmux -L herdr-autostart kill-server</span>
<span class="py">TimeoutStartSec</span><span class="p">=</span><span class="s">60</span>

<span class="nn">[Install]</span>
<span class="py">WantedBy</span><span class="p">=</span><span class="s">default.target</span>
</code></pre></div></div>

<p>Its status will read <code class="language-plaintext highlighter-rouge">active (exited)</code>, which is expected. The unit creates the background session and finishes; it isn’t a watchdog for the individual agents.</p>

<h3 id="a-launcher-that-resumes-or-starts-fresh">A launcher that resumes or starts fresh</h3>

<p>The launcher reads a JSON file of commands, <code class="language-plaintext highlighter-rouge">~/.config/herdr/agent-startup.json</code>:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"herdr"</span><span class="p">:</span><span class="w"> </span><span class="s2">"~/.local/bin/herdr"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"path"</span><span class="p">:</span><span class="w"> </span><span class="s2">"$HOME/.opencode/bin:$HOME/.local/agy-compat/bin:$HOME/.local/bin:$HOME/.grok/bin:/usr/local/bin:/usr/bin:/bin"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"workspace_root"</span><span class="p">:</span><span class="w"> </span><span class="s2">"~/agents"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"ready_timeout_seconds"</span><span class="p">:</span><span class="w"> </span><span class="mi">45</span><span class="p">,</span><span class="w">
  </span><span class="nl">"interrupt_exit_codes"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="mi">129</span><span class="p">,</span><span class="w"> </span><span class="mi">130</span><span class="p">,</span><span class="w"> </span><span class="mi">131</span><span class="p">,</span><span class="w"> </span><span class="mi">137</span><span class="p">,</span><span class="w"> </span><span class="mi">143</span><span class="p">],</span><span class="w">
  </span><span class="nl">"agents"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"claude"</span><span class="p">:</span><span class="w">  </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"claude"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--continue"</span><span class="p">],</span><span class="w">               </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"claude"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
    </span><span class="nl">"codex"</span><span class="p">:</span><span class="w">   </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"codex"</span><span class="p">,</span><span class="w"> </span><span class="s2">"resume"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--last"</span><span class="p">],</span><span class="w">          </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"codex"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
    </span><span class="nl">"agy"</span><span class="p">:</span><span class="w">     </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"agy"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--continue"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--remote-control"</span><span class="p">],</span><span class="w">
                 </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w">  </span><span class="p">[</span><span class="s2">"agy"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--remote-control"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
    </span><span class="nl">"grok"</span><span class="p">:</span><span class="w">    </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"grok"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--continue"</span><span class="p">],</span><span class="w">                 </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"grok"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
    </span><span class="nl">"hermes"</span><span class="p">:</span><span class="w">  </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"hermes"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--continue"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--no-restore-cwd"</span><span class="p">],</span><span class="w">
                 </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w">  </span><span class="p">[</span><span class="s2">"hermes"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
    </span><span class="nl">"copilot"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"copilot"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--continue"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--remote"</span><span class="p">],</span><span class="w">
                 </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w">  </span><span class="p">[</span><span class="s2">"copilot"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--remote"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">
    </span><span class="nl">"opencode-scoped"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"/bin/bash"</span><span class="p">,</span><span class="w"> </span><span class="s2">"-c"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"set -a; source </span><span class="se">\"</span><span class="s2">$HOME/.config/opencode/service.env</span><span class="se">\"</span><span class="s2">; set +a; exec opencode --standalone"</span><span class="p">],</span><span class="w">
      </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w">  </span><span class="p">[</span><span class="s2">"/bin/bash"</span><span class="p">,</span><span class="w"> </span><span class="s2">"-c"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"set -a; source </span><span class="se">\"</span><span class="s2">$HOME/.config/opencode/service.env</span><span class="se">\"</span><span class="s2">; set +a; exec opencode --standalone"</span><span class="p">]</span><span class="w">
    </span><span class="p">},</span><span class="w">
    </span><span class="nl">"opencode"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"/bin/bash"</span><span class="p">,</span><span class="w"> </span><span class="s2">"-c"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"R=$HOME/.local/opencode-general; exec env XDG_CONFIG_HOME=$R/config XDG_DATA_HOME=$R/data XDG_STATE_HOME=$R/state XDG_CACHE_HOME=$R/cache GH_CONFIG_DIR=$HOME/.config/gh opencode --standalone --continue"</span><span class="p">],</span><span class="w">
      </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w">  </span><span class="p">[</span><span class="s2">"/bin/bash"</span><span class="p">,</span><span class="w"> </span><span class="s2">"-c"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"R=$HOME/.local/opencode-general; exec env XDG_CONFIG_HOME=$R/config XDG_DATA_HOME=$R/data XDG_STATE_HOME=$R/state XDG_CACHE_HOME=$R/cache GH_CONFIG_DIR=$HOME/.config/gh opencode --standalone"</span><span class="p">]</span><span class="w">
    </span><span class="p">},</span><span class="w">
    </span><span class="nl">"pi"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"resume"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"pi"</span><span class="p">,</span><span class="w"> </span><span class="s2">"--continue"</span><span class="p">],</span><span class="w"> </span><span class="nl">"fresh"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"pi"</span><span class="p">]</span><span class="w"> </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Hermes gets <code class="language-plaintext highlighter-rouge">--no-restore-cwd</code> so it doesn’t jump back to an old conversation’s directory. The two OpenCode entries differ from the rest, and from each other. The scoped one sources its private environment file before starting, which matters in the credential section below. The general one sources nothing and instead points OpenCode at its own XDG directories, so it never reads the scoped copy’s config. Each tab gets its own working directory from its label, so the two OpenCodes keep separate histories under <code class="language-plaintext highlighter-rouge">~/agents/opencode-scoped</code> and <code class="language-plaintext highlighter-rouge">~/agents/opencode</code>.</p>

<p>The launcher itself, <code class="language-plaintext highlighter-rouge">~/.config/herdr/agent-startup.py</code>, has two modes. In <code class="language-plaintext highlighter-rouge">boot</code> mode it waits for Herdr’s tabs to appear, matches each configured agent to exactly one tab by label, skips any pane that already reports a running agent, and submits a command that re-invokes the script in <code class="language-plaintext highlighter-rouge">agent</code> mode inside each remaining pane. In <code class="language-plaintext highlighter-rouge">agent</code> mode it changes into that agent’s workspace, runs the resume command, and falls back to the fresh command once if resume exits with an error. A normal exit or an interrupt leaves you at a shell instead of retrying.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#!/usr/bin/env python3
</span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">pathlib</span> <span class="kn">import</span> <span class="n">Path</span>
<span class="kn">import</span> <span class="nn">shlex</span>
<span class="kn">import</span> <span class="nn">signal</span>
<span class="kn">import</span> <span class="nn">subprocess</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">tomllib</span>
<span class="kn">import</span> <span class="nn">traceback</span>

<span class="n">CONFIG</span> <span class="o">=</span> <span class="n">Path</span><span class="p">.</span><span class="n">home</span><span class="p">()</span> <span class="o">/</span> <span class="s">".config/herdr/agent-startup.json"</span>

<span class="k">def</span> <span class="nf">load_config</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">CONFIG</span><span class="p">.</span><span class="n">read_text</span><span class="p">())</span>

<span class="k">def</span> <span class="nf">api</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">subprocess</span><span class="p">.</span><span class="n">run</span><span class="p">(</span>
        <span class="p">[</span><span class="n">os</span><span class="p">.</span><span class="n">path</span><span class="p">.</span><span class="n">expanduser</span><span class="p">(</span><span class="n">config</span><span class="p">[</span><span class="s">"herdr"</span><span class="p">]),</span> <span class="o">*</span><span class="n">args</span><span class="p">],</span> <span class="n">capture_output</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
        <span class="n">text</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">check</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">output</span> <span class="o">=</span> <span class="n">result</span><span class="p">.</span><span class="n">stdout</span><span class="p">.</span><span class="n">strip</span><span class="p">()</span>
    <span class="c1"># Some Herdr versions return empty stdout on a successful pane run.
</span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">output</span> <span class="ow">and</span> <span class="n">args</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="p">(</span><span class="s">"pane"</span><span class="p">,</span> <span class="s">"run"</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">{}</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">output</span><span class="p">)</span>
    <span class="k">if</span> <span class="s">"error"</span> <span class="ow">in</span> <span class="n">response</span><span class="p">:</span>
        <span class="k">raise</span> <span class="nb">RuntimeError</span><span class="p">(</span><span class="n">response</span><span class="p">[</span><span class="s">"error"</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">response</span><span class="p">[</span><span class="s">"result"</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">run_agent</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
    <span class="n">commands</span> <span class="o">=</span> <span class="n">config</span><span class="p">[</span><span class="s">"agents"</span><span class="p">][</span><span class="n">name</span><span class="p">]</span>
    <span class="n">workspace</span> <span class="o">=</span> <span class="n">Path</span><span class="p">(</span><span class="n">config</span><span class="p">[</span><span class="s">"workspace_root"</span><span class="p">]).</span><span class="n">expanduser</span><span class="p">()</span> <span class="o">/</span> <span class="n">name</span>
    <span class="n">workspace</span><span class="p">.</span><span class="n">mkdir</span><span class="p">(</span><span class="n">parents</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">exist_ok</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">os</span><span class="p">.</span><span class="n">chdir</span><span class="p">(</span><span class="n">workspace</span><span class="p">)</span>
    <span class="n">environment</span> <span class="o">=</span> <span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">.</span><span class="n">copy</span><span class="p">()</span>
    <span class="n">environment</span><span class="p">[</span><span class="s">"PATH"</span><span class="p">]</span> <span class="o">=</span> <span class="n">os</span><span class="p">.</span><span class="n">path</span><span class="p">.</span><span class="n">expandvars</span><span class="p">(</span><span class="n">config</span><span class="p">[</span><span class="s">"path"</span><span class="p">])</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[agent-startup] </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s">: trying latest session in </span><span class="si">{</span><span class="n">workspace</span><span class="si">}</span><span class="s">"</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">child</span> <span class="o">=</span> <span class="n">subprocess</span><span class="p">.</span><span class="n">Popen</span><span class="p">(</span><span class="n">commands</span><span class="p">[</span><span class="s">"resume"</span><span class="p">],</span> <span class="n">env</span><span class="o">=</span><span class="n">environment</span><span class="p">)</span>
    <span class="n">previous</span> <span class="o">=</span> <span class="n">signal</span><span class="p">.</span><span class="n">signal</span><span class="p">(</span><span class="n">signal</span><span class="p">.</span><span class="n">SIGINT</span><span class="p">,</span> <span class="n">signal</span><span class="p">.</span><span class="n">SIG_IGN</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">status</span> <span class="o">=</span> <span class="n">child</span><span class="p">.</span><span class="n">wait</span><span class="p">()</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">signal</span><span class="p">.</span><span class="n">signal</span><span class="p">(</span><span class="n">signal</span><span class="p">.</span><span class="n">SIGINT</span><span class="p">,</span> <span class="n">previous</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">status</span> <span class="o">==</span> <span class="mi">0</span> <span class="ow">or</span> <span class="n">status</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="ow">or</span> <span class="n">status</span> <span class="ow">in</span> <span class="n">config</span><span class="p">[</span><span class="s">"interrupt_exit_codes"</span><span class="p">]:</span>
        <span class="k">return</span> <span class="n">status</span> <span class="k">if</span> <span class="n">status</span> <span class="o">&gt;=</span> <span class="mi">0</span> <span class="k">else</span> <span class="mi">128</span> <span class="o">-</span> <span class="n">status</span>
    <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[agent-startup] </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s">: resume exited </span><span class="si">{</span><span class="n">status</span><span class="si">}</span><span class="s">; starting fresh once"</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">command</span> <span class="o">=</span> <span class="n">commands</span><span class="p">[</span><span class="s">"fresh"</span><span class="p">]</span>
    <span class="n">os</span><span class="p">.</span><span class="n">execvpe</span><span class="p">(</span><span class="n">command</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">command</span><span class="p">,</span> <span class="n">environment</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">plan</span><span class="p">(</span><span class="n">config</span><span class="p">):</span>
    <span class="n">tabs</span> <span class="o">=</span> <span class="n">api</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="s">"tab"</span><span class="p">,</span> <span class="s">"list"</span><span class="p">)[</span><span class="s">"tabs"</span><span class="p">]</span>
    <span class="n">panes</span> <span class="o">=</span> <span class="n">api</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="s">"pane"</span><span class="p">,</span> <span class="s">"list"</span><span class="p">)[</span><span class="s">"panes"</span><span class="p">]</span>
    <span class="n">selected</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">config</span><span class="p">[</span><span class="s">"agents"</span><span class="p">]:</span>
        <span class="n">matches</span> <span class="o">=</span> <span class="p">[</span><span class="n">tab</span> <span class="k">for</span> <span class="n">tab</span> <span class="ow">in</span> <span class="n">tabs</span> <span class="k">if</span> <span class="n">tab</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"label"</span><span class="p">)</span> <span class="o">==</span> <span class="n">name</span><span class="p">]</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">matches</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nb">RuntimeError</span><span class="p">(</span><span class="sa">f</span><span class="s">"Expected one tab labelled </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s">; found </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">matches</span><span class="p">)</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
        <span class="n">members</span> <span class="o">=</span> <span class="p">[</span><span class="n">pane</span> <span class="k">for</span> <span class="n">pane</span> <span class="ow">in</span> <span class="n">panes</span> <span class="k">if</span> <span class="n">pane</span><span class="p">[</span><span class="s">"tab_id"</span><span class="p">]</span> <span class="o">==</span> <span class="n">matches</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="s">"tab_id"</span><span class="p">]]</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">members</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nb">RuntimeError</span><span class="p">(</span><span class="sa">f</span><span class="s">"Expected one pane in </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s">; found </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">members</span><span class="p">)</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
        <span class="n">selected</span><span class="p">.</span><span class="n">append</span><span class="p">((</span><span class="n">name</span><span class="p">,</span> <span class="n">members</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
    <span class="k">return</span> <span class="n">selected</span>

<span class="k">def</span> <span class="nf">boot</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="nb">apply</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">apply</span><span class="p">:</span>
        <span class="n">settings</span> <span class="o">=</span> <span class="n">tomllib</span><span class="p">.</span><span class="n">loads</span><span class="p">((</span><span class="n">Path</span><span class="p">.</span><span class="n">home</span><span class="p">()</span> <span class="o">/</span> <span class="s">".config/herdr/config.toml"</span><span class="p">).</span><span class="n">read_text</span><span class="p">())</span>
        <span class="k">if</span> <span class="n">settings</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"session"</span><span class="p">,</span> <span class="p">{}).</span><span class="n">get</span><span class="p">(</span><span class="s">"resume_agents_on_restore"</span><span class="p">)</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">False</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nb">RuntimeError</span><span class="p">(</span><span class="s">"Set [session] resume_agents_on_restore = false first"</span><span class="p">)</span>
    <span class="n">deadline</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">+</span> <span class="n">config</span><span class="p">[</span><span class="s">"ready_timeout_seconds"</span><span class="p">]</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">selected</span> <span class="o">=</span> <span class="n">plan</span><span class="p">(</span><span class="n">config</span><span class="p">)</span>
            <span class="k">break</span>
        <span class="k">except</span> <span class="p">(</span><span class="n">subprocess</span><span class="p">.</span><span class="n">SubprocessError</span><span class="p">,</span> <span class="nb">OSError</span><span class="p">,</span> <span class="nb">ValueError</span><span class="p">,</span> <span class="nb">KeyError</span><span class="p">,</span> <span class="nb">RuntimeError</span><span class="p">)</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[agent-startup:boot] readiness: </span><span class="si">{</span><span class="n">e</span><span class="si">}</span><span class="s">"</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
            <span class="n">traceback</span><span class="p">.</span><span class="n">print_exc</span><span class="p">()</span>
            <span class="k">if</span> <span class="n">time</span><span class="p">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">&gt;=</span> <span class="n">deadline</span><span class="p">:</span>
                <span class="k">raise</span>
            <span class="n">time</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">pane</span> <span class="ow">in</span> <span class="n">selected</span><span class="p">:</span>
        <span class="n">pane_id</span> <span class="o">=</span> <span class="n">pane</span><span class="p">[</span><span class="s">"pane_id"</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">pane</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">"agent"</span><span class="p">):</span>
            <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[agent-startup] skip </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s">: agent already present in </span><span class="si">{</span><span class="n">pane_id</span><span class="si">}</span><span class="s">"</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
            <span class="k">continue</span>
        <span class="n">command</span> <span class="o">=</span> <span class="n">shlex</span><span class="p">.</span><span class="n">join</span><span class="p">([</span><span class="s">"/usr/bin/python3"</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">Path</span><span class="p">(</span><span class="n">__file__</span><span class="p">).</span><span class="n">resolve</span><span class="p">()),</span> <span class="s">"agent"</span><span class="p">,</span> <span class="n">name</span><span class="p">])</span>
        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[agent-startup] </span><span class="si">{</span><span class="s">'launch'</span> <span class="k">if</span> <span class="nb">apply</span> <span class="k">else</span> <span class="s">'would launch'</span><span class="si">}</span><span class="s"> </span><span class="si">{</span><span class="n">name</span><span class="si">}</span><span class="s"> in </span><span class="si">{</span><span class="n">pane_id</span><span class="si">}</span><span class="s">"</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">apply</span><span class="p">:</span>
            <span class="n">api</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="s">"pane"</span><span class="p">,</span> <span class="s">"run"</span><span class="p">,</span> <span class="n">pane_id</span><span class="p">,</span> <span class="n">command</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="p">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
    <span class="n">sub</span> <span class="o">=</span> <span class="n">parser</span><span class="p">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">dest</span><span class="o">=</span><span class="s">"mode"</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">boot_parser</span> <span class="o">=</span> <span class="n">sub</span><span class="p">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s">"boot"</span><span class="p">)</span>
    <span class="n">boot_parser</span><span class="p">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">"--apply"</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">"store_true"</span><span class="p">)</span>
    <span class="n">agent_parser</span> <span class="o">=</span> <span class="n">sub</span><span class="p">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s">"agent"</span><span class="p">)</span>
    <span class="n">agent_parser</span><span class="p">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">"name"</span><span class="p">)</span>
    <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="p">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">config</span> <span class="o">=</span> <span class="n">load_config</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">args</span><span class="p">.</span><span class="n">mode</span> <span class="o">==</span> <span class="s">"agent"</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">run_agent</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">args</span><span class="p">.</span><span class="n">name</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">boot</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">args</span><span class="p">.</span><span class="nb">apply</span><span class="p">)</span>
    <span class="k">except</span> <span class="nb">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"[agent-startup:main] </span><span class="si">{</span><span class="n">args</span><span class="p">.</span><span class="n">mode</span><span class="si">}</span><span class="s">: </span><span class="si">{</span><span class="n">e</span><span class="si">}</span><span class="s">"</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
        <span class="n">traceback</span><span class="p">.</span><span class="n">print_exc</span><span class="p">()</span>
        <span class="k">return</span> <span class="mi">1</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">"__main__"</span><span class="p">:</span>
    <span class="n">sys</span><span class="p">.</span><span class="nb">exit</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
</code></pre></div></div>

<p>If you need the Antigravity CPU workaround, the wrapper directory in <code class="language-plaintext highlighter-rouge">path</code> covers the launcher too.</p>

<p>A drop-in at <code class="language-plaintext highlighter-rouge">~/.config/systemd/user/herdr-autostart.service.d/agent-startup.conf</code> runs the launcher after the tmux session starts:</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">[Service]</span>
<span class="py">TimeoutStartSec</span><span class="p">=</span><span class="s">90</span>
<span class="py">ExecStartPost</span><span class="p">=</span><span class="s">/usr/bin/python3 %h/.config/herdr/agent-startup.py boot --apply</span>
</code></pre></div></div>

<p>Adding a tab later follows the same order: create the labelled tab first, then add its entry to <code class="language-plaintext highlighter-rouge">agent-startup.json</code>. The launcher refuses to plan a boot when a configured label has no tab, so editing the JSON first would block every agent at the next reboot, not just the new one. To start a newly added agent without rebooting, exit whatever is in its pane and run <code class="language-plaintext highlighter-rouge">python3 ~/.config/herdr/agent-startup.py agent &lt;label&gt;</code> there.</p>

<p>Before enabling anything, do a dry run. Without <code class="language-plaintext highlighter-rouge">--apply</code>, the launcher only prints <code class="language-plaintext highlighter-rouge">would launch</code> or <code class="language-plaintext highlighter-rouge">skip</code> for each tab:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>python3 <span class="nt">-m</span> json.tool ~/.config/herdr/agent-startup.json <span class="o">&gt;</span>/dev/null
python3 <span class="nt">-m</span> py_compile ~/.config/herdr/agent-startup.py
python3 ~/.config/herdr/agent-startup.py boot
systemctl <span class="nt">--user</span> daemon-reload
systemd-analyze <span class="nt">--user</span> verify ~/.config/systemd/user/herdr-autostart.service
systemctl <span class="nt">--user</span> <span class="nb">enable </span>herdr-autostart.service
</code></pre></div></div>

<p>Don’t run <code class="language-plaintext highlighter-rouge">boot --apply</code> by hand while a pane has an editor or some other program open. The launcher skips panes that Herdr recognizes as agents, but it can’t tell whether every other pane is sitting at a safe shell prompt. It’s meant for freshly restored shells at boot.</p>

<p>After the next planned reboot, check the result:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>herdr agent list
journalctl <span class="nt">--user</span> <span class="nt">-b</span> <span class="nt">-u</span> herdr-autostart.service <span class="nt">-n</span> 80 <span class="nt">--no-pager</span>
</code></pre></div></div>

<p>In <code class="language-plaintext highlighter-rouge">herdr agent list</code>, <code class="language-plaintext highlighter-rouge">blocked</code> means an agent is waiting on an approval or question, and <code class="language-plaintext highlighter-rouge">unknown</code> only means Herdr couldn’t classify it, which isn’t proof of failure.</p>

<p>This arrangement submits commands once, at boot. It doesn’t restart an agent that crashes later, and resuming a conversation doesn’t mean an interrupted task picks up where it left off. A resume can also fail for reasons unrelated to missing history, such as an expired login, and then the fresh attempt usually fails the same way. Workspace-trust prompts and sign-in prompts can still pause startup, so I glance at each tab after a reboot.</p>

<h2 id="running-mcpproxy">Running mcpproxy</h2>

<p>Install Docker Engine from Docker’s official apt repository, following their Ubuntu instructions, and enable it so it starts at boot. I keep using <code class="language-plaintext highlighter-rouge">sudo docker</code> rather than adding my account to the <code class="language-plaintext highlighter-rouge">docker</code> group, since that group is effectively root.</p>

<p>mcpproxy reads its tool providers from a directory of YAML files and its secrets from an <code class="language-plaintext highlighter-rouge">.env</code> file. I keep both under <code class="language-plaintext highlighter-rouge">~/.config/mcpproxy</code>, put the containers on a private Docker network, and publish ports only on <code class="language-plaintext highlighter-rouge">127.0.0.1</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/.config/mcpproxy/tools
<span class="o">(</span> <span class="nb">umask </span>077<span class="p">;</span> <span class="nb">touch</span> ~/.config/mcpproxy/.env <span class="o">)</span>
<span class="nb">chmod </span>600 ~/.config/mcpproxy/.env
<span class="nb">sudo </span>docker network inspect agent-services <span class="o">&gt;</span>/dev/null 2&gt;&amp;1 <span class="se">\</span>
  <span class="o">||</span> <span class="nb">sudo </span>docker network create agent-services

<span class="nb">sudo </span>docker run <span class="nt">-d</span> <span class="se">\</span>
  <span class="nt">--name</span> mcpproxy <span class="se">\</span>
  <span class="nt">--network</span> agent-services <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">-p</span> 127.0.0.1:8888:8888 <span class="se">\</span>
  <span class="nt">-p</span> 127.0.0.1:8889:8889 <span class="se">\</span>
  <span class="nt">--env-file</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.config/mcpproxy/.env"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">MCP_TOOL_CONFIG_DIR</span><span class="o">=</span>/app/tools <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">MCP_ENV_FILE</span><span class="o">=</span>/app/.env <span class="se">\</span>
  <span class="nt">--mount</span> <span class="nb">type</span><span class="o">=</span><span class="nb">bind</span>,src<span class="o">=</span><span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.config/mcpproxy/tools"</span>,dst<span class="o">=</span>/app/tools <span class="se">\</span>
  <span class="nt">--mount</span> <span class="nb">type</span><span class="o">=</span><span class="nb">bind</span>,src<span class="o">=</span><span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.config/mcpproxy/.env"</span>,dst<span class="o">=</span>/app/.env <span class="se">\</span>
  ghcr.io/billjr99/mcpproxy:latest
</code></pre></div></div>

<p>The MCP endpoint is then <code class="language-plaintext highlighter-rouge">http://127.0.0.1:8888/mcp</code> and the management UI is on port 8889. From another computer, an SSH tunnel (<code class="language-plaintext highlighter-rouge">ssh -N -L 18889:127.0.0.1:8889 you@server</code>) reaches the UI without opening a port. The <a href="/posts/2026/05/mcpproxy/">earlier post</a> covers how providers are written and how its secret injection works: a provider declares which handler arguments come from environment variables, the proxy fills them in at call time, and the model never sees the values in a tool schema.</p>

<p>That keeps keys away from the model. It doesn’t keep them away from other clients. If a key sits in the proxy’s <code class="language-plaintext highlighter-rouge">.env</code>, every agent that connects to the proxy can call the tool with it. For most of my tools, that’s fine. For one service it isn’t.</p>

<h2 id="scoping-a-credential-to-one-agent">Scoping a credential to one agent</h2>

<p>The service in question has a personal API key and holds data that the general-purpose agents have no reason to touch. I want exactly one agent to be able to use it, and the others to see a tool that fails to authenticate.</p>

<h3 id="let-the-caller-supply-the-key">Let the caller supply the key</h3>

<p>mcpproxy providers can declare a secret in two ways at once: a server-side environment variable and a request header supplied by the caller. The provider’s <code class="language-plaintext highlighter-rouge">secrets</code> block looks like this:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">secrets</span><span class="pi">:</span>
  <span class="na">env</span><span class="pi">:</span>
    <span class="na">api_url</span><span class="pi">:</span> <span class="s">SERVICE_API_URL</span>
    <span class="na">api_key</span><span class="pi">:</span> <span class="s">SERVICE_API_KEY</span>
  <span class="na">headers</span><span class="pi">:</span>
    <span class="na">api_key</span><span class="pi">:</span> <span class="s">X-MCPProxy-Service-Key</span>
</code></pre></div></div>

<p>Both <code class="language-plaintext highlighter-rouge">api_url</code> and <code class="language-plaintext highlighter-rouge">api_key</code> become handler arguments. <code class="language-plaintext highlighter-rouge">api_url</code> always comes from the proxy’s environment. <code class="language-plaintext highlighter-rouge">api_key</code> can come from <code class="language-plaintext highlighter-rouge">SERVICE_API_KEY</code> on the server or from the <code class="language-plaintext highlighter-rouge">X-MCPProxy-Service-Key</code> header on the incoming MCP request.</p>

<p>The trick is to set only the first. The proxy’s <code class="language-plaintext highlighter-rouge">.env</code> gets the base URL, which isn’t a secret, and leaves the key out entirely:</p>

<pre><code class="language-dotenv">SERVICE_API_URL=https://service.example.com
# SERVICE_API_KEY stays unset here.
</code></pre>

<p>Now the proxy has no credential of its own for this service. A request authenticates only if the client brings the key in the header. After changing the <code class="language-plaintext highlighter-rouge">.env</code>, restart the container so it picks up the new values.</p>

<h3 id="give-the-key-to-one-agent-only">Give the key to one agent only</h3>

<p>Add the service key to the scoped OpenCode’s private environment file, next to the provider key:</p>

<pre><code class="language-dotenv">MYPROVIDER_API_KEY=...
SERVICE_API_KEY=...
</code></pre>

<p>Then add an <code class="language-plaintext highlighter-rouge">mcp</code> block to <code class="language-plaintext highlighter-rouge">opencode.jsonc</code> that registers mcpproxy as a remote MCP server and forwards that variable as the header:</p>

<div class="language-jsonc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="w">  </span><span class="nl">"mcp"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"servers"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"mcpproxy"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"remote"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"url"</span><span class="p">:</span><span class="w"> </span><span class="s2">"http://127.0.0.1:8888/mcp"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"oauth"</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="p">,</span><span class="w">
        </span><span class="nl">"headers"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
          </span><span class="nl">"X-MCPProxy-Service-Key"</span><span class="p">:</span><span class="w"> </span><span class="s2">"{env:SERVICE_API_KEY}"</span><span class="w">
        </span><span class="p">}</span><span class="w">
      </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>As with the provider key, the <code class="language-plaintext highlighter-rouge">{env:...}</code> substitution means the config file names the variable but contains no secret.</p>

<p>The last piece is OpenCode’s launch command in <code class="language-plaintext highlighter-rouge">agent-startup.json</code>. Herdr starts OpenCode through a small Bash wrapper that sources <code class="language-plaintext highlighter-rouge">service.env</code> with <code class="language-plaintext highlighter-rouge">set -a</code> (so every assignment is exported) and then <code class="language-plaintext highlighter-rouge">exec</code>s OpenCode. The variable exists in OpenCode’s process and its children, and nowhere else. None of the other launch commands source that file, including the general-purpose OpenCode’s, so none of those agents ever has <code class="language-plaintext highlighter-rouge">SERVICE_API_KEY</code> in its environment. They can still list and call the tool through mcpproxy, but without the header the call has no key and the service rejects it.</p>

<p>Two side effects follow from this. Because OpenCode’s children inherit the variable, shell commands that OpenCode runs can use the key too, so a script it writes against the same API works without extra setup. And because <code class="language-plaintext highlighter-rouge">exec</code> replaces the wrapper shell, no extra Bash process sits around holding a copy of the environment.</p>

<h3 id="delegating-instead-of-sharing-the-key">Delegating instead of sharing the key</h3>

<p>Usually another agent doesn’t need the key at all. It needs the result. My Hermes agent handles requests that touch this service by writing a narrow prompt and sending it to the scoped OpenCode with <code class="language-plaintext highlighter-rouge">herdr agent prompt</code>, waiting for the reply, and reading it back with <code class="language-plaintext highlighter-rouge">herdr agent read</code>. Hermes never holds the credential, and the scoped OpenCode still only does what the MCP provider exposes.</p>

<p>With two OpenCodes running, the delegation has to find the right one. <code class="language-plaintext highlighter-rouge">herdr agent list</code> reports both as <code class="language-plaintext highlighter-rouge">opencode</code>, so matching on the agent type would sometimes pick the general copy, which has no key. My helper looks up the tab labelled <code class="language-plaintext highlighter-rouge">opencode-scoped</code> with <code class="language-plaintext highlighter-rouge">herdr tab list</code>, then takes the OpenCode agent in that tab. Pane and tab IDs change across reboots, so it resolves them fresh on every call, and it refuses to send anything if that OpenCode is already busy.</p>

<h3 id="turning-the-tool-on-for-another-agent">Turning the tool on for another agent</h3>

<p>Another agent registering the tool isn’t a mistake, and it doesn’t need to be removed. Hermes, for instance, can keep the tool in its MCP include list. Those calls fail only because no key reaches the proxy, and there are two ways to change that. Setting <code class="language-plaintext highlighter-rouge">SERVICE_API_KEY</code> in mcpproxy’s own <code class="language-plaintext highlighter-rouge">.env</code> turns the tool on for every client at once, which is the right choice if the service isn’t sensitive after all. To enable it for one more agent, give that agent its own environment variable and have its MCP client forward it as the <code class="language-plaintext highlighter-rouge">X-MCPProxy-Service-Key</code> header, the same way OpenCode does. Either way it’s a configuration change, not a code change, and the provider YAML stays the same.</p>

<h3 id="checking-it-without-printing-the-key">Checking it without printing the key</h3>

<p>I verify each layer without echoing secrets to the terminal:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># The proxy has the URL but no fallback key.</span>
<span class="nb">grep</span> <span class="nt">-q</span> <span class="s1">'^SERVICE_API_URL=.'</span> ~/.config/mcpproxy/.env <span class="se">\</span>
  <span class="o">&amp;&amp;</span> <span class="nb">echo</span> <span class="s1">'SERVICE_API_URL=set'</span> <span class="o">||</span> <span class="nb">echo</span> <span class="s1">'SERVICE_API_URL=MISSING'</span>
<span class="nb">grep</span> <span class="nt">-q</span> <span class="s1">'^SERVICE_API_KEY=.'</span> ~/.config/mcpproxy/.env <span class="se">\</span>
  <span class="o">&amp;&amp;</span> <span class="nb">echo</span> <span class="s1">'WARNING: fallback key present'</span> <span class="o">||</span> <span class="nb">echo</span> <span class="s1">'fallback key absent'</span>

<span class="c"># The scoped OpenCode, launched the same way Herdr launches it, can reach the proxy.</span>
<span class="nb">cd</span> ~/agents/opencode-scoped
/bin/bash <span class="nt">-c</span> <span class="s1">'
  set -a; source "$HOME/.config/opencode/service.env"; set +a
  test -n "$SERVICE_API_KEY" &amp;&amp; echo "SERVICE_API_KEY=set"
  exec opencode --print-logs mcp list
'</span>
</code></pre></div></div>

<p>Inside the <code class="language-plaintext highlighter-rouge">opencode-scoped</code> tab, <code class="language-plaintext highlighter-rouge">/mcps</code> should show mcpproxy connected. A read-only tool call against the service then confirms that the header made it through and the service accepted it.</p>

<h3 id="what-this-does-and-doesnt-protect-against">What this does and doesn’t protect against</h3>

<blockquote>
  <p><strong>A disclaimer before relying on this.</strong> Confining a credential to one Herdr environment does not completely isolate it. The key can still leak: OpenCode, or a script it runs, could print it, write it to a file, or include it in a log that another agent later reads. The other agents can also reach it indirectly, because any agent with a shell can start OpenCode with the same wrapper command, or use <code class="language-plaintext highlighter-rouge">herdr pane run</code> to type a request into OpenCode’s tab and let OpenCode make the call on its behalf. What this setup does give me is a meaningful layer of protection. I can define exactly which functionality the service exposes through an MCP provider, and that provider acts as a partial firewall: the other agents see a tool that refuses to authenticate, rather than an open path to the service and its data.</p>
</blockquote>

<p>This is least privilege by process environment on a single-user machine. It is not a hard security boundary, and I don’t treat it as one.</p>

<p>It keeps the key out of the other agents’ environments, so they can’t use it by accident and can’t leak it through a tool that dumps environment variables. It keeps the key out of the proxy’s configuration, so the proxy can’t hand it to whoever connects. And the key never appears in a tool schema the model can read.</p>

<p>It does not stop a determined process running as the same Unix user. Any agent with shell access could, in principle, read <code class="language-plaintext highlighter-rouge">~/.config/opencode/service.env</code> directly. The same goes for the general-purpose OpenCode: separate XDG directories keep it from loading the scoped copy’s config by accident, but they’re not a permission boundary. The header also travels over plain HTTP, which is acceptable only because the proxy listens on loopback. If I needed isolation from the other agents themselves, I would run them as separate Unix users or in separate containers. For my purpose, keeping a sensitive tool out of reach of agents that have no business using it, process scoping is enough.</p>

<p>One more layer helps when a service returns personal information. My provider for that service pseudonymizes personal identifiers before they reach the model, using an HMAC keyed by a stable secret that lives only on the proxy side. That secret isn’t a credential for the service, so it can sit in the proxy’s <code class="language-plaintext highlighter-rouge">.env</code> without widening access. It has to stay stable, though, or the pseudonyms change from one session to the next.</p>

<h2 id="other-services-on-the-same-network">Other services on the same network</h2>

<p>mcpproxy isn’t the only container on the box. A few other self-hosted services give the agents and mcpproxy providers capabilities that would otherwise mean calling a third-party API:</p>

<ul>
  <li><strong>SearXNG</strong>, a metasearch engine. Out of the box it only serves HTML, so I enabled JSON output in its <code class="language-plaintext highlighter-rouge">settings.yml</code> (adding <code class="language-plaintext highlighter-rouge">json</code> alongside <code class="language-plaintext highlighter-rouge">html</code> under <code class="language-plaintext highlighter-rouge">search.formats</code>), which lets tools call it as a search API.</li>
  <li><strong>Firecrawl</strong>, which scrapes pages and returns clean Markdown. I run its Docker Compose stack pinned to a specific release, with reduced worker counts so it shares the machine politely with everything else. Its self-hosted API has no authentication, which is one more reason it stays on loopback.</li>
  <li><strong>Camofox</strong>, a browser automation service with a small HTTP API, built from the upstream source.</li>
  <li><strong>llmproxy</strong>, a small OpenAI-compatible LLM proxy of my own, with an admin page for its provider settings. It routes requests across many upstream providers and publishes the result as one <code class="language-plaintext highlighter-rouge">/v1/models</code> list, including tiered routes such as a free flagship tier. The general OpenCode and pi both use it as their only provider.</li>
</ul>

<p>These all follow the same pattern as mcpproxy. Each publishes its ports on <code class="language-plaintext highlighter-rouge">127.0.0.1</code> only, so nothing outside the machine can reach them, and from another computer I use an SSH tunnel. They also share the private <code class="language-plaintext highlighter-rouge">agent-services</code> Docker network, where containers reach each other by name (an mcpproxy provider can call <code class="language-plaintext highlighter-rouge">http://searxng:8080</code> directly, for example) without any extra published ports. Most use <code class="language-plaintext highlighter-rouge">--restart unless-stopped</code> or <code class="language-plaintext highlighter-rouge">--restart always</code>, so Docker brings them back after a reboot. Firecrawl’s Compose stack is the exception in my setup; I start it by hand when I need it.</p>

<p>Apart from llmproxy’s role as a model provider, none of these are wired into the agents automatically. An agent reaches one only through a tool I’ve written for it in mcpproxy or by calling it directly, which is the same choke point the credential scoping above relies on.</p>

<h2 id="day-to-day-notes">Day-to-day notes</h2>

<p>After a reboot, Herdr and OpenCode are often up before Docker has finished starting mcpproxy. On my machine the proxy takes about a minute. If <code class="language-plaintext highlighter-rouge">/mcps</code> shows the proxy disconnected right after boot, wait and check again before assuming something broke.</p>

<p>With two OpenCodes running, check which one you’re talking to before changing anything. Each tab’s working directory (<code class="language-plaintext highlighter-rouge">herdr agent list</code> shows it) tells them apart, and so does the model name in OpenCode’s status line. To restart one, exit it in its tab and run <code class="language-plaintext highlighter-rouge">python3 ~/.config/herdr/agent-startup.py agent &lt;label&gt;</code> in the same pane. A restart is how either copy picks up a change to its config or environment file, since both read them only at startup.</p>

<p>If an OpenCode tab reports <code class="language-plaintext highlighter-rouge">opencode: not found</code>, the launcher’s <code class="language-plaintext highlighter-rouge">path</code> is missing OpenCode’s install directory. Using the absolute binary path in the launch command avoids depending on <code class="language-plaintext highlighter-rouge">.bashrc</code> at all.</p>

<p>Herdr integrations change between releases. After updating Herdr or an agent, run <code class="language-plaintext highlighter-rouge">herdr integration status</code> and reinstall anything that’s out of date, checking the changes first on any agent whose config you’ve customized. When something misbehaves, inspect it before reinstalling; reinstalling or deleting configuration shouldn’t be the first troubleshooting step, since it can throw away sign-ins and conversation history.</p>

<p>Finally, keep every environment file at mode <code class="language-plaintext highlighter-rouge">0600</code>, keep them out of version control, and redact secrets before sharing logs or asking anyone, human or agent, for help.</p>

<h2 id="references">References</h2>

<ul>
  <li><a href="https://herdr.dev/docs/install/">Herdr documentation</a>, including the <a href="https://herdr.dev/docs/cli-reference/">CLI reference</a>, <a href="https://herdr.dev/docs/integrations/">integrations</a>, and <a href="https://herdr.dev/docs/session-state/">session restoration</a></li>
  <li><a href="https://github.com/herdr-go/herdr-go">HerdrGo</a></li>
  <li><a href="https://code.claude.com/docs/en/setup">Claude Code setup</a> and <a href="https://code.claude.com/docs/en/remote-control">Remote Control</a></li>
  <li><a href="https://github.com/openai/codex">Codex</a></li>
  <li><a href="https://antigravity.google/docs/cli/install/">Antigravity CLI installation</a> and <a href="https://antigravity.google/docs/remote-control?tab=cli">remote control</a></li>
  <li><a href="https://docs.x.ai/build/overview">Grok Build</a></li>
  <li><a href="https://hermes-agent.nousresearch.com/docs/getting-started/installation">Hermes Agent installation</a> and <a href="https://hermes-agent.nousresearch.com/docs/user-guide/features/web-dashboard">web dashboard</a></li>
  <li><a href="https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli">GitHub Copilot CLI installation</a> and <a href="https://docs.github.com/en/copilot/how-tos/copilot-cli/use-copilot-cli/steer-remotely">remote steering</a></li>
  <li><a href="https://opencode.ai/v2/docs/config/">OpenCode V2 configuration</a>, <a href="https://opencode.ai/v2/docs/providers/">providers</a>, and <a href="https://opencode.ai/v2/docs/mcp-servers/">MCP servers</a></li>
  <li><a href="https://github.com/BillJr99/opencode-auto-models">opencode-auto-models</a></li>
  <li><a href="https://github.com/badlogic/pi-mono">pi</a> and <a href="https://www.npmjs.com/package/@billjr99/pi-openai-compat">pi-openai-compat</a></li>
  <li><a href="https://docs.docker.com/engine/install/ubuntu/">Docker Engine on Ubuntu</a></li>
  <li><a href="https://docs.searxng.org/admin/installation-docker.html">SearXNG container installation</a> and <a href="https://docs.searxng.org/admin/settings/settings_search.html">search settings</a></li>
  <li><a href="https://docs.firecrawl.dev/contributing/self-host">Firecrawl self-hosting guide</a></li>
  <li><a href="https://github.com/jo-inc/camofox-browser">Camofox Browser</a></li>
  <li><a href="https://github.com/BillJr99/mcpproxy">mcpproxy on GitHub</a> and the <a href="/posts/2026/05/mcpproxy/">earlier post</a> describing it</li>
</ul>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="mcp" /><category term="agentic" /><category term="herdr" /><category term="opencode" /><category term="security" /><summary type="html"><![CDATA[I now run nine coding agents side by side on a small always-on Ubuntu server: Claude Code, Codex, Antigravity, Grok Build, Hermes, GitHub Copilot, two separate copies of OpenCode, and pi. Herdr keeps them organized, one labelled tab per agent, and brings them back after a reboot. Most of them share one mcpproxy instance for tools. One of those tools talks to a service that needs a personal API key, and only one agent ever holds that key: a deliberately fenced-in OpenCode. The other agents can see the tool, but they can’t authenticate to the service behind it. When they need that service, they hand the task to that OpenCode through Herdr.]]></summary></entry><entry><title type="html">mcpproxy: A Config-Driven MCP Host with a Built-In Web UI</title><link href="https://www.billmongan.com/posts/2026/05/mcpproxy/" rel="alternate" type="text/html" title="mcpproxy: A Config-Driven MCP Host with a Built-In Web UI" /><published>2026-05-25T00:00:00+00:00</published><updated>2026-05-25T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/mcpproxy</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/mcpproxy/"><![CDATA[<p>The <a href="https://modelcontextprotocol.io/">Model Context Protocol</a> defines a standard
way for AI clients to discover and call tools, but standing up a personal MCP
server still usually means writing Python glue code, wiring up a framework, and
restarting a process every time you add a tool.  <a href="https://github.com/BillJr99/mcpproxy">mcpproxy</a>
takes a different approach: every tool provider is a single YAML file, the server
reloads tools at startup without any code changes to the host, and a browser-based
web UI handles the full provider lifecycle — editing, secret management, and
live command streaming — without leaving the browser.</p>

<blockquote>
  <p><strong>Experimental software — use with caution and in isolation.</strong>
<code class="language-plaintext highlighter-rouge">mcpproxy</code> is a research prototype provided as-is, with no guarantees of
security, stability, or fitness for any particular purpose.  It has not
undergone a security audit.  The web UI has no authentication.  Do not
expose it to untrusted networks or use it to process sensitive data in
production.  Run it on a trusted network, preferably in a container or VM
you are prepared to reset.  See the LICENSE for full MIT terms.</p>
</blockquote>

<h2 id="how-it-works">How It Works</h2>

<p><code class="language-plaintext highlighter-rouge">mcpproxy</code> exposes two ports: the MCP endpoint on <strong>8888</strong> (<code class="language-plaintext highlighter-rouge">http://localhost:8888/mcp</code>)
and a web UI on <strong>8889</strong> (<code class="language-plaintext highlighter-rouge">http://localhost:8889</code>).  The core server (<code class="language-plaintext highlighter-rouge">server.py</code>)
scans a <code class="language-plaintext highlighter-rouge">tools/</code> directory at startup.  Each YAML file there is a <em>provider</em>.
A provider either embeds Python <code class="language-plaintext highlighter-rouge">async def</code> handler functions directly in a
<code class="language-plaintext highlighter-rouge">code:</code> block, or delegates to an existing MCP npm package via an <code class="language-plaintext highlighter-rouge">npx:</code> block.
<code class="language-plaintext highlighter-rouge">server.py</code> executes each code block (or spawns the npx process), registers
every declared tool automatically, and serves them all through the single MCP
endpoint — no changes to <code class="language-plaintext highlighter-rouge">server.py</code> ever needed.</p>

<p>A minimal Python provider looks like this:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">code</span><span class="pi">:</span> <span class="pi">|</span>
  <span class="s">import datetime</span>
  <span class="s">from typing import Any</span>

  <span class="s">async def ping(context: dict[str, Any], message: str = "hello") -&gt; dict[str, Any]:</span>
      <span class="s">return {</span>
          <span class="s">"ok": True,</span>
          <span class="s">"echo": message,</span>
          <span class="s">"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),</span>
      <span class="s">}</span>

<span class="na">tools</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">ping</span>
    <span class="na">function</span><span class="pi">:</span> <span class="s">ping</span>
    <span class="na">description</span><span class="pi">:</span> <span class="s">Echo a message back with a server-side UTC timestamp.</span>
    <span class="na">input_schema</span><span class="pi">:</span>
      <span class="na">type</span><span class="pi">:</span> <span class="s">object</span>
      <span class="na">properties</span><span class="pi">:</span>
        <span class="na">message</span><span class="pi">:</span>
          <span class="na">type</span><span class="pi">:</span> <span class="s">string</span>
          <span class="na">default</span><span class="pi">:</span> <span class="s2">"</span><span class="s">hello"</span>
          <span class="na">description</span><span class="pi">:</span> <span class="s">The text to echo back.</span>
      <span class="na">required</span><span class="pi">:</span> <span class="pi">[]</span>
</code></pre></div></div>

<p>An npx-based provider is even shorter — just point at the package:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">npx</span><span class="pi">:</span>
  <span class="na">command</span><span class="pi">:</span> <span class="s">npx @playwright/mcp@latest --headless --isolated</span>

<span class="na">tools</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">browser_navigate</span>
    <span class="na">description</span><span class="pi">:</span> <span class="s">Navigate to a URL in a browser.</span>
    <span class="na">input_schema</span><span class="pi">:</span>
      <span class="na">type</span><span class="pi">:</span> <span class="s">object</span>
      <span class="na">properties</span><span class="pi">:</span>
        <span class="na">url</span><span class="pi">:</span>
          <span class="na">type</span><span class="pi">:</span> <span class="s">string</span>
      <span class="na">required</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">url</span><span class="pi">]</span>
</code></pre></div></div>

<h2 id="secret-injection">Secret Injection</h2>

<p>Secrets are declared in the provider YAML and injected from the environment at
call time.  The key design property is that secret values are <strong>never part of
the MCP tool schema</strong> — the LLM never sees them:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">tools</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">get_weather</span>
    <span class="na">function</span><span class="pi">:</span> <span class="s">get_weather</span>
    <span class="s">...</span>
    <span class="na">secrets</span><span class="pi">:</span>
      <span class="na">env</span><span class="pi">:</span>
        <span class="na">api_key</span><span class="pi">:</span> <span class="s">WEATHER_API_KEY</span>   <span class="c1"># handler arg → env var name</span>
</code></pre></div></div>

<p>The server reads <code class="language-plaintext highlighter-rouge">WEATHER_API_KEY</code> from <code class="language-plaintext highlighter-rouge">.env</code> (loaded via Docker Compose
<code class="language-plaintext highlighter-rouge">env_file</code>) and passes it to the handler as the <code class="language-plaintext highlighter-rouge">api_key</code> argument.  The LLM’s
tool schema only shows the public parameters.</p>

<h2 id="the-web-ui">The Web UI</h2>

<p>A FastAPI frontend on port 8889 handles the full provider lifecycle.</p>

<p><strong>Tools tab</strong> — lists all loaded providers in a left panel.  Click any provider
to open a form editor with its documentation, code, and per-tool fields (name,
description, parameters).  Add or remove tools with the <strong>+ Add Tool</strong> / <strong>✕</strong>
buttons, save to disk, and restart the MCP server in place — no shell access
needed.</p>

<p><strong>+ New Provider wizard</strong> — choose between a Python code provider (write
<code class="language-plaintext highlighter-rouge">async def</code> functions) and an npx package provider (enter an npx command;
the UI auto-introspects the MCP server and populates tool definitions).  The
wizard’s final step lists all required secrets and writes them to <code class="language-plaintext highlighter-rouge">.env</code>
directly.</p>

<p><strong>🔑 Secrets panel</strong> — reads all <code class="language-plaintext highlighter-rouge">secrets.env</code> entries from the selected
provider, shows which variables are already set in <code class="language-plaintext highlighter-rouge">.env</code>, and lets you fill
in or update missing values interactively.</p>

<p><strong>🛠 Run Command</strong> — runs any shell command inside the server environment and
streams output live.  Particularly useful for npx-based providers: after adding
a Playwright provider, install the Chrome binary with
<code class="language-plaintext highlighter-rouge">npx playwright install chrome</code> right from the browser panel.</p>

<h2 id="connecting-a-client">Connecting a Client</h2>

<p>The MCP endpoint is <code class="language-plaintext highlighter-rouge">http://localhost:8888/mcp</code>.  Most major clients support
the HTTP transport natively:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Claude Code</span>
claude mcp add <span class="nt">--transport</span> http mcpproxy http://localhost:8888/mcp
</code></pre></div></div>

<p>For Claude Desktop, Cursor, Cline, Continue, OpenCode, and Windsurf, add a
JSON server entry pointing at the same URL.  For Ollama (which does not speak
MCP natively), the included <code class="language-plaintext highlighter-rouge">tests/ollama_agent.py</code> bridges MCP → Ollama
tool-calling automatically:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>python3 tests/ollama_agent.py <span class="s2">"List the tools you have available"</span>
</code></pre></div></div>

<h2 id="docker">Docker</h2>

<p>A pre-built image is published to the GitHub Container Registry on every push
to <code class="language-plaintext highlighter-rouge">main</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker pull ghcr.io/billjr99/mcpproxy:latest
docker run <span class="nt">-d</span> <span class="nt">--rm</span> <span class="se">\</span>
  <span class="nt">-p</span> 8888:8888 <span class="nt">-p</span> 8889:8889 <span class="se">\</span>
  <span class="nt">--env-file</span> .env <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="si">$(</span><span class="nb">pwd</span><span class="si">)</span><span class="s2">/tools"</span>:/app/tools <span class="se">\</span>
  <span class="nt">--name</span> mcpproxy <span class="se">\</span>
  ghcr.io/billjr99/mcpproxy:latest
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">tools/</code> directory is gitignored and never baked into the image — it is
always mounted at runtime so your provider files stay outside the container.
For a persistent home directory setup that also lets the web UI’s Secrets
panel read and write <code class="language-plaintext highlighter-rouge">.env</code>, bind-mount <code class="language-plaintext highlighter-rouge">~/.mcpproxy/.env</code> into the container
and pass <code class="language-plaintext highlighter-rouge">-e MCP_ENV_FILE=/app/.env</code>.</p>

<p>A <code class="language-plaintext highlighter-rouge">docker-compose.override.yml</code> is provided for local development with
bind mounts; the base <code class="language-plaintext highlighter-rouge">docker-compose.yml</code> uses named volumes for
production/CI.</p>

<h2 id="getting-started">Getting Started</h2>

<p>The fastest path is <code class="language-plaintext highlighter-rouge">run_local.sh</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://github.com/BillJr99/mcpproxy
<span class="nb">cd </span>mcpproxy
./run_local.sh
</code></pre></div></div>

<p>The script generates <code class="language-plaintext highlighter-rouge">.env.example</code> from any existing tool YAMLs, prompts for
missing secret values, creates a virtualenv, installs dependencies, and starts
both the MCP server and the web UI.  Then open <code class="language-plaintext highlighter-rouge">http://localhost:8889</code>, click
<strong>+ New Provider</strong>, and add your first tool.</p>

<p>The unit test suite covers <code class="language-plaintext highlighter-rouge">server.py</code> helpers and all <code class="language-plaintext highlighter-rouge">frontend/app.py</code>
endpoints and runs on every push via GitHub Actions:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pip <span class="nb">install</span> <span class="nt">-r</span> requirements.txt <span class="nt">-r</span> requirements-dev.txt
pytest tests/ <span class="nt">-v</span>
</code></pre></div></div>

<p>Source code and further documentation are at
<a href="https://github.com/BillJr99/mcpproxy">https://github.com/BillJr99/mcpproxy</a>.</p>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="mcp" /><category term="agentic" /><category term="python" /><category term="docker" /><summary type="html"><![CDATA[The Model Context Protocol defines a standard way for AI clients to discover and call tools, but standing up a personal MCP server still usually means writing Python glue code, wiring up a framework, and restarting a process every time you add a tool. mcpproxy takes a different approach: every tool provider is a single YAML file, the server reloads tools at startup without any code changes to the host, and a browser-based web UI handles the full provider lifecycle — editing, secret management, and live command streaming — without leaving the browser.]]></summary></entry><entry><title type="html">AutoGUI: A Vendor-Neutral Desktop Automation Agent for LLMs</title><link href="https://www.billmongan.com/posts/2026/05/autogui/" rel="alternate" type="text/html" title="AutoGUI: A Vendor-Neutral Desktop Automation Agent for LLMs" /><published>2026-05-15T00:00:00+00:00</published><updated>2026-05-15T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/autogui</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/autogui/"><![CDATA[<p>Most LLM agents can read files, call APIs, and run shell commands, but they have
no reliable way to operate a graphical desktop. They cannot click a button in a
running application, verify that a dialog appeared, fill a form field, or observe
what is currently on screen. <a href="https://github.com/BillJr99/AutoGUI">AutoGUI</a> is a
research prototype that fills that gap. It connects any OpenAI-compatible LLM —
including models served locally through <a href="https://openwebui.com/">OpenWebUI</a> or
directly through <a href="https://ollama.com/">Ollama</a> — to a full suite of OS-level desktop
controls via a ReAct-style agentic loop.</p>

<blockquote>
  <p><strong>Experimental software — use at your own risk.</strong>
AutoGUI is a research prototype. It is not intended for, and has not been
evaluated or deemed suitable for, any particular purpose, production
use, or critical workload. No warranty is provided, express or implied.
The agent operates at OS level and can run shell commands, click anything,
type anywhere, read and write files, and take screenshots.
<strong>Run it only in a sandbox, VM, or container that you are willing to reset.</strong>
Restrict the REST API to loopback (<code class="language-plaintext highlighter-rouge">AUTOGUI_API_HOST=127.0.0.1</code>) and consider
disabling shell access (<code class="language-plaintext highlighter-rouge">"allowed_shell": false</code>) if you do not fully trust
the task or the model driving it.</p>
</blockquote>

<h2 id="two-delivery-modes">Two Delivery Modes</h2>

<p>AutoGUI ships in two forms. The standalone Python CLI/TUI agent connects any
OpenWebUI instance (or any OpenAI-compatible endpoint) to your desktop. The
native TypeScript Pi extension brings the same tools into the
<a href="https://pi.dev">Pi</a> terminal harness behind a single <code class="language-plaintext highlighter-rouge">/autogui</code> command, with
no dependency on the Python agent or OpenWebUI.</p>

<p>Both share the same tool surface — shell execution, filesystem access, pixel
and accessibility-tree clicking, Playwright browser automation — but they differ
in how the LLM loop is owned. The standalone agent runs its own ReAct loop;
the Pi extension delegates loop ownership to Pi.</p>

<h2 id="architecture">Architecture</h2>

<p>The standalone Python agent is organized around five main components.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>main.py             Entry point — validation, component wiring, TUI/CLI dispatch
│
├── agent.py        ReAct loop + typed-plan controller
│   └─ controller   Preflight, predicate checks, replan-on-block, budget ceilings
│
├── tools.py        Tool registry
│   ├─ shell_run / fs_read / fs_write / fs_list
│   ├─ desktop_screenshot / click / type / hotkey / scroll / launch
│   ├─ desktop_click_element   (a11y-first: UIAutomation / AT-SPI)
│   ├─ desktop_click_mark      (Set-of-Mark grounding)
│   ├─ browser_navigate / click / fill / eval   (Playwright)
│   ├─ skill_save / skill_list / skill_run
│   └─ memory_get / memory_note
│
├── backends/       Platform-specific automation backends
│   ├─ windows.py   UIAutomation + SendInput (user32)
│   ├─ macos.py     screencapture + osascript
│   ├─ linux_x11.py xdotool + wmctrl
│   └─ linux_wayland.py  grim + ydotool + swaymsg
│
├── api.py          FastAPI REST server (auto-started in background)
│   ├─ POST /api/task          Submit task
│   ├─ GET  /api/task/{id}/stream  SSE live event stream
│   └─ GET  /api/healthz
│
└── tui.py          Textual TUI (status bar, model picker, tool visibility toggle)
</code></pre></div></div>

<p>The agentic loop in <code class="language-plaintext highlighter-rouge">agent.py</code> follows a standard ReAct pattern — append the
user message to history, POST the history and tool schemas to the LLM, receive
either a tool call or a stop response, execute the tool, append the result, and
repeat. On top of that loop sits the controller, which adds:</p>

<ul>
  <li><strong>Planner</strong> — one extra LLM call up front that produces a numbered, high-level
plan injected as a <code class="language-plaintext highlighter-rouge">[PLAN]</code> block into the executor’s context</li>
  <li><strong>Plan critique</strong> — a second LLM call that reviews the plan and returns a
revised version when issues are found</li>
  <li><strong>Preflight</strong> — before the first state-changing action, verifies that apps are
on PATH, files exist, URLs are TCP-reachable, and named tools are registered</li>
  <li><strong>Predicate checks</strong> — when a plan step declares a typed post-condition
(<code class="language-plaintext highlighter-rouge">window_title_contains</code>, <code class="language-plaintext highlighter-rouge">file_exists</code>, <code class="language-plaintext highlighter-rouge">text_visible</code>, etc.), the controller
verifies it deterministically after each step completes</li>
  <li><strong>Replan-on-block</strong> — when a step is classified as BLOCKED, the controller
re-invokes the planner with the failure reason as context</li>
  <li><strong>Visual diff</strong> — perceptual hash of pre/post screenshots flags silent no-ops
where a state-changing action left the screen unchanged</li>
  <li><strong>Watchdog</strong> — detects when the loop is stuck by hashing the per-iteration
signature and routing repeated matches through the BLOCKED path</li>
</ul>

<h2 id="platform-support">Platform Support</h2>

<p>The correct backend is detected automatically at startup via <code class="language-plaintext highlighter-rouge">platform_detect.detect()</code>.
No configuration is required.</p>

<table>
  <thead>
    <tr>
      <th>Platform</th>
      <th>Screenshot</th>
      <th>Click/Type</th>
      <th>Accessibility Tree</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Windows</strong></td>
      <td>pyautogui</td>
      <td>SendInput (user32)</td>
      <td>UIAutomation</td>
    </tr>
    <tr>
      <td><strong>WSL</strong></td>
      <td>pyautogui</td>
      <td>pyautogui</td>
      <td>PowerShell UIAutomation</td>
    </tr>
    <tr>
      <td><strong>macOS</strong></td>
      <td>screencapture</td>
      <td>pyautogui</td>
      <td>osascript</td>
    </tr>
    <tr>
      <td><strong>Linux X11</strong></td>
      <td>pyautogui</td>
      <td>xdotool</td>
      <td>AT-SPI</td>
    </tr>
    <tr>
      <td><strong>Linux Wayland</strong></td>
      <td>grim</td>
      <td>ydotool</td>
      <td>AT-SPI</td>
    </tr>
  </tbody>
</table>

<p>On Windows, click and type operations go through <code class="language-plaintext highlighter-rouge">user32.SendInput</code> directly
via ctypes, producing real INPUT events indistinguishable from a physical
keyboard and mouse, with correct per-monitor DPI handling and full Unicode
support. On Linux, the <code class="language-plaintext highlighter-rouge">desktop_click_element</code> tool talks to the accessibility
tree via AT-SPI, letting the agent click real UI controls by name and role
rather than guessing pixel positions.</p>

<h2 id="a11y-first-clicking-and-set-of-mark-grounding">A11y-First Clicking and Set-of-Mark Grounding</h2>

<p>AutoGUI implements two layers above raw pixel clicking.</p>

<p><code class="language-plaintext highlighter-rouge">desktop_click_element(name, control_type)</code> resolves the target UI control
through the OS accessibility API and clicks it by logical identity rather than
screen position. This survives window moves, DPI scaling, and async UI redraws
that would break a coordinate-based click.</p>

<p>For cases where the accessibility tree is sparse or unavailable, Set-of-Mark
grounding overlays numbered boxes on detected UI elements in a screenshot. The
model selects an element by ID via <code class="language-plaintext highlighter-rouge">desktop_click_mark(mark_id)</code> rather than
guessing coordinates. The fallback ladder is: <code class="language-plaintext highlighter-rouge">desktop_click_element</code> →
<code class="language-plaintext highlighter-rouge">desktop_click_text</code> (OCR anchor) → <code class="language-plaintext highlighter-rouge">desktop_click_mark</code> → <code class="language-plaintext highlighter-rouge">desktop_click(x, y)</code>.</p>

<h2 id="skill-library-and-app-memory">Skill Library and App Memory</h2>

<p>Two optional persistence layers accumulate knowledge across tasks.</p>

<p>The skill library records successful tool sequences with <code class="language-plaintext highlighter-rouge">skill_save</code> and
retruns them by keyword with <code class="language-plaintext highlighter-rouge">skill_list</code> and <code class="language-plaintext highlighter-rouge">skill_run</code>. At the start of each
task the planner receives the top-3 matching skills as few-shot exemplars, so
recurring workflows get faster and more reliable over time. Skill creation is
gated by <code class="language-plaintext highlighter-rouge">agent.skills_enabled</code> (default false); reads always work.</p>

<p>The app-memory store records per-app quirks, failure counts, and free-form notes
via <code class="language-plaintext highlighter-rouge">memory_note</code>. At the start of each task the planner receives app memory
hints for any visible applications, biasing plans toward strategies that worked
before. Memory creation is gated by <code class="language-plaintext highlighter-rouge">agent.memory.enabled</code> (default false);
reads always work.</p>

<h2 id="rest-api-and-tui">REST API and TUI</h2>

<p>The FastAPI REST server starts automatically in the background whenever you run
<code class="language-plaintext highlighter-rouge">main.py</code>. It exposes task submission, SSE live event streaming, and a liveness
probe, making AutoGUI accessible to web UIs, scripts, and CI pipelines without
the terminal UI.</p>

<p>The Textual TUI provides a scrollable conversation pane with a status bar
showing the current model name, conversation length, and tool visibility state.
The live model picker (Ctrl+P → “Change Model”) fetches the current model list
from the server; selecting a model takes effect immediately and can optionally
be persisted to <code class="language-plaintext highlighter-rouge">config.json</code>.</p>

<h2 id="experimental-nature-and-safety-considerations">Experimental Nature and Safety Considerations</h2>

<p>AutoGUI is a research prototype, not a production tool. A few properties of the
current design are worth understanding before running it.</p>

<p>The destructive command guard in <code class="language-plaintext highlighter-rouge">shell_run</code> blocks patterns like <code class="language-plaintext highlighter-rouge">rm -rf</code>,
<code class="language-plaintext highlighter-rouge">DROP TABLE</code>, and <code class="language-plaintext highlighter-rouge">dd if=</code>, but it is a regex filter, not a sandbox. For
untrusted tasks, set <code class="language-plaintext highlighter-rouge">"allowed_shell": false</code> or run the agent inside a
container with a disposable filesystem.</p>

<p>The REST API has no authentication and binds to <code class="language-plaintext highlighter-rouge">0.0.0.0</code> by default. Set
<code class="language-plaintext highlighter-rouge">AUTOGUI_API_HOST=127.0.0.1</code> for loopback-only access or
<code class="language-plaintext highlighter-rouge">AUTOGUI_DISABLE_API=1</code> to disable the background API entirely.</p>

<p>The agent operates at OS level. It can click anything, type anywhere, read and
write files, and take screenshots. The safety countdown (<code class="language-plaintext highlighter-rouge">safety.command_confirm_delay_seconds</code>,
default 5 seconds) gives a visible window before each tool dispatch, with
Escape-to-cancel, but it is not a substitute for running in an environment you
are prepared to reset.</p>

<p>For the same reason, AutoGUI should not be pointed at tasks that involve
sensitive data or credentials unless the environment is appropriately isolated.
Screen content captured during observation passes through the model’s context
window; if you are using a cloud-hosted model, treat everything visible on
screen as potentially logged.</p>

<h2 id="getting-started">Getting Started</h2>

<p>Clone the repository from <a href="https://github.com/BillJr99/AutoGUI">https://github.com/BillJr99/AutoGUI</a>,
install the Python dependencies, copy <code class="language-plaintext highlighter-rouge">config.json.example</code> to <code class="language-plaintext highlighter-rouge">config.json</code>,
and set your OpenWebUI URL, API key, and model. Run <code class="language-plaintext highlighter-rouge">python main.py --check</code>
to verify connectivity before launching the TUI or issuing single-command
tasks.</p>

<p>The optional install script at <code class="language-plaintext highlighter-rouge">scripts/install-dependencies.sh</code> (or <code class="language-plaintext highlighter-rouge">.cmd</code>/<code class="language-plaintext highlighter-rouge">.ps1</code>
on Windows) adds Tesseract for OCR-anchored clicking, Playwright for browser
automation, AT-SPI on Linux for accessibility-tree element clicking, and
ImageMagick for Set-of-Mark overlays and failure GIF recording.</p>

<p>A pytest suite under <code class="language-plaintext highlighter-rouge">tests/</code> exercises the controller, predicates, budget
ceilings, preflight, and visual diff modules with no live model and no desktop
required — useful for validating changes to the orchestration logic without
burning real API calls.</p>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="agents" /><category term="desktop" /><category term="automation" /><category term="python" /><category term="typescript" /><summary type="html"><![CDATA[Most LLM agents can read files, call APIs, and run shell commands, but they have no reliable way to operate a graphical desktop. They cannot click a button in a running application, verify that a dialog appeared, fill a form field, or observe what is currently on screen. AutoGUI is a research prototype that fills that gap. It connects any OpenAI-compatible LLM — including models served locally through OpenWebUI or directly through Ollama — to a full suite of OS-level desktop controls via a ReAct-style agentic loop.]]></summary></entry><entry><title type="html">BetterWebUI: A Faculty-Friendly Agentic Front End for OpenWebUI</title><link href="https://www.billmongan.com/posts/2026/05/betterwebui/" rel="alternate" type="text/html" title="BetterWebUI: A Faculty-Friendly Agentic Front End for OpenWebUI" /><published>2026-05-15T00:00:00+00:00</published><updated>2026-05-15T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/betterwebui</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/betterwebui/"><![CDATA[<p>Most large language model interfaces are designed for developers or for a general consumer audience.
Faculty who want to use an AI assistant to help with grading, research, or course preparation either accept the
limitations of a consumer chat interface or invest significant time learning to run and configure a developer-grade
setup. <a href="https://github.com/BillJr99/BetterWebUI">BetterWebUI</a> is an attempt to close that gap.
It is a local Python/FastAPI server with a pure-HTML front end that connects to an existing
<a href="https://github.com/open-webui/open-webui">OpenWebUI</a> instance and layers on the features that make an agentic
assistant genuinely useful in a higher-education context: workspaces, skills, MCP server management, CLI shortcuts,
math rendering, and a suite of integrations with sibling agentic services.</p>

<blockquote>
  <p><strong>Experimental software — use at your own risk.</strong>
BetterWebUI is a research prototype. It is not intended for, and has not been
evaluated or deemed suitable for, any particular purpose, production
use, or critical workload. No warranty is provided, express or implied.
Shell commands approved in the chat interface execute directly on the host machine;
integrated services (CLK, AutoGUI, OSScreenObserver) may take real actions on your desktop.
Run this software only in an isolated, sandboxed environment and review
every command before approving it. By using this software you accept all
associated risks.</p>

  <p>Contributions, bug reports, and ideas are very welcome — feel free to
open an issue or pull request!</p>
</blockquote>

<h2 id="the-problem">The Problem</h2>

<p>OpenWebUI is an excellent self-hosted model interface with a wide feature set, but its feature set is also its
complexity. A faculty member who wants to run a grading assistant, attach a course rubric to every conversation in
that context, switch to a research assistant context, and then have the assistant read a file from the local
filesystem is navigating four separate configuration surfaces. BetterWebUI reduces that to a single workspace
dropdown and a file picker, while keeping all data local.</p>

<p>A second problem is tooling reach. An AI assistant that can only generate text is useful; one that can run a
pandoc conversion, call a GitHub API, fetch a web page, read the current screen state, or orchestrate a multi-step
research workflow is qualitatively more useful for the kinds of tasks faculty actually do. BetterWebUI provides
a unified approval-gated interface for all of these capabilities.</p>

<h2 id="architecture">Architecture</h2>

<p>BetterWebUI is organized around three layers: a FastAPI backend that manages state and proxies model requests;
a zero-build-step HTML/CSS/JS frontend that communicates with the backend over localhost REST calls; and an
integration layer that wraps three sibling agentic services behind a common <code class="language-plaintext highlighter-rouge">/api/services/*</code> routing namespace.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>betterwebui/
├── app.py              # FastAPI backend — model proxy, MCP manager, approval flow
├── static/             # HTML/CSS/JS frontend
├── skills/             # skill markdown files (loaded on demand)
├── services/           # integration clients (CLK, AutoGUI, OSSO)
└── data/               # config.json, conversations, workspaces, uploads
</code></pre></div></div>

<p>There is no external state. All persistent data — settings, conversations, workspaces, skill files, and
uploaded attachments — lives in the <code class="language-plaintext highlighter-rouge">data/</code> directory on the local machine. The only network traffic is
outbound to the configured OpenWebUI instance (which may itself be local) and, optionally, to the three
sibling services.</p>

<h3 id="frontend">Frontend</h3>

<p>The frontend is intentionally dependency-free from a build perspective. There is no npm build step, no webpack,
and no framework. Every feature is plain HTML, CSS, and vanilla JavaScript, loaded directly from the <code class="language-plaintext highlighter-rouge">static/</code>
directory. KaTeX is loaded from a CDN for math rendering. This makes the frontend trivially auditable and
deployable: <code class="language-plaintext highlighter-rouge">docker compose up</code> or <code class="language-plaintext highlighter-rouge">./start.sh</code> is sufficient, and the UI is available immediately at
<code class="language-plaintext highlighter-rouge">http://localhost:8765</code>.</p>

<h3 id="backend">Backend</h3>

<p>The FastAPI backend handles five primary concerns:</p>

<ul>
  <li><strong>Model proxying</strong>: BetterWebUI auto-detects which API path OpenWebUI exposes (<code class="language-plaintext highlighter-rouge">/api</code>, <code class="language-plaintext highlighter-rouge">/v1</code>, <code class="language-plaintext highlighter-rouge">/openai/v1</code>,
etc.) and forwards requests transparently, enriching them with the active workspace’s system prompt, skill
content, and any persistent files attached to the workspace.</li>
  <li><strong>MCP server management</strong>: MCP servers are spawned as subprocesses (via <code class="language-plaintext highlighter-rouge">npx</code> or <code class="language-plaintext highlighter-rouge">uvx</code>) and managed over
stdio. The backend tracks process health and surfaces startup errors in the UI.</li>
  <li><strong>Skill loading</strong>: When the assistant calls <code class="language-plaintext highlighter-rouge">load_skill</code>, the backend reads the requested skill markdown file
and injects its content into the conversation context.</li>
  <li><strong>CLI tool dispatch</strong>: The <code class="language-plaintext highlighter-rouge">cli_call</code> tool constructs a command from a registered template and the
assistant’s arguments, presents it for user approval, and executes it on approval.</li>
  <li><strong>Service integration</strong>: The <code class="language-plaintext highlighter-rouge">/api/services/*</code> namespace routes requests to CLK, AutoGUI, or OSSO,
enforces the per-service enable/disable state, and handles graceful degradation when a service is
unreachable.</li>
</ul>

<h3 id="approval-flow">Approval Flow</h3>

<p>Every action that touches the host machine is gated. Shell commands (from <code class="language-plaintext highlighter-rouge">cli_call</code> or a raw <code class="language-plaintext highlighter-rouge">run</code> block)
display a dialog showing the exact command and the assistant’s stated reason before execution. File saves
show a filename preview. File reads open a native file picker so the assistant only ever sees what the user
explicitly selects. Side-effect calls to CLK (<code class="language-plaintext highlighter-rouge">clk_research</code>), AutoGUI (<code class="language-plaintext highlighter-rouge">autogui_task</code>), and OSSO
(<code class="language-plaintext highlighter-rouge">screen_action</code>) are similarly gated. Read-only service calls (<code class="language-plaintext highlighter-rouge">screen_windows</code>, <code class="language-plaintext highlighter-rouge">screen_description</code>,
<code class="language-plaintext highlighter-rouge">screen_screenshot</code>) run without an approval prompt.</p>

<p>Shell execution can be disabled entirely from Settings, in which case <code class="language-plaintext highlighter-rouge">cli_call</code> and raw shell blocks
return a descriptive error rather than presenting an approval dialog.</p>

<h2 id="workspaces">Workspaces</h2>

<p>A workspace is a saved bundle of context: a system prompt, a chosen subset of skills, a chosen subset of MCP
servers, a chosen subset of CLI shortcuts, persistent files that are attached to every new chat in that
workspace, and an optional default model. The workspace dropdown at the top of the chat interface switches
between them with a single click, reloading the entire context.</p>

<p>The workspace model reflects how faculty actually work. A “Grading” workspace has the grading-rubric skill
loaded, a PDF of the current rubric attached, and a system prompt that frames the assistant as a grading
helper. A “Research” workspace has the research-citations skill, the Fetch and Brave Search MCP servers
enabled, and a system prompt oriented toward literature review. Switching contexts does not require
re-configuring anything; the workspace carries all of that state.</p>

<h2 id="skills">Skills</h2>

<p>Skills are markdown files in the <code class="language-plaintext highlighter-rouge">skills/</code> directory, each with a YAML frontmatter header:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">Grading Rubric Helper</span>
<span class="na">description</span><span class="pi">:</span> <span class="s">When the user wants to evaluate student work against a rubric</span>
<span class="nn">---</span>

When this skill is loaded, apply the attached rubric to the student submission...
</code></pre></div></div>

<p>The assistant sees a list of available skills and their descriptions. When a user request matches a skill’s
description, the assistant calls <code class="language-plaintext highlighter-rouge">load_skill</code> to read the full instructions and follow them. Skills are
loaded on demand rather than injected into every conversation, which keeps the context window efficient.</p>

<p>Three example skills ship with the repository: a rubric helper, a citation helper, and a computer helper.
New skills can be added from the Skills sidebar or by dropping a <code class="language-plaintext highlighter-rouge">.md</code> file into the <code class="language-plaintext highlighter-rouge">skills/</code> folder.</p>

<h2 id="mcp-servers">MCP Servers</h2>

<p>BetterWebUI manages MCP server subprocesses directly and presents them through a curated registry in the
Tools sidebar:</p>

<table>
  <thead>
    <tr>
      <th>Server</th>
      <th>Transport</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Filesystem</td>
      <td><code class="language-plaintext highlighter-rouge">npx</code></td>
      <td>Read/write files in a chosen directory</td>
    </tr>
    <tr>
      <td>GitHub</td>
      <td><code class="language-plaintext highlighter-rouge">npx</code></td>
      <td>Repos, issues, PRs (requires a PAT)</td>
    </tr>
    <tr>
      <td>Fetch</td>
      <td><code class="language-plaintext highlighter-rouge">uvx</code></td>
      <td>Retrieve and parse web pages</td>
    </tr>
    <tr>
      <td>Brave Search</td>
      <td><code class="language-plaintext highlighter-rouge">npx</code></td>
      <td>Web search (requires a Brave API key)</td>
    </tr>
    <tr>
      <td>Memory</td>
      <td><code class="language-plaintext highlighter-rouge">npx</code></td>
      <td>Persistent knowledge graph</td>
    </tr>
    <tr>
      <td>Git</td>
      <td><code class="language-plaintext highlighter-rouge">uvx</code></td>
      <td>Read a local git repo’s history</td>
    </tr>
    <tr>
      <td>Sequential Thinking</td>
      <td><code class="language-plaintext highlighter-rouge">npx</code></td>
      <td>Stepped reasoning</td>
    </tr>
    <tr>
      <td>Time</td>
      <td><code class="language-plaintext highlighter-rouge">uvx</code></td>
      <td>Accurate time and timezone conversion</td>
    </tr>
  </tbody>
</table>

<p>Custom entries can be registered with an arbitrary command and argument list. If a server fails to start,
the error message from the subprocess is surfaced in the server’s UI row so the prerequisite (typically
a missing <code class="language-plaintext highlighter-rouge">npx</code> or <code class="language-plaintext highlighter-rouge">uvx</code>) is immediately visible.</p>

<h2 id="service-integrations">Service Integrations</h2>

<p>BetterWebUI exposes three sibling agentic services through a unified <code class="language-plaintext highlighter-rouge">/api/services/*</code> routing namespace.
Each service can be enabled or disabled independently from Settings → Services. Disabled services return
HTTP 503 immediately. Enabled but unreachable services return a descriptive HTTP 503 rather than crashing.</p>

<h3 id="cognitiveloopkernel-clk">CognitiveLoopKernel (CLK)</h3>

<p><a href="https://github.com/BillJr99/CognitiveLoopKernel">CLK</a> is a local-first multi-agent development harness that
takes a natural-language idea and iterates it toward a working implementation through dynamic agent casting,
YAML workflow orchestration, and automatic git commits. Through BetterWebUI, the <code class="language-plaintext highlighter-rouge">/research &lt;topic&gt;</code> slash
command starts a CLK workflow, and the <code class="language-plaintext highlighter-rouge">clk_research</code> tool allows the assistant to initiate, monitor, and
retrieve artifacts from research loops. Every invocation requires a one-click approval showing the workflow
and command before anything executes.</p>

<h3 id="autogui">AutoGUI</h3>

<p>AutoGUI provides desktop GUI automation via a ReAct-style loop. The <code class="language-plaintext highlighter-rouge">/automate &lt;task&gt;</code> slash command sends a
task description to AutoGUI. The <code class="language-plaintext highlighter-rouge">autogui_task</code> tool surfaces the task for approval before execution. AutoGUI
runs in dry-run mode by default, which reports what it would do without taking real actions.</p>

<h3 id="osscreenobserver-osso">OSScreenObserver (OSSO)</h3>

<p><a href="https://github.com/BillJr99/OSScreenObserver">OSScreenObserver</a> exposes the operating system’s UI
accessibility tree, OCR text, and ASCII spatial sketches through an MCP interface. Through BetterWebUI, the
<code class="language-plaintext highlighter-rouge">/observe</code> slash command returns a description of the current screen. Read-only tools (<code class="language-plaintext highlighter-rouge">screen_windows</code>,
<code class="language-plaintext highlighter-rouge">screen_description</code>, <code class="language-plaintext highlighter-rouge">screen_screenshot</code>) run without an approval prompt; the <code class="language-plaintext highlighter-rouge">screen_action</code> tool, which
can click, type, and press keys on real OS controls, requires explicit approval.</p>

<h2 id="math-and-markdown">Math and Markdown</h2>

<p>The frontend renders the assistant’s responses as full markdown — headings, lists, tables, code blocks, and
links — and passes mathematical expressions through KaTeX for display-quality typesetting. Both inline
(<code class="language-plaintext highlighter-rouge">$...$</code>, <code class="language-plaintext highlighter-rouge">\(...\)</code>) and display (<code class="language-plaintext highlighter-rouge">$$...$$</code>, <code class="language-plaintext highlighter-rouge">\[...\]</code>) delimiters are supported. The assistant is
explicitly told in its system context that these delimiters are available, so it uses them naturally when
the conversation calls for mathematical notation.</p>

<h2 id="safety-considerations">Safety Considerations</h2>

<p>BetterWebUI’s approval flow is a usability safeguard, not a security boundary. Shell commands execute on
the host machine with the permissions of the user running the server. The approval dialog makes every
proposed command visible and requires an explicit click before execution, but it does not sandbox or
restrict what an approved command can do. Similarly, AutoGUI and OSScreenObserver can take real actions on
the desktop once approved.</p>

<p>This means BetterWebUI should be run in a controlled, sandboxed environment — a dedicated virtual machine
or container with limited access to sensitive files and services is the appropriate deployment context for
any non-trivial use. Multi-user deployment is not supported in the current prototype; the <code class="language-plaintext highlighter-rouge">data/</code>
directory is a flat, single-user store with no access controls.</p>

<p>Shell execution can be disabled entirely from Settings. When disabled, <code class="language-plaintext highlighter-rouge">cli_call</code> and any raw shell blocks
return a descriptive error rather than presenting an approval dialog, which reduces the tool surface to
model inference, skill loading, MCP tool calls, and read-only service queries.</p>

<h2 id="getting-started">Getting Started</h2>

<p>The fastest path is Docker:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up
<span class="c"># open http://localhost:8765</span>
</code></pre></div></div>

<p>Or directly with Python:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># macOS/Linux</span>
./start.sh

<span class="c"># Windows</span>
start.bat
</code></pre></div></div>

<p>On first run, open Settings, paste your OpenWebUI URL and API key, click <strong>Save &amp; test</strong>, and pick a
default model. If you have CLK, AutoGUI, or OSScreenObserver running on their default ports, enable them
from Settings → Services. Everything else — workspaces, skills, MCP servers — can be configured from the
sidebar without a restart.</p>

<p>The source and full documentation are available on <a href="https://github.com/BillJr99/BetterWebUI">GitHub</a>
under the MIT License.</p>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="agentic" /><category term="technical" /><category term="software" /><summary type="html"><![CDATA[Most large language model interfaces are designed for developers or for a general consumer audience. Faculty who want to use an AI assistant to help with grading, research, or course preparation either accept the limitations of a consumer chat interface or invest significant time learning to run and configure a developer-grade setup. BetterWebUI is an attempt to close that gap. It is a local Python/FastAPI server with a pure-HTML front end that connects to an existing OpenWebUI instance and layers on the features that make an agentic assistant genuinely useful in a higher-education context: workspaces, skills, MCP server management, CLI shortcuts, math rendering, and a suite of integrations with sibling agentic services.]]></summary></entry><entry><title type="html">OSScreenObserver: Giving AI Agents Eyes and Hands on Your Desktop</title><link href="https://www.billmongan.com/posts/2026/05/os-screen-observer/" rel="alternate" type="text/html" title="OSScreenObserver: Giving AI Agents Eyes and Hands on Your Desktop" /><published>2026-05-11T00:00:00+00:00</published><updated>2026-05-11T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/osscreenobserver</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/os-screen-observer/"><![CDATA[<p>Most AI agents, whether a
large language model assistant running locally or a cloud-hosted agentic framework, have no reliable way to see or
interact with the desktop applications running on the machine they are supposed to be helping with. They can read
files, call APIs, and run shell commands, but they cannot observe that a dialog box appeared, that a form field is
waiting for input, or that an application is in a specific state.
<a href="https://github.com/BillJr99/OSScreenObserver">OSScreenObserver</a> is a prototype that changes that. It exposes the
operating system’s UI accessibility tree, textual descriptions from multiple sources, and ASCII spatial sketches of
the current screen layout through two simultaneous interfaces: a browser-based web inspector for humans and an MCP
sees are always consistent.</p>

<blockquote>
  <p><strong>Experimental software — use at your own risk.</strong>
This is a research prototype. It is not intended for, and has not been
evaluated or deemed suitable for, any particular purpose, production
use, or critical workload. No warranty is provided, express or implied.
By using this software you accept all associated risks. In particular, 
I sandbox this software and use it only with local AI 
to isolate the environment and to reduce the risk of leaking
sensitive information from the desktop environment.</p>

  <p>Contributions, bug reports, and ideas are very welcome — feel free to
open an issue or pull request!</p>
</blockquote>

<h2 id="the-problem-agents-without-peripheral-vision">The Problem: Agents Without Peripheral Vision</h2>

<p>The practical limitation that motivated this project is easy to state. You are running an AI agent that is supposed to
 help you complete a task in a desktop application. The agent can reason about what to do. It can call tools. But it
cannot see the application. It cannot verify that a dialog appeared after it clicked a button. It cannot read the text
 that is currently visible on screen. It cannot detect that the application has changed state between one observation
and the next. Without that feedback loop, agentic workflows that involve desktop applications either require the human
 to narrate the screen state continuously or break silently when an unexpected dialog or error appears.</p>

<p>The two standard approaches to this problem, taking screenshots and reading them with a vision model, and using the
operating system’s accessibility API to read the UI element tree, are complementary rather than competing. Screenshots
 capture everything visible but require a model call to interpret. Accessibility trees give structured, queryable
information about UI elements but miss applications that do not instrument the accessibility API. OCR bridges the gap
for applications that are neither fully instrumented nor processed by a vision model. OSScreenObserver supports all
three modalities and lets the calling agent choose which one to use, or use all three in combination.</p>

<h2 id="architecture-two-interfaces-one-observer">Architecture: Two Interfaces, One Observer</h2>

<p>The architecture follows a principle that turns out to matter a great deal in practice: any new capability must land
simultaneously on both the REST API and the MCP server, backed by shared logic. There is no divergence between what
you can do from a browser and what an agent can do over MCP.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─────────────────────────────────────────────────────────────────────────┐
│  main.py                                                                │
│  ┌──────────────────────┐      ┌───────────────────────────────────┐    │
│  │  Flask web inspector │      │  MCP stdio server                 │    │
│  │  (background thread) │      │  (main thread, stdin/stdout)      │    │
│  └──────────┬───────────┘      └──────────────────┬────────────────┘    │
│             │                                     │                     │
│             └──────────────┬──────────────────────┘                     │
│                            ▼                                            │
│                    ScreenObserver                                       │
│                   /      │       \                                      │
│          Accessibility  ASCII    Description                            │
│             Tree      Renderer   Generator                              │
│           (observer)             (description)                          │
│                                  ┌──── accessibility (tree prose)       │
│                                  ├──── ocr (Tesseract)                  │
│                                  └──── vlm (Claude Vision)              │
└─────────────────────────────────────────────────────────────────────────┘
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">ScreenObserver</code> facade sits below both interfaces and provides three types of observation: the accessibility
element tree (structured JSON that describes every visible UI element, its role, name, value, bounds, and parent-child
 relationships), a textual description generated from the tree, from OCR, or from a vision language model, and an
ASCII spatial sketch that renders the layout of the screen as a character grid using Unicode box-drawing characters.
The sketch is more useful than it sounds: it gives an agent a token-efficient representation of the spatial
arrangement of UI elements without requiring image processing.</p>

<h2 id="observation-modalities">Observation Modalities</h2>

<h3 id="accessibility-tree">Accessibility Tree</h3>

<p>On Windows, the accessibility tree is populated using the UI Automation API, which gives full element-level
information for any application that instruments UIA. This includes most standard Windows applications: browsers,
Office applications, system dialogs, and many third-party tools. The tree traversal respects a configurable maximum
depth to avoid excessive latency on complex windows such as a browser with many DOM-mapped UIA nodes.</p>

<p>On macOS and Linux, window enumeration and screenshot capture are fully functional. Full accessibility tree support
requires additional platform libraries (pyobjc on macOS for the AX API, pyatspi on Linux for AT-SPI), and the adapter
stubs in <code class="language-plaintext highlighter-rouge">observer.py</code> provide the correct extension points for anyone who wants to contribute those implementations.</p>

<h3 id="ocr">OCR</h3>

<p>Tesseract-backed OCR runs on a screenshot of the target window and extracts text with per-word confidence scores.
Words below a configurable confidence threshold are discarded. OCR is the most broadly applicable modality: it works
on any application regardless of accessibility instrumentation, though it obviously captures only visible text and not
 the structural relationships between elements.</p>

<h3 id="vision-language-model-descriptions">Vision Language Model Descriptions</h3>

<p>When <code class="language-plaintext highlighter-rouge">vlm.enabled</code> is set to <code class="language-plaintext highlighter-rouge">true</code> in <code class="language-plaintext highlighter-rouge">config.json</code> and an Anthropic API key is present, the server can send a
screenshot to Claude and request a structured description of what is visible. The VLM description is the richest of
the three modalities in terms of semantic content, and the most expensive in terms of latency and token cost. It is
best reserved for situations where the accessibility tree is sparse (applications that do not instrument UIA), OCR is
insufficient (images, icons, non-text UI elements), or the agent needs a holistic interpretation of what is happening
on screen rather than a list of element properties.</p>

<h2 id="mcp-integration">MCP Integration</h2>

<p>The MCP server speaks JSON-RPC 2.0 over stdin/stdout and is compatible with Claude Desktop and Claude Code. Adding it
to the Claude Desktop configuration exposes a set of tools that an agent can call to observe and interact with the
desktop:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"mcpServers"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"os-screen-observer"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"command"</span><span class="p">:</span><span class="w"> </span><span class="s2">"python"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"args"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
        </span><span class="s2">"/absolute/path/to/screen_observer/main.py"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"--mode"</span><span class="p">,</span><span class="w"> </span><span class="s2">"both"</span><span class="w">
      </span><span class="p">]</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The tool surface covers observation and interaction:</p>

<table>
  <thead>
    <tr>
      <th>Tool</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">list_windows</code></td>
      <td>Enumerate all visible top-level windows</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">get_window_structure</code></td>
      <td>Full accessibility element tree as JSON</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">get_screen_description</code></td>
      <td>Prose description (accessibility / ocr / vlm / combined)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">get_screen_sketch</code></td>
      <td>ASCII spatial layout diagram</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">get_screenshot</code></td>
      <td>Screenshot as base64 PNG</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">get_full_screenshot</code></td>
      <td>Screenshot + ASCII sketch in one call</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">get_visible_areas</code></td>
      <td>Visible non-occluded bounding boxes for a window</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">bring_to_foreground</code></td>
      <td>Raise a window above others</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">click_at</code></td>
      <td>Click at pixel coordinates</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">type_text</code></td>
      <td>Type text into the focused element</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">press_key</code></td>
      <td>Press a key combination</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">scroll</code></td>
      <td>Scroll the mouse wheel at an optional screen position</td>
    </tr>
  </tbody>
</table>

<p>The get_full_screenshot tool is particularly useful for agentic workflows because it combines a screenshot with an
ASCII sketch in a single call, giving the agent both a pixel-level image and a token-efficient structural
representation without two round-trips.</p>

<h2 id="agentic-features">Agentic Features</h2>

<p>The current codebase is a working prototype. A parallel design document, agentic_features_design.md, specifies a
production-grade feature set organized into six implementation phases. The decisions in that document reflect what it
actually takes to build a reliable agentic observation loop rather than a demo.</p>

<h3 id="stable-window-identity">Stable window identity</h3>

<p>The prototype uses positional window indices, which break silently when windows open, close,
or reorder between tool calls. The agentic design introduces window_uid, a stable opaque identifier that persists
until the window closes. On Windows it is win:{pid}:{hwnd}; on macOS, mac:{cg_window_number}; on Linux,
x11:{wmctrl_id}. Every tool that accepts a window index also accepts a window UID, and a stale UID returns a typed
WindowGone error rather than silently operating on the wrong window.</p>

<h3 id="element-selectors">Element selectors</h3>

<p>Clicking at pixel coordinates is brittle. The agentic design specifies a selector grammar, both
XPath-ish and CSS-ish, both compiling to the same AST, that lets an agent refer to elements by their role, name,
value, or ancestry path through the tree. Window[name=”Notepad”]/Pane/Button[name=”OK”] is stable across window moves
and size changes in a way that a pixel coordinate is not.</p>

<h3 id="actionreceipt">ActionReceipt</h3>

<p>Every input action, click, type, key press, scroll, returns a structured receipt that includes the
before and after tree hashes, whether the tree changed as a result of the action, and whether any new dialogs
appeared. This gives an agent the feedback it needs to decide what to do next without a separate observation call.</p>

<h3 id="observe-with-diff">Observe with diff</h3>

<p>Full tree snapshots are expensive in tokens. The agentic design specifies that every tree-producing
 tool returns a tree_token, and that passing since=<tree_token> returns only a diff against the previous observation.
The diff format is a custom structure by default, with an option to request RFC 6902 JSON Patch instead.</tree_token></p>

<h3 id="wait-and-synchronize">Wait and synchronize</h3>

<p>Agents cannot reliably click a button and immediately check the result, because the result may
not be visible yet. The wait_for tool takes a list of conditions, element appears, element disappears, text becomes
visible, window appears, tree changes, and polls until one of them is satisfied or a timeout is reached. The response
includes which condition matched and how many polls it took.</p>

<h3 id="typed-error-taxonomy">Typed error taxonomy</h3>

<p>Rather than returning a generic error string, every failure returns a structured object with a
code, a recoverable flag, and a suggested_next_tool. ElementNotFound suggests find_element. ElementOccluded suggests
bring_to_foreground. ConfirmationRequired suggests propose_action. An agent that branches on error.code can recover
from most transient failures without human intervention.</p>

<h3 id="record-replay-and-evaluation">Record, replay, and evaluation</h3>

<p>Building an evaluation substrate for desktop agents requires the ability to record
what an agent did and replay it against a consistent environment. The design specifies a tracing format (JSONL with
per-step screenshots), a replay engine with per-tool comparison rules that know which fields are deterministic and
which are not, and a YAML scenario DSL for scripting mock environments with state-machine reactions. An agent can be
evaluated against a scripted scenario, its trace replayed in verify mode, and the divergences surfaced as structured
data.</p>

<h3 id="confirmation-tokens">Confirmation tokens</h3>

<p>Some actions are destructive. The confirmation token flow lets an agent propose an action and
receive a token bound to the target element’s position and identity. The actual action only proceeds if the agent
presents a valid, unexpired token and the element has not moved by more than a configurable pixel tolerance. This is a
 lightweight safeguard against the category of error where an agent clicks the wrong thing because the UI shifted
between the proposal and the execution.</p>

<h3 id="redaction">Redaction</h3>

<p>Screen content may contain sensitive information: passwords, PINs, SSNs, anything that should not appear in
 a trace or in the context window of a cloud-hosted model. The redaction system matches element names, values, OCR
text, and window titles against configurable patterns and replaces matches with a replacement string before they
appear in any tool response or trace entry. Screenshot blur is available as an opt-in for visual redaction.</p>

<h2 id="the-web-inspector">The Web Inspector</h2>

<p>The web inspector at <code class="language-plaintext highlighter-rouge">localhost:5001</code> provides five tabs for human-facing observation.</p>

<p>The <code class="language-plaintext highlighter-rouge">STRUCTURE</code> tab renders the accessibility element hierarchy as an interactive collapsible JSON tree. This is the
fastest way to understand what elements a particular application exposes and how they are organized.</p>

<p>The <code class="language-plaintext highlighter-rouge">DESCRIPTION</code> tab shows a prose description of the selected window, with a mode selector that switches between
accessibility tree prose, OCR output, VLM output, and a combined view.</p>

<p>The <code class="language-plaintext highlighter-rouge">SKETCH</code> tab renders the ASCII spatial diagram of the window layout, the same output that the get_screen_sketch MCP
tool returns.</p>

<p>The <code class="language-plaintext highlighter-rouge">SCREENSHOT</code> tab shows the pixel screenshot alongside visible-area bounding boxes and the ASCII sketch in a single
panel.</p>

<p>The <code class="language-plaintext highlighter-rouge">ACTIONS</code> tab provides a UI for clicking at coordinates, typing text, and pressing key combinations, which is useful
 for testing input flows interactively before encoding them in an agent script.</p>

<p>The sidebar lists all visible windows. Clicking one selects it, and all tabs update to reflect the selected window.
Auto-refresh polls every three seconds.</p>

<h2 id="mock-mode-and-testing">Mock Mode and Testing</h2>

<p>A persistent problem with tools that depend on a running desktop is that they are difficult to test in CI.
OSScreenObserver includes a mock adapter that returns scripted window and tree data without requiring any OS access.
Tests run under –mock or via direct module imports and never need a desktop session. The CI workflow runs ruff for
linting and pytest for the test suite, with no Docker or virtual display required.</p>

<p>The agentic feature design extends mock mode with the scenario DSL, which lets you script a realistic application
environment with state-machine reactions: set a username field and the element’s value changes; click the login button
 with the right credentials and the application transitions to the welcome screen. This is the substrate on which
agent evaluation becomes reproducible rather than dependent on whatever application happens to be running.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Running OSScreenObserver against real applications quickly reveals which applications are well-instrumented for
accessibility and which are not. Standard Windows applications, system dialogs, and browsers expose rich trees.
Electron applications with custom renderers, games, and some creative tools produce sparse trees where OCR and VLM
descriptions carry most of the weight. The three-modality design is not over-engineering; it reflects the actual
distribution of desktop applications that an agent might encounter.</p>

<p>The prompt injection risk is worth naming explicitly: screen content is included verbatim in tool results, which means
 that malicious content visible on screen, a web page with injected text, a document with embedded instructions, could
 attempt to influence the agent’s behavior. The same trust boundaries that apply to any tool that reads external
content apply here. The redaction system is a partial mitigation, but the appropriate response to this risk depends on
 the deployment context.</p>

<p>The setup cost is low for Windows users who want full functionality. Python, Tesseract for OCR, an Anthropic API key
for VLM descriptions if desired, and the package from the repository (<a href="https://github.com/BillJr99/OSScreenObserver">https://github.com/BillJr99/OSScreenObserver</a>).
The mock mode means you can explore the API and the web inspector without any platform-specific setup at all.</p>

<p>What OSScreenObserver ultimately provides is a bridge between the textual nature of large language models and the inherently visual, event-driven world of desktop applications. Rather than forcing agents to reason about pixel coordinates or raw images, the accessibility tree, OCR output, and ASCII spatial sketches give them structured, token-efficient representations of the desktop that align naturally with how LLMs process information. An agent that can read the UI as text, act on it through typed tool calls, and receive structured feedback about what changed is operating in a modality much closer to its native one — and that alignment is what makes reliable agentic desktop interaction tractable rather than brittle.</p>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="agents" /><category term="mcp" /><category term="accessibility" /><category term="python" /><summary type="html"><![CDATA[Most AI agents, whether a large language model assistant running locally or a cloud-hosted agentic framework, have no reliable way to see or interact with the desktop applications running on the machine they are supposed to be helping with. They can read files, call APIs, and run shell commands, but they cannot observe that a dialog box appeared, that a form field is waiting for input, or that an application is in a specific state. OSScreenObserver is a prototype that changes that. It exposes the operating system’s UI accessibility tree, textual descriptions from multiple sources, and ASCII spatial sketches of the current screen layout through two simultaneous interfaces: a browser-based web inspector for humans and an MCP sees are always consistent.]]></summary></entry><entry><title type="html">A Private AI Knowledge Base: Obsidian, GitHub Sync, and Cross-Platform AI Context</title><link href="https://www.billmongan.com/posts/2026/05/obsidian-ai-vault/" rel="alternate" type="text/html" title="A Private AI Knowledge Base: Obsidian, GitHub Sync, and Cross-Platform AI Context" /><published>2026-05-02T00:00:00+00:00</published><updated>2026-05-02T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/obsidianai</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/obsidian-ai-vault/"><![CDATA[<p>For the past year I have been building a knowledge management system with a specific design constraint in mind: every AI system I work with, whether a cloud-hosted assistant, a local agentic coding tool, or an automated GitHub Action, should be able to read the same authoritative description of who I am, what I am working on, and how I want to interact. More importantly, those systems should be able to write back into the knowledge base and have their work appear seamlessly in Obsidian on my local machine the next time I open the app. The proliferation of capable AI tools in 2025-2026 made both sides of this problem, reading and writing, tractable in a way they had not been before. This post documents the architecture I settled on: an Obsidian vault hosted on GitHub, synchronized via the Gitless Sync plugin, structured around three canonical files that any AI system can read and act on, and organized into a curated wiki that agents can query, extend, and maintain across platforms.</p>

<h2 id="motivation-context-as-a-first-class-artifact">Motivation: Context as a First-Class Artifact</h2>

<p>The practical problem is straightforward. Suppose you work with five or six AI tools on a regular basis: a web-based assistant with a custom instructions field, a local agentic coding CLI with a project context file, a GitHub-hosted agent that runs on repository events, and a few others. Each of these tools has its own mechanism for persistent context, and none of them are the same. You end up with five slightly different versions of your professional profile, your project list, and your working preferences, stored in five incompatible formats in five different places. When something changes, such as a new role, a new project, or a preference update, you update one and forget the others.</p>

<p>The deeper problem is that these tools are increasingly doing things that matter: drafting documents, running code, making commits, composing correspondence. Inconsistent context means inconsistent decisions about what to include, what to assume, and how to frame outputs. Getting this right is worth the architectural investment.</p>

<p>The solution is to store context in a Git repository, maintain it with the same discipline you would apply to any other codebase, and give every AI system a well-specified path to read from and write to it. Obsidian provides the human-readable and human-editable interface. GitHub provides the hosting, versioning, and webhook surface that agents need. The Gitless Sync plugin provides the bridge between the two, and the key insight of the design is that this bridge works in both directions: agents can push changes to GitHub and those changes will appear in Obsidian on the next sync, as long as they follow the metadata protocol described in <code class="language-plaintext highlighter-rouge">AGENTS.md</code>.</p>

<h2 id="hardware-and-local-setup">Hardware and Local Setup</h2>

<p>The vault lives on my primary workstation. Obsidian is installed and runs against a directory in the home filesystem. This placement is intentional: on machines that also run local agentic tools, the vault directory is on the same filesystem as the agent workspace, so local agents can read from or write to it without any network call by bind-mounting the directory into their container.</p>

<p>The GitHub repository that backs the vault is a standard private repository. The local Obsidian directory and the GitHub repository are not connected through standard Git tooling on the workstation. There is no <code class="language-plaintext highlighter-rouge">.git</code> directory in the vault folder, no <code class="language-plaintext highlighter-rouge">git pull</code> or <code class="language-plaintext highlighter-rouge">git push</code> in any shell script, and no SSH key configured for this purpose. Synchronization is handled entirely by the Obsidian plugin described in the next section. This is a deliberate choice: it removes any risk of a merge conflict or detached HEAD state caused by operations outside of Obsidian, and it means the sync mechanism is consistent regardless of whether I am running Obsidian on a desktop, a laptop, or the mobile app.</p>

<h2 id="github-gitless-sync-plugin-setup">GitHub Gitless Sync: Plugin Setup</h2>

<p><a href="https://github.com/silvanocerza/obsidian-github-sync">Obsidian Gitless Sync</a> is a community plugin that synchronizes an Obsidian vault directly with a GitHub repository using the GitHub REST API, without requiring Git to be installed locally and without creating a <code class="language-plaintext highlighter-rouge">.git</code> directory. Each file operation, create, modify, rename, delete, is translated into the corresponding GitHub API call, and the plugin tracks the synchronization state of every file in a local metadata file at <code class="language-plaintext highlighter-rouge">.obsidian/github-sync-metadata.json</code>.</p>

<p>Installation follows the standard community plugin path in Obsidian Settings: disable safe mode, browse community plugins, search for Gitless Sync, install, and enable. Configuration requires four values: a GitHub Personal Access Token with <code class="language-plaintext highlighter-rouge">repo</code> scope, the repository owner, the repository name, and the branch to synchronize against.</p>

<p>After configuration, the plugin performs an initial sync that either pushes the local vault to the empty repository or pulls a pre-existing repository into the local vault. Subsequent syncs are triggered manually through the command palette or automatically on a configurable interval. The sync direction is bidirectional: local changes are pushed to GitHub, and remote changes, including those made by agents or GitHub Actions, are pulled to the local vault.</p>

<p>The operational requirement worth emphasizing is that the GitHub PAT must have <code class="language-plaintext highlighter-rouge">repo</code> scope and must not expire during active use. A token expiration silently breaks sync in a way that is not immediately obvious: Obsidian continues to operate against the local files, and the failure only becomes apparent when an agent’s changes from two days ago have not appeared.</p>

<h2 id="the-key-insight-agents-can-write-not-just-read">The Key Insight: Agents Can Write, Not Just Read</h2>

<p>A common misunderstanding about this setup is that it is read-only from the agent’s perspective, with agents merely consuming context and humans maintaining the vault. The actual design is the opposite. Agents are the primary authors of <code class="language-plaintext highlighter-rouge">/wiki/</code>. Their job is to read source material from <code class="language-plaintext highlighter-rouge">/raw/</code>, synthesize it into structured Markdown, and write the results into <code class="language-plaintext highlighter-rouge">/wiki/</code> through the GitHub REST API. Those writes propagate to Obsidian on the next sync, and the result appears in the local vault as fully navigable, cross-linked notes.</p>

<p>The mechanism that makes this work is the metadata file. Any process that creates or modifies vault files through GitHub must also update <code class="language-plaintext highlighter-rouge">.obsidian/github-sync-metadata.json</code> in the same atomic commit. Without that update, Obsidian’s sync plugin has no record of the change and will not pull it on the next sync. The entire agent write protocol is designed around maintaining this invariant. The full specification of how agents must behave is documented in <code class="language-plaintext highlighter-rouge">AGENTS.md</code>, linked and described in detail below.</p>

<h2 id="the-sha-computation-protocol">The SHA Computation Protocol</h2>

<p>The <code class="language-plaintext highlighter-rouge">sha</code> field in the sync metadata is not a plain SHA-1 of the file’s bytes. It is a Git blob SHA, which Git computes by prepending a header to the raw file content before hashing. Any agent writing to the repository and updating the metadata must implement this correctly, or the sync plugin will treat the file as modified on the next pull.</p>

<p>The algorithm is:</p>

<ol>
  <li>Read the raw bytes of the file. Use the byte length, not the character count; this distinction matters for any file containing multi-byte Unicode characters.</li>
  <li>Construct the header string <code class="language-plaintext highlighter-rouge">blob {N}\0</code>, where <code class="language-plaintext highlighter-rouge">{N}</code> is the ASCII decimal representation of the byte length and <code class="language-plaintext highlighter-rouge">\0</code> is a literal null byte (0x00).</li>
  <li>Concatenate the header bytes and the raw file bytes.</li>
  <li>Apply SHA-1 to the concatenated byte stream.</li>
  <li>Encode the result as a 40-character lowercase hexadecimal string.
This is exactly what <code class="language-plaintext highlighter-rouge">git hash-object</code> produces and what the GitHub REST API returns in the <code class="language-plaintext highlighter-rouge">sha</code> field of blob responses. A common mistake is to hash the string representation of the content rather than the raw bytes, or to apply SHA-1 without the header. Both produce incorrect values that will not match what GitHub stores.</li>
</ol>

<p>In practice, there is a simpler path for most agent use cases: set <code class="language-plaintext highlighter-rouge">sha</code> to <code class="language-plaintext highlighter-rouge">null</code> and <code class="language-plaintext highlighter-rouge">dirty</code> to <code class="language-plaintext highlighter-rouge">true</code> in the metadata entry after creating or modifying a file. The sync plugin will upload the file on the next sync and replace the null with the API-confirmed SHA. The full SHA computation is only necessary when you want to pre-cache the expected value and avoid a redundant upload. Each metadata entry follows this schema:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"path"</span><span class="p">:</span><span class="w"> </span><span class="s2">"relative/path/from/vault/root/to/file.md"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"sha"</span><span class="p">:</span><span class="w"> </span><span class="s2">"&lt;40-char hex string or null&gt;"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"dirty"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w">
  </span><span class="nl">"justDownloaded"</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="p">,</span><span class="w">
  </span><span class="nl">"lastModified"</span><span class="p">:</span><span class="w"> </span><span class="mi">1234567890000</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>After creating or modifying a file, set <code class="language-plaintext highlighter-rouge">dirty: true</code> and <code class="language-plaintext highlighter-rouge">lastModified</code> to <code class="language-plaintext highlighter-rouge">Date.now()</code> in milliseconds. The file and the metadata update must be committed together, atomically. Splitting them across separate commits will cause the sync plugin to mis-handle the change.</p>

<p>For deletions, the entry must include <code class="language-plaintext highlighter-rouge">deleted: true</code> and <code class="language-plaintext highlighter-rouge">deletedAt</code> alongside the path. The deleted file and the metadata update must again be committed in a single atomic operation.</p>

<h2 id="vault-structure-the-three-zone-design">Vault Structure: The Three-Zone Design</h2>

<p>The three-zone structure closely follows the layered architecture Andrej Karpathy described in his April 2026 LLM Wiki gist (<a href="https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f">gist.github.com/karpathy/442a6bf555914893e9891c11519de94f</a>): immutable raw sources that the LLM reads but never modifies, a wiki layer of structured Markdown that the LLM writes and maintains, and a schema file (his term for what this vault calls <code class="language-plaintext highlighter-rouge">AGENTS.md</code>) that specifies conventions and workflows.</p>

<p>The vault is organized into three functional zones with strictly enforced read/write boundaries.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vault/
├── AGENTS.md           # Agent instructions (authoritative)
├── LLMMEMORIES.md      # Persistent user context for AI systems
├── SYSTEMPROMPT.md     # Standing system prompt and interaction preferences
├── raw/                # READ-ONLY source material inbox
│   └── *.md, *.pdf     # Unprocessed documents; never modified by agents
├── wiki/               # Curated, cross-linked knowledge base
│   ├── index.md        # Hub: overview and active work
│   └── */              # Subdirectories organized by domain
└── .obsidian/
    └── github-sync-metadata.json   # Sync state (managed by plugin + agents)
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">raw/</code> directory is a one-way inbox. Documents are dropped there and never touched again by anyone, human or agent. Agents read from <code class="language-plaintext highlighter-rouge">raw/</code> and write exclusively to <code class="language-plaintext highlighter-rouge">wiki/</code>. This separation means that the curated knowledge base in <code class="language-plaintext highlighter-rouge">wiki/</code> is never contaminated by unprocessed source material, and source documents are never accidentally overwritten by agent activity.</p>

<p>The root-level canonical files (<code class="language-plaintext highlighter-rouge">AGENTS.md</code>, <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code>, <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code>) are the only files that belong at the repository root. All authored content, every wiki page, every topic note, every hub index, belongs inside <code class="language-plaintext highlighter-rouge">wiki/</code> under an appropriate subdirectory. The root is intentionally clean. If a change appears to require a new root-level file or directory, the right answer is almost certainly that it belongs inside <code class="language-plaintext highlighter-rouge">wiki/</code> instead.</p>

<h2 id="agentsmd-the-complete-agent-specification">AGENTS.md: The Complete Agent Specification</h2>

<p>The <code class="language-plaintext highlighter-rouge">AGENTS.md</code> file is the single most important document in the repository. It is the file that GitHub-hosted agents, agentic CLI tools, GitHub Actions workflows, and any other automated process reads first when it encounters this repository.</p>

<p>The file opens with a non-negotiable preamble that instructs any agent encountering the repository to stop and read the file completely before taking any action. This is the architectural guarantee that makes the system self-documenting: the repository itself carries the complete specification for how to operate on it.</p>

<h3 id="repository-role-and-core-mandate">Repository Role and Core Mandate</h3>

<p>The opening section establishes the conceptual model precisely. <code class="language-plaintext highlighter-rouge">/raw/</code> is the unprocessed source-material inbox. <code class="language-plaintext highlighter-rouge">/wiki/</code> is the curated knowledge base. The agent’s responsibility is to transform material from <code class="language-plaintext highlighter-rouge">/raw/</code> into a structured, cross-linked, maintainable Markdown knowledge base in <code class="language-plaintext highlighter-rouge">/wiki/</code>. The core mandate is stated as a numbered list: open and inspect the repository; read relevant materials in <code class="language-plaintext highlighter-rouge">/raw/</code>; build, maintain, and improve a coherent knowledge base in <code class="language-plaintext highlighter-rouge">/wiki/</code>; create, update, reorganize, and cross-link Markdown notes in <code class="language-plaintext highlighter-rouge">/wiki/</code>; commit and push changes back to the repository when changes are made; and when asked questions, answer using <code class="language-plaintext highlighter-rouge">/wiki/</code> first.</p>

<h3 id="boundary-rules-what-agents-must-never-touch">Boundary Rules: What Agents Must Never Touch</h3>

<p><code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies three zones that are completely off-limits to agents, and the specificity of these prohibitions is what makes them enforceable.</p>

<p><code class="language-plaintext highlighter-rouge">/raw/</code> is strictly read-only. Agents must never modify, delete, rename, move, or create files in <code class="language-plaintext highlighter-rouge">/raw/</code>. All synthesis, editing, organization, and authored content must go into <code class="language-plaintext highlighter-rouge">/wiki/</code>. The source inbox is preserved exactly as it was received.</p>

<p><code class="language-plaintext highlighter-rouge">.obsidian/</code> is managed exclusively by Obsidian and must not be modified by agents, with one precisely stated exception: <code class="language-plaintext highlighter-rouge">.obsidian/github-sync-metadata.json</code> must be updated whenever an agent creates, modifies, renames, or deletes any file outside of Obsidian. No other file inside <code class="language-plaintext highlighter-rouge">.obsidian/</code> may be touched under any circumstances.</p>

<p><code class="language-plaintext highlighter-rouge">/.trash/</code> is managed exclusively by Obsidian offline and must be left entirely alone. Agents must not read, modify, delete, or create files in <code class="language-plaintext highlighter-rouge">/.trash/</code>, and must ignore its contents entirely during all operations. This directory accumulates files that Obsidian has soft-deleted, and any agent interaction with it could corrupt Obsidian’s delete state.</p>

<h3 id="quick-start-workflow">Quick Start Workflow</h3>

<p>For any agent starting a session against this repository, <code class="language-plaintext highlighter-rouge">AGENTS.md</code> provides a numbered quick-start workflow that specifies exactly what to do and in what order. Open the repository; read <code class="language-plaintext highlighter-rouge">AGENTS.md</code> completely; inspect the current structure and contents of <code class="language-plaintext highlighter-rouge">/wiki/</code>; inspect relevant material in <code class="language-plaintext highlighter-rouge">/raw/</code>; decide what should be created, updated, merged, linked, or reorganized in <code class="language-plaintext highlighter-rouge">/wiki/</code>; apply changes in <code class="language-plaintext highlighter-rouge">/wiki/</code> only; commit and push the changes; and if a question was asked, answer it using the curated knowledge in <code class="language-plaintext highlighter-rouge">/wiki/</code>.</p>

<p>The sequencing is intentional. Reading the existing wiki structure before making any changes prevents agents from creating duplicate pages, overwriting useful content, or restructuring areas that are already well-organized.</p>

<h3 id="operational-rules-synthesis-not-mirroring">Operational Rules: Synthesis, Not Mirroring</h3>

<p>A critical section of <code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies how agents should treat source material. The wiki is a curated layer, not a verbatim mirror of <code class="language-plaintext highlighter-rouge">/raw/</code>. Agents are expected to synthesize, summarize, normalize, deduplicate, and organize source material rather than transcribing it. They should prefer updating existing canonical notes over creating duplicates, and should create new notes when a topic clearly deserves its own page. Existing wiki content should be preserved unless it is redundant, obsolete, inaccurate, or clearly inferior to better source material.</p>

<p>The rules also require maintaining factual nuance and uncertainty. Agents must not overstate claims found in source materials. If source materials conflict, the disagreement must be explicitly noted rather than silently resolved. If a source is incomplete, fragmented, or ambiguous, the uncertainty must be marked in the resulting wiki page rather than smoothed over.</p>

<h3 id="organization-requirements">Organization Requirements</h3>

<p><code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies that <code class="language-plaintext highlighter-rouge">/wiki/</code> must be organized into clear, intuitive, scalable topical categories expressed as high-level directories with meaningful subdirectories. The wiki must never be a flat dump of loose notes at its top level. Related notes must be grouped under shared parent directories, with finer topics nested beneath broader domains. New top-level categories should be introduced when they have earned their place, and subdirectories should be split further as a topic grows.</p>

<p>The file explicitly names the page types that should be maintained where appropriate: overview pages, topic pages, concept and reference pages, project pages, people pages, hub and index pages, and chronology or notes pages. Category and hub pages should be created when they improve navigation. Filenames should be stable and human-readable. The guiding principle is a small number of well-maintained canonical pages over many fragmented or overlapping notes.</p>

<p>Reorganization is permitted and encouraged when it improves hierarchy, clarity, or navigability, but specifically prohibited when it is cosmetic or churns structure for its own sake. The instruction is direct: do not degrade a well-organized area with unnecessary restructuring.</p>

<h3 id="linking-and-navigation">Linking and Navigation</h3>

<p><code class="language-plaintext highlighter-rouge">AGENTS.md</code> requires that agents use Obsidian wikilinks extensively and meaningfully:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[[Page Name]]
</code></pre></div></div>

<p>Every wiki note should connect related ideas across the vault. “Related” or “See also” sections should be added where useful. Large blocks of content should be linked rather than duplicated. Each page should fit meaningfully into the larger structure, and hub pages should be created when they improve discoverability.</p>

<h3 id="formatting-expectations">Formatting Expectations</h3>

<p>All authored content must be Markdown only, clearly titled, readable and well-structured, concise but sufficiently specific, and polished rather than raw. Headings should be used when they improve structure, bullet points when they improve clarity, and tables only when they are genuinely useful. Pages should begin with a short summary when appropriate. Generic filler summaries that erase important details are explicitly prohibited.</p>

<h3 id="document-ingestion-protocol">Document Ingestion Protocol</h3>

<p>When a new document appears in <code class="language-plaintext highlighter-rouge">/raw/</code> or an agent is asked to ingest a document, <code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies a complete ingestion protocol. Read the document fully before making any changes. Identify content that maps to existing wiki pages and merge or enrich those pages rather than duplicating them. Create new wiki pages when a topic is substantial enough to deserve its own page. Reorganize files and directory structures when the new content warrants it, for example by introducing a new subdirectory if a category of content has grown, or renaming pages, or moving pages between directories. Update all hub and index pages to reflect any new pages created or any structural changes made. Cross-link newly created or updated pages into related pages using Obsidian wikilinks. Update <code class="language-plaintext highlighter-rouge">.obsidian/github-sync-metadata.json</code> for every file created or modified, following the SHA computation protocol. Commit and push all changes atomically when the ingestion is complete.</p>

<h3 id="wiki-linter-a-built-in-maintenance-agent-task">Wiki Linter: A Built-In Maintenance Agent Task</h3>

<p>One of the more distinctive features of <code class="language-plaintext highlighter-rouge">AGENTS.md</code> is a detailed specification for a wiki linter, a maintenance agent task that audits and repairs the vault’s structural integrity, link validity, and metadata completeness. The linter is described as a seven-step workflow that any agent can execute.</p>

<p>Step 1 identifies the vault metadata JSON file by checking the standard locations for community plugins before proceeding. Step 2 recursively enumerates all vault files, including those in <code class="language-plaintext highlighter-rouge">.trash/</code>, building complete lists of markdown files and non-markdown assets. Step 3 scans every markdown file for internal Obsidian wikilinks and standard relative markdown links, resolves each link against the full file list using Obsidian’s resolution rules (case-insensitive match on filename without extension, shortest-path-wins for ambiguous names), and classifies each as valid, broken due to file not found, broken due to ambiguity, or broken due to a missing heading. Broken links are repaired according to a precisely specified strategy: links with no plausible near-match have their syntax removed with an inline comment; links with a near-match (edit distance of 2 or less on the base filename) have the target corrected with an inline comment; broken heading links have the fragment removed while the file link is preserved.</p>

<p>Step 4 audits the metadata JSON for completeness, verifying that every markdown file has a corresponding entry with all required fields. Missing entries are synthesized using the existing schema as a template, populated from the file’s YAML frontmatter and filesystem timestamps where available. Step 5 validates the metadata JSON for well-formedness: valid JSON with no trailing commas or comments, all path keys using forward slashes, all date fields in ISO 8601 format, no raw newlines within string values, and UTF-8 encoding without BOM.</p>

<p>Step 6 updates <code class="language-plaintext highlighter-rouge">AGENTS.md</code> itself and its metadata entry to reflect the current UTC datetime, so that Obsidian Sync recognizes the file as modified and pulls the updated version on the next sync. Step 7 writes a linting report file to the repository root with a full summary of findings, broken links, metadata gaps, items requiring manual review, and files modified during the run.</p>

<p>The linter’s execution rules are notable for their conservatism: every file write is preceded by a diff against the current content, and the file is not written if the diff is empty. Ambiguous or destructive repairs, such as removing more than a link fragment, are flagged for manual review rather than applied automatically. The linter never modifies any file in <code class="language-plaintext highlighter-rouge">.obsidian/</code> except the metadata JSON, and if running in an environment without write access it produces a dry-run diff report instead of writing files.</p>

<h3 id="question-answering-mode">Question-Answering Mode</h3>

<p><code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies how agents should behave when asked a question and told to use the vault. They must open the repository and read <code class="language-plaintext highlighter-rouge">/wiki/</code> first as the primary and authoritative curated knowledge source. <code class="language-plaintext highlighter-rouge">/raw/</code> is consulted only to fill gaps, verify details, or incorporate newly added material not yet reflected in <code class="language-plaintext highlighter-rouge">/wiki/</code>. If <code class="language-plaintext highlighter-rouge">/wiki/</code> is incomplete or outdated relative to <code class="language-plaintext highlighter-rouge">/raw/</code>, the agent should update <code class="language-plaintext highlighter-rouge">/wiki/</code> first when appropriate, before answering the question.</p>

<p>This sequencing, wiki first and raw as a fallback rather than a primary source, is what makes the curated knowledge base progressively more valuable over time. Each question that exposes a gap is an opportunity to improve the wiki before answering.</p>

<h2 id="llmmemoriesmd-cross-platform-persistent-memory">LLMMEMORIES.md: Cross-Platform Persistent Memory</h2>

<p><code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code> is the canonical record of persistent user context. It is structured as a Markdown document with clearly delineated sections covering identity and roles, academic credentials, teaching responsibilities, research background, active funded projects, collaborators, and working preferences.</p>

<p>The key design principle, stated explicitly in <code class="language-plaintext highlighter-rouge">AGENTS.md</code>, is that this file is bidirectionally synchronized. When an AI system forms a more accurate or more detailed picture of some aspect of your context through extended interaction, that updated understanding should be written back into <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code>. When <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code> is updated in the repository, any agent starting a new session should read the new version and treat it as authoritative. The file is, in effect, an externalized, version-controlled memory store that persists across tools, sessions, and platforms.</p>

<p>When starting any session, <code class="language-plaintext highlighter-rouge">AGENTS.md</code> instructs agents to read both <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code> and <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code> and treat them as authoritative context alongside <code class="language-plaintext highlighter-rouge">AGENTS.md</code> itself.</p>

<h2 id="systempromptmd-twelve-sections-of-standing-instructions">SYSTEMPROMPT.md: Twelve Sections of Standing Instructions</h2>

<p><code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code> captures the behavioral and stylistic instructions that would otherwise need to be pasted into the system prompt or custom instructions field of each tool individually. It is organized into twelve numbered sections.</p>

<p><strong>Section 1: Identity and Role Context</strong> establishes professional identity and secondary identities relevant to task framing, including domain-specific calibration instructions. The purpose is not to describe the person to themselves but to give AI tools enough context to calibrate depth, vocabulary, and framing automatically without requiring re-explanation each session.</p>

<p><strong>Section 2: Communication and Output Style</strong> covers prose and academic writing, email and correspondence, and document formatting. Academic writing uses complex and compound-complex sentences with commas, a challenges-first structure, first-person plural (“we”) for academic contexts, hedging by scope condition rather than weakened claims, precise technical vocabulary, and lists framed by prose. The prohibition on em dashes is explicit: they must be replaced with commas, subordinate clauses, or restructured sentences. Email style is short, direct, and warm, opening with “Hi [Name]!” and closing with “Bill”, committing rather than hedging, and appropriate for mild humor in familiar professional contexts.</p>

<p><strong>Section 3: Technical and Coding Preferences</strong> specifies exception handling conventions (print with a location-specific prefix string plus <code class="language-plaintext highlighter-rouge">traceback.print_exc()</code>, never silently swallow exceptions), a requirement to provide complete revised function definitions rather than partial snippets or ellipsis-truncated fragments, a preference for externalizing all configuration into JSON files with configurable logging levels, a preferred technical stack for ML and pipeline work, and instructional code conventions that interleave mathematical derivations and conceptual explanations with implementation.</p>

<p><strong>Section 4: Task Execution Behavior</strong> covers three sub-protocols. Before starting any task, an agent must read any <code class="language-plaintext highlighter-rouge">context/</code> or <code class="language-plaintext highlighter-rouge">ABOUT-ME/</code> directory, any <code class="language-plaintext highlighter-rouge">SYSTEM-RULES.md</code> or <code class="language-plaintext highlighter-rouge">HOW-I-WORK.md</code> file, and any project-specific subfolder or template that applies to the task. The clarification protocol prohibits beginning execution if the goal, intended audience, output format, or scope is ambiguous in ways that would materially affect the output. Output discipline requires stating assumptions explicitly and flagging uncertainty inline rather than omitting it.</p>

<p><strong>Section 5: Domain-Specific Standing Instructions</strong> covers machine learning and AI (maintaining precision with probabilistic claims and applying existing pipeline architecture by default), computer science education and SoTL (grounding pedagogical recommendations in literature and noting evidentiary basis), grant and sponsored research writing (active voice, outcome-oriented framing, explicit distinctions between completed and proposed work), aviation and drone operations (applying FAA regulatory context from 14 CFR Parts 61, 91, and 107 as appropriate), and amateur radio (applying ITU and FCC Part 97 context, distinguishing between amateur and emergency communication contexts).</p>

<p><strong>Section 6: Memory and Context Hygiene</strong> addresses the stateless nature of many AI sessions. Workspace folder context files are the authoritative persistent memory, not inferred prior session context. If a task produces information that should persist across sessions, the instruction is to suggest saving it to the appropriate context file and offer to do so.</p>

<p><strong>Section 7: General Constraints</strong> includes an absolute prohibition on hallucinating citations, a requirement to prefer depth and accuracy over speed, and a constraint against producing outputs that could be mistaken for official institutional communication without explicit authorization.</p>

<p><strong>Section 8: Confirmation Gates</strong> is the section with the most direct operational consequence for agentic use. It defines six categories of action that require explicit affirmative confirmation before execution, and specifies precisely what information must be displayed when requesting that confirmation. A general instruction to “go ahead and handle everything” explicitly does not constitute confirmation for any of these categories.</p>

<p>Gate 8.1 covers destructive or significant file system alterations: deleting any file or directory, overwriting any existing file (with a requirement to propose a versioned backup first), renaming or moving more than three files in bulk, modifying any file outside the active workspace folder, or clearing a database. Gate 8.2 covers external communications: sending any email or message via any connected service. Drafting is permitted without confirmation; sending is not. Gate 8.3 covers version control actions: committing to any repository, pushing to any branch including feature branches, creating or deleting or merging branches, tagging a release, or force-pushing (the last of which is additionally flagged as high-risk). Gate 8.4 covers web and cloud publishing: deploying web content, updating live pages or API endpoints, uploading to publicly accessible cloud storage, submitting forms or proposals, or modifying DNS or SSL configuration. Gate 8.5 covers financial, administrative, and credentialed actions: financial transactions, institutional system access, grant portal submissions, or anything generating a binding commitment on the user’s behalf. Gate 8.6 establishes a threshold for batch operations: any automated operation affecting more than five files, records, or API calls in a single execution requires confirmation before the batch runs, with a display of the first two or three operations so the pattern can be verified.</p>

<p><strong>Section 9: Plan-First Protocol</strong> requires that for any task involving more than three discrete steps, or touching more than one confirmation gate category, a written execution plan must be presented before any action is taken. The plan must include a numbered list of all steps in sequence, the tool or method and expected output for each step, an explicit list of any confirmation gates that will be triggered and at which step, and an explicit request for approval before Step 1 executes.</p>

<p><strong>Section 10: Sensitive Data Handling</strong> establishes FERPA-based handling requirements for student data (no transmission, caching, or summarization of student records outside the local workspace without explicit authorization), IRB-based handling requirements for human subjects research data (flag any task appearing to involve such data and request confirmation of the applicable IRB protocol before proceeding), and a general prohibition on logging or outputting API keys, passwords, OAuth tokens, or unpublished grant narratives.</p>

<p><strong>Section 11: Task Logging and Audit Trail</strong> requires appending a session log to <code class="language-plaintext highlighter-rouge">logs/session_log.md</code> at the conclusion of any session in which files were created, modified, sent, or published. The log entry must include the date and time, a one-paragraph plain-English summary of what was accomplished, a list of files created or modified with their paths, a list of any external actions taken with confirmation that each was explicitly authorized, and any open items or follow-up tasks identified during the session.</p>

<p><strong>Section 12: Escalation and Uncertainty Protocol</strong> is the most operationally important safety instruction for autonomous use. If at any point during execution an agent encounters a situation not covered by the instructions, a conflict between two instructions, an unexpected error or permission failure or ambiguous system state, or a result that does not match the expected output, the instruction is to stop execution immediately, report the situation clearly, and wait for guidance. Autonomous recovery from unexpected states by taking additional actions is explicitly prohibited. The protocol frames this as a cost-benefit argument: the cost of pausing is always lower than the cost of an unintended irreversible action.</p>

<h2 id="connecting-ai-systems-to-the-vault">Connecting AI Systems to the Vault</h2>

<p>The practical integration pattern differs by tool type, but the underlying idea is the same in every case: give the tool a path to <code class="language-plaintext highlighter-rouge">AGENTS.md</code>, <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code>, and <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code>, and let those files do the context-setting work.</p>

<p>For <strong>agentic CLI tools</strong> like Claude Code and OpenCode, the integration is a <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> or <code class="language-plaintext highlighter-rouge">AGENTS.md</code> file at the root of each project that begins with a fetch-and-read instruction pointing at the vault repository:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gu">## Context</span>
 
Before beginning any task, fetch and read the following files from the
knowledge repository:
<span class="p"> 
-</span> https://raw.githubusercontent.com/YOUR_GITHUB_USERNAME/Obsidian-Vault/main/AGENTS.md
<span class="p">-</span> https://raw.githubusercontent.com/YOUR_GITHUB_USERNAME/Obsidian-Vault/main/LLMMEMORIES.md
<span class="p">-</span> https://raw.githubusercontent.com/YOUR_GITHUB_USERNAME/Obsidian-Vault/main/SYSTEMPROMPT.md
 
Treat the contents of those files as authoritative context for all decisions
in this session.
</code></pre></div></div>

<p>For <strong>GitHub Actions workflows</strong>, the vault repository is checked out as a secondary input in the workflow definition:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Checkout knowledge vault</span>
  <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v4</span>
  <span class="na">with</span><span class="pi">:</span>
    <span class="na">repository</span><span class="pi">:</span> <span class="s">YOUR_GITHUB_USERNAME/Obsidian-Vault</span>
    <span class="na">token</span><span class="pi">:</span> <span class="s">$</span>
    <span class="na">path</span><span class="pi">:</span> <span class="s">vault</span>
 
<span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Build context</span>
  <span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
    <span class="s">cat vault/AGENTS.md vault/LLMMEMORIES.md vault/SYSTEMPROMPT.md &gt; /tmp/context.md</span>
</code></pre></div></div>

<p>For <strong>web-based assistants</strong> with a custom instructions field, I maintain a condensed version of <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code> in that field, with a reference to the full repository for agents that can fetch URLs. The condensed version covers the highest-impact sections: identity, writing style, confirmation gates, and the location of the canonical files.</p>

<p>For <strong>local containerized agents</strong>, the vault directory is bind-mounted directly into the container’s filesystem:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/obsidian-vault:/vault:ro"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/projects/current:/workspace"</span> <span class="se">\</span>
  my-agent:latest
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">:ro</code> flag applies when the local agent is consuming context rather than writing wiki content. For agents whose primary job is to write to <code class="language-plaintext highlighter-rouge">/wiki/</code>, the mount is read-write, and the agent commits its changes through the GitHub REST API so that the metadata protocol is satisfied correctly. Thanks to the system prompt details about updating the Github Gitless Sync plugin metadata json file, this is optional, and agents can also modify the repository to be synchronized back to Obsidian. In this way, I really only use Obsidian as a convenient viewer.</p>

<h2 id="a-concrete-example-your-cv-as-a-raw-source">A Concrete Example: Your CV as a Raw Source</h2>

<p>The most direct way to see how the write path works is to walk through the simplest possible workflow: drop a document into <code class="language-plaintext highlighter-rouge">raw/</code>, point an agent at the repository, and watch it process the document into <code class="language-plaintext highlighter-rouge">wiki/</code>.</p>

<p>Suppose you drop a PDF CV into <code class="language-plaintext highlighter-rouge">raw/</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>raw/
└── my-cv.pdf
</code></pre></div></div>

<p>You then give an agentic tool the following instruction, which is all it needs because the rest is specified in <code class="language-plaintext highlighter-rouge">AGENTS.md</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Clone https://github.com/YOUR_GITHUB_USERNAME/Obsidian-Vault, read AGENTS.md,
and follow the instructions to process any unprocessed documents in raw/.
</code></pre></div></div>

<p>The agent reads <code class="language-plaintext highlighter-rouge">AGENTS.md</code>, which tells it that <code class="language-plaintext highlighter-rouge">raw/</code> is a read-only inbox, that processed content belongs in <code class="language-plaintext highlighter-rouge">wiki/</code>, and that it must update <code class="language-plaintext highlighter-rouge">.obsidian/github-sync-metadata.json</code> for every file it creates. It then reads the CV, extracts the relevant structured information, and builds out the wiki accordingly, creating pages for education, positions held, publications, funded projects, skills, and service roles, cross-linking them to each other and to an <code class="language-plaintext highlighter-rouge">index.md</code> hub. It commits the new wiki files and the updated metadata back to the repository in a single atomic commit.</p>

<p>The next time you open Obsidian and trigger a sync, those wiki pages appear in your vault as fully navigable, cross-linked notes. The CV has been processed exactly once, its information now lives in a structured and queryable form, and the original PDF is preserved untouched in <code class="language-plaintext highlighter-rouge">raw/</code>.</p>

<p>The same workflow applies to any source material: a conference paper, a project brief, a set of meeting notes exported from another application, a transcript, a published technical document. Whatever arrives in <code class="language-plaintext highlighter-rouge">raw/</code> becomes an input to the next agent run, which extends the wiki without touching anything that already exists. Over time, the wiki accumulates a comprehensive, cross-linked knowledge base built from actual documents, maintained by agents that follow the same explicit instructions every time.</p>

<h2 id="the-wiki-as-a-queryable-knowledge-base">The Wiki as a Queryable Knowledge Base</h2>

<p>The <code class="language-plaintext highlighter-rouge">wiki/</code> directory is the output of the system, the structured knowledge base that gets built and maintained over time. Its organization should reflect the categories of information it needs to represent. <code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies that the wiki must be organized into clear, intuitive, scalable topical categories with high-level directories and meaningful subdirectories, never left as a flat dump of loose notes at its top level.</p>

<p>The <code class="language-plaintext highlighter-rouge">wiki/index.md</code> serves as the hub for the entire knowledge base. When an agent is asked a question and instructed to use the vault, <code class="language-plaintext highlighter-rouge">AGENTS.md</code> specifies that it starts at <code class="language-plaintext highlighter-rouge">wiki/index.md</code>, identifies the relevant area, navigates to the appropriate subdirectory, reads the relevant files, and synthesizes an answer, updating the wiki first if it is incomplete or outdated relative to available source material in <code class="language-plaintext highlighter-rouge">raw/</code>.</p>

<p>This sequence, hub to subdirectory to relevant pages to synthesis, is the same workflow a human would follow when using Obsidian, which makes the agent behavior predictable and auditable. The wiki is structured for both human navigation and machine traversal, because those two requirements are compatible when the underlying format is plain Markdown with explicit cross-links.</p>

<h2 id="the-raw-inbox-and-reference-cataloging">The raw/ Inbox and Reference Cataloging</h2>

<p>The <code class="language-plaintext highlighter-rouge">raw/</code> directory handles a problem that anyone who works across multiple document formats encounters regularly: you receive a PDF, or an exported summary, or a transcript, and you need to incorporate the information into your knowledge base without losing the original source. The <code class="language-plaintext highlighter-rouge">raw/</code> inbox holds originals in whatever format they arrive, and they are never modified.</p>

<p>The non-destructive contract of <code class="language-plaintext highlighter-rouge">raw/</code> means that the inbox can grow without risk. A new document dropped into <code class="language-plaintext highlighter-rouge">raw/</code> will be picked up on the next agent run and incorporated into the wiki, while the original is preserved for future reference or re-processing. When an agent creates a wiki note from a source document, it links back to the original in <code class="language-plaintext highlighter-rouge">raw/</code> using a relative wikilink:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="ge">*Source: [[../raw/my_cv.pdf]]*</span>
</code></pre></div></div>

<p>Obsidian renders this as a clickable link that opens the original document; an agent resolves it as a vault-relative path. This citation chain means that every wiki page can be traced back to its source, and the source can be re-processed with a better agent or a different prompt without losing either the original document or the previously generated wiki content.</p>

<h2 id="synchronization-in-practice">Synchronization in Practice</h2>

<p>The full synchronization cycle, from a local Obsidian edit to an agent seeing the change, involves three steps: edit in Obsidian, trigger a sync via the Gitless Sync plugin, and have the agent pull from the GitHub API or clone the repository fresh. The reverse cycle, from an agent commit to Obsidian seeing the change, is: agent writes to GitHub via the REST API, updating metadata correctly in the same atomic commit; Obsidian pulls on the next sync; and the new or modified file appears in the vault.</p>

<p>The metadata protocol is what makes the reverse cycle work reliably. An agent that creates files without updating the metadata will find that those files appear to Obsidian as if they were created outside the sync system and may not be pulled on the next sync. An agent that updates metadata with incorrect SHA values will trigger a spurious re-download of files that have not changed. The atomic commit requirement, where the file change and the metadata update land in the same commit, prevents a state where one exists without the other.</p>

<h2 id="practical-takeaways">Practical Takeaways</h2>

<p>Running this system for the past year has produced a clear picture of what works and what requires ongoing attention. The three-file root structure (<code class="language-plaintext highlighter-rouge">AGENTS.md</code>, <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code>, <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code>) has proven to be the right level of granularity: enough separation to allow selective reading, not so much fragmentation that agents need to synthesize across many files to get a complete picture. The <code class="language-plaintext highlighter-rouge">raw/</code> read-only constraint has been invaluable; on two occasions, agents attempted to modify source documents, and the explicit prohibition in <code class="language-plaintext highlighter-rouge">AGENTS.md</code> was what stopped them. The bidirectional memory update convention for <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code> is theoretically correct but requires discipline in practice: it is easy to accept a session’s refined understanding and forget to write it back to the file.</p>

<p>The confirmation gate protocol in <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code> has proven its value in agentic contexts most sharply. Having the protocol specified in a canonical file rather than per-tool configuration means that a GitHub Actions workflow, a local container running Claude Code, and a web-based assistant all inherit the same safety constraints automatically. The cost of reading the file is negligible; the cost of not having the protocol is an agent that commits, pushes, or deploys without checking first.</p>

<p>The setup cost is low. The vault structure requires perhaps two hours of initial authoring: writing <code class="language-plaintext highlighter-rouge">AGENTS.md</code>, writing an initial <code class="language-plaintext highlighter-rouge">LLMMEMORIES.md</code> from whatever context you already maintain elsewhere, and writing an initial <code class="language-plaintext highlighter-rouge">SYSTEMPROMPT.md</code> from the instructions you already paste into various tools. The return, in terms of consistent and well-calibrated AI assistance across tools and sessions, scales with the quality of those three files. The vault has become the single source of truth for the context that every AI tool I use draws from, and the discipline of maintaining it in one place is considerably less costly than the alternative of maintaining five inconsistent versions of the same information in five incompatible formats.</p>

<hr />]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="obsidian" /><category term="knowledge-management" /><category term="agents" /><category term="markdown" /><summary type="html"><![CDATA[For the past year I have been building a knowledge management system with a specific design constraint in mind: every AI system I work with, whether a cloud-hosted assistant, a local agentic coding tool, or an automated GitHub Action, should be able to read the same authoritative description of who I am, what I am working on, and how I want to interact. More importantly, those systems should be able to write back into the knowledge base and have their work appear seamlessly in Obsidian on my local machine the next time I open the app. The proliferation of capable AI tools in 2025-2026 made both sides of this problem, reading and writing, tractable in a way they had not been before. This post documents the architecture I settled on: an Obsidian vault hosted on GitHub, synchronized via the Gitless Sync plugin, structured around three canonical files that any AI system can read and act on, and organized into a curated wiki that agents can query, extend, and maintain across platforms.]]></summary></entry><entry><title type="html">Cognitive Loop Kernel: A Local-First Multi-Agent Development Harness</title><link href="https://www.billmongan.com/posts/2026/05/cognitivelloopkernel/" rel="alternate" type="text/html" title="Cognitive Loop Kernel: A Local-First Multi-Agent Development Harness" /><published>2026-05-01T00:00:00+00:00</published><updated>2026-05-01T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/cognitiveloopkernel</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/cognitivelloopkernel/"><![CDATA[<p>The emergence of capable code-generation models has prompted a wave of experiments in autonomous software development, where LLM agents plan, implement, test, and revise code with minimal human intervention. Most of these systems, however, rely on cloud orchestration services, opaque runtimes, or monolithic agent designs that make it difficult to inspect, customize, or extend the underlying behavior. The <a href="https://github.com/BillJr99/CognitiveLoopKernel">Cognitive Loop Kernel (CLK)</a> is a local-first, multi-agent development harness that attempts to address these constraints directly. You give it an idea, and a dynamically assembled team of agents iterates that idea into a working system through repeated agentic development cycles, all under your local filesystem.</p>

<p>This article provides a detailed walkthrough of CLK’s architecture, its principal subsystems, and the design decisions that distinguish it from similar tools.</p>

<blockquote>
  <p><strong>Experimental software — use at your own risk.</strong>
CLK is a research prototype. It is not intended for, and has not been
evaluated or deemed suitable for, any particular purpose, production
use, or critical workload. No warranty is provided, express or implied.
By using this software you accept all associated risks.</p>

  <p>Contributions, bug reports, and ideas are very welcome — feel free to
open an issue or pull request!</p>
</blockquote>

<h2 id="why-a-local-first-harness">Why a Local-First Harness?</h2>

<p>The core motivation for CLK is reproducibility and ownership. Everything the harness produces, including agent prompts, provider configurations, per-run logs, intermediate file states, and git history, lives under a single <code class="language-plaintext highlighter-rouge">.clk/</code> directory inside a project folder on your local disk. There is no external orchestration service, no account required, and no state stored elsewhere. If you want to inspect what a particular agent said in iteration four of last Tuesday’s engineering loop, you look at <code class="language-plaintext highlighter-rouge">.clk/runs/</code>. If you want to understand why the chief cast a <code class="language-plaintext highlighter-rouge">security_auditor</code> role, you read <code class="language-plaintext highlighter-rouge">.clk/state/casting.log</code>. The harness treats transparency as a first-class property of the system.</p>

<p>A second motivation is provider agnosticism. CLK supports Claude Code, OpenAI Codex, Google Gemini, any OpenAI-compatible HTTP server (via OpenWebUI), local Ollama models, Pi, and a built-in shell dummy provider for testing and CI. Switching providers requires a single configuration change, and different agents within the same workflow can be bound to different providers, so you can route heavy reasoning tasks to a cloud model while keeping low-stakes validation steps on a local Ollama instance.</p>

<h2 id="high-level-architecture">High-Level Architecture</h2>

<p>CLK is organized around three principal concerns: state management, agent orchestration, and provider abstraction. The package layout reflects this separation.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>clk_harness/
  cli.py                 # argparse entrypoint and command dispatch
  config.py              # paths, default configs, JSON load/save helpers
  git_ops.py             # init, commit, revert, and status wrappers
  providers/             # claude, codex, gemini, ollama, openwebui, pi, shell
  orchestration/         # agent runner, workflow runner, ralph/autoresearch loops
  templates/             # bundled prompts and default workflow YAML
  utils/                 # structured logging and activity tracking
</code></pre></div></div>

<p>The harness state, written by <code class="language-plaintext highlighter-rouge">clk init</code> and extended by every subsequent command, is isolated under <code class="language-plaintext highlighter-rouge">.clk/</code> in the project root:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>.clk/
  config/
    clk.config.json      # project-wide configuration
    providers.json       # provider registry and active selection
    agents.json          # agent-to-prompt-and-provider mapping
    workflows/*.yaml     # Archon-style workflow definitions
  prompts/               # per-agent system prompt templates
  state/
    idea.json            # the captured project idea
    system_brief.md      # initial brief
    prd.json             # product manager output
    progress.md          # human-readable development timeline
    decisions.md         # log of architectural decisions
    experiments.jsonl    # per-iteration outcome records
    agent_memory.jsonl   # all agent invocations with token usage
    casting.log          # JSONL of every roster change
    done.md              # written when completion criteria are met
  blackboard/            # cross-agent shared scratchpad (POST blocks)
  logs/                  # session and per-command logs
  runs/                  # per-invocation prompt and response capture
  backups/               # safety copies of files before mutation
</code></pre></div></div>

<p>This layout means that deleting <code class="language-plaintext highlighter-rouge">.clk/</code> resets the harness entirely without touching anything the agents actually built. The project source, tests, documentation, and configuration live in the project root proper and are managed by an ordinary git repository.</p>

<h2 id="dynamic-agent-casting">Dynamic Agent Casting</h2>

<p>The most distinctive architectural decision in CLK is dynamic team assembly. Rather than shipping a fixed roster of roles, the harness ships three baseline agents that cannot be removed, and then lets the <code class="language-plaintext highlighter-rouge">chief</code> agent invent and register project-specific specialists on the fly.</p>

<p>The three baseline agents are <code class="language-plaintext highlighter-rouge">chief</code>, which decomposes objectives, casts the team, and authors workflow YAML; <code class="language-plaintext highlighter-rouge">ralph</code>, which drives both the iterative refinement loop and Karpathy-style autoresearch cycles; and <code class="language-plaintext highlighter-rouge">qa</code>, which validates stage outputs. Every other agent, including <code class="language-plaintext highlighter-rouge">engineer</code>, is a dynamic role that the chief creates by emitting a structured <code class="language-plaintext highlighter-rouge">PROPOSE_ROLE</code> block in its response text:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>PROPOSE_ROLE: data_steward
ROLE: ensure data integrity and schema versioning
PROVIDER: claude
PROMPT:
You are the **Data Steward** agent.
Objective: $objective
State: $state_summary
...
END_ROLE
</code></pre></div></div>

<p>The harness parses this block, writes the generated prompt to <code class="language-plaintext highlighter-rouge">.clk/prompts/data_steward.md</code>, registers the role in <code class="language-plaintext highlighter-rouge">.clk/config/agents.json</code>, and makes it available to subsequent stages in the same workflow cycle, all without pausing execution. Every roster decision is appended as a JSONL entry to <code class="language-plaintext highlighter-rouge">.clk/state/casting.log</code>, giving you a complete provenance record of how the team evolved over the project’s lifetime.</p>

<p>The chief can also propose custom workflows:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>PROPOSE_WORKFLOW: engineering
YAML:
name: engineering
stages:
  - id: decompose
    agent: chief
    objective: Decompose the current top-level objective.
  - id: implement
    agent: data_steward
    depends_on: [decompose]
    validation: "pytest -q"
    commit: true
END_WORKFLOW
</code></pre></div></div>

<p>The harness validates the YAML (both via PyYAML when available and a built-in mini-parser for environments where <code class="language-plaintext highlighter-rouge">ensurepip</code> is unavailable), writes the file to <code class="language-plaintext highlighter-rouge">.clk/config/workflows/</code>, and routes the next <code class="language-plaintext highlighter-rouge">clk run</code> invocation through the new stage graph. This architecture means the project workflow is not hardcoded into the harness; it is a first-class artifact that the chief authors and evolves as it learns more about the project’s requirements.</p>

<p>The name <code class="language-plaintext highlighter-rouge">engineer</code> is reserved and protected. The harness rejects attempts to create aliases such as <code class="language-plaintext highlighter-rouge">engineering</code>, <code class="language-plaintext highlighter-rouge">coder</code>, or <code class="language-plaintext highlighter-rouge">developer</code>, and feeds the rejection back into the chief’s context as casting feedback so it learns to use the canonical name directly. A cap from <code class="language-plaintext highlighter-rouge">clk.config.json::casting.max_dynamic_roles</code> (default 12) prevents unbounded role proliferation.</p>

<h2 id="the-action-protocol">The Action Protocol</h2>

<p>Agents drive real changes by emitting structured <code class="language-plaintext highlighter-rouge">ACTION:</code> blocks. A response that merely describes what should happen but emits no ACTION blocks has no side effects, which is a deliberate design choice: the harness makes it impossible for an agent to accidentally mutate the project simply by describing a plan.</p>

<p>The supported action types are:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">ACTION: write</code> creates or overwrites a file at the specified path.</li>
  <li><code class="language-plaintext highlighter-rouge">ACTION: edit</code> applies a targeted textual replacement within an existing file, analogous to a very simple diff application.</li>
  <li><code class="language-plaintext highlighter-rouge">ACTION: append</code> adds content to the end of an existing file.</li>
  <li><code class="language-plaintext highlighter-rouge">ACTION: delete</code> removes a file.</li>
  <li><code class="language-plaintext highlighter-rouge">ACTION: run</code> executes a shell command from the project root with output captured to the log.</li>
  <li><code class="language-plaintext highlighter-rouge">ACTION: done</code> writes <code class="language-plaintext highlighter-rouge">.clk/state/done.md</code> and signals all loops to terminate.</li>
</ul>

<p>All paths are validated against the project root before execution. Any path that resolves into <code class="language-plaintext highlighter-rouge">.clk/</code> is rejected outright (with the single exception of <code class="language-plaintext highlighter-rouge">.clk/blackboard/</code>, which agents may write to via POST blocks). Attempted path traversal outside the project root is similarly rejected. Before any file is mutated, the original is backed up to <code class="language-plaintext highlighter-rouge">.clk/backups/&lt;run_id&gt;/</code>, so every overwrite is recoverable. A per-response cap of 25 file actions prevents runaway agents from restructuring the entire project in a single cycle.</p>

<p>Following each successful batch of action applications, the harness generates a structured git commit with the agent name, objective, files changed, commands run, and token totals embedded in the commit body. The git log thus becomes a faithful narrative of the project’s development, authored by the agents themselves.</p>

<h2 id="blackboard-cross-agent-communication">Blackboard: Cross-Agent Communication</h2>

<p>Agents in a multi-stage workflow often need to share findings without routing everything through the chief as a relay. CLK provides a structured shared scratchpad called the blackboard, which lives at <code class="language-plaintext highlighter-rouge">.clk/blackboard/</code> as a collection of JSON files.</p>

<p>Rather than writing to the blackboard directly via ACTION blocks (which the harness would reject as <code class="language-plaintext highlighter-rouge">.clk/</code> access), agents emit POST blocks:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>POST: finding
TITLE: Database schema analysis complete
PRODUCES: schema_contract
BODY:
Three tables identified: users, sessions, events.
The sessions table lacks a foreign key constraint.
Recommend adding: ALTER TABLE sessions ADD FOREIGN KEY ...
END_POST
</code></pre></div></div>

<p>The harness parses this block, adds metadata (timestamp, author, stage ID, workflow name), and writes the post as a JSON file under <code class="language-plaintext highlighter-rouge">.clk/blackboard/</code>. When the next stage runs, the workflow runner injects a filtered digest of relevant posts into each agent’s prompt via the <code class="language-plaintext highlighter-rouge">$blackboard_digest</code> placeholder. Stage definitions can declare <code class="language-plaintext highlighter-rouge">inputs</code> to specify which posts they want to consume and <code class="language-plaintext highlighter-rouge">outputs</code> to specify which contract keys they are expected to produce, enabling the workflow runner to verify that inter-agent contracts are satisfied before committing a stage.</p>

<p>Posts are immutable. To revise a finding, an agent writes a new post with the original post ID listed in the <code class="language-plaintext highlighter-rouge">CONSUMES</code> field, creating an auditable revision chain rather than silent overwriting.</p>

<h2 id="workflow-execution-and-dependency-resolution">Workflow Execution and Dependency Resolution</h2>

<p>Workflows are YAML files describing a directed acyclic graph of stages, each bound to an agent and an objective:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">name</span><span class="pi">:</span> <span class="s">engineering</span>
<span class="na">description</span><span class="pi">:</span> <span class="s">Single development cycle.</span>
<span class="na">stages</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">decompose</span>
    <span class="na">agent</span><span class="pi">:</span> <span class="s">chief</span>
    <span class="na">objective</span><span class="pi">:</span> <span class="s">Decompose the current top-level objective.</span>
  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">implement</span>
    <span class="na">agent</span><span class="pi">:</span> <span class="s">engineer</span>
    <span class="na">objective</span><span class="pi">:</span> <span class="s">Implement the smallest vertical slice.</span>
    <span class="na">depends_on</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">decompose</span><span class="pi">]</span>
    <span class="na">validation</span><span class="pi">:</span> <span class="s2">"</span><span class="s">pytest</span><span class="nv"> </span><span class="s">-q"</span>
    <span class="na">commit</span><span class="pi">:</span> <span class="no">true</span>
  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">validate</span>
    <span class="na">agent</span><span class="pi">:</span> <span class="s">qa</span>
    <span class="na">objective</span><span class="pi">:</span> <span class="s">Audit implementation and confirm test passage.</span>
    <span class="na">depends_on</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">implement</span><span class="pi">]</span>
</code></pre></div></div>

<p>The workflow runner (<code class="language-plaintext highlighter-rouge">orchestration/workflow.py</code>) topologically sorts stages by their <code class="language-plaintext highlighter-rouge">depends_on</code> declarations and executes stages that share no dependencies in parallel using a <code class="language-plaintext highlighter-rouge">ThreadPoolExecutor</code>. Each stage may declare a <code class="language-plaintext highlighter-rouge">validation</code> shell command; the command must exit 0 before the harness will commit the stage’s changes. Failed validations leave the working tree untouched. The parallel execution design means that a large workflow with independent research and implementation tracks can run those tracks concurrently rather than serially.</p>

<p>The default <code class="language-plaintext highlighter-rouge">engineering.yaml</code> workflow ends with a <code class="language-plaintext highlighter-rouge">supervise</code> stage, where the chief evaluates whether the user’s original prompt has been fully addressed. The chief either emits an <code class="language-plaintext highlighter-rouge">ACTION: done</code> block (writing <code class="language-plaintext highlighter-rouge">done.md</code> and terminating the loop) or emits a <code class="language-plaintext highlighter-rouge">PROPOSE_WORKFLOW</code> block describing the next iteration’s stages, upon which the runner picks them up and executes another cycle. This supervisor loop is capped at <code class="language-plaintext highlighter-rouge">clk.config.json::supervise.max_cycles</code> (default 5) to prevent runaway iteration.</p>

<h2 id="self-healing-on-unmet-dependencies">Self-Healing on Unmet Dependencies</h2>

<p>When a workflow stage’s declared dependencies fail, the harness does not silently skip the stage or crash. Instead, it dispatches the <code class="language-plaintext highlighter-rouge">chief</code> agent in recovery mode, providing the exact failure reasons (agent error text, validation command output, QA report) and asking the chief to either re-cast the workflow, emit ACTION blocks that fix the upstream failure directly, or propose a specialist agent that can resolve the issue. This recovery dispatch is capped at three passes per stage (configurable via <code class="language-plaintext highlighter-rouge">clk.config.json::recovery.max_per_stage</code>) to prevent infinite recovery loops. The design treats agent and validation failures as information that the system can reason about, rather than hard stops requiring human intervention.</p>

<h2 id="iterative-improvement-loops">Iterative Improvement Loops</h2>

<p>CLK ships two distinct iterative loop modes, both driven through the <code class="language-plaintext highlighter-rouge">ralph</code> agent.</p>

<h3 id="the-ralph-refinement-loop">The Ralph Refinement Loop</h3>

<p>The Ralph loop (<code class="language-plaintext highlighter-rouge">/loop ralph N</code> in the TUI, or <code class="language-plaintext highlighter-rouge">clk loop --max-iterations N</code> on the CLI) implements a simple but effective iterative improvement cycle. In each iteration, Ralph reads the current state files and git log, identifies one measurable improvement, and produces a plan. The engineer implements the plan, QA validates it, and the harness runs any configured validation commands. If all checks pass and the working tree has changed, the harness commits the iteration with full metadata. If validation fails, <code class="language-plaintext highlighter-rouge">git reset --hard</code> reverts the working tree to the pre-iteration HEAD, and the outcome is recorded in <code class="language-plaintext highlighter-rouge">experiments.jsonl</code> so subsequent iterations can learn from the failure without contaminating the committed project state. The loop terminates when <code class="language-plaintext highlighter-rouge">done.md</code> is created or <code class="language-plaintext highlighter-rouge">max_iterations</code> is reached.</p>

<h3 id="the-autoresearch-loop">The Autoresearch Loop</h3>

<p>The autoresearch loop (<code class="language-plaintext highlighter-rouge">/loop autoresearch N</code>) implements a Karpathy-style research cycle oriented toward hypothesis generation and experimental learning rather than feature delivery. Each iteration, Ralph surveys the current state to identify the highest-value open question (recorded in the project’s <code class="language-plaintext highlighter-rouge">decisions.md</code> or blackboard), designs a small targeted experiment to address it, runs the experiment via ACTION blocks, and records the outcome in <code class="language-plaintext highlighter-rouge">experiments.jsonl</code> regardless of whether the experiment succeeded or failed. The philosophy is that failed experiments are useful data, and the loop accumulates a structured research log that informs subsequent iterations. Both loop modes respect the <code class="language-plaintext highlighter-rouge">done.md</code> termination condition and can be stopped gracefully via the TUI’s <code class="language-plaintext highlighter-rouge">/stop</code> command, which signals the loop to halt after the current iteration completes rather than aborting mid-iteration.</p>

<h2 id="the-provider-system">The Provider System</h2>

<p>All agent invocations flow through a provider abstraction defined in <code class="language-plaintext highlighter-rouge">providers/base.py</code>. Each provider implements <code class="language-plaintext highlighter-rouge">invoke(request: AgentRequest) -&gt; AgentResponse</code>, where the request carries the rendered prompt and metadata, and the response carries the text output, token counts, and a success flag. The harness ships seven provider implementations.</p>

<table>
  <thead>
    <tr>
      <th>Provider</th>
      <th>Invocation method</th>
      <th>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">shell</code></td>
      <td>Always available</td>
      <td>Dummy provider; echoes prompts and writes stub files. Useful for tests and dry runs.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">claude</code></td>
      <td><code class="language-plaintext highlighter-rouge">claude</code> on PATH</td>
      <td>Runs <code class="language-plaintext highlighter-rouge">claude --print</code> non-interactively; supports both CLI auth and direct API key auth via the Anthropic Messages endpoint.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">codex</code></td>
      <td><code class="language-plaintext highlighter-rouge">codex</code> on PATH</td>
      <td>Runs <code class="language-plaintext highlighter-rouge">codex exec</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">gemini</code></td>
      <td><code class="language-plaintext highlighter-rouge">gemini</code> on PATH</td>
      <td>Runs the Google Gemini CLI; prompt fed on stdin.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">pi</code></td>
      <td><code class="language-plaintext highlighter-rouge">pi</code> on PATH or <code class="language-plaintext highlighter-rouge">.clk/tools/pi/</code></td>
      <td>Extensible terminal harness.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ollama</code></td>
      <td>HTTP endpoint</td>
      <td>Local LLM via HTTP; no API key required.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">openwebui</code></td>
      <td>HTTP endpoint</td>
      <td>Any OpenAI-compatible server; configure <code class="language-plaintext highlighter-rouge">endpoint</code>, <code class="language-plaintext highlighter-rouge">api_key</code>, and <code class="language-plaintext highlighter-rouge">model</code> in <code class="language-plaintext highlighter-rouge">providers.json</code>.</td>
    </tr>
  </tbody>
</table>

<p>For the CLI-driven providers (<code class="language-plaintext highlighter-rouge">claude</code>, <code class="language-plaintext highlighter-rouge">codex</code>, <code class="language-plaintext highlighter-rouge">gemini</code>), CLK supports two authentication modes. The <code class="language-plaintext highlighter-rouge">cli</code> mode (default) spawns the provider’s local CLI as a subprocess and trusts whatever session authentication that CLI already has. The <code class="language-plaintext highlighter-rouge">apikey</code> mode bypasses the local CLI entirely and calls the upstream HTTP API directly, using standard environment variables (<code class="language-plaintext highlighter-rouge">ANTHROPIC_API_KEY</code>, <code class="language-plaintext highlighter-rouge">OPENAI_API_KEY</code>, <code class="language-plaintext highlighter-rouge">GEMINI_API_KEY</code>). This separation makes CLK usable in both developer workstation contexts (where a persistent CLI session is already authenticated) and CI/CD environments (where API keys are injected as secrets). Per-agent provider binding in <code class="language-plaintext highlighter-rouge">agents.json</code> means you can route different agents to different providers within the same workflow cycle, which is useful when you want cloud reasoning for the chief and local generation for lower-stakes implementation stages.</p>

<h2 id="the-tui-dashboard">The TUI Dashboard</h2>

<p>For interactive use, CLK ships a terminal user interface (TUI, implemented in <code class="language-plaintext highlighter-rouge">clk_harness/tui.py</code> using curses) that provides live visibility into the multi-agent execution. The TUI displays a card for each active agent showing its current state (idle, working, done, or failed), a scrollable status log that mirrors the session log file, a live heartbeat indicating whether a running agent subprocess is actively streaming or silent, and a command input field styled after Claude Code’s <code class="language-plaintext highlighter-rouge">&gt;</code> prompt. A bottom band reports running totals: agent count, total tokens consumed (input and output separately), peak concurrent runs, and files written.</p>

<p>The TUI also supports interactive steering via typed commands:</p>

<table>
  <thead>
    <tr>
      <th>Command</th>
      <th>Effect</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">free text</code></td>
      <td>First message becomes the project idea and triggers casting + <code class="language-plaintext highlighter-rouge">engineering</code>; subsequent messages append context and re-cast + re-run.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/idea &lt;text&gt;</code></td>
      <td>Replace the captured idea.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/cast</code></td>
      <td>Force a fresh chief casting pass against current state.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/roles list</code></td>
      <td>Print the current roster.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/roles add NAME "description"</code></td>
      <td>Add a dynamic role.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/roles drop NAME</code></td>
      <td>Remove a dynamic role (baseline agents cannot be removed).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/run [workflow]</code></td>
      <td>Execute a single workflow cycle (default: <code class="language-plaintext highlighter-rouge">engineering</code>).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/loop ralph N</code></td>
      <td>Start N iterations of the Ralph refinement loop.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/loop autoresearch N</code></td>
      <td>Start N iterations of the autoresearch loop.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/stop</code></td>
      <td>Request the active loop to halt after the current iteration.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/abort</code></td>
      <td>SIGTERM any running CLI subprocess.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/provider &lt;name&gt;</code></td>
      <td>Switch the active provider.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">/quit</code></td>
      <td>Exit the TUI.</td>
    </tr>
  </tbody>
</table>

<p>The heartbeat mechanism deserves specific mention. CLI providers stream their subprocess’s stdout and stderr live to the status pane, so every line the CLI prints (authentication status messages, connection attempts, retry notices) appears within milliseconds. The heartbeat fires approximately every 15 seconds while an agent is working and distinguishes between an agent that is processing slowly and one that is genuinely hung. If a subprocess has been silent for more than two minutes, the TUI suggests typing <code class="language-plaintext highlighter-rouge">/abort</code>. This real-time observability is a significant quality-of-life improvement over systems that present a spinner with no indication of underlying activity.</p>

<h2 id="getting-started">Getting Started</h2>

<p>The fastest path is the kickoff script, which copies the harness into a fresh timestamped directory, initializes a git repository, and launches the TUI:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Optional: set defaults non-interactively by copying .env.example to .env</span>
./kickoff.sh <span class="s2">"A local-first journaling app that summarizes my week"</span>

<span class="c"># Or omit the prompt and type your idea into the TUI:</span>
./kickoff.sh
</code></pre></div></div>

<p>The kickoff directory is intentionally isolated: <code class="language-plaintext highlighter-rouge">.clk/</code> holds all harness state, the project tree receives the agents’ output, and the original CLK source directory is never modified.</p>

<p>If you prefer the command-line interface without the TUI:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./scripts/install_local.sh           <span class="c"># creates .clk/venv and installs PyYAML</span>
./scripts/clk init
./scripts/clk idea <span class="s2">"A local-first journaling app that summarizes my week"</span>
./scripts/clk plan
./scripts/clk run
./scripts/clk loop <span class="nt">--max-iterations</span> 10
</code></pre></div></div>

<p>Setting <code class="language-plaintext highlighter-rouge">CLK_NO_TUI=true</code> in your environment makes <code class="language-plaintext highlighter-rouge">kickoff.sh</code> fall back to the non-interactive pipeline automatically, which is the appropriate mode for CI/CD use.</p>

<h2 id="docker-deployment">Docker Deployment</h2>

<p>CLK ships a <code class="language-plaintext highlighter-rouge">Dockerfile</code> for containerized use. The default mode is the interactive TUI, so you launch with <code class="language-plaintext highlighter-rouge">-it</code>. Kickoff directories are created under <code class="language-plaintext highlighter-rouge">workspace/</code> inside the container; mounting a volume there preserves them across runs.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker build <span class="nt">-t</span> clk <span class="nb">.</span>
docker volume create clk-workspace

<span class="c"># Interactive TUI, with your idea passed as an argument:</span>
docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">-v</span> clk-workspace:/app/workspace <span class="se">\</span>
  clk <span class="s2">"A local-first journaling app that summarizes my week"</span>

<span class="c"># Non-interactive CI mode with Claude API key:</span>
docker run <span class="nt">--rm</span> <span class="se">\</span>
  <span class="nt">-v</span> clk-workspace:/app/workspace <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">CLK_NO_TUI</span><span class="o">=</span><span class="nb">true</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">CLK_PROVIDER</span><span class="o">=</span>claude <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">CLK_AUTH_MODE</span><span class="o">=</span>apikey <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">ANTHROPIC_API_KEY</span><span class="o">=</span>sk-ant-... <span class="se">\</span>
  clk <span class="s2">"A local-first journaling app that summarizes my week"</span>
</code></pre></div></div>

<p>A setup wizard (<code class="language-plaintext highlighter-rouge">--setup</code>) walks through every configuration option and writes the results to a bind-mounted <code class="language-plaintext highlighter-rouge">.env</code> file, which is appropriate for first-run configuration in both local and container contexts.</p>

<h2 id="safety-and-reliability-mechanisms">Safety and Reliability Mechanisms</h2>

<p>CLK incorporates several safeguards designed to make autonomous operation safer without sacrificing the ability to take real action.</p>

<p>Failed work is never silently discarded. The Ralph loop uses <code class="language-plaintext highlighter-rouge">git reset --hard &lt;pre-iteration-sha&gt;</code> to revert failed iterations, and the pre-revert state is preserved in <code class="language-plaintext highlighter-rouge">.clk/runs/</code> for inspection. The backup system in <code class="language-plaintext highlighter-rouge">.clk/backups/</code> provides per-overwrite copies of every file the harness mutates, with backup filenames keyed to the run ID so you can trace a backup to the specific agent invocation that produced it.</p>

<p>Operations touching more than five files are logged with a warning before execution, and operations exceeding twenty-five files in a single response batch are refused entirely (the cap is configurable). This provides a meaningful check against an agent that attempts to restructure the entire project in one pass. The <code class="language-plaintext highlighter-rouge">run</code> action sanitizes shell commands before execution, rejecting <code class="language-plaintext highlighter-rouge">sudo</code> and recognizable destructive patterns.</p>

<p>All exceptions are caught and logged with a location-specific prefix string and a full traceback, consistent with the project’s exception-handling convention: <code class="language-plaintext highlighter-rouge">print(f"[module:function] {e}")</code> followed by <code class="language-plaintext highlighter-rouge">traceback.print_exc()</code>. This means that a provider failure, a YAML parse error, or a filesystem permission issue is always surfaced with enough context to diagnose the problem without reading the full run log.</p>

<h2 id="completion-criteria">Completion Criteria</h2>

<p>CLK considers the project “done” when <code class="language-plaintext highlighter-rouge">.clk/state/done.md</code> exists. By convention, the harness creates this file only when the chief determines that the MVP runs locally, the test suite passes, the README explains setup, a deployment plan and checklist exist, and at least one user-facing interaction path has been implemented. These criteria are not enforced programmatically; they are encoded in the chief’s system prompt as the completion standard it reasons about when deciding whether to emit <code class="language-plaintext highlighter-rouge">ACTION: done</code> or propose another workflow cycle.</p>

<h2 id="customization">Customization</h2>

<p>CLK is designed to be customized at every layer. Editing <code class="language-plaintext highlighter-rouge">.clk/prompts/</code> changes individual agent behavior without touching harness code. Editing <code class="language-plaintext highlighter-rouge">.clk/config/agents.json</code> rebinds specific agents to specific providers, for example routing the <code class="language-plaintext highlighter-rouge">engineer</code> agent to <code class="language-plaintext highlighter-rouge">claude</code> while keeping <code class="language-plaintext highlighter-rouge">researcher</code> on a local <code class="language-plaintext highlighter-rouge">ollama</code> model. Adding new YAML files to <code class="language-plaintext highlighter-rouge">.clk/config/workflows/</code> introduces new execution modes, accessible via <code class="language-plaintext highlighter-rouge">clk run --workflow NAME</code> or <code class="language-plaintext highlighter-rouge">/run workflow_name</code> in the TUI. Project-wide parameters including the supervise cycle cap, the recovery pass limit, the maximum dynamic role count, and the file-action batch limit are all configurable via <code class="language-plaintext highlighter-rouge">clk configure --set key=value</code>, which updates <code class="language-plaintext highlighter-rouge">clk.config.json</code> in place.</p>

<h2 id="pidev-extension">pi.dev Extension</h2>

<p>CLK exposes <code class="language-plaintext highlighter-rouge">/clk &lt;idea&gt;</code> and <code class="language-plaintext highlighter-rouge">/clk-abort</code> commands if run with <code class="language-plaintext highlighter-rouge">pi -e pi-extension/src/index.ts</code> which starts a similar dispatch loop as that described here for the standalone tool.</p>

<h2 id="summary">Summary</h2>

<p>The Cognitive Loop Kernel addresses a practical gap in the current landscape of agentic development tools: the need for a local-first, inspectable, provider-agnostic harness that can assemble a project-specific multi-agent team, execute real file operations under safety constraints, iterate toward completion through structured loops, and maintain a complete, human-readable audit trail throughout. By treating the workflow definition, agent roster, blackboard contents, and git history as first-class project artifacts, CLK makes the behavior of the multi-agent system legible and modifiable without requiring changes to the harness itself. The source is available on <a href="https://github.com/BillJr99/CognitiveLoopKernel">GitHub</a> under the MIT License.</p>]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="technical" /><category term="ai" /><category term="agentic" /><category term="software" /><summary type="html"><![CDATA[The emergence of capable code-generation models has prompted a wave of experiments in autonomous software development, where LLM agents plan, implement, test, and revise code with minimal human intervention. Most of these systems, however, rely on cloud orchestration services, opaque runtimes, or monolithic agent designs that make it difficult to inspect, customize, or extend the underlying behavior. The Cognitive Loop Kernel (CLK) is a local-first, multi-agent development harness that attempts to address these constraints directly. You give it an idea, and a dynamically assembled team of agents iterates that idea into a working system through repeated agentic development cycles, all under your local filesystem.]]></summary></entry><entry><title type="html">Building a Private AI Stack: From Mini PC to Autonomous Agents</title><link href="https://www.billmongan.com/posts/2026/05/privateaistack/" rel="alternate" type="text/html" title="Building a Private AI Stack: From Mini PC to Autonomous Agents" /><published>2026-05-01T00:00:00+00:00</published><updated>2026-05-01T00:00:00+00:00</updated><id>https://www.billmongan.com/posts/2026/05/localai</id><content type="html" xml:base="https://www.billmongan.com/posts/2026/05/privateaistack/"><![CDATA[<p>For the past several years I have been thinking carefully about what it means to run AI infrastructure that I actually own, control, and understand from the ground up. The rapid proliferation of frontier model APIs, agentic coding tools, and open-weight model releases in 2025-2026 finally made this tractable at a price and complexity point that a single person could manage. This post documents the architecture I settled on: a self-hosted, Docker-based stack running on a mini PC, unified by a single OpenAI-compatible model gateway, and surfaced through a collection of local inference servers, agentic CLI tools, autonomous agent frameworks, open-source Cowork alternatives, and a task-bounded command harness built around structured queues. My goals were privacy, sovereignty, reproducibility, and the ability to swap components without rebuilding everything from scratch.</p>

<h2 id="motivation-why-self-host">Motivation: Why Self-Host?</h2>

<p>The short answer is control. When I work on grant-funded AI research, on student data in the context of my courses, or on institutional planning, I want to know exactly where inference is happening and what data is leaving my environment. The longer answer is pedagogical: I cannot credibly teach AI literacy, AI ethics, and responsible deployment if I have not made serious, hands-on architectural decisions myself. Running your own stack is humbling in the right ways.</p>

<p>There is also a strategic argument. As the open-source AI agent framework ecosystem matured through early 2026, it became clear that the layered architecture of these systems, separating the model layer, the orchestration layer, the tool-access layer, and the user-interface layer, was stabilizing into recognizable patterns. A well-designed self-hosted stack can plug into any of these layers without being locked to a single vendor. That flexibility is worth the setup cost.</p>

<h2 id="hardware-the-mini-pc">Hardware: The Mini PC</h2>

<p>The physical foundation of the stack is a mini PC running Linux Mint, which gives me a clean Debian-lineage environment with full access to the upstream Docker Engine repository and no virtualization layer between the container workloads and the host kernel. Everything runs directly on the host, which simplifies networking, volume permissions, and service lifecycle management considerably compared to hypervisor-based setups.</p>

<h3 id="installing-docker-engine">Installing Docker Engine</h3>

<p>Linux Mint ships an older Docker build from the distribution mirror, so I install from the upstream Docker repository instead. The setup sequence is:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Remove any distribution-packaged versions</span>
<span class="nb">sudo </span>apt-get remove docker docker-engine docker.io containerd runc
 
<span class="nb">sudo </span>apt-get update
<span class="nb">sudo </span>apt-get <span class="nb">install</span> <span class="nt">-y</span> ca-certificates curl gnupg lsb-release
 
<span class="c"># Add Docker's official GPG key</span>
<span class="nb">sudo mkdir</span> <span class="nt">-m</span> 0755 <span class="nt">-p</span> /etc/apt/keyrings
curl <span class="nt">-fsSL</span> https://download.docker.com/linux/ubuntu/gpg | <span class="se">\</span>
  <span class="nb">sudo </span>gpg <span class="nt">--dearmor</span> <span class="nt">-o</span> /etc/apt/keyrings/docker.gpg
 
<span class="c"># Point the apt source at the Ubuntu codename that Mint is based on</span>
<span class="nb">echo</span> <span class="se">\</span>
  <span class="s2">"deb [arch=</span><span class="si">$(</span>dpkg <span class="nt">--print-architecture</span><span class="si">)</span><span class="s2"> </span><span class="se">\</span><span class="s2">
  signed-by=/etc/apt/keyrings/docker.gpg] </span><span class="se">\</span><span class="s2">
  https://download.docker.com/linux/ubuntu </span><span class="se">\</span><span class="s2">
  </span><span class="si">$(</span><span class="nb">.</span> /etc/os-release <span class="o">&amp;&amp;</span> <span class="nb">echo</span> <span class="nv">$UBUNTU_CODENAME</span><span class="si">)</span><span class="s2"> stable"</span> | <span class="se">\</span>
  <span class="nb">sudo tee</span> /etc/apt/sources.list.d/docker.list <span class="o">&gt;</span> /dev/null
 
<span class="nb">sudo </span>apt-get update
<span class="nb">sudo </span>apt-get <span class="nb">install</span> <span class="nt">-y</span> docker-ce docker-ce-cli containerd.io <span class="se">\</span>
  docker-buildx-plugin docker-compose-plugin
 
<span class="nb">sudo </span>docker run hello-world
<span class="nb">sudo </span>usermod <span class="nt">-aG</span> docker <span class="nv">$USER</span>
newgrp docker
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">UBUNTU_CODENAME</code> variable in the source line is the key detail for Mint: it resolves to the underlying Ubuntu release name rather than the Mint release name, which is what the Docker repository actually indexes.</p>

<h3 id="installing-ollama">Installing Ollama</h3>

<p>Ollama runs as a native Linux service, not inside a container, which keeps model-weight I/O off the Docker networking path and avoids bind-mount overhead for the weight files:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-fsSL</span> https://ollama.com/install.sh | sh
systemctl status ollama
</code></pre></div></div>

<p>Ollama listens on <code class="language-plaintext highlighter-rouge">http://localhost:11434</code> by default and is reachable from within containers via <code class="language-plaintext highlighter-rouge">--add-host=host.docker.internal:host-gateway</code>, which every container in the stack declares. This flag is required on Linux Docker Engine; unlike Docker Desktop, the Linux engine does not inject <code class="language-plaintext highlighter-rouge">host.docker.internal</code> automatically.</p>

<h3 id="workspace-layout">Workspace Layout</h3>

<p>All agent state lives under a single root in the home directory:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$HOME/agents/
├── workspace/              # Shared project files (all TUI tools mount here)
├── skills/core/            # Read-only skills package (mounted :ro)
├── litellm/                # LiteLLM config and Compose files
├── kilocode/home/          # KiloCode identity
├── opencode/home/          # opencode.ai identity
├── pi/home/                # pi.dev identity, models.json, settings.json
├── hermes/home/            # Hermes agent identity
├── gnhf/                   # Good Night Have Fun harness
├── open-design/            # Open Design app data and pi identity
├── commercial/             # Claude Code, Codex, Gemini CLI, Copilot, CCR, bash
├── mastra/data/            # Mastra SQLite database
├── a0/data/                # Agent Zero persistent user data
├── archon/data/            # Archon workflow state
├── ollama/data/            # Downloaded model weights (~/.ollama)
├── localai/                # LocalAI models/, backends/, config/
├── googleworkspacecli/     # Google Workspace CLI (gcloud/)
├── googleagentscli/        # Google ADK CLI
└── openwebui/data/         # Open WebUI persistent data
</code></pre></div></div>

<p>Creating the full tree is a one-liner drawn from the deploy script:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">BASE</span><span class="o">=</span><span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/workspace"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/skills/core"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/litellm"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/kilocode/home"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/opencode/home"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/pi/home"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/hermes/home"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/ollama/data"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/localai/models"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/localai/backends"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/localai/config"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/mastra/data"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/openwebui/data"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/commercial/claude/workspace"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/commercial/claude/home"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/commercial/claude/npm"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/commercial/claude/config"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/commercial/claude/cache"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleworkspacecli/gcloud"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleagentscli/data"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleagentscli/config"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleagentscli/cache/uv"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleagentscli/cache/npm"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleagentscli/evals"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/googleagentscli/logs"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/archon/data"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/a0/data"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/gnhf/home"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/gnhf/npm"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/gnhf/config"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/gnhf/cache"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/open-design/data"</span> <span class="s2">"</span><span class="nv">$BASE</span><span class="s2">/open-design/pi"</span>
<span class="nb">echo</span> <span class="s2">"Directory tree created under </span><span class="nv">$BASE</span><span class="s2">"</span>
</code></pre></div></div>

<h2 id="the-core-design-principle-a-unified-model-gateway">The Core Design Principle: A Unified Model Gateway</h2>

<p>The single most important architectural decision I made was to route all LLM inference through a single OpenAI-compatible endpoint rather than having each tool reach out to Ollama, Anthropic, or OpenRouter independently. I use <a href="https://github.com/BerriAI/litellm">LiteLLM</a> for this. Every service in the stack sends its requests to <code class="language-plaintext highlighter-rouge">http://localhost:4000/v1</code> with the bearer token <code class="language-plaintext highlighter-rouge">sk-litellm-local</code>. LiteLLM translates those requests to whatever backend is appropriate, whether a local Ollama model, a LocalAI GGUF endpoint, or an OpenRouter free-tier model, according to a YAML routing configuration.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">model_list</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">model_name</span><span class="pi">:</span> <span class="s">llama3</span>
    <span class="na">litellm_params</span><span class="pi">:</span>
      <span class="na">model</span><span class="pi">:</span> <span class="s">ollama/llama3</span>
      <span class="na">api_base</span><span class="pi">:</span> <span class="s">http://host.docker.internal:11434</span>
 
  <span class="pi">-</span> <span class="na">model_name</span><span class="pi">:</span> <span class="s">qwen2.5-3b</span>
    <span class="na">litellm_params</span><span class="pi">:</span>
      <span class="na">model</span><span class="pi">:</span> <span class="s">ollama/qwen2.5:3b</span>
      <span class="na">api_base</span><span class="pi">:</span> <span class="s">http://host.docker.internal:11434</span>
 
  <span class="pi">-</span> <span class="na">model_name</span><span class="pi">:</span> <span class="s">hermes3</span>
    <span class="na">litellm_params</span><span class="pi">:</span>
      <span class="na">model</span><span class="pi">:</span> <span class="s">ollama/hermes3:8b</span>
      <span class="na">api_base</span><span class="pi">:</span> <span class="s">http://host.docker.internal:11434</span>
 
  <span class="pi">-</span> <span class="na">model_name</span><span class="pi">:</span> <span class="s">openrouter/auto</span>
    <span class="na">litellm_params</span><span class="pi">:</span>
      <span class="na">model</span><span class="pi">:</span> <span class="s">openrouter/auto</span>
      <span class="na">api_key</span><span class="pi">:</span> <span class="s">${OPENROUTER_API_KEY}</span>
      <span class="na">api_base</span><span class="pi">:</span> <span class="s">https://openrouter.ai/api/v1</span>
</code></pre></div></div>

<p>The practical consequence is that changing a model, adding a provider, or adjusting routing requires editing one YAML file and restarting one service. No other container needs to know that anything changed. This is the same composability principle I teach in software engineering: minimize coupling, maximize cohesion.</p>

<p>Connecting a commercial CLI tool like Claude Code to the local stack requires only two environment variable exports:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">export </span><span class="nv">ANTHROPIC_BASE_URL</span><span class="o">=</span>http://localhost:4000
<span class="nb">export </span><span class="nv">ANTHROPIC_API_KEY</span><span class="o">=</span>sk-litellm-local
</code></pre></div></div>

<h3 id="litellm-deployment">LiteLLM Deployment</h3>

<p>LiteLLM runs as a Docker Compose service. The <code class="language-plaintext highlighter-rouge">docker-compose.yml</code> pulls the pre-built image; everything else is bind-mounted configuration.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># litellm/docker-compose.yml</span>
<span class="na">version</span><span class="pi">:</span> <span class="s2">"</span><span class="s">3.9"</span>
<span class="na">services</span><span class="pi">:</span>
  <span class="na">litellm</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">ghcr.io/berriai/litellm:main-latest</span>
    <span class="na">container_name</span><span class="pi">:</span> <span class="s">litellm-${USER}</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">4000:4000"</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">./litellm_config.yaml:/app/config.yaml:ro</span>
    <span class="na">env_file</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">.env</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">--config"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">/app/config.yaml"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">--port"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">4000"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">--num_workers"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">2"</span><span class="pi">]</span>
    <span class="na">extra_hosts</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">host.docker.internal:host-gateway"</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">.env</code> file holds the master key and any cloud provider keys:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># litellm/.env</span>
<span class="nv">LITELLM_MASTER_KEY</span><span class="o">=</span>sk-litellm-local
<span class="nv">OPENROUTER_API_KEY</span><span class="o">=</span>YOUR_OPENROUTER_API_KEY
</code></pre></div></div>

<p>Build and run scripts are minimal wrappers around Compose:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># litellm/build.sh — pull image, start, verify endpoint</span>
<span class="nb">cd</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/litellm"</span>
docker compose pull
docker compose up <span class="nt">-d</span>
<span class="nb">sleep </span>20
curl <span class="nt">-s</span> http://localhost:4000/models <span class="se">\</span>
  <span class="nt">-H</span> <span class="s2">"Authorization: Bearer sk-litellm-local"</span> | python3 <span class="nt">-m</span> json.tool | <span class="nb">head</span> <span class="nt">-20</span>
 
<span class="c"># litellm/run.sh — start after reboot</span>
<span class="nb">cd</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/litellm"</span> <span class="o">&amp;&amp;</span> docker compose up <span class="nt">-d</span>
 
<span class="c"># litellm/attach.sh — tail live logs</span>
<span class="nb">cd</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/litellm"</span> <span class="o">&amp;&amp;</span> docker compose logs <span class="nt">--tail</span><span class="o">=</span>30 <span class="nt">-f</span> litellm-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p>Restart after a config change: <code class="language-plaintext highlighter-rouge">cd $HOME/agents/litellm &amp;&amp; docker compose down &amp;&amp; docker compose up -d</code>.</p>

<h2 id="the-full-stack-services-and-ports">The Full Stack: Services and Ports</h2>

<table>
  <thead>
    <tr>
      <th>Service</th>
      <th>Port</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>LiteLLM</td>
      <td>4000</td>
      <td>Unified model gateway (OpenAI-compatible)</td>
    </tr>
    <tr>
      <td>Ollama</td>
      <td>11434</td>
      <td>Local LLM inference (native systemd service)</td>
    </tr>
    <tr>
      <td>LocalAI</td>
      <td>8080</td>
      <td>GGUF model inference (OpenAI-compatible)</td>
    </tr>
    <tr>
      <td>Open WebUI</td>
      <td>3000</td>
      <td>Browser-based LLM frontend with MCP tool calling</td>
    </tr>
    <tr>
      <td>Mastra</td>
      <td>4111</td>
      <td>TypeScript AI agent server (API + Studio UI)</td>
    </tr>
    <tr>
      <td>Agent Zero</td>
      <td>8081</td>
      <td>Autonomous hierarchical agent with web UI</td>
    </tr>
    <tr>
      <td>Archon</td>
      <td>3090</td>
      <td>Workflow-driven agent runner</td>
    </tr>
    <tr>
      <td>Open Design</td>
      <td>5173</td>
      <td>Collaborative design canvas with embedded pi agent</td>
    </tr>
    <tr>
      <td>Portainer</td>
      <td>9000</td>
      <td>Docker management UI</td>
    </tr>
  </tbody>
</table>

<h2 id="local-inference-ollama-and-localai">Local Inference: Ollama and LocalAI</h2>

<p>The stack runs two local inference backends with distinct tradeoffs, and LiteLLM routes between them transparently based on model alias.</p>

<p><strong>Ollama</strong> is the primary inference backend. Its systemd service model keeps it available before Docker is fully up, its model management CLI is clean, and its HTTP API is stable. The models I maintain are selected for RAM footprint first: <code class="language-plaintext highlighter-rouge">phi4-mini</code>, <code class="language-plaintext highlighter-rouge">smollm2</code>, <code class="language-plaintext highlighter-rouge">gemma4:e2b</code>, <code class="language-plaintext highlighter-rouge">qwen2.5:1.5b</code>, <code class="language-plaintext highlighter-rouge">qwen2.5:3b</code>, <code class="language-plaintext highlighter-rouge">llama3</code>, and <code class="language-plaintext highlighter-rouge">hermes3:8b</code>.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># ollama/run.sh</span>
docker run <span class="nt">-d</span> <span class="se">\</span>
  <span class="nt">--name</span> ollama-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">--restart</span> no <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-p</span> 11434:11434 <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/ollama/data:/root/.ollama"</span> <span class="se">\</span>
  ollama/ollama:latest
 
<span class="c"># Pull models after starting</span>
<span class="k">for </span>model <span class="k">in </span>phi4-mini smollm2 <span class="s2">"gemma4:e2b"</span> <span class="s2">"qwen2.5:1.5b"</span> <span class="s2">"qwen2.5:3b"</span> llama3 <span class="s2">"hermes3:8b"</span><span class="p">;</span> <span class="k">do
  </span>docker <span class="nb">exec </span>ollama-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> ollama pull <span class="s2">"</span><span class="nv">$model</span><span class="s2">"</span>
<span class="k">done</span>
</code></pre></div></div>

<p><strong>LocalAI</strong> (<a href="https://github.com/mudler/LocalAI">github.com/mudler/LocalAI</a>) is the secondary inference backend, running on port 8080 behind an OpenAI-compatible API surface. It supports llama.cpp for text generation, whisper.cpp for speech transcription, and stable diffusion for image generation, all behind the same endpoint. LocalAI is organized around three bind-mounted directories: <code class="language-plaintext highlighter-rouge">models/</code> holds GGUF weight files, <code class="language-plaintext highlighter-rouge">backends/</code> holds compiled backend binaries, and <code class="language-plaintext highlighter-rouge">config/</code> holds per-model YAML configuration. Note that the host directory is named <code class="language-plaintext highlighter-rouge">config/</code> while the container mount path is <code class="language-plaintext highlighter-rouge">/configuration</code>; this asymmetry is intentional and must be preserved.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># localai/run.sh</span>
docker run <span class="nt">-d</span> <span class="se">\</span>
  <span class="nt">--name</span> localai-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">--restart</span> no <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-p</span> 8080:8080 <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/localai/models:/models"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/localai/backends:/backends"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/localai/config:/configuration"</span> <span class="se">\</span>
  localai/localai:latest
</code></pre></div></div>

<p>A per-model YAML config controls backend selection and context length:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># localai/config/phi4-mini.yaml</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">phi4-mini</span>
<span class="na">backend</span><span class="pi">:</span> <span class="s">llama</span>
<span class="na">parameters</span><span class="pi">:</span>
  <span class="na">model</span><span class="pi">:</span> <span class="s">phi-4-mini-instruct.Q4_K_M.gguf</span>
  <span class="na">context_size</span><span class="pi">:</span> <span class="m">8192</span>
  <span class="na">threads</span><span class="pi">:</span> <span class="m">8</span>
</code></pre></div></div>

<h2 id="browser-frontend-open-webui">Browser Frontend: Open WebUI</h2>

<p><a href="https://github.com/open-webui/open-webui">Open WebUI</a> is the browser-based interface for direct LLM interaction, running on port 3000. It connects to Ollama directly and enumerates available models automatically. Its native MCP tool-calling support (version 0.4 and later) intercepts tool-call responses, dispatches them to registered MCP servers, and injects results back into the conversation.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># openwebui/run.sh</span>
docker run <span class="nt">-d</span> <span class="nt">-p</span> 3000:8080 <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/openwebui/data:/app/backend/data"</span> <span class="se">\</span>
  <span class="nt">--name</span> open-webui-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  ghcr.io/open-webui/open-webui:main
</code></pre></div></div>

<p>After launch, connect to LiteLLM via Admin Settings → Connections → OpenAI: set the URL to <code class="language-plaintext highlighter-rouge">http://host.docker.internal:4000/v1</code> and the API key to <code class="language-plaintext highlighter-rouge">sk-litellm-local</code>. Models confirmed to work reliably with Open WebUI tool calling include <code class="language-plaintext highlighter-rouge">hermes3:8b</code>, <code class="language-plaintext highlighter-rouge">llama3.1:8b</code>, <code class="language-plaintext highlighter-rouge">qwen2.5:7b</code>, <code class="language-plaintext highlighter-rouge">qwen2.5:14b</code>, and <code class="language-plaintext highlighter-rouge">mistral-nemo:12b</code>.</p>

<h2 id="agentic-cli-tools-a-comparative-survey">Agentic CLI Tools: A Comparative Survey</h2>

<p>By April 2026, a mature set of agentic coding CLI tools has emerged with distinct architectural philosophies, and I run all of them through the unified LiteLLM gateway. Each tool runs inside a dedicated Docker container with an identity bind mount, a shared workspace mount, and an optional skills mount. The sections below show the Dockerfile, build script, and run script for each.</p>

<p><strong>Claude Code</strong> (Anthropic, Node.js) is the most fully featured in terms of built-in subagent support, MCP integration, and permission gate granularity. It uses <code class="language-plaintext highlighter-rouge">CLAUDE.md</code> files for project context and <code class="language-plaintext highlighter-rouge">.claude/agents/</code> Markdown files for custom subagent definitions.</p>

<p><strong>OpenAI Codex CLI</strong> (Rust) supports native multi-provider configuration through a TOML config file. Custom providers are defined as named sections:</p>

<div class="language-toml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="py">model</span> <span class="p">=</span> <span class="s">"llama3.3:70b"</span>
<span class="py">model_provider</span> <span class="p">=</span> <span class="s">"openwebui"</span>
 
<span class="nn">[model_providers.openwebui]</span>
<span class="py">name</span> <span class="p">=</span> <span class="s">"Open WebUI"</span>
<span class="py">base_url</span> <span class="p">=</span> <span class="s">"http://localhost:3000/openai"</span>
<span class="py">env_key</span> <span class="p">=</span> <span class="s">"OPENWEBUI_API_KEY"</span>
</code></pre></div></div>

<p><strong>Gemini CLI</strong> (Google, Node.js) uses <code class="language-plaintext highlighter-rouge">GEMINI.md</code> files for project context and a three-tier discovery hierarchy for skills. Routing it through an OpenAI-compatible endpoint requires the <code class="language-plaintext highlighter-rouge">open-gemini-cli</code> fork, which injects an adapter layer that translates Gemini’s internal message format.</p>

<p><strong>OpenCode</strong> (opencode.ai, Go) is the most flexible in terms of provider support, relying on the <code class="language-plaintext highlighter-rouge">@ai-sdk/openai-compatible</code> adapter to connect to any OpenAI-compatible backend:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"provider"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"litellm"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"npm"</span><span class="p">:</span><span class="w"> </span><span class="s2">"@ai-sdk/openai-compatible"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"options"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"baseURL"</span><span class="p">:</span><span class="w"> </span><span class="s2">"http://localhost:4000/v1"</span><span class="w"> </span><span class="p">},</span><span class="w">
      </span><span class="nl">"models"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"llama3"</span><span class="p">:</span><span class="w"> </span><span class="p">{},</span><span class="w"> </span><span class="nl">"qwen2.5-3b"</span><span class="p">:</span><span class="w"> </span><span class="p">{},</span><span class="w"> </span><span class="nl">"hermes3"</span><span class="p">:</span><span class="w"> </span><span class="p">{}</span><span class="w"> </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h3 id="commercial-tools-deployment-claude-code-codex-gemini-cli-copilot-ccr-bash">Commercial Tools Deployment (Claude Code, Codex, Gemini CLI, Copilot, CCR, bash)</h3>

<p>Claude Code, Codex, Gemini CLI, GitHub Copilot, the Claude Code Router, and a plain <code class="language-plaintext highlighter-rouge">bash</code> shell all share a single Docker image. The tool to launch is selected at runtime as an argument to <code class="language-plaintext highlighter-rouge">run.sh</code>. The <code class="language-plaintext highlighter-rouge">bash</code> option is a deliberately included escape hatch: it drops into an interactive shell inside the <code class="language-plaintext highlighter-rouge">commercial-ai</code> container with all identity and workspace volumes mounted, but without launching any AI tool. This is useful for inspecting the container environment, running scripts manually, debugging mount layouts, or staging files before invoking an AI tool in a separate session.</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># commercial/Dockerfile</span>
<span class="k">FROM</span><span class="s"> node:22-bookworm</span>
 
<span class="k">RUN </span>apt-get update <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>    git curl ca-certificates ripgrep less nano vim <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">-g</span> <span class="se">\
</span>    @anthropic-ai/claude-code <span class="se">\
</span>    @openai/codex <span class="se">\
</span>    @google/gemini-cli <span class="se">\
</span>    @github/copilot <span class="se">\
</span>    @musistudio/claude-code-router
 
<span class="k">RUN </span><span class="nb">mkdir</span> <span class="nt">-p</span> /root/.claude-code-router
<span class="k">WORKDIR</span><span class="s"> /workspace</span>
<span class="k">CMD</span><span class="s"> ["/bin/bash"]</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">build.sh</code> creates per-tool identity directories for all six options, including <code class="language-plaintext highlighter-rouge">bash</code>, so the directory layout is consistent regardless of which tool is invoked:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env bash</span>
<span class="nb">set</span> <span class="nt">-euo</span> pipefail
 
docker build <span class="nt">-t</span> commercial-ai:latest <span class="nb">.</span>
 
<span class="nv">BASE_DIR</span><span class="o">=</span><span class="s2">"/home/bill/agents/commercial"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/workspace"</span>
 
<span class="k">for </span>tool <span class="k">in </span>claude codex gemini copilot ccr bash<span class="p">;</span> <span class="k">do
  </span><span class="nb">mkdir</span> <span class="nt">-p</span> <span class="se">\</span>
    <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/</span><span class="k">${</span><span class="nv">tool</span><span class="k">}</span><span class="s2">/home"</span> <span class="se">\</span>
    <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/</span><span class="k">${</span><span class="nv">tool</span><span class="k">}</span><span class="s2">/npm"</span> <span class="se">\</span>
    <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/</span><span class="k">${</span><span class="nv">tool</span><span class="k">}</span><span class="s2">/config"</span> <span class="se">\</span>
    <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/</span><span class="k">${</span><span class="nv">tool</span><span class="k">}</span><span class="s2">/cache"</span>
<span class="k">done</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">run.sh</code> dispatches on the tool name to set the API variable and CLI command. The <code class="language-plaintext highlighter-rouge">bash</code> case sets no API variable and uses <code class="language-plaintext highlighter-rouge">/bin/bash</code> as the command, so no credential prompt is issued and the container simply provides an interactive shell:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/usr/bin/env bash</span>
<span class="nb">set</span> <span class="nt">-euo</span> pipefail
 
<span class="nv">IMAGE</span><span class="o">=</span><span class="s2">"commercial-ai:latest"</span>
<span class="nv">BASE_DIR</span><span class="o">=</span><span class="s2">"/home/bill/agents/commercial"</span>
<span class="nv">CCR_CONFIG</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/ccr/config.json"</span>
 
<span class="k">if</span> <span class="o">[[</span> <span class="nv">$# </span><span class="nt">-ne</span> 1 <span class="o">]]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">echo</span> <span class="s2">"[run.sh] Usage: </span><span class="nv">$0</span><span class="s2"> {bash|claude|codex|gemini|copilot|ccr}"</span>
  <span class="nb">exit </span>1
<span class="k">fi
 
</span><span class="nv">TOOL</span><span class="o">=</span><span class="s2">"</span><span class="nv">$1</span><span class="s2">"</span>
<span class="nv">EXTRA_ARGS</span><span class="o">=()</span>
<span class="nv">ENV_ARGS</span><span class="o">=()</span>
 
<span class="k">case</span> <span class="s2">"</span><span class="nv">$TOOL</span><span class="s2">"</span> <span class="k">in
  </span>bash<span class="p">)</span>
    <span class="nv">API_VAR</span><span class="o">=</span><span class="s2">""</span>
    <span class="nv">CLI_CMD</span><span class="o">=</span><span class="s2">"/bin/bash"</span>
    <span class="p">;;</span>
  claude<span class="p">)</span>
    <span class="nv">API_VAR</span><span class="o">=</span><span class="s2">"ANTHROPIC_API_KEY"</span>
    <span class="nv">CLI_CMD</span><span class="o">=</span><span class="s2">"claude"</span>
    <span class="p">;;</span>
  ccr<span class="p">)</span>
    <span class="nv">API_VAR</span><span class="o">=</span><span class="s2">"ANTHROPIC_API_KEY"</span>
    <span class="nv">CLI_CMD</span><span class="o">=</span><span class="s2">"ccr code"</span>
    <span class="k">if</span> <span class="o">[[</span> <span class="o">!</span> <span class="nt">-f</span> <span class="s2">"</span><span class="k">${</span><span class="nv">CCR_CONFIG</span><span class="k">}</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
      </span><span class="nb">echo</span> <span class="s2">"[run.sh] CCR config not found at </span><span class="k">${</span><span class="nv">CCR_CONFIG</span><span class="k">}</span><span class="s2">"</span>
      <span class="nb">echo</span> <span class="s2">"[run.sh] Create it before running with the ccr option."</span>
      <span class="nb">exit </span>1
    <span class="k">fi
    </span>EXTRA_ARGS+<span class="o">=(</span><span class="nt">-v</span> <span class="s2">"</span><span class="k">${</span><span class="nv">CCR_CONFIG</span><span class="k">}</span><span class="s2">:/home/agent/.claude-code-router/config.json:ro"</span><span class="o">)</span>
    <span class="p">;;</span>
  codex<span class="p">)</span>
    <span class="nv">API_VAR</span><span class="o">=</span><span class="s2">"OPENAI_API_KEY"</span>
    <span class="nv">CLI_CMD</span><span class="o">=</span><span class="s2">"codex"</span>
    <span class="p">;;</span>
  gemini<span class="p">)</span>
    <span class="nv">API_VAR</span><span class="o">=</span><span class="s2">"GEMINI_API_KEY"</span>
    <span class="nv">CLI_CMD</span><span class="o">=</span><span class="s2">"gemini"</span>
    <span class="p">;;</span>
  copilot<span class="p">)</span>
    <span class="nv">API_VAR</span><span class="o">=</span><span class="s2">"GITHUB_TOKEN"</span>
    <span class="nv">CLI_CMD</span><span class="o">=</span><span class="s2">"copilot"</span>
    <span class="p">;;</span>
  <span class="k">*</span><span class="p">)</span>
    <span class="nb">echo</span> <span class="s2">"[run.sh] Invalid tool: </span><span class="nv">$TOOL</span><span class="s2">"</span>
    <span class="nb">echo</span> <span class="s2">"[run.sh] Valid options: bash | claude | codex | gemini | copilot | ccr"</span>
    <span class="nb">exit </span>1
    <span class="p">;;</span>
<span class="k">esac</span>
 
<span class="nv">TOOL_DIR</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/</span><span class="k">${</span><span class="nv">TOOL</span><span class="k">}</span><span class="s2">"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/workspace"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/home"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/npm"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/config"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/cache"</span>
 
<span class="k">if</span> <span class="o">[[</span> <span class="nt">-n</span> <span class="s2">"</span><span class="k">${</span><span class="nv">API_VAR</span><span class="k">}</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
  if</span> <span class="o">[[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="k">${</span><span class="p">!API_VAR</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
    </span><span class="nb">echo</span> <span class="s2">"[run.sh] </span><span class="k">${</span><span class="nv">API_VAR</span><span class="k">}</span><span class="s2"> is not set. Please enter it:"</span>
    <span class="nb">read</span> <span class="nt">-rsp</span> <span class="s2">"&gt;&gt;&gt; "</span> USER_KEY
    <span class="nb">echo</span> <span class="s2">""</span>
    <span class="nb">export</span> <span class="s2">"</span><span class="k">${</span><span class="nv">API_VAR</span><span class="k">}</span><span class="s2">=</span><span class="k">${</span><span class="nv">USER_KEY</span><span class="k">}</span><span class="s2">"</span>
  <span class="k">fi
  </span>ENV_ARGS+<span class="o">=(</span><span class="s2">"-e"</span> <span class="s2">"</span><span class="k">${</span><span class="nv">API_VAR</span><span class="k">}</span><span class="s2">=</span><span class="k">${</span><span class="p">!API_VAR</span><span class="k">}</span><span class="s2">"</span><span class="o">)</span>
<span class="k">fi
 
</span>docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> <span class="s2">"commercial-</span><span class="k">${</span><span class="nv">TOOL</span><span class="k">}</span><span class="s2">-bill"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">HOME</span><span class="o">=</span><span class="s2">"/home/agent"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">ENV_ARGS</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="k">${</span><span class="nv">BASE_DIR</span><span class="k">}</span><span class="s2">/workspace:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/home:/home/agent"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/npm:/home/agent/.npm"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/config:/home/agent/.config"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="k">${</span><span class="nv">TOOL_DIR</span><span class="k">}</span><span class="s2">/cache:/home/agent/.cache"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">EXTRA_ARGS</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-w</span> /workspace <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">IMAGE</span><span class="k">}</span><span class="s2">"</span> <span class="k">${</span><span class="nv">CLI_CMD</span><span class="k">}</span>
</code></pre></div></div>

<p>Invoking <code class="language-plaintext highlighter-rouge">./run.sh bash</code> thus drops into the container with the full commercial identity environment present but no tool running, which makes it straightforward to inspect installed package versions, verify that volume mounts resolved correctly, or stage configuration files before running a tool. Because the <code class="language-plaintext highlighter-rouge">bash</code> identity directory (<code class="language-plaintext highlighter-rouge">commercial/bash/home</code>) is separate from all other tool identity directories, any modifications made in a shell session cannot bleed into a Claude Code or Codex session.</p>

<p>The <code class="language-plaintext highlighter-rouge">ccr</code> (Claude Code Router) variant additionally mounts its routing config read-only:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">//</span><span class="w"> </span><span class="err">commercial/ccr/config.json</span><span class="w"> </span><span class="err">—</span><span class="w"> </span><span class="err">routing</span><span class="w"> </span><span class="err">table</span><span class="w">
</span><span class="p">{</span><span class="w">
  </span><span class="nl">"Router"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"default"</span><span class="p">:</span><span class="w">          </span><span class="s2">"ollama,llama3:latest"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"background"</span><span class="p">:</span><span class="w">       </span><span class="s2">"ollama,qwen2.5:1.5b"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"think"</span><span class="p">:</span><span class="w">            </span><span class="s2">"ollama,gemma4:e2b"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"longContext"</span><span class="p">:</span><span class="w">      </span><span class="s2">"openrouter,google/gemini-2.5-pro-exp-03-25:free"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"longContextThreshold"</span><span class="p">:</span><span class="w"> </span><span class="mi">60000</span><span class="p">,</span><span class="w">
    </span><span class="nl">"webSearch"</span><span class="p">:</span><span class="w">        </span><span class="s2">"openrouter,google/gemini-2.5-pro-exp-03-25:online"</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Switching the active model within a running Claude Code session is a single slash command: <code class="language-plaintext highlighter-rouge">/model ollama,llama3:latest</code>.</p>

<h3 id="opencode-deployment">OpenCode Deployment</h3>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># opencode/Dockerfile</span>
<span class="k">FROM</span><span class="s"> node:20-bookworm-slim</span>
 
<span class="k">RUN </span>apt-get update <span class="se">\
</span>    <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>        curl ca-certificates git bash findutils <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>curl <span class="nt">-fsSL</span> https://opencode.ai/install | bash <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">mkdir</span> <span class="nt">-p</span> /opt/opencode/bin <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">cp</span> <span class="s2">"</span><span class="si">$(</span>find /root <span class="nt">-type</span> f <span class="nt">-name</span> opencode | <span class="nb">head</span> <span class="nt">-n</span> 1<span class="si">)</span><span class="s2">"</span> /opt/opencode/bin/opencode <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">chmod </span>755 /opt/opencode/bin/opencode
 
<span class="k">ENV</span><span class="s"> PATH="/opt/opencode/bin:${PATH}"</span>
<span class="k">ENV</span><span class="s"> HOME=/home/opencode</span>
<span class="k">VOLUME</span><span class="s"> ["/workspace"]</span>
<span class="k">WORKDIR</span><span class="s"> /workspace</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["/opt/opencode/bin/opencode"]</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># opencode/build.sh</span>
docker build <span class="nt">-t</span> opencode:local <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/opencode"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/opencode/home"</span>
 
<span class="c"># opencode/run.sh</span>
docker run <span class="nt">--restart</span> no <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> opencode-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/opencode/home:/home/opencode"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/skills/core:/app/skills/core:ro"</span> <span class="se">\</span>
  opencode:local
 
<span class="c"># opencode/attach.sh</span>
docker start <span class="nt">-ai</span> opencode-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p><strong>KiloCode</strong> (VS Code extension, Node.js) is the VS Code-native member of the survey. It brings the agentic loop into the editor rather than the terminal, with direct access to the VS Code language server for diagnostics, symbol navigation, and refactoring. Connecting it to LiteLLM is a one-field change in its settings JSON.</p>

<h3 id="kilocode-deployment">KiloCode Deployment</h3>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># kilocode/Dockerfile</span>
<span class="k">FROM</span><span class="s"> debian:bookworm-slim</span>
 
<span class="k">RUN </span>apt-get update <span class="o">&amp;&amp;</span> <span class="se">\
</span>    apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>        ca-certificates git bash wget curl <span class="o">&amp;&amp;</span> <span class="se">\
</span>    <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">ARG</span><span class="s"> TARGETARCH=amd64</span>
 
<span class="k">RUN </span><span class="nv">ARCH</span><span class="o">=</span><span class="k">${</span><span class="nv">TARGETARCH</span><span class="k">}</span> <span class="o">&amp;&amp;</span> <span class="se">\
</span>    <span class="k">if</span> <span class="o">[</span> <span class="s2">"</span><span class="nv">$ARCH</span><span class="s2">"</span> <span class="o">=</span> <span class="s2">"arm64"</span> <span class="o">]</span><span class="p">;</span> <span class="k">then </span><span class="nv">ARCH</span><span class="o">=</span><span class="s2">"arm64"</span><span class="p">;</span> <span class="k">else </span><span class="nv">ARCH</span><span class="o">=</span><span class="s2">"x64"</span><span class="p">;</span> <span class="k">fi</span> <span class="o">&amp;&amp;</span> <span class="se">\
</span>    wget <span class="nt">-qO</span> /tmp/kilo.tar.gz <span class="se">\
</span>        <span class="s2">"https://github.com/Kilo-Org/kilocode/releases/latest/download/kilo-linux-</span><span class="k">${</span><span class="nv">ARCH</span><span class="k">}</span><span class="s2">.tar.gz"</span> <span class="o">&amp;&amp;</span> <span class="se">\
</span>    <span class="nb">tar</span> <span class="nt">-xzf</span> /tmp/kilo.tar.gz <span class="nt">-C</span> /usr/local/bin <span class="o">&amp;&amp;</span> <span class="se">\
</span>    <span class="nb">chmod</span> +x /usr/local/bin/kilo <span class="o">&amp;&amp;</span> <span class="se">\
</span>    <span class="nb">rm</span> /tmp/kilo.tar.gz
 
<span class="k">VOLUME</span><span class="s"> ["/workspace"]</span>
<span class="k">WORKDIR</span><span class="s"> /workspace</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["kilo"]</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># kilocode/build.sh</span>
docker build <span class="nt">-t</span> kilocode:local <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/kilocode"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/kilocode/home"</span>
<span class="nb">chown</span> <span class="nt">-R</span> <span class="si">$(</span><span class="nb">id</span> <span class="nt">-u</span><span class="si">)</span>:<span class="si">$(</span><span class="nb">id</span> <span class="nt">-g</span><span class="si">)</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/kilocode/home"</span>
<span class="nb">chmod</span> <span class="nt">-R</span> u+rwX <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/kilocode/home"</span>
 
<span class="c"># kilocode/run.sh</span>
docker run <span class="nt">--restart</span> no <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--user</span> <span class="si">$(</span><span class="nb">id</span> <span class="nt">-u</span><span class="si">)</span>:<span class="si">$(</span><span class="nb">id</span> <span class="nt">-g</span><span class="si">)</span> <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">HOME</span><span class="o">=</span>/home/kilo <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">XDG_CONFIG_HOME</span><span class="o">=</span>/home/kilo/.config <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">XDG_DATA_HOME</span><span class="o">=</span>/home/kilo/.local/share <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">XDG_CACHE_HOME</span><span class="o">=</span>/home/kilo/.cache <span class="se">\</span>
  <span class="nt">--name</span> kilocode-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">TERM</span><span class="o">=</span>xterm-256color <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/kilocode/home:/home/kilo"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/skills/core:/app/skills/core:ro"</span> <span class="se">\</span>
  kilocode:local
 
<span class="c"># kilocode/attach.sh</span>
docker start <span class="nt">-ai</span> kilocode-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p><strong>pi</strong> (pi.dev, Node.js) takes a deliberately minimal stance, omitting built-in MCP, plan mode, and permission gates in favor of a package-based extensibility model. It supports OpenRouter directly through a provider block in <code class="language-plaintext highlighter-rouge">models.json</code>, and NVIDIA NIM endpoints are equally accessible through the same mechanism. I reach for pi primarily for rapid exploratory work precisely because it does not impose an opinionated workflow.</p>

<h3 id="pi-deployment">Pi Deployment</h3>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># pi/Dockerfile</span>
<span class="k">FROM</span><span class="s"> node:22-bookworm-slim</span>
 
<span class="k">RUN </span>apt-get update <span class="se">\
</span> <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>    bash ca-certificates curl git openssh-client <span class="se">\
</span> <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">-g</span> @mariozechner/pi-coding-agent
 
<span class="k">ENV</span><span class="s"> HOME=/home/pi-agent</span>
<span class="k">VOLUME</span><span class="s"> ["/workspace"]</span>
<span class="k">WORKDIR</span><span class="s"> /workspace</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["pi"]</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># pi/build.sh</span>
docker build <span class="nt">-t</span> pi:local <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/pi"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/pi/home/.pi/agent"</span>
 
<span class="c"># Write default models.json pointing at Ollama</span>
<span class="nb">cat</span> <span class="o">&gt;</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/pi/home/.pi/agent/models.json"</span> <span class="o">&lt;&lt;</span> <span class="sh">'</span><span class="no">EOF</span><span class="sh">'
{
  "providers": {
    "ollama": {
      "baseUrl": "http://host.docker.internal:11434/v1",
      "api": "openai-completions",
      "apiKey": "ollama",
      "models": [
        {
          "id": "qwen2.5:7b",
          "name": "Qwen 2.5 7B (Local)",
          "contextWindow": 32768,
          "maxTokens": 8192,
          "cost": { "input": 0, "output": 0 }
        }
      ]
    },
    "openrouter": {
      "baseUrl": "https://openrouter.ai/api/v1",
      "apiKey": "</span><span class="k">${</span><span class="nv">OPENROUTER_API_KEY</span><span class="k">}</span><span class="sh">",
      "models": [
        { "id": "google/gemini-2.5-pro-exp-03-25:free", "contextWindow": 1000000 },
        { "id": "meta-llama/llama-4-maverick:free",      "contextWindow": 128000  }
      ]
    }
  }
}
</span><span class="no">EOF
 
</span><span class="c"># pi/run.sh</span>
docker run <span class="nt">--restart</span> no <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> pi-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">TERM</span><span class="o">=</span>xterm-256color <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">OLLAMA_HOST</span><span class="o">=</span><span class="s2">"http://host.docker.internal:11434"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">OPENROUTER_API_KEY</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">OPENROUTER_API_KEY</span><span class="k">:-</span><span class="nv">YOUR_OPENROUTER_API_KEY</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/pi/home:/home/pi-agent"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/skills/core:/app/skills/core:ro"</span> <span class="se">\</span>
  pi:local
 
<span class="c"># pi/attach.sh</span>
docker start <span class="nt">-ai</span> pi-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p><strong>Hermes</strong> is a named agent identity maintained around Nous Research’s Hermes 3 model family. The <code class="language-plaintext highlighter-rouge">hermes/home/</code> directory holds a configuration and prompt library tuned for Hermes 3’s specific instruction format and function-calling conventions. Because Hermes 3 handles structured output and tool-use with uncommon consistency, I route all tool-calling-heavy workloads to this identity.</p>

<h3 id="hermes-agent-deployment">Hermes Agent Deployment</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># hermes/build.sh — probe first, then run</span>
<span class="c"># Confirm the image's runtime user and home directory before committing a mount path:</span>
docker pull nousresearch/hermes-agent:latest
docker run <span class="nt">--rm</span> <span class="nt">--entrypoint</span> sh nousresearch/hermes-agent:latest <span class="se">\</span>
  <span class="nt">-c</span> <span class="s1">'id &amp;&amp; echo HOME=$HOME'</span>
 
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/hermes/home"</span>
 
<span class="c"># hermes/run.sh</span>
<span class="c"># Always launch with -it — running detached causes immediate exit</span>
docker run <span class="nt">--restart</span> no <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> hermes-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">TERM</span><span class="o">=</span>xterm-256color <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/hermes/home:/home/hermes/.hermes"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/workspace"</span> <span class="se">\</span>
  nousresearch/hermes-agent:latest
 
<span class="c"># hermes/attach.sh</span>
docker start <span class="nt">-ai</span> hermes-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p><strong>GNHF</strong> (Good Night Have Fun) is the task-bounded harness I use when I want a single-purpose agent that executes a defined workflow, reports results, and stops. The name is a ham radio sign-off, which fits its character: polite, brief, and does exactly what it was asked to do. Unlike Claude Code or pi, which are interactive and session-oriented, GNHF takes a task description and a workspace path as inputs, executes against the LiteLLM gateway, writes its outputs to the workspace, and exits.</p>

<h3 id="gnhf-deployment">GNHF Deployment</h3>

<p>GNHF requires a Dockerfile placed at <code class="language-plaintext highlighter-rouge">$HOME/agents/gnhf/Dockerfile</code> before <code class="language-plaintext highlighter-rouge">build.sh</code> can execute, because the gnhf binary distribution mechanism is external to this stack. A representative starting point:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># gnhf/Dockerfile — adapt to your gnhf binary distribution</span>
<span class="k">FROM</span><span class="s"> node:22-bookworm</span>
 
<span class="k">RUN </span>apt-get update <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>    git curl ca-certificates ripgrep less <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="c"># Install the agent CLIs that gnhf wraps</span>
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">-g</span> <span class="se">\
</span>    @anthropic-ai/claude-code <span class="se">\
</span>    @openai/codex <span class="se">\
</span>    @github/copilot
 
<span class="c"># Install gnhf — adapt to your distribution method:</span>
<span class="c"># RUN npm install -g gnhf</span>
<span class="c"># or: COPY gnhf /usr/local/bin/gnhf &amp;&amp; chmod +x /usr/local/bin/gnhf</span>
 
<span class="k">WORKDIR</span><span class="s"> /workspace</span>
<span class="k">CMD</span><span class="s"> ["/bin/bash"]</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># gnhf/build.sh</span>
<span class="k">if</span> <span class="o">[[</span> <span class="o">!</span> <span class="nt">-f</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/gnhf/Dockerfile"</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">echo</span> <span class="s2">"ERROR: place Dockerfile in </span><span class="nv">$HOME</span><span class="s2">/agents/gnhf/ first"</span><span class="p">;</span> <span class="nb">exit </span>1
<span class="k">fi
</span>docker build <span class="nt">-t</span> gnhf:latest <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/gnhf"</span>
 
<span class="c"># gnhf/run.sh — key arguments shown; full script handles key resolution per agent</span>
<span class="c"># Usage: ./run.sh --agent &lt;codex|claude|copilot&gt; --repo &lt;path&gt; \</span>
<span class="c">#                 [--max-iterations N] [--max-tokens N] "task description"</span>
docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> <span class="s2">"gnhf-</span><span class="k">${</span><span class="nv">AGENT</span><span class="k">}</span><span class="s2">-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">ANTHROPIC_API_KEY</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">ANTHROPIC_API_KEY</span><span class="k">:-</span><span class="nv">YOUR_ANTHROPIC_API_KEY</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">HOME</span><span class="o">=</span><span class="s2">"/home/agent"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/gnhf/home:/home/agent"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/gnhf/npm:/home/agent/.npm"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/gnhf/config:/home/agent/.config"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/gnhf/cache:/home/agent/.cache"</span> <span class="se">\</span>
  gnhf:latest <span class="se">\</span>
  bash <span class="nt">-lc</span> <span class="s1">'
    cd "$1" &amp;&amp;
    git config --global --add safe.directory "$1" &amp;&amp;
    shift &amp;&amp; exec "$@"
  '</span> _ <span class="s2">"</span><span class="k">${</span><span class="nv">REPO_PATH</span><span class="k">}</span><span class="s2">"</span> gnhf <span class="nt">--agent</span> <span class="s2">"</span><span class="k">${</span><span class="nv">AGENT</span><span class="k">}</span><span class="s2">"</span> <span class="s2">"</span><span class="k">${</span><span class="nv">PROMPT</span><span class="k">}</span><span class="s2">"</span>
</code></pre></div></div>

<p>All six tools use project context files (<code class="language-plaintext highlighter-rouge">CLAUDE.md</code>, <code class="language-plaintext highlighter-rouge">AGENTS.md</code>, <code class="language-plaintext highlighter-rouge">GEMINI.md</code>) to provide persistent project instructions without consuming prompt tokens on every turn, and all six are converging on MCP as the standard for tool integration.</p>

<h2 id="the-google-ecosystem-agents-cli-and-workspace-cli">The Google Ecosystem: Agents CLI and Workspace CLI</h2>

<p>Two Google-specific tools occupy their own tier in the stack, with independent container identities and a shared philosophy of treating Google’s API surface as a set of agent-accessible tools.</p>

<p><strong>Google Agents CLI</strong> is the command-line interface for Google’s Agent Development Kit (ADK), a Python framework for building multi-agent systems that run on Google’s infrastructure and interact with Gemini models. The <code class="language-plaintext highlighter-rouge">uv</code> cache indicates a Python-heavy dependency footprint, the <code class="language-plaintext highlighter-rouge">evals/</code> directory holds evaluation datasets and result logs, and the container runs as a non-root user to match the bind-mounted volume permissions.</p>

<h3 id="google-agents-cli-deployment">Google Agents CLI Deployment</h3>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># googleagentscli/Dockerfile</span>
<span class="k">FROM</span><span class="s"> python:3.12-slim</span>
 
<span class="k">RUN </span>apt-get update <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>        ca-certificates curl git gnupg lsb-release unzip wget <span class="se">\
</span>        jq vim less procps build-essential <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>curl <span class="nt">-fsSL</span> https://deb.nodesource.com/setup_lts.x | bash - <span class="se">\
</span>    <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> nodejs <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">COPY</span><span class="s"> --from=ghcr.io/astral-sh/uv:latest /uv /uvx /usr/local/bin/</span>
 
<span class="c"># Google Cloud SDK</span>
<span class="k">RUN </span><span class="nb">echo</span> <span class="s2">"deb [signed-by=/usr/share/keyrings/cloud.google.gpg] </span><span class="se">\
</span><span class="s2">        https://packages.cloud.google.com/apt cloud-sdk main"</span> <span class="se">\
</span>        | <span class="nb">tee</span> /etc/apt/sources.list.d/google-cloud-sdk.list <span class="se">\
</span>    <span class="o">&amp;&amp;</span> curl <span class="nt">-fsSL</span> https://packages.cloud.google.com/apt/doc/apt-key.gpg <span class="se">\
</span>        | gpg <span class="nt">--dearmor</span> <span class="nt">-o</span> /usr/share/keyrings/cloud.google.gpg <span class="se">\
</span>    <span class="o">&amp;&amp;</span> apt-get update <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> google-cloud-cli <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>groupadd <span class="nt">-g</span> 1000 agent <span class="o">&amp;&amp;</span> useradd <span class="nt">-m</span> <span class="nt">-u</span> 1000 <span class="nt">-g</span> agent <span class="nt">-s</span> /bin/bash agent
 
<span class="k">ENV</span><span class="s"> UV_TOOL_DIR=/usr/local/uv-tools</span>
<span class="k">ENV</span><span class="s"> PATH="${UV_TOOL_DIR}/bin:${PATH}"</span>
 
<span class="k">RUN </span>uv tool <span class="nb">install </span>google-agents-cli <span class="o">&amp;&amp;</span> <span class="nb">chown</span> <span class="nt">-R</span> agent:agent <span class="s2">"</span><span class="k">${</span><span class="nv">UV_TOOL_DIR</span><span class="k">}</span><span class="s2">"</span>
 
<span class="k">RUN </span><span class="nb">mkdir</span> <span class="nt">-p</span> /workspace /home/agent/.config/agents-cli /home/agent/.config/gcloud <span class="se">\
</span>        /home/agent/.cache/uv /home/agent/.cache/npm /home/agent/evals /home/agent/logs <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">chown</span> <span class="nt">-R</span> agent:agent /workspace /home/agent/.config /home/agent/.cache <span class="se">\
</span>        /home/agent/evals /home/agent/logs
 
<span class="k">USER</span><span class="s"> agent</span>
<span class="k">WORKDIR</span><span class="s"> /workspace</span>
<span class="k">CMD</span><span class="s"> ["sleep", "infinity"]</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># googleagentscli/build.sh</span>
docker build <span class="nt">--progress</span><span class="o">=</span>plain <span class="nt">-t</span> google-agents-cli:local <span class="se">\</span>
  <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli"</span>
 
<span class="c"># googleagentscli/run.sh — starts detached; exec in with attach.sh</span>
<span class="nv">GCLOUD_MOUNT</span><span class="o">=()</span>
<span class="o">[[</span> <span class="nt">-d</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.config/gcloud"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="se">\</span>
  <span class="nv">GCLOUD_MOUNT</span><span class="o">=(</span><span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/.config/gcloud:/home/agent/.config/gcloud:ro"</span><span class="o">)</span>
 
docker run <span class="se">\</span>
  <span class="nt">--detach</span> <span class="se">\</span>
  <span class="nt">--name</span> <span class="s2">"googleagentscli-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli/data:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli/config:/home/agent/.config/agents-cli"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli/cache/uv:/home/agent/.cache/uv"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli/cache/npm:/home/agent/.cache/npm"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli/evals:/home/agent/evals"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleagentscli/logs:/home/agent/logs"</span> <span class="se">\</span>
  <span class="s2">"</span><span class="k">${</span><span class="nv">GCLOUD_MOUNT</span><span class="p">[@]</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">GOOGLE_API_KEY</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">GOOGLE_API_KEY</span><span class="k">:-</span><span class="nv">YOUR_GOOGLE_API_KEY</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">--workdir</span> /workspace <span class="se">\</span>
  google-agents-cli:local
 
<span class="c"># googleagentscli/attach.sh</span>
docker <span class="nb">exec</span> <span class="nt">-it</span> <span class="nt">--user</span> agent <span class="nt">--workdir</span> /workspace <span class="se">\</span>
  <span class="s2">"googleagentscli-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span> bash <span class="nt">--login</span>
</code></pre></div></div>

<p>Post-launch authentication: Option A (AI Studio key, no Cloud billing) is <code class="language-plaintext highlighter-rouge">docker exec -it googleagentscli-${USER} agents-cli login</code>. Option B (Google Cloud ADC for production workloads) requires running <code class="language-plaintext highlighter-rouge">gcloud auth application-default login</code> on the host machine; the <code class="language-plaintext highlighter-rouge">run.sh</code> mounts <code class="language-plaintext highlighter-rouge">~/.config/gcloud</code> read-only into the container automatically.</p>

<p><strong>Google Workspace CLI</strong> is a containerized <code class="language-plaintext highlighter-rouge">gcloud</code> environment configured with the scopes necessary to drive the Google Workspace APIs programmatically: Gmail, Drive, Calendar, Sheets, and Docs. Authenticate once inside the container; the bind-mounted credentials directory persists across container recreations.</p>

<h3 id="google-workspace-cli-deployment">Google Workspace CLI Deployment</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># googleworkspacecli/run.sh</span>
docker run <span class="nt">--restart</span> no <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> gworkspace-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/googleworkspacecli/gcloud:/root/.config/gcloud"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/workspace"</span> <span class="se">\</span>
  google/cloud-sdk:slim <span class="se">\</span>
  bash
 
<span class="c"># Inside container (first time only):</span>
<span class="c"># gcloud auth login</span>
<span class="c"># gcloud config set project YOUR_PROJECT_ID</span>
 
<span class="c"># googleworkspacecli/attach.sh</span>
docker start <span class="nt">-ai</span> gworkspace-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p>The authentication separation between the Workspace CLI container and the rest of the stack is intentional: the container that holds the Google credentials never has access to the project workspace or to any other agent’s identity directory. Data flows through the workspace volume only.</p>

<h2 id="agent-frameworks-agent-zero-archon-and-mastra">Agent Frameworks: Agent Zero, Archon, and Mastra</h2>

<p>The stack runs three agent frameworks that occupy distinct positions on the spectrum from fully autonomous to fully programmable.</p>

<h3 id="agent-zero">Agent Zero</h3>

<p><a href="https://github.com/frdel/agent-zero">Agent Zero</a> is the most autonomous framework in the stack, designed around the premise that the agent should be able to self-improve its own instructions and tools over the course of a session. It runs as a web UI on port 8081 and exposes a chat interface backed by a hierarchical agent system where the primary agent can spawn specialized subagents. The persistent state in <code class="language-plaintext highlighter-rouge">a0/data/</code> includes the agent’s memory bank, its accumulated tool library, and its evolving system prompt, all of which carry forward across container restarts.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># a0/build.sh</span>
docker pull agent0ai/agent-zero
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/a0/data"</span>
 
<span class="c"># a0/run.sh</span>
docker run <span class="nt">-d</span> <span class="se">\</span>
  <span class="nt">--name</span> <span class="s2">"a0-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">--restart</span> no <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-p</span> 8081:80 <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/a0/data:/a0/usr"</span> <span class="se">\</span>
  agent0ai/agent-zero
 
<span class="c"># a0/attach.sh — tail live logs (Ctrl+C safe; container keeps running)</span>
docker logs <span class="nt">--follow</span> <span class="nt">--timestamps</span> <span class="s2">"a0-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span>
</code></pre></div></div>

<p>Open <code class="language-plaintext highlighter-rouge">http://localhost:8081</code> in a browser after the container starts.</p>

<h3 id="archon">Archon</h3>

<p><a href="https://github.com/coleam00/Archon">Archon</a> occupies a meta-level in the stack: it is an agent framework whose purpose is to help build other agent frameworks. Its Streamlit-based UI presents a development environment where I describe the agent I want to build in natural language, and Archon generates the scaffolding, tool definitions, system prompt, and evaluation harness for that agent. Archon-generated agents are configured at generation time to use the LiteLLM endpoint, so they enter the stack already wired to the unified gateway without any post-generation modification.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># archon/build.sh</span>
docker pull ghcr.io/coleam00/archon:latest
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/archon/data/workflows"</span>
 
<span class="c"># archon/data/config.yaml — default model routing</span>
<span class="nb">cat</span> <span class="o">&gt;</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/archon/data/config.yaml"</span> <span class="o">&lt;&lt;</span> <span class="sh">'</span><span class="no">EOF</span><span class="sh">'
assistant: pi
assistants:
  pi:
    provider: openrouter
    model: openrouter/openrouter/free
</span><span class="no">EOF
 
</span><span class="c"># archon/run.sh — ephemeral (--rm); exits after task</span>
<span class="o">[[</span> <span class="nt">-z</span> <span class="s2">"</span><span class="k">${</span><span class="nv">OPENROUTER_API_KEY</span><span class="k">:-}</span><span class="s2">"</span> <span class="o">]]</span> <span class="o">&amp;&amp;</span> <span class="se">\</span>
  <span class="o">{</span> <span class="nb">echo</span> <span class="s2">"ERROR: OPENROUTER_API_KEY not set"</span><span class="p">;</span> <span class="nb">exit </span>1<span class="p">;</span> <span class="o">}</span>
 
docker run <span class="nt">--rm</span> <span class="se">\</span>
  <span class="nt">--name</span> <span class="s2">"archon-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">--user</span> <span class="s2">"</span><span class="si">$(</span><span class="nb">id</span> <span class="nt">-u</span><span class="si">)</span><span class="s2">:</span><span class="si">$(</span><span class="nb">id</span> <span class="nt">-g</span><span class="si">)</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/workspace:/home/bun/.archon/workspaces"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/archon/data:/home/bun/.archon"</span> <span class="se">\</span>
  <span class="nt">-p</span> 3090:3090 <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">OPENROUTER_API_KEY</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">OPENROUTER_API_KEY</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">DEFAULT_AI_ASSISTANT</span><span class="o">=</span>pi <span class="se">\</span>
  ghcr.io/coleam00/archon:latest workflow list
</code></pre></div></div>

<h3 id="mastra">Mastra</h3>

<p><a href="https://mastra.ai">Mastra</a> is a TypeScript-based AI agent framework that runs as a Docker Compose service exposing a REST API and a Studio UI on port 4111. It uses LibSQL for persistent conversation history, meaning that agent memory survives container restarts. Mastra occupies the programmable end of the spectrum: rather than autonomous self-direction, it provides a typed API for defining agents, tools, workflows, and memory retrievers in TypeScript.</p>

<p>The Mastra image is a multi-stage build. Critically, it handles the <code class="language-plaintext highlighter-rouge">instrumentation.mjs</code> file conditionally, since its presence varies across Mastra version upgrades.</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># mastra/Dockerfile (multi-stage)</span>
<span class="k">FROM</span><span class="w"> </span><span class="s">node:22-alpine</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">builder</span>
<span class="k">WORKDIR</span><span class="s"> /app</span>
<span class="k">RUN </span>apk add <span class="nt">--no-cache</span> gcompat
<span class="k">COPY</span><span class="s"> package*.json ./</span>
<span class="k">RUN </span>npm <span class="nb">install</span>
<span class="k">COPY</span><span class="s"> tsconfig*.json ./</span>
<span class="k">COPY</span><span class="s"> src ./src</span>
<span class="k">RUN </span>npx mastra build
 
<span class="k">FROM</span><span class="w"> </span><span class="s">node:22-alpine</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">runner</span>
<span class="k">WORKDIR</span><span class="s"> /app</span>
<span class="k">RUN </span>apk add <span class="nt">--no-cache</span> gcompat wget
<span class="k">RUN </span>addgroup <span class="nt">-g</span> 1001 <span class="nt">-S</span> nodejs <span class="o">&amp;&amp;</span> adduser <span class="nt">-S</span> mastra <span class="nt">-u</span> 1001
<span class="k">COPY</span><span class="s"> --from=builder --chown=mastra:nodejs /app/.mastra/output ./.mastra/output</span>
<span class="k">COPY</span><span class="s"> --from=builder --chown=mastra:nodejs /app/node_modules ./node_modules</span>
<span class="k">COPY</span><span class="s"> --from=builder --chown=mastra:nodejs /app/package.json ./package.json</span>
<span class="k">RUN </span><span class="nb">mkdir</span> <span class="nt">-p</span> /app/data <span class="o">&amp;&amp;</span> <span class="nb">chown </span>mastra:nodejs /app/data
<span class="k">USER</span><span class="s"> mastra</span>
<span class="k">ENV</span><span class="s"> PORT=4111</span>
<span class="k">ENV</span><span class="s"> NODE_ENV=production</span>
<span class="k">ENV</span><span class="s"> DATABASE_URL="file:/app/data/mastra.db"</span>
<span class="k">EXPOSE</span><span class="s"> 4111</span>
<span class="k">HEALTHCHECK</span><span class="s"> --interval=30s --timeout=10s --start-period=20s --retries=3 \</span>
    CMD wget -qO- http://localhost:4111/api &gt; /dev/null || exit 1
<span class="c"># Conditional instrumentation: works across Mastra versions</span>
<span class="k">CMD</span><span class="s"> ["sh", "-c", "if [ -f .mastra/output/instrumentation.mjs ]; then \</span>
  node --import=./.mastra/output/instrumentation.mjs .mastra/output/index.mjs; \
  else node .mastra/output/index.mjs; fi"]
</code></pre></div></div>

<p>The agent definition is deliberately minimal:</p>

<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// src/mastra/agents/assistant.ts</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">Agent</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@mastra/core/agent</span><span class="dl">"</span><span class="p">;</span>
 
<span class="k">export</span> <span class="kd">const</span> <span class="nx">assistant</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Agent</span><span class="p">({</span>
  <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">assistant</span><span class="dl">"</span><span class="p">,</span>
  <span class="na">instructions</span><span class="p">:</span> <span class="dl">"</span><span class="s2">You are a helpful, concise, and accurate assistant.</span><span class="dl">"</span><span class="p">,</span>
  <span class="na">model</span><span class="p">:</span> <span class="dl">"</span><span class="s2">openrouter/meta-llama/llama-3.1-8b-instruct:free</span><span class="dl">"</span><span class="p">,</span>
  <span class="c1">// Other free-tier options:</span>
  <span class="c1">// openrouter/mistralai/mistral-7b-instruct:free</span>
  <span class="c1">// openrouter/google/gemma-3-12b-it:free</span>
<span class="p">});</span>
</code></pre></div></div>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># mastra/docker-compose.yml</span>
<span class="na">services</span><span class="pi">:</span>
  <span class="na">mastra</span><span class="pi">:</span>
    <span class="na">build</span><span class="pi">:</span>
      <span class="na">context</span><span class="pi">:</span> <span class="s">.</span>
      <span class="na">dockerfile</span><span class="pi">:</span> <span class="s">Dockerfile</span>
    <span class="na">container_name</span><span class="pi">:</span> <span class="s">mastra-${USER}</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">4111:4111"</span>
    <span class="na">environment</span><span class="pi">:</span>
      <span class="na">OPENROUTER_API_KEY</span><span class="pi">:</span> <span class="s">${OPENROUTER_API_KEY}</span>
      <span class="na">NODE_ENV</span><span class="pi">:</span> <span class="s">production</span>
      <span class="na">DATABASE_URL</span><span class="pi">:</span> <span class="s2">"</span><span class="s">file:/app/data/mastra.db"</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">/home/${USER}/agents/mastra/data:/app/data</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>
    <span class="na">healthcheck</span><span class="pi">:</span>
      <span class="na">test</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">CMD"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">wget"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">-qO-"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">http://localhost:4111/api"</span><span class="pi">]</span>
      <span class="na">interval</span><span class="pi">:</span> <span class="s">30s</span>
      <span class="na">timeout</span><span class="pi">:</span> <span class="s">10s</span>
      <span class="na">retries</span><span class="pi">:</span> <span class="m">3</span>
      <span class="na">start_period</span><span class="pi">:</span> <span class="s">20s</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># mastra/build.sh — self-contained; creates src files if absent, prompts for key</span>
<span class="nb">cd</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/mastra"</span>
docker compose up <span class="nt">--build</span> <span class="nt">-d</span>
 
<span class="c"># mastra/run.sh — start after reboot without rebuild</span>
<span class="nb">cd</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/mastra"</span> <span class="o">&amp;&amp;</span> docker compose up <span class="nt">-d</span>
 
<span class="c"># mastra/attach.sh — tail live logs</span>
docker logs <span class="nt">--follow</span> <span class="nt">--timestamps</span> <span class="s2">"mastra-</span><span class="k">${</span><span class="nv">USER</span><span class="k">}</span><span class="s2">"</span>
</code></pre></div></div>

<p>The agent server exposes a standard REST endpoint:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-X</span> POST http://localhost:4111/api/agents/assistant/generate <span class="se">\</span>
  <span class="nt">-H</span> <span class="s2">"Content-Type: application/json"</span> <span class="se">\</span>
  <span class="nt">-d</span> <span class="s1">'{"messages": [{"role": "user", "content": "Summarize this document."}]}'</span>
</code></pre></div></div>

<h2 id="open-design-collaborative-canvas-with-embedded-agent">Open Design: Collaborative Canvas with Embedded Agent</h2>

<p><a href="https://github.com/nexu-io/open-design">Open Design</a> is a web-based collaborative design canvas with an embedded pi coding agent, running on port 5173. It is the visual layer of the stack, useful for design work where the agent can read and modify the canvas state directly. The pi identity directory is separate from the main pi tool identity, so Open Design’s agent configuration does not interfere with standalone pi sessions.</p>

<h3 id="open-design-deployment">Open Design Deployment</h3>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># open-design/Dockerfile</span>
<span class="k">FROM</span><span class="s"> node:24-bookworm</span>
 
<span class="k">ARG</span><span class="s"> OPEN_DESIGN_REPO=https://github.com/nexu-io/open-design.git</span>
<span class="k">ARG</span><span class="s"> OPEN_DESIGN_REF=main</span>
 
<span class="k">ENV</span><span class="s"> APP_DIR=/opt/open-design</span>
<span class="k">ENV</span><span class="s"> PNPM_HOME=/root/.local/share/pnpm</span>
<span class="k">ENV</span><span class="s"> PATH=/root/.local/share/pnpm:/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin</span>
<span class="k">ENV</span><span class="s"> PORT=5173</span>
<span class="k">ENV</span><span class="s"> HOST=0.0.0.0</span>
<span class="k">ENV</span><span class="s"> OD_HOST=0.0.0.0</span>
<span class="k">ENV</span><span class="s"> OD_ALLOWED_DEV_ORIGINS=127.0.0.1,localhost</span>
 
<span class="k">RUN </span>apt-get update <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>    git ca-certificates curl bash python3 <span class="se">\
</span>    <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>corepack <span class="nb">enable</span>
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">-g</span> @mariozechner/pi-coding-agent
 
<span class="k">RUN </span>git clone <span class="nt">--branch</span> <span class="s2">"</span><span class="k">${</span><span class="nv">OPEN_DESIGN_REF</span><span class="k">}</span><span class="s2">"</span> <span class="nt">--depth</span> 1 <span class="se">\
</span>    <span class="s2">"</span><span class="k">${</span><span class="nv">OPEN_DESIGN_REPO</span><span class="k">}</span><span class="s2">"</span> <span class="s2">"</span><span class="k">${</span><span class="nv">APP_DIR</span><span class="k">}</span><span class="s2">"</span>
 
<span class="k">WORKDIR</span><span class="s"> ${APP_DIR}</span>
 
<span class="c"># Patch next.config.ts to accept OD_ALLOWED_DEV_ORIGINS from environment</span>
<span class="k">RUN </span>python3 - <span class="o">&lt;&lt;</span> <span class="sh">'</span><span class="no">PY</span><span class="sh">'</span>
<span class="k">from</span><span class="s"> pathlib import Path</span>
p = Path("apps/web/next.config.ts")
s = p.read_text()
old = "allowedDevOrigins: ['127.0.0.1'],"
new = """allowedDevOrigins: (
    process.env.OD_ALLOWED_DEV_ORIGINS
      ? process.env.OD_ALLOWED_DEV_ORIGINS.split(',').map((s) =&gt; s.trim()).filter(Boolean)
      : ['127.0.0.1']
  ),"""
if old not in s:
    raise SystemExit("Could not find allowedDevOrigins line")
p.write_text(s.replace(old, new))
PY
 
<span class="k">RUN </span>corepack pnpm <span class="nt">--version</span> <span class="o">&amp;&amp;</span> pnpm <span class="nb">install</span>
 
<span class="k">EXPOSE</span><span class="s"> 5173</span>
<span class="k">CMD</span><span class="s"> ["pnpm", "tools-dev", "run", "web", "--web-port", "5173"]</span>
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># open-design/build.sh</span>
docker build <span class="nt">-t</span> open-design-pi <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/open-design"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/open-design/data"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/open-design/pi"</span>
 
<span class="c"># First-time pi setup (run once to authenticate)</span>
docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/open-design/pi:/root/.pi"</span> <span class="se">\</span>
  open-design-pi <span class="se">\</span>
  pi
<span class="c"># Inside pi session: /login</span>
 
<span class="c"># open-design/run.sh</span>
<span class="c"># OD_ALLOWED_DEV_ORIGINS must match the IP the browser uses to reach the container</span>
docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--name</span> open-design-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="s2">"OD_ALLOWED_DEV_ORIGINS=YOUR_HOST_IP"</span> <span class="se">\</span>
  <span class="nt">-p</span> 5173:5173 <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/open-design/data:/opt/open-design/.od"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/open-design/pi:/root/.pi"</span> <span class="se">\</span>
  open-design-pi
</code></pre></div></div>

<p>Open the canvas at <code class="language-plaintext highlighter-rouge">http://YOUR_HOST_IP:5173</code>. <code class="language-plaintext highlighter-rouge">OD_ALLOWED_DEV_ORIGINS</code> must match the IP address the browser uses to reach the container. To detect it automatically, substitute <code class="language-plaintext highlighter-rouge">$(hostname -I | awk '{print $1}')</code> for the hardcoded value.</p>

<h2 id="docker-volume-architecture-identity-workspace-skills">Docker Volume Architecture: Identity, Workspace, Skills</h2>

<p>One of the more carefully considered design decisions in this stack is the separation of Docker bind mounts into four independent tiers, which I call identity, workspace, skills, and tool data. This separation means that swapping a user identity, adding a skills package, or destroying an experimental container affects only its own tier; the other three are untouched.</p>

<table>
  <thead>
    <tr>
      <th>Tier</th>
      <th>Host Path Pattern</th>
      <th>Container Mount</th>
      <th>Shared?</th>
      <th>Destroyable?</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Identity</td>
      <td><code class="language-plaintext highlighter-rouge">$HOME/agents/{tool}/home</code></td>
      <td>varies per tool</td>
      <td>No</td>
      <td>Backup first</td>
    </tr>
    <tr>
      <td>Workspace</td>
      <td><code class="language-plaintext highlighter-rouge">$HOME/agents/workspace</code></td>
      <td><code class="language-plaintext highlighter-rouge">/workspace</code></td>
      <td>Yes</td>
      <td>No</td>
    </tr>
    <tr>
      <td>Skills</td>
      <td><code class="language-plaintext highlighter-rouge">$HOME/agents/skills/{name}</code></td>
      <td><code class="language-plaintext highlighter-rouge">/app/skills/{name}</code></td>
      <td>Yes</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>Tool Data</td>
      <td><code class="language-plaintext highlighter-rouge">$HOME/agents/{tool}/data</code></td>
      <td>varies</td>
      <td>No</td>
      <td>Snapshot first</td>
    </tr>
  </tbody>
</table>

<p>The identity hot-swap pattern is simple enough to describe in three commands: stop the container, remove it (volumes are untouched), and rerun with a different <code class="language-plaintext highlighter-rouge">home/</code> path. The workspace and skills mount points are identical in both invocations. This makes it straightforward to work on the same project files under different API key contexts or with different tool configurations.</p>

<p>Permission repair across containers with differing internal UID/GID values is handled by a disposable Alpine container:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--rm</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/some-tool/home:/mnt/target"</span> <span class="se">\</span>
  alpine <span class="se">\</span>
  <span class="nb">chown</span> <span class="nt">-R</span> 1000:1000 /mnt/target
</code></pre></div></div>

<h2 id="container-isolated-tool-invocation">Container-Isolated Tool Invocation</h2>

<p>One of the more practically useful habits I have developed with this stack is running agentic CLI tools inside dedicated Docker containers rather than installing them to my host user environment. The motivation is threefold: environment isolation, workspace scope control, and plugin sandboxing.</p>

<p><strong>Workspace scope control</strong> is where the bind-mount architecture pays its most direct dividend. Rather than giving a tool access to the entire home filesystem, I mount only the specific project directories I want it to operate on:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">ANTHROPIC_API_KEY</span><span class="o">=</span><span class="s2">"</span><span class="k">${</span><span class="nv">ANTHROPIC_API_KEY</span><span class="k">:-</span><span class="nv">YOUR_ANTHROPIC_API_KEY</span><span class="k">}</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/commercial/claude/home:/home/agent"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/projects/project-alpha:/workspace/project-alpha"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/projects/project-beta:/workspace/project-beta"</span> <span class="se">\</span>
  <span class="nt">-w</span> /workspace/project-alpha <span class="se">\</span>
  commercial-ai:latest claude
</code></pre></div></div>

<p>From inside the container, the agent sees exactly two project directories and nothing else. For work involving student data or grant-sensitive materials, this mount-scoping discipline is not optional; it is the architectural enforcement of the data minimization principle.</p>

<p><strong>Plugin sandboxing</strong> makes it practical to evaluate new tools without risk. I can install an untrusted npm package, register a new MCP server, or try an experimental integration inside an ephemeral container with a scratch identity directory, observe its behavior against a scoped workspace mount, and discard the container entirely if I decide against it. The two-stage pattern, scratch evaluation followed by deliberate promotion to the production identity directory, is something the tiered bind-mount architecture makes nearly effortless.</p>

<h2 id="the-extended-ecosystem-containerized-evaluation-of-ai-tools">The Extended Ecosystem: Containerized Evaluation of AI Tools</h2>

<p>The stack described above is not a closed list. One of the structural advantages of the containerized, mount-scoped architecture is that any new AI tool can be evaluated, and subsequently adopted or discarded, without touching host state, leaking credentials, or requiring destructive cleanup. The evaluation pattern is consistent: build a throw-away image that installs the candidate tool and any dependencies it requires; run a container with a scratch identity directory and a scoped workspace mount containing only the project data relevant to the evaluation task; observe behavior against a free or low-cost model routed through LiteLLM; and either promote the configuration to a named identity directory or <code class="language-plaintext highlighter-rouge">docker rmi</code> the image and move on. What follows is a survey of tools I use or actively monitor, each of which fits neatly into this workflow.</p>

<h3 id="fabric">Fabric</h3>

<p><a href="https://github.com/danielmiessler/fabric">Fabric</a> (Go) is an AI augmentation framework built around the concept of patterns, which are markdown-formatted system prompt templates stored in <code class="language-plaintext highlighter-rouge">~/.config/fabric/patterns/</code>. Rather than a conversational agent, Fabric is a UNIX-pipeline-oriented tool: it reads from stdin or a file, applies a named pattern as the system prompt, and writes the model’s response to stdout. This makes it composable with every other shell tool by design. Because Fabric speaks to any OpenAI-compatible endpoint, it integrates with the LiteLLM gateway through a single environment variable, <code class="language-plaintext highlighter-rouge">OPENAI_BASE_URL=http://localhost:4000/v1</code>, and is well-suited to free-model operation for batch summarization, extraction, and classification tasks. The container footprint is minimal: the Go binary, the patterns directory bind-mounted from <code class="language-plaintext highlighter-rouge">~/.config/fabric/patterns</code>, and a workspace volume.</p>

<h3 id="anythingllm">AnythingLLM</h3>

<p><a href="https://github.com/Mintplex-Labs/anything-llm">AnythingLLM</a> is a full-stack application that provides document ingestion, vector storage, and retrieval-augmented generation through a browser-based interface, all self-hostable and all pointing at whatever OpenAI-compatible endpoint you configure. Unlike Open WebUI, which is primarily a chat interface to models you have already pulled, AnythingLLM is organized around workspaces that each maintain their own document corpus and retrieval context. This makes it the most natural comparison point for evaluating RAG pipeline quality, including chunking strategies and retrieval configurations, against the same local models without committing to a production indexing infrastructure. It runs as a single Docker container and connects to LiteLLM without modification.</p>

<h3 id="autogpt">AutoGPT</h3>

<p><a href="https://github.com/Significant-Gravitas/AutoGPT">AutoGPT</a> is one of the original autonomous agent frameworks, now significantly matured into a platform with a visual workflow builder and a marketplace of pre-built agents. Its architectural evolution mirrors the broader field: the early single-agent loop has been replaced by a multi-agent orchestration model where specialized agents collaborate on subtasks. AutoGPT’s containerized deployment is well-documented, and its use of a PostgreSQL backend for persistent agent state means that evaluation sessions survive container restarts. I evaluate AutoGPT primarily for its workflow builder, which provides a visual alternative to writing agent orchestration code by hand, and because its agent marketplace offers a useful inventory of community-developed task patterns.</p>

<h3 id="cli-anything">CLI-Anything</h3>

<p>CLI-Anything is a natural-language shell interface that translates plain-English task descriptions into shell command sequences, explains the commands it generates before executing them, and allows interactive refinement. The evaluation pattern is particularly straightforward: mount a scratch workspace, describe a file manipulation or build task in natural language, and assess the fidelity of the generated commands against the intent. Because CLI-Anything operates at the shell command level rather than the source code level, it is usable with substantially smaller models than coding-focused tools, which makes it a good candidate for free-tier or small local model evaluation.</p>

<h3 id="google-antigravity">Google Antigravity</h3>

<p>Google Antigravity is an experimental framework for rapid agent prototyping that provides a higher-level abstraction layer over the Google Agent Development Kit described above. It is oriented toward fast iteration on multi-agent system designs, with an emphasis on making architectural experiments cheap to run and discard, which maps naturally onto the containerized evaluation philosophy of this stack. I use it alongside the Google Agents CLI container, sharing the same workspace volume but maintaining a separate identity directory so that Antigravity’s experimental state does not contaminate the production ADK configuration.</p>

<h3 id="t3-code">T3 Code</h3>

<p><a href="https://t3.chat">T3 Code</a> is a code generation tool that applies Theo Browne’s T3 stack architectural preferences (TypeScript, tRPC, Tailwind, Prisma) to AI-assisted scaffolding. Its opinionated output is both a strength and a constraint: the generated code is immediately coherent within the T3 ecosystem but requires deliberate adaptation outside it. I evaluate it in a container against a workspace containing a greenfield TypeScript project, routed through LiteLLM, and find it most useful as a rapid scaffolding baseline rather than a continuous coding companion.</p>

<h3 id="paperclip">Paperclip</h3>

<p><a href="https://github.com/paperclip-ai/paperclip">Paperclip</a> is a document-aware coding assistant that maintains a live index of a project’s files and surfaces relevant context into the model’s prompt automatically as the conversation evolves. The document-indexing architecture distinguishes it from tools that rely on the user to provide context explicitly: Paperclip’s retrieval layer operates continuously in the background, which makes it well-suited to exploration of unfamiliar codebases. Containerized evaluation against a read-only mount of a target codebase is a clean pattern: the index lives in the scratch identity directory, the codebase is mounted read-only, and the entire evaluation state is discardable.</p>

<h3 id="open-source-cowork-alternatives-in-the-ecosystem">Open-Source Cowork Alternatives in the Ecosystem</h3>

<p>The tools already described in dedicated sections below, including OpenWork, OpenCoworkAI, and Multica, represent the most directly Cowork-comparable options in the ecosystem, but several adjacent tools occupy related positions.</p>

<p><a href="https://accomplish.ai/">Accomplish</a> takes a “BYO-AI” stance, functioning as the orchestration layer (hands and eyes) while allowing model selection, supporting OpenAI, Anthropic, Google, and Ollama backends without lock-in.</p>

<p><a href="https://github.com/kuse-ai/kuse_cowork">Kuse Cowork</a> implements the agent runtime in Rust with Docker-based sandboxing built into the design, which makes its security boundary properties particularly legible from the perspective of this stack’s threat model.</p>

<h3 id="the-containerization-argument">The Containerization Argument</h3>

<p>The tooling landscape I have described, spanning fabric, AnythingLLM, AutoGPT, CLI-Anything, Antigravity, T3 Code, Paperclip, and the Cowork-adjacent frameworks, shares a property that makes the containerized evaluation pattern especially productive: nearly all of them support connection to a popular API-compatible backend (OpenAI, Anthropic, or a generic OpenAI-compatible endpoint), and nearly all of them can be pointed at free-tier models on OpenRouter or at local Ollama models with no modification beyond a base URL. This means that a feasibility evaluation of any tool in the list, assessing whether its interaction model, output quality, and integration characteristics are worth the effort of a production deployment, can be conducted at near-zero cost: no paid API usage, no host-level installation, no persistent state that requires cleanup. The directory structure is created by <code class="language-plaintext highlighter-rouge">build.sh</code>, the container runs against a scoped workspace mount, the evaluation task executes against a free model, and the result determines whether to invest in a full identity directory configuration or to <code class="language-plaintext highlighter-rouge">docker rmi</code> and move on. This evaluation-first discipline is, I would argue, the appropriate epistemological stance toward a tool ecosystem that is evolving faster than any individual practitioner can track.</p>

<h2 id="open-source-cowork-alternatives">Open-Source Cowork Alternatives</h2>

<p>Anthropic’s Claude Cowork launch in January 2026 triggered a vigorous open-source response. I track several of the resulting projects.</p>

<p><a href="https://github.com/different-ai/openwork">OpenWork</a> is the most actively developed, functioning as a control surface for agentic workflows with hot-reloadable skills, session management, and SSE event stream subscriptions. It is ejectable to OpenCode, which provides a meaningful portability guarantee.</p>

<h3 id="openwork-deployment">OpenWork Deployment</h3>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># openwork/Dockerfile</span>
<span class="k">FROM</span><span class="s"> node:22-bookworm-slim</span>
 
<span class="k">ARG</span><span class="s"> OPENWORK_ORCHESTRATOR_VERSION=latest</span>
 
<span class="k">RUN </span>apt-get update <span class="se">\
</span> <span class="o">&amp;&amp;</span> apt-get <span class="nb">install</span> <span class="nt">-y</span> <span class="nt">--no-install-recommends</span> <span class="se">\
</span>    ca-certificates curl git <span class="nb">tar </span>unzip <span class="se">\
</span> <span class="o">&amp;&amp;</span> <span class="nb">rm</span> <span class="nt">-rf</span> /var/lib/apt/lists/<span class="k">*</span>
 
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">-g</span> <span class="s2">"openwork-orchestrator@</span><span class="k">${</span><span class="nv">OPENWORK_ORCHESTRATOR_VERSION</span><span class="k">}</span><span class="s2">"</span>
 
<span class="k">ENV</span><span class="s"> OPENWORK_DATA_DIR=/data/openwork-orchestrator</span>
<span class="k">ENV</span><span class="s"> OPENWORK_SIDECAR_DIR=/data/sidecars</span>
<span class="k">ENV</span><span class="s"> OPENWORK_WORKSPACE=/workspace</span>
 
<span class="k">EXPOSE</span><span class="s"> 8787</span>
<span class="k">VOLUME</span><span class="s"> ["/workspace", "/data"]</span>
 
<span class="k">CMD</span><span class="s"> ["openwork", "serve", "--workspace", "/workspace", "--remote-access", \</span>
     "--openwork-port", "8787", "--opencode-host", "127.0.0.1", \
     "--opencode-port", "4096", "--connect-host", "127.0.0.1", \
     "--cors", "*", "--approval", "manual", "--no-opencode-router"]
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># openwork/build.sh</span>
docker build <span class="nt">-t</span> openwork:local <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/openwork"</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/openwork/workspace"</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/openwork/data"</span>
 
<span class="c"># openwork/run.sh</span>
docker run <span class="nt">-it</span> <span class="se">\</span>
  <span class="nt">--restart</span> no <span class="se">\</span>
  <span class="nt">--add-host</span><span class="o">=</span>host.docker.internal:host-gateway <span class="se">\</span>
  <span class="nt">-p</span> 8787:8787 <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/openwork/workspace:/workspace"</span> <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$HOME</span><span class="s2">/agents/openwork/data:/data"</span> <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">OPENWORK_TOKEN</span><span class="o">=</span>dev-token <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">OPENWORK_HOST_TOKEN</span><span class="o">=</span>dev-host-token <span class="se">\</span>
  <span class="nt">--name</span> openwork-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span> <span class="se">\</span>
  openwork:local
 
<span class="c"># openwork/attach.sh</span>
docker start <span class="nt">-ai</span> openwork-<span class="k">${</span><span class="nv">USER</span><span class="k">}</span>
</code></pre></div></div>

<p><a href="https://accomplish.ai/">Accomplish</a> takes a “BYO-AI” stance, functioning as the orchestration layer (hands and eyes) while allowing model selection, supporting OpenAI, Anthropic, Google, and Ollama backends without lock-in. <a href="https://github.com/kuse-ai/kuse_cowork">Kuse Cowork</a> implements the agent runtime in Rust with Docker-based sandboxing. <a href="https://github.com/opencowork-ai/opencowork">OpenCoworkAI</a> explicitly commits to VM/bwrap isolation and checkpoint-rollback capability.</p>

<p><a href="https://github.com/multica-ai/multica">Multica</a> occupies a different conceptual position as a managed agents platform rather than a desktop agent. It assigns issues to AI agents as you would assign them to human teammates, and it implements skill compounding: when an agent completes a task successfully, the solution is saved as a reusable skill that future tasks can leverage. This maps interestingly onto organizational learning theory, though a thoughtful critique in the project’s issue tracker notes that the human-management metaphor may be insufficient for genuinely autonomous AI orchestration at scale. I find this a productive tension worth thinking about seriously.</p>

<h2 id="mcp-servers-extending-the-stack-with-custom-tools">MCP Servers: Extending the Stack with Custom Tools</h2>

<p>The Model Context Protocol (MCP), introduced by Anthropic in late 2024, defines how AI assistants communicate with external tools through four primitive types: tools (callable functions), resources (readable data streams), prompts (reusable templates), and sampling (delegated inference requests). Running MCP servers in Docker and connecting them to the local stack over a shared external network is straightforward.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network create mcp-shared
</code></pre></div></div>

<p>With this network in place, any container that declares <code class="language-plaintext highlighter-rouge">mcp-shared</code> as an external network can reach an MCP server at its container DNS name, such as <code class="language-plaintext highlighter-rouge">http://mcp-bibliography:8000/mcp</code>, without host port exposure. For backends that use OpenAI function-calling format rather than MCP’s JSON-RPC protocol, a thin Flask adapter service translates between the two on startup:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">mcp_post</span><span class="p">(</span><span class="n">method</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">params</span><span class="p">:</span> <span class="nb">dict</span><span class="p">,</span> <span class="n">req_id</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">dict</span><span class="p">:</span>
    <span class="n">payload</span> <span class="o">=</span> <span class="n">json</span><span class="p">.</span><span class="n">dumps</span><span class="p">({</span>
        <span class="s">"jsonrpc"</span><span class="p">:</span> <span class="s">"2.0"</span><span class="p">,</span> <span class="s">"id"</span><span class="p">:</span> <span class="n">req_id</span><span class="p">,</span>
        <span class="s">"method"</span><span class="p">:</span> <span class="n">method</span><span class="p">,</span> <span class="s">"params"</span><span class="p">:</span> <span class="n">params</span>
    <span class="p">}).</span><span class="n">encode</span><span class="p">()</span>
    <span class="n">req</span> <span class="o">=</span> <span class="n">urllib</span><span class="p">.</span><span class="n">request</span><span class="p">.</span><span class="n">Request</span><span class="p">(</span>
        <span class="n">MCP_URL</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">payload</span><span class="p">,</span>
        <span class="n">headers</span><span class="o">=</span><span class="p">{</span><span class="s">"Content-Type"</span><span class="p">:</span> <span class="s">"application/json"</span><span class="p">},</span> <span class="n">method</span><span class="o">=</span><span class="s">"POST"</span>
    <span class="p">)</span>
    <span class="k">with</span> <span class="n">urllib</span><span class="p">.</span><span class="n">request</span><span class="p">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> <span class="k">as</span> <span class="n">r</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">r</span><span class="p">.</span><span class="n">read</span><span class="p">())</span>
</code></pre></div></div>

<h2 id="openrouter-a-cloud-model-interface">OpenRouter: A Cloud Model Interface</h2>

<p><a href="https://openrouter.ai">OpenRouter</a> serves as the cloud model interface for tasks I route away from local inference. It exposes multiple model providers through an OpenAI-compatible API surface, so the same client code that talks to the local LiteLLM gateway can talk to OpenRouter without modification. Model identifiers follow a provider-qualified format:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>anthropic/claude-3-opus
openai/gpt-4o
mistralai/mixtral-8x7b
meta-llama/llama-3-70b-instruct
</code></pre></div></div>

<p>The free-tier model list changes, but as of early 2026 includes Gemini 2.5 Pro, DeepSeek Chat v3.5, and LLaMA 4 Maverick. I use OpenRouter as a fallback in the Mastra agent server, as the primary cloud provider for pi, and as the escalation path from GNHF when a batch task exceeds local model capability. All API key management is handled through environment variables; no key is ever written into a container image.</p>

<h2 id="reproducibility-the-one-shot-deploy-script">Reproducibility: The One-Shot Deploy Script</h2>

<p>The entire stack, including all Dockerfiles, helper scripts, LiteLLM configuration, Mastra project files, and the directory tree, is generated by a single bash script called <code class="language-plaintext highlighter-rouge">deploy-agents.sh</code>. Running this script on a new machine, after providing the necessary API keys, produces a fully functional environment covering all the services described above with no manual steps (except placing a Dockerfile in <code class="language-plaintext highlighter-rouge">gnhf/</code> for the task-bounded harness).</p>

<p>The script follows a fixed sequence: create the directory tree; write Dockerfiles for each custom image; write LiteLLM, LocalAI, and CCR configs; write Mastra project files; write GNHF task modules; write Agent Zero and Archon startup scripts; build custom images; clone and build OpenClaude; pull pre-built images; and finally start all daemon containers. This design means the script itself is the documentation, and any configuration drift between machines is detected by diffing the generated files against a known-good reference.</p>

<p>Publishing a custom Docker image to GitHub Container Registry follows the same minimal GitHub Actions pattern:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">docker/login-action@v3</span>
  <span class="na">with</span><span class="pi">:</span>
    <span class="na">registry</span><span class="pi">:</span> <span class="s">ghcr.io</span>
    <span class="na">username</span><span class="pi">:</span> <span class="s">$</span>
    <span class="na">password</span><span class="pi">:</span> <span class="s">$</span>
 
<span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">docker/build-push-action@v6</span>
  <span class="na">with</span><span class="pi">:</span>
    <span class="na">context</span><span class="pi">:</span> <span class="s">.</span>
    <span class="na">push</span><span class="pi">:</span> <span class="no">true</span>
    <span class="na">tags</span><span class="pi">:</span> <span class="s">$</span>
</code></pre></div></div>

<p>After the workflow runs, making the resulting package public in the GitHub package settings allows anyone to <code class="language-plaintext highlighter-rouge">docker pull ghcr.io/yourusername/yourrepo:main</code> without further configuration.</p>

<h2 id="model-selection-notes">Model Selection Notes</h2>

<p>A few observations on local model selection from operational experience. For the think-heavy routing slot I use <code class="language-plaintext highlighter-rouge">gemma4:e2b</code>; for lightweight background tasks such as file summarization and classification I use <code class="language-plaintext highlighter-rouge">qwen2.5:1.5b</code>; for tool-calling workflows in Open WebUI and via the Hermes agent identity I use <code class="language-plaintext highlighter-rouge">hermes3:8b</code>; for general interactive sessions I use <code class="language-plaintext highlighter-rouge">llama3</code>. The selection criteria are principally RAM footprint and whether the model’s function-calling format is well-supported by the tool in question.</p>

<hr />]]></content><author><name>Bill Mongan</name><email>billmongan+website@gmail.com</email></author><category term="ai" /><category term="technical" /><category term="docker" /><category term="llm" /><category term="agents" /><summary type="html"><![CDATA[For the past several years I have been thinking carefully about what it means to run AI infrastructure that I actually own, control, and understand from the ground up. The rapid proliferation of frontier model APIs, agentic coding tools, and open-weight model releases in 2025-2026 finally made this tractable at a price and complexity point that a single person could manage. This post documents the architecture I settled on: a self-hosted, Docker-based stack running on a mini PC, unified by a single OpenAI-compatible model gateway, and surfaced through a collection of local inference servers, agentic CLI tools, autonomous agent frameworks, open-source Cowork alternatives, and a task-bounded command harness built around structured queues. My goals were privacy, sovereignty, reproducibility, and the ability to swap components without rebuilding everything from scratch.]]></summary></entry></feed>