Architecture Overview
Sora is a local-first personal AI agent with several surfaces that share one runtime. The Android app and the Desktop client run the same Kotlin Multiplatform agent core, so sessions, approvals, Memory v3, timers, and workers behave identically on a phone and on a workstation. A self-hosted Relay connects devices, and every capability beyond the core ships as a signed plugin.
flowchart LR
subgraph Mobile["Android · apps/android"]
APP[":app · Compose client"]
SHELL[":shell · Alpine proot / Root"]
PAPI[":plugin-api · SDK 2.0.2"]
DESIGN[":design · 1.1.0"]
end
subgraph Desktop["Desktop · apps/desktop + apps/web"]
ELECTRON["Electron shell"]
WEB["React 19 workbench"]
end
subgraph JVM["JVM Host · apps/host"]
HOST["Ktor + SSE + sora CLI"]
end
subgraph Core["Shared KMP core"]
RUNTIME["core/runtime · agent loop, sessions, Memory v3"]
API["core/runtime-api · contracts"]
RELAYC["core/relay · CA-pinned client"]
end
subgraph Server["Self-hosted Relay · apps/relay"]
RELAY["Node 24 HTTPS/WSS"]
DB[("SQLite · relay.db")]
end
subgraph Wire["Protocol"]
PROTO["@sora/protocol · frames + vectors"]
end
APP --> RUNTIME
APP --> RELAYC
APP --> SHELL
APP --> PAPI
APP --> DESIGN
HOST --> RUNTIME
HOST --> RELAYC
RUNTIME --> API
RELAYC --> RUNTIME
WEB --> HOST
ELECTRON --> WEB
ELECTRON --> HOST
RELAYC <-->|"WSS / HTTPS · CA pinning"| RELAY
RELAY --- DB
RELAY --- PROTO
RELAYC --- PROTORepository layout
| Path | Stack | Responsibility |
|---|---|---|
core/runtime-api/ | Kotlin JVM | Contracts only: session and run types, tool approvals, tool catalog, memory scopes, jobs, timers, super/worker payloads |
core/runtime/ | Kotlin Multiplatform (JvmCommon + Android) | Agent loop, JSONL session engine, Memory v3 SQLite/FTS5, skills, MCP, jobs, timers, compaction, Orchestrator |
core/relay/ | Kotlin Multiplatform | Relay WebSocket/HTTP client, memory sync, remote worker gateway, Orch host handover |
apps/android/ | Kotlin · Compose · Gradle | Android client (:app), shell (:shell), design system (:design), plugin SDK (:plugin-api) |
apps/host/ | Kotlin JVM · Ktor · Clikt | Local HTTP/SSE daemon and sora CLI; bridges the Desktop browser and exposes the workspace API |
apps/web/ | React 19 · TypeScript · Vite | UI workbench used by the Desktop client and a browser |
apps/desktop/ | Electron · TypeScript · esbuild | Native window shell, tray, sora:// deep links, sidecar lifecycle, embedded browser host |
apps/relay/ | Node 24 · TypeScript | Self-hosted HTTPS/WSS service: pairing, presence, routing, Memory v3 sync |
packages/protocol/ | TypeScript | Canonical frames, validators, Memory v3 schemas, JSON vectors (@sora/protocol) |
plugins/ | Kotlin · .ddp | Official modules, third-party template, and E2E sample |
docs/ · docs-site/ | Markdown · VitePress | Repository docs and the bilingual public documentation site |
Module boundaries
The Gradle graph is enforced at build time by :verifyModuleBoundaries and :verifyPackageBoundaries:
flowchart TD
APP[":apps:android:app"]
HOST[":apps:host"]
SHELL[":apps:android:shell"]
PAPI[":apps:android:plugin-api"]
DESIGN[":apps:android:design"]
RLYC[":core:relay"]
RTM[":core:runtime"]
RAPI[":core:runtime-api"]
APP --> RLYC
APP --> RTM
APP --> RAPI
APP --> SHELL
APP --> DESIGN
APP --> PAPI
HOST --> RLYC
HOST --> RTM
HOST --> RAPI
RLYC --> RTM
RLYC --> RAPI
RTM --> RAPI
PAPI --> DESIGNcore/runtime-apidepends on nothing but Kotlin and serialization. It is the contract seam used by both hosts and by plugins.core/runtimeowns state and execution; it must not depend on Android or Ktor. Android-specific pieces live inandroidMain, JVM pieces injvmMain.core/relayprovides the Relay client and remote gateways. The Android app and the JVM Host open Relay connections on behalf of their devices.apps/hostis one JVM process: Ktor server, CLI, background jobs, and the Desktop browser bridge. The Web UI has no direct filesystem or process access; it talks HTTP/SSE to the Host.- The TypeScript workspace has its own boundaries:
@sora/protocolhas no runtime dependencies and is imported by@sora/relay;@sora/weband@sora/desktopcommunicate with the JVM Host, never with the Relay directly.
Shared Kotlin core
core/runtime-api defines the vocabulary every host shares: SessionBinding, RuntimeModels, ToolApprovalTypes (ToolRiskLevel, ToolApprovalReason, ToolApprovalDecision), QuestionContracts, MemoryContracts, JobContracts, BaseToolCatalog, SuperTypes, and provider defaults.
core/runtime implements the engine:
- Agent loop — built on the Sora Kotlin SDK (
pi-ai,pi-agent,pi-coding-agent,pi-mcp).SessionEngineandPiSessionEngineturn model responses and tool calls into session events. - JSONL sessions —
SessionJsonlHistoryOps,SessionCatalog,SessionIndex, andSessionMetaStore. Session JSONL files under~/.soraare the single source of truth; lists, pins, archives, and unread counts are projections. - Memory v3 —
MemoryDatabase(SQLite WAL + FTS5),MemoryBlockStorage,MemoryGraphStorage,MemoryRetriever,MemoryContextRenderer,MemoryAgentService, andMemorySyncStorage. Four budgets, proposals, audit history, consolidation leases, and incremental sync cursors. - Orchestration —
SuperOrchestrator,SuperTaskStore,SuperThreadEngine,LocalWorkerPool, andRemoteWorkerGatewaygive the coordinator separate worker sessions with their own JSONL history and approvals. - Execution plumbing —
JobRegistry,TimerService/TimerCron,RuntimeMcp/McpServices,SkillCatalog, and compaction live here so every surface gets the same semantics. - Host environments —
HostEnvironmentProviderandDynamicHostAccessresolve the execution tier (LOCAL,ADB,ROOT) and the matching file system and shell executor for each tool call instead of caching a snapshot at session creation.
core/relay adds RelayClient, RelaySocket (WSS with CA pinning and per-device tokens), RelayController, RelayMemorySync, and the remote worker gateway. RelayFrames.kt mirrors the TypeScript protocol shapes for the Kotlin side.
Android app modules
:apps:android:app is the Compose client, application id io.github.sadami3066.sora, minSdk 29, compileSdk/targetSdk 36. Its packages map to surfaces rather than layers:
| Package | Surface |
|---|---|
conversation/, ui/chat/ | Sessions, streaming turns, tool cards, approvals, queue and steering |
floating/ | Nebula Aura overlay and floating bubble |
ui/superagent/ | Orch coordinator and worker monitor |
screen/, vscreen/ | Screen capture/control and the background virtual display |
adb/ | Wireless-debugging shell daemon client with HMAC-SHA256 challenge-response |
plugin/ | Plugin loading, API-level checks, .ddp install and lifecycle |
market/ | Signed registry parsing, catalog, install/update |
arrange/, voice/, theme/, service/ | Mini-apps, voice, design tokens, foreground services |
The sibling modules are shared with the published SDK:
:shell— bundled Alpine Linux in user space throughproot, withLinuxEnvironment,PRootExecutor, and Root chroot support.LOCALmode runs here;ADBroutes through the shell daemon;ROOTuses a native root shell. Mode selection has explicit fallbacks (ADB_UNAVAILABLE,ROOT_UNAVAILABLE) so a tool never claims a privilege it does not have.:design— typography, light/dark tokens, icons, and components, published asdesign 1.1.0.:plugin-api— the binary-stable host-to-plugin ABI (API level 7, host UI API level 3), published asplugin-api 2.0.2.
Desktop stack
The Desktop client is three processes:
- Electron shell (
apps/desktop) — window state, tray,sora://deep links, auto-start, crash logging, auto-update checks, and theEmbeddedBrowserManager(WebContentsViewtabs, persistent/ephemeral partitions, element picker, CDP gate). The renderer is isolated (contextIsolation: true,nodeIntegration: false,sandbox: true) and served with a strict CSP. - React workbench (
apps/web) — React 19 + Vite. It renders chat, split previews, diff editing, terminal, git worktrees, management pages, and built-in browser controls from the Host API. - JVM Host sidecar (
apps/host) — Ktor CIO server on loopback plus thesoraCLI. The Electron main process starts it (host-manager.ts), waits for/api/v1/health, and passes the Bearer token from~/.sora/cache/serve.lock.
Communication is HTTP + SSE on 127.0.0.1: REST under /api/v1/* for state and actions, and the /api/v1/events stream for turns, tool calls, approvals, and run state. SSE connections authenticate with single-use tickets issued by /api/v1/auth/sse-ticket. Desktop browser tools are requested over a local endpoint implemented by Electron, so the agent never receives raw CDP access.
Self-hosted Relay
apps/relay is a small Node.js 24 service with no model or tool execution:
- HTTP —
/v1/health,/v1/ca, pairing (/v1/pair/enroll,/v1/pair/code), devices, profile, and thesuperhost/snapshot records. Memory v3 uses/v3/memory/push,/v3/memory/pull, and/v3/memory/consolidation-lease. - WebSocket —
hello/hello_ok,presence, routed frames, sync events, heartbeat, and capability negotiation. Payloads are bounded (8 MiB frames, 4 MiB route results). - Storage —
node:sqliterelay.db: accounts, hashed device tokens, pair codes, the memory graph, sequence counters, and leases. - Security — HTTPS/WSS only, CA fingerprint advertised so clients can pin it, revocable per-device bearer tokens, rate-limited enrollment, and bounded request bodies.
Configuration is entirely SORA_* environment variables (SORA_PORT, SORA_DATA_DIR, SORA_CERT, SORA_KEY, SORA_CA, SORA_PUBLIC_ORIGIN, SORA_LAN_ORIGIN). See Self-Hosting Relay.
Protocol package
@sora/protocol 0.1.0 is the canonical wire definition: client/server frame types and validators (frames.ts), Memory v3 sync schemas (memory.ts), HTTP DTOs (http.ts), and shared JSON vectors under vectors/. The Relay and both Kotlin clients validate against the same shapes, and the vector files are used by both TypeScript and Kotlin tests. Details are on the Wire Protocol page.
Plugin platform
A plugin is an Android Kotlin module that is never compiled into the app. It is compiled against plugin-api + design, packaged into a signed .ddp archive, and loaded in the host process after verification:
assets/plugin.jsondeclaresid,version,apiLevel,minHostVersion, capabilities, permissions, components, and the entry class.META-INF/plugin-signature.jsoncarries an Ed25519 signature over a canonical entry digest; the publisher identity is the signing key'skeyId.- The host verifies the signature and recomputes the
keyIdbefore install, pins the publisher on first install, re-checks the package hash before each load, and requires the same key for updates. - Plugins contribute tools, skills, prompt sections, hooks, and Compose UI. They run with the host UID and app permissions — signatures prove integrity and publisher continuity, not sandboxing.
Official plugins live in plugins/official/, third-party starters in plugins/template/, and the E2E fixture in plugins/sample/. Distribution goes through the ECDSA-signed Sora-Market registry. Start with Plugin Overview.
Request lifecycle
A single prompt crosses these boundaries:
sequenceDiagram
participant UI as "Android UI / Web UI"
participant Host as "Runtime host (Android app or apps/host)"
participant Engine as "SessionEngine + Agent loop"
participant Model as "Provider endpoint"
participant Tools as "Tool harness"
participant Store as "JSONL + Memory v3"
UI->>Host: prompt / steer / approval
Host->>Engine: run or resume session
Engine->>Model: messages + system prompt + tool list
Model-->>Engine: streamed text, reasoning, tool calls
Engine->>Tools: execute with approvals and hooks
Tools-->>Engine: tool results, artifacts, cards
Engine->>Store: append JSONL entries, memory writes
Engine-->>Host: session events (text, tools, approvals)
Host-->>UI: SSE / Compose state- Sessions are appended as JSONL first; UI projections read from that log.
- Approvals pause a tool call inside the runtime, surface a pending approval to the UI, and resume only after an explicit decision.
- Memory is written asynchronously: per-turn context is rendered from storage, and consolidation runs as its own agent with a cross-device lease.
- Multi-device traffic is the same event flow wrapped in Relay frames; remote sessions and workers are hosted by the device that owns them, and Orch handover transfers host ownership with a snapshot.
Invariants worth preserving
- JSONL authority: never treat a session index, UI cache, or memory copy as the source of truth.
- Dynamic environment: resolve shell mode and filesystem per tool call; fallbacks must be visible to the user and the model.
- Process steps are not answers: tool calls stream as execution records; deliverables render as cards or artifacts.
- Browser safety: Desktop browser actions respect site policy (
allow/ask/deny), pause/take-over state, and never trust anapprovedflag supplied by the model. - Orch isolation: coordinator state (
super/router) and worker sessions are separate engines; handover exports a bounded snapshot, and the previous host is revoked explicitly. - Update contract: only Android
vX.Y.Ztags are "Latest"; other components publish with--latest=falseso the in-app updater never picks a non-Android artifact.
Continue with the Tool Harness, Wire Protocol, or Contributing pages.
