- Go 78.6%
- JavaScript 19.3%
- templ 1.4%
- CSS 0.7%
| internal | ||
| providers | ||
| .gitignore | ||
| go.mod | ||
| go.sum | ||
| LICENSE | ||
| main.go | ||
| README.md | ||
gorunit
gorunit is a small Go LLM application with an embedded web chat UI and an OpenAI-compatible API for Open WebUI.
Features
- A single Go binary serves the templ-rendered UI and API, with locally embedded HTMX; no Node.js required.
- OpenAI-compatible model backends, including OpenAI and local tool-capable Ollama models, plus ChatGPT subscription access through Codex.
- A bounded agent loop: the model requests a tool, the runner executes it, and the result goes back to the model until it produces an answer.
- Arithmetic, scheduling, permission-scoped file tools, operator-enabled sandboxed command execution, and an optional public web-fetch tool. Commands and web fetch are disabled by default.
- Persistent directory grants with independent Read and Write permissions, managed in Settings; filesystem access is denied by default.
- File tools run in short-lived OS-sandboxed subprocesses: Linux Landlock or macOS Seatbelt. Unsupported sandbox configurations fail closed.
- Persistent scheduled tasks, created in the UI or by asking the chat agent, with one-time and cron-style repeats.
- Bearer-token authentication, request deadlines, cancellation, body/response size limits, and a maximum of eight concurrent agent requests.
- Persistent UI chat transcripts and stateless
/v1conversations. Runner API keys stay in browser memory.
Quick start
Requires Go 1.25+ and a tool-capable OpenAI-compatible backend or a ChatGPT subscription with Codex access.
OpenAI
export LLM_API_KEY='your-openai-key'
# Defaults: LLM_BASE_URL=https://api.openai.com/v1, LLM_MODEL=gpt-4o-mini
# Recommended even on localhost; this is separate from your backend key.
export AGENT_API_KEY='choose-a-runner-token'
go run .
Open http://127.0.0.1:8080, enter the runner token and select a provider/model in Settings, then open Main chat and try What is (145 + 27) * 8 / 4?.
The web UI offers OpenAI, Ollama, and Codex. Its model dropdown loads the selected provider's live catalog (/models for OpenAI-compatible backends and Codex's authenticated model catalog). Use Refresh models after installing an Ollama model or updating credentials. Models listed by a provider are not necessarily tool-capable; choose one that supports tool calls. Discovery failures leave sending disabled and show an error.
LLM_PROVIDER selects the startup default, and LLM_BASE_URL, LLM_MODEL, and LLM_API_KEY apply only to that provider. The other UI choices use the standard OpenAI, local Ollama, and Codex endpoints. When OpenAI is not the startup provider, set OPENAI_API_KEY for its UI choice; custom backend keys are never reused for another provider. Codex uses its CLI login. Existing Ollama configurations using LLM_PROVIDER=openai still work, but appear under the OpenAI choice; use LLM_PROVIDER=ollama to label it explicitly.
UI selections are per request/tab and do not change the /v1 API's configured default or public alias. Switching providers retains the conversation; use New chat first if you do not want to send existing history to a different provider.
Local sandbox shell
Run gorunit shell from your own terminal to configure credentials or tools without putting secrets in a chat prompt:
gorunit shell
# Reuse a systemd instance or the installed macOS LaunchAgent:
gorunit shell --service auto
# Select a specific systemd instance if both are running:
gorunit shell --service user
# Or select a workspace and a different shell explicitly:
gorunit shell --directory-id YOUR_GRANT_ID --path . --shell /bin/bash
Without --service, the CLI uses its local configuration environment (SETTINGS_FILE and FILE_PERMISSIONS_FILE overrides are supported). With --service auto|system|user, it instead reuses the instance's saved settings, directory grants, persistent command home and sandbox defaults; the selected instance's configuration takes precedence over your terminal's configuration environment. On Linux this reads the running systemd service's effective environment and delegated cgroup, including environment-file overrides; the service must remain running for the session. auto selects the only accessible running instance and rejects ambiguity. On macOS, auto and user read the installed ~/Library/LaunchAgents/io.gorunit.agent.plist (reload the agent after changing it to keep the running instance in sync). No service credentials are imported, and the command does not start services, change OS identity or bypass filesystem/cgroup permissions. Run it as the service's OS account, or with appropriate privileges for a system service. Commands must be enabled and at least one directory grant must have Read permission. It selects the grant containing your current directory (the most specific one if nested), or the only readable grant; otherwise pass --directory-id. The shell starts at that grant's root unless --path selects a grant-relative subdirectory. Linux still exposes the workspace at /workspace/<directory_id>.
The shell has a dedicated pseudo-terminal, supports interactive password prompts, terminal resizing and Ctrl-C, and exits with exit or Ctrl-D. Input and output connect directly to your terminal: no LLM/backend is initialized and no chat/tool transcript is created. Host environment variables, API keys, shell configuration and SSH agents are not inherited. The default executable is /bin/sh; --shell must name a permitted executable available inside the sandbox. Shell history is disabled via HISTFILE=/dev/null by default, but programs or shell startup files may still save their own history/logs.
HOME is the normal persistent private command home: logins and configuration stored there survive the session and are available to later sandboxed commands. This avoids sending credentials through the LLM, but does not hide saved credentials from commands the agent subsequently runs. Do not print secrets into later tool output or store them in granted project files or project guidance. Your terminal/OS may also retain scrollback or session recordings.
Normal sandbox restrictions remain in force: only the selected workspace grant, configured runtime paths, persistent command home and temporary storage are accessible; workspace writes follow its Write permission. Networking, when enabled, remains proxy-only and respects the allowed-host policy. Local browser/callback login flows and tools requiring direct networking may not work; prefer supported device-code/token flows. Existing resource limits and command timeouts apply, including the default 30-second session limit. --timeout SECONDS can choose a shorter limit; increase the configured maximum in Settings for longer setup sessions. Linux requires access to the configured delegated cgroup; the CLI does not create or bypass delegation. macOS requires a cgo-enabled build, and its existing detached-descendant cleanup limitations still apply.
Voice mode
In Main chat, select a provider/model, then click Start voice mode and accept the privacy notice and microphone permission. Speech configuration is independent of the selected tool-capable chat model. Providers without configured speech use browser speech services. Typed chat remains available.
Codex subscription realtime voice agent
Codex voice reuses the file-backed ChatGPT login from codex login, exactly like Codex chat. No OpenAI API key is required. Open Settings → Codex realtime voice agent, uncheck Inherit server environment configuration, then click Load / refresh voice options. Choose a realtime model and voice from the dropdowns, or enter custom IDs directly. The provider-default voice option clears the explicit voice ID (blank uses cove). Choose which speech directions use the provider, then click Save settings. Settings are persisted on the server and apply to new voice sessions without a server restart. Stop and restart an already-running voice session to use the new selection. Uncheck both provider directions to force browser-only speech, even when environment variables are set.
The authenticated speech-options endpoint (GET /api/voice/catalog?provider=codex) currently returns the official Codex CLI's bundled V3/frameless catalog: the known model gpt-live-1-codex and 25 supported voices, including cove, juniper, maple, and breeze. The UI explicitly labels these as known choices, not a live account-availability check or complete model inventory; subscription access is determined when a call starts. Ordinary text models and API-key/V2-only voices are not mixed into this list. Refresh reloads the server's catalog and never replaces saved/manual IDs. Catalog loading failures leave manual entry usable.
Alternatively, leave Inherit server environment configuration checked (the default for existing installations) and configure speech before starting gorunit:
export CODEX_VOICE_MODEL='gpt-live-1-codex'
# Optional; the default is cove.
export CODEX_SPEECH_VOICE='cove'
The model above is the official Codex CLI's frameless realtime default. The implementation follows its call creation, frameless session/delegation protocol, and subscription sideband authentication. Availability depends on the account and OpenAI's rollout. This integration uses the CLI's subscription WebRTC call-creation route and its authenticated server-side sideband connection, not the public API-key transcription or speech endpoints. The subscription bearer token and account ID never leave the server. Reverse proxies must allow same-origin WebSocket upgrades at /api/voice/session; the browser also needs WebRTC media connectivity to the provider. Configured provider failures stop voice with an error; they do not silently send audio to another speech service.
The realtime voice agent manages a persistent spoken conversation. It delegates actionable requests to the selected chat agent, which runs through the same saved-chat, tool, sandbox, permission, and approval paths as typed chat. Final results are returned to the voice agent as delegation context, not as new user queries, so it can explain them aloud without repeating tool execution. Native realtime input can continue while the background agent works; additional delegations queue (up to eight) rather than interrupt or duplicate the running task. Switching to a different chat model does not change the separately configured speech model.
For independent browser fallback, uncheck the corresponding provider direction in Settings. When inheriting environment configuration instead, leave CODEX_VOICE_MODEL unset and configure either or both directions:
export CODEX_SPEECH_TO_TEXT_MODEL='gpt-live-1-codex'
export CODEX_TEXT_TO_SPEECH_MODEL='gpt-live-1-codex'
An unconfigured input direction uses browser recognition and forwards recognized utterances to the realtime agent. An unconfigured output direction uses browser synthesis for the realtime agent's spoken transcript. These are realtime-agent model selections, not standalone transcription/TTS model names; when both directions are configured they must name the same realtime model because they share one session. CODEX_VOICE_MODEL supplies the default for both direction variables. With no speech models configured, the original browser-only transcribe → chat → read-aloud flow is used. OpenAI-compatible and Ollama providers currently use that browser-only fallback.
Browser support, privacy, and lifecycle
Voice requires HTTPS or localhost. Provider voice uses WebRTC; each unconfigured direction additionally requires that browser's corresponding Web Speech API. Browser recognition support varies; try current Chrome if it is unavailable. If automatic audio playback is blocked, tap Read answer aloud below the voice status. A playback retry does not resubmit a task. Browser synthesis pauses recognition/microphone input to avoid transcribing its own voice; native provider audio uses the realtime conversation's turn handling and browser echo cancellation.
Privacy and history: provider voice sends microphone media to the configured provider; browser recognition and some browser synthesis voices may use remote vendor services. This is not guaranteed offline processing. Gorunit does not store raw audio. Delegated user requests, tool activity, and background-agent results are saved through the normal chat flow. Voice-only conversation and spoken summaries are transient and are not archived or restored on reconnect. The voice agent starts without existing chat history; the background agent retains the saved conversation. Speech-session usage is not currently included in per-turn chat billing. Sessions have a 30-minute lifetime and a maximum of eight concurrent connections.
Click Stop voice mode to release the microphone, media peer, and control connection; already accepted chat work continues. Use the chat's Stop button to cancel that work. Voice also stops on draft edits, chat/provider/model changes, navigation, tab hiding, sign-out, or recognition/chat/connection errors. It never overwrites a draft or automatically retries a failed task. After a disconnect, inspect saved history before restarting; no voice tasks or audio sessions are replayed automatically. Voice is opt-in per session and is not restored on reload.
Saved chats
UI chats are saved automatically. Use Past chats in the sidebar to select a previous conversation, or Open / reload chat to reload the selected one. The list is ordered by latest activity. New chat starts a separate session without deleting earlier conversations. Resume restores the saved provider/model; switching providers in Settings sends the conversation to that newly selected backend.
Like Codeit, the archive keeps system/user/assistant/tool messages, tool-call IDs and arguments, tool results, and reasoning supplied by the backend. Assistant tool batches and individual tool results are checkpointed during execution, not just at the end. Tool calls, results, system instructions, and reasoning use collapsed <details> in the UI. Expand them to inspect their contents. Codex encrypted continuation data is preserved for resuming, but encrypted or unexposed reasoning cannot be turned into readable text; only provider-returned summaries/text can be shown.
Each chat is an atomic JSON file under CHAT_DIR (default chats/). New directories use mode 0700, files 0600. Protect this directory and backups: archives include complete prompts, outputs, tool arguments/results, and reasoning. Chats are shared with everyone who has the runner token (or everyone who can reach the listener if authentication is disabled). Use one runner process per chat directory. The /v1 compatibility API remains stateless and does not save its requests as UI sessions.
Once a UI message has been accepted and saved, closing the tab/browser, refreshing the page, or losing the connection does not cancel the agent. It continues in the background while the gorunit process remains running, subject to the usual timeout, round limits, and permissions. Use Past chats to reopen it, then Open / reload chat (or Reload latest state) to see saved progress and the final response. Reopening or reloading a running chat automatically reattaches its live stream: it catches up on missed answer text, readable reasoning, tool-call arguments/results, and billing updates, then follows new events through completion. Reattachment is read-only; it does not start another run or repeat tools, and your next-message draft is preserved when using Reload latest state. Stop explicitly requests server-side cancellation; disconnecting alone does not. Server shutdown/restart can still interrupt a run, and interrupted runs are not automatically replayed.
Concurrent writes to the same chat are rejected using revision checks; reload a stale chat before resuming it. After a stop/disconnect, use Refresh chats, then reopen the saved session to recover the latest server state. Interrupted tool calls are closed with an explicit unknown-result marker, never automatically re-executed: side effects may already have happened. Failed/partial turns remain in the archive. Files are limited to 32 MiB; oversized chats fail explicitly rather than silently dropping history. Context management reduces model input automatically, but does not shrink the archive; start a new chat if the archive limit is reached. Chats from before this feature were browser-memory-only and cannot be recovered after their tab was closed.
Authenticated history endpoints: GET /api/chats lists metadata; GET /ui/chats/{id} returns the escaped transcript and resume fields for the UI; GET /ui/chats/{id}/stream replays and follows the current run (or returns the final snapshot if it already finished); GET /api/chats/{id}/progress reports status/activity; POST /api/chats/{id}/stop requests cancellation (also harmless for an already-finished chat). UI turns send only a chat ID, revision, prompt, and backend selection; client-supplied tool/reasoning history is not trusted.
Run a scheduled task now
In Scheduled tasks, use Run now on a task card to queue an immediate extra run with the task's saved prompt, backend, permissions, cost cap, and other settings. It uses the normal scheduled-task execution path, including security review and usage history. Future scheduled occurrences are preserved, including a one-time task's future run; completed tasks can also be run again. If a scheduled occurrence is already due, the immediate run satisfies that occurrence rather than running it twice.
The authenticated API equivalent is POST /api/tasks/{id}/run (no body required). It returns 202 with {"queued":true} after the request is saved and the scheduler is signaled; execution continues independently of the HTTP request. Queued requests survive a restart, but runs interrupted after starting are not replayed automatically. Already queued, running, or waiting-for-input tasks return 409; unknown IDs return 404. The UI disables Run now while a task is queued, running, or waiting for input.
Cost and usage per run
The chat cost line shows cumulative USD spend or observed Codex subscription consumption, input/output tokens, and cache-hit rate. Open Run usage history in a saved chat to inspect each turn separately, or expand the same section on a scheduled task card to compare individual runs. The latest 100 compact accounting records are retained per chat/task, including failed and interrupted runs; chat totals still cover the entire saved conversation. Accounting is checkpointed during execution and includes context compaction and independent security-review requests, not just the visible answer.
USD amounts use provider-reported charges; missing prices are unknown, never inferred to be free. Codex consumption is reported in percentage points of its primary and secondary subscription windows, not dollars. These are account observations and may include concurrent activity outside this run; resets or unavailable observations make consumption incomplete.
Cache-hit rate is cached input tokens / input tokens across requests that actually report cache counts (OpenAI-compatible prompt_tokens_details.cached_tokens, prompt_cache_hit_tokens, or Codex input_tokens_details.cached_tokens). It is token-weighted, not an average of request percentages. Missing cache metrics show unavailable, and incomplete coverage is labeled partial coverage. Cached tokens are included in input tokens, not added to them. Older archives retain their known cost but cannot reconstruct missing token metrics or earlier per-run history. Task history is removed when its task is deleted.
Working directories and project guidance
Chats and tasks have an optional Working directory field: a clean absolute host path inside an existing Read directory grant (for example /home/user/project/subdir). It does not grant new access or change the server's process directory. UI chats save it with each accepted turn and restore it on reload; New chat clears it. Task creation and each saved task card expose the same setting. Running tasks cannot be edited. Blank disables autoloading and retains the previous grant-root command default.
At the start of each run, gorunit reloads AGENTS.md and CLAUDE.md from the containing grant's root, then each directory down to the selected working directory. It reads neither parent directories above the grant nor unrelated descendants; changing directories during a run does not trigger another scan. Both filenames are case-sensitive. More-specific guidance takes precedence, with CLAUDE.md after AGENTS.md in each directory. Project guidance cannot override user requests, system policy, permissions, or approval requirements. Loading these files does not authorize commands or writes.
Reads use the existing OS-sandboxed file worker and current grants, including per-task Read restrictions. The selected directory must exist and contain no symlink components beneath its grant. Missing guidance files are ignored; symlink/special, unreadable, non-UTF-8, and oversized files are skipped with warnings included in context. Limits are 32 directory levels, 64 KiB per file, and 256 KiB total file contents. An invalid/revoked directory or unavailable file sandbox fails the run closed. File contents and source paths are included in the model's context and saved UI system-message snapshot, so do not place secrets in these files. Permission revocation does not erase previously archived or provider-visible content.
Commands with an omitted path default to the selected working directory when using its grant; explicit paths remain grant-relative, and other grants retain their root defaults. File tool paths remain grant-relative as before. On Linux, commands still see /workspace/<directory_id>, not the absolute host path.
The JSON field is working_directory on task creation and /v1/chat/completions requests. API conversations remain stateless, so send it on every request. Update a non-running task with PATCH /api/tasks/{id} and {"working_directory":"/home/user/project"}; "" or null clears it. The agent's schedule_task tool inherits the current run's directory when omitted; an explicit empty string clears it. Scheduled runs reload guidance at execution time, rather than saving a copy at scheduling time. Existing chats/tasks without this field retain their previous behavior.
Agent skills
Skills are enabled by default. At the start of each chat/API/task run, gorunit discovers <name>/SKILL.md under .agents/skills, .claude/skills, and skills. With a working directory selected, it searches each ancestor from the containing Read grant's root down to that directory, never above the grant or in unrelated descendants. Without a working directory it searches readable grant roots only. A Read grant pointing directly at a directory named skills also supports <name>/SKILL.md directly. User-level skill directories therefore need an explicit Read grant; gorunit never implicitly reads your home directory. Both directory and file names are case-sensitive.
Each enabled SKILL.md is included in the run's context, including any YAML frontmatter (name/description) and Markdown instructions. The catalog name is its containing directory name. The model is instructed to apply only relevant skills and resolve supporting resources relative to the skill file using normal permission-scoped file tools. Bundled scripts are not executed automatically. Skills remain lower-priority guidance and cannot authorize commands, writes, scheduling, or new access. Duplicate names retain distinct source IDs; excluding a name disables all copies, or use an exact catalog ID to exclude just one.
In the Main chat settings popup, expand Agent skills to Disable all skills for this chat, or enter individual disabled names/IDs, one per line. Find available skills lists names and IDs using the current working directory and Read grants. Policy is saved with each accepted turn and restored on reopening the chat; New chat resets it. Scheduled task creation and saved task cards have the same controls; use Save skills on an existing task. Running tasks cannot be changed. Scheduled runs reload the current files at execution time, not a copy captured at creation. Tasks created through the agent inherit the chat's skill restrictions and cannot re-enable them through tool arguments.
Task creation and /v1/chat/completions accept a skills object. Stateless API clients must send it with every request. For example, disable everything with:
{"skills":{"disabled":true}}
Or disable named skills (or exact IDs returned by authenticated GET /api/skills?working_directory=...):
{"skills":{"disabled":false,"excluded":["deploy","release"]}}
Update a saved task using PATCH /api/tasks/{id} with either object above; {"skills":{}} resets to enabled with no exclusions. Existing chats/tasks without a policy remain enabled. Discovery uses the sandboxed file worker and current Read grants, including task overrides. Symlinks and special files are skipped. Limits: 32 ancestry levels, 256 catalog entries inspected per grant, 64 skills, 64 KiB per skill, and 256 KiB combined skill contents. Skipped files and truncation warnings are included in context. Frontmatter is passed through as text rather than interpreted as configuration.
Disabling skills stops automatic skill loading and instructs the model not to discover or apply that guidance. It is not a filesystem access restriction: ordinary user-requested file access still follows grants. It also cannot erase skill content already present in archived conversations, model outputs, or provider-visible history. Do not store secrets in skill files.
Independent security reviewer
Settings → Independent security reviewer controls a separate model that reviews every proposed agent tool call before execution. It is enabled by default for scheduled task runs and disabled by default for Main chat and /v1 API runs. These global defaults also apply to existing tasks. Task overrides and agent tools cannot change reviewer enablement, provider/model, or reviewer instructions. Operators can add task-specific reviewer instructions through the task editor or authenticated task API.
Choose the reviewer's provider and model independently of the execution agent. Leaving both blank uses the server's saved global provider/model defaults (or startup defaults), not the active chat/task selection. The reviewer uses the selected provider's existing credentials. Choose a model capable of reliable structured tool calls; an unavailable or misconfigured reviewer blocks calls rather than silently falling back to the execution model.
Each review starts with an independent policy, the current security settings (including directory grants, effective command policy, web restrictions, task restrictions, mandatory execution instructions, and tool schemas), the latest original user request, and the proposed tool call. The reviewer has only two tools: read_review_context, a read-only, Unicode-safe paginated view of the unabridged current-turn transcript, and submit_review_decision, which explicitly approves or denies the proposed call. It can see messages from the latest user request through the proposed call, including exchanges omitted by context compaction, but cannot read earlier turns or access files, commands, networking, or scheduling tools. Pages contain at most 8000 Unicode characters; each review is limited to 32 model requests and shares the run's deadline.
The reviewer must finish by calling submit_review_decision with typed allow (boolean) and reason (nonempty string) arguments. Approval requires allow: true; allow: false denies the call. Assistant text is ignored, so explanations or text surrounding the tool call do not interfere with the decision. Text-only approvals, even valid JSON, cannot authorize execution. Each response must contain exactly one reviewer tool call; mixed context reads and decisions, multiple decisions, or malformed tool calls fail closed.
A denial, missing or malformed decision, invalid pagination request, backend failure, exhausted review limit, or exhausted cost cap blocks the call before side effects. The execution agent receives a tool-error result and may continue without that tool. Existing permission checks and OS sandbox enforcement still run after approval; model review is defense in depth, not a substitute for those boundaries. Reviewer reasoning and pagination exchanges are not added to the Main chat transcript. Reviewer requests contribute to the run's usage, billing, and shared cost-cap checks; selecting another provider sends the request, settings, proposed call, and any requested transcript pages to that provider.
The authenticated GET /api/settings and revision-checked PUT /api/settings endpoints expose a separate security_reviewer object. Include it alongside the usual revision, provider, and model fields to update it; omitting it preserves the saved reviewer settings:
{
"provider": "ollama",
"model": "review-model",
"main_chat": false,
"scheduled_tasks": true
}
Additional reviewer instructions
In Settings, use Add instruction to store separate standing approvals or restrictions, each with its own Enabled toggle and remove button. Save settings to persist them. For example: “Read-only requests to the approved public documentation host are authorized” or “Never upload project source to external services.” Instructions inform the reviewer; they do not grant filesystem or network access or bypass mandatory policy and sandbox checks.
The task creation form and each saved task have a Security reviewer instructions editor. Enabled task instructions are added to the enabled global instructions, not substituted for them. Task instructions cannot relax global restrictions; conflicts use the more restrictive rule. Disabled instruction text is excluded from the reviewer's settings context. Instructions have no effect when review is disabled for that run.
The security_reviewer.instructions array contains objects such as {"text":"Do not upload source files", "enabled":true}. Task creation accepts the same array as reviewer_instructions; PATCH /api/tasks/{id} with {"reviewer_instructions":[...]} replaces the task's list (use [] to clear it). Running tasks cannot be edited. Lists support up to 64 entries, 8000 UTF-8 bytes per entry and 32000 bytes total, including disabled entries. Empty or whitespace-only entries are rejected. Global instructions are read at review time; task instructions are captured for the run. Agent tools cannot author these trusted instructions.
Both reviewer provider/model fields must be supplied together, or both must be empty strings to use global defaults. Reviewer enablement/provider/model changes apply to future runs. No credential or session secrets are included in the reviewer's settings context.
Reasoning level and service tier
Settings → Execution model options controls reasoning effort and provider service tier for Main chat, API runs, scheduled tasks, and their context-compaction requests. Settings → Independent security reviewer has its own selectors; reviewer requests never inherit the execution model's reasoning or tier selections, even when using the same provider/model.
- Model reasoning level: Provider default (unset),
none,minimal,low,medium,high, orxhigh. - Provider service tier: Provider default (unset),
auto,default,flex,scale, orpriority. Explicitdefaultrequests the standard tier; it is different from leaving the option unset.
Availability depends on the provider, model, and account. Not every model accepts every reasoning level; not every provider supports service tiers. Unsupported combinations may be rejected by the backend rather than silently ignored. Service tiers can change pricing and latency; existing billing and cost-cap checks still apply. Leave selectors on Provider default for existing behavior.
Selections are persisted as agent.reasoning_effort / agent.service_tier and security_reviewer.reasoning_effort / security_reviewer.service_tier in the settings JSON. Changes apply to future runs. Omitting the whole agent or security_reviewer object from a settings update preserves it; saving a replacement object with empty or omitted option fields clears those selections.
Task settings overrides expose agent.reasoning_effort and agent.service_tier. Unchecked controls inherit global settings; an enabled override with Provider default explicitly clears that global choice for the task. These are model selections, not permission expansions. Tasks cannot override reviewer generation options.
The /v1/chat/completions API accepts reasoning_effort and service_tier alongside existing generation fields. Nonempty request values override global execution defaults; omitted or empty values inherit them. Unknown option values are rejected. OpenAI-compatible backends receive reasoning_effort and service_tier; Codex Responses receives reasoning: {"effort":"high"} and service_tier. Unset options are omitted from backend requests. Codex still omits unsupported sampling and output-token-limit parameters.
Context management
Every tool schema requires a boolean keep_in_context. Calls marked false and their matching results are omitted from future model context after the user turn ends, without an extra summary. Missing flags in older histories conservatively mean keep. The full transcript remains available in saved chats, including omitted calls and results.
Before each model round, the runner checks a JSON-size token estimate (not an exact provider tokenizer), including tool schemas and private continuation reasoning. Near 75% of the model window, or sooner when output headroom requires it, it first removes completed exchanges marked false. Only if input is still near the threshold does it summarize older context using the selected model with tools disabled. During a user turn, both pruning and compaction protect the latest two assistant rounds and all their tool results, as well as system instructions and the current user request. At turn end, the two-round exception no longer applies to calls marked false.
In Settings → Context window, configure the global fallback token window and an optional override for the provider/model currently selected in Main chat. Overrides are saved separately for each provider/model; leave the override blank and save to remove it. Both settings accept 1024–10000000 tokens and persist on the server. Changes apply to future chat, API, and scheduled runs, not runs already in progress.
Context-window precedence is: saved provider/model override → provider-discovered limit → saved global fallback → AGENT_CONTEXT_WINDOW → 128000 tokens. An override bypasses discovery entirely and can raise or lower the model's reported window. Discovery reads the selected model's metadata from the provider catalog (context_length, context_window, or max_model_len; Codex uses its authenticated catalog), is bounded to five seconds per run, and falls back on errors. Providers that omit this metadata, including the standard OpenAI and Ollama OpenAI-compatible catalogs, use the fallback. Set it to the actual usable window of your backend; the default is not a guarantee that every model supports 128k. API runs use the configured backend's provider/model override, while chat and scheduled runs use their selected provider/model.
Compaction preserves actionable decisions, tool outcomes, and unresolved work; private reasoning is not included in summary input. Large transcripts are summarized in bounded fragments, and summaries plus pruning state survive saved-chat reloads. Compaction requests contribute to usage and share the request timeout, but do not consume AGENT_MAX_TURNS. Invalid summaries or an oversized protected tail fail explicitly rather than silently discarding protected context. The /v1 API remains stateless: these changes apply within a request, while saved UI chats also retain the resulting context state across requests.
Codex (ChatGPT subscription)
Install the Codex CLI and sign in with your ChatGPT account using a file-backed login (auth.json, not keychain-only storage or API-key login):
codex login
export LLM_PROVIDER='codex'
# Defaults: LLM_BASE_URL=https://chatgpt.com/backend-api/codex
# LLM_MODEL=gpt-5.3-codex
export AGENT_API_KEY='choose-a-runner-token'
go run .
The runner reads $CODEX_HOME/auth.json (default ~/.codex/auth.json) on each model turn. It never changes the file or refreshes shared login tokens. If the login expires or is rejected, run codex login again. LLM_API_KEY is not used for this provider. Clear any OpenAI/Ollama LLM_BASE_URL or LLM_MODEL overrides when switching, or set them explicitly for Codex.
A Codex LLM_BASE_URL override receives your ChatGPT access token. Keep the official HTTPS endpoint unless you explicitly trust the replacement; do not send a real login token to an untrusted or plain-HTTP endpoint.
Codex requires upstream SSE; the runner forwards text deltas live for streaming requests and buffers the completed reply for non-streaming requests. Encrypted reasoning is replayed internally across tool rounds and is not returned to clients. Codex does not accept the runner's temperature, top_p, or max_tokens options, so they are ignored for this provider; the request deadline and turn limit still apply.
Ollama
Start Ollama and download a model with tool-calling support, for example:
ollama pull qwen2.5:7b
export LLM_PROVIDER='ollama'
export LLM_BASE_URL='http://127.0.0.1:11434/v1'
export LLM_MODEL='qwen2.5:7b'
unset LLM_API_KEY
export AGENT_API_KEY='choose-a-runner-token'
go run .
Model availability and tool-calling quality depend on your backend/version. This runner does not download or host model weights.
Build and test
go test -race ./...
go vet ./...
go build -o gorunit .
./gorunit
Browser discovery logic has dependency-free tests: run node --test internal/web/*_test.js if Node.js is available (Node.js is not required to build or run the server).
The UI is defined in internal/app/ui.templ. Generated internal/app/ui_templ.go is checked in, so normal builds need only Go. After editing templates, regenerate with the pinned templ version:
go generate ./...
UI assets are embedded at build time. Restart go run . or rebuild after changing them. HTMX 2.0.4 is vendored in internal/web/htmx.min.js (license: internal/web/HTMX-LICENSE), so the browser does not need a CDN. Provider/model discovery uses authenticated GET /ui/providers and GET /ui/models?provider=…. Chat submissions use POST /ui/chat, which applies the same bearer authentication, deadlines, concurrency limits, and agent loop as the JSON API and returns escaped HTML fragments. UI conversation history, including file tool activity, is saved in server-side chat sessions; API keys are not saved in browser storage.
Code organization
This repository uses a single Go module with feature packages; no separate module setup is needed.
main.go Thin executable entry point (go run . still works)
internal/
app/ Startup, agent orchestration, scheduling, chats, HTTP handlers,
templ templates and their integration tests
files/ Permission-scoped filesystem access, search and platform helpers
command/ Native command launchers, isolation policies and resource controls
sandbox/ Platform-specific Landlock/Seatbelt enforcement
settings/ Persistent preferences and authentication session storage
setup/ Systemd installer, cgroup setup probes, embedded service
templates and installer tests
web/ Embedded JavaScript/CSS, browser tests and vendored HTMX
providers/ Model backends, authentication, model discovery and tool schemas
The root contains the executable entry point, module metadata, and project documentation. Systemd service templates are embedded from internal/setup/; installed service names and paths are unchanged. Local build output (gorunit) and runtime data (chats/, scheduled_tasks.json) are ignored by Git and are not source packages; the repository layout does not change their locations.
Tests live alongside the packages they exercise. internal/app wires the feature packages together; storage and filesystem packages do not depend on the HTTP server. Chat rendering, scheduling and agent orchestration remain together because they share request execution and transcript state. This keeps those interactions explicit without introducing circular imports or a large interface layer solely to split files.
Browser asset paths on the server are unchanged. To change UI markup, edit the .templ source rather than its generated Go file, then run go generate ./... from the repository root.
Chat costs and per-task run caps
The chat composer displays accumulated usage beside the status. API costs use
server-reported USD charges (usage.cost, including streaming usage), not
configured model prices or token-based estimates. Copilot-compatible responses
with copilot_usage.total_nano_aiu are normalized to USD using the same units as
codeit.nvim (100 billion nano-AIU per USD). A reported zero is free; an absent or
invalid charge is unknown, not zero. Many APIs, including standard OpenAI and
local Ollama deployments, return token counts without monetary costs. Those chats
remain unknown unless the configured backend reports charges.
Totals include every model request, including tool-loop rounds and context
summarization. Observed charges are checkpointed even when a response fails or is
interrupted. Existing archives without billing history show earlier usage as
untracked; costs cannot be reconstructed retroactively. Totals and unknown
counters persist with chats. A pending-request checkpoint marks unreported charges
as unknown after a process crash, rather than treating that request as free.
Switching provider within a chat preserves its totals.
The /v1 usage response includes known aggregate cost when all API requests
in that run reported it; incomplete monetary usage omits cost.
Codex subscription requests are not converted to dollars. The UI shows the
observed percentage-point consumption of the primary and secondary windows and
the last observed account-wide usage. Fresh authenticated snapshots are fetched
from the configured Codex server's sibling /wham/usage endpoint before and after
requests; subscription headers and SSE rate-limit events are also parsed. These
are observations, not a per-chat invoice: concurrent Codex activity on the same
account during a request may be included, and delayed/rounded reporting limits
precision. Increases observed between requests advance the baseline without
consuming the run budget; delayed reporting can therefore undercount consumption.
Each window retains a high-water mark, so decreases and later rebounds cannot
count the same usage twice. Window resets, changed window metadata, or unexplained
decreases mark consumption incomplete rather than subtracting already-counted
usage. A changed window's current utilization is never charged as new consumption;
observations with different window metadata are excluded for the rest of that run.
The UI's last observed account usage remains separate from these high-water marks.
Custom Codex gateways need to expose the usage endpoint for reliable per-run caps;
unavailable snapshots are shown as unknown.
In Scheduled tasks, set an optional Per-run cost cap when creating a task, or use the individual task's Save cap control. Blank means no cap. Each run starts a fresh budget, independent of other tasks and earlier runs:
- API tasks: positive USD amount, for example
0.50for fifty cents. - Codex tasks: positive percentage-point amount, at most 100;
2stops when either primary or secondary consumption reaches 2pp during that run. Starting account utilization (for example 80%) does not itself consume the run budget.
Caps are checked between requests, not as a provider-enforced billing ceiling. The first/in-flight request can exceed the remaining cap. Reaching a cap prevents further model requests and new tool execution; already-running tools cannot be undone. Missing USD charges stop capped API tasks after that response. Codex capped tasks require a valid baseline before sending a completion and stop on missing snapshots or a window reset. Uncapped runs continue while displaying unknown usage. Running tasks cannot have their caps changed. Latest-run accounting is persisted and shown on each task, including failed/interrupted runs; it resets at the next run.
The task JSON field is optional cost_cap. The authenticated
PATCH /api/tasks/{id} endpoint accepts {"cost_cap": 0.50} (or null to
remove a cap), or a separate {"overrides": {...}} update. The unit follows that task's backend, not a global setting. A cap
may also be requested when scheduling through the agent tool. Tool permissions,
network policy, round limits and timeouts remain independent constraints.
Saved settings and sign-in
In Settings, select a provider/model and click Save settings on server. The selected provider and each provider's saved model persist across page visits, browsers, and server restarts. Reload saved settings restores those defaults without saving a draft. Settings are shared by everyone authorized to use this runner; they do not change the environment-configured /v1 backend. Directory grants continue to use their separate Save permissions action and are also persisted on the server.
When AGENT_API_KEY is configured, enter it and click Sign in. The runner creates a persistent 30-day session and clears the API-key input. The browser keeps only an opaque HttpOnly, SameSite=Strict authentication cookie, not settings or a saved API key in localStorage/sessionStorage. The server stores only hashes of session tokens, expiration times, and an API-key binding; changing AGENT_API_KEY invalidates existing sessions. Sign out revokes the current session on disk as well as clearing its cookie. With no runner API key configured, authentication remains disabled.
UI defaults and session records are stored atomically in SETTINGS_FILE (default settings.json beside FILE_PERMISSIONS_FILE, normally ~/.config/gorunit/settings.json on Linux). New files use mode 0600 and new directories use 0700; protect existing directories yourself and run one runner process per settings file. The file must differ from FILE_PERMISSIONS_FILE, and neither private store may be contained by an agent write grant. No API returns the API key or the session database. Revision checks reject saves from stale Settings tabs without discarding their choices; reload saved settings before retrying a conflicted save.
Use HTTPS for non-local access. Session cookies are marked Secure for HTTPS connections, HTTPS login Origins, or X-Forwarded-Proto: https. A TLS reverse proxy must preserve the original Host and set the forwarded scheme. State-changing browser requests must have a matching Origin (or same-origin request metadata for cookie-authenticated requests); cross-origin requests are rejected. Existing API clients can continue using bearer authentication without cookies. Cookies are host-scoped, not port-scoped: use a dedicated trusted hostname for shared deployments.
Filesystem access
Open Settings → Filesystem access, add an existing absolute directory path, enable Read, Write, or both, and click Save permissions. New entries start with both permissions disabled. Remove an entry or turn its flags off to revoke access. Unsaved changes do not affect the agent. Grants are recursive, server-wide, and shared by chat, /v1 API, and scheduled agents; they are not per user or per chat. Set AGENT_API_KEY before granting access, even for local use: anyone able to use an unauthenticated runner can otherwise ask it to read or write permitted files or change grants.
Directory grants must not overlap, including symlink aliases. For example, do not grant /work and /work/private separately: choose non-overlapping project roots instead. The server canonicalizes directory paths and rejects missing/inaccessible roots. A directory can be write-only; that permits file creation/replacement but never reading, listing, or searching its contents.
The model receives these tools:
list_allowed_directories: discover current directory IDs, paths, and Read/Write flags; cannot modify grants.read_file: paginated regular UTF-8 disk-file reads, with optional inclusive 1-basedstart_lineandend_line. Returnslines, parallelline_numbers,start_line,end_line,total_lines,truncated, and optionalnext_start_line; there is no longer a whole-filecontentfield. Pages contain at most 200 lines and 20,000 encoded JSON bytes. Omit bounds to start at line 1; follownext_start_lineto continue, including after a completed explicit range. An end past EOF is clamped; a start past EOF returns an empty page with the actualtotal_lines, not an error. Empty files have one empty line. Zero/negative/reversed ranges still fail. A single line too large for a page fails with an actionable error rather than silently losing text.list_directory: sorted immediate entries in a readable directory, with optional nonnegativeoffset. Returnsentries,offset,total_matches,truncated, and optionalnext_offset.list_files: sorted grant-relative file listing, with optionalpath, literal path-substringquery, nonnegativeoffset, and booleanrecursive(defaultfalse). By default only files directly in the selected directory are returned; setrecursive: trueto include files in subdirectories. Filtering precedes pagination. Returnsfiles,offset,total_matches,truncated,scan_truncated, and optionalnext_offset. Listing pages contain at most 200 items / 20,000 encoded bytes. Offsets at/past the end return an empty page with the total count, not an error. Both listings are stateless; restart pagination if the tree or ignore rules change.search_files: case-sensitive literal content search (default) or filename/path search (mode: "name"), with an optional basename glob such as*.go. Only readable roots can be searched. Both listings and search respect nested.gitignorefiles, including ancestor rules when selecting a subtree; filename filters never override ignores.write_file: create a new text file, or atomically replace a regular file only whenoverwrite: trueis explicitly supplied. Parent directories must already exist. No append, delete, shell execution, or directory-creation tool is provided.
Tools use a directory_id from the directory list and a relative path, never an arbitrary absolute path. Paginated reads stream and validate files up to 32 MiB while returning only the requested page; writes, edits, search input files, and the internal whole-text reader retain their 1 MiB limit. Text must be UTF-8 without NUL bytes. Reads are disk snapshots taken afresh per call, not editor buffers; pagination does not pin a revision.
Discovery respects grant-local .gitignore rules: comments, escaped leading #/!, trailing-space escaping, *, ?, character classes, **, rooted/directory-only patterns, negation, and nested overrides. Ignored directories are pruned, so a child cannot be re-included unless its parents are included too. .git, symlinks, special files and private temporary write files are omitted. Hidden files otherwise remain eligible. No Git/ripgrep process is launched; global excludes, .git/info/exclude, .ignore, and ignore files above the grant are not consulted. Gitignore is a discovery filter, not a permission boundary: an explicit read_file can still read an ignored file if its grant permits it. Ignore files must be regular UTF-8 text, at most 64 KiB each / 256 KiB per scan, with at most 4096 active rules; inaccessible/unsafe/oversized ignore files fail discovery closed.
Search skips binary, oversized, and unreadable files. Results are bounded to 100 matches, 1000 files, 5000 visited entries, depth 64, approximately 32 MiB of file reads, and approximately 64 KiB of match data, with shortened text snippets and explicit truncation/skipped counts. Recursive listing uses the same 5000-entry/depth-64 discovery bounds. If scan_truncated is true, total_matches describes only the scanned portion and next_offset is omitted: narrow path rather than paginating an incomplete scan. A single directory exceeding 5000 entries fails explicitly. Narrow the path or query when search is truncated.
For example, call read_file with {"directory_id":"<id>","path":"src/main.go","start_line":100,"end_line":9999,"keep_in_context":true} to read from line 100 up through EOF or the page cap; continue at the returned next_start_line. Call list_files with {"directory_id":"<id>","query":".go","recursive":true,"offset":0,"keep_in_context":false} and use the returned next_offset for the next page.
Permissions are stored atomically with mode 0600 in FILE_PERMISSIONS_FILE, defaulting to gorunit/file_permissions.json beneath Go's os.UserConfigDir() (typically ~/.config/gorunit/file_permissions.json on Linux, respecting XDG_CONFIG_HOME). New configuration directories use mode 0700; secure existing directories yourself. Write grants cannot contain this configuration file or the server settings/session file, preventing the agent from editing its own permissions. If necessary, relocate it outside the directories you wish to grant. Use one runner process per permission file. Settings changes use revision checks so stale tabs cannot silently overwrite one another.
File operations use Go 1.25's os.Root, with directory handles pinned after a grant is opened. Absolute paths, escaping .. paths, and symlinks escaping a root are rejected without relying on a check-then-open path prefix. Reading contained relative symlinks is allowed; discovery omits symlinks, and writing a final symlink is rejected. Atomic replacement breaks an existing hard link rather than modifying other paths to its old inode; replacement may change ownership/ACL metadata. Permissions are checked on every operation, including scheduled runs. Saving a revocation waits for in-progress file operations, then prevents subsequent access. Revoking permission does not erase content already sent to a provider or saved in a chat.
There is no aggregate disk quota for writes; a Write grant trusts the agent to consume space in that directory, subject to your OS quotas and the runner's per-request limits. This is a file-tool boundary, not an OS process sandbox: grants include ordinary mounted content and hard links already present within the allowed tree. Do not grant virtual filesystems (/proc, /sys, /dev), credential/configuration directories, or trees containing untrusted mounts. Local users who can edit the server's config/code still control the process. Secure file access is not supported on Go's js or plan9 targets. On startup, invalid, missing, or redirected saved roots cause a fail-closed startup error; repair the saved config or choose a different FILE_PERMISSIONS_FILE to start with no grants.
Authenticated settings endpoints: GET /api/file-permissions returns {revision, directories}; PUT /api/file-permissions replaces that configuration with a matching revision and directory records {id, path, read, write}. Omit/empty id on new records to get a generated ID. Only the settings API can change grants; the model has no permission-editing tool.
Approvals and agent-proposed settings changes
The agent can read effective settings with get_settings and submit an update_settings proposal with a reason and a changes_json object. For example, {"commands":{"timeout_seconds":3600}} proposes a larger sandbox wall-clock limit while preserving other command settings. Nested objects merge; arrays and scalar values replace; omitted sections are preserved. Null, unknown fields, credentials, authentication, and directory-grant changes are not supported.
Proposing is not applying. Open the Approvals navigation tab to inspect pending requests, exact before/proposed differences, the original settings snapshot, and the immutable payload. Approve and apply a request or deny it. The agent has no approval/denial tool. Approval is specific to one proposal and never authorizes future changes. Treat reasons as untrusted agent text and review security-sensitive settings (including network access, runtime directories, and sandbox limits) carefully.
Decisions use the same authenticated, same-origin-protected API as Settings. Approving revalidates the proposal through the manual settings validation path, atomically saves the settings and approval decision, and activates command policy changes. Stale proposals return a conflict rather than overwriting newer settings: deny the old proposal and ask for a fresh one. Denial changes no settings. Agent limits apply to future runs; command policy changes do not stop commands already running. Approving a settings proposal does not resume or retry the originating agent run. Scheduled-task input requests, described below, have a separate resume workflow.
Settings requests and their decision history persist inside the protected SETTINGS_FILE (mode 0600), surviving restarts alongside settings. The tab refreshes every five seconds while visible. History includes request ID, type, reason, timestamps, status, and proposal data; all authenticated users of this shared runner see the same queue. Limits are 64 pending and 512 total records, with the existing 1 MiB settings-file limit; a full queue/history rejects new requests rather than silently discarding audit records. No retention/deletion UI is provided yet.
Authenticated endpoints:
GET /api/approvals— list pending requests and decision history.POST /api/approvals/{id}/decisionwith{"decision":"approve"}or{"decision":"deny"}— decide a pending permission/settings request. For task questions use{"decision":"answer","answer":"your response"}or deny. Repeated decisions return a conflict.
Approval records have an explicit type discriminator: settings_update, task_approval, and task_question currently have separate handlers. Future approval types must have their own server-side handler and cannot be implicitly executed as settings updates. Direct operator saves in Settings remain immediate and do not need a second approval.
Scheduled tasks
Open Scheduled tasks in the UI to create a self-contained prompt. New tasks inherit the saved global provider/model at run time by default; uncheck Use global provider/model defaults to show task-specific provider and model controls. Choose an available model or enter a model ID directly; this selection is independent of Main chat and is pinned to the new task. Choose a one-time local date/time, or a five-field cron expression and IANA timezone (for example America/New_York). You can also ask the chat agent to schedule a task; its schedule_task tool saves the current provider/model and returns the task ID and next run. Include all needed context in the task prompt: runs start fresh, without the original chat history.
The chat agent can inspect existing tasks with list_scheduled_tasks (compact summaries with IDs) and read_scheduled_task (full prompt, configuration and latest result, without private conversation checkpoints). When you ask it to edit a task, it can use update_scheduled_task to change its name, prompt, cron, one-time run timestamp or timezone. Omitted fields stay unchanged; switching between cron and one-time scheduling requires explicitly clearing the other field with "". Prompt/name-only edits preserve the next run and do not requeue completed tasks. Edits are rejected while a task is queued, running or waiting for input. These tools do not change permissions, backend/model selection, skill restrictions, reviewer policy or cost caps. Scheduled runs do not receive task-management tools.
Cron fields are minute hour day-of-month month day-of-week, supporting *, lists, ranges, and steps. For example, 0 9 * * 1-5 runs weekdays at 09:00; */15 * * * * runs every 15 minutes. Sunday is 0; when both day fields are restricted, either matching field triggers a run (standard cron OR semantics). Timezones follow daylight-saving changes: nonexistent local times are skipped and repeated local times may run twice. Cron defaults to UTC when no timezone is supplied.
Schedules and the latest result/error are saved in SCHEDULE_FILE (default scheduled_tasks.json, mode 0600); protect this file and its directory because they contain prompts and model output. The parent directory must exist. There is a shared limit of 100 tasks, including completed one-time tasks; delete old tasks in the UI. Only the latest result is retained, capped at 32 KB. Schedules are shared by everyone with the runner token, not isolated by user.
The runner must be running to execute tasks. Overdue tasks run once on startup; recurring schedules then advance to the next future occurrence, rather than replaying missed intervals. Runs never overlap with themselves, use the normal timeout and shared concurrency limit, and record a failed result if the runner is busy. A run is claimed on disk before execution: interrupted runs are not retried automatically. Scheduled prompts cannot create further schedules. Command and web tools follow the current operator settings; there are no external notifications. View results in the UI, which refreshes every 15 seconds while the panel is open. Tasks without an explicit provider/model follow saved global defaults (or the startup backend when no defaults have been saved). Existing tasks with an explicit provider/model retain that selection.
Authenticated JSON endpoints (same bearer token as chat):
GET /api/tasks— list schedules and latest results.POST /api/tasks— create withname,prompt, and eitherrun_at(future RFC3339 timestamp with offset) orcronplus optionaltimezone. Supplyproviderandmodelto pin a UI backend; omit them to inherit saved global defaults, falling back to the startup backend. Optionaloverridesstores per-field restrictions.PATCH /api/tasks/{id}— update one ofcost_cap,overrides, orworking_directoryfor a non-running task.overridesreplaces the complete task override object;{}ornullrestores inheritance.DELETE /api/tasks/{id}— delete a non-running task.
Human approvals and questions during a scheduled run
Scheduled agents have a last-resort request_user_input tool:
{"kind":"question","question":"Which deployment target should I use?","reason":"The prompt and available project configuration do not identify a safe target."}
Use kind: "approval" for permission to perform one specific action, or kind: "question" for essential missing information. Both the tool schema and agent instructions discourage using it except when absolutely necessary: it delays completion until a person responds, potentially indefinitely. It must be the only tool call in its turn; mixed batches execute no tools. The tool is unavailable to ordinary chat/API agents and security reviewers.
A successful request ends the active execution and marks the task waiting_for_user. Its complete saved conversation (including tool context), billing, spent model rounds, active execution time, and selected backend are checkpointed with the request. No worker, command slot, or agent concurrency slot stays occupied. Recurring occurrences cannot overlap the paused run.
In Approvals, select Approve and resume for a permission request, or enter an answer and select Submit answer and resume for a question. The response and resume_ready state are saved atomically; the scheduler then claims the continuation once, restores the conversation, and delivers the actual user response before requesting another model response. Completed tools are not replayed. Approvals do not expand sandbox permissions or authorize unrelated actions; current global restrictions and the original task restrictions are checked again. The same run's cost cap and model-round budget remain in force, and only active execution (not time waiting for a human) consumes its wall-clock budget. User responses are capped at 8000 UTF-8 bytes.
Denial ends that run without continuation; a recurring task can still execute its next scheduled occurrence. Pending and ready continuations survive restarts, but a crash after a continuation has been claimed is marked interrupted and is not automatically replayed. Task edits and deletion are blocked while waiting/queued/running; deny a pending request to release it. Task approval history is retained even after a completed task is deleted.
Task requests, answers, history, and private checkpoints live in the protected SCHEDULE_FILE, not SETTINGS_FILE, so an accepted answer and the task's state are one atomic transaction. Legacy array-only schedule files are read automatically; new saves use an object containing tasks and approvals. Keep this file outside every agent Write grant and command home directory (move it and set SCHEDULE_FILE if necessary). It is now protected like settings to prevent tools from forging user decisions. The 16 MiB schedule-file limit includes checkpoints and approval history; limits are 64 pending/512 total task requests and 384 KiB for the initial conversation checkpoint (with room reserved for an answer). Oversized checkpoints or failed writes fail closed rather than discarding context or silently resuming. The task-list API does not expose private conversation checkpoints.
Per-task settings overrides
Expand Task settings overrides when creating a task or on an existing task card. Enable only the fields you want to override; unchecked fields follow the current global value. Existing-task edits use Save task overrides, independently of the cost cap. Polling preserves unsaved edits. Overrides persist in the task's schedule record, not in global settings. Running tasks cannot be edited.
The controls cover provider/model selection, agent rounds and timeout, context windows, command enablement and networking, allowed programs/hosts, runtime paths, command resource/time/storage limits, public web fetch and its hosts, and Read/Write restrictions for each existing directory grant. Sign-in/session credentials are never stored per task. Sandbox home and cgroup locations must remain identical to the global paths; changing them is not a restriction.
Global permissions are the ceiling. Boolean permissions can only be disabled, numeric limits can only be lowered, runtime paths must be selected from the global list, and allowlists can only be narrowed. Empty host/program lists mean unrestricted, so a task cannot clear a nonempty global list; disable the capability to deny it entirely. Host entries must match a global entry or narrow a globally allowed wildcard. Directory restrictions reference existing grant IDs and cannot add paths or grant rights. A task model-context override is an additional ceiling and cannot enlarge a smaller global or provider-discovered window.
Restrictions are checked when saving and again for every run. If globals become stricter and a saved override would now broaden them, the run fails closed with a policy error; clear or lower the obsolete override before retrying. File workers, command launches, and web fetches also enforce the current global permissions at execution time. Task restrictions never mutate the shared policy or bypass command serialization and sandbox cleanup-failure state.
The JSON overrides object uses flat field names, for example:
{
"agent.max_rounds": 8,
"agent.timeout_seconds": 60,
"commands.enabled": false,
"web_fetch": false,
"context_window_override": 32000
}
Other keys follow the global settings names, such as commands.memory_bytes, commands.allowed_programs, web_fetch_allowed_hosts, provider, and model. Directory flags use directories.<grant-id>.read and directories.<grant-id>.write. GET /api/tasks includes override_fields metadata with the available keys, types, current global values and restriction rules. Values are typed JSON (including explicit false); omit a key to inherit rather than setting it to null.
{"name":"Weekday arithmetic","prompt":"Calculate 145 * 8 / 4.","cron":"0 9 * * 1-5","timezone":"America/New_York","provider":"ollama","model":"qwen2.5:7b"}
Connect Open WebUI
In Open WebUI's admin connection settings, add an OpenAI-compatible connection:
- Base URL:
http://127.0.0.1:8080/v1 - API key: the value of
AGENT_API_KEY - Model:
agent(discovered through/v1/models)
Labels vary by Open WebUI version. Use ordinary text chat, and leave Open WebUI's own tools/native function calling disabled for this connection: tools are managed inside this runner.
If Open WebUI runs in Docker, 127.0.0.1 inside that container is not the host. Use a reachable host address, often http://host.docker.internal:8080/v1, and bind the runner to an appropriate interface with LISTEN_ADDR. Linux Docker may need --add-host=host.docker.internal:host-gateway. Set a runner token and restrict network access before changing the localhost-only binding. If runner authentication is disabled, a placeholder key can be used where Open WebUI requires one.
API
GET /healthz— process liveness, not backend readiness; no authentication.GET /v1/models— lists the runner's public model alias.POST /v1/chat/completions— runs the agent and returns its final assistant response.
The two /v1 endpoints require Authorization: Bearer <AGENT_API_KEY> when configured. The public UI/assets contain no secrets.
curl http://127.0.0.1:8080/v1/chat/completions \
-H "Authorization: Bearer $AGENT_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"model":"agent","messages":[{"role":"user","content":"What is 6 * 7?"}]}'
Add "stream":true for live OpenAI-style SSE text deltas ending in [DONE] (use curl -N to disable client buffering). stream_options.include_usage adds a final usage chunk summed across model turns. OpenAI-compatible backends must support streaming chat completions; Codex text deltas are also forwarded live. Non-streaming requests retain the normal JSON response.
Streaming emits assistant text from each model turn, including commentary before tool calls. Tool arguments/results and private reasoning are not exposed through /v1. After generation succeeds, a finish-reason chunk precedes optional usage and [DONE]. Failures before the first chunk use normal HTTP JSON errors; failures after streaming starts use a sanitized SSE error object followed by [DONE], without a successful finish chunk. For the stateless /v1 API, disconnects still cancel generation; saved UI chats instead continue in the background. Disable reverse-proxy buffering and configure proxy/client timeouts to accommodate REQUEST_TIMEOUT.
The web UI streams answer text, provider-supplied readable reasoning, incremental tool-call arguments, and tool execution/results while retaining tool-activity polling. Consecutive reasoning and tool entries share a collapsed Activity · N items fold, like Codeit; normal assistant text stays outside. Nested folds let you inspect individual reasoning, calls, and results, both live and in saved chats. Codex encrypted reasoning cannot be decrypted or streamed as readable text. POST /ui/chat accepts X-Chat-Stream: true: it flushes X-Chat-ID and escaped, inert <template data-chat-delta> text frames and <template data-chat-event> JSON activity frames (turn, reasoning, tool_call, tool_start, tool_result), then returns the complete saved HTML transcript. The browser renders partial text safely as plain text and replaces it with the final transcript. Stop/interruption retains received partial assistant text and readable reasoning in the failed saved turn when the server can finalize storage; reload the chat before continuing. Reattachment via GET /ui/chats/{id}/stream first emits an escaped <template data-chat-snapshot> containing the run's initial transcript, replays its delta/event frames, follows live updates, and emits a final snapshot with the saved transcript and resume fields. This initial baseline prevents duplicating already-checkpointed text or activity. The stream sends inert heartbeat templates during idle tools; disconnected observers release their resources without canceling execution. Replay uses a private temporary journal in CHAT_DIR, unlinked while open on Linux/macOS and closed when execution and its attached readers finish, rather than an unbounded in-memory token buffer. Replay is available only for runs started by the current runner process; a process restart still interrupts execution. The existing non-streaming HTML and /api/chats/{id}/progress JSON contracts are unchanged.
Supported inputs:
model: the configured public alias, not an arbitrary backend model.messages: 1–128 messages, withsystem,developer,user, orassistantroles. Content is a string or an array of text parts. Backend support fordevelopermessages varies.stream,stream_options.include_usage,temperature,top_p,max_tokens, andn=1.
Client-supplied tools, tool selection, tool history, images, and other non-text content are rejected. Other unknown request fields are ignored, not forwarded; JSON/structured-output mode, stop sequences, logprobs, embeddings, audio, the Responses API, and other OpenAI endpoints are not implemented. This is a text-chat-compatible API, not a complete OpenAI API replacement. Open WebUI features beyond ordinary chat may require additional endpoints/parameters.
Usage counts sum all backend model turns, including the internal tool round trips, when the backend reports usage. The /v1 chat API is stateless. UI chats are persisted with their complete transcript; scheduled prompts and their latest results are persisted separately. Conversation content is not written to application logs. Authentication is a shared API token, not per-user isolation or billing.
File-tool sandbox
Each file-tool invocation re-executes the running binary as a one-shot worker. The parent alone loads and updates directory permissions. It pins the granted directories and an immutable policy snapshot until the worker exits; permission updates wait for active calls, so a completed revocation cannot leave an older worker running. Workers have a 30-second maximum lifetime (or the request's shorter deadline), bounded JSON IPC, no inherited application environment or server sockets, and only explicitly passed directory descriptors. Cancellation kills and reaps the worker; an interrupted write may already have completed and is not rolled back.
Workers authenticate directory identities, apply the OS sandbox, close the inherited descriptors, then dispatch the file tool using the existing os.Root containment, permission checks and file-size/type limits. They do not load server settings or backend credentials. Sandbox setup failure is a tool error; there is no unrestricted fallback.
- Linux: requires Landlock enabled and ABI 3+ (Linux 6.2+ normally; availability also depends on the kernel and container configuration). The policy denies file reads, directory listing, file-content writes, creation, removal and execution outside the granted rights. ABI 4+ also denies TCP bind/connect; ABI 5+ mediates and denies device ioctls. Write grants permit regular-file publication, not special-file creation or execution.
- macOS: requires a cgo-enabled build and the private
sandbox_initSeatbelt API. The generated default-deny policy allows granted directory reads/writes and runtime metadata access, but not network access or execution. Because this API is private, compatibility must be tested on the target macOS release. Builds without cgo fail closed for file tools. - Other platforms: file-tool execution fails closed. Non-file server features remain available.
The file-worker policy deliberately denies execution. Landlock alone does not mediate every metadata operation or provide complete process/network isolation. File workers must keep their synchronous filesystem work on the locked OS thread. Command launchers use the separate, stronger boundary below and directly exec the payload on that restricted thread.
Public web fetch
Web fetch is disabled by default, independently of command networking. Set AGENT_API_KEY, then enable Settings → Commands and sandbox → Enable public web fetch and click Save settings on server. The saved web_fetch setting applies server-wide to chat, API, and scheduled agents. It requires neither command execution nor directory grants. Disabling it blocks subsequent fetches, but does not cancel one already in progress.
The fetch_url tool makes an unauthenticated HTTP(S) GET on standard ports, follows at most four redirects, and returns the final URL, HTTP status, content type, and up to 64 KiB of text, HTML, JSON, or XML within 15 seconds. Non-2xx responses are explicitly marked. It does not render HTML, execute scripts, use cookies/proxy settings, or accept credentials/custom headers. Localhost, private, link-local, and special-purpose addresses are blocked at connection time, including after DNS resolution and redirects. Treat fetched pages as untrusted data. URLs and queries are sent to external servers; never include secrets. Public addressing is not a substitute for an operator-managed egress firewall.
Command execution
The run_command tool is disabled by default. To enable it, run as a non-root, non-setid service account and set COMMANDS_ENABLED=true and a nonempty AGENT_API_KEY. Grant a workspace Read permission in Settings; add Write only if commands should be able to modify it. The tool is then available to both normal and provider-selected/scheduled agents. Only the selected directory grant is exposed to an invocation; other grants are not inherited.
{"argv":["git","status","--short"],"directory_id":"<granted-directory-id>","path":".","timeout_seconds":30}
Arguments are passed directly, without an implicit shell. A shell can be requested explicitly subject to the same restrictions. Empty arguments are supported, but argv[0] must name an executable. Working paths must remain within the selected directory. The operator owns the policy: the model cannot supply environment variables, runtime mounts, network permissions or resource limits. Commands inherit no application credentials, agent sockets, settings descriptors or policy channels. HOME and temporary storage are private. Results contain stdout/stderr, exit code, timeout/cancellation flags, truncation flags and a side-effects warning. Each output stream retains at most 64 KiB of raw bytes, with invalid UTF-8 replaced for JSON. Output beyond the limit is drained and discarded.
Commands are serialized per runner. The operator-configured wall-clock maximum defaults to 30 seconds and can be configured up to 86400 seconds. Omitting timeout_seconds, or setting it to 0 or -1, means unlimited up to that configured sandbox maximum (including any stricter task limit); positive values request a timeout no larger than that maximum. The enclosing request deadline may be shorter. Default limits are 512 MiB memory, 30 seconds CPU time per process, 16 MiB per regular output file, 256 descriptors and no core dumps. Interrupted or failed commands may already have changed files: there is no rollback or automatic retry. Permission updates wait until the invocation and descendant cleanup finish. An unverified cleanup failure disables further commands until restart.
Linux
The native backend currently supports Linux amd64, requires unprivileged user namespaces, modern mount APIs, Landlock ABI 3+, seccomp and delegated cgroup v2 with the cpu, memory and pids controllers. No Bubblewrap, container executable or helper binary is required. Unsupported architectures and failed setup stages fail closed.
Set COMMAND_CGROUP_ROOT to an operator-provisioned cgroup subtree writable by the runner's UID. Enable cpu, memory and pids in that directory's cgroup.subtree_control, and keep the server outside it or in a separate leaf. The runner creates a fresh child cgroup per command and does not modify the server's existing limits. The bundled services use --systemd-service to enable child controllers only within their own delegation after the server enters its supervisor leaf; they never enable controllers in ancestor cgroups. The systemd setup below provides delegation; systemd is not required by the implementation.
Automatic setup with systemd
The binary embeds both system and user service templates: only the single executable needs to be distributed. On Linux, ./gorunit setup detects whether it is running as root. Normal execution never performs setup. Both installation modes require systemd 254+ and cgroup v2.
As a normal user, setup checks the user manager, install-path permissions, and actual cgroup delegation. It announces a short-lived transient user service, then uses that service to create a child cgroup, configure CPU/memory/no-swap/task limits, start a no-op process directly inside the child cgroup, and exercise cgroup.kill. The probe is stopped/collected afterward; a runtime deadline bounds it if the client disappears. This permission check happens before installation confirmation and does not install application files.
If the checks succeed, setup offers a user-service installation running as the current user, explains all target paths and changes, and asks [y/N]. Only y or yes proceeds. Setup does not create accounts, enable/start the service, or enable lingering. The defaults are:
- Binary:
~/.local/lib/gorunit/gorunit. - Unit:
$XDG_CONFIG_HOME/systemd/user/gorunit.service(default~/.config/systemd/user/gorunit.service). - Credentials:
$XDG_CONFIG_HOME/gorunit/environment, created with mode0600; existing credentials are preserved. - State and private HOME:
$XDG_STATE_HOME/gorunit(default~/.local/state/gorunit). - Command cgroup: setup previews the detected user manager/app slice plus
gorunit.service. The unit setsCOMMAND_CGROUP_ROOT=auto; at startup, the app discovers its actual delegated parent from/proc/self/cgroupand supplies that resolved path to fresh UI settings. Discovery fails closed outside a delegated service'ssupervisorleaf.
go build -o gorunit .
./gorunit setup
# Edit the environment file printed by setup: configure AGENT_API_KEY and backend
# credentials; set COMMANDS_ENABLED=true if command execution is wanted.
systemctl --user enable --now gorunit.service
systemctl --user status gorunit.service
journalctl --user -u gorunit.service -n 50 --no-pager
Setup prints these next steps, UI/directory-grant instructions, and the detected cgroup path on completion. A user service shares your account's existing access and groups; a dedicated system-service account offers stronger separation. Saved UI command settings take precedence over the unit's environment defaults. Stop an existing user installation before updates (systemctl --user stop gorunit.service). The cgroup path is rediscovered at each service startup; rerun setup if installation paths change. Use environment directories consistent with your user manager's XDG configuration. Do not run system and user installations on the same listening address.
If permission checks fail, setup reports the cause, installs no application files, and prints both recovery options. For missing controller delegation, ask an administrator to review/create /etc/systemd/system/user@.service.d/delegate.conf:
[Service]
Delegate=cpu memory pids
The administrator must run sudo systemctl daemon-reload; fully log out of all sessions and log back in to recreate the user manager (interrupting existing user services). An ancestor slice or container policy may also withhold controllers and require host-level changes. Do not make the whole cgroup filesystem writable. A missing user bus requires a normal login session/reachable user manager, not broader filesystem permissions.
For operation after logout or without a login, check loginctl show-user "$USER" -p Linger; if needed, ask an administrator to run sudo loginctl enable-linger "$USER". Lingering is not required for login-session operation and is never changed by setup. Alternatively, use sudo ./gorunit setup for the system-service installation below. A successful cgroup probe does not verify every namespace, Landlock, or seccomp prerequisite; test a sandboxed command after installation.
System-service setup (root)
When run as root, setup installs the embedded system unit and a copy of the running executable.
Setup requires systemd 254+ (for DelegateSubgroup=) running as the host service manager, a unified cgroup v2 hierarchy mounted at /sys/fs/cgroup, and the Linux sandbox features listed above. The host must provide systemctl and, if creating the default account, useradd. Setup checks the systemd version and cgroup filesystem; command sandbox compatibility still needs to be tested after installation.
Build as your normal user (or use an already-built binary), then run:
go build -o gorunit .
sudo ./gorunit setup
sudoedit /etc/gorunit.env
After read-only prerequisite checks, setup asks for an existing non-root username. Press Enter to create/use the dedicated gorunit account instead. An explicitly entered username must already exist; setup rejects root accounts and root primary groups. Existing accounts retain their primary group and are not modified. The installed unit uses the selected account's numeric UID/GID. Setup then explains the selected identity and planned binary, unit, and environment-file changes and asks Proceed with installation? [y/N]. Only y or yes (case-insensitive) confirms; blank input, EOF, and other answers cancel without making changes. On success, setup prints instructions for credentials, command enablement, service startup, logs, UI access, and workspace grants.
After confirmation, setup creates the dedicated gorunit user/group only if the default was selected and it is missing, installs the binary at /usr/local/lib/gorunit/gorunit and unit at /etc/systemd/system/gorunit.service, and reloads systemd. It creates a root-owned mode-0600 environment template with commands disabled, but preserves an existing environment file. Existing environment files must already be root-owned regular files with mode 0600; symlinks are rejected. The service is not enabled or started automatically.
Using an existing personal/shared account gives the server that account's existing filesystem access and supplementary groups, so a dedicated account provides stronger separation. HOME and private state remain /var/lib/gorunit, not the selected user's home. When starting the service, systemd assigns ownership of that state directory to the selected account; selecting a different account on an existing installation changes state ownership at startup.
For updates, stop the service first (sudo systemctl stop gorunit.service), then run the new binary's setup command and select the same account again. Setup refuses an active service, replaces the installed binary and unit, and leaves persistent state and credentials intact. Back up any local unit changes first; use systemd drop-ins for customization. Installation is not transactional across all steps: if a step fails, fix the reported problem and rerun setup.
Set the environment file contents before starting (systemd syntax, without export):
AGENT_API_KEY=replace-with-a-long-random-runner-token
LLM_PROVIDER=openai
LLM_API_KEY=replace-with-your-backend-key
COMMANDS_ENABLED=true
Alternatively configure your chosen backend as described in Quick start. The service does not inherit your shell environment or Codex login, even when using your existing account; provision its backend credentials separately if needed. Keep this file root-owned and mode 0600. Do not override COMMAND_CGROUP_ROOT unless also adapting the unit's cgroup layout.
sudo systemd-analyze verify /etc/systemd/system/gorunit.service
sudo systemctl enable --now gorunit.service
sudo systemctl status gorunit.service
sudo journalctl -u gorunit.service -n 50 --no-pager
Systemd performs the privileged delegation at each service start, including after reboot. The server itself runs as the selected non-root account (gorunit by default), never root. StateDirectory= creates private persistent state under /var/lib/gorunit; the binary and unit remain root-owned and outside writable workspace grants. Grant the service account access only to the workspaces it needs, then configure directory grants in the UI. This starts a separate installation: it does not migrate existing settings, chats, or directory grants.
COMMAND_CGROUP_ROOT points to /sys/fs/cgroup/system.slice/gorunit.service, not its supervisor child. Systemd delegates the controllers and places the server in supervisor, leaving the parent free of processes. The launched server then enables cpu, memory, and pids in its delegated parent's cgroup.subtree_control, allowing resource-limited sibling cgroups for commands. KillMode=control-group also lets systemd terminate remaining service descendants when stopping the service. Do not add hardening options that hide or make the delegated cgroup subtree read-only, or disable the user namespaces needed by the command sandbox.
To inspect the layout after startup:
sudo systemctl show gorunit.service -p User -p ControlGroup -p Delegate
sudo cat /sys/fs/cgroup/system.slice/gorunit.service/cgroup.subtree_control
sudo cat /sys/fs/cgroup/system.slice/gorunit.service/supervisor/cgroup.procs
The controller list should contain cpu, memory, and pids. Successfully starting the HTTP server is not an end-to-end sandbox check: run a simple command through the authenticated UI with a directory grant to verify command setup on this host. Saved UI command settings take precedence over the environment defaults; if reusing state, check that commands are enabled and the cgroup root matches this unit.
Linux command isolation
Each command gets private user, mount, PID, IPC, UTS, and (including when networking is enabled) private network namespaces. Network opt-in creates a loopback-only proxy endpoint inside the command namespace; the parent serves HTTP forward requests, HTTP CONNECT, and SOCKS5 CONNECT outside the namespace. The parent resolves proxy hostnames and performs the outbound connections, so commands have no direct egress path. The launcher constructs an immutable root, recursively read-only runtime mounts, /workspace/<directory_id>, minimal device files, and size-limited temporary tmpfs mounts. A fresh procfs mounted inside the command's private PID namespace provides /proc/self/exe and sandbox process information, without exposing host processes. It is read-only, nosuid,nodev,noexec, and uses subset=pid to hide global kernel interfaces such as /proc/sys. It pivots away from the host root; there are no ambient mounts of host home directories, /etc, the host's /proc, /sys, credentials or Unix sockets beyond the explicitly selected workspace and runtime paths. When networking is enabled, small read-only snapshots of available CA bundles are exposed at their standard /etc paths; DNS for proxy destinations is resolved by the parent. HTTP_PROXY, HTTPS_PROXY, and their lowercase variants point clients at the loopback HTTP proxy, while ALL_PROXY and its lowercase variant use the loopback SOCKS5 proxy with remote hostname resolution. The workspace is read-only unless its grant permits writes. Commands must use relative workspace paths, not the host paths returned by directory discovery.
Landlock limits filesystem access and execution. Capabilities are dropped and locked down with no_new_privs. A syscall allowlist denies socket creation by default. Network opt-in permits only the loopback proxy listener setup and proxy client traffic needed by the sandbox; direct outbound connections, UDP, BIND, and server/listener use by payloads remain unavailable. HTTP-aware clients can use the forward/CONNECT proxy; arbitrary TCP clients can use SOCKS5. Git-over-SSH is configured automatically as described below; standalone SSH still needs an explicit ProxyCommand. Both modes deny namespace changes, mounts, ptrace/process-memory access, keyrings, BPF, io_uring and other unsupported operations; namespace creation through clone and alternate syscall ABIs are also blocked. Namespace PID 1 is killed on parent death. The command cgroup enforces aggregate memory/no swap, one CPU of bandwidth and at most 32 tasks, and is killed and verified empty on completion or cancellation, including detached descendants.
With Linux command networking enabled, the launcher sets GIT_SSH_COMMAND and GIT_SSH_VARIANT=ssh so /usr/bin/ssh uses a gorunit SOCKS5 forwarding helper. The helper sends hostnames to the existing parent-side proxy, which still enforces the allowed-host list. Linux's listener is isolated in the private network namespace and uses SOCKS5 no-auth; this does not relax macOS's requirement for per-command proxy credentials. The helper offers only the required authentication method and never falls back to direct connections.
The Linux launcher pins the running executable before pivoting away from the host filesystem and copies it to /tmp/ssh-proxy in the size-limited private temporary mount. The copy inherits Landlock, seccomp and the command cgroup. It is not a privileged broker, and creating it consumes temporary-storage quota. Minimal synthetic /etc/passwd, /etc/group and /etc/nsswitch.conf files allow OpenSSH's local account lookup: namespace UID/GID 0 is named agent, with home /home/agent. No host account database, password hashes, resolver configuration or directory-service configuration is copied. These exact files are readable under Landlock and become immutable with the root skeleton. Network-disabled commands get neither the helper nor these account files nor the Git SSH environment.
SSH uses /home/agent/.ssh/config if present (otherwise -F /dev/null), /home/agent/.ssh/known_hosts, and private-home default identity paths. Account-home/system SSH configs and global known-hosts files are not loaded automatically. Strict host-key checking remains enabled. Provision verified host keys and credentials in the persistent command home through an operator-approved workflow; host keys, private keys and SSH agents are not copied or inherited. A private config may add custom identities and host aliases. In Linux's synthetic account, ~ also resolves to /home/agent; ${HOME} works on both platforms. The runtime must contain /usr/bin/git, /usr/bin/ssh and their libraries. Native Git/SSH integration tests require Linux amd64 and COMMAND_TEST_CGROUP_ROOT pointing to an empty delegated cgroup v2 subtree with cpu,memory,pids enabled.
macOS
Automatic setup with launchd
Build with cgo enabled on the target Mac, then run ./gorunit setup as your normal login user, without sudo, from a logged-in graphical session. Normal execution never installs anything. Setup asks for confirmation and installs a per-user LaunchAgent (not a root LaunchDaemon):
- Binary:
~/Library/Application Support/gorunit/bin/gorunit. - LaunchAgent:
~/Library/LaunchAgents/io.gorunit.agent.plist, mode0600. - Private state and service HOME:
~/Library/Application Support/gorunit/state. - Private logs:
~/Library/Application Support/gorunit/logs/{stdout,stderr}.log. - Initial
settings.jsonandpermissions.jsonare created in the state directory with mode0600; existing settings, grants, credentials, chats and scheduled tasks are preserved.
This keeps the running executable and private stores outside your development checkout, so the checkout can receive a write grant without removing the protected-server-file restriction. Do not grant write access to the installation/state directory or put these protected files inside a workspace. The service shares your account's filesystem access and groups; it is not a dedicated service account. Its HOME is private, and shell/Codex credentials are not copied or inherited.
The plist's EnvironmentVariables dictionary is the macOS service configuration. Before loading, edit it with a text editor or /usr/libexec/PlistBuddy: set AGENT_API_KEY to a long random runner token, select LLM_PROVIDER, and set LLM_API_KEY (plus any provider-specific variables). Commands default to disabled; optionally set the string value COMMANDS_ENABLED to true after configuring the token. Keep the plist private; avoid placing credentials directly on a shell command line or in shell history. XML special characters in manually edited values must be escaped. Saved UI command settings override environment defaults.
Setup does not load or start the agent. After configuring credentials:
plutil -lint "$HOME/Library/LaunchAgents/io.gorunit.agent.plist"
launchctl bootstrap gui/$(id -u) "$HOME/Library/LaunchAgents/io.gorunit.agent.plist"
launchctl print gui/$(id -u)/io.gorunit.agent
Open http://127.0.0.1:8080, authenticate, and add your development directory grants in Settings. Once loaded, launchd starts the agent at login and restarts it if it exits; a per-user LaunchAgent does not run after logout. Review the private log files for startup failures. Logs are not automatically rotated by this installer.
For updates or configuration changes, unload first:
launchctl bootout gui/$(id -u)/io.gorunit.agent
# Run the NEW binary's setup to update the installed executable:
./gorunit setup
launchctl bootstrap gui/$(id -u) "$HOME/Library/LaunchAgents/io.gorunit.agent.plist"
Setup refuses a loaded agent, rejects symlinks and insecure installation paths, atomically replaces the installed binary, and preserves an existing plist (including credentials and customizations). If future versions change the plist template, merge those changes manually. Installation is not transactional across all files; fix errors and rerun. To uninstall, unload and remove the plist; remove application data separately only if no longer needed. macOS privacy controls may require approval for access to protected folders; setup does not bypass them.
A successful service start is not a sandbox verification: test a file tool and a sandboxed command on the target Mac. Use a cgo-enabled build; no-cgo builds fail closed for those tools. This installer requires runtime testing on macOS; it has not been runtime-tested from the Linux development environment.
macOS command isolation
With command networking enabled, Git-over-SSH is automatically routed through the command's authenticated SOCKS5 proxy. The launcher sets GIT_SSH_COMMAND and GIT_SSH_VARIANT=ssh to use /usr/bin/ssh with a gorunit ProxyCommand helper. Hostnames are sent to the proxy for parent-side resolution, and the same allowed-host policy applies. A private copy of the gorunit executable supplies the forwarding helper and is removed with the command's temporary root; it inherits the existing sandbox and has no privileged forwarding path. Linux uses the same Git SSH file policy with its private-namespace proxy, as described above. Neither backend automatically proxies standalone ssh invocations.
The launcher does not expose the host's SSH keys, agent, keychain, or normal home directory. OpenSSH normally derives ~ from the account database rather than $HOME, so the launcher explicitly selects SSH files instead of relying on the private HOME alone:
- Config:
$HOME/.ssh/configvia-F, or/dev/nullif absent. The normal account-home and system SSH configs are not loaded automatically. - Host keys:
$HOME/.ssh/known_hosts, withStrictHostKeyChecking=yesand no global known-hosts files. Unknown or changed keys fail; there is no automatic trust-on-first-use. - Default identities: the usual
id_rsa,id_ecdsa,id_ecdsa_sk,id_ed25519,id_ed25519_sk,id_xmss, andid_dsanames under$HOME/.ssh, not the account-home defaults. Missing key files are not created.
Here $HOME means the persistent command home. Provision verified host keys and any required identity using an operator-approved workflow; a working proxy transport alone does not authorize a push. The private SSH config can supply host aliases and additional identities. Use ${HOME}/.ssh/custom_key for private-home paths: explicit ~ paths in that config still refer to the macOS account home and are not rewritten. The launcher supplies the proxy transport and disables hostname canonicalization and proxy FD passing. Network-disabled commands do not receive this configuration or a forwarding helper.
The native backend requires cgo and the private Seatbelt API; it needs no external sandbox executable. The profile defaults to deny, grants runtime execution/read access and the selected workspace's read/write access, allows child-process creation, and denies networking by default. Children inherit the Seatbelt policy and resource limits. With network access enabled, the trusted parent serves an authenticated, per-command IPv4 loopback HTTP/CONNECT/SOCKS5 proxy. Seatbelt allows outbound TCP only to that exact address and port; direct destinations, other loopback ports, UDP, and command-side DNS remain denied. Proxy environment variables include fresh per-command credentials, and the parent resolves destinations and enforces the allowed-host list. Before exec, the payload verifies forbidden IPv4/IPv6 and UDP operations are denied and the proxy is reachable; failed checks abort setup. This uses the host network stack, not a Linux-style network namespace. Shells, compilers, Git operations and other commands may spawn helpers, provided those executables are allowed by the runtime/workspace policy. Seatbelt alone does not give this implementation Linux-equivalent process-tree containment.
macOS uses private per-command HOME/tmp directories and a trusted supervisor re-executed from the same binary. The supervisor watches a parent-owned control pipe, enforces an independent wall deadline, kills the payload's process group on completion, cancellation or server death, reaps the direct payload, and attempts temporary-directory cleanup. Process-group cleanup is best-effort: descendants that detach into a different group/session can survive command completion and permission revocation, retaining their inherited sandbox access. Do not use this backend for workloads requiring guaranteed descendant termination. The payload, not the supervisor, receives the Seatbelt policy and OS resource limits. Its memory/task/CPU-bandwidth limits are not equivalent to Linux cgroup accounting, and its temporary storage has no hard aggregate quota. The profile also permits general filesystem metadata inspection, not arbitrary file-content reads. The private API and required runtime permissions must be validated on the target macOS release; the macOS cgo backend has not been runtime-tested from this Linux environment. No-cgo builds fail closed for command execution.
Allowed programs
In Settings → Commands and sandbox → Allowed programs, enter one binary file
name per line, for example cat, grep, and go, then save settings. The API
field is commands.allowed_programs, an array of strings. A missing, null, or
empty list preserves unrestricted program selection. Names are case-sensitive;
paths, whitespace and wildcard patterns are rejected. Every argument is allowed,
subject to existing argument-size and sandbox limits.
Matching uses the filename of argv[0]: go, /usr/local/go/bin/go, and
./go all match go. This does not verify executable identity or resolve symlinks.
It checks direct run_command launches, not subprocesses, interpreter input, or
code executed by an allowed program. In particular, allowing go, a shell, or an
interpreter can allow arbitrary code inside the sandbox. Landlock, runtime paths,
directory grants, network policy and resource limits remain mandatory and unchanged.
A name match never grants filesystem access or makes an unavailable binary runnable.
The startup default can be set with COMMAND_ALLOWED_PROGRAMS=cat,grep,go.
Saved command settings override this environment default, apply server-wide to
future launches, and persist across restarts. Clearing the list removes only this
additional restriction; disable command usage to deny all launches.
Additional sandbox PATH directories
In Settings → Commands and sandbox → Additional PATH directories, enter one absolute directory per line. The API field is commands.path_entries, for example {"commands":{"path_entries":["/usr/local/go/bin","/home/agent/.local/bin"]}} as part of the command settings object. The startup default can also be set with COMMAND_PATH_ENTRIES=/usr/local/go/bin:/home/agent/.local/bin; saved command settings take precedence.
On both macOS and Linux these entries are appended, in order, after /usr/bin:/bin and any enabled macOS Homebrew bin directories. Duplicate entries are removed without changing the first occurrence's precedence. Both bare initial commands and child processes use the same PATH. Blank restores the default PATH; an individual executable filename does not belong in this setting. Relative entries, empty entries, colons within a directory, non-clean paths, and control characters are rejected (maximum 64 entries, 4096 bytes each and 16384 bytes total). No shell variables or ~ are expanded.
PATH does not grant access or mount directories. Tool installations outside a grant still need appropriate runtime access. For example, expose /usr/local/go through Runtime directories and add /usr/local/go/bin to PATH. Use paths as seen inside the sandbox: a Linux workspace bin is /workspace/<directory_id>/bin, and its persistent home is /home/agent, regardless of the host home path. On macOS use the actual granted workspace or configured command-home path. Entries may refer to directories that do not exist yet. Scheduled-task overrides may remove configured entries but cannot add new ones. Existing filesystem, allowed-program and network restrictions remain in force.
Runtime policy and remaining risks
COMMAND_RUNTIME_PATHS can replace the default colon-separated runtime directories. Defaults expose /usr/bin, /bin, /usr/lib, /lib and available lib64 aliases on Linux; /bin, /usr/bin, /usr/lib and /System/Library on macOS. Runtime directories are readable/executable even when outside workspace grants: include only trusted runtime files, never a home directory or credential directory. Runtime paths may overlap writable directory grants, including through symlinks. Such runtime files are mutable through the writable grant, so only allow this for toolchains you trust commands to modify. Runtime paths must still remain separate from the persistent command home and private sandbox paths. Extra toolchains may require explicit runtime paths plus additional PATH directories (or absolute executable names). The minimal filesystem and syscall policy will not support every program.
Keep the runner executable and private server state outside writable grants. The executable is protected alongside permission/settings files, and Linux re-execs the running image through /proc/self/exe instead of trusting a replaceable filename. Use dedicated workspace directories without special IPC files, aliases or pre-existing hard links to private files; arbitrary commands modify real inodes, unlike the file tool's atomic replacement behavior. Do not grant writes to server storage; grant writes to runtime installations only when their modification is intentional.
Neither backend is a VM boundary or a guarantee against host-kernel exploits. Writable host workspaces have no aggregate disk quota: per-file limits and bounded temporary storage do not prevent creating many workspace files. Use filesystem/project quotas or a dedicated volume when this matters. macOS additionally lacks hard aggregate temporary-storage accounting. For fully hostile workloads or broader compatibility, use a future dedicated runtime image/VM boundary rather than broadening this policy.
The normal Go suite exercises argument/schema validation, runtime integrity and raw Linux seccomp denials. End-to-end Linux namespace, agent dispatch, resource-limit, timeout and cleanup tests are opt-in: set COMMAND_TEST_CGROUP_ROOT to a prepared delegated subtree and run go test -p 1 -v ./internal/command ./internal/app -run '^(TestNativeCommandIntegration|TestAgentCommandIntegration)$'. On macOS, use a cgo build and COMMAND_TEST_MACOS=1 go test -v ./internal/command -run '^TestNativeMac(Command|Proxy)Integration$' to validate the target release before enabling the tool.
Configuration
Startup configuration uses environment variables; saved UI defaults and directory grants use server-side files; .env files are not loaded automatically.
| Variable | Default | Purpose |
|---|---|---|
LISTEN_ADDR |
127.0.0.1:8080 |
HTTP listen address |
LLM_PROVIDER |
openai |
Default provider: openai, ollama (OpenAI-compatible), or codex |
LLM_BASE_URL |
https://api.openai.com/v1 (openai); https://chatgpt.com/backend-api/codex (codex) |
Startup backend base URL, including /v1 where required; Ollama defaults to http://127.0.0.1:11434/v1 |
LLM_API_KEY |
empty | Startup OpenAI-compatible backend bearer token; unused for Codex |
OPENAI_API_KEY |
empty | OpenAI UI credential when a different startup provider is selected |
LLM_MODEL |
gpt-4o-mini (openai); gpt-5.3-codex (codex) |
Startup backend model; Ollama defaults to qwen2.5:7b |
CODEX_HOME |
$HOME/.codex, then the OS account's .codex directory |
Codex CLI directory containing a ChatGPT auth.json login; an explicit value disables fallback. The account home is checked only when the default file is missing, allowing discovery when a user service overrides HOME. |
AGENT_MODEL |
agent |
Model alias advertised to clients |
AGENT_API_KEY |
empty | Runner bearer token; empty disables authentication |
AGENT_MAX_TURNS |
64 |
Maximum agent rounds per request, from 1 to 100000 (excludes compaction calls) |
AGENT_CONTEXT_WINDOW |
128000 |
Fallback token window when the provider omits model limits; from 1024 to 10000000 |
SETTINGS_FILE |
settings.json beside FILE_PERMISSIONS_FILE |
Private shared UI defaults and persistent session records; must be outside all write grants |
FILE_PERMISSIONS_FILE |
OS user config directory + gorunit/file_permissions.json |
Persistent shared directory Read/Write grants; must be outside all write grants |
CHAT_DIR |
chats |
Private saved UI chat directory; created if missing; run only one process per directory |
SCHEDULE_FILE |
scheduled_tasks.json |
Persistent task file; parent directory must exist; run only one runner process per file |
LOCAL_TOOLS_FILE |
unset | Optional operator-managed JSON catalog for task-local function tools; loaded at startup |
REQUEST_TIMEOUT |
300s |
Whole agent request deadline, from 1s to 10m |
COMMANDS_ENABLED |
false |
Initial sandboxed run_command default; requires a nonempty AGENT_API_KEY; saved UI command settings take precedence |
COMMAND_NETWORK_ACCESS |
false |
Initial command network-access default; saved UI command settings take precedence; Linux opt-in uses only the private loopback HTTP/HTTPS and SOCKS5 proxies, which can reach host/private services and readable files |
COMMAND_CGROUP_ROOT |
/sys/fs/cgroup/system.slice/gorunit.service on Linux; empty elsewhere |
Initial app/UI cgroup default; auto discovers the delegated service parent at startup (used by the user unit). Must be a delegated cgroup v2 subtree with cpu/memory/pids enabled before commands can run |
COMMAND_ALLOWED_PROGRAMS |
empty (any program) | Comma-separated binary names for initial run_command launches; all arguments allowed; saved command settings take precedence |
COMMAND_RUNTIME_PATHS |
Platform runtime directories above | Colon-separated replacement read/execute runtime policy; never include credentials |
COMMAND_PATH_ENTRIES |
empty | Colon-separated additional sandbox PATH directories, appended after platform defaults; does not grant filesystem access |
Settings → Commands and sandbox exposes command enablement, additional PATH directories, runtime directories, the Linux cgroup root, and memory/process/file-size/CPU limits. Save settings applies these server-wide to future command executions in chat, API requests, and scheduled tasks, and persists them across restarts. Saved command settings override COMMANDS_ENABLED, COMMAND_NETWORK_ACCESS, COMMAND_CGROUP_ROOT, COMMAND_RUNTIME_PATHS, and COMMAND_PATH_ENTRIES; environment values are defaults until command settings are saved. Disabling commands does not terminate an execution already running. Isolation remains mandatory and network access stays disabled by default. The operator can explicitly enable it with the Network access checkbox or COMMAND_NETWORK_ACCESS=true; this gives commands access to the host network, including localhost/private services, and permits exfiltration of any readable files. Enabling still requires AGENT_API_KEY, a supported non-root service account, and the platform sandbox prerequisites. Runtime directories are readable/executable outside filesystem grants; never include secrets.
The last model turn must produce a final answer; repeated tool calls exhaust the limit and return an error. At most eight tool calls are accepted per model turn.
Local tools for scheduled tasks
Local tools appear as individual function tools to the model, like MCP tools, but don't require an MCP server. Set LOCAL_TOOLS_FILE to a JSON file and restart gorunit. Then select the tools on the Scheduled Tasks page, either when creating a task or under Local tools on an existing task. The task API accepts a local_tools array of configured names in POST /api/tasks and PATCH /api/tasks/{id}; [] detaches all tools. GET /api/tasks includes local_tool_options for discovery. Chat and model-created tasks do not inherit attachments, and the model cannot edit tasks that have local tools attached. A task with a missing definition cannot run until you restore it or detach it.
Example catalog:
[
{
"name": "local_git_status",
"description": "Show Git status for the task's configured checkout",
"mode": "sandbox",
"argv": ["git", "status", "--short"]
},
{
"name": "local_service_status",
"description": "Check the status of a service using an operator-maintained wrapper",
"mode": "host",
"argv": ["/opt/gorunit/bin/service-status", "--"],
"inputs": [
{ "name": "service", "description": "Service to check", "pattern": "(web|worker)" }
],
"timeout_seconds": 15
}
]
Each tool needs a unique local_ name, a description, an explicit mode, and a fixed argv array. Optional inputs are required string fields when declared. Each value must match its entire Go regular expression and becomes exactly one argv element, appended in declaration order. The model cannot add flags or arguments outside the declared inputs, change the executable, or choose a mode. Gorunit does not invoke a shell to interpret argv.
sandboxuses the same runner, enablement, program allowlist, file grants, resource limits, network policy, and task restrictions asrun_command. Usedirectory_idand optional grant-relativepath, or configure a working directory on the task. An omittedtimeout_secondsuses the task's applicable command limit.hostrequiresAGENT_API_KEYand an absolute executable path. It runs as the gorunit service account, outside the command sandbox and its policies (includingCOMMANDS_ENABLED), with working directory/, no inherited service environment, and a fixedPATH=/usr/bin:/binandLANG=C. Timeout defaults to 30 seconds; gorunit bounds captured output and stops the direct process on cancellation or timeout. A wrapper that starts subprocesses must manage and clean them up itself.
Only install host tools you would trust to run under the service account with model-selected inputs. Keep the catalog, executables, and wrapper dependencies outside model-writable locations. Use narrow input patterns, separate options from operands with -- where supported, and make the wrapper enforce its own permissions and resource limits. Avoid passing model input to interpreters, shell snippets, or general-purpose dispatchers. Changing a catalog definition changes the behavior of every task attached to that name after restart.
Security and extension points
Keep the default loopback binding for local use. For shared or remote access, set AGENT_API_KEY, use a TLS reverse proxy, and apply network/rate limits. The runner itself serves plain HTTP, has no CORS access policy for external browser apps, and does not enforce per-user quotas. Model prompts and output travel to the selected backend; follow its privacy policy. Client system/developer instructions are accepted for chat compatibility, not treated as a security boundary. The actual tool allowlist is enforced in Go.
providers/provider.go: shared provider types, backend interface, OpenAI transport, and tool schema.providers/codex.go,providers/codex_auth.go: Codex Responses transport and read-only CLI login loading.main.go: executable argument dispatch and service startup.internal/setup/: Linux systemd and macOS launchd installation, delegation probes, embedded system/user service templates, and installer tests.internal/app/agent.go: agent policy, turn loop, and tool dispatch.internal/app/api.go: HTTP API, validation, authentication, and SSE formatting.internal/app/bootstrap.go: configuration and graceful shutdown.internal/app/ui.templ,ui_templ.go,ui.go: templ page, generated components, and HTMX chat handlers; model output is escaped text, never trusted HTML.internal/app/scheduler.go,scheduled_api.go, andproviders/scheduling.go: persistent schedule storage, execution, authenticated API, and optional agent tool.internal/app/chats.go,chat_api.go,chat_view.go: per-chat archive, checkpoint/recovery, history endpoints, and transcript formatting.internal/files/,internal/app/file_tools.go,internal/app/file_permissions_api.go, andproviders/files.go: rooted filesystem enforcement, bounded search, tools, and permission settings.internal/web/: browser lifecycle hooks, styling, and vendored HTMX.
To add a tool, add its schema to the provider's tool list and explicitly dispatch it in executeTool. Scheduling remains in-process; file tools and commands use distinct re-exec workers. Do not introduce new worker capabilities or network access by changing prompts: extend the parent-owned policy and OS enforcement, with adversarial regression tests.
Allowed network hosts
Settings includes independent Command allowed hosts and Web fetch allowed hosts lists.
Enter one exact DNS hostname or IP address per line, or use *.example.com to allow
subdomains (not example.com itself). Matching is case-insensitive and ignores a
final DNS dot. IP literals are matched by address; DNS entries do not implicitly
allow requests made directly to their resolved IPs. URLs, ports and CIDRs are not
accepted. A blank list preserves unrestricted host selection.
The API fields are commands.allowed_hosts and web_fetch_allowed_hosts (arrays
of strings). Omitting a fetch list on PUT preserves it; an empty array clears it.
Lists are persisted and apply to future commands/fetches. Command network access
and web fetch must still be enabled separately. Command HTTP, CONNECT and SOCKS5
connections all enforce the command list before DNS resolution. Fetch enforces
its list on the initial URL and every redirect, without relaxing public-IP,
standard-port or other existing fetch restrictions. Host lists restrict connection
destinations, not individual services behind an allowed proxy or shared host.