osborn
AGENTS.md8 starsChanged 14 days agoMITView on GitHub
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository. Osborn is a voice AI engineer and thinking partner: you talk, it researches, writes and ships the work. Users speak through a Next.js frontend; audio routes through LiveKit Cloud to a local TypeScript agent that researches topics, explores and edits codebases, runs commands, and documents its work via the Codex Agent SDK. There is no test suite. Agent needs: agent/.env with LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET, ANTHROPIC_API_KEY, SONIOX_API_KEY…
- Reads credentials
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,040 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository6 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- browser-screen-recorderSkill
- ci-typecheckSkill
- meetingsSkill
- org-migrationSkill
- osborn-opsSkill
The file
We split this AGENTS.md into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 273
Every prompt layer (realtime teleprompter, research system prompts, fast brain, spec consolidation, proactive loop, voice-queue injection …
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
Project Overview
Osborn is a voice AI engineer and thinking partner: you talk, it researches, writes and ships the work. Users speak through a Next.js frontend; audio routes through LiveKit Cloud to a local TypeScript agent that researches topics, explores and edits codebases, runs commands, and documents its work via the Codex Agent SDK.
Development Commands
Agent (from agent/)
npm install
npm run dev # Start agent with tsx (auto-reload)
npm run dev -- --room X # Join a specific LiveKit room
npm run room X # Shortcut for above
npm run build # TypeScript compile to dist/Frontend (from frontend/)
npm install
npm run dev # Next.js dev server on :3000
npm run build # Production build
npm run lint # ESLint via next lintThere is no test suite.
Deployment
Frontend deploys to Railway (nixpacks, Node 24). Build: cd frontend && npm install && npm run build. Start: cd frontend && npm run start.
Required Environment
Agent needs: agent/.env with LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET, ANTHROPIC_API_KEY, SONIOX_API_KEY (default STT and TTS, config.ts DEFAULT_CONFIG), and at least one of OPENAI_API_KEY / GOOGLE_API_KEY. Optional: DEEPGRAM_API_KEY only when OSBORN_STT_PROVIDER/OSBORN_TTS_PROVIDER selects Deepgram. Optional: SMITHERY_API_KEY for cloud-hosted MCP servers (YouTube, GitHub via Smithery; not connected to sessions yet, #501). Optional: RECALL_API_KEY for Zoom/Google Meet bot integration via Recall.ai.
Frontend needs: frontend/.env.local with NEXT_PUBLIC_LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET. For cloud sandbox provisioning (optional): DAYTONA_API_KEY, DAYTONA_API_URL, DAYTONA_PROXY_DOMAIN, DAYTONA_REGION, plus the platform infra keys forwarded into sandboxes (OPENAI_API_KEY, GOOGLE_API_KEY, SONIOX_API_KEY, DEEPGRAM_API_KEY, RECALL_API_KEY, SMITHERY_API_KEY).
Architecture
Frontend (Next.js 14) <-> LiveKit Cloud <-> Agent (Node.js/tsx on local machine)
├── Codex Agent SDK (coding tools)
├── OpenAI/Gemini Realtime (voice)
└── MCP Servers (extensions)Three Voice Modes
- direct: STT (Deepgram Flux with semantic turn detection) → Codex Agent SDK → TTS. Full tool access, all research capabilities.
skipTTSQueue: truebypasses LiveKit's BufferedTokenStream and emitstts_sayevents that route directly tosession.say(). - pipeline (default): Same as direct, but
ClaudeLLMis wrapped byPipelineDirectLLM. Every user turn fires a parallel Gemini Flash AFC observer (pipeline-fastbrain.ts) that searches the JSONL summary index, surfaces results to the frontend panel, and can call anemergency_stoptool that aborts and restarts the Codex subprocess with a new prompt. Interruption context (word-accurate spoken text + JSONL replay of recent assistant messages) is enriched into the next user message. - realtime: OpenAI/Gemini native speech-to-speech. The realtime model is a thin teleprompter with only two tools:
ask_fast_brain(called for every user message — the fast brain decides everything) andrespond_permission. Returned scripts are spoken verbatim. Deep research is triggered indirectly when the fast brain returns aNEEDS_DEEPER_RESEARCHmarker.
Persistent Session Architecture
The Codex Agent SDK query() function accepts AsyncIterable<SDKUserMessage> as its prompt. Instead of spawning a fresh subprocess per message (which replays the full JSONL history each time), a single query() is created on the first chat() call with a MessageChannel (pushable async iterable). Subsequent messages are pushed to the channel — the subprocess stays alive, no JSONL replay. This is implemented in Codex-llm.ts:
MessageChannel<T>class — pushable async iterable feeding the subprocess stdin#persistentQuery: SDKQuery— singleton query reference, kept alive for the voice sessionpushMessage()— first call does cold start (JSONL replay), subsequent calls are instant#startBackgroundConsumer()— long-runningfor awaitloop routing SDK events to TTS/frontendcloseSession()— kills subprocess on disconnect/session switch/recoveryinterruptQuery()— callspersistentQuery.interrupt()(graceful Esc, subprocess stays alive)abortQuery()→closeSession()(kills subprocess, next call cold starts)
Multi-Agent Orchestration
The main agent (Sonnet) is an orchestrator with three named sub-agents defined in the agents config in Codex-llm.ts:
- researcher (Sonnet) — information gathering: codebase, web, multi-file reads. Tools: Read, Glob, Grep, Bash, WebSearch, WebFetch, Task. Does NOT edit files.
- reasoner (Opus) — deep thinking: architecture decisions, tradeoffs, implementation planning. Read-only tools. Returns plans for the writer.
- writer (Sonnet) — execution with verify-first workflow: check assumptions → clarify unknowns → execute → verify (run tests/build). Tools: Read, Write, Edit, MultiEdit, Bash, Glob, Grep. Only agent with write access outside workspace.
The PreToolUse hook checks input.agent_type — the writer agent (agent_type === 'writer') gets full write access everywhere. All other agents are restricted to workspace-only writes. The prompts cap the main agent at 3 direct tool calls per turn (MAIN_DIRECT_CALL_CAP); anything more must be delegated.
Research Mode
The agent operates in a single research mode. It can read any file, search the web, run commands, fetch YouTube transcripts, and save findings to a per-session workspace. There are no plan/execute or read-only/edit mode toggles.
Write safety: A PreToolUse hook in Codex-llm.ts blocks Write/Edit/MultiEdit outside the session workspace (/osb/ path or legacy .osborn/sessions/), UNLESS the calling agent is the writer sub-agent (agent_type === 'writer'). The canUseTool callback auto-approves writes to the session workspace (no permission prompt), while all other tools use permissionMode: 'default'. The system prompt has strict file writing rules (full absolute paths, no hallucinated writes).
Session workspace — co-located with Codex's native JSONL files:
~/.Codex/projects/{slug}/osb/<session-uuid>/
spec.md # Portable research output: goal, user context, open questions (bidirectional), decisions, findings, plan
search-index.txt # Compact summary index for fast search
search-index-meta.json # Index metadata (byte offsets, timestamps)The fast brain (fast-brain.ts) maintains spec.md — reading FULL untruncated data from Codex's JSONL session files via session-access.ts after research completes. The research agent focuses on thorough investigation; the fast brain consolidates findings into spec.md.
System prompt: Defined in prompts.ts via getResearchSystemPrompt(), injected via systemPrompt field in Codex-llm.ts. The research agent reads spec.md for context but does NOT write to it — the fast brain handles all spec writes via updateSpecFromJSONL().
Legacy types: EditMode and AgentMode are still exported from config.ts for backward compatibility with old .session-meta.json files, but are not used in the active code path.
Key Source Files
Agent:
agent/src/index.ts— Main entry (~3000 lines): LiveKit room events, session creation (createDirectSession/createRealtimeSession), HTTP API server (port 8741, configurable viaOSBORN_API_PORT, auto-bumps on EADDRINUSE), self-healing CWD fallback chain (OSBORN_CWD→config.workingDirectory→process.cwd(), each verified withexistsSync),killCurrentLLM()helper that callsabortQuery()/abortAgent()to kill the persistent Codex subprocess on disconnect (the JS-reference null alone left the SDK draining MessageChannel into a dead session). Realtime mode wires only two tools on the agent:ask_fast_brainandrespond_permission— all routing happens inside the fast brain. Background research viaexecuteResearch(), debounced 8s research batch viascheduleResearchBatch(), post-research consolidation viaupdateSpecFromJSONL(), proactive conversational loop (15s, capped 4 prompts).agent/src/Codex-llm.ts—ClaudeLLMextendsllm.LLM(~1300 lines). Persistent session:MessageChannel<SDKUserMessage>(pushable async iterable),#persistentQuery: SDKQuerysingleton,#startBackgroundConsumer()long-runningfor awaitloop routing SDK events to TTS/frontend,pushMessage()for cold-start vs fast-path push,closeSession()to kill the subprocess. Three named sub-agents (researcherSonnet /reasonerOpus /writerSonnet, each with explicit tool lists and detailed prompts).PreToolUsehook isagent_type-aware: writer agent defers tocanUseToolfor permission dialog (permissionDecision: 'ask'); all other agents are restricted to workspace paths (/osb/,.osborn/sessions/,.osborn/research/).canUseToolauto-approves workspace writes EXCEPTspec.md(deny — fast brain manages it), auto-approves writer writes to.Codex/skills/<name>/(so multi-file skill installs don't cascade permission prompts), auto-approvesAskUserQuestion, auto-deniesEnterPlanMode/ExitPlanMode. Loads.Codex/skills/*/SKILL.mdfiles into the system prompt as<available-skills>.interruptQuery()/abortQuery()/rewindToCheckpoint()exposed for fast brain agent control.#activeQueries: Settracks both persistent and one-shot queries.agent/src/fast-brain.ts— Central orchestrator (~2200 lines).askFastBrain()is the single gateway — the realtime voice model callsask_fast_brainfor every user turn, fast brain decides whether to answer directly (type: 'answer'), trigger background research (NEEDS_DEEPER_RESEARCH→triggerResearchcallback), record decisions (RECORDED:), or ask the user a clarifying question (ASK_USER:). Provider chain: PRIMARY = Gemini Flash (~1-2s, 1M token context, no cold start) via@google/genai; FALLBACK = direct Anthropic API (Haiku) via@anthropic-ai/sdk; LAST RESORT = Agent SDK (Haiku) for tool-loop cases. 12 fast brain tools:read_file,write_file,read_agent_results(last 40 tool results),read_agent_text(last 60 assistant messages),read_subagents,search_jsonl,read_conversation,get_full_transcript,get_session_stats,deep_read_results(FULL session, optional toolFilter),deep_read_text(FULL session reasoning),send_to_chat(push markdown to frontend chat panel), plus Gemini-onlyweb_search.processResearchChunk()/updateSpecFromJSONL()post-research spec consolidation reading FULL untruncated JSONL viasession-access.ts.generateVisualDocument()for Mermaid/comparison/analysis docs.prepareBriefingScript()/prepareRecoveryScript()build voice resume/recovery briefings.agent/src/session-access.ts— Programmatic JSONL session access (~1000 lines, 25+ exported functions):readSessionHistory(),getRecentToolResults(),getSubagentTranscripts(),getSessionTranscripts(),searchSessionJsonl(),getConversationText(),watchSessionFile(),getRawSessionJsonl(),getSessionStats(),getSessionPlan(),getSessionTodos(),getSessionSummary(),projectPathToSlug(),getSessionPaths(),getSessionSubAgents(). HonorsCLAUDE_CONFIG_DIRenv var. Reads FULL untruncated tool results and agent reasoning from~/.Codex/projects/{slug}/.agent/src/jsonl-search.ts— Two search strategies over session JSONL.ripgrepSearch()shells out to the bundled@vscode/ripgrepbinary (withgrepfallback) — validates patterns against shell-injection chars, optionalfromEnd: truefor "most recent matches" mode.bm25Search()builds an in-memoryminisearchindex fromreadSessionHistory({ lastN: 500 }), cached persessionId, invalidated viainvalidateBM25Cache().resolveJsonlDir()mirrorssession-access.tsslug logic.agent/src/summary-index.ts— Compact line-oriented searchable index over JSONL session files (~700 lines).buildSummaryIndex()walks JSONL, extracts a one-line summary per entry with the byte offset back into the source, writes to~/.Codex/projects/{slug}/osb/{sessionId}/search-index.txt.startIndexWatcher()tails the JSONL and incrementally appends.readFullContent()uses the byte offset to fetch the full original entry without re-parsing the file. Used bypipeline-fastbrain.ts.agent/src/prompts.ts— Centralized prompt definitions (~2100 lines, 15+ exports). System prompts:DIRECT_MODE_PROMPT,getRealtimeInstructions(),getDirectModeResearchPrompt(),getResearchSystemPrompt(),FAST_BRAIN_SYSTEM_PROMPT,CHUNK_PROCESS_SYSTEM,REFINEMENT_PROCESS_SYSTEM,AUGMENT_RESULT_SYSTEM,CONTEXTUALIZE_UPDATE_SYSTEM,PROACTIVE_PROMPT_SYSTEM,VISUAL_DOCUMENT_SYSTEM,RESEARCH_COMPLETION_SYSTEM. Voice injection helpers:getScriptInjection(),getProactiveInjection(),getNotificationInjection(),getResearchCompleteInjection(),getResearchUpdateInjection(). Builders:buildFastBrainSdkPrompt(),buildGeminiContextPrompt(). Note: legacyprompts-2-25-26.tsandprompts-3-2-26.tsare kept on disk as historical snapshots — onlyprompts.tsis imported by the active code.agent/src/config.ts—OsbornConfigloading from~/.osborn/config.yaml(~1300 lines).VoiceMode = 'direct' | 'realtime' | 'pipeline'. Session management:listSessions(),listAllClaudeSessions()(scans every~/.Codex/projects/*/folder),getMostRecentSessionId(),sessionExists(),getSessionSummary(),getConversationHistory(). Workspace helpers:getSessionWorkspace(),ensureSessionWorkspace(),readSessionSpec(),listWorkspaceArtifacts().MCP_CATALOGwith Smithery cloud entries,buildMcpServersForKeys(),getMcpServerStatusList(),getMcpToolPatterns().extractTextContent()strips rawtool_use/tool_resultJSON from history reads.agent/src/smithery-proxy.ts— In-process MCP proxy for Smithery cloud servers. Bypasses Codex Agent SDK HTTP bug (#18296) by using@smithery/api/mcpcreateConnection()+ MCP SDKClientto get a working transport, then wraps in a localMcpServerreturned as{ type: 'sdk', name, instance }. Patches bothMcpServer.connectandServer._server.connectto handle reconnection across SDKquery()calls.agent/src/recall-client.ts— Recall.ai API wrapper for meeting bot integration.RecallClientclass:joinMeeting(),leaveMeeting(),handleWebhook(),registerBot(). Singleton viagetRecallClient()(returns null ifRECALL_API_KEYnot set). Meeting transcripts surface astranscriptevents thatindex.tsroutes intocurrentLLM.chat()as[Meeting — Speaker]: text.agent/src/pipeline-direct-llm.ts—PipelineDirectLLMwrapsClaudeLLM. Proxies all properties/methods. On everychat()call: extracts user text, consumes pending interruption context ([INTERRUPTED]enriched message with spoken text + last 10 assistant messages from JSONL), firesfirePipelineFastBrain()in background. Builds + watches the summary index lazily on first question. ExposesinterruptAgent(),abortAgent(),rewindAgent(),sendPrompt()for fast brain agent control.agent/src/pipeline-fastbrain.ts— Pipeline fast brain: Gemini Flash AFC (Automatic Function Calling) agent. 3 tools:search_session(ripgrep over the summary index, then byte-offset reads of full content),get_recent(most recent session activity),emergency_stop(kills + restarts the main Codex agent with an[EMERGENCY STOP]prompt that includes the user's recent messages and recent activity). OnegenerateContentcall handles the whole loop via AFC, capped at 4 calls.agent/src/Codex-auth.ts— Codex OAuth flow for headless/cloud environments. Auth priority:CLAUDE_CODE_OAUTH_TOKENenv →~/.Codex/.credentials.json→Codex auth status --jsonCLI check → interactiveCodex setup-tokenvianode-pty.resolveClaudePath()walks shellwhich, common paths (homebrew/nvm/Linux), andnpm bin -g. The pty's auth URL output is captured and surfaced via callback so the frontend can show it; the user pastes the code back, fast brain forwards via callback.agent/src/voice-io.ts— Factory functions for STT (Deepgram Flux with semantic turn detection), TTS (Deepgram/OpenAI/ElevenLabs/Gemini), VAD (Silero), and realtime model creation (createRealtimeModelFromConfig()).agent/src/turn-detector-shim.ts—CloudTurnDetectorimplements LiveKit's_TurnDetectorinterface without requiringJobContext/ worker framework. CallsLIVEKIT_REMOTE_EOT_URLdirectly viafetchfor end-of-turn probability. Falls back to1.0(always end of turn) when the env var is unset, letting STT endpointing handle turn detection.agent/src/status-manager.ts—StatusManager(singletonstatusManager) tracks backgroundTaskStatusrecords (pending/running/completed/failed). Used for reporting interim progress to the voice model.getLatestProgressUpdate()returns + clears the latest unspoken update,getStatusUpdate()returns a natural-language summary,clearReportedTasks()GCs completed tasks older than 2 minutes.agent/src/codex-llm.ts/agent/src/codex-handler.ts— Optional alternative LLM wrapper for the OpenAI Codex SDK (@openai/codex-sdk).CodexLLMextendsllm.LLM, persists a single CodexThreadacross user turns. Currently not wired into the default voice flow but available for swapping in.agent/src/bridge-llm.ts—createBridgeLLM()factory that returns a Gemini or GPT-4o LiveKit LLM instance for "bridge LLM" voice setups (a conversation manager LLM separate from Codex). Exists for future pipelined voice configurations; not used by the default flow.agent/src/Codex-handler.ts— StandaloneClaudeHandlerclass wrapping the Agent SDK with permission interception. Predates the persistent-sessionClaudeLLM; kept around but not used by the default voice flow.agent/src/meeting-output.html— Output Media webpage for Recall.ai bot audio (WebSocket client served atGET /meeting-output).
Frontend:
frontend/src/components/VoiceRoom.tsx— Main UI component (~2000 lines): voice visualization, chat (withMessageContentfor inline images and download cards), permission UI, session management, always-visible files panel with session artifact persistence, Codex OAuth modal, meeting join controls.frontend/src/components/MarkdownMessage.tsx— Markdown renderer with syntax highlighting (highlight.js + rehype).CodeBlockacceptsReact.ReactNodechildren (notString()) to preserve rehype-highlight spans.extractText()walks React tree for copy button. ExportsMermaidBlockfor inline mermaid diagrams.frontend/src/components/SessionBrowser.tsx— Past session browser, scans across all Codex projects.frontend/src/components/FilesExplorerModal.tsx— Full-screen files explorer modal with type badges, copy/copy-all, and inline rendering of plans/diagrams/notes/HTML.frontend/src/components/LogsDrawer.tsx— Bottom drawer for debug message log (user/assistant/system) with unread badge.frontend/src/components/SetupWizard.tsx— 6-step env setup wizard for first-time local users (LiveKit + Anthropic + voice provider keys), generatesagent/.envandfrontend/.env.localcontent.frontend/src/lib/setup.ts— Pure setup utilities:EnvConfig,generateAgentEnv(),generateFrontendEnv(),validateLivekitUrl(),validateAnthropicKey(),checkAgentHealth(). Used bySetupWizard.frontend/src/lib/sessions.ts— Client-safe session helpers (no Node imports).formatTime()for relative timestamps;SessionInfointerface.frontend/src/lib/daytona.ts— Server-only sandbox provisioning (see "Cloud Sandboxes" section).frontend/src/lib/supabase.ts/supabase-browser.ts/supabase-server.ts— Supabase client factories for browser, server, and middleware contexts.frontend/src/app/api/token/route.ts— LiveKit JWT token generation with metadata (provider, voiceArch, sessionId, workingDirectory).frontend/src/app/api/instance/route.ts— User instance CRUD (Supabase-backed).frontend/src/app/api/sandbox/route.ts— sandbox CRUD (Sprites or Fly Machines, vialib/cloud).frontend/src/app/page.tsx— Landing page: Google/GitHub OAuth + guest connect.frontend/src/app/dashboard/page.tsx— Dashboard: recent chats, settings (connectionModelocal/cloud), agent health, profile.frontend/src/app/chat/page.tsx— Voice chat wrapper that auto-resolves the agent URL (cloud sandbox or local) and mountsVoiceRoom.frontend/src/middleware.ts— Supabase auth session middleware.
Data Channel Protocol
Frontend ↔ Agent communication uses LiveKit data channels:
- Agent → Frontend (
topic: 'osborn-updates'):tool_use,tool_result,tool_blocked,agent_state,agent_ready,permission_request,claude_output,assistant_response,user_transcript,task_completed,plan_file_updated,plan_file_content,research_artifact_updated,research_artifact_content,research_task_started,session_resume_set,session_resume_failed,session_artifacts,mcp_toggle_result,mcp_servers_changed,mcp_status,checkpoint_captured,session_switched,current_session,fast_brain_response,meeting_joining,meeting_joined,meeting_left,meeting_error,claude_auth_url,claude_auth_success,claude_auth_error,skills_status,agents_status - Frontend → Agent (
topic: 'user-input'):permission_response,user_text,resume_session,continue_session,switch_session,mcp_toggle,get_mcp_status,session_selected,get_plan_file,get_research_artifact,get_session_artifacts,get_current_session,join_meeting,leave_meeting,claude_auth_code,get_skills,set_agents,skill_get,skill_add,skill_fork,skill_remove,get_agent_prompt
Authentication & Multi-User
- Supabase Auth: Google + GitHub OAuth via
@supabase/ssr. Callback at/auth/callback. - Database: Supabase Postgres with RLS. Tables:
instances(user→server URL),agent_sessions,always_allow_paths. - Instance API:
GET/POST /api/instance— stores user's agent server URL + LiveKit room name. - File uploads: Supabase Storage bucket
osborn-storage. Images/files uploaded → public URL sent via data channel.
Cloud Sandboxes (Self-Hosted Daytona)
Each user can be provisioned an isolated Linux sandbox running their own osborn agent + Codex CLI, instead of running the agent locally. Provisioning is handled by frontend/src/lib/daytona.ts against a self-hosted Daytona instance at daytona.voice-native.com (Hostinger VPS, Caddy + Let's Encrypt). Full deployment notes are in DAYTONA-SETUP.md.
Key files:
frontend/src/lib/daytona.ts— Server-only sandbox library. Raw HTTP (the@daytonaio/sdkis buggy with self-hosted). Functions:createSandbox,findUserSandbox,startSandbox,stopSandbox,deleteSandbox.getPlatformEnvVars()injects platform infra keys (LiveKit, Deepgram, OpenAI, Google, Recall, Smithery) — NOT user authfrontend/src/app/api/sandbox/route.ts— Next.js endpoint for sandbox CRUD. Backed by Supabase auth — each user gets exactly one sandbox labeled{ userId, app: 'osborn' }frontend/supabase/migrations/002_sandbox_support.sql— Addssandbox_id+sandbox_urlcolumns toinstancestable
Provisioning steps in createSandbox():
POST /api/sandboxwithimage: 'node:22',env,target: 'us',labels,autoStopInterval: 0(auto-stop disabled — see "disk-fill bug" below),autoArchiveInterval: 10080- Poll
GET /api/sandbox/{id}untilstate === 'started'(~10–25s) waitForToolboxReady(): Pollecho readyvia toolboxprocess/executeuntil it succeeds. Daytona flipsstatetostarted~3-6s before its toolbox reverse-proxy can resolve the container IP; without this poll the next exec call gets400 failed to resolve container IP, the install/start step silently fails, the API returns 500, the dashboard ignores it, and the user is left with a "running" sandbox that has nothing on port 8741 (reproduces as 502 Bad Gateway in chat after Resume).sudo env PATH=/usr/local/nvm/versions/node/v22.14.0/bin:$PATH npm install -g osborn@latest @anthropic-ai/Codex(~60s)- Symlink step:
sudo ln -sf /usr/local/nvm/.../bin/{node,osborn,Codex} /usr/local/bin/so they're in every user's default PATH (including root's, including any spawn lookup) mkdir -p /home/daytona/workspace && cd /home/daytona/workspace && sudo -E setsid nohup env HOME=/home/daytona OSBORN_CWD=/home/daytona/workspace PATH=... osborn >> /tmp/osborn.log 2>&1 </dev/null & disown—OSBORN_CWDis forced inline (not just from sandbox env) to defeat any stale value baked into older sandboxes' persisted env field- Poll
curl http://localhost:8741/healthuntil 200 (up to 60s) - Return
{ id, status: 'running', previewUrl: 'https://8741-{id}.daytona.voice-native.com' }
autoStopInterval: 0 — disk-fill bug: Self-hosted Daytona has a chronic backup-system bug. Every auto-stop fires a CREATE_BACKUP job that races a STOP_SANDBOX job; the stop wins (millisecond commit vs second commit), leaving the backup context canceled. The few backups that DO win are accumulated forever — backup.manager.ts has 4 cron jobs that CREATE backups but ZERO that delete them, and deleteBackupImageFromRegistry() (docker-registry.service.ts:710) is dead code with no callers. Hit 100/100 GB on Hostinger after one day of debug; recovery required SSH + manual docker image prune + registry GC. Defense in depth: (1) autoStopInterval: 0 here so backup cycles only fire on explicit stops; (2) /etc/cron.daily/daytona-backup-prune on the VPS keeps the latest 2 backups per sandbox. Trade-off: sandboxes stay running until explicitly stopped — fine on a single-tenant VPS where compute is already paid for, but re-enable auto-stop only AFTER patching backup.manager.ts if scaling to many users.
Background process detachment — DO NOT use bash -c 'while true; do osborn; done' supervisor wrappers. Even though that looks cleaner than letting osborn self-exit, it has a fatal bug: the bash outer process inherits the toolbox process/execute stdout/stderr pipe and never closes it. The toolbox endpoint waits indefinitely for the pipe to close before returning, the Next.js fetch hangs for the full undici 5-minute headers timeout (UND_ERR_HEADERS_TIMEOUT), and startSandbox() returns null with a misleading "fetch failed" message. Symptom is identical to the toolbox-race bug: Resume click hangs forever, dashboard shows "running", chat connect 502s. When osborn is the immediate child of nohup, Node closes the inherited stdio fds during its own logging setup, the toolbox sees the close, and exec returns in ~2s. Trade-off: no auto-restart on osborn's self-exit path — but that self-exit is a separate bug that should be fixed in osborn (don't process.exit(0) when no process manager exists), not papered over with a wrapper that breaks startup.
Critical sandbox patterns:
OSBORN_CWDMUST match the directory we create + cd into. Earlier bug: env var was set to/root/workspace(which doesn't exist and is unreadable to non-root), so when osborn passed it ascwdto the SDK'schild_process.spawn, spawn errored ENOENT and the SDK reported the misleadingCodex executable not found at .../cli.js. Fix:OSBORN_CWD=/home/daytona/workspaceto match themkdir -p /home/daytona/workspace && cd /home/daytona/workspacein the start command.- osborn runs as root via
sudo -E— running as thedaytonauser hit EACCES on subprocess spawning.-Epreserves env vars from the sandboxenvfield.HOME=/home/daytonais forced so OAuth credentials persist in the same place across user/root contexts. sudostrips PATH — every install/start command must explicitly preserve PATH viasudo env PATH=/usr/local/nvm/versions/node/v22.14.0/bin:$PATH .... nvm's bin dir isn't in root's default PATH.- Background process detachment —
nohup ... &alone doesn't survive the toolboxexecuteCommandreturning. Needsetsid(detach from controlling terminal) ANDdisown(detach from parent shell). - Per-user Codex OAuth — first user message in a fresh sandbox triggers
Codex setup-tokenvia pty inside the sandbox. The OAuth URL surfaces via theclaude_auth_urldata channel message. User opens it, pastes the code back via the auth modal, token persists at/home/daytona/.Codex/.credentials.json. SurvivesautoStopInterval(15min idle → stop, fs preserved). - No keepalive ping — nothing resets Daytona's idle timer from the chat page. The chat page stops the machine and shows an idle overlay after 15min with no voice activity.
@daytonaio/sdk workarounds (raw HTTP only):
| Bug | Workaround |
daytona.list/create/get throw on undefined fields | Use raw fetch against /api/sandbox |
SDK uses envVars/region, API expects env/target | Use API field names directly |
Toolbox URL: :4000 cloud vs /toolbox path self-hosted (HTTPS via Caddy) | getToolboxBase() detects protocol |
list() returns [] self-hosted, {items: []} cloud | data.items || data |
Local vs Cloud Mode
frontend/src/app/dashboard/page.tsx settings panel writes localStorage['osborn-connection-mode'] ('local' or 'cloud'). The chat page reads this on mount:
'local'(default) — usesagentUrlfrom query param / localStorage as-is (typicallyhttp://localhost:8741)'cloud'— calls/api/sandboxto find/start the user's sandbox, setsagentUrlto itspreviewUrl. Auto-starts a stopped sandbox if needed
The local-mode branch must NOT touch /api/sandbox — earlier bug had it unconditionally fetching the sandbox, so local mode would hijack the user's connection to the cloud sandbox if one existed.
Cloud Sandboxes (Fly.io Sprites — current production system)
Sprites (frontend/src/lib/sprites.ts) replaced the self-hosted Daytona setup in April 2026 and is the current production cloud-sandbox system. The Daytona section above is preserved for historical reference; daytona.ts is no longer active.
Sprites are persistent Linux sandboxes (Ubuntu, Node 22, 100GB NVMe) managed by Fly.io. Required env: SPRITES_API_TOKEN in frontend/.env.local.
Key files:
frontend/src/lib/sprites.ts— Provisioning, lifecycle, fs API helpers, marker bootstrap, warm-wake handling.frontend/src/app/api/sandbox/route.ts— Same endpoint as the Daytona version; switched-out backend.agent/src/index.ts—/health,/events(SSE keepalive),/room-code,/meeting-output,/sessionsHTTP API.
Architecture quirks tracked in docs/critical-patterns.md ("Sprites cloud-sandbox patterns") and CHANGELOG.md (v0.8.30–0.8.38 entry):
- Unique sprite names per
createSandbox:generateUniqueSpriteName(userId)adds a base36 timestamp suffix.findUserSandbox(userId, knownSandboxId?)reads the actual sprite name from Supabase as source of truth. Required because Sprites' API gateway can develop "stuck routing" entries per sprite name. - Restart service on warm-wake: When
startSandbox()resumes a sprite that was warm AND has marker bootstrap, itrestartService()to give the agent a fresh process with a fresh LiveKit WebSocket. CRIU snapshot preserves the local socket state but LiveKit Cloud has evicted the agent during hibernation; without process restart the agent is a "ghost" in the room (in-memory state says "Connected", but real connection is dead). - Never restore checkpoint on transient API failure:
startSandbox()tracksserviceCheckSucceededseparately. The destructiverestoreCheckpoint()only fires when we positively know the service lacks marker logic — never when the API call to determine that just transiently 503'd. Prior version silently restored on 503s, wiping.credentials.jsonand session JSONLs. - Marker bootstrap:
buildOsbornBootstrap()writes/home/sprite/.osborn-installed-versionafter install. Subsequent restarts compare WANT vs marker and skip install when they match. The bootstrap also emits a "Session inventory (container view)" log at boot showing JSONL counts per project — visible via Sprites' service-logs API for layer-divergence diagnostics. - Two-click delete confirmation: Trash icon arms on first click, deletes on second within 4s. Sprites does NOT soft-delete (verified by probing 6 different undelete endpoint shapes — all 404). Once deleted, overlay + persistent disk + checkpoints are unrecoverable.
- fs API ≠ container view:
GET /v1/sprites/<id>/fs/list|readreads persistent disk; the running container reads through the CRIU overlay. They can desync.fs/writereturns 405 on POST but works on PUT — yet writes via fs API land on persistent disk and are NOT visible to the running container at the same path. process.cwd()is/home/sprite/workspacein production (set viaOSBORN_CWD), NOT the package install directory. Files shipped with the npm package (e.g.meeting-output.html) must resolve via ESM__dirname(fileURLToPath(import.meta.url)+dirname). The build script copies static files todist/so they ship with the package.- Recall.ai bot payload field names:
recording_config.transcriptis a dict (omit iftranscription_optionsis set);output_media.camera.kindis the field (NOTtype).RECALL_REGIONenv var selects the regional endpoint (defaultus-west-2); 401 with region-mismatch detail if your token belongs to a different region.
Frontend Routes
/— Landing/login (Google/GitHub OAuth + guest connect). Authenticated users redirect to/dashboard./dashboard— Recent conversations, agent health, settings, user profile. Click chat →/chat./chat— Auto-connects to agent, wraps VoiceRoom. Disconnect → back to/dashboard./auth/callback— Supabase OAuth code exchange./api/token— LiveKit JWT token generation./api/instance— User instance CRUD.
File Attachment Flow
- Frontend: user attaches file → uploads to Supabase Storage → gets public URL
- Data channel: sends
{ type: 'user_text', content: 'text', files: [{ name, type, url }] } - Agent
user_texthandler: buildsfullContentappending[Image: name](url)or[File: name]\ncontent - Frontend rendering:
MessageContentcomponent renders images as<img>, files as download cards
Session & File Storage
- Sessions:
~/.Codex/projects/<slug>/as.jsonlfiles (Codex's native storage) - Session workspace:
~/.Codex/projects/<slug>/osb/<session-uuid>/(spec.md + search index) - Session scanner:
listAllClaudeSessions()scans ALL project folders, returns sessions sorted by mtime - Legacy:
.osborn/sessions/and.osborn/research/paths still accepted by write hooks for backward compat - Plan files:
~/.Codex/plans/ - Config:
~/.osborn/config.yaml(auto-created on first run)
MCP Server System
Status (#501): the configured MCP servers (config.yaml, catalog toggles) are NOT passed to the SDK query, so the UI shows a note instead of toggles; the backend below is kept but inert. MCP servers would extend Codex with external tools (GitHub, YouTube, etc.). Three transport types:
- stdio (local): Spawns a local process (
npx -y @modelcontextprotocol/server-...). No auth needed. - http (cloud): Standard Streamable HTTP MCP endpoints. Note: Codex Agent SDK has a known bug (#18296, #7290) where
type: 'http'forces OAuth discovery on all HTTP servers, ignoring configured auth headers. As a workaround, Smithery servers use thesdkproxy (see below). - sdk (in-process proxy): Used for Smithery cloud servers via
smithery-proxy.ts. Uses@smithery/api/mcpcreateConnection()to get a workingStreamableHTTPClientTransport, connects an MCPClient, lists remote tools, then wraps them in a localMcpServerpassed as{ type: 'sdk', name, instance }to the Codex SDK.
Catalog (MCP_CATALOG in config.ts): Built-in server definitions. McpCatalogEntry supports stdio (command, args, env) and http (transport, url, requiredHeaders) fields. For Smithery servers, the URL is used by smithery-proxy.ts to extract namespace/connectionId.
Key functions in config.ts:
buildMcpServersForKeys()— Merges catalog defaults with user config overrides for non-Smithery servers (stdio)getMcpServerStatusList()— Returns availability status for UI toggles. Checks env vars for stdio, headers for httpgetMcpToolPatterns()— Returnsmcp__<name>__*glob patterns forallowedTools
Smithery proxy (smithery-proxy.ts):
createSmitheryProxy(config)— Async. Connects to Smithery, discovers tools, creates proxyMcpServer. ReturnsMcpSdkServerConfigWithInstancedestroySmitheryProxy(name)— Cleans up client/server connectionsparseSmitheryUrl(url)— Extracts{namespace, connectionId}fromapi.smithery.ai/connect/.../mcpURLsisSmitheryUrl(url)— Checks if a URL is a Smithery Connect endpoint
Toggle flow (no client sends it): mcp_toggle → index.ts checks if Smithery URL → if yes, createSmitheryProxy() builds type: 'sdk' config → currentLLM.enableMcpServer(key, config) → stored on the ClaudeLLM, but not currently passed to any query() (#501)
Init logging: ClaudeLLMStream.run() logs ✅ MCP server <name>: connected or ❌ MCP server <name>: <status> from the SDK's system init message.
User time (guiding principle)
Osborn exists to shorten the path from idea to done, so a user's time and effort in a conversation is never wasted (#381). Every change states whether it saves or costs the user time, and why, in the "User time" section of its PR description. A change that adds waiting, clicks or questions says why it is worth that cost.
Critical Patterns
Bug fixes and gotchas (persistent session lifecycle, voice queue timing, Gemini quirks, research batching, Smithery proxy, etc.) live in docs/critical-patterns.md. Read that file when debugging anything non-obvious. Representative first entry:
- Self-healing CWD fallback chain:
index.ts main()walks[OSBORN_CWD env, config.workingDirectory, process.cwd()]and picks the FIRST entry whose path actually exists on disk. Blindly trusting any of these has bitten us — e.g. cloud sandboxes hadOSBORN_CWD=/root/workspacebaked in but/rootisdrwx------and the dir doesn't exist, so the SDK'schild_process.spawn(node, [cli.js], { cwd })errored ENOENT and reported the misleading "Codex executable not found at .../cli.js".process.cwd()is the ultimate safety net — it exists by definition.
Prompt System
Every prompt layer (realtime teleprompter, research system prompts, fast brain, spec consolidation, proactive loop, voice-queue injection prefixes, etc.) is centralized in prompts.ts and documented in docs/prompt-system.md.
TypeScript Config Notes
- Agent:
strict: false, ESM (module: ESNext,moduleResolution: bundler,target: ES2022) - Frontend:
strict: true, path alias@/*→./src/* dotenv/configmust be the first import inagent/src/index.ts(env vars needed before other modules load)
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

