Skip to content

An open-source, faster Devin alternative

TypeScript

computer/host: model protocol 5, every runner bound at the model proxy (097 5a) (#1049)

opencomputer-app[bot]046b5332b7c0
diff --git a/.github/workflows/computer.yml b/.github/workflows/computer.yml
index 3a32bc3e..eb736049 100644
--- a/.github/workflows/computer.yml
+++ b/.github/workflows/computer.yml
@@ -103,7 +103,12 @@ jobs:
- run: go test -run '^$' -bench ProxyOverhead -benchtime 5000x ./...
env:
MODELPROXY_OVERHEAD_GATE: 1
- - run: CGO_ENABLED=0 go build -trimpath -o "$RUNNER_TEMP/oc-modelproxy" .
+ - run: CGO_ENABLED=0 go build -trimpath -ldflags "-X main.version=$VERSION" -o "$RUNNER_TEMP/oc-modelproxy" .
+ env:
+ VERSION: ${{ github.sha }}
+ # The shipped profiles load as a computer's start would load them (deploy/vm/modelproxy.sh checks the same).
+ - run: |
+ "$RUNNER_TEMP/oc-modelproxy" -check -profiles profiles
secrets:
name: Secret scan
diff --git a/computer/README.md b/computer/README.md
index 4489548c..48989c90 100644
--- a/computer/README.md
+++ b/computer/README.md
@@ -258,6 +258,9 @@ Start any message with `+smart` or `+fast` (or `+default`) to switch the
thread's model and send the rest, e.g. `@Computer +smart redesign the router`
or `@Computer +fast ch bump the deps`. People pick a tier, not a model: the tiers
map to ids in `src/tiers.ts` (smart → Fable, fast → Sonnet, default → `MODEL`).
+On a computer, a new thread's first message may start with `+codex` to run the
+thread on Codex instead of Claude Code (or `+claude`, the default); with no
+OpenAI credential configured the bot says so and starts nothing.
A new session's first reply is a small header with the thread's id
(the fork directory and `sp/<id>` branch suffix, in a copyable form) and a
pointer to `!help`; `!status` repeats the id.
@@ -343,7 +346,27 @@ In production the gateway is the backend, managed-agents
run on Azure VMs provisioned by `deploy/vm/provision.sh` (Ubuntu 24.04; EC2
also works), one per organization, sized to its plan. Runners are `systemd --user` units, and the runner user cannot
reach the cloud metadata server. Hosts take new code as a release bundle
-(`deploy/bundle.sh`) and update themselves (`deploy/vm/self-update.sh`).
+(`deploy/bundle.sh <out.bundle>`: the committed `computer/` tree, with
+oc-modelproxy built from it) and update themselves (`deploy/vm/self-update.sh`).
+
+No model credential is in a session's environment, files or logs (work 097).
+Every model request goes through oc-modelproxy (`modelproxy/`), which
+`deploy/vm/modelproxy.sh` installs on each provision from the release: the
+binary as `/usr/local/libexec/oc-modelproxy`, the shipped profiles into
+`/etc/oc-modelproxy/profiles.d/`, and its socket-activated units. A session's
+model client holds only a placeholder; the host binds each runner to its
+session's profile and credential, which the gateway sends as `models`. The
+self-hosted gateway takes them from `MODEL_PROFILE` + `MODEL_TOKEN` (any
+profile in `profiles.d`), else `CLAUDE_CODE_OAUTH_TOKEN` (`claude-oauth`),
+else `ANTHROPIC_API_KEY` (`anthropic-key`), and `OPENAI_API_KEY` for `+codex`
+threads (`openai-key`). A host whose runners are not systemd units (a laptop)
+uses the proxy with `-identity=single`, one session at a time:
+
+```sh
+cd modelproxy && go build -o /tmp/mp/oc-modelproxy . && /tmp/mp/oc-modelproxy -identity=single -profiles ./profiles \
+ -api-socket /tmp/mp/api.sock -control-socket /tmp/mp/control.sock -bindings-file ""
+# the host: SP_MODEL_PROXY=/tmp/mp/control.sock SP_MODEL_SOCKET=/tmp/mp/api.sock
+```
The Node gateway in `src/gateway/` is the self-hosted alternative and what the
laptop and the e2e checks use; the `Dockerfile` packages it as a container.
@@ -398,7 +421,7 @@ credentials are written there for you.
| `MODEL` | `claude-opus-5-5` | the `default` tier; per thread: `+smart`/`+fast`, `!model <tier|id>` |
| `STREAMING` | on | `off` forces the `chat.update` renderer |
| `FLUSH_MS` | `600` | minimum interval between timed native stream flushes; the first update after an idle gap flushes immediately |
-| `SP_PROMPT_CACHE_TTL` | `1h` on Anthropic's API; Claude Code's default (`5m` on a key) through `anthropicBaseUrl` | Claude Code's prompt cache TTL, main conversation and subagents (`5m` or `1h`; sets `CLAUDE_CODE_PROMPT_CACHE_TTL` and `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`); also passed from a host to its runners. Through an Anthropic-compatible endpoint (an organization's OpenRouter key) OpenRouter documents `cache_control.ttl: "1h"` on its Messages API, but it is untested with Claude Code (which also sends the `extended-cache-ttl-2025-04-11` beta), so it is opt-in there |
+| `SP_PROMPT_CACHE_TTL` | the model profile's Claude Code `promptCacheTtl` (`1h` on the shipped Anthropic profiles), else Claude Code's default | Claude Code's prompt cache TTL, main conversation and subagents (`5m` or `1h`; sets `CLAUDE_CODE_PROMPT_CACHE_TTL` and `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`); also passed from a host to its runners, and over any profile's. Through an Anthropic-compatible endpoint (an organization's OpenRouter key) OpenRouter documents `cache_control.ttl: "1h"` on its Messages API, but it is untested with Claude Code (which also sends the `extended-cache-ttl-2025-04-11` beta), so its profile does not ask for it |
| `SP_PROMPT_GUARD` | on | `off` stops withholding copies of Calvin's own prompt from what it posts (`runner/prompt-guard.ts`), for a deployment that works on Calvin itself; also passed from a host to its runners |
| `SP_COMPACT_AT` | `120000` | after a turn whose last request carried more than this many tokens (or after 40 min idle above 60k), the conversation is compacted between turns in a fork that is swapped in only if no message arrived meanwhile (`runner/harness/claude/shadow.ts`, work 068 1c); `0` turns it off. Also passed from a host to its runners |
| `SP_CONTEXT_WINDOW` | `183000` | Claude Code's own auto-compact window in tokens, the backstop for a single turn that grows past the fork compaction (sets `CLAUDE_CODE_AUTO_COMPACT_WINDOW`; `0` leaves Claude Code's default, the model's window, 1M for Opus here). Claude Code compacts inside the turn, which waits, once a request would carry about the window minus 33k (150k at the default; the window is floored at 100k). Also passed from a host to its runners |
@@ -420,9 +443,9 @@ environment, which any session can change.
| `SP_FORK_RETENTION_DAYS` | `14` | idle forks with nothing unpushed are removed after this |
| `SP_ARTIFACTS_IDLE_HOURS` | `24` | forks idle this long (no live runner) lose their git-ignored build and dependency directories (`node_modules`, Rust `target`, `.venv`, `.next`, caches; `src/workspaces/idle.ts`); an install or build restores them |
| `SP_POOL_SIZE` | `2` | spare runners a host keeps with Claude Code parked, so a new session's first message skips the runner's launch and Claude Code's start (`host/pool.ts`, work 069). A spare is claimed into the session's fork; resumed sessions, and hosts without a prepared workspace for the owner, start cold. `0` turns the pool off |
-| `SP_MODEL_PROXY` | unset (every session on the organization's credentials) | oc-modelproxy's control socket (`/run/oc-modelproxy/control.sock`): sessions may run on their owner's Claude subscription (work 077); set only on a host running as `sp-host` |
+| `SP_MODEL_PROXY` | unset (the model proxy is down: no session starts, logged as an error) | oc-modelproxy's control socket (`/run/oc-modelproxy/control.sock`); the host binds every runner there to its session's model profile (work 097, `host/model-access.ts`). Required |
| `SP_RUNNER_USER` | unset (runners run as the host's user) | start runners as this user through `sudo -n -u` (work 077, `host/runner-user.ts`), for a host running as `sp-host` |
-| `SP_MODEL_SOCKET` | `/run/oc-modelproxy/api.sock` | the proxy's socket a subscription session's Claude Code uses (`ANTHROPIC_UNIX_SOCKET`); passed to runners |
+| `SP_MODEL_SOCKET` | `/run/oc-modelproxy/api.sock` | the proxy's API socket, which runners' model clients connect to; sent to runners in their credentials' `model.endpoint` |
| `SP_CODEX_BIN` | `/usr/local/lib/codex/bin/codex` | the pinned Codex CLI a `harness: 'codex'` session runs as `codex app-server` (work 082); passed to runners |
| `SP_CODEX_PEER_CHECK` | on | `off` lets any local process use a Codex session's model loopback; only where runners are not systemd units (a laptop). On, a connection is forwarded only when a process in the runner's own cgroup holds it, and refused if the cgroup cannot be read. Read from the host's own environment only: runners always get `on` unless the host runs with `off` |
@@ -445,7 +468,7 @@ environment, which any session can change.
| `SP_VERSION` | `dev` | the release's commit, in `ready.server.version` (the unit reads it from `.sp-version.env`) |
| `SP_REGION` | unset (`null`) | `ready.server.region` |
-Gateway variables are documented at the top of `src/gateway/main.ts`.
+Gateway variables, the model credentials among them, are documented at the top of `src/gateway/main.ts`.
## Development
@@ -462,7 +485,7 @@ of them need a real Slack workspace.
|---|---|
| `npx tsx src/dev/fake-run.ts "<prompt>" ["<steer sent 8s later>"]` | A real agent session against a fake Slack client. Prints every Slack API call with a timestamp and approves prompts automatically. The fast loop for event mapping, batching and steering. |
| `npx tsx src/dev/e2e-check.ts [--keep]` | The whole split deployment on one machine, with fake Slack and GitHub APIs served by the check itself: `/setup`, mention → fork → runner → turn, thread replies, mid-turn messages, a permission button, host and gateway restarts under a live runner, GitHub tokens through the credential helper and `gh` shim, a push webhook. Prints the latency rows it can measure. Scratch space is `/tmp/spe2e`. |
-| `npx tsx src/dev/host-check.ts [--claude]` | The host agent against an in-process fake gateway: spawn, forwarding, token relay, restart with rediscovery, idle exit. With a fake telemetry collector (work 054): host events per trace, the `new`/`warm`/`resume` path, spooling through a collector outage and a host restart, gap-free batch numbers, and `turn.abandoned` for a runner killed mid-turn, before and after a host restart. |
+| `npx tsx src/dev/host-check.ts [--claude]` | The host agent against an in-process fake gateway, with oc-modelproxy built from `modelproxy/` (needs Go and openssl; Linux) and run with `-identity=single`: spawn, forwarding, token relay, restart with rediscovery, idle exit. `--claude` makes the first turn real, on `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` as the gateway routes them. With a fake telemetry collector (work 054): host events per trace, the `new`/`warm`/`resume` path, spooling through a collector outage and a host restart, gap-free batch numbers, and `turn.abandoned` for a runner killed mid-turn (its request held by a profile whose upstream never answers), before and after a host restart. |
| `npx tsx src/dev/workspaces-check.ts [--real]` | Clones, forks, housekeeping and git auth against local bare repositories. |
| `npx tsx src/dev/gateway-check.ts`, `setup-check.ts` | Gateway routing and `/setup`. |
| `npx tsx src/dev/links-check.ts` | Linked threads against a fake workspace: public, private, DM, guest and Slack Connect cases, other workspaces, caps, and injected instructions in linked text. |
diff --git a/computer/deploy/bundle.sh b/computer/deploy/bundle.sh
index ae495d42..926c3193 100755
--- a/computer/deploy/bundle.sh
+++ b/computer/deploy/bundle.sh
@@ -1,36 +1,39 @@
#!/usr/bin/env bash
-# The release bundle: HEAD of this checkout as a git bundle whose only ref is
-# main, with the oc-modelproxy binary CI built committed on top of HEAD as
-# modelproxy/oc-modelproxy (work 077). Computers never compile the proxy: they
-# install that file from the release (deploy/vm/modelproxy.sh). One artifact
-# per release, so every path that fetches a bundle (deploy/update.sh,
-# azure-computer-boot.sh, self-update.sh) carries the binary without knowing.
+# The release bundle: this checkout's committed computer/ tree as a git bundle
+# whose only ref is main, with oc-modelproxy built from it and committed as
+# modelproxy/oc-modelproxy. Computers never compile the proxy: they install
+# that file from the release (deploy/vm/modelproxy.sh). One artifact per
+# release, so every path that fetches a bundle (azure-computer-boot.sh,
+# self-update.sh) carries the binary without knowing.
#
-# deploy/bundle.sh <out.bundle> <oc-modelproxy> prints the release commit
+# deploy/bundle.sh <out.bundle> prints the release commit
#
-# The release commit is HEAD plus one file, so its sha (the release's version,
-# what `releases/<sha>` and calvin-latest.version say) is not on main; its
-# message names the main commit it was made from. The binary is content-
-# addressed by git, so a bundle that fetches is a bundle whose binary is intact.
+# The bundle's root is computer/, not the repository's, since a computer runs
+# deploy/vm/provision.sh from the root of what it fetches. Its one commit has
+# no parent, a fixed author and HEAD's date, so one HEAD gives one release
+# commit; the message names HEAD, and the proxy reports HEAD as its version.
+# Built from HEAD, not the working tree: uncommitted changes are not shipped.
+# The binary is for linux/amd64 (the computers' VMs).
set -euo pipefail
-out="${1:?usage: bundle.sh <out.bundle> <oc-modelproxy>}"
-bin="${2:?usage: bundle.sh <out.bundle> <oc-modelproxy>}"
-[[ -r $bin ]] || { echo "no binary at $bin" >&2; exit 1; }
+out="${1:?usage: bundle.sh <out.bundle>}"
cd "$(dirname "$0")/.."
-out="$(realpath -m "$out")"; bin="$(realpath "$bin")"
+out="$(realpath -m "$out")"
+head="$(git rev-parse HEAD)"
+date="$(git log -1 --format=%ct HEAD)"
tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
-repo="$tmp/repo"
-git init -q --bare "$repo"
-git -C "$repo" fetch -q "$PWD" "+HEAD:refs/heads/main"
-base="$(git -C "$repo" rev-parse refs/heads/main)"
-blob="$(git -C "$repo" hash-object -w "$bin")"
-export GIT_INDEX_FILE="$tmp/index"
-git -C "$repo" read-tree refs/heads/main
-git -C "$repo" update-index --add --cacheinfo "100755,$blob,modelproxy/oc-modelproxy"
-tree="$(git -C "$repo" write-tree)"
-unset GIT_INDEX_FILE
-commit="$(git -C "$repo" -c user.name=calvin-deploy -c [email protected] \
- commit-tree "$tree" -p "$base" -m "release: $base with oc-modelproxy built by CI")"
-git -C "$repo" update-ref refs/heads/main "$commit"
-git -C "$repo" bundle create -q "$out" refs/heads/main
-echo "$commit"
+tree="$tmp/tree"
+mkdir "$tree"
+git archive HEAD | tar -x -C "$tree" # in a subdirectory: that directory, as the root
+
+(cd "$tree/modelproxy" && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
+ go build -trimpath -buildvcs=false -ldflags "-X main.version=$head" -o oc-modelproxy .)
+
+export GIT_AUTHOR_NAME=opencomputer-release [email protected]
+export GIT_COMMITTER_NAME=opencomputer-release [email protected]
+export GIT_AUTHOR_DATE="@$date +0000" GIT_COMMITTER_DATE="@$date +0000"
+git -C "$tree" init -q -b main
+git -C "$tree" -c core.autocrlf=false -c core.fileMode=true add -A -f .
+git -C "$tree" -c commit.gpgsign=false commit -q \
+ -m "release: computer/ at $head, with oc-modelproxy built from it"
+git -C "$tree" bundle create -q "$out" refs/heads/main
+git -C "$tree" rev-parse HEAD
diff --git a/computer/deploy/vm/RUNBOOK.md b/computer/deploy/vm/RUNBOOK.md
index 05f335b7..501cbea1 100644
--- a/computer/deploy/vm/RUNBOOK.md
+++ b/computer/deploy/vm/RUNBOOK.md
@@ -1,7 +1,8 @@
-# Computer runbook: the client relay (work 084)
+# Computer runbook: the client relay (work 084) and the model proxy (work 097)
What runs on a computer for the Computer API's WebSocket and `/files`, where
-its logs are, and how to find why a client cannot connect. Commands run as
+its logs are, and how to find why a client cannot connect. The model proxy,
+which every session's model requests go through, is [at the end](#the-model-proxy-work-097). Commands run as
root on the computer (Azure Run Command or a shell through the host).
## The pieces
@@ -106,3 +107,38 @@ systemctl stop slack-presence-wire # the API's live wire is down; HTTP re
A release rollback (`self-update.sh` to an older commit) restarts the relay
with that release's bundle. The relay keeps no state of its own: restarting it
never loses an event.
+
+## The model proxy (work 097)
+
+`oc-modelproxy.service`, user `modelproxy`, `/usr/local/libexec/oc-modelproxy`
+(`modelproxy/`, its README). `deploy/vm/modelproxy.sh install` puts it there on
+every provision and code-only update, from the release (`deploy/bundle.sh`
+builds the binary into it; nothing is compiled on a computer), with the
+shipped profiles in `/etc/oc-modelproxy/profiles.d/`. Before it installs
+anything it runs the new binary's `-check` on the profile set it would serve;
+on a failure nothing changes and the installed proxy keeps serving.
+
+| Socket | Owner | Who |
+|---|---|---|
+| `/run/oc-modelproxy/api.sock` | `modelproxy:agent` 0660 | the sessions' model clients (the host's `SP_MODEL_SOCKET`) |
+| `/run/oc-modelproxy/control.sock` | `modelproxy:sp-host` 0660 | the host only (`SP_MODEL_PROXY`, set by `sp-host.sh migrate`) |
+
+Both are socket units, so a restart refuses no connection. A new binary or
+profile is a handoff (`systemctl reload oc-modelproxy`: SIGUSR2, a replacement
+with the same command line, the old process drains up to 630 s); only a
+changed unit file restarts it. A reload during a drain is ignored: the new
+binary waits for the next one. Files in `profiles.d` that a release does not
+ship are kept and checked with the rest.
+
+```sh
+systemctl status oc-modelproxy oc-modelproxy-api.socket oc-modelproxy-control.socket
+journalctl -u oc-modelproxy -n 200 --no-pager # JSON lines: ready, bound, denied, handoff
+/usr/local/libexec/oc-modelproxy -version # the release commit it was built from
+/usr/local/libexec/oc-modelproxy -check -profiles /etc/oc-modelproxy/profiles.d
+journalctl -u slack-presence-host | grep -i 'model proxy' # the host's side: down for 30 s, rebinds
+```
+
+No proxy (not installed, or the host has no `SP_MODEL_PROXY`, as on a
+computer not migrated to `sp-host`): the host logs an error and no session
+starts; the person sees "This computer's model proxy is not running." A
+session bound to no credential gets the host's reason in the thread.
diff --git a/computer/deploy/vm/modelproxy.sh b/computer/deploy/vm/modelproxy.sh
index e1c7af9f..f14c6b0e 100755
--- a/computer/deploy/vm/modelproxy.sh
+++ b/computer/deploy/vm/modelproxy.sh
@@ -1,50 +1,88 @@
#!/usr/bin/env bash
-# oc-modelproxy on a computer (work 077): Claude Code in runners reaches the
-# owner's Claude subscription through it, never holding the token.
+# oc-modelproxy on a computer (work 097 C9): every session's model client
+# reaches its upstream through it, and holds only a placeholder, never the
+# credential.
#
# provision.sh runs `modelproxy.sh install` on every provision and code-only
-# update: it installs the binary CI built, shipped in the release as
-# modelproxy/oc-modelproxy (deploy/bundle.sh), as /usr/local/libexec/oc-modelproxy
-# when it changed, and writes its socket and service units. Nothing is
-# compiled on a computer.
+# update. From this release it installs the binary deploy/bundle.sh built
+# (modelproxy/oc-modelproxy) as /usr/local/libexec/oc-modelproxy, and the
+# shipped profiles (modelproxy/profiles/*.json) into
+# /etc/oc-modelproxy/profiles.d/, then writes the socket and service units.
+# Nothing is compiled on a computer.
#
-# /run/oc-modelproxy/api.sock group agent: runners' Claude Code (ANTHROPIC_UNIX_SOCKET)
-# /run/oc-modelproxy/control.sock group sp-host: the host agent only (SP_MODEL_PROXY)
+# /run/oc-modelproxy/api.sock group agent: the sessions' model clients (SP_MODEL_SOCKET)
+# /run/oc-modelproxy/control.sock group sp-host: the host agent only (SP_MODEL_PROXY, sp-host.sh)
#
# Invariants:
-# - Inert until the host agent runs as sp-host (sp-host.sh migrate): before
-# that the host cannot open the control socket, sets no SP_MODEL_PROXY, and
-# the gateway routes every session managed.
-# - Best effort: a release without a working binary leaves the previous one
-# (or none) and never fails the provision; the host then advertises no `model-proxy`.
+# - Checked before installed: the release's binary loads the profile set it
+# would serve (profiles.d as it is, with this release's files over it) in a
+# temporary directory first. When it does not, nothing installed changes and
+# the script fails; the installed proxy, if any, keeps serving.
+# - A new binary or profile is a handoff (SIGUSR2, `systemctl reload`), never
+# a stop: no connection is refused and streams in flight finish. Only a
+# changed unit file restarts the service, since a handoff keeps the old
+# command line and limits.
+# - Files in profiles.d that the release does not ship (an operator's own)
+# are left as they are, and checked with the rest.
+# - Profiles are 0640 root:modelproxy: the proxy reads them, sessions do not.
# - The proxy runs as its own system user with no home and no write access
-# outside its runtime directory, so a runner (uid agent) can neither read its
-# memory nor its tokens.
+# outside its runtime directory, so a runner (uid agent) can read neither its
+# memory nor its credentials.
set -euo pipefail
AGENT_USER="${AGENT_USER:-agent}"
SP_CURRENT="${SP_CURRENT:-/opt/slack-presence/current}"
BIN=/usr/local/libexec/oc-modelproxy
+PROFILES=/etc/oc-modelproxy/profiles.d
USER_=modelproxy
RUN=/run/oc-modelproxy
+UNITS=/etc/systemd/system
[[ ${1:-} == install ]] || { echo "usage: modelproxy.sh install" >&2; exit 2; }
+die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
+
+src="$SP_CURRENT/modelproxy/oc-modelproxy"
+"$src" -version >/dev/null 2>&1 \
+ || die "no working oc-modelproxy in this release ($src; deploy/bundle.sh builds it); nothing installed"
+shopt -s nullglob
+shipped=("$SP_CURRENT"/modelproxy/profiles/*.json)
+installed=("$PROFILES"/*.json)
+shopt -u nullglob
+((${#shipped[@]})) || die "no profiles in this release ($SP_CURRENT/modelproxy/profiles); nothing installed"
+
+tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
+mkdir "$tmp/profiles.d"
+((${#installed[@]} == 0)) || cp "${installed[@]}" "$tmp/profiles.d/"
+cp "${shipped[@]}" "$tmp/profiles.d/"
+"$src" -check -profiles "$tmp/profiles.d" \
+ || die "this release's oc-modelproxy does not load the profiles it would serve; nothing installed"
getent group sp-host >/dev/null || groupadd --system sp-host
id "$USER_" >/dev/null 2>&1 || useradd --system --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin "$USER_"
-# Install only a binary that answers --version (a bundle made without one, or
-# built for another platform, keeps whatever is installed).
-src="$SP_CURRENT/modelproxy/oc-modelproxy"
-if [[ -f $src ]] && "$src" --version >/dev/null 2>&1; then
- if ! cmp -s "$src" "$BIN"; then
- install -D -m 0755 "$src" "$BIN"
+changed=0 # binary or profiles: a handoff
+unit_changed=0 # a unit file: a restart
+
+if ! cmp -s "$src" "$BIN"; then
+ install -D -m 0755 -o root -g root "$src" "$BIN"
+ changed=1
+fi
+install -d -m 0755 -o root -g root "${PROFILES%/*}" "$PROFILES"
+for f in "${shipped[@]}"; do
+ dst="$PROFILES/${f##*/}"
+ if ! cmp -s "$f" "$dst"; then
+ install -m 0640 -o root -g "$USER_" "$f" "$dst"
changed=1
fi
-else
- echo "WARNING: no working oc-modelproxy in this release (deploy/bundle.sh ships CI's build); keeping $([[ -x $BIN ]] && echo the installed one || echo none)" >&2
-fi
-[[ -x $BIN ]] || exit 0
+done
+
+# put <path>: stdin to path when it differs; a unit that changed restarts the service.
+put() {
+ cat > "$tmp/unit"
+ cmp -s "$tmp/unit" "$1" && return
+ install -m 0644 "$tmp/unit" "$1"
+ unit_changed=1
+}
# Not RuntimeDirectory=: it would go when the service stops, taking the sockets runners hold.
cat > /etc/tmpfiles.d/oc-modelproxy.conf <<EOF
@@ -52,10 +90,10 @@ d $RUN 0755 $USER_ $USER_ -
EOF
systemd-tmpfiles --create /etc/tmpfiles.d/oc-modelproxy.conf
-cat > /etc/systemd/system/oc-modelproxy-api.socket <<EOF
+put "$UNITS/oc-modelproxy-api.socket" <<EOF
# Written by deploy/vm/modelproxy.sh install.
[Unit]
-Description=oc-modelproxy: Claude Code's socket (runners)
+Description=oc-modelproxy: the sessions' model clients
[Socket]
ListenStream=$RUN/api.sock
@@ -69,7 +107,7 @@ Service=oc-modelproxy.service
WantedBy=sockets.target
EOF
-cat > /etc/systemd/system/oc-modelproxy-control.socket <<EOF
+put "$UNITS/oc-modelproxy-control.socket" <<EOF
# Written by deploy/vm/modelproxy.sh install.
[Unit]
Description=oc-modelproxy: the host agent's control socket
@@ -86,26 +124,36 @@ Service=oc-modelproxy.service
WantedBy=sockets.target
EOF
-cat > /etc/systemd/system/oc-modelproxy.service <<EOF
+put "$UNITS/oc-modelproxy.service" <<EOF
# Written by deploy/vm/modelproxy.sh install.
[Unit]
-Description=oc-modelproxy: Claude subscriptions for runners (work 077)
+Description=oc-modelproxy: the sessions' model credentials (work 097)
Requires=oc-modelproxy-api.socket oc-modelproxy-control.socket
After=oc-modelproxy-api.socket oc-modelproxy-control.socket network-online.target
Wants=network-online.target
[Service]
+# The handoff's replacement reports itself as the main pid (MAINPID=).
Type=notify
+NotifyAccess=all
User=$USER_
Group=$USER_
-ExecStart=$BIN --bindings-file=$RUN/bindings.json
+ExecStartPre=$BIN -check -profiles $PROFILES
+ExecStart=$BIN -profiles $PROFILES
+# The handoff: a replacement with the binary and profiles now on disk.
+ExecReload=/bin/kill -USR2 \$MAINPID
Restart=always
RestartSec=1
-# Streams in flight may finish on a restart (Claude Code's own request timeout is 600 s).
+# Streams in flight finish on a stop (-drain-timeout 630s; Claude Code's own request timeout is 600 s).
TimeoutStopSec=660
# A memory-pressured computer kills a runner, not every stream.
OOMScoreAdjust=-900
MemoryMax=512M
+# A ceiling, not a raise (Go lifts its soft limit to the hard one): two
+# descriptors a stream, the caller's and the upstream's.
+LimitNOFILE=65536
+# A core would hold credentials.
+LimitCORE=0
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=$RUN
@@ -121,17 +169,24 @@ LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
CapabilityBoundingSet=
-# Reads callers' cgroups to tell runners apart (unit sp-runner-<id>.service).
+# Not invisible: a caller is named by /proc/<pid>/cgroup of its process,
+# which runs as $AGENT_USER (identity.go), and invisible hides other users' processes.
ProtectProc=default
[Install]
WantedBy=multi-user.target
EOF
-systemctl daemon-reload
+((unit_changed == 0)) || systemctl daemon-reload
systemctl enable --now oc-modelproxy-api.socket oc-modelproxy-control.socket
systemctl enable oc-modelproxy.service
-# A new binary takes over without blocking the provision: the old one drains its streams (up to 10 min)
-# while new connections wait on the sockets; the host resyncs its binds when it reconnects.
-if [[ ${changed:-0} == 1 ]]; then systemctl restart --no-block oc-modelproxy.service; else systemctl start --no-block oc-modelproxy.service; fi
-echo "oc-modelproxy: $("$BIN" --version 2>/dev/null || echo installed)"
+if ! systemctl is-active --quiet oc-modelproxy.service; then
+ systemctl start --no-block oc-modelproxy.service
+elif ((unit_changed)); then
+ # The old process drains its streams (up to 10 min) while new connections
+ # wait on the sockets; the host re-binds when it reconnects.
+ systemctl restart --no-block oc-modelproxy.service
+elif ((changed)); then
+ systemctl reload oc-modelproxy.service
+fi
+echo "oc-modelproxy $("$BIN" -version)"
diff --git a/computer/deploy/vm/provision.sh b/computer/deploy/vm/provision.sh
index e7b6e6f9..92633f9e 100755
--- a/computer/deploy/vm/provision.sh
+++ b/computer/deploy/vm/provision.sh
@@ -649,11 +649,13 @@ bash "$SP_CURRENT/deploy/vm/grow-data.sh" install
# (deploy/vm/self-update.sh). A no-op on hosts without /root/calvin-computer.env.
bash "$SP_CURRENT/deploy/vm/self-update.sh" install
-# oc-modelproxy (work 077): runners reach their owner's Claude subscription
-# through it. Installed from this release (CI built it; deploy/bundle.sh ships it); inert until the host runs as sp-host
-# (deploy/vm/sp-host.sh migrate). Never fails the provision.
+# oc-modelproxy (work 097): every session reaches its model through it, and no
+# session starts without it. Installed from this release (deploy/bundle.sh
+# builds the binary) after a check of the profiles it would serve; a release
+# that fails it leaves the installed proxy serving, and a computer without one
+# starts no session until a release passes.
AGENT_USER="$AGENT_USER" SP_CURRENT="$SP_CURRENT" bash "$SP_CURRENT/deploy/vm/modelproxy.sh" install \
- || warn "oc-modelproxy not installed; sessions stay on the organization's credentials"
+ || warn "oc-modelproxy not updated: the installed one, if any, keeps serving; without one no session starts"
# The host agent: a system service running as the agent user. KillMode is the
# default (control-group) on purpose: runners are NOT in this unit's cgroup
diff --git a/computer/modelproxy/README.md b/computer/modelproxy/README.md
index 7b90080a..6bb86468 100644
--- a/computer/modelproxy/README.md
+++ b/computer/modelproxy/README.md
@@ -57,7 +57,7 @@ Any Anthropic-compatible or Responses-compatible API is one more entry:
| `report` | Globs of response header names sent to the binder with each `observed`. |
| `concurrency` | `{ "key": "{variable}", "limit": n }`: a cap on requests in flight across every caller whose binding expands `key` alike. Over it: 429, `Retry-After: 1`. |
| `websocket` | `false` refuses the profile's WS routes with 426, so clients go on over HTTP. |
-| `harness` | Per harness name, an object passed to the binder in `hello`; the proxy does not read it. It is where a profile says how each model client is configured for it. |
+| `harness` | Per harness name, an object passed to the binder in `hello`; the proxy does not read it. It is where a profile says how each model client is configured for it: Claude Code reads `{ "tokenEnv": "ANTHROPIC_API_KEY" \| "ANTHROPIC_AUTH_TOKEN" \| "CLAUDE_CODE_OAUTH_TOKEN", "promptCacheTtl"?: "1h", "downgradeOnModelRefusal"?: true }` (the variable it sends the placeholder in, its prompt cache TTL, and whether a refused model steps down a family), Codex `{}`; anything else in them is malformed, and a computer's runner refuses the turn. |
| `errors` | Texts replacing the proxy's own: `require`, `notReady`, `refused`, `refusedPrefix`, `unreachable`, `concurrency`. |
Per route:
diff --git a/computer/modelproxy/control_test.go b/computer/modelproxy/control_test.go
index ad4c64b1..ed533b4d 100644
--- a/computer/modelproxy/control_test.go
+++ b/computer/modelproxy/control_test.go
@@ -54,7 +54,7 @@ func TestHelloFirst(t *testing.T) {
t.Fatalf("hello profiles %v", names)
}
if toJSON(ps[0]) != `{"harness":{"codex":{"cache":"1h"}},"name":"alt","vars":["accountId","token"]}` ||
- toJSON(ps[2]) != `{"harness":{"claude":{"tokenEnv":"CLAUDE_CODE_OAUTH_TOKEN"}},"name":"claude-oauth","vars":["token"]}` {
+ toJSON(ps[2]) != `{"harness":{"claude":{"promptCacheTtl":"1h","tokenEnv":"CLAUDE_CODE_OAUTH_TOKEN"}},"name":"claude-oauth","vars":["token"]}` {
t.Fatalf("hello profiles %v", ps)
}
// model.proxy_started, sent before any binder connected, is kept for the first.
diff --git a/computer/modelproxy/profiles/default.json b/computer/modelproxy/profiles/default.json
index 842e3d31..006dea24 100644
--- a/computer/modelproxy/profiles/default.json
+++ b/computer/modelproxy/profiles/default.json
@@ -8,7 +8,7 @@
"set": { "X-Api-Key": "{token}" },
"remove": ["Cookie"],
"report": ["retry-after", "request-id", "anthropic-ratelimit-*"],
- "harness": { "claude": { "tokenEnv": "ANTHROPIC_API_KEY" } }
+ "harness": { "claude": { "tokenEnv": "ANTHROPIC_API_KEY", "promptCacheTtl": "1h" } }
},
"claude-oauth": {
"upstream": "https://api.anthropic.com",
@@ -25,7 +25,7 @@
"set": { "Authorization": "Bearer {token}" },
"remove": ["Cookie"],
"report": ["retry-after", "request-id", "anthropic-ratelimit-*"],
- "harness": { "claude": { "tokenEnv": "CLAUDE_CODE_OAUTH_TOKEN" } }
+ "harness": { "claude": { "tokenEnv": "CLAUDE_CODE_OAUTH_TOKEN", "promptCacheTtl": "1h" } }
},
"openrouter": {
"upstream": "https://openrouter.ai/api",
diff --git a/computer/src/credential-fingerprint.test.ts b/computer/src/credential-fingerprint.test.ts
deleted file mode 100644
index d506341e..00000000
--- a/computer/src/credential-fingerprint.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { credentialFingerprint, subscriptionFingerprint } from './credential-fingerprint.js';
-
-describe('credentialFingerprint', () => {
- it('is undefined without a Claude credential', () => {
- expect(credentialFingerprint(undefined)).toBeUndefined();
- expect(credentialFingerprint({})).toBeUndefined();
- });
- it('tells credentials and endpoints apart, and never contains the credential', () => {
- const a = credentialFingerprint({ anthropicApiKey: 'sk-secret-1' });
- expect(a).toMatch(/^[0-9a-f]{16}$/);
- expect(a).not.toContain('secret');
- expect(credentialFingerprint({ anthropicApiKey: 'sk-secret-1' })).toBe(a);
- expect(credentialFingerprint({ anthropicApiKey: 'sk-secret-2' })).not.toBe(a);
- expect(credentialFingerprint({ anthropicApiKey: 'sk-secret-1', anthropicBaseUrl: 'https://openrouter.ai/api' })).not.toBe(a);
- expect(credentialFingerprint({ claudeOAuthToken: 'sk-secret-1' })).not.toBe(a);
- });
-});
-
-describe('subscriptionFingerprint (work 082)', () => {
- it('names the owner and account, as the gateway computes it, and not the token', () => {
- // Pinned: blue's model-subscriptions.ts computes sha256(`chatgpt\0owner\0accountId`).slice(0, 12); both must agree.
- expect(subscriptionFingerprint('U1', 'chatgpt', 'acct-123')).toBe('df471168c415');
- expect(subscriptionFingerprint('U2', 'chatgpt', 'acct-123')).not.toBe('df471168c415');
- });
-});
diff --git a/computer/src/credential-fingerprint.ts b/computer/src/credential-fingerprint.ts
deleted file mode 100644
index 5dbf4f32..00000000
--- a/computer/src/credential-fingerprint.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// Which Claude credential a process runs with, as a short fingerprint both
-// the host and a spare runner compute (work 069): a spare may serve a
-// delivery only if it was started with the delivery's credential, since its
-// Claude Code copied the environment when it started.
-//
-// A ChatGPT subscription's fingerprint (work 082) names the owner and the
-// account instead: its access token is refreshed every few days, and a
-// refresh must look like the same credential so the proxy swaps the token in
-// place. The gateway (blue's model-subscriptions.ts) computes it the same way.
-//
-// Invariant: one-way and short; never the credential itself, so it may be
-// logged and sent over the socket.
-
-import { createHash } from 'node:crypto';
-import type { HostCredentials } from './protocol.js';
-
-/** The fingerprint of `c`'s Claude credential; undefined when it carries none. */
-export function credentialFingerprint(c: Pick<HostCredentials, 'claudeOAuthToken' | 'anthropicApiKey' | 'anthropicBaseUrl'> | undefined) {
- if (!c?.claudeOAuthToken && !c?.anthropicApiKey) return undefined;
- const parts = c.claudeOAuthToken ? ['oauth', c.claudeOAuthToken] : ['key', c.anthropicApiKey ?? '', c.anthropicBaseUrl ?? ''];
- return createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 16);
-}
-
-/** A ChatGPT route's fingerprint: sha256(`chatgpt\0owner\0accountId`), 12 hex, as the gateway computes it. Not the token. */
-export function subscriptionFingerprint(owner: string, provider: 'chatgpt', accountId: string) {
- return createHash('sha256').update(`${provider}\0${owner}\0${accountId}`).digest('hex').slice(0, 12);
-}
diff --git a/computer/src/dev/gateway-check.ts b/computer/src/dev/gateway-check.ts
index 796e1235..af664ab8 100644
--- a/computer/src/dev/gateway-check.ts
+++ b/computer/src/dev/gateway-check.ts
@@ -10,6 +10,7 @@ import os from 'node:os';
import path from 'node:path';
import { WebSocket } from 'ws';
import { encodeActionId, type GatewayToHost, type HostToGateway, type SlackPerson } from '../protocol.js';
+import type { ModelRoutes } from '../protocol-model.js';
import { Store } from '../gateway/db.js';
import { Hub } from '../gateway/hosts.js';
import { createRouter, type Msg } from '../gateway/routing.js';
@@ -48,16 +49,19 @@ store.putPerson(owner);
store.putHost('vm-1', 'issued-token');
const setupToken = issueHostToken(store.db, 'vm-2');
let botToken = 'xoxb-fake';
+const claudeRoute = { mode: 'profile', profile: 'anthropic-key', vars: { token: 'fake-key' }, key: 'k-claude' } as const;
+const models: ModelRoutes = { claude: claudeRoute };
const hub = new Hub({
store,
tokens: ['static-token'],
checkToken: (t) => checkHostToken(store.db, t),
- credentials: () => ({ slackBotToken: botToken, slackBotUserId: BOT, claudeOAuthToken: 'sk-fake' }),
+ credentials: () => ({ slackBotToken: botToken, slackBotUserId: BOT }),
+ models: () => models,
mintToken: async () => {
throw new Error('GitHub App not configured');
},
});
-const router = createRouter({ store, hub, mode: 'bypassPermissions' });
+const router = createRouter({ store, hub, mode: 'bypassPermissions', models: () => models });
const server = createServer((_, res) => res.writeHead(404).end());
hub.attach(server);
await new Promise<void>((ok) => server.listen(0, ok));
@@ -114,12 +118,14 @@ check('issued token accepted', await host.opened());
host.hello();
const welcome = await host.next('welcome');
check('welcome carries credentials and people', welcome?.credentials.slackBotToken === 'xoxb-fake' && welcome.people[0]?.dir === 'owner', welcome);
+check('welcome carries the model routes', JSON.stringify(welcome?.models) === JSON.stringify({ claude: claudeRoute }), welcome?.models);
// 1b. A fresh install pushes credentials instead of dropping the host
botToken = 'xoxb-new';
hub.refreshCredentials();
const cr = await host.next('credentials');
check('credentials pushed after an install, host stays connected', cr?.credentials.slackBotToken === 'xoxb-new' && host.ws.readyState === WebSocket.OPEN, cr);
+check('credentials carry the model routes', JSON.stringify(cr?.models) === JSON.stringify({ claude: claudeRoute }), cr?.models);
// 2. Allowlist
calls.length = 0;
@@ -202,6 +208,7 @@ await route(msg({ text: `<@${BOT}> ch build a thing` }), true);
const cc = await host.next('deliver');
check('ch → code channel session', cc?.session.key === 'C_CODE' && cc.session.kind === 'channel' && cc.msg.text === 'build a thing', cc?.session);
+
// 9. Button click routed by decodeActionId; stop button
await router.action(encodeActionId(`C1:${first.ts}`, 'pr7', 'allow'), owner.slackUserId, client, 'C1');
const a = await host.next('action');
diff --git a/computer/src/dev/host-check.ts b/computer/src/dev/host-check.ts
index bcc87d71..0f6f3c60 100644
--- a/computer/src/dev/host-check.ts
+++ b/computer/src/dev/host-check.ts
@@ -6,21 +6,29 @@
// Telemetry (work 054): host events reach a fake collector through the spool,
// across a collector outage and a host restart, with the path decided per
// delivery; a runner killed mid-turn (with and without a host restart in
-// between) gives `turn.abandoned` with its trace. A fake model API that never
-// answers keeps those turns running.
-// npx tsx src/dev/host-check.ts (no model calls: `!status` deliveries)
-// npx tsx src/dev/host-check.ts --claude (first delivery is one tiny real Claude turn)
+// between) gives `turn.abandoned` with its trace.
+//
+// Model access is real (work 097): oc-modelproxy is built from modelproxy/
+// (Go on PATH) and run with -identity=single on temp sockets, with the
+// shipped profiles and one more, `hang`, whose upstream is a local TLS server
+// that never answers; it keeps those mid-turn turns running. The proxy trusts
+// that server's self-signed certificate through SSL_CERT_FILE (Linux only).
+// npx tsx src/dev/host-check.ts (no model calls but the hanging ones: `!status` deliveries)
+// npx tsx src/dev/host-check.ts --claude (first delivery is one tiny real Claude turn: CLAUDE_CODE_OAUTH_TOKEN,
+// else ANTHROPIC_API_KEY, through the proxy as the gateway routes them)
// npx tsx src/dev/host-check.ts --workspace (workspace definition of one local bare repository: the first
// start forks it while the runner launches, cold-start.ts)
import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
-import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import net from 'node:net';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import http from 'node:http';
+import https from 'node:https';
import { WebSocketServer, type WebSocket } from 'ws';
-import type { GatewayToHost, HostToGateway, SessionSpec, TraceContext } from '../protocol.js';
+import { modelKey } from '../model-key.js';
+import type { GatewayToHost, HostToGateway, ModelRoute, SessionSpec, TraceContext } from '../protocol.js';
import { type TelemetryEvent, uuidv7 } from '../telemetry/envelope.js';
const ROOT = path.resolve(import.meta.dirname, '..', '..');
@@ -40,9 +48,8 @@ if (DEFINITION) {
}
const RUN = path.join(dir, 'run');
const KEY = `C_CHECK:${Date.now() / 1000}`;
-const b64 = Buffer.from(KEY).toString('base64url');
-const SOCK = path.join(RUN, 'runners', `${b64}.sock`);
-const LOG = path.join(RUN, 'logs', `${b64}.log`);
+const RUNNERS = path.join(RUN, 'runners');
+const LOGS = path.join(RUN, 'logs');
const t0 = Date.now();
const say = (...a: unknown[]) => console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, ...a);
let failed = 0;
@@ -58,7 +65,7 @@ async function until<T>(f: () => T | undefined, ms = 30_000): Promise<T | undefi
}
}
-// ---- fake collector: 503 while `outage`, else 202; and a model API that never answers
+// ---- fake collector: 503 while `outage`, else 202
const batches: { boot: string; seq: number; auth?: string; events: TelemetryEvent[] }[] = [];
let outage = true;
@@ -73,9 +80,6 @@ const collector = http.createServer((req, res) => {
});
await new Promise<void>((r) => collector.listen(0, '127.0.0.1', r));
const COLLECTOR = `http://127.0.0.1:${(collector.address() as net.AddressInfo).port}`;
-const hang = http.createServer(() => {});
-await new Promise<void>((r) => hang.listen(0, '127.0.0.1', r));
-const HANG_URL = `http://127.0.0.1:${(hang.address() as net.AddressInfo).port}`;
const tel = () => batches.flatMap((b) => b.events);
const telOf = (trace: TraceContext, name: string) => tel().filter((e) => e.trace_id === trace.id && e.event_name === name);
function mkTrace(): TraceContext {
@@ -84,6 +88,45 @@ function mkTrace(): TraceContext {
conversationId: 'C_CHECK', personId: 'U_OWNER' };
}
+// ---- model access: a model API that never answers, behind oc-modelproxy
+
+const KEYFILE = path.join(dir, 'hang.key');
+const CERT = path.join(dir, 'hang.crt');
+execFileSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1', '-subj', '/CN=127.0.0.1',
+ '-addext', 'subjectAltName=IP:127.0.0.1', '-keyout', KEYFILE, '-out', CERT], { stdio: 'ignore' });
+const hangs: http.ServerResponse[] = []; // held open, never answered
+const hangServer = https.createServer({ key: readFileSync(KEYFILE), cert: readFileSync(CERT) }, (_, res) => void hangs.push(res));
+await new Promise<void>((r) => hangServer.listen(0, '127.0.0.1', r));
+
+const shipped = JSON.parse(readFileSync(path.join(ROOT, 'modelproxy', 'profiles', 'default.json'), 'utf8'));
+const route = (profile: string, token: string): ModelRoute => ({ mode: 'profile', profile, vars: { token }, key: modelKey(profile, { token }) });
+// --claude: the route the gateway gives these settings (gateway/main.ts); a turn on it is real.
+const real = !CLAUDE ? undefined
+ : process.env.CLAUDE_CODE_OAUTH_TOKEN ? route('claude-oauth', process.env.CLAUDE_CODE_OAUTH_TOKEN)
+ : process.env.ANTHROPIC_API_KEY ? route('anthropic-key', process.env.ANTHROPIC_API_KEY)
+ : undefined;
+if (CLAUDE && !real) throw new Error('--claude needs CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY');
+// `hang` runs Claude Code as the real route's profile does, so moving a live session onto it rebinds in place.
+const HANG = route('hang', 'check-not-a-credential');
+const profiles = path.join(dir, 'profiles.d');
+mkdirSync(profiles);
+writeFileSync(path.join(profiles, 'default.json'), JSON.stringify(shipped));
+writeFileSync(path.join(profiles, 'hang.json'), JSON.stringify({ hang: {
+ upstream: `https://127.0.0.1:${(hangServer.address() as net.AddressInfo).port}`,
+ routes: { 'POST /v1/messages': {}, 'POST /v1/messages/count_tokens': {} },
+ set: { 'X-Api-Key': '{token}' },
+ harness: { claude: shipped[real?.mode === 'profile' ? real.profile : 'anthropic-key'].harness.claude },
+} }));
+const PROXY_BIN = path.join(dir, 'oc-modelproxy');
+execFileSync('go', ['build', '-o', PROXY_BIN, '.'], { cwd: path.join(ROOT, 'modelproxy'), stdio: 'inherit', env: { ...process.env, CGO_ENABLED: '0' } });
+const CONTROL = path.join(dir, 'control.sock');
+const API = path.join(dir, 'api.sock');
+const proxy = spawn(PROXY_BIN, ['-identity=single', '-profiles', profiles, '-api-socket', API, '-control-socket', CONTROL, '-bindings-file', ''], {
+ env: { PATH: process.env.PATH, SSL_CERT_FILE: CERT },
+ stdio: ['ignore', 'pipe', 'pipe'],
+});
+for (const s of [proxy.stdout!, proxy.stderr!]) s.on('data', (d) => process.stdout.write(String(d).replace(/^(?=.)/gm, ' proxy| ')));
+
// ---- fake gateway
const events: HostToGateway[] = [];
@@ -107,9 +150,7 @@ wss.on('connection', (c) => {
if (m.t === 'hello')
toHost({ t: 'welcome', protocol: 1, credentials: {
slackBotToken: '', slackBotUserId: '',
- ...(process.env.CLAUDE_CODE_OAUTH_TOKEN ? { claudeOAuthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN } : {}),
- ...(process.env.ANTHROPIC_API_KEY ? { anthropicApiKey: process.env.ANTHROPIC_API_KEY } : {}),
- }, people: [owner] });
+ }, models: { claude: real ?? HANG }, people: [owner] });
if (m.t === 'token') {
tokenRequests++;
tokenSessions.push(m.sessionKey);
@@ -131,8 +172,6 @@ const spec: SessionSpec = { key: KEY, kind: 'thread', channel: 'C_CHECK', thread
const scopedCredentials = {
slackBotToken: 'xoxb-fake',
slackBotUserId: 'U_BOT',
- ...(process.env.CLAUDE_CODE_OAUTH_TOKEN ? { claudeOAuthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN } : {}),
- ...(process.env.ANTHROPIC_API_KEY ? { anthropicApiKey: process.env.ANTHROPIC_API_KEY } : {}),
};
function startHost(idleMs: number): ChildProcess {
const { SP_DEFINITION, WORKDIR, SLACK_BOT_TOKEN, ...rest } = process.env;
@@ -140,6 +179,7 @@ function startHost(idleMs: number): ChildProcess {
cwd: ROOT,
env: { ...rest, SP_GATEWAY_URL: `ws://127.0.0.1:${port}/host`, SP_HOST_TOKEN: 'check-token', SP_HOST_ID: 'check',
SP_RUN: RUN, SP_DATA: path.join(dir, 'data'), SP_IDLE_MS: String(idleMs), SP_LAUNCH: 'detached', SP_FAKE_SLACK: '1',
+ SP_MODEL_PROXY: CONTROL, SP_MODEL_SOCKET: API,
SP_TELEMETRY_URL: COLLECTOR, SP_TELEMETRY_CREDENTIAL: 'check-credential', SP_REGION: 'local', SP_SUBSTRATE: 'laptop',
...(DEFINITION && { SP_DEFINITION: DEFINITION }) },
stdio: ['ignore', 'pipe', 'pipe'],
@@ -147,7 +187,12 @@ function startHost(idleMs: number): ChildProcess {
for (const s of [h.stdout!, h.stderr!]) s.on('data', (d) => process.stdout.write(String(d).replace(/^(?=.)/gm,' host| ')));
return h;
}
-const runnerPid = () => (existsSync(SOCK.replace(/\.sock$/, '.pid')) ? Number(readFileSync(SOCK.replace(/\.sock$/, '.pid'), 'utf8')) : 0);
+// Runners are named by id, not session. The session's runner is the only one: with -identity=single the host keeps no spares.
+const runnerId = () => (existsSync(RUNNERS) ? readdirSync(RUNNERS).find((f) => f.endsWith('.sock') && !f.endsWith('.api.sock'))?.slice(0, -'.sock'.length) : undefined);
+const runnerPid = () => {
+ const f = path.join(RUNNERS, `${runnerId()}.pid`);
+ return existsSync(f) ? Number(readFileSync(f, 'utf8')) : 0;
+};
const alive = (pid: number) => {
try {
return pid > 0 && process.kill(pid, 0);
@@ -155,7 +200,9 @@ const alive = (pid: number) => {
return false;
}
};
-const runnerLog = () => (existsSync(LOG) ? readFileSync(LOG, 'utf8') : '');
+/** Every runner's log, oldest first. */
+const runnerLog = () => (existsSync(LOGS) ? readdirSync(LOGS).map((f) => path.join(LOGS, f)).sort((a, b) => statSync(a).mtimeMs - statSync(b).mtimeMs)
+ .map((f) => readFileSync(f, 'utf8')).join('') : '');
function askToken(sessionKey: string, socket = path.join(RUN, 'token.sock')) {
return new Promise<any>((resolve, reject) => {
const s = net.createConnection(socket, () => s.write(JSON.stringify({ sessionKey }) + '\n'));
@@ -176,7 +223,7 @@ try {
const r1 = await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text, ts: '2.1' }, credentials: scopedCredentials, trace: tr1 });
check(!!r1?.ok, `deliver "${text}" → reply ok (${r1?.error ?? ''})`);
pid = runnerPid();
- check(alive(pid) && existsSync(SOCK), `runner process ${pid} spawned, listening on its socket`);
+ check(alive(pid) && !!runnerId(), `runner process ${pid} spawned, listening on its socket`);
if (CLAUDE) {
await until(() => reports().some((r) => r.status === 'busy') && reports().at(-1)?.status === 'idle' ? true : undefined, 120_000);
check(/chat\.(startStream|postMessage)/.test(runnerLog()) && !!reports().at(-1)?.sdkSessionId, 'Claude turn rendered to fake Slack, sdkSessionId reported');
@@ -238,7 +285,7 @@ try {
check(batches.every((b) => b.auth === 'Bearer check-credential'), 'batches carry the credential');
check(!!(await until(() => (!alive(pid) ? true : undefined), 20_000)), 'runner exited after the idle timeout');
- check(reports().at(-1)?.status === 'stopped' && !existsSync(SOCK), 'runner reported stopped and removed its socket');
+ check(reports().at(-1)?.status === 'stopped' && !runnerId(), 'runner reported stopped and removed its socket');
check(!!(await until(() => tel().find((e) => e.event_name === 'runner.exited' && e.data.exit_reason === 'idle' && e.data.busy === false))),
'runner.exited: idle, not busy');
@@ -258,19 +305,18 @@ try {
check(!!r4?.ok && !!r5?.ok && !alive(pid) && alive(pid5) && pid5 !== pid, `!restart exits the runner; the next message starts a fresh one (${pid5}) (${r5?.error ?? ''})`);
pid = pid5;
- // Mid-turn: a model that never answers keeps the runner busy.
- const hanging = { ...scopedCredentials, claudeOAuthToken: undefined, anthropicApiKey: 'sk-check', anthropicBaseUrl: HANG_URL };
+ // Mid-turn: a model that never answers keeps the runner busy. The route, not the credentials, says where a turn goes.
const busy = () => reports().at(-1)?.status === 'busy' || undefined;
const tr6 = mkTrace();
- check(!!(await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text: 'hello', ts: '2.6' }, credentials: hanging, trace: tr6 }))?.ok
- && !!(await until(busy)), 'a turn is running (model never answers)');
- process.kill(pid, 'SIGKILL');
+ check(!!(await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text: 'hello', ts: '2.6' }, credentials: scopedCredentials, model: HANG, trace: tr6 }))?.ok
+ && !!(await until(busy)) && !!(await until(() => hangs.length || undefined)), 'a turn is running: its request reached the model, which never answers');
+ if (alive(pid)) process.kill(pid, 'SIGKILL'); // never 0: that is this process's group
const ab6 = await until(() => telOf(tr6, 'turn.abandoned')[0]);
check(ab6?.outcome === 'abandoned' && ab6.data.exit_reason === 'unknown' && typeof ab6.duration_ms === 'number',
'runner killed mid-turn → turn.abandoned with its trace');
const tr7 = mkTrace();
- check(!!(await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text: 'hello again', ts: '2.7' }, credentials: hanging, trace: tr7 }))?.ok
+ check(!!(await request({ t: 'deliver', id: randomUUID(), session: spec, msg: { userId: 'U_OWNER', text: 'hello again', ts: '2.7' }, credentials: scopedCredentials, model: HANG, trace: tr7 }))?.ok
&& !!(await until(busy)), 'another turn is running');
pid = runnerPid();
await sleep(2500);
@@ -278,7 +324,7 @@ try {
await sleep(500);
host = startHost(600_000);
check(!!(await until(() => hellos()[2]))?.sessions.some((s) => s.key === KEY && s.status === 'busy'), 'restarted host found the busy runner');
- process.kill(pid, 'SIGKILL');
+ if (alive(pid)) process.kill(pid, 'SIGKILL');
check(!!(await until(() => telOf(tr7, 'turn.abandoned')[0])), 'host restarted mid-turn, then the runner killed → turn.abandoned still names the trace');
if (WORKSPACE) {
@@ -308,6 +354,7 @@ try {
check(new Set(ids).size === ids.length, `no event sent twice (${ids.length} events)`);
} finally {
host.kill('SIGTERM');
+ proxy.kill('SIGTERM');
if (alive(pid)) process.kill(pid, 'SIGTERM');
await sleep(500);
say('runner log (last lines):\n' + runnerLog().split('\n').slice(-12).map((l) => ' runner| ' + l).join('\n'));
@@ -315,7 +362,8 @@ try {
rmSync(path.join(ROOT, 'workspaces', KEY.replace(/[^a-zA-Z0-9]+/g, '-')), { recursive: true, force: true });
wss.close();
collector.close();
- hang.close();
+ for (const r of hangs) r.destroy();
+ hangServer.close();
say(failed ? `${failed} check(s) failed` : 'all checks passed');
process.exit(failed ? 1 : 0);
}
diff --git a/computer/src/dev/secrets-check.ts b/computer/src/dev/secrets-check.ts
index 3a02e16b..a8b2aa96 100644
--- a/computer/src/dev/secrets-check.ts
+++ b/computer/src/dev/secrets-check.ts
@@ -273,14 +273,15 @@ const vault = new Vault(store.db, KEY);
const hub: Hub = new Hub({
store,
tokens: [],
- credentials: () => ({ slackBotToken: 'xoxb', slackBotUserId: BOT, claudeOAuthToken: 'x' }),
+ credentials: () => ({ slackBotToken: 'xoxb', slackBotUserId: BOT }),
+ models: () => ({}),
mintToken: async () => ({ token: 't', expiresAt: new Date().toISOString() }),
secretsFor: (spec) => (isSlackSpec(spec) ? vault.forSession(spec.key, spec.owner.slackUserId) : []),
requestSecret: (from, req) => ui.request(from, req, client),
});
const ui = createSecretsUi({ store, vault, hub });
const vars = createVariablesUi({ store, vault, hub });
-const router = createRouter({ store, hub, mode: 'bypassPermissions', secrets: ui, variables: vars });
+const router = createRouter({ store, hub, mode: 'bypassPermissions', models: () => ({}), secrets: ui, variables: vars });
const server = createServer((_, res) => res.writeHead(404).end());
hub.attach(server);
await new Promise<void>((ok) => server.listen(0, ok));
diff --git a/computer/src/gateway/hosts.ts b/computer/src/gateway/hosts.ts
index 53b77909..e8269f7b 100644
--- a/computer/src/gateway/hosts.ts
+++ b/computer/src/gateway/hosts.ts
@@ -26,6 +26,7 @@ import {
type WorkspaceStatus,
} from '../protocol.js';
import type { Linked } from '../links.js';
+import type { ModelRoutes } from '../protocol-model.js';
import type { Store, Queued } from './db.js';
import { errorText, log } from '../log.js';
@@ -36,6 +37,8 @@ export interface HubDeps {
/** Tokens issued by /setup (S3's checkHostToken): the host's label, or undefined. */
checkToken?(token: string): string | undefined;
credentials(): HostCredentials;
+ /** Work 097: the route of a session whose delivery carries none, by harness; sent in `welcome` and `credentials`. */
+ models(): ModelRoutes;
mintToken(repos?: string[]): Promise<{ token: string; expiresAt: string }>;
/** A session starts a new thread (work 047): the router posts it and creates the session. */
spawn?(from: string, req: SpawnRequest): Promise<SpawnResult>;
@@ -148,7 +151,7 @@ export class Hub {
this.conns.get(m.hostId)?.ws.close(4001, 'replaced');
const conn: Conn = { ws, hostId: m.hostId, version: m.version, pending: new Map() };
this.conns.set(m.hostId, conn);
- this.send(conn, { t: 'welcome', protocol: PROTOCOL_VERSION, credentials: this.deps.credentials(), people: this.deps.store.people() });
+ this.send(conn, { t: 'welcome', protocol: PROTOCOL_VERSION, credentials: this.deps.credentials(), models: this.deps.models(), people: this.deps.store.people() });
for (const r of m.sessions) this.deps.store.report(r, m.hostId);
log.info(`host ${m.hostId} connected (${m.version}, ${m.sessions.length} sessions)`);
void this.flush();
@@ -292,10 +295,11 @@ export class Hub {
for (const conn of this.conns.values()) this.send(conn, m);
}
- /** Credentials changed (a fresh install, a new Claude token): push them; hosts forward them to their runners. */
+ /** Credentials changed (a fresh install, a new model credential): push them and the model routes; hosts forward them to their runners. */
refreshCredentials() {
const credentials = this.deps.credentials();
- for (const conn of this.conns.values()) this.send(conn, { t: 'credentials', credentials });
+ const models = this.deps.models();
+ for (const conn of this.conns.values()) this.send(conn, { t: 'credentials', credentials, models });
if (this.conns.size) log.info(`credentials pushed to ${this.conns.size} host(s)`);
}
diff --git a/computer/src/gateway/main.ts b/computer/src/gateway/main.ts
index 72ca2183..7a5956b4 100644
--- a/computer/src/gateway/main.ts
+++ b/computer/src/gateway/main.ts
@@ -13,6 +13,14 @@
// SP_PEOPLE JSON array of SlackPerson, upserted into the people table on start
// SP_SLACK_API_URL dev only: Slack Web API base URL (a local fake), for every Slack call the gateway makes
//
+// The sessions' model credentials (work 097 C9), sent to hosts as `models`;
+// the host binds each runner to one through the computer's model proxy:
+// MODEL_PROFILE + MODEL_TOKEN Claude Code on that profile (an operator's own, in the proxy's profiles.d);
+// wins over the two below
+// CLAUDE_CODE_OAUTH_TOKEN else Claude Code on `claude-oauth` (also from /setup)
+// ANTHROPIC_API_KEY else Claude Code on `anthropic-key` (also from /setup)
+// OPENAI_API_KEY Codex on `openai-key`, for threads started with `+codex`
+//
// Slack credentials come from env first, then the secret store. One HTTP
// server listens the whole time; what answers behind it is either the setup
// routes (no Slack app yet) or Bolt (the app exists). When /setup stores new
@@ -29,6 +37,8 @@ import { WebClient } from '@slack/web-api';
import { loadEnv, setEnv } from '../env.js';
import { SCOPES, ensureApp, startTunnel, syncManifest } from '../provision.js';
import { type HostCredentials, isSlackSpec, type PermissionMode, type SlackPerson } from '../protocol.js';
+import type { ModelRoute, ModelRoutes } from '../protocol-model.js';
+import { modelKey } from '../model-key.js';
import { openSecrets, type Secrets } from '../setup/secrets.js';
import { checkHostToken, setupRoutes, slackAppReady, slackReady, type SetupStep } from '../setup/index.js';
import { slackApi } from '../setup/slack.js';
@@ -86,14 +96,23 @@ const purge = () => {
purge();
setInterval(purge, 24 * 3600_000).unref();
-const credentials = (): HostCredentials => {
- const claude = get('CLAUDE_CODE_OAUTH_TOKEN');
- return {
- slackBotToken: get('SLACK_BOT_TOKEN') ?? '',
- slackBotUserId: get('SLACK_BOT_USER_ID') ?? '',
- teamId: get('SLACK_TEAM_ID'),
- ...(claude ? { claudeOAuthToken: claude } : { anthropicApiKey: get('ANTHROPIC_API_KEY') }),
- };
+const credentials = (): HostCredentials => ({
+ slackBotToken: get('SLACK_BOT_TOKEN') ?? '',
+ slackBotUserId: get('SLACK_BOT_USER_ID') ?? '',
+ teamId: get('SLACK_TEAM_ID'),
+});
+
+/** The sessions' model routes, by harness (the table above). */
+const models = (): ModelRoutes => {
+ const route = (profile: string, token: string): ModelRoute => ({ mode: 'profile', profile, vars: { token }, key: modelKey(profile, { token }) });
+ const profile = get('MODEL_PROFILE');
+ const token = get('MODEL_TOKEN');
+ const oauth = get('CLAUDE_CODE_OAUTH_TOKEN');
+ const apiKey = get('ANTHROPIC_API_KEY');
+ const openai = get('OPENAI_API_KEY');
+ const claude =
+ profile && token ? route(profile, token) : oauth ? route('claude-oauth', oauth) : apiKey ? route('anthropic-key', apiKey) : undefined;
+ return { ...(claude ? { claude } : {}), ...(openai ? { codex: route('openai-key', openai) } : {}) };
};
const hub = new Hub({
@@ -101,6 +120,7 @@ const hub = new Hub({
tokens: (env.SP_HOST_TOKENS ?? '').split(',').map((t) => t.trim()).filter(Boolean),
checkToken: (t) => checkHostToken(store.db, t),
credentials,
+ models,
mintToken: (repos) => mintInstallationToken(secrets, repos),
spawn: (from, req) => {
if (!slackRouter) throw new Error('Slack is not set up on the gateway');
@@ -128,7 +148,7 @@ if (laptop) {
origin = await startTunnel(PORT);
}
-/** A setup step stored something: Slack app credentials rebuild Bolt; a new Claude token goes to the hosts. */
+/** A setup step stored something: Slack app credentials rebuild Bolt; a new Claude token goes to the hosts as `models`. */
function onChange(step: SetupStep) {
if (step === 'slack') reload();
if (step === 'claude' || step === 'slack') hub.refreshCredentials();
@@ -286,6 +306,7 @@ function boltHandler(): RequestListener {
store,
hub,
mode: (env.PERMISSION_MODE ?? 'bypassPermissions') as PermissionMode,
+ models,
secrets: secretsUi,
variables: variablesUi,
}));
diff --git a/computer/src/gateway/routing.test.ts b/computer/src/gateway/routing.test.ts
index 5e583a1b..ad5f8b65 100644
--- a/computer/src/gateway/routing.test.ts
+++ b/computer/src/gateway/routing.test.ts
@@ -4,10 +4,11 @@
import { beforeEach, describe, expect, it } from 'vitest';
import type { WebClient } from '@slack/web-api';
import type { Delivery, SlackPerson, SlackSessionSpec } from '../protocol.js';
+import type { ModelRoutes } from '../protocol-model.js';
import type { Store } from './db.js';
import type { Hub } from './hosts.js';
import { withLinked } from '../links.js';
-import { type Ctx, createRouter, type Msg } from './routing.js';
+import { type Ctx, createRouter, type Msg, takeHarness } from './routing.js';
const owner: SlackPerson = { slackUserId: 'U1', dir: 'owner', gitName: 'Owner', gitEmail: '[email protected]' };
const BOT = 'UBOT';
@@ -62,6 +63,8 @@ let hub: ReturnType<typeof fakeHub>;
let client: ReturnType<typeof fakeClient>;
let router: ReturnType<typeof createRouter>;
let n = 0;
+let models: ModelRoutes;
+const claude = { mode: 'profile', profile: 'anthropic-key', vars: { token: 'fake' }, key: 'k1' } as const;
const msg = (over: Partial<Msg> = {}): Msg => ({ channel: 'C1', ts: `1.${++n}`, user: owner.slackUserId, text: `<@${BOT}> do it`, ...over });
const ctx = (): Ctx => ({ client: client as unknown as WebClient, botUserId: BOT, teamId: 'T1', eventId: `ev-${++n}` });
@@ -70,7 +73,8 @@ beforeEach(() => {
store = fakeStore();
hub = fakeHub();
client = fakeClient();
- router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'bypassPermissions' });
+ models = { claude };
+ router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'bypassPermissions', models: () => models });
});
describe('starting sessions', () => {
@@ -274,10 +278,42 @@ describe('de-duplication', () => {
});
});
+describe('+codex', () => {
+ it('takes a leading +claude or +codex only, as a word', () => {
+ expect(takeHarness('+Codex fix it')).toEqual({ harness: 'codex', text: 'fix it' });
+ expect(takeHarness('+claude')).toEqual({ harness: 'claude', text: '' });
+ expect(takeHarness('+codexy fix')).toEqual({ text: '+codexy fix' });
+ expect(takeHarness('fix +codex')).toEqual({ text: 'fix +codex' });
+ });
+
+ it('a first message starting with +codex starts a Codex session, without the prefix', async () => {
+ models = { claude, codex: { mode: 'profile', profile: 'openai-key', vars: { token: 'fake' }, key: 'k2' } };
+ const m = msg({ text: `<@${BOT}> +codex +smart port it` });
+ await router.route(m, ctx(), true);
+ expect(store.sessions.get(`C1:${m.ts}`)).toMatchObject({ harness: 'codex', title: 'port it' });
+ expect(hub.delivered[0].msg.text).toBe('+smart port it');
+ });
+
+ it('without a route for Codex the person is told why and no session starts', async () => {
+ await router.route(msg({ text: `<@${BOT}> +codex port it` }), ctx(), true);
+ expect(client.of('chat.postEphemeral')[0].text).toBe('Codex needs OPENAI_API_KEY on this computer.');
+ expect(store.sessions.size).toBe(0);
+ expect(hub.delivered).toHaveLength(0);
+ });
+
+ it('a session started without a prefix names no harness, and a later +codex is only text', async () => {
+ const m = msg();
+ await router.route(m, ctx(), true);
+ await router.route(msg({ thread_ts: m.ts, text: '+codex now' }), ctx(), false);
+ expect(store.sessions.get(`C1:${m.ts}`)?.harness).toBeUndefined();
+ expect(hub.delivered[1].msg.text).toBe('+codex now');
+ });
+});
+
describe('with no host connected', () => {
it('tells the person the message is queued', async () => {
hub = fakeHub(false);
- router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'default' });
+ router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'default', models: () => models });
await router.route(msg(), ctx(), true);
expect(client.of('chat.postEphemeral')[0].text).toMatch(/offline/);
expect(client.of('agents.sessions.setStatus')).toHaveLength(0);
diff --git a/computer/src/gateway/routing.ts b/computer/src/gateway/routing.ts
index 48576b7f..6212c8a2 100644
--- a/computer/src/gateway/routing.ts
+++ b/computer/src/gateway/routing.ts
@@ -4,6 +4,7 @@
//
// @bot <task> in a channel → new session in that thread
// @bot ch <task> in a channel → new session in a new Slack Code channel
+// @bot +codex <task> → the new session runs Codex (when the gateway has OPENAI_API_KEY)
// DM the bot → new session in that DM thread
// reply in a session's thread/channel → deliver (`!` commands too: the runner handles them),
// marked mentioned or not; the agent may stay silent
@@ -16,8 +17,9 @@
// "not enabled for you yet" and nothing else.
import type { WebClient } from '@slack/web-api';
-import { decodeActionId, type Delivery, type PermissionMode, type SlackPerson, type SlackSessionSpec, type SpawnRequest, type SpawnResult } from '../protocol.js';
+import { decodeActionId, type Delivery, type HarnessName, type PermissionMode, type SlackPerson, type SlackSessionSpec, type SpawnRequest, type SpawnResult } from '../protocol.js';
import type { SlackFile } from '../protocol.js';
+import type { ModelRoutes } from '../protocol-model.js';
import { addressed, decodeSlack } from '../slack-text.js';
import { findPermalinks, forwarded, linkResolver, type Linked, type SharedAttachment } from '../links.js';
import { TIERS, takeTier } from '../tiers.js';
@@ -51,6 +53,8 @@ export interface RouterDeps {
store: Store;
hub: Hub;
mode: PermissionMode;
+ /** The model routes hosts get (main.ts): a thread starts on Codex only when there is one for it. */
+ models(): ModelRoutes;
secrets?: SecretsUi;
variables?: VariablesUi;
}
@@ -60,8 +64,15 @@ const NOT_ENABLED = `${APP_NAME} is not enabled for you yet. Ask the instance ow
const OFFLINE = 'The agent host is offline; your message will be delivered when it reconnects.';
/** Reading linked threads must not hold a message up for long. */
const LINKS_TIMEOUT_MS = 10_000;
+const CODEX_NEEDS_KEY = 'Codex needs OPENAI_API_KEY on this computer.';
-export function createRouter({ store, hub, mode, secrets, variables }: RouterDeps) {
+/** `+codex fix it` → `{ harness: 'codex', text: 'fix it' }`; the first message of a thread picks its harness. */
+export function takeHarness(text: string): { harness?: HarnessName; text: string } {
+ const m = /^\+(claude|codex)(?=\s|$)\s*/i.exec(text);
+ return m ? { harness: m[1].toLowerCase() as HarnessName, text: text.slice(m[0].length) } : { text };
+}
+
+export function createRouter({ store, hub, mode, models, secrets, variables }: RouterDeps) {
// Slack sends both `message` and `app_mention` for a mention (different
// event ids, same channel:ts); the first one routes, the second is dropped.
const seen = new Set<string>();
@@ -99,21 +110,26 @@ export function createRouter({ store, hub, mode, secrets, variables }: RouterDep
// In a DM or a code channel every message is for the bot.
if (existing) return forward(existing.spec, m, text, client, mentioned || m.channel_type === 'im' || existing.spec.kind === 'channel', a.inline);
- // `+smart ch <task>` and `ch +smart <task>` both work; the tier stays on the task for the session.
- const { tier, rest } = takeTier(text);
+ // `+codex` first; then `+smart ch <task>` and `ch +smart <task>` both work; the tier stays on the task for the session.
+ const { harness, text: asked } = takeHarness(text);
+ if (harness === 'codex' && !models().codex) return ephemeral(client, m.channel, m.user, CODEX_NEEDS_KEY, m.thread_ts);
+ const { tier, rest } = takeTier(asked);
const wantsChannel = /^(ch|channel)\b/i.test(rest) && m.channel_type !== 'im';
- const task = wantsChannel ? (tier ? `+${tier} ` : '') + rest.replace(/^(ch|channel)\b\s*/i, '') : text;
+ const task = wantsChannel ? (tier ? `+${tier} ` : '') + rest.replace(/^(ch|channel)\b\s*/i, '') : asked;
const title = takeTier(task).rest.replace(/\s+/g, ' ');
const threadTs = m.thread_ts ?? m.ts;
- const spec: SlackSessionSpec = (wantsChannel && (await codeChannel(m, ctx, title, person))) || {
- key: `${m.channel}:${threadTs}`,
- kind: 'thread',
- channel: m.channel,
- threadTs,
- owner: person,
- teamId: ctx.teamId,
- title: title.slice(0, 80),
- mode,
+ const spec: SlackSessionSpec = {
+ ...((wantsChannel && (await codeChannel(m, ctx, title, person))) || {
+ key: `${m.channel}:${threadTs}`,
+ kind: 'thread',
+ channel: m.channel,
+ threadTs,
+ owner: person,
+ teamId: ctx.teamId,
+ title: title.slice(0, 80),
+ mode,
+ }),
+ ...(harness ? { harness } : {}),
};
store.putSession(spec);
log.info(`new session ${spec.key} for ${person.dir}`);
diff --git a/computer/src/host/claim.ts b/computer/src/host/claim.ts
index 19c1b2f3..32297f0d 100644
--- a/computer/src/host/claim.ts
+++ b/computer/src/host/claim.ts
@@ -1,5 +1,5 @@
// A new session's runner from the warm pool (work 069): take a parked spare
-// whose Claude credential matches the delivery's, make the session's fork,
+// of the session's spare kind (pool.ts), make the session's fork,
// then `claim` the spare into it. Anything short of a claimed spare falls back
// to a cold start, in the fork when it was made.
//
@@ -34,7 +34,7 @@ export const isGone = (e: unknown) => /runner gone/.test(String((e as Error)?.me
export async function claimSpare<R>(s: ClaimSteps<R>): Promise<ClaimOutcome<R>> {
const taken = s.take();
- if (taken === 'none' || taken === 'credential') return { missed: taken as MissReason };
+ if (taken === 'none' || taken === 'kind') return { missed: taken as MissReason };
const r = taken as R;
let forkPath: string;
try {
diff --git a/computer/src/host/gateway-link.ts b/computer/src/host/gateway-link.ts
index 76023ec3..c6f81406 100644
--- a/computer/src/host/gateway-link.ts
+++ b/computer/src/host/gateway-link.ts
@@ -9,7 +9,7 @@
// gateway's to retry, and a reply to a gone gateway is moot.
// - `redial` drops the link now rather than waiting for a close handshake
// (~11 s on the preview) and dials again within 200 ms: for a new identity
-// (`assign`) or a changed hello (subscriptions.ts).
+// (`assign`) or a changed hello (model-access.ts).
// - `url` and `token` are asked at every dial, so an `assign` saved before a
// redial is what the next dial uses.
diff --git a/computer/src/host/gateway-updates.test.ts b/computer/src/host/gateway-updates.test.ts
index 401f4ee8..b393a84b 100644
--- a/computer/src/host/gateway-updates.test.ts
+++ b/computer/src/host/gateway-updates.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import net from 'node:net';
-import type { HostCredentials, HostToRunner, Person } from '../protocol.js';
+import type { HostCredentials, HostToRunner, Person, RunnerModel } from '../protocol.js';
import { gatewayUpdates } from './gateway-updates.js';
/** A runner's end as the host sees it: a socket whose writes are kept as parsed messages. */
@@ -11,7 +11,10 @@ function runner(key: string, owner?: Person) {
return { key, sock, owner, sent };
}
const person = (slackUserId: string, gitName = 'A', gitEmail = 'a@x'): Person => ({ slackUserId, dir: slackUserId, gitName, gitEmail });
-const creds = (slackBotToken: string): HostCredentials => ({ slackBotToken, slackBotUserId: 'B', claudeOAuthToken: 'c' });
+const creds = (slackBotToken: string): HostCredentials => ({ slackBotToken, slackBotUserId: 'B' });
+const model = (profile: string): RunnerModel => ({ profile, key: 'k', harness: {}, endpoint: { unixSocket: '/s' }, placeholder: 'ph' });
+/** model-access.ts's shape: Slack's fields, plus the session's model (a spare's is key ''). */
+const shaped = (key: string, c: HostCredentials): HostCredentials => ({ ...c, model: model(key || 'spare') });
function setup() {
const a = runner('a', person('U1'));
@@ -21,7 +24,7 @@ function setup() {
const org = gatewayUpdates({
runners: () => [a],
spares: () => [spare],
- forRunner: (key, c) => (key === 'a' ? { ...c, claudeOAuthToken: undefined, claudeSubscription: { owner: 'U1', fingerprint: 'f' } } : c),
+ forRunner: shaped,
fillPool: () => filled++,
prepare: (p) => prepared.push(p),
});
@@ -29,13 +32,13 @@ function setup() {
}
describe('gateway updates (welcome, credentials, people)', () => {
- it('welcome: credentials to runners shaped per session, to spares as they are, then the pool fills', () => {
+ it('welcome: credentials to runners and spares shaped per session, then the pool fills', () => {
const t = setup();
t.org.welcome({ t: 'welcome', protocol: 1, credentials: creds('xoxb'), people: [person('U1')] });
expect(t.org.creds?.slackBotToken).toBe('xoxb');
expect(t.org.people.map((p) => p.slackUserId)).toEqual(['U1']);
- expect(t.a.sent).toEqual([{ t: 'credentials', credentials: { slackBotToken: 'xoxb', slackBotUserId: 'B', claudeSubscription: { owner: 'U1', fingerprint: 'f' } } }]);
- expect(t.spare.sent).toEqual([{ t: 'credentials', credentials: creds('xoxb') }]);
+ expect(t.a.sent).toEqual([{ t: 'credentials', credentials: { slackBotToken: 'xoxb', slackBotUserId: 'B', model: model('a') } }]);
+ expect(t.spare.sent).toEqual([{ t: 'credentials', credentials: shaped('', creds('xoxb')) }]);
expect(t.fill()).toBe(1);
});
@@ -50,8 +53,8 @@ describe('gateway updates (welcome, credentials, people)', () => {
const t = setup();
t.org.credentials({ t: 'credentials', credentials: creds('new') });
expect(t.org.creds?.slackBotToken).toBe('new');
- expect(t.a.sent[0]).toMatchObject({ t: 'credentials', credentials: { slackBotToken: 'new', claudeSubscription: { owner: 'U1' } } });
- expect(t.spare.sent).toEqual([{ t: 'credentials', credentials: creds('new') }]);
+ expect(t.a.sent[0]).toMatchObject({ t: 'credentials', credentials: { slackBotToken: 'new', model: { profile: 'a' } } });
+ expect(t.spare.sent).toEqual([{ t: 'credentials', credentials: shaped('', creds('new')) }]);
expect(t.fill()).toBe(1);
});
diff --git a/computer/src/host/gateway-updates.ts b/computer/src/host/gateway-updates.ts
index ba649335..e297088f 100644
--- a/computer/src/host/gateway-updates.ts
+++ b/computer/src/host/gateway-updates.ts
@@ -5,8 +5,8 @@
//
// Invariants:
// - Credentials live in memory only and reach runners over their sockets,
-// shaped per session by `forRunner` (subscriptions.ts); spares take them as
-// they are, since they serve no session yet.
+// shaped per session by `forRunner` (model-access.ts: Slack's, plus the
+// session's model, never a model credential); a spare's as key ''.
// - A multi-workspace gateway's welcome has only the shared agent credentials
// (each delivery brings its workspace's Slack installation): its empty Slack
// values must not replace live runners' after a host reconnect.
@@ -25,7 +25,7 @@ export interface UpdateTargets {
spares(): Iterable<{ sock: net.Socket }>;
/** Credentials as `key`'s runner gets them. */
forRunner(key: string, c: HostCredentials): HostCredentials | undefined;
- /** Spares start once there is a Claude credential to park with. */
+ /** Spares start once there is a model route to park with. */
fillPool(): void;
/** A member the gateway just learned: prepare their workspace (a no-op without workspaces). */
prepare(p: Person): void;
@@ -52,7 +52,7 @@ export function gatewayUpdates(o: UpdateTargets) {
creds = m.credentials;
people = m.people;
if (creds.slackBotToken) for (const r of o.runners()) push(r, creds);
- for (const r of o.spares()) send(r.sock, { t: 'credentials', credentials: creds } satisfies HostToRunner);
+ for (const r of o.spares()) push({ key: '', sock: r.sock }, creds);
o.fillPool();
},
credentials(m: Credentials) {
diff --git a/computer/src/host/launch.test.ts b/computer/src/host/launch.test.ts
index 2ead8c43..20fece27 100644
--- a/computer/src/host/launch.test.ts
+++ b/computer/src/host/launch.test.ts
@@ -33,10 +33,10 @@ describe('launchCommand', () => {
};
it('pins every runner variable, empty when the host has none', () => {
- const vars = setenv({ PATH: '/bin', SP_MODEL_SOCKET: '/run/m.sock' });
+ const vars = setenv({ PATH: '/bin', SP_COMPACT_AT: '0.8' });
for (const k of RUNNER_ENV) expect(vars.has(k), k).toBe(true);
expect(vars.get('PATH')).toBe('/bin');
- expect(vars.get('SP_MODEL_SOCKET')).toBe('/run/m.sock');
+ expect(vars.get('SP_COMPACT_AT')).toBe('0.8');
// Empty, not absent: absent would let the user manager's environment (set by any session) through.
expect(vars.get('SP_CODEX_BIN')).toBe('');
});
@@ -56,8 +56,8 @@ describe('launchCommand', () => {
describe('dropEmpty', () => {
it('unsets runner variables the host set empty, and only those', () => {
- const env: NodeJS.ProcessEnv = { SP_CODEX_BIN: '', SP_MODEL_SOCKET: '/m', OTHER: '' };
+ const env: NodeJS.ProcessEnv = { SP_CODEX_BIN: '', SP_COMPACT_AT: '0.8', OTHER: '' };
dropEmpty(env);
- expect(env).toEqual({ SP_MODEL_SOCKET: '/m', OTHER: '' });
+ expect(env).toEqual({ SP_COMPACT_AT: '0.8', OTHER: '' });
});
});
diff --git a/computer/src/host/launch.ts b/computer/src/host/launch.ts
index a6425d1e..d3785d48 100644
--- a/computer/src/host/launch.ts
+++ b/computer/src/host/launch.ts
@@ -89,3 +89,21 @@ export async function launch(rs: RunnerSpec, how: LaunchMode | string, env: Node
spawn(c.cmd, c.args, { cwd: workingDirectory(rs, env), env: c.env, detached: true, stdio: ['ignore', fd, fd] }).unref();
closeSync(fd);
}
+
+/**
+ * Whether runner `id`'s systemd unit still exists (work 097: the model proxy's
+ * binding for a caller whose unit is gone is released). Detached runners have
+ * no unit, and any doubt (systemctl failing) answers true: a binding is never
+ * released on a guess.
+ */
+export async function unitExists(id: string, how: LaunchMode | string, env: NodeJS.ProcessEnv): Promise<boolean> {
+ if (how !== 'systemd') return true;
+ const as = runnerUser(env);
+ const [cmd, ...args] = [...(as?.sudo ?? []), 'systemctl', '--user', 'show', '-p', 'LoadState', '--value', `sp-runner-${id}.service`];
+ try {
+ const { stdout } = await promisify(execFile)(cmd, args, { env: { ...env, ...as?.env } as NodeJS.ProcessEnv });
+ return stdout.trim() !== 'not-found';
+ } catch {
+ return true;
+ }
+}
diff --git a/computer/src/host/main.ts b/computer/src/host/main.ts
index 3ab73808..1a45a116 100644
--- a/computer/src/host/main.ts
+++ b/computer/src/host/main.ts
@@ -16,7 +16,8 @@
// [SP_TELEMETRY_URL] telemetry collector (work 054); unset: telemetry is validated and discarded
// [SP_TELEMETRY_CREDENTIAL] the collector credential the gateway signed for this host; a `welcome` renews it
// [SP_REGION] [SP_SUBSTRATE] telemetry dimensions (`westus2`, `vm`)
-// [SP_MODEL_PROXY] oc-modelproxy's control socket (work 077, subscriptions.ts); unset: every session managed
+// SP_MODEL_PROXY the model proxy's control socket (work 097, model-access.ts); unset: the proxy is down, no session starts
+// [SP_MODEL_SOCKET=/run/oc-modelproxy/api.sock] where runners reach the proxy's API (sent to them, C4)
// [SP_RUNNER_USER=agent] run runners as this user, through sudo (work 077, runner-user.ts); the host then runs as another
// [SP_RUNNER_PATH=...] the PATH runners and workspace commands get then (the host's own has no agent-owned directory)
// node --import tsx src/host/main.ts
@@ -39,22 +40,8 @@ import { existsSync, mkdirSync } from 'node:fs';
import { HOST_DATA, HOST_RUN, HOST_TOKEN_SOCKET, PROTOCOL_VERSION, RUNNER_TOKEN_DIR } from '../protocol.js';
import { codexBin } from '../runner-env.js';
import { prereadCodex } from './codex-preread.js';
-import type {
- Delivery,
- GatewayToHost,
- HarnessName,
- HostCredentials,
- HostToGateway,
- ModelRoute,
- HostToRunner,
- Person,
- RunnerToHost,
- SessionReport,
- SessionSecret,
- SessionSpec,
- SpareReport,
- TraceContext,
-} from '../protocol.js';
+import type { Delivery, GatewayToHost, HarnessName, HostCredentials, HostToGateway, ModelRoute, HostToRunner, Person,
+ RunnerToHost, SessionReport, SessionSecret, SessionSpec, SpareReport, TraceContext } from '../protocol.js';
import {
applyGatewayDefinition,
checkoutRepos,
@@ -78,7 +65,6 @@ import { closed, launchRunner, rediscover, retire } from './runner-sockets.js';
import { adoption, type First } from './adoption.js';
import { Pool } from './pool.js';
import { claimSpare } from './claim.js';
-import { credentialFingerprint } from '../credential-fingerprint.js';
import { tokenRelay } from './tokens.js';
import { hostPreviews } from './previews.js';
import { startHostTelemetry, workspaceTelemetry } from './telemetry.js';
@@ -86,7 +72,8 @@ import { diskReport, hostSampler } from './sample.js';
import { type ColdStart, decidePath, type Forwarded, forwardTrace, loadForwarded, runnerGone, saveForwarded, traceFields } from './trace.js';
import type { Dimensions } from '../telemetry/envelope.js';
import { assignedIdentity, codeVersion, identityFile, loadIdentity, saveIdentity } from './identity.js';
-import { createHostModelAccess } from './model-access-impl.js';
+import { hostModelAccess, PROXY_DOWN } from './model-access.js';
+import { unitExists } from './launch.js';
import { runnerUser } from './runner-user.js';
import { gatewayLink } from './gateway-link.js';
import { gatewayUpdates } from './gateway-updates.js';
@@ -121,8 +108,9 @@ observeWorkspaces(workspaceTelemetry(tm, () => forkContext.getStore()));
/** The organization's credentials and people, as the gateway last sent them. */
const org = gatewayUpdates({ runners: () => runners.values(), spares: () => pool.spares, forRunner: (key, c) => subs.forRunner(key, c),
fillPool: () => fillPool(), prepare: (p) => workspacesEnabled() && prepareInBackground(p) });
-const subs = createHostModelAccess({ controlSocket: env.SP_MODEL_PROXY || undefined, dataDir: HOST_DATA, toGateway, tm, // the seam: model-access.ts (work 097)
- runner: (key) => runners.get(key), rehello: () => link.redial(), codexBin: codexBin(env) });
+const subs = hostModelAccess({ controlSocket: env.SP_MODEL_PROXY || undefined, modelSocket: env.SP_MODEL_SOCKET || undefined, single: LAUNCH !== 'systemd',
+ toGateway, tm, runner: (key) => runners.get(key), creds: () => org.creds, exit: switchRunner, unitExists: (id) => unitExists(id, LAUNCH, env),
+ rehello: () => link.redial(), codexBin: codexBin(env) });
// ---------------------------------------------------------------- runners
@@ -141,6 +129,8 @@ interface Runner {
lastDelivery: number;
connectedAt: number;
exiting?: boolean;
+ /** Told to exit for its session's new route (model-access.ts): a delivery waits for it to go and starts another. */
+ switching?: boolean;
/** Set by a launch, taken by the delivery that caused it: the path is not `warm`. */
cold?: ColdStart;
/** The last trace forwarded (also in `<key>.trace.json`), for `turn.abandoned`. */
@@ -160,11 +150,15 @@ const pool = new Pool<Runner>({
});
/** Every connected runner: the sessions' and the spares. */
const allRunners = () => [...runners.values(), ...pool.spares];
-const fillPool = () => !stopping && pool.fill(!!credentialFingerprint(org.creds));
+const fillPool = () => !stopping && pool.fill(subs.canSpare());
function exitRunner(sock: net.Socket) {
send(sock, { t: 'exit' } satisfies HostToRunner);
sock.end();
}
+/** A busy one is only told to go (its turn ends at its next model call); an idle one is closed as well. */
+function switchRunner(key: string, r = runners.get(key)) {
+ if (r) (r.switching = true), r.report?.status === 'busy' ? send(r.sock, { t: 'exit' } satisfies HostToRunner) : exitRunner(r.sock);
+}
/** Its session's epoch moved on (api-host `epoch`): end its turn now, then exit; killed after 10 s. */
const retireRunner = async (id: string, r = [...runners.values()].find((x) => x.id === id)) =>
r && ((r.exiting = true), retire(r.sock, socketFor(r.id), () => void call(r, { t: 'stop' }, 10_000).catch(() => {})));
@@ -189,7 +183,7 @@ function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean
const take = (m?: First) => {
if (m?.t === 'report') (r.key = m.report.key), (r.harness ??= m.report.harness);
if (m?.t === 'spare') r.spare = m.spare;
- if (r.key) register(r);
+ if (r.key) register(r, !!o.verify);
else {
pool.add(r);
pool.changed(r);
@@ -211,28 +205,25 @@ function adopt(id: string, sock: net.Socket, o: { key?: string; verify?: boolean
}
/** The runner serves its session from now on; one already there for it (found twice after a restart) is told to go. */
-function register(r: Runner) {
+function register(r: Runner, found = false) {
const old = runners.get(r.key);
if (old && old !== r) exitRunner(old.sock);
runners.set(r.key, r);
- subs.routes.registered(r.key, r.id, r.harness);
+ subs.registered(r.key, r.id, r.harness, found);
r.forwarded ??= loadForwarded(r.key);
api.up(r.id);
}
function runnerClosed(r: Runner) {
for (const c of r.calls.values()) c({ ok: false, error: 'runner gone' });
- if (!stopping) api.down(r.id);
+ if (!stopping) api.down(r.id), subs.closed(r.key, r.id);
if (!r.key) {
pool.gone(r);
fillPool();
return;
}
if (runners.get(r.key) !== r) return;
- if (!stopping) {
- runnerGone(tm, r);
- subs.routes.closed(r.key, r.id);
- }
+ if (!stopping) runnerGone(tm, r);
runners.delete(r.key);
if (r.report && r.report.status !== 'stopped') toGateway({ t: 'session', report: { ...r.report, status: 'error', error: 'runner exited' } });
}
@@ -295,20 +286,21 @@ function ensureRunner(spec: SessionSpec, f: Fields, first?: HostCredentials): Pr
}
async function startRunner(spec: SessionSpec, f: Fields, first?: HostCredentials): Promise<Runner> {
+ if (!subs.up) throw new Error(PROXY_DOWN);
let existing = spec.forkPath && existsSync(spec.forkPath) && forkComplete(spec.forkPath) ? spec.forkPath : undefined;
// A new session in a prepared workspace may take a spare (work 069); a resumed one starts cold, to resume.
- // Claude takes one on the managed route, whose credential spares park with; Codex (work 082) on its ChatGPT subscription.
+ // Claude takes one of its route's spare kind (C6); Codex (work 082) any.
const codex = spec.harness === 'codex';
- if (pool.enabled && !spec.sdkSessionId && workspacesEnabled() && workspacePrepared(spec.owner)
- && subs.routes.mode(spec.key) === (codex ? 'subscription' : 'managed')) {
+ if (pool.enabled && !spec.sdkSessionId && workspacesEnabled() && workspacePrepared(spec.owner) && subs.canSpare()) {
const t0 = Date.now();
const got = await claimSpare<Runner>({
// Refill as soon as the spare is ours: the fork and the claim take seconds, in which another session may arrive.
- take: () => { const t = pool.take(credentialFingerprint(first) ?? credentialFingerprint(org.creds), codex); fillPool(); return t; },
+ take: () => { const t = pool.take(subs.kind(spec.key, 'claude'), codex); fillPool(); return t; },
fork: async () => existing ?? forkContext.run(f, () => forkFor(tm, spec, f)),
claim: async (r, forkPath) => {
- // Claude's credential goes first, as its parked Claude Code has it; a Codex claim drops the spare's, so the session's follow.
- const c = codex ? (first ?? subs.forRunner(spec.key, org.creds, 'codex')) : first;
+ // Bound to the session first (C6); Claude's credentials go before the claim, Codex's after (its claim drops the spare's).
+ await subs.claim(r.id, spec.key, spec.harness ?? 'claude');
+ const c = first ?? subs.forRunner(spec.key, org.creds, spec.harness ?? 'claude');
if (c && !codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
await call(r, { t: 'claim', session: { ...spec, forkPath }, api: await api.mint(spec, r.id) }, 5000);
if (c && codex) send(r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
@@ -349,10 +341,12 @@ async function startRunner(spec: SessionSpec, f: Fields, first?: HostCredentials
return r;
}
-/** Start a spare for the pool: a runner with no session, which parks a Claude Code once it has credentials (a Codex claim replaces it). */
+/** Start a spare for the pool, bound to `models.claude` first: a runner with no session, which parks a Claude Code once it has credentials. */
async function launchSpare() {
const id = newRunnerId();
- await adopt(id, await launchRunner({ id, socket: socketFor(id), version: VERSION }, launchOpts));
+ await subs.spare(id);
+ await launchRunner({ id, socket: socketFor(id), version: VERSION }, launchOpts).then((sock) => adopt(id, sock))
+ .catch((e) => (subs.closed('', id), Promise.reject(e)));
tm.emit('pool.spare_started', { data: { launch_mode: LAUNCH } });
}
@@ -373,7 +367,7 @@ const link = gatewayLink({
url: () => identity.gatewayUrl,
token: () => identity.token,
hello: () => ({ t: 'hello', protocol: PROTOCOL_VERSION, hostId: identity.hostId, version: VERSION,
- sessions: [...runners.values()].flatMap((r) => (r.report ? [r.report] : [])), features: subs.features(), journals: api.journals() }),
+ sessions: [...runners.values()].flatMap((r) => (r.report ? [r.report] : [])), profiles: subs.profiles(), journals: api.journals() }),
message: (m) => void onGateway(m).catch((e) => log.error('gateway message', m.t, e)),
});
function toGateway(m: HostToGateway) {
@@ -394,7 +388,7 @@ async function onGateway(m: GatewayToHost) {
() => toGateway({ t: 'reply', id, ok: true }),
(e) => toGateway({ t: 'reply', id, ok: false, error: String(e?.message ?? e) }),
);
- if (subs.onGateway(m, org.creds)) return; // `model`, `probe` (work 077)
+ if (subs.onGateway(m)) return; // `model`, `model-request` (work 097); reads `models` from `welcome` and `credentials`
if (await api.onGateway(m)) return; // `start`, `api`, `journal-ack`, `access`, `revoked` (work 084, api-host.ts)
switch (m.t) {
case 'welcome':
@@ -474,13 +468,11 @@ async function deliver(spec: SessionSpec, msg: Delivery, delivered: HostCredenti
const deliveryCredentials = await subs.delivered(spec.key, delivered, rx.model, spec.harness);
for (let attempt = 0; ; attempt++) {
let r = await ensureRunner(spec, rx.f, deliveryCredentials);
- if ((r.harness ?? 'claude') !== (spec.harness ?? 'claude')) {
- // On the other harness still (busy past the switch's wait, or started before it): never given this delivery.
- if (attempt) throw new Error(`session ${spec.key}: its runner is still on ${r.harness ?? 'claude'}; try again when its turn ends`);
- // A busy one is only told to go (its turn ends at its next model call); an idle one is closed as well. At most 5 s.
- if (r.report?.status === 'busy') send(r.sock, { t: 'exit' } satisfies HostToRunner);
- else exitRunner(r.sock);
- await closed(r.sock);
+ if (r.switching || (r.harness ?? 'claude') !== (spec.harness ?? 'claude')) {
+ // On the other harness or route still (busy past the switch's wait, or started before it): never given this delivery.
+ if (attempt) throw new Error(`session ${spec.key}: its runner is still on its previous agent or model; try again when its turn ends`);
+ switchRunner(spec.key, r);
+ await closed(r.sock); // at most 5 s
continue;
}
// Reported `stopped` (idle exit, !restart): let it go, then start a new one from the current release.
@@ -488,6 +480,7 @@ async function deliver(spec: SessionSpec, msg: Delivery, delivered: HostCredenti
await closed(r.sock);
r = await ensureRunner(spec, rx.f, deliveryCredentials);
}
+ await subs.ready(r.key); // its bind answered: its first model request finds it
const cold = r.cold;
r.cold = undefined;
// A Cloudflare Durable Object gateway supplies the Slack installation for
@@ -577,6 +570,7 @@ const emitSample = () =>
since_gateway_message_s: link.seenAt ? Math.round((Date.now() - link.seenAt) / 1000) : undefined,
telemetry_spooled_bytes: telemetry.spooledBytes,
telemetry_dropped: telemetry.dropped,
+ model_proxy_down_s: subs.downS(),
}) });
emitSample();
setInterval(emitSample, 60_000).unref();
diff --git a/computer/src/host/model-access-impl.ts b/computer/src/host/model-access-impl.ts
deleted file mode 100644
index 7f2bee4e..00000000
--- a/computer/src/host/model-access-impl.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// The seam for the host's model access: host/main.ts imports
-// `createHostModelAccess` from here and nothing else about it. This build
-// runs every session on the organization's managed credentials
-// (model-access.ts); a build with subscription routing replaces this file.
-
-import { type HostModelAccess, type HostModelAccessDeps, noHostModelAccess } from './model-access.js';
-
-export function createHostModelAccess(deps: HostModelAccessDeps): HostModelAccess {
- return noHostModelAccess(deps);
-}
diff --git a/computer/src/host/model-access.test.ts b/computer/src/host/model-access.test.ts
index cf1402cf..c367bb7b 100644
--- a/computer/src/host/model-access.test.ts
+++ b/computer/src/host/model-access.test.ts
@@ -1,116 +1,368 @@
+// The host's model access (design C3, C4, C6) against the real model proxy:
+// computer/modelproxy built into a temp directory and run on test profiles
+// whose upstream nothing listens on. What the proxy holds is read from the
+// hello a second binder gets, which also replaces the host's connection, so
+// every peek exercises a re-hello. The relays of observed and event frames
+// use the proxy's golden frames. Skipped when there is no Go toolchain.
+
+import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import net from 'node:net';
-import { mkdtempSync, readdirSync, readFileSync, statSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { describe, expect, it } from 'vitest';
-import type { GatewayToHost, HostCredentials, HostToGateway, HostToRunner } from '../protocol.js';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import type { GatewayToHost, HarnessName, HostCredentials, HostToGateway, HostToRunner, ModelRoute } from '../protocol.js';
import type { Telemetry } from '../telemetry/emitter.js';
-import { type HostModelAccessDeps, noHostModelAccess } from './model-access.js';
-import { createHostModelAccess } from './model-access-impl.js';
+import { lines } from '../ipc.js';
+import { spareKind } from '../model-key.js';
+import { hostModelAccess, NO_MODEL_CREDENTIAL, noProfile, proxyRefused, SWITCHING, type HostModelAccessDeps } from './model-access.js';
+
+const PROXY_SRC = path.resolve(import.meta.dirname, '../../modelproxy');
+const GO = ['go', '/usr/local/go/bin/go'].find((g) => {
+ try {
+ return execFileSync(g, ['version'], { stdio: 'pipe' }) && true;
+ } catch {
+ return false;
+ }
+});
+
+const claudeKey = { tokenEnv: 'ANTHROPIC_API_KEY' };
+const profile = (harness: object) => ({ upstream: 'https://127.0.0.1:1', routes: { 'GET /v1/models': {} }, set: { 'X-Api-Key': '{token}' }, harness });
+const PROFILES = {
+ 'claude-a': profile({ claude: claudeKey }),
+ 'claude-b': profile({ claude: claudeKey }),
+ 'claude-c': profile({ claude: { tokenEnv: 'ANTHROPIC_AUTH_TOKEN' } }),
+ 'codex-only': profile({ codex: {} }),
+};
+const route = (p: string, token = 'sk-test-1', key = `${p}-key`): ModelRoute => ({ mode: 'profile', profile: p, vars: { token }, key });
+// A field no runner may get (protocol 4's Claude credential), as an older gateway would still send it.
+const creds = { slackBotToken: 'xoxb', slackBotUserId: 'B', claudeOAuthToken: 'never-forwarded' } as HostCredentials;
+const welcome = (models: Record<string, ModelRoute>) => ({ t: 'welcome', protocol: 5, credentials: creds, people: [], models }) as unknown as GatewayToHost;
+
+let dir: string;
+let bin: string;
+let proxy: ChildProcess | undefined;
+let cleanup: (() => unknown)[] = [];
-const tm = { emit() {} } as unknown as Telemetry;
-const creds: HostCredentials = { slackBotToken: 'xoxb', slackBotUserId: 'B', claudeOAuthToken: 'org', anthropicApiKey: 'k', anthropicBaseUrl: 'https://x' };
-const slackOnly = { slackBotToken: 'xoxb', slackBotUserId: 'B' };
+async function startProxy() {
+ const control = path.join(dir, 'control.sock');
+ rmSync(control, { force: true });
+ proxy = spawn(bin, ['-profiles', path.join(dir, 'profiles'), '-api-socket', path.join(dir, 'api.sock'), '-control-socket', control,
+ '-bindings-file', '', '-hold-timeout', '1s', '-drain-timeout', '1s'], { stdio: 'ignore' });
+ await vi.waitFor(() => expect(existsSync(control)).toBe(true), { timeout: 5000 });
+}
+async function stopProxy() {
+ const p = proxy;
+ proxy = undefined;
+ if (!p || p.exitCode !== null) return;
+ await new Promise((r) => (p.once('exit', r), p.kill('SIGKILL')));
+}
+
+/** Every host model access under test that is not stopped: how often it dialled, and whether it is up. */
+const hosts = new Set<{ dials: number; up: () => boolean }>();
+
+/**
+ * What the proxy holds, from the hello a new binder gets. That replaces each live host's connection:
+ * resolves once every one dialled again and is up (its re-sent binds are on their way).
+ */
+async function peek(): Promise<{ caller: string; sessionKey: string; mode: string; profile?: string; key?: string }[]> {
+ const before = [...hosts].map((h) => [h, h.dials] as const);
+ const bindings = await new Promise<{ caller: string; sessionKey: string; mode: string; profile?: string; key?: string }[]>((resolve, reject) => {
+ const s = net.createConnection(path.join(dir, 'control.sock'));
+ s.on('error', reject);
+ lines(s, (m) => m.t === 'hello' && (s.destroy(), resolve(m.bindings)));
+ });
+ for (const [h, n] of before) if (hosts.has(h)) await vi.waitFor(() => expect(h.dials > n && h.up()).toBe(true), { timeout: 8000 });
+ return bindings;
+}
-/** A runner's end as the host sees it: a socket whose writes are kept as parsed messages. */
-function runner(harness?: 'codex') {
+interface FakeRunner { id: string; sock: net.Socket; harness?: HarnessName; sent: HostToRunner[] }
+function fakeRunner(id: string, harness?: HarnessName): FakeRunner {
const sent: HostToRunner[] = [];
const sock = new net.Socket();
Object.assign(sock, { writable: true, write: (d: string) => (sent.push(JSON.parse(d)), true) });
- return { sock, sent, report: undefined, harness };
+ return { id, sock, harness, sent };
}
-function deps(live?: ReturnType<typeof runner>) {
- const frames: HostToGateway[] = [];
- const d: HostModelAccessDeps = { dataDir: mkdtempSync(path.join(os.tmpdir(), 'ma-')), toGateway: (m) => frames.push(m), tm, runner: () => live, rehello() {} };
- return { d, frames };
+function setup(o: Partial<HostModelAccessDeps> = {}) {
+ const runners = new Map<string, FakeRunner>();
+ const out: HostToGateway[] = [];
+ const emit = vi.fn();
+ const deps = {
+ controlSocket: path.join(dir, 'control.sock'),
+ modelSocket: '/run/test/api.sock',
+ toGateway: (m: HostToGateway) => out.push(m),
+ runner: (key: string) => runners.get(key),
+ creds: () => creds,
+ exit: vi.fn(),
+ unitExists: vi.fn(async () => true),
+ rehello: vi.fn(),
+ tm: { emit } as unknown as Telemetry,
+ ...o,
+ };
+ const host = { dials: 0, up: () => a.up };
+ const a = hostModelAccess({ ...deps, proxy: { connect: (p) => (host.dials++, net.createConnection(p)) } });
+ hosts.add(host);
+ const stop = a.stop;
+ a.stop = () => (hosts.delete(host), stop());
+ cleanup.push(() => a.stop());
+ /** A runner `id` on `harness` serves `key` and is bound. */
+ const register = async (key: string, id: string, harness: HarnessName = 'claude') => {
+ const r = fakeRunner(id, harness);
+ runners.set(key, r);
+ a.registered(key, id, harness);
+ await a.ready(key);
+ return r;
+ };
+ const up = () => vi.waitFor(() => expect(a.up).toBe(true), { timeout: 8000 });
+ return { a, deps, runners, out, emit, register, up };
}
-describe('noHostModelAccess (work 097): the public build, every session managed', () => {
- it('advertises nothing, calls every route managed, and never throws', async () => {
- const { d, frames } = deps();
- const a = noHostModelAccess(d);
- expect(a.features()).toBeUndefined();
- expect(a.routes.mode('k')).toBe('managed');
- a.routes.registered('k', 'id', 'claude');
- a.routes.closed('k', 'id');
- a.stop();
- expect(await a.delivered('k', creds, undefined)).toBe(creds);
- expect(await a.delivered('k', creds, { mode: 'managed' }, 'claude')).toBe(creds);
- expect(a.forRunner('k', creds)).toBe(creds);
- expect(a.forRunner('k', undefined)).toBeUndefined();
- expect(frames).toEqual([]);
+const held = async (caller: string) => (await peek()).find((b) => b.caller === caller);
+
+describe.skipIf(!GO)('host model access against the real model proxy', () => {
+ beforeAll(async () => {
+ dir = mkdtempSync(path.join(os.tmpdir(), 'hma-'));
+ bin = path.join(dir, 'oc-modelproxy');
+ execFileSync(GO!, ['build', '-o', bin, '.'], { cwd: PROXY_SRC, env: { ...process.env, CGO_ENABLED: '0' }, stdio: 'pipe' });
+ mkdirSync(path.join(dir, 'profiles'));
+ writeFileSync(path.join(dir, 'profiles', 'test.json'), JSON.stringify(PROFILES));
+ await startProxy();
+ }, 180_000);
+ afterEach(async () => {
+ for (const c of cleanup.reverse()) await c();
+ cleanup = [];
+ if (!proxy) await startProxy();
+ });
+ afterAll(async () => {
+ await stopProxy();
+ rmSync(dir, { recursive: true, force: true });
});
- it('never hands a Codex runner the organization’s Claude credentials', async () => {
- const { d } = deps(runner('codex'));
- const a = noHostModelAccess(d);
- expect(await a.delivered('k', creds, undefined, 'codex')).toEqual(slackOnly);
- expect(a.forRunner('k', creds, 'codex')).toEqual(slackOnly);
- expect(a.forRunner('k', creds)).toEqual(slackOnly); // its live runner is Codex
- expect(a.forRunner('k', undefined, 'codex')).toEqual({ slackBotToken: '', slackBotUserId: '' });
+ it('bind: a registered runner is bound to its session route, `model-bound` is relayed, and the runner gets C4 and no value', async () => {
+ const t = setup();
+ await t.up();
+ t.a.onGateway(welcome({ claude: route('claude-a') }));
+ await t.register('s1', 'r1');
+ expect(t.out).toContainEqual({ t: 'model-bound', sessionKey: 's1', mode: 'profile', profile: 'claude-a', key: 'claude-a-key' });
+ expect(await held('r1')).toEqual({ caller: 'r1', sessionKey: 's1', mode: 'profile', profile: 'claude-a', key: 'claude-a-key' });
+ const c = t.a.forRunner('s1', creds)!;
+ expect(c).toEqual({ slackBotToken: 'xoxb', slackBotUserId: 'B', model: { profile: 'claude-a', key: 'claude-a-key', harness: claudeKey,
+ endpoint: { unixSocket: '/run/test/api.sock' }, placeholder: 'ssh-placeholder' } });
+ expect(JSON.stringify(c)).not.toMatch(/sk-test|never-forwarded/);
+ expect(t.a.profiles()?.map((p) => p.name)).toEqual(['claude-a', 'claude-b', 'claude-c']); // codex-only: no Codex binary
});
- it('answers a probe `proxy_unavailable`, drops a subscription route, and leaves other frames to the host', async () => {
- const live = runner();
- const { d, frames } = deps(live);
- const a = noHostModelAccess(d);
- expect(a.onGateway({ t: 'probe', id: 'p1', token: 't' } as GatewayToHost, creds)).toBe(true);
- expect(frames).toEqual([{ t: 'probed', id: 'p1', error: 'proxy_unavailable' }]);
- const sub: GatewayToHost = { t: 'model', sessionKey: 'k', model: { mode: 'subscription', owner: 'U1', fingerprint: 'fp', token: 'tok' } };
- expect(a.onGateway(sub, creds)).toBe(true);
- expect(live.sent).toEqual([]); // nothing pushed to the runner for a route it cannot take
- expect(a.onGateway({ t: 'credentials', credentials: creds } as GatewayToHost, creds)).toBe(false);
- expect(a.routes.mode('k')).toBe('managed');
- expect(await a.delivered('k', creds, { mode: 'subscription', owner: 'U1', fingerprint: 'fp', token: 'tok' })).toBe(creds);
- // A managed push re-sends the runner what it was delivered (the hosted build does: a push back to managed carries them).
- expect(a.onGateway({ t: 'model', sessionKey: 'k', model: { mode: 'managed' } }, slackOnly)).toBe(true);
- expect(live.sent).toEqual([{ t: 'credentials', credentials: creds }]);
- expect(frames).toHaveLength(1);
+ it('refuse: no route, an unknown profile, a profile without the harness, and a refuse route are bound as refusals, and the runner told why', async () => {
+ const t = setup();
+ await t.up();
+ const none = await t.register('none', 'r-none');
+ expect(t.out).toContainEqual({ t: 'model-bound', sessionKey: 'none', mode: 'refuse' });
+ t.a.onGateway({ t: 'model', sessionKey: 'gone', model: route('no-such-profile') });
+ await t.register('gone', 'r-gone');
+ t.a.onGateway({ t: 'model', sessionKey: 'codex', model: route('claude-a') });
+ await t.register('codex', 'r-codex', 'codex');
+ t.a.onGateway({ t: 'model', sessionKey: 'paused', model: { mode: 'refuse', reason: 'paused' } });
+ await t.register('paused', 'r-paused');
+ const b = await peek();
+ for (const caller of ['r-none', 'r-gone', 'r-codex', 'r-paused']) expect(b.find((x) => x.caller === caller)?.mode).toBe('refuse');
+ expect(t.a.forRunner('none', creds)).toEqual({ slackBotToken: 'xoxb', slackBotUserId: 'B', model: { refused: NO_MODEL_CREDENTIAL } });
+ expect(none.sent.at(-1)).toEqual({ t: 'credentials', credentials: { slackBotToken: 'xoxb', slackBotUserId: 'B', model: { refused: NO_MODEL_CREDENTIAL } } });
+ expect(t.a.forRunner('gone', creds)?.model).toEqual({ refused: noProfile('no-such-profile') });
+ expect(t.a.forRunner('codex', creds)?.model).toEqual({ refused: SWITCHING });
+ expect(t.a.forRunner('paused', creds)?.model).toEqual({ refused: 'paused' });
+ expect(t.deps.exit).not.toHaveBeenCalled();
+ expect(NO_MODEL_CREDENTIAL).toBe('No model credential is configured for this computer.');
});
-});
-describe('the seam’s implementation', () => {
- it('createHostModelAccess builds something of the interface’s shape', () => {
- const { d } = deps();
- const a = createHostModelAccess(d);
- for (const k of ['features', 'delivered', 'forRunner', 'onGateway', 'stop'] as const) expect(typeof a[k]).toBe('function');
- for (const k of ['mode', 'registered', 'closed'] as const) expect(typeof a.routes[k]).toBe('function');
- a.stop();
+ it('a bind the proxy refuses is bound again as a refusal and reported as model.profile_refused', async () => {
+ const t = setup();
+ await t.up();
+ t.a.onGateway({ t: 'model', sessionKey: 's2', model: { mode: 'profile', profile: 'claude-a', vars: {}, key: 'k' } }); // missing_var
+ const r = await t.register('s2', 'r2');
+ await vi.waitFor(async () => expect((await held('r2'))?.mode).toBe('refuse'), { timeout: 8000 });
+ await vi.waitFor(() => expect(r.sent.at(-1)).toMatchObject({ t: 'credentials', credentials: { model: { refused: proxyRefused('missing_var') } } }));
+ expect(t.emit).toHaveBeenCalledWith('model.profile_refused', expect.objectContaining({ session_key: 's2', provider: 'claude-a', data: { caller: 'r2', code: 'missing_var' } }));
});
-});
-describe('the seam (work 097, 6b)', () => {
- const SRC = path.resolve(import.meta.dirname, '..');
- const HOSTED = ['host/subscriptions.ts', 'host/model-proxy.ts', 'host/model-routes.ts'];
- const IMPORT = /^\s*(?:import|export)\b[^'"]*?from\s+['"]([^'"]+)['"]/gm;
- function* walk(dir: string): Generator<string> {
- for (const name of readdirSync(dir)) {
- const p = path.join(dir, name);
- if (statSync(p).isDirectory()) yield* walk(p);
- else if (p.endsWith('.ts') && !p.endsWith('.test.ts')) yield p;
- }
- }
- /** Non-test files under src/ importing any of `targets` (paths under src/, .ts), as paths under src/. */
- const importers = (targets: string[]) => {
- const found: string[] = [];
- for (const file of walk(SRC)) {
- const text = readFileSync(file, 'utf8');
- for (const m of text.matchAll(IMPORT)) {
- if (!m[1].startsWith('.')) continue;
- const target = path.relative(SRC, path.resolve(path.dirname(file), m[1])).replace(/\.js$/, '.ts');
- if (targets.includes(target)) found.push(path.relative(SRC, file));
- }
+ it('rebind: an equal harness object rebinds in place and pushes C4; another exits the runner; a refusal only rebinds', async () => {
+ const t = setup();
+ await t.up();
+ t.a.onGateway(welcome({ claude: route('claude-a') }));
+ const r = await t.register('s3', 'r3');
+ await t.a.delivered('s3', creds, undefined, 'claude');
+ t.a.onGateway({ t: 'model', sessionKey: 's3', model: route('claude-b', 'sk-test-2') });
+ await t.a.ready('s3');
+ expect(await held('r3')).toMatchObject({ sessionKey: 's3', profile: 'claude-b', key: 'claude-b-key' });
+ expect(r.sent.at(-1)).toMatchObject({ t: 'credentials', credentials: { model: { profile: 'claude-b' } } });
+ expect(t.deps.exit).not.toHaveBeenCalled();
+
+ // The same route again changes nothing. (held() reconnects, and the host binds again: wait for that first.)
+ await t.a.ready('s3');
+ const n = r.sent.length;
+ await t.a.delivered('s3', creds, route('claude-b', 'sk-test-2'), 'claude');
+ expect(r.sent.length).toBe(n);
+
+ await t.up();
+ t.a.onGateway({ t: 'model', sessionKey: 's3', model: route('claude-c') });
+ await t.a.ready('s3');
+ expect(t.deps.exit).toHaveBeenCalledWith('s3');
+ expect(await held('r3')).toMatchObject({ profile: 'claude-c' });
+
+ await t.up();
+ t.a.onGateway({ t: 'model', sessionKey: 's3', model: { mode: 'refuse', reason: 'limit' } });
+ await t.a.ready('s3');
+ expect(t.deps.exit).toHaveBeenCalledTimes(1);
+ expect((await held('r3'))?.mode).toBe('refuse');
+ });
+
+ it('a `credentials` frame replaces `models` and rebinds the sessions that run on it, not those with their own route', async () => {
+ const t = setup();
+ await t.up();
+ t.a.onGateway(welcome({ claude: route('claude-a') }));
+ await t.register('on-models', 'r-m');
+ t.a.onGateway({ t: 'model', sessionKey: 'own', model: route('claude-a', 'sk-own', 'own-key') });
+ await t.register('own', 'r-o');
+ t.a.onGateway({ t: 'credentials', credentials: creds, models: { claude: route('claude-b') } });
+ await t.a.ready('on-models');
+ const b = await peek();
+ expect(b.find((x) => x.caller === 'r-m')).toMatchObject({ profile: 'claude-b' });
+ expect(b.find((x) => x.caller === 'r-o')).toMatchObject({ profile: 'claude-a', key: 'own-key' });
+ });
+
+ it('release: a closed runner is released; on hello, a listed caller whose unit is gone is released and a live one kept', async () => {
+ const t = setup({ unitExists: vi.fn(async (c: string) => c !== 'ghost') });
+ await t.up();
+ await t.register('s4', 'r4');
+ await t.register('ghost-session', 'ghost');
+ t.runners.delete('ghost-session');
+ t.a.stop(); // the host goes: its bindings stay with the proxy
+ await vi.waitFor(async () => expect((await peek()).map((b) => b.caller)).toEqual(expect.arrayContaining(['r4', 'ghost'])));
+
+ const u = setup({ unitExists: vi.fn(async (c: string) => c !== 'ghost') });
+ await u.up();
+ u.a.registered('s4', 'r4', 'claude', true); // found again: not bound until its route arrives
+ const callers = async () => (await peek()).map((b) => b.caller);
+ await vi.waitFor(async () => expect(await callers()).not.toContain('ghost'), { timeout: 8000 });
+ expect(await callers()).toContain('r4');
+ await u.up();
+ u.a.closed('s4', 'r4');
+ await vi.waitFor(async () => expect(await callers()).not.toContain('r4'), { timeout: 8000 });
+ }, 30_000);
+
+ it('a runner found after a restart keeps its binding until a delivery brings its route', async () => {
+ const t = setup();
+ await t.up();
+ await t.register('s5', 'r5');
+ t.a.stop();
+ const u = setup();
+ await u.up();
+ u.a.onGateway(welcome({ claude: route('claude-a') }));
+ u.runners.set('s5', fakeRunner('r5'));
+ u.a.registered('s5', 'r5', 'claude', true);
+ expect(u.a.forRunner('s5', creds)?.model).toBeUndefined();
+ expect((await held('r5'))?.mode).toBe('refuse'); // the old binding, untouched by `models`
+ await u.up();
+ const c = await u.a.delivered('s5', creds, route('claude-b'), 'claude');
+ expect(c?.model).toMatchObject({ profile: 'claude-b' });
+ expect(await held('r5')).toMatchObject({ profile: 'claude-b' });
+ });
+
+ it('re-hello: a proxy that restarts empty gets every held bind again; while down the host advertises no profiles', async () => {
+ const t = setup();
+ await t.up();
+ t.a.onGateway(welcome({ claude: route('claude-a') }));
+ await t.register('s6', 'r6');
+ expect(t.deps.rehello).toHaveBeenCalledTimes(1);
+ await stopProxy();
+ await vi.waitFor(() => expect(t.a.up).toBe(false));
+ expect(t.a.profiles()).toBeUndefined();
+ expect(t.deps.rehello).toHaveBeenCalledTimes(2);
+ expect(t.a.canSpare()).toBe(false);
+ expect(t.a.downS()).toBeGreaterThanOrEqual(0);
+ t.a.onGateway({ t: 'model-request', id: 'q1', profile: 'claude-a', vars: { token: 'x' }, method: 'GET', path: '/v1/models' });
+ await vi.waitFor(() => expect(t.out).toContainEqual({ t: 'model-response', id: 'q1', error: 'proxy_unavailable' }));
+ await startProxy();
+ await t.up();
+ expect(t.deps.rehello).toHaveBeenCalledTimes(3);
+ await vi.waitFor(async () => expect(await held('r6')).toMatchObject({ sessionKey: 's6', profile: 'claude-a' }), { timeout: 8000 });
+ }, 30_000);
+
+ it('proxy down from the start: no SP_MODEL_PROXY, or nothing listening', async () => {
+ for (const controlSocket of [undefined, path.join(dir, 'nothing.sock')]) {
+ const t = setup({ controlSocket });
+ expect(t.a.up).toBe(false);
+ expect(t.a.profiles()).toBeUndefined();
+ await expect(t.a.spare('x')).rejects.toThrow();
}
- return [...new Set(found)].sort();
- };
+ });
+
+ it('model-request: relayed to the proxy, and its response back', async () => {
+ const t = setup();
+ await t.up();
+ t.a.onGateway({ t: 'model-request', id: 'q2', profile: 'claude-a', vars: { token: 'x' }, method: 'GET', path: '/v1/models' });
+ t.a.onGateway({ t: 'model-request', id: 'q3', profile: 'claude-a', vars: { token: 'x' }, method: 'GET', path: '/elsewhere' });
+ await vi.waitFor(() => expect(t.out).toContainEqual({ t: 'model-response', id: 'q2', error: 'unreachable' }), { timeout: 15_000 });
+ expect(t.out).toContainEqual({ t: 'model-response', id: 'q3', error: 'unknown_route' });
+ }, 20_000);
+
+ it('spares: bound as spare/<id> to models.claude, matched by kind, released and bound to the session when claimed', async () => {
+ // No spare unit exists: a release lost with a replaced connection is made good on the next hello.
+ const t = setup({ unitExists: vi.fn(async () => false) });
+ await t.up();
+ expect(t.a.canSpare()).toBe(false); // no models.claude yet
+ t.a.onGateway(welcome({ claude: route('claude-a') }));
+ expect(t.a.canSpare()).toBe(true);
+ await t.a.spare('sp1');
+ expect(await held('sp1')).toEqual({ caller: 'sp1', sessionKey: 'spare/sp1', mode: 'profile', profile: 'claude-a', key: 'claude-a-key' });
+ expect(t.out.filter((m) => m.t === 'model-bound')).toEqual([]); // a spare is no session
+ expect(t.a.forRunner('', creds)?.model).toMatchObject({ harness: claudeKey });
+ expect(t.a.kind('s7', 'claude')).toBe(spareKind('claude', claudeKey));
+ t.a.onGateway({ t: 'model', sessionKey: 's8', model: route('claude-c') });
+ expect(t.a.kind('s8', 'claude')).not.toBe(t.a.kind('s7', 'claude'));
+ await t.up();
+ await t.a.claim('sp1', 's7', 'claude');
+ expect(await held('sp1')).toMatchObject({ sessionKey: 's7', profile: 'claude-a' });
- // In the public build the hosted modules are absent and nothing imports them (model-access.hosted.test.ts covers the hosted build).
- it('nothing but host/model-access-impl.ts imports the hosted modules (they may import each other)', () => {
- expect(importers(HOSTED).filter((f) => !HOSTED.includes(f) && f !== 'host/model-access-impl.ts')).toEqual([]);
+ await t.up();
+ t.a.onGateway(welcome({ claude: { mode: 'profile', profile: 'claude-a', vars: {}, key: 'k' } }));
+ await expect(t.a.spare('sp2')).rejects.toThrow(/did not bind/);
+ await vi.waitFor(async () => expect(await held('sp2')).toBeUndefined(), { timeout: 8000 });
});
- it('host/main.ts gets its model access from the seam, not from the hosted modules', () => {
- expect(importers(['host/model-access-impl.ts'])).toEqual(['host/main.ts']);
+ it('a profile only for Codex is advertised only when the Codex binary exists', async () => {
+ const t = setup({ codexBin: path.join(dir, 'profiles', 'test.json') });
+ await t.up();
+ expect(t.a.profiles()?.map((p) => p.name)).toContain('codex-only');
+ });
+});
+
+describe('host model access relays (golden frames)', () => {
+ const GOLDEN = path.resolve(import.meta.dirname, '../../modelproxy/testdata/control');
+ const golden = (name: string) => readFileSync(path.join(GOLDEN, `${name}.json`), 'utf8');
+
+ it('observed → model-observed without the caller (never for a spare), event → telemetry with the profile as provider', async () => {
+ const d = mkdtempSync(path.join(os.tmpdir(), 'hmr-'));
+ const control = path.join(d, 'control.sock');
+ let conn: net.Socket | undefined;
+ const server = net.createServer((c) => ((conn = c), c.write(golden('hello'))));
+ await new Promise<void>((r) => server.listen(control, r));
+ const out: HostToGateway[] = [];
+ const emit = vi.fn();
+ const a = hostModelAccess({ controlSocket: control, toGateway: (m) => out.push(m), runner: () => undefined, creds: () => undefined, exit: () => {},
+ unitExists: async () => true, rehello: () => {}, tm: { emit } as unknown as Telemetry });
+ await vi.waitFor(() => expect(a.up).toBe(true));
+ conn!.write(golden('observed') + golden('observed-error') + golden('event-request') + golden('event-binding'));
+ conn!.write(`${JSON.stringify({ ...JSON.parse(golden('observed')), sessionKey: 'spare/x' })}\n`);
+ conn!.write(`${JSON.stringify({ t: 'event', name: 'not.an.event', at: 1 })}\n`);
+ await vi.waitFor(() => expect(emit).toHaveBeenCalledTimes(2));
+ const { t: _, caller: _c, ...observed } = JSON.parse(golden('observed'));
+ expect(out).toEqual([{ t: 'model-observed', ...observed }, expect.objectContaining({ t: 'model-observed', error: 'connect' })]);
+ const e = JSON.parse(golden('event-request'));
+ expect(emit).toHaveBeenCalledWith('model.request', { session_key: e.session_key, duration_ms: e.duration_ms, outcome: 'completed', provider: 'openai-key', data: e.data }, e.at);
+ a.stop();
+ conn?.destroy();
+ await new Promise((r) => server.close(r));
+ rmSync(d, { recursive: true, force: true });
});
});
diff --git a/computer/src/host/model-access.ts b/computer/src/host/model-access.ts
index e7f0f3cf..62482ab1 100644
--- a/computer/src/host/model-access.ts
+++ b/computer/src/host/model-access.ts
@@ -1,108 +1,355 @@
-// The host's model access (work 097, 6b): one interface for how a session's
-// runner gets its model credentials, and the public build's implementation of
-// it, in which every session runs on the organization's managed credentials.
-//
-// The hosted build (subscriptions.ts, model-proxy.ts, model-routes.ts: an
-// owner's Claude or ChatGPT subscription through oc-modelproxy) implements the
-// same interface; model-access-impl.ts is the one place that chooses, and
-// host/main.ts sees only this file's types. Whatever is behind it, the wire
-// is protocol.ts's and unchanged: `model-bound`, `model-health`, `probe`,
-// `claudeSubscription`.
+// The host's model access (work 097, design C3, C4 and C6): every session's
+// runner reaches its model through the model proxy (computer/modelproxy), and
+// this module binds each runner there to its session's route. A route is a
+// profile the proxy loaded plus the values of its variables, or a refusal.
+// The gateway sends routes; the proxy's control socket (model-proxy.ts) takes
+// binds; a runner gets only the profile's `harness` object and where to
+// connect (C4), never a variable. host/main.ts sees only this file.
//
// Invariants:
-// - `noHostModelAccess` is what `hostSubscriptions` did with no control
-// socket (SP_MODEL_PROXY unset): no `model-proxy` feature is advertised, so
-// the gateway routes every session managed; credentials pass through to a
-// Claude runner unchanged; a Codex runner never gets Claude's fields; a
-// `probe` is answered `proxy_unavailable`; a managed `model` push re-sends
-// a live runner its credentials; nothing binds, persists or exits a runner. A route the gateway would only send to a proxy host (a
-// subscription) is dropped with a warning rather than acted on.
-// - Nothing here throws: a host with no hosted module never fails on a
-// model frame.
+// - A runner's caller at the proxy is its runner id (`single` when runners are
+// not systemd units, `-identity=single`). One caller serves one session from
+// its bind to its release; a spare's session key is `spare/<id>`.
+// - A session's route is the last one its own `deliver`, `start` or `model`
+// carried, else `models[harness]` from the last `welcome` or `credentials`,
+// else none, which is bound as a refusal. Nothing is persisted: a runner
+// found again after a host restart keeps the binding the proxy holds until
+// its session's route arrives with a delivery or a `model` frame.
+// - A bind the proxy refuses is bound again as a refusal naming the code; a
+// refusal is never retried, so this cannot loop. A bind with no answer in
+// 5 s drops the control connection, and the next hello re-sends every bind.
+// - A route change on a live runner: an equal `harness[h]` rebinds in place and
+// pushes the runner its C4; any other rebinds and tells the runner to exit
+// after its turn. A new refusal only rebinds.
+// - A runner learns why its session has no route it can run on: `model` is
+// `{ refused }` with the text its caller is bound to (C3's), sent when it
+// starts and again whenever a bind of its caller is answered.
+// - Proxy down (no control connection with a hello): no `profiles` in the
+// gateway hello, `model-request` answers `proxy_unavailable`, no runner or
+// spare starts, live runners are left alone; 30 s down is logged as an error.
+// - Variables never reach a log, a runner or telemetry.
+import { existsSync } from 'node:fs';
import type net from 'node:net';
-import type { GatewayToHost, HarnessName, HostCredentials, HostToGateway, HostToRunner, ModelRoute, SessionReport } from '../protocol.js';
+import { isDeepStrictEqual } from 'node:util';
+import { MODEL_SOCKET } from '../protocol.js';
+import type { GatewayToHost, HarnessName, HostCredentials, HostToGateway, HostToRunner, ModelProfile, ModelRoute, ModelRoutes } from '../protocol.js';
+import { isEventName } from '../telemetry/catalog.js';
import type { Telemetry } from '../telemetry/emitter.js';
import { send } from '../ipc.js';
import { log } from '../log.js';
+import { spareKind } from '../model-key.js';
+import { type ModelProxy, modelProxy, type ProxyBind, type ProxyEvent, type ProxyOptions } from './model-proxy.js';
+
+export const NO_MODEL_CREDENTIAL = 'No model credential is configured for this computer.';
+export const PROXY_DOWN = "This computer's model proxy is not running.";
+export const SWITCHING = 'This thread is switching agents: it continues on the new one at your next message.';
+export const noProfile = (name: string) => `This computer has no model profile \`${name}\`.`;
+export const proxyRefused = (code: string) => `This computer's model proxy refused the session's credential (${code}).`;
+
+const SPARE = 'spare/';
+/** The proxy's events the host relays (computer/modelproxy/README.md); the catalog checks their data again. */
+const RELAYED = new Set(['model.request', 'model.held', 'model.denied', 'model.binding', 'model.proxy_started', 'model.pool']);
+const DOWN_ERROR_MS = 30_000;
-/** What host/main.ts hands the model access; the hosted build reads every field, the public build only `runner` and `toGateway`. */
export interface HostModelAccessDeps {
- /** oc-modelproxy's control socket, from SP_MODEL_PROXY. */
+ /** The proxy's control socket, SP_MODEL_PROXY; unset: the proxy is down. */
controlSocket?: string;
- dataDir: string;
+ /** Where runners reach the proxy's API, SP_MODEL_SOCKET; default MODEL_SOCKET. */
+ modelSocket?: string;
+ /** Runners are not systemd units: every runner is the proxy's caller `single`, and there are no spares. */
+ single?: boolean;
toGateway(m: HostToGateway): void;
/** `key`'s runner, if it has one. */
- runner(key: string): { sock: net.Socket; report?: SessionReport; harness?: HarnessName } | undefined;
- /** The proxy came up or went away since the gateway hello: say hello again so the gateway sees whether `model-proxy` is there. */
+ runner(key: string): { id: string; sock: net.Socket; harness?: HarnessName } | undefined;
+ /** The organization's credentials, as the gateway last sent them. */
+ creds(): HostCredentials | undefined;
+ /** Tell `key`'s runner to exit after its turn: its route needs a new start. */
+ exit(key: string): void;
+ /** Whether runner `caller`'s unit still exists; a binding the proxy lists for one that does not is released. */
+ unitExists(caller: string): Promise<boolean>;
+ /** The profiles the host advertises changed: say hello to the gateway again. */
rehello(): void;
tm: Telemetry;
- /** The Codex CLI runners launch (runner-env.ts `codexBin`): no `model-proxy/chatgpt` without it. */
+ /** The Codex CLI runners launch: a profile only for Codex is not advertised without it. */
codexBin?: string;
+ proxy?: ProxyOptions;
}
-/** How host/main.ts asks about, and tells of, each session's model route. */
-export interface HostModelAccess {
- routes: {
- /** `key`'s route now: managed, its owner's subscription, or refused (absent route: managed). */
- mode(key: string): ModelRoute['mode'];
- /** Runner `id`, on `harness`, now serves `key`. */
- registered(key: string, id: string, harness?: HarnessName): void;
- /** `key`'s runner `id` is gone. */
- closed(key: string, id: string): void;
- };
- /** For the gateway hello: the features this host's model access adds (`model-proxy`, `model-proxy/chatgpt`), or none. */
- features(): string[] | undefined;
- /** A delivery's credentials and route, for `key`'s runner on `harness`: resolves to the credentials that runner gets. */
- delivered(key: string, c: HostCredentials | undefined, route: ModelRoute | undefined, harness?: HarnessName): Promise<HostCredentials | undefined>;
- /** Credentials as `key`'s runner (on `harness`, else its live runner's) gets them (welcome and `credentials` pushes go through here). */
- forRunner(key: string, c: HostCredentials | undefined, harness?: HarnessName): HostCredentials | undefined;
- /** Gateway frames about model routes (`model`, `probe`); false for every other message. */
- onGateway(m: GatewayToHost, fallback: HostCredentials | undefined): boolean;
- stop(): void;
+export type HostModelAccess = ReturnType<typeof hostModelAccess>;
+
+/** Only `c`'s Slack fields, whatever else a gateway sent: no runner gets a model credential's value. */
+export function slackOnly({ slackBotToken, slackBotUserId, teamId }: HostCredentials): HostCredentials {
+ return { slackBotToken, slackBotUserId, ...(teamId !== undefined && { teamId }) };
}
-/** `c` without its Claude fields: what a Codex runner gets on any route (it has no Claude credential, as model-routes.ts has it). */
-export function withoutClaude(c: HostCredentials | undefined): HostCredentials {
- const { claudeOAuthToken: _o, anthropicApiKey: _k, anthropicBaseUrl: _u, ...slack } = c ?? { slackBotToken: '', slackBotUserId: '' };
- return slack;
+interface Held {
+ sessionKey: string;
+ harness: HarnessName;
+ /** The proxy refused this caller's route: bound as a refusal with this text until the route changes or the proxy says hello. */
+ refused?: string;
+ /** The latest bind, true once bound to the session's route. */
+ pending?: Promise<boolean>;
}
-/** The public build: every session on the organization's managed credentials, no proxy, nothing advertised. */
-/** Takes the same deps as the hosted build, so `createHostModelAccess = noHostModelAccess` is a drop-in; only `runner` and `toGateway` are read. */
-export function noHostModelAccess(o: HostModelAccessDeps): HostModelAccess {
- /** The last credentials each session's runner was delivered, re-sent on a `model` push (as the hosted build does); ends with the runner. */
+type Resolved = ({ profile: string; vars: Record<string, string>; key: string } | { mode: 'refuse'; reason: string }) & { switching?: true };
+
+export function hostModelAccess(o: HostModelAccessDeps) {
+ const own = new Map<string, ModelRoute>();
+ let models: ModelRoutes | undefined;
+ /** By caller: what the host has bound there. */
+ const held = new Map<string, Held>();
+ /** Sessions whose runner was found after a host restart and whose route has not arrived yet. */
+ const unknown = new Set<string>();
+ /** The credentials each session's runner was last delivered, for a C4 push. */
const last = new Map<string, HostCredentials>();
- const forRunner = (key: string, c: HostCredentials | undefined, harness = o.runner(key)?.harness) => (harness === 'codex' ? withoutClaude(c) : c);
- return {
- routes: {
- mode: () => 'managed',
- registered() {},
- closed(key) {
- last.delete(key);
+ let advertised = 'null';
+ let downLogged = false;
+
+ const callerOf = (id: string) => (o.single ? 'single' : id);
+ const routeOf = (key: string, h: HarnessName) => own.get(key) ?? models?.[h];
+ const profileOf = (name: string): ModelProfile | undefined => proxy.hello?.profiles.find((p) => p.name === name);
+ const harnessOf = (route: ModelRoute | undefined, h: HarnessName) => (route?.mode === 'profile' ? profileOf(route.profile)?.harness[h] : undefined);
+
+ function resolve(key: string, h: HarnessName): Resolved {
+ const route = routeOf(key, h);
+ if (!route) return { mode: 'refuse', reason: NO_MODEL_CREDENTIAL };
+ if (route.mode === 'refuse') return { mode: 'refuse', reason: route.reason };
+ const p = profileOf(route.profile);
+ if (!p) return { mode: 'refuse', reason: noProfile(route.profile) };
+ if (p.harness[h] === undefined) return { mode: 'refuse', reason: SWITCHING, switching: true };
+ return { profile: route.profile, vars: route.vars, key: route.key };
+ }
+
+ /** Send `caller`'s bind; resolves true once bound to its session's route. */
+ function bind(caller: string): Promise<boolean> {
+ const h = held.get(caller);
+ if (!h) return Promise.resolve(false);
+ const { switching: _, ...b } = h.refused ? ({ mode: 'refuse', reason: h.refused } as Resolved) : resolve(h.sessionKey, h.harness);
+ const p = proxy.bind({ caller, sessionKey: h.sessionKey, ...b } as ProxyBind).then((a): boolean | Promise<boolean> => {
+ if (held.get(caller) !== h) return false;
+ if (a.bound) {
+ if (!h.sessionKey.startsWith(SPARE)) {
+ o.toGateway({ t: 'model-bound', sessionKey: h.sessionKey, ...('profile' in b ? { mode: 'profile', profile: b.profile, key: b.key } : { mode: 'refuse' }) });
+ tell(h.sessionKey);
+ }
+ return 'profile' in b;
+ }
+ // Down or slow: the next hello re-sends it. A refusal refused: logged, never retried.
+ if (a.code === 'proxy_unavailable' || a.code === 'timeout') return false;
+ if (!('profile' in b)) return log.warn(`caller ${caller}: the model proxy refused to bind ${h.sessionKey} as refused (${a.code})`), false;
+ log.warn(`session ${h.sessionKey}: the model proxy refused its credential (${a.code}); its requests are refused`);
+ o.tm.emit('model.profile_refused', { session_key: h.sessionKey, provider: b.profile, outcome: 'failed', data: { caller, code: a.code } });
+ h.refused = proxyRefused(a.code);
+ return bind(caller).then(() => false);
+ });
+ h.pending = p;
+ return p;
+ }
+
+ /** `caller` serves `sessionKey` from now on: release it from any other session, then bind it. */
+ function hold(caller: string, sessionKey: string, harness: HarnessName) {
+ const was = held.get(caller);
+ if (was && was.sessionKey !== sessionKey) proxy.release(caller);
+ held.set(caller, { sessionKey, harness });
+ return bind(caller);
+ }
+
+ /** `key`'s live runner, with its caller, when the host holds it for `key`. */
+ function live(key: string) {
+ const r = o.runner(key);
+ const caller = r && callerOf(r.id);
+ return caller && held.get(caller)?.sessionKey === key ? { r: r!, caller, h: held.get(caller)! } : undefined;
+ }
+
+ /** Push `key`'s live runner what it knows of its route now: C4, or why it has none. */
+ function tell(key: string) {
+ const l = live(key);
+ const c = l && forRunner(key, last.get(key) ?? o.creds(), l.h.harness);
+ if (c) send(l.r.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
+ }
+
+ /** `key`'s route was `before`: rebind its live runner, and push it the new C4 or tell it to exit. */
+ function changed(key: string, before: ModelRoute | undefined) {
+ const l = live(key);
+ if (!l) return;
+ const after = routeOf(key, l.h.harness);
+ if (isDeepStrictEqual(before, after)) return;
+ l.h.refused = undefined;
+ void bind(l.caller);
+ if (!after || after.mode === 'refuse') return;
+ const next = harnessOf(after, l.h.harness);
+ if (next !== undefined && isDeepStrictEqual(harnessOf(before, l.h.harness), next)) tell(key);
+ else o.exit(key);
+ }
+
+ /** Apply a route change to the sessions in `keys`. */
+ function update(keys: string[], apply: () => void) {
+ const before = keys.map((k) => [k, routeOf(k, o.runner(k)?.harness ?? 'claude')] as const);
+ apply();
+ for (const [k, b] of before) changed(k, b);
+ }
+
+ /** `key`'s own route arrived (`route` may be absent: a delivery without one, which settles a found runner on `models`). */
+ function routed(key: string, route: ModelRoute | undefined) {
+ if (unknown.delete(key)) {
+ if (route) own.set(key, route);
+ const r = o.runner(key);
+ if (r) void hold(callerOf(r.id), key, r.harness ?? 'claude');
+ } else if (route) update([key], () => own.set(key, route));
+ }
+
+ function forRunner(key: string, c: HostCredentials | undefined, harness = o.runner(key)?.harness ?? 'claude'): HostCredentials | undefined {
+ if (!c) return undefined;
+ const slack = slackOnly(c);
+ if (unknown.has(key) || !proxy.hello) return slack;
+ const l = live(key);
+ const refused = l?.h.harness === harness ? l.h.refused : undefined;
+ const r = refused ? { reason: refused } : resolve(key, harness);
+ if ('reason' in r) return { ...slack, model: { refused: r.reason } };
+ const route = routeOf(key, harness) as Extract<ModelRoute, { mode: 'profile' }>;
+ const { profile, key: k, owner, maxModel } = route;
+ const h = harnessOf(route, harness);
+ return { ...slack, model: { profile, key: k, harness: h, owner, maxModel, endpoint: { unixSocket: o.modelSocket || MODEL_SOCKET }, placeholder: proxy.hello.placeholder } };
+ }
+
+ function profiles(): ModelProfile[] | undefined {
+ if (!proxy.up) return undefined;
+ const codex = !!o.codexBin && existsSync(o.codexBin);
+ return proxy.hello!.profiles.filter((p) => codex || Object.keys(p.harness).some((h) => h !== 'codex'));
+ }
+
+ const recheck = () => {
+ const a = JSON.stringify(profiles() ?? null);
+ if (a === advertised) return;
+ advertised = a;
+ o.rehello();
+ };
+
+ function relay(e: ProxyEvent) {
+ if (!RELAYED.has(e.name) || !isEventName(e.name)) return;
+ const data = Object.fromEntries(Object.entries(e.data ?? {}).filter(([, v]) => ['string', 'number', 'boolean'].includes(typeof v)));
+ const fields = Object.fromEntries(
+ Object.entries({ session_key: e.session_key, duration_ms: e.duration_ms, outcome: e.outcome, error_type: e.error_type, provider: e.profile }).filter(
+ ([, v]) => v !== undefined,
+ ),
+ );
+ o.tm.emit(e.name, { ...fields, data } as never, e.at);
+ }
+
+ const proxy: ModelProxy = modelProxy(
+ o.controlSocket,
+ {
+ hello(hello) {
+ for (const [caller, h] of held) {
+ h.refused = undefined;
+ void bind(caller);
+ }
+ for (const b of hello.bindings) {
+ if (held.has(b.caller)) continue;
+ void o.unitExists(b.caller).then((exists) => exists || held.has(b.caller) || proxy.release(b.caller));
+ }
+ recheck();
},
+ changed(up) {
+ if (up) downLogged = false;
+ recheck();
+ },
+ observed({ caller: _, ...m }) {
+ if (!m.sessionKey.startsWith(SPARE)) o.toGateway({ t: 'model-observed', ...m });
+ },
+ event: relay,
+ },
+ o.proxy,
+ );
+
+ if (!o.controlSocket) log.error('SP_MODEL_PROXY is not set: the model proxy is down and no session can start');
+ const watch = setInterval(() => {
+ if (proxy.downSince === undefined || downLogged || Date.now() - proxy.downSince < DOWN_ERROR_MS) return;
+ downLogged = true;
+ log.error(`the model proxy has been down for ${Math.round((Date.now() - proxy.downSince) / 1000)} s: no session can start`);
+ }, 5000);
+ watch.unref();
+
+ return {
+ get up() {
+ return proxy.up;
+ },
+ /** Seconds the proxy has been down; 0 while up (host.sample `model_proxy_down_s`). */
+ downS: () => (proxy.downSince === undefined ? 0 : Math.round((Date.now() - proxy.downSince) / 1000)),
+ /** For the gateway hello: the proxy's profiles this host can serve, while it is up. */
+ profiles,
+ /** Runner `id`, on `harness`, now serves `key`: bind it, unless it was found after a restart (its route comes later). */
+ registered(key: string, id: string, harness: HarnessName = 'claude', found = false) {
+ if (found) return void unknown.add(key);
+ const caller = callerOf(id);
+ const h = held.get(caller);
+ if (h?.sessionKey !== key || h.harness !== harness) void hold(caller, key, harness);
},
- features: () => undefined,
- async delivered(key, c, route, harness) {
- if (route && route.mode !== 'managed') log.warn(`session ${key}: a ${route.mode} route on a host without a model proxy; running managed`);
+ /** Runner `id` (of `key`, '' for a spare) is gone: release its caller. Not called while the host stops. */
+ closed(key: string, id: string) {
+ const caller = callerOf(id);
+ const h = held.get(caller);
+ unknown.delete(key);
+ if (o.single && h && h.sessionKey !== (key || SPARE + id)) return;
+ held.delete(caller);
+ proxy.release(caller);
+ },
+ /** Settles once `key`'s latest bind was answered (or there is none). */
+ ready: async (key: string) => void (await live(key)?.h.pending),
+ /** A delivery's credentials and route for `key` on `harness`: binds any change, resolves to what its runner gets. */
+ async delivered(key: string, c: HostCredentials | undefined, route: ModelRoute | undefined, harness: HarnessName = 'claude') {
if (c) last.set(key, c);
- return forRunner(key, c, harness ?? 'claude');
+ routed(key, route);
+ await live(key)?.h.pending;
+ return forRunner(key, c, harness);
},
+ /** Credentials as `key`'s runner (on `harness`, else its live runner's; '' for a spare) gets them: Slack's, plus C4. */
forRunner,
- onGateway(m, fallback) {
- if (m.t === 'probe') {
- o.toGateway({ t: 'probed', id: m.id, error: 'proxy_unavailable' });
- return true;
- }
- if (m.t !== 'model') return false;
- if (m.model.mode !== 'managed') {
- log.warn(`session ${m.sessionKey}: a ${m.model.mode} route on a host without a model proxy; ignored`);
- return true;
+ /** The spare kind `key` on `harness` may take (model-key.ts), if its route has one. */
+ kind: (key: string, harness: HarnessName) => {
+ const h = harnessOf(unknown.has(key) ? undefined : routeOf(key, harness), harness);
+ return h === undefined ? undefined : spareKind(harness, h);
+ },
+ /** Spares start while the proxy is up and `models.claude` names a profile it serves for Claude. */
+ canSpare: () => !o.single && proxy.up && harnessOf(models?.claude, 'claude') !== undefined,
+ /** Bind spare `id` to `models.claude` before it launches; rejects if it was not bound. */
+ async spare(id: string) {
+ if (await hold(id, SPARE + id, 'claude')) return;
+ held.delete(id);
+ proxy.release(id);
+ throw new Error(`spare ${id}: the model proxy did not bind it`);
+ },
+ /** Spare `id` becomes `key`'s: release it, bind it to the session; rejects if it was not bound (start cold). */
+ async claim(id: string, key: string, harness: HarnessName) {
+ if (!(await hold(callerOf(id), key, harness))) throw new Error(`spare ${id}: the model proxy did not bind it for ${key}`);
+ },
+ /** Gateway frames: `model` and `model-request` are this module's (true); `welcome` and `credentials` are read for `models` and passed on. */
+ onGateway(m: GatewayToHost): boolean {
+ switch (m.t) {
+ case 'welcome':
+ case 'credentials': {
+ const before = models?.claude;
+ const keys = [...held.values()].map((h) => h.sessionKey).filter((k) => !k.startsWith(SPARE) && !own.has(k));
+ update(keys, () => (models = m.models));
+ if (!isDeepStrictEqual(before, models?.claude)) for (const [caller, h] of held) if (h.sessionKey.startsWith(SPARE)) void bind(caller);
+ return false;
+ }
+ case 'model':
+ routed(m.sessionKey, m.model);
+ return true;
+ case 'model-request': {
+ const { t: _, ...req } = m;
+ void proxy.request(req).then((r) => o.toGateway({ t: 'model-response', ...r }));
+ return true;
+ }
+ default:
+ return false;
}
- const c = forRunner(m.sessionKey, last.get(m.sessionKey) ?? fallback);
- if (c) send(o.runner(m.sessionKey)?.sock, { t: 'credentials', credentials: c } satisfies HostToRunner);
- return true;
},
- stop() {},
+ stop() {
+ clearInterval(watch);
+ proxy.stop();
+ },
};
}
diff --git a/computer/src/host/model-proxy.test.ts b/computer/src/host/model-proxy.test.ts
new file mode 100644
index 00000000..2d7128ec
--- /dev/null
+++ b/computer/src/host/model-proxy.test.ts
@@ -0,0 +1,170 @@
+// The control-socket client against the proxy's golden frames
+// (computer/modelproxy/testdata/control): what it sends has the shape of
+// bind.json, bind-refuse.json, release.json, request.json and synced.json;
+// what it reads is the proxy's hello, bound, refused, observed, event and
+// response files verbatim. model-access.test.ts runs the real binary.
+
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import net from 'node:net';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { lines } from '../ipc.js';
+import { type ModelProxy, modelProxy, type ProxyHooks } from './model-proxy.js';
+
+const GOLDEN = path.resolve(import.meta.dirname, '../../modelproxy/testdata/control');
+const golden = (name: string) => JSON.parse(readFileSync(path.join(GOLDEN, `${name}.json`), 'utf8'));
+const keys = (o: object) => Object.keys(o).sort();
+
+/** A fake proxy: a control socket that records frames and lets the test answer. */
+function fakeProxy(o: { hello?: boolean } = {}) {
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'mp-'));
+ const sockPath = path.join(dir, 'control.sock');
+ const got: Record<string, unknown>[] = [];
+ let conn: net.Socket | undefined;
+ let conns = 0;
+ const server = net.createServer((c) => {
+ conn = c;
+ conns++;
+ lines(c, (m) => got.push(m));
+ if (o.hello !== false) c.write(`${JSON.stringify(golden('hello'))}\n`);
+ });
+ server.listen(sockPath);
+ return {
+ sockPath,
+ got,
+ get conns() {
+ return conns;
+ },
+ say: (m: object) => conn?.write(`${JSON.stringify(m)}\n`),
+ drop: () => conn?.destroy(),
+ close: () => new Promise<void>((r) => (conn?.destroy(), server.close(() => (rmSync(dir, { recursive: true, force: true }), r())))),
+ };
+}
+
+const hooks = (): ProxyHooks & { calls: Record<string, unknown[]> } => {
+ const calls: Record<string, unknown[]> = { hello: [], changed: [], observed: [], event: [] };
+ return {
+ calls,
+ hello: (h) => calls.hello.push(h),
+ changed: (u) => calls.changed.push(u),
+ observed: (m) => calls.observed.push(m),
+ event: (e) => calls.event.push(e),
+ };
+};
+
+let cleanup: (() => unknown)[] = [];
+afterEach(async () => {
+ for (const c of cleanup.reverse()) await c();
+ cleanup = [];
+});
+
+function start(o: { hello?: boolean } = {}, opts = {}) {
+ const fake = fakeProxy(o);
+ const h = hooks();
+ const p = modelProxy(fake.sockPath, h, opts);
+ cleanup.push(fake.close, () => p.stop());
+ return { fake, h, p };
+}
+
+const upWithin = (p: ModelProxy, up = true) => vi.waitFor(() => expect(p.up).toBe(up), { timeout: 3000 });
+
+describe('model proxy control client (golden frames)', () => {
+ it('reads the hello, keeps it, answers `synced` after the hello hook, and is up', async () => {
+ const { fake, h, p } = start();
+ await upWithin(p);
+ const hello = golden('hello');
+ expect(p.hello).toEqual({ version: hello.version, protocol: 1, placeholder: hello.placeholder, profiles: hello.profiles, bindings: hello.bindings });
+ expect(h.calls.hello).toHaveLength(1);
+ expect(h.calls.changed).toEqual([true]);
+ await vi.waitFor(() => expect(fake.got).toEqual([golden('synced')]));
+ expect(p.downSince).toBeUndefined();
+ });
+
+ it('binds with the shape of bind.json and resolves on bound.json; refused.json resolves its code', async () => {
+ const { fake, p } = start();
+ await upWithin(p);
+ const b = golden('bind');
+ const bound = p.bind({ caller: b.caller, sessionKey: b.sessionKey, profile: b.profile, vars: b.vars, key: b.key });
+ await vi.waitFor(() => expect(fake.got.length).toBe(2));
+ const sent = fake.got[1];
+ expect(keys(sent)).toEqual(keys(b));
+ expect({ ...sent, id: b.id }).toEqual(b);
+ fake.say({ ...golden('bound'), id: sent.id });
+ expect(await bound).toEqual({ bound: true, key: 'k1' });
+
+ const r = golden('bind-refuse');
+ const refused = p.bind({ caller: r.caller, sessionKey: r.sessionKey, mode: 'refuse', reason: r.reason });
+ await vi.waitFor(() => expect(fake.got.length).toBe(3));
+ expect(fake.got[2]).toEqual({ ...r, id: fake.got[2].id });
+ fake.say({ ...golden('refused'), id: fake.got[2].id });
+ expect(await refused).toEqual({ bound: false, code: 'caller_in_use' });
+ });
+
+ it('a bind with no answer in time times out and drops the connection; it dials again', async () => {
+ const { fake, h, p } = start({}, { bindMs: 100 });
+ await upWithin(p);
+ expect(await p.bind({ caller: 'c', sessionKey: 's', mode: 'refuse', reason: 'r' })).toEqual({ bound: false, code: 'timeout' });
+ await vi.waitFor(() => expect(h.calls.changed).toEqual([true, false, true]), { timeout: 3000 });
+ expect(fake.conns).toBe(2);
+ });
+
+ it('releases with release.json; relays observed and events unread', async () => {
+ const { fake, h, p } = start();
+ await upWithin(p);
+ p.release('abc123');
+ await vi.waitFor(() => expect(fake.got[1]).toEqual(golden('release')));
+ for (const name of ['observed', 'observed-error']) fake.say(golden(name));
+ for (const name of ['event-request', 'event-binding', 'event-denied', 'event-held', 'event-pool', 'event-proxy-started']) fake.say(golden(name));
+ await vi.waitFor(() => expect(h.calls.event).toHaveLength(6));
+ const { t: _, ...observed } = golden('observed');
+ expect(h.calls.observed[0]).toMatchObject(observed);
+ expect((h.calls.event[0] as { name: string }).name).toBe('model.request');
+ });
+
+ it('requests with the shape of request.json and resolves on response.json or response-error.json', async () => {
+ const { fake, p } = start();
+ await upWithin(p);
+ const { t: _, ...req } = golden('request');
+ const answer = p.request(req);
+ await vi.waitFor(() => expect(fake.got[1]).toEqual(golden('request')));
+ const { t: _r, ...res } = golden('response');
+ fake.say(golden('response'));
+ expect(await answer).toEqual(res);
+ const failed = p.request(req);
+ fake.say(golden('response-error'));
+ expect(await failed).toEqual({ id: req.id, error: 'unreachable' });
+ });
+
+ it('a request times out after its limit', async () => {
+ const { p } = start({}, { requestMs: 50 });
+ await upWithin(p);
+ expect(await p.request({ id: 'x', profile: 'p', vars: {}, method: 'GET', path: '/' })).toEqual({ id: 'x', error: 'timeout' });
+ });
+
+ it('down: no hello within its limit, a close, or no socket at all; binds and requests answer proxy_unavailable', async () => {
+ const { fake, p } = start({ hello: false }, { helloMs: 100 });
+ await vi.waitFor(() => expect(fake.conns).toBeGreaterThanOrEqual(2), { timeout: 3000 }); // dropped, dialled again
+ expect(p.up).toBe(false);
+ expect(p.downSince).toBeTypeOf('number');
+ expect(await p.bind({ caller: 'c', sessionKey: 's', mode: 'refuse', reason: 'r' })).toEqual({ bound: false, code: 'proxy_unavailable' });
+ expect(await p.request({ id: 'x', profile: 'p', vars: {}, method: 'GET', path: '/' })).toEqual({ id: 'x', error: 'proxy_unavailable' });
+
+ const none = modelProxy(undefined, hooks());
+ expect(none.up).toBe(false);
+ none.stop();
+ });
+
+ it('settles pending binds and requests when the connection goes, and says hello again after a redial', async () => {
+ const { fake, h, p } = start();
+ await upWithin(p);
+ const b = p.bind({ caller: 'c', sessionKey: 's', mode: 'refuse', reason: 'r' });
+ const r = p.request({ id: 'x', profile: 'p', vars: {}, method: 'GET', path: '/' });
+ await vi.waitFor(() => expect(fake.got.length).toBe(3));
+ fake.drop();
+ expect(await b).toEqual({ bound: false, code: 'proxy_unavailable' });
+ expect(await r).toEqual({ id: 'x', error: 'proxy_unavailable' });
+ await vi.waitFor(() => expect(h.calls.hello).toHaveLength(2), { timeout: 3000 });
+ expect(p.hello?.placeholder).toBe('ssh-placeholder');
+ });
+});
diff --git a/computer/src/host/model-proxy.ts b/computer/src/host/model-proxy.ts
new file mode 100644
index 00000000..caadd2e8
--- /dev/null
+++ b/computer/src/host/model-proxy.ts
@@ -0,0 +1,194 @@
+// The host's end of the model proxy's control socket (work 097, design C1
+// and C3; computer/modelproxy/README.md is the protocol): one connection,
+// dialled again after every close, that carries binds and releases out and
+// answers, reports and telemetry in. It keeps no bindings itself: on every
+// `hello` it asks `hooks.hello` to re-send them, then says `synced`.
+//
+// Invariants:
+// - Up means connected and a `hello` received. A connection with no `hello`
+// within 5 s, or a bind with no answer within 5 s, is dropped as down; so
+// is any close. Reconnect backoff is 250 ms, doubling to 5 s, reset by a hello.
+// - Nothing here logs a frame: binds and requests carry variables.
+// - Every promise settles: a bind with its answer, `proxy_unavailable` while
+// down or when the connection goes, `timeout` past 5 s; a request with the
+// proxy's response, `proxy_unavailable`, or `timeout` past 20 s.
+
+import net from 'node:net';
+import { randomUUID } from 'node:crypto';
+import { lines, send } from '../ipc.js';
+import type { ModelObserved, ModelProfile, ModelRequest, ModelResponse } from '../protocol.js';
+
+export interface ProxyHello {
+ version: string;
+ protocol: number;
+ /** What runners send as their credential. */
+ placeholder: string;
+ profiles: ModelProfile[];
+ /** Every binding the proxy holds. */
+ bindings: { caller: string; sessionKey: string; mode: string; profile?: string; key?: string }[];
+}
+
+/** A bind as the host sends it, without its `id`. */
+export type ProxyBind = { caller: string; sessionKey: string } & (
+ | { profile: string; vars: Record<string, string>; key: string }
+ | { mode: 'refuse'; reason: string }
+);
+
+export interface ProxyEvent {
+ name: string;
+ at: number;
+ outcome?: string;
+ duration_ms?: number;
+ error_type?: string;
+ session_key?: string;
+ profile?: string;
+ data?: Record<string, unknown>;
+}
+
+/** A bind's answer: `code` is the proxy's refusal code, `proxy_unavailable` or `timeout`. */
+export type BindAnswer = { bound: true; key?: string } | { bound: false; code: string };
+
+export interface ProxyHooks {
+ /** A hello arrived (the client is up): re-send every bind now; `synced` follows. */
+ hello(h: ProxyHello): void;
+ /** Up or down changed. */
+ changed(up: boolean): void;
+ observed(m: ModelObserved & { caller: string }): void;
+ event(e: ProxyEvent): void;
+}
+
+export interface ModelProxy {
+ readonly up: boolean;
+ /** The last hello, kept while down (its profiles and placeholder still describe live runners). */
+ readonly hello: ProxyHello | undefined;
+ /** When it went down; undefined while up. */
+ readonly downSince: number | undefined;
+ bind(b: ProxyBind): Promise<BindAnswer>;
+ release(caller: string): void;
+ request(m: ModelRequest): Promise<ModelResponse>;
+ stop(): void;
+}
+
+export interface ProxyOptions {
+ connect?: (path: string) => net.Socket;
+ helloMs?: number;
+ bindMs?: number;
+ requestMs?: number;
+ now?: () => number;
+}
+
+type In =
+ | ({ t: 'hello' } & ProxyHello)
+ | { t: 'bound'; id?: string; caller: string; sessionKey: string; key?: string }
+ | { t: 'refused'; id?: string; caller: string; code: string; message: string }
+ | ({ t: 'observed'; caller: string } & ModelObserved)
+ | ({ t: 'response' } & ModelResponse)
+ | ({ t: 'event' } & ProxyEvent);
+
+/** Dial `path` and keep dialling; `path` undefined (SP_MODEL_PROXY unset): never up. */
+export function modelProxy(path: string | undefined, hooks: ProxyHooks, o: ProxyOptions = {}): ModelProxy {
+ const now = o.now ?? Date.now;
+ const binds = new Map<string, (a: BindAnswer) => void>();
+ const requests = new Map<string, (r: ModelResponse) => void>();
+ let sock: net.Socket | undefined;
+ let hello: ProxyHello | undefined;
+ let up = false;
+ let downSince: number | undefined = now();
+ let stopped = false;
+ let backoff = 250;
+
+ const settleAll = () => {
+ for (const [id, done] of binds) done({ bound: false, code: 'proxy_unavailable' }), binds.delete(id);
+ for (const [id, done] of requests) done({ id, error: 'proxy_unavailable' }), requests.delete(id);
+ };
+
+ const dial = () => {
+ if (stopped || !path) return;
+ const s = (o.connect ?? ((p) => net.createConnection(p)))(path);
+ sock = s;
+ const helloTimer = setTimeout(() => s.destroy(), o.helloMs ?? 5000);
+ helloTimer.unref();
+ s.on('error', () => {});
+ s.on('close', () => {
+ clearTimeout(helloTimer);
+ if (sock !== s) return;
+ sock = undefined;
+ settleAll();
+ if (up) (up = false), (downSince = now()), hooks.changed(false);
+ if (stopped) return;
+ setTimeout(dial, backoff).unref();
+ backoff = Math.min(backoff * 2, 5000);
+ });
+ lines(s, (m: In) => {
+ if (sock !== s) return;
+ switch (m.t) {
+ case 'hello': {
+ clearTimeout(helloTimer);
+ backoff = 250;
+ hello = { version: m.version, protocol: m.protocol, placeholder: m.placeholder, profiles: m.profiles ?? [], bindings: m.bindings ?? [] };
+ const was = up;
+ (up = true), (downSince = undefined);
+ hooks.hello(hello);
+ send(s, { t: 'synced' });
+ if (!was) hooks.changed(true);
+ return;
+ }
+ case 'bound':
+ return m.id && binds.get(m.id)?.({ bound: true, key: m.key });
+ case 'refused':
+ return m.id && binds.get(m.id)?.({ bound: false, code: m.code });
+ case 'response':
+ return requests.get(m.id)?.({ id: m.id, status: m.status, headers: m.headers, body: m.body, error: m.error });
+ case 'observed':
+ case 'event': {
+ const { t, ...rest } = m;
+ return t === 'observed' ? hooks.observed(rest as ModelObserved & { caller: string }) : hooks.event(rest as ProxyEvent);
+ }
+ }
+ });
+ };
+ dial();
+
+ return {
+ get up() {
+ return up;
+ },
+ get hello() {
+ return hello;
+ },
+ get downSince() {
+ return downSince;
+ },
+ bind(b) {
+ if (!up) return Promise.resolve({ bound: false, code: 'proxy_unavailable' });
+ const id = randomUUID();
+ const s = sock;
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ binds.delete(id);
+ resolve({ bound: false, code: 'timeout' });
+ s?.destroy(); // no answer in time: down, and the next hello re-sends every bind
+ }, o.bindMs ?? 5000);
+ timer.unref();
+ binds.set(id, (a) => (clearTimeout(timer), binds.delete(id), resolve(a)));
+ send(s, { t: 'bind', id, ...b });
+ });
+ },
+ release(caller) {
+ if (up) send(sock, { t: 'release', caller });
+ },
+ request(m) {
+ if (!up) return Promise.resolve({ id: m.id, error: 'proxy_unavailable' });
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => (requests.delete(m.id), resolve({ id: m.id, error: 'timeout' })), o.requestMs ?? 20_000);
+ timer.unref();
+ requests.set(m.id, (r) => (clearTimeout(timer), requests.delete(m.id), resolve(r)));
+ send(sock, { t: 'request', ...m });
+ });
+ },
+ stop() {
+ stopped = true;
+ sock?.destroy();
+ },
+ };
+}
diff --git a/computer/src/host/pool.test.ts b/computer/src/host/pool.test.ts
index 58da7ad1..5280603e 100644
--- a/computer/src/host/pool.test.ts
+++ b/computer/src/host/pool.test.ts
@@ -3,7 +3,7 @@ import type { SpareReport } from '../protocol.js';
import { Pool } from './pool.js';
type R = { spare?: SpareReport; name: string };
-const spare = (name: string, s: Partial<SpareReport> = {}): R => ({ name, spare: { id: name, ready: true, version: 'v1', credential: 'fp', ...s } });
+const spare = (name: string, s: Partial<SpareReport> = {}): R => ({ name, spare: { id: name, ready: true, version: 'v1', kind: 'fp', ...s } });
function pool(size = 2) {
let t = 0;
@@ -32,7 +32,7 @@ describe('Pool', () => {
expect(launches).toHaveLength(0);
});
- it('launches up to size, counting spares still launching, and only with a credential', () => {
+ it('launches up to size, counting spares still launching, and only with a route', () => {
const { p, launches } = pool(2);
p.fill(false);
expect(launches).toHaveLength(0);
@@ -45,24 +45,24 @@ describe('Pool', () => {
expect(launches).toHaveLength(2);
});
- it('gives a ready spare of this release with the delivery credential, once', () => {
+ it('gives a ready spare of this release of the session’s kind, once', () => {
const { p } = pool();
const a = spare('a', { ready: false });
- const b = spare('b', { credential: 'other' });
+ const b = spare('b', { kind: 'other' });
const c = spare('c', { version: 'v0' });
for (const r of [a, b, c]) p.add(r);
- expect(p.take('fp')).toBe('credential');
- expect(p.take(undefined)).toBe('credential');
+ expect(p.take('fp')).toBe('kind');
+ expect(p.take(undefined)).toBe('kind');
a.spare!.ready = true;
expect(p.take('fp')).toBe(a);
- expect(p.take('fp')).toBe('credential');
+ expect(p.take('fp')).toBe('kind');
expect(pool().p.take('fp')).toBe('none');
});
- it('gives Codex a ready spare whatever its credential', () => {
+ it('gives Codex a ready spare whatever its kind', () => {
const { p } = pool();
const a = spare('a', { ready: false });
- const b = spare('b', { credential: 'other' });
+ const b = spare('b', { kind: 'other' });
for (const r of [a, b]) p.add(r);
expect(p.take(undefined, true)).toBe(b);
expect(p.take(undefined, true)).toBe('none');
diff --git a/computer/src/host/pool.ts b/computer/src/host/pool.ts
index 12d294cb..0e90cdb3 100644
--- a/computer/src/host/pool.ts
+++ b/computer/src/host/pool.ts
@@ -8,9 +8,9 @@
//
// Invariants: at most `size` spares, counting those still launching; size 0
// is off. A spare is taken only when it is parked (`ready`), from this host's
-// release, and, for Claude, started with the Claude credential the delivery
-// carries (its fingerprint): Claude Code copied the environment when it
-// started. Codex holds no credential (the proxy does), so any will do. One taken
+// release, and, for Claude, of the session's spare kind (model-key.ts
+// `spareKind`, design C6): Claude Code read its model settings when it
+// started. Codex reads its own when it starts, so any will do. One taken
// is the caller's, never offered again. A spare that dies before it was ever
// ready, or within `minLifeMs` of parking, backs the pool off (doubling, up to
// `maxBackoffMs`), so a Claude Code that cannot start or stay up is not
@@ -24,7 +24,7 @@ export interface SpareRunner {
}
export type EvictReason = 'version' | 'surplus';
-export type MissReason = 'none' | 'credential';
+export type MissReason = 'none' | 'kind';
export interface PoolOptions<R> {
size: number;
@@ -79,7 +79,7 @@ export class Pool<R extends SpareRunner> {
this.backOff();
}
- /** Start spares up to `size`; `canStart` is false while there is no Claude credential to start them with. */
+ /** Start spares up to `size`; `canStart` is false while there is no model route to start them on. */
fill(canStart: boolean) {
const surplus = [...this.spares].slice(this.o.size);
for (const r of surplus) this.evict(r, 'surplus');
@@ -96,11 +96,11 @@ export class Pool<R extends SpareRunner> {
}
}
- /** A parked spare started with `credential` (a fingerprint; `any` for Codex), now the caller's; else why there is none. */
- take(credential: string | undefined, any = false): R | MissReason {
+ /** A parked spare of `kind` (`any` for Codex), now the caller's; else why there is none. */
+ take(kind: string | undefined, any = false): R | MissReason {
const ready = [...this.spares].filter((r) => r.spare?.ready && r.spare.version === this.o.version);
- const r = any ? ready[0] : credential ? ready.find((s) => s.spare!.credential === credential) : undefined;
- if (!r) return ready.length ? 'credential' : 'none';
+ const r = any ? ready[0] : kind ? ready.find((s) => s.spare!.kind === kind) : undefined;
+ if (!r) return ready.length ? 'kind' : 'none';
this.spares.delete(r);
return r;
}
diff --git a/computer/src/host/sample.ts b/computer/src/host/sample.ts
index 58175640..8c83b295 100644
--- a/computer/src/host/sample.ts
+++ b/computer/src/host/sample.ts
@@ -18,6 +18,8 @@ export interface HostFigures {
since_gateway_message_s?: number;
telemetry_spooled_bytes: number;
telemetry_dropped: number;
+ /** Seconds the model proxy's control socket has been down (work 097); 0 while up. A host's health fails past 30. */
+ model_proxy_down_s?: number;
}
interface CpuTimes {
diff --git a/computer/src/main.ts b/computer/src/main.ts
index 20433536..fc41f6bd 100644
--- a/computer/src/main.ts
+++ b/computer/src/main.ts
@@ -33,8 +33,8 @@ const env = process.env;
const STATE = path.resolve(import.meta.dirname, '..', 'state.json');
const DEFAULT_MODE = (env.PERMISSION_MODE ?? 'bypassPermissions') as PermissionMode;
const PORT = Number(env.PORT ?? 3170);
-// Prompt cache TTL for Claude Code: 1 hour on Anthropic's own API (runner/cache-ttl.ts).
-applyPromptCacheTtl(env, env.SP_PROMPT_CACHE_TTL, presetTtls(env));
+// Prompt cache TTL for Claude Code: SP_PROMPT_CACHE_TTL, else Claude Code's default (no model profile here; runner/cache-ttl.ts).
+applyPromptCacheTtl(env, { explicit: env.SP_PROMPT_CACHE_TTL, preset: presetTtls(env) }, undefined);
// Compaction: between turns in a fork (runner/harness/claude/shadow.ts), Claude Code's own as the backstop.
configureCompaction(env);
diff --git a/computer/src/model-key.test.ts b/computer/src/model-key.test.ts
new file mode 100644
index 00000000..34468e64
--- /dev/null
+++ b/computer/src/model-key.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+import { modelKey, sortedJson, spareKind } from './model-key.js';
+
+// The same vectors as the backend's test (services/managed-agents test/computer-model-profiles.test.ts).
+describe('modelKey (design C2)', () => {
+ it('is the first 16 hex digits of sha256 over the profile and its variables in name order, joined by NUL', () => {
+ // printf 'openrouter\0token=sk-or-test' | sha256sum
+ expect(modelKey('openrouter', { token: 'sk-or-test' })).toBe('427939d396f90454');
+ // printf 'p\0a=1\0b=2' | sha256sum
+ expect(modelKey('p', { b: '2', a: '1' })).toBe('c79bd378f5b5e1f1');
+ });
+
+ it('differs by profile and by value', () => {
+ const key = modelKey('openrouter', { token: 'sk-or-test' });
+ expect(modelKey('anthropic-key', { token: 'sk-or-test' })).not.toBe(key);
+ expect(modelKey('openrouter', { token: 'sk-or-other' })).not.toBe(key);
+ });
+});
+
+describe('spareKind (design C6)', () => {
+ it('hashes the harness name and its object as JSON with sorted keys', () => {
+ // printf 'claude\0{"promptCacheTtl":"1h","tokenEnv":"ANTHROPIC_API_KEY"}' | sha256sum
+ expect(spareKind('claude', { tokenEnv: 'ANTHROPIC_API_KEY', promptCacheTtl: '1h' })).toBe('4213d268b442d1fc');
+ // printf 'codex\0{}' | sha256sum
+ expect(spareKind('codex', {})).toBe('766c08abd4f9dbf2');
+ expect(spareKind('codex', undefined)).toBe('766c08abd4f9dbf2');
+ });
+
+ it('is the same for equal objects in any key order, and differs by harness', () => {
+ expect(spareKind('claude', { b: { y: 1, x: [2, { d: 1, c: 2 }] }, a: 1 })).toBe(spareKind('claude', { a: 1, b: { x: [2, { c: 2, d: 1 }], y: 1 } }));
+ expect(spareKind('claude', {})).not.toBe(spareKind('codex', {}));
+ expect(sortedJson({ b: 1, a: { d: 1, c: 2 } })).toBe('{"a":{"c":2,"d":1},"b":1}');
+ });
+});
diff --git a/computer/src/model-key.ts b/computer/src/model-key.ts
new file mode 100644
index 00000000..7f8c5503
--- /dev/null
+++ b/computer/src/model-key.ts
@@ -0,0 +1,37 @@
+// The two short hashes of work 097 (design C2 and C6), computed the same way
+// by the host and the backend (services/managed-agents src/computer/model-key.ts):
+//
+// - `modelKey`: a credential's `key` when its author has no better name, the
+// first 16 hex digits of sha256 over the profile, then every variable as
+// `name=value` in name order, joined by NUL. All variables sent are hashed,
+// used by the profile or not.
+// - `spareKind`: what a warm-pool spare was started for, the first 16 hex
+// digits of sha256 over the harness name and the profile's `harness[h]` as
+// JSON with sorted keys (`{}` when absent), joined by NUL. A session may
+// claim a spare of its own kind.
+//
+// Invariant: one-way and short. `modelKey` suits high-entropy values only; the
+// result may be logged and sent anywhere, the values never.
+
+import { createHash } from 'node:crypto';
+import type { HarnessName } from './protocol.js';
+
+const hex16 = (s: string) => createHash('sha256').update(s, 'utf8').digest('hex').slice(0, 16);
+
+/** `profile` with `vars`, as a key (C2). */
+export function modelKey(profile: string, vars: Record<string, string>): string {
+ const names = Object.keys(vars).sort();
+ return hex16([profile, ...names.map((n) => `${n}=${vars[n]}`)].join('\0'));
+}
+
+/** JSON with every object's keys sorted, at any depth. */
+export function sortedJson(v: unknown): string {
+ return JSON.stringify(v, (_, x) =>
+ x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x,
+ );
+}
+
+/** A spare's kind for `harness` started with the profile's `harness[h]` object `h` (C6). */
+export function spareKind(harness: HarnessName, h: unknown): string {
+ return hex16(`${harness}\0${sortedJson(h ?? {})}`);
+}
diff --git a/computer/src/protocol-model.ts b/computer/src/protocol-model.ts
new file mode 100644
index 00000000..182bb8ba
--- /dev/null
+++ b/computer/src/protocol-model.ts
@@ -0,0 +1,111 @@
+// Protocol v5's model frames (work 097, design C2 and C4): how the gateway,
+// the host and a runner speak of a session's model credential once every
+// request goes through the host's model proxy (computer/modelproxy). The
+// gateway names a profile the proxy loaded and the values of its variables;
+// the host binds them to the session's runner at the proxy; the runner learns
+// the profile's `harness` object and where to connect, never a variable.
+// protocol.ts re-exports everything here and splices the frames into its
+// unions; the backend's copy of the protocol mirrors it.
+//
+// gateway → host `welcome.models`, `credentials.models`, `deliver.model`, `start.model`, `model`, `model-request`
+// host → gateway `hello.profiles`, `model-bound`, `model-observed`, `model-response`
+// host → runner `credentials.credentials.model` (RunnerModel, or RunnerRefused)
+//
+// Invariants:
+// - A variable's value travels gateway → host → proxy only: never to a runner,
+// never into a log or telemetry. `key` names a credential without revealing it.
+// - A session's route is the last `model` it received in a `deliver`, `start` or
+// `model` frame, else `models[harness]` of the last `welcome` or `credentials`,
+// else none (the host refuses it).
+
+import type { HarnessName } from './protocol.js';
+
+/** The model proxy's API socket where the host's SP_MODEL_SOCKET is unset. */
+export const MODEL_SOCKET = '/run/oc-modelproxy/api.sock';
+
+/** A profile as the proxy's hello lists it; the host forwards it unread. */
+export interface ModelProfile {
+ name: string;
+ /** Names of the variables a bind must carry. */
+ vars: string[];
+ /** harness → what that harness's adapter needs (design C5). Opaque to the host and the gateway. */
+ harness: Partial<Record<HarnessName, unknown>>;
+}
+
+/** Which credential a session runs on: a profile with its variables, or a refusal with a sentence for the thread. */
+export type ModelRoute =
+ | { mode: 'profile'; profile: string; vars: Record<string, string>; key: string; owner?: string; maxModel?: string }
+ | { mode: 'refuse'; reason: string };
+
+/** The routes of sessions whose own delivery carries none, by harness; a `credentials` frame replaces the whole map. */
+export type ModelRoutes = Partial<Record<HarnessName, ModelRoute>>;
+
+/** What a runner knows of its session's route (design C4): never a variable. */
+export interface RunnerModel {
+ profile: string;
+ key: string;
+ /** The profile's `harness[h]` for the runner's own harness. */
+ harness: unknown;
+ owner?: string;
+ maxModel?: string;
+ /** Where the runner's model client connects: the host's SP_MODEL_SOCKET. */
+ endpoint: { unixSocket: string };
+ /** What it sends as its credential: the proxy's, from its hello. */
+ placeholder: string;
+}
+
+/** Why a runner's session has no route it can run on, as the host words it (C3): the runner refuses its turns with it. */
+export interface RunnerRefused {
+ refused: string;
+}
+
+/** The proxy's report of what an upstream answered on a credential, relayed by the host unread. */
+export interface ModelObserved {
+ sessionKey: string;
+ key: string;
+ profile: string;
+ status?: number;
+ /** Lower-case name → value. */
+ headers?: Record<string, string>;
+ /** The start of an error body: upstream text, never logged. */
+ body?: string;
+ error?: string;
+}
+
+/** A request of the gateway's own through a profile, with the credential in `vars`; answered by `model-response`. */
+export interface ModelRequest {
+ id: string;
+ profile: string;
+ vars: Record<string, string>;
+ method: string;
+ /** One of the profile's routes. */
+ path: string;
+ /** The raw query string, without the `?`. */
+ query?: string;
+ headers?: Record<string, string>;
+ body?: string;
+}
+
+/** `error`: the proxy's own code, `proxy_unavailable`, or `timeout` when the host gave up waiting (20 s). */
+export interface ModelResponse {
+ id: string;
+ status?: number;
+ headers?: Record<string, string>;
+ body?: string;
+ error?: string;
+}
+
+/** Spliced into GatewayToHost. */
+export type GatewayToHostModel =
+ /** A session's route changed (pause, limit, revoke, policy): the host rebinds its runner, or tells it to exit. */
+ | { t: 'model'; sessionKey: string; model: ModelRoute }
+ | ({ t: 'model-request' } & ModelRequest);
+
+/** Spliced into HostToGateway. */
+export type HostToGatewayModel =
+ /** A session's bind took effect at the proxy. */
+ | { t: 'model-bound'; sessionKey: string; mode: ModelRoute['mode']; profile?: string; key?: string }
+ | ({ t: 'model-observed' } & ModelObserved)
+ | ({ t: 'model-response' } & ModelResponse)
+ /** The credential refused `model`; the session now runs on `fallbackTo`. */
+ | { t: 'model-denied'; sessionKey: string; model: string; fallbackTo: string };
diff --git a/computer/src/protocol.ts b/computer/src/protocol.ts
index af883ad5..c8f18636 100644
--- a/computer/src/protocol.ts
+++ b/computer/src/protocol.ts
@@ -18,9 +18,11 @@ import type { Tier } from './tiers.js';
import type { Linked } from './links.js';
import type { Batch } from './telemetry/emitter.js';
import type { ApiDelivery, GatewayToHostV4, HostToGatewayV4, HostToRunnerV4, JournalReport, RunnerApi, WireConfig } from './protocol-api.js';
+import type { GatewayToHostModel, HostToGatewayModel, ModelProfile, ModelRoute, ModelRoutes, RunnerModel, RunnerRefused } from './protocol-model.js';
import type { WorkspaceDefinition } from './protocol-workspace.js';
export * from './protocol-api.js';
+export * from './protocol-model.js';
export * from './protocol-workspace.js';
// 2 (work 077): the hello carries `features`; `deliver.model`, `model`, `probe`/`probed`,
@@ -33,10 +35,10 @@ export * from './protocol-workspace.js';
// 4 (work 084): the streaming session API (protocol-api.ts); a session may have no Slack thread and
// carries its `cs_` id; a person may have no Slack id. All optional: a v3 frame reads unchanged, and
// the gateway sends v4 frames only to a host that says 4.
-export const PROTOCOL_VERSION = 4;
-
-/** Whose subscription a route spends (work 082). Absent wherever it is optional: anthropic. */
-export type ModelProvider = 'anthropic' | 'chatgpt';
+// 5 (work 097): model routes are profiles of the host's model proxy (protocol-model.ts). The hello
+// lists `profiles` in place of `features`; the earlier route modes, `probe`/`probed` and
+// `model-health` are gone. A host at 5 speaks nothing older about models.
+export const PROTOCOL_VERSION = 5;
/** Which agent runs a session's turns (work 082). Absent: claude. */
export type HarnessName = 'claude' | 'codex';
@@ -108,7 +110,7 @@ export interface SessionSpec {
sdkSessionId?: string;
/** Set once the host forked; present means the fork exists. */
forkPath?: string;
- /** Work 082: the agent that runs its turns; absent = claude. `codex` comes only with a chatgpt subscription route. */
+ /** Work 082: the agent that runs its turns; absent = claude. `codex` needs a route whose profile serves Codex. */
harness?: HarnessName;
}
@@ -200,59 +202,11 @@ export interface HostCredentials {
slackBotToken: string;
slackBotUserId: string;
teamId?: string;
- /** Exactly one of these. */
- claudeOAuthToken?: string;
- anthropicApiKey?: string;
/**
- * With anthropicApiKey: an Anthropic-compatible endpoint the key belongs to
- * (work 052: the organization's metered model key, https://openrouter.ai/api).
- * The runner sets ANTHROPIC_BASE_URL and passes the key as ANTHROPIC_AUTH_TOKEN.
+ * Host → runner only (work 097, C4): the session's route as its runner knows it, or why there is none it can run on.
+ * Absent: no change (the host does not know the route yet, or the proxy is down).
*/
- anthropicBaseUrl?: string;
- /** Work 077: the session runs on its owner's subscription through the proxy; set only with no Claude fields. */
- claudeSubscription?: ClaudeSubscription;
-}
-
-/**
- * Which model credential a session runs on (work 077). `subscription`: its
- * owner's Claude Pro/Max seat, or (work 082, `provider: 'chatgpt'`) their
- * ChatGPT plan, through the VM's oc-modelproxy; the token goes to the proxy
- * only, never to a runner. A chatgpt route's `fingerprint` names the owner
- * and account, not the token (credential-fingerprint.ts), so a refreshed
- * token is the same credential and the proxy swaps it in place.
- * `managed`: the delivery's (or the welcome's) `credentials`, as before 077.
- * `refuse`: only on `model` pushes.
- */
-export type ModelRoute =
- | {
- mode: 'subscription';
- /** Absent: anthropic. */
- provider?: ModelProvider;
- owner: string;
- token: string;
- fingerprint: string;
- /** chatgpt: required (the proxy sends it upstream as `chatgpt-account-id`). */
- accountId?: string;
- maxModel?: string;
- }
- | { mode: 'managed' }
- | { mode: 'refuse'; reason: string };
-
-/** A subscription's usage windows, as Anthropic's rate-limit headers and /api/oauth/usage give them. */
-export interface ModelUsage {
- fiveHourPct?: number;
- fiveHourReset?: number;
- sevenDayPct?: number;
- sevenDayReset?: number;
-}
-
-/** What a runner on a subscription knows of it: never the token. */
-export interface ClaudeSubscription {
- owner: string;
- fingerprint: string;
- maxModel?: string;
- /** Work 082: whose subscription the fingerprint is (absent: anthropic). The field keeps its v2 name for wire compatibility. */
- provider?: ModelProvider;
+ model?: RunnerModel | RunnerRefused;
}
/** A session asks for a new thread to run work in parallel (work 047). */
@@ -365,11 +319,8 @@ export type TokenKind = 'github' | 'opencomputer' | 'automation-repo';
/** Sent by the host. The host authenticates with `Authorization: Bearer <host token>` on the upgrade. */
export type HostToGateway =
- /**
- * `features`: `model-proxy` once this host runs as sp-host with oc-modelproxy's control socket up (work 077);
- * `model-proxy/chatgpt` too when that proxy's own hello lists `chatgpt` among its providers (work 082).
- */
- | { t: 'hello'; protocol: number; hostId: string; version: string; sessions: SessionReport[]; features?: string[]; journals?: JournalReport[] }
+ /** `profiles` (work 097): the model proxy's, while the host is connected to it; a change re-sends the hello. */
+ | { t: 'hello'; protocol: number; hostId: string; version: string; sessions: SessionReport[]; profiles?: ModelProfile[]; journals?: JournalReport[] }
| { t: 'session'; report: SessionReport }
| { t: 'workspace'; status: WorkspaceStatus }
/**
@@ -392,17 +343,8 @@ export type HostToGateway =
| { t: 'unpreview'; id: string; from: string; req: { name: string } }
/** The model provider refused session `sessionKey`'s turn for credits (a 402): the gateway tells the thread how to get more. */
| { t: 'out-of-credits'; sessionKey: string }
- /** Work 077: answers `probe`. `error` is a class only ('timeout' | 'proxy_unavailable' | 'error'), never an error's text. */
- | { t: 'probed'; id: string; result?: { status: number; usage?: ModelUsage }; error?: string }
- /** A session's route took effect at the proxy (subscription, refuse) or at a runner start (managed). */
- | { t: 'model-bound'; sessionKey: string; mode: ModelRoute['mode']; fingerprint?: string }
- /** A subscription's health, on change and at most once a minute otherwise; `unauthorized` is one upstream 401. */
- /** Work 082: `provider` is whose upstream answered (absent: anthropic); a chatgpt `unauthorized` asks the gateway for a refreshed token. */
- | { t: 'model-health'; sessionKey: string; fingerprint: string; provider?: ModelProvider; status: 'ok' | 'limited' | 'unauthorized' | 'error';
- limitedUntil?: number; errorClass?: string; usage?: ModelUsage }
- /** The seat refused `model`; the session now runs on `fallbackTo`. */
- | { t: 'model-denied'; sessionKey: string; model: string; fallbackTo: string }
| { t: 'reply'; id: string; ok: boolean; error?: string }
+ | HostToGatewayModel
| HostToGatewayV4;
export type GatewayToHost =
@@ -415,6 +357,8 @@ export type GatewayToHost =
t: 'welcome';
protocol: number;
credentials: HostCredentials;
+ /** Work 097: the route of a session whose own delivery carries none, by harness. */
+ models?: ModelRoutes;
people: Person[];
definition?: WorkspaceDefinition;
telemetryCredential?: string;
@@ -433,21 +377,14 @@ export type GatewayToHost =
* keep this identity and reconnect as it. Refused by any other host.
*/
| { t: 'assign'; organizationId: string; hostToken: string; gatewayUrl: string }
- /** Credentials changed (fresh Slack install, new Claude token): replaces the welcome's; the host forwards to runners. */
- | { t: 'credentials'; credentials: HostCredentials }
+ /** Credentials changed (fresh Slack install, a new model credential): replaces the welcome's; the host forwards the Slack ones to runners and rebinds sessions on changed `models`. */
+ | { t: 'credentials'; credentials: HostCredentials; models?: ModelRoutes }
/** Start the runner if needed (fork if no forkPath, resume if sdkSessionId), then deliver. */
/** Per-delivery credentials let a multi-tenant gateway keep workspace tokens scoped to one session. */
- /** `model` (work 077): the session's route; absent means managed (gateways before 077). */
+ /** `model` (work 097): the session's route; absent: the one it had, else `models[harness]`. */
/** Work 084: `epoch` and `lastSeq` seed the session's journal as on `start` (absent: 1 and 0, or the local journal's). */
| { t: 'deliver'; id: string; session: SessionSpec; msg: Delivery; credentials?: HostCredentials; secrets?: SessionSecret[]; trace?: TraceContext;
model?: ModelRoute; epoch?: number; lastSeq?: number }
- /** Work 077: a session's route changed (pause, limit, revoke, policy); applied by the proxy or at the runner's next start. */
- | { t: 'model'; sessionKey: string; model: ModelRoute }
- /**
- * Work 077: validate a Claude token (GET /api/oauth/usage through the proxy); answered by `probed`.
- * Work 082: `provider`/`accountId` for a ChatGPT token (absent: anthropic).
- */
- | { t: 'probe'; id: string; token: string; provider?: ModelProvider; accountId?: string }
/** A session's secrets changed: the host passes them to its runner, if one is running. */
| { t: 'secrets'; sessionKey: string; secrets: SessionSecret[] }
/** A button click on a prompt the session's runner posted. */
@@ -464,6 +401,7 @@ export type GatewayToHost =
| { t: 'previewed'; id: string; result?: PreviewResult; error?: string }
| { t: 'secret-asked'; id: string; error?: string }
| { t: 'reply'; id: string; ok: boolean; error?: string }
+ | GatewayToHostModel
| GatewayToHostV4;
// ---------------------------------------------------------------- host ⇄ runner
@@ -492,8 +430,8 @@ export interface SpareReport {
/** Parked and claimable; false while (re)starting its Claude Code. */
ready: boolean;
version: string;
- /** Fingerprint of the Claude credential it was started with (credential-fingerprint.ts). */
- credential?: string;
+ /** What its harness was started for (model-key.ts `spareKind`, design C6): a session with the same kind may claim it. */
+ kind?: string;
}
export type HostToRunner =
diff --git a/computer/src/runner-env.ts b/computer/src/runner-env.ts
index 506fc880..26abdd8a 100644
--- a/computer/src/runner-env.ts
+++ b/computer/src/runner-env.ts
@@ -7,7 +7,7 @@
// the host sets every variable here on every launch, from its own
// environment: one it lacks is set empty, and a runner treats empty as unset
// (it deletes them before anything reads them). No session can choose
-// another runner's model socket, Codex binary or PATH.
+// another runner's Codex binary or PATH.
//
// Invariants:
// - every name in RUNNER_ENV is in every launch's variables, empty or not;
@@ -19,7 +19,7 @@ export const RUNNER_ENV = [
'PATH', 'HOME', 'USER', 'SHELL', 'LANG', 'TMPDIR', 'CLAUDE_CONFIG_DIR', 'SP_RUN', 'SP_DATA', 'SP_DEFINITION', 'SP_VERSION',
'SP_COMMITTER_NAME', 'SP_COMMITTER_EMAIL', 'SP_REAL_GH', 'SP_REAL_OPENCOMPUTER', 'SP_FAKE_SLACK', 'SP_SLACK_API_URL', 'MODEL', 'FOLD_AT', 'WORKDIR',
'PERMISSION_MODE', 'DISABLE_AUTOUPDATER', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM', 'SP_REGION', 'SP_SUBSTRATE',
- 'SP_PROMPT_CACHE_TTL', 'SP_CONTEXT_WINDOW', 'SP_COMPACT_AT', 'SP_PROMPT_GUARD', 'SP_MODEL_SOCKET', 'SP_CODEX_BIN', 'SP_CODEX_PEER_CHECK',
+ 'SP_PROMPT_CACHE_TTL', 'SP_CONTEXT_WINDOW', 'SP_COMPACT_AT', 'SP_PROMPT_GUARD', 'SP_CODEX_BIN', 'SP_CODEX_PEER_CHECK',
// Unset on a computer's host, but inherited each would run a session's code in, or route the traffic of,
// another session's runner. The host's own value when it has one (a laptop's proxy).
'NODE_OPTIONS', 'NODE_PATH', 'NODE_EXTRA_CA_CERTS', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'BASH_ENV',
diff --git a/computer/src/runner/cache-ttl.test.ts b/computer/src/runner/cache-ttl.test.ts
index 03a15b80..28a0527b 100644
--- a/computer/src/runner/cache-ttl.test.ts
+++ b/computer/src/runner/cache-ttl.test.ts
@@ -1,33 +1,29 @@
import { describe, expect, it } from 'vitest';
import { applyPromptCacheTtl, presetTtls, promptCacheTtls } from './cache-ttl.js';
-describe('prompt cache TTL', () => {
- it('1h for main and subagents on Anthropic’s own API', () => {
- expect(promptCacheTtls(undefined, {}, undefined)).toEqual({ CLAUDE_CODE_PROMPT_CACHE_TTL: '1h', CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: '1h' });
- });
+const none = { explicit: undefined, preset: {} };
- it('Claude Code’s default through a compatible endpoint, unless asked', () => {
- const url = 'https://openrouter.ai/api';
- expect(promptCacheTtls(undefined, {}, url)).toEqual({ CLAUDE_CODE_PROMPT_CACHE_TTL: undefined, CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: undefined });
- expect(promptCacheTtls('1h', {}, url).CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('1h');
+describe('prompt cache TTL', () => {
+ it('the profile’s promptCacheTtl, for main and subagents', () => {
+ expect(promptCacheTtls(none, '1h')).toEqual({ CLAUDE_CODE_PROMPT_CACHE_TTL: '1h', CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: '1h' });
});
- it('1h through a subscription’s tunnel, which names Anthropic’s API (work 077)', () => {
- expect(promptCacheTtls(undefined, {}, 'http://api.anthropic.com').CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('1h');
+ it('Claude Code’s default when nothing asks', () => {
+ expect(promptCacheTtls(none, undefined)).toEqual({ CLAUDE_CODE_PROMPT_CACHE_TTL: undefined, CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL: undefined });
});
- it('SP_PROMPT_CACHE_TTL wins over the variables the process started with', () => {
- expect(promptCacheTtls('5m', { CLAUDE_CODE_PROMPT_CACHE_TTL: '1h' }, undefined).CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('5m');
- expect(promptCacheTtls(undefined, { CLAUDE_CODE_PROMPT_CACHE_TTL: '5m' }, undefined).CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('5m');
+ it('SP_PROMPT_CACHE_TTL, then the preset, then the profile', () => {
+ expect(promptCacheTtls({ explicit: '5m', preset: { CLAUDE_CODE_PROMPT_CACHE_TTL: '1h' } }, '1h').CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('5m');
+ expect(promptCacheTtls({ explicit: undefined, preset: { CLAUDE_CODE_PROMPT_CACHE_TTL: '5m' } }, '1h').CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('5m');
+ expect(promptCacheTtls({ explicit: '1h', preset: {} }, undefined).CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL).toBe('1h');
});
- it('follows the endpoint when the credentials change', () => {
+ it('sets and clears the variables in an environment', () => {
const env: NodeJS.ProcessEnv = {};
- const preset = presetTtls(env);
- applyPromptCacheTtl(env, undefined, preset);
+ const o = { explicit: undefined, preset: presetTtls(env) };
+ applyPromptCacheTtl(env, o, '1h');
expect(env.CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL).toBe('1h');
- env.ANTHROPIC_BASE_URL = 'https://openrouter.ai/api';
- applyPromptCacheTtl(env, undefined, preset);
+ applyPromptCacheTtl(env, o, undefined);
expect(env.CLAUDE_CODE_PROMPT_CACHE_TTL).toBeUndefined();
});
});
diff --git a/computer/src/runner/cache-ttl.ts b/computer/src/runner/cache-ttl.ts
index ca930680..6e4aec71 100644
--- a/computer/src/runner/cache-ttl.ts
+++ b/computer/src/runner/cache-ttl.ts
@@ -1,37 +1,35 @@
// Claude Code's prompt cache TTL (CLAUDE_CODE_PROMPT_CACHE_TTL, and the
-// subagent one), decided where a process starts and again whenever its Claude
-// endpoint changes; the harness copies the environment when it spawns.
+// subagent one), decided where a process starts and again when its model
+// route arrives; the harness copies the environment when it spawns.
//
-// Why 1 hour: on an API key Claude Code caches for 5 minutes, and telemetry
-// showed every turn after a longer pause re-writing the whole 190–330k-token
-// conversation, 11–14 s to the first token. 1-hour cache writes cost 2× base
-// input instead of 1.25×; one avoided rewrite pays for it.
+// Why a profile asks for 1 hour: on an API key Claude Code caches for 5
+// minutes, and telemetry showed every turn after a longer pause re-writing the
+// whole 190–330k-token conversation, 11–14 s to the first token. 1-hour cache
+// writes cost 2× base input instead of 1.25×; one avoided rewrite pays for it.
+// Which endpoints take it is the model profile's to say (its Claude Code
+// `promptCacheTtl`, work 097 C5), not something guessed from a base URL.
//
-// Only on Anthropic's own API by default: through an Anthropic-compatible
-// endpoint (an organization's OpenRouter key, work 052) the 1-hour TTL is
-// documented by OpenRouter (`cache_control.ttl: "1h"` on its Messages API)
-// but untested with Claude Code, which also sends the
-// `extended-cache-ttl-2025-04-11` beta. There it stays Claude Code's default
-// unless SP_PROMPT_CACHE_TTL is set.
+// Order: SP_PROMPT_CACHE_TTL, then what the process was started with (the
+// preset), then the profile's `promptCacheTtl`, else Claude Code's default.
const VARS = ['CLAUDE_CODE_PROMPT_CACHE_TTL', 'CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL'] as const;
-type Ttls = Partial<Record<(typeof VARS)[number], string>>;
+export type Ttls = Partial<Record<(typeof VARS)[number], string>>;
-/**
- * Both TTL variables for an endpoint (`baseUrl` unset: Anthropic's own);
- * undefined leaves Claude Code's default. `explicit` (SP_PROMPT_CACHE_TTL)
- * wins, then what the process was started with (`preset`).
- */
-export function promptCacheTtls(explicit: string | undefined, preset: Ttls, baseUrl: string | undefined): Record<(typeof VARS)[number], string | undefined> {
- // A subscription's tunnel (work 077) names Anthropic's own API over the proxy's socket.
- const dflt = !baseUrl || /^https?:\/\/api\.anthropic\.com\/?$/.test(baseUrl) ? '1h' : undefined;
- return Object.fromEntries(VARS.map((k) => [k, explicit || preset[k] || dflt])) as Record<(typeof VARS)[number], string | undefined>;
+/** SP_PROMPT_CACHE_TTL and the preset, as runner/main.ts read them at start. */
+export interface CacheTtlSettings {
+ explicit: string | undefined;
+ preset: Ttls;
}
-/** Set (or clear) both TTL variables in `env` for its current endpoint. */
-export function applyPromptCacheTtl(env: NodeJS.ProcessEnv, explicit: string | undefined, preset: Ttls) {
- for (const [k, v] of Object.entries(promptCacheTtls(explicit, preset, env.ANTHROPIC_BASE_URL))) {
+/** Both TTL variables for a route whose profile asks for `profile`; undefined leaves Claude Code's default. */
+export function promptCacheTtls(o: CacheTtlSettings, profile: string | undefined): Record<(typeof VARS)[number], string | undefined> {
+ return Object.fromEntries(VARS.map((k) => [k, o.explicit || o.preset[k] || profile])) as Record<(typeof VARS)[number], string | undefined>;
+}
+
+/** Set (or clear) both TTL variables in `env`. */
+export function applyPromptCacheTtl(env: NodeJS.ProcessEnv, o: CacheTtlSettings, profile: string | undefined) {
+ for (const [k, v] of Object.entries(promptCacheTtls(o, profile))) {
if (v) env[k] = v;
else delete env[k];
}
diff --git a/computer/src/runner/commands.ts b/computer/src/runner/commands.ts
index cabc1030..15476569 100644
--- a/computer/src/runner/commands.ts
+++ b/computer/src/runner/commands.ts
@@ -86,7 +86,7 @@ export async function runCommand(s: CommandHost, cmd: string | undefined, arg: s
async function restart(s: CommandHost) {
if (!s.hooks.restart) return s.say('`!restart` works on a hosted runner; here, restart the process');
const latest = latestRelease();
- // Restart even on the newest version: a new agent process also picks up rotated Claude credentials.
+ // Restart even on the newest version: a new agent process also starts from a clean environment.
const to = latest && latest !== bootCommit ? ` → \`${latest}\`` : '';
await s.say(
s.isBusy
diff --git a/computer/src/runner/harness/claude/model-env.test.ts b/computer/src/runner/harness/claude/model-env.test.ts
new file mode 100644
index 00000000..1f42607e
--- /dev/null
+++ b/computer/src/runner/harness/claude/model-env.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { CLAUDE_MODEL_VARS, type ClaudeModel, claudeModelEnv, clearClaudeModelEnv } from './model-env.js';
+
+const SECRET = 'sk-ant-real-credential';
+const TTL = { explicit: undefined, preset: {} };
+
+describe("Claude Code's model environment (work 097 C5)", () => {
+ it.each(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN'] as const)(
+ 'tokenEnv %s: the runner environment holds only the placeholder, never a credential',
+ (tokenEnv) => {
+ // Whatever the process was started with, no credential survives.
+ const env: NodeJS.ProcessEnv = Object.fromEntries(CLAUDE_MODEL_VARS.map((k) => [k, SECRET]));
+ claudeModelEnv(env, { tokenEnv } satisfies ClaudeModel, '/run/api.sock', 'ph', TTL);
+ expect(Object.values(env)).not.toContain(SECRET);
+ const creds = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN'].flatMap((k) => (env[k] ? [env[k]] : []));
+ expect(creds).toEqual(['ph']);
+ },
+ );
+
+ it('clearing removes every model variable', () => {
+ const env: NodeJS.ProcessEnv = { HOME: '/h' };
+ claudeModelEnv(env, { tokenEnv: 'ANTHROPIC_AUTH_TOKEN' }, '/run/api.sock', 'ph', TTL);
+ clearClaudeModelEnv(env);
+ for (const k of CLAUDE_MODEL_VARS) expect(env).not.toHaveProperty(k);
+ });
+});
diff --git a/computer/src/runner/harness/claude/model-env.ts b/computer/src/runner/harness/claude/model-env.ts
new file mode 100644
index 00000000..b9343a0c
--- /dev/null
+++ b/computer/src/runner/harness/claude/model-env.ts
@@ -0,0 +1,49 @@
+// Claude Code's model adapter (work 097, design C5): what a model profile's
+// `harness.claude` object means for the environment Claude Code is spawned
+// from. Claude Code talks to the model proxy's API socket in its tunnel mode
+// (ANTHROPIC_UNIX_SOCKET under Anthropic's base URL) and holds only the
+// placeholder, in the variable the profile's `tokenEnv` names; the proxy puts
+// the credential on each request.
+//
+// Invariants:
+// - No credential value is ever set here: every Claude credential variable is
+// the placeholder, '' or unset (the env test in model-env.test.ts).
+// - The object is validated whole: an unknown field or another `tokenEnv` is
+// malformed, and malformed sets nothing (model-access.ts refuses the turn).
+
+import { z } from 'zod';
+import { type CacheTtlSettings, applyPromptCacheTtl } from '../../cache-ttl.js';
+
+/** The profile's `harness.claude` (design C5, C7). */
+export const ClaudeModel = z.strictObject({
+ /** The variable Claude Code reads its credential from: here, the placeholder. */
+ tokenEnv: z.enum(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN']),
+ /** Claude Code's prompt cache TTL on this route (cache-ttl.ts), e.g. `1h`. */
+ promptCacheTtl: z.string().min(1).optional(),
+ /** A refused model steps down a family and the turn is retried (model-downgrade.ts). */
+ downgradeOnModelRefusal: z.boolean().optional(),
+});
+export type ClaudeModel = z.infer<typeof ClaudeModel>;
+
+/** Every variable Claude Code may take a credential or an endpoint from. */
+export const CLAUDE_MODEL_VARS = [
+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_UNIX_SOCKET',
+] as const;
+
+/** Point Claude Code in `env` at the proxy's socket `unixSocket`, with `placeholder` in `m.tokenEnv`. */
+export function claudeModelEnv(env: NodeJS.ProcessEnv, m: ClaudeModel, unixSocket: string, placeholder: string, ttl: CacheTtlSettings) {
+ for (const k of CLAUDE_MODEL_VARS) delete env[k];
+ env.ANTHROPIC_BASE_URL = 'http://api.anthropic.com';
+ env.ANTHROPIC_UNIX_SOCKET = unixSocket;
+ // Remote settings and other extras would go direct, around the socket.
+ env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1';
+ env[m.tokenEnv] = placeholder;
+ // A bearer token with an empty API key, so that none is sent in its place.
+ if (m.tokenEnv === 'ANTHROPIC_AUTH_TOKEN') env.ANTHROPIC_API_KEY = '';
+ applyPromptCacheTtl(env, ttl, m.promptCacheTtl);
+}
+
+/** No route: none of the model variables (a spare claimed for Codex). */
+export function clearClaudeModelEnv(env: NodeJS.ProcessEnv) {
+ for (const k of CLAUDE_MODEL_VARS) delete env[k];
+}
diff --git a/computer/src/runner/harness/claude/spare.test.ts b/computer/src/runner/harness/claude/spare.test.ts
index 58966d92..65717f57 100644
--- a/computer/src/runner/harness/claude/spare.test.ts
+++ b/computer/src/runner/harness/claude/spare.test.ts
@@ -16,18 +16,18 @@ function holder(procs: ReturnType<typeof fake>[]) {
}
describe('Spare', () => {
- it('parks a process, keeps it for the same credential and replaces it for another', async () => {
+ it('parks a process, keeps it for the same kind and replaces it for another', async () => {
const a = fake();
const b = fake();
const { spare, log } = holder([a, b]);
- spare.warm('fp1');
+ spare.warm('k1');
expect(spare.ready).toBe(false);
await tick();
expect(spare.ready).toBe(true);
- spare.warm('fp1');
- spare.warm('fp2');
+ spare.warm('k1');
+ spare.warm('k2');
expect(a.p.closed).toBe(true);
- expect(spare.credential).toBe('fp2');
+ expect(spare.kind).toBe('k2');
await tick();
expect(spare.take()).toBe(b.p);
expect(spare.ready).toBe(false);
@@ -40,7 +40,7 @@ describe('Spare', () => {
it('reports a parked process that exits', async () => {
const a = fake();
const { spare, log } = holder([a]);
- spare.warm('fp');
+ spare.warm('k');
await tick();
a.exit();
await tick();
@@ -55,8 +55,8 @@ describe('Spare', () => {
const gate = new Promise<void>((r) => (release = r));
let n = 0;
const spare = new Spare(async () => (n++ === 0 ? (await gate, a.p) : b.p), { changed: () => {}, died: () => {} });
- spare.warm('fp1');
- spare.warm('fp2');
+ spare.warm('k1');
+ spare.warm('k2');
await tick();
release();
await tick();
diff --git a/computer/src/runner/harness/claude/spare.ts b/computer/src/runner/harness/claude/spare.ts
index 7d903e92..bb6eef0b 100644
--- a/computer/src/runner/harness/claude/spare.ts
+++ b/computer/src/runner/harness/claude/spare.ts
@@ -1,11 +1,10 @@
// A spare runner's parked Claude Code (work 069): started before any session
-// is known, with the Claude credential the host gave it, and handed over
-// whole to the session that claims the runner.
+// is known, on the model route the host gave it, and handed over whole to
+// the session that claims the runner.
//
// Invariants: at most one process is parked, and it was started with the
-// credential `credential` names (its fingerprint): Claude Code copies the
-// environment when it starts, so a new credential means close and start
-// again. A parked process that goes away, or never starts, is reported as
+// environment `kind` names (model-key.ts `spareKind`): Claude Code copies the
+// environment when it starts, so another kind means close and start again. A parked process that goes away, or never starts, is reported as
// `died`: the runner exits and the host starts another spare. Taken or
// closed, a process is no longer this holder's to report.
@@ -20,7 +19,7 @@ export interface SpareEvents {
export class Spare {
private p?: SpareProcess;
- private fp?: string;
+ private k?: string;
/** Bumped by every start, take and close: a start that finishes late is closed, not parked. */
private gen = 0;
@@ -34,16 +33,16 @@ export class Spare {
return !!this.p;
}
- /** The fingerprint of the credential the process was (or is being) started with. */
- get credential() {
- return this.fp;
+ /** The kind of environment the process was (or is being) started with. */
+ get kind() {
+ return this.k;
}
- /** Park a process started with the credential now in the environment; a different credential replaces it. */
- warm(credential: string) {
- if (credential === this.fp) return;
+ /** Park a process started with the environment now set, of `kind`; another kind replaces it. */
+ warm(kind: string) {
+ if (kind === this.k) return;
this.close();
- this.fp = credential;
+ this.k = kind;
const gen = this.gen;
this.on.changed();
this.start().then(
diff --git a/computer/src/runner/harness/codex/config.test.ts b/computer/src/runner/harness/codex/config.test.ts
index 374ff417..f3378b17 100644
--- a/computer/src/runner/harness/codex/config.test.ts
+++ b/computer/src/runner/harness/codex/config.test.ts
@@ -58,7 +58,6 @@ persistence = "none"
HOME: '/home/agent',
SP_FILES_SOCKET: '/run/r1.files',
SP_TOKEN_SOCKET: '/run/token.sock',
- SP_MODEL_SOCKET: '/run/model.sock',
CLAUDE_ENV_FILE: '/c.sh',
RUNNER_SPEC: '{}',
OPENAI_API_KEY: 'k',
@@ -70,7 +69,7 @@ persistence = "none"
AZURE_OPENAI_API_KEY: 'k',
BASH_ENV: '/runner/own.sh',
},
- { home: '/h', envFile: '/e.sh' },
+ { home: '/h', envFile: '/e.sh', placeholder: 'ssh-placeholder' },
);
expect(env).toEqual({
PATH: '/bin',
@@ -81,6 +80,6 @@ persistence = "none"
RUST_LOG: 'warn',
BASH_ENV: '/e.sh',
});
- expect(spawnEnv({ BASH_ENV: '/runner/own.sh' }, { home: '/h' })).not.toHaveProperty('BASH_ENV');
+ expect(spawnEnv({ BASH_ENV: '/runner/own.sh' }, { home: '/h', placeholder: 'p' })).not.toHaveProperty('BASH_ENV');
});
});
diff --git a/computer/src/runner/harness/codex/config.ts b/computer/src/runner/harness/codex/config.ts
index 20f59376..afd67843 100644
--- a/computer/src/runner/harness/codex/config.ts
+++ b/computer/src/runner/harness/codex/config.ts
@@ -1,7 +1,8 @@
// Where a session's Codex keeps its state, what it is configured with, and
// the environment it runs in (work 082, contract sections 1 and 5). Codex
// reaches the model only through Calvin's loopback (loopback.ts) as a custom
-// provider in API-key mode, with a placeholder the proxy replaces.
+// provider in API-key mode, with the placeholder the proxy replaces (the
+// host's, in the session's route: work 097 C4).
//
// Invariants:
// - one CODEX_HOME per session, named by a hash of its key, mode 0700, under
@@ -13,8 +14,8 @@
// - no auth.json is ever written;
// - the child's environment is an allow-list (CHILD_ENV): what launch.ts
// passes a runner that commands need, and what Calvin's bin/ shims read.
-// No credential, no runner-internal socket (SP_TOKEN_SOCKET,
-// SP_MODEL_SOCKET) and nothing that would change Codex's auth or endpoint
+// No credential, no runner-internal socket (SP_TOKEN_SOCKET, the model
+// proxy's) and nothing that would change Codex's auth or endpoint
// (`OPENAI_*`, `CODEX_*`) reaches Codex or the commands it runs;
// - the placeholder never reaches commands Codex runs (shell policy excludes
// it);
@@ -24,8 +25,6 @@
import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
-/** What Codex sends as its key; the proxy replaces it (as for Claude, work 077). */
-export const PLACEHOLDER = 'ssh-placeholder';
/** The variable Codex reads its provider key (the placeholder) from. */
export const KEY_VAR = 'CALVIN_MODEL_KEY';
export const PROVIDER = 'calvin';
@@ -108,11 +107,11 @@ export function writeHome(home: string, toml: string) {
* placeholder, Codex's log level, and the session's secrets sourced before each
* command Codex runs through bash (as CLAUDE_ENV_FILE does for Claude).
*/
-export function spawnEnv(base: NodeJS.ProcessEnv, o: { home: string; envFile?: string }): NodeJS.ProcessEnv {
+export function spawnEnv(base: NodeJS.ProcessEnv, o: { home: string; envFile?: string; placeholder: string }): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {};
for (const k of CHILD_ENV) if (base[k] !== undefined) env[k] = base[k];
env.CODEX_HOME = o.home;
- env[KEY_VAR] = PLACEHOLDER;
+ env[KEY_VAR] = o.placeholder;
env.RUST_LOG = 'warn';
if (o.envFile) env.BASH_ENV = o.envFile;
return env;
diff --git a/computer/src/runner/harness/codex/harness.test.ts b/computer/src/runner/harness/codex/harness.test.ts
index 70d7ca6c..28149cea 100644
--- a/computer/src/runner/harness/codex/harness.test.ts
+++ b/computer/src/runner/harness/codex/harness.test.ts
@@ -51,7 +51,7 @@ function start(name: string, spec: Partial<StartSpec> = {}, env: Record<string,
const kind = codexKind(
{
bin: launcher({ FAKE_CODEX_TRANSCRIPT: transcript(name), FAKE_CODEX_LOG: logFile, ...env }),
- socket: path.join(dir, 'model.sock'),
+ endpoint: () => ({ unixSocket: path.join(dir, 'model.sock'), placeholder: 'ssh-placeholder' }),
root: path.join(dir, 'codex'),
peerCheck: false,
env: {
@@ -312,7 +312,7 @@ describe('CodexHarness', () => {
});
const bare = (bin: string, socket?: string) => {
- const run = codexKind({ bin, socket, root: dir, peerCheck: false, env: {}, version: '0' }, 'k').start({
+ const run = codexKind({ bin, endpoint: () => (socket ? { unixSocket: socket, placeholder: 'p' } : undefined), root: dir, peerCheck: false, env: {}, version: '0' }, 'k').start({
cwd: dir,
mode: 'default',
model: 'm',
diff --git a/computer/src/runner/harness/codex/harness.ts b/computer/src/runner/harness/codex/harness.ts
index 4cc069e2..05b15420 100644
--- a/computer/src/runner/harness/codex/harness.ts
+++ b/computer/src/runner/harness/codex/harness.ts
@@ -62,8 +62,8 @@ export const CODEX_CAPS: Capabilities = {
export interface CodexOptions {
/** The `codex` launcher (SP_CODEX_BIN). */
bin: string;
- /** oc-modelproxy's socket (SP_MODEL_SOCKET); absent or missing, Codex has no model and fails to start. */
- socket?: string;
+ /** The model proxy's API socket and placeholder, from the session's route (work 097 C4), read at each start; absent or missing, Codex has no model and fails to start. */
+ endpoint(): { unixSocket: string; placeholder: string } | undefined;
/** Where sessions' CODEX_HOMEs live: a directory the runner's user owns (main.ts: under its HOME). */
root: string;
/** Attest each loopback peer's cgroup (loopback.ts); false only where runners are not systemd units (SP_CODEX_PEER_CHECK=off). */
@@ -176,8 +176,9 @@ export class CodexHarness implements Harness {
private async boot(spec: StartSpec, o: CodexOptions) {
const t0 = performance.now();
// Codex reaches a model only through the proxy (no credential of its own): no socket, no Codex.
- if (!o.socket || !existsSync(o.socket)) throw new HarnessFailed({ reason: 'exit', message: 'harness unavailable: codex (this computer has no model proxy)' });
- const { port } = await loopback(o.socket, { peerCheck: o.peerCheck, checked: o.peerChecked });
+ const model = o.endpoint();
+ if (!model || !existsSync(model.unixSocket)) throw new HarnessFailed({ reason: 'exit', message: 'harness unavailable: codex (this computer has no model proxy)' });
+ const { port } = await loopback(model.unixSocket, { peerCheck: o.peerCheck, checked: o.peerChecked });
if (this.closed) throw new HarnessFailed({ reason: 'exit', message: 'closed before it started' });
const home = codexHome(o.root, o.sessionKey);
writeHome(home, configToml({ model: this.model, port, cwd: spec.cwd }));
@@ -185,7 +186,7 @@ export class CodexHarness implements Harness {
bin: o.bin,
args: ['app-server'],
cwd: spec.cwd,
- env: spawnEnv(o.env, { home, envFile: o.envFile }),
+ env: spawnEnv(o.env, { home, envFile: o.envFile, placeholder: model.placeholder }),
onNotification: (m, p) => this.note(m, p),
onRequest: (m, p, id) => this.served.request(m, p, id),
onClose: (why) => {
diff --git a/computer/src/runner/harness/codex/loopback.ts b/computer/src/runner/harness/codex/loopback.ts
index 781455bb..58a38556 100644
--- a/computer/src/runner/harness/codex/loopback.ts
+++ b/computer/src/runner/harness/codex/loopback.ts
@@ -7,7 +7,7 @@
//
// Threat model. A port on 127.0.0.1 is open to every process on the
// computer, and through it they would reach the model as this runner (its
-// session's subscription). Every session's runner, Codex and commands run as
+// session's model credential). Every session's runner, Codex and commands run as
// the same user, so nothing in Codex's environment or files is secret from
// another session: a shared key (this file's first design) was readable from
// /proc/<codex>/environ. What another session cannot fake is where it runs:
diff --git a/computer/src/runner/main.ts b/computer/src/runner/main.ts
index 9a746046..465a04a5 100644
--- a/computer/src/runner/main.ts
+++ b/computer/src/runner/main.ts
@@ -9,18 +9,20 @@
// (spare.ts) and reports `spare` until the host `claim`s it for a session,
// whose fork is complete by then; from there it is that session's runner.
// Its socket, unit and secrets are named by its id, not the session.
+// A spare's kind (model-key.ts `spareKind`) is the route it parked on's.
//
// The session's harness is its spec's (work 082): Claude Code, or Codex for
// `harness: 'codex'`. harness/codex/ is imported only then, so a Claude
// runner neither loads nor parses it. A spare parks Claude Code; claimed for
-// a Codex session it closes it, drops the managed Claude credential it parked
-// with, and starts Codex as a cold runner would, minus the runner's launch.
+// a Codex session it closes it, drops the model route it parked with, and
+// starts Codex as a cold runner would, minus the runner's launch.
//
// RUNNER_SPEC='<RunnerSpec JSON>' node --import tsx src/runner/main.ts
//
-// Credentials arrive as a `credentials` message (or SLACK_BOT_TOKEN /
-// CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the environment) and are kept
-// in memory and in this process's environment only. Secrets people give the
+// Credentials arrive as a `credentials` message (or SLACK_BOT_TOKEN in the
+// environment) and are kept in memory only. The model's never reach a runner:
+// the message's `model` names the session's route through the host's model
+// proxy (model-access.ts, work 097). Secrets people give the
// session (work 046) arrive as `secrets` before deliveries and on change; see
// session-secrets.ts for how they reach commands and stay out of Slack.
// Work 084: with RunnerSpec.api or claim.api it is the session's API writer too (api/attach.ts).
@@ -74,16 +76,14 @@ import { serveFiles } from './send-file-socket.js';
import { Waiters } from './waiters.js';
import { TurnEvents } from './turn-events.js';
import { sampleLoopLag } from './loop-lag.js';
-import { applyPromptCacheTtl, presetTtls } from './cache-ttl.js';
+import { presetTtls } from './cache-ttl.js';
import { configureCompaction } from './harness/claude/shadow.js';
import { Ordered } from './ordered.js';
import { Spare } from './harness/claude/spare.js';
import { claudeSpare } from './harness/claude/harness.js';
import { effortOf, speedOf } from './model-switch.js';
import { ensureSkills } from './skills.js';
-import { credentialFingerprint } from '../credential-fingerprint.js';
-import { MODEL_SOCKET } from './model-access.js';
-import { createRunnerModelAccess } from './model-access-impl.js';
+import { runnerModelAccess } from './model-access.js';
import type { Harness, HarnessKind } from './harness/types.js';
import { nameSession } from './harness/claude/title.js';
@@ -111,12 +111,6 @@ Object.assign(env, {
// Sourced by Claude Code before Bash commands: the session's secrets, current at each command.
CLAUDE_ENV_FILE: secrets.envFile,
});
-// Prompt cache TTL (cache-ttl.ts): 1 hour on Anthropic's own API, set again
-// whenever the credentials change the endpoint.
-const CACHE_TTL = env.SP_PROMPT_CACHE_TTL;
-const presetCacheTtl = presetTtls(env);
-const applyCacheTtl = () => applyPromptCacheTtl(env, CACHE_TTL, presetCacheTtl);
-applyCacheTtl();
configureCompaction(env); // between turns in a fork (shadow.ts), Claude Code's own as the backstop
// The gh shim (this release's bin/) goes first on PATH: gh gets a GitHub App
// token from the host's token socket, or runs as is when there is none. With a
@@ -159,15 +153,13 @@ setInterval(flushTelemetry, 2000).unref();
const turns = new TurnEvents(telemetry, {
model: () => s?.info.model,
tierOf, apiClients: () => api?.api.log.hub.clients, // Q1: turn.started splits by protocol and clients
- provider: () =>
- ss?.harness === 'codex' ? 'chatgpt-subscription'
- : sub.route() === 'subscription' ? 'anthropic-subscription' : env.ANTHROPIC_BASE_URL ? 'anthropic-compatible' : 'anthropic',
+ provider: () => sub.profile(),
});
sampleLoopLag((l) => turns.loopLag(l));
-// Work 097: the model access behind one seam (model-access.ts); hosted builds run the owner's Claude subscription
-// through oc-modelproxy (work 077; SP_MODEL_SOCKET: its socket, for tests).
-const sub = createRunnerModelAccess({ env, socket: env.SP_MODEL_SOCKET || undefined, hooks: {
+// Work 097: the session's route through the host's model proxy; the prompt cache TTL (cache-ttl.ts) comes with it.
+const sub = runnerModelAccess({ env, cacheTtl: { explicit: env.SP_PROMPT_CACHE_TTL, preset: presetTtls(env) }, hooks: {
session: () => s,
+ harness: () => ss?.harness ?? 'claude',
out: (m) => out(m),
downgraded: (from, to) => telemetry.emit('model.downgraded', { data: { from, to } }),
} });
@@ -185,52 +177,19 @@ const makeClient = (token?: string) =>
);
let botToken = env.SLACK_BOT_TOKEN;
-/** The Claude credential in this process's environment, as the harness copies it at spawn. */
-const claudeCredential = () =>
- [env.CLAUDE_CODE_OAUTH_TOKEN, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN, env.ANTHROPIC_BASE_URL].map((v) => v ?? '').join('\n');
-const hasClaudeCredential = () => !!(env.CLAUDE_CODE_OAUTH_TOKEN || env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN);
-/** The fingerprint of that credential, as the host computes it from the credentials it sends. */
-const claudeFingerprint = () =>
- credentialFingerprint({ claudeOAuthToken: env.CLAUDE_CODE_OAUTH_TOKEN, anthropicApiKey: env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_API_KEY,
- anthropicBaseUrl: env.ANTHROPIC_BASE_URL });
-
function applyCredentials(c: HostCredentials) {
- const before = claudeCredential();
- const route = sub.apply(c);
- if (route === 'switch') s && hooks.restart?.(); // a new route is a new harness environment: finish the turn, exit
- else if (c.claudeOAuthToken) {
- env.CLAUDE_CODE_OAUTH_TOKEN = c.claudeOAuthToken;
- delete env.ANTHROPIC_API_KEY;
- } else if (c.anthropicApiKey && c.anthropicBaseUrl) {
- // Another Anthropic-compatible endpoint (an organization's metered key,
- // work 052): bearer auth, and an empty API key so it is not sent instead.
- env.ANTHROPIC_BASE_URL = c.anthropicBaseUrl;
- env.ANTHROPIC_AUTH_TOKEN = c.anthropicApiKey;
- env.ANTHROPIC_API_KEY = '';
- delete env.CLAUDE_CODE_OAUTH_TOKEN;
- } else if (c.anthropicApiKey) {
- env.ANTHROPIC_API_KEY = c.anthropicApiKey;
- delete env.CLAUDE_CODE_OAUTH_TOKEN;
- }
- // A Claude credential without an endpoint means Anthropic's own: drop a
- // previous endpoint. Updates carrying no Claude credential change nothing.
- if (route === 'managed' && !c.anthropicBaseUrl) {
- delete env.ANTHROPIC_BASE_URL;
- delete env.ANTHROPIC_AUTH_TOKEN;
- }
- applyCacheTtl();
+ const route = sub.apply(c.model);
+ if (route === 'switch') hooks.restart?.(); // another harness environment: finish the turn, exit
if (c.slackBotToken && c.slackBotToken !== botToken) {
botToken = c.slackBotToken;
if (s?.thread.slack) s.client = makeClient(botToken);
}
- // The host sends credentials on connect, so the harness starts before the
- // first message; one no message went into yet restarts on a new credential
- // (a delivery's own, work 052). A harness in use keeps its own until `!restart`.
- // A spare parks one with them, and starts again on another.
- if (!hasClaudeCredential() || route === 'switch') return;
- // A Claude credential change replaces an unused Claude Code; Codex never reads one (it is on the proxy).
- if (s) s.prewarm(s.kind.id === 'claude' && claudeCredential() !== before);
- else spare?.warm(claudeFingerprint()!);
+ // The host sends credentials on connect, so Claude Code starts before the first
+ // message, replacing one no message went into yet. A spare parks one with them,
+ // and parks again on another kind. Codex starts at its first message.
+ if (route !== 'set') return;
+ if (s) s.kind.id === 'claude' && s.prewarm(true);
+ else spare?.warm(sub.kind()!);
}
// ---- the session
@@ -255,7 +214,7 @@ const report = (status: SessionReport['status'] = s!.isBusy ? 'busy' : 'idle'):
...(ss!.harness === 'codex' && { harness: 'codex' as const }), // absent for Claude: its report is unchanged
...(tasks.size > 0 && { subagents: tasks.size }), // absent: none (work 084)
});
-const sendSpare = () => spare && out({ t: 'spare', spare: { id: spec.id!, ready: spare.ready, version: spec.version, credential: spare.credential } });
+const sendSpare = () => spare && out({ t: 'spare', spare: { id: spec.id!, ready: spare.ready, version: spec.version, kind: spare.kind } });
const hooks: SessionHooks = {
busy: (busy) => {
@@ -311,7 +270,7 @@ async function codexFor(b: Bound): Promise<HarnessKind | undefined> {
return codexKind(
{
bin: codexBin(env),
- socket: env.SP_MODEL_SOCKET || MODEL_SOCKET,
+ endpoint: sub.endpoint,
// Under the runner user's own home: /data is root's, and $SP_DATA/state is the host's after sp-host.sh's migration.
root: codexRoot(env.HOME || os.homedir()),
peerCheck: env.SP_CODEX_PEER_CHECK !== 'off',
@@ -356,6 +315,7 @@ function bind(b: Bound, kind?: HarnessKind) {
kind,
);
files = serveFiles(env.SP_FILES_SOCKET!, s.sendFile);
+ sub.cap(); // a claimed spare's route arrived before its session
if (b.kind === 'channel') void s.updateContextBar();
return s;
}
@@ -407,9 +367,8 @@ async function claimForCodex(b: Bound, a?: RunnerApi) {
if (!spare || s) throw new Error(s ? 'already claimed' : 'no spare is parked');
const kind = await codexFor(b);
spare.close();
- // A Codex runner holds no Claude credential (host model-routes.ts forRunner): it gets only the session's.
- for (const k of ['CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL']) delete env[k];
- sub.reset();
+ sub.reset(); // the session's route comes next; the proxy's endpoint stays
+
const session = bind(b, kind);
session.prewarm();
await link(b, a);
@@ -419,8 +378,6 @@ async function claimForCodex(b: Bound, a?: RunnerApi) {
}
if (ss) bind(ss, ss.harness === 'codex' ? await codexFor(ss) : undefined), await link(ss);
-// Credentials in the environment (dev); otherwise they come with the host.
-if (hasClaudeCredential()) s ? s.prewarm() : spare?.warm(claudeFingerprint()!);
// The gateway acknowledges a message on receipt with 👀 (or the assistant
// thread status, which Slack clears when we post). Once output starts, the 👀
@@ -446,6 +403,9 @@ async function handle(m: Delivery, trace?: TraceContext) {
// A re-sent dispatch (the gateway re-flushes after a reconnect) was handled already.
if (!turns.delivered(trace)) return;
exiting = false; // new work cancels a pending idle exit
+ // No route this harness can run on (model-access.ts): the turn is refused; commands still run.
+ const refused = !m.text.startsWith('!') && sub.refusal();
+ if (refused && m.api) throw new Error(refused);
if (m.api) {
if (!api) throw new Error('this runner is not the session API writer');
return void (await api.api.deliver(m.text, m.api));
@@ -454,6 +414,7 @@ async function handle(m: Delivery, trace?: TraceContext) {
await s.command(m.text, m.userId);
return clearFeedback(m.ts);
}
+ if (refused) return void (await s.say(refused), clearFeedback(m.ts));
if (!s.isBusy) awaitingOutput.push(m.ts);
else if (s.thread.slack) void s.client.reactions.add({ channel: ss.channel!, timestamp: m.ts, name: 'eyes' }).catch(() => {});
const fetching = fetchAttachments(m.files, botToken, ss.key);
diff --git a/computer/src/runner/model-access-impl.ts b/computer/src/runner/model-access-impl.ts
deleted file mode 100644
index 38eb9687..00000000
--- a/computer/src/runner/model-access-impl.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// The seam for the runner's model access: runner/main.ts imports
-// `createRunnerModelAccess` from here and nothing else about it. In this
-// build a runner holds managed credentials only (model-access.ts); a build
-// with subscription routing replaces this file.
-
-import { type RunnerModelAccess, type RunnerModelAccessDeps, noRunnerModelAccess } from './model-access.js';
-
-export function createRunnerModelAccess(deps: RunnerModelAccessDeps): RunnerModelAccess {
- return noRunnerModelAccess(deps);
-}
diff --git a/computer/src/runner/model-access.test.ts b/computer/src/runner/model-access.test.ts
index aa8f6861..a0d1df5d 100644
--- a/computer/src/runner/model-access.test.ts
+++ b/computer/src/runner/model-access.test.ts
@@ -1,106 +1,204 @@
-import { readdirSync, readFileSync, statSync } from 'node:fs';
-import path from 'node:path';
+import { Effect } from 'effect';
import { describe, expect, it, vi } from 'vitest';
-import type { HostCredentials, RunnerToHost } from '../protocol.js';
+import type { HarnessName, RunnerModel, RunnerToHost } from '../protocol.js';
import type { HarnessEvent } from './harness/types.js';
+import { NO_FIT, runnerModelAccess } from './model-access.js';
import type { Session } from './session.js';
-import { MODEL_SOCKET, noRunnerModelAccess, routeOf } from './model-access.js';
-import { createRunnerModelAccess } from './model-access-impl.js';
-const slack = { slackBotToken: 'xoxb', slackBotUserId: 'B1' };
-const managed: HostCredentials = { ...slack, claudeOAuthToken: 'org' };
-const metered: HostCredentials = { ...slack, anthropicApiKey: 'k', anthropicBaseUrl: 'https://x' };
-const onSub: HostCredentials = { ...slack, claudeSubscription: { owner: 'U1', fingerprint: 'fp', maxModel: 'claude-sonnet-5-5' } };
+const SOCK = '/run/oc-modelproxy/api.sock';
+const route = (harness: unknown, more: Partial<RunnerModel> = {}): RunnerModel => ({
+ profile: 'anthropic-key',
+ key: 'ANTHROPIC_API_KEY',
+ harness,
+ endpoint: { unixSocket: SOCK },
+ placeholder: 'ph',
+ ...more,
+});
const denied: HarnessEvent = { t: 'error', kind: 'model', code: 'model_not_found', message: '' };
-function setup() {
- const env: NodeJS.ProcessEnv = { ANTHROPIC_API_KEY: 'k', ANTHROPIC_AUTH_TOKEN: 't', HOME: '/h' };
- const s = { info: { model: 'claude-fable-5-1', userId: 'U1' }, model: 'claude-fable-5-1', maxModel: undefined, persist: vi.fn(), say: vi.fn(), send: vi.fn() };
+function setup(o: { session?: boolean; harness?: HarnessName; ttl?: string } = {}) {
+ const env: NodeJS.ProcessEnv = { ANTHROPIC_API_KEY: 'stale', ANTHROPIC_AUTH_TOKEN: 'stale', HOME: '/h' };
+ const setModel = vi.fn(() => Effect.void);
+ const s = {
+ info: { model: 'claude-opus-5-5', userId: 'U1' },
+ get model() {
+ return this.info.model;
+ },
+ maxModel: undefined as string | undefined,
+ persist: vi.fn(),
+ say: vi.fn(async () => {}),
+ send: vi.fn(async () => {}),
+ ensureHarness: () => ({ setModel }),
+ };
const out: RunnerToHost[] = [];
const downgraded = vi.fn();
- const hooks = { session: () => s as unknown as Session, out: (m: RunnerToHost) => out.push(m), downgraded };
- return { env, s, out, downgraded, hooks };
+ const a = runnerModelAccess({
+ env,
+ cacheTtl: { explicit: o.ttl, preset: {} },
+ hooks: {
+ session: () => (o.session === false ? undefined : (s as unknown as Session)),
+ harness: () => o.harness ?? 'claude',
+ out: (m) => out.push(m),
+ downgraded,
+ },
+ });
+ return { a, env, s, out, downgraded, setModel };
}
-describe('noRunnerModelAccess (work 097): the public build, managed credentials only', () => {
- it('reports the route the credentials carry and leaves the environment alone', async () => {
- const { env, hooks } = setup();
+describe('runnerModelAccess: the Claude adapter (work 097 C5)', () => {
+ it.each([
+ ['ANTHROPIC_API_KEY', { ANTHROPIC_API_KEY: 'ph' }, ['ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN']],
+ ['ANTHROPIC_AUTH_TOKEN', { ANTHROPIC_AUTH_TOKEN: 'ph', ANTHROPIC_API_KEY: '' }, ['CLAUDE_CODE_OAUTH_TOKEN']],
+ ['CLAUDE_CODE_OAUTH_TOKEN', { CLAUDE_CODE_OAUTH_TOKEN: 'ph' }, ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']],
+ ])('tokenEnv %s: the placeholder there, through the socket', (tokenEnv, set, unset) => {
+ const { a, env } = setup();
+ expect(a.apply(route({ tokenEnv }))).toBe('set');
+ expect(env).toMatchObject({
+ ...set,
+ ANTHROPIC_BASE_URL: 'http://api.anthropic.com',
+ ANTHROPIC_UNIX_SOCKET: SOCK,
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
+ HOME: '/h',
+ });
+ for (const k of unset) expect(env).not.toHaveProperty(k);
+ expect(a.refusal()).toBeUndefined();
+ expect(a.profile()).toBe('anthropic-key');
+ expect(a.endpoint()).toEqual({ unixSocket: SOCK, placeholder: 'ph' });
+ });
+
+ it.each([
+ ['no tokenEnv', {}],
+ ['another tokenEnv', { tokenEnv: 'OPENAI_API_KEY' }],
+ ['an unknown field', { tokenEnv: 'ANTHROPIC_API_KEY', extra: 1 }],
+ ['a wrong type', { tokenEnv: 'ANTHROPIC_API_KEY', downgradeOnModelRefusal: 'yes' }],
+ ['not an object', 'claude'],
+ ])('malformed (%s): nothing set, the turn refused', (_, harness) => {
+ const { a, env } = setup();
+ expect(a.apply(route(harness))).toBeUndefined();
+ expect(a.refusal()).toBe(NO_FIT);
+ expect(a.kind()).toBeUndefined();
+ expect(env).toEqual({ HOME: '/h' });
+ });
+
+ it('no route yet: the turn is refused; an absent model keeps the current one', () => {
+ const { a } = setup();
+ expect(a.refusal()).toBe(NO_FIT);
+ expect(a.apply(undefined)).toBeUndefined();
+ a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }));
+ expect(a.apply(undefined)).toBeUndefined();
+ expect(a.refusal()).toBeUndefined();
+ });
+
+ it("the host's refusal: the turn is refused with its reason, the environment kept, until a route clears it", () => {
+ const { a, env } = setup();
+ const untouched = { ...env };
+ expect(a.apply({ refused: 'No model credential for this session.' })).toBeUndefined();
+ expect(a.refusal()).toBe('No model credential for this session.');
+ expect(env).toEqual(untouched);
+ expect(a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }))).toBe('set');
+ expect(a.refusal()).toBeUndefined();
const before = { ...env };
- const a = noRunnerModelAccess({ env, socket: undefined, hooks });
- expect(a.route()).toBeUndefined();
- expect(a.apply(managed)).toBe('managed');
- expect(a.route()).toBe('managed');
- expect(a.apply(slack)).toBeUndefined(); // Slack only: no Claude part
- expect(a.route()).toBe('managed');
- expect(a.apply(metered)).toBe('managed');
- await a.event(denied);
- expect(a.idle()).toBe(false);
- a.reset();
- expect(a.route()).toBeUndefined();
+ expect(a.apply({ refused: 'paused' })).toBeUndefined();
+ expect(a.refusal()).toBe('paused');
expect(env).toEqual(before);
+ expect(a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }))).toBeUndefined();
+ expect(a.refusal()).toBeUndefined();
});
- it('a subscription credential is no Claude part: nothing tunnelled, no switch, the runner keeps what it has', () => {
- const { env, s, hooks } = setup();
+ it("the cache TTL: SP_PROMPT_CACHE_TTL over the profile's", () => {
+ const own = setup();
+ own.a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY', promptCacheTtl: '1h' }));
+ expect(own.env.CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('1h');
+ const explicit = setup({ ttl: '5m' });
+ explicit.a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY', promptCacheTtl: '1h' }));
+ expect(explicit.env.CLAUDE_CODE_PROMPT_CACHE_TTL).toBe('5m');
+ });
+});
+
+describe('runnerModelAccess: a later route', () => {
+ const first = route({ tokenEnv: 'ANTHROPIC_API_KEY' });
+
+ it("a session's runner: a changed harness object, endpoint or placeholder is a switch; the key alone changes nothing", () => {
+ for (const next of [
+ route({ tokenEnv: 'CLAUDE_CODE_OAUTH_TOKEN' }),
+ route({ tokenEnv: 'ANTHROPIC_API_KEY' }, { endpoint: { unixSocket: '/other.sock' } }),
+ route({ tokenEnv: 'ANTHROPIC_API_KEY' }, { placeholder: 'other' }),
+ ]) {
+ const { a, env } = setup();
+ a.apply(first);
+ const before = { ...env };
+ expect(a.apply(next)).toBe('switch');
+ expect(env).toEqual(before);
+ }
+ const { a, env } = setup();
+ a.apply(first);
const before = { ...env };
- const a = noRunnerModelAccess({ env, socket: undefined, hooks });
- expect(a.apply(managed)).toBe('managed');
- expect(a.apply(onSub)).toBeUndefined();
- expect(a.route()).toBe('managed');
+ expect(a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }, { key: 'OTHER_KEY', profile: 'other' }))).toBeUndefined();
expect(env).toEqual(before);
- expect(env.ANTHROPIC_UNIX_SOCKET).toBeUndefined();
- expect(s.maxModel).toBeUndefined();
- expect(s.info.model).toBe('claude-fable-5-1');
+ expect(a.profile()).toBe('other');
});
- it('exports what public code shares with the hosted build', () => {
- expect(MODEL_SOCKET).toBe('/run/oc-modelproxy/api.sock');
- expect(routeOf(managed)).toBe('managed');
- expect(routeOf(metered)).toBe('managed');
- expect(routeOf(slack)).toBeUndefined();
- expect(routeOf(onSub)).toBe('subscription');
+ it('a spare: the new route is applied, to park again on it', () => {
+ const { a, env } = setup({ session: false });
+ a.apply(first);
+ const k = a.kind();
+ expect(a.apply(route({ tokenEnv: 'CLAUDE_CODE_OAUTH_TOKEN' }))).toBe('set');
+ expect(env.CLAUDE_CODE_OAUTH_TOKEN).toBe('ph');
+ expect(env).not.toHaveProperty('ANTHROPIC_API_KEY');
+ expect(a.kind()).not.toBe(k);
});
-});
-describe('the seam’s implementation', () => {
- it('createRunnerModelAccess builds something of the interface’s shape', () => {
- const { env, hooks } = setup();
- const a = createRunnerModelAccess({ env, socket: undefined, hooks });
- for (const k of ['route', 'reset', 'apply', 'event', 'idle'] as const) expect(typeof a[k]).toBe('function');
+ it('a spare claimed for Codex: reset clears the route but keeps the endpoint', () => {
+ const { a, env } = setup({ session: false });
+ a.apply(first);
+ a.reset();
+ expect(a.refusal()).toBe(NO_FIT);
+ expect(a.endpoint()).toEqual({ unixSocket: SOCK, placeholder: 'ph' });
+ for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_UNIX_SOCKET']) expect(env).not.toHaveProperty(k);
+ });
+
+ it("Codex reads {} and leaves Claude's environment alone", () => {
+ const { a, env } = setup({ harness: 'codex', session: false });
+ expect(a.apply(route({}))).toBe('set');
+ expect(a.refusal()).toBeUndefined();
+ expect(env).toEqual({ ANTHROPIC_API_KEY: 'stale', ANTHROPIC_AUTH_TOKEN: 'stale', HOME: '/h' });
+ const bad = setup({ harness: 'codex' });
+ expect(bad.a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }))).toBeUndefined();
+ expect(bad.a.refusal()).toBe(NO_FIT);
});
});
-describe('the seam (work 097, 6b)', () => {
- const SRC = path.resolve(import.meta.dirname, '..');
- const HOSTED = ['runner/subscription.ts'];
- const IMPORT = /^\s*(?:import|export)\b[^'"]*?from\s+['"]([^'"]+)['"]/gm;
- function* walk(dir: string): Generator<string> {
- for (const name of readdirSync(dir)) {
- const p = path.join(dir, name);
- if (statSync(p).isDirectory()) yield* walk(p);
- else if (p.endsWith('.ts') && !p.endsWith('.test.ts')) yield p;
- }
- }
- const importers = (targets: string[]) => {
- const found: string[] = [];
- for (const file of walk(SRC)) {
- const text = readFileSync(file, 'utf8');
- for (const m of text.matchAll(IMPORT)) {
- if (!m[1].startsWith('.')) continue;
- const target = path.relative(SRC, path.resolve(path.dirname(file), m[1])).replace(/\.js$/, '.ts');
- if (targets.includes(target)) found.push(path.relative(SRC, file));
- }
- }
- return [...new Set(found)].sort();
- };
+describe('runnerModelAccess: the ceiling and a refused model', () => {
+ it("maxModel caps the session on any route, moving a model above it down", () => {
+ const { a, s } = setup();
+ a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }, { maxModel: 'claude-sonnet-5-5' }));
+ expect(s.maxModel).toBe('claude-sonnet-5-5');
+ expect(s.info.model).toBe('claude-sonnet-5-5');
+ expect(s.persist).toHaveBeenCalled();
+ });
- // In the public build the hosted module is absent and nothing imports it (model-access.hosted.test.ts covers the hosted build).
- it('nothing but runner/model-access-impl.ts imports the hosted module', () => {
- expect(importers(HOSTED).filter((f) => f !== 'runner/model-access-impl.ts')).toEqual([]);
+ it('without downgradeOnModelRefusal, a refusal stays an error', async () => {
+ const { a, out, setModel } = setup();
+ a.apply(route({ tokenEnv: 'ANTHROPIC_API_KEY' }));
+ await a.event(denied);
+ expect(setModel).not.toHaveBeenCalled();
+ expect(out).toEqual([]);
+ expect(a.idle()).toBe(false);
});
- it('runner/main.ts gets its model access from the seam; the Codex harness never imports it', () => {
- expect(importers(['runner/model-access-impl.ts'])).toEqual(['runner/main.ts']);
- expect(importers(['runner/model-access.ts']).filter((f) => f.startsWith('runner/harness/'))).toEqual([]);
+ it('with it, the model steps down a family and the turn is retried', async () => {
+ const { a, s, out, downgraded, setModel } = setup();
+ a.apply(route({ tokenEnv: 'CLAUDE_CODE_OAUTH_TOKEN', downgradeOnModelRefusal: true }));
+ await a.event(denied);
+ expect(setModel).toHaveBeenCalledOnce();
+ const to = s.info.model;
+ expect(to).not.toBe('claude-opus-5-5');
+ expect(s.maxModel).toBe(to);
+ expect(out).toEqual([{ t: 'model-denied', model: 'claude-opus-5-5', fallbackTo: to }]);
+ expect(downgraded).toHaveBeenCalledWith('claude-opus-5-5', to);
+ expect(s.say).toHaveBeenCalledOnce();
+ expect(a.idle()).toBe(true);
+ expect(s.send).toHaveBeenCalledOnce();
+ expect(a.idle()).toBe(false);
});
});
diff --git a/computer/src/runner/model-access.ts b/computer/src/runner/model-access.ts
index f44fcb1e..af1ba7f0 100644
--- a/computer/src/runner/model-access.ts
+++ b/computer/src/runner/model-access.ts
@@ -1,92 +1,162 @@
-// The runner's model access (work 097, 6b): one interface for what the
-// credentials the host sends mean to this runner's harness, and the public
-// build's implementation of it, in which a runner only ever holds managed
-// credentials (the organization's, applied to its environment by main.ts).
-//
-// The hosted build (subscription.ts: the owner's Claude subscription through
-// oc-modelproxy's socket, with the model downgrades it brings) implements the
-// same interface; model-access-impl.ts is the one place that chooses, and
-// runner/main.ts sees only this file's types. The frames stay protocol.ts's:
-// `claudeSubscription` in HostCredentials, `model-denied` out.
+// The runner's model access (work 097, design C4 and C5): what the session's
+// route, as the host sends it in `credentials.model`, means for this runner.
+// Every model request goes through the host's model proxy; the runner learns
+// the profile's `harness` object for its own harness, where to connect and
+// the placeholder to send, never a credential. Each harness's adapter
+// validates its own object: Claude Code's (harness/claude/model-env.ts) sets
+// the environment Claude Code is spawned from; Codex reads `{}` and takes
+// only the endpoint and placeholder (its loopback and config.toml).
//
// Invariants:
-// - `noRunnerModelAccess` never touches the environment: `apply` only reports
-// the route the credentials carry ('managed', or undefined for a Slack-only
-// update) and main.ts applies them as before. A `claudeSubscription`
-// credential, which only a proxy host sends, is reported as no Claude part
-// (undefined) with a warning: the runner keeps the credential it has rather
-// than pointing its harness at a socket that is not there or restarting
-// into the same delivery again.
-// - Nothing here throws, and no method is ever 'switch' or 'subscription'.
+// - An absent `model` keeps the current one. A later `model` whose `harness`
+// object, endpoint or placeholder differs moves a session's runner to
+// another harness environment: 'switch', it finishes its turn and exits. A
+// changed `key` (or profile name, owner, ceiling) alone changes nothing in
+// the environment. A spare has no turn: it applies the new one and parks
+// again.
+// - A refused route (`{ refused }`: the host bound the session to no
+// credential) refuses the turn with the host's reason and leaves the
+// environment as it is; the next route clears it. No route, or a `harness`
+// object its adapter does not accept: the turn is refused with NO_FIT, and
+// nothing is set.
+// - A refused model steps down only when the profile says
+// `downgradeOnModelRefusal`; `maxModel` caps the session on any route.
+// - Nothing here throws.
-import type { HostCredentials, RunnerToHost } from '../protocol.js';
+import { isDeepStrictEqual } from 'node:util';
+import { z } from 'zod';
+import { Effect } from 'effect';
+import type { HarnessName, RunnerModel, RunnerRefused, RunnerToHost } from '../protocol.js';
import { log } from '../log.js';
+import { spareKind } from '../model-key.js';
+import type { CacheTtlSettings } from './cache-ttl.js';
+import { ClaudeModel, claudeModelEnv, clearClaudeModelEnv } from './harness/claude/model-env.js';
import type { HarnessEvent } from './harness/types.js';
+import { RETRY_TEXT, aboveCeiling, deniedLine, nextDown } from './model-downgrade.js';
import type { Session } from './session.js';
-/** oc-modelproxy's API socket, where a hosted computer's Codex (through its loopback) and subscription Claude Code reach the model. */
-export const MODEL_SOCKET = '/run/oc-modelproxy/api.sock';
-
-export type Route = 'managed' | 'subscription';
+export const NO_FIT = "This computer's model profile does not fit this agent.";
-/** The route `c` carries; undefined for an update with no Claude part (Slack only). */
-export const routeOf = (c: HostCredentials): Route | undefined =>
- c.claudeSubscription ? 'subscription' : c.claudeOAuthToken || c.anthropicApiKey ? 'managed' : undefined;
+/** Each harness's `harness[h]` object. Codex reads nothing from it (design C5). */
+const ADAPTERS = { claude: ClaudeModel, codex: z.strictObject({}) } satisfies Record<HarnessName, z.ZodType>;
/** What runner/main.ts hands the model access. */
export interface RunnerModelAccessDeps {
/** The runner's environment, which its harness is spawned from. */
env: NodeJS.ProcessEnv;
- /** The proxy's socket (SP_MODEL_SOCKET), when not the default. */
- socket: string | undefined;
+ cacheTtl: CacheTtlSettings;
hooks: RunnerModelAccessHooks;
}
export interface RunnerModelAccessHooks {
session(): Session | undefined;
+ /** The harness this runner runs: its session's, else Claude (a spare parks Claude Code). */
+ harness(): HarnessName;
out(m: RunnerToHost): void;
/** Telemetry: a refused model was stepped down. */
downgraded(from: string, to: string): void;
}
-/** How runner/main.ts asks what its credentials mean, and tells of what the harness says. */
-export interface RunnerModelAccess {
- /** The route this runner started on, once credentials arrived. */
- route(): Route | undefined;
- /** A spare claimed for another harness: the route it parked on is not the session's. */
- reset(): void;
- /**
- * Credentials from the host: 'switch' when they move this runner to another route (it should finish and exit),
- * 'subscription' once its harness is pointed at the proxy, 'managed' or undefined for main.ts to apply them.
- */
- apply(c: HostCredentials): Route | 'switch' | undefined;
- /** A harness record, for whatever the route makes of it (a refused model on a subscription steps down). */
- event(e: HarnessEvent): Promise<void>;
- /** The turn ended; true when the model access retries it (on another model). */
- idle(): boolean;
-}
+/** Where the model client connects and what it sends as its credential (design C4). */
+export type Endpoint = { unixSocket: string; placeholder: string };
+
+export type RunnerModelAccess = ReturnType<typeof runnerModelAccess>;
+
+export function runnerModelAccess({ env, cacheTtl, hooks: o }: RunnerModelAccessDeps) {
+ /** The route this runner's environment was set for. */
+ let cur: RunnerModel | undefined;
+ /** Its `harness` object as the adapter read it; undefined: none, or malformed. */
+ let read: z.infer<(typeof ADAPTERS)[HarnessName]> | undefined;
+ /** The proxy's endpoint, kept across a reset: it is the host's, not the route's. */
+ let endpoint: Endpoint | undefined;
+ /** The host's reason it binds this runner's session to no credential. */
+ let refused: string | undefined;
+ let retry = false;
+
+ const same = (a: RunnerModel, b: RunnerModel) =>
+ isDeepStrictEqual([a.harness, a.endpoint, a.placeholder], [b.harness, b.endpoint, b.placeholder]);
+
+ /** The route's ceiling on the session: `!model` stays at or below it, and a model above it moves down now. */
+ function cap() {
+ const s = o.session();
+ if (!s) return;
+ s.maxModel = cur?.maxModel;
+ if (aboveCeiling(s.model, s.maxModel)) {
+ s.info.model = s.maxModel!;
+ s.persist();
+ }
+ }
-/** The public build: managed credentials only, applied by main.ts; nothing to tunnel, downgrade or retry. */
-/** Takes the same deps as the hosted build, so `createRunnerModelAccess = noRunnerModelAccess` is a drop-in; none is read. */
-export function noRunnerModelAccess(_: RunnerModelAccessDeps): RunnerModelAccess {
- let route: Route | undefined;
- let warned = false;
return {
- route: () => route,
+ /** The route's profile name (telemetry `provider`). */
+ profile: () => cur?.profile,
+ endpoint: () => endpoint,
+ /** The spare kind of the environment Claude Code is started from (model-key.ts). */
+ kind: () => (cur && read ? spareKind('claude', cur.harness) : undefined),
+ /** The host's refusal, else NO_FIT while this runner has no route its harness's adapter accepts. */
+ refusal: () => refused ?? (read ? undefined : NO_FIT),
+ /** A spare claimed for Codex: the route it parked Claude Code on is not the session's. */
reset() {
- route = undefined;
+ cur = read = undefined;
+ clearClaudeModelEnv(env);
},
- apply(c) {
- const next = routeOf(c);
- if (next === 'subscription') {
- if (!warned) log.warn('credentials name a subscription, which this runner has no model proxy for; keeping the credential it has');
- warned = true;
+ /** A session became this runner's (a claim): the route's ceiling applies to it. */
+ cap,
+ /**
+ * `credentials.model` from the host: 'set' once the environment is set for it (start or re-park the harness),
+ * 'switch' when the session's runner should finish its turn and exit, undefined when nothing changed.
+ */
+ apply(m: RunnerModel | RunnerRefused | undefined): 'set' | 'switch' | undefined {
+ if (!m) return undefined;
+ if ('refused' in m) {
+ refused = m.refused;
+ return undefined;
+ }
+ refused = undefined;
+ if (cur && !same(cur, m) && o.session()) return 'switch';
+ const changed = !cur || !same(cur, m);
+ cur = m;
+ cap();
+ if (!changed) return undefined;
+ endpoint = { unixSocket: m.endpoint.unixSocket, placeholder: m.placeholder };
+ const h = o.harness();
+ const r = ADAPTERS[h].safeParse(m.harness);
+ read = r.success ? r.data : undefined;
+ if (!r.success) {
+ log.warn(`model profile ${m.profile}: its ${h} settings are not this runner's (${r.error.issues.map((i) => i.path.join('.') || i.message).join(', ')})`);
+ if (h === 'claude') clearClaudeModelEnv(env);
return undefined;
}
- route = next ?? route;
- return next;
+ if (h === 'claude') claudeModelEnv(env, r.data as ClaudeModel, m.endpoint.unixSocket, m.placeholder, cacheTtl);
+ return 'set';
+ },
+ /** A harness record: a refused model (the main thread's) steps down one family, and the turn is retried when it ends. */
+ async event(e: HarnessEvent) {
+ const s = o.session();
+ if (!s || !(read as ClaudeModel | undefined)?.downgradeOnModelRefusal || !(e.t === 'error' && e.code === 'model_not_found')) return;
+ const from = s.model;
+ const to = nextDown(from);
+ if (!to) return;
+ try {
+ await Effect.runPromise(s.ensureHarness().setModel(to));
+ } catch (e: any) {
+ return log.warn(`downgrade to ${to}:`, e?.message ?? e);
+ }
+ s.info.model = to;
+ s.persist();
+ s.maxModel = to;
+ retry = true;
+ o.out({ t: 'model-denied', model: from, fallbackTo: to });
+ o.downgraded(from, to);
+ await s.say(deniedLine(from, to));
+ },
+ /** The turn ended; true when it is retried (on the lower model). */
+ idle(): boolean {
+ const s = o.session();
+ if (!retry || !s) return false;
+ retry = false;
+ void s.send(RETRY_TEXT, s.info.userId);
+ return true;
},
- event: async () => {},
- idle: () => false,
};
}
diff --git a/computer/src/runner/model-downgrade.test.ts b/computer/src/runner/model-downgrade.test.ts
index e8ca6702..0db9b375 100644
--- a/computer/src/runner/model-downgrade.test.ts
+++ b/computer/src/runner/model-downgrade.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { aboveCeiling, deniedLine, familyName, nextDown } from './model-downgrade.js';
+import { RETRY_TEXT, aboveCeiling, deniedLine, familyName, nextDown } from './model-downgrade.js';
describe('model downgrade (work 077)', () => {
it('steps one family down, and stops at the bottom or an unknown model', () => {
@@ -20,6 +20,7 @@ describe('model downgrade (work 077)', () => {
it('says it in family names', () => {
expect(familyName('claude-opus-5-5')).toBe('Opus');
- expect(deniedLine('claude-fable-5-1', 'claude-opus-5-5')).toBe("Your Claude subscription doesn't include Fable; this thread is on Opus.");
+ expect(RETRY_TEXT).toBe('The last request failed because the model was not available; it has been switched. Continue where you left off.');
+ expect(deniedLine('claude-fable-5-1', 'claude-opus-5-5')).toBe("This credential doesn't include Fable; this thread is on Opus.");
});
});
diff --git a/computer/src/runner/model-downgrade.ts b/computer/src/runner/model-downgrade.ts
index 40e04bf5..25c1a410 100644
--- a/computer/src/runner/model-downgrade.ts
+++ b/computer/src/runner/model-downgrade.ts
@@ -1,10 +1,11 @@
-// A Claude subscription's model ceiling (work 077). The seat's entitlements
-// are unknown up front (no bootstrap on the proxy's socket), so a Pro seat
-// asked for Opus finds out from the API: Claude Code turns the error into an
-// assistant message with `error: 'model_not_found'`. The runner then steps the
-// session one family down (fable → opus → sonnet → haiku), retries the turn
-// once, says so in the thread, and the host reports `model-denied` so the
-// gateway starts the owner's next threads at the ceiling.
+// A credential's model ceiling (work 077, 097 C5). What a credential may use
+// can be unknown up front, so a route whose profile says
+// `downgradeOnModelRefusal` finds out from the API: Claude Code turns the
+// error into an assistant message with `error: 'model_not_found'`. The runner
+// then steps the session one family down (fable → opus → sonnet → haiku),
+// retries the turn once, says so in the thread, and the host reports
+// `model-denied` so the gateway starts the owner's next threads at the
+// ceiling. A route's `maxModel` is a ceiling known in advance, on any route.
//
// Invariant: only ever downward, one family per denial; a model with no
// known family is never switched (it may be a full id the person chose).
@@ -31,7 +32,7 @@ export function nextDown(model: string): string | undefined {
return i < 0 ? undefined : LADDER[i + 1]?.[1];
}
-/** Whether `model` is above the subscription's ceiling `max` (both known families). */
+/** Whether `model` is above the ceiling `max` (both known families). */
export function aboveCeiling(model: string, max: string | undefined) {
if (!max) return false;
const [m, c] = [rank(model), rank(max)];
@@ -40,7 +41,7 @@ export function aboveCeiling(model: string, max: string | undefined) {
/** The line posted when a model is refused or `!model` asks above the ceiling. */
export const deniedLine = (model: string, to: string) =>
- `Your Claude subscription doesn't include ${familyName(model)}; this thread is on ${familyName(to)}.`;
+ `This credential doesn't include ${familyName(model)}; this thread is on ${familyName(to)}.`;
/** What a retried turn says to the model: the request that failed is the one to redo. */
-export const RETRY_TEXT = 'The last request failed because the model was not available on this subscription; it has been switched. Continue where you left off.';
+export const RETRY_TEXT = 'The last request failed because the model was not available; it has been switched. Continue where you left off.';
diff --git a/computer/src/runner/model-switch.ts b/computer/src/runner/model-switch.ts
index 3a3faa22..a36d0d5b 100644
--- a/computer/src/runner/model-switch.ts
+++ b/computer/src/runner/model-switch.ts
@@ -15,7 +15,7 @@ export interface ModelHost {
info: { model?: string; effort?: EffortLevel; speed?: Speed; kind: 'thread' | 'channel' };
/** The model in effect. */
model: string;
- /** A Claude subscription's ceiling (work 077). */
+ /** The route's model ceiling, `maxModel` (work 097 C5). */
maxModel?: string;
isBusy: boolean;
say(text: string): Promise<void>;
diff --git a/computer/src/runner/session.ts b/computer/src/runner/session.ts
index c7d9a86f..fdf6ed89 100644
--- a/computer/src/runner/session.ts
+++ b/computer/src/runner/session.ts
@@ -148,7 +148,7 @@ export class Session {
private addressed = true;
/** The prompt a typed reply answers (prompts.ts), by prompt id. */
openPrompt?: string;
- maxModel?: string; // a Claude subscription's ceiling (work 077, subscription.ts): `!model` stays at or below it
+ maxModel?: string; // the route's model ceiling (model-access.ts): `!model` stays at or below it
private costUsd = 0;
private ctxTokens = 0;
/** Whether the current model message already arrived as deltas. */
@@ -271,8 +271,8 @@ export class Session {
/**
* Start the harness before the first message, so its start-up (230–450 ms)
* is off the turn. It copies the environment at spawn, so call it once the
- * Claude credentials are in place; `renew` replaces a harness no message
- * went into yet (the credentials changed since it started).
+ * model environment is set (runner/model-access.ts); `renew` replaces a
+ * harness no message went into yet (that environment changed since it started).
*/
prewarm(renew = false) {
if (renew) this.shadow.cancel();
diff --git a/computer/src/runner/turn-events.ts b/computer/src/runner/turn-events.ts
index 8e3479c3..ec14f36e 100644
--- a/computer/src/runner/turn-events.ts
+++ b/computer/src/runner/turn-events.ts
@@ -32,7 +32,8 @@ export interface TurnEventsContext {
/** The model id in effect (it changes with `!model` and at init). */
model(): string | undefined;
tierOf(model: string): string | undefined;
- provider(): string;
+ /** The route's profile name; undefined before the host sent one. */
+ provider(): string | undefined;
/** While this runner writes the session's journal (work 084): the API clients attached now, the host's mirror excluded. */
apiClients?(): number | undefined;
}
@@ -360,7 +361,7 @@ export class TurnEvents {
trace_id: turn.trace?.id ?? turn.id,
turn_id: turn.id,
sent_at: tbTime(turn.sentAt),
- provider: this.ctx.provider(),
+ ...(this.ctx.provider() ? { provider: this.ctx.provider() } : {}),
...(model ? { model, tier: this.ctx.tierOf(model) ?? 'custom' } : {}),
};
}
diff --git a/computer/src/telemetry/catalog.ts b/computer/src/telemetry/catalog.ts
index 7ce11d21..eb19babf 100644
--- a/computer/src/telemetry/catalog.ts
+++ b/computer/src/telemetry/catalog.ts
@@ -87,28 +87,23 @@ export const CATALOG = {
'pool.spare_evicted': host('reason'),
// A spare that exited before it was ever ready (its Claude Code did not start).
'pool.spare_failed': host(),
- // A delivery that could have taken a spare and started cold. `reason`: none, credential, refused, timeout, gone (the spare exited first).
+ // A delivery that could have taken a spare and started cold. `reason`: none, kind (none of the session's spare kind), refused, timeout, gone (the spare exited first).
'pool.spare_missed': host('reason'),
- // Claude subscriptions (work 077): oc-modelproxy's events, relayed by the host from its control socket.
- // A ChatGPT Responses request adds `first_output_ms` (headers written → its first output item; `ttfb_ms` ends at
- // response.created) and the `service_tier` it was served on, both read from its stream (modelproxy/responses.go).
- // Over Codex's WebSocket each response is one (route responses, `transport` websocket, `prewarm` for its warm-up) and the
- // connection one more (route responses_ws, `responses` it carried, `closed`: idle | rebind | drain) (modelproxy/websocket.go).
- 'model.request': host('status', 'route', 'stream', 'overhead_us', 'ttfb_ms', 'first_output_ms', 'service_tier', 'fingerprint', 'swapped', 'limit_type',
- 'transport', 'prewarm', 'responses', 'closed'),
+ // The model proxy's events (work 097, computer/modelproxy/README.md), relayed by the host from its control socket;
+ // the envelope's `provider` dimension is the event's profile. A Responses request adds `first_output_ms` (headers
+ // written → its first output item) and the `service_tier` it was served on. Over a WebSocket each response is one
+ // (`transport` websocket, `prewarm` for its warm-up) and the connection one more (`responses` it carried, `closed`).
+ 'model.request': host('status', 'route', 'stream', 'overhead_us', 'ttfb_ms', 'first_output_ms', 'service_tier', 'key', 'swapped',
+ 'conn_wait_ms', 'conn_reused', 'transport', 'prewarm', 'responses', 'closed'),
'model.held': host('held_ms', 'released'),
- 'model.denied': host('reason', 'route', 'bound_provider'),
+ 'model.denied': host('reason', 'route', 'suppressed'),
'model.proxy_started': host('version', 'bindings'),
- // A unit's credential bound, swapped, released or refused; `mode`, `fingerprint` as the seat's.
- 'model.binding': host('action', 'unit', 'mode', 'fingerprint'),
- // Work 082: a session's route was for a provider the connected proxy does not list (a proxy before 082 would have
- // read it as anthropic); the host refused it instead of binding. The `provider` dimension is the route's.
- 'model.provider_refused': host('unit'),
- // Work 082: a session's live runner runs another harness than its route (`at: 'route'`) or delivery (`at: 'delivery'`)
- // needs; the host refuses the route to it and restarts the session on `to`. The `harness` dimension is the runner's.
- 'model.harness_switch': host('to', 'at'),
+ // A caller's credential bound, released or refused (`code`); `key` names the credential, never its value.
+ 'model.binding': host('action', 'caller', 'mode', 'key', 'code'),
+ // Work 097: the proxy refused a session's bind (`code`); the host bound the caller as refuse instead. `provider` is the profile.
+ 'model.profile_refused': host('caller', 'code'),
// Upstream pool gauges every minute, counters since the previous one.
- 'model.pool': host('open_conns', 'idle_conns', 'active_streams', 'warm_conns', 'idle_pool_miss', 'warm_hits', 'warm_failed', 'dials', 'bindings', 'dropped_messages'),
+ 'model.pool': host('open_conns', 'idle_conns', 'active_streams', 'idle_pool_miss', 'dials', 'bindings', 'dropped_messages'),
// The runner stepped a subscription session's model down after the seat refused it.
'model.downgraded': runner('from', 'to'),
// A spare became this session's runner; `duration_ms` is the claim's round trip.
@@ -132,6 +127,7 @@ export const CATALOG = {
'since_gateway_message_s',
'telemetry_spooled_bytes',
'telemetry_dropped',
+ 'model_proxy_down_s',
),
// ---------------------------------------------------------------- host: the computer API (work 084 instrumentation)
// /tmp/build084/instrumentation-catalog.md (v2) is the contract (blue mirrors it). One event per unit of work, never a
diff --git a/computer/src/telemetry/envelope.ts b/computer/src/telemetry/envelope.ts
index 2789ea96..b2b6a438 100644
--- a/computer/src/telemetry/envelope.ts
+++ b/computer/src/telemetry/envelope.ts
@@ -26,10 +26,9 @@ export const ERROR_TYPES = [
'launch',
'socket',
'invalid_message',
- // oc-modelproxy denials (work 082): a WebSocket upgrade, a ChatGPT seat at its in-flight cap, a binding used on another provider's route
+ // the model proxy's (computer/modelproxy): a WebSocket upgrade, a credential at its concurrency cap
'websocket',
- 'account_inflight',
- 'provider_mismatch',
+ 'concurrency',
'unknown',
] as const;
export const PATHS = ['warm', 'new', 'resume', 'prewarmed'] as const;