A high-throughput, terminal-based AI coding assistant engineered for local workspace operations.
Architected on Bun, React 19, OpenTUI, Hono, Prisma ORM, Clerk OAuth PKCE, Polar usage metering, and multi-provider Vercel AI SDK streaming.
- System Architecture
- Design Decisions and Technical Trade-offs
- Operational Agent Modes
- Tool Execution Runtime and Security Boundaries
- Model Registry and Pricing Schema
- CLI Interface and Keybinding Architecture
- Monorepo Structure
- Getting Started
- System Requirements
- 1. Installation and Dependency Resolution
- 2. Environment Variable Configuration
- 3. Clerk OAuth 2.0 Identity Provider Configuration
- 4. Polar Usage Metering and Credit Setup
- 5. Database Provisioning and Schema Sync
- 6. Running the API Gateway Server
- 7. CLI Compilation and Global Binary Linking
- Engineering Milestones and Branch Architecture
- Future Roadmap: Enterprise AI Governance and Cryptography
- Contributing
- License
YourCode utilizes a decoupled Client-Server-Agent architecture. Heavy model orchestration, token metering, and state management are isolated in a centralized backend service, while code analysis, filesystem mutations, and shell operations execute strictly on the client host within sandboxed workspace boundaries.
flowchart TB
subgraph ClientHost ["Client Tier (packages/cli)"]
UI["OpenTUI + React 19 Render Engine\nCustom Hooks · Keyboard Layers · Terminal Viewport"]
ChatTransport["AI SDK Chat Transport\nSSE Stream Processing · Message State Reconciliation"]
ToolExecutor["Local Tool Execution Runtime\nStrict CWD Path Sanitization · Subprocess Management"]
PKCEService["Loopback Auth Listener\nRFC 7636 PKCE Challenge Generation"]
Workspace[("Local Host Filesystem\nProject Root (process.cwd())")]
end
subgraph ServerTier ["Server Tier (packages/server)"]
Gateway["Hono API Gateway Router\n/chat · /sessions · /auth · /billing"]
AuthMiddleware["Clerk JWT Authentication Guard\nHeader Verification · Identity Resolution"]
BalanceGuard["Polar Credit Balance Guard\nPre-Flight Rate & Credit Authorization"]
SystemPromptEngine["Context & System Prompt Engine\nMode-Aware Behavioral Constraints"]
InferenceEngine["Vercel AI SDK Core\nstreamText Multi-Provider Dispatcher"]
end
subgraph UpstreamServices ["Upstream Infrastructure"]
ClerkService["Clerk Identity Platform\nOAuth 2.0 Auth Code with PKCE"]
PolarBilling["Polar.sh Billing Infrastructure\nAggregated Meter Ingestion · Customer Portal"]
Database[("PostgreSQL via Prisma 7\nJSONB Session Store · Indexed Queries")]
ModelProviders["Foundation Model APIs\nGoogle AI Studio · Anthropic · OpenAI"]
end
UI --> ChatTransport
ChatTransport <-->|Server-Sent Events / HTTP POST| Gateway
Gateway --> AuthMiddleware
AuthMiddleware --> BalanceGuard
BalanceGuard --> SystemPromptEngine
SystemPromptEngine --> InferenceEngine
InferenceEngine <-->|Prompt / Completion Protocol| ModelProviders
InferenceEngine -->|Streaming Tool Call Specs| ChatTransport
ChatTransport -->|Dispatch Local Action| ToolExecutor
ToolExecutor <-->|Constrained I/O & Shell Exec| Workspace
ToolExecutor -->|Structured Tool Output| ChatTransport
Gateway <-->|Persist Session & Message Graph| Database
AuthMiddleware <-->|Verify Bearer JWT| ClerkService
PKCEService <-->|Authorize / Token Exchange| ClerkService
BalanceGuard <-->|Check Balance & Record Event| PolarBilling
Most cloud-based coding platforms require developers to synchronize their entire source tree with a remote server, introducing significant latency, high storage costs, and severe security/compliance liabilities.
YourCode solves this by shifting tool execution entirely to the client:
- Zero Remote Code Exposure: Proprietary codebase files are never transmitted to or cached on the application backend. Only contextual snippets explicitly queried by the LLM are exchanged.
- Autonomous Multi-Step Loop: When the model decides to invoke a tool (e.g.,
readFile,grep,editFile), the backend streams a structured tool execution frame. The CLI intercepts the frame, executes the command against the local filesystem, and returns the result via an automated message continuation without requiring manual user dispatch. - Path Confinement Guards: All file operations validate canonical path targets against
process.cwd(). Path traversal attacks (../, symlink attacks, absolute root access) are caught and rejected prior to filesystem invocation.
Terminal applications typically suffer from visual tearing and clunky synchronous rendering loops. YourCode builds on OpenTUI and React 19:
- Declarative Layouts: Utilizes Flexbox-style viewport partitioning (
box,scrollbox,text) driven by terminal cell coordinates. - Multi-Layer Responder Stack: A custom
KeyboardLayerProvidermanages keyboard event delegation across base inputs, floating command palettes, context autocompletion menus, and modal dialogs with strict modal capture semantics. - Streaming State Synchronization: As token chunks stream over SSE, the UI incrementally reconciles assistant responses, dynamic tool progress indicators, and native reasoning/thinking traces (
reasoningmessage parts) with minimal layout jitter.
Command-line interfaces cannot securely store client secrets. YourCode implements RFC 7636 (Proof Key for Code Exchange by OAuth Public Clients):
- The CLI generates a cryptographically random 32-byte
code_verifierusingcrypto.getRandomValues. - Computes the SHA-256 digest of the verifier to produce the
code_challenge(base64url-encoded). - The CLI starts an ephemeral HTTP server on a random high-order loopback port (
port: 0) and launches the default system browser to Clerk's authorization endpoint with the challenge and state payload. - Clerk redirects through the backend relay (
/auth/callback), which forwards the authorization code to the CLI loopback listener. - The CLI exchanges the authorization code alongside the original unhashed
code_verifierdirectly for a secure session JWT.
To support sustainable multi-model usage without exposing provider-level API keys to end users:
- Rate Base Normalization: 1 internal Credit is pegged to
$0.01 USD. - Pre-Flight Authorization: The server validates that the authenticated account maintains an active credit balance (
> 0) before initiating inference streams. - Post-Stream Micro-Accounting: Upon response completion (
onFinish), the server extracts exact token counts (inputTokens,outputTokens) fromLanguageModelUsage. The cost is calculated using exact provider pricing vectors and converted into an integer credit charge (ceil(cost / 0.01)). - Asynchronous Ingestion: Billable usage events (
yourcode_usage) are ingested into Polar's metering API with unique message event IDs (chat-message:<id>), ensuring strict idempotency and zero duplicate charges.
The runtime provides two distinct operational postures enforcing strict functional boundaries:
| Mode | Trigger | Tool Whitelist | Purpose and Behavioral Profile |
|---|---|---|---|
PLAN |
Tab or /agents |
readFile, listDirectory, glob, grep |
Read-only architectural analysis. The model explores the codebase, maps call hierarchies, reads configurations, and designs implementation blueprints. All filesystem mutation tools and shell capabilities are structurally withheld from the model prompt schema. |
BUILD |
Tab or /agents |
readFile, writeFile, editFile, listDirectory, glob, grep, bash |
Full implementation runtime. The agent actively generates code, writes new modules, performs atomic surgical string replacements, and executes shell scripts, test suites, and build commands within configurable execution timeouts. |
All local tool invocations are executed by packages/cli/src/lib/local-tools.ts using strict path normalization and bounded system resources.
Every path parameter undergoes canonical resolution against the current working directory:
function resolveInsideCwd(path: string) {
const cwd = process.cwd();
const resolved = resolve(cwd, path);
const rel = relative(cwd, resolved);
if (rel.startsWith("..") || isAbsolute(rel)) {
throw new Error("Path is outside the project directory");
}
return { cwd, resolved };
}-
readFile: Reads file content with an upper-bound chunk limit of 10,000 characters. Content exceeding this threshold is safely truncated with length annotations to prevent terminal buffer overflows. -
writeFile: Writes full file payloads to disk. Automatically resolves directory hierarchy and creates missing parent paths recursively. -
editFile: Performs atomic in-place edits. Requires an exact, uniqueoldStringmatch. If 0 occurrences or$>1$ ambiguous matches are found, the transaction is aborted with an error to prevent file corruption. -
listDirectory: Scans directory structures, explicitly ignoring.git,node_modules, and hidden dot-directories. Sorts directories ahead of files alphabetically. -
glob: Fast filesystem traversal usingBun.Globwith match caps (max 200 entries) and exclusion filters. -
grep: Spawns an optimizedgrepsubprocess (-rn -E) excluding.gitandnode_modules, returning structured matches containing relative file paths, line numbers, and line content (capped at 50 results). -
bash: Spawns shell processes viaBun.spawnwith an isolated environment (TERM=dumb), 30-second default execution timeout watchdog, and maximum stdout/stderr capture buffers (20,000 characters).
Supported models and their associated token rate cards defined in @yourcode/shared:
| Model Identifier | Provider | Input Cost ($ / 1M tokens) | Output Cost ($ / 1M tokens) | Status |
|---|---|---|---|---|
gemini-3.1-flash-lite |
$0.25 | $1.50 | Default Model | |
claude-sonnet-4-6 |
Anthropic | $3.00 | $15.00 | Supported |
claude-haiku-4-5 |
Anthropic | $1.00 | $5.00 | Supported |
claude-opus-4-6 |
Anthropic | $5.00 | $25.00 | Supported |
gpt-5.4 |
OpenAI | $2.50 | $15.00 | Supported |
gpt-5.4-mini |
OpenAI | $0.75 | $4.50 | Supported |
gpt-5.4-nano |
OpenAI | $0.20 | $1.25 | Supported |
The command menu is accessible by entering / in the input buffer:
| Command | Category | Description | Technical Action |
|---|---|---|---|
/new |
Session | Reset active session | Navigates to root / route |
/agents |
Agent Mode | Toggle agent persona | Opens modal dialog to select PLAN or BUILD |
/models |
LLM Config | Switch active model | Opens model selection dialog linked to SUPPORTED_CHAT_MODELS |
/sessions |
Persistence | Browse session history | Fetches session records via Hono client; restores message tree |
/theme |
Interface | Switch color palette | Updates active theme context (Nightfox, Catppuccin, Dracula, etc.) |
/login |
Identity | Authenticate CLI | Initializes ephemeral loopback server and launches OAuth PKCE |
/logout |
Identity | De-authenticate | Purges cached access tokens from local state |
/upgrade |
Billing | Purchase credits | Resolves checkout URL via Polar SDK; triggers browser redirection |
/usage |
Billing | Inspect meter usage | Retrieves Polar customer portal session URL and opens browser |
/exit |
Application | Terminate process | Invokes terminal teardown handlers and exits process |
- Tab: Toggles runtime mode between
PLANandBUILD. - Enter / Return: Submits the input buffer or selects active menu candidate.
- Shift + Enter: Appends an unescaped newline into the multiline editor.
- @: Opens fuzzy filesystem autocomplete popup, querying files and subdirectories recursively.
- Esc: Dismisses open dialogs/menus, or aborts active streaming inference requests via
AbortController. - Ctrl + C: Clears the current input buffer, or terminates the application if buffer is empty.
- ↑ / ↓: Navigates selection indexes within dialog pickers and autocomplete dropdowns.
The project is configured as a high-performance Bun Workspace:
yourcode/
├── packages/
│ ├── cli/ # Terminal client application (OpenTUI + React 19)
│ │ ├── bin/ # Global binary execution shim
│ │ └── src/
│ │ ├── components/ # Viewport primitives, input bars, dialogs, status monitors
│ │ │ ├── command-menu/ # Command palette state machine and filter logic
│ │ │ ├── dialogs/ # Modal components (Agents, Models, Sessions, Themes)
│ │ │ └── messages/ # Token stream renderers, reasoning traces, tool indicators
│ │ ├── hooks/ # useChat AI stream lifecycle bindings and tool output relays
│ │ ├── layouts/ # Responsive terminal viewport scaffoldings
│ │ ├── lib/ # OAuth loopback engine, local tool runtime, API client
│ │ ├── providers/ # React Context providers (Keyboard, Theme, Dialog, Toast)
│ │ ├── screens/ # Route handlers (Home, NewSession, SessionView)
│ │ └── theme.ts # 12-bit hex palette schemas and styling tokens
│ ├── database/ # Database access layer and Prisma schema
│ │ ├── prisma/
│ │ │ └── schema.prisma # Postgres models (Session, Message JSON payload)
│ │ ├── generated/ # Generated Prisma Client artifacts
│ │ └── src/ # Connection pool abstraction and database client export
│ ├── server/ # Hono API backend gateway
│ │ └── src/
│ │ ├── lib/ # Pricing arithmetic, Polar SDK bindings, model resolvers
│ │ ├── middleware/ # Clerk JWT validation and Polar credit balance gate
│ │ ├── routes/ # HTTP Route endpoints (/chat, /sessions, /auth, /billing)
│ │ ├── system-prompt.ts # Prompt compiler injecting mode constraints and tool protocols
│ │ └── index.ts # Gateway entrypoint configured with high idle timeouts
│ └── shared/ # Isomorphic TypeScript module contracts
│ └── src/
│ ├── index.ts # Shared module namespace export
│ ├── models.ts # Supported model registry, provider types, and pricing definitions
│ └── schemas.ts # Zod validation schemas and tool calling contract specifications
├── dev-files/ # Internal PR specifications and architecture logs
├── .env.example # Environment configuration reference
├── package.json # Monorepo root manifest and workspace commands
├── tsconfig.base.json # Shared strict TypeScript configuration
└── bun.lock # Deterministic Bun dependency lockfile
- Runtime: Bun (v1.1.0 or higher)
- Database: PostgreSQL 14+ (or serverless instances such as Neon)
- Identity Provider: Active Clerk account
- Billing Infrastructure: Polar.sh account
- Foundation Model API Keys: At least one key from Google AI Studio, Anthropic, or OpenAI
Clone the repository and install workspace dependencies using Bun:
git clone https://github.com/devvrat-hans/yourcode.git
cd yourcode
bun installCreate a root .env configuration file based on .env.example:
cp .env.example .envPopulate the required configuration variables:
# Gateway Configuration
API_URL=http://localhost:3000
# PostgreSQL Connection String
DATABASE_URL=postgresql://user:password@localhost:5432/yourcode_db
# Foundation Model Providers (Provide at least one)
GOOGLE_GENERATIVE_AI_API_KEY=your_gemini_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
OPENAI_API_KEY=your_openai_api_key
# Clerk Authentication (OAuth PKCE Client)
CLERK_FRONTEND_API=your_instance.clerk.accounts.dev
CLERK_OAUTH_CLIENT_ID=your_clerk_oauth_client_id
CLERK_OAUTH_CLIENT_SECRET=your_clerk_oauth_client_secret
CLERK_PUBLISHABLE_KEY=pk_test_...
CLERK_SECRET_KEY=sk_test_...
JWT_SECRET=your_signing_jwt_secret
# Polar Billing Integration
POLAR_ACCESS_TOKEN=polar_at_...
POLAR_PRODUCT_ID=your_polar_product_id
POLAR_SERVER=sandbox # 'sandbox' for staging, 'production' for live billing
POLAR_CREDITS_METER_ID=your_polar_credits_meter_idTo support browser-based CLI PKCE login:
- Access the Clerk Dashboard > Configure > Developers > OAuth applications.
- Create a new OAuth application named
YourCode. - Enable the required authorization scopes:
openid,email,profile,offline_access. - Toggle Public to
ON(enables the Authorization Code with PKCE grant type). - Toggle Consent screen to
ON. - Configure the authorized redirect URIs:
- Development:
http://localhost:3000/auth/callback - Production:
https://<your-api-domain>/auth/callback
- Development:
- Copy the client credentials into
CLERK_OAUTH_CLIENT_IDandCLERK_OAUTH_CLIENT_SECRET.
- Open your Polar Dashboard (ensure Sandbox Mode is toggled for development).
- Navigate to Meters and configure an aggregated credit meter:
- Meter Name:
yourcode_credits - Filter Clause: Name equals
yourcode_usage - Aggregation Function:
Sum - Target Property:
credits
- Meter Name:
- Navigate to Benefits > Create a benefit attached to the
yourcode_creditsmeter (e.g., granting 1,000 units). - Navigate to Products > Create a one-time payment product (e.g., $10 for 1,000 credits), link the credit benefit, and set Customer Portal visibility to private.
- Export the resulting Product ID and Meter ID to your
.envconfiguration.
Generate the Prisma Client artifacts and apply the schema to your PostgreSQL database:
# Generate Prisma Client
bun run --cwd packages/database db:generate
# Synchronize schema directly with database
bunx --cwd packages/database prisma db pushStart the Hono backend server in development mode:
bun run dev:serverThe server binds to port 3000 with hot code reloading and an extended idleTimeout (255 seconds) to accommodate sustained LLM tool execution streams.
To run the terminal client in watch mode during development:
bun run dev:cliTo build and install the yourcode binary globally into your system path:
bun run link:cliOnce linked, execute the agent inside any project workspace on your machine:
yourcodeThe repository was engineered via modular, reviewable pull requests merged into main:
| Branch Identifier | Architectural Deliverables |
|---|---|
feature/monorepo-scaffolding |
Bun workspaces setup, multi-package TSConfig inheritance, dependency resolution |
feature/cli-ui-components |
OpenTUI runtime integration, declarative text components, header ASCII rendering |
feature/cli-routing-screens |
React Router terminal layout abstraction, dynamic route views (/, /sessions/:id) |
feature/session-api-integration |
Hono session CRUD endpoints, Prisma schema definitions, JSON message serialization |
feature/chat-streaming-integration |
Vercel AI SDK SSE protocol bridge, multi-provider model routing, stream lifecycle hooks |
feature/cli-theming |
Dynamic theme state provider, ANSI color mappings, theme selector modal |
feature/auth-file-mentions-cli |
RFC 7636 PKCE browser authentication, @ context mention tokenization and autocomplete |
feature/billing-cli |
Pre-flight credit authorization middleware, token-to-USD pricing vectors, Polar event sync |
feat/client-side-tool-execution |
Decoupled local tool executor, CWD directory boundary guards, subprocess runners |
feature/cli-command |
Bun binary entrypoint (bin/yourcode), bundle output generation, global linking script |
To support enterprise deployment, regulatory compliance (SOC2, ISO 27001, HIPAA), and zero-trust engineering environments, the following technical milestones are currently planned:
flowchart LR
InboundPrompt["Developer Prompt & Filesystem Data"] --> DLPScanner["Client-Side DLP & PII Scanner\nRegex + Local NER Engine"]
DLPScanner --> SanitizedPayload["Sanitized Token Stream"]
SanitizedPayload --> InjectionFilter["Indirect Prompt Injection Classifier\nHeuristic Boundary Verification"]
InjectionFilter --> RemoteLLM["External Foundation Model\n(Inference Processing)"]
RemoteLLM --> ToolValidator["Tool Invocation Authority\nBlast-Radius & Permissions Filter"]
ToolValidator --> NamespaceSandbox["Isolated Subprocess Runner\nLinux Namespaces / Container Jail"]
- Pre-Flight DLP Sanitization: Implement a client-side scanning phase before prompts or file contents leave the local host.
- Automated High-Entropy Token Redaction: Scans for RSA/ECDSA private keys, AWS/GCP access tokens, JWT strings, environment passwords, and database connection strings using Shannon entropy evaluation and deterministic regular expressions.
- Named Entity Recognition (NER): Integration with local tokenizers (such as Microsoft Presidio or ONNX-compiled NER models) to redact personally identifiable information (emails, phone numbers, government identification numbers) and replace them with reversible pseudonymized tokens.
- Workspace Exclusions (
.aiignore): Support for root-level.aiignorerule files adhering to glob specifications, guaranteeing designated directories or sensitive credential files are never accessible to read tools.
- Indirect Jailbreak Protection: Unchecked code ingestion from external open-source repositories can contain malicious instructions embedded within comments or documentation files.
- Structured Boundary Framing: Wrap all external file contents in strict XML/Markdown boundary encapsulations with prompt directives that instruct the model to treat external code as data rather than instructions.
- Tool Argument Sanitization: Enforce schema validation and AST verification on generated shell arguments prior to handing execution over to system subprocesses.
- Containerized Process Jailing: Migrate arbitrary
bashcommands into ephemeral Linux container namespaces (unshare,cgroups v2,chroot) or lightweight virtualization environments (e.g., Docker, Podman, or Applesandbox-execprofiles on macOS). - Interactive Human-In-The-Loop (HITL) Authorizations: Require explicit terminal approval whenever the agent attempts to run irreversible system actions (e.g., destructive file removals
rm -rf, Git force pushes, package publishing, or unauthorized network calls). - Cryptographic Audit Logging: Generate an append-only, tamper-evident audit log of all generated prompts, tool invocations, shell executions, and diff outputs, secured with local HMAC signatures for enterprise governance.
- Currently, conversation histories are persisted as JSON objects in PostgreSQL (
Session.messages). - Client-Side Envelope Encryption: Transition to client-side authenticated encryption using AES-256-GCM or ChaCha20-Poly1305.
- Key Derivation via Argon2id: Session encryption keys are derived on the client from a user-supplied master passphrase using memory-hard key derivation (Argon2id). The server stores only the encrypted ciphertext and nonce. Database breaches yield zero plaintext access to proprietary codebase logic or architectural discussions.
- Deprecate plaintext token caching in favor of operating system cryptographic credential vaults:
- macOS: Keychain Services API via native bindings
- Linux: Secret Service API /
libsecretover D-Bus - Windows: Windows Credential Manager DPAPI
- Embedded Vector Search Engine: Local semantic codebase indexing using embedded vector stores (e.g., SQLite-VSS or LanceDB). Code chunk embeddings generated locally using compact embedding models to eliminate cloud-dependent vector synchronization.
- Language Server Protocol (LSP) Bridge: Direct RPC bridge into language servers (
typescript-language-server,gopls,pyright,rust-analyzer). Equips the AI agent with compiler-grade diagnostic trees, exact go-to-definition references, and type-safe refactoring verification before committing diffs. - Model Context Protocol (MCP) Client: Full implementation of Anthropic's Model Context Protocol, enabling engineers to connect external tool providers, enterprise SQL databases, issue trackers (Jira, Linear), and GitHub pull request automation into the YourCode agentic loop.
- Autonomous Multi-Agent Coordination: Hierarchical agent orchestration: a primary Architect Agent breaks user requests into validated technical specifications and delegates sub-tasks to concurrent Implementation Agents, while a dedicated Verification Agent compiles code and executes test suites to ensure zero regressions.
- Fork the repository.
- Create a targeted feature branch (
git checkout -b feature/targeted-enhancement). - Commit deterministic, atomic changes (
git commit -m 'feat: implement targeted enhancement'). - Push the branch upstream (
git push origin feature/targeted-enhancement). - Submit a pull request detailing the technical implementation, architectural impact, and verification steps.
Distributed under the MIT License.