### Install OpenCode with Bun Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Install the `opencode-ai` package globally using Bun. ```bash bun install -g opencode-ai ``` -------------------------------- ### Start the SolidStart development server with npm run dev Source: https://github.com/anomalyco/opencode/blob/dev/services/site/README.md After installing dependencies with npm install (or pnpm install or yarn), run npm run dev to start the development server. Add -- --open to automatically open the app in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Run /connect command in the TUI Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Run this command in the TUI to start connecting a provider, then select opencode and head to opencode.ai/auth. ```txt /connect ``` -------------------------------- ### Initialize project with /init Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Run this command to have OpenCode analyze your project and create an AGENTS.md file in the project root. ```bash /init ``` -------------------------------- ### Navigate to project directory Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Change into the project you want to work on before running OpenCode. ```bash cd /path/to/project ``` -------------------------------- ### Run OpenCode Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Launch OpenCode from within your project directory. ```bash opencode ``` -------------------------------- ### Install OpenCode on Windows with Mise Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Install OpenCode globally on Windows using Mise from the GitHub repository. ```bash mise use -g github:anomalyco/opencode ``` -------------------------------- ### Ask OpenCode to explain a file Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Use the @ key to fuzzy search for files; this prompt asks how authentication is handled in a specific file. ```txt How is authentication handled in @packages/functions/src/api/index.ts ``` -------------------------------- ### Install OpenCode with Yarn Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Add the `opencode-ai` package globally using Yarn. ```bash yarn global add opencode-ai ``` -------------------------------- ### Start development server with npm run dev Source: https://github.com/anomalyco/opencode/blob/dev/packages/console/app/README.md Start the local development server after installing dependencies, with an optional flag to automatically open the application in a new browser tab. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Install OpenCode with npm Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Install the `opencode-ai` package globally using npm. ```bash npm install -g opencode-ai ``` -------------------------------- ### Install OpenCode 1 via install script Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx The easiest way to install OpenCode 1. This installs the `opencode` binary and can conflict with or replace an OpenCode 2 installation. ```bash curl -fsSL https://opencode.ai/install | bash ``` -------------------------------- ### Ask OpenCode to make the changes Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx After switching to Build mode, ask OpenCode to implement the planned changes. ```bash Sounds good! Go ahead and make the changes. ``` -------------------------------- ### Install OpenCode with pnpm Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Install the `opencode-ai` package globally using pnpm. ```bash pnpm install -g opencode-ai ``` -------------------------------- ### Describe the feature to implement Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Provide enough detail for OpenCode to understand the desired feature, such as flagging deleted notes and building a recently deleted screen. ```txt When a user deletes a note, we'd like to flag it as deleted in the database. Then create a screen that shows all the recently deleted notes. From this screen, the user can undelete a note or permanently delete it. ``` -------------------------------- ### Install OpenCode on Windows with Scoop Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Install OpenCode on Windows using Scoop. WSL is recommended for the best experience. ```bash scoop install opencode ``` -------------------------------- ### Iterate on the plan with an image reference Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Give feedback or add details to the plan; drag and drop images into the terminal to add them to the prompt. ```txt We'd like to design this new screen using a design I've used before. [Image #1] Take a look at this image and use it as a reference. ``` -------------------------------- ### Paste API key prompt Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx After signing in and copying your API key, paste it at this prompt. ```txt ┌ API key │ │ └ enter ``` -------------------------------- ### Request a refactor of a function Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Example prompt asking OpenCode to refactor a function in a referenced file. ```txt Can you refactor the function in @packages/functions/src/api/index.ts? ``` -------------------------------- ### Configuration search example from /home/user/projects/acme/packages/web Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/config.mdx OpenCode searches from the current directory to the filesystem root. This example shows the files discovered when starting OpenCode from /home/user/projects/acme/packages/web. ```text /etc/opencode/opencode.json ~/.config/opencode/opencode.json /home/user/projects/acme/ ├── opencode.json └── packages/ └── web/ ├── opencode.json └── src/ ``` -------------------------------- ### Start OpenCode server for desktop app connection Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/windows-wsl.mdx Starts the server in WSL listening on 0.0.0.0 at port 4096 to allow external desktop app connections. ```bash opencode serve --hostname 0.0.0.0 --port 4096 ``` -------------------------------- ### Make changes directly with file references Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx For straightforward changes, ask OpenCode to build directly without reviewing a plan, referencing the relevant files with @. ```txt We need to add authentication to the /settings route. Take a look at how this is handled in the /notes route in @packages/functions/src/notes.ts and implement the same logic in @packages/functions/src/settings.ts ``` -------------------------------- ### Install OpenCode on Windows with Chocolatey Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Install OpenCode on Windows using Chocolatey. WSL is recommended for the best experience. ```bash choco install opencode ``` -------------------------------- ### Window setup with createKeyed and cleanup function Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Window setup must be synchronous; start asynchronous work inside createKeyed or createLatest. Registrations made through ctx are withdrawn when the owning scope ends. Return a cleanup function for other resources like timers. ```tsx import { Command, createKeyed, Plugin } from "@opencode/plugin/gui" import { Changes } from "@opencode/plugin/gui/review" export default Plugin.define({ i18n: { en: { changes: "Show changes" } }, setup(ctx) { // Runs once per active generation of Changes; the command is withdrawn with it. createKeyed(ctx.use(Changes), (changes) => { ctx.add(Command, () => ({ id: "changes", title: ctx.t("changes"), run: () => { const session = ctx.sessions.current() if (session) changes.open(session) }, })) }) const timer = setInterval(() => console.log("still here"), 60_000) return () => clearInterval(timer) }, }) ``` -------------------------------- ### Run OpenCode with Docker Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Run OpenCode in an interactive Docker container from the GitHub Container Registry. ```bash docker run -it --rm ghcr.io/anomalyco/opencode ``` -------------------------------- ### Start the API and web server with opencode serve Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/cli/commands.mdx Starts the API and web server. ```bash $ opencode serve ``` -------------------------------- ### Define a main setup with Plugin.MainSetup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Main setup in src/gui/main.ts typed as Plugin.MainSetup, which runs on desktop only. Writes a log line via ctx.log. ```ts import type { Plugin } from "@opencode/plugin/gui" export const main: Plugin.MainSetup = (ctx) => { ctx.log.write("info", "acme started") } ``` -------------------------------- ### Redo changes with /redo Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Use the /redo command to redo changes that were undone. ```bash /redo ``` -------------------------------- ### Find instances with SelectorOptions examples Source: https://github.com/anomalyco/opencode/blob/dev/packages/plugins/figma/skills/figma-code-connect/references/api.md Usage examples for finding instances by specific hierarchy path or traversing all nested instances. ```javascript // Find icon only in specific hierarchy const icon = instance.findInstance('Icon', { path: ['Header', 'Actions', 'IconSlot'] }) // Search everywhere including nested instances const anyIcon = instance.findInstance('Icon', { traverseInstances: true }) ``` -------------------------------- ### Install dependencies and start development Source: https://github.com/anomalyco/opencode/blob/dev/packages/desktop/README.md Installs dependencies and launches the desktop app in development mode. `bun dev` uses local renderer/server mode, the dev app identity, and the CLI source by default. ```bash bun install bun dev ``` -------------------------------- ### Run opencode with a prompt example Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/cli.mdx Example of running opencode with a prompt to explain the use of context in Go. ```bash opencode run Explain the use of context in Go ``` -------------------------------- ### Launch Vite TUI live development session with bun Source: https://github.com/anomalyco/opencode/blob/dev/packages/cli/dev/README.md Starts the CLI and its TUI via Vite and solid-refresh from the repository root, connecting directly to the installed server. Component edits trigger hot updates while the backend remains active across syntax error retries and full reloads. ```sh bun run dev:vite:live /path/to/project ``` -------------------------------- ### Switch to Plan mode with Tab Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Press Tab to switch to Plan mode, which disables changes and suggests how the feature will be implemented. ```bash ``` -------------------------------- ### Run startup benchmark with strobe bench Source: https://github.com/anomalyco/opencode/blob/dev/packages/desktop/README.md Runs the startup benchmark defined in perf/startup.bench.ts using strobe. The first command benchmarks two packaged builds or installed channels; the second benchmarks the first launch after an install; the third benchmarks the dev loop's cold start. strobe runs on Windows, macOS, and Linux. ```bash # A returning user's launches of two packaged builds (pack each with OPENCODE_CHANNEL=beta or prod), or two installed # channels. strobe bench perf/startup.bench.ts --target desktop --base exe:/OpenCode.exe --head exe:/OpenCode.exe strobe bench perf/startup.bench.ts --target desktop --base app:opencode --head app:opencode-beta # The first launch after an install. strobe bench perf/startup.bench.ts --target install --base app:opencode --head app:opencode-beta # The dev loop's cold start, dev against this checkout. strobe bench perf/startup.bench.ts --target dev --base origin/dev --head . ``` -------------------------------- ### Return a cleanup function from setup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/cli.mdx Return a cleanup function to release resources owned by the plugin. The example subscribes to `session.execution.succeeded` and stops the subscription when cleanup runs. ```ts setup(context) { const stop = context.data.on("session.execution.succeeded", () => {}) return () => stop() } ``` -------------------------------- ### Start OpenCode in a project directory Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/cli/tui.mdx Run OpenCode from your project root to begin a session. After launching, type a request and press Enter. ```bash cd ~/code/my-project opencode ``` -------------------------------- ### Return a cleanup function from setup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/server.mdx `setup` may return a cleanup function that runs when the plugin unloads. The context exposes `ctx.app.version`. ```typescript import { Plugin } from "@opencode/plugin" export default Plugin.define({ id: "example", setup(ctx) { console.log(`loaded in OpenCode ${ctx.app.version}`) return () => console.log("unloaded") }, }) ``` -------------------------------- ### Install Figma Code Connect CLI globally Source: https://github.com/anomalyco/opencode/blob/dev/packages/plugins/figma/skills/figma-code-connect/references/api.md Installs the `@figma/code-connect` package globally using npm. ```bash npm install --global @figma/code-connect@latest ``` -------------------------------- ### Initial load and background plugin boot flow Source: https://github.com/anomalyco/opencode/blob/dev/specs/v2/catalog-config-plugin-lifecycle.md Illustrates building a baseline catalog from immediate sources while background fibers activate slower plugins asynchronously. ```ts LocationServiceMap.get(ref) → build location layer → Catalog.layer creates empty catalog state → PluginBoot.layer activates immediately available plugins → ConfigProviderPlugin installs Catalog.transform() → ModelsDevPlugin installs Catalog.transform() → AuthPlugin installs Catalog.transform() → Catalog.layer applies active transforms during boot → apply policy → materialize baseline provider/model catalog → PluginBoot baseline ready → Frontend.fetchCatalog() PluginBoot background fiber → install/update plugin packages concurrently → activate completed plugins → Catalog.transform() → transform(updateCatalog) → Catalog internally rebuilds → Catalog.Event.Updated → Frontend.refetchCatalog() ``` -------------------------------- ### Create a GUI main plugin setup with pairing service and screen blocker Source: https://github.com/anomalyco/opencode/blob/dev/packages/gui-plugins/README.md Defines a `Plugin.MainSetup` that wires a pairing state machine to CLI service commands, power-save blocking, and persisted settings. Register it as the default export; it provides the `Pairing` service and cleans up on disposal. ```ts import { execFile } from "node:child_process" import { powerSaveBlocker } from "electron" import { Schema } from "effect" import { builtinMainContext } from "@opencode/plugin/gui/builtin" import type { Plugin } from "@opencode/plugin/gui/main" import { Pairing } from "./contract" import { createDispatch } from "./dispatch" import { createPairingMainState, pairingMainEffectFailed, selectBlocker, transitionPairingMain, type PairingMainEffect, type ServiceRequest, } from "./main-machine" type Waiter = { resolve: (value: boolean | undefined) => void; reject: (error: Error) => void } const setup: Plugin.MainSetup = (ctx) => { // Whether main keeps the display awake; stored before in the desktop's own settings namespace. const stored = builtinMainContext(ctx).storage.store("keepScreenActive", { schema: Schema.Boolean, initial: false, from: { state: ["opencode.settings", "keepScreenActive"] }, }) const cli = ctx.cli const log = ctx.log const current = { state: createPairingMainState(), waiter: 0 } // Each running command's abort controller, and each caller waiting on a command. const commands = new Map() const waiters = new Map() const dispatch = createDispatch({ read: () => current.state, write: (state) => { current.state = state }, transition: transitionPairingMain, run: (effect: PairingMainEffect) => run(effect), failed: pairingMainEffectFailed, }) // The OS can drop the blocker, so whether main holds it is asked each time. const screenActive = () => { const id = selectBlocker(current.state) return id !== undefined && powerSaveBlocker.isStarted(id) } const run = (effect: PairingMainEffect) => { if (effect.type === "blocker.start") return dispatch({ type: "blocker.started", id: powerSaveBlocker.start("prevent-display-sleep") }) if (effect.type === "blocker.stop") { if (powerSaveBlocker.isStarted(effect.id)) powerSaveBlocker.stop(effect.id) return } if (effect.type === "persist.screen") return stored.set(effect.enabled) if (effect.type === "service.abort") { commands.get(effect.attempt)?.abort() commands.delete(effect.attempt) return } if (effect.type === "waiter.resolve" || effect.type === "waiter.reject") { const waiter = waiters.get(effect.waiter) waiters.delete(effect.waiter) if (effect.type === "waiter.resolve") return waiter?.resolve(effect.value) return waiter?.reject(new Error(effect.message)) } // Remote access is a setting of the background service, so it changes through the CLI the app runs, as with // `opencode pair --remote`. A hung command ends at its timeout, so the next one always runs. const attempt = effect.attempt const controller = new AbortController() commands.set(attempt, controller) execFile( cli.command[0] ?? "opencode", [...cli.command.slice(1), "service", ...effect.args], { signal: AbortSignal.any([ctx.signal, controller.signal]), timeout: effect.timeoutMs, windowsHide: true }, (error, stdout, stderr) => { commands.delete(attempt) if (!error) return dispatch({ type: "service.succeeded", attempt, stdout: stdout.trim() }) log.write("error", "pairing service command failed", { args: effect.args, error: error.message, stderr }) dispatch({ type: "service.failed", attempt, message: error.message }) }, ) } // Queues a command. A read stops when its caller goes away; a change goes on. const service = (request: ServiceRequest, signal?: AbortSignal) => { current.waiter += 1 const waiter = current.waiter const cancel = () => dispatch({ type: "waiter.cancelled", waiter }) return new Promise((resolve, reject) => { waiters.set(waiter, { resolve, reject }) signal?.addEventListener("abort", cancel, { once: true }) dispatch({ type: "service.requested", waiter, request }) if (signal?.aborted) cancel() }).finally(() => signal?.removeEventListener("abort", cancel)) } if (stored.value) dispatch({ type: "screen.set", enabled: true, started: false }) ctx.onCleanup(() => dispatch({ type: "disposed" })) ctx.provide(Pairing, { remote: async (_, caller) => (await service({ kind: "get-remote" }, caller.signal)) === true, // Changing the setting stops the service, and starting it again brings it back. A window that closes meanwhile // does not cancel the change. setRemote: async (enabled) => { await service({ kind: "set-remote", enabled }) }, screenActive, setScreenActive: (enabled) => dispatch({ type: "screen.set", enabled, started: screenActive() }), }) } export default setup ``` -------------------------------- ### Example playground session Source: https://github.com/anomalyco/opencode/blob/dev/packages/process-daemon/README.md Sample sequence exercising demo, terminal creation, shell commands, screen/replay inspection, resize, kill, and quit. ```text demo new run printf '\033[32mgreen from the shell\033[0m\n' new /bin/sh list use 1 screen replay 1 0 resize 72 20 kill 2 quit ``` -------------------------------- ### Combine definition, setup, and main in src/gui.tsx Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Entry file that imports the definition, window setup, and main setup and exports the combined plugin via Plugin.define. ```tsx import { Plugin } from "@opencode/plugin/gui" import { definition } from "./gui/definition" import { main } from "./gui/main" import { setup } from "./gui/window" export default Plugin.define({ ...definition, setup, main }) ``` -------------------------------- ### Register a Server with ready and entries Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Use ctx.add to register a Server that contributes a list of server connections. Startup waits for every source to be ready; a ready source's entries are its complete inventory. Each entry's key is :. ```ts import { Server } from "@opencode/plugin/gui" ctx.add( Server, (): Server => ({ ready: loaded(), entries: machines().map((machine) => ({ id: machine.id, name: machine.name, label: "Acme", state: machine.url ? "ready" : "starting", http: machine.url ? { url: machine.url } : undefined, })), }), ) ``` -------------------------------- ### Install OpenCode on Arch Linux Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx The official Arch package installs OpenCode 2; use the AUR `opencode-bin` package to install OpenCode 1. ```bash sudo pacman -S opencode # Arch Linux (OpenCode 2) paru -S opencode-bin # Arch Linux (OpenCode 1, from AUR) ``` -------------------------------- ### Créer un thème spécifique au projet Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/fr/themes.mdx Crée le dossier .opencode/themes à la racine du projet et initialise un fichier de thème local. ```bash mkdir -p .opencode/themes vim .opencode/themes/my-theme.json ``` -------------------------------- ### Define a GUI plugin with Plugin.define and setup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx A plugin's setup runs in every desktop app window. Pass it to Plugin.define from @opencode/plugin/gui in the plugin's ./gui-experimental file. setup is synchronous and may return a cleanup function. ```tsx import { Command, Plugin } from "@opencode/plugin/gui" export default Plugin.define({ i18n: { en: { open: "Open Acme" } }, setup(ctx) { ctx.add(Command, () => ({ id: "open", title: ctx.t("open"), run: () => ctx.system.openExternal("https://acme.example"), })) }, }) ``` -------------------------------- ### Install the Figma plugin via CLI Source: https://github.com/anomalyco/opencode/blob/dev/packages/plugins/figma/README.md Installs the plugin directly from the Git repository's Figma directory using the default branch. ```sh opencode plugin add 'git+https://github.com/anomalyco/opencode.git#path:packages/plugins/figma' ``` -------------------------------- ### Create a new SolidStart project Source: https://github.com/anomalyco/opencode/blob/dev/packages/console/app/README.md Initialize a new SolidStart project in the current working directory or a specified folder using npm init. ```bash # create a new project in the current directory npm init solid@latest # create a new project in my-app npm init solid@latest my-app ``` -------------------------------- ### Install OpenCode 1 with Homebrew Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Use the OpenCode tap for V1 on macOS and Linux. Homebrew's `brew install opencode` formula currently installs V2. ```bash brew install anomalyco/tap/opencode ``` -------------------------------- ### Start the playground with cargo run -- play Source: https://github.com/anomalyco/opencode/blob/dev/packages/process-daemon/README.md Starts and owns a new daemon named play; it cannot adopt an already running daemon. ```sh cargo run -- play --name play ``` -------------------------------- ### Plugin setup with ctx.use, ctx.stores, and ctx.add Source: https://github.com/anomalyco/opencode/blob/dev/packages/gui-plugins/README.md Access another plugin's contract via ctx.use(Changes) and read a declared store with ctx.stores.prefs.value, which is loaded before setup. Contribute a command using the function form so labels are re-read when the language changes. ```ts const setup: Plugin.Setup = (ctx) => { const changes = ctx.use(Changes) // Accessor> const prefs = ctx.stores.prefs.value // loaded before setup ctx.add(Command, () => ({ id: "open", title: ctx.t("open"), run: () => ctx.layout.settings(ctx.id) })) } ``` -------------------------------- ### Install the GitHub agent in your repository Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/cli.mdx Install the GitHub agent in your repository. This sets up the necessary GitHub Actions workflow and guides you through the configuration process. ```bash opencode github install ``` -------------------------------- ### Install xvfb and start virtual display for headless Linux copy/paste Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/troubleshooting.mdx Install xvfb and run a virtual display for copy/paste in headless environments. The export sets DISPLAY to the virtual display. ```bash apt install -y xvfb # and run: Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & export DISPLAY=:99.0 ``` -------------------------------- ### TextNode Range Methods Source: https://github.com/anomalyco/opencode/blob/dev/packages/plugins/figma/skills/figma-use-figjam/references/edit-text.md SDK methods on TextNode for getting and setting properties across a specific character range (start to end indices). ```APIDOC ## TextNode Range Methods ### Description Methods available on `TextNode` instances to apply mixed styling, fonts, fills, hyperlinks, and list options to specific character ranges. ### Methods - `textNode.setRangeFontName(start, end, fontName)` - `textNode.setRangeFontSize(start, end, size)` - `textNode.setRangeFills(start, end, fills)` - `textNode.setRangeTextDecoration(start, end, decoration)` - `textNode.setRangeTextCase(start, end, textCase)` - `textNode.setRangeLetterSpacing(start, end, spacing)` - `textNode.setRangeLineHeight(start, end, lineHeight)` - `textNode.setRangeHyperlink(start, end, hyperlink)` - `textNode.setRangeListOptions(start, end, listOptions)` - `textNode.setRangeIndentation(start, end, indentation)` - `textNode.getRangeFontName(start, end)` - `textNode.getRangeFontSize(start, end)` ### Usage Examples ```javascript // Make "Hello" bold (characters 0-5) textNode.setRangeFontName(0, 5, { family: 'Inter', style: 'Bold' }); // Make "World" red (characters 6-11) textNode.setRangeFills(6, 11, [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }]); // Change size of "World" textNode.setRangeFontSize(6, 11, 24); // Get properties for a range const fontAtStart = textNode.getRangeFontName(0, 1); const sizeAtEnd = textNode.getRangeFontSize(10, 11); ``` ``` -------------------------------- ### Main setup with async and ctx.onCleanup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx main may be async. Return or resolve to a cleanup function for resources it opens, or register it with ctx.onCleanup(fn). ctx.onCleanup runs functions when the plugin is disabled, reloaded, or removed, or the app quits, last registered first. ```ts async main(ctx) { const socket = await connect(ctx.options) ctx.onCleanup(() => socket.close()) } ``` -------------------------------- ### Example prompt to explain authentication Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/cli/tui.mdx Type a natural-language request in the OpenCode prompt and press Enter to send it. ```text Explain how authentication works in this project ``` -------------------------------- ### Add a custom LSP server with command and extensions Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/lsp.mdx Add custom LSP servers by specifying the command and file extensions. The example defines a server named `custom-lsp`. ```json { "$schema": "https://opencode.ai/config.json", "lsp": { "custom-lsp": { "command": ["custom-lsp-server", "--stdio"], "extensions": [".custom"] } } } ``` -------------------------------- ### Run Hermes model setup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/console/harnesses/hermes.mdx Run the model setup and select OpenCode Zen for pay-as-you-go or OpenCode Go for Go. Paste a personal API key, then choose a model; Hermes saves the key to ~/.hermes/.env and the selection to ~/.hermes/config.yaml. ```bash hermes model ``` -------------------------------- ### Run /connect in OpenCode to choose a workspace Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/console/index.mdx Use the /connect command in OpenCode to select the workspace after subscribing to Go, adding credits, or connecting a provider. ```text /connect ``` -------------------------------- ### Write the window entry with lazy-loaded settings page and Pairing Source: https://github.com/anomalyco/opencode/blob/dev/packages/gui-plugins/README.md Defines the plugin setup for the desktop window, returning early when `ctx.desktop` is absent. The settings page loads behind `lazy()` and preloads on idle; the local server is found via `ctx.servers` by `builtin`, and remote access/display entries appear only while pairing status is `active`. ```tsx import { lazy, onCleanup, Suspense } from "solid-js" import { Command, SettingsPage, type Plugin } from "@opencode/plugin/gui" import { onIdle } from "@opencode/plugin/gui/builtin" import { Pairing } from "./contract" import type definition from "./index" const setup: Plugin.Setup = (ctx) => { if (!ctx.desktop) return const layout = ctx.layout const servers = ctx.servers const pairing = ctx.use(Pairing) const Page = lazy(() => import("./page")) // Settings rows are small; load them while idle so settings opens without a blank row. onCleanup(onIdle(() => void Page.preload())) // The desktop's own server. Its ref is already authenticated in this window, so codes need no main process. const local = () => servers .list() .map((id) => servers.get(id)) .find((server) => server?.builtin) ctx.add(SettingsPage, { id: "pairing", icon: "outline-pair", get title() { return ctx.t("title") }, get entries() { const pairingEntry = { id: "pairing", title: ctx.t("title"), keywords: "pair device qr phone remote" } // Remote access and the display setting exist only while pairing's main side answers. if (pairing().status !== "active") return [pairingEntry] return [ pairingEntry, { id: "settings-remote-access", title: ctx.t("remote.title"), description: ctx.t("remote.description"), keywords: "internet tunnel opentunnel", }, { id: "settings-keep-screen-active", title: ctx.t("screenActive.title"), description: ctx.t("screenActive.description"), keywords: "display sleep awake local", }, ] }, render: () => ( ), }) ctx.add(Command, () => ({ id: "open", title: ctx.t("command.title"), group: ctx.t("command.category.server"), run: () => layout.settings("pairing"), })) } export default setup ``` -------------------------------- ### desktop.launch(path: string, app?: string): Promise Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Opens a path with an app, or with the default app. Desktop only. ```APIDOC ## desktop.launch(path: string, app?: string): Promise ### Description Opens a path with an app, or with the default app. Desktop only. ### Method desktop.launch ### Parameters - **path** (string) - Required - The path to open. - **app** (string) - Optional - The app to use. If omitted, the default app is used. ### Response Returns a Promise that resolves when the launch is complete. ``` -------------------------------- ### Create, get, and read session context Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/server.mdx Use ctx.session.create to start a session, ctx.session.get to fetch it by sessionID, and ctx.session.context to read its messages. ```ts const created = await ctx.session.create({ title: "Review" }) const session = await ctx.session.get({ sessionID }) const messages = await ctx.session.context({ sessionID }) ``` -------------------------------- ### Set environment variables for an LSP server with env Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/lsp.mdx Use the `env` property to set environment variables when starting the LSP server. The example sets `RUST_LOG` to `debug` for rust-analyzer. ```json { "$schema": "https://opencode.ai/config.json", "lsp": { "rust": { "command": ["rust-analyzer"], "env": { "RUST_LOG": "debug" } } } } ``` -------------------------------- ### Type a window setup with Plugin.Setup Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Window setup in src/gui/window.tsx typed as Plugin.Setup, which types ctx.stores from the declared stores. Provides the Notes token from the contract. ```tsx import type { Plugin } from "@opencode/plugin/gui" import { Notes } from "./contract" import type { definition } from "./definition" export const setup: Plugin.Setup = (ctx) => { ctx.provide(Notes, { count: () => ctx.stores.notes.value.count }) } ``` -------------------------------- ### View CLI help documentation Source: https://github.com/anomalyco/opencode/blob/dev/packages/plugins/figma/skills/figma-code-connect/references/api.md Displays help information for the figma connect CLI and its subcommands. ```bash npx figma connect --help npx figma connect publish --help npx figma connect unpublish --help ``` -------------------------------- ### Install Playwright Chromium and run local E2E tests Source: https://github.com/anomalyco/opencode/blob/dev/packages/app/README.md Install the Chromium browser, then run the local E2E suite. Playwright starts the Vite dev server automatically via webServer or reuses one already running; the --grep flag filters tests by name. ```bash bunx playwright install chromium bun run test:e2e:local bun run test:e2e:local -- --grep "settings" ``` -------------------------------- ### Set OPENCODE_CLAUDE_PATH for a non-PATH Claude install Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/claude-agent.mdx OpenCode finds claude on your PATH by default. Set OPENCODE_CLAUDE_PATH on the server to point at another Claude Code copy. ```bash opencode service set env OPENCODE_CLAUDE_PATH /opt/claude/bin/claude ``` -------------------------------- ### ctx.layout.ready() Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Returns `true` once the stored layout has loaded. ```APIDOC ## ctx.layout.ready() ### Description Returns `true` once the stored layout has loaded. ### Method `ready(): boolean` ### Response - **boolean** - `true` once the stored layout has loaded. ``` -------------------------------- ### Undo changes with /undo Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/index.mdx Use the /undo command to revert changes; OpenCode shows your original message again so you can tweak the prompt. Run it multiple times to undo multiple changes. ```bash /undo ``` -------------------------------- ### Log in to Claude Code with claude auth login Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/claude-agent.mdx Run this to sign in to Claude Code before connecting Claude Agent. Claude Code 2.1.248 or later must be installed first. ```bash claude auth login ``` -------------------------------- ### SetupContext and Context interface reference Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx TypeScript interface definitions for SetupContext and Context, listing the properties and methods available on the GUI plugin host context. ```ts interface SetupContext extends Context { stores: Record | ((session: SessionRef) => Persisted)> } interface Context { id: string options: PluginOptions client: OpenCodeClient app: App signal: AbortSignal add(registry: Registry, item: () => T | undefined): Cleanup add(registry: Registry, item: T): Cleanup list(registry: Registry): T[] provide(token: Contract, impl: T): Cleanup use(token: Contract): () => Live use(token: Ipc): () => Live> main(token: Ipc): IpcClient t(key: string, params?: Record): string plural(key: string, count: number, params?: Record): string layout: Layout sessions: Sessions screen: Screen servers: Servers storage: Storage dialogs: Dialogs toast: Toasts attention: Attention tabs: Tabs keybinds: Keybinds commands: Commands links: Links embeds: Embeds ui: Ui system: System desktop: Desktop | undefined locale: Locale appearance: Appearance router: Router workspaces: Workspaces } ``` -------------------------------- ### Import a main store from the desktop settings file with builtinMainContext Source: https://github.com/anomalyco/opencode/blob/dev/packages/gui-plugins/README.md Creates a main store for saved SSH hosts, importing the older `ssh.servers` key from the desktop settings file via `from: { settings: ... }`. Use `{ state: [namespace, key] }` instead to name a key of another main storage namespace. ```typescript // The saved hosts; stored before in the desktop settings file. const saved = builtinMainContext(ctx).storage.store("servers", { schema: Schema.Array(SshConfig), initial: [], from: { settings: "ssh.servers" }, }) ``` -------------------------------- ### Start a video generation and stream events with ai.experimental.video.start Source: https://github.com/anomalyco/opencode/blob/dev/packages/ai/README.md Starts a video generation, iterates its events with a 10-second poll interval, awaits the result, and writes the video to disk. The handle's status and progress are snapshots from creation; call refresh() to get a new handle. Every promise method and stream accepts { signal }, and aborting rejects with signal.reason. ```ts import { ai } from "@opencode/ai" const generation = await ai.experimental.video.start({ model, prompt }) for await (const event of generation.events({ poll: { interval: 10_000 } })) console.log(event.type) const video = await generation.result({ signal }) await ai.write(video.video, "./kite.mp4") ``` -------------------------------- ### Run GitHub snapshot script with GITHUB_TOKEN Source: https://github.com/anomalyco/opencode/blob/dev/services/site/README.md The snapshot script uses GITHUB_TOKEN when set; CI passes the workflow's own token. Never commit a token. ```bash GITHUB_TOKEN=$(gh auth token) bun ./script/github-snapshot.ts ``` -------------------------------- ### Start OpenCode web client in WSL Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/windows-wsl.mdx Launches the web client from the WSL terminal bound to 0.0.0.0 for access via a Windows web browser. ```bash opencode web --hostname 0.0.0.0 ``` -------------------------------- ### Set EDITOR and start OpenCode to edit prompts Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/cli/tui.mdx Set VISUAL or EDITOR, then press Ctrl+X then E, or run /editor, to edit the current prompt in that editor. Save and exit to return the text to the composer. ```bash export EDITOR="nvim" opencode ``` -------------------------------- ### Run a shell command in shell mode Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/cli/tui.mdx Type ! at the start of an empty prompt to enter shell mode, then enter a command and press Enter. Press Esc to leave shell mode without running a command. ```text !git status ``` -------------------------------- ### ctx.layout.project(server, title) Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Opens a project's directory picker and a new draft. ```APIDOC ## ctx.layout.project(server, title) ### Description Opens a project's directory picker and a new draft. ### Method `project(server: string, title: string): void` ### Parameters - **server** (string) - Required - The server identifier. - **title** (string) - Required - The title. ``` -------------------------------- ### Install OpenCode via install script and package managers Source: https://github.com/anomalyco/opencode/blob/dev/README.md Installation commands for OpenCode across multiple package managers. Remove versions older than 0.1.x before installing. ```bash # YOLO curl -fsSL https://opencode.ai/v2/install | bash # Package managers npm i -g @opencode/cli@latest # or bun/pnpm/yarn brew install anomalyco/tap/opencode-v2 # macOS and Linux (recommended, always up to date) brew install opencode # macOS and Linux (official brew formula, updated less) sudo pacman -S opencode # Arch Linux (Stable) paru -S opencode-beta # Arch Linux (Latest from AUR) mise use -g opencode # Any OS nix run github:anomalyco/opencode # Nix ``` -------------------------------- ### Define a Contract with a valid and invalid token id Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Use `Contract.define` to create a token. A plugin can only provide tokens whose id is its own id or starts with it, as `.`. The second example uses the id `"badge"`, which would cause `ctx.provide` to throw in plugin `acme`. ```ts Contract.define("acme.badge") // Plugin acme can provide it. Contract.define("badge") // ctx.provide throws in plugin acme. ``` -------------------------------- ### Configure Atomic Chat local provider in opencode.json Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/providers.mdx Defines a custom provider ID `atomic-chat` using `@ai-sdk/openai-compatible` pointed at the local Atomic Chat server at `http://127.0.0.1:1337/v1`. Each model ID must match an id returned by `GET /v1/models`; change the host and port to match your setup. ```json { "$schema": "https://opencode.ai/config.json", "provider": { "atomic-chat": { "npm": "@ai-sdk/openai-compatible", "name": "Atomic Chat (local)", "options": { "baseURL": "http://127.0.0.1:1337/v1" }, "models": { "": { "name": "" } } } } } ``` -------------------------------- ### Create project-specific theme file Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/themes.mdx Create a new JSON theme file in the local project's .opencode/themes directory. ```bash mkdir -p .opencode/themes vim .opencode/themes/my-theme.json ``` -------------------------------- ### Install Electron and Node types Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/build/plugins/gui/index.mdx Add `electron` and `@types/node` as devDependencies for the Electron and Node types used in `main`. ```bash bun add -d electron @types/node ``` -------------------------------- ### Run backend and app dev servers separately for local UI changes Source: https://github.com/anomalyco/opencode/blob/dev/packages/app/AGENTS.md `opencode dev web` proxies the hosted app, so local UI/CSS changes won't appear there. Start the backend from the repository root and the app from packages/app, then open http://localhost:4444, which targets the backend at http://localhost:4096. ```shell bun dev serve --port 4096 ``` ```shell bun dev -- --port 4444 ``` -------------------------------- ### Create user-wide theme file Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/themes.mdx Create a new JSON theme file in the user configuration directory ~/.config/opencode/themes. ```bash mkdir -p ~/.config/opencode/themes vim ~/.config/opencode/themes/my-theme.json ``` -------------------------------- ### Install dependencies with bun install in sdks/vscode Source: https://github.com/anomalyco/opencode/blob/dev/sdks/vscode/README.md Run inside the sdks/vscode directory to install the extension's dependencies before debugging. ```shell bun install ``` -------------------------------- ### Install OpenCode Desktop on macOS via Homebrew Source: https://github.com/anomalyco/opencode/blob/dev/README.md Installs the OpenCode desktop application (BETA) using the Homebrew cask on macOS. ```bash # macOS (Homebrew) brew install --cask opencode-desktop ``` -------------------------------- ### Créer un thème à l'échelle de l'utilisateur Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/fr/themes.mdx Crée le répertoire de thèmes dans la configuration globale de l'utilisateur et initialise un nouveau fichier de thème. ```bash mkdir -p ~/.config/opencode/themes vim ~/.config/opencode/themes/my-theme.json ``` -------------------------------- ### Create Starlight Project with Astro CLI Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/README.md Scaffolds a new Astro documentation site configured with the official Starlight template. ```bash npm create astro@latest -- --template starlight ``` -------------------------------- ### Run OpenCode from WSL in a Windows project path Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/windows-wsl.mdx Navigates to a Windows drive mount path under /mnt/ and launches OpenCode. ```bash cd /mnt/c/Users/YourName/project opencode ``` -------------------------------- ### Install a plugin with opencode plugin Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/cli.mdx Installs a plugin and updates your config. Use --global to install in global config, --force to replace existing plugin version. ```bash opencode plugin ``` ```bash opencode plug ``` -------------------------------- ### GET /file/status Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/server.mdx Get status for tracked files. Returns an array of File objects. ```APIDOC ## GET /file/status ### Description Get status for tracked files. Returns an array of File objects. ### Method GET ### Endpoint /file/status ### Response #### Success Response (200) - **File[]** (File[]) - List of files #### Response Example [ "" ] ``` -------------------------------- ### GET /session/:id Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/server.mdx Get session details by ID. Returns the Session object. ```APIDOC ## GET /session/:id ### Description Get session details. ### Method GET ### Endpoint /session/:id ### Parameters #### Path Parameters - **id** (string) - Required - Session ID ### Response #### Success Response (200) - **Session** - The Session object ``` -------------------------------- ### Stop and start the service explicitly Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/troubleshooting.mdx Explicitly stops then starts the background service. Service commands are only needed when diagnosing its lifecycle, since OpenCode normally discovers or starts the service automatically. ```bash opencode service stop opencode service start ``` -------------------------------- ### Start opencode mini with a model and initial prompt Source: https://github.com/anomalyco/opencode/blob/dev/services/site/src/docs/content/cli/commands.mdx Begins a minimal session using the specified model and an initial prompt. ```bash $ opencode mini --model anthropic/claude-sonnet-5-5 --prompt "Summarize this repository" ``` -------------------------------- ### Automatically review pull requests with OpenCode Source: https://github.com/anomalyco/opencode/blob/dev/packages/web/src/content/docs/github.mdx Use this workflow to automatically review PRs when they are opened or updated. If no `prompt` is provided, OpenCode defaults to reviewing the pull request. `issues: write` lets OpenCode react to and comment on the PR, since GitHub handles PR comments through the issues API. This example is intended for PRs from branches in the same repository; PRs from forks normally get a read-only `GITHUB_TOKEN` and no secrets. ```yaml name: opencode-review on: pull_request: types: [opened, synchronize, reopened, ready_for_review] jobs: review: runs-on: ubuntu-latest permissions: contents: read pull-requests: read issues: write steps: - uses: actions/checkout@v6 - uses: anomalyco/opencode/github@latest env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: model: anthropic/claude-sonnet-5-5 use_github_token: true prompt: | Review this pull request: - Check for code quality issues - Look for potential bugs - Suggest improvements ```