Backup and design reference for the Open WebUI deployment at chat.bayleaf.dev.
This directory is a recovery-oriented backup of the BayLeaf Chat service. It captures the Digital Ocean App Platform deployment configuration, the OWUI workspace models (with system prompts), custom tools, and filter/action functions. Combined with the env vars documented below, this should be sufficient to reconstruct the service from scratch.
This repo is public. Secret values (API keys, OAuth secrets, DB credentials) are listed by name but redacted. Actual values live in the DO App Platform console and are never committed.
Note from Adam (not sure where to organize this, but I need to write it somewhere): There are a some important ways the skills you practice as a user of BayLeaf Chat don't transfer over to services like ChatGPT. On BayLeaf Chat, you can edit your old messages, you can edit assistant messages, and you can easily branch or even navigate between branches of a chat. The chat structure is a user-malleable document. This means you'll be able to practice certain writing aspects of AI literacy (narrowly, kinds of context engineering) that would be difficult to impossible on other services. The interface to BayLeaf Chat tries to make cached and uncached token counts visible along side output token counts and processing costs so that you can, if you want, get a bit technical about the quantitative aspects of your interactions with the models. You can practice a kind of manual session compaction so that you can develop the taste needed to critique automatic session compaction mechanisms. These features are important to me as the system designer. However, I'll admit that they weren't strategically chosen by me so much as adopted after experience comparing Open WebUI to ChatGPT across several months of parallel use a while back. This makes me curious about other ways of having BayLeaf Chat (or ideally OWUI generally) not be a simple clone of the ChatGPT interface. Admin and user-level extensibility via code seems to be another important and open-ended example of this intentional gap.
All resources live in the BayLeaf / UCSC DigitalOcean team
(slug: bayleaf-ucsc), under the adam@adamsmith.as account with
amsmith@ucsc.edu invited as a second owner. See
politics/ACCOUNTS.md §2 for the account/team migration history and
handover plan.
Use doctl --context bayleaf to target this team from the CLI; the
default context points at the personal Just Adam team.
| Property | Value |
|---|---|
| App name | bayleaf-chat-owui-app |
| App ID | f1a1e758-62e9-4e99-90cb-212cab12958d |
| Default ingress | bayleaf-chat-owui-app-6uicw.ondigitalocean.app |
| Region | sfo |
| Images | Built locally by chat/release.py (open-webui from chat/image/Dockerfile, retention-cleanup from chat/Dockerfile.retention); public ghcr.io/bayleaf-ucsc/bayleaf-chat, deployed by fingerprint-named tag (chat/DEPLOYED.json) |
| Instance | apps-s-1vcpu-2gb (1 instance) |
| HTTP port | 8080 |
Image choice. Use version-specific standard-image tags (currently
v0.13.3), not rolling main or slim. BayLeaf stores uploads in DO Spaces
via OWUI's S3 provider (§1, Object Storage). Before v0.12.0, the slim image
omitted S3 support and refused to start with S3 storage configured. Upstream
v0.12.0 adds S3 support to slim, but BayLeaf retains the standard image;
switching image variants requires separate dependency and upload qualification.
Native aggregate telemetry (2026-10-20). The live rung-4 build adds the
qualified source minimization to the v0.13.3 standard image (upgraded 2026-11-10), pinned by
immutable upstream index
sha256:46b59158e6558eeb980bc828e0f1b30238ad24d82ed84d5e5eda1dab2a082f14.
The service command is python /opt/bayleaf-otlp/startup_patch.py, not the former
echo-and-start wrapper. Exact source/package guards run at build and startup;
the entrypoint prints guarded startup markers and retains the exec handoff to
uvicorn PID 1. Never bypass these guards or enable unpatched native metrics.
Native qualification used deployment b36b8678-f928-4db2-81e1-a3ebcb35fc34 from
published source 1d56584c4d2b8576413ad615e625addab70e0f7e. The first build failed unpacking the
pinned upstream image (unexpected EOF); one unchanged-source retry succeeded.
One instance, one worker, the original size/pool and retention job were preserved.
Repository-push auto-deploy remains disabled, so documentation publication
does not restart Chat. This is not an OWUI upgrade or schema migration.
OWUI v0.13.3 upgrade (2026-11-10): deployment
4e42953a-2d5f-4e64-acfa-869693edc362 reached ACTIVE from published source
12927dced930c71a453ab9e9905bc836a398c44f. Both builds, all 16 Chromium arrival
cases, a synthetic existing-database upgrade, full five-minute arm64 PG/TLS export
and amd64 boot/inference passed. The telemetry adapter/dependency pins are
unchanged; frontend guards were refreshed. All three migrations completed through
9f6c2a8d1b43; image-only rollback is not qualified. Today's managed database
backup was verified. Exact build checkout, source guards, server PID 1,
health/version and authenticated Basic/Help inference passed in production.
The complete app spec, resources, hidden base model, grants and valves remained
byte-identical. Existing global settings were unchanged; new defaults include
90-day renewable session expiry, 50,000-character full-text threshold, disabled
auto tool approval/labels, keyword tool search and no chat-read character limit.
Tool search remains disabled and terminal connections empty. Saved retrieval
values remain 3/3/1000. Served arrival assets match qualified bytes. Adam confirmed
the production experience works and accepted the upgrade; individual browser
sign-in/tool/skill/upload scenarios were not itemized.
See image/UPGRADE-0.13.3.md.
OWUI v0.13.0 upgrade (2026-11-04 Pacific): deployment
79af5c90-9217-45ac-ad66-6399a8846ec3 reached ACTIVE from published source
364ac9e731234b39fa4a15293140f4dd36356ecd. Both architecture builds, amd64
boot/inference, full five-minute arm64 PostgreSQL/TLS export, all 16 Chromium
arrival cases and a synthetic existing-database upgrade passed. The telemetry
source adapter was adapted to upstream middleware changes without changing the
collection policy. Three migrations completed through e42c8f710a36; an
image-only rollback is not qualified. Today's managed PG backup was verified.
Production guards, PID 1, health/version and authenticated Basic/Help inference
passed. The complete app spec stayed unchanged. Full private pre/post pulls
found only the new true is_active field on all nine tools; sources, schemas,
valves, models, skills, grants and the hidden underlying model were unchanged.
Config added comments off, notifications on and empty Mistral OCR params.
Adam explicitly accepted the new notification inbox and 1024 tool-call default;
sub-agents remain disabled with their saved finite limits. Served arrival assets
match the qualified bytes. Adam confirmed fresh CILogon sign-in, Sandbox and
web-context tools work and accepted the upgrade. Upload scenarios were not
itemized; the 1024-round limit was deliberately not exercised. See
image/UPGRADE-0.13.0.md.
OWUI v0.12.4 upgrade (2026-10-27): deployment
c63a7deb-02c0-4261-880c-8a0eb8d0b2bd reached ACTIVE from published source
09aeebff5d2ffef6fc835607472f3e9158be9df0. Both architecture builds, full arm64
PostgreSQL/TLS metrics export, amd64 boot/inference and all 16 real Chromium
arrival cases passed. No migration source changes; guarded telemetry dependencies
and minimized adapter bytes are unchanged. The image now uses Python 3.12 / Debian
13. Guarded startup, PID 1, health/version and authenticated Basic/Help responses
passed in production. The complete app spec and resource definitions stayed
unchanged. New config defaults are an empty LDAP fallback domain, lazy skills off
and empty UI visibility settings. Lathe 1.3.3 source/valves survived unchanged.
See image/UPGRADE-0.12.4.md for qualification and rollback;
Adam confirmed the production experience works after deployment; individual
browser/tool/upload scenarios were not itemized.
Only aggregate native metrics are enabled: ENABLE_OTEL=true,
ENABLE_OTEL_METRICS=true, traces/logs false, five-minute export
(OTEL_METRICS_EXPORT_INTERVAL_MILLIS=300000) to
https://telemetry.bayleaf.dev/v1/otlp/metrics. A dedicated source-scoped
write-only bearer capability is held in the DO SECRET
OTEL_EXPORTER_OTLP_METRICS_HEADERS; no collector read capability enters Chat.
The full mandatory environment, empty Basic/resource overrides, timeout units,
hash/version update ritual and source behavior are in
otlp-rollout.md.
Use that complete configuration for recovery, not just the enable flags here.
Traces, logs, exemplars and automatic instrumentation remain off. HTTP
route/method minimization occurs before aggregation; resource attributes are empty.
Exports page complete cumulative HTTP tuples at 99 points maximum, preserving
reset metadata. Three native user-count gauges run in a background collection
thread using one dedicated read-only PostgreSQL connection (200-ms statement,
100-ms lock and pool-wait limits), not the application pool. No individual request
stream, identity, prompt or completion is exported by this lane.
The bounded five-minute on/off production gate passed: CPU changed −1.534
percentage points; loopback health/version p95 changed +2.50%, with no HTTP errors
or observed pool/cancellation errors; one metrics connection; warmed callback
probes 7.934–11.427 ms. RSS peak on was approximately 1.64 GB (off approximately
1.82 GB), not a long-term memory/capacity guarantee for this 2-GB instance. These
sequential windows are not matched campus-user load or full user-request p95.
Live private collector readback verified all five metric names, approved
dimensions, the observed source batch bound and 90-day active expiry. No
gauge values were retained in qualification evidence. See
native-production.md.
The 120-points/minute retry budget still has the documented lost-ack headroom
limitation. Five-minute paging reduces freshness; the active-user gauge still
counts the previous three minutes, not five-minute unique users. Collector
freshness matters because dedicated exporter errors are suppressed.
For source shutdown set all four OTel enable flags to literal false, retaining
the guarded entrypoint. Full rollback restores the protected pre-change upstream
image/spec and prior wrapper with native export disabled, preserving all
unrelated settings. Never combine the unpatched image with enabled metrics.
Collector admission off alone does not stop source export. Every OWUI version
upgrade must regenerate and requalify the guarded artifact before activation.
Signed-out root arrivals (2026-10-20). Current deployment
a5319b41-56ca-452d-a74e-bee904458baf is ACTIVE from published source
13a3a67b6642e49429ac22483121df9e389057ab, preserving the native configuration
above. BAYLEAF_CHAT_ARRIVALS_ENABLED=true independently installs a guarded
first-party static loader/module. One initial public-root document may send one
identity-free arrival only after ordinary session resolution renders the sign-in
card; existing token markers, direct auth entries and private deep links are
excluded. The client sends only schema version, destination chat and null
referrer, with no credentials/referrer. The collector stores schema 2/policy 3
records with approved coarse network classification and 90-day expiry. Actual
anonymous HTTP → HTTPS → auth browser delivery, stored readback, served asset
hashes and native-export continuity passed; signed-in non-collection has isolated
local browser proof, not a new live authenticated test. See
chat-arrivals.md. Set this one
switch to false to disable arrivals without changing native metrics. Do not add
FRONTEND_BUILD_DIR or STATIC_DIR overrides; the pinned asset installer refuses
them. Recovery must preserve this explicit switch as well as the native settings.
Resolved incident and upgrade (2026-10-18). Promoted v0.12.3 after Adam confirmed at
least a day of issue-free personal-service use. Only the image tag changed;
the startup harness and environment were preserved. This addresses the v0.12.0
socket reconnect/authentication storm documented in upstream
issue #32338 and fixed
by PR #32341, released in
v0.12.1. Before the upgrade, the main Python thread sustained 88–93% CPU,
authentication-related queries dominated approximately 168 SQL calls/second,
and application requests hit database-pool timeouts despite a healthy /health.
A restart alone immediately reproduced the load. The database showed no
long-running queries or blocked locks. Enabled pg_stat_statements in the
application database without a restart; DO had already loaded its collector.
Normalized query counters, not raw parameters or chat content, identified the
authentication amplification.
Both new migrations completed (b8f2c6d91a04 → c92da83b017f →
0bd252b206fb); the harness preceded server PID 1, health passed, and
/api/version reported 0.12.3. Initial 15-second samples fell to 1.3–1.9%
CPU with one 26.3% interval, and 1.7–9.7 SQL calls/second. Startup logs showed
no session errors or pool timeouts. Four subsequent 20-second samples measured
19.8%, 9.1%, 2.0%, and 11.7% CPU, with 9.1 then approximately 2 SQL calls/second;
all eight observed application database connections were idle. Adam confirmed
normal-browser sign-in was working after recovery. Existing browser tabs must
reload to receive the frontend fix. Today's managed database backup was verified. The expired
admin JWT and unresponsive UI prevented a fresh pre-upgrade resource pull;
recovery proceeded using the managed backup and preserved app spec rather than
blocking on the failed service. After token renewal, authenticated Basic and Help
inference returned the expected smoke-test response (1.0 and 7.9 seconds).
Full private pulls captured 9 tools, 6 functions, 8 skills and 4 workspace
models. Tool/function sources and tool schemas matched the repository after
normalizing schema order. Model differences were new null voice defaults;
known Brace3 metadata drift remained outside this upgrade. The live Code Sandbox
skill had three added decorative characters, left untouched pending confirmation.
The hidden base model remained active, hidden and wildcard-user readable.
Adam accepted incident closure after recovery and authenticated inference
verification. Full Basic/Help browser/tool/upload acceptance is a deferred
follow-up, not a completed check. Monitoring and capacity design are separate
post-incident work.
The private specs are under the session's temporary
bayleaf-upgrade-20261018 directory. Image-only rollback is not qualified
across the new migration revision. No diagnostic hook, pool increase, or
additional worker was deployed.
Upgrade evidence (2026-10-12). Promoted v0.12.0 after Adam confirmed personal
service soak. Deployment 737f9787-eb3e-4d6c-b26d-3041322d1fd7 reached ACTIVE;
all six Alembic migrations completed, the startup harness preceded server PID 1,
health passed, and /api/version reported 0.12.0. Authenticated admin Basic
and Help inference returned the expected smoke-test response. Full private
before/after pulls (9 tools, 6 functions, 8 skills, 4 workspace models) differed
only by newly assigned version-history IDs; content, sources, images and grants
were unchanged. The hidden base model remained active with wildcard-user read.
Environment settings were unchanged and all names were documented here.
Snapshots and the previous deployment spec are under
~/.tokens/bayleaf-owui-upgrade-20261012; today's managed database backup was
verified, with no laptop database access opened. Adam confirmed that the browser
experience feels good after the upgrade; fresh CILogon sign-in was not separately
verified. Reverting the
image alone is not a verified rollback across the new migration revision.
| Rule | Target |
|---|---|
chat.bayleaf.dev / |
open-webui service |
bayleaf.dev |
About/landing page (GitHub Pages) |
DNS setup. chat.bayleaf.dev is served by DigitalOcean App Platform's
shared edge (which itself runs on Cloudflare infrastructure). In the
Cloudflare zone for bayleaf.dev, chat is configured as two A records
pointing at DO's published static ingress IPs: 172.66.0.96 and
162.159.140.98 (plus optional AAAA records 2606:4700:7::60 and
2a06:98c1:58::60). These IPs are documented and stable per DO policy
(see https://docs.digitalocean.com/products/app-platform/how-to/add-ip-address/).
Both records are "DNS only" (grey cloud); we do NOT proxy through the
user-owned Cloudflare layer, because DO's edge is already Cloudflare-based
and a second layer would add latency without value. The TLS cert on
chat.bayleaf.dev is issued by Google Trust Services via DO's edge, not
Let's Encrypt.
A CNAME pointing at the default ingress hostname would also work and reads more self-documenting, but the A-record approach is the DO-documented default and avoids binding the DNS record to this specific app's random slug (which would change if the app is ever rebuilt).
Managed PostgreSQL 17 cluster bayleaf-chat-db.
| Property | Value |
|---|---|
| Cluster ID | ea8c7549-e761-44e1-a9c3-e45e478a5202 |
| Engine | PostgreSQL 17 |
| Region | sfo2 |
| Size | db-s-1vcpu-1gb (10 GB storage, 25 max connections) |
| Connection | ${bayleaf-chat-db.DATABASE_URL} at runtime (spec binding) |
| Network access | Trusted sources: one rule of type app scoped to app f1a1e758-…. No IP or VPC rules. |
App-only database access is intentional. The cluster's trusted-source list
contains exactly one entry, the OWUI app itself, so the database is not
reachable from the public internet (or from an admin laptop) even with valid
credentials. App Platform components egress from outside the VPC, so the
app-type rule is the correct mechanism rather than a VPC rule; the cluster's
private_connection endpoint goes unused. The retention-cleanup job is a
component of the same app and is therefore covered, though it holds no DB
credentials and reaches OWUI over HTTPS (see RETENTION.md).
DO Spaces bucket for file uploads and OWUI storage.
| Property | Value |
|---|---|
| Bucket | bayleaf-ucsc-storage |
| Region | sfo2 |
| Endpoint | https://sfo2.digitaloceanspaces.com (path-style; see §6a) |
| Access key | Scoped (Read/Write/Delete on this bucket only), not account-wide full access |
Objects are stored flat at the bucket root (no key prefix). Uploaded via OWUI
yield keys of the form <uuid>_<original-filename>.
All env vars are set with scope RUN_AND_BUILD_TIME unless noted.
| Variable | Value | Notes |
|---|---|---|
WEBUI_NAME |
BayLeaf |
Branding |
ENABLE_SIGNUP |
false |
No direct registration |
ENABLE_OAUTH_SIGNUP |
true |
Users sign up via CILogon |
ENABLE_LOGIN_FORM |
false |
No password login |
OAUTH_MERGE_ACCOUNTS_BY_EMAIL |
true |
Merge accounts across auth migrations |
OAUTH_UPDATE_NAME_ON_LOGIN |
true |
Overwrite display name from OIDC claim on each login |
OAUTH_UPDATE_PICTURE_ON_LOGIN |
true |
Overwrite avatar from OIDC claim on each login (no-op for CILogon which sends no picture) |
OPENID_PROVIDER_URL |
https://cilogon.org/.well-known/openid-configuration |
CILogon OIDC |
OAUTH_PROVIDER_NAME |
UCSC |
Login button label |
OAUTH_SCOPES |
openid email profile org.cilogon.userinfo |
Includes affiliation claim |
OAUTH_AUTHORIZE_PARAMS |
{"idphint":"urn:mace:incommon:ucsc.edu"} |
Preselect UCSC IdP (requires v0.8.11+). A user-editable hint, not enforcement: Chat does not check the idp claim (the API does, via OIDC_REQUIRED_IDP) |
OAUTH_ALLOWED_DOMAINS |
ucsc.edu |
Exact email-domain gate on every OAuth callback; not a wildcard or suffix match |
ENABLE_OAUTH_PERSISTENT_CONFIG |
false |
Keep the deployment environment authoritative for the OAuth domain gate |
OAUTH_CLIENT_ID |
cilogon:/client_id/... |
CILogon client |
OAUTH_CLIENT_SECRET |
<REDACTED> |
Encrypted in DO |
WEBUI_SECRET_KEY |
<REDACTED> |
Encrypted in DO; must be set explicitly (see below) |
CORS_ALLOW_ORIGIN |
https://chat.bayleaf.dev |
Restrict CORS to production origin |
USER_AGENT |
BayLeaf/1.0 (https://chat.bayleaf.dev) |
Identify outbound HTTP requests |
ENABLE_OAUTH_GROUP_MANAGEMENT |
true |
Sync groups from OAuth claims; see §1a |
ENABLE_OAUTH_GROUP_CREATION |
true |
Auto-create groups from claims |
OAUTH_GROUPS_CLAIM |
affiliation |
CILogon eduPerson affiliation |
OAUTH_GROUPS_SEPARATOR |
; |
CILogon uses semicolons |
OAUTH_BLOCKED_GROUPS |
["legacy:*","course:*","hold:*"] |
Protect manually-managed groups; see §1a |
ENABLE_EVALUATION_ARENA_MODELS |
false |
|
ENABLE_MESSAGE_RATING |
false |
|
ENABLE_COMMUNITY_SHARING |
false |
|
DATABASE_POOL_SIZE |
10 |
Headroom above OWUI's default of 5; see §1c. |
DATABASE_URL |
${bayleaf-chat-db.DATABASE_URL} |
Scope: RUN_TIME only |
STORAGE_PROVIDER |
s3 |
|
S3_BUCKET_NAME |
bayleaf-ucsc-storage |
|
S3_ENDPOINT_URL |
https://sfo2.digitaloceanspaces.com |
Region endpoint (path-style); do not use the virtual-hosted <bucket>.sfo2.digitaloceanspaces.com form — see §6a |
S3_REGION_NAME |
sfo2 |
|
S3_ACCESS_KEY_ID |
<REDACTED> |
Encrypted in DO (was plaintext in the pre-migration app; hardened to SECRET during 2026-04 migration) |
S3_SECRET_ACCESS_KEY |
<REDACTED> |
Encrypted in DO (same as above) |
WEBUI_URL |
https://chat.bayleaf.dev |
Canonical URL for OAuth callbacks |
WEBUI_SECRET_KEY gotcha. OWUI's Docker entrypoint (start.sh) checks
for this env var in the shell before Python starts. If the var is missing or
empty, OWUI generates a random key and writes it to .webui_secret_key inside
the container. On ephemeral container platforms like DO App Platform, this file
doesn't survive redeploys — so every deploy gets a new key, silently
invalidating all JWTs and any invite codes signed with the old key. Always set
WEBUI_SECRET_KEY explicitly as a type: SECRET env var in the app spec.
OAuth access boundary. CILogon login is restricted to an asserted email
whose domain is exactly ucsc.edu. Open WebUI lowercases the asserted email and
compares the portion after the final @ to OAUTH_ALLOWED_DOMAINS; subdomains
and suffix lookalikes do not match. The check runs on every OAuth callback before
new-versus-existing account lookup, so previously admitted non-UCSC accounts
cannot sign in again through CILogon. When the gate was enabled on 2026-09-15,
the two existing non-UCSC human accounts were also moved to pending so their
already-issued sessions did not remain an access path; their stored data was
preserved.
The dedicated probe@bayleaf.dev user is not an OAuth-domain exception. It uses
the hidden password endpoint only for local credential renewal, an OWUI API key
for the HTTP probe, and an ordinary injected session JWT for the browser probe.
ENABLE_LOGIN_FORM=false keeps password login unavailable in the public UI.
The probe remains a non-admin user; see probe/README.md for its narrower
credential and endpoint constraints.
OWUI is configured (via admin UI, not env vars) with an OpenRouter API connection that exposes all ZDR-eligible models. The OpenRouter API key is stored in OWUI's admin settings, not in the app spec.
Read back from the live persistent config and admin API after operator edits. These are observed current values, not a before/after diff: earlier resource backups did not capture global admin settings. No production settings were changed during this backup.
- Workspace Tools/Functions: creation and import are admin-only (default user
permissions leave
workspace.toolsand functions off; confirmed by the operator 2026-11-21). This is load-bearing: tool valves hold the Daytona key, Google client secret and instructor Canvas/GitHub tokens, and arbitrary user Python would reach them. - Automations:
automations.enable=false; default user permissionuser.permissions.features.automations=false. This is OWUI user automation, not the separate DigitalOcean retention-cleanup job. - Comments:
comments.enable=false; new notification inbox:notifications.enable=true. Adam accepted the default-on inbox on upgrade. Tool-call rounds now use upstream's 1024 default. Sub-agents remain disabled with saved limits of 20 concurrent, 20 async, 30 iterations and 30,000 output characters. The upgrade added emptyrag.mistral_ocr_params={}. - Context compaction:
chat.context_compaction.enable=true, token threshold80000, token cap80000, retention percentage40. The compaction model and prompt-template overrides are both empty strings. - Default chat model:
ui.default_models="basic"; default pinned models: null. Default and external task models are bothopenrouter.z-ai/glm-5.3-flash; task-model params are{}. - Global default model params:
{"custom_params": {}}. - Global default model capabilities: file context, vision, file upload, image generation, code interpreter, citations, status updates, usage and builtin tools enabled; web search, terminal and memory disabled. Default builtin-tool overrides disable memory, notes, channels and chats.
These global defaults are distinct from saved workspace-model definitions and do not establish which capabilities a particular model actually exposes. The full resource pull found no new prompt, parameter, capability or binding changes in Basic, Help, Basic Canary or Brace. The hidden shared base model was verified active, hidden and wildcard-user readable. Full config exports can contain credentials and stay private; only these reviewed settings belong in the repo.
BayLeaf uses OWUI's OAuth group sync to automatically assign users to groups
based on CILogon's affiliation claim. When a user logs in, CILogon returns
semicolon-separated eduPerson values like
Faculty@ucsc.edu;Employee@ucsc.edu;Member@ucsc.edu. OWUI parses these into
individual group names, creates groups that don't exist yet, and reconciles
membership — adding the user to groups in the claim and removing them from
groups not in the claim.
The clobbering problem. OAuth group sync is a full reconcile: it removes users from any group not present in the current claim. Without protection, manually-managed groups (invite-code groups, course groups, research groups) would be stripped from users on their next login.
Solution: namespaced groups with OAUTH_BLOCKED_GROUPS. Blocked groups are
immune to OAuth sync in both directions — they are never added to or removed
from during the login reconciliation. OWUI's is_in_blocked_groups() supports
exact matches, shell-style wildcards (*, ?), and regex patterns.
Naming convention:
| Prefix | Purpose | Examples |
|---|---|---|
legacy: |
Pre-existing manually-managed groups | legacy:amsmith-group, legacy:https://canvas.ucsc.edu/courses/89028 |
course: |
Per-course access; suffix is Canvas course ID | course:92591 |
access: |
Special access tiers (future) | access:beta-testers, access:elevated-rate |
admin: |
Operational groups (future) | admin:operators |
hold: |
Users on administrative hold | hold:graduation-pending |
(no prefix, @ucsc.edu suffix) |
OAuth-managed affiliation | Faculty@ucsc.edu, Student@ucsc.edu, Member@ucsc.edu |
The current blocked pattern is ["legacy:*", "course:*", "hold:*"]. As new prefixes are introduced,
add them: ["legacy:*", "course:*", "hold:*", "access:*", "admin:*"].
Key details:
- Invite codes are UUID-based. The
help_toolkit(formerlyaccept_invites_toolkit) encodes the group UUID (not name) into invite JWTs. Renaming a group does not invalidate outstanding invite codes. - Model access grants use UUIDs. Renaming a group does not affect which
users can see which models —
access_grantsreference group IDs, not names. - User grants are unaffected. OAuth group sync only touches group
membership. Direct user grants on models (via
access_grantswithprincipal_type: "user") are a separate system entirely. - OAuth group creation is enabled. If a user logs in with an affiliation
value that doesn't match any existing group, OWUI auto-creates it. This means
new affiliation groups (e.g.
Affiliate@ucsc.edu) appear automatically.
Students can't be granted access to a course-specific model (e.g. Brace) until they have OWUI accounts — but most students haven't logged in yet at the start of term. The solution is to create placeholder accounts before term begins, add them to the course group, and let the OIDC merge mechanism handle the rest when students first log in.
How it works:
- Pull the Canvas roster:
canvaslms users -c COURSE_ID -s -e - For each student email, create a placeholder:
owui-cli users add <email> <name>(exits 2 if already exists — safe to re-run) - Look up the user ID and add to the course group:
owui-cli groups add-user <group-id> <user-id> - Student logs in via CILogon for the first time → OWUI finds the placeholder
by email (
OAUTH_MERGE_ACCOUNTS_BY_EMAIL=true), stamps the OIDCsubonto it, and updates the display name from the OIDC claim (OAUTH_UPDATE_NAME_ON_LOGIN=true). The account is now permanently linked. - The course model (e.g.
brace3-92591) is already in the group — Brace just appears in the student's model list with no action required from them.
Tooling: See owui-cli (users add,
users find, users show, groups add-user) and canvaslms for roster export.
A provisioning script for a given course should pull the roster programmatically
rather than transcribing emails by hand to avoid transcription errors.
TAs and guests: Add non-student enrollments (TAs, guests) the same way —
canvaslms users -c COURSE_ID -a -e lists TAs. Add them to the group manually
if not on the Canvas roster.
Re-running is safe: owui-cli users add exits with code 2 if the account
already exists (either a prior placeholder or a student who logged in early).
owui-cli groups add-user is idempotent for existing members. A provisioning
script can be re-run mid-term to catch late adds from the registrar.
Caveats:
- Placeholder passwords are set to the string
placeholder-no-login. Direct password login is disabled (ENABLE_LOGIN_FORM=false) so this is never usable, but it is not a real secret. OAUTH_UPDATE_EMAIL_ON_LOGINis intentionally not set. If CILogon were ever to assert a different email than the placeholder (e.g. a preferred email alias), leaving this off prevents the stored email from drifting and breaking future lookups.- CILogon does not send a
pictureclaim, soOAUTH_UPDATE_PICTURE_ON_LOGINis a no-op in practice but is set for correctness if the IdP ever changes.
BayLeaf Chat runs as 1 instance × 1 uvicorn worker. The instance is
apps-s-1vcpu-2gb; UVICORN_WORKERS is unset, which means OWUI's start.sh
defaults to --workers 1. DATABASE_POOL_SIZE=10 (above OWUI's default of
5) provides headroom for the warm-up burst after process restarts without
approaching the managed PG cluster's max_connections=25 cap.
This is intentional. Going to multiple workers (or multiple replicas) is not a single-flag change on this stack: it requires every shared-state subsystem to use external coordination, per Open WebUI's own guidance:
The gaps today, mapped to that doc's checklist:
| Requirement | Current state | Notes |
|---|---|---|
Shared WEBUI_SECRET_KEY |
✓ set explicitly as a SECRET env var | §1 already documents the gotcha |
| External database (PostgreSQL) | ✓ managed PG 17 | bayleaf-chat-db |
| Redis for WebSockets / config sync | ✗ not configured | streaming events and config-change broadcast would diverge across workers |
| Shared file storage | ✓ DO Spaces (S3) | uploads land in the bucket regardless of worker |
| External vector DB | ✗ default ChromaDB (SQLite-backed) | known to crash workers during RAG ingestion under multi-worker |
| Toolkit ephemeral state | ✗ gws_toolkit uses per-worker app.state |
tracked at rndmcnlly/gws-toolkit#7 |
The architectural cliff is the database connection cap: with 1 instance × 1 worker × pool 10 = 10 connections out of 25 max. Going to 2 workers (20 conn) is still within budget; a second instance would force either a DB upgrade or a connection pooler.
Capacity sizing for "campus, not the world": even at full UCSC adoption (~95 concurrent active sessions estimated, ~5–15 in-flight requests at peak), a single worker with the pool bump should cope. The argument for going multi-worker is availability (cold-start tail mitigation, deploy-window coverage) rather than throughput. Until the readiness gaps above are closed, the cost of going multi-worker (broken RAG, broken Google integration) exceeds the benefit.
Tracked as a longer-term, incremental readiness effort at bayleaf-ucsc/bayleaf#35.
BayLeaf exposes curated "workspace models" that wrap OpenRouter base models with
system prompts, capability flags, tool bindings, and access controls. Each model
is defined in models/<id>/model.json.
| ID | Name | Base Model | Description |
|---|---|---|---|
basic |
Basic | openrouter.z-ai/glm-5.3-flash |
Default model for all users. Campus-aware system prompt (Basic v1.4), builtin tools enabled, skills for Google Workspace, Canvas, web search, and code sandbox. Vision enabled (glm-5.3-flash is vision-capable); reasoning_effort: low. |
help |
Help | openrouter.z-ai/glm-5.3-flash |
BayLeaf help desk. Lists user groups and available models, inspects model configurations, processes invite codes. Binds help_toolkit and web_context_toolkit directly via the model's toolIds. System prompt (Help v1.5). reasoning_effort: low; vision on (glm-5.3-flash is vision-capable). |
Sharing a workspace preset is not sufficient: OWUI also requires non-admin
callers to have read access to every underlying model in its base_model_id
chain. A model discovered from OpenRouter but absent from OWUI's model table is
admin-only for this check. The picker can still display the shared preset even
when inference will fail with Model not found.
The shared underlying openrouter.z-ai/glm-5.3-flash model is now registered as
active, public read, and hidden. Source:
models/base-glm-5.3-flash/model.json. Hidden removes it from the normal picker,
not from authorization or API discovery: users may invoke the raw model directly.
That tradeoff was explicitly accepted on 2026-09-07 when the new non-admin probe
exposed the missing grant. The outage's start time was not established.
Every model swap must check the new base's record/grants and perform an actual non-admin inference request. Admin canary success and model-list visibility do not establish campus-user access.
Admin-private models used to exercise a candidate base model in prod before
swapping a production model to it. The canary's configuration is an
intentional clone of its production counterpart except for base_model_id
and reasoning-effort tuning, so the model is the only variable. No
campus-wide grants: a single read grant for the admin user (zero grants
would hide the model even from the admin on the completions path).
| ID | Name | Base Model | Purpose |
|---|---|---|---|
basic-canary |
Basic Canary | openrouter.z-ai/glm-5.3-flash |
Clone of basic used to evaluate glm-5.3-flash before the 2026-09-01 production swap (ZDR ✓ via 18 OpenRouter endpoints, several US-based). Its prompt may lag Basic between evaluations; retarget per evaluation cycle. |
| ID | Name | Base Model | Access |
|---|---|---|---|
brace3-94741 |
Brace (CMPM 121, Fall 2026) | openrouter.z-ai/glm-5.3-flash |
course:94741 (84 roster students, 2 TAs, instructor; provisioned 2026-09-24) |
The model's meta.toolIds directly binds brace3_canvas_toolkit. OWUI 0.11.4
also requires a tool read grant for non-admin execution, so the toolkit has
a course:94741 group grant and can appear in those users' tool pickers on
other models. The brace3_canvas_system_prompt_filter fetches the course
prompt from Canvas; it does not inject tools.
Both have separate CANVAS_ACCESS_TOKEN valves with the same credential for
this Adam-taught course. The toolkit restricts endpoint types and URLs to
course 94741, including pagination links; the group grant must not expose
Adam's other Canvas courses. Revisit credential
ownership before onboarding another instructor's course. See the playbook under
../.agents/skills/bayleaf-ops-router/playbooks/brace3-course-access.md for
the provisioning and verification procedure.
These models remain on the live instance but are deactivated (is_active: false).
Their configurations are preserved in models/ for reference.
None.
Basic — The default landing model. System prompt (Basic v1.4) orients the
model as a sub-trillion-parameter open-weight campus assistant, encourages
concise replies, and suggests users start fresh conversations when changing
topics. It flags when an opening Canvas
assignment link might mean the user intended a course-specific agent and directs
them to their instructor for access instructions. Since 2026-10-27, inherits
global model capabilities and builtin-tool defaults rather than storing its own
overrides. Native function calling is OWUI v0.12.3's fallback, so Basic no longer
stores function_calling. The global defaults disable memory, notes, channels
and chats; other tools remain subject to service and permission gates. Skills
bound: google-workspace, bayleaf-for-students, bayleaf-for-faculty,
bayleaf-for-employees, canvas-api, web-search, code-sandbox,
offramp. Vision enabled (glm-5.3-flash is vision-capable); file upload
enabled. reasoning_effort: low (the flash model is always-on reasoning, so
low is the responsiveness-prioritizing setting).
The 2026-10-27 simplification preserved the avatar, prompt, reasoning effort,
skills, basic_prompt_filter, suggestions, base model and public grant. Live
stored-model and avatar readback passed; /api/models confirmed inherited
global capabilities and builtin-tool defaults. A full private before/after
resource backup found only Basic changed. OWUI serializes its omitted
capabilities field as null, which still inherits defaults. Adam confirmed the
live conversation playtest works on 2026-10-27.
Basic Canary — Canary clone of basic (see Canary Models above): its
system prompt can lag production between evaluations; skills, filters, and
capabilities remain aligned. It carried the glm-5.3-flash canary evaluation
(vision on, reasoning_effort: low) that passed on 2026-09-01; retarget it to
the next candidate during the next model-swap evaluation. Private to admins;
delete or retarget it after each evaluation cycle rather than exposing it.
Help — Capabilities match the flash base model's offering (vision and file
upload enabled; no code interpreter, usage display enabled). Vision was
initially held off as a minimal-capabilities posture, then enabled once the
vision-capable glm-5.3-flash base landed (2026-09-01). Binds help_toolkit and web_context_toolkit directly via the model's
toolIds (no filter; the stealth injection via help_filter was retired in
June 2026 in favor of plain model-bound tools), giving users tools to list
their groups, see available models, inspect model configurations, process
invite codes, and search the web for self-discovery (including consulting
BayLeaf's own source on GitHub). Binds the offramp skill via skillIds (its
only bound skill). System prompt
(Help v1.5) describes BayLeaf facts and firmly redirects non-help tasks to
Basic.
Deep Research (removed September 2026) predated BayLeaf's skill system and made it straightforward to start a research chat without external-data tools. Basic can now use a skill to remind users to choose that posture themselves.
Gambit (removed September 2026) was a highly effective, tool-free rapid
game-prototyping assistant for CMPM 171. Its full pre-agentic system prompt is
preserved in archive/gambit-system-prompt.md.
Earlier Brace3 course models (removed September 2026) paired a workspace
model with a filter that force-enabled brace3_canvas_toolkit. The Fall 2026
course model retains the dynamic prompt filter and binds the toolkit directly.
OWUI 0.11.4 still checks tool-level access on dispatch: the toolkit needs a
course group grant, so students can also select it on other models. Its
course-specific URL allowlist limits what that choice can read.
Fall 2026 Canvas submission Action. brace3-94741 binds
brace3_submit_action via meta.actionIds. It is active and non-global; the
legacy brace_submit_action was retired on 2026-09-30. The new Action accepts only
assignment URLs in course 94741, requires HTML file-upload submissions,
matches non-admin users to Canvas student enrollments by BayLeaf email, and
asks for confirmation before uploading. It scans user messages on the selected
chat branch for exactly one valid assignment URL; with zero or multiple matches
it prompts for the URL. Submission success shows a dialog and toast. The Canvas
token is an admin valve, copied from the Brace3 prompt filter, never committed.
Admin trials use course-94741 Test Student ID 152664. A test submission to
assignment 897740 succeeded; a non-admin student submission and the latest
export format have not yet been verified end to end. Canvas's 201 Created
upload Location provides a file ID without a follow-up GET (which can return
403 for a student-private file); 3xx redirects still require confirmation.
The Action reads the owner's stored chat branch, not the flattened Action
payload. Its script-free HTML uses <article data-schema="brace3-transcript" data-schema-version="1"> with course, assignment, and chat IDs; ordered
.turn and .event elements identify roles, message/event IDs and indices,
tool names, and linking data-call-id values. Escaped <pre class="payload">
elements declare data-format="markdown|text|yaml"; tool YAML can be parsed
with yaml.safe_load. Only recorded times get <time datetime="…"> and
data-timestamp: tool times are never inferred. Tool calls start expanded,
reasoning starts collapsed, and tool results start collapsed only above 256
bytes of UTF-8 YAML. The transcript includes reasoning and tool outputs and
is stored in Canvas, outside Chat's history-retention boundary; grading tools
must treat it as student work with the submission's access restrictions.
Procurement (removed September 2026) established the whole_document_retrieval
toolkit pattern: agentic, access-gated reads of complete OWUI Knowledge Base
documents by file ID, without relying on vector or embedding retrieval. The
toolkit remains available for a future use; the model configuration and its
large checked-in policy source were removed.
Everett Program Chat (removed September 2026) was an early trial of having a non-technical community manage a workspace model. OWUI configuration proved too unfamiliar to sustain participation. A future approach could let a community manage a bounded Google Doc or Drive folder, potentially shared with a dedicated service account for sensitive scopes, while an agent reads that source. This would also let people use agents that access the same materials through their own Google accounts rather than requiring OWUI adoption.
Tools are Python classes that OWUI calls on behalf of the LLM. Each tool is in
tools/<id>/ with tool.py (source) and meta.json (metadata, specs, access
grants).
| ID | Name | Description |
|---|---|---|
lathe |
Code Sandbox | Coding agent tools backed by per-user Daytona sandbox VMs (see below) |
web_context_toolkit |
Web Context | Tavily-backed web search and page-content extraction in one toolkit (valve: API key) |
campus_directory_toolkit |
Campus Directory | Scrapes UCSC campus directory with CSRF handling. General-access name search, bounded by a process-wide politeness cap (20 searches/min, 1000/day across all users) so BayLeaf does not concentrate load on upstream. Looser than the API's /directory (exact CruzID, per-account cap) by design |
whole_document_retrieval |
Whole Document Retrieval | Agentic KB retrieval — list and read full documents by file ID, bypassing vector/embedding search. Access-controlled via __user__ and __model_knowledge__. |
The former YouTube stub, Random Choice example, DateTime Converter, and DeepInfra key generator were retired on 2026-09-24. Scoped keys backed by a user's BayLeaf API budget are proposed in issue #76.
The most substantial toolkit on the deployment. Source: rndmcnlly/lathe. Available to all users but not bound to any model by default — users enable it per-chat via the tool picker in the chat composer.
Current version: 1.3.3 (2026-10-27), byte-identical to upstream
commit 864e709 and Adam's personal deployment. expose requires an explicit
private or public policy and accepts
an optional untrusted hostname tag, which BayLeaf ignores. Private is the
default guidance and fails closed; headerless public calls may fall back to Daytona's direct
signed URL if wrapping fails. The installation credential is an admin valve
backed by the API's PREVIEWS_INSTALLATION_KEY Worker Secret.
Hardening upgrade (2026-10-27): promoted personally playtested 1.3.3 from
BayLeaf's 1.3.0 (SHA-256
0fb5de39473418d2c8578a5f1f7660b1272466d5dc17e0d53138457a6787cdad).
All 837 offline tests passed. Browser clicks now refuse ambiguous or covered
targets before sending input. Background completion notices are sandbox-owned,
claimed by a later tool result in the originating chat, with duration measured
from sandbox launch/completion records. Nothing wakes an idle chat.
Requirements, valve definitions and tool signatures are unchanged. Exact live
source readback, all 14 existing valves, Code Sandbox name/grants and health 200
passed without restart. Full private pre/post resource reconciliation found only
Lathe source/schema changes; the hidden Basic base model was checked separately.
The existing Code Sandbox skill needed no change. Rollback source and valves,
plus full private snapshots: ~/.tokens/bayleaf-lathe-133-20261027/.
Model-mediated BayLeaf playtesting remains with Adam.
Upgrade (2026-10-21): promoted Adam's personally used upstream 1.1.0
(SHA-256 d5fea4351de5cb065a2d1696c729e0358d79740a878ed29a2dcb3a0d0eeb0937).
All 510 upstream offline tests passed. Production source and complete generated
schema matched; supported existing valves, Code Sandbox name, and grants were
preserved, and health passed without restart. New onboarding_instructions and
handbook_url valves remain empty. Dependencies are now httpx, pydantic>=2,
cachetools, and PyYAML; Lathe no longer requires Pydantic AI or httpx-ws.
Rollback and full private before/after snapshots:
~/.tokens/bayleaf-lathe-rollout-20261021.
Full pre/post pulls found only Lathe source/schema changes before the companion
Code Sandbox skill update. The skill's updated guidance was deployed and read
back, preserving its existing live decorative suffixes outside the repo copy.
Python sessions are now owned by a supervisor inside the sandbox, keyed by
deployment, caller, conversation, and sandbox. Worker-local caches no longer
select interpreter identity. Old Daytona interpreter variables are not migrated:
users must rerun setup. Stop/restart or timeout loses Python memory, not saved
workspace files. Session journals and bounded code/output records live under
/home/daytona/.local/share/lathe/python; completed records expire on later
submissions after at least 24 hours. Uncertain execution must not be blindly
replayed. This does not establish live multi-worker OWUI qualification.
delegate, handoff, built-in volume support, and managed application target
shortcuts have been removed. expose now only publishes an already-running
http:<port> service; optional applications are installed/launched with bash.
Adam confirmed production playtesting works. Automated live model-mediated
qualification was not run: the upstream deployment collector still lacks
chat/message filtering and must not use Adam's admin identity.
Refactor upgrade (2026-10-12): promoted the unchanged personally used 0.32.0
build (SHA-256 d7d26ad8151fa0a85e76fadc583585060a001863c4059c59f750f4ea907c45b3).
All 494 upstream offline tests and six isolated BayLeaf OWUI checks passed:
complete source/schema, bash, write/read, interpreter, view, and delegate.
The additional first-time-agent scenario timed out; that broader workflow is
not qualified by this run. Production readback matched the personal source and
complete schema; all valves, the Code Sandbox name, and grants were preserved.
Health returned 200, with no restart. Full private before/after pulls found only
the Lathe source/schema changes; the hidden Basic base model was checked separately.
Snapshots are under ~/.tokens/bayleaf-lathe-refactor-20261012-193329.
Adam confirmed production playtesting works. A foreground diagnostic rerun
exposed an upstream deployment-harness isolation bug: the suite used Adam's
admin identity, and its Socket.IO collector accepted unrelated chats' events.
An in-memory request-ID filter eliminated that false delegation failure; all
six core checks passed again. The first-time scenario still timed out after
240 seconds without a tool-status event, so its cause remains undiagnosed.
Further live qualification should use a dedicated synthetic account, not Adam's
admin session. The separate Docker monitor already uses a synthetic identity.
Upstream repair and regression-test proposal:
Lathe #107.
No tools, parameter contracts, dependencies, valves, or preview protocol were added. Search now returns bounded concrete paths/hits, text previews are bounded, and completed bash logs/exit evidence are retained for 24 hours (or until sandbox stop/restart). Delegate references have an aggregate 50-KiB limit and fail rather than silently clip. Interpreter identity is separated from evictable chat notices; it remains local to one loaded toolkit instance, not durable across OWUI reloads or workers. Failure reporting and workspace readiness checks were hardened.
Production reconciliation (2026-10-11): pulled Adam's subsequent 0.31.2
deployment back into the repository, byte-identical to upstream 74b42c2.
The first-call snapshot now includes discovered skill names, descriptions, and
paths using the same catalog builder as explicit onboard(); full skill bodies
still require read(path). Dependencies and tool schema are unchanged. The full
private pull is under ~/.tokens/bayleaf-prod-pull-20261011-120432; unrelated
Brace3 metadata-format differences were left untouched.
Earlier upgrade (2026-10-11): deployed unchanged upstream 0.31.1, commit 9642168
(SHA-256 00d56dc8125891ba0d30b5c71cb1a7abdb5171c60b4208e2e6b512c385ab1567).
This adds agent-facing skill-discovery paths to onboarding and the workspace
snapshot, with no mechanical, dependency, valve, or tool-signature changes.
Adam explicitly waived personal-instance testing and long-term soak for the
hackathon rollout. All 323 upstream unit tests passed. Production source readback
matched upstream; valves, tool name, grants, and generated schema were unchanged.
Health returned 200; no restart was needed. Full private before/after pulls
found only the expected Lathe source/version changes, apart from rotating metadata.
Rollback and reconciliation snapshots are under
~/.tokens/bayleaf-lathe-rollout-20261011. Human model-mediated playtesting
remains separate.
Previous upgrade (2026-10-08): the deployed and vendored source was upstream 0.31.0,
commit 4cd5663, byte-identical to the personal Chat deployment (SHA-256
816b84af2c2e24d6f6024d49f55a8ef9d1faf23057a425da4a77a7d746e8e29c).
All 347 upstream offline tests passed. After refreshing the expired admin token,
BayLeaf source and complete generated schema were verified, all valves and tool
grants/name were preserved, and the Code Sandbox skill content and grants/active
state were read back. Health returned 200; no app restart was needed. Six isolated
OWUI core checks passed (source/schema, bash, write/read, interpreter, view,
delegate); the additional first-time-agent check failed because Basic skipped
the overview manual. Private before/after backups are under
~/.tokens/bayleaf-lathe-upgrade-20261008. Full reconciliation found only the
Lathe source/schema and Code Sandbox skill changes. The new
expose(..., upstream_headers={...}) parameter configures fixed application
headers independently of public/private policy. Nonempty headers require exact
boolean upstream_headers_applied: true from BayLeaf's registration endpoint:
missing acknowledgement fails closed with no direct fallback in either mode.
API support was deployed separately in issue #86. Values remain in Chat tool arguments,
and applications can reflect them.
Production Basic → loaded Lathe expose → BayLeaf API → Daytona qualification
verified public HTTP injection of fixed Basic credentials and a custom header,
including replacement of browser spoof values. Private header-bearing exposure
returned a wrapped URL and denied unauthenticated requests with HTTP 401.
The focused headerless regression passed: public HTTP 200 served the fixture
with no injected Authorization or custom header, preserving gateway filtering.
The fixture used a separately tracked /tmp/lathe-smoke-* directory and port
8943 in the coordinated API test sandbox; existing applications were untouched.
Two harness assumptions needed correction: private denial can be 401 rather than
a redirect, and BayLeaf filters unconfigured custom browser headers. Each run
revoked its exact leases, verified preview 404s, and removed only its fixture.
All six previews from the three production-smoke runs were revoked and returned
404. Final read-only cleanup verification found no /tmp/lathe-smoke-*
directories and no listener on 8943. Sandbox
6dc25038-2a83-4061-a4a7-5ebbc845d14e was preserved by coordination decision:
work of unestablished provenance had appeared outside this fixture. The final
read-only check no longer found workspace/headercheck.py; this session did not
remove it or change port 8765. No claim of whole-sandbox teardown is made.
The isolated suite cleaned up its separate staging toolkit and sandbox.
Human workload playtesting remains separate.
What it does. Gives any OWUI model a coding-agent tool surface — lathe,
bash, read, write, edit, glob, grep, view, interpret,
onboard, expose, destroy — executing against per-user sandbox VMs
(Daytona) with transparent lifecycle management. Each
user gets a single persistent sandbox identified by email; the sandbox is
created lazily on first tool call and survives across conversations.
Zero-token artifacts. In Kelsey Hightower's
sense, the Code Sandbox is
a construction and maintenance site where inference tokens can be spent to
produce deterministic artifacts that subsequently run without inference.
Gambit's one-prototype, edit-directly discipline prefigures this: the generated
artifact is the output, not a reason to keep an LLM in its runtime loop. The
expose tool provides transient file and service access; durable Pages and
Apps export
layers remain planned in issues
#57 and
#51, respectively.
Tools exposed to the model:
| Tool | Purpose |
|---|---|
lathe(manpage) |
Toolkit manual; lathe("overview") before first use teaches the sandbox model and workflows |
bash(command, workdir, foreground_seconds) |
Execute shell commands; long-running commands auto-background with log paths for monitoring. Output truncated to last 2000 lines / 50 KB |
read(path, start, stop) |
Read file with line numbers |
write(path, content) |
Write/create file (parent dirs created automatically) |
edit(path, old_string, new_string, replace_all) |
Exact string replacement; fails on ambiguous matches unless replace_all=true |
glob(pattern, max_lines) |
Search for files in the workspace by glob pattern |
grep(pattern, files, max_lines) |
Search file contents in the workspace by regex |
view(path) |
Load a PNG, JPEG, GIF, or WebP image into a vision-capable model's context (up to 4 MiB) |
interpret(code, timeout) |
Run Python in a persistent REPL session (variables and imports persist across calls) |
onboard(path) |
Load project context (directory listing, AGENTS.md, skill catalog) for agentic workflows |
expose(target, access, tag, upstream_headers) |
Publish an already-running http:<port> service; access is required (private or public), tag and fixed application upstream_headers are optional. Nonempty headers require acknowledged wrapper injection in either access mode. Start applications with bash; keep terminals and IDEs private |
destroy() |
Permanently destroy the sandbox VM (irreversible) |
Sandbox lifecycle. Sandboxes idle-stop after 15 min, archive after 60 min
past stop. The first tool call in a conversation transparently creates, starts,
or unarchives the sandbox as needed, but BayLeaf disables automatic creation
(see provisioning policy below). Lathe no longer supports built-in persistent
volumes: the VM filesystem survives stop/archive, but deleting the sandbox is
final. Ephemeral command and interpreter runtime state lives under /dev/shm/lathe
and is lost on stop; interpreter journals live separately in the VM filesystem.
Transient previews. HTTP expose calls register with
https://api.bayleaf.dev/previews/registrations. Private access requires the
owner's API login, which is separate from Chat login, and never downgrades.
Public access serves anyone with the URL; headerless calls may return Daytona's direct
signed URL if public wrapping fails. BayLeaf-wrapped URLs use
https://{cruzid}-{access}-{nonce}.bayleaf-proxies.dev/, with no visible port,
application tag, or stable alias. CruzID makes ownership legible in group
settings, while the access segment preserves the agent's policy choice after a
URL leaves its initiating conversation. Each Lathe registration is an independent 24-hour
lease because upstream no longer sends a stable slot. The gateway does not
manage sandbox wake/sleep or service relaunch. See
the gateway contract and evidence.
Accepted risk: the model chooses public access. access="public" and
public_headers_acknowledged are model-supplied arguments; Lathe asks for no
human confirmation, and nothing beyond docstring guidance stops a public VNC
desktop, terminal or IDE. A prompt-injected or confused model could therefore
publish remote control of the user's sandbox. This is deliberate. Sandboxes
are meant for wild exploration: a mistake there is recoverable with
destroy() and a fresh machine, which is the point of not running agents on
your own computer. Gating VNC alone would be theatre, since a few shell
commands can expose a terminal or desktop through any http:<port> or an
outbound tunnel. The real boundary is what the user puts in the sandbox: do not
log in to accounts there that you would not hand to a stranger with the URL.
The gateway supports WebSockets, service workers on fresh nonce origins, and server-managed application cookies. JavaScript-managed original cookie names are not supported. Browser caches can outlive the server-side grant. The current 1-GiB sandbox OOM-killed code-server during qualification; a disposable 4-GiB test confirmed core IDE and terminal operation. This did not change BayLeaf's default sandbox size at that time. On 2026-09-30, Adam approved 2-GiB RAM for new Chat sandboxes after his expected workload hit the 1-GiB limit; existing sandboxes remain unchanged. The off-ramp policy still applies.
Historical project-rooted services (Lathe 0.30.7, removed in 1.0). These
managed target shortcuts no longer work in 1.1.0; install and launch services
with bash, then publish http:<port>. The former behavior was:
dufs:/home/daytona/workspace/project
serves a selected directory; code-server:/home/daytona/workspace/project
opens the IDE there. Bare names use the whole workspace. Named service roots
must exist inside the workspace after symlink resolution. Each dufs/code-server
instance uses a fixed port and refuses a mismatched existing root rather than
replacing the running service. Managed dufs enables upload, delete, search,
folder ZIP downloads, and file hashes without permitting symlinks outside its
served root. Older running dufs processes using --allow-all must be stopped
before re-exposure; do not stop users' services automatically. Code-server's
opening folder is not filesystem confinement, and both managed code-server and
ttyd require private access. Python static-site serving can still follow symlinks
inside the served directory. These controls do not confine a model-controlled
shell or an arbitrary http:<port> service.
UserValves. Users can configure env_vars (a JSON object of environment
variables like {"GITHUB_TOKEN":"ghp_..."}) that are injected into every
bash command. The field is masked in the settings UI, but the model-controlled
shell can read and disclose those values; use narrowly scoped credentials.
Admin valves (live OWUI configuration; credentials and full backups are never committed, selected non-secret overrides may be tracked):
daytona_api_key— Daytona API keydaytona_api_url— Control plane URL (default:https://app.daytona.io/api)daytona_proxy_url— Toolbox proxy URLpreview_wrapper_url: HTTPS registration endpoint (configured for BayLeaf API)preview_wrapper_key: secret installation credential (admin-only password field)preview_expiry_seconds: upstream HTTP signed-URL lifetime (configured as86400)deployment_label— Label key for sandbox tagging (e.g.chat.bayleaf.dev)auto_stop_minutes— Idle timeout (default: 15)auto_archive_minutes— Archive delay after stop (default: 60)auto_delete_minutes— Daytona stopped-state deletion interval (-1 = never); inactive while automatic creation is disabledonboarding_instructions: optional agent-visible admin guidance (empty on BayLeaf; never put secrets here)handbook_url: optional agent handbook reference (empty on BayLeaf; Lathe does not fetch it)foreground_timeout_seconds— Seconds to wait for bash before auto-backgrounding (default: 30)auto_create_sandbox— Automatically create a sandbox when none exists for the user (default:true; disable for deployments where sandboxes are provisioned externally)sandbox_missing_message— Custom message returned to the agent when no sandbox exists and auto-create is off (empty falls back to a generic message)
Provisioning policy (2026-10-06). Live Lathe has auto_create_sandbox=false.
Missing-sandbox errors direct users to https://api.bayleaf.dev/, UCSC sign-in,
and “Set up sandbox,” then back to Chat to retry. Existing sandboxes still
resume normally. The two non-secret overrides are saved in
tools/lathe/valves.public.json; this is a partial configuration, not a full
valve backup. Merge it into existing valves, never replace credentials with it.
Live readback verified these two changes and unchanged remaining valves.
sandbox_create_overrides: JSON of extra Daytona create args. Cannot overridename,labels, orvolumes. Snapshot resources come from the snapshot; current Daytona rejects cpu/memory overrides with a snapshot (including the default). The disposable custom-shape test usedbuildInfo.
New-sandbox shape (2026-09-30). The configured creation override is
{"cpu":1,"memory":2,"disk":3,"buildInfo":{"dockerfileContent":"FROM daytonaio/sandbox:0.9.0\n"}}.
This uses the same base image as daytona-small but requests 2 GiB rather than
its fixed 1-GiB allocation. No test TTL is included in production. CPU, disk,
idle stop/archive/deletion, and disabled persistent-volume settings are unchanged.
This applies only at creation: existing sandboxes are not resized or recreated.
The eight legacy 1-GiB sandboxes remain small. Adam will advise users in person
about opting into a fresh 2-GiB sandbox: first export any files they need, then
deliberately destroy and recreate their own environment. Destruction is permanent;
there is no automatic migration or file preservation across recreation.
Upgrade evidence (2026-09-17). Full OWUI regression passed 7/7 scenarios:
source/schema, bash, write/read, interpreter, view, delegate, and protected expose.
A separate smoke test invoked production lathe and received a protected CruzID
URL. Original grants and existing valves were preserved. Rollback source/valves
and full before/after snapshots are private under
~/.tokens/bayleaf-lathe-rollout-20260917. The service restart completed as
deployment a25ae1e8-7d81-481b-aa09-e6f57c595b1b; the OWUI image remains v0.11.3.
OWUI installs requirements when code changes. This restart was a precaution
against cached imports across the dependency major-version change, not evidence
that missing-dependency installation requires restarting. Personal proxy
dogfooding was deferred; the coordinated rollout was explicitly approved.
Upgrade evidence (2026-09-18). Version 0.28.0 was explicitly approved for
rollout despite a short soak because it closes the unwrapped bearer-token SSH
path. Upstream unit tests passed 722/722. Production source matched upstream
byte-for-byte, access grants and valves were preserved, /health returned 200,
and the protected-expose smoke test returned an owner-authenticated URL with no
upstream hostname. The same production smoke confirmed that expose("ssh") is
refused without returning access material. Rollback snapshots are private under
~/.tokens/bayleaf-lathe-rollout-20260918.
Upgrade evidence (2026-09-20). Version 0.29.6 and BayLeaf's integrated v2
wrapper contract were deployed together. Upstream's 118 offline tests, the
25-check workerd/D1 preview suite, TypeScript checks, isolated private and public
OWUI exposure tests, and production-tool private/public smokes passed. The
production public URL served the tracked fixture without login; private returned
only an owner-authenticated CruzID URL; neither exposed the Daytona hostname.
SSH refusal still passed. The full isolated seven-scenario run passed its first
six checks, then its final model-mediated expose timed out; the same path passed
separately before and after that nondeterministic timeout. Rollback snapshots are
private under ~/.tokens/bayleaf-lathe-rollout-20260920.
Upgrade evidence (2026-09-24). Version 0.30.5 was deployed from the source
running on chat.adamsmith.as, byte-identical to upstream main. The personal
install was from the same day; Adam explicitly waived the usual soak gate. This
version raises the Open WebUI floor to 0.11.0 (BayLeaf runs 0.11.3) and changes
sandbox lifecycle, command cleanup, delegation, and file searches; its admin
valves, dependencies, and tool names/parameters are unchanged. Upstream Python
CI and CodeQL passed. The isolated live monitor passed source/schema, bash,
write/read, and interpreter checks; its view check failed when the model called
lathe("overview") instead of view. BayLeaf production source matched the
candidate byte-for-byte after deployment; grants, active state, and valves
were preserved, and /health returned 200. Rollback snapshots are private
under ~/.tokens/bayleaf-lathe-rollout-20260924. A model-mediated BayLeaf
playtest passed: Basic selected Code Sandbox, called Lathe bash, and returned
the expected lathe-0305-ok output.
Upgrade evidence (2026-09-30). Lathe 0.30.7 was promoted from the personal
instance after Adam confirmed sufficient use; it matched upstream byte-for-byte.
All 276 offline tests passed and upstream's isolated live monitor was green.
BayLeaf's staging suite passed all six core scenarios on retry after an initial
delegation timeout. Model-mediated preview attempts failed at tool selection or
call budget, not an observed preview service failure. Direct upstream-tool calls
against a disposable real sandbox verified the 1-CPU / 2-GiB / 3-GiB creation
shape and Linux cgroup limit, project-rooted private/public static previews,
anonymous private-access denial, and managed public IDE refusal. The initial
direct private check omitted the trusted OWUI user ID and correctly failed
closed; the corrected identity fixture passed. Test preview registrations were
revoked and sandbox deletion verified. Production source, all valves, grants,
and display name were read back after deployment; /health returned 200.
The Code Sandbox skill was updated. Secret-bearing rollback snapshots and full
before/after backups remain private under
~/.tokens/bayleaf-lathe-upgrade-20260930-132308. No existing user sandbox was
resized or destroyed. Human post-upgrade workload testing remains pending.
| ID | Name | Access | Injected by | Description |
|---|---|---|---|---|
brace3_canvas_toolkit |
Brace3 Canvas | course:94741 group read grant |
brace3-94741 via meta.toolIds |
Course-94741-only Canvas read access + date localization for Brace v3. Own CANVAS_ACCESS_TOKEN valve. |
brace3_github_toolkit |
Brace3 GitHub | course:94741 group read grant |
brace3-94741 via meta.toolIds |
Public GitHub discovery, files, history and Actions/Pages evidence. |
brace3_drive_toolkit |
Brace3 Drive | course:94741 group read grant |
brace3-94741 via meta.toolIds |
Shared Brace identity; Docs, Sheets, Slides and folder-scoped search. |
Brace2's all-in-one toolkit, prompt/tool-injection filter and submission action were deleted from production and the current tree on 2026-09-30. Their source and non-secret metadata remain in Git; see retirement records.
Version 2.0.3 replaces use_canvas_api(resource_url, jq_expr) with eight
named tools so course activity is legible in tool calls and submitted transcripts:
canvas_list_assignments,canvas_read_assignment(assignment_id)canvas_list_pages,canvas_read_page(page_slug)canvas_list_quizzes,canvas_read_quiz(quiz_id)canvas_read_syllabus,canvas_localize_date(iso_date_str, timezone_str)
Lists return named arrays (assignments, pages, quizzes) of identifying
metadata; individual reads return objects with full HTML content. Assignment
details preserve submission types, allowed extensions, attempts and rubrics when
present. Quiz details expose descriptions and general requirements, not questions,
answers, access codes or attempts. Explicit field projections exclude instructor
administration fields, page editor identities and student-specific records.
Course-wide UTC dates retain their original fields and gain *_local counterparts
with Los Angeles UTC offsets, including daylight-saving changes. They do not
represent individual extensions.
The view is depersonalized: published course-wide resources only, excluding student-hidden pages and resources explicitly restricted to overrides. Direct reads apply the same publication checks as lists. Unavailable reads say the resource might not exist or might be unpublished; they do not confirm hidden titles. This is not impersonation of a specific student or a determination of their individual availability, enrollment, accommodations or module prerequisites. Instructor credentials remain inside the fetcher, with course-scoped validation on initial and pagination URLs and redirects disabled.
2026-09-30 verification: ten local tests passed, plus read-only calls against course 94741 (8 visible assignments, 7 quizzes, 1 page, syllabus and representative details). The unpublished staff page was excluded from lists and direct reads. Production source and eight generated schemas were read back after deployment; grants and credential valves were preserved. Adam updated the Canvas-hosted prompt himself to replace the old jq instruction. New chats fetch that updated prompt; existing chats can retain the per-session cached version. A fresh-chat human playtest remains pending.
The 2.0.3 docstring follow-up is also deployed and readback-verified: quiz guidance distinguishes assessments from activity containers and surveys; syllabus guidance directs AI-policy discovery and conspicuous citations to the direct syllabus URL. Quiz question/content-item retrieval remains unimplemented; the quiz tool still returns only its description and general requirements.
Brace3 Drive (2026-09-30). brace3_drive_toolkit v0.2.0 is bound to
brace3-94741 with course-group tool read access. Seven gdrive_* tools read
Docs, Sheets and Slides, browse/search folders, identify the sharing account,
and view Doc images, rendered slides or standalone Drive images. One global admin valve,
GOOGLE_DRIVE_SERVICE_ACCOUNT_KEY_JSON, holds the shared Brace identity's key,
copied from the legacy toolkit. Authorized courses share the same Drive library;
course membership gates toolkit invocation, not file-level separation. UCSC-only
sharing does not grant this service account access. Source, schemas, credential,
grant and binding readbacks passed; 36 offline tests passed. Search requires a
nonempty folder and covers direct children only, reducing bulk discovery without
introducing course-level file isolation. A production folder
search now returns two Docs after removing orderBy from full-text queries:
Google requires relevance ordering and returns 403 for explicit sorting. Errors
no longer assume every 403 is a sharing denial. Adam confirmed the production
vision playtest works; dedicated non-admin verification remains pending. See
tools/brace3_drive_toolkit/README.md for setup, limits and evidence.
The v0.2.0 Drive deployment replaces the vision stub with bounded Doc-image, rendered-slide and standalone-image delivery. Live Google retrieval works for two lecture-note images and the supplied slide. Source and all seven schemas were read back with credentials, grants and model configuration preserved. Adam confirmed the OWUI vision playtest works. Independent provider-payload inspection and exported-transcript image rendering remain unverified.
Brace3 GitHub (2026-09-30). brace3_github_toolkit v0.2.0 is explicitly
bound to brace3-94741, alongside Canvas, with a course-group tool read grant.
Its eleven named read-only tools discover public user/org repositories and
inspect repository metadata, commits/files,
comparisons, Actions runs/jobs/logs, and distinct Pages build/deployment evidence.
The toolkit rereads the selected workspace model's meta.bayleaf_course_id
and binding, verifies course membership and model read access, then chooses a
PAT from the admin-only COURSE_GITHUB_CONFIG_JSON valve. Anonymous repository
visibility checks independently enforce public-only access, even with a broad
PAT. Credentials and signed log download URLs never enter tool results.
Course 94741's PAT has a 90-day lifetime, approximately through 2026-12-29;
replace it before later reuse. Source, schemas, grants, valves, and binding
readbacks passed, as did 30 local tests and direct public API smoke tests.
Repository metadata includes public GitHub-recorded fork parent/network root
and generating-template summaries. Template origin can support an assignment's
starter requirement; missing origin is inconclusive, not proof of noncompliance.
Adam confirmed production playtesting works as expected; non-admin authorization
and transcript export were not separately verified. See
tools/brace3_github_toolkit/README.md for boundaries and remaining checks.
| ID | Name | Access | Description |
|---|---|---|---|
help_toolkit |
Help | No grants (model-bound via toolIds on help) |
Group membership listing, model access listing, invite code acceptance/creation. Valve: INVITE_SIGNING_KEY (optional, falls back to WEBUI_SECRET_KEY). |
gws_toolkit |
Google Workspace | All users (user:*) |
Per-user, per-chat OAuth2 access to Google Workspace APIs (see below) |
Model-prompt transparency. BayLeaf Chat rejects the idea that someone can
converse with an agent but not know its system prompt. Help's
get_model_details returns the system prompt to anyone with read access
to that workspace model, even though OWUI's ordinary model API strips params
for read-only callers. This is intentional: BayLeaf's model definitions are
public on GitHub, and Help also makes non-sensitive live configuration
inspectable. The toolkit must still verify the caller's model read access
before returning live details; transparency is not permission to reveal
models the caller cannot access. A Canvas-generated prompt may be absent from
the static model record because the filter assembles it at request time.
Help and Brace3 bind tools through meta.toolIds. Brace3's Canvas filter
fetches the course system prompt, not tool bindings. On OWUI 0.11.4, model
binding does not bypass get_tools()'s access check: non-admin users also need
tool read grants, which can expose those tools in their other model pickers.
The toolkits enforce their own resource/access boundaries at invocation time.
The former stealth pattern injected body["tool_ids"] from a filter. Help
stopped using it in June 2026; the remaining Brace2 implementation was retired
on 2026-09-30. Historical source is linked in the retirement records above.
Per-user, per-chat OAuth2 integration with Google Workspace APIs. Source: rndmcnlly/gws-toolkit. Users connect their own Google account via an in-chat OAuth flow. Tokens are ephemeral (in-process memory, no DB persistence) and scoped to a single chat; every chat starts unauthorized and users consent to exactly the capabilities they need. Available to all users.
Tools exposed to the model:
| Tool | Purpose |
|---|---|
gws_authorize(capabilities) |
Request authorization for capabilities in the current chat, or inspect current status |
gws_action(action, params) |
Execute a Google Workspace action, gated by admin capabilities and per-chat authorization |
Actions (22 across 4 services, dispatched via gws_action):
| Action | Capability | Description |
|---|---|---|
drive.files.search |
drive.readonly |
Full-text search across Drive |
drive.files.get |
drive.readonly |
Read a file (exports Docs as markdown, Sheets as CSV, Slides as text) |
drive.files.list |
drive.readonly |
List folder contents |
gmail.messages.search |
gmail.readonly |
Search messages using Gmail syntax |
gmail.messages.get |
gmail.readonly |
Read a message (decodes MIME body) |
gmail.threads.list |
gmail.readonly |
Search threads |
gmail.threads.get |
gmail.readonly |
Read all messages in a thread |
gmail.drafts.create |
gmail.compose |
Create a draft (does NOT send) |
gmail.drafts.list |
gmail.readonly |
List drafts |
gmail.drafts.get |
gmail.readonly |
Read a specific draft |
calendar.calendars.list |
calendar.readonly |
List available calendars |
calendar.events.list |
calendar.readonly |
List/search events (defaults to upcoming) |
calendar.events.get |
calendar.readonly |
Full event details |
calendar.freebusy.query |
calendar.readonly |
Check free/busy status |
calendar.events.create |
calendar.events |
Create an event |
calendar.events.patch |
calendar.events |
Update specific fields of an event |
calendar.events.delete |
calendar.events |
Delete an event |
sheets.spreadsheets.get |
spreadsheets.readonly |
Spreadsheet metadata |
sheets.values.get |
spreadsheets.readonly |
Read a cell range |
sheets.values.batchGet |
spreadsheets.readonly |
Read multiple cell ranges |
sheets.values.update |
spreadsheets |
Write values to a cell range |
sheets.values.append |
spreadsheets |
Append rows to a detected table |
Design. The toolkit self-registers an OAuth callback route on the OWUI
FastAPI app at startup. Authorization uses OWUI event emitters (__event_call__)
to show a confirmation modal with the OAuth link; the user right-clicks to open
it in a new tab, completes Google consent, then confirms back in the chat.
Tokens live in-process keyed by (user_id, chat_id) and are lost on server
restart — this is by design. The enabled_capabilities valve sets an admin
ceiling; users can only authorize up to the admin-allowed maximum. The
gws_authorize response includes current UTC time so the LLM can ground
time-relative API parameters.
Capabilities (mirror Google OAuth scope suffixes):
| Capability | Description |
|---|---|
drive.readonly |
Search, read, list Drive files |
drive |
Full Drive access |
gmail.readonly |
Read Gmail messages and drafts |
gmail.compose |
Create and manage email drafts |
calendar.readonly |
View calendar events |
calendar.events |
Create, edit, and delete events |
spreadsheets.readonly |
Read Sheets data |
spreadsheets |
Read and write Sheets |
tasks.readonly |
View Google Tasks |
tasks |
Manage Google Tasks |
documents.readonly |
Read Docs content |
documents |
Read and write Docs |
presentations.readonly |
Read Slides content |
presentations |
Read and write Slides |
Drive, Gmail, Calendar, and Sheets have action handlers. Tasks, Docs, and Slides are scope-ready in the capability registry but have no handlers yet.
Admin valves (configured in OWUI admin panel, never committed):
google_client_id— Google OAuth client IDgoogle_client_secret— Google OAuth client secretbase_url— OWUI base URL for the OAuth callback (e.g.https://chat.bayleaf.dev)enabled_capabilities— Comma-separated capability ceiling (default:drive.readonly). Production read back 2026-11-21:drive.readonly,gmail.readonly,calendar.readonly,spreadsheets.readonly, so no GWS write channel (calendar invites, drafts) is live
Several tools require API keys configured as "valves" in the OWUI admin panel. These are never committed to this repo:
lathe:daytona_api_key,daytona_api_url,daytona_proxy_url,deployment_label,auto_stop_minutes,auto_archive_minutes,auto_delete_minutes,foreground_timeout_seconds,auto_create_sandbox,sandbox_missing_message,sandbox_create_overrides,preview_wrapper_url,preview_wrapper_key,preview_expiry_seconds,onboarding_instructions,handbook_urlgws_toolkit—google_client_id,google_client_secret,base_url,enabled_capabilitiesweb_context_toolkit—tavily_api_key,search_depth,include_answer,max_results,extract_depthhelp_toolkit—INVITE_SIGNING_KEY(optional; falls back toWEBUI_SECRET_KEYif empty)brace3_github_toolkit—COURSE_GITHUB_CONFIG_JSONbrace3_drive_toolkit—GOOGLE_DRIVE_SERVICE_ACCOUNT_KEY_JSONbrace3_canvas_system_prompt_filter—CANVAS_ACCESS_TOKEN(fetches the course system prompt)brace3_canvas_toolkit—CANVAS_ACCESS_TOKEN(independent tool-time Canvas access; currently duplicated from the filter valve)
Non-secret, non-default valve values (safe to record as recovery backup):
lathe:deployment_label=chat.bayleaf.dev,auto_delete_minutes=129600(90 days); built-in volume support removed in 1.0 (previously disabled here)
Functions are Python classes that intercept or augment the request/response
pipeline. Each is in functions/<id>/ with function.py and meta.json.
| ID | Type | Global | Active | Description |
|---|---|---|---|---|
rate_limit_filter |
filter | yes | yes | Per-user rate limiting (10/min, 100/hr, 1000/60hr sliding windows) |
basic_prompt_filter |
filter | no | yes | Assembles per-request system-prompt augmentations for the Basic model (OAuth role + chat-storage context); attached via Basic's filterIds. See issue #44. |
depth_limit_filter |
filter | no | no | Archived: divides max response tokens by user-turn count |
brace3_submit_action |
action | no | yes | Model-bound button to submit a structured Brace3 transcript to an HTML-upload assignment in course 94741. |
brace3_canvas_system_prompt_filter |
filter | no | yes | Fetches system prompt from Canvas page by title "Brace3 System Prompt" (Brace v3). Derives course ID from model ID (brace3-NNN). Raises on missing page. Valve: CANVAS_ACCESS_TOKEN. Toolkit bound separately on the model. |
The only globally active filter. Applies to all models and all users (including admins). Live valves verified 2026-10-27 (these override source defaults):
- 10 requests per minute
- 100 requests per hour
- 1000 requests per 60-hour sliding window (
sliding_window_minutes=3600)
global_limit=true pools each user's requests across models; it is not a shared
campus-wide quota. enabled_for_admins=true, priority 0. The inlet checks all
three rolling windows before recording an admitted request. Rejections raise a
wait-time error and do not consume another request; downstream failures still
count. This counts filter inlet invocations, not tokens or dollars.
In v0.12.4, ordinary native tool-loop continuations run the separate request
filter hook, not inlet (utils/middleware.py). This filter defines only
inlet, so an initial chat request plus ten internal continuation completions
normally consumes one quota unit, not eleven. Builtin code-interpreter
continuations use the same request hook. A separately submitted HTTP request
(for example a resume) can enter inlet again; this is not a strict count of
human-authored messages. Verified by tracing the pinned upstream release, not
by generating a production tool loop.
Counters are in process-local memory, not shared or durable storage. Restarts reset them, multiple processes can enforce separate quotas, and check/record is not atomic. Treat this as a soft usage guard, not strict budget enforcement.
Before tuning thresholds, use the read-only
request-rate analysis playbook
and analysis/request_rates.py to compare retained-message rate distributions
against live valves. Saved messages are a submission proxy, not admission logs.
Disabled and removed from global execution on 2026-10-27 after enabling native
context compaction (see global admin settings above). No saved workspace model
binds it. Source and live valves are preserved for rollback; rate limiting is
unchanged. When active, it divides an initial_token_budget (default 16384) by
the number of user turns, making responses progressively shorter in long
conversations. Compaction bounds input context, not total inference cost.
Skills are markdown documents (Workspace → Skills). In OWUI v0.11.4, the
model can discover available skills by name and description and load their
full text when needed, even if the user did not explicitly select a skill.
Access is controlled by access_grants — the same mechanism as models and
tools; inactive skills are not available for discovery. BayLeaf uses skills
for platform feature hints and has inactive role-specific guidance scoped to
OAuth groups corresponding to campus affiliations.
Manage via owui-cli skills or the admin API at /api/v1/skills/.
| ID | Active | Access | Description |
|---|---|---|---|
web-search |
yes | all users (user:*) |
Describes the Web Context toolkit (Tavily-backed search and page extraction) and how to enable it. |
code-sandbox |
yes | 1 group | Points to the Lathe coding agent toolkit and Daytona sandboxes; tells users to enable the Code Sandbox toolkit. |
google-workspace |
yes | 1 group (same group as code-sandbox) |
Points to the Google Workspace toolkit (gws_toolkit): how to enable the integration and complete the per-service OAuth consent flow. |
canvas-api |
yes | 1 group | Guides agents using the Canvas LMS API via the Code Sandbox toolkit's CANVAS_ACCESS_TOKEN env var; includes canvaslms CLI usage, REST API pointer, data hygiene rules, and escalation to a desktop agent for complex tasks. |
offramp |
yes | all users (user:*) |
Exit-path guidance for users outgrowing Chat or wanting stronger privacy: local harnesses (OpenChamber + BayLeaf API), individual ZDR subscriptions, confidential inference (Tinfoil), local inference. Frames leaving BayLeaf Chat as a legitimate use of BayLeaf Chat. |
bayleaf-for-students |
no | 1 group (Student@ucsc.edu) |
Instructs the agent to prioritize learning, build writing literacy, and points to the learning-opportunities skill package. |
bayleaf-for-employees |
no | 1 group (Employee@ucsc.edu) |
Placeholder — acknowledges employee role, no special instructions yet. |
bayleaf-for-faculty |
no | 0 grants (owner-only) | Suggests AI integration paths for research and teaching; mentions Canvas LMS and BayLeaf as a campus-scoped alternative to commercial tools. |
The bayleaf-for-* skills implement a lightweight skill system: each skill is
granted read access to the OAuth-managed group that corresponds to the
relevant eduPerson affiliation (e.g. Student@ucsc.edu,
Employee@ucsc.edu). When active, a skill granted to that affiliation can be
discovered and loaded by the model without requiring a separate workspace model
per role.
bayleaf-for-faculty currently has no grants (owner-only) — it is visible
only to admins while its content is being refined.
All three bayleaf-for-* skills are currently deactivated in prod
(is_active: false). Their grants and content are preserved for a fast
restore. Role-scoped context for Basic now comes from
basic_prompt_filter's per-request augmentations instead (see §4).
To reconstruct BayLeaf Chat from this backup:
-
Create DO App Platform app with a single service using the qualified repo-root
chat/image/Dockerfilebuild and guarded startup command from §1, with repository-push auto-deploy disabled. Attach a managed PG 17 database and configure S3 storage via DO Spaces. Set all env vars from the table in §1 and the complete linked telemetry environment. Do not enable telemetry until its collector/capability/retention and connection-headroom gates are verified. An upstream-image recovery must keep all four OTel enable flags false. -
Configure OpenRouter in the OWUI admin panel (Admin → Settings → Connections) with a ZDR-eligible OpenRouter API key.
-
Import models — The model JSON files in
models/match the OWUI import format. Use the admin APIPOST /api/v1/models/importor recreate them manually in the Workspace → Models UI. -
Import tools — For each tool in
tools/, create a new tool in the admin UI (Workspace → Tools), paste the source fromtool.py, and configure the access grants and valves permeta.json.brace3_canvas_toolkithas a course-group read grant. Configure its ownCANVAS_ACCESS_TOKENvalve for tool-time Canvas reads; do not rely on the filter's separate prompt-fetch token valve. -
Import functions — Same process via Workspace → Functions. Set
is_globalandis_activeflags permeta.json. Configure function valves (Canvas tokens etc.) in the admin panel.For
brace3_canvas_system_prompt_filter: setCANVAS_ACCESS_TOKENin the filter's valve for dynamic prompt fetching. Attach to a model with IDbrace3-NNN, whereNNNis the Canvas course ID, and set the toolkit's token valve separately. -
Configure model bindings — Attach tools, filters, and actions to models per the
toolIds,filterIds, andactionIdsin eachmodel.json. -
Set access grants — Configure group-based access for restricted models and tools. Group UUIDs will differ in a new deployment; map by group name.
Public-backup privacy boundary: models/ preserves model configuration and
grant references, not course rosters, group records, membership lists, user
accounts, or chats. Never add roster files or a groups/users export to this
public repo. To recover a course group on a fresh deployment, obtain a current
roster from the authorized instructor, recreate course:<Canvas ID>, provision
accounts/memberships as in §1b, and grant the new group UUID access to the
restored model. The old grant UUID in model.json is not portable. Canvas
credential valves are also intentionally absent from this backup and must be
restored through an authorized private channel.
In the first-ever recovery exercise of BayLeaf Chat's storage layer, two independent bugs were found and fixed in the same session. Documented here so the next operator (or agent) can recognise the failure modes quickly.
- All file attachments in chats returned HTTP 400
{"detail": "[ERROR: Error getting file content]"}fromGET /api/v1/files/{id}/content. - One post-migration file retrieved 200 early in the debugging session but 404 later — a red herring that turned out to be the OWUI local cache warming from upload-time bytes, then getting wiped on redeploy.
The app spec had S3_ENDPOINT_URL=https://bayleaf-ucsc-storage.sfo2.digitaloceanspaces.com,
i.e. the bucket name in the hostname. Combined with S3_BUCKET_NAME=bayleaf-ucsc-storage
and boto3's default path-style addressing, every request path was
https://bayleaf-ucsc-storage.sfo2.digitaloceanspaces.com/bayleaf-ucsc-storage/<key> —
DigitalOcean saw the bucket in the hostname AND as the first path segment, so
uploads landed at key bayleaf-ucsc-storage/<real-key> and retrievals looked
up the same doubly-prefixed key. Upstream OWUI _extract_s3_key stripped the
first path segment, making the key round-trip correctly in principle, but the
physical storage layout was inconsistent with what the rest of the system
assumed.
Fix: endpoint URL changed to https://sfo2.digitaloceanspaces.com (region
endpoint, path-style). Verified with a boto3 repro that constructed both URL
forms and HEAD'd the same key against both.
The 2026-04-29 bucket rename from bayleaf-chat-space → bayleaf-ucsc-storage
copied 273 objects server-side (preserving them under a bayleaf-chat-space/
key prefix inside the new bucket) but did not update the file.path column in
the managed PostgreSQL database. 224 DB rows continued to point at
s3://bayleaf-chat-space/....
Fix: collapsed all 274 objects (273 migrated + 1 post-migration stray) to the
bucket root via server-side copy_object, then rewrote all 225 file-table rows
to the flat form s3://bayleaf-ucsc-storage/<uuid>_<filename>, then deleted
the prefixed sources. Idempotent, transactional on the DB side, verified
end-to-end with upload/retrieve/delete smoke test.
Either bug alone would have been easy to isolate. Together, they produced confusing signals:
- The one post-migration file "worked" earlier in the session (local cache, see above) but "didn't work" later, making it unclear whether bug 2 was active or resolved.
- Rewriting a single DB row's path as a canary didn't fix retrieval, because bug 1 would have caused a 404 regardless.
- The canary evidence suggested the path rewrite theory was wrong; only constructing the actual request URLs against DO Spaces (outside boto3) revealed bug 1.
The diagnostic path that worked: tail the running container's logs during a
failed retrieval, see the raw (404) when calling the HeadObject operation
from boto3, inspect the deployed provider.py source to confirm
_extract_s3_key behavior, then independently construct path-style vs.
virtual-hosted-style requests to see which DigitalOcean responds to.
During reconciliation, 49 objects in the bucket had no matching file row
(true S3-level orphans from pre-migration deleted chats) and 112 file rows
had no surviving chat/KB reference (true DB-level orphans). Both classes were
cleaned up during this session's post-migration pass, and an automated orphan
sweep (§5 of RETENTION.md) now runs daily to keep the bucket and DB in sync
going forward.
For any future bucket migration:
- Migrations must update DB references in the same transactional scope as object copies, or at minimum in the same runbook step. Decoupling the two is how bug 2 happened.
- Storage config should be validated against physical layout after any change. A simple smoke test (upload a file, retrieve it, check the object key in the bucket matches the DB path) catches bug 1 immediately.
S3_ENDPOINT_URLfor DigitalOcean Spaces should always be the region endpoint (https://<region>.digitaloceanspaces.com), never a bucket-hostname endpoint. Bucket goes in theS3_BUCKET_NAMEenv var; the endpoint stays generic. DO's documentation shows both forms and does not warn that using both together causes double-prefixing.
This directory is the source of truth for model system prompts, tool source code, and function source code. Changes flow in two directions.
owui-cli is a purpose-built CLI
for the OWUI admin API. Install via uvx owui-cli.
export OWUI_URL=https://chat.bayleaf.dev # target instance
export OWUI_TOKEN=<bearer-token> # admin JWT
owui-cli tools list # list all tools
owui-cli tools pull <id> # dump tool source to stdout
owui-cli tools deploy <source.py> [id] # push tool source to live
owui-cli functions pull <id> # dump function source to stdout
owui-cli functions deploy <source.py> # push function source to live
owui-cli --json models show <id> # full model JSON
owui-cli models update <model.json> # push model config to live
owui-cli users find <query> # search users
owui-cli groups add-user <id> <user-id> # add user to group
owui-cli schema # explore the full OWUI API surfaceRun owui-cli with no arguments for the full command listing.
owui-cli reads OWUI_URL and OWUI_TOKEN from the environment. Tokens
are JWTs that expire; refresh by copying a fresh token from
localStorage.getItem("token") in the browser console.
probe.bayleaf.dev/chat/basic is a separate Cloudflare Worker for UptimeRobot
Free, not a public service or metrics store. Source and operational instructions:
probe/README.md. It submits a fixed opening prompt through
Basic as a dedicated non-admin user, consumes the complete HTTP stream, then
returns a status code. Both GET and HEAD withhold headers until completion.
The deployed HTTP layer retains no prompt or answer and creates no saved
conversation. It does not test browser rendering, Socket.IO, campus login, or
saved-chat persistence. A browser layer at /chat/basic/e2e was deployed and
qualified on 2026-09-08 with both Worker and browser running in Cloudflare.
It lives in the same Worker, verifies rendering and persistence, then
deletes its marked synthetic chat. Session injection still skips campus login.
The deployed /openrouter/basic route runs in this same Worker, using an
inference-only OpenRouter secret, fixed z-ai/glm-5.3-flash, and enforced
provider.zdr: true. It omits Basic's system prompt and injected context, so
independent request differences are not pure OWUI overhead. Metrics v2 returns
authenticated GET JSON and HEAD timing headers for all three layers, including
admission failures. Sequential awaited durations and overlapping event offsets
are separate; browser close and exact-chat cleanup are measured independently.
All three routes passed authenticated GET/HEAD and anonymous 401 checks in
production. Independent observation verified both synthetic browser chats were
deleted. Browser work has a 55-second deadline plus bounded close/cleanup;
HTTP routes retain 25 seconds. See the probe README for version, measurements,
and exact semantics. No new monitor was created.
A fourth /api/recommended layer for keyed BayLeaf API inference was deployed
and qualified on 2026-09-09 UTC. It uses a separate sk-bayleaf- credential for
the same probe@bayleaf.dev pseudo-user and the checked-in namespaced API
recommendation, exercising D1 auth resolution, per-user upstream credential
handling, open-weight enforcement, explicit ZDR routing, and complete SSE
consumption. Its OpenRouter key is capped at $1/day. Adam created its
UptimeRobot monitor manually at a 15-minute interval before deployment; initial
green samples and alert delivery remain to be verified. See the probe playbook
and README.
A Sealed backend HTTP check at /api/sealed is deployed and production-qualified
(2026-10-07), with UptimeRobot setup confirmed by Adam and public inclusion
observed; alert delivery remains unverified. It uses the dedicated BayLeaf probe identity,
verifies fresh Tinfoil attestation, encrypts a fixed GLM 5.3 request through the
relay, then decrypts and validates the complete SSE answer. No Chat/browser
dependency. See probe/README.md for boundaries and deployment/monitor gates.
A passive /api/sandbox existence check was deployed and GET/HEAD-qualified on
2026-10-27 Pacific. It reuses the dedicated BayLeaf API credential, never wakes
compute or refreshes activity, and accepts any existing non-deleting sandbox
regardless of runtime health. The exact probe owner is exempt from the API's
90-day sandbox reaper. UptimeRobot monitor 804453127 uses hourly HEAD checks
and a 30-second timeout; public BayLeaf Status inclusion was observed. No new
telemetry export vocabulary; alert delivery remains unverified. See the probe README.
API keys were enabled for this on 2026-09-07. Ordinary default permissions and
existing group permissions remain unchanged; only the dedicated operational
group received features.api_keys. An instance-wide API-key endpoint allowlist
permits only /api/chat/completions. Session JWTs are unaffected. The Worker
holds the dedicated account's API key and its ordinary monitoring
session JWT for the browser layer, never an admin credential or JWT-signing
secret. API-key expiry is not enforced by OWUI 0.11.3; explicitly revoke/rotate
when required. The deployed session expires 2026-10-08 at 19:38:04 UTC;
manual renewal is required, with no automatic renewal scheduled.
The existing UptimeRobot monitor remains the basic reachability check. The new transaction monitor is configured manually by Adam; verify its first samples and alert delivery before treating setup as complete.
owui-cli tools pull lathe > chat/tools/lathe/tool.py
owui-cli functions pull rate_limit_filter > chat/functions/rate_limit_filter/function.py
owui-cli --json models show basic > chat/models/basic/model.jsonThen git diff chat/ to review changes.
owui-cli tools pull-all chat/tools/
owui-cli functions pull-all chat/functions/
owui-cli skills pull-all chat/skills/
owui-cli models pull-all chat/models/Each pull-all command writes <dir>/<id>/source + <dir>/<id>/meta.json.
Models pull-all filters to workspace models only (those with a
base_model_id), discovers all models dynamically, and extracts base64
data-URI profile images into separate files. Then git diff chat/ to review.
Global admin settings are not included in these four resource pulls. After
admin-side changes, also capture owui-cli --json configs show and
owui-cli --json configs admin in private, mode-restricted storage outside the
repository. Full exports may contain credentials. Compare with an earlier
private snapshot when available, and document only reviewed non-secret values
here. See the backup-reconcile playbook for the public-backup boundary.
owui-cli tools deploy chat/tools/lathe/tool.py lathe
owui-cli functions deploy chat/functions/rate_limit_filter/function.py rate_limit_filter
owui-cli models update chat/models/basic/model.jsonAlternatively, edit items manually in the OWUI admin UI (Admin Panel → Workspace → Models / Tools / Functions).
The authoritative route definitions live in the Open WebUI repo:
backend/open_webui/routers/models.pybackend/open_webui/routers/tools.pybackend/open_webui/routers/functions.py
owui-cli schema and owui-cli schema <resource> can also be used to
explore the API surface directly.
chat/
├── DESIGN.md # This file
├── models/
│ ├── basic/
│ │ ├── model.json # Params, meta, system prompt, capabilities
│ │ └── profile.png # Model avatar
│ ├── help/
│ │ ├── model.json
│ │ └── profile.png
├── archive/
│ ├── brace2-retirement.md # Historical source links and retirement evidence
│ └── gambit-system-prompt.md # Preserved pre-agentic rapid-prototyping prompt
├── analysis/
│ └── clio-gist/ # Privacy-preserving aggregate Chat-use analysis pipeline
├── skills/ # One dir per skill: skill.md + meta.json
│ ├── web-search/ # Active — all users
│ ├── code-sandbox/ # Active — 1 group
│ ├── google-workspace/ # Active — 1 group
│ ├── canvas-api/ # Active — 1 group
│ ├── offramp/ # Active — all users
│ ├── bayleaf-for-students/ # Inactive — 1 group (Student@ucsc.edu)
│ ├── bayleaf-for-employees/ # Inactive — 1 group (Employee@ucsc.edu)
│ └── bayleaf-for-faculty/ # Inactive — owner-only
├── tools/
│ ├── lathe/
│ │ ├── tool.py # Code Sandbox — coding agent tools (Daytona sandboxes)
│ │ └── meta.json
│ ├── help_toolkit/ # Bound to Help model via toolIds (no grants)
│ │ ├── tool.py
│ │ └── meta.json
│ ├── web_context_toolkit/
│ │ ├── tool.py
│ │ └── meta.json
│ ├── gws_toolkit/
│ │ ├── tool.py # Google Workspace — per-user, per-chat OAuth2 (Drive, Gmail, Calendar, Sheets)
│ │ └── meta.json
│ ├── brace3_drive_toolkit/ # Shared Drive identity, folder-scoped search
│ ├── brace3_github_toolkit/ # Public GitHub reads, course credentials
│ ├── brace3_canvas_toolkit/ # Brace v3 — Canvas read-only, model-bound with own token valve
│ │ ├── tool.py
│ │ └── meta.json
│ ├── campus_directory_toolkit/
│ │ ├── tool.py
│ │ └── meta.json
│ └── whole_document_retrieval/
│ ├── tool.py
│ └── meta.json
└── functions/
├── rate_limit_filter/
│ ├── function.py
│ └── meta.json
├── depth_limit_filter/
│ ├── function.py
│ └── meta.json
├── basic_prompt_filter/ # Basic model prompt augmentations (active)
│ ├── function.py
│ └── meta.json
├── brace3_submit_action/ # Brace v3 structured Canvas transcript submission
│ ├── function.py
│ └── meta.json
├── brace3_canvas_system_prompt_filter/ # Brace v3 — Canvas-sourced prompt
│ ├── function.py
│ └── meta.json
└── vertex_pipe/ # Disabled — Google Vertex manifold pipe
├── function.py
└── meta.json