# Agent engine Agent engine [#agent-engine] XibeCode’s core (`xibecode-core`) runs an **autonomous coding agent**: model calls → tool use → file/shell changes → verify → continue until the task is done or you stop it. Surfaces [#surfaces] | Surface | Command | Notes | | ---------------- | ----------------------------- | ------------------------------ | | One-shot task | `xibecode run "…"` | Non-interactive autonomous run | | Task + PR | `xibecode run-pr "…"` | Branch + GitHub PR after work | | Interactive chat | `xibecode chat` / `xc` | TUI with slash commands | | Messaging | `xibecode daemon` / `gateway` | Telegram / Discord / Slack | | Scheduled | `xibecode cron` + daemon | Periodic agent jobs | | IDE / ACP | VS Code extension, ACP stdio | Same engine, different hosts | Agent loop [#agent-loop] 1. Build context (project files, curated memory, skills, session history). 2. Call the LLM with tools (read/write/edit, shell, search, MCP, etc.). 3. Execute tool calls safely under permission rules. 4. Feed results back; **repeat** until: * the model finishes with a final answer, or * you **abort** (Ctrl+C, chat cancel, daemon `/stop`), or * a **finite** iteration cap is hit. On **tool failure**, the engine injects a recovery message (retry with new params, alternative tool, or finish with a failure summary) so runs do not spin silently. Max iterations (unlimited by default) [#max-iterations-unlimited-by-default] | Value | Behavior | | ----------------- | ---------------------------------------------- | | **`0`** (default) | **Unlimited** — loop until completion or abort | | Positive integer | Hard stop after N model turns | ```bash # Unlimited (default) xibecode run "refactor auth module" # Cap at 100 turns xibecode run "…" -d 100 # Profile default xibecode config # or setup agent → Max agent iterations = 0 ``` Economy cost mode still applies a separate lower cap (`economyMaxIterations`) so cheap runs stay bounded. **Anti-runaway:** repeated identical tool calls are blocked by the loop detector; you can always interrupt. Auto-compact [#auto-compact] When the conversation nears the model’s context budget, XibeCode **auto-compacts** so long tasks can continue. When it triggers [#when-it-triggers] * **Preflight** and **post-turn** checks each agent iteration. * Roughly **\~75%** of context for typical windows (≤512k), **\~50%** for huge windows. * Always leaves headroom: never later than `window − autoCompactThreshold` (default **\~13k** tokens free for the next reply). What happens [#what-happens] 1. **Microcompact** — strip or shrink old tool results. 2. **Full handoff** — structured summary + grounded facts ledger + **token-budget tail** (not a fixed message count). 3. Prior compaction summaries are folded in; the model is told not to re-answer resolved work. User-visible status [#user-visible-status] * Compacting context — summarizing earlier conversation… * Context compacted · … tokens (Telegram/daemon shows the same as progress messages.) Disable / tune [#disable--tune] ```json { "autoCompactEnabled": false, "autoCompactThreshold": 13000 } ``` ```bash XIBECODE_AUTO_COMPACT=0 # disable ``` Lifecycle hooks: `PreCompact` / `PostCompact` (see [Hooks](/docs/hooks)). Modes [#modes] Modes control tool categories and behavior (agent, plan, review, debugger, …). See [Modes](/docs/modes). Plan and review modes still allow shell where needed for verification. Tools [#tools] File ops, shell, search, web fetch, memory (`curated_memory`, project memory), skills (`list_skills` / `view_skill`), swarm, MCP tools, screenshots, and more. See [Tools](/docs/tools). Browser note: **Playwright is not bundled**. Prefer **`agent-browser`** (optional install) or host Chromium for screenshots; other browser audit tools may return guidance stubs. Learning & memory [#learning--memory] After turns, optional **learning loop** features: * Curated `MEMORY.md` / `USER.md` (frozen at session start; disk updates immediate for next session) * Post-turn review (optional cheap model) * Write-approval for sensitive memory/skill writes * Session search across past work * Skill learner for reusable procedures See [Memory](/docs/memory). Providers & models [#providers--models] Any catalog entry from [Providers](/docs/providers). Live `/models`, models.dev registry, and curated fallbacks. Failover pools improve reliability under rate limits. Cloud execution [#cloud-execution] Optional E2B sandbox runtime: shell in the cloud while files stay on host (`host_only`) or full workspace sync (`sandbox_full`). See [Cloud / E2B](/docs/cloud-e2b). File history / checkpoints [#file-history--checkpoints] On-disk checkpoints under `~/.xibecode/file-history/` with message-linked snapshots. Disable with `XIBECODE_DISABLE_FILE_CHECKPOINTING=1`. Best practices [#best-practices] 1. Run `xibecode setup` once, then `xibecode chat` for interactive work. 2. Prefer **unlimited iterations** for large refactors; use `-d N` only when you want a hard budget. 3. Use **economy mode** for cheap drafts; normal mode for production changes. 4. For always-on coding from phone/Telegram, install the [daemon](/docs/gateway) and use `/stop` if a run goes wrong; `/cmd` for quick shell without the agent. 5. Let auto-compact run on long chats; only disable if you need the full raw history in context. # Canonical Facts for Assistants Use these facts as the source of truth for common support questions. Current product line: **CLI/Core 1.17.x**. Runtime Facts [#runtime-facts] * If a user asks “what does `xc` run by default?”, the correct answer is: default `xc`/`xibecode` runs **local** mode for that process. * If a user asks “how do I run cloud mode?”, the correct answer is: use `xibecode cloud` (or `xc cloud`). * If a user asks “is the whole CLI streamed from sandbox?”, the correct answer is: for laptop `xibecode cloud`, no — chat CLI runs locally; tools route remotely. A daemon **installed inside** E2B is a different hosted setup. * If a user asks “does plain `xibecode resume` open cloud?”, the correct answer is: **no** — host-stored sessions resume **locally**. Use `xibecode cloud resume ` (or `xibecode resume cloud `) for shared sandboxes. Strategy Facts [#strategy-facts] * If a user asks “what is `host_only`?”, the correct answer is: command execution is remote, file tools stay local. * If a user asks “what is `sandbox_full`?”, the correct answer is: workspace is synced to sandbox and file + command tools run there. * If a user asks “why did host absolute paths fail?”, the correct answer is: in `sandbox_full`, host absolute paths are outside the sandbox workspace; use repo-relative paths. Session Facts [#session-facts] * If a user asks “where are interactive sessions stored?”, the correct answer is under `~/.xibecode/` project-scoped session paths (JSONL primary; legacy `.json` may exist). * If a user asks “where are Telegram/daemon chats stored?”, the correct answer is: `~/.xibecode/daemon/sessions/` (kept across E2B `/update` restart). * If a user asks “how can I resume a cloud sandbox by id?”, the correct answer is: `xibecode cloud resume `. Pull and Preview Facts [#pull-and-preview-facts] * If a user asks “how do I pull cloud changes locally?”, the correct answer is: `xibecode cloud pull --session ` or `/cpull` in chat. * If a user asks “how do I apply pulled files directly?”, the correct answer is: use `--apply` (merges **new/changed** files only; identical local files are skipped). * If a user asks “how do I overwrite every file from the sandbox like a full extract?”, the correct answer is: `--apply --full` or `/cpull --apply --full`. * If a user asks “does cloud pull download only diffs?”, the correct answer is: the gateway export is still a **full workspace archive**; `--apply` avoids rewriting identical files on disk. * If a user asks “what is the preview URL shape?”, the correct answer is: usually `https://{port}-{sandboxId}.e2b.dev`. * If a user asks “why is Vite blocking the preview host?”, the correct answer is: set `server.host: '0.0.0.0'` and `server.allowedHosts: true` (or allow `.e2b.dev`). Daemon / Messaging Facts [#daemon--messaging-facts] * If a user asks “gateway vs daemon?”, the correct answer is: `xibecode daemon` is primary; `xibecode gateway` is a full alias of the same process. * If a user asks “what is `/cmd`?”, the correct answer is: runs a shell command in the chat **workdir** without the agent loop; aliases `/sh` `/shell`; timeout via `XIBECODE_CMD_TIMEOUT_MS` (default 60s). * If a user asks “what happens if I message while the agent is busy?”, the correct answer is: default **steer** injects into the same run; `/queue` forces FIFO; `/stop` interrupts and frees the chat. Env: `XIBECODE_BUSY_INPUT_MODE=steer|queue|interrupt`. * If a user asks “how do I update the CLI on E2B Telegram?”, the correct answer is: `/update yes` (or dashboard Update) — install latest (sudo when needed) + restart daemon; chat sessions kept. * If a user asks “can Telegram send files?”, the correct answer is: yes — agent replies with `MEDIA:path` (images, documents, video, audio); screenshots auto-attach when possible. Memory Facts [#memory-facts] * If a user asks “where is durable memory?”, the correct answer is: `~/.xibecode/memories/MEMORY.md` and `USER.md`, written via `curated_memory`. * If a user asks “are mid-session memory writes in the prompt immediately?”, the correct answer is: disk is updated immediately, but the **system-prompt snapshot is frozen at session start**; next session loads them. * If a user asks “what is auto-compact?”, the correct answer is: when context nears budget, microcompact then full handoff (summary + grounded facts + token-budget tail). Disable with `autoCompactEnabled: false` or `XIBECODE_AUTO_COMPACT=0`. Chat Slash Command Facts [#chat-slash-command-facts] * If a user asks “is `/cpull` supported?”, the correct answer is: yes, for cloud `sandbox_full` chat sessions. * If a user asks “what does `/commit` do?”, the correct answer is: stages all changes and commits; no-arg auto-message, arg form uses provided message. * If a user asks “where is the canonical slash command list?”, the correct answer is: `/docs/chat-slash-commands` (TUI) and `/docs/gateway` (messaging). Config Resolution Facts [#config-resolution-facts] * If a user asks “how are cloud gateway values resolved?”, the correct answer is: environment variables first, then profile config, then built-in defaults. * If a user asks “what is maxIterations default?”, the correct answer is: **`0` (unlimited)** until completion or abort. * If a user asks “is Playwright installed with xibecode?”, the correct answer is: **no** — not a dependency; use `agent-browser`, host Chromium, MCP, or project Playwright. File History Facts [#file-history-facts] * If a user asks “where are file checkpoints stored?”, the correct answer is: `~/.xibecode/file-history/`. * If a user asks “how do I disable checkpointing?”, the correct answer is: set `XIBECODE_DISABLE_FILE_CHECKPOINTING=1`. Source References [#source-references] * Daemon: [/docs/gateway](/docs/gateway) * Cloud: [/docs/cloud-e2b](/docs/cloud-e2b) * Memory: [/docs/memory](/docs/memory) * Agent / auto-compact: [/docs/agent](/docs/agent) * Security: [SECURITY.md](https://github.com/iotserver24/Xibecode/blob/main/SECURITY.md) * Repo guide: [DOCS.md](https://github.com/iotserver24/Xibecode/blob/main/DOCS.md) (if present) # Chat Slash Commands XibeCode has **two** slash-command surfaces: 1. **Interactive TUI** — `xibecode chat` / `xc` (this page, first half) 2. **Messaging daemon** — Telegram / Discord / Slack via `xibecode daemon` (second half + [full daemon docs](/docs/gateway)) Interactive chat (TUI) [#interactive-chat-tui] Autocomplete and input [#autocomplete-and-input] * Type `/` and a prefix: **↑/↓** cycles matching commands; **Tab** fills in the highlighted command. * **Tab** adds a trailing space after `/model`, `/format`, and `/mode` so you can type an argument immediately. * While the agent **is running**, your next line is **queued** (you see `Queued message — will run next.`) instead of interrupting; after the run finishes, that line is sent automatically. * During a run, **Esc** aborts the current turn (not the whole session). * **Ctrl+C** exits the chat app. Status line [#status-line] The footer shows **`model`**, **`format`** (`auto` | `openai` | `anthropic`), **`mode`**, and **`provider`**, plus idle vs working state (spinner and elapsed time when busy). `/setup` — guided setup [#setup--guided-setup] Runs when you type `/setup`, or **automatically on first launch** if no API key is configured. **Flow** 1. **Provider preset** (↑/↓, **Enter**, **Esc** cancels) * Routing.run, zenllm.org, OpenAI, Anthropic, OpenRouter, Groq, DeepSeek, Google (Gemini), xAI (Grok), Moonshot (Kimi), Zhipu AI (z.ai), or **Custom**. 2. **Base URL** (Custom path, or skipped for presets) 3. **API key** — stored via `ConfigManager` 4. **Fetch `/models`** — OpenAI-style `GET {baseUrl}/models` 5. **Pick a model** — same apply path as `/model` `/config` — quick config menu [#config--quick-config-menu] | Item | What it does | | ---------------------------- | ---------------------------------------------------------------------------------------------------- | | Set Base URL (OpenAI format) | Prompts for URL | | Set API key | Prompts for key | | Pick model from `/models` | Requires base URL + key | | Set provider | auto-detect, openai, anthropic, deepseek, openrouter, google, grok, kimi, zai, routingrun, zenllm, … | | Set cost mode | `normal` or `economy` | | Set economy model | Prompts for model id | | Show config summary | apiKey, provider, model, costMode, baseUrl, requestFormat, sandbox/runtime | | Close | Returns to chat | `/format` [#format] * No argument: prints current `requestFormat` and effective wire format. * `/format auto | anthropic | openai` — updates format and clears the cached model list. `/model` [#model] * No argument: interactive picker, or `/model ` directly. * `/model default` restores the default model for the session/profile. `/mode` [#mode] * No argument: mode picker (agent, plan, review, …). * `/mode ` switches directly. `/help` [#help] Prints the shortcut list and notes **vision**: image paths or `@path` can attach pixels when the file exists. `/memory` [#memory] * `/memory` or `/memory list` — up to 10 project auto-memories (`xc memory list` for full list) * `/memory dream` — dream consolidation * `/memory path` — memory directory Curated global MEMORY/USER is agent-driven (`curated_memory` tool); see [Memory](/docs/memory). `/hooks` [#hooks] `/hooks` or `/hooks list` — lifecycle hooks. Manage with **`xc hooks`**. TUI command summary [#tui-command-summary] | Command | What it does | | ---------------------- | -------------------------------------------- | | `/help` | Shortcuts + vision hint | | `/mode` | Mode picker or `/mode ` | | `/clear` | Transcript cleared divider (scrollback kept) | | `/format` | Show or set wire format | | `/model` | Model picker or `/model ` | | `/setup` | Full setup wizard | | `/config` | Quick config menu | | `/memory` | `list` / `dream` / `path` | | `/hooks` | `list` | | `/cpull` | Pull sandbox workspace (`sandbox_full` only) | | `/commit` | `git add` + commit | | `/donate` / `/sponsor` | Opens donation site | | `/exit` | Persist session, exit | `/cpull` (cloud TUI) [#cpull-cloud-tui] ```bash /cpull /cpull --apply /cpull --apply --full /cpull --output .xibecode/sandbox-pull-manual /cpull --apply --force ``` Only in **cloud `sandbox_full`** sessions. Without `--apply`, downloads to a timestamped folder. With `--apply`, merges **new/changed** files only; `--apply --full` overwrites like a full extract. See [Cloud / E2B](/docs/cloud-e2b). `/commit` [#commit] ```bash /commit /commit fix: handle missing cloud session id ``` Runs `git add .`, then commits (auto message or provided message). No-op if nothing staged. Plan mode questions [#plan-mode-questions] **↑/↓** + **Enter** to choose; **custom / type yourself** for free text; **Esc** from custom returns to the list. *** Messaging daemon (Telegram / Discord / Slack) [#messaging-daemon-telegram--discord--slack] Full reference: [Xibe Daemon](/docs/gateway). Summary: | Command | What it does | | --------------------------------------------- | ------------------------------------------------------- | | `/start` `/help` | Welcome / full help | | `/new` `/reset` `/clear` | Clear conversation | | `/stop` | Interrupt run + free chat immediately | | `/status` | Workdir, busy, progress, sandbox id | | `/queue` · `/queue ` · `/queue clear` | FIFO queue control | | `/workdir [path]` | Project directory for this chat | | `/progress on\|off` | Tool progress | | `/level yolo\|default\|strict` | Approval / evidence rigor | | `/model` `/models` | Model list / set (`--global` optional) | | `/skills` `/skill ` | Skills catalog | | **`/cmd `** | Shell in workdir (**no agent**); aliases `/sh` `/shell` | | `/update` · `/update yes` · `/update no` | CLI update (e2b: install + restart) | | `/mode` | Runtime mode `default` \| `e2b` | | `/sethome` | Cron delivery home | | `/once` `/session` `/always` `/deny` | Approve/deny dangerous commands | Busy behavior (daemon) [#busy-behavior-daemon] Default **`steer`**: plain messages inject into the current run. Use `/queue …` for FIFO only, `/stop` to hard interrupt. ```bash XIBECODE_BUSY_INPUT_MODE=steer|queue|interrupt XIBECODE_CMD_TIMEOUT_MS=60000 ``` Examples [#examples] ```text /cmd ls -la /cmd tail -n 40 ~/.xibecode/daemon/logs/daemon.log /update yes /queue run the unit tests after this finishes ``` *** Tips [#tips] * Use `/help` anytime for the commands available on **that** surface (TUI vs Telegram menu). * Use `/mode plan` for design, then `/mode agent` to execute (TUI). * Use `/cpull` to bring sandbox work back without leaving cloud chat. * On Telegram, type `/` to open the bot command menu. # Cloud & E2B Runtime This page is the canonical runtime guide for cloud execution in XibeCode. Local vs Cloud (Critical) [#local-vs-cloud-critical] * Running `xibecode` or `xc` with no subcommand runs in **local** mode for that process. * Running `xibecode cloud` or `xc cloud` forces **E2B-backed** execution for that process. * The terminal UI still runs on your machine. In cloud mode, tool execution is routed through the configured gateway/E2B session. * Plain `xibecode resume` resumes **host-stored** sessions **locally** — it does **not** pick up global E2B / `sandbox_full` from profile alone. * To continue a **shared cloud sandbox**, use explicitly: ```bash xibecode cloud resume # or xibecode resume cloud ``` What Runs Where [#what-runs-where] In cloud mode, behavior depends on `sandboxSessionStrategy`: `host_only` [#host_only] * `run_command` executes in the remote sandbox. * File tools still read and write your local repository. * Best when you only need isolated command execution. `sandbox_full` [#sandbox_full] * The CLI syncs your workspace to a sandbox first. * File tools and command tools run in the sandbox workspace. * Use **repo-relative** paths in prompts and tool calls. * Do not rely on host absolute paths for sandbox file operations. Core Cloud Commands [#core-cloud-commands] ```bash # Start cloud chat (E2B-backed for this process) xibecode cloud # Resume a shared/existing sandbox using sandbox ID xibecode cloud resume # Pull sandbox workspace back to local disk (extracts to a timestamped folder under .xibecode/) xibecode cloud pull --session # Merge sandbox files into the current directory (default: only new or changed files; skips identical copies) xibecode cloud pull --session --apply # Legacy: extract the full archive over cwd (every path from the archive is written) xibecode cloud pull --session --apply --full ``` What `--apply` does (default) [#what---apply-does-default] With `--apply`, the CLI still **downloads the full workspace archive** from the gateway, but copies into your project only when: * the file is **missing** locally, or * the file **exists but content differs** (size or bytes). Identical files are left untouched. Files only on your machine are **not** deleted. Use **`--apply --full`** to extract the entire tarball **directly** into the working directory. In-chat pull shortcut [#in-chat-pull-shortcut] ```bash /cpull /cpull --apply /cpull --apply --full /cpull --output .xibecode/sandbox-pull-manual ``` `/cpull` is only available in `sandbox_full` sessions. Options match the CLI. Runtime modes on hosted sandboxes [#runtime-modes-on-hosted-sandboxes] When the **daemon** runs **inside** an E2B (or similar) sandbox — e.g. a always-on Telegram box — it uses runtime mode **`e2b`** (auto-detected or `XIBECODE_RUNTIME_MODE=e2b`): | Feature | Behavior | | ------------------------- | ----------------------------------------------------------------------------------------------------- | | `/update` · `/update yes` | `npm i -g xibecode@latest` (with `sudo -n` when global prefix is root-owned), then **restart daemon** | | Chat memory | Kept in `~/.xibecode/daemon/sessions/` across restart | | Sandbox id | Injected into system prompt; shown on `/status` / `/mode` | | Passwordless sudo | Allowed for package installs; catastrophic cmds still blocked | | Preview URLs | `https://{port}-{sandboxId}.e2b.dev` | | Startup update offer | Only in e2b mode | Local host daemons use mode **`default`** (no auto self-update restart). CLI update anywhere (never silent): ```bash xibecode update --check xibecode update --apply --yes xibecode update --apply --yes --to 1.17.0 ``` Disable checks: `XIBECODE_DISABLE_UPDATE_CHECK=1` or `XIBECODE_DISABLE_AUTO_UPDATE=1`. Preview URLs & Vite [#preview-urls--vite] Typical shape: `https://{port}-{sandboxId}.e2b.dev` For **Vite** apps in the sandbox, configure: ```ts // vite.config — required so e2b.dev host is allowed server: { host: '0.0.0.0', allowedHosts: true, // or include '.e2b.dev' } ``` Without this, the preview may show “host is not allowed”. Browser / screenshots in the sandbox [#browser--screenshots-in-the-sandbox] * **Playwright is not a CLI dependency** (no Chromium download on `npm install`). * Prefer **`agent-browser`** for `take_screenshot` (then headless Chrome/Chromium). * Official E2B templates may ship `agent-browser` + Chrome for Testing + a pinned `xibecode` tarball. * Screenshot **paths must be workspace-relative** (e.g. `screenshots/home.png`). Absolute `/tmp/...` paths are remapped into `screenshots/`. * Include `MEDIA:path` in the final reply (or rely on auto-attach) so Telegram delivers the PNG. Override browser preference: `XIBECODE_PREFERRED_BROWSER=chrome`. Gateway and Auth Resolution [#gateway-and-auth-resolution] For gateway URL and auth token, the CLI resolves values in this order: 1. Runtime environment variables (`XIBECODE_SANDBOX_*`) 2. Saved profile/config values (`xibecode config --set-sandbox-*`) 3. Built-in defaults configured by the distributor Team E2B gateway: pause and auto-resume [#team-e2b-gateway-pause-and-auto-resume] If you self-host `packages/e2b-gateway`, sandboxes are created with **pause on idle timeout** (not kill) and **auto-resume** on the next gateway request, SDK operation, or HTTP hit to a preview URL. * **`XIBECODE_E2B_SANDBOX_TIMEOUT_MS`** — inactivity before pause (default **900000**, 15 minutes). * **`XIBECODE_E2B_TEMPLATE`** — published template id or alias. See `packages/e2b-gateway/.env.example` for copy-paste variables. Cloud Configuration Flags [#cloud-configuration-flags] ```bash xibecode config --set-sandbox-mode e2b xibecode config --set-sandbox-gateway-url "https://your-gateway.example.com" xibecode config --set-sandbox-auth-token "your-shared-token" xibecode config --set-sandbox-session-strategy sandbox_full xibecode config --set-sandbox-sync-max-mb 50 xibecode config --set-sandbox-sync-exclude ".git,node_modules,.xibecode,dist,build,.env,.env.*" xibecode config --set-sandbox-sync-respect-gitignore true ``` Environment Variables Reference [#environment-variables-reference] * `XIBECODE_SANDBOX_MODE` (`local` or `e2b`) * `XIBECODE_SANDBOX_SESSION_ID` (reuse an existing session id) * `XIBECODE_SANDBOX_SKIP_SYNC` (`1`/`true` skips initial sync) * `XIBECODE_SANDBOX_GATEWAY_URL` * `XIBECODE_SANDBOX_AUTH_TOKEN` * `XIBECODE_SANDBOX_STRATEGY` (`host_only` or `sandbox_full`) * `XIBECODE_SANDBOX_SYNC_MAX_MB` * `XIBECODE_SANDBOX_SYNC_EXCLUDE` * `XIBECODE_SANDBOX_SYNC_RESPECT_GITIGNORE` * `XIBECODE_RUNTIME_MODE` (`default` | `e2b` — daemon inside sandbox) * `XIBECODE_E2B_TEMPLATE` * `XIBECODE_E2B_SANDBOX_TIMEOUT_MS` * `E2B_SANDBOX_ID` (or file `/run/e2b/.E2B_SANDBOX_ID`) FAQ [#faq] Is the full CLI running inside E2B and streamed back? [#is-the-full-cli-running-inside-e2b-and-streamed-back] For **`xibecode cloud`** from your laptop: no — the CLI process and chat UI run locally; tool execution is remote. For a **hosted daemon** installed *inside* a sandbox (Telegram 24/7 box): yes, the daemon process lives in the sandbox; clients are messaging apps, not a streamed TUI. Why do some paths fail in `sandbox_full`? [#why-do-some-paths-fail-in-sandbox_full] The sandbox does not share your host absolute paths. Use paths relative to the synced repo root. How do I share work with another user? [#how-do-i-share-work-with-another-user] Share the sandbox ID: ```bash xibecode cloud resume ``` Then pull with `xibecode cloud pull` or `/cpull`. How do I get the latest CLI on a live sandbox? [#how-do-i-get-the-latest-cli-on-a-live-sandbox] Use **`/update yes`** in Telegram (or the dashboard Update control), or rebuild the E2B template so new sandboxes ship a newer pin. Related [#related] * [Xibe Daemon](/docs/gateway) — `/cmd`, `/update`, media, steer * [Chat slash commands](/docs/chat-slash-commands) * [Configuration](/docs/configuration) # Configuration XibeCode stores its configuration in `~/.xibecode/`. You can manage settings via the CLI or by editing the config file directly. Interactive Setup [#interactive-setup] ```bash xibecode config ``` This opens an interactive menu to configure all settings including API key, model, package manager, default mode, and safety settings. Quick Commands [#quick-commands] ```bash # Set API key xibecode config --set-key YOUR_ANTHROPIC_API_KEY # Set custom API endpoint xibecode config --set-url https://your-custom-endpoint.com # Set default model xibecode config --set-model claude-sonnet-4-5-20250929 # View current config xibecode config --show # Reset all settings xibecode config --reset ``` Configuration File [#configuration-file] The main configuration file is located at `~/.xibecode/config.json`: ```json { "apiKey": "sk-ant-...", "baseUrl": "https://api.anthropic.com", "model": "claude-sonnet-4-5-20250929", "maxIterations": 0, "autoCompactEnabled": true, "autoCompactThreshold": 13000, "defaultVerbose": false, "preferredPackageManager": "pnpm", "enableDryRunByDefault": false, "gitCheckpointStrategy": "stash", "defaultMode": "agent", "autoApprovalPolicy": "always", "plugins": [], "mcpServers": {} } ``` Configuration Options [#configuration-options] | Setting | Description | Default | | ------------------------- | ---------------------------------------------------- | ---------------------------- | | `apiKey` | Your AI provider API key (Anthropic, OpenAI) | — | | `baseUrl` | Custom API endpoint (Azure, AWS Bedrock, etc.) | Anthropic default | | `model` | Default AI model to use | `claude-sonnet-4-5-20250929` | | `maxIterations` | Max agent turns; **`0` = unlimited** | `0` | | `autoCompactEnabled` | Auto microcompact + full handoff near context budget | `true` | | `autoCompactThreshold` | Tokens to keep free when deciding to compact | `13000` | | `defaultVerbose` | Enable verbose logging by default | `false` | | `preferredPackageManager` | Package manager: pnpm, bun, npm, or yarn | `pnpm` | | `enableDryRunByDefault` | Run in dry-run mode by default | `false` | | `gitCheckpointStrategy` | Git checkpoint method: stash or commit | `stash` | | `defaultMode` | Default agent mode to start in | `agent` | | `autoApprovalPolicy` | Mode transition approval: always, prompt-only, never | `always` | | `testCommandOverride` | Custom test command (overrides auto-detection) | Auto-detected | | `plugins` | Array of plugin file paths | `[]` | | `mcpServers` | MCP server configurations | `{}` | Environment Variables [#environment-variables] ```bash # API Keys (examples — many providers supported; see Providers docs) ANTHROPIC_API_KEY=your_key OPENAI_API_KEY=your_key OPENROUTER_API_KEY=your_key ROUTINGRUN_API_KEY=your_key ZENLLM_API_KEY=your_key # API Configuration ANTHROPIC_BASE_URL=https://... # Custom endpoint XIBECODE_MODEL=claude-opus-4-... # Default model # Behavior XIBECODE_DRY_RUN=true # Enable dry-run by default XIBECODE_VERBOSE=true # Enable verbose logging XIBECODE_MODE=plan # Default agent mode XIBECODE_AUTO_COMPACT=0 # Disable auto-compact XIBECODE_DISABLE_FILE_CHECKPOINTING=1 # Disable file-history snapshots XIBECODE_HOME=~/.xibecode # Override home directory # Daemon / messaging XIBECODE_BUSY_INPUT_MODE=steer # steer | queue | interrupt XIBECODE_RUNTIME_MODE=default # default | e2b XIBECODE_CMD_TIMEOUT_MS=60000 # /cmd shell timeout XIBECODE_DAEMON_VERBOSE=1 # Tool traces in daemon logs XIBECODE_DISABLE_UPDATE_CHECK=1 # Skip npm update offers ``` Sandbox / Cloud Configuration [#sandbox--cloud-configuration] Cloud execution is configured with dedicated sandbox settings: ```bash xibecode config --set-sandbox-mode e2b xibecode config --set-sandbox-gateway-url "https://your-gateway.example.com" xibecode config --set-sandbox-auth-token "your-shared-token" xibecode config --set-sandbox-session-strategy sandbox_full xibecode config --set-sandbox-sync-max-mb 50 xibecode config --set-sandbox-sync-exclude ".git,node_modules,.xibecode,dist,build,.env,.env.*" xibecode config --set-sandbox-sync-respect-gitignore true ``` Strategies [#strategies] * `host_only` - remote shell execution, local file tools * `sandbox_full` - synced workspace, remote file and command execution Relevant cloud env vars [#relevant-cloud-env-vars] ```bash XIBECODE_SANDBOX_MODE=e2b XIBECODE_SANDBOX_GATEWAY_URL=https://your-gateway.example.com XIBECODE_SANDBOX_AUTH_TOKEN=your-shared-token XIBECODE_SANDBOX_STRATEGY=sandbox_full XIBECODE_SANDBOX_SYNC_MAX_MB=50 XIBECODE_SANDBOX_SYNC_EXCLUDE=.git,node_modules,.xibecode XIBECODE_SANDBOX_SYNC_RESPECT_GITIGNORE=1 XIBECODE_SANDBOX_SESSION_ID= XIBECODE_SANDBOX_SKIP_SYNC=1 XIBECODE_E2B_TEMPLATE= XIBECODE_E2B_SANDBOX_TIMEOUT_MS=900000 XIBECODE_RUNTIME_MODE=e2b ``` Priority Order [#priority-order] Configuration is resolved in this order (highest priority first): 1. **CLI flags** (e.g., `--api-key`, `--model`) 2. **Environment variables** 3. **Project-level config** (`.xibecode/config.json`) 4. **Global config file** (`~/.xibecode/config.json`) Agent Mode Configuration [#agent-mode-configuration] ```json { "defaultMode": "agent", "autoApprovalPolicy": "prompt-only" } ``` Auto-approval policies: * `always` — Auto-approve all mode transitions * `prompt-only` — Require confirmation for escalation (read -> write) * `always-for-debugger` — Auto-approve only debugger transitions * `never` — Always require confirmation Custom API Endpoints [#custom-api-endpoints] XibeCode supports custom API endpoints, making it compatible with Azure OpenAI, AWS Bedrock, or any Claude-compatible API: ```bash # Via config xibecode config --set-url https://your-custom-endpoint.com # Via CLI flag xibecode run "task" --base-url https://your-custom-endpoint.com # Via environment variable export ANTHROPIC_BASE_URL=https://your-custom-endpoint.com ``` Azure OpenAI Example [#azure-openai-example] ```json { "baseUrl": "https://your-resource.openai.azure.com", "apiKey": "your-azure-api-key", "model": "your-deployment-name" } ``` AWS Bedrock Example [#aws-bedrock-example] ```json { "baseUrl": "https://bedrock-runtime.us-east-1.amazonaws.com", "apiKey": "your-aws-credentials", "model": "anthropic.claude-3-sonnet-20240229-v1:0" } ``` Package Manager Detection [#package-manager-detection] XibeCode automatically detects your preferred package manager by checking for lock files: 1. `pnpm-lock.yaml` → pnpm 2. `bun.lockb` → bun 3. `yarn.lock` → yarn 4. `package-lock.json` → npm Override this with the `preferredPackageManager` setting. Test Runner Configuration [#test-runner-configuration] XibeCode auto-detects test runners: * **Vitest** — vitest.config.ts or vitest in package.json * **Jest** — jest.config.js or jest in package.json * **Mocha** — .mocharc.js or mocha in package.json * **pytest** — pytest.ini or pyproject.toml * **Go test** — go.mod file present * **Cargo test** — Cargo.toml file present Override with a custom test command: ```json { "testCommandOverride": "npm run test:unit" } ``` Git Checkpoint Strategies [#git-checkpoint-strategies] * `stash` — Uses git stash (recommended, lightweight) * `commit` — Creates a commit (persistent history) ```json { "gitCheckpointStrategy": "stash" } ``` Project-Level Configuration [#project-level-configuration] Create a `.xibecode/config.json` in your project root for project-specific settings: ```json { "testCommandOverride": "pnpm test", "defaultMode": "tester", "plugins": ["./custom-plugin.js"] } ``` Backup Configuration [#backup-configuration] XibeCode automatically backs up files before editing. Backups are stored in `~/.xibecode/backups/` with timestamps: ``` ~/.xibecode/backups/ ├── src_app.ts_2024-01-15T10-30-00.bak ├── src_utils_helper.ts_2024-01-15T10-31-00.bak └── ... ``` Additional CLI Commands [#additional-cli-commands] XibeCode v1.1 introduces dedicated commands for the new subsystems: Settings Management [#settings-management] ```bash xc settings list # Show fully merged settings xc settings get # Get a specific setting value xc settings set # Set a value (writes to user source) xc settings set --source project # Write to project source xc settings sources # Show all settings sources xc settings paths # Show file paths for each source ``` See [Settings](/docs/settings) for full documentation. Hooks Management [#hooks-management] ```bash xc hooks list # Show all registered hooks xc hooks add # Register a new hook xc hooks remove # Remove a hook by index xc hooks events # Show available lifecycle events ``` See [Lifecycle Hooks](/docs/hooks) for full documentation. Memory Management [#memory-management] ```bash xc memory list # List all project memories xc memory search # Search memories by keyword xc memory dream # Run dream consolidation xc memory path # Show memory directory path ``` See [Auto-Memory](/docs/memory) for full documentation. Next Steps [#next-steps] * [Agent Modes](/docs/modes) — Learn about all 13 personas * [MCP Integration](/docs/mcp) — Set up external tool servers * [Plugins](/docs/plugins) — Create custom plugins * [Settings](/docs/settings) — Multi-source layered configuration * [Lifecycle Hooks](/docs/hooks) — Run custom logic at agent events * [Auto-Memory](/docs/memory) — Persistent project memory * [Permissions](/docs/permissions) — Fine-grained tool execution rules Max iterations [#max-iterations] | Config / flag | Meaning | | ---------------------------- | -------------------------- | | `maxIterations: 0` (default) | **Unlimited** agent loops | | `maxIterations: 100` | Stop after 100 model turns | | `xibecode run -d 0` | Unlimited for this run | | `xibecode run -d 50` | Cap this run at 50 | Economy mode still applies `economyMaxIterations` as a separate lower bound for cheap runs. See [Agent engine](/docs/agent) and [Providers](/docs/providers). # Cron & scheduled tasks Cron & scheduled tasks [#cron--scheduled-tasks] Schedule agent prompts to run on an interval or classic 5-field cron expression. The **daemon must be running** (`xibecode daemon` / `xibecode gateway` or systemd service). Commands [#commands] ```bash xibecode cron list xibecode cron create "every 1d" "Summarize git status and open issues" --name daily-status xibecode cron create "30m" "Run tests and report failures" xibecode cron create "0 9 * * *" "Morning repo health check" --deliver telegram xibecode cron show xibecode cron pause xibecode cron resume xibecode cron remove xibecode cron edit --schedule "every 2h" --prompt "…" ``` Schedule formats [#schedule-formats] | Form | Example | | ---------------- | ------------------------------------- | | Interval minutes | `30m`, `every 30m` | | Interval hours | `2h`, `every 2h` | | Interval days | `1d`, `every 1d` | | 5-field cron | `0 9 * * *` (09:00 daily) | | One-shot ISO | Absolute time (parsed when supported) | Options [#options] | Flag | Purpose | | ------------------------- | ------------------------------------------- | | `--name ` | Human label | | `--deliver ` | `local` \| `telegram` \| `telegram:CHAT_ID` | | `--workdir ` | Job working directory | | `-m, --model` | Pin model | | `--provider` | Pin provider | | `--schedule` / `--prompt` | For create/edit | Storage [#storage] Jobs live under `~/.xibecode/cron/jobs.json`. The daemon process ticks the scheduler (default \~60s). Tips [#tips] 1. Set a **home channel** in Telegram (`/sethome`) for cron delivery. 2. Keep prompts **idempotent** (safe to re-run). 3. Use a dedicated workdir for production repos. 4. Agent iterations for cron runs are **unlimited by default** — write focused prompts. 5. Delivered replies can include `MEDIA:path` attachments the same way as live chats. Related [#related] * [Xibe Daemon](/docs/gateway) — must be started * [Agent engine](/docs/agent) — how each job executes # Desktop App (Not Available) XibeCode does not currently have a desktop app. XibeCode is available as: * **CLI**: `xibecode run`, `xibecode run-pr`, and `xibecode chat` * **Core library**: `xibecode-core` on npm for building custom interfaces Build a Custom Interface [#build-a-custom-interface] Since `xibecode-core` is published as a standalone npm package, you can use it to build your own desktop app, web interface, or any custom tool: ```bash pnpm add xibecode-core ``` ```typescript import { EnhancedAgent, CodingToolExecutor, NeuralMemory, } from 'xibecode-core'; // Build your own UI around the core engine ``` See [Installation](/docs/installation) and [Examples](/docs/examples) for more details. # Examples & Workflows Real-world examples showing how to use XibeCode for common development tasks. Each example demonstrates autonomous AI-assisted coding. Building Features [#building-features] Add User Authentication [#add-user-authentication] ```bash xibecode run "Add JWT authentication: 1. Install jsonwebtoken and bcrypt 2. Create auth middleware 3. Add /login and /register endpoints 4. Protect existing routes 5. Add tests" ``` Create a REST API [#create-a-rest-api] ```bash xibecode run "Create a REST API with Express for a todo app: - GET /todos - List all todos - POST /todos - Create a todo - PUT /todos/:id - Update a todo - DELETE /todos/:id - Delete a todo - Add input validation - Include error handling" ``` Add Database Integration [#add-database-integration] ```bash xibecode run "Add PostgreSQL database integration: - Set up Prisma ORM - Create user and post models - Add migration scripts - Create seed data" ``` Build a React Component [#build-a-react-component] ```bash xibecode run "Create a DataTable component in React: - Sortable columns - Pagination - Search/filter functionality - Loading and empty states - Use TypeScript and Tailwind CSS" ``` Fixing Bugs [#fixing-bugs] Debug Failing Tests [#debug-failing-tests] ```bash xibecode run "The tests in test/user.test.js are failing. Debug and fix." --verbose --mode debugger ``` Dex the Debugger will: run tests, read source code, identify root cause, apply minimal fix, re-run tests to verify. Fix a Production Error [#fix-a-production-error] ```bash xibecode run "Production error: 'Cannot read property x of undefined' in userController.js line 42. Fix it." --verbose --mode debugger ``` Fix Type Errors [#fix-type-errors] ```bash xibecode run "Fix all TypeScript errors in the src/ directory" --verbose ``` Fix Linting Errors [#fix-linting-errors] ```bash xibecode run "Fix linting errors in changed files" --changed-only ``` Memory Leak Investigation [#memory-leak-investigation] ```bash xibecode run "There's a memory leak in the WebSocket handler. Investigate and fix it." --mode debugger --verbose ``` Refactoring [#refactoring] Convert to TypeScript [#convert-to-typescript] ```bash xibecode run "Refactor src/ to use TypeScript: - Convert all .js files to .ts - Add type annotations - Create types.ts for shared types - Update tsconfig.json - Fix any type errors" ``` Improve Code Quality [#improve-code-quality] ```bash xibecode run "Refactor the authentication module to follow SOLID principles" ``` Extract Common Logic [#extract-common-logic] ```bash xibecode run "Extract duplicate validation logic into a shared utils file: - Find all validation patterns - Create a validation.ts utility - Update all files to use the new utility - Add tests for the utility" ``` Modernize Legacy Code [#modernize-legacy-code] ```bash xibecode run "Modernize the callback-based API to use async/await: - Convert callbacks to Promises - Use async/await syntax - Maintain backwards compatibility - Update tests" ``` Testing [#testing] Generate Tests for a Module [#generate-tests-for-a-module] ```bash xibecode run "Write comprehensive tests for userController.js: - Test all endpoints - Test error cases and edge cases - Test validation - Use Jest - Achieve >80% coverage" --mode tester ``` Add Integration Tests [#add-integration-tests] ```bash xibecode run "Add integration tests for the checkout flow: - Test the complete purchase flow - Test payment processing - Test inventory updates - Test email notifications" --mode tester ``` Fix Flaky Tests [#fix-flaky-tests] ```bash xibecode run "The test 'should handle concurrent requests' is flaky. Investigate and fix it." --mode debugger ``` Code Review & Security [#code-review--security] Security Audit [#security-audit] ```bash xibecode run "Perform a security audit on the auth module: - Check for injection vulnerabilities - Review authentication flow - Check for data exposure risks - Suggest improvements" --mode security ``` Code Review [#code-review] ```bash xibecode run "Review the recent changes in the payment module: - Check code quality - Identify potential issues - Suggest improvements" --mode review ``` Dependency Audit [#dependency-audit] ```bash xibecode run "Check all dependencies for security vulnerabilities and suggest updates" --mode security ``` Full Pentest of a Project [#full-pentest-of-a-project] ```bash xibecode run "Pentest this project and generate pentest-report.md with: - HTTP attacks (SQL injection, XSS, auth bypass, path traversal) - A table of vulnerabilities with severity - A security score out of 100 - Concrete remediation steps" --mode pentest ``` This will: * Start or connect to your dev server. * Use HTTP and agent-browser (via `run_command`) to probe endpoints and UI flows. * Write `pentest-report.md` in the project root with findings and a score. After the pentest, you can review the report card and switch to a debugging-focused mode to apply fixes. Git Workflows [#git-workflows] Safe Refactoring with Checkpoints [#safe-refactoring-with-checkpoints] ```bash xibecode run "Refactor the database layer (create checkpoint first)" ``` XibeCode creates a git checkpoint before making changes, so you can revert if anything goes wrong. Focus on Changed Files [#focus-on-changed-files] ```bash xibecode run "Review and fix issues in changed files only" --changed-only ``` Prepare for Code Review [#prepare-for-code-review] ```bash xibecode run "Prepare this branch for code review: - Run tests - Fix linting errors - Add missing documentation - Generate a summary of changes" ``` Using Different Modes [#using-different-modes] Planning Mode [#planning-mode] ```bash xibecode run "Analyze the codebase and create a plan for adding real-time notifications" --mode plan ``` Aria the Architect will analyze and create a detailed plan without making changes. Debug Mode [#debug-mode] ```bash xibecode run "The API is returning 500 errors intermittently. Investigate and fix." --mode debugger ``` Team Leader Mode [#team-leader-mode] ```bash xibecode run "Build a complete user management system with registration, login, and profile editing" --mode team_leader ``` Arya the Team Leader will coordinate tasks and delegate to specialized agents. Using Dry-Run Mode [#using-dry-run-mode] Preview changes before they're made: ```bash xibecode run "Refactor the auth module" --dry-run ``` Output will show: ``` [DRY RUN] Would replace lines 15-20 with 8 new lines [DRY RUN] Would write 150 lines to src/auth/index.ts [DRY RUN] Would create stash checkpoint: "before auth refactor" ``` Smart Context in Action [#smart-context-in-action] When you ask XibeCode to modify a file, it automatically discovers related files: ```bash xibecode run "Add error handling to userController.js" ``` XibeCode will: 1. Read `userController.js` 2. Extract and follow imports (User model, auth middleware) 3. Find related test files 4. Check config files (package.json, tsconfig.json) 5. Make edits with full understanding of the codebase Multi-Step Workflows [#multi-step-workflows] Full Feature Implementation [#full-feature-implementation] ```bash xibecode run "Implement a complete user profile system: 1. Create database schema for profiles 2. Add API endpoints (GET, PUT) 3. Create React components 4. Add form validation 5. Write tests 6. Update documentation" ``` Migration Workflow [#migration-workflow] ```bash xibecode run "Migrate from Express to Fastify: 1. Set up Fastify with similar middleware 2. Convert routes one by one 3. Update error handling 4. Update tests 5. Verify all endpoints work" ``` Tips & Best Practices [#tips--best-practices] * **Be specific about files** — `"Fix src/api/users.js"` is better than `"Fix the users file"` * **Mention line numbers for large files** — `"Bug around line 500 in data-processor.js"` * **Use the right mode** — `--mode debugger` for bugs, `--mode tester` for tests * **Use verbose mode for complex tasks** — `--verbose` shows every tool call * **Preview with dry-run** — `--dry-run` for risky changes * **Break down huge tasks** — Do it module by module instead of "Build entire platform" * **Let AI discover context** — Don't manually list imports, XibeCode finds them * **Use checkpoints** — Ask for checkpoints before major refactors Next Steps [#next-steps] * [Agent Modes](/docs/modes) — Learn about all 13 personas * [Tools Reference](/docs/tools) — Explore all 40+ tools * [Configuration](/docs/configuration) — Configure XibeCode for your workflow * [Plugins](/docs/plugins) — Create custom plugins # Xibe Daemon (24/7) Xibe Daemon (24/7) [#xibe-daemon-247] **Xibe Daemon** is the always-on coding agent: Telegram / Discord / Slack, **cron**, pairing, delivery ledger, screenshots/files in chat, and operator shell via `/cmd`. | CLI | Notes | | ------------------ | ------------------------- | | `xibecode daemon` | Primary command | | `xibecode gateway` | Full alias (same process) | This is **separate** from the **E2B cloud gateway** (sandbox HTTP proxy). See [Cloud / E2B](/docs/cloud-e2b). Home layout (`~/.xibecode` or `$XIBECODE_HOME`) [#home-layout-xibecode-or-xibecode_home] | Path | Purpose | | ------------------------------------- | -------------------------------------------------------------- | | `profile-*.json` | Interactive CLI profiles | | `.env` / `daemon.env` / `gateway.env` | Secrets (API keys, bot tokens) | | `daemon-.env` | Per-profile secrets (overrides global when `--profile` is set) | | `daemon/` | Daemon runtime (migrates from legacy `gateway/`) | | `daemon/sessions/` | Messaging chat sessions (kept across E2B `/update` restart) | | `daemon/logs/daemon.log` | Daemon log (`daemon-.log` for non-default profiles) | | `daemon/pairing.json` | DM pairing state | | `daemon/delivery-ledger.json` | At-least-once outbound delivery | | `cron/` | Scheduled jobs | | `memories/` | Curated `MEMORY.md` / `USER.md` | | `skills/` | Learned / user skills | | `projects/` | JSONL transcripts per project cwd | | `logs/` | Shared logs | Override root with **`XIBECODE_HOME`**. Quick start [#quick-start] ```bash # Configure tokens (wizard) xibecode setup gateway # Or edit secrets manually: # ~/.xibecode/daemon.env (or gateway.env / .env) # TELEGRAM_BOT_TOKEN=... # TELEGRAM_ALLOWED_USERS=123456789 # ANTHROPIC_API_KEY=... # or your provider key # Foreground xibecode daemon --workdir /path/to/repo # Always-on (systemd user service) xibecode daemon --install --workdir /path/to/repo xibecode daemon --start xibecode daemon --status ``` Multi-profile bots [#multi-profile-bots] ```bash xibecode daemon --profile test --workdir /path/to/repo # Loads ~/.xibecode/daemon-test.env over global secrets # Logs: ~/.xibecode/daemon/logs/daemon-test.log ``` Start / stop / status [#start--stop--status] | Command | Effect | | ---------------------------------- | ---------------------------------------------- | | `xibecode daemon` | Run in foreground (Ctrl+C stops) | | `xibecode daemon --install` | Install systemd unit `xibecode-daemon.service` | | `xibecode daemon --start` | Start the service | | `xibecode daemon --stop` | Stop the service | | `xibecode daemon --status` | Service status | | `xibecode daemon --cron-only` | Cron only (no messaging) | | `xibecode daemon --workdir ` | Default project directory | | `xibecode daemon --profile ` | Use named profile + `daemon-.env` | `xibecode gateway …` accepts the same flags. Systemd helpers after install: ```bash systemctl --user daemon-reload systemctl --user enable --now xibecode-daemon # Optional: keep running after logout sudo loginctl enable-linger $USER ``` Do not run two processes polling the same bot token. Legacy `xibecode-gateway.service` is a oneshot alias of the daemon — enable only one unit. Environment (`~/.xibecode/daemon.env` or `gateway.env`) [#environment-xibecodedaemonenv-or-gatewayenv] | Variable | Purpose | | ---------------------------------------------- | ----------------------------------------------------------------------------- | | `TELEGRAM_BOT_TOKEN` | BotFather token | | `TELEGRAM_ALLOWED_USERS` | Comma-separated Telegram user ids | | `TELEGRAM_HOME_CHANNEL` | Default channel for cron delivery | | `DISCORD_*` / `SLACK_*` | Optional adapters | | Provider API keys | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `OPENROUTER_API_KEY`, … | | `XIBECODE_FALLBACK_PROVIDERS` | Failover pool string | | `XIBECODE_GATEWAY_WORKDIR` | Default workdir | | `GATEWAY_ALLOW_ALL_USERS` | Dev-only; do not enable on public bots | | `XIBECODE_BUSY_INPUT_MODE` | `steer` (default) \| `queue` \| `interrupt` | | `XIBECODE_RUNTIME_MODE` | `default` \| `e2b` (auto-detected on hosted sandboxes) | | `XIBECODE_CMD_TIMEOUT_MS` | `/cmd` shell timeout (default 60000) | | `XIBECODE_DAEMON_VERBOSE` / `XIBECODE_VERBOSE` | Headless tool tracing in daemon logs | | `XIBECODE_PROGRESS_GROUPING` | `accumulate` to edit one progress bubble (default: new message per tool line) | | `XIBECODE_STREAM_EDIT` | `1` to restore mid-turn draft edits (off by default) | | `XIBECODE_DISABLE_UPDATE_CHECK` | Skip npm update offers | | `XIBECODE_DISABLE_AUTO_UPDATE` | Skip auto-update behavior | Messaging slash commands [#messaging-slash-commands] Registered on Telegram’s `/` menu and answered in all adapters: | Slash | Meaning | | ------------------------------------ | ------------------------------------------------------------------------------- | | `/start` | Welcome + list commands | | `/help` | Full help text | | `/new` `/reset` `/clear` | Clear conversation (keep workdir) | | `/stop` | **Interrupt run** + free the chat immediately (next message is not stuck) | | `/status` | Workdir, busy state, progress, sandbox id when in e2b mode | | `/queue` | List queue · `/queue ` force FIFO · `/queue clear` | | `/workdir [path]` | Show or set project directory for this chat | | `/progress on\|off` | Tool progress updates | | `/level` | Rigor: `yolo` \| `default` \| `strict` | | `/model` `/models` | Show/list/set model (`--global` to save profile default) | | `/skills` `/skill` | List / search / view skills | | `/cmd ` | **Shell in chat workdir** — no agent loop (aliases: `/sh`, `/shell`) | | `/update` | Check CLI update · `/update yes` install (e2b: + daemon restart) · `/update no` | | `/mode` | Show runtime mode (`default` \| `e2b`) | | `/sethome` | Set this chat as cron delivery home | | `/once` `/session` `/always` `/deny` | Resolve pending dangerous-command approval | **Process lifecycle** = `daemon --start` / `--stop`.\ **Run lifecycle** = `/stop` or natural completion. `/cmd` — operator shell (no agent) [#cmd--operator-shell-no-agent] ```text /cmd ls -la /cmd pwd /cmd tail -n 40 ~/.xibecode/daemon/logs/daemon.log ``` * Runs in the chat **workdir** via spawn + shell. * Default timeout **60s** (`XIBECODE_CMD_TIMEOUT_MS`). * Large stdout/stderr is truncated (tail kept). * Empty `/cmd` prints usage. While the agent is busy [#while-the-agent-is-busy] | Mode | Behavior | | --------------------- | --------------------------------------------------------------------------------- | | **`steer`** (default) | Plain text injects into the **same run** after tools / before the next model step | | **`queue`** | Follow-ups wait until the current run finishes | | **`interrupt`** | Next plain message aborts and starts a new run | ```bash # In daemon.env XIBECODE_BUSY_INPUT_MODE=steer # default ``` * `/queue ` always forces FIFO without interrupt. * `/stop` hard-interrupts and frees the chat so the next message is not blocked. * `?` can request a quick status without queueing. Approvals and questions [#approvals-and-questions] * Dangerous commands pause for **Once / Session / Always / Deny** (inline buttons or slash commands). After resolve, the prompt message is edited and the keyboard is removed. * Mid-run **agent questions** use numbered options; reply with a number or free text (not `/status`). Media & screenshots (Telegram) [#media--screenshots-telegram] Agent replies can deliver files with: ```text MEDIA:screenshots/home.png MEDIA:dist/report.pdf MEDIA:relative/path/from/workdir.zip ``` | Type | Telegram API | | ------------------------- | ------------------------- | | Images | `sendPhoto` | | Video | `sendVideo` | | Audio | `sendAudio` / `sendVoice` | | Other (PDF, zip, code, …) | `sendDocument` (≤50MB) | * Relative paths resolve against the session **workdir**. * Successful **`take_screenshot`** is auto-queued if the model omits `MEDIA:`. * Optional directives: `[[as_document]]`, `[[audio_as_voice]]`. * Text file attachments **you send** (`.txt`, `.md`, code, … up to 512KB) are downloaded and inlined into the prompt. Progress UX [#progress-ux] * Tool progress is sent as **new messages** by default (not one long edited bubble). * Heartbeats about every **30s** while busy. * Final answer is a new message (mid-turn draft edits off unless `XIBECODE_STREAM_EDIT=1`). * Curated memory progress: saving… then **Saved · MEMORY/USER · usage%**. * Auto-compact progress: compacting… then **Context compacted**. * `[[TASK_COMPLETE | summary=…]]` is stripped and shown as a plain **Done** footer. Runtime modes (`default` vs `e2b`) [#runtime-modes-default-vs-e2b] | Mode | When | Behavior | | ------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **`default`** | Local host daemon | No auto self-update restart | | **`e2b`** | Hosted sandbox (auto-detect or `XIBECODE_RUNTIME_MODE=e2b`) | `/update yes` → install latest CLI (sudo when needed) → **restart daemon**; chat sessions under `daemon/sessions/` kept; agent knows sandbox id; preview `https://{port}-{sandboxId}.e2b.dev` | ```bash # Force mode (then restart daemon) XIBECODE_RUNTIME_MODE=e2b ``` `/mode` shows the current runtime mode and sandbox id when applicable. `/update` flow (E2B) [#update-flow-e2b] 1. Daemon or `/update` reports a newer npm version. 2. Reply **`/update yes`** (or use the dashboard Update button). 3. Install tries `sudo -n npm i -g xibecode@…` first when the global prefix is root-owned, then plain npm, then user-local prefix fallback. 4. Daemon restarts; messaging chat history is preserved. CLI equivalent (any machine): ```bash xibecode update --check xibecode update --apply --yes # Pin: xibecode update --apply --yes --to 1.17.0 ``` Never silent — always requires explicit apply / `/update yes`. Security [#security] * Prefer allowlists (`TELEGRAM_ALLOWED_USERS`) or **pairing** (`xibecode pair`). * Never commit `daemon.env` / `gateway.env`. * Treat bot tokens like production secrets. * `/cmd` runs as the daemon user in the chat workdir — lock down who can talk to the bot. Pairing [#pairing] ```bash xibecode pair list xibecode pair approve telegram xibecode pair revoke telegram ``` Logs & sessions [#logs--sessions] * Logs: `~/.xibecode/daemon/logs/daemon.log` (and `daemon-.log`) * Sessions: `~/.xibecode/daemon/sessions/` * Verbose agent tools: `XIBECODE_DAEMON_VERBOSE=1` Iterations [#iterations] Daemon agent runs default to **unlimited** iterations (`0`). Abort with `/stop` if needed. See [Agent engine](/docs/agent). Related [#related] * [Cron](/docs/cron) — scheduled tasks (requires daemon running) * [Chat slash commands](/docs/chat-slash-commands) — TUI + gateway summary * [Memory](/docs/memory) — curated MEMORY / USER * [Cloud / E2B](/docs/cloud-e2b) — sandbox runtime and `/update` on hosted boxes * [Setup](/docs/setup) — wizard path for Telegram * [Providers](/docs/providers) — API keys for the agent # Lifecycle Hooks Lifecycle hooks let you run custom commands, inject prompts, or call HTTP endpoints at key points during the agent's execution. This enables auditing, logging, notifications, and custom integrations. Available Events [#available-events] XibeCode supports 9 lifecycle events: | Event | When It Fires | Use Case | | ------------------ | ------------------------------------ | --------------------------------------- | | `SessionStart` | When a new session begins | Initialize state, log session start | | `SessionEnd` | When a session completes | Generate reports, cleanup | | `UserPromptSubmit` | When the user submits a prompt | Input validation, preprocessing | | `PreToolUse` | Before a tool is executed | Audit tool calls, enforce policies | | `PostToolUse` | After a tool finishes | Log results, trigger downstream actions | | `Stop` | When the agent stops normally | Notifications, summary generation | | `StopFailure` | When the agent stops due to an error | Alerting, error tracking | | `PreCompact` | Before context compaction | Save important context | | `PostCompact` | After context compaction | Verify compaction quality | Hook Types [#hook-types] Each hook can be one of three types: Command Hook [#command-hook] Runs a shell command. The command receives context via environment variables. ```json { "type": "command", "value": "echo 'Tool used: $TOOL_NAME'" } ``` Environment variables available in command hooks: | Variable | Events | Description | | ------------- | ------------------------ | -------------------------------- | | `TOOL_NAME` | PreToolUse, PostToolUse | Name of the tool being called | | `TOOL_INPUT` | PreToolUse | JSON string of tool input | | `TOOL_OUTPUT` | PostToolUse | JSON string of tool output | | `SESSION_ID` | SessionStart, SessionEnd | Session identifier | | `PROMPT` | UserPromptSubmit | The user's submitted prompt | | `ERROR` | StopFailure | Error message | | `DURATION_MS` | SessionEnd | Session duration in milliseconds | Prompt Hook [#prompt-hook] Injects a text prompt into the agent's context. ```json { "type": "prompt", "value": "Always follow the project's coding standards in CONTRIBUTING.md." } ``` Prompt hooks are injected as system-level instructions that the agent sees when the event fires. HTTP Hook [#http-hook] Sends an HTTP POST request with event context as JSON. ```json { "type": "http", "value": "https://hooks.example.com/xibecode", "headers": { "Authorization": "Bearer your-token" }, "timeout": 5000 } ``` The POST body contains: ```json { "event": "PreToolUse", "timestamp": "2026-05-03T10:00:00Z", "toolName": "write_file", "toolInput": { "path": "/src/app.ts", "content": "..." }, "sessionId": "abc-123" } ``` CLI Commands [#cli-commands] List registered hooks [#list-registered-hooks] ```bash xc hooks list ``` Shows all hooks grouped by event. View available events [#view-available-events] ```bash xc hooks events ``` Add a hook [#add-a-hook] ```bash # Command hook xc hooks add PreToolUse command "audit-log.sh" # Prompt hook xc hooks add SessionStart prompt "Follow the project style guide." # HTTP hook xc hooks add SessionEnd http "https://hooks.example.com/done" ``` Remove a hook [#remove-a-hook] ```bash xc hooks remove PreToolUse 0 ``` The index corresponds to the position in the hooks list for that event (0-based). Chat Commands [#chat-commands] Inside an interactive chat session: ``` /hooks list Show all registered hooks /hooks events Show available events ``` Configuration [#configuration] Hooks are stored in settings files. You can define them in any settings source: User-level hooks (~/.xibecode/settings.json) [#user-level-hooks-xibecodesettingsjson] ```json { "hooks": { "SessionStart": [ { "type": "prompt", "value": "You are working on the XibeCode project." } ] } } ``` Project-level hooks (.xibecode/settings.json) [#project-level-hooks-xibecodesettingsjson] ```json { "hooks": { "PreToolUse": [ { "type": "command", "value": "scripts/audit-tool-use.sh" } ], "PostToolUse": [ { "type": "command", "value": "scripts/log-tool-result.sh" } ], "SessionEnd": [ { "type": "http", "value": "https://api.example.com/session-done" } ] } } ``` Hook Execution [#hook-execution] * Hooks run **sequentially** in the order they are defined * If a command hook exits with a non-zero code, a warning is logged but execution continues * If an HTTP hook times out (default 5 seconds), the hook is skipped * Prompt hooks are injected silently into the agent's context * Hooks cannot modify tool input/output (they are observers, not middleware) Example Workflows [#example-workflows] Audit trail for tool usage [#audit-trail-for-tool-usage] Create `.xibecode/settings.json`: ```json { "hooks": { "PreToolUse": [ { "type": "command", "value": "echo \"[$(date)] Tool: $TOOL_NAME Input: $TOOL_INPUT\" >> .xibecode/audit.log" } ] } } ``` Slack notification on session end [#slack-notification-on-session-end] ```json { "hooks": { "SessionEnd": [ { "type": "http", "value": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL", "headers": { "Content-Type": "application/json" } } ] } } ``` Project-specific agent instructions [#project-specific-agent-instructions] ```json { "hooks": { "SessionStart": [ { "type": "prompt", "value": "This project uses pnpm. Always use pnpm for package management. Follow the coding standards in CONTRIBUTING.md." } ] } } ``` Next Steps [#next-steps] * [Settings](/docs/settings) — Configure settings sources * [Permissions](/docs/permissions) — Control tool execution with rules * [Auto-Memory](/docs/memory) — Persistent project memory # Documentation Everything you need to know about using XibeCode — the autonomous AI coding assistant. Feature Highlights [#feature-highlights] * **13 Agent Modes** for planning, coding, testing, security, review, team leadership, and more * **50+** Built-in Tools for file I/O, code search, git, shell, web, skills, and MCP * **Multi-Source Settings** layered config from user, project, local, and policy sources * **Lifecycle Hooks** run custom commands at session start/end, before/after tool use, and more * **Auto-Memory** project memories plus durable curated `MEMORY.md` / `USER.md` * **Auto-compact** microcompact + full handoff when context nears budget * **Permission Rules** fine-grained allow/deny/ask patterns for tool execution * **MCP** Protocol Support for extending capabilities with external tools * **Swarm Orchestration** for parallel task execution * **Skill System** progressive `list_skills` / `view_skill` plus learned skills * **Open Source** (Apache 2.0) Current Runtime Highlights [#current-runtime-highlights] As of CLI/Core **1.17.0**, XibeCode includes local-first coding, cloud (E2B) sandboxes, and always-on messaging. * **Setup wizard**: `xibecode setup` for providers, API keys, 24/7 daemon, and agent defaults. * **30+ providers**: Routing.run, zenllm.org, Anthropic, OpenAI, OpenRouter, DeepSeek, Gemini, Grok, Z.AI, Kimi, MiniMax, Fireworks, models.dev catalog, and more — see [Providers](/docs/providers). * **Unlimited agent loops** by default (`maxIterations: 0`); set `-d N` or config when you want a hard cap. * **Xibe Daemon (24/7)**: Telegram / Discord / Slack with `xibecode daemon` (alias: `xibecode gateway`). * **`/cmd` shell** from Telegram — run shell in the chat workdir without the agent loop. * **Mid-run steer** (default): new messages inject into the current run; `/queue` for FIFO; `/stop` to free the chat. * **Media delivery**: screenshots and any workspace file via `MEDIA:path` (photo/document/video/audio). * **Cron**: `xibecode cron` scheduled agent jobs while the daemon runs. * **Curated memory**: durable saves with clear “Saved” feedback; frozen snapshot at session start. * **Cloud Runtime**: `xc cloud`, `xc cloud resume `, `xc cloud pull`, chat `/cpull`. * **E2B runtime mode**: `/update yes` installs latest CLI + restarts daemon (chat sessions kept). * **Diagnostics**: `xibecode diagnostics` redacted markdown bundle. * **CLI update**: `xibecode update --check` / `--apply --yes` (never silent). Getting Started [#getting-started] Core Features [#core-features] Cloud + Operations [#cloud--operations] Advanced [#advanced] Quick Links [#quick-links] * [GitHub Repository](https://github.com/iotserver24/Xibecode) * [npm Package (CLI)](https://www.npmjs.com/package/xibecode) * [npm Package (Core)](https://www.npmjs.com/package/xibecode-core) * [Installation Guide](/docs/installation) * [Cloud & E2B Runtime](/docs/cloud-e2b) * [Xibe Daemon](/docs/gateway) * [Chat Slash Commands](/docs/chat-slash-commands) * [Agent Modes](/docs/modes) * [Tools Reference](/docs/tools) * [Example Use Cases](/docs/examples) Start with the [Quick Start](/docs/quickstart) guide, then explore the [Agent Modes](/docs/modes) and [Tools Reference](/docs/tools) to see how XibeCode works in depth. # Installation Get XibeCode up and running in under a minute. Requirements [#requirements] * **Node.js 18.0.0** or higher * An **AI provider API key** (Anthropic, OpenAI, or compatible) Install from npm (Recommended) [#install-from-npm-recommended] ```bash pnpm add -g xibecode ``` Or use your preferred package manager: ```bash # npm npm install -g xibecode # bun bun add -g xibecode ``` Using xibecode-core as a Library [#using-xibecode-core-as-a-library] The AI engine is available as a standalone package: ```bash pnpm add xibecode-core ``` ```typescript import { EnhancedAgent, CodingToolExecutor, NeuralMemory, AutoMemoryManager, SettingsManager, HooksManager, PermissionRuleManager, HOOK_EVENTS, PROVIDER_CONFIGS, } from 'xibecode-core'; ``` This allows you to build custom AI coding tools, desktop apps, or extensions on top of the XibeCode engine. Install from Source [#install-from-source] ```bash git clone https://github.com/iotserver24/Xibecode cd Xibecode pnpm install pnpm run build pnpm link --global --dir packages/cli ``` Verify install [#verify-install] ```bash xibecode --version # expect 1.17.x or newer xc --version # same binary (alias) ``` Upgrade later: ```bash pnpm add -g xibecode@latest # or xibecode update --check xibecode update --apply --yes ``` Set up API Key [#set-up-api-key] XibeCode needs an AI provider API key (Anthropic, OpenAI, OpenRouter, Routing.run, zenllm.org, or any compatible endpoint). You can set it up in three ways: Option 1: Interactive Setup (Recommended) [#option-1-interactive-setup-recommended] ```bash xibecode setup # full wizard: provider → gateway → agent # or xibecode config ``` Option 2: Direct Configuration [#option-2-direct-configuration] ```bash # Set API key xibecode config --set-key YOUR_ANTHROPIC_API_KEY # Or for OpenAI xibecode config --set-key YOUR_OPENAI_API_KEY ``` Option 3: Environment Variable [#option-3-environment-variable] ```bash # Anthropic export ANTHROPIC_API_KEY=your_key_here # OpenAI export OPENAI_API_KEY=your_key_here # Google export GOOGLE_API_KEY=your_key_here # Groq export GROQ_API_KEY=your_key_here ``` Verify Installation [#verify-installation] ```bash # Check version xibecode --version # View current configuration xibecode config --show # Run a simple test xibecode chat ``` Directory Structure [#directory-structure] XibeCode creates the following directories: ``` ~/.xibecode/ # Global configuration ├── config.json # Main configuration file ├── settings.json # User-level settings (permissions, hooks, memory config) ├── mcp-servers.json # MCP server configurations └── backups/ # File backups ~/.xibecode/projects/ # Project-scoped data └── / # Per-project directory ├── .jsonl # Append-only session transcripts (primary format) ├── .json # Legacy format (backward compatibility) └── memory/ # Auto-extracted memory files .xibecode/ # Project-level (in your working directory) ├── settings.json # Project settings (committed, shared with team) ├── settings.local.json # Local settings (not committed, personal overrides) ├── memory.md # Project memory notes └── skills/ # Custom skills for this project ``` Supported Platforms [#supported-platforms] * **macOS** — Full support (Intel and Apple Silicon) * **Linux** — Full support (Ubuntu, Debian, Fedora, Arch) * **Windows** — Full support (PowerShell and WSL) Troubleshooting [#troubleshooting] Permission Denied on Global Install [#permission-denied-on-global-install] ```bash # Better: Fix npm permissions mkdir ~/.npm-global npm config set prefix '~/.npm-global' export PATH=~/.npm-global/bin:$PATH ``` Node.js Version Too Old [#nodejs-version-too-old] ```bash # Using nvm (Node Version Manager) nvm install 18 nvm use 18 ``` Next Steps [#next-steps] * [Quick Start Guide](/docs/quickstart) — Run your first autonomous coding task * [Configuration](/docs/configuration) — Customize XibeCode for your workflow * [Agent Modes](/docs/modes) — Learn about the 13 specialized agent personas * [Settings](/docs/settings) — Multi-source layered configuration * [Auto-Memory](/docs/memory) — Persistent project memory * [Lifecycle Hooks](/docs/hooks) — Run custom logic at agent events * [Permissions](/docs/permissions) — Control tool execution with rules Recommended first-run [#recommended-first-run] ```bash # After global install xibecode setup # or xibecode setup --quick ``` The [setup wizard](/docs/setup) configures providers, API keys, optional Telegram 24/7 gateway, and agent defaults (including **unlimited iterations** with `maxIterations: 0`). Full provider list: [Providers](/docs/providers). # MCP Integration XibeCode supports the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/), an open protocol that standardizes how applications provide context to LLMs. Connect to external servers for databases, APIs, file systems, and more. What is MCP? [#what-is-mcp] MCP enables: * **Extended Tools** — Add tools from external servers (databases, APIs, etc.) * **Access Resources** — Read data from external sources * **Prompt Templates** — Use pre-built prompts from servers * **Context Sharing** — Share context between different AI tools Quick Start [#quick-start] ```bash # Initialize MCP configuration xibecode mcp init # Add a server xibecode mcp add # List configured servers xibecode mcp list # Reload after editing xibecode mcp reload ``` Adding MCP Servers [#adding-mcp-servers] File-Based Configuration (Recommended) [#file-based-configuration-recommended] ```bash # Show the config file path xibecode mcp file # Open in your default editor xibecode mcp edit ``` Configuration Format [#configuration-format] ```json { "mcpServers": { "filesystem": { "command": "mcp-server-filesystem", "args": ["--root", "/path/to/files"] }, "github": { "command": "mcp-server-github", "env": { "GITHUB_TOKEN": "your_token_here" } }, "postgres": { "command": "mcp-server-postgres", "env": { "DATABASE_URL": "postgresql://user:pass@localhost/db" } } } } ``` MCP Commands [#mcp-commands] ```bash xibecode mcp init # Initialize default config xibecode mcp add # Add a server xibecode mcp edit # Edit configuration xibecode mcp list # List configured servers xibecode mcp remove # Remove a server xibecode mcp reload # Reload after editing xibecode mcp file # Show file path xibecode mcp status # Check connection status ``` Using MCP Tools [#using-mcp-tools] Once configured, MCP tools are automatically available. Tools are prefixed with the server name: ``` filesystem::read_file github::create_issue github::list_repos postgres::query slack::send_message ``` In chat mode, view MCP tools: ```bash xibecode chat > /mcp # Show MCP status and tools > /mcp list # List all MCP tools > /mcp reload # Reload MCP servers ``` Server Configuration Options [#server-configuration-options] | Option | Description | Required | | --------- | ------------------------------------ | -------- | | `command` | The command to start the MCP server | Yes | | `args` | Array of command-line arguments | No | | `env` | Environment variables for the server | No | | `cwd` | Working directory for the server | No | Example Configurations [#example-configurations] GitHub MCP Server [#github-mcp-server] ```bash npm install -g @modelcontextprotocol/server-github ``` ```json { "mcpServers": { "github": { "command": "mcp-server-github", "env": { "GITHUB_TOKEN": "ghp_your_token_here" } } } } ``` ```bash xibecode chat > Create an issue about the login bug in the main repo ``` PostgreSQL MCP Server [#postgresql-mcp-server] ```bash npm install -g @modelcontextprotocol/server-postgres ``` ```json { "mcpServers": { "postgres": { "command": "mcp-server-postgres", "env": { "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb" } } } } ``` Filesystem MCP Server [#filesystem-mcp-server] ```bash npm install -g @modelcontextprotocol/server-filesystem ``` ```json { "mcpServers": { "docs": { "command": "mcp-server-filesystem", "args": ["--root", "/path/to/documentation"] } } } ``` Slack MCP Server [#slack-mcp-server] ```json { "mcpServers": { "slack": { "command": "mcp-server-slack", "env": { "SLACK_BOT_TOKEN": "xoxb-your-token", "SLACK_TEAM_ID": "T01234567" } } } } ``` Popular MCP Servers [#popular-mcp-servers] | Server | Description | Package | | ------------ | ---------------------- | ----------------------------------------- | | Filesystem | File system access | `@modelcontextprotocol/server-filesystem` | | GitHub | GitHub API integration | `@modelcontextprotocol/server-github` | | PostgreSQL | PostgreSQL database | `@modelcontextprotocol/server-postgres` | | Slack | Slack messaging | `@modelcontextprotocol/server-slack` | | Google Drive | Google Drive access | `@modelcontextprotocol/server-gdrive` | | SQLite | SQLite database | `@modelcontextprotocol/server-sqlite` | | Puppeteer | Browser automation | `@modelcontextprotocol/server-puppeteer` | Transport Types [#transport-types] XibeCode supports **stdio transport** — MCP servers run as local subprocesses. The server communicates via standard input/output streams using JSON-RPC messages. Debugging MCP Connections [#debugging-mcp-connections] ```bash # Check server status xibecode mcp status # View server logs (verbose mode) xibecode chat --verbose > /mcp # Test a specific tool xibecode chat > Use the github::list_repos tool to list my repositories ``` Security Considerations [#security-considerations] * Store sensitive tokens in environment variables, not in config files * Use read-only database credentials when possible * Limit filesystem access to specific directories * Review MCP server permissions before installation Building Custom MCP Servers [#building-custom-mcp-servers] ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const server = new Server( { name: "my-custom-server", version: "1.0.0", }, { capabilities: { tools: {} }, }, ); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "my_custom_tool", description: "Does something custom", inputSchema: { type: "object", properties: { input: { type: "string" }, }, }, }, ], })); const transport = new StdioServerTransport(); await server.connect(transport); ``` XibeCode Docs MCP Server [#xibecode-docs-mcp-server] XibeCode exposes its own documentation as an MCP server, allowing any AI tool (Claude Code, Cursor, Windsurf, etc.) to search and read XibeCode docs in real-time. **Endpoint**: `https://xibeai.in/api/mcp` Available Tools [#available-tools] | Tool | Description | | ------------- | ----------------------------------------------------------------------------------------------- | | `search_docs` | Search XibeCode documentation by keyword. Returns matching page titles, descriptions, and URLs. | | `read_doc` | Read the full content of a documentation page by its slug. | | `list_docs` | List all available documentation pages with titles, descriptions, and URLs. | Connect from Claude Code [#connect-from-claude-code] ```bash claude mcp add --transport http xibecode-docs https://xibeai.in/api/mcp ``` Connect from Cursor [#connect-from-cursor] Add to your `.cursor/mcp.json`: ```json { "mcpServers": { "xibecode-docs": { "url": "https://xibeai.in/api/mcp" } } } ``` Connect from Any MCP Client [#connect-from-any-mcp-client] The server supports the Streamable HTTP transport. Connect to: ``` https://xibeai.in/api/mcp ``` For stdio-only clients, use the [mcp-remote](https://github.com/geelen/mcp-remote) proxy: ```bash npx mcp-remote https://xibeai.in/api/mcp ``` Next Steps [#next-steps] * [Plugins](/docs/plugins) — Create simpler tool extensions * [Examples](/docs/examples) — See MCP in action * [Configuration](/docs/configuration) — Configure XibeCode # Memory XibeCode has **two complementary memory layers**: 1. **Project auto-memory** — markdown files per project (facts, patterns, decisions). 2. **Curated global memory** — durable `MEMORY.md` + `USER.md` injected every session (bounded budget, frozen at session start). Curated memory (global, durable) [#curated-memory-global-durable] Files: ``` ~/.xibecode/memories/MEMORY.md # agent notes: env, conventions, lessons ~/.xibecode/memories/USER.md # who you are: name, role, preferences, style ``` How writes work [#how-writes-work] * The agent uses the **`curated_memory`** tool (`add` / `replace` / `remove`, or an atomic **`operations`** batch). * On success: `done=true` and a note that the write is complete (do not repeat). * Success responses avoid dumping the full entry list (reduces re-save thrash). If the store is full, overflow errors return entries so the agent can consolidate. * **Frozen snapshot**: the system prompt loads MEMORY/USER **once at session start**. Mid-session disk writes are immediate for the next session, but the in-prompt snapshot stays fixed until a new session. Messaging progress (Telegram / daemon) [#messaging-progress-telegram--daemon] When the agent saves curated memory you see progress like: 1. Saving MEMORY/USER… 2. **Saved · MEMORY · usage% · N entries** Post-turn auto notes can surface the same way. CLI write-approval (optional staging) [#cli-write-approval-optional-staging] ```bash xibecode memory pending xibecode memory approve xibecode memory reject ``` What belongs in curated memory [#what-belongs-in-curated-memory] | Save | Skip | | -------------------------------- | -------------------------------------------- | | User preferences & corrections | Trivial / obvious facts | | Stable environment & conventions | Raw data dumps, task TODOs | | Durable procedures (short) | Full session logs → use `session_search` | | | Reusable multi-step workflows → `save_skill` | Project auto-memory [#project-auto-memory] Project-specific extraction and retrieval for coding conventions and past decisions. How it works [#how-it-works] 1. **Automatic Extraction**: After conversation turns, notable facts/patterns can be stored as memory files 2. **Context Retrieval**: On session start, memories relevant to the prompt are ranked and injected 3. **Dream Consolidation**: Overlapping or stale entries are merged and pruned Storage [#storage] ``` ~/.xibecode/projects//memory/ ├── 2026-05-03-api-patterns.md └── ... ``` Additionally, project-local notes: ``` /.xibecode/memory.md ``` Both locations are scanned when listing or searching. Memory file format [#memory-file-format] ```markdown --- type: pattern tags: [api, rest, express] created: 2026-05-03T10:00:00Z updated: 2026-05-03T10:00:00Z relevance: 0.8 --- ## API Pattern All REST endpoints follow the controller-service-repository pattern. ``` | Type | Description | | ------------ | -------------------------------------- | | `fact` | Factual observation about the codebase | | `pattern` | Recurring convention | | `decision` | Architecture / design decision | | `correction` | User correction to remember | | `preference` | How code should be written | CLI commands [#cli-commands] ```bash # Project auto-memory xc memory list xc memory search "authentication flow" xc memory dream xc memory path # Learning loop extras xibecode memory sessions # search past sessions xibecode memory skills # learned skills xibecode memory pending # staged curated writes (if enabled) ``` Ranking for search uses tag overlap, keyword match, and recency. Chat commands (interactive TUI) [#chat-commands-interactive-tui] ``` /memory list Show project memories (up to 10; full list via CLI) /memory dream Run dream consolidation /memory path Print memory directory ``` Configuration [#configuration] ```json { "memory": { "enabled": true, "maxMemories": 100, "relevanceThreshold": 0.3, "dreamConsolidationInterval": 3600 } } ``` | Setting | Description | Default | | ----------------------------------- | --------------------------------------- | ------- | | `memory.enabled` | Enable project auto-memory | `true` | | `memory.maxMemories` | Max files before consolidation pressure | `100` | | `memory.relevanceThreshold` | Min score for injection | `0.3` | | `memory.dreamConsolidationInterval` | Seconds between auto dream | `3600` | Optional post-turn review uses `XIBECODE_REVIEW_*` env vars (cheap review model). Session search & skills [#session-search--skills] | Feature | Tool / path | | ------------------ | ----------------------------------------------------------------------- | | Past conversations | `session_search` tool · `xibecode memory sessions` | | Learned skills | `~/.xibecode/skills/learned/` · `save_skill` · `xibecode memory skills` | | Progressive skills | `list_skills` then `view_skill` | Manual project memory [#manual-project-memory] Write freely to `.xibecode/memory.md` in the project root — included in memory scans: ```markdown # Project Memory ## Conventions - Always use pnpm - Conventional commits - TypeScript strict mode ``` Context injection [#context-injection] On a new session the agent: 1. Loads **frozen** curated MEMORY + USER (global) 2. Searches project memory files for relevance 3. Injects hits above threshold into context You should not need to restate stable preferences every session. Related: auto-compact [#related-auto-compact] Long chats trigger **auto-compact** (microcompact of old tool results, then a full handoff summary). That is separate from memory files — see [Agent engine](/docs/agent#auto-compact). Disable with `autoCompactEnabled: false` or `XIBECODE_AUTO_COMPACT=0`. Next Steps [#next-steps] * [Agent engine](/docs/agent) — loop, auto-compact, learning * [Settings](/docs/settings) — configure memory behavior * [Xibe Daemon](/docs/gateway) — memory progress on Telegram * [Permissions](/docs/permissions) — control tool execution # Agent Modes XibeCode features a set of core agent modes (personas) optimized for different types of tasks. Each mode has a unique personality, set of allowed tools, and behavioral characteristics. Quick Reference [#quick-reference] | Mode | Persona | Best For | Can Modify | | ------------- | --------------------- | ------------------------------------------------------ | ----------------------------- | | `agent` | (Default) | Full-stack development | Yes | | `plan` | Strategic Planner | Interactive planning with web research | Yes (implementations.md only) | | `tester` | Tess the QA Engineer | Testing, quality | Yes | | `security` | Sentinel the Guardian | Security audits | No | | `review` | Nova the Critic | Code reviews | No | | `team_leader` | Arya the Leader | Task orchestration | Yes | | `pentest` | Penetration Tester | Dynamic pentesting & security exploitation (read-only) | No | Switching Modes [#switching-modes] ```bash # Via CLI flag xibecode run "task" --mode plan xibecode run "task" --mode debugger # In chat mode xibecode chat > /mode plan > /mode agent ``` Development Modes (Core) [#development-modes-core] Agent Mode (Default) [#agent-mode-default] Full autonomous coding with all capabilities enabled. **Best For:** Building new features, full-stack development, multi-step coding tasks, installing dependencies, running tests and commands. **Capabilities:** Read and modify files, create new files and directories, run shell commands, execute tests, git operations (read and write), web search and fetch. ```bash xibecode run "Add a user authentication system" --mode agent ``` Engineer Mode [#engineer-mode] **Persona:** Alex the Implementer Focused implementation mode for building features. **Best For:** Implementing specific features, writing clean maintainable code, following specifications, writing tests for implementations. ```bash xibecode run "Implement the checkout flow" --mode engineer ``` Planning & Analysis Modes [#planning--analysis-modes] Plan Mode [#plan-mode] **Persona:** Strategic Planner Interactive planning mode with web research, clarifying questions, and structured `implementations.md` generation. **Best For:** Creating detailed implementation plans, researching solutions, breaking down complex features into tasks, generating step-by-step plans with code snippets. **How It Works:** 1. Reads the codebase and researches online 2. Asks clarifying questions (inquirer prompts in CLI) 3. Generates `implementations.md` with checkbox tasks, file paths, and code snippets 4. Shows a plan preview with "View Plan" and "Build" buttons 5. On "Build", switches to Agent mode to execute the plan automatically **Tools Available:** File reading, web search, fetch URL, git read, context search, and write to `implementations.md` only. ```bash xibecode run "Plan how to add authentication to this app" --mode plan ``` Architect Mode [#architect-mode] **Persona:** Anna the Designer System design and high-level architecture planning. **Best For:** System design documents, component architecture, tech stack selection, design patterns, scalability planning. ```bash xibecode run "Design the microservices architecture" --mode architect ``` Researcher Mode [#researcher-mode] **Persona:** Sanvi the Scholar Deep research and investigation mode. **Best For:** Investigating complex topics, reading documentation, analyzing papers and specs, synthesizing information. ```bash xibecode run "Research best practices for API rate limiting" --mode researcher ``` Quality & Testing Modes [#quality--testing-modes] Debugger Mode [#debugger-mode] **Persona:** Dex the Detective Systematic debugging and root cause analysis. **Best For:** Finding and fixing bugs, analyzing error messages, root cause investigation, targeted surgical fixes. **Approach:** 1. Reproduce the issue 2. Isolate the root cause 3. Apply minimal fix 4. Verify the fix works ```bash xibecode run "The login form is not working. Fix it." --mode debugger ``` Tester Mode [#tester-mode] **Persona:** Tess the QA Engineer Comprehensive testing and quality assurance. **Best For:** Writing unit tests, integration testing, test coverage improvement, TDD workflows. ```bash xibecode run "Write tests for the user service" --mode tester ``` Review Mode [#review-mode] **Persona:** Nova the Critic Code review and quality analysis (read-only). **Best For:** Code quality review, best practices check, performance analysis, maintainability assessment. **Restrictions:** Cannot modify files. ```bash xibecode run "Review the authentication module" --mode review ``` Security Mode [#security-mode] **Persona:** Sentinel the Guardian Security analysis and vulnerability detection (read-only). **Best For:** Security audits, vulnerability scanning, injection attack detection, authentication review, data exposure analysis. **Restrictions:** Cannot modify files, requires confirmation. ```bash xibecode run "Perform a security audit" --mode security ``` Specialized Modes [#specialized-modes] Team Leader Mode [#team-leader-mode] **Persona:** Arya the Leader Task coordination and delegation to other modes. **Best For:** Complex multi-step projects, coordinating multiple concerns, breaking down large tasks. The Team Leader delegates tasks to specialized agents (Engineer, Architect, Tester, etc.) rather than implementing directly. ```bash xibecode run "Build a complete e-commerce system" --mode team_leader ``` Product Mode [#product-mode] **Persona:** Agni the Strategist Product requirements and user stories. **Best For:** Requirements gathering, user stories, feature prioritization, PRD creation. ```bash xibecode run "Create user stories for the dashboard" --mode product ``` SEO Mode [#seo-mode] **Persona:** Siri the Optimizer SEO and web optimization. **Best For:** Keyword research, on-page SEO, meta tag optimization, web performance. ```bash xibecode run "Optimize the landing page for SEO" --mode seo ``` Data Mode [#data-mode] **Persona:** David the Analyst Data processing and analysis. **Best For:** Data analysis, log processing, metrics definition, data visualization prep. ```bash xibecode run "Analyze the server logs for errors" --mode data ``` Pentest Mode [#pentest-mode] Pentest Mode [#pentest-mode-1] **Persona:** Penetration Tester Dynamic penetration testing and exploit simulation for running applications. **Best For:** Running HTTP-based attacks (SQL injection, XSS, auth bypass, traversal) against a dev instance of your app, then generating a detailed `pentest-report.md` with findings and a security score. **Workflow:** 1. Start your app (or let the agent start it via `run_command`). 2. Use HTTP and `agent-browser` (via `run_command`) to probe endpoints and UIs. 3. Write `pentest-report.md` with vulnerabilities, attack vectors, and a 0–100 score. 4. Optionally switch to debugger/agent modes to fix findings. ```bash xibecode run "Pentest this project and generate pentest-report.md" --mode pentest ``` Tool Permissions by Mode [#tool-permissions-by-mode] Each mode has access to specific tool categories: | Category | Description | Modes with Access | | --------------- | ----------------- | ------------------------------------------------------------------------------------------ | | `read_only` | Read files | All modes | | `write_fs` | Write/edit files | agent, engineer, tester, debugger, architect, team\_leader, product, seo, data, researcher | | `git_read` | Git status, diff | All modes | | `git_mutation` | Git commit, reset | agent, engineer, tester, debugger | | `shell_command` | Run commands | agent, engineer, debugger, security, data | | `tests` | Run tests | agent, engineer, tester, debugger, security, review | | `network` | Web search, fetch | agent, engineer, seo, researcher | | `context` | Code search | All modes | Mode Transitions [#mode-transitions] Modes can automatically transition based on the task: * Plan mode may suggest switching to Agent mode for implementation * Team Leader delegates to Engineer for coding tasks * Agent can switch to Debugger when encountering bugs Configure auto-approval policy in your config: ```json { "autoApprovalPolicy": "always" } ``` Reliability Behavior in Modes (v0.9.1) [#reliability-behavior-in-modes-v091] Across writable and autonomous modes, XibeCode now applies stronger runtime quality controls: * Completion is gated by recent grounded evidence. * Mutating tool actions can be post-verified with read-back checks. * Repetitive low-variation command/tool loops are detected earlier. * Conversation compaction preserves a grounded facts ledger and summary in long sessions. Best Practices [#best-practices] * **Start with Plan mode** for complex tasks to understand the codebase first * **Use Debugger mode** for bugs rather than Agent mode for more targeted fixes * **Use Security mode** before deploying to production * **Use Review mode** for code quality checks without modifications * **Use Team Leader** for complex projects that span multiple concerns Next Steps [#next-steps] * [Tools Reference](/docs/tools) — Explore all 40+ tools * [Configuration](/docs/configuration) — Configure mode behavior * [Examples](/docs/examples) — See modes in action # Permission Rules XibeCode's permission rules system gives you fine-grained control over which tools the agent can use and when it should ask for confirmation. Rules are configured through the settings system and evaluated on every tool call. Rule Types [#rule-types] There are three rule types, evaluated in order of priority: 1. **Deny** — The tool call is blocked immediately 2. **Ask** — The agent requests user confirmation before proceeding 3. **Allow** — The tool call proceeds automatically Rules are checked in this order: if a tool matches a **deny** rule, it is blocked regardless of any allow rules. If it matches an **ask** rule, the user is prompted. If it matches an **allow** rule and no deny/ask rules match, it proceeds automatically. Rule Syntax [#rule-syntax] Rules use a `Tool(pattern)` format: ``` ToolName(pattern) ``` * `ToolName` — The name of the tool (e.g., `Bash`, `Read`, `Write`, `Edit`) * `pattern` — A glob-like pattern matching the tool's primary argument Pattern Examples [#pattern-examples] | Rule | Meaning | | ------------------ | --------------------------------------------- | | `Bash(git *)` | Allow/deny bash commands starting with `git` | | `Bash(pnpm *)` | Allow/deny bash commands starting with `pnpm` | | `Read(*)` | Allow/deny all file reads | | `Write(src/**)` | Allow/deny writes to files under `src/` | | `Write(*.test.ts)` | Allow/deny writes to test files | | `Bash(rm -rf *)` | Deny dangerous recursive delete commands | | `Edit(*)` | Allow/deny all file edits | Wildcards [#wildcards] * `*` matches any sequence of characters within a single path segment * `**` matches any sequence of characters across path segments * `*` at the end matches any suffix Configuration [#configuration] Permission rules are defined in settings files: ```json { "permissions": { "allow": [ "Bash(git *)", "Bash(pnpm *)", "Read(*)", "Write(*)", "Edit(*)" ], "deny": [ "Bash(rm -rf *)", "Bash(curl *|*)", "Bash(wget *)" ], "ask": [ "Bash(*)" ] } } ``` Setting Rules via CLI [#setting-rules-via-cli] ```bash # Set allow rules xc settings set permissions.allow '["Bash(git *)","Read(*)","Write(*)"]' # Set deny rules xc settings set permissions.deny '["Bash(rm -rf *)"]' # Set ask rules xc settings set permissions.ask '["Bash(*)"]' ``` Evaluation Flow [#evaluation-flow] When the agent wants to use a tool: 1. Check **deny** rules — if any match, the tool call is blocked 2. Check **ask** rules — if any match, the user is prompted for confirmation 3. Check **allow** rules — if any match, the tool call proceeds 4. If no rules match — the default policy applies (configurable, typically `ask`) Tool-Specific Rules [#tool-specific-rules] Bash Rules [#bash-rules] Bash rules match against the full command string: ``` Bash(git commit -m "fix: typo") → matches Bash(git *) Bash(rm -rf /) → matches Bash(rm -rf *) Bash(pnpm install) → matches Bash(pnpm *) Bash(npm run build) → matches Bash(*) (ask rule) ``` File Tool Rules [#file-tool-rules] File tools (`Read`, `Write`, `Edit`) match against the file path: ``` Read(src/agent.ts) → matches Read(*) Write(src/utils.ts) → matches Write(src/**) Edit(package.json) → matches Edit(*) Write(.env) → matches Write(*) but you might want to deny it ``` Example Configurations [#example-configurations] Permissive (Full Autonomy) [#permissive-full-autonomy] ```json { "permissions": { "allow": ["Bash(*)", "Read(*)", "Write(*)", "Edit(*)"], "deny": ["Bash(rm -rf *)"], "ask": [] } } ``` Cautious (Confirm Shell Commands) [#cautious-confirm-shell-commands] ```json { "permissions": { "allow": ["Read(*)", "Write(src/**)", "Edit(src/**)"], "deny": ["Bash(rm -rf *)", "Bash(curl *|*)"], "ask": ["Bash(*)", "Write(*)", "Edit(*)"] } } ``` Read-Only [#read-only] ```json { "permissions": { "allow": ["Read(*)"], "deny": ["Write(*)", "Edit(*)", "Bash(*)"], "ask": [] } } ``` Project-Enforced Policy [#project-enforced-policy] In `/etc/xibecode/settings.json` (policy source, cannot be overridden): ```json { "permissions": { "deny": [ "Bash(rm -rf *)", "Bash(curl *|*)", "Bash(wget *)", "Write(.env*)" ], "allow": ["Read(*)", "Write(src/**)", "Edit(src/**)", "Bash(git *)", "Bash(pnpm *)"] } } ``` Agent Behavior [#agent-behavior] When a tool call is denied: * The agent receives a "Tool call denied by permission rules" message * The agent does **not** retry the denied tool call * The agent attempts to accomplish the task using alternative approaches * If no alternative exists, the agent reports the denial to the user When a tool call requires confirmation: * The agent pauses and waits for user approval * The user can approve or deny the specific call * The user can approve all similar calls for the session Interaction with Agent Modes [#interaction-with-agent-modes] Agent modes have built-in tool restrictions that combine with permission rules: * **Review mode** — Read-only by mode definition, regardless of permission rules * **Security mode** — Read-only by mode definition * **Agent mode** — Full access, filtered by permission rules * **Plan mode** — Can only write to `implementations.md` Permission rules add a layer on top of mode restrictions. Even in agent mode, denied tools remain denied. Next Steps [#next-steps] * [Settings](/docs/settings) — Configure settings sources and merging * [Lifecycle Hooks](/docs/hooks) — Run custom logic at agent events * [Agent Modes](/docs/modes) — Understand mode-based tool restrictions # Plugin System XibeCode's plugin system lets you extend the AI with custom tools and domain-specific logic. Plugins are JavaScript/TypeScript modules that register new tool definitions. Why Use Plugins? [#why-use-plugins] * **Custom Tools** — Add tools specific to your workflow * **Domain Logic** — Integrate with internal APIs and services * **Automation** — Create deployment, testing, or CI/CD tools * **Data Access** — Connect to databases, APIs, or file systems Quick Start [#quick-start] ```bash # 1. Create a plugin file touch my-plugin.js # 2. Add to config (~/.xibecode/config.json) # "plugins": ["/path/to/my-plugin.js"] # 3. Reload XibeCode xibecode chat > /reload ``` Creating a Plugin [#creating-a-plugin] A plugin exports a default object with metadata and a `registerTools()` method: ```javascript export default { name: "my-custom-plugin", version: "1.0.0", description: "Adds custom tools for my workflow", registerTools() { return [ { schema: { name: "deploy_to_staging", description: "Deploy the app to staging environment", input_schema: { type: "object", properties: { branch: { type: "string", description: "Branch to deploy" }, force: { type: "boolean", description: "Force deploy" }, }, required: ["branch"], }, }, async handler(input) { console.log(`Deploying ${input.branch} to staging...`); await new Promise((resolve) => setTimeout(resolve, 2000)); return { success: true, url: "https://staging.example.com" }; }, }, ]; }, initialize() { console.log("Plugin loaded!"); }, cleanup() { console.log("Plugin unloaded!"); }, }; ``` Loading Plugins [#loading-plugins] Add plugin paths to your config: ```json { "plugins": [ "/absolute/path/to/my-plugin.js", "./relative/path/to/plugin.js", "~/plugins/deploy-plugin.js" ] } ``` Plugin API [#plugin-api] | Property | Type | Required | Description | | ----------------- | -------- | -------- | --------------------------------- | | `name` | `string` | Yes | Unique plugin identifier | | `version` | `string` | Yes | Semver version string | | `description` | `string` | Yes | What the plugin does | | `registerTools()` | `Tool[]` | Yes | Returns array of tool definitions | | `initialize()` | `void` | No | Setup hook | | `cleanup()` | `void` | No | Cleanup hook | Tool Schema [#tool-schema] Each tool follows the Anthropic tool use schema: ```javascript { schema: { name: 'tool_name', description: 'What it does', input_schema: { type: 'object', properties: { param1: { type: 'string', description: 'Description' }, param2: { type: 'number', description: 'Description' }, param3: { type: 'boolean', description: 'Description' }, param4: { type: 'array', items: { type: 'string' }, description: 'List' } }, required: ['param1'] } }, handler: async (input) => { return { result: '...' }; } } ``` Plugin Examples [#plugin-examples] Deployment Plugin [#deployment-plugin] ```javascript export default { name: "deploy-plugin", version: "1.0.0", description: "Deployment tools for staging and production", registerTools() { return [ { schema: { name: "deploy_to_staging", description: "Deploy the current branch to staging", input_schema: { type: "object", properties: { branch: { type: "string" } }, required: ["branch"], }, }, async handler(input) { const { execSync } = await import("child_process"); execSync(`git push origin ${input.branch}:staging`); return { success: true, environment: "staging" }; }, }, { schema: { name: "check_deployment_status", description: "Check if deployment is complete", input_schema: { type: "object", properties: { environment: { type: "string", enum: ["staging", "production"] }, }, required: ["environment"], }, }, async handler(input) { return { status: "deployed", environment: input.environment }; }, }, ]; }, }; ``` Database Migration Plugin [#database-migration-plugin] ```javascript export default { name: "migration-plugin", version: "1.0.0", description: "Database migration tools", registerTools() { return [ { schema: { name: "run_migration", description: "Run database migration", input_schema: { type: "object", properties: { direction: { type: "string", enum: ["up", "down"] }, steps: { type: "number" }, }, required: ["direction"], }, }, async handler(input) { const { execSync } = await import("child_process"); const cmd = input.direction === "up" ? "npx prisma migrate deploy" : "npx prisma migrate reset --skip-seed"; execSync(cmd, { stdio: "inherit" }); return { success: true, direction: input.direction }; }, }, ]; }, }; ``` Internal API Integration [#internal-api-integration] ```javascript export default { name: "internal-api-plugin", version: "1.0.0", description: "Connect to internal company APIs", initialize() { this.apiBase = process.env.INTERNAL_API_URL; this.apiKey = process.env.INTERNAL_API_KEY; }, registerTools() { const apiBase = this.apiBase; const apiKey = this.apiKey; return [ { schema: { name: "query_internal_api", description: "Query internal company API", input_schema: { type: "object", properties: { endpoint: { type: "string" }, method: { type: "string", enum: ["GET", "POST", "PUT", "DELETE"], }, body: { type: "object" }, }, required: ["endpoint"], }, }, async handler(input) { const res = await fetch(`${apiBase}${input.endpoint}`, { method: input.method || "GET", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: input.body ? JSON.stringify(input.body) : undefined, }); return await res.json(); }, }, ]; }, }; ``` Notification Plugin [#notification-plugin] ```javascript export default { name: "notification-plugin", version: "1.0.0", description: "Send notifications via Slack", registerTools() { return [ { schema: { name: "send_slack_message", description: "Send a message to Slack", input_schema: { type: "object", properties: { channel: { type: "string" }, message: { type: "string" }, }, required: ["channel", "message"], }, }, async handler(input) { const webhookUrl = process.env.SLACK_WEBHOOK_URL; await fetch(webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ channel: input.channel, text: input.message, }), }); return { success: true, channel: input.channel }; }, }, ]; }, }; ``` Error Handling [#error-handling] ```javascript async handler(input) { try { const result = await someOperation(input); return { success: true, data: result }; } catch (error) { return { success: false, error: error.message, suggestion: 'Try checking if the service is running' }; } } ``` Best Practices [#best-practices] * **Clear descriptions** — The AI reads tool descriptions to decide when to use them * **Handle errors gracefully** — Return useful error messages * **Keep plugins focused** — One concern per plugin * **Use `initialize()` for setup** — Database connections, API clients * **Use `cleanup()` for teardown** — Close connections, clean resources * **Validate inputs** — Check required inputs before proceeding * **Return structured data** — Objects with clear success/failure status Debugging Plugins [#debugging-plugins] ```bash xibecode chat > /plugins # Check if plugin is loaded > /tools # View available tools from plugins > Use the deploy_to_staging tool with branch "main" ``` Next Steps [#next-steps] * [MCP Integration](/docs/mcp) — Connect to external servers * [Tools Reference](/docs/tools) — Built-in tools * [Examples](/docs/examples) — Real-world workflows # Providers Providers [#providers] XibeCode talks to **OpenAI-compatible** and **Anthropic-compatible** HTTP APIs. Pick a provider in `xibecode setup`, chat `/setup`, or config flags. Recommended [#recommended] | Id | Name | Base URL | Format | Env key | | ------------ | ----------- | ---------------------------- | ------ | -------------------- | | `routingrun` | Routing.run | `https://api.routing.run/v1` | openai | `ROUTINGRUN_API_KEY` | | `zenllm` | zenllm.org | `https://api.zenllm.org/v1` | openai | `ZENLLM_API_KEY` | Major APIs [#major-apis] | Id | Name | Base URL | Format | Env key | | -------------- | ------------------------- | --------------------------------------------------------- | --------- | -------------------- | | `anthropic` | Anthropic | `https://api.anthropic.com/v1` | anthropic | `ANTHROPIC_API_KEY` | | `openai` | OpenAI | `https://api.openai.com/v1` | openai | `OPENAI_API_KEY` | | `openrouter` | OpenRouter | `https://openrouter.ai/api/v1` | openai | `OPENROUTER_API_KEY` | | `deepseek` | DeepSeek | `https://api.deepseek.com/v1` | openai | `DEEPSEEK_API_KEY` | | `google` | Google AI Studio (Gemini) | `https://generativelanguage.googleapis.com/v1beta/openai` | openai | `GOOGLE_API_KEY` | | `grok` / `xai` | xAI (Grok) | `https://api.x.ai/v1` | openai | `XAI_API_KEY` | | `groq` | Groq | `https://api.groq.com/openai/v1` | openai | `GROQ_API_KEY` | Zhipu / Moonshot / MiniMax / Qwen [#zhipu--moonshot--minimax--qwen] | Id | Name | Base URL | Format | Env key | | --------------------- | ------------------------- | -------------------------------------------------------- | --------- | ----------------------------- | | `zai` | Z.AI / GLM | `https://api.z.ai/api/paas/v4` | openai | `ZAI_API_KEY` | | `kimi` | Moonshot (Kimi Anthropic) | `https://api.moonshot.ai/anthropic` | anthropic | `MOONSHOT_API_KEY` | | `kimi-coding` | Kimi Coding Plan | `https://api.moonshot.ai/v1` | openai | `KIMI_API_KEY` | | `kimi-coding-cn` | Kimi China | `https://api.moonshot.cn/v1` | openai | `KIMI_CN_API_KEY` | | `alibaba` | Qwen Cloud (DashScope) | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1` | openai | `DASHSCOPE_API_KEY` | | `alibaba-coding-plan` | Alibaba Coding Plan | `https://coding-intl.dashscope.aliyuncs.com/v1` | openai | `ALIBABA_CODING_PLAN_API_KEY` | | `minimax` | MiniMax | `https://api.minimax.io/anthropic` | anthropic | `MINIMAX_API_KEY` | | `minimax-cn` | MiniMax China | `https://api.minimaxi.com/anthropic` | anthropic | `MINIMAX_CN_API_KEY` | Aggregators & gateways [#aggregators--gateways] | Id | Name | Base URL | Format | Env key | | -------------- | ------------ | --------------------------------------- | ------ | ---------------------- | | `fireworks` | Fireworks AI | `https://api.fireworks.ai/inference/v1` | openai | `FIREWORKS_API_KEY` | | `novita` | NovitaAI | `https://api.novita.ai/openai/v1` | openai | `NOVITA_API_KEY` | | `huggingface` | Hugging Face | `https://router.huggingface.co/v1` | openai | `HF_TOKEN` | | `opencode-zen` | OpenCode Zen | `https://opencode.ai/zen/v1` | openai | `OPENCODE_ZEN_API_KEY` | | `opencode-go` | OpenCode Go | `https://opencode.ai/zen/go/v1` | openai | `OPENCODE_GO_API_KEY` | | `kilocode` | Kilo Code | `https://api.kilo.ai/api/gateway` | openai | `KILOCODE_API_KEY` | | `ollama-cloud` | Ollama Cloud | `https://ollama.com/v1` | openai | `OLLAMA_API_KEY` | Specialized & local [#specialized--local] | Id | Name | Base URL | Format | Env key | | ------------------ | ----------------- | ------------------------------------- | ------ | ----------------------- | | `nvidia` | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | openai | `NVIDIA_API_KEY` | | `xiaomi` | Xiaomi MiMo | `https://api.xiaomimimo.com/v1` | openai | `XIAOMI_API_KEY` | | `tencent-tokenhub` | Tencent TokenHub | `https://tokenhub.tencentmaas.com/v1` | openai | `TOKENHUB_API_KEY` | | `stepfun` | StepFun Step Plan | `https://api.stepfun.ai/step_plan/v1` | openai | `STEPFUN_API_KEY` | | `arcee` | Arcee AI | `https://api.arcee.ai/api/v1` | openai | `ARCEEAI_API_KEY` | | `gmi` | GMI Cloud | `https://api.gmi-serving.com/v1` | openai | `GMI_API_KEY` | | `lmstudio` | LM Studio (local) | `http://127.0.0.1:1234/v1` | openai | `LM_API_KEY` | | `azure-foundry` | Azure AI Foundry | *(you provide)* | openai | `AZURE_FOUNDRY_API_KEY` | Config flags [#config-flags] ```bash xibecode config --set-provider openrouter xibecode config --set-key sk-or-... xibecode config --set-model anthropic/claude-sonnet-4-6 xibecode config --set-base-url https://openrouter.ai/api/v1 ``` Custom / proxy: ```bash xibecode setup model # choose Custom / auto-detect, paste any OpenAI-compatible base URL ``` Or set `baseUrl` + `requestFormat` (`openai` | `anthropic` | `auto`) in the profile. Failover pool [#failover-pool] For higher reliability, configure fallback endpoints (tried on rate limits / outages): ```bash export XIBECODE_FALLBACK_PROVIDERS='openrouter|anthropic/claude-sonnet-4-6|sk-or-...|https://openrouter.ai/api/v1,deepseek|deepseek-chat|sk-...|https://api.deepseek.com/v1' ``` Format per entry: `provider|model|apiKey|baseUrl` (comma-separated list). Also available as profile `fallbackProviders`. Priority for API keys [#priority-for-api-keys] 1. Profile `apiKey` (from setup / config) 2. Provider-specific env var (`envKey` column) 3. Alternate env vars (e.g. `GLM_API_KEY` for zai, `GEMINI_API_KEY` for google) Model catalogs [#model-catalogs] When you run `/model` or `xibecode models`, the CLI may combine: 1. Live provider `GET /models` (when the base URL supports it) 2. **models.dev** registry (broad multi-provider catalog) 3. Built-in curated fallbacks Non-chat models are filtered by default. Anthropic-style endpoints receive appropriate headers for model listing. Related [#related] * [Setup wizard](/docs/setup) * [Configuration](/docs/configuration) * [Chat slash commands](/docs/chat-slash-commands) — `/setup`, `/model`, `/format` # Quick Start Get productive with XibeCode in minutes. This guide walks you through your first autonomous coding session and introduces key features. Your First Task [#your-first-task] The `run` command lets XibeCode autonomously complete coding tasks. Just describe what you want: ```bash xibecode run "Create a Python script that prints hello world" ``` XibeCode will read your project, create the file, and verify it works — all autonomously. For a more realistic first task: ```bash # Add a simple healthcheck endpoint to an Express API xibecode run "Add GET /health that returns { status: 'ok' } and tests for it" --mode agent ``` Interactive Chat [#interactive-chat] For iterative development and quick questions, use chat mode: ```bash xibecode chat ``` This starts the interactive terminal UI. In chat mode you can: * Ask questions about your codebase * Request code changes step by step * Run `/setup` for a guided provider → API key → model flow (or use `/config` for quick edits) * Switch between agent personas with `/mode` * Type `/exit` to leave Full command reference: [Chat slash commands](/docs/chat-slash-commands). Local-first default [#local-first-default] If you run `xc` or `xibecode` with no subcommand, it starts local chat behavior by default. Cloud Runtime Quickstart [#cloud-runtime-quickstart] Use cloud mode when you want E2B-backed execution: ```bash # Start cloud chat xibecode cloud # Resume an existing sandbox by sandbox id xibecode cloud resume # Pull sandbox workspace changes back to local xibecode cloud pull --session ``` In cloud `sandbox_full` chat sessions, you can also use: ```bash /cpull /cpull --apply ``` See [Cloud & E2B Runtime](/docs/cloud-e2b) for full details. 24/7 Daemon (Telegram) [#247-daemon-telegram] Code from your phone while the agent runs on a host or E2B sandbox: ```bash xibecode setup gateway xibecode daemon --install --workdir /path/to/repo xibecode daemon --start ``` In Telegram: | Command | Use | | -------------- | ---------------------------------------------------------- | | Normal message | Start / continue a coding task (steers mid-run by default) | | `/cmd ls -la` | Shell in the chat workdir **without** the agent | | `/stop` | Interrupt the current run and free the chat | | `/update yes` | On E2B: install latest CLI + restart (chats kept) | | `/status` | Workdir, busy state, sandbox id | Full guide: [Xibe Daemon](/docs/gateway). Diagnostics Bundle [#diagnostics-bundle] When debugging issues or preparing a bug report: ```bash xibecode diagnostics ``` This generates a redacted markdown diagnostics bundle you can share safely. ```bash # Optional: check for CLI updates (never silent) xibecode update --check xibecode whats-new ``` Agent Modes (Personas) [#agent-modes-personas] XibeCode features 13 agent personas, each optimized for different tasks. Switch modes to get specialized assistance: ```bash # In chat mode, switch personas /mode plan # Aria the Architect - planning and analysis /mode agent # Default mode - full coding capabilities /mode debugger # Dex the Detective - bug hunting and fixing /mode tester # Tess the QA Engineer - testing and quality /mode security # Sentinel the Guardian - security audits /mode review # Nova the Critic - code reviews ``` Key Personas [#key-personas] | Mode | Persona | Best For | | ---------- | --------------------- | ------------------------------------------------- | | `agent` | Blaze the Builder | Full-stack development, building features | | `plan` | Aria the Architect | Understanding codebases, planning implementations | | `tester` | Tess the QA Engineer | Writing tests, ensuring quality | | `security` | Sentinel the Guardian | Security audits, vulnerability detection | | `review` | Nova the Critic | Code quality checks without modifications | Currently enabled for user selection: `agent`, `plan`, `review`. Other modes are defined internally. Run Command Options [#run-command-options] ```bash xibecode run [prompt] [options] Options: -f, --file Read prompt from a file -m, --model AI model to use -b, --base-url Custom API base URL -k, --api-key API key (overrides config) -d, --max-iterations Maximum iterations (default: 150) -v, --verbose Show detailed logs --dry-run Preview changes without making them --changed-only Focus only on git-changed files --mode Start in a specific agent mode --cost-mode normal or economy --provider anthropic, openai, google, groq, custom ``` Example Tasks [#example-tasks] Build a Feature [#build-a-feature] ```bash xibecode run "Add user authentication to the Express API: - POST /auth/register - POST /auth/login - JWT token generation - Middleware to protect routes" ``` Fix a Bug [#fix-a-bug] ```bash xibecode run "The tests in test/user.test.js are failing. Debug and fix the issues." --verbose ``` Refactor Code [#refactor-code] ```bash xibecode run "Refactor src/ to use TypeScript: - Convert all .js files to .ts - Add type annotations - Create types.ts for shared types" ``` Generate Tests [#generate-tests] ```bash xibecode run "Write comprehensive tests for userController.js: - Test all endpoints - Test error cases - Use Jest - Achieve >80% coverage" ``` Preview Changes (Dry Run) [#preview-changes-dry-run] ```bash xibecode run "Refactor authentication module" --dry-run ``` Create a PR [#create-a-pr] ```bash xibecode run-pr "Add input validation to all API endpoints" --draft ``` How XibeCode Works [#how-xibecode-works] When you give XibeCode a task, it follows this autonomous loop: 1. **Read** — Analyzes your project structure, reads relevant files 2. **Plan** — Breaks down the task into steps 3. **Execute** — Creates/edits files, runs commands using 50+ tools 4. **Verify** — Runs tests, checks for errors 5. **Iterate** — Fixes any issues until the task is complete The entire process is autonomous — XibeCode continues iterating until the task is done or it reaches the maximum iteration limit. It has built-in loop detection to prevent infinite loops. Key Features [#key-features] Smart Context Discovery [#smart-context-discovery] XibeCode automatically discovers related files by following imports, finding tests, and understanding project configuration. Automatic Backups [#automatic-backups] Every file edit creates a timestamped backup. You can revert to any previous state: ```bash # In chat mode /revert src/app.ts # Revert to previous version ``` Git Integration [#git-integration] XibeCode can create checkpoints before making changes: ```bash xibecode run "Refactor the database layer (create checkpoint first)" ``` Test Integration [#test-integration] XibeCode auto-detects your test runner (Vitest, Jest, pytest, Go test, etc.) and runs tests to verify changes. Safety Controls [#safety-controls] Dangerous commands are blocked, and risky operations are flagged: * Dry-run mode for safe previews * Risk assessment before execution * Command blocking for destructive operations * Path sandboxing prevents access outside working directory Neural Memory [#neural-memory] XibeCode learns from your project over time. It remembers patterns, preferences, and lessons learned: ```bash # The agent automatically stores lessons # You can also manually teach it xibecode chat > Remember that we use Prisma for database access in this project ``` Auto-Memory (v1.1) [#auto-memory-v11] XibeCode automatically extracts and persists project-specific memories across sessions. Relevant memories are injected into context when you start a new task: ```bash # View all project memories xc memory list # Search for specific memories xc memory search "authentication" # Run dream consolidation to merge and prune stale entries xc memory dream ``` Permission Rules (v1.1) [#permission-rules-v11] Control which tools the agent can use with allow/deny/ask rules: ```bash # Allow git commands, deny dangerous deletes, ask for other shell commands xc settings set permissions.allow '["Bash(git *)","Read(*)","Write(*)"]' xc settings set permissions.deny '["Bash(rm -rf *)"]' xc settings set permissions.ask '["Bash(*)"]' ``` Lifecycle Hooks (v1.1) [#lifecycle-hooks-v11] Run custom scripts at key agent events: ```bash # Log every tool use xc hooks add PreToolUse command "echo 'Using: $TOOL_NAME' >> audit.log" # Notify on session end xc hooks add SessionEnd http "https://hooks.example.com/done" ``` Multi-Source Settings (v1.1) [#multi-source-settings-v11] Configuration is merged from multiple sources with clear priority: ```bash # View merged settings xc settings list # Set a global default xc settings set agent.defaultMode plan # Set a project-specific override xc settings set agent.defaultMode agent --source project ``` Next Steps [#next-steps] * [Agent Modes](/docs/modes) — Deep dive into the core personas * [Configuration](/docs/configuration) — Configure XibeCode for your workflow * [Tools Reference](/docs/tools) — Explore all 50+ available tools * [Cloud & E2B Runtime](/docs/cloud-e2b) — Understand cloud execution, resume, and pull flows * [Chat Slash Commands](/docs/chat-slash-commands) — `/cpull`, `/commit`, and other shortcuts * [MCP Integration](/docs/mcp) — Set up extended capabilities * [Settings](/docs/settings) — Multi-source layered configuration * [Lifecycle Hooks](/docs/hooks) — Custom logic at agent events * [Auto-Memory](/docs/memory) — Persistent project memory * [Permissions](/docs/permissions) — Fine-grained tool execution rules * [Examples](/docs/examples) — See more real-world tasks Unlimited iterations [#unlimited-iterations] By default the agent loop is **not** capped. Use a positive `-d` only when you want a hard budget: ```bash xibecode run "large refactor" # unlimited xibecode run "quick fix" -d 40 # stop after 40 turns ``` See [Agent engine](/docs/agent). # Settings XibeCode uses a layered configuration system that merges settings from multiple sources. This lets you set global preferences, override them per-project, and enforce organizational policies. Settings Sources [#settings-sources] Settings are loaded from four sources, merged in priority order (highest wins): | Priority | Source | Path | Scope | | ----------- | ----------- | ------------------------------- | ------------------------- | | 1 (highest) | **Policy** | `/etc/xibecode/settings.json` | Machine-wide, enforced | | 2 | **Local** | `.xibecode/settings.local.json` | Project, not committed | | 3 | **Project** | `.xibecode/settings.json` | Project, committed to git | | 4 (lowest) | **User** | `~/.xibecode/settings.json` | Global, personal defaults | When the same key exists in multiple sources, the higher-priority source wins. Settings Schema [#settings-schema] ```json { "permissions": { "allow": ["Bash(git *)", "Read(*)", "Write(*)"], "deny": ["Bash(rm -rf *)"], "ask": ["Bash(*)"] }, "hooks": { "PreToolUse": [ { "type": "command", "value": "echo 'about to use a tool'" } ], "SessionStart": [ { "type": "command", "value": "echo 'session started'" } ] }, "agent": { "defaultMode": "agent", "autoApprovalPolicy": "always", "microcompactThreshold": 0.75, "dreamConsolidationInterval": 3600 }, "memory": { "enabled": true, "maxMemories": 100, "relevanceThreshold": 0.3 } } ``` CLI Commands [#cli-commands] List all settings [#list-all-settings] ```bash xc settings list ``` Shows the fully merged settings with the source of each value indicated. Get a specific key [#get-a-specific-key] ```bash xc settings get permissions.allow xc settings get agent.defaultMode ``` Set a value [#set-a-value] ```bash xc settings set agent.defaultMode plan xc settings set permissions.allow '["Bash(git *)","Read(*)"]' ``` By default, values are written to the **user** settings file. Use `--source` to target a specific layer: ```bash xc settings set agent.defaultMode plan --source project xc settings set permissions.deny '["Bash(rm -rf *)"]' --source policy ``` View source files [#view-source-files] ```bash xc settings sources ``` Lists all setting sources with their paths and whether they exist. View file paths [#view-file-paths] ```bash xc settings paths ``` Shows the exact file paths for each settings source. Example Workflows [#example-workflows] Global defaults with per-project overrides [#global-defaults-with-per-project-overrides] Set your preferred model globally: ```bash xc settings set agent.defaultMode agent ``` Override for a specific project by creating `.xibecode/settings.json` in the project root: ```json { "agent": { "defaultMode": "plan" } } ``` Team-shared project settings [#team-shared-project-settings] Commit `.xibecode/settings.json` to share settings with your team: ```json { "permissions": { "allow": ["Read(*)", "Write(src/**)"], "deny": ["Bash(rm -rf *)"], "ask": ["Bash(*)"] }, "hooks": { "PreToolUse": [ { "type": "command", "value": "audit-log.sh" } ] } } ``` Keep personal overrides in `.xibecode/settings.local.json` (add to `.gitignore`): ```json { "agent": { "autoApprovalPolicy": "always" } } ``` Enforced organizational policies [#enforced-organizational-policies] Place machine-wide policies in `/etc/xibecode/settings.json`: ```json { "permissions": { "deny": ["Bash(curl *|*)", "Bash(wget *)"], "allow": ["Read(*)", "Write(*)", "Bash(git *)", "Bash(pnpm *)"] } } ``` Policy settings cannot be overridden by user or project settings. How Merging Works [#how-merging-works] The merge is a deep merge: * **Objects** are merged recursively (nested keys from higher priority override lower) * **Arrays** are replaced entirely by the higher-priority source (not concatenated) * **Primitives** use the highest-priority value For example, if user settings has `permissions.allow: ["Read(*)"]` and project settings has `permissions.allow: ["Read(*)", "Write(*)"]`, the merged result is `["Read(*)", "Write(*)"]` — the project array replaces the user array entirely. Next Steps [#next-steps] * [Permissions](/docs/permissions) — Configure allow/deny/ask rules * [Lifecycle Hooks](/docs/hooks) — Register custom logic at agent events * [Auto-Memory](/docs/memory) — Persistent project memory system # Setup wizard Setup wizard [#setup-wizard] `xibecode setup` walks you through first-time configuration: **LLM provider + API key**, optional **24/7 Xibe Daemon** (Telegram / Discord / Slack), and **agent defaults**. Commands [#commands] ```bash # Full wizard (model → gateway → agent) xibecode setup # Sections only xibecode setup model xibecode setup gateway xibecode setup agent # Model + Telegram only xibecode setup --quick # Print flags/env guidance (CI / headless) xibecode setup --non-interactive ``` Requires an interactive TTY for the numbered menus. In CI, use config flags instead (see Non-interactive). What it configures [#what-it-configures] 1\. Model & provider (`setup model`) [#1-model--provider-setup-model] 1. **Numbered provider list** — full XibeCode catalog (Routing.run, zenllm.org, Anthropic, OpenAI, OpenRouter, DeepSeek, Gemini, Grok, Z.AI, Kimi, MiniMax, Fireworks, Novita, local LM Studio, Azure Foundry, models.dev-backed catalogs, and more). 2. **API key** — stored in your profile (`~/.xibecode/profile-*.json`). 3. **Default model** — provider presets or custom id. 4. **Base URL** — optional override for proxies / OpenAI-compatible endpoints. 5. **Request format** — OpenAI or Anthropic wire format from the provider preset. 6. Mirrors the key into `~/.xibecode/daemon.env` / `gateway.env` for the always-on daemon. See [Providers](/docs/providers) for the full table. 2\. 24/7 daemon (`setup gateway`) [#2-247-daemon-setup-gateway] Optional Telegram (and Discord/Slack via env) configuration: * Writes `TELEGRAM_BOT_TOKEN`, `TELEGRAM_ALLOWED_USERS`, etc. to `~/.xibecode/daemon.env` (or `gateway.env`) * Can install and start the **systemd user service** (`xibecode-daemon`) for always-on coding from chat CLI primary command is **`xibecode daemon`** (`xibecode gateway` is an alias). See [Xibe Daemon](/docs/gateway) for `/cmd`, `/update`, steer mode, media, start/stop, and pairing. 3\. Agent defaults (`setup agent`) [#3-agent-defaults-setup-agent] * Working directory preferences * **Max iterations** — `0` means **unlimited** (recommended for long autonomous tasks; abort with Ctrl+C or daemon `/stop`) * Cost mode and related caps * Auto-compact stays on by default (see [Agent engine](/docs/agent#auto-compact)) Non-interactive / CI [#non-interactive--ci] ```bash xibecode config --set-key YOUR_API_KEY xibecode config --set-provider anthropic xibecode config --set-model claude-sonnet-4-6 xibecode config --show ``` Daemon without the wizard: ```bash # Edit ~/.xibecode/daemon.env (or gateway.env) TELEGRAM_BOT_TOKEN=... TELEGRAM_ALLOWED_USERS=your_user_id ANTHROPIC_API_KEY=... # or provider-specific key xibecode daemon --install --workdir /path/to/repo xibecode daemon --start # alias: xibecode gateway --install / --start ``` Related [#related] | Command | Purpose | | ------------------------- | --------------------------------------------- | | `xibecode config` | Interactive or flag-based profile edits | | Chat `/setup` | In-session provider/key/model (chat TUI only) | | `xibecode diagnostics` | Redacted diagnostics bundle | | `xibecode update --check` | Check for newer npm CLI (never silent apply) | **Note:** CLI `xibecode setup` is the full onboarding path. Chat slash `/setup` only updates the active chat profile for that session. # AI Test Generation Automatically generate comprehensive test suites for your code using AI-powered analysis. Quick Start [#quick-start] Via CLI (in chat mode) [#via-cli-in-chat-mode] ```bash xibecode chat > generate tests for src/utils/helpers.ts ``` Via Autonomous Run [#via-autonomous-run] ```bash xibecode run "Generate comprehensive tests for src/utils/helpers.ts" ``` Supported Frameworks [#supported-frameworks] | Framework | Language | Features | | ----------- | --------------------- | ------------------------------------------------------------- | | Vitest | JavaScript/TypeScript | describe/it blocks, vi.mock() setup, expect assertions | | Jest | JavaScript/TypeScript | describe/it blocks, jest.mock() setup, expect assertions | | Mocha | JavaScript/TypeScript | describe/it blocks, Sinon mocks, Chai assertions | | pytest | Python | class TestX format, Mock/patch setup, assert statements | | Go test | Go | func TestX format, testify/mock, assert package | | Auto-detect | Any | Reads package.json, checks dependencies, falls back to Vitest | Features [#features] * **Code Analysis** — Understands functions, classes, types, imports, and exports. Detects complexity and dependencies. * **Edge Case Generation** — Automatically generates tests for null values, empty strings, boundary conditions, and error cases. * **Type Checking** — Creates assertions for return types, ensuring functions return expected data types. * **Mock Setup** — Automatically configures mocks for dependencies and external modules. Tool API [#tool-api] generate_tests [#generate_tests] Analyze a source file and generate comprehensive test cases. | Parameter | Type | Description | | ------------------------ | ------- | ----------------------------------------------- | | `file_path` | string | Path to source file (required) | | `framework` | string | vitest, jest, mocha, pytest, go (auto-detected) | | `output_dir` | string | Custom output directory for tests | | `include_edge_cases` | boolean | Include edge case tests (default: true) | | `include_mocks` | boolean | Include mock setup code (default: true) | | `max_tests_per_function` | number | Maximum tests per function (default: 5) | | `write_file` | boolean | Write to file (default: false) | analyze_code_for_tests [#analyze_code_for_tests] Analyze a source file to understand its structure before generating tests. | Parameter | Type | Description | | ----------- | ------ | ------------------------------ | | `file_path` | string | Path to source file (required) | Example Output [#example-output] Given a file with a `calculateTotal` function: ```javascript import { describe, it, expect, vi } from "vitest"; import { calculateTotal } from "../utils/helpers"; beforeEach(() => { vi.clearAllMocks(); }); describe("calculateTotal", () => { it("should execute calculateTotal successfully", () => { expect(calculateTotal([])).toBeDefined(); }); it("should return correct type from calculateTotal", () => { expect(typeof calculateTotal([])).toBe("number"); }); it("should handle empty array", () => { expect(calculateTotal([])).toBe(0); }); it("should handle single element", () => { expect(calculateTotal([10])).toBe(10); }); it("should handle errors in calculateTotal", () => { expect(() => calculateTotal(undefined)).toThrow(); }); }); ``` Generated Test Types [#generated-test-types] | Type | Description | Example | | ---------- | ---------------------------- | ------------------------------- | | `unit` | Basic functionality tests | Function returns expected value | | `edge` | Edge case and boundary tests | Empty string, null, MAX\_INT | | `boundary` | Boundary condition tests | Array length 0, 1, MAX | | `error` | Error handling tests | Invalid input throws error | Best Practices [#best-practices] * **Review generated tests** — AI-generated tests are a starting point, not the final product * **Add domain-specific assertions** — The generator may miss business logic requirements * **Use `write_file: false` first** — Preview tests before writing to disk * **Run tests after generation** — Verify they pass and cover expected behavior * **Customize edge cases** — Add project-specific edge cases as needed Programmatic Usage [#programmatic-usage] Use test generation from the `xibecode-core` library: ```typescript import { CodingToolExecutor } from 'xibecode-core'; const executor = new CodingToolExecutor(process.cwd()); const result = await executor.executeTool('generate_tests', { file_path: 'src/utils/helpers.ts', framework: 'vitest', }); ``` # Tools Reference XibeCode provides 50+ built-in tools across 8 categories for autonomous coding operations. These tools are automatically available to the AI agent based on the current mode's permissions. Tool Categories Overview [#tool-categories-overview] | Category | Tools | Description | | -------------------- | ----- | ------------------------------------------------- | | File Operations | 8 | Read, write, edit, delete files | | Directory Operations | 3 | List, search, create, move | | Git Operations | 7 | Status, diff, checkpoints, revert | | Shell & Code Search | 2 | Execute commands, grep code | | Web Operations | 2 | Search, fetch URLs | | Test Operations | 4 | Run tests, generate tests, analyze code | | Memory Operations | 6+ | curated\_memory, session\_search, skills, lessons | | Browser Operations | 8 | Screenshots, testing, performance, accessibility | Reliability Controls (v0.9.1) [#reliability-controls-v091] Recent versions add stronger guardrails around tool execution quality: * **Evidence-aware completion gating**: the agent must gather grounded evidence before it can conclude work. * **Post-edit verification**: edit/write actions are validated with read-back checks. * **Improved loop resistance**: repeated same/near-same tool input patterns are detected and blocked earlier. * **Safer memory recall**: recalled memories are treated as hints and filtered by relevance. * **Grounded context compaction**: old context keeps summarized facts instead of silently dropping all detail. File Operations [#file-operations] read_file [#read_file] Read the contents of a file. ```json { "path": "src/app.ts", "start_line": 1, "end_line": 100 } ``` read_multiple_files [#read_multiple_files] Read multiple files at once for context. ```json { "paths": ["src/app.ts", "src/utils.ts", "package.json"] } ``` write_file [#write_file] Write content to a file (creates or overwrites). ```json { "path": "src/new-file.ts", "content": "export const hello = 'world';" } ``` edit_file [#edit_file] Edit a file using search and replace. ```json { "path": "src/app.ts", "search": "const oldValue = 1;", "replace": "const newValue = 2;" } ``` edit_lines [#edit_lines] Edit specific line ranges in a file. ```json { "path": "src/app.ts", "start_line": 10, "end_line": 15, "content": "// New content" } ``` insert_at_line [#insert_at_line] Insert content at a specific line. ```json { "path": "src/app.ts", "line": 5, "content": "import { newModule } from './module';" } ``` verified_edit [#verified_edit] Edit with verification — ensures the search pattern exists before replacing. ```json { "path": "src/app.ts", "search": "exact content to find", "replace": "replacement content" } ``` delete_file [#delete_file] Delete a file. ```json { "path": "src/deprecated.ts" } ``` Directory Operations [#directory-operations] list_directory [#list_directory] ```json { "path": "src/", "recursive": false } ``` search_files [#search_files] ```json { "pattern": "*.ts", "path": "src/" } ``` create_directory [#create_directory] ```json { "path": "src/new-feature/" } ``` move_file [#move_file] ```json { "source": "src/old-name.ts", "destination": "src/new-name.ts" } ``` Git Operations [#git-operations] get_git_status [#get_git_status] Returns staged, unstaged, and untracked files. get_git_diff_summary [#get_git_diff_summary] ```json { "staged": true } ``` get_git_changed_files [#get_git_changed_files] Get list of files changed in the current branch. create_git_checkpoint [#create_git_checkpoint] ```json { "message": "before auth refactor", "strategy": "stash" } ``` revert_to_git_checkpoint [#revert_to_git_checkpoint] ```json { "checkpoint_id": "stash@{0}" } ``` git_show_diff [#git_show_diff] ```json { "path": "src/app.ts" } ``` get_mcp_status [#get_mcp_status] Get MCP server status. Shell Commands [#shell-commands] run_command [#run_command] ```json { "command": "npm install express", "cwd": "./", "timeout": 30000, "stdin": "input data" } ``` Dangerous commands like `rm -rf /` are blocked automatically. In cloud `sandbox_full` mode, file and command tools execute against the remote sandbox workspace (not your host absolute paths). Use repo-relative paths for reliable results. Code Search [#code-search] grep_code [#grep_code] ```json { "pattern": "function.*async", "path": "src/", "include": "*.ts", "case_sensitive": false } ``` Web Operations [#web-operations] web_search [#web_search] ```json { "query": "typescript best practices 2024", "num_results": 5 } ``` fetch_url [#fetch_url] ```json { "url": "https://api.example.com/data", "method": "GET" } ``` Test Operations [#test-operations] run_tests [#run_tests] ```json { "path": "src/", "filter": "auth", "verbose": true } ``` Supports: Vitest, Jest, Mocha, pytest, Go test, Cargo test. get_test_status [#get_test_status] Returns passed, failed, and skipped test counts. Memory Operations [#memory-operations] curated_memory [#curated_memory] Durable global memory in `~/.xibecode/memories/MEMORY.md` and `USER.md`. Prefer an atomic **`operations`** batch for multi-change or consolidation when full. ```json { "target": "memory", "operations": [ { "action": "remove", "old_text": "stale fact" }, { "action": "add", "content": "Prefer pnpm for all package installs" } ] } ``` * `target`: `memory` (agent notes) or `user` (profile/preferences) * Single-op fields: `action`, `content`, `old_text` * Frozen into the system prompt at **session start**; mid-session writes apply next session * On success: `done=true` — do not re-save the same entry See [Memory](/docs/memory). session_search [#session_search] Search past sessions when details are not in MEMORY.md. ```json { "query": "auth middleware fix", "limit": 8 } ``` save_skill / list_skills / view_skill [#save_skill--list_skills--view_skill] * **`save_skill`** — write a reusable procedure under `~/.xibecode/skills/learned/` * **`list_skills`** — progressive disclosure (metadata only) * **`view_skill`** — load full skill body by name remember_lesson [#remember_lesson] ```json { "trigger": "Build failed after git pull", "action": "Ran pnpm install and rebuilt", "outcome": "Typecheck passed", "tags": ["deps", "pnpm"] } ``` update_memory [#update_memory] Legacy/project memory key-value style updates (project auto-memory layer). Prefer `curated_memory` for durable cross-session facts. Browser & screenshots [#browser--screenshots] **Playwright is not bundled** with the CLI (no Chromium download on install). Prefer: 1. **`take_screenshot`** (agent-browser first, then headless Chrome/Chromium) 2. **`run_command` + `agent-browser`** for interactive browser flows 3. MCP or project-local Playwright if you need full E2E in the consumer repo Optional: install `agent-browser` globally on supported platforms. Override with `XIBECODE_PREFERRED_BROWSER=chrome`. take_screenshot [#take_screenshot] ```json { "url": "http://localhost:3000", "path": "screenshots/home.png", "fullPage": true } ``` * **`path` must be under the project workspace** (e.g. `screenshots/home.png`). Absolute `/tmp/...` paths are remapped into `screenshots/`. * Result includes a **`MEDIA:…`** line — put it in the final reply so Telegram uploads the PNG. * Localhost is allowed. Other browser tools [#other-browser-tools] `get_console_logs`, `run_visual_test`, accessibility/performance/responsive helpers may return **guidance stubs** when no bundled browser is available — use `agent-browser` or host tooling instead. Context Operations [#context-operations] get_context [#get_context] Get smart context for a file (imports, tests, related files). revert_file [#revert_file] Revert a file to its last backed-up state. Skills Operations [#skills-operations] search_skills_sh [#search_skills_sh] Search for skills on skills.sh marketplace. install_skill_from_skills_sh [#install_skill_from_skills_sh] Install a skill from skills.sh. Tool Permissions by Mode [#tool-permissions-by-mode] * **read\_only**: read\_file, read\_multiple\_files, list\_directory, search\_files * **write\_fs**: write\_file, edit\_file, edit\_lines, insert\_at\_line, delete\_file, move\_file, create\_directory * **git\_read**: get\_git\_status, get\_git\_diff\_summary, get\_git\_changed\_files, git\_show\_diff * **git\_mutation**: create\_git\_checkpoint, revert\_to\_git\_checkpoint * **shell\_command**: run\_command * **tests**: run\_tests, get\_test\_status * **network**: web\_search, fetch\_url * **context**: grep\_code, get\_context Safety Features [#safety-features] * **Command Blocking** — Dangerous commands like `rm -rf /` are blocked * **Risk Assessment** — High-risk operations are flagged with warnings * **Automatic Backups** — Files are backed up before editing * **Dry-Run Mode** — Preview changes without executing * **Mode Permissions** — Tools are restricted based on current mode * **Completion Evidence Gate** — Prevents premature “done” responses without grounded proof Extending Tools [#extending-tools] You can add custom tools via: * [Plugins](/docs/plugins) — JavaScript/TypeScript modules * [MCP Servers](/docs/mcp) — External tool servers Next Steps [#next-steps] * [Agent Modes](/docs/modes) — Learn about mode permissions * [Plugins](/docs/plugins) — Create custom tools * [Examples](/docs/examples) — See tools in action