Skip to content
项目

关于

The DeepSeek and OpenRouter Harness built on Elixir

人工智能与机器学习

这些数字如何统计

实测星标增长

24小时
0
7天
正在收集历史
15天
正在收集历史
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

Yoke logo

Yoke

An agentic CLI coding harness (originally built for DeepSeek models,) purely on Elixir & Erlang/OTP

Elixir Erlang/OTP Version Architecture

An agentic CLI coding harness for DeepSeek models (deepseek-chat V3, deepseek-coder V2.5, and deepseek-reasoner R1), built in Elixir & Erlang/OTP. OpenRouter and local models are also supported.

Derived from José Valim's architectural framework for process-isolated AI agents, DeepSeek V3/R1 model architecture, Google Antigravity, and Warp Terminal TUI patterns.


Table of Contents


Architectural Foundation: José Valim's Vision & DeepSeek Model Integration

Yoke (Yoke) bridges modern LLM reasoning capabilities with Erlang/OTP's battle-tested fault tolerance and process concurrency model.

1. José Valim's Actor-Driven Harness Architecture

In traditional AI harnesses (typically single-threaded Node.js or Python runtimes), a tool execution error or unhandled exception can crash the entire interactive session, wiping out conversation context and active state. Yoke implements José Valim's vision for agentic harnesses on the BEAM virtual machine:

  • Decoupled Brain & Hands Architecture: The agent's cognitive state ("Brain") runs as an isolated GenServer process (Yoke.Brain.Session). Tool execution ("Hands") is cleanly separated (Yoke.Hands.Executor), allowing commands to execute locally, on remote Erlang nodes, or inside isolated Docker containers.
  • Fault-Tolerant Supervision: If a tool execution or sub-task process fails, the OTP supervision tree isolates the failure without impacting the user's interactive REPL session.
  • Spatiotemporal Checkpoints & Instant Rollback: State snapshots record conversation history, model configurations, and context state before each tool execution turn, providing temporal undo capabilities (/undo) and state branching.
  • Live Hot-Code Tool Reloading: Tools and plugins can be compiled, hot-swapped, or reloaded live (/plugins reload) without losing conversation memory or resetting GenServer process state.
  • Lightweight Parallel Subagents: Sub-tasks can be delegated to child session processes (SessionSupervisor.start_session), running parallel agentic loops concurrently across BEAM worker threads.
  • Concurrent OTP Task Engine: Batches of tool calls (Yoke.TaskEngine.Orchestrator) run concurrently under a Task.Supervisor, with per-file write locks and a real-time "N running" badge on the status bar ruler.
  • Distributed Erlang Node Clustering: Hands execution can target the local host, a remote Erlang node (/mode remote <node>), or a Docker container (/mode docker <id>), decoupling where the Brain thinks from where the Hands act.

2. DeepSeek Model Selection & Best Practices

Yoke supports the full suite of official DeepSeek models, local open-weights models, and third-party API aggregators. Switch models anytime via /model <alias> or --model <alias>:

Model ID / Alias in Yoke Best Used For Strengths & Characteristics
DeepSeek-Flash deepseek-flash
/model flash
(aliases: chat, v3)
Agentic workflows & multi-tool tasks (Default) Fast, high general intelligence and highest tool-calling precision across multi-turn agent loops. Runs in silent mode by default.
DeepSeek-Coder-V2.5 deepseek-coder
/model coder
Direct code generation, syntax completion & refactoring Trained specifically on 338+ programming languages. Produces idiomatic Elixir/C++/Rust code with high precision on syntax and language conventions.
DeepSeek-R1 deepseek-reasoner
/model reasoner
(alias: r1)
Complex debugging & architectural design Reinforcement Learning (RL) reasoning model. Yoke captures and streams [DeepSeek-R1 Reasoning] Chain-of-Thought output live before tool execution.

3. Reasoning Mode vs. “Silent” Mode (Chain-of-Thought Control)

Yoke provides flexible control over model Chain-of-Thought (CoT) generation, allowing you to toggle between Reasoning Mode and “Silent” Mode:

  • Reasoning Mode:
    • What it does: Captures the model's inner reasoning/thinking process and streams it live to the terminal prior to executing tool calls or outputting final responses.
    • Terminal formatting: Rendered as syntax-highlighted Markdown via Marcli in yellow default text (or your configured reasoning_color) under a ● [<Model> Reasoning] header block. Code blocks, lists, headings, and tables within reasoning are fully rendered.
    • Best for: Deep architectural analysis, diagnosing complex stack traces, algorithm design, and root-cause debugging.
  • “Silent” Mode:
    • What it does: Completely suppresses chain-of-thought/thinking tokens by sending {"type": "disabled"} for thinking and "none" for reasoning_effort in API completion requests. The model outputs only the direct response and tool invocations without intermediate deliberation monologue.
    • Best for: Fast, token-efficient agentic workflows, multi-tool automated task loops, routine edits, and quick refactoring passes.

How to Switch Between Reasoning and Silent Modes

1. Model Switching (Automatic Detection)

Yoke automatically identifies reasoning models (e.g. deepseek-reasoner, R1, o1, o3) vs. standard models:

  • Switch to Reasoning Mode:
    • Interactive REPL:
      /model reasoner
      # or
      /model r1
      
    • CLI flag at launch:
      yoke --model deepseek-reasoner
      # or
      yoke -m reasoner
      
  • Switch to Silent Mode:
    • Interactive REPL:
      /model flash
      # or aliases:
      /model chat
      /model coder
      
    • CLI flag at launch:
      yoke --model deepseek-flash
      # or
      yoke -m flash
      
2. Workspace & Global Configuration (.yoke/config.json)

You can force reasoning or silent mode for hybrid models and thinking-capable endpoints in ~/.yoke/config.json (global) or .yoke/config.json (per-workspace):

  • Enable Reasoning Mode explicitly:
    {
      "reasoning": true,
      "reasoning_effort": "medium",
      "reasoning_color": "yellow"
    }
    
  • Enforce Silent Mode explicitly:
    {
      "reasoning": false,
      "reasoning_effort": "none"
    }
    

Supported configuration keys:

  • reasoning (or enable_reasoning): true to enable thinking traces (thinking: {"type": "enabled"}), false to disable (thinking: {"type": "disabled"}). If omitted, automatically determined by model name.
  • reasoning_effort: Set reasoning effort constraint (e.g. "none", "low", "medium", "high"). Defaults to "none" in silent mode.
  • reasoning_color: ANSI color for Marcli Markdown reasoning output blocks ("yellow", "cyan", "magenta", "green", "blue", "white"). Defaults to "yellow".
3. Dynamic In-REPL Toggling

Toggle reasoning on/off live during an active session using /config toggle:

/config toggle reasoning

(or /config toggle enable_reasoning)

You can view current config state at any time with /config.

4. OpenRouter, OpenCode Go & Local Model Integration (SGLang, Ollama, LM Studio, vLLM)

While yoke defaults to the official remote DeepSeek API (https://api.deepseek.com/chat/completions with deepseek-chat), it provides native support for OpenRouter, OpenCode Go (Console Go), and local inference engines (SGLang, Ollama, LM Studio, vLLM).

A. OpenRouter Configuration

Connect yoke to OpenRouter endpoints (such as meta-llama/llama-3.3-70b-instruct:free, qwen/qwen-2.5-coder-32b-instruct:free, or deepseek/deepseek-r1:free):

  • Environment Variables:
    export OPENROUTER_API_KEY="sk-or-v1-..."
    export DEEPSEEK_ENDPOINT="https://openrouter.ai/api/v1/chat/completions"
    export DEEPSEEK_MODEL="meta-llama/llama-3.3-70b-instruct:free"
    
    yoke
    
  • CLI Flags:
    yoke -e openrouter -m meta-llama/llama-3.3-70b-instruct:free
    
  • Live REPL Commands:
    /endpoint openrouter
    /model openrouter-free
    

B. OpenCode Go (Console Go) Configuration

Connect yoke to OpenCode Go / Zen endpoints:

  • Automatic x-opencode-session Routing Header: OpenCode Go requires the x-opencode-session header on every request for backend routing and prompt caching optimization. Yoke automatically attaches this header using the session's unique identifier.
  • Environment Variables:
    export OPENCODE_API_KEY="your-opencode-key"
    # Optional custom base URL (defaults to OpenCode Go endpoint when using shortcut):
    export OPENCODE_BASE_URL="https://opencode.ai/zen/go/v1/chat/completions"
    
    yoke
    
  • CLI Flags & REPL:
    yoke -e opencode -m deepseek-chat
    # Or switch live in REPL:
    /endpoint opencode
    

C. Local Models (SGLang, Ollama, LM Studio, vLLM)

Named profiles: local inference versus remote DeepSeek

Select the model and endpoint together:

yoke --provider local        # Devstral Small 2 24B Q4_K_M, localhost Ollama
yoke --provider local-qwen   # Qwen3-Coder 30B-A3B Q4_K_M, localhost Ollama
yoke --provider deepseek     # deepseek-flash, official remote DeepSeek API

Inside the REPL, /provider shows the profile, model, endpoint, and LOCAL/REMOTE transport. /provider local, /provider local-qwen, and /provider deepseek switch all settings atomically while idle. The prompt always includes [LOCAL] or [REMOTE], independently of Hands /mode. A remote switch warns that subsequent requests send the conversation history; use /reset for a fresh conversation.

Selection precedence is CLI --provider, then YOKE_PROVIDER, then "provider" in global/workspace config. Without a profile, existing model/endpoint behavior is preserved. Explicit profiles ignore unrelated DEEPSEEK_MODEL, DEEPSEEK_ENDPOINT, aggregator routing, and OLLAMA_HOST. Explicit --model and --endpoint overrides remain available; local profiles reject non-loopback endpoints.

Local profiles send no API credentials and omit DeepSeek-only thinking controls. They have zero API token prices, without erasing earlier remote costs. DeepSeek resolves its own credentials rather than aggregator environment keys. Provider identity survives session/workflow resume without persisting credentials. Subagents, plans, compression, practice learning, and workflow steps inherit the selected transport. Local failures never fall back remotely.

Sharing a 24 GB NVIDIA GPU with Ragex

Devstral Small 2 is the conservative local default: approximately 15 GB of Q4_K_M weights versus Qwen's 19 GB. It is Apache-2.0; its upstream card reports 68% SWE-bench Verified and 256K context. These are upstream results, not measurements of this quantization or Yoke. Qwen is a sparse MoE, useful for coding-speed comparisons, but all its weights still occupy memory.

Use a current Ollama Linux distribution. For a rootless installation, inspect and extract the official amd64 archive under ~/.local (it contains bin/ollama and lib/ollama). On this workstation Ollama is installed this way and enabled as a user service at ~/.config/systemd/user/yoke-ollama.service. Its environment is:

OLLAMA_HOST=127.0.0.1:11434
OLLAMA_NO_CLOUD=1
OLLAMA_CONTEXT_LENGTH=16384
OLLAMA_FLASH_ATTENTION=1
OLLAMA_KV_CACHE_TYPE=q8_0
OLLAMA_NUM_PARALLEL=1
OLLAMA_MAX_LOADED_MODELS=1
OLLAMA_GPU_OVERHEAD=4294967296
OLLAMA_KEEP_ALIVE=2m

These are server settings, not environment variables to put on the Yoke client. For a manual server, export them before running ollama serve. The 4 GiB scheduler margin is not a hard cross-process memory partition. Only one generation model is loaded, and it unloads after two minutes idle.

systemctl --user status yoke-ollama.service --no-pager
systemctl --user restart yoke-ollama.service
systemctl --user stop yoke-ollama.service
journalctl --user -u yoke-ollama.service --no-pager
ollama pull devstral-small-2:24b-instruct-2512-q4_K_M
ollama pull qwen3-coder:30b-a3b-q4_K_M

Both pinned baselines need approximately 34 GB total disk space. Leave EXLA preallocation disabled and initially budget roughly 3 GiB for embeddings:

EXLA_GPU_MEMORY_FRACTION=0.125 \
EXLA_GPU_PREALLOCATE=false \
XLA_PYTHON_CLIENT_MEM_FRACTION=0.125 \
XLA_PYTHON_CLIENT_PREALLOCATE=false \
yoke --provider local

The workstation's ~/.config/yoke/cuda.sh supplies these defaults while preserving explicit environment overrides. An already-open shell may carry older exported values; use the command above or open a fresh shell. Other machines retain Yoke's existing EXLA defaults.

Check ollama ps and nvidia-smi before increasing context/concurrency. Multiple Yoke processes also multiply embedding memory. Advertised maximum context does not imply it fits a shared 24 GB GPU: local profiles assume the server's 16,384-token context. If tuning the server, align the profile's max_context_tokens setting in Yoke.Provider too.

Authenticated local OpenAI-compatible endpoints (oMLX, vLLM, llama-server)

Local OpenAI-compatible endpoints requiring an API key or bearer token (such as oMLX, vLLM, or LocalAI configured with --api-key) are first-class configurations.

Credentials and custom local endpoints can be configured using provider-neutral environment variables:

# Provider-neutral variables for authenticated local servers
export OPENAI_API_KEY="your-local-bearer-token"      # or YOKE_API_KEY
export OPENAI_BASE_URL="http://127.0.0.1:8000/v1"   # or YOKE_ENDPOINT
export OPENAI_MODEL="Qwen3.6-35B-A3B-4bit"          # or YOKE_MODEL

# Launch Yoke targeting the authenticated local server directly
yoke

Credentials are resolved when a session starts and whenever the endpoint changes, so exporting the variable after Yoke is already running does not reach an open session. Start a new session, or re-run /endpoint after exporting it, to pick the credential up.

Or switch endpoints dynamically within the REPL:

/endpoint http://127.0.0.1:8000/v1/chat/completions
/model Qwen3.6-35B-A3B-4bit

/endpoint reports the resulting session credential state immediately, so a missing token is visible before the next turn fails. /env shows the effective credential state and the variable or setting it came from, without revealing the secret.

When connecting to authenticated loopback endpoints, Yoke includes the bearer token in the Authorization header while retaining loopback transport isolation. Deterministic failures stop immediately instead of being retried:

  • HTTP 401 reports that the loopback server requires a bearer token and names the variables to set.
  • HTTP 403 reports that the request was rejected and points at key permissions.
  • Other 4xx responses report that the request itself was refused, and suggest checking the model name, max_tokens, and request options.

Only rate limiting (429) and server-side unavailability (500, 502, 503, 504) are retried.

Retries are bounded by one cumulative budget shared by the HTTP client and the agent harness, so a single turn cannot multiply into a long silent retry loop. The budget counts total attempts, enforces a wall-clock deadline, caps exponential backoff, and stops early after repeated identical failures:

Key Default Meaning
api_retry_max_attempts 6 Total provider attempts per turn
api_retry_total_timeout_ms 120000 Cumulative wall-clock limit for those attempts
api_retry_max_backoff_ms 8000 Ceiling on the delay between attempts
api_retry_identical_failure_limit 2 Stop after this many identical consecutive failures

When the budget is exhausted, the error names the attempt count, elapsed time, and the request's byte size (total payload, message count, largest message, and tool-definition bytes), so a transport failure can be correlated with payload size. /cost reports the current turn's retry consumption. Set any key in ~/.yoke/config.json or .yoke/config.json to tune the limits.

Reproduce real client tool-call/result round trips with overlapping 32-item CUDA embedding batches:

EXLA_GPU_MEMORY_FRACTION=0.125 \
XLA_PYTHON_CLIENT_MEM_FRACTION=0.125 \
mix run --no-start scripts/verify_local.exs

The script executes CUDA servings directly so CPU fallback cannot hide failure, prints VRAM allocation, and unloads both generation models afterwards. No remote generation requests are made. Embedding weights may initially be downloaded from Hugging Face.

ollama stop devstral-small-2:24b-instruct-2512-q4_K_M
ollama stop qwen3-coder:30b-a3b-q4_K_M
Custom local endpoints

Run yoke completely offline against local LLM servers without requiring API keys:

  • SGLang (http://localhost:30000):
    yoke -e http://localhost:30000/v1 -m deepseek-ai/DeepSeek-V3
    
  • Ollama (http://localhost:11434):
    # 1. Start Ollama model
    ollama run qwen2.5-coder:14b
    
    # 2. Launch yoke with local endpoint
    yoke -e ollama -m qwen2.5-coder:14b
    
    # Or via environment variables:
    export OLLAMA_HOST="http://localhost:11434"
    export DEEPSEEK_MODEL="qwen2.5-coder:14b"
    yoke
    
  • LM Studio (http://localhost:1234) & vLLM (http://localhost:8000):
    yoke -e lmstudio -m qwen2.5-coder-32b-instruct
    # OR
    yoke -e vllm -m deepseek-r1-distill-qwen-32b
    
  • Automatic Reasoning & <think> Tag Extraction: Local models and OpenRouter models that return reasoning inside <think>...</think> tags are automatically parsed into [Reasoning] output.
  • API Key Bypass: Local loopback endpoints (localhost, 127.0.0.1, ::1, 192.168.*) do not require API keys and automatically bypass offline mock mode.

Key Features & Capabilities

1. Persistent Session Resumption (yoke -c <id> & /resume)

  • Every session is assigned a unique UUID (e.g. df97eb34-cb33-4f21-bada-2e9c3cf75d46).
  • On exit, yoke prints your conversation ID:
    Resume with -c (or command below):
    yoke --conversation=df97eb34-cb33-4f21-bada-2e9c3cf75d46
    
  • Resume any conversation across restarts with yoke -c <id> or interactively pick past sessions in the REPL via /resume.
  • Conversations are stored in lmml (a Markdown-superset markup for LLM conversations) as <session_id>.lmml narratives under .yoke/sessions/ — plain, self-contained Markdown that any Markdown viewer renders sensibly, yet round-trips every structured message losslessly through its inline-embed model. Legacy .json session files from earlier versions are still read transparently on resume.

2. Scoped Rule Engine (/rules)

  • Manage prompt preambles and execution constraints.
  • Scopes:
    • all: — Applied to all user prompt turns (e.g. all: typographic quotes “” mean the exact quote).
    • <command>: — Applied only when executing specific commands (e.g. cr: format table cells multiline to fit in 80 symbols width for /cr).
  • Use /rules to list rules, /rules add <scope: text> to add rules, and /rules delete to launch the interactive checkbox modal.

3. Context Reference Expansion (@) & Smart Error Resolution

  • Type @filename, @/path, @file://..., or @https://... anywhere in user prompts to attach contents.
  • @ triggers an interactive TUI file picker filtered by .gitignore rules (excluding _build, deps, .elixir_ls).
  • Intelligently expands ambiguous error references ("error above", @error) and tracks :open vs :resolved issue status across tool calls.

4. Interactive Question TUI Modal (ask_question)

  • Allows the AI model to request user feedback, clarify requirements, or present multi-choice design decisions with keyboard navigation and OK/Cancel buttons.

5. Model Context Protocol (MCP) & First-Class Ragex Integration

  • Mount external Model Context Protocol (MCP) servers via stdio (JSON-RPC) or HTTP/SSE.
  • Native integration with Ragex for SCIP code indexing, AST refactoring, and semantic code search (/ragex).

6. One-Command Global Installation & Updates

  • Install globally to ~/.local/bin/yoke via mix yoke.install or install.sh.
  • Run yoke smoothly from any workspace directory.
  • Run in-place self-updates using yoke --update or /update. Updates wait for the pull and release build to finish and report failures rather than announcing success in advance.

7. Pure Console Mode (!!)

  • Type !! on its own line to flip yoke completely out of the way: no Brain/Hands actors, no LLM turns, no slash-command dispatch -- just a bare sh -c passthrough with live-streamed output.
  • cd is applied to yoke's own process, exactly like a real shell builtin, so navigation persists across commands.
  • Type !! again (or Ctrl+D) to flip straight back into the harness REPL -- no need to open a second terminal tab for a quick burst of plain shell commands.

8. Concurrent OTP Task Engine

  • Tool call batches execute concurrently under Yoke.TaskEngine.Orchestrator, each in its own supervised Task, with automatic per-file write locking to prevent concurrent edit races.
  • The idle status bar surfaces a live "N running" badge with per-task summaries whenever background tool work is in flight.

9. Native Elixir Static Analysis (/linter, /lint)

  • Runs oeditus_credo, propwise, credo, or dialyzer against the full project, a git diff, or a branch code review via /linter <tool> [project|diff|cr] [args...].

10. Configurable Prompt Styles & Status Bar (/config)

  • Switch prompt layout with /config style <starship|extended|compact|minimal> or supply a fully custom template via /config prompt <template>.
  • Toggle UI features (enable_autosuggestions, enable_syntax_highlighting, enable_context_gauge, compact_status_bar, and more) with /config toggle <key>.

11. Customizable Multi-Step Workflows (/workflow)

  • Runs a named, customizable, multi-step process on top of the ordinary agent loop: branch off main/master (with a warn/confirm gate), summarize the task, propose a non-clashing split for parallel execution, require tests + docs, lint, and commit -- with the entire run persisted under .yoke/workflows/.
  • Parallel subtasks each get their own isolated git worktree and branch, so concurrent agent processes can never clash on disk.
  • Ships with a built-in elixir workflow; scaffold your own with /workflow init <name> [--from <template>]. Full reference: docs/WORKFLOW_ENGINE.md.

12. Idea Lifecycle Pipeline & Strategic Memory Engine (/sweep, /spar, /thought, /backlog)

  • Implements an idea-lifecycle pipeline (thoughts/ → backlog/ → active/ → completed/) with git-ignored derived maps (_MAP.md, _DEPS.md) parsed from YAML frontmatter metadata.
  • Multi-Corpus Prior-Art Sweep (/sweep <tokens>): Searches active pipeline, reference docs, operational lessons, and local knowledge vault to prevent repeating past work.
  • Socratic & Adversarial Sparring (/spar [soc|adv] <topic>): Pressure-tests new feature designs turn-by-turn with Socratic requirement probing and blunt Adversarial counter-arguments.
  • Structured Memory Architecture: Transient scratch notes (/scrap), operational lessons learned (/lessons), and automated close-out gates.

13. Whole-Project Audit (/audit)

  • /audit measures the project first (languages, source/test file counts, line counts, largest modules, TODO/FIXME markers, formatter/credo/dialyzer/CI/lockfile/docs presence, test-to-source ratio, source files with no matching test) and then hands those facts to the agent for a grounded narrative audit.
  • The report has four sections: strong parts (with the mechanism that keeps them strong), weaknesses & glitches to fix (worst first, each with a location and a fix), codebase improvement ideas, and UX improvement ideas.
  • Narrow the scope with /audit code or /audit ux. The deterministic half never calls the network, so the measured facts are reproducible run to run.

14. Session Command Aliases (/alias, /<name>)

  • Declare custom command sequences (slash commands, shell commands !cmd, or LLM agent prompts) that execute sequentially within the current active session.
  • Stored in .yoke/aliases.json (workspace), ~/.yoke/aliases.json (global), or under "aliases" in .yoke/config.json.
  • Supports parameter placeholders ({{args}}, $@, $1), auto-appended arguments, and conditionals ({{#if_args}}...{{/if_args}}, {{#if_commit_only}}...{{/if_commit_only}}).
  • Built-in default aliases out-of-the-box:
    • /finish [files] [--commit-only] (alias: /pr): Runs mix format, creates a comprehensive commit explicitly documenting The PR reason, Implementation, How to verify, Risk & rollout, and Reviewer guidance, and opens a GitHub pull request. Supports --commit-only (or -c) to commit without creating a PR, and stages optional files or commits manually added files.
    • /commit-structured [files] (alias: /cpr): Creates a commit with the comprehensive 5-section format without opening a PR.

Yoke

Installation & Setup

This guide provides step-by-step instructions to get Yoke (yoke) up and running on your system, along with its database backend dllb (which powers Ragex code analysis and knowledge graph indexing).


Prerequisites (What You Need First)

Before installing yoke or dllb, ensure your machine has the following tools installed:

  1. Elixir & Erlang/OTP:
    • yoke is built using the Elixir programming language on top of the Erlang runtime engine.
    • Required versions: Elixir 1.19+ and Erlang/OTP 27+.
    • How to install: Use your system package manager (e.g. brew install elixir on macOS or sudo apt install elixir on Ubuntu) or a version manager like asdf / mise.
  2. Git: Required to download the project source code.
  3. C/C++ Build Tools & Libraries (Linux only):
    • Required for compiling native code dependencies: build-essential and libgit2-dev.
    • Ubuntu/Debian command: sudo apt-get install -y build-essential libgit2-dev

1. Installing yoke (Yoke)

Choose one of the two installation methods below:

Option A: Quick Automated Installer (Recommended)

Run this single command in your terminal to automatically clone, build, and install yoke:

curl -fsSL https://raw.githubusercontent.com/Oeditus/yoke/main/install.sh | bash

Option B: Manual Installation from Source

If you prefer installing manually from the source code:

# 1. Clone the repository
git clone https://github.com/Oeditus/yoke.git
cd yoke

# 2. Fetch project dependencies
mix deps.get

# 3. Compile and install yoke globally to ~/.local/bin/yoke
mix yoke.install

Running tests without CUDA

Run MIX_ENV=test mix deps.get followed by mix test. Ordinary tests exclude the optional Bumblebee/Nx/EXLA/Image dependency group, so they do not need CUDA, NCCL, or XLA archives. Ragex still starts its non-embedding services and uses the ETS graph backend in tests. Other core dependencies, such as the Markdown parser's precompiled NIF, remain part of the build.

For native integration testing, use YOKE_EMBEDDINGS=true mix test. These artifacts live in _build/test_native (or beneath MIX_BUILD_ROOT) so switching back cannot reuse native-enabled yoke.app metadata in the ordinary test build. On a CPU-only host, also set XLA_TARGET=cpu EXLA_CPU_ONLY=true when compiling the native dependencies; those settings cannot turn an already compiled CUDA NIF into a CPU NIF. Rebuild EXLA when changing its target. Keep hardware/model integration checks separate from ordinary unit tests.

Dev/prod builds retain embeddings and image processing by default. Escript builds always exclude this native feature group, even with the opt-in flag. mix test --no-start remains available for tests that do not need Yoke's supervision tree; app-dependent cases are excluded in that mode.

Testing local Ragex changes

Set LOCAL_RAGEX to an absolute Ragex checkout path to use unpublished source changes instead of the Hex dependency. For example, run LOCAL_RAGEX=/path/to/ragex mix test from this checkout. The same override applies when building a release with LOCAL_RAGEX=/path/to/ragex MIX_ENV=prod mix release --overwrite.

Rebuild the sibling Dllb server with cargo build --release -p dllb-server from its checkout when changing database index behavior. Existing running processes retain their old code; restart Yoke normally after rebuilding. Do not delete .ragex or the fingerprint cache to apply startup fixes.

For unpublished Ragex startup fixes, launch with LOCAL_RAGEX=/path/to/ragex YOKE_REBUILD=1 yoke to rebuild the OTP release against that checkout. LOCAL_RAGEX must also be set for subsequent builds until the fix is published; the default dependency still comes from Hex.

Incremental graph indexing should not wait for the embedding model to download or initialize. Ragex readiness checks must remain nonblocking, and unchanged directory scans should not rewrite the graph and fingerprint caches. Switching branches still scans for added, changed and deleted files; an existing graph is not a reason to skip that validation.

Ragex source discovery must honor nested .gitignore files, particularly in umbrella applications where generated bundles live under an app's priv/static/assets/. Otherwise an unchanged restart can repeatedly attempt to parse large ignored bundles that never acquired successful fingerprints. Git-aware discovery includes tracked and non-ignored untracked source files, while retaining explicit build-directory exclusions and depth limits. Ragex.Analyzers.Directory.discover_files/2 provides a read-only way to inspect the selected files without re-indexing the graph.

Testing local Markdown changes

Set LOCAL_MD to the Markdown parser checkout to validate unpublished md fixes, for example LOCAL_MD=/path/to/md mix quality.ci. It can be combined with LOCAL_RAGEX; without an override, the normal Hex dependency is used.

When Dialyzer reports LMML constructors as error-only despite successful runtime round trips, check the upstream parser contracts. Parser finalization passes a list of AST nodes to Md.Deferred.apply/2, and Md.Engine.flatten/1 handles both scalar nodes and lists. Excluding those supported inputs from their specs can make Dialyzer infer that every generated parser is non-returning, propagating impossible-success warnings throughout session persistence. Correct the dependency contracts rather than suppressing the callers or deleting valid success branches.

Adding ~/.local/bin to Your System $PATH

After installation, ensure ~/.local/bin is included in your shell path so you can run yoke from any terminal directory:

export PATH="$HOME/.local/bin:$PATH"

Tip: Add the line above to your shell configuration file (e.g. ~/.bashrc or ~/.zshrc) so it is available automatically in every new terminal window.


2. Installing dllb for ragex Code Indexing

What is dllb and why do I need it?

yoke features a powerful code intelligence engine called Ragex (/ragex). To store code symbol relationship graphs, perform fast full-text code searches, and cache project metadata across restarts, Ragex uses a lightweight, high-performance database server called dllb-server (written in Rust).

Installing dllb-server enables persistent, per-project database indexing.

Option A: Download Pre-Compiled Binary (Easiest)

  1. Go to the dllb GitHub Releases page.
  2. Download the dllb-server binary for your platform (e.g., Linux or macOS).
  3. Move the binary into your ~/.local/bin directory (or any directory in your system $PATH) and make it executable:
# Move to local bin directory
mv dllb-server ~/.local/bin/

# Make executable
chmod +x ~/.local/bin/dllb-server

Option B: Compile dllb-server from Source (Rust / Cargo)

If you have the Rust toolchain installed (cargo):

# 1. Clone the dllb repository
git clone https://github.com/Oeditus/dllb.git
cd dllb

# 2. Build the optimized release binary
cargo build --release -p dllb-server

# 3. Option i: Copy the compiled binary to your PATH
cp target/release/dllb-server ~/.local/bin/

# OR Option ii: Leave it in sibling directory `../dllb/target/release/dllb-server`

How Ragex Finds dllb-server (Path Resolution Precedence)

When you run /ragex inside yoke, Ragex looks for the dllb-server executable automatically in this order:

  1. Custom Environment Variable: DLLB_SERVER_BIN=/path/to/dllb-server
  2. System $PATH: Directories in your $PATH (e.g. ~/.local/bin/dllb-server or /usr/local/bin/dllb-server).
  3. Sibling Repository Path: Relative path ../dllb/target/release/dllb-server or ../dllb/target/debug/dllb-server.

3. Verifying Your Installation

  1. Check yoke CLI:
    yoke --version
    
  2. Start yoke in any project:
    cd /path/to/your/project
    yoke
    
  3. Test Ragex Code Indexing: Inside the yoke REPL session, type:
    /ragex
    
    You should see confirmation that Ragex and the dllb knowledge graph backend have been successfully initialized!

Getting Started & Customization Guide

For complete, step-by-step instructions on onboarding, teaching Yoke language idiomatics, driving multi-step workflows, writing custom plugins, setting scoped rules, and tuning the iterative feedback loop, refer to the full Getting Started & Customization Guide (also accessible inside the REPL via /guide or /docs).

Onboarding & Customization Summary

  1. Core Architecture & Quickstart
    • BEAM actor isolation (Brain GenServer decoupled from Hands executor).
    • Basic CLI invocation (yoke, yoke "prompt"), inline @file / @url context references, and spatiotemporal /checkpoint & /undo.
  2. Teaching Yoke New Language Idiomatics (.yoke/practices)
    • LMML practice manifests in .yoke/practices/<language>.lmml.
    • Run /practices teach <language> to automatically inspect exemplary codebases and extract team-specific coding conventions.
  3. Starting & Driving Workflows (/workflow)
    • Run built-in engineering pipelines (/workflow run elixir "<task>").
    • Parallel subtasks execute in physically isolated Git worktrees under .yoke/workflows/.
  4. Tuning Workflows for Your Team's Needs
    • Scaffold custom JSON workflow definitions via /workflow init my-team-flow --from elixir.
  5. Writing Custom Elixir Plugins (Plugin.Behaviour)
    • Expose domain-specific tools by implementing Yoke.Plugin.Behaviour and hot-reloading live with /plugins reload.
  6. Managing Scoped Rules, Custom Skills & Ragex MCP
    • Set prompt preambles via /rules add <scope>:<text>, add modular skill packages in .yoke/skills/, and mount /ragex for SCIP/AST symbol graph search.
  7. The Iterative Feedback Loop: Fitting Expectations 100%
    • 4-step tuning cycle: Observe → Codify (.yoke/practices) → Automate (.yoke/workflows) → Snapshot & Replicate (version control .yoke/).

REPL Slash Commands & Shortcuts

The full reference lives in docs/cheat_sheet.md; the essentials are grouped below.

Shell & Console

Command Action
!command Execute shell command directly (e.g. !git status, !mix test)
!! Flip into/out of pure console mode (plain shell passthrough, no AI/tooling)
/git <subcommand> Run a raw git subcommand and print colorized output

Session, History & Persistence

Command Action
/resume [id] Resume specific session ID or open interactive conversation picker modal
/session [list|switch|cleanup] Inspect, switch, or prune persisted workspace sessions
/status Alias for /session -- active session & system status
/checkpoint List checkpoints with ID, label, and turn
/checkpoint <label> Save a labeled conversation snapshot
/undo Restore the latest conversation checkpoint and identify what was restored
/compact Compress context and show before/after token estimates and percentage change
/export [json|markdown] Export full session transcript to disk
/history [search <query>] Show or search persistent REPL input history
/cost | /tokens Display token usage breakdown and cumulative session cost

Git & Code Review

Command Action
/review [<base> [head] | <pr>] Interactive Human-in-the-Loop PR Code Review with finding triage ([i] Include, [e] Edit, [d] Drop), atomic inline diff comments, and living memory
/cr [<base> [head] | <pr>] Exact alias of /review, including explicit PR numbers and head revisions
/prboard | /review queue Live Pull Request review queue board (CI state, approval thresholds, re-review readiness)
/review next Auto-advance and start reviewing the next recommended PR in the queue
/review skip <pr> | /review unskip <pr> Commit-pinned PR skip (hides PR until author pushes new commits)
/review patterns View living codebase review tripwires (.yoke/review_patterns.md)
/review help Display comprehensive in-terminal review guide
/diff [branch] Display colorized git diff of workspace or against target branch
/commit <message> Auto-stage and commit workspace changes
/finish [files] [--commit-only] | /pr Complete work: auto-format, write 5-section structured commit, and create GitHub PR (or commit only with --commit-only)
/commit-structured [files] | /cpr Commit staged changes with the 5 structured PR sections without creating a PR
/linter <tool> [project|diff|cr] Run oeditus_credo, propwise, credo, or dialyzer (alias: /lint)
/audit [code|ux] Whole-project audit: strong parts, weaknesses & glitches, codebase + UX improvement ideas (grounded in measured facts)

Review commands inspect committed branch changes, not staged, unstaged, or untracked workspace edits. The default compares the configured base branch with HEAD; use /review HEAD~1 HEAD to review the last commit. Empty diffs and diffs over 300 KB stop with a diagnostic rather than generating a partial review.

For /review <pr_number>, Yoke fetches the exact GitHub base/head commits without checking out a branch or changing your files. Each review starts with fresh review context and revision-pinned, read-only tools. A configured model provider is required; offline canned responses are never treated as reviews. Malformed, truncated, or off-diff findings stop the workflow instead of becoming fix requests.

GitHub submission is opt-in and available for explicit PR-number reviews. Reviews retain the selected PR number and reviewed commit, and submission stops if the PR base or head has changed. Local branch reviews never guess a PR to publish to. Fix application is opt-in and offered only when Yoke runs at the repository root in a clean checkout of the reviewed head. The checkout is checked again after confirmation. Optional endorsements stay separate from actionable issues; pattern memory updates are also opt-in and happen after fix handling.

Model, Execution & Rules

Command Action
/model [flash|reasoner|coder|chat|r1|openrouter-free|ollama-qwen] Switch active model & reasoning/silent mode (deepseek-flash, deepseek-reasoner, deepseek-coder, etc.)
/endpoint [url|default|openrouter|opencode|ollama|lmstudio] Switch API base endpoint URL dynamically
/mode [local|remote|docker] Set Hands execution target
/sandbox [on|off] Restrict file references & tools to the workspace directory
/permissions [auto|ask] Set tool execution safety mode
/rules [add|delete|toggle] Manage scoped prompt preambles and launch deletion checkbox modal
/nodes View distributed Erlang node cluster status

Tooling & Extensibility

Command Action
/alias [list|show|add|rm|run|<name>] | /<name> Declare, inspect, manage, and execute reusable session command aliases
/plugins [reload|info] List tools or hot-reload plugins live without dropping state
/mcp [list|add|load] Manage Model Context Protocol (MCP) servers and tools
/ragex [stats|reindex|export] Mount and drive the first-class Ragex code analysis & refactoring MCP server
/skills [list|show|path|edit|new|<name>] | /skill <name> List, inspect, scaffold, or execute skills (arguments may be passed to a skill)
/subagent <prompt> Spawn a background subagent worker for sub-tasks
/workflow [list|run|status|resume|abort|init] Run customizable multi-step workflows (branch, describe, split & parallelize, test/docs, lint, commit)
/config [style|prompt|toggle] Manage prompt styles and UI toggles
/env Show runtime environment (Elixir/OTP version, model, workspace)
/update Update the release in the foreground and report its actual result

Utility

Command Action
/cb | /clipboard Copy latest assistant response to system clipboard
/clear Clear terminal output
/help Display help menu
/exit | /quit Exit Yoke and print conversation resume banner

CLI Subcommands

Besides the interactive REPL, yoke dispatches a handful of one-shot subcommands (yoke <subcommand> ...):

Subcommand Action
yoke review CI code review of a branch range
yoke lint Run the project's linters in CI mode
yoke describe Summarize the change set
yoke run <workflow> "<task>" Run a named workflow end-to-end
yoke audit Emit the AI Guard audit trail as a CI artifact
yoke fix [options] ["<command>"] Replay the last terminal command, analyse the failure, and plan a fix
yoke rag Query the Ragex knowledge graph
yoke report Upload a completed run's artifact to Yoke Cloud (optional, fail-open)

yoke fix

yoke fix reads the most recent command from your shell history (zsh extended format, bash, or fish -- Yoke's own invocations are skipped), re-runs it here, captures the output and exit status, and asks the agent to diagnose the root cause(s) and propose a concrete fix plan.

$ mix test test/foo_test.exs:42     # fails in your shell
$ yoke fix                          # replays it, triages, and plans the fix
$ yoke fix --apply                  # ...and lets the agent apply it
$ yoke fix --no-run                 # plan only, execute nothing
$ yoke fix "mix compile"            # explicit command instead of history

Options: -n/--no-run, -a/--apply, -p/--previous, --command <cmd>, --history-file <path>, --timeout <ms>, --session <id>, -h/--help. Exit codes: 0 the command succeeded, 1 it failed and a plan was produced, 2 usage error, 3 no command found in history.

--agent-timeout <ms> bounds the analysis turn separately from command replay. On timeout, Yoke cancels the turn and attempts to save its triage prompt and session. After a successful save it prints the session ID and an explicit continuation command using yoke -c <id>. This starts a new turn from saved context; it does not resurrect the cancelled task. Persistence failures are reported without claiming the session is resumable. Independently started background jobs retain their own lifecycle; inspect them with /jobs. Cancelling a turn does not undo side effects already performed.

Conversation checkpoints restore messages and provider settings, not working-tree files. /checkpoint lists them without creating a new one; use /checkpoint <label> to save a snapshot before an operation.


GitHub Action

Oeditus/yoke ships a composite GitHub Action (action.yml) for headless PR reviews, static linting, change descriptions, and audit reporting.

Quickstart: Pull Request Review

name: Yoke Review

on:
  pull_request:
    branches: [main]

permissions:
  contents: read
  pull-requests: write # required when post: 'true'

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # required to diff base and head commits

      - uses: Oeditus/yoke@v0
        with:
          command: review
          fail-on: high
          post: 'true'
        env:
          DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}

Static Linting (No LLM / No API Key)

- uses: Oeditus/yoke@v0
  with:
    command: lint
    fail-on: high
    post: 'false'

Inputs

Input Default Description
command 'review' Subcommand to run: review, lint, describe, run, audit, or rag
base '' Base revision to review or describe from (defaults to PR base SHA)
head '' Head revision to review or describe to (defaults to PR head SHA)
pr '' Pull request number (defaults to the triggering PR)
provider '' Provider profile name (deepseek, local, local-qwen)
model '' Model identifier for review, describe, or run (falls back to .yoke/config.json)
endpoint '' Chat-completions endpoint URL
fail-on '' Severity threshold (high, medium, low, info, never; defaults to high on PRs, never on push)
format '' Output format: summary, markdown, or json
max-cost '' Hard USD budget for review or describe
max-diff-bytes '' Override the review/describe diff cap in bytes (default 300000)
dry-run 'false' Resolve review context and exit without calling the model
post 'true' Post inline PR review comments (requires pull-requests: write)
with-ragex 'false' Enable Ragex code intelligence (dllb-server + .ragex/.yoke caches)
dllb-version '' dllb-server release tag (defaults to latest; 'skip' to disable)
upload 'true' Upload the JSON report artifact
artifact-name '' Uploaded artifact name (defaults to yoke-<command>)
yoke-version '' yoke release tag (defaults to latest, cached daily)
build-from-source 'false' Build the escript from the checked-out tree instead of downloading a release
elixir-version '1.20' Elixir version installed via erlef/setup-beam
otp-version '29' Erlang/OTP version installed via erlef/setup-beam

Outputs

Output Description
findings-count Number of issues found (endorsements excluded)
max-severity Highest issue severity found, or "none"
run-uid Stable identifier for the review run
report-path Path to the JSON artifact describing the run

[!NOTE] Fork PRs: GitHub does not expose repository secrets to pull_request workflows triggered from forks, and GITHUB_TOKEN is read-only. For fork PRs, run command: lint (no secret required) or set post: 'false' when credentials are absent.


Configuration

yoke reads settings from ~/.yoke/config.json (global) merged with .yoke/config.json (per-workspace override, taking precedence). Notable keys:

Key Default Purpose
model "deepseek-flash" Default LLM model identifier
reasoning nil (auto) Enable/disable thinking & reasoning traces (true or false)
reasoning_effort nil (or "none") Reasoning effort constraint ("none", "low", "medium", "high")
reasoning_color "yellow" ANSI color for Marcli Markdown reasoning output blocks
endpoint "https://api.deepseek.com/chat/completions" LLM API base endpoint URL (DeepSeek, OpenRouter, Ollama, etc.)
prompt_style "starship" Prompt layout: starship, extended, compact, or minimal
permission_mode "ask_confirm" Tool execution safety mode (ask_confirm or auto_approve)
sandbox_workspace false Restrict file references & tools to the workspace directory
enable_autosuggestions true Fish-style ghost autosuggestions from input history
enable_syntax_highlighting true Highlight /commands and !shell lines as you type
enable_context_gauge true Show the token/cost usage gauge on the idle status bar
compact_status_bar false Swap the gauge for a compact id + message count line
max_context_tokens 64000 Assumed model context window used by the usage gauge
max_tool_depth 1000 Consecutive tool-calling turns before pausing to confirm
chat_receive_timeout_ms 300000 Wall-clock ceiling for one chat-completion HTTP response. A provider that accepts the connection and then never responds fails with a timeout instead of wedging the session. Raise it for very slow local models.

Manage most of these live from the REPL with /config style <name>, /config prompt <template>, and /config toggle <key> -- or toggle permission mode, sandbox bounds, and the status bar mode instantly with Ctrl+P, Ctrl+G, and Ctrl+B.


Documentation


Roadmap & Future Enhancements (TODO)

  • Sandboxed Code Mode over MCP: Implement a sandboxed Lua expression surface over MCP tools (lua_docs, lua_eval) allowing external and internal subagents to project, filter, and aggregate large data structures or file fields on the host without loading multi-megabyte raw context into model prompts.
  • Enhanced Git Worktree Isolation & Multi-Lock Serialization: Introduce dual-lock mechanics (gate_lock for CPU/testing serialization and land_lock for branch advancement) alongside warm dependency cache copying (deps/_build) for git worktree subagents managed by the workflow engine.

License

MIT, see LICENSE -- with one additional restriction: this project may not be used, modified, or distributed as a harness, adapter, or integration layer for proprietary third-party models from OpenAI, Anthropic, or Google (e.g. GPT, Claude, Gemini), whether accessed directly or through an intermediary API, proxy, or aggregator.

Yoke
Yoke (Yoke) -- Actors, Hot-Code Reloading, Distributed Brain/Hands, Spatiotemporal Checkpoints.

探索相关项目

加载中…