chore: merge dev into beta

This commit is contained in:
Luke Parker
2026-10-23 09:41:06 +10:00
Unverified
262 changed files with 5344 additions and 2224 deletions
+6 -2
View File
@@ -25,8 +25,12 @@ jobs:
- name: Setup Bun
uses: ./.github/actions/setup-bun
- name: Run checks
run: bun run check
- name: Lint
run: bun run lint
# Local `bun run check` uses `bun check`; CI keeps the official TypeScript compiler as the source of truth.
- name: Typecheck (TypeScript 7.1)
run: bun run typecheck:tsc
# Every GUI package file (app, desktop, gui-extensions, ui, session-ui) a pull request adds or edits must be free of
# oxlint problems, warn-level rules (anti-slop) included. Other packages are not affected.
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
- name: Typecheck
working-directory: services/changelog
run: bun typecheck
run: bun run typecheck:tsc
- name: Test
working-directory: services/changelog
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
- name: Typecheck
working-directory: services/files
run: bun typecheck
run: bun run typecheck:tsc
- name: Deploy
working-directory: services/files
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
- name: Typecheck
working-directory: services/update
run: bun typecheck
run: bun run typecheck:tsc
- name: Deploy
working-directory: services/update
-72
View File
@@ -1,72 +0,0 @@
name: docs-update
on:
schedule:
- cron: "0 */12 * * *"
workflow_dispatch:
env:
LOOKBACK_HOURS: 4
jobs:
update-docs:
if: github.repository == 'sst/opencode'
runs-on: blacksmith-4vcpu-ubuntu-2404
permissions:
id-token: write
contents: write
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
fetch-depth: 0 # Fetch full history to access commits
- name: Setup Bun
uses: ./.github/actions/setup-bun
- name: Get recent commits
id: commits
run: |
COMMITS=$(git log --since="${{ env.LOOKBACK_HOURS }} hours ago" --pretty=format:"- %h %s" 2>/dev/null || echo "")
if [ -z "$COMMITS" ]; then
echo "No commits in the last ${{ env.LOOKBACK_HOURS }} hours"
echo "has_commits=false" >> $GITHUB_OUTPUT
else
echo "has_commits=true" >> $GITHUB_OUTPUT
{
echo "list<<EOF"
echo "$COMMITS"
echo "EOF"
} >> $GITHUB_OUTPUT
fi
- name: Run opencode
if: steps.commits.outputs.has_commits == 'true'
uses: sst/opencode/github@2c14fc5586fe0b88e5c04732d2e846769cc35671 # latest
env:
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
with:
model: opencode/gpt-5.2
agent: docs
prompt: |
Review the following commits from the last ${{ env.LOOKBACK_HOURS }} hours and identify any new features that may need documentation.
<recent_commits>
${{ steps.commits.outputs.list }}
</recent_commits>
Steps:
1. For each commit that looks like a new feature or significant change:
- Read the changed files to understand what was added
- Check if the feature is already documented in packages/web/src/content/docs/*
2. If you find undocumented features:
- Update the relevant documentation files in packages/web/src/content/docs/*
- Follow the existing documentation style and structure
- Make sure to document the feature clearly with examples where appropriate
3. If all new features are already documented, report that no updates are needed
4. If you are creating a new documentation file be sure to update packages/web/astro.config.mjs too.
Focus on user-facing features and API changes. Skip internal refactors, bug fixes, and test updates unless they affect user-facing behavior.
Don't feel the need to document every little thing. It is perfectly okay to make 0 changes at all.
Try to keep documentation only for large features or changes that already have a good spot to be documented.
+2 -2
View File
@@ -114,7 +114,7 @@ jobs:
- uses: ./.github/actions/setup-bun
with:
bun-version: 1.4.2
bun-version: 1.4.4
- name: Setup git committer
id: committer
@@ -136,7 +136,7 @@ jobs:
id: build
run: ./packages/cli/script/build.ts ${{ (github.ref_name == 'beta' && '--sourcemaps') || '' }}
env:
BUN_COMPILE_RELEASE: bun-v1.4.2
BUN_COMPILE_RELEASE: bun-v1.4.4
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
+40 -49
View File
@@ -1,19 +1,19 @@
---
name: opencode-dev
description: Use when interactively running, debugging, or verifying opencode's own V2 CLI/TUI or server during development in this repo — starting the dev TUI, driving it with termctrl, comparing V2 against the legacy TUI, hitting the V2 server/API directly, reading log files, or attaching Bun's inspector.
description: Use when interactively running, debugging, or verifying opencode's own CLI/TUI or server during development in this repo — starting the dev TUI, driving it with termctrl, hitting the server/API directly, reading log files, or attaching Bun's inspector.
---
# Debugging opencode itself
Workflow for interactively exercising the V2 CLI/TUI and server while developing in this repo. All commands below run from `packages/cli` unless noted otherwise.
Workflow for interactively exercising the CLI/TUI and server while developing in this repo. All commands below run from `packages/cli` unless noted otherwise.
## Server/client model
opencode V2 is a client/server system, not a single monolithic process:
opencode is a client/server system, not a single monolithic process:
- **Server process** runs the Effect HTTP API (`packages/server`) and owns all domain state: sessions, database, plugins, permissions, Location services. It's started by the `serve` command (`packages/cli/src/commands/handlers/serve.ts`).
- **TUI process** is a separate process that runs no application logic itself — it's an HTTP/SSE client of the server via the generated SDK (`createOpencodeClient` / `sdk.client.v2`).
- **Discovery**: CLI processes find the shared server through a JSON registration file at `~/.local/state/opencode/service.json` (or `service-local.json` for the local/dev channel) containing `{id, version, url, pid}`. A separate password file under `~/.config/opencode/service.json` provides HTTP Basic auth. Before reusing a registration, the client calls `GET /health` to confirm the server is alive, authenticated, and version-compatible.
- **TUI process** is a separate process that runs no application logic itself — it's an HTTP/SSE client of the server via `@opencode/client` (`OpenCode.make`).
- **Discovery**: CLI processes find the shared server through a JSON registration file at `~/.local/state/opencode/service.json` (or `service-local.json` for the local/dev channel) containing `{id, version, url, pid, password}`; the password is used for HTTP Basic auth. Before reusing a registration, the client calls `GET /api/info` to confirm the server is alive, is the registered PID, and is version-compatible. `opencode service status` prints the registered URL.
- **Sharing**: because of this registration/health-check dance, many concurrent `opencode`/TUI invocations converge on one shared background daemon rather than each spawning their own. If no compatible healthy daemon is found, a new one is spawned detached (`serve --service`) and registers itself.
- **`bun dev service start|status|stop|restart`** manages this shared background daemon's lifecycle directly — useful when you need to force a fresh server, confirm one is running, or kill a stuck one.
- **Standalone mode** (`--standalone`) opts a single invocation out of the shared daemon: it spawns a private one-off `serve --stdio --port 0` child tied to that invocation's lifetime, with its own random password. Use this to isolate a debugging session from your other running opencode sessions.
@@ -21,8 +21,9 @@ opencode V2 is a client/server system, not a single monolithic process:
## Starting the dev TUI
- This package is the V2 CLI adapter. Run its `dev` script when testing the TUI; do not use the repository-root `bun dev`, which launches the legacy `packages/opencode` CLI.
- Run commands from `packages/cli`. Use `bun dev` for most debugging so the TUI starts with a private V2 server.
- `packages/cli` is the CLI and TUI entrypoint. `bun dev` from `packages/cli` and the repository-root `bun dev` both run `packages/cli/src/index.ts`.
- `bun dev` connects to the shared local-channel background service (`service-local.json`), starting it if needed. Every worktree on the machine shares that service. Add `--standalone` for a private server tied to this one process.
- Use `bun run dev:live` from the repository root to run this worktree's TUI against the installed `opencode` background server and your real sessions.
## Interactive debugging with termctrl
@@ -30,67 +31,49 @@ opencode V2 is a client/server system, not a single monolithic process:
- Use a dedicated session name and do not reuse or kill an unrelated session.
```bash
termctrl start opencode-v2-dev --host opentui --cols 112 --rows 34 -- bun dev
termctrl wait opencode-v2-dev "Ask anything" --timeout 20000
termctrl show opencode-v2-dev
termctrl start opencode-dev --host opentui --cols 112 --rows 34 -- bun dev
termctrl wait opencode-dev "Ask anything" --timeout 20000
termctrl show opencode-dev
```
- Wait for visible text before interacting instead of relying on fixed sleeps. Use the text expected from the screen under test, such as `Ask anything` or `Connect a provider`.
- Drive the running TUI with `termctrl send`. Prefix typed input with `text:` and send control keys separately so the interaction matches real terminal input.
```bash
termctrl send opencode-v2-dev 'text:example prompt' enter
termctrl send opencode-v2-dev ctrl-c
termctrl send opencode-dev 'text:example prompt' enter
termctrl send opencode-dev ctrl-c
```
- Use `termctrl show` after each meaningful interaction and inspect the full visible screen for rendering errors, stale state, error toasts, and unexpected exits.
- Save PNG evidence for every user-visible bug and fix. Do not save text captures; inspect the rendered PNG. Write temporary captures outside the repository unless the artifact is intended to be committed.
```bash
termctrl save opencode-v2-dev --format png --out /tmp/opencode/v2-tui.png
termctrl save opencode-dev --format png --out /tmp/opencode/tui.png
```
- For resize-sensitive changes, resize the viewport, wait for the expected content, and capture the screen again:
```bash
termctrl resize opencode-v2-dev --cols 100 --rows 30
termctrl show opencode-v2-dev
termctrl resize opencode-dev --cols 100 --rows 30
termctrl show opencode-dev
```
- Source changes may require restarting the process. Use `termctrl restart opencode-v2-dev` rather than assuming the running TUI reloaded the change.
- Source changes may require restarting the process. Use `termctrl restart opencode-dev` rather than assuming the running TUI reloaded the change. Restarting the TUI does not restart the shared background service, so run `bun dev service restart` after server-side changes, or use `--standalone`.
- To exercise background-service behavior, use `bun dev service start`, `bun dev service status`, and `bun dev service stop`.
- Always clean up the Terminal Control session when the check is complete:
```bash
termctrl stop opencode-v2-dev
termctrl stop opencode-dev
```
## Comparing V2 against the legacy TUI
Run both versions in separate Terminal Control sessions and save PNG-only captures at equivalent states:
```bash
# From packages/cli: local V2 TUI
termctrl start opencode-v2-dev --host opentui --cols 112 --rows 34 -- bun dev
# Released legacy TUI behavior reference
termctrl start opencode-legacy --host opentui --cols 112 --rows 34 -- bunx opencode-ai@latest
termctrl save opencode-v2-dev --format png --out /tmp/opencode/v2.png
termctrl save opencode-legacy --format png --out /tmp/opencode/legacy.png
```
- Use the same viewport and send equivalent inputs to both sessions before comparing screenshots. The released CLI is a behavioral reference, not a source of V2 API design; keep the local implementation on V2 endpoints.
- Stop both sessions after comparison: `termctrl stop opencode-v2-dev` and `termctrl stop opencode-legacy`.
## Server/API debugging
- Use `bun dev api --help` from `packages/cli` to inspect the API debugging command. It sends one request to the V2 server using the same daemon discovery/auth path as the CLI.
- Use `bun dev api --help` from `packages/cli` to inspect the API debugging command. It sends one request to the server using the same daemon discovery/auth path as the CLI.
- Use `bun dev api` to introspect the server-side data backing the TUI. This is useful when debugging UI bugs: compare what the screen renders with the raw session, message, event, agent, or health data returned by the API to determine whether the bug is in the server state, the client data layer, or the TUI rendering.
- `bun dev api` accepts either an OpenAPI operation ID or a raw HTTP method plus path:
```bash
bun dev api get /health
bun dev api get /api/info
bun dev api get /openapi.json
bun dev api <operationId> --param key=value
```
@@ -99,13 +82,13 @@ bun dev api <operationId> --param key=value
- If no compatible background server is registered, `bun dev api` starts one through the daemon service. Use `bun dev service status`, `bun dev service restart`, and `bun dev service stop` when you need explicit lifecycle control.
- Prefer raw method/path calls for quick server debugging and operation IDs when exercising documented OpenAPI routes with path or query parameters.
## Auditing installed `opencode2` sessions
## Auditing installed `opencode` sessions
Installed next-channel sessions normally use `~/.local/share/opencode/opencode-next.db` and `~/.local/share/opencode/log/opencode.log`; `OPENCODE_DB` can override the database. Before calling `opencode2 api`, inspect `~/.local/state/opencode/service.json` because the command may start a daemon when none is healthy.
Installed (released) sessions use `~/.local/share/opencode/opencode.db` and `~/.local/share/opencode/log/opencode.log`. A local/dev checkout uses `opencode-local.db` and `opencode-local.log` instead, and `OPENCODE_DB` overrides the database. Run `opencode service status` before `opencode api`, because `opencode api` starts a server when none is healthy.
For a supplied `ses_...` ID, compare three sources:
- `opencode2 api get /api/session/active` and the Session/message endpoints for live server state.
- `opencode api get /api/session/active` and the Session/message endpoints for live server state.
- The database's ordered `event` rows for durable history.
- `packages/tui/src/context/data.tsx` and the relevant route for client projection and rendering.
@@ -141,16 +124,24 @@ grep 'role=server' ~/.local/share/opencode/log/opencode-local.log
## Heap snapshots
The CLI installs a `SIGUSR1` listener on non-Windows processes in `packages/cli/src/heap.ts`. Use it to capture the installed `opencode2` server without restarting it or attaching an inspector.
On every platform, including Windows, capture the running background server without restarting it or attaching an inspector:
```bash
opencode debug heap-dump
```
It discovers the already-running service (never starts or replaces one), calls `POST /api/debug/heap-dump`, waits until the file is complete, and prints its server-local path. Pass `--server <url>` (with `OPENCODE_PASSWORD`) for a server started with `serve`. A 404 means the running server predates the endpoint.
The Unix `SIGUSR1` listener in `packages/cli/src/heap.ts` shares the same writer (`packages/util/src/heap-snapshot.ts`) and is still useful for a process that is not an HTTP server, such as a TUI client:
1. Find the processes and inspect their roles and memory:
```bash
pgrep -a -f 'opencode2\.exe|opencode2'
pgrep -af opencode
ps -o pid,ppid,rss,vsz,lstart,etime,cmd -p <pid>,<pid>
```
2. Signal the process whose heap needs investigation. For shared-service memory, target the `opencode2.exe serve --service` child, not the short wrapper/TUI process:
2. Signal the process whose heap needs investigation. For shared-service memory, target the `opencode serve --service` process, not a TUI process:
```bash
kill -USR1 <server-pid>
@@ -189,13 +180,13 @@ Heap serialization itself can temporarily increase RSS and allocator high-water
The CLI installs a `SIGPROF` listener on non-Windows processes in `packages/cli/src/cpu-profile.ts`. One signal starts a ten-second CPU profile and stops it automatically; additional signals are ignored while a profile is active. There is no CPU profile CLI flag or environment variable.
1. Get the PID from the health endpoint. For shared-service performance, target the server PID returned here rather than the short wrapper or TUI process:
1. Get the PID from the info endpoint. For shared-service performance, target the server PID returned here rather than a TUI process:
```bash
opencode2 api get /api/health
opencode api get /api/info
```
Use `bun dev api get /api/health` instead when targeting the local/dev channel.
Use `bun dev api get /api/info` instead when targeting the local/dev channel.
2. Start the capture:
@@ -214,15 +205,15 @@ Use `opencode-local.log` for a local/dev process. Load the completed `.cpuprofil
## Debugger
- To debug the V2 CLI or TUI with Bun's inspector, launch the CLI entrypoint through Terminal Control with an inspector URL, then attach a debugger to that URL:
- To debug the CLI or TUI with Bun's inspector, launch the CLI entrypoint through Terminal Control with an inspector URL, then attach a debugger to that URL:
```bash
termctrl start opencode-v2-debug --host opentui --cols 112 --rows 34 -- \
termctrl start opencode-debug --host opentui --cols 112 --rows 34 -- \
bun run --inspect=ws://localhost:6499/ src/index.ts
```
- Use `--inspect-wait` or `--inspect-brk` when execution must pause until a debugger attaches.
- Use `termctrl logs opencode-v2-debug` for inspector output or startup failures emitted before the TUI renderer starts. Use `termctrl show` for the visible full-screen TUI.
- Use `termctrl logs opencode-debug` for inspector output or startup failures emitted before the TUI renderer starts. Use `termctrl show` for the visible full-screen TUI.
## Verification
+2
View File
@@ -174,6 +174,8 @@ const table = sqliteTable("session", {
- Run `bun run check` from the repository root as the canonical full lint and type-check verification.
- During focused iteration, run `bun typecheck` from the affected package directory (for example, `packages/core`). Never run `tsc` directly.
- Local `typecheck` scripts use `bun check`. CI and package publishing run `typecheck:tsc`, which uses the official TypeScript compiler (`@typescript/native`). When the two disagree, `tsc` is the source of truth; reproduce with `bun run typecheck:tsc` from the package directory.
- `bun check` aims to match TypeScript 7.1, not the `7.0.2` that `process.versions.typescript` reports (oven-sh/bun#46536). When `bun check` and `tsc` from the pinned `@typescript/native` report different errors, file a minimal, dependency-free repro at https://github.com/oven-sh/bun/issues, with the output of both. `bun check` writes no declaration files, so declaration-emit errors such as TS5088 or TS2883 are expected to appear only in `tsc`; do not report those.
## Session Core
+56
View File
@@ -2,6 +2,62 @@
Release notes for OpenCode V2, newest first.
## v2.1.3 — 2026-10-22
### Highlights
- **Bun 1.4.4 Security Fixes**: OpenCode now runs on Bun 1.4.4, which includes security fixes for Brotli, TLS, HTTP/3, WebSocket, and more, along with updated root certificates. ([#58087](https://github.com/anomalyco/opencode/pull/58087))
- **Faster Code Display**: Code blocks, file views, and review diffs in Desktop now use Pierre Highlights, reducing highlighting time and memory use for large files and diffs. ([#57937](https://github.com/anomalyco/opencode/pull/57937))
- **Discover and Start Voice Models**: SDK clients can call `client.voice.models()` to find available experimental voice models and supported transports. Connected OpenCode Console workspaces can also host GPT-Live sessions through `client.voice.session()`. ([#57194](https://github.com/anomalyco/opencode/pull/57194), [#57735](https://github.com/anomalyco/opencode/pull/57735))
### Core
#### Improvements
- Upgraded the bundled Bun runtime to 1.4.4, which includes [security fixes](https://bun.com/blog/bun-v1.4.4#security) for Brotli, TLS, HTTP/1.1, HTTP/2, HTTP/3, WebSocket, and `fetch`, and updates root certificates to NSS 3.131.1. ([#58087](https://github.com/anomalyco/opencode/pull/58087))
- Generated session titles now use the lowest suitable model variant and more focused naming instructions. ([#51939](https://github.com/anomalyco/opencode/pull/51939), [#57648](https://github.com/anomalyco/opencode/pull/57648))
- Windows managed services now use port `28894`, avoiding ranges reserved by Windows and WSL mirrored networking. ([#57428](https://github.com/anomalyco/opencode/pull/57428))
#### Bug fixes
- Custom provider `baseURL` settings now override catalog model endpoints as expected. Thanks [@Tarquinen](https://github.com/Tarquinen) and [@bercedev](https://github.com/bercedev). ([#57810](https://github.com/anomalyco/opencode/pull/57810))
- Compaction summaries can use the same model output limit as normal responses, preventing incomplete summaries. ([#57564](https://github.com/anomalyco/opencode/pull/57564))
- Legacy `apply_patch` permissions now migrate to the `edit` permission. ([#57900](https://github.com/anomalyco/opencode/pull/57900))
- V1 sessions with relative working directories now migrate using their project worktree. Thanks [@MohammadAlMasalmeh](https://github.com/MohammadAlMasalmeh). ([#57618](https://github.com/anomalyco/opencode/pull/57618))
- Unsupported legacy agent colors no longer prevent agents from loading. Thanks [@4sDriven](https://github.com/4sDriven). ([#57910](https://github.com/anomalyco/opencode/pull/57910))
### TUI
#### Bug fixes
- The TUI no longer crashes when file watchers are unavailable or system watch limits are exhausted. Thanks [@ANSHSINGH050404](https://github.com/ANSHSINGH050404). ([#51536](https://github.com/anomalyco/opencode/pull/51536))
### Desktop
#### Improvements
- Code blocks, streaming output, file views, and review diffs now use Pierre Highlights for faster highlighting and lower memory use on large inputs. ([#57937](https://github.com/anomalyco/opencode/pull/57937))
#### Bug fixes
- Renaming a session tab now pastes plain text instead of formatted content. ([#58036](https://github.com/anomalyco/opencode/pull/58036))
- Dragging the session scrollbar no longer forces the timeline back to its end. ([#57831](https://github.com/anomalyco/opencode/pull/57831))
- RPM packages no longer conflict with build-ID links installed by other Electron applications. ([#58093](https://github.com/anomalyco/opencode/pull/58093))
### SDK
#### Improvements
- Added `client.voice.models()` to list experimental voice models, availability, and supported WebRTC or WebSocket transports. ([#57194](https://github.com/anomalyco/opencode/pull/57194))
- Voice sessions can now use GPT-Live hosted by a connected OpenCode Console workspace. Hosted sessions expose an ID and support instruction updates through `client.voice.instructions()`. ([#57735](https://github.com/anomalyco/opencode/pull/57735))
### Extensions
#### Bug fixes
- MCP results now keep supported media inline, decode textual resources, and save unsupported binary resources to files instead of creating invalid model attachments. ([#57640](https://github.com/anomalyco/opencode/pull/57640))
- Updates to MCP instructions, skills, and project references now send only changed entries instead of repeating the full list. ([#57626](https://github.com/anomalyco/opencode/pull/57626))
## v2.1.2 — 2026-10-21
### Highlights
+181 -828
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2,7 +2,7 @@
exact = true
# Only install newly resolved package versions published at least 3 days ago.
minimumReleaseAge = 259200
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode-ai/pty", "@opencode-ai/pty-darwin-arm64", "@opencode-ai/pty-darwin-x64", "@opencode-ai/pty-linux-arm64-gnu", "@opencode-ai/pty-linux-arm64-musl", "@opencode-ai/pty-linux-x64-gnu", "@opencode-ai/pty-linux-x64-musl", "@opencode-ai/pty-win32-arm64", "@opencode-ai/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele"]
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode-ai/pty", "@opencode-ai/pty-darwin-arm64", "@opencode-ai/pty-darwin-x64", "@opencode-ai/pty-linux-arm64-gnu", "@opencode-ai/pty-linux-arm64-musl", "@opencode-ai/pty-linux-x64-gnu", "@opencode-ai/pty-linux-x64-musl", "@opencode-ai/pty-win32-arm64", "@opencode-ai/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta"]
[test]
root = "./do-not-run-tests-from-root"
-7
View File
@@ -13,13 +13,6 @@ export const api = new sst.cloudflare.Worker("Api", {
transform: {
worker: (args) => {
args.logpush = true
if ($app.stage === "vimtor" || $app.stage === "adam") return
// Deleting the class erases every SyncServer Durable Object and its stored share data.
args.migrations = {
oldTag: $app.stage === "production" || $app.stage === "thdxr" ? undefined : "v1",
newTag: "v2",
deletedClasses: ["SyncServer"],
}
},
},
})
+3 -3
View File
@@ -1,7 +1,7 @@
{
"nodeModules": {
"x86_64-linux": "sha256-y9Zr4/sIxFh5i/6AYl/1N9PzdFBfPnyXEyjqW/idPes=",
"aarch64-linux": "sha256-4JBTGcwS4GsfSSvnKvcBR/6aCBghTwUSRz+E8lsQpO4=",
"aarch64-darwin": "sha256-hn62idpf73/uW+nCLLO5hhn/HTwwdV2NmmkqNTqo+2g="
"x86_64-linux": "sha256-7vFZ0VdbzW+MFcGUy8PKtEqKivCA0t4yyvPYcltioqU=",
"aarch64-linux": "sha256-p4D4/H8RTVztbEEqXFgwD6oj6Fw8mHsFWNRgIWzNF+s=",
"aarch64-darwin": "sha256-2Ngf2q+h6xH87HVbFo6gIxFgJ/4QU8dEZ1pe4WVJUSA="
}
}
+7 -6
View File
@@ -2,10 +2,10 @@
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode",
"description": "AI-powered development tool",
"version": "2.1.2",
"version": "2.1.3",
"private": true,
"type": "module",
"packageManager": "bun@1.4.2",
"packageManager": "bun@1.4.4",
"scripts": {
"dev": "bun run --cwd packages/cli src/index.ts",
"dev:live": "sh -c 'OPENCODE_TUI_CHANNEL=dev OPENCODE_PASSWORD=\"$(opencode service get password)\" exec bun run dev \"$@\" --server \"$(opencode service status)\"' --",
@@ -24,6 +24,7 @@
"test:lint-rules": "ast-grep test -c script/ast-grep/sgconfig.yml",
"test:effect-simplification-rules": "ast-grep test -c script/ast-grep/effect-simplifications/sgconfig.yml",
"typecheck": "bun turbo typecheck --concurrency=3",
"typecheck:tsc": "bun turbo typecheck:tsc --concurrency=3",
"check": "bun run lint && bun run typecheck",
"typecheck:profile": "bun script/profile-typecheck.ts",
"typecheck:profile:packages": "bun script/profile-typecheck-packages.ts",
@@ -48,7 +49,7 @@
"@effect/platform-node-shared": "4.0.1",
"@effect/sql-sqlite-bun": "4.0.1",
"@npmcli/arborist": "9.4.0",
"@types/bun": "1.4.0",
"@types/bun": "1.4.3",
"@types/cross-spawn": "6.0.6",
"@octokit/rest": "22.0.0",
"@hono/standard-validator": "0.2.0",
@@ -92,7 +93,7 @@
"@playwright/test": "1.60.0",
"semver": "7.7.4",
"typescript": "npm:@typescript/typescript6@6.0.2",
"@typescript/native": "npm:typescript@7.0.2",
"@typescript/native": "npm:typescript@7.1.0-beta",
"zod": "4.1.8",
"remeda": "2.26.0",
"sst": "4.13.1",
@@ -161,7 +162,7 @@
"@effect/platform-node-shared": "catalog:",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"bun-types": "1.4.2",
"bun-types": "1.4.4",
"effect": "catalog:",
"open": "11.0.4",
"solid-js": "catalog:"
@@ -180,7 +181,7 @@
"@tanstack/virtual-core@3.17.8": "patches/@tanstack%2Fvirtual-core@3.17.8.patch",
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
"@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch",
"@modelcontextprotocol/client@2.3.1": "patches/@modelcontextprotocol%2Fclient@2.3.1.patch",
"@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch",
"app-builder-lib@26.15.7": "patches/app-builder-lib@26.15.7.patch",
"electron-updater@6.8.9": "patches/electron-updater@6.8.9.patch",
+3 -2
View File
@@ -1,13 +1,14 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.1.2",
"version": "2.1.3",
"name": "@opencode/ai",
"type": "module",
"license": "MIT",
"scripts": {
"setup:recording-env": "bun run script/setup-recording-env.ts",
"test": "bun test --timeout 30000 --only-failures",
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.types.json",
"typecheck": "bun check --no-script && bun check --no-script -p tsconfig.types.json",
"typecheck:tsc": "tsc --noEmit && tsc --noEmit -p tsconfig.types.json",
"build": "tsc -p tsconfig.build.json"
},
"files": [
@@ -53,7 +53,6 @@ const SSE_EVENTS = new Set([
])
export const framing = Framing.sseEvents(SSE_EVENTS)
export type ThinkingBlockBinding = typeof AnthropicThinkingBlockBinding.Type
export type ThinkingInput = typeof Thinking.Encoded
/** Caller-facing provider options; unknown keys are accepted and ignored. `Options.Type` is the wire-ready form. */
export type OptionsInput = ProviderOptions & typeof Options.Encoded
@@ -818,7 +817,7 @@ const requireThinkingSignature = (request: LLMRequest) => {
// Opus 4.8 and every Claude 5 model accept mid-conversation system messages; later versions inherit support.
const supportsNativeSystemUpdates = (request: LLMRequest) => {
const version = claudeVersion(String(request.model.id))
const version = claudeVersion(request.model.id)
if (version === undefined) return false
if (version.family === "opus" && version.major === 4) return version.minor >= 8
return version.major >= 5
@@ -871,7 +870,7 @@ const appendToUserTurn = (messages: AnthropicMessage[], block: AnthropicUserBloc
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoints: Cache.Breakpoints) {
const messages: AnthropicMessage[] = []
const providerMetadataKey = request.model.route.providerMetadataKey ?? String(request.model.provider)
const providerMetadataKey = request.model.route.providerMetadataKey ?? request.model.provider
// Text updates stay where they are unless a user turn follows them; then they move after the latest
// user turn, the nearest spot where Anthropic accepts a native system message.
const holdUpdates = supportsNativeSystemUpdates(request)
@@ -1602,7 +1601,7 @@ export const protocol = Protocol.make({
initial: (request) => ({
provider: request.model.provider,
compactions: {},
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
tools: ToolStream.empty<number>(),
reasoningSignatures: {},
lifecycle: Lifecycle.initial(),
@@ -331,7 +331,7 @@ const lowerMessages = Effect.fnUntraced(function* (
const documentNames = new Set<string>()
// Mistral can reject replay IDs even when they satisfy Converse's broader ID syntax.
const normalizeID = request.model.id.includes("mistral.") ? MistralToolID.normalizer(request) : (id: string) => id
const providerMetadataKey = request.model.route.providerMetadataKey ?? String(request.model.provider)
const providerMetadataKey = request.model.route.providerMetadataKey ?? request.model.provider
const hoistImages = !keepToolImagesInline(request.model.id)
// Bedrock expects parallel tool results before any images hoisted beside them.
const pendingImages: BedrockMedia.ImageBlock[] = []
@@ -862,7 +862,7 @@ export const protocol = Protocol.make({
stream: {
event: BedrockEventStream.Frame.pipe(Schema.decodeTo(BedrockEvent)),
initial: (request) => ({
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
tools: ToolStream.empty<number>(),
finishReason: undefined,
usage: undefined,
@@ -891,6 +891,4 @@ export const route = Route.make({
framing,
})
export const sigV4Auth = BedrockAuth.sigV4
export * as BedrockConverse from "./bedrock-converse.js"
+2 -2
View File
@@ -321,7 +321,7 @@ const lowerToolCall = (part: ToolCallPart, omitIds: boolean, metadataKey: string
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) {
const contents: GeminiContent[] = []
const metadataKey = request.model.route.providerMetadataKey ?? String(request.model.provider)
const metadataKey = request.model.route.providerMetadataKey ?? request.model.provider
const omitCallIds = omitsFunctionCallIds(request.model.id)
const legacyToolMedia = routesLegacyToolMedia(request.model.id)
let pendingMedia: GeminiInlineDataPart[] | undefined
@@ -960,7 +960,7 @@ export const protocol = Protocol.make({
event: Schema.Union([Schema.instanceOf(NextRequest), GeminiEvent]),
initial: (request): ParserState => ({
route: `${request.model.provider}/${request.model.route.id}`,
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
hasToolCalls: false,
lifecycle: Lifecycle.initial(),
nextReasoningId: 0,
@@ -236,7 +236,7 @@ const signature = (metadata: ProviderMetadata | undefined, key: string) => {
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) {
const steps: InputStep[] = []
const key = request.model.route.providerMetadataKey ?? String(request.model.provider)
const key = request.model.route.providerMetadataKey ?? request.model.provider
for (const message of request.messages) {
if (message.role === "system") {
const part = yield* ProviderShared.wrappedSystemUpdate("Google Interactions", message)
@@ -562,7 +562,7 @@ export const protocol = Protocol.make({
event: Protocol.jsonEvent(Event),
initial: (request): ParserState => ({
route: `${request.model.provider}/${ADAPTER}`,
metadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
lifecycle: Lifecycle.initial(),
steps: {},
tools: ToolStream.empty<number>(),
+8 -7
View File
@@ -774,7 +774,7 @@ export const lowerConversation = Effect.fnUntraced(function* (
export const lowerGeneration = (request: LLMRequest, options = OpenResponsesOptions.resolve(request)) => {
const generation = request.generation
const cacheKey = ProviderShared.promptCacheKey(request)
const parallelToolCalls = resolveParallelToolCalls(request)
const parallelToolCalls = resolveParallelToolCalls(request, options)
return {
stream: true as const,
max_output_tokens: generation?.maxTokens,
@@ -802,15 +802,15 @@ export const lowerGeneration = (request: LLMRequest, options = OpenResponsesOpti
}
}
export const resolveParallelToolCalls = (request: LLMRequest) => {
const configured = OpenResponsesOptions.resolve(request).parallelToolCalls
export const resolveParallelToolCalls = (request: LLMRequest, options = OpenResponsesOptions.resolve(request)) => {
const configured = options.parallelToolCalls
if (configured !== undefined) return configured
const disabled = request.toolChoice?.disableParallelToolUse
return disabled === undefined ? undefined : !disabled
}
export const allowedToolChoice = (request: LLMRequest) => {
const allowed = OpenResponsesOptions.resolve(request).allowedTools
export const allowedToolChoice = (request: LLMRequest, options = OpenResponsesOptions.resolve(request)) => {
const allowed = options.allowedTools
if (!allowed) return undefined
return {
type: "allowed_tools" as const,
@@ -824,12 +824,13 @@ export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAd
adapter: ProviderAdapter,
) {
const projected = ProviderShared.flattenToolRequest(request)
const options = OpenResponsesOptions.resolve(request)
return {
...(yield* lowerConversation(projected.request, adapter)),
...lowerGeneration(request),
...lowerGeneration(request, options),
tools: projected.tools.length === 0 ? undefined : yield* lowerTools(projected.tools, adapter),
tool_choice:
allowedToolChoice(request) ??
allowedToolChoice(request, options) ??
(request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice) : undefined),
}
})
+3 -3
View File
@@ -577,7 +577,7 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, options:
const mistral = ["mistral", "devstral", "codestral", "pixtral", "mixtral"].some((family) => modelID.includes(family))
const lowering = {
...options,
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
toolCallID: (id: string) => {
if (mistral)
return id
@@ -783,7 +783,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
)
const generation = request.generation
const flattened = ProviderShared.flattenToolRequest(request)
const provider = String(request.model.provider)
const provider = request.model.provider
const baseURL = request.model.route.endpoint.baseURL
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
const maxTokensField = request.model.compatibility?.maxTokensField ?? detectedMaxTokensField
@@ -1252,7 +1252,7 @@ export const protocol = Protocol.make({
stream: {
event: OpenAIChatStreamEvent,
initial: (request) => ({
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
tools: ToolStream.empty<number>(),
pendingTools: {},
toolCallEvents: [],
@@ -1,11 +1,9 @@
import { Route, type RouteRoutedLanguageModelInput } from "../route/client.js"
import { Route } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import * as OpenAIChat from "./openai-chat.js"
const ADAPTER = "openai-compatible-chat"
export type OpenAICompatibleChatLanguageModelInput = RouteRoutedLanguageModelInput
/**
* Route for non-OpenAI providers that expose an OpenAI Chat-compatible
* `/chat/completions` endpoint. Reuses `OpenAIChat.protocol` end-to-end and
@@ -1,11 +1,9 @@
import { Route, type RouteRoutedLanguageModelInput } from "../route/client.js"
import { Route } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import { OpenResponses } from "./open-responses.js"
const ADAPTER = "openai-compatible-responses"
export type OpenAICompatibleResponsesLanguageModelInput = RouteRoutedLanguageModelInput
/**
* Deployment adapter for providers that expose an Open Responses-compatible
* `/responses` endpoint. Provider helpers configure identity, endpoint, and
@@ -210,7 +210,7 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
tool_choice:
request.tools.length === 0
? undefined
: (OpenResponses.allowedToolChoice(request) ??
: (OpenResponses.allowedToolChoice(request, options) ??
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined)),
}
})
@@ -1,4 +1,4 @@
import { Effect, Schema, Stream } from "effect"
import { Effect, Schema, SchemaGetter, Stream } from "effect"
import { classifyProviderFailure } from "../provider-error.js"
import { Framing } from "../route/framing.js"
import { MediaProtocol } from "../route/media-protocol.js"
@@ -79,8 +79,16 @@ const transcriptFields = {
usage: Schema.optional(Usage),
}
/** OpenAI may add stream event types; frames outside `EVENT_TYPES` are ignored. */
const EventType = Schema.Struct({ type: Schema.String })
const EVENT_TYPES = new Set(["transcript.text.delta", "transcript.text.segment", "transcript.text.done", "error"])
/** OpenAI may add stream event types; frames outside `EVENT_TYPES` are ignored, while a malformed known type still fails decoding. */
const UnknownEvent = Schema.Struct({
type: Schema.String.check(Schema.makeFilter((type) => !EVENT_TYPES.has(type))),
}).pipe(
Schema.decodeTo(Schema.Struct({ type: Schema.Literal("unknown"), rawType: Schema.String }), {
decode: SchemaGetter.transform((event) => ({ type: "unknown" as const, rawType: event.type })),
encode: SchemaGetter.forbidden(() => "Unknown OpenAI Transcription stream events are decode-only"),
}),
)
const Event = Schema.Union([
Schema.Struct({ type: Schema.Literal("transcript.text.delta"), delta: Schema.String }),
Schema.Struct({ type: Schema.Literal("transcript.text.segment"), ...Segment.fields }),
@@ -90,12 +98,11 @@ const Event = Schema.Union([
message: Schema.optional(Schema.String),
error: Schema.optional(Schema.Struct({ message: Schema.optional(Schema.String) })),
}),
UnknownEvent,
])
const EVENT_TYPES = new Set(["transcript.text.delta", "transcript.text.segment", "transcript.text.done", "error"])
const Transcript = Schema.Struct(transcriptFields)
type Transcript = Schema.Schema.Type<typeof Transcript>
const decodeEventType = route.decodeFrame(EventType)
const decodeEvent = route.decodeFrame(Event)
const decodeTranscript = route.decodeFrame(Transcript)
@@ -211,8 +218,8 @@ const segment = (value: Schema.Schema.Type<typeof Segment>): TranscriptionSegmen
})
const onEvent = Effect.fnUntraced(function* (state: State, frame: string) {
if (!EVENT_TYPES.has((yield* decodeEventType(frame)).type)) return [state, []] as const
const event = yield* decodeEvent(frame)
if (event.type === "unknown") return [state, []] as const
if (event.type === "error")
return yield* new AIError({
reason: classifyProviderFailure({
@@ -60,5 +60,3 @@ export const ALL = ATOM | COLLECTION
* The default is to allow all types to be partially parsed, which in most cases is the best option.
*/
export const Allow = { STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, _INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL }
export default Allow
+5 -3
View File
@@ -17,7 +17,9 @@ import { isRecord } from "./utils/record.js"
const patterns = [
/prompt is too long/i,
/input is too long for requested model/i,
/input is too long for (?:the )?(?:requested|selected) model/i,
// OpenCode Go
/too large for the model'?s configured input limit/i,
// Cloudflare Workers AI reports this as HTTP 413.
/exceeded this model context window limit/i,
/exceeds the context window/i,
@@ -44,8 +46,8 @@ const patterns = [
/context[_ ]length[_ ]exceeded/i,
/context length is only \d+ tokens/i,
/input length.*exceeds.*context length/i,
// Z.ai code 1261 arrives as `Prompt too long` or `Prompt 超长`.
/prompt (?:too long|超长)/i,
// Z.ai code 1261 arrives as `Prompt too long`, `Prompt exceeds max length` or `Prompt 超长`.
/prompt (?:too long|exceeds max length|超长)/i,
/too large for model with \d+ maximum context length/i,
/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,
/model_context_window_exceeded/i,
@@ -120,8 +120,7 @@ export const configure = (input: LanguageModelOptions) => {
const chat = route.with(rest)
return {
id,
model: (input: string | ModelID) => {
const value = String(input)
model: (value: string | ModelID) => {
if (value.startsWith("openai/"))
return responses.model<OpenAIProviderOptionsInput>({ id: native ? value.slice("openai/".length) : value })
if (value.startsWith("anthropic/"))
+2 -2
View File
@@ -60,7 +60,7 @@ const route = Route.make({
providerMetadataKey: "vertex",
protocol,
endpoint: Endpoint.path(({ request }) => {
const model = String(request.model.id)
const model = request.model.id
return `/${model.startsWith("endpoints/") ? model : `models/${model}`}:streamGenerateContent?alt=sse`
}),
auth: Auth.none,
@@ -84,7 +84,7 @@ const configuredRoute = (input: Config, modelID: string | ModelID) => {
...rest
} = input
const apiKey = GoogleVertexShared.apiKey(input)
const endpointModel = String(modelID).startsWith("endpoints/")
const endpointModel = modelID.startsWith("endpoints/")
if (apiKey !== undefined && endpointModel)
throw new ProviderConfigurationError({
provider: id,
@@ -2,5 +2,3 @@ import type { Options } from "../protocols/utils/open-responses-options.js"
export type OpenResponsesOptionsInput = Options & { readonly [key: string]: unknown }
export type OpenResponsesProviderOptionsInput = OpenResponsesOptionsInput
export * as OpenResponsesProviderOptions from "./open-responses-options.js"
@@ -34,8 +34,7 @@ export const configure = (input: GenericModelOptions) => {
})
return {
id: ProviderID.make(provider),
model: (modelID: string | ModelID) =>
route.model<OpenAIProviderOptionsInput>({ id: modelID, provider: ProviderID.make(provider) }),
model: (modelID: string | ModelID) => route.model<OpenAIProviderOptionsInput>({ id: modelID }),
configure,
}
}
@@ -62,5 +62,3 @@ export const withOpenAIOptions = <Options extends { readonly providerOptions?: P
providerOptions: mergeProviderOptions(openAIDefaultOptions(modelID), options.providerOptions),
}
}
export * as OpenAIProviderOptions from "./openai-options.js"
-12
View File
@@ -22,18 +22,6 @@ export type ProviderAuthOption<Mode extends ApiKeyMode> =
| AuthOverride
| (Mode extends "optional" ? OptionalApiKeyAuth : RequiredApiKeyAuth)
export type LanguageModelOptions<Base, Mode extends ApiKeyMode> = Omit<Base, "apiKey" | "auth"> &
ProviderAuthOption<Mode>
export type LanguageModelArgs<Base, Mode extends ApiKeyMode> = Mode extends "optional"
? readonly [options?: LanguageModelOptions<Base, Mode>]
: readonly [options: LanguageModelOptions<Base, Mode>]
export type LanguageModelFactory<Base, Mode extends ApiKeyMode, LanguageModel> = (
id: string,
...args: LanguageModelArgs<Base, Mode>
) => LanguageModel
/**
* Require at least one of the keys in `T`. Use for option shapes where any
* subset of fields is acceptable but at least one must be present (e.g. Azure
-5
View File
@@ -40,9 +40,6 @@ export interface Definition {
readonly pipe: <A>(f: (self: Definition) => A) => A
}
export const isAuth = (input: unknown): input is Definition =>
typeof input === "object" && input !== null && "apply" in input && typeof input.apply === "function"
const credential = (load: Effect.Effect<Redacted.Redacted, CredentialError>): Credential => {
const self: Credential = {
load,
@@ -124,8 +121,6 @@ export function bearer(source: Secret | Credential) {
return credentialInput(source).bearer()
}
export const apiKey = bearer
export function header(name: string): (source: Secret | Credential) => Definition
export function header(name: string, source: Secret | Credential): Definition
export function header(name: string, source?: Secret | Credential) {
+3 -8
View File
@@ -94,8 +94,6 @@ export type AnyRoute<Compact extends CompactionOperations | undefined = Compacti
Compact
>
export type HttpOptionsInput = HttpOptions.Input
export type RouteLanguageModelInput = Omit<LanguageModel.Input, "provider" | "route">
export type RouteRoutedLanguageModelInput = Omit<LanguageModel.Input, "route">
@@ -150,7 +148,7 @@ const mergeRouteDefaults = (base: RouteDefaults | undefined, patch: RouteDefault
...base,
...patch,
headers,
generation: mergeGenerationOptions(generationOptions(base?.generation), generationOptions(patch.generation)),
generation: mergeGenerationOptions(base?.generation, patch.generation),
providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions),
http: mergeHttpOptions(
base?.http,
@@ -168,9 +166,6 @@ const mergeHeaders = (...items: ReadonlyArray<Record<string, string> | undefined
return Object.fromEntries(entries)
}
export const generationOptions = (input: GenerationOptions.Input | undefined) =>
input === undefined ? undefined : GenerationOptions.make(input)
export interface Interface {
readonly compact: CompactMethod
readonly stream: StreamMethod
@@ -396,8 +391,8 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
provider: provider ?? routeInput.provider,
providerMetadataKey:
providerMetadataKey ??
(provider !== undefined && String(provider) !== String(routeInput.provider)
? String(provider)
(provider !== undefined && provider !== routeInput.provider
? provider
: routeInput.providerMetadataKey),
auth: auth ?? routeInput.auth,
endpoint: endpoint ? Endpoint.merge(routeInput.endpoint, endpoint) : routeInput.endpoint,
+1 -1
View File
@@ -26,7 +26,7 @@ export const Service = RequestExecutorService
export type Service = RequestExecutorService
export const headerDetails = (headers: Headers.Headers) =>
Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, String(value)]))
Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, value]))
export const responseHttp = (response: HttpClientResponse.HttpClientResponse) =>
new HttpContext({
+3 -3
View File
@@ -1,6 +1,6 @@
import { Config } from "effect"
import { Auth } from "../src/route.js"
import type { LanguageModelFactory } from "../src/route/auth-options.js"
import type { ProviderAuthOption } from "../src/route/auth-options.js"
import * as OpenAIChat from "../src/protocols/openai-chat.js"
import * as AmazonBedrock from "../src/providers/amazon-bedrock.js"
import * as Anthropic from "../src/providers/anthropic.js"
@@ -27,8 +27,8 @@ type LanguageModel = {
}
declare const auth: Auth.Definition
declare const optionalAuthModel: LanguageModelFactory<BaseOptions, "optional", LanguageModel>
declare const requiredAuthModel: LanguageModelFactory<BaseOptions, "required", LanguageModel>
declare const optionalAuthModel: (id: string, options?: BaseOptions & ProviderAuthOption<"optional">) => LanguageModel
declare const requiredAuthModel: (id: string, options: BaseOptions & ProviderAuthOption<"required">) => LanguageModel
const configApiKey = Config.Redacted("OPENAI_API_KEY")
OpenAIChat.route.model({ id: "gpt-4.1-mini" })
+3
View File
@@ -17,6 +17,9 @@ describe("provider error classification", () => {
"Too many tokens",
"Input validation error: `inputs` tokens + `max_new_tokens` must be <= 131073. Given: 600035 `inputs` tokens and 16 `max_new_tokens`",
"Token limit exceeded",
"Prompt exceeds max length",
"The input is too long for the selected model.",
"This text request is too large for the model's configured input limit.",
]
expect(messages.every(isContextOverflow)).toBe(true)
@@ -399,7 +399,7 @@ test.describe("rename", () => {
await expect(tab).toBeFocused()
await tab.press("Shift+F10")
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
const input = page.locator('[data-slot="tab-title"][contenteditable="true"]')
const input = page.locator('[data-slot="tab-title"][contenteditable="plaintext-only"]')
await expect(input).toBeFocused()
await input.fill("Renamed from tab")
await input.press("Enter")
@@ -423,7 +423,7 @@ test.describe("rename", () => {
await expect(heading(page, fixture.expected.sourceTitle)).toBeVisible()
await tabs(page).filter({ hasText: fixture.expected.targetTitle }).click({ button: "right" })
await page.getByRole("menuitem", { name: "Rename", exact: true }).click()
const input = page.locator('[data-slot="tab-title"][contenteditable="true"]')
const input = page.locator('[data-slot="tab-title"][contenteditable="plaintext-only"]')
await expect(input).toBeFocused()
await input.fill("Inactive tab renamed")
await input.press("Tab")
+1 -1
View File
@@ -229,7 +229,7 @@ for (const tabLayout of ["horizontal", "vertical"] as const) {
await mockWorkspace(page, { name: "Tabs", sessions: [a, b], seed: { settings: { appearance: { tabLayout } } } })
await page.goto(sessionHref(a.id))
const title = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(a.id)}"]) [data-slot="tab-title"]`)
const editor = page.locator('[data-slot="tab-title"][contenteditable="true"]')
const editor = page.locator('[data-slot="tab-title"][contenteditable="plaintext-only"]')
await expect(title).toHaveText(a.title)
const save = await holdRoute(page, (url) => url.pathname === `/api/session/${a.id}`, { method: "PATCH" })
+6 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/app",
"version": "2.1.2",
"version": "2.1.3",
"description": "",
"type": "module",
"exports": {
@@ -12,7 +12,8 @@
"./index.css": "./src/index.css"
},
"scripts": {
"typecheck": "tsc -b",
"typecheck": "bun check --no-script -b",
"typecheck:tsc": "tsc -b",
"typecheck:e2e": "tsc -p e2e/tsconfig.json",
"start": "vite",
"dev": "vite",
@@ -20,9 +21,9 @@
"generate:css-orb": "bun src/session/agent-glyph/generate-css-agent-orb.ts",
"serve": "vite preview",
"test": "bun run test:unit && bun run test:browser",
"test:unit": "bun test --conditions=solid --only-failures --isolate --preload ./happydom.ts ./src",
"test:browser": "bun test --conditions=browser --isolate --preload ./happydom.ts ./test-browser",
"test:unit:watch": "bun test --conditions=solid --watch --isolate --preload ./happydom.ts ./src",
"test:unit": "bun test --conditions=solid --only-failures --isolate --preload ../ui/test/solid-jsx.ts --preload ./happydom.ts ./src",
"test:browser": "bun test --conditions=browser --isolate --preload ../ui/test/solid-jsx.ts --preload ./happydom.ts ./test-browser",
"test:unit:watch": "bun test --conditions=solid --watch --isolate --preload ../ui/test/solid-jsx.ts --preload ./happydom.ts ./src",
"test:e2e": "playwright test",
"test:e2e:built": "PLAYWRIGHT_BUILD=1 playwright test",
"test:e2e:local": "playwright test",
+4 -1
View File
@@ -1,4 +1,7 @@
import { fileURLToPath } from "node:url"
import type { PlaywrightTestConfig } from "@playwright/test"
import { componentConfig } from "../stories/playwright/config"
export default componentConfig(fileURLToPath(new URL(".", import.meta.url)))
const config: PlaywrightTestConfig = componentConfig(fileURLToPath(new URL(".", import.meta.url)))
export default config
+35 -1
View File
@@ -86,7 +86,41 @@ function initialComposerStore(initial?: InitialPrompt): ComposerStore {
}
}
function createComposerStateValue(store: ComposerStore, setStore: SetStoreFunction<ComposerStore>) {
// Named because `capture` returns the value itself: declaration emit cannot serialize the inferred cyclic type.
export interface ComposerStateValue {
readonly store: [Accessor<ComposerStore>, SetStoreFunction<ComposerStore>]
readonly current: () => Prompt
readonly cursor: () => ComposerStore["cursor"]
readonly model: {
readonly current: () => ComposerStore["model"]
readonly set: (model: PromptModel | undefined) => void
}
readonly mode: {
readonly current: () => NonNullable<ComposerStore["mode"]>
readonly set: (mode: "normal" | "shell") => void
}
readonly retry: {
readonly current: () => ComposerStore["retry"]
readonly set: (retry: NonNullable<ComposerStore["retry"]>) => void
}
readonly context: {
readonly items: () => ComposerStore["context"]["items"]
add(item: ContextItem): void
remove(key: string): void
removeComment(commentID: string): void
updateComment(commentID: string, next: { readonly comment?: string; readonly preview?: string }): void
replace(items: ContextItem[]): void
replaceComments(items: ContextItem[]): void
}
readonly set: (prompt: Prompt, cursorPosition?: number) => void
readonly reset: () => void
readonly capture: () => ComposerStateValue
}
function createComposerStateValue(
store: ComposerStore,
setStore: SetStoreFunction<ComposerStore>,
): ComposerStateValue {
const actions = createComposerActions(setStore)
// The quote whose comment editor is open, by key; a request made before the composer shows waits for it.
const [quoteComment, setQuoteComment] = createSignal<string>()
+1 -1
View File
@@ -330,7 +330,7 @@ export function TabNavItem(props: {
"overflow-hidden text-clip whitespace-nowrap": !editing(),
"select-text": editing(),
}}
contenteditable={editing() ? true : undefined}
contenteditable={editing() ? "plaintext-only" : undefined}
onDblClick={openRename}
onKeyDown={(event) => {
event.stopPropagation()
@@ -481,7 +481,7 @@ export function TitlebarTabStrip(props: {
: [new PointerActivationConstraints.Distance({ value: 4 })],
preventActivation: (event) =>
event.target instanceof Element &&
!!event.target.closest('[data-slot="tab-close"], [contenteditable="true"]'),
!!event.target.closest('[data-slot="tab-close"], [contenteditable="true"], [contenteditable="plaintext-only"]'),
}),
]}
modifiers={[
@@ -7,7 +7,8 @@ import type { ModelKey } from "@/providers/models/selection"
import { ServerScope } from "@/runtime/server/scope"
// Bun does not compile Solid JSX. Compile the real context provider with the
// same presets as Vite instead of replacing LocalProvider's implementation.
// same presets as Vite, along with every TSX module it loads, instead of
// replacing LocalProvider's implementation.
const require = createRequire(import.meta.url)
const solid = createRequire(require.resolve("vite-plugin-solid"))
@@ -17,7 +18,7 @@ const { transformSync } = solid("@babel/core")
Bun.plugin({
name: "selection-solid-context",
setup(build) {
build.onLoad({ filter: /[\\/]ui[\\/]src[\\/]context[\\/]helper\.tsx$/ }, async (args) => ({
build.onLoad({ filter: /\.tsx$/ }, async (args) => ({
contents: transformSync(await Bun.file(args.path).text(), {
filename: args.path,
presets: [solid.resolve("babel-preset-solid"), solid.resolve("@babel/preset-typescript")],
+3 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/cli",
"version": "2.1.2",
"version": "2.1.3",
"type": "module",
"license": "MIT",
"bin": {
@@ -21,7 +21,8 @@
"build:node": "bun run script/build-node.ts",
"dev": "bun run src/index.ts",
"test": "bun test --timeout 30000 --only-failures",
"typecheck": "tsc -b"
"typecheck": "bun check --no-script -b",
"typecheck:tsc": "tsc -b"
},
"dependencies": {
"@agentclientprotocol/sdk": "1.6.0",
+9
View File
@@ -117,6 +117,15 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
commands: [
Spec.make("agents", { description: "List all agents" }),
Spec.make("config", { description: "List configuration sources" }),
Spec.make("heap-dump", {
description: "Write a heap snapshot of the running server and print its path",
params: {
server: Flag.String("server").pipe(
Flag.withDescription("Connect to a server URL instead of the background service"),
Flag.optional,
),
},
}),
Spec.make("paths", {
description: "Show global paths (data, config, cache, state)",
params: {
@@ -0,0 +1,50 @@
import { ClientError, OpenCode } from "@opencode/client"
import { Service } from "@opencode/client/effect/service"
import { Effect, Option, Predicate } from "effect"
import { EOL } from "node:os"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
import { ServerConnection } from "../../../services/server-connection"
import { ServiceConfig } from "../../../services/service-config"
import { errorMessage } from "../../../util/error"
const handler = Effect.fn("cli.debug.heap-dump")(function* (
input: Runtime.Input<(typeof Commands.commands.debug.commands)["heap-dump"]>,
) {
const endpoint = yield* running(Option.getOrUndefined(input.server))
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
const snapshot = yield* Effect.tryPromise({
try: (signal) => client.debug.heapDump({ signal }),
catch: (cause) =>
cause instanceof ClientError &&
cause.reason === "UnexpectedStatus" &&
Predicate.hasProperty(cause.cause, "status") &&
cause.cause.status === 404
? new Error(`The server at ${endpoint.url} does not support heap dumps. Update and restart it first.`)
: cause,
})
process.stdout.write(snapshot.path + EOL)
})
export default Runtime.handler(Commands.commands.debug.commands["heap-dump"], (input) =>
handler(input).pipe(
Effect.catch((error) =>
Effect.sync(() => {
process.stderr.write(errorMessage(error) + EOL)
process.exitCode = 1
}),
),
),
)
// A fresh server has nothing worth capturing, so only an already-running one is used: never start,
// replace, or restart the background service.
const running = Effect.fnUntraced(function* (server: string | undefined) {
if (server !== undefined) return (yield* ServerConnection.resolve({ server })).endpoint
const options = yield* ServiceConfig.options()
const endpoint = yield* Service.discover({ ...options, version: undefined })
if (endpoint) return endpoint
return yield* Effect.fail(
new Error("No background server is running. Pass --server <url> to capture a server started another way."),
)
})
+4 -13
View File
@@ -1,6 +1,6 @@
import { Global } from "@opencode/util/global"
import { HeapSnapshot } from "@opencode/util/heap-snapshot"
import { Effect, Queue } from "effect"
import path from "node:path"
export const listen = Effect.gen(function* () {
const global = yield* Global.Service
@@ -16,18 +16,9 @@ export const listen = Effect.gen(function* () {
)
yield* Queue.take(signals).pipe(
Effect.andThen(
Effect.suspend(() => {
const file = path.join(
global.log,
`heap-${process.pid}-${new Date().toISOString().replace(/[:.]/g, "")}.heapsnapshot`,
)
return Effect.gen(function* () {
yield* Effect.logInfo("writing heap snapshot", { path: file })
const { writeHeapSnapshot } = yield* Effect.tryPromise(() => import("node:v8"))
yield* Effect.try(() => writeHeapSnapshot(file))
yield* Effect.logInfo("heap snapshot written", { path: file })
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to write heap snapshot", { path: file, cause })))
}),
HeapSnapshot.write(global.log).pipe(
Effect.catchCause((cause) => Effect.logError("failed to write heap snapshot", { cause })),
),
),
Effect.forever,
Effect.forkScoped({ startImmediately: true }),
+1
View File
@@ -42,6 +42,7 @@ const Handlers = Runtime.handlers(Commands, {
debug: {
agents: () => import("./commands/handlers/debug/agents"),
config: () => import("./commands/handlers/debug/config"),
"heap-dump": () => import("./commands/handlers/debug/heap-dump"),
paths: () => import("./commands/handlers/debug/paths"),
},
mcp: {
+95
View File
@@ -0,0 +1,95 @@
import { expect, test } from "bun:test"
import fs from "node:fs/promises"
import path from "node:path"
import { ServiceConfig } from "../src/services/service-config"
import { OPENCODE_VERSION } from "../src/version"
import { isolatedEnv } from "./fixture/environment"
import { tmpdir } from "./fixture/tmpdir"
// The server owns the snapshot writer (packages/server/test/heap-dump.test.ts); these cover how the
// command finds a server, what it prints, and that it never starts or replaces one.
test("prints the snapshot path from the registered server without replacing it", async () => {
await using root = await tmpdir()
const requests: Array<{ method: string; path: string; authorization: string | null }> = []
using server = fake((request) => {
requests.push({
method: request.method,
path: new URL(request.url).pathname,
authorization: request.headers.get("authorization"),
})
return Response.json({ path: "/server/log/heap-1-2.heapsnapshot", pid: process.pid })
})
const registration = await register(root.path, server.url.href)
const result = await cli(root.path, ["debug", "heap-dump"])
expect({ code: result.code, stderr: result.stderr, stdout: result.stdout.trim() }).toEqual({
code: 0,
stderr: "",
stdout: "/server/log/heap-1-2.heapsnapshot",
})
expect(requests).toEqual([
{ method: "POST", path: "/api/debug/heap-dump", authorization: `Basic ${btoa("opencode:secret")}` },
])
expect(await Bun.file(registration.file).json()).toEqual(registration.info)
})
test("fails without starting a server when none is registered", async () => {
await using root = await tmpdir()
const result = await cli(root.path, ["debug", "heap-dump"])
expect(result.stderr).toContain("No background server is running")
expect(result.code).toBe(1)
expect(await Bun.file(path.join(root.path, "state", "opencode", ServiceConfig.filename())).exists()).toBe(false)
})
test("explains when the server predates heap dumps", async () => {
await using root = await tmpdir()
using server = fake(() => new Response(null, { status: 404 }))
const result = await cli(root.path, ["debug", "heap-dump", "--server", server.url.href], {
OPENCODE_PASSWORD: "secret",
})
expect(result.stderr.trim()).toBe(
`The server at ${server.url.href} does not support heap dumps. Update and restart it first.`,
)
expect(result.code).toBe(1)
})
// Answers the health probe like a ready V2 server and passes every other request to `handle`.
function fake(handle: (request: Request) => Response) {
return Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch: (request) =>
new URL(request.url).pathname === "/api/info"
? Response.json({ version: OPENCODE_VERSION, pid: process.pid, urls: [] })
: handle(request),
})
}
async function register(root: string, url: string) {
const file = path.join(root, "state", "opencode", ServiceConfig.filename())
const info = { version: OPENCODE_VERSION, url, pid: process.pid, password: "secret" }
await fs.mkdir(path.dirname(file), { recursive: true })
await fs.writeFile(file, JSON.stringify(info))
return { file, info }
}
async function cli(root: string, args: string[], env: Record<string, string> = {}) {
const child = Bun.spawn([process.execPath, "run", path.join(import.meta.dir, "../src/index.ts"), ...args], {
cwd: path.join(import.meta.dir, ".."),
env: isolatedEnv(root, env),
stdout: "pipe",
stderr: "pipe",
})
const [stdout, stderr, code] = await Promise.all([
new Response(child.stdout).text(),
new Response(child.stderr).text(),
child.exited,
])
return { stdout, stderr, code }
}
+6 -3
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/client",
"version": "2.1.2",
"version": "2.1.3",
"type": "module",
"license": "MIT",
"repository": {
@@ -23,14 +23,16 @@
"./solid": "./src/solid/index.ts",
"./effect": "./src/effect/index.ts",
"./effect/api": "./src/effect/api.ts",
"./effect/service": "./src/effect/service.ts"
"./effect/service": "./src/effect/service.ts",
"./mcp": "./src/mcp.ts"
},
"scripts": {
"build": "bun run script/build-package.ts",
"generate": "bun run script/build.ts",
"check:generated": "bun run generate && git diff --exit-code -- src/promise/generated src/effect/generated src/effect/api",
"test": "bun test --timeout 5000",
"typecheck": "tsc --noEmit"
"typecheck": "bun check --no-script",
"typecheck:tsc": "tsc --noEmit"
},
"dependencies": {
"@opencode/schema": "workspace:*",
@@ -50,6 +52,7 @@
},
"devDependencies": {
"@effect/platform-node": "catalog:",
"@modelcontextprotocol/client": "2.3.1",
"@opencode/httpapi-codegen": "workspace:*",
"@tsconfig/bun": "catalog:",
"@types/bun": "catalog:",
+1 -1
View File
@@ -21,7 +21,7 @@ if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode ==
}
try {
await $`bun run typecheck`
await $`bun run typecheck:tsc`
await $`bun run build`
pkg.exports = Object.fromEntries(
Object.entries(pkg.exports).map(([key, value]) => {
+14 -1
View File
@@ -29,13 +29,13 @@ import type { Form } from "@opencode/schema/form"
import type { Provider } from "@opencode/schema/provider"
import type { Integration } from "@opencode/schema/integration"
import type { Mcp } from "@opencode/schema/mcp"
import type { PtyTicket } from "@opencode/schema/pty-ticket"
import type { Credential } from "@opencode/schema/credential"
import type { PermissionSaved } from "@opencode/schema/permission-saved"
import type { FileSystem } from "@opencode/schema/filesystem"
import type { Command } from "@opencode/schema/command"
import type { OpenCodeEvent } from "@opencode/protocol/groups/event"
import type { Pty } from "@opencode/schema/pty"
import type { PtyTicket } from "@opencode/schema/pty-ticket"
import type { Reference } from "@opencode/schema/reference"
import type { Worktree } from "@opencode/schema/worktree"
import type { Vcs } from "@opencode/schema/vcs"
@@ -1671,6 +1671,14 @@ export type McpResourceCatalogOperation<E = never> = (
input?: McpResourceCatalogInput,
) => Effect.Effect<McpResourceCatalogOutput, E>
export type McpClientTokenInput = {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly name: string
readonly "x-opencode-ticket"?: string | undefined
}
export type McpClientTokenOutput = { readonly location: Location.PublicRef; readonly data: PtyTicket.ConnectToken }
export type McpClientTokenOperation<E = never> = (input: McpClientTokenInput) => Effect.Effect<McpClientTokenOutput, E>
export interface McpApi<E = never> {
readonly list: McpListOperation<E>
readonly add: McpAddOperation<E>
@@ -1678,6 +1686,7 @@ export interface McpApi<E = never> {
readonly connect: McpConnectOperation<E>
readonly disconnect: McpDisconnectOperation<E>
readonly resource: { readonly catalog: McpResourceCatalogOperation<E> }
readonly client: { readonly token: McpClientTokenOperation<E> }
}
export type CredentialListOutput = ReadonlyArray<Credential.Entry>
@@ -2279,6 +2288,9 @@ export interface VcsApi<E = never> {
readonly diff: VcsDiffOperation<E>
}
export type DebugHeapDumpOutput = { readonly path: string; readonly pid: number }
export type DebugHeapDumpOperation<E = never> = () => Effect.Effect<DebugHeapDumpOutput, E>
export type DebugLocationListOutput = ReadonlyArray<Location.PublicRef>
export type DebugLocationListOperation<E = never> = () => Effect.Effect<DebugLocationListOutput, E>
@@ -2289,6 +2301,7 @@ export type DebugLocationEvictOperation<E = never> = (
) => Effect.Effect<DebugLocationEvictOutput, E>
export interface DebugApi<E = never> {
readonly heapDump: DebugHeapDumpOperation<E>
readonly location: { readonly list: DebugLocationListOperation<E>; readonly evict: DebugLocationEvictOperation<E> }
}
@@ -160,6 +160,8 @@ import type {
McpDisconnectOutput,
McpResourceCatalogInput,
McpResourceCatalogOutput,
McpClientTokenInput,
McpClientTokenOutput,
CredentialListOutput,
CredentialCreateInput,
CredentialCreateOutput,
@@ -268,6 +270,7 @@ import type {
VcsBranchListOutput,
VcsDiffInput,
VcsDiffOutput,
DebugHeapDumpOutput,
DebugLocationListOutput,
DebugLocationEvictInput,
DebugLocationEvictOutput,
@@ -1091,6 +1094,14 @@ const EndpointMcpResourceCatalog = (raw: RawClient["server.mcp"]) => (input?: Mc
raw["mcp.resource.catalog"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)),
)
const EndpointMcpClientToken = (raw: RawClient["server.mcp"]) => (input: McpClientTokenInput) =>
preserveEffect<McpClientTokenOutput>()(
raw["mcp.clientToken"]({
query: { location: input["location"], name: input["name"] },
headers: { "x-opencode-ticket": input["x-opencode-ticket"] },
}).pipe(Effect.mapError(mapClientError)),
)
const adaptGroupMcp = (raw: RawClient["server.mcp"]) => ({
list: EndpointMcpList(raw),
add: EndpointMcpAdd(raw),
@@ -1098,6 +1109,7 @@ const adaptGroupMcp = (raw: RawClient["server.mcp"]) => ({
connect: EndpointMcpConnect(raw),
disconnect: EndpointMcpDisconnect(raw),
resource: { catalog: EndpointMcpResourceCatalog(raw) },
client: { token: EndpointMcpClientToken(raw) },
})
const EndpointCredentialList = (raw: RawClient["server.credential"]) => () =>
@@ -1642,6 +1654,9 @@ const adaptGroupVcs = (raw: RawClient["server.vcs"]) => ({
diff: EndpointVcsDiff(raw),
})
const EndpointDebugHeapDump = (raw: RawClient["server.debug"]) => () =>
preserveEffect<DebugHeapDumpOutput>()(raw["debug.heapDump"]({}).pipe(Effect.mapError(mapClientError)))
const EndpointDebugLocationList = (raw: RawClient["server.debug"]) => () =>
preserveEffect<DebugLocationListOutput>()(raw["debug.location"]({}).pipe(Effect.mapError(mapClientError)))
@@ -1651,6 +1666,7 @@ const EndpointDebugLocationEvict = (raw: RawClient["server.debug"]) => (input?:
)
const adaptGroupDebug = (raw: RawClient["server.debug"]) => ({
heapDump: EndpointDebugHeapDump(raw),
location: { list: EndpointDebugLocationList(raw), evict: EndpointDebugLocationEvict(raw) },
})
+175
View File
@@ -0,0 +1,175 @@
export type ClientMcpOptions = {
/** Base URL of the opencode server, for example `http://127.0.0.1:4096`. Its query params are kept. */
readonly url: string
/** Client name, `[a-zA-Z0-9_-]+`. Tools are exposed to the model as `<name>_<tool>`. */
readonly name: string
/** Sent as `location[directory]`. */
readonly directory?: string
/** Handshake headers, such as `authorization`. Browsers cannot send them; use a ticket in `url` instead. */
readonly headers?: Record<string, string>
readonly tools: ReadonlyArray<ClientMcpTool>
readonly WebSocket?: typeof WebSocket
}
export type ClientMcpTool = {
/** `[a-zA-Z0-9_-]+` */
readonly name: string
readonly description?: string
/** JSON Schema for the arguments; `type: "object"` is always set. Arguments are not validated here. */
readonly inputSchema?: Record<string, unknown>
readonly handler: (
args: Record<string, unknown>,
ctx: ClientMcpToolContext,
) => ClientMcpToolResult | Promise<ClientMcpToolResult>
}
export type ClientMcpToolContext = {
/** The opencode session that issued the call. */
readonly sessionID?: string
}
export type ClientMcpToolResult = {
readonly content: ReadonlyArray<
| { readonly type: "text"; readonly text: string }
| { readonly type: "image"; readonly data: string; readonly mimeType: string }
>
readonly isError?: boolean
}
export type ClientMcpConnection = {
close(): Promise<void>
}
type Message = {
readonly id?: unknown
readonly method?: unknown
readonly params?: {
readonly protocolVersion?: unknown
readonly name?: unknown
readonly arguments?: Record<string, unknown>
readonly _meta?: Record<string, unknown>
}
}
const SESSION_ID_META_KEY = "ai.opencode/sessionID"
const PROTOCOL_VERSION = "2025-11-25"
const RECONNECT_MIN = 500
const RECONNECT_MAX = 10_000
/**
* Exposes tools to the opencode server: opens a WebSocket to `/api/experimental/client-mcp` and answers MCP
* JSON-RPC over it (one message per text frame), so the opencode server is the MCP client. Reconnects with
* backoff until `close()`.
*/
export function connectClientMcp(options: ClientMcpOptions): ClientMcpConnection {
const state: { disposed: boolean; delay: number; timer?: ReturnType<typeof setTimeout>; socket?: WebSocket } = {
disposed: false,
delay: RECONNECT_MIN,
}
const connect = () => {
if (state.disposed) return
const Socket = options.WebSocket ?? WebSocket
const socket = options.headers
? // Bun and Node accept a `{ headers }` init as the second argument; the DOM typings only know protocols.
new Socket(endpoint(options), { headers: options.headers } as unknown as string[])
: new Socket(endpoint(options))
state.socket = socket
socket.addEventListener("message", (event) => {
if (state.disposed || typeof event.data !== "string") return
const message = parse(event.data)
if (!message) return
// Reset backoff only once the opencode server finished initializing, so a failed attach keeps backing off.
if (message.method === "notifications/initialized") state.delay = RECONNECT_MIN
// Notifications and responses need no reply.
if ((typeof message.id !== "string" && typeof message.id !== "number") || typeof message.method !== "string")
return
void respond(options, message.method, message.params).then((reply) =>
send(socket, { jsonrpc: "2.0", id: message.id, ...reply }),
)
})
socket.addEventListener("close", () => {
if (state.socket === socket) state.socket = undefined
if (state.disposed) return
state.timer = setTimeout(connect, state.delay)
state.delay = Math.min(state.delay * 2, RECONNECT_MAX)
})
}
connect()
return {
async close() {
state.disposed = true
clearTimeout(state.timer)
state.socket?.close(1000)
},
}
}
async function respond(options: ClientMcpOptions, method: string, params: Message["params"]) {
switch (method) {
case "initialize":
return {
result: {
// The opencode server only offers versions it supports, so echo its choice.
protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION,
capabilities: { tools: {} },
serverInfo: { name: options.name, version: "1.0.0" },
},
}
case "ping":
return { result: {} }
case "tools/list":
return {
result: {
tools: options.tools.map((tool) => ({
name: tool.name,
description: tool.description,
inputSchema: { type: "object", ...tool.inputSchema },
})),
},
}
case "tools/call": {
const tool = options.tools.find((tool) => tool.name === params?.name)
if (!tool) return { error: { code: -32602, message: `Unknown tool: ${String(params?.name)}` } }
const meta = params?._meta?.[SESSION_ID_META_KEY]
return Promise.resolve()
.then(() => tool.handler(params?.arguments ?? {}, { sessionID: typeof meta === "string" ? meta : undefined }))
.then(
(result) => ({ result }),
(error) => ({
result: {
content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
isError: true,
},
}),
)
}
}
return { error: { code: -32601, message: `Method not found: ${method}` } }
}
function send(socket: WebSocket, message: object) {
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(message))
}
function parse(text: string): Message | undefined {
try {
const value: unknown = JSON.parse(text)
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined
} catch {
return undefined
}
}
function endpoint(options: ClientMcpOptions) {
const base = new URL(options.url)
if (!base.pathname.endsWith("/")) base.pathname += "/"
const url = new URL("api/experimental/client-mcp", base)
url.search = base.search
if (options.directory) url.searchParams.set("location[directory]", options.directory)
url.searchParams.set("name", options.name)
url.protocol = url.protocol === "https:" || url.protocol === "wss:" ? "wss:" : "ws:"
return url
}
@@ -154,6 +154,8 @@ import type {
McpDisconnectOutput,
McpResourceCatalogInput,
McpResourceCatalogOutput,
McpClientTokenInput,
McpClientTokenOutput,
CredentialListOutput,
CredentialCreateInput,
CredentialCreateOutput,
@@ -266,6 +268,7 @@ import type {
VcsBranchListOutput,
VcsDiffInput,
VcsDiffOutput,
DebugHeapDumpOutput,
DebugLocationListOutput,
DebugLocationEvictInput,
DebugLocationEvictOutput,
@@ -1467,6 +1470,21 @@ export function make(options: ClientOptions) {
requestOptions,
),
},
client: {
token: (input: McpClientTokenInput, requestOptions?: RequestOptions) =>
request<McpClientTokenOutput>(
{
method: "POST",
path: `/api/experimental/client-mcp/token`,
query: { location: input["location"], name: input["name"] },
headers: { "x-opencode-ticket": input["x-opencode-ticket"] },
successStatus: 200,
declaredStatuses: [400, 401, 403, 404],
empty: false,
},
requestOptions,
),
},
},
credential: {
list: (requestOptions?: RequestOptions) =>
@@ -2239,6 +2257,17 @@ export function make(options: ClientOptions) {
),
},
debug: {
heapDump: (requestOptions?: RequestOptions) =>
request<DebugHeapDumpOutput>(
{
method: "POST",
path: `/api/debug/heap-dump`,
successStatus: 200,
declaredStatuses: [400, 401, 500],
empty: false,
},
requestOptions,
),
location: {
list: (requestOptions?: RequestOptions) =>
request<DebugLocationListOutput>(
+23 -6
View File
@@ -247,6 +247,8 @@ export type McpResourceTemplate = {
mimeType?: string
}
export type PtyTicketConnectToken = { ticket: string; expires_in: number }
export type CredentialKey = { type: "key"; key: string; metadata?: { [x: string]: JsonValue } }
export type ProjectVcs = string
@@ -288,8 +290,6 @@ export type SessionStatus =
}
| { type: "busy" }
export type PtyTicketConnectToken = { ticket: string; expires_in: number }
export type PersistentPtyHandoff = { directory: string; instanceID: string; ticket: string; expiresAt: number }
export type ReferenceGitSource = { type: "git"; repository: string; branch?: string }
@@ -2352,6 +2352,7 @@ export type ConfigEntry =
experimental?: {
portable_shell_scanner?: boolean
todo?: boolean
precompute_compaction?: boolean
subagent_depth?: number
location_idle_timeout?: string | false
policies?: Array<{
@@ -2861,6 +2862,10 @@ export type McpServerNotFoundError = {
export const isMcpServerNotFoundError = (value: unknown): value is McpServerNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "McpServerNotFoundError"
export type ForbiddenError = { readonly _tag: "ForbiddenError"; readonly message: string }
export const isForbiddenError = (value: unknown): value is ForbiddenError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ForbiddenError"
export type ProjectNotFoundError = {
readonly _tag: "ProjectNotFoundError"
readonly projectID: string
@@ -2911,10 +2916,6 @@ export type PtyNotFoundError = { readonly _tag: "PtyNotFoundError"; readonly pty
export const isPtyNotFoundError = (value: unknown): value is PtyNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "PtyNotFoundError"
export type ForbiddenError = { readonly _tag: "ForbiddenError"; readonly message: string }
export const isForbiddenError = (value: unknown): value is ForbiddenError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ForbiddenError"
export type ShellNotFoundError = { readonly _tag: "ShellNotFoundError"; readonly id: string; readonly message: string }
export const isShellNotFoundError = (value: unknown): value is ShellNotFoundError =>
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "ShellNotFoundError"
@@ -5241,6 +5242,20 @@ export type McpResourceCatalogInput = {
export type McpResourceCatalogOutput = { location: LocationPublicRef; data: McpResourceCatalog }
export type McpClientTokenInput = {
readonly location?: {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly name: string
}["location"]
readonly name: {
readonly location?: { readonly directory?: string | undefined } | undefined
readonly name: string
}["name"]
readonly "x-opencode-ticket"?: { readonly "x-opencode-ticket"?: string | undefined }["x-opencode-ticket"]
}
export type McpClientTokenOutput = { location: LocationPublicRef; data: PtyTicketConnectToken }
export type CredentialListOutput = { data: Array<CredentialEntry> }["data"]
export type CredentialCreateInput = {
@@ -6035,6 +6050,8 @@ export type VcsDiffInput = {
export type VcsDiffOutput = { location: LocationPublicRef; data: Array<FileDiffInfo> }
export type DebugHeapDumpOutput = { path: string; pid: number }
export type DebugLocationListOutput = Array<LocationPublicRef>
export type DebugLocationEvictInput = {
@@ -41,6 +41,11 @@ describe("public import boundaries", () => {
expect(within(effectService.eager, effect).length).toBeGreaterThan(0)
expect(within(effectService.all, core)).toEqual([])
expect(within(effectService.all, server)).toEqual([])
const mcp = await bundleInputs("@opencode/client/mcp", "browser")
// The MCP entrypoint is dependency-free: only the generated entry and mcp.ts itself.
expect(mcp.all.filter((file) => !file.endsWith("index.ts"))).toEqual([resolve(directory, "src/mcp.ts")])
})
})
+257
View File
@@ -0,0 +1,257 @@
import { afterEach, describe, expect, jest, test } from "bun:test"
import { Client, type JSONRPCMessage, type Transport } from "@modelcontextprotocol/client"
import type { ServerWebSocket } from "bun"
import { connectClientMcp } from "../src/mcp"
type Peer = {
readonly request: Request
readonly socket: ServerWebSocket<{ id: number; request: Request }>
readonly client: Client
readonly closed: Promise<void>
}
const servers: Array<{ stop(force: boolean): Promise<void> }> = []
afterEach(async () => {
jest.useRealTimers()
await Promise.all(servers.splice(0).map((server) => server.stop(true)))
})
describe("connectClientMcp", () => {
test("serves registered tools to the opencode server", async () => {
const server = serve()
const connection = connectClientMcp({
url: server.url + "?ticket=t1",
name: "tui",
directory: "/repo",
headers: { authorization: "Basic secret" },
tools: [
{
name: "whoami",
description: "Return the calling session",
handler: (_args, ctx) => ({ content: [{ type: "text", text: ctx.sessionID ?? "none" }] }),
},
{
name: "echo",
inputSchema: { properties: { text: { type: "string" } }, required: ["text"] },
handler: (args) => ({ content: [{ type: "text", text: String(args.text) }] }),
},
{
name: "fail",
handler: () => {
throw new Error("boom")
},
},
],
})
const peer = await server.next()
const url = new URL(peer.request.url)
expect(url.pathname).toBe("/api/experimental/client-mcp")
expect(url.searchParams.get("name")).toBe("tui")
expect(url.searchParams.get("ticket")).toBe("t1")
expect(url.searchParams.get("location[directory]")).toBe("/repo")
expect(peer.request.headers.get("authorization")).toBe("Basic secret")
await peer.client.ping()
expect((await peer.client.listTools()).tools).toEqual([
{ name: "whoami", description: "Return the calling session", inputSchema: { type: "object" } },
{
name: "echo",
inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
},
{ name: "fail", inputSchema: { type: "object" } },
])
expect(
await peer.client.callTool({ name: "whoami", arguments: {}, _meta: { "ai.opencode/sessionID": "ses_1" } }),
).toMatchObject({ content: [{ type: "text", text: "ses_1" }] })
expect(await peer.client.callTool({ name: "whoami", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "none" }],
})
expect(await peer.client.callTool({ name: "echo", arguments: { text: "hi" } })).toMatchObject({
content: [{ type: "text", text: "hi" }],
})
expect(await peer.client.callTool({ name: "fail", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "boom" }],
isError: true,
})
await expect(peer.client.callTool({ name: "missing", arguments: {} })).rejects.toThrow("Unknown tool: missing")
await connection.close()
await peer.closed
})
test("reconnects after the server drops the socket", async () => {
const server = serve()
const connection = connectClientMcp({
url: server.url,
name: "tui",
tools: [{ name: "ping", handler: () => ({ content: [{ type: "text", text: "pong" }] }) }],
})
const first = await server.next()
expect((await first.client.listTools()).tools).toHaveLength(1)
first.socket.close(1011, "internal")
const second = await server.next()
expect(await second.client.callTool({ name: "ping", arguments: {} })).toMatchObject({
content: [{ type: "text", text: "pong" }],
})
await connection.close()
})
test("close cancels a pending reconnect", async () => {
const server = serve()
const socket = trackedSocket()
const connection = connectClientMcp({ url: server.url, name: "tui", tools: [], WebSocket: socket.WebSocket })
const peer = await server.next()
jest.useFakeTimers()
peer.socket.close(1011, "internal")
await socket.closed(1)
await connection.close()
jest.advanceTimersByTime(10_000)
expect(socket.opened()).toBe(1)
})
test("keeps backing off while the opencode server never initializes", async () => {
const server = Bun.serve({
port: 0,
fetch(request, server) {
if (server.upgrade(request)) return
return new Response("upgrade required", { status: 426 })
},
websocket: {
open(socket) {
socket.send("not json")
socket.close(1011, "internal")
},
message() {},
},
})
servers.push(server)
const socket = trackedSocket()
jest.useFakeTimers()
const connection = connectClientMcp({
url: server.url.href,
name: "tui",
tools: [],
WebSocket: socket.WebSocket,
})
await socket.closed(1)
jest.advanceTimersByTime(500)
expect(socket.opened()).toBe(2)
await socket.closed(2)
jest.advanceTimersByTime(999)
expect(socket.opened()).toBe(2)
jest.advanceTimersByTime(1)
expect(socket.opened()).toBe(3)
await connection.close()
})
})
/** Counts sockets synchronously at construction, so fake-timer reconnects are observable without real waits. */
function trackedSocket() {
const state = { opened: 0, closed: 0, waiting: [] as Array<{ count: number; resolve: () => void }> }
class Tracked extends WebSocket {
constructor(url: string | URL, init?: string | string[]) {
super(url, init)
state.opened++
this.addEventListener("close", () => {
state.closed++
state.waiting = state.waiting.filter((waiter) => {
if (state.closed < waiter.count) return true
// Let connectClientMcp's own close listener run before the test continues.
setImmediate(waiter.resolve)
return false
})
})
}
}
return {
WebSocket: Tracked,
opened: () => state.opened,
closed: (count: number) =>
new Promise<void>((resolve) => {
if (state.closed >= count) return resolve()
state.waiting.push({ count, resolve })
}),
}
}
function serve() {
const waiting: Array<(peer: Peer) => void> = []
const ready: Peer[] = []
const transports = new Map<number, ReturnType<typeof socketTransport>>()
const state = { connections: 0 }
const server = Bun.serve<{ id: number; request: Request }>({
port: 0,
fetch(request, server) {
if (server.upgrade(request, { data: { id: ++state.connections, request } })) return
return new Response("upgrade required", { status: 426 })
},
websocket: {
open(socket) {
const transport = socketTransport(socket)
transports.set(socket.data.id, transport)
const client = new Client({ name: "opencode", version: "1.0.0" })
const closed = new Promise<void>((resolve) => {
client.onclose = resolve
})
void client.connect(transport).then(() => {
const peer = { request: socket.data.request, socket, client, closed }
const resolve = waiting.shift()
if (resolve) return resolve(peer)
ready.push(peer)
})
},
// Deliver outside the uWS callback: on Bun 1.4.4, replying from the SDK's microtasks inside it can make the
// server reject the client's next frame ("Received new message inside a fragmented message").
message(socket, message) {
const text = String(message)
setImmediate(() => transports.get(socket.data.id)?.deliver(text))
},
close(socket) {
setImmediate(() => transports.get(socket.data.id)?.ended())
},
},
})
const result = {
url: server.url.href,
next: () =>
new Promise<Peer>((resolve) => {
const peer = ready.shift()
if (peer) return resolve(peer)
waiting.push(resolve)
}),
stop: (force: boolean) => server.stop(force),
}
servers.push(result)
return result
}
function socketTransport(socket: ServerWebSocket<{ id: number; request: Request }>) {
const state = { closed: false }
const transport: Transport & { deliver(text: string): void; ended(): void } = {
async start() {},
async send(message: JSONRPCMessage) {
if (state.closed) throw new Error("Not connected")
socket.send(JSON.stringify(message))
},
async close() {
socket.close(1000)
transport.ended()
},
deliver(text) {
transport.onmessage?.(JSON.parse(text))
},
ended() {
if (state.closed) return
state.closed = true
transport.onclose?.()
},
}
return transport
}
+1 -1
View File
@@ -37,7 +37,7 @@ test("exposes every standard HTTP API group", () => {
"websearch",
"config",
])
expect(Object.keys(client.debug)).toEqual(["location"])
expect(Object.keys(client.debug)).toEqual(["heapDump", "location"])
expect(Object.keys(client.debug.location)).toEqual(["list", "evict"])
expect(Object.keys(client.message)).toEqual(["list"])
expect(Object.keys(client.integration)).toEqual(["list", "get", "wellknown", "connect", "oauth", "command"])
+3 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/codemode",
"version": "2.1.2",
"version": "2.1.3",
"description": "Effect-native confined code execution over schema-described tools",
"type": "module",
"license": "MIT",
@@ -21,7 +21,8 @@
},
"scripts": {
"build": "bun run script/build.ts",
"typecheck": "tsc --noEmit",
"typecheck": "bun check --no-script",
"typecheck:tsc": "tsc --noEmit",
"test": "bun test"
},
"dependencies": {
+1 -1
View File
@@ -27,7 +27,7 @@ if (!dryRun && (await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).
}
try {
await $`bun run typecheck`
await $`bun run typecheck:tsc`
await $`bun run build`
pkg.exports = Object.fromEntries(
Object.entries(pkg.exports).map(([key, value]) => {
+3 -2
View File
@@ -1,10 +1,11 @@
{
"name": "@opencode/console-app",
"version": "2.1.2",
"version": "2.1.3",
"type": "module",
"license": "MIT",
"scripts": {
"typecheck": "tsc --noEmit",
"typecheck": "bun check --no-script",
"typecheck:tsc": "tsc --noEmit",
"dev": "vite dev --host 0.0.0.0",
"dev:enterprise": "bun --watch script/dev-enterprise.ts",
"dev:remote": "bun sst shell --stage=dev bun dev",
@@ -23,6 +23,7 @@ export const goModels = [
{ id: "minimax-m3", name: "MiniMax M3", requests: 3200, allowance: 60, featured: true },
{ id: "mimo-v2.6-pro", name: "MiMo-V2.6-Pro", requests: 3250, allowance: 15 },
{ id: "mimo-v2.5-pro", name: "MiMo-V2.5-Pro", requests: 3250, allowance: 15 },
{ id: "minimax-m3.1-flash", name: "MiniMax M3.1 Flash", requests: 3880, allowance: 20, featured: true },
{ id: "claude-haiku-5-5", name: "Claude Haiku 5.5", requests: 3850, allowance: 15, featured: true, fresh: true },
{ id: "qwen3.7-plus", name: "Qwen3.7 Plus", requests: 4300, allowance: 60, featured: true },
{ id: "gpt-6-luna", name: "GPT 6 Luna", requests: 4230, allowance: 15, featured: true },
@@ -68,15 +69,6 @@ export const goModels = [
featured: true,
limitedTime: true,
},
{
id: "minimax-m3.1-flash-free",
name: "MiniMax M3.1 Flash Free",
requests: Infinity,
allowance: Infinity,
featured: true,
fresh: true,
limitedTime: true,
},
{
id: "beam-free",
name: "Beam Free",
@@ -101,10 +93,10 @@ const plusLimits: Record<string, [number, number]> = {
"kimi-k2.7-code": [4050, 180],
"hy4-preview": [5400, 120],
"gpt-5.6-luna": [8200, 60],
"minimax-m3.1-flash-free": [Infinity, Infinity],
"minimax-m3": [9600, 180],
"mimo-v2.6-pro": [13000, 60],
"mimo-v2.5-pro": [13000, 60],
"minimax-m3.1-flash": [15500, 80],
"qwen3.7-plus": [12900, 180],
"gpt-6-luna": [16920, 60],
"claude-haiku-5-5": [15380, 60],
-1
View File
@@ -201,7 +201,6 @@ export const dict = {
"تتم استضافة جميع نماذج Zen في الولايات المتحدة. يتبع المزودون سياسة عدم الاحتفاظ بالبيانات ولا يستخدمون بياناتك لتدريب النماذج، مع",
"zen.privacy.exceptionsLink": "الاستثناءات التالية",
"go.promo.minimaxM31FlashFree": "يتوفر MiniMax M3.1 Flash Free الآن في Go مجانًا لفترة محدودة.",
"go.title": "OpenCode Go | نماذج برمجة منخفضة التكلفة للجميع",
"go.meta.description": "يبلغ سعر Go ‏$10/شهر، مع حدود استخدام سخية ووصول موثوق إلى نماذج البرمجة الرائدة.",
"go.hero.title": "نماذج برمجة منخفضة التكلفة للجميع",
-1
View File
@@ -205,7 +205,6 @@ export const dict = {
"Todos os modelos Zen são hospedados nos EUA. Os provedores seguem uma política de retenção zero e não usam seus dados para treinamento de modelo, com as",
"zen.privacy.exceptionsLink": "seguintes exceções",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free já está disponível no Go, grátis por tempo limitado.",
"go.title": "OpenCode Go | Modelos de codificação de baixo custo para todos",
"go.meta.description":
"O Go custa $10/mês, com limites generosos de uso e acesso confiável aos principais modelos de codificação.",
-1
View File
@@ -204,7 +204,6 @@ export const dict = {
"Alle Zen-modeller er hostet i USA. Udbydere følger en nulopbevaringspolitik og bruger ikke dine data til modeltræning med",
"zen.privacy.exceptionsLink": "følgende undtagelser",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free er nu tilgængelig i Go, gratis i en begrænset periode.",
"go.title": "OpenCode Go | Kodningsmodeller til lav pris for alle",
"go.meta.description":
"Go koster $10/måned, med generøse brugsgrænser og pålidelig adgang til førende kodningsmodeller.",
-1
View File
@@ -205,7 +205,6 @@ export const dict = {
"Alle Zen-Modelle werden in den USA gehostet. Anbieter folgen einer Zero-Retention-Policy und nutzen deine Daten nicht für Modelltraining, mit den",
"zen.privacy.exceptionsLink": "folgenden Ausnahmen",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free ist jetzt in Go für begrenzte Zeit kostenlos verfügbar.",
"go.title": "OpenCode Go | Kostengünstige Coding-Modelle für alle",
"go.meta.description":
"Go kostet $10/Monat, mit großzügigen Nutzungslimits und zuverlässigem Zugang zu führenden Coding-Modellen.",
-1
View File
@@ -203,7 +203,6 @@ export const dict = {
"All Zen models are hosted in the US. Providers follow a zero-retention policy and do not use your data for model training, with the",
"zen.privacy.exceptionsLink": "following exceptions",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free is now available in Go, free for a limited time.",
"go.title": "OpenCode Go | Low cost coding models for everyone",
"go.meta.description": "Go costs $10/month, with generous usage limits and reliable access to leading coding models.",
"go.hero.title": "Low cost coding models for everyone",
-1
View File
@@ -206,7 +206,6 @@ export const dict = {
"Todos los modelos Zen están alojados en EE. UU. Los proveedores siguen una política de cero retención y no usan tus datos para entrenamiento de modelos, con las",
"zen.privacy.exceptionsLink": "siguientes excepciones",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free ya está disponible en Go, gratis por tiempo limitado.",
"go.title": "OpenCode Go | Modelos de programación de bajo coste para todos",
"go.meta.description":
"Go cuesta 10 $/mes, con límites de uso generosos y acceso fiable a modelos de programación líderes.",
-1
View File
@@ -208,7 +208,6 @@ export const dict = {
"Tous les modèles Zen sont hébergés aux États-Unis. Les fournisseurs suivent une politique de rétention zéro et n'utilisent pas vos données pour l'entraînement des modèles, avec les",
"zen.privacy.exceptionsLink": "exceptions suivantes",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free est désormais disponible dans Go, gratuitement pour une durée limitée.",
"go.title": "OpenCode Go | Modèles de code à faible coût pour tous",
"go.meta.description":
"Go coûte 10 $/mois, avec des limites d'utilisation généreuses et un accès fiable aux principaux modèles de codage.",
-1
View File
@@ -203,7 +203,6 @@ export const dict = {
"Tutti i modelli Zen sono ospitati negli Stati Uniti. I provider seguono una policy di zero-retention e non usano i tuoi dati per l'addestramento dei modelli, con le",
"zen.privacy.exceptionsLink": "seguenti eccezioni",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free è ora disponibile in Go, gratis per un periodo limitato.",
"go.title": "OpenCode Go | Modelli di coding a basso costo per tutti",
"go.meta.description":
"Go costa $10/mese, con limiti di utilizzo generosi e un accesso affidabile ai principali modelli di coding.",
-1
View File
@@ -203,7 +203,6 @@ export const dict = {
"すべてのZenモデルは米国でホストされています。プロバイダーはゼロ保持ポリシーに従い、モデルのトレーニングにデータを使用しません(",
"zen.privacy.exceptionsLink": "以下の例外",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free を Go で期間限定・無料で提供中です。",
"go.title": "OpenCode Go | すべての人のための低価格なコーディングモデル",
"go.meta.description":
"Goは月額$10で、主要なコーディングモデルへのゆとりある利用上限と安定したアクセスを提供します。",
-1
View File
@@ -200,7 +200,6 @@ export const dict = {
"모든 Zen 모델은 미국에서 호스팅됩니다. 제공자들은 데이터 보존 금지 정책을 따르며 모델 학습에 데이터를 사용하지 않습니다. 단,",
"zen.privacy.exceptionsLink": "다음 예외",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free를 Go에서 한정 기간 동안 무료로 이용할 수 있습니다.",
"go.title": "OpenCode Go | 모두를 위한 저비용 코딩 모델",
"go.meta.description": "Go는 월 $10이며, 넉넉한 사용 한도와 주요 코딩 모델에 대한 안정적인 액세스를 제공합니다.",
"go.hero.title": "모두를 위한 저비용 코딩 모델",
-1
View File
@@ -204,7 +204,6 @@ export const dict = {
"Alle Zen-modeller hostes i USA. Leverandører følger en policy om null oppbevaring og bruker ikke dataene dine til modelltrening, med",
"zen.privacy.exceptionsLink": "følgende unntak",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free er nå tilgjengelig i Go, gratis i en begrenset periode.",
"go.title": "OpenCode Go | Rimelige kodemodeller for alle",
"go.meta.description":
"Go koster $10/måned, med sjenerøse bruksgrenser og pålitelig tilgang til ledende kodemodeller.",
-1
View File
@@ -204,7 +204,6 @@ export const dict = {
"Wszystkie modele Zen są hostowane w USA. Dostawcy stosują politykę zerowej retencji i nie wykorzystują Twoich danych do trenowania modeli, z",
"zen.privacy.exceptionsLink": "następującymi wyjątkami",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free jest już dostępny w Go, za darmo przez ograniczony czas.",
"go.title": "OpenCode Go | Niskokosztowe modele do kodowania dla każdego",
"go.meta.description":
"Go kosztuje $10/miesiąc, oferując hojne limity użycia i niezawodny dostęp do wiodących modeli do kodowania.",
-1
View File
@@ -207,7 +207,6 @@ export const dict = {
"Все модели Zen размещены в США. Провайдеры следуют политике нулевого хранения и не используют ваши данные для обучения моделей, за",
"zen.privacy.exceptionsLink": "следующими исключениями",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free уже доступна в Go бесплатно в течение ограниченного времени.",
"go.title": "OpenCode Go | Недорогие модели для кодинга для всех",
"go.meta.description":
"Go стоит $10/месяц и предлагает щедрые лимиты использования и надежный доступ к ведущим моделям для кодинга.",
-1
View File
@@ -202,7 +202,6 @@ export const dict = {
"โมเดล Zen ทั้งหมดโฮสต์ในสหรัฐอเมริกา ผู้ให้บริการปฏิบัติตามนโยบายไม่เก็บรักษาข้อมูล (zero-retention policy) และไม่ใช้ข้อมูลของคุณสำหรับการฝึกโมเดล โดยมี",
"zen.privacy.exceptionsLink": "ข้อยกเว้นดังนี้",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free พร้อมให้ใช้งานใน Go แล้ว ใช้ฟรีในช่วงเวลาจำกัด",
"go.title": "OpenCode Go | โมเดลเขียนโค้ดราคาประหยัดสำหรับทุกคน",
"go.meta.description":
"Go มีราคา $10/เดือน พร้อมขีดจำกัดการใช้งานที่เอื้อเฟื้อและการเข้าถึงโมเดลเขียนโค้ดชั้นนำอย่างเชื่อถือได้",
-1
View File
@@ -205,7 +205,6 @@ export const dict = {
"Tüm Zen modelleri ABD'de barındırılmaktadır. Sağlayıcılar sıfır saklama politikası izler ve verilerinizi model eğitimi için kullanmaz; şu",
"zen.privacy.exceptionsLink": "aşağıdaki istisnalar",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free artık Go'da sınırlı bir süre için ücretsiz sunuluyor.",
"go.title": "OpenCode Go | Herkes için düşük maliyetli kodlama modelleri",
"go.meta.description":
"Go ayda 10$'dır; cömert kullanım limitleri ve önde gelen kodlama modellerine güvenilir erişim sunar.",
-1
View File
@@ -203,7 +203,6 @@ export const dict = {
"Усі моделі Zen розміщені в США. Провайдери дотримуються політики нульового зберігання та не використовують ваші дані для навчання моделей, за",
"zen.privacy.exceptionsLink": "такими винятками",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free уже доступна в Go безкоштовно протягом обмеженого часу.",
"go.title": "OpenCode Go | Недорогі моделі кодування для всіх",
"go.meta.description":
"Go коштує $10/місяць, зі щедрими лімітами використання та надійним доступом до провідних моделей для кодування.",
-1
View File
@@ -193,7 +193,6 @@ export const dict = {
"zen.privacy.beforeExceptions": "所有 Zen 模型均托管在美国。提供商遵循零留存政策,不使用您的数据进行模型训练,",
"zen.privacy.exceptionsLink": "以下例外情况除外",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free 现已上线 Go,限时免费。",
"go.title": "OpenCode Go | 人人可用的低成本编程模型",
"go.meta.description": "Go 每月 $10,提供充裕的使用限额,并可可靠访问领先的编程模型。",
"go.hero.title": "人人可用的低成本编程模型",
-1
View File
@@ -192,7 +192,6 @@ export const dict = {
"zen.privacy.beforeExceptions": "所有 Zen 模型均在美國託管。供應商遵循零留存政策,不會將你的資料用於模型訓練,並且有",
"zen.privacy.exceptionsLink": "以下例外情況",
"go.promo.minimaxM31FlashFree": "MiniMax M3.1 Flash Free 現已上線 Go,限時免費。",
"go.title": "OpenCode Go | 低成本全民編碼模型",
"go.meta.description": "Go 每月 $10,提供充裕的使用限額,並可穩定存取領先的編碼模型。",
"go.hero.title": "低成本全民編碼模型",
+1 -7
View File
@@ -30,7 +30,7 @@ import { LocaleLinks } from "~/component/locale-links"
import { SocialMeta } from "~/component/social-meta"
const models = [
{ name: "MiniMax M3.1 Flash Free", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "MiniMax M3.1 Flash", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "LongCat 2.5 Preview Free", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "Step 5 Preview", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "Beam Free", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
@@ -83,12 +83,6 @@ export default function Home() {
<div data-component="content">
<section data-component="hero">
<div data-component="desktop-app-banner">
<span data-slot="badge">{i18n.t("home.banner.badge")}</span>
<div data-slot="content">
<span data-slot="text">{i18n.t("go.promo.minimaxM31FlashFree")}</span>
</div>
</div>
<Show when={searchParams.ref}>
<aside data-component="referral-ended-notice" aria-label={i18n.t("go.referral.ended.label")}>
<strong>{i18n.t("go.referral.ended.label")}</strong>
+1 -1
View File
@@ -4,7 +4,7 @@ FROM ${REGISTRY}/build/base:24.04
SHELL ["/bin/bash", "-lc"]
ARG NODE_VERSION=24.4.0
ARG BUN_VERSION=1.4.2
ARG BUN_VERSION=1.4.4
ENV BUN_INSTALL=/opt/bun
ENV PATH=/opt/bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+6 -5
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.1.2",
"version": "2.1.3",
"name": "@opencode/core",
"type": "module",
"license": "MIT",
@@ -24,7 +24,8 @@
"build": "bun run script/build.ts",
"update-models-snapshot": "bun run script/update-models-snapshot.ts",
"test": "bun run script/test.ts",
"typecheck": "tsc -b tsconfig.json tsconfig.tests.json"
"typecheck": "bun check --no-script -b -p tsconfig.tests.json",
"typecheck:tsc": "tsc -b tsconfig.json tsconfig.tests.json"
},
"exports": {
"./*": "./src/*.ts"
@@ -78,7 +79,7 @@
"@ai-sdk/openai-compatible": "2.0.41",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@modelcontextprotocol/server": "2.0.0",
"@modelcontextprotocol/server": "2.3.1",
"@opencode/http-recorder": "workspace:*",
"@parcel/watcher-darwin-arm64": "2.5.1",
"@parcel/watcher-darwin-x64": "2.5.1",
@@ -104,8 +105,8 @@
"@ff-labs/fff-bun": "0.10.5",
"@ff-labs/fff-node": "0.10.5",
"@lydell/node-pty": "catalog:",
"@modelcontextprotocol/client": "2.0.0",
"@modelcontextprotocol/core": "2.0.0",
"@modelcontextprotocol/client": "2.3.1",
"@modelcontextprotocol/core": "2.3.1",
"@opencode-ai/pty": "0.3.1",
"@opencode/ai": "workspace:*",
"@opencode/codemode": "workspace:*",
+1 -1
View File
@@ -24,7 +24,7 @@ if ((await $`npm view ${pkg.name}@${pkg.version} version`.nothrow()).exitCode ==
}
try {
await $`bun run typecheck`
await $`bun run typecheck:tsc`
await $`bun run build`
pkg.exports = Object.fromEntries(
Object.entries(pkg.exports).map(([key, value]) => {
+3 -6
View File
@@ -40,7 +40,7 @@ export type Editor = {
export interface Interface extends State.Transformable<Editor> {
readonly get: (id: ID) => Effect.Effect<Info | undefined>
readonly resolve: (id?: ID | string) => Effect.Effect<Info | undefined>
readonly select: (id?: ID | string) => Effect.Effect<Selection>
readonly select: (id?: ID) => Effect.Effect<Selection>
readonly list: () => Effect.Effect<Info[]>
}
@@ -55,7 +55,7 @@ const layer = Layer.effect(
const selectedDefault = (data: Data) => {
const configured = data.default ? selectable(data.agents.get(data.default)) : undefined
if (configured) return configured
const build = selectable(data.agents.get(ID.make("build")))
const build = selectable(data.agents.get(defaultID))
if (build) return build
for (const agent of data.agents.values()) {
const fallback = selectable(agent)
@@ -101,10 +101,7 @@ const layer = Layer.effect(
return selectedDefault(state.get())
}),
select: Effect.fn("Agent.select")(function* (id) {
if (id !== undefined) {
const selected = ID.make(id)
return { id: selected, info: state.get().agents.get(selected) }
}
if (id !== undefined) return { id, info: state.get().agents.get(id) }
const info = selectedDefault(state.get())
return { id: info?.id ?? defaultID, info }
}),
+7 -8
View File
@@ -2,14 +2,13 @@ export * as CodeModeCatalog from "./catalog.js"
import { Schema } from "effect"
export const Tool = Schema.Struct({
type: Schema.Literal("tool"),
name: Schema.String,
description: Schema.String,
signature: Schema.String,
pinned: Schema.optionalKey(Schema.Boolean),
})
export type Tool = typeof Tool.Type
export type Tool = {
readonly type: "tool"
readonly name: string
readonly description: string
readonly signature: string
readonly pinned?: boolean
}
export type Namespace = {
readonly type: "namespace"
+4 -2
View File
@@ -1,6 +1,7 @@
export * as CodeModeWeb from "./web.js"
import { Extension } from "@opencode/codemode"
import { isRecord } from "@opencode/ai/utils/record"
const TIMEOUT_MS = 30_000
@@ -43,6 +44,7 @@ export const extension = Extension.make({ name: "web", globals: { fetch } })
/** What to show for a fetch call: its method and URL. */
export const display = (args: ReadonlyArray<unknown>) => {
const [input, init] = args as [string | URL, Init | undefined]
return { method: init?.method?.toUpperCase() ?? "GET", url: String(input) }
const [input, init] = args
const method = isRecord(init) && typeof init.method === "string" ? init.method.toUpperCase() : "GET"
return { method, url: String(input) }
}
+9
View File
@@ -476,6 +476,15 @@ function normalizeExperimental(
)
if (value !== undefined) result.todo = value
}
if (own(experimental, "precompute_compaction")) {
const value = decodeEncoded(
ConfigExperimental.Info.fields.precompute_compaction,
experimental.precompute_compaction,
["experimental", "precompute_compaction"],
diagnostics,
)
if (value !== undefined) result.precompute_compaction = value
}
if (own(experimental, "subagent_depth")) {
const value = decodeEncoded(
ConfigExperimental.Info.fields.subagent_depth,
+16 -11
View File
@@ -26,10 +26,11 @@ const legacySources = [
const sourceDirectories = ["agent", "agents", "mode", "modes"] as const
const decodeAgent = Schema.decodeUnknownOption(ConfigAgent.Info)
const decodeLegacyAgent = Schema.decodeUnknownOption(ConfigAgentV1.Info)
const decodeConfig = Schema.decodeUnknownOption(Info)
type PathAction = FileAccess.ExternalDirectoryAuthorization["action"] | typeof ReadTool.name | typeof EditTool.name
const pathActions = ["external_directory", "read", "edit"] as const satisfies readonly PathAction[]
const agentKeys = new Set(["variant", ...Object.keys(ConfigAgent.Info.fields)])
// Fields only V2 understands. A file that uses any of them is read as V2, whatever else it contains.
const nativeKeys = ["permissions", "request", "system", "disabled"]
export const Plugin = define({
id: "opencode.config.agent",
@@ -43,7 +44,7 @@ export const Plugin = define({
const files = yield* discover(fs, entry.path)
return yield* Effect.forEach(files, (file) =>
fs.readFileStringSafe(file.filepath).pipe(
Effect.map((content) => (content ? decode(file, content) : undefined)),
Effect.flatMap((content) => (content ? decode(file, content) : Effect.succeed(undefined))),
Effect.orElseSucceed(() => undefined),
),
).pipe(Effect.map((documents) => documents.filter((document): document is Document => document !== undefined)))
@@ -174,7 +175,10 @@ function discover(fs: FSUtil.Interface, directory: string) {
)
}
function decode(file: { directory: string; filepath: string; primary: boolean }, content: string) {
const decode = Effect.fnUntraced(function* (
file: { directory: string; filepath: string; primary: boolean },
content: string,
) {
const markdown = ConfigMarkdown.parseOption(content)
if (!markdown) return
const name = path
@@ -183,7 +187,11 @@ function decode(file: { directory: string; filepath: string; primary: boolean },
.replace(/^(agent|agents|mode|modes)\//, "")
.replace(/\.md$/, "")
const body = markdown.content.trim()
const legacy = Object.keys(markdown.data).some((key) => !agentKeys.has(key))
const keys = Object.keys(markdown.data)
const unsupported = keys.filter((key) => !agentKeys.has(key))
const legacy = unsupported.length > 0 && !keys.some((key) => nativeKeys.includes(key))
if (!legacy && unsupported.length > 0)
yield* Effect.logWarning("ignored unsupported agent fields", { path: file.filepath, fields: unsupported })
// Join legacy model + variant without sending native request/permissions through migration.
// Embedded and structured native selections, and a variant without a model, stay unchanged.
const data =
@@ -202,11 +210,8 @@ function decode(file: { directory: string; filepath: string; primary: boolean },
)
: Option.getOrUndefined(decodeAgent({ ...data, system: body }, { errors: "all" }))
if (!agent) return
const info = Option.getOrUndefined(
decodeConfig({
agents: { [name]: file.primary ? { ...agent, mode: "primary" } : agent },
}),
)
if (!info) return
const info = Info.make({
agents: { [name]: file.primary ? ConfigAgent.Info.make({ ...agent, mode: "primary" }) : agent },
})
return new Document({ type: "document", path: AbsolutePath.make(file.filepath), info })
}
})
+3 -7
View File
@@ -3,8 +3,6 @@ export * as ConfigCommandPlugin from "./command.js"
import { define } from "@opencode/plugin/effect/plugin"
import { Info, type Entry } from "@opencode/schema/config"
import { ConfigCommand } from "@opencode/schema/config/command"
import { Model } from "@opencode/schema/model"
import { Provider } from "@opencode/schema/provider"
import { AppProcess } from "@opencode/util/process"
import path from "path"
import { Effect, Option, PubSub, Schema, Stream } from "effect"
@@ -84,11 +82,9 @@ export const Plugin = define({
command.model === undefined
? commandAgent?.model
: {
id: Model.ID.make(command.model.model),
providerID: Provider.ID.make(command.model.providerID),
...(command.model.variant === undefined
? {}
: { variant: Model.VariantID.make(command.model.variant) }),
id: command.model.model,
providerID: command.model.providerID,
...(command.model.variant === undefined ? {} : { variant: command.model.variant }),
}
const text = yield* evaluateTemplate(command.template, input.prompt.text, {
location,
@@ -13,6 +13,7 @@ export const Plugin = define({
const compaction = yield* SessionCompaction.Service
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, compaction.reload())
yield* compaction.transform((editor) => {
editor.configure({ precompute: Config.latest(loaded.entries, "experimental")?.precompute_compaction === true })
for (const entry of loaded.entries) {
if (entry.type !== "document" || !entry.info.compaction) continue
editor.configure({
+94 -16
View File
@@ -1,6 +1,6 @@
export * as V1Migration from "./v1-migration.js"
import { Cause, Effect, Layer, Option, Schema, Semaphore } from "effect"
import { Cause, Effect, Fiber, Layer, Option, Schema, Semaphore } from "effect"
import { Database } from "./database.js"
import { storedAbsolutePath } from "./path.js"
import { SessionMessageTable, SessionTable } from "../session/sql.js"
@@ -11,11 +11,14 @@ import { KVTable } from "../kv/sql.js"
import { EventSequenceTable } from "../event/sql.js"
import { eq, sql } from "drizzle-orm"
import { Global } from "@opencode/util/global"
import { FSUtil } from "@opencode/util/fs-util"
import { existsSync } from "node:fs"
import path from "node:path"
import type { Database as SQLiteDatabase } from "bun:sqlite"
import { Project } from "@opencode/schema/project"
import { Agent } from "@opencode/schema/agent"
import { Project } from "../project.js"
import { AbsolutePath } from "../schema.js"
import { ProjectTable } from "../project/sql.js"
export type SourceMessage = {
readonly id: string
@@ -535,7 +538,9 @@ function updateProgress(progress: Progress) {
if (runtimeState.status === "running") runtimeState = { status: "running", progress }
}
export function run(options: Options = {}): Effect.Effect<RunResult, never, Database.Service | Global.Service> {
export function run(
options: Options = {},
): Effect.Effect<RunResult, never, Database.Service | Global.Service | Project.Service | FSUtil.Service> {
return lock.withPermit(
Effect.gen(function* () {
const db = (yield* Database.Service).db
@@ -588,15 +593,49 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
project.worktree,
]),
)
const directories = new Map<string, { project: Project.Resolved; path: string } | undefined>()
let lookupTimedOut = false
while (true) {
const state = yield* readState(db)
const cursorValue = state?.phase === "sessions" ? state.cursor : undefined
const nextID = yield* db.get<{ id: string; project_id: string; directory: string }>(
cursorValue === undefined
? sql`SELECT id, project_id, directory FROM session ORDER BY id DESC LIMIT 1`
: sql`SELECT id, project_id, directory FROM session WHERE id < ${cursorValue} ORDER BY id DESC LIMIT 1`,
)
const nextID = yield* db.get<{
id: string
project_id: string
workspace_id: string | null
directory: string
path: string | null
time_updated: number
imported: number
}>(sql`
SELECT id, project_id, workspace_id, directory, path, time_updated,
EXISTS (SELECT 1 FROM session_v2 WHERE session_v2.id = session.id) AS imported
FROM session
${cursorValue === undefined ? sql`` : sql`WHERE id < ${cursorValue}`}
ORDER BY id DESC LIMIT 1
`)
if (!nextID) break
const projectID = projects.has(nextID.project_id) ? nextID.project_id : Project.ID.global
// Legacy ACP sessions can store a cwd relative to an unknown process directory.
// Use the project worktree instead, and leave the original V1 row intact.
const directory =
!nextID.directory || storedAbsolutePath(nextID.directory)
? nextID.directory
: (storedAbsolutePath(projects.get(projectID) ?? path.parse(global.data).root) ?? "")
const unowned =
projectID === Project.ID.global &&
nextID.workspace_id === null &&
!nextID.imported &&
directory === nextID.directory
if (unowned && !lookupTimedOut && !directories.has(directory)) {
const resolved = yield* resolveDirectory(directory)
// One hung directory (e.g. a dead network mount) usually means more; leave the rest under global.
if (Option.isNone(resolved)) {
lookupTimedOut = true
yield* Effect.logWarning("Stopped resolving V1 session directories after a timeout", { directory })
}
directories.set(directory, Option.getOrUndefined(resolved))
}
const owner = unowned ? directories.get(directory) : undefined
yield* db
.transaction((tx) =>
Effect.gen(function* () {
@@ -608,24 +647,29 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
set: { value: { phase: "sessions", cursor: nextID.id }, time_updated: Date.now() },
})
.run()
const projectID = projects.has(nextID.project_id) ? nextID.project_id : Project.ID.global
if (projectID !== nextID.project_id)
yield* Effect.logWarning("Reassigned V1 session with missing project", {
sessionID: nextID.id,
projectID: nextID.project_id,
})
// Legacy ACP sessions can store a cwd relative to an unknown process directory.
// Use the project worktree instead, and leave the original V1 row intact.
const directory =
!nextID.directory || storedAbsolutePath(nextID.directory)
? nextID.directory
: (storedAbsolutePath(projects.get(projectID) ?? path.parse(global.data).root) ?? "")
if (directory !== nextID.directory)
yield* Effect.logWarning("Replaced relative V1 session directory", {
sessionID: nextID.id,
directory: nextID.directory,
resolved: directory,
})
if (owner && !projects.has(owner.project.id))
yield* tx
.insert(ProjectTable)
.values({
id: owner.project.id,
worktree: owner.project.canonical,
vcs: owner.project.vcs?.type,
sandboxes: [],
time_active: nextID.time_updated,
})
.onConflictDoNothing()
.run()
yield* tx.run(sql`
INSERT OR IGNORE INTO session_v2 (
id, project_id, workspace_id, parent_id, slug, directory, path, title, version, share_url,
@@ -634,7 +678,7 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
revert, permission, agent, model, time_created, time_updated, time_compacting, time_archived
)
SELECT
id, ${projectID}, workspace_id, parent_id, slug, ${directory}, path, title, version, share_url,
id, ${owner?.project.id ?? projectID}, workspace_id, parent_id, slug, ${directory}, ${owner?.path ?? nextID.path}, title, version, share_url,
summary_additions, summary_deletions, summary_files, summary_diffs, metadata, cost,
tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write,
revert, NULL, agent, model, time_created, time_updated, time_compacting, time_archived
@@ -688,6 +732,7 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
}),
)
.pipe(Effect.orDie)
if (owner && !projects.has(owner.project.id)) projects.set(owner.project.id, owner.project.canonical)
if (runtimeState.status === "running")
runtimeState = {
status: "running",
@@ -718,6 +763,39 @@ export function run(options: Options = {}): Effect.Effect<RunResult, never, Data
)
}
// V1 grouped non-git sessions under global; V2 resolves an owner for each directory.
// Discovery must not publish adoption events for sessions already stored in V2.
// Any failure keeps the session under global. The lookup runs detached so a filesystem or git call
// that ignores interruption cannot stall the migration; Option.none means it timed out.
function resolveDirectory(directory: string) {
return Effect.gen(function* () {
const fiber = yield* Effect.forkDetach(
Effect.gen(function* () {
if (!directory) return
const fs = yield* FSUtil.Service
const normalized = yield* fs
.realPath(path.resolve(FSUtil.windowsPath(directory)))
.pipe(Effect.orElseSucceed(() => undefined))
if (!normalized || !(yield* fs.isDir(normalized))) return
const projects = yield* Project.Service
const project = yield* projects.resolve(AbsolutePath.make(normalized), { persist: false })
return {
project,
path: path.relative(project.directory, normalized).replaceAll("\\", "/"),
}
}),
)
const result = yield* Fiber.join(fiber).pipe(
Effect.catchDefect((defect) =>
Effect.logWarning("Failed to resolve V1 session directory", { directory, defect }).pipe(Effect.as(undefined)),
),
Effect.timeoutOption("5 seconds"),
)
if (Option.isNone(result)) yield* Effect.forkDetach(Fiber.interrupt(fiber))
return result
})
}
function nextPath(options: Options, data: string) {
if (options.nextDatabasePath) return options.nextDatabasePath
if (process.env.OPENCODE_DB === ":memory:") return undefined
+10 -13
View File
@@ -10,17 +10,15 @@ import { FileSystemSearch } from "./filesystem/search.js"
import { Entry, FileSystem, FindInput, Write } from "@opencode/schema/filesystem"
export { Entry, Match, Submatch } from "@opencode/schema/filesystem"
export const ReadInput = Schema.Struct({
path: RelativePath,
})
export type ReadInput = typeof ReadInput.Type
export interface ReadInput {
readonly path: RelativePath
}
export const WriteInput = Schema.Struct({
export interface WriteInput {
/** Absolute, or relative to the location directory. */
path: Schema.String,
data: Schema.Uint8Array,
})
export type WriteInput = typeof WriteInput.Type
readonly path: string
readonly data: Uint8Array
}
export class NotFoundError extends Schema.TaggedError<NotFoundError>()("FileSystem.NotFoundError", {
path: RelativePath,
@@ -59,10 +57,9 @@ export const Content = Schema.Struct({
}).annotate({ identifier: "FileSystem.Content" })
export type Content = typeof Content.Type
export const ListInput = Schema.Struct({
path: Schema.String.pipe(Schema.optional),
})
export type ListInput = typeof ListInput.Type
export interface ListInput {
readonly path?: string
}
export { FindInput, Write }
+6 -7
View File
@@ -2,7 +2,7 @@ export * as FileSystemSearch from "./search.js"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import path from "path"
import { Clock, Context, Deferred, Duration, Effect, Layer, Schema, Scope } from "effect"
import { Clock, Context, Deferred, Duration, Effect, Layer, Scope } from "effect"
import { Fff } from "#fff"
import fuzzysort from "fuzzysort"
import { FileSystem } from "@opencode/schema/filesystem"
@@ -15,10 +15,9 @@ export interface Interface {
readonly find: (input: FileSystem.FindInput) => Effect.Effect<FileSystem.Entry[]>
}
export const Options = Schema.Struct({
fff: Schema.optional(Schema.Boolean),
})
export type Options = typeof Options.Type
export interface Options {
readonly fff?: boolean
}
export class Service extends Context.Service<Service, Interface>()("@opencode/FileSystem/Search") {}
@@ -50,7 +49,7 @@ function search(index: ReturnType<typeof emptyIndex>, input: FileSystem.FindInpu
})
}
export const ripgrepLayer = Layer.effect(
const ripgrepLayer = Layer.effect(
Service,
Effect.gen(function* () {
const location = yield* Location.Service
@@ -181,7 +180,7 @@ export const fffLayer = Layer.effect(
}),
)
export const layer = (options?: Options) =>
const layer = (options?: Options) =>
Layer.unwrap(
Effect.gen(function* () {
const location = yield* Location.Service
+7 -10
View File
@@ -3,17 +3,15 @@ export * as Watcher from "./watcher.js"
// @ts-ignore
import { createWrapper } from "@parcel/watcher/wrapper.js"
import type ParcelWatcher from "@parcel/watcher"
import { FileSystem } from "@opencode/schema/filesystem"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { FSUtil } from "@opencode/util/fs-util"
import { Cause, Context, Effect, Layer, PubSub, RcMap, Schema, Stream } from "effect"
import { Cause, Context, Effect, Layer, PubSub, RcMap, Stream } from "effect"
import { lazy } from "../util/lazy.js"
import { watch } from "node:fs"
import path from "path"
import loadBinding from "./watcher-binding.js"
const SUBSCRIBE_TIMEOUT_MS = 10_000
export const Event = { Updated: FileSystem.Event.Changed }
const watcher = lazy((): typeof ParcelWatcher | undefined => {
try {
@@ -37,7 +35,7 @@ export type WatchInput =
| { readonly path: string; readonly type: "entries"; readonly names: readonly string[] }
| { readonly path: string; readonly type: "directory"; readonly ignore?: readonly string[] }
export type Subscription = {
type Subscription = {
readonly unsubscribe: () => Promise<void>
/** Backend name for logging, e.g. "node" or "fs-events". */
readonly backend?: string
@@ -65,14 +63,13 @@ export interface Interface {
readonly subscribe: (input: WatchInput, onReady?: Effect.Effect<void>) => Effect.Effect<Stream.Stream<Update>>
}
export const Options = Schema.Struct({
enabled: Schema.optional(Schema.Boolean),
})
export type Options = typeof Options.Type
export interface Options {
readonly enabled?: boolean
}
export class Service extends Context.Service<Service, Interface>()("@opencode/Watcher") {}
export interface TestInterface extends Interface {
interface TestInterface extends Interface {
/** Delivers one update to every active watch whose target covers `update.path`. */
readonly emit: (update: Update) => Effect.Effect<void>
/** Returns every subscribe call observed so far, in order. */
@@ -233,7 +230,7 @@ export const nativeLayer = Layer.succeed(
}),
)
export const nativeNode = makeGlobalNode({ service: Native, layer: nativeLayer, deps: [] })
const nativeNode = makeGlobalNode({ service: Native, layer: nativeLayer, deps: [] })
export function configured(options?: Options) {
return makeGlobalNode({ service: Service, layer: layer(options), deps: [nativeNode] })
+41 -21
View File
@@ -34,6 +34,7 @@ import { McpStdio } from "./stdio.js"
const DEFAULT_STARTUP_TIMEOUT = 30_000
const DEFAULT_CATALOG_TIMEOUT = 30_000
const DEFAULT_EXECUTION_TIMEOUT = 12 * 60 * 60 * 1_000 // 12 hours
const ATTACHED_EXECUTION_TIMEOUT = 10 * 60 * 1_000 // 10 minutes
const TERMINATE_TIMEOUT = 1_000
const toError = (error: unknown) => (error instanceof Error ? error : new Error(String(error)))
@@ -137,6 +138,12 @@ export interface Connection {
readonly onResourcesChanged: (callback: () => void) => void
}
/** An MCP server reached over a transport someone else already opened, such as a client socket. */
export interface Attached {
readonly type: "attached"
readonly transport: Transport
}
/**
* Connects an MCP server; closing the calling scope tears down the transport and any spawned process.
* A stdio server is spawned through the location's `Environment`, so it runs wherever the location's
@@ -144,7 +151,7 @@ export interface Connection {
*/
export const connect = Effect.fnUntraced(function* (
server: string,
config: typeof ConfigMCP.Server.Type,
config: typeof ConfigMCP.Server.Type | Attached,
directory: string,
// Remote only. A provider with no stored token and a no-op redirect ends in UnauthorizedError → needs_auth.
authProvider?: OAuthClientProvider,
@@ -153,6 +160,10 @@ export const connect = Effect.fnUntraced(function* (
) {
// The SDK takes list-changed handlers at construction, but consumers register after connect. On a
// modern connection the SDK opens the subscriptions/listen stream behind these itself.
const timeout: (typeof ConfigMCP.Server.Type)["timeout"] =
config.type === "attached" ? { execution: ATTACHED_EXECUTION_TIMEOUT } : config.timeout
// Attached clients run ordinary SDK servers over the initialize handshake.
const protocol = config.type === "attached" ? "legacy" : config.protocol
const changed = { tools: () => {}, prompts: () => {}, resources: () => {} }
const listChanged = (key: keyof typeof changed) => ({
autoRefresh: false,
@@ -182,7 +193,11 @@ export const connect = Effect.fnUntraced(function* (
)
const initialize = Effect.fnUntraced(function* (transport: Transport) {
const runFork = Effect.runForkWith(yield* Effect.context())
// SDK callbacks run outside any fiber. They must run with this context so events they publish keep
// the server's Location; clients drop unlocated `form.created` events and elicitations then hang.
const context = yield* Effect.context()
const runFork = Effect.runForkWith(context)
const runPromise = Effect.runPromiseWith(context)
const client = new Client(clientInfo, {
capabilities: {
...(elicitation ? { elicitation: { form: {}, url: {} } } : {}),
@@ -190,7 +205,7 @@ export const connect = Effect.fnUntraced(function* (
// Some legacy servers refuse to run without one (https://github.com/anomalyco/opencode/issues/2308).
roots: {},
},
versionNegotiation: negotiation(config.protocol),
versionNegotiation: negotiation(protocol),
listChanged: {
tools: listChanged("tools"),
prompts: listChanged("prompts"),
@@ -206,16 +221,15 @@ export const connect = Effect.fnUntraced(function* (
client.setRequestHandler("roots/list", () => ({ roots: [{ uri: pathToFileURL(directory).href }] }))
if (elicitation) {
client.setRequestHandler("elicitation/create", (request, ctx) =>
Effect.runPromise(elicitation.create({ server, params: request.params, signal: ctx.mcpReq.signal })),
runPromise(elicitation.create({ server, params: request.params, signal: ctx.mcpReq.signal })),
)
client.setNotificationHandler("notifications/elicitation/complete", (notification) =>
Effect.runPromise(elicitation.complete({ server, elicitationID: notification.params.elicitationId })),
runPromise(elicitation.complete({ server, elicitationID: notification.params.elicitationId })),
)
}
yield* Effect.tryPromise({
try: (signal) =>
client.connect(transport, { timeout: config.timeout?.startup ?? DEFAULT_STARTUP_TIMEOUT, signal }),
try: (signal) => client.connect(transport, { timeout: timeout?.startup ?? DEFAULT_STARTUP_TIMEOUT, signal }),
catch: (error) => error,
}).pipe(Effect.onError(() => Effect.promise(() => transport.close()).pipe(Effect.ignore)))
return client
@@ -244,6 +258,7 @@ export const connect = Effect.fnUntraced(function* (
}
const exit = yield* Effect.gen(function* () {
if (config.type === "attached") return yield* initialize(config.transport)
if (config.type === "local") {
const [command, ...args] = config.command
const transport = yield* McpStdio.make({
@@ -265,8 +280,7 @@ export const connect = Effect.fnUntraced(function* (
// Servers that bundle their own Code Mode (Cloudflare and others) expose raw tools when asked
// with ?codemode=false, which is what our Code Mode wants. The configured URL stays the OAuth identity.
const url = new URL(config.url)
const addedCodemode =
config.codemode !== false && !url.searchParams.has("codemode") && !rejectsUnknownQuery(url)
const addedCodemode = config.codemode !== false && !url.searchParams.has("codemode") && !rejectsUnknownQuery(url)
if (addedCodemode) url.searchParams.set("codemode", "false")
const open = Effect.fnUntraced(function* (url: URL) {
session.transport = new StreamableHTTPClientTransport(url, {
@@ -278,7 +292,7 @@ export const connect = Effect.fnUntraced(function* (
})
// Every attempt opens a fresh transport; no retry starts once the startup timeout has passed.
const deadline = (yield* Clock.currentTimeMillis) + (config.timeout?.startup ?? DEFAULT_STARTUP_TIMEOUT)
const deadline = (yield* Clock.currentTimeMillis) + (timeout?.startup ?? DEFAULT_STARTUP_TIMEOUT)
return yield* retrying(
"MCP connect",
open(url).pipe(
@@ -315,14 +329,14 @@ export const connect = Effect.fnUntraced(function* (
yield* Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
}),
)
const catalog = { timeout: config.timeout?.catalog ?? DEFAULT_CATALOG_TIMEOUT }
const execution = config.timeout?.execution ?? DEFAULT_EXECUTION_TIMEOUT
const catalog = { timeout: timeout?.catalog ?? DEFAULT_CATALOG_TIMEOUT }
const execution = timeout?.execution ?? DEFAULT_EXECUTION_TIMEOUT
const request = <A>(what: string, run: (signal: AbortSignal) => Promise<A>) =>
Effect.tryPromise({ try: run, catch: failure }).pipe(
Effect.tapError((error) => Effect.logWarning(`failed to ${what}`, { server, error: error.message })),
)
// Listing is read-only, so a transient failure is safe to retry.
const list = <A>(what: string, run: () => Promise<A>) =>
const list = <A>(what: string, run: (signal: AbortSignal) => Promise<A>) =>
retrying(what, Effect.tryPromise({ try: run, catch: (error) => error })).pipe(
Effect.mapError(failure),
Effect.tapError((error) => Effect.logWarning(`failed to ${what}`, { server, error: error.message })),
@@ -333,28 +347,33 @@ export const connect = Effect.fnUntraced(function* (
const advertised = (capability: "tools" | "prompts" | "resources") =>
Boolean(client.getServerCapabilities()?.[capability])
return {
// Annotated rather than `satisfies`: the inferred SDK types are cyclic, so declaration emit needs the named type.
const connection: Connection = {
modern: client.getProtocolEra() === "modern",
instructions: client.getInstructions()?.trim() || undefined,
tools: () =>
advertised("tools")
? list("list MCP tools", () => client.listTools(undefined, catalog)).pipe(Effect.map((r) => r.tools))
? list("list MCP tools", (signal) => client.listTools(undefined, { ...catalog, signal })).pipe(
Effect.map((r) => r.tools),
)
: Effect.succeed([]),
prompts: () =>
advertised("prompts")
? list("list MCP prompts", () => client.listPrompts(undefined, catalog)).pipe(Effect.map((r) => r.prompts))
? list("list MCP prompts", (signal) => client.listPrompts(undefined, { ...catalog, signal })).pipe(
Effect.map((r) => r.prompts),
)
: Effect.succeed([]),
resources: () =>
advertised("resources")
? list("list MCP resources", () => client.listResources(undefined, catalog)).pipe(
? list("list MCP resources", (signal) => client.listResources(undefined, { ...catalog, signal })).pipe(
Effect.map((r) => r.resources),
)
: Effect.succeed([]),
resourceTemplates: () =>
advertised("resources")
? list("list MCP resource templates", () => client.listResourceTemplates(undefined, catalog)).pipe(
Effect.map((r) => r.resourceTemplates),
)
? list("list MCP resource templates", (signal) =>
client.listResourceTemplates(undefined, { ...catalog, signal }),
).pipe(Effect.map((r) => r.resourceTemplates))
: Effect.succeed([]),
readResource: (input) => {
if (!client.getServerCapabilities()?.resources) return Effect.succeed(undefined)
@@ -393,7 +412,8 @@ export const connect = Effect.fnUntraced(function* (
onResourcesChanged: (callback) => {
changed.resources = callback
},
} satisfies Connection
}
return connection
}
const error = Cause.squash(exit.cause)

Some files were not shown because too many files have changed in this diff Show More