cconnect / backend
CLAUDE.md6 starsChanged 14 days agoMITView on GitHub
FastAPI bridge between the CConnect apps and Claude Code, on the user's PC. It drives the CLI through claude-agent-sdk on the subscription: core/sdk.ensure_subscription_auth() drops ANTHROPIC_API_KEY, which would otherwise win and bill API credits. The SDK import is deferred inside claude_runtime because the SDK upgrades itself on startup (sdk_auto_update). - core/app.py — the app (core.app:app): router auto-discovery, gzip, catch-all 404. - core/cli.py — the cconnect command and the supervisor that runs uvicorn as a child. run.py is the checkout's entry. Always…
- Reads credentials
- Installs packages
In this repository2 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- client/CLAUDE.mdCLAUDE.md
The file
We split this CLAUDE.md into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 56
Every conversation CLI gets its environment from claude_runtime._cli_env.
- Very specific: line 117
Every event is typed in schemas/chat_events.py.
- Distinctive: line 239
Every record the server keeps lives in SQLite (WAL), never in a loose JSON file.
- Distinctive: line 246
Every table and column carries an English comment, in the migration and in the model.
- Very specific: line 305
Every query has a deadline: the engine's statement timeout, or a timer that calls the DBAPI's cancel / interrupt.
- Very specific: line 348
Every route and tool takes the key (devices in KEYED_CAPABILITIES).
≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.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
CLAUDE.md — backend
FastAPI bridge between the CConnect apps and Claude Code, on the user's PC. It drives the CLI
through claude-agent-sdk on the subscription: core/sdk.ensure_subscription_auth() drops
ANTHROPIC_API_KEY, which would otherwise win and bill API credits. The SDK import is deferred
inside claude_runtime because the SDK upgrades itself on startup (sdk_auto_update).
[app] ──WS /api/chat/ws──> chat router ──> live_sessions ──> claude_runtime ──> SDK query()
──REST /api/sessions ─> sessions router ──> services/sessions (~/.claude/projects JSONL)
──REST /api/shared ───> shared router ──> backend/data/shared/
──REST /api/claude ───> claude router ──> claude_assets (read) + claude_manage (mutate)Layout
core/app.py— the app (core.app:app): router auto-discovery, gzip, catch-all 404.core/cli.py— thecconnectcommand and the supervisor that runs uvicorn as a child.run.pyis the checkout's entry. Always one worker: every registry lives in memory. WithCCONNECT_LIFELINE=1the server stops when its stdin pipe closes, so it never outlives the desktop app; uvicorn getsstdin=DEVNULL, or Windows deadlocks on the inherited pipe. The runtime record names the supervisor (SUPERVISOR).--detachover a running server stops it with the stop flag and waits for that supervisor to exit, whoseatexitdrops the funnel, before exposing again; it reports success once the recorded server itself listens on the port. On Windows an installed release never upgrades from inside its own environment (uv cannot replace theScriptsof a running python):core/self_updatehands the upgrade to a detached PowerShell that waits until nothing runs fromsys.prefix, then restarts a detached backend. A server that is not detached refuses, and the desktop app stops its own and runs the commandcconnect update --planprints.core/—paths(the path table;INSTALLEDpicks the data folder),release,config,db/models/migrations/,settings_defs/settings_store,responses(the envelope{success, status, message, data}),ws(the handshake:accept_authorized,opening_message,stream_watch),process_job(Windows job object that takes child processes down with the server).core/packs/— built-in packs and the pack format (schema.json,builtin.json); the client build and Tauri read them too, as they docore/scripts/page_icon.js.core/prompts/— the system prompt pieces (CCONNECT.md,BLOCKS.md,BROWSER.md,INSTALL.md,MODS.md,SUGGESTIONS.md,TOOLS.md). User-owned prompts (USER.md, per project) live indata/config/prompts/and are emptied, never deleted.{{SHARED_URL}}becomescconnect://shared, never a host: the prompt is fixed when the CLI session starts, and the app swaps the scheme for the server it talks to (shared_schemein health).middleware/—public_auth,security,error_handler.routers/— thin: validate, call a service, returnapi_response().services/— all the logic, one module per integration. Watchers (chat_list,directory_watch,project_watch) runwatchfilesin their own thread, never on the event loop.chat_listmerges a chat's live state (activity,resident) under its lock when it stores a scan, never while scanning.project_watchnever recurses (on Linux that is an inotify watch per folder): it watches the folders the clients send as open, the ones git tracks and each.git.services/accounts/cli_login— an account is only its credentials: the CLI runs on the primary config withCLAUDE_SECURESTORAGE_CONFIG_DIRset to the account folder. Sign-in and the models, plan and fast mode CConnect offers useidentity_env(the account folder as the whole config). Sign-in goes through the CLI's control requests (claude_authenticate,mcp_authenticate), never a pseudo-terminal.wait_mcpwatches.credentials.jsonbecause the CLI reports no event when an MCP login finishes.login_expirycaches per.credentials.json.- Every conversation CLI gets its environment from
claude_runtime._cli_env; a provider model without a known window getsCLAUDE_CODE_DISABLE_1M_CONTEXT=1. mcps/— the in-process MCP server Claude sees ascconnect.
Auth
PUBLIC_ACCESS_TOKENapplies only withCCONNECT_AUTH_ACTIVE=1.PublicAuthMiddlewaregates every/api/*except/api/healthand the loopback routes that carry their own token (/api/agents/browse,/api/mcp/agent/<token>,/api/mcp/lazy/<token>,/api/pages/<id>/…, since an iframe cannot send headers). WS handshakes check it inaccept_authorizedbefore accepting.SECURITY_KEY(X-Security-Key,core/access.key_matches()) guards what belongs to the machine: shells, git-ignored files, git writes, deleting a server pack, an agent's environment, saved database connections and their drivers. Each route checks it itself, and it only gates while the Bearer gate is on (gated()). Reads the panels need before asking (repos,databases/engines) stay outside it.- A turn sent without the key loses the
terminalanddatabasescapabilities (core/access.authorize, perprompt), and the PreToolUse hook keeps Claude offpaths.ENV_FILEand the key-gated tools. The capabilities are part of the persistent CLI'smark, so unlocking mid-chat restarts it. --expose tailnetskips the token.--expose caddyonly advertises, so--stopnever closes a Funnel it did not open (.detached.provider).
HTTP API
Everything returns api_response(); routers are auto-discovered from routers/. A route that
answers with a file uses FILE_HEADERS (Cache-Control: no-cache), or a rewritten file shows
its old copy.
The shared and project file routes share their renditions: attachments.rendering decides what
?size= and ?fit= make (image, still of a video, cover of an audio file) and
responses.rendition_response answers it with an ETag keyed by that variant, so a change in how one
is made needs a new variant name. services/file_info.describe reads a file's own metadata
(Pillow, PyAV, pypdf); PyAV also opens text and images, so media counts only with an audio stream or
a video stream with a duration. Transcript slices are cursor-based (before_index), and while a live session has
events to replay the tail is cut at turn_start_index so a turn never arrives twice. Uploads
stream to disk, so PUT is outside MAX_BODY_SIZE.
A plugin's icon (icon in its plugin.json, inside the plugin) and an MCP server's (icons in
the serverInfo its stored catalog holds, else its plugin's) reach the apps only through
/claude/plugins/icon and /claude/mcp/icon (services/asset_icons). An SVG goes as it is, any
other image is decoded and encoded again, and an https: icon is fetched by the server, without
credentials or redirects; the apps never fetch an icon's own URL.
A relative-path plugin of a marketplace added from a local path is read where the CLI loads it, in
place (_in_place), not from its copy in cache/. A plugin's MCP servers are read in the CLI's order: its .mcp.json, then each mcpServers shape
(a JSON file, an inline map, a .mcpb/.dxt bundle named by its own manifest, or a list of them).
A bundle's config keeps ${__dirname}, so it stays with the CLI. listed_plugins asks
claude plugin list --json which plugins the CLI refuses for their engines["claude-code"] range,
and only when one declares it. A plugin's latest is its marketplace catalog's version when it differs
from the installed one, read from the local copy, so it moves only when that marketplace is updated.
A plugin update is queued in services/plugin_updates and runs one CLI command at a time; its lock
also serializes the other plugin and marketplace actions, which write the same files. The update
runs with --json, and one the CLI reports as up_to_date reloads no chat. Each plugin's
state (queued, updating, failed with the CLI's message) travels in /claude/plugins and as
plugin_updates on the list socket, with finished naming the ones just done and whether a reload
was held.
Chat socket (/api/chat/ws)
- Every event is typed in
schemas/chat_events.py.python -m schemas.contractwritesschemas/chat_events.json, which the app'snpm run checkturns into types; the release runs it with--check, andCCONNECT_CONTRACT_CHECK=1validates each event as it is sent. - Events are seq'd per session except the control ones (
ready,permission_mode,history_chunk,usage,session_info,ask_*,activity) and the mods ones.mod_toast/mod_invalidate/mod_focus/mod_scroll/mod_requestare never replayed, and everymod_rendergets amod_tree, null when no CLI is attached. - Re-attaching with
channel+last_seqreplays only when the outbox covers it (LiveSession.covers); otherwisereadysaysstaleand the app reopens from the transcript. Re-attaching never changes the chat's account (readycarries it, onlyset_generationchanges it). Model, effort and permission mode answer only the socket that set them. file_changereplacestool_use/tool_resultfor Edit, Write, MultiEdit and NotebookEdit.db_query/db_executecarryqueryandstatements(mcps/databases.statements_of) and, like shared files, always arrive whole whatevershow_tool_usesays.- An
api_errortakes itsseverityand itsresume(continueorretry) from the CLI's error category, inservices/api_errorsalone, live and on resume. The app offers that action, and Continue afterinterrupted, only on the last row of an idle chat. - The live
compact_boundaryusescompact_metadatawithpre_tokens/post_tokens, not the transcript's camelCase, andcompactcarriesearlierforload_history(until=…). - The plan windows (
rate_limit) come only on a CLI's first turn, sousage.live_windowskeeps the last ones per account and sends them to every socket that attaches. - An ACP agent's chat (a
startthat names one) getsagent_stateandhistoryoutside the seq'd stream. Its rows come from the agent (session/load); the server stores only session ids of agents withoutsession/listand the titles the user gives. - Context size travels only in
context, and clients assign it, sonullclears the ring. It isinput_tokens + cache_read + cache_creationfrom eachAssistantMessage.usageand from the main conversation'smessage_delta(a provider can send0inmessage_start), andpost_tokenson a live boundary. A manual/compacthas no live boundary, so the router readslatest_compact()after the turn; a closed session readssessions.last_context_tokens.
Transcripts and compaction
services/sessions.get_session_messages normalizes the JSONL so resume equals live. The CLI's
format is not a contract; what currently holds:
_active_entrieswalksparentUuid(thenlogicalParentUuid) back from the last entry to drop rewound branches, only when some node has two or more children.- Compaction markers survive that walk (
_is_compact_marker): the summary hangs off the boundary while the conversation continues fromcompactMetadata.preservedSegment, so it looks like a dead branch. - Reading starts at
_last_compact_offset(file).session_segment(..., until=<boundary>)reads the stretch before a boundary, only when the user asks for earlier messages, andlist_checkpoints(..., until=…)answers{points, earlier}. The CLI rewinds nothing before the last boundary, so those points only fork. - Filter non-conversation entries (
queue-operation,attachment,file-history-snapshot,custom-title,mode,last-prompt…) by type, never by position. - A message from another Claude session is a meta
userentry withorigin.kind: "peer"; it is read fromorigin(name,body) live and on resume, never from the text around it. - A block a tool emits live when it runs (shared files, a pack export,
show_component) is rebuilt only when its call answered without an error (_ran), so a call a hook refused shows nothing on resume either. Tools mark their failures withreply(..., error=True). - The SDK writes
"entrypoint":"sdk-py", which hides a session fromclaude --resume. Each turn rewrites it to a space-padded"cli"in place, only over the bytes it wrote, in a worker thread.
Message queue
A prompt sent mid-turn is injected into the same turn: run_prompt runs the SDK in
streaming-input mode and drains the queue, rendering each item from the transcript
(_flush_users), so resume and live agree when the CLI joins messages. A task notification is
written twice, so LiveSession.shown_notices keeps what the tail already sent and
_flush_users skips it; a byte offset is not enough.
The turn's own prompt is handed over with a uuid like the drained ones, and the CLI replays it
(replay-user-messages) before that prompt's result, slash commands included. A result
that arrives before the replay belongs to a turn the CLI ran first on its own (a new CLI's
"didn't finish before the previous session ended" notice), so the turn goes on; ending there
left the prompt to arrive as a tail and the sender saw it twice.
Persistent sessions and mods
- With
persistent_sessionson,persistent_sessions.poolkeeps oneClaudeSDKClientper channel, keyed by cwd, account and scope.session_limitcaps chats holding a process (CLIs and ACP agents together) andregistry.trimreleases the least recently used idle ones. - The grace (
session_grace) is one timer, started when the last socket leaves or, if work is running, when it ends (_schedule_cooldown); nothing polls it. - A turn whose
markdiffers only in model or permission mode changes them live (PersistentSession.retune, inside the bound turn); any other difference (effort, mods, capabilities, scope…) or another account restarts the CLI. A change sent mid-turn (set_model,set_permission_mode) updates the resident's mark too, so the next turn does not repeat it. A turn the CLI starts on its own is adopted (own_turn) withresident(keep=True)and never reshapes the process. - A restart kills the CLI's background tasks, so while
LiveSession.tasks_alivea differingmarkdoes not restart: the model and permission mode change live (PersistentSession.retune) and the rest waits for a turn without tasks.retuneruns inside the bound turn, beforesettle(): the CLI answersset_modelwith a user line of its own, which an unbound pump takes for a turn of the CLI's and waits out. memory_reserveis read only before starting a process and on the system's low-memory signal (services/memory_pressure.py), never polled. Below it,registry.relievestops idle MCP servers, then releases idle chats, oldest first. A one-shot CLI always gets the no-background environment (_background_guard(kept=False)).- Mods use the CLI's internal UI protocol (
services/mods.py), which moves between versions: every request goes throughmods.request, which returnsNoneon failure.forget_plugindrops a disabled plugin's surface once its turn ends. control_requestsanswers what the SDK rejects as unknown: MCPelicitation(turned into the chat's form byelicitation) and the mods'ui_*.servewraps a persistent CLI's query andAnsweringa one-shot's transport.- Stopping the server closes the CLIs and agents first (
live_sessions.close_processes).
Local MCP servers on demand (services/mcp_lazy.py)
Each stdio MCP server of user, local or plugin scope reaches a chat's CLI as
{"type": "http", "url": ".../api/mcp/lazy/<token>"} under its own name. Project servers, the
disabled ones and any config with an unresolved ${…} stay with the CLI.
initializeand every list come frommcp_catalogs(keyed by command, arguments and environment), so the CLI starts with no server process. A server with no catalog starts as before while one is read in the background.- The real process starts on the first call (
_Link) with the environment the CLI would give it. Every start rereads the lists and sendslist_changedwhen they changed. - The first start per backend run goes through the launcher (
uvx,npx); later ones run the process it spawned directly (CCONNECT_MCP_SPAWNmarker), falling back to the launcher. Every start carries the marker, and Processes shows a marked tree as one part, like the CLI's own MCPs. - The proxy speaks the handshake era: it answers a newer
mcp-protocol-versionwith the 400 an older server gives. - mcp 2.3: one stateful
StreamableHTTPSessionManagerper server and CLI,json_response=False(JSON drops progress, logs and forms) andsession_idle_timeout=None._Proxyoverridesget_capabilities.stdio_clientneeds the whole environment passed. - A persistent CLI's servers close with it, a one-shot's at the end of the turn, and
release_idlestops unused ones when memory runs short.
Database (data/config/cconnect.db)
Every record the server keeps lives in SQLite (WAL), never in a loose JSON file. Files are only for prompts, packs, account folders, caches, logs and process files.
- The migrations are the schema (
core/migrations/versions/), each with a workingdowngrade(), run toheadon every start. Scaffold withalembic revision -m "<what>"and write it by hand;create_allis never called andcore/models.pymirrors the result. schema_migrationsstores each migration's SHA-256. A released migration is immutable.- Every table and column carries an English comment, in the migration and in the model.
- Timestamps are UTC ISO 8601 text (
Timestamp); the API answers epoch seconds where it did. - Triggers (all of them):
session_todos_touchedstampssession_todos.updated_at.
Settings and visibility
Model, effort, permission mode, streaming, CLI source and block visibility are backend-owned, in
the settings table. show_thinking / show_tool_use / show_file_change / show_compact take
full | label | off, applied the same live and on resume; label never strips an agent's
subtasks. Simple mode never hides file changes, shared files, query blocks, forms or the
task_* / agent_result events Running needs. Every write (settings_store.set / reset,
cli_settings.set / reset) ends in settings_store.announce, which pushes the whole
settings_changed payload on the list socket, so no client keeps a stale copy.
MCP server (mcps/)
- Each tool is a module-level
Definition(mcps/definition.py) named in capitals (DB_QUERY).make_tools(context)runs every turn and binds it to its handler; returning[]removes the module's tools from that turn. A turn-dependent description is areplace, and every text answer goes throughreply. A module whose tools reach key-gated things declaresneeds_key(name, args). - Families behind a setting are left out while it is off, key-gated ones need the key, and the
rest are deferred behind tool search.
eagerloads a tool up front (_metaanthropic/alwaysLoad, through mcp 2's handler API).guideputs the first paragraph of the description in the system prompt (TOOLS.md), which is what makes Claude reach for it. ask_componentandshow_componentsharemcps/components.py: every value is a string, anidmeans the element carries a value, labels travel as keys,show_ifalso drops the value, validation is client-side.mcps/media.pyis the one table of what renders inline.- Adding an element (no generator):
TYPES+LEAFand its line inDESCRIPTION/SHOW_DESCRIPTION;ComponentElementinclient/.../data/chatModels.tsandtoElementin.../services/chatSocket.ts; the{#if}chain inComponentBlock.svelte; the summary (componentSummary/summary), which must keepsecretvalues out of the chat; the validation (componentMissing/missing);en.jsonand the other catalogs.
Databases
core/databases/engines.json is the engine catalog (dialect, driver packages, port, read-only
preludes, timeout, binary literal, hidden schemas, URL options, quote, auto_increment,
identity_sync, identity_insert_on/off), with defaults and extends for the families.
Connections are file, server or url (custom, which borrows its backend's rules through
spec_of). Every data call takes a Scope (connection and database), one engine per scope.
- A driver install pins every requirement of
cconnectat its installed version, so it never moves the server's packages. Engines with the samepackagesshare one driver (driver_of). A driver counts as installed when its distributions are on disk (importlib.metadata). - An update keeps the drivers.
uv tool upgraderemoves everything its receipt does not list, sorepo.upgrade_commandrunsuv tool install --upgrade --with <installed drivers>(kept_packages), which also writes them into the receipt. - A database file opens without a connection (
open_file): the engine comes from the file's header (signature), the entry lives in memory under afile:id, andNullPoolholds no lock. - Nothing in
database_datatrusts the client. Reads and writes are told apart by sqlglot, failing closed: only SELECT, set operations, DESCRIBE, SHOW, EXPLAIN of a read and a PRAGMA without=read; anything else writes and takes the key. A read runs in a transaction that is rolled back, after the engine's read-only preludes. - Each statement answers on its own (
results, withkindandeffect). Writes return the rows touched wherereturningallows (clauseorcte). A CREATE or ALTER is reflected on its own connection right after it runs; an ALTER also carrieschanges. A statement no transaction admits (OUTSIDE_TRANSACTION) runs in autocommit afterrelease_others. - The WHERE filter must be one reading statement, with colons escaped and closed on a newline.
- Every query has a deadline: the engine's statement timeout, or a timer that calls the DBAPI's
cancel/interrupt. - Optional reflection runs in its own session (
_probe): a failed statement aborts the rest of the transaction in PostgreSQL and DuckDB. - Tables are rebuilt from columns and primary key, never autoloaded: duckdb-engine cannot reflect
under SQLAlchemy 2.1, so the catalog carries DuckDB's own
columns/primary_keyqueries anddeclared_typemaps types through sqlglot. - Claude's tools answer in text (
mcps/databases.render), read back bystatements_of, so the two change together. - Cells leave JSON-safe (
cell); exports keep full values: CSV with a BOM, SQL through each column's literal processor. - A SQL export is a dump built from the catalog, never
pg_dump(export_dump, for a table, a schema or the database): tables in foreign key order, indexes, streamed inserts, then views. Function defaults go in parentheses (SQLite). Sequence-fed columns useauto_increment,identity_syncmoves the sequence,identity_insert_on/offwrap SQL Server's inserts.
Devices
core/devices/tools.json pins the tools: Google's platform-tools archive per platform and
scrcpy's server, each with its URL, size and SHA-256. services/device_tools finds adb on the
PATH, in the SDK (ANDROID_HOME, ANDROID_SDK_ROOT, the default folders) or in
paths.ANDROID_TOOLS_DIR, where install() downloads what is missing; nothing is bundled.
services/adbspeaks adb's host protocol on its socket (%04xlength,OKAY/FAIL), starting the server when nothing listens. Pushes, installs, pairing's crypto and the emulator console go through the binary (run).services/devices.hubis the state:host:track-devices-lis a push stream andservices/discoverybrowses the Wi-Fi debugging services itself with zeroconf on every interface (adb's own discovery misses them on a machine with several adapters), so the panel never polls. Each authorized device is described once withgetpropand remembered indevicesby its hardware serial (ro.serialno), the same over USB and Wi-Fi; emulators are never saved. A QR pairing waits for the_adb-tls-pairing._tcpservice whose instance name is the one in the code, then pairs. A_adb-tls-connect._tcpservice named after a saved serial, or on a host paired this run, is connected once per address (_auto_connect), and a saved entry answers with the discovered address, so the port Android changes never has to be typed.- Emulators come from the AVD folder (
ANDROID_AVD_HOME, else~/.android/avd), never from a process, and start detached from the server with no snapshot. While one boots, its AVD name comes from the emulator console (adb.console), sincegetpropneeds adbd. services/device_screenruns scrcpy's server on the device (adb reversefirst,adb forwardwith a bounded connect retry when the device refuses reverse) and turns its stream into the browser pane's frame wire (services/frames): the config packet is prepended to every key frame, the codec string comes from the SPS, and viewers without WebCodecs get JPEGs decoded on a thread with PyAV. One session per device, shared by its viewers, stopped with the last one.- Every route and tool takes the key (
devicesinKEYED_CAPABILITIES); the panel's socket and each screen socket read it from their opening message. An APK to install is an absolute path on the machine (the panel's picker, the tool) or a path inside Shared or a project.
Configuration
Environment variables, declared in core/config.py. A checkout's backend/.env is loaded by
core/paths before any path is computed, so the supervisor and the server it runs agree on the
data folder and cconnect restart reaches both. The table lives in the root README.md only.
Conventions
- Routers stay thin; logic lives in
services/, new integrations get their own module. - No comments. A one-line descriptive docstring only when a constraint cannot be expressed in code.
- Imports at the top, except the deferred
claude_agent_sdk. - Subprocesses that print text use
encoding="utf-8", errors="replace"(Windows is cp1252). - Auto-reload only in a checkout on Linux/macOS, never in the installed package (every
pip installwould restart it), excluding the data folder andsys.prefix. On Windows it breaks the CLI subprocess, so restart by hand.
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.

