Compare commits

...

21 Commits

Author SHA1 Message Date
Kit Langton b57c1cc47c docs: align v2 specification index 2026-08-14 23:36:15 -04:00
Kit Langton 082423126c docs: remove obsolete project api sketch 2026-08-14 23:34:24 -04:00
Kit Langton 7c4fbdd291 docs: remove obsolete sqlite proposal 2026-08-14 23:33:22 -04:00
Kit Langton a01cd34acc docs: remove completed storage plan 2026-08-14 23:32:23 -04:00
Kit Langton d5a58e756f docs: remove obsolete migration plan 2026-08-14 23:28:46 -04:00
Kit Langton e57a1c7930 docs: refresh agent guidance 2026-08-14 23:25:47 -04:00
Kit Langton 98f5e86122 fix(tui): refresh moved tab metadata (#42696) 2026-08-14 23:25:25 -04:00
Kit Langton c42c7f7793 docs(tui): remove completed extraction plan 2026-08-14 23:18:46 -04:00
Kit Langton ab7a0bf65c fix(tui): ignore stray releases on new session controls (#42673) 2026-08-14 20:57:49 -04:00
Kit Langton 552fd40ef8 docs: update contributing guide 2026-08-14 20:54:35 -04:00
Kit Langton 8afcb3870e fix(plugin): derive promise adapter from protocol schemas (#42669) 2026-08-15 00:52:06 +00:00
Kit Langton 014a364dfd docs(core): refresh session architecture 2026-08-14 20:32:06 -04:00
opencode-agent[bot] a45b12cfa4 fix(app): use location VCS state (#42666) 2026-08-15 10:30:46 +10:00
Kit Langton 7484e32f62 refactor(protocol): harden simulation wire contract (#42628) 2026-08-14 20:29:53 -04:00
opencode-agent[bot] 650f7e8cdd chore: generate 2026-08-15 00:20:16 +00:00
Dax 5c7f5840ee feat(core): persist web search provider selection (#42663) 2026-08-14 20:19:02 -04:00
opencode-agent[bot] 08a6d7b619 docs: fix package manager code blocks (#42313)
Co-authored-by: Kit Langton <7587245+kitlangton@users.noreply.github.com>
2026-08-14 20:03:48 -04:00
opencode-agent[bot] 1580e7cc3a chore: generate 2026-08-14 23:41:12 +00:00
Aiden Cline 8640ea3374 minimize system prompt (#42638) 2026-08-14 18:39:27 -05:00
opencode-agent[bot] e6a3b951b5 chore: generate 2026-08-14 22:19:55 +00:00
James Long 62b67f2761 refactor(protocol): move worktree routes out of experimental namespace (#42656) 2026-08-14 18:18:40 -04:00
79 changed files with 1333 additions and 2650 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@opencode-ai/plugin": patch
---
Derive Promise plugin API request and response conversion from the canonical protocol schemas.
+1 -1
View File
@@ -2,7 +2,7 @@
description: "Bump AI sdk dependencies minor / patch versions only"
---
Please read @package.json and @packages/opencode/package.json.
Please read @package.json and @packages/core/package.json.
Your job is to look into AI SDK dependencies, figure out if they have versions that can be upgraded (minor or patch versions ONLY no major ignore major changes).
+1 -9
View File
@@ -6,15 +6,7 @@ subtask: true
commit and push
make sure it includes a prefix like
docs:
tui:
core:
ci:
ignore:
wip:
For anything in the packages/web use the docs: prefix.
Use `type(scope): summary` with one of these types: `feat`, `fix`, `docs`, `chore`, `refactor`, or `test`. The scope is optional.
prefer to explain WHY something was done from an end user perspective instead of
WHAT was done.
+1 -1
View File
@@ -2,7 +2,7 @@
description: Remove AI code slop
---
Check the diff against dev, and remove all AI generated slop introduced in this branch.
Check the diff against `origin/v2`, and remove all AI generated slop introduced in this branch.
This includes:
+7 -7
View File
@@ -1,6 +1,6 @@
---
name: effect
description: Work with Effect v4 / effect-smol TypeScript code in this repo
description: Work with Effect v4 TypeScript code in this repo
---
# Effect
@@ -9,10 +9,10 @@ This codebase uses Effect for typed, composable TypeScript services, schemas, an
## Source Of Truth
Use the current Effect v4 / effect-smol source, not memory or older Effect v2/v3 examples.
Use the current Effect v4 source, not memory or older Effect v2/v3 examples.
1. If `.opencode/references/effect-smol` is missing, clone `https://github.com/Effect-TS/effect-smol` there. Do this in the project, not in the skill folder.
2. Search `.opencode/references/effect-smol` for exact APIs, examples, tests, and naming patterns before answering or implementing Effect-specific code.
1. If `.opencode/references/effect` is missing, clone `https://github.com/Effect-TS/effect` there. Do this in the project, not in the skill folder.
2. Search `.opencode/references/effect` for exact APIs, examples, tests, and naming patterns before answering or implementing Effect-specific code.
3. Also inspect existing repo code for local house style before introducing new patterns.
4. Prefer answers and implementations backed by specific source files or nearby repo examples.
@@ -27,12 +27,12 @@ Use the current Effect v4 / effect-smol source, not memory or older Effect v2/v3
- Keep layer composition explicit. Avoid broad hidden provisioning that makes missing dependencies hard to see.
- In tests, prefer the repo's existing Effect test helpers and live tests for filesystem, git, child process, locks, or timing behavior.
- Do not introduce `any`, non-null assertions, unchecked casts, or older Effect APIs just to satisfy types.
- Do not answer from memory. Verify against `.opencode/references/effect-smol` or nearby code first.
- Do not answer from memory. Verify against `.opencode/references/effect` or nearby code first.
## Testing Patterns
- Use `testEffect(...)` from `packages/opencode/test/lib/effect.ts` for tests that exercise Effect services, layers, runtime context, scoped resources, or platform integrations.
- Use `testEffect(...)` from `packages/core/test/lib/effect.ts` for tests that exercise Effect services, layers, runtime context, scoped resources, or platform integrations.
- Use `it.live(...)` for filesystem, git repositories, HTTP servers, sockets, child processes, locks, real time, and other live platform behavior.
- Run tests from package directories such as `packages/opencode`; never run package tests from the repo root.
- Run tests from package directories such as `packages/core`; never run package tests from the repo root.
- Prefer explicit test layers over ad hoc managed runtimes. Keep dependency provisioning visible in the test file.
- Use scoped fixtures and finalizers for resources that must be cleaned up, including temporary directories, flags, databases, fibers, servers, and global state.
+11 -11
View File
@@ -1,6 +1,6 @@
- After changing the public Protocol or Server `HttpApi`, run `bun run generate` from `packages/client`. Do not edit `src/generated` or `src/generated-effect` directly.
- After changing the public Protocol or Server `HttpApi`, run `bun run generate` from `packages/client`. Do not edit generated client files directly.
- Keep runtime dependencies directed from Schema to Core and Protocol, then from Core and Protocol to Server. Client runtime code may depend on Schema and Protocol but never Core or Server; `sdk-next` composes Client, Core, and Server.
- Do not modify `packages/opencode` unless the user explicitly asks for V1 work. `packages/opencode` is the V1 implementation and is present for reference only. New implementation changes should land in the V2 package set: `packages/core`, `packages/cli`, `packages/server`, `packages/protocol`, `packages/schema`, and related generated client surfaces when required.
- Current implementation changes belong in `packages/core`, `packages/cli`, `packages/server`, `packages/protocol`, `packages/schema`, and related generated client surfaces when required.
- The default branch in this repo is `v2`.
- Base all new branches and worktrees on `v2`, or `origin/v2` when the local `v2` ref is unavailable. Do not base them on `dev`.
- Local `main` ref may not exist; use `v2` or `origin/v2` for diffs.
@@ -166,23 +166,23 @@ const table = sqliteTable("session", {
- Avoid mocks as much as possible, you shouldn't be using globalThis.\* at all unless it's the only option.
- Test actual implementation, do not duplicate logic into tests
- Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package dirs like `packages/opencode`.
- Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package directories such as `packages/core`.
## Type Checking
- Always run `bun typecheck` from package directories (e.g., `packages/opencode`), never `tsc` directly.
- Always run `bun typecheck` from package directories (for example, `packages/core`), never `tsc` directly.
## V2 Session Core
- Keep durable events minimal: record irreducible new facts and do not repeat state derivable by folding the ordered aggregate history. Enrich projections and read models with previous or derived state when consumers need self-contained views.
- Keep durable prompt admission separate from model execution. `SessionV2.prompt(...)` admits one durable `session_pending` row before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. The serialized runner promotes admitted inputs into visible user messages at safe boundaries, consuming the pending row in the same event transaction; `session_pending` stores only unconsumed work.
- Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Retry of an already-promoted input reconciles against the projected message and the durable admitted event rather than a retained row.
- Keep durable prompt admission separate from model execution. `Session.prompt(...)` publishes `session.inbox.enqueued`, whose projection inserts one durable `session_inbox` row, before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. Delivery publishes `session.inbox.delivered`; its projection consumes the inbox row and inserts the visible message in the same transaction. `session_inbox` stores only unconsumed work.
- Reusing a Session ID adopts the existing Session. While a user or synthetic inbox item is pending, reusing its ID reconciles only when Session, type, complete payload, metadata, and delivery match; conflicting reuse fails. Once delivered, retry reconciliation for those message-producing items uses the projected message and does not require retained enqueue history or the original delivery mode. Control items keep their operation-specific conflict behavior.
- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; interruption of a known but idle or locally unowned Session is a no-op, while the public API rejects an unknown Session.
- Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics.
- Preserve one explicit `llm.stream(request)` call per Physical Attempt and reload projected history before durable continuation. Most Steps have one Physical Attempt; overflow-triggered compaction recovery may rebuild one Step for a second attempt. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop.
- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. Advisory wakes drain eligible durable inbox rows only; post-crash continuation recovery requires a separate explicit design before it may retry provider work. A drain has no durable identity or transcript boundary.
- Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe step boundary while the current drain requires continuation. An explicit `queue` input remains pending until the Session would otherwise become idle; promote one queued input at that boundary, then reevaluate continuation before promoting another. Promoting any new user input resets the selected agent's step allowance; a batch of steers resets it once.
- Preserve one explicit `llm.stream(request)` call per Physical Attempt and reload projected history before durable continuation. A logical Step may use generic pre-output retries, one full-context retry after continuation rejection, incomplete-stream continuation, or one overflow-compaction rebuild. Generic retries retain the logical step number and do not consume another agent-step allowance. Do not delegate orchestration to an in-memory tool loop.
- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. A write-ahead execution claim marks a process-local busy period for restart recovery: terminal completion, failure, or user interruption releases it, while shutdown interruption and process death preserve it. Startup recovery resumes claimed top-level Sessions with durable per-execution attempt accounting. The claim is a recovery marker, not clustered ownership, fencing, or an exactly-once guarantee.
- Keep delivery vocabulary explicit. Prompts steer by default. Steers deliver in enqueue order at safe step boundaries, stopping before compaction or move control items. At an idle boundary, steers take priority; otherwise exactly one queued item delivers before the runner reevaluates continuation. Inbox items may be cancelled or changed between queue and steer before delivery. Promoting new user input resets the selected agent's step allowance; a batch of steers resets it once.
- One step is one logical LLM call; its durable record covers only the model-visible span. Do not write "provider turn", and do not use bare "turn" for a single call: "turn" is reserved for the future assistant-turn unit containing all steps from prompt promotion until the session would go idle.
- Keep EventV2 replay owner claims separate from clustered Session execution ownership.
- Keep event replay ownership separate from clustered Session execution ownership.
- Keep the Instructions algebra and built-ins in `src/instructions`; keep instruction producers with their observed domains, and keep Session History selection plus `InstructionState` and `InstructionEntry` persistence Session-owned. `InstructionDiscovery` observes ambient global and upward-project instructions. The runner composes built-ins, discovery, guidance, and entries explicitly in `loadInstructions`; there is no instruction registry.
- `session.instructions.updated` stores only changed source keys and content hashes. Blob values live once in `instruction_blob`; `instruction_state` is a rebuildable fold cache, never primary state. Render initial instructions and chronological updates from values during request assembly. Completed compaction moves the instruction epoch; Session movement retains it so destination instruction changes are chronological, while committed revert clears it. Unavailable sources retain the last value and block only the initial complete delta.
- `session.instructions.updated` stores changed source keys and content hashes and may freeze rendered chronological update text. Blob values live once in `instruction_blob`; the projected `instruction_state` row is the normal boundary-processing source of current and initial values. Request assembly renders the epoch baseline from stored values, while later frozen updates enter history as durable System messages. Completed compaction moves the instruction epoch; Session movement retains it so destination instruction changes are chronological, while committed revert clears it. Forks adopt the parent's newest instruction values even when copied message history ends at an earlier boundary. Unavailable sources retain the last value and block only the initial complete delta.
+63 -223
View File
@@ -1,272 +1,112 @@
# Contributing to OpenCode
We want to make it easy for you to contribute to OpenCode. Here are the most common type of changes that get merged:
The changes most likely to be accepted are:
- Bug fixes
- Additional LSPs / Formatters
- Improvements to LLM performance
- Support for new providers
- Fixes for environment-specific quirks
- Additional LSPs and formatters
- LLM performance improvements
- Environment-specific fixes
- Missing standard behavior
- Documentation improvements
However, any UI or core product feature must go through a design review with the core team before implementation.
UI and core product features require design review before implementation. If you are unsure whether a change fits, ask a maintainer or choose an issue labeled [`help wanted`](https://github.com/anomalyco/opencode/issues?q=is%3Aissue%20state%3Aopen%20label%3Ahelp-wanted), [`good first issue`](https://github.com/anomalyco/opencode/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22), [`bug`](https://github.com/anomalyco/opencode/issues?q=is%3Aissue%20state%3Aopen%20label%3Abug), or [`perf`](https://github.com/anomalyco/opencode/issues?q=is%3Aopen%20is%3Aissue%20label%3A%22perf%22).
If you are unsure if a PR would be accepted, feel free to ask a maintainer or look for issues with any of the following labels:
- [`help wanted`](https://github.com/anomalyco/opencode/issues?q=is%3Aissue%20state%3Aopen%20label%3Ahelp-wanted)
- [`good first issue`](https://github.com/anomalyco/opencode/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22)
- [`bug`](https://github.com/anomalyco/opencode/issues?q=is%3Aissue%20state%3Aopen%20label%3Abug)
- [`perf`](https://github.com/anomalyco/opencode/issues?q=is%3Aopen%20is%3Aissue%20label%3A%22perf%22)
Want to take on an issue? Leave a comment and a maintainer may assign it unless it is already being worked on.
> [!NOTE]
> PRs that ignore these guardrails will likely be closed.
Want to take on an issue? Leave a comment and a maintainer may assign it to you unless it is something we are already working on.
## Adding Providers
## Adding New Providers
New providers should rarely require OpenCode changes. Add the provider to [models.dev](https://github.com/anomalyco/models.dev) first.
New providers shouldn't require many if ANY code changes, but if you want to add support for a new provider first make a PR to:
https://github.com/anomalyco/models.dev
## Development
## Developing OpenCode
- Requirements: Bun 1.3+
- Install dependencies and start the dev server from the repo root:
```bash
bun install
bun dev
```
### Running against a different directory
By default, `bun dev` runs OpenCode in the `packages/opencode` directory. To run it against a different directory or repository:
OpenCode requires Bun 1.3 or newer. From the repository root:
```bash
bun dev <directory>
bun install
bun dev [directory]
```
To run OpenCode in the root of the opencode repo itself:
`bun dev` runs the V2 CLI and TUI. Pass a directory to open another project, or `.` to open this repository.
To test a development TUI against your installed OpenCode V2 background service and live sessions:
```bash
bun dev .
bun run dev:live [directory]
```
### Building a "localcode"
To compile a standalone executable:
For web development, run the backend and app in separate terminals. Other interfaces have root scripts:
```bash
./packages/opencode/script/build.ts --single
bun dev serve --port 4096
bun run dev:web
bun run dev:desktop
bun run dev:www
```
Then run it with:
### Packages
- `packages/schema`: shared wire and storage contracts
- `packages/core`: domain behavior and persistence
- `packages/protocol`: public API definitions
- `packages/server`: HTTP server and runtime composition
- `packages/client`: generated TypeScript clients
- `packages/cli`: command-line entrypoint and service lifecycle
- `packages/tui`: terminal interface
- `packages/app`: shared web interface
- `packages/desktop`: Electron desktop application
- `packages/plugin`: plugin API
### Verification
Run typechecks, and tests where defined, from the affected package rather than the repository root:
```bash
./packages/opencode/dist/opencode-<platform>/bin/opencode
cd packages/core
bun run test
bun typecheck
```
Replace `<platform>` with your platform (e.g., `darwin-arm64`, `linux-x64`).
Follow package-specific instructions in nearby `AGENTS.md` files. After changing the public Protocol or Server `HttpApi`, run `bun run generate` from `packages/client`; never edit generated client files directly.
- Core pieces:
- `packages/opencode`: OpenCode core business logic & server.
- `packages/opencode/src/cli/cmd/tui/`: The TUI code, written in SolidJS with [opentui](https://github.com/sst/opentui)
- `packages/app`: The shared web UI components, written in SolidJS
- `packages/desktop`: The native desktop app, built with Electron (wraps `packages/app`)
- `packages/plugin`: Source for `@opencode-ai/plugin`
Follow the repository [style guide](./AGENTS.md).
### Understanding bun dev vs opencode
## Pull Requests
During development, `bun dev` is the local equivalent of the built `opencode` command. Both run the same CLI interface:
### Link Issues When Required
```bash
# Development (from project root)
bun dev --help # Show all available commands
bun dev serve # Start headless API server
bun dev web # Start server + open web interface
bun dev <directory> # Start TUI in specific directory
Bug fixes, chores, and tests must reference an existing issue. Documentation, refactor, and feature PRs are exempt from the automated linked-issue check. When required, use `Fixes #123` or `Closes #123` in the PR description.
# Production
opencode --help # Show all available commands
opencode serve # Start headless API server
opencode web # Start server + open web interface
opencode <directory> # Start TUI in specific directory
```
Before implementing new functionality, open a feature request describing the problem, why it belongs in OpenCode, and your proposed approach if you have one. Wait for design approval before opening the implementation PR.
### Running the API Server
Base branches on `v2`, not `dev`, and complete the provided pull request template.
To start the OpenCode headless API server:
### Keep It Focused
```bash
bun dev serve
```
- Keep PRs small and focused.
- Explain the problem and why the change fixes it.
- Check whether the functionality already exists.
- For UI changes, include before-and-after screenshots or video.
- For logic changes, explain what you tested and how a reviewer can verify it.
This starts the headless server on port 4096 by default. You can specify a different port:
### Keep It Brief
```bash
bun dev serve --port 8080
```
Long, AI-generated PR descriptions and issues may be ignored. Write a short explanation in your own words. If the change cannot be explained briefly, the PR may be too large.
### Running the Web App
### Use Conventional Titles
To test UI changes during development:
1. **First, start the OpenCode server** (see [Running the API Server](#running-the-api-server) section above)
2. **Then run the web app:**
```bash
bun run --cwd packages/app dev
```
This starts a local dev server at http://localhost:5173 (or similar port shown in output). Most UI changes can be tested here, but the server must be running for full functionality.
### Running the Desktop App
The desktop app is an Electron application that wraps the web UI.
To run the desktop app in development:
```bash
bun run --cwd packages/desktop dev
```
To create a production build and package the app:
```bash
bun run --cwd packages/desktop build
bun run --cwd packages/desktop package
```
> [!NOTE]
> If you make changes to the API or SDK (e.g. `packages/opencode/src/server/server.ts`), run `./script/generate.ts` to regenerate the SDK and related files.
Please try to follow the [style guide](./AGENTS.md)
### Setting up a Debugger
Bun debugging is currently rough around the edges. We hope this guide helps you get set up and avoid some pain points.
The most reliable way to debug OpenCode is to run it manually in a terminal via `bun run --inspect=<url> dev ...` and attach
your debugger via that URL. Other methods can result in breakpoints being mapped incorrectly, at least in VSCode (YMMV).
Caveats:
- If you want to run the OpenCode TUI and have breakpoints triggered in the server code, you might need to run `bun dev spawn` instead of
the usual `bun dev`. This is because `bun dev` runs the server in a worker thread and breakpoints might not work there.
- If `spawn` does not work for you, you can debug the server separately:
- Debug server: `bun run --inspect=ws://localhost:6499/ --cwd packages/opencode ./src/index.ts serve --port 4096`,
then attach TUI with `opencode attach http://localhost:4096`
- Debug TUI: `bun run --inspect=ws://localhost:6499/ --cwd packages/opencode --conditions=browser ./src/index.ts`
Other tips and tricks:
- You might want to use `--inspect-wait` or `--inspect-brk` instead of `--inspect`, depending on your workflow
- Specifying `--inspect=ws://localhost:6499/` on every invocation can be tiresome, you may want to `export BUN_OPTIONS=--inspect=ws://localhost:6499/` instead
#### VSCode Setup
If you use VSCode, you can use our example configurations [.vscode/settings.example.json](.vscode/settings.example.json) and [.vscode/launch.example.json](.vscode/launch.example.json).
Some debug methods that can be problematic:
- Debug configurations with `"request": "launch"` can have breakpoints incorrectly mapped and thus unusable
- The same problem arises when running OpenCode in the VSCode `JavaScript Debug Terminal`
With that said, you may want to try these methods, as they might work for you.
## Pull Request Expectations
### Issue First Policy
**All PRs must reference an existing issue.** Before opening a PR, open an issue describing the bug or feature. This helps maintainers triage and prevents duplicate work. PRs without a linked issue may be closed without review.
- Use `Fixes #123` or `Closes #123` in your PR description to link the issue
- For small fixes, a brief issue is fine - just enough context for maintainers to understand the problem
### General Requirements
- Keep pull requests small and focused
- Explain the issue and why your change fixes it
- Before adding new functionality, ensure it doesn't already exist elsewhere in the codebase
### UI Changes
If your PR includes UI changes, please include screenshots or videos showing the before and after. This helps maintainers review faster and gives you quicker feedback.
### Logic Changes
For non-UI changes (bug fixes, new features, refactors), explain **how you verified it works**:
- What did you test?
- How can a reviewer reproduce/confirm the fix?
### No AI-Generated Walls of Text
Long, AI-generated PR descriptions and issues are not acceptable and may be ignored. Respect the maintainers' time:
- Write short, focused descriptions
- Explain what changed and why in your own words
- If you can't explain it briefly, your PR might be too large
### PR Titles
PR titles should follow conventional commit standards:
- `feat:` new feature or functionality
- `fix:` bug fix
- `docs:` documentation or README changes
- `chore:` maintenance tasks, dependency updates, etc.
- `refactor:` code refactoring without changing behavior
- `test:` adding or updating tests
You can optionally include a scope to indicate which package is affected:
- `feat(app):` feature in the app package
- `fix(desktop):` bug fix in the desktop package
- `chore(opencode):` maintenance in the opencode package
Use `type(scope): summary`. Supported types are `feat`, `fix`, `docs`, `chore`, `refactor`, and `test`. The scope is optional.
Examples:
- `docs: update contributing guidelines`
- `fix: resolve crash on startup`
- `feat: add dark mode support`
- `feat(app): add dark mode support`
- `fix(desktop): resolve crash on startup`
- `chore: bump dependency versions`
- `docs: update contributing guide`
- `fix(tui): restore scroll position`
- `feat(app): add workspace search`
### Style Preferences
## Issues
These are not strictly enforced, they are just general guidelines:
Bug reports and feature requests must use their issue templates. Blank issues are not allowed; ask support and how-to questions in the [Discord community](https://discord.gg/opencode).
- **Functions:** Keep logic within a single function unless breaking it out adds clear reuse or composition benefits.
- **Destructuring:** Do not do unnecessary destructuring of variables.
- **Control flow:** Avoid `else` statements.
- **Error handling:** Prefer `.catch(...)` instead of `try`/`catch` when possible.
- **Types:** Reach for precise types and avoid `any`.
- **Variables:** Stick to immutable patterns and avoid `let`.
- **Naming:** Choose concise single-word identifiers when they remain descriptive.
- **Runtime APIs:** Use Bun helpers such as `Bun.file()` when they fit the use case.
## Feature Requests
For net-new functionality, start with a design conversation. Open an issue describing the problem, your proposed approach (optional), and why it belongs in OpenCode. The core team will help decide whether it should move forward; please wait for that approval instead of opening a feature PR directly.
## Issue Requirements
All issues **must** use one of our issue templates:
- **Bug report** — for reporting bugs (requires a description)
- **Feature request** — for suggesting enhancements (requires verification checkbox and description)
- **Question** — for asking questions (requires the question)
Blank issues are not allowed. When a new issue is opened, an automated check verifies that it follows a template and meets our contributing guidelines. If an issue doesn't meet the requirements, you'll receive a comment explaining what needs to be fixed and have **2 hours** to edit the issue. After that, it will be automatically closed.
Issues may be flagged for:
- Not using a template
- Required fields left empty or filled with placeholder text
- AI-generated walls of text
- Missing meaningful content
If you believe your issue was incorrectly flagged, let a maintainer know.
Automated checks flag missing templates, placeholder text, AI-generated walls of text, and missing meaningful content. You have two hours to correct a flagged issue before it closes automatically. Ask a maintainer if an issue was flagged incorrectly.
+1
View File
@@ -568,6 +568,7 @@
"@ai-sdk/provider": "3.0.8",
"@opencode-ai/ai": "workspace:*",
"@opencode-ai/client": "workspace:*",
"@opencode-ai/protocol": "workspace:*",
"@opencode-ai/schema": "workspace:*",
"@opencode-ai/sdk": "1.18.5",
"@standard-schema/spec": "catalog:",
+34 -29
View File
@@ -27,8 +27,9 @@ exits before expensive server boot. The design does not require clients to
agree on a single initiator.
This proposal does not introduce a supervisor process, warm candidate server,
protocol negotiation, idle background restart, or general execution-recovery
framework.
protocol negotiation, idle background restart, or clustered or exactly-once
execution recovery. Session execution separately provides bounded local recovery
through durable write-ahead claims.
## Architecture at a Glance
@@ -176,9 +177,9 @@ This design gives each concept one authority.
- Adding a permanent steward, proxy, or supervisor process.
- Zero-downtime worker handoff or automatic rollback.
- Application protocol negotiation or automatic TUI self-restart.
- General hard-crash recovery for active Sessions.
- Defining recovery semantics for provider attempts, tools, shells, sub-agents,
permissions, questions, or background jobs.
- Exactly-once recovery for provider attempts, tools, shells, sub-agents,
permissions, questions, or background jobs. Top-level Session continuation
after process death is handled separately through durable execution claims.
- Automatically killing a frozen owner.
- Bounding concurrent location cold boots after clients reconnect.
- Multi-machine or clustered service placement.
@@ -202,9 +203,10 @@ This design gives each concept one authority.
diagnosed, non-retryable cause.
8. **Clients do not kill an unresponsive owner automatically.** Destructive
recovery requires the explicit `service restart` command.
9. **Lifecycle does not promise execution semantics.** Graceful replacement
invokes Session suspension and resumption hooks, but tool-level continuity
belongs to a separate design.
9. **Lifecycle does not promise exactly-once execution.** A successor invokes
the Session execution-claim sweep, which resumes from durable history.
Provider-attempt identity and tool-side-effect fencing belong to separate
designs.
## System Model
@@ -485,23 +487,20 @@ The UI derives text from status:
| `ready` | Normal TUI |
## Session Continuity
Every process-local Session busy period writes a durable execution claim before
resumption hooks:
its runner starts. Success, failure, and user interruption release the claim;
shutdown interruption and process death leave it intact. The
successor sweeps claimed top-level Sessions, durably counts a recovery attempt,
appends a continuation instruction, and resumes from projected history. The same
mechanism covers graceful replacement, crash, SIGKILL, and runtime eviction.
Recovery fails stale running tool projections before further model work, but it
2. The successor schedules those Sessions for continuation.
3. The runner reloads durable Session history before continuing.
This lifecycle design does not define what an interrupted physical provider
attempt or tool invocation means. It does not promise that external side effects
did not occur, replay the exact interrupted tool, preserve an in-memory form, or
recover process-local background work.
Those concerns require a separate execution-continuity design covering tools,
shells, sub-agents, permissions, questions, provider attempts, and hard-crash
recovery.
does not prove whether an interrupted provider request or external operation
already took effect. It does not replay the exact interrupted tool, preserve an
in-memory form, recover process-local background work, or guarantee exactly-once
provider or tool behavior.
## Unresponsive Owner
An unreachable registration does not prove that the owner is dead. A contender
@@ -531,13 +530,15 @@ Automatic frozen-owner recovery is deferred.
1. The old service installs vNext but keeps running.
2. A fresh vNext TUI finds the healthy vOld service and requests graceful stop.
3. The old service reports `stopping` and exits. Shutdown interruption preserves
4. Open TUIs enter their indefinite status loops.
the execution claims already written by active Sessions.
4. Open TUIs enter their indefinite status loops.
5. One or more clients spawn contenders.
6. One contender acquires the service lock. Losers exit before heavy boot.
7. The winner binds and registers the lifecycle shell as `starting`.
8. Clients stop spawning and wait on the observable winner.
9. The winner initializes the application, sweeps orphaned execution claims,
10. TUIs rebuild clients, reconcile state, and resume.
and reports `ready`.
10. TUIs rebuild clients, reconcile state, and resume.
### Server crashes while ready
@@ -546,7 +547,9 @@ Automatic frozen-owner recovery is deferred.
3. Process death has released the service lock.
4. One contender wins, replaces registration, and starts normally.
5. Application startup sweeps orphaned top-level execution claims and resumes
them with bounded attempt accounting. External side effects remain
potentially ambiguous.
### Winner crashes during startup
1. Clients observed `starting` and remain alive.
@@ -650,8 +653,9 @@ was the observed incident cost.
6. **Codify launch versus reconnect.** Fresh launch enforces installed version;
reconnect never activates replacement.
7. **Integrate Session continuity.** Preserve current background-install and
fresh-launch activation behavior while invoking Session continuity hooks.
8. **Harden explicit recovery.** Verify exact process identity during explicit
fresh-launch activation behavior while invoking startup execution-claim
recovery.
8. **Harden explicit recovery.** Verify exact process identity during explicit
`service restart`; never automatically kill an unresponsive owner.
9. **Run the full multi-process suite.** Include repeated restart cycles and
assert that no contender or child process remains afterward.
@@ -677,7 +681,8 @@ was the observed incident cost.
- Idle background update activation with an admission fence.
- Application protocol compatibility and automatic local TUI re-exec.
- Stronger execution recovery with provider-attempt identity, tool-side-effect
- Shell, sub-agent, permission, question, and background-job continuity.
idempotency or fencing, and clustered ownership.
- Shell, sub-agent, permission, question, and background-job continuity.
- Automatic recovery for a positively identified frozen owner.
- Cold-boot concurrency limits and interaction-prioritized location loading.
- A steward or socket-handoff architecture if zero-downtime replacement becomes
-298
View File
@@ -1,298 +0,0 @@
# V1 to V2 Database Migration
## Approach
- Use the `dev` branch database schema and migration registry as the V1 baseline.
- Remove migrations that exist only on the V2 branch.
- Generate one canonical migration from the `dev` schema to the final V2 schema.
- Keep the canonical migration focused on schema changes and dropping obsolete tables.
- Run the V1 history backfill through an experimental server endpoint invoked by the CLI before it opens the TUI.
- Show committed session progress while the endpoint runs.
Expose `GET /api/experimental/migration/v1` for status and a blocking `POST /api/experimental/migration/v1` to run or
resume the backfill. The status is `required`, `running`, or `completed`. On startup, the CLI checks status first and
renders no migration UI when it is already complete. For required or running status, it shows a spinner and waits for the
blocking POST without a request timeout. While migration runs, poll GET once per second and render completed and total
session counts. GET derives total from all session rows and completed from rows through the stored cursor; the count
advances only after a session transaction commits. The POST returns `{ status: "completed" }`. Do not add a background
job or streaming progress protocol. Interrupted calls resume from the stored cursor.
Initially, only interactive TUI startup performs this check; noninteractive run, ACP, raw API, service, health, version,
and help flows do not trigger the backfill.
Keep migration behavior in Core: status, semaphore, checkpointing, V1 decoding, transformation, and database writes.
Protocol owns the experimental GET/POST contracts, Server handlers delegate to Core, and the interactive CLI owns only
the status check and spinner presentation.
Guard the endpoint with one process-local Effect `Semaphore`. Concurrent callers wait; after the active call completes,
waiting callers acquire the permit, observe the completion key, and return immediately. No distributed lock is required
for the current single elected server process.
## Preserve
The canonical V1 data remains in its existing tables. In particular, preserve `session`, `message`, and `part` rows.
Preserve `workspace` rows and existing `session.workspace_id` values unchanged. The migration must not clear or rebuild
workspace relationships.
Preserve existing non-null `session.agent` and `session.model` selections. Fill missing values from the latest ordinary
V1 user message ordered by `time_created` and `id`, excluding compaction and subtask-only messages. Copy agent, provider
ID, model ID, and variant, normalizing an absent variant to `default`.
Recompute session usage aggregates from all canonical V1 assistant messages, including compaction or other internal
assistants omitted from the V2 projection. Overwrite session cost and input, output, reasoning, cache-read, and
cache-write token totals with those sums.
Clear persisted `session.revert` state. A staged revert is transient operational state and may refer to omitted projection
rows or unavailable snapshots; it must not resume automatically after upgrading. Preserve the underlying messages,
parts, and file history.
Clear `session.time_compacting`, leave the new `time_suspended` column as `NULL`, and preserve session creation, update,
and archive timestamps. Preserve project `time_initialized`; it is unrelated durable state.
Keep the legacy `todo` table and its data physically unchanged, but do not include it in the final V2 Drizzle schema.
After generation, remove the generated `DROP TABLE todo` statement from the canonical migration so the table remains as
unmanaged legacy storage.
## Per-Session Replacement
Do not truncate `event`, `event_sequence`, or `session_message` globally before the backfill. A whole-table delete can
hold SQLite's writer lock long enough to block the running TUI.
Replace each legacy session's V2 state inside that session's checkpointed migration transaction. Delete `event` rows for
the session aggregate, delete its `session_message` rows, rebuild its projection from canonical V1 `message` and `part`
rows, and overwrite its `event_sequence` watermark. If migration of that session fails, all replacements roll back and
the durable cursor remains at the previously committed session. Rows owned by sessions outside the legacy migration set
remain untouched.
## Message Backfill
Backfill canonical V1 history from `message` and `part` into `session_message`. This is the main data transformation in
the migration. Preserving the V1 tables alone keeps the data safe but does not make existing history visible through the
V2 session APIs, which read `session_message`.
Do not fail the whole migration when a V1 message or part payload cannot be decoded. Skip an undecodable message's V2
projection and log its session and message IDs. Skip an undecodable part while continuing to map its message, and perform
special-message pairing only with decoded rows. Assign sequences after filtering. Leave every malformed source row
untouched in the V1 tables.
Skip and log orphan parts whose source message does not exist and parts with unknown or unsupported types. Continue
migrating the owning message and other valid parts. Include session, message, part ID, and observed type in warnings, and
leave skipped source rows unchanged.
Reuse each V1 `message.id` as the corresponding `session_message.id`. Stable IDs keep the migration deterministic and
avoid rewriting other persisted state that may refer to a message.
For ordinary user and assistant rows, preserve source `message.time_created` and `message.time_updated`. Entirely
synthetic messages preserve their source timestamps, and synthetic rows split from mixed messages use the source user
timestamps. A collapsed compaction uses the compaction user creation time and the later update time of the compaction
user and summary assistant. Keep payload creation/completion times consistent with row timestamps.
Within each session, order V1 messages by `time_created` and then `id`, matching the existing V1 message index. Assign
contiguous `session_message.seq` values starting at `0`.
Map ordinary V1 messages one-to-one by role. Each ordinary V1 user message becomes one V2 `user` row, and each ordinary
V1 assistant message becomes one V2 `assistant` row. Fold the source message's ordered V1 parts into that row's V2
payload.
Keep ordinary messages even when their transformed payload becomes empty after filtering. Preserve an empty V2 user row
with `text: ""` and an empty V2 assistant row with `content: []` so IDs, chronology, and conversation structure remain
stable. Omit only explicitly dropped internal concepts and undecodable messages.
Handle semantic marker parts before applying the ordinary mapping. In particular, a V1 user message containing a
`compaction` part and its paired assistant summary represent one compaction operation, not two ordinary messages. Special
part mappings must be decided explicitly before implementing the backfill.
Do not carry the V1 subtask concept into the V2 projection. Omit user messages containing only `subtask` parts and omit
the paired assistant task-tool messages generated from those markers. For mixed user messages, ignore the `subtask`
parts while preserving ordinary content, and still omit assistant task-tool messages generated by the skipped subtasks.
Keep all source rows unchanged in the V1 `message` and `part` tables.
Map ordinary V1 assistant `text` and `reasoning` parts into the V2 assistant `content` array in part order. Preserve text,
including empty assistant text parts used as structural separators. Map V1 part metadata to optional V2 provider state.
For reasoning, map `time.start` to `time.created` and optional `time.end` to `time.completed`.
Preserve V1 tool parts that are `pending` or `running`, but convert them to terminal V2 tool error states. Preserve the
call ID, tool name, parsed input, metadata, and available start time. Use the assistant message creation time when the V1
state has no start time. Set the error to type `tool.interrupted` with message
`Tool execution was interrupted before V2 migration`. Never resume migrated tool executions.
For a completed V1 tool part, use `callID` as the V2 tool content ID and preserve the tool name and parsed input. Set the
state to `completed`. Convert V1 output into the first text content item and convert stored output attachments into
following file content items with their URI, MIME type, and filename. Preserve state metadata. Map `time.start` to
`time.created` and `time.end` to `time.completed`. When `time.compacted` exists, use
`[Old tool result content cleared]` as the only output and omit attachments.
For a failed V1 tool part, preserve the call ID, tool name, parsed input, metadata, and timestamps, and set the V2 state
to `error`. Convert the V1 error string to a structured error with type `tool.execution`. If V1 metadata contains a string
`output`, preserve it as optional V2 text content. Map `time.start` to `time.created` and `time.end` to `time.completed`.
For an ordinary V1 assistant message, preserve agent, provider ID, model ID, optional variant, creation and completion
times, cost, and input/output/reasoning/cache token counts. Use `default` when the V1 variant is absent. Ignore V1
`tokens.total` because it is derivable and V2 does not persist it.
Use V1 assistant `parentID` only while pairing compactions and skipped subtasks with their originating user messages. Do
not persist it in ordinary V2 assistant rows; V2 uses ordered history rather than user/assistant parent links.
Ignore the optional V1 assistant `structured` output value. V2 has no equivalent top-level assistant field, and visible
text and tool content are migrated separately. Retain the original structured value only in the V1 `message` row.
Ignore V1 assistant `mode` and historical `path` (`cwd` and `root`). Mode is redundant with the preserved assistant
agent, and historical filesystem paths do not belong to the V2 assistant message contract. Retain them only in the V1
`message` row.
For assistant finish reasons, preserve `stop`, `length`, `tool-calls`, `content-filter`, `error`, and `unknown`. Map every
other nonempty V1 finish value to `unknown`, and leave the field absent when V1 omitted it. Do not retain unrecognized raw
finish values in metadata.
Map V1 assistant errors into the current V2 `{ type, message }` storage shape. Normalize Auth, content-filter, context
overflow, structured-output, output-length, aborted, API, and unknown errors to the established V2 string conventions,
preserve the message, and discard V1-only retryability and raw provider details.
Ignore V1 `retry` parts. Do not populate the V2 assistant `retry` field during migration; historical retry state is not
useful enough to preserve. The original retry rows remain in the V1 `part` table.
Do not emit V2 assistant content for V1 `step-start` and `step-finish` parts. Use the first available
`step-start.snapshot` as `assistant.snapshot.start` and the last available `step-finish.snapshot` as
`assistant.snapshot.end`. Continue to source finish, cost, and tokens from the assistant message itself. Ignore step
markers without snapshots.
Do not emit assistant content for standalone V1 `snapshot` or `patch` parts. If no start snapshot came from `step-start`,
use the first standalone snapshot value, then the first patch hash as a final fallback. Only `step-finish.snapshot` may
populate the end snapshot. Merge patch file lists into `assistant.snapshot.files` in first-seen order with duplicates
removed.
V2 follow-up: replace the open `SessionError.Error` string shape with a properly typed persisted error union. This is not
a blocker for the V1 migration, which should target the current storage contract.
V1 synthetic content is represented by user text parts with `synthetic: true`, not by a separate message role. A V1 user
message whose visible text parts are all synthetic should become a V2 `synthetic` message. If a V1 user message mixes
ordinary and synthetic content, preserve the ordinary content in the V2 `user` row and emit the synthetic content as an
adjacent V2 `synthetic` row. Ignore text parts marked `ignored`, matching V1 model-history behavior.
For an ordinary V2 user message, take visible V1 text parts that are neither ignored nor synthetic, preserve part order,
and join their text with `"\n\n"`. Use an empty string when the message contains attachments but no ordinary text.
Ignore the optional V1 user-message `system` override. Do not create a V2 system message or preserve the override in
metadata. The original value remains in the V1 `message` row.
Ignore the optional V1 user-message `tools` map. It represented request-time tool enablement for a historical step and
must not affect future V2 execution. The original value remains in the V1 `message` row.
Ignore the optional V1 user-message `format` field and its schema. It controlled structured-output behavior for a
historical request and must not affect future V2 runs. Preserve visible assistant text normally; retain the original
format only in the V1 `message` row.
Ignore V1 user-message `summary` metadata, including title, body, and diffs. V2 user messages have no equivalent field,
and session-level summary data is already persisted separately. Retain the original summary only in the V1 `message`
row.
Map V1 `agent` parts into the V2 user message's `agents` array in part order. Preserve `name`. When the V1 part has
`source`, map its `value`, `start`, and `end` into the V2 attachment's `mention.text`, `mention.start`, and `mention.end`.
Omit `agents` when there are no agent parts.
Do not read the filesystem or network while migrating V1 file attachments. Attachment migration must be deterministic
from database contents alone. Convert persisted `data:` URLs; represent non-embedded `file:`, HTTP, and other external
URLs with deterministic text rather than fetching them. Keep the original V1 `part` rows unchanged.
For a V1 file backed by a `data:` URL, decode the URL and normalize its payload to base64 for the V2 attachment's `data`.
Preserve `mime` and optional `filename` as `name`. Use a V2 `uri` source with the original URI for a V1 resource source;
otherwise use an `inline` source. When V1 source text metadata exists, map its `value`, `start`, and `end` into the V2
attachment mention. Leave `description` unset and preserve file-part order in the V2 `files` array.
For a non-embedded V1 file, do not create a V2 file attachment. Append
`[Attachment unavailable after migration: <name-or-url> (<mime>)]` to the V2 user text in original part order, separated
by blank lines. Prefer the V1 filename, then resource URI, then part URL for the label. The original URL remains only in
the preserved V1 `part` row.
For a synthetic row split from a mixed user message, derive a generated-looking ID from the source message ID. Preserve
the source ID's 12-character timestamp component and replace its 14-character random component with a deterministic
base-62 encoding of a hash of `v1-synthetic:` plus the source message ID. If that candidate collides with an existing or
derived message ID, deterministically retry with an incrementing salt. Place the synthetic row immediately after its
source user row. Entirely synthetic messages continue to reuse their original message ID.
Use the V1 compaction user message ID as the ID of the collapsed V2 compaction message. This matches V2's use of the
admitted compaction input ID and preserves references to the initiating message.
For a completed compaction, create one V2 `compaction` row with `status: "completed"`. Set `reason` from the V1
compaction part's `auto` flag, join the paired summary assistant's nonempty text parts with blank lines for `summary`, and
serialize the retained V1 tail beginning at `tail_start_id` for `recent`. Use an empty `recent` value when no tail was
retained, and use the compaction user message creation time. Do not emit the paired summary assistant as a separate V2
assistant row.
Do not project incomplete or failed V1 compactions into `session_message`. Omit both the internal compaction user marker
and its paired summary assistant when no successful summary was completed. Assign final sequence numbers after filtering
so omitted compactions leave no gaps. Their source rows remain preserved in the V1 `message` and `part` tables.
After rebuilding a session's `session_message`, replace its `event_sequence` watermark with that session's maximum
backfilled `session_message.seq`. This prevents new V2 events from reusing sequence numbers or sorting before migrated
history. The migrated session's prior `event` rows are removed in the same transaction.
## Drop
Drop these pre-launch V2 tables without preserving or transforming their rows:
- `session_input`
- `session_context_epoch`
- `data_migration`
Do not transfer `session_input` rows into `session_pending`.
## Create Empty
Let the generated migration create these tables empty:
- `instruction_blob`
- `instruction_entry`
- `instruction_state`
- `session_pending`
- `kv`
V1 has no canonical data to backfill into these tables. V2 initializes their state as it runs.
## Fork Storage
V1 has no fork-boundary state to backfill. New V2 forks use a required message boundary and persist it in
`session.fork_boundary`. The durable fork event contains no parent sequence. Its resolved boundary is one of:
- `before`: copy messages before the identified message.
- `through`: copy messages through the identified message.
Forking an empty session is not supported. `session.fork_seq` and `session.fork_message_id` are not part of the final V2
schema.
New nullable session columns, including `fork_session_id`, `fork_boundary`, and `time_suspended`, require no explicit
backfill. Existing rows naturally receive `NULL` when the generated migration adds the columns.
## Execution
Before transforming V1 rows, look for `opencode-next.db` in the data directory. This file was used by pre-launch V2
builds. Open it read-only with Bun SQLite and copy its `project`, `session`, and `session_message` rows directly into the
current `project`, `session_v2`, and `session_message` tables. Existing current projects and Sessions win ID collisions.
Do not copy its durable events or runtime caches; initialize each imported Session's `event_sequence` watermark from its
maximum message sequence. Commit each imported Session independently and leave the source database untouched.
The previous V2 import is part of this migration and uses the same completion marker. It needs no source-specific cursor:
the destination Session row is the per-Session idempotency boundary, so a retry skips transactions that already committed.
Store V1 backfill state in `kv`; do not retain a dedicated `data_migration` table. Store the last successfully migrated
session ID under `migration.v1-v2.session.cursor` and write `migration.v1-v2.completed` with value `true` after every
session finishes. Delete the cursor key on completion and return immediately on later calls when the completion key
exists.
Absence of the completion key means migration is required, including on a fresh database. Running the endpoint against a
database with no sessions completes immediately and writes the completion key; fresh database initialization does not
seed migration state specially.
Process sessions in stable ID order. Rebuild one session in one transaction, including its `session_message` rows,
session-level backfills, `event_sequence` watermark, and cursor update. If interrupted during a session, that transaction
rolls back and the next endpoint call retries the same session. If it committed, the next call continues after the stored
cursor. Mark the migration complete after the final session and return immediately on later calls.
Ensure the global project exists using the current platform's filesystem root as its worktree. Process every `session`
row, including archived, root, child, and empty sessions, as well as sessions whose messages are all skipped or internal.
Reassign beta and V1 Sessions whose referenced project row is missing to the global project and log a warning. Each
successfully committed session advances the cursor.
## Testing
Detailed migration test design is deferred until after the canonical migration is implemented.
+2 -7
View File
@@ -23,14 +23,9 @@ Per-type constructors live on the type, not as top-level re-exports. Use `Messag
This package is an Effect Schema-first LLM core. The Schema classes in `src/schema/` are the canonical runtime data model. Convenience functions in `src/llm.ts` are thin constructors that return those same Schema class instances; they should improve callsites without creating a second model.
Primary in-repo integration point:
Session integration lives in `packages/core/src/session`: `runner/llm.ts` owns orchestration, `model-request.ts` lowers Session state into `LLMRequest`, and `model-transport.ts` selects transport behavior.
- `packages/opencode/src/session/llm.ts` is the session-owned orchestration layer that decides whether a request uses AI SDK or this package's native route runtime.
- `packages/opencode/src/session/llm/native-request.ts` is the lowering adapter from opencode's session/AI SDK-shaped data into this package's `LLMRequest` model.
- `packages/opencode/src/session/llm/native-runtime.ts` is the execution adapter that calls raw `LLMClient.stream(request)` and bridges one provider turn of opencode tool calls through this package's typed dispatcher.
- `packages/opencode/src/session/llm/ai-sdk.ts` keeps the default AI SDK path compatible by converting AI SDK stream parts into this package's shared `LLMEvent`s.
Keep this package independent of session concerns. Session auth, permissions, plugins, telemetry headers, and runtime selection belong in `packages/opencode/src/session/llm.ts` and its local adapters.
Keep this package independent of Session concerns. Session auth, permissions, plugins, telemetry headers, and runtime selection belong in Core.
### Request Flow
+1 -1
View File
@@ -11,7 +11,7 @@
- `opencode dev web` proxies `https://app.opencode.ai`, so local UI/CSS changes will not show there.
- For local UI changes, run the backend and app dev servers separately.
- Backend (from `packages/opencode`): `bun run --conditions=browser ./src/index.ts serve --port 4096`
- Backend (from the repository root): `bun dev serve --port 4096`
- App (from `packages/app`): `bun dev -- --port 4444`
- Open `http://localhost:4444` to verify UI changes (it targets the backend at `http://localhost:4096`).
+2 -2
View File
@@ -278,7 +278,7 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
}
if (path === "/api/project/current")
return json(route, { id: (config.project as { id?: string }).id, directory: config.directory })
const worktree = path.match(/^\/api\/experimental\/project\/([^/]+)\/worktree$/)?.[1]
const worktree = path.match(/^\/api\/worktree\/([^/]+)$/)?.[1]
if (worktree && route.request().method() === "GET")
return json(route, [
{ directory: config.directory },
@@ -294,7 +294,7 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
}
if (worktree && route.request().method() === "DELETE")
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
if (/^\/api\/experimental\/project\/[^/]+\/worktree\/refresh$/.test(path))
if (/^\/api\/worktree\/[^/]+\/refresh$/.test(path))
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
if (path === "/api/permission/request")
return json(route, {
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
import {
normalizeNewSessionWorktree,
resolveNewSessionBranch,
resolveNewSessionGit,
resolveNewSessionWorktree,
} from "./new-session-workspace-controller"
@@ -47,4 +48,10 @@ describe("new session workspace selection", () => {
)
expect(resolveNewSessionBranch({ worktree: "/missing", local: "dev", worktreeBranch: branch })).toBe("dev")
})
test("uses location VCS state when the project inventory is stale", () => {
expect(resolveNewSessionGit({ branch: "dev" })).toBe(true)
expect(resolveNewSessionGit({ projectVcs: "git" })).toBe(true)
expect(resolveNewSessionGit({})).toBe(false)
})
})
@@ -39,6 +39,10 @@ export function resolveNewSessionBranch(input: {
return input.worktreeBranch(input.worktree) ?? input.local
}
export function resolveNewSessionGit(input: { projectVcs?: string; branch?: string }) {
return input.projectVcs === "git" || input.branch !== undefined
}
export function createNewSessionWorkspaceController(input: {
selected: () => string | undefined
setSelected: (worktree: string | undefined) => void
@@ -49,7 +53,10 @@ export function createNewSessionWorkspaceController(input: {
const serverSDK = useServerSDK()
const serverSync = useServerSync()
const settings = useSettings()
const visible = createMemo(() => sync().project?.vcs === "git")
const localVcs = createMemo(() => serverSync.child(sdk().directory)[0].vcs)
const visible = createMemo(() =>
resolveNewSessionGit({ projectVcs: sync().project?.vcs, branch: localVcs()?.branch }),
)
const selected = createMemo(() => {
const project = sync().project
const worktree = input.selected()
@@ -110,7 +117,7 @@ export function createNewSessionWorkspaceController(input: {
const project = sync().project
return project ? workspaceDirectories(project) : []
},
git: () => sync().project?.vcs === "git",
git: visible,
openAll: input.onViewAll,
},
bar: {
+2 -5
View File
@@ -1,7 +1,4 @@
# V2 CLI and TUI development guide
# CLI and TUI development guide
## Migration context
- The TUI is being ported from legacy APIs to the new V2 APIs. New and migrated TUI behavior should use `sdk.client.v2` and the location-scoped data in `packages/tui/src/context/data.tsx` instead of adding dependencies on legacy sync state.
- Use `@opencode-ai/client` and the location-scoped data in `packages/tui/src/context/data.tsx` instead of adding dependencies on legacy sync state.
- Preserve established TUI behavior unless the task intentionally changes it.
- Load the `opencode-dev` skill before interactively running, debugging, or verifying opencode's V2 CLI, TUI, or server.
-1
View File
@@ -30,7 +30,6 @@ describe("debug config command", () => {
],
},
},
{ type: "file", path: path.join(project, "opencode.json") },
]
let requested: URL | undefined
const authorization: Array<string | null> = []
@@ -1671,7 +1671,7 @@ export function make(options: ClientOptions) {
request<WorktreeListOutput>(
{
method: "GET",
path: `/api/experimental/project/${encodeURIComponent(input.projectID)}/worktree`,
path: `/api/worktree/${encodeURIComponent(input.projectID)}`,
successStatus: 200,
declaredStatuses: [401, 400],
empty: false,
@@ -1682,7 +1682,7 @@ export function make(options: ClientOptions) {
request<WorktreeCreateOutput>(
{
method: "POST",
path: `/api/experimental/project/${encodeURIComponent(input.projectID)}/worktree`,
path: `/api/worktree/${encodeURIComponent(input.projectID)}`,
body: {
strategy: input["strategy"],
from: input["from"],
@@ -1699,7 +1699,7 @@ export function make(options: ClientOptions) {
request<WorktreeRemoveOutput>(
{
method: "DELETE",
path: `/api/experimental/project/${encodeURIComponent(input.projectID)}/worktree`,
path: `/api/worktree/${encodeURIComponent(input.projectID)}`,
body: { directory: input["directory"], force: input["force"] },
successStatus: 204,
declaredStatuses: [400, 401],
@@ -1711,7 +1711,7 @@ export function make(options: ClientOptions) {
request<WorktreeRefreshOutput>(
{
method: "POST",
path: `/api/experimental/project/${encodeURIComponent(input.projectID)}/worktree/refresh`,
path: `/api/worktree/${encodeURIComponent(input.projectID)}/refresh`,
successStatus: 204,
declaredStatuses: [400, 401],
empty: true,
@@ -1787,7 +1787,7 @@ export type ConfigEntry =
| { repository: string; branch?: string; description?: string; hidden?: boolean }
| { path: string; description?: string; hidden?: boolean }
}
websearch?: { provider: string }
websearch?: false | { provider: "random" | (string & {}) }
plugins?: Array<string | { package: string; options?: { [x: string]: JsonValue } }>
warming?: boolean | { prompt?: string; interval?: string; duration?: string }
providers?: {
@@ -1842,7 +1842,6 @@ export type ConfigEntry =
}
}
| { type: "directory"; path: string }
| { type: "file"; path: string }
| { type: "agents"; path: string }
| { type: "claude"; path: string }
+4 -5
View File
@@ -66,7 +66,6 @@ test("config.get returns ordered config entries for a location", async () => {
],
},
},
{ type: "file" as const, path: "/tmp/project/opencode.json" },
]
const client = OpenCode.make({
baseUrl: "http://localhost:3000",
@@ -283,10 +282,10 @@ test("worktree methods use the global project contract", async () => {
await client.worktree.refresh({ projectID: "proj_test" })
expect(requests.map((request) => [request.method, request.url])).toEqual([
["GET", "http://localhost:3000/api/experimental/project/proj_test/worktree"],
["POST", "http://localhost:3000/api/experimental/project/proj_test/worktree"],
["DELETE", "http://localhost:3000/api/experimental/project/proj_test/worktree"],
["POST", "http://localhost:3000/api/experimental/project/proj_test/worktree/refresh"],
["GET", "http://localhost:3000/api/worktree/proj_test"],
["POST", "http://localhost:3000/api/worktree/proj_test"],
["DELETE", "http://localhost:3000/api/worktree/proj_test"],
["POST", "http://localhost:3000/api/worktree/proj_test/refresh"],
])
expect(await requests[1]?.json()).toEqual({
strategy: "git",
+102 -17
View File
@@ -4,13 +4,14 @@ import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import path from "path"
import { isDeepStrictEqual } from "node:util"
import { type ParseError, parse } from "jsonc-parser"
import { applyEdits, modify } from "jsonc-parser"
import { Context, Effect, Layer, Option, PubSub, Ref, Schema, Semaphore, Stream } from "effect"
import { produce, type Draft } from "immer"
import {
AgentsDirectory,
ClaudeDirectory,
Directory,
Document,
File,
Info,
type Entry,
Event,
@@ -36,6 +37,8 @@ export function latest<K extends keyof Info>(entries: readonly Entry[], key: K):
export interface Interface {
/** Returns location config documents and discovery sources from lowest to highest priority. */
readonly entries: () => Effect.Effect<Entry[]>
/** Updates the first file-backed configuration document. */
readonly update: (update: (draft: Draft<Info>) => void) => Effect.Effect<Info, UpdateError>
/**
* Streams raw filesystem updates under config roots. Config owns root
* topology and watch reconciliation; domain owners filter this feed for the
@@ -44,6 +47,11 @@ export interface Interface {
readonly changes: () => Stream.Stream<Watcher.Update>
}
export class UpdateError extends Schema.TaggedErrorClass<UpdateError>()("Config.UpdateError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export const Options = Schema.Struct({
project: Schema.optional(Schema.Boolean),
file: Schema.optional(Schema.String),
@@ -70,6 +78,19 @@ export const testLayer = (initial: Entry[] = []) =>
const updates = yield* PubSub.unbounded<Watcher.Update>()
const service = Test.of({
entries: () => Ref.get(entries),
update: (update) =>
Effect.gen(function* () {
const current = yield* Ref.get(entries)
const index = current.findIndex((entry) => entry.type === "document" && entry.path !== undefined)
if (index === -1)
return yield* Effect.fail(new UpdateError({ message: "No editable config document found" }))
const entry = current[index]
if (!entry || entry.type !== "document")
return yield* Effect.fail(new UpdateError({ message: "No editable config document found" }))
const info = produce(entry.info, update)
yield* Ref.set(entries, current.with(index, new Document({ type: "document", path: entry.path, info })))
return info
}),
changes: () => Stream.fromPubSub(updates),
setEntries: (next) => Ref.set(entries, next),
emitChange: (update) => PubSub.publish(updates, update).pipe(Effect.asVoid),
@@ -91,6 +112,7 @@ export const layer = (options?: Options) =>
const wellknown = yield* WellKnown.Service
const names = ["opencode.json", "opencode.jsonc"]
const reloadLock = Semaphore.makeUnsafe(1)
const fileTargets = new Set<AbsolutePath>()
const decodeOptions = { errors: "all", onExcessProperty: "ignore", propertyOrder: "original" } as const
const decodeInfo = Schema.decodeUnknownOption(Info, decodeOptions)
const parseInfo = Effect.fn("Config.parseInfo")(function* (text: string, source: string) {
@@ -131,7 +153,7 @@ export const layer = (options?: Options) =>
const substituted = yield* ConfigVariable.substitute({ type: "path", path: filepath, text })
const info = yield* parseInfo(substituted, filepath)
if (!info) return
return new Document({ type: "document", path: filepath, info })
return new Document({ type: "document", path: AbsolutePath.make(filepath), info })
})
const loadWellknown = Effect.fn("Config.loadWellknown")(function* () {
@@ -224,25 +246,18 @@ export const layer = (options?: Options) =>
const directPaths = discovered
.filter((item) => ![".agents", ".claude", ".opencode"].includes(path.basename(item)))
.toReversed()
const direct = yield* Effect.forEach(directPaths, (filepath) =>
loadFile(filepath).pipe(
Effect.map((config) => [
...(config ? [config] : []),
new File({ type: "file", path: AbsolutePath.make(filepath) }),
]),
),
).pipe(
fileTargets.clear()
directPaths.forEach((filepath) => fileTargets.add(AbsolutePath.make(filepath)))
const direct = yield* Effect.forEach(directPaths, (filepath) => loadFile(filepath)).pipe(
Effect.orDie,
Effect.map((entries) => entries.flat()),
Effect.map((entries) => entries.filter((entry): entry is Document => entry !== undefined)),
)
const file = options?.file
if (file) fileTargets.add(AbsolutePath.make(path.resolve(file)))
const explicit = file
? yield* loadFile(path.resolve(file)).pipe(
Effect.map((config) => [
...(config ? [config] : []),
new File({ type: "file", path: AbsolutePath.make(path.resolve(file)) }),
]),
Effect.map((config) => (config ? [config] : [])),
Effect.orDie,
)
: []
@@ -285,7 +300,10 @@ export const layer = (options?: Options) =>
const watched = new Set<string>()
const reconcile = Effect.fn("Config.reconcileWatches")(function* (entries: readonly Entry[]) {
const directories = entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : []))
const files = entries.flatMap((entry) => (entry.type === "file" ? [entry.path] : []))
const files = [
...entries.flatMap((entry) => (entry.type === "document" && entry.path ? [entry.path] : [])),
...fileTargets,
]
const targets = [
...directories.map((path) => ({ path, type: "directory" as const, ignore })),
...files
@@ -308,9 +326,9 @@ export const layer = (options?: Options) =>
reloadLock.withPermit(
Effect.gen(function* () {
const next = yield* discover()
yield* reconcile(next)
if (isDeepStrictEqual(configs, next)) return
configs = next
yield* reconcile(next)
yield* bus.publish(Event.Updated, {})
}),
),
@@ -364,10 +382,54 @@ export const layer = (options?: Options) =>
)
yield* reconcile(initial)
const update = Effect.fn("Config.update")((mutate: (draft: Draft<Info>) => void) =>
reloadLock.withPermit(
Effect.gen(function* () {
// TODO: Replace entry-order selection with an explicit config scope/target model.
const document = configs.find((entry) => entry.type === "document" && entry.path !== undefined)
if (!document || document.type !== "document" || !document.path)
return yield* Effect.fail(new UpdateError({ message: "No editable config document found" }))
const next = yield* Effect.try({
try: () => produce(document.info, mutate),
catch: (cause) => new UpdateError({ message: "Config update failed", cause }),
})
const edits = changes(document.info, next)
if (!edits.length) return document.info
const text = yield* fs
.readFileString(document.path)
.pipe(
Effect.mapError(
(cause) => new UpdateError({ message: `Failed to read config: ${document.path}`, cause }),
),
)
const updated = edits.reduce(
(text, edit) =>
applyEdits(
text,
modify(text, edit.path, edit.value, { formattingOptions: { tabSize: 2, insertSpaces: true } }),
),
text,
)
const info = yield* parseInfo(updated, document.path)
if (!info)
return yield* Effect.fail(new UpdateError({ message: `Invalid config update: ${document.path}` }))
const temporary = document.path + ".tmp"
yield* fs.writeFileString(temporary, updated.endsWith("\n") ? updated : updated + "\n").pipe(
Effect.andThen(fs.rename(temporary, document.path)),
Effect.mapError(
(cause) => new UpdateError({ message: `Failed to write config: ${document.path}`, cause }),
),
)
return info
}),
),
)
return Service.of({
entries: Effect.fn("Config.entries")(function* () {
return configs
}),
update,
changes: () => Stream.fromPubSub(updates),
})
}),
@@ -382,3 +444,26 @@ export function configured(options?: Options) {
}
export const node = configured()
type Edit = { readonly path: (string | number)[]; readonly value: unknown }
function changes(before: unknown, after: unknown, path: (string | number)[] = []): Edit[] {
if (Object.is(before, after)) return []
if (
before !== null &&
after !== null &&
typeof before === "object" &&
typeof after === "object" &&
!Array.isArray(before) &&
!Array.isArray(after)
) {
const previous = before as Record<string, unknown>
const next = after as Record<string, unknown>
return [...new Set([...Object.keys(previous), ...Object.keys(next)])].flatMap((key) => {
if (!(key in next)) return [{ path: [...path, key], value: undefined }]
if (!(key in previous)) return [{ path: [...path, key], value: next[key] }]
return changes(previous[key], next[key], [...path, key])
})
}
return [{ path, value: after }]
}
+2 -1
View File
@@ -16,6 +16,7 @@ import { Permission } from "../../permission.js"
import type { LocationMutation } from "../../location-mutation.js"
import type { ReadTool } from "../../tool/plugin/read.js"
import type { EditTool } from "../../tool/plugin/edit.js"
import { AbsolutePath } from "../../schema.js"
const legacySources = [
{ pattern: "{agent,agents}/**/*.md", primary: false },
@@ -210,5 +211,5 @@ function decode(file: { directory: string; filepath: string; primary: boolean },
}),
)
if (!info) return
return new Document({ type: "document", path: file.filepath, info })
return new Document({ type: "document", path: AbsolutePath.make(file.filepath), info })
}
+3 -2
View File
@@ -10,8 +10,9 @@ export const Plugin = define({
const config = yield* Config.Service
const loaded = { entries: yield* config.entries() }
yield* ctx.websearch.transform((websearch) => {
const providerID = Config.latest(loaded.entries, "websearch")?.provider
if (providerID) websearch.default.set(providerID)
const selection = Config.latest(loaded.entries, "websearch")
if (selection === false) websearch.default.set(false)
if (selection) websearch.default.set(selection.provider)
})
yield* ctx.event.subscribe().pipe(
Stream.filter((event) => event.type === "config.updated"),
+4 -1
View File
@@ -332,7 +332,10 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: import("../p
}),
default: {
get: draft.default.get,
set: (providerID) => draft.default.set(WebSearch.ID.make(providerID)),
set: (selection) =>
draft.default.set(
selection === false || selection === "random" ? selection : WebSearch.ID.make(selection),
),
},
})
}),
+1 -394
View File
@@ -1,396 +1,3 @@
export * as PluginPromise from "./promise.js"
import { define } from "@opencode-ai/plugin/effect/plugin"
import type { Context, Plugin } from "@opencode-ai/plugin/promise/plugin"
import type { Info } from "@opencode-ai/plugin/promise/tool"
import { Agent } from "@opencode-ai/schema/agent"
import { Integration } from "@opencode-ai/schema/integration"
import { Location } from "@opencode-ai/schema/location"
import { Model } from "@opencode-ai/schema/model"
import { Provider } from "@opencode-ai/schema/provider"
import { AbsolutePath } from "@opencode-ai/schema/schema"
import { Session } from "@opencode-ai/schema/session"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { Skill } from "@opencode-ai/schema/skill"
import { Workspace } from "@opencode-ai/schema/workspace"
import { WebSearch } from "@opencode-ai/schema/websearch"
import { DateTime, Effect, Scope, Stream } from "effect"
import { Tool } from "../tool.js"
type HostRegistration = { readonly dispose: Effect.Effect<void> }
type Registration = { readonly dispose: () => Promise<void> }
type PromiseEvent = ReturnType<Context["event"]["subscribe"]> extends AsyncIterable<infer Event> ? Event : never
type JsonValue = null | boolean | number | string | Array<JsonValue> | { [key: string]: JsonValue }
/**
* Adapts a Promise plugin into an Effect plugin so the existing Effect-only
* loader (`Plugin` / `PluginSupervisor`) can run it unchanged.
*
* Hook registrations created during the async `setup` attach to the plugin's
* scope, so unloading the plugin disposes them. The captured fiber context
* preserves boot-time batching, so Promise-plugin transforms still coalesce
* into one reload per domain.
*/
export function fromPromise(plugin: Plugin) {
return define({
id: plugin.id,
effect: (host) =>
Effect.gen(function* () {
const scope = yield* Scope.Scope
const context = yield* Effect.context<Scope.Scope>()
// Run a hook registration on the plugin scope and resolve once it is registered.
const register = (effect: Effect.Effect<HostRegistration, never, Scope.Scope>): Promise<Registration> =>
Effect.runPromiseWith(context)(Scope.provide(scope)(effect)).then((registration) => ({
dispose: () => Effect.runPromiseWith(context)(registration.dispose),
}))
const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromiseWith(context)(effect).then(wire)
const transform =
<Draft>(domain: {
transform: (callback: (draft: Draft) => void) => Effect.Effect<HostRegistration, never, Scope.Scope>
}) =>
(callback: (draft: Draft) => void) =>
register(
domain.transform((draft) => {
callback(draft)
}),
)
const context2: Context = {
app: host.app,
options: host.options,
agent: {
get: (input) => run(host.agent.get({ ...input, agentID: Agent.ID.make(input.agentID) })),
list: (input) => run(host.agent.list(input)),
transform: transform(host.agent),
reload: () => run(host.agent.reload()),
},
aisdk: {
hook: (name, callback) =>
register(host.aisdk.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
catalog: {
provider: {
list: (input) => run(host.catalog.provider.list(input)),
get: (input) =>
run(host.catalog.provider.get({ ...input, providerID: Provider.ID.make(input.providerID) })),
},
model: {
list: (input) => run(host.catalog.model.list(input)),
default: (input) =>
run(host.catalog.model.default(input)).then((result) => ({ ...result, data: result.data ?? null })),
},
transform: transform(host.catalog),
reload: () => run(host.catalog.reload()),
},
command: {
list: (input) => run(host.command.list(input)),
transform: transform(host.command),
reload: () => run(host.command.reload()),
},
event: {
subscribe: () => Stream.toAsyncIterable(host.event.subscribe().pipe(Stream.map(wireEvent))),
},
integration: {
list: (input) => run(host.integration.list(input)),
get: (input) =>
run(host.integration.get({ ...input, integrationID: Integration.ID.make(input.integrationID) })).then(
(result) => ({ ...result, data: result.data ?? null }),
),
connect: {
key: (input) =>
run(
host.integration.connect.key({ ...input, integrationID: Integration.ID.make(input.integrationID) }),
),
},
oauth: {
connect: (input) =>
run(
host.integration.oauth.connect({
...input,
integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID),
}),
),
status: (input) =>
run(
host.integration.oauth.status({
...input,
integrationID: Integration.ID.make(input.integrationID),
attemptID: Integration.AttemptID.make(input.attemptID),
}),
),
complete: (input) =>
run(
host.integration.oauth.complete({
...input,
integrationID: Integration.ID.make(input.integrationID),
attemptID: Integration.AttemptID.make(input.attemptID),
}),
),
cancel: (input) =>
run(
host.integration.oauth.cancel({
...input,
integrationID: Integration.ID.make(input.integrationID),
attemptID: Integration.AttemptID.make(input.attemptID),
}),
),
},
command: {
connect: (input) =>
run(
host.integration.command.connect({
...input,
integrationID: Integration.ID.make(input.integrationID),
methodID: Integration.MethodID.make(input.methodID),
}),
),
status: (input) =>
run(
host.integration.command.status({
...input,
integrationID: Integration.ID.make(input.integrationID),
attemptID: Integration.AttemptID.make(input.attemptID),
}),
),
cancel: (input) =>
run(
host.integration.command.cancel({
...input,
integrationID: Integration.ID.make(input.integrationID),
attemptID: Integration.AttemptID.make(input.attemptID),
}),
),
},
transform: (callback) =>
register(
host.integration.transform((draft) =>
callback({
list: draft.list,
get: draft.get,
update: draft.update,
remove: draft.remove,
method: {
list: draft.method.list,
update: (input) => {
if (!("authorize" in input)) return draft.method.update(input)
const refresh = input.refresh
draft.method.update({
...input,
authorize: (answer) =>
Effect.promise(() => input.authorize(answer)).pipe(
Effect.map((authorization) =>
authorization.mode === "auto"
? {
...authorization,
callback: Effect.promise(() => authorization.callback),
}
: {
...authorization,
callback: (code) => Effect.promise(() => authorization.callback(code)),
},
),
),
refresh:
refresh === undefined
? undefined
: (credential) => Effect.promise(() => refresh(credential)),
})
},
remove: draft.method.remove,
},
}),
),
),
reload: () => run(host.integration.reload()),
connection: {
active: (id) => Effect.runPromiseWith(context)(host.integration.connection.active(id)),
resolve: (connection) => Effect.runPromiseWith(context)(host.integration.connection.resolve(connection)),
},
},
plugin: {
list: (input) => run(host.plugin.list(input)),
},
reference: {
list: (input) => run(host.reference.list(input)),
transform: transform(host.reference),
reload: () => run(host.reference.reload()),
},
skill: {
list: (input) => run(host.skill.list(input)),
transform: transform(host.skill),
reload: () => run(host.skill.reload()),
},
tool: {
transform: (callback) =>
register(
host.tool.transform((draft) =>
callback({
add: (tool: Info) =>
draft.add({
...tool,
execute: (input, context) => executePromiseTool(tool, input, context),
}),
}),
),
),
hook: (name, callback) =>
register(host.tool.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
websearch: {
providers: (input) => run(host.websearch.providers(input)),
query: (input) =>
run(
host.websearch.query({
...input,
providerID: input.providerID === undefined ? undefined : WebSearch.ID.make(input.providerID),
}),
),
reload: () => run(host.websearch.reload()),
transform: (callback) =>
register(
host.websearch.transform((draft) => {
callback({
add: (definition) =>
draft.add({
id: definition.id,
name: definition.name,
execute: (input) => attempt((signal) => definition.execute(input, { signal })),
}),
default: draft.default,
})
}),
),
},
session: {
hook: (name, callback) =>
register(host.session.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
create: (input) =>
run(
host.session.create(
input === undefined
? undefined
: {
id: input.id == null ? undefined : Session.ID.make(input.id),
agent: input.agent == null ? undefined : Agent.ID.make(input.agent),
model: input.model == null ? undefined : model(input.model),
location:
input.location == null
? undefined
: Location.Ref.make({
directory: AbsolutePath.make(input.location.directory),
workspaceID:
input.location.workspaceID === undefined
? undefined
: Workspace.ID.make(input.location.workspaceID),
}),
},
),
),
get: (input) => run(host.session.get({ sessionID: Session.ID.make(input.sessionID) })),
prompt: (input) =>
run(
host.session.prompt({
...input,
sessionID: Session.ID.make(input.sessionID),
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
delivery: input.delivery ?? undefined,
resume: input.resume ?? undefined,
}),
),
generate: (input) =>
run(host.session.generate({ sessionID: Session.ID.make(input.sessionID), prompt: input.prompt })),
command: (input) =>
run(
host.session.command({
...input,
sessionID: Session.ID.make(input.sessionID),
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
agent: input.agent == null ? undefined : Agent.ID.make(input.agent),
model: input.model == null ? undefined : model(input.model),
skills: input.skills?.map((skill) => ({ ...skill, id: Skill.ID.make(skill.id) })),
arguments: input.arguments ?? undefined,
delivery: input.delivery ?? undefined,
resume: input.resume ?? undefined,
}),
),
synthetic: (input) =>
run(
host.session.synthetic({
...input,
sessionID: Session.ID.make(input.sessionID),
id: input.id == null ? undefined : SessionMessage.ID.make(input.id),
description: input.description ?? undefined,
delivery: input.delivery ?? undefined,
resume: input.resume ?? undefined,
}),
),
interrupt: (input) => run(host.session.interrupt({ sessionID: Session.ID.make(input.sessionID) })),
},
shell: {
hook: (name, callback) =>
register(host.shell.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
}
const cleanup = yield* Effect.promise(() => Promise.resolve(plugin.setup(context2)))
if (!cleanup) return
yield* Effect.addFinalizer(() => Effect.promise(() => Promise.resolve(cleanup())))
}),
})
}
function attempt<A>(evaluate: (signal: AbortSignal) => PromiseLike<A>) {
return Effect.tryPromise({ try: evaluate, catch: (cause) => cause })
}
function model(input: { readonly id: string; readonly providerID: string; readonly variant?: string }) {
return Model.Ref.make({
id: Model.ID.make(input.id),
providerID: Provider.ID.make(input.providerID),
variant: input.variant === undefined ? undefined : Model.VariantID.make(input.variant),
})
}
type Wire<Value> = unknown extends Value
? JsonValue
: Value extends string | number | boolean | bigint | symbol | null | undefined
? Value
: Value extends DateTime.DateTime
? number
: Value extends readonly [infer Head, ...infer Tail]
? [Wire<Head>, ...WireTuple<Tail>]
: Value extends ReadonlyArray<infer Item>
? Array<Wire<Item>>
: Value extends object
? { -readonly [Key in keyof Value]: Wire<Value[Key]> }
: Value
type WireTuple<Value extends ReadonlyArray<unknown>> = {
-readonly [Key in keyof Value]: Wire<Value[Key]>
}
function wire<Value>(value: Value): Wire<Value>
function wire(value: unknown): unknown {
if (DateTime.isDateTime(value)) return DateTime.toEpochMillis(value)
if (Array.isArray(value)) return value.map(wire)
if (typeof value !== "object" || value === null) return value
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, wire(item)]))
}
function wireEvent(value: unknown): PromiseEvent
function wireEvent(value: unknown): unknown {
return wire(value)
}
const executePromiseTool = (tool: Info, input: any, context: Tool.Context) =>
Effect.promise(() =>
tool.execute(input, {
...context,
progress: (update) => Effect.runPromise(context.progress(update)),
}),
)
export { fromPromise } from "@opencode-ai/plugin/promise/adapter"
+7 -2
View File
@@ -13,7 +13,7 @@ import { SessionHistory } from "./history.js"
import { SessionModelHeaders } from "./model-headers.js"
import { SessionPromptCacheKey } from "./prompt-cache-key.js"
import { SessionRunnerModel } from "./runner/model.js"
import PROMPT_DEFAULT from "./runner/prompt/base.txt"
import { SessionSystemPrompt } from "./system-prompt.js"
import { toLLMMessages } from "./runner/to-llm-message.js"
export const layer = Layer.effect(
@@ -39,7 +39,12 @@ export const layer = Layer.effect(
sessionID: selection.session.id,
agent: selection.agent.id,
model: model.ref,
system: [selection.agent.info.system ? selection.agent.info.system : PROMPT_DEFAULT, history.initial]
system: [
selection.agent.info.system
? selection.agent.info.system
: SessionSystemPrompt.make(toolDefinitions.map((tool) => tool.name)),
history.initial,
]
.filter((part) => part.length > 0)
.map(SystemPart.make),
messages: [
+5 -2
View File
@@ -19,7 +19,7 @@ import { SessionModelTransport } from "./model-transport.js"
import { SessionPromptCacheKey } from "./prompt-cache-key.js"
import { PromptCacheDiagnostics } from "./prompt-cache-diagnostics.js"
import { MAX_STEPS_PROMPT } from "./runner/max-steps.js"
import PROMPT_DEFAULT from "./runner/prompt/base.txt"
import { SessionSystemPrompt } from "./system-prompt.js"
import { toLLMMessages } from "./runner/to-llm-message.js"
const IMAGE_BYTES_TRIGGER = 25 * 1024 * 1024 // 25 MiB
@@ -190,7 +190,10 @@ export const layer = Layer.effect(
// The final Step keeps definitions available to protocols with native "none",
// preserving their prompt cache prefix. Calls are still rejected at execution.
const tools = input.context.tools
const system = [agent.info.system ? agent.info.system : PROMPT_DEFAULT, input.context.initial]
const system = [
agent.info.system ? agent.info.system : SessionSystemPrompt.make(tools.definitions.map((tool) => tool.name)),
input.context.initial,
]
.filter((part) => part.length > 0)
.map(SystemPart.make)
const history = toLLMMessages(input.context.messages, resolved.ref, providerMetadataKey)
@@ -1,95 +0,0 @@
You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
If the user asks for help or wants to give feedback inform them of the following:
- /help: Get help with using opencode
- To give feedback, users should report the issue at https://github.com/anomalyco/opencode/issues
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the webfetch tool to gather information to answer the question from opencode docs at https://opencode.ai/v2/docs/
# Tone and style
You should be concise, direct, and to the point. When you run a non-trivial shell command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
Remember that your output will be displayed on a command line interface. Your responses can use GitHub-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like the shell tool or code comments as means to communicate with the user during the session.
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
<example>
user: what is 2+2?
assistant: 4
</example>
<example>
user: is 11 a prime number?
assistant: Yes
</example>
<example>
user: what command should I run to list files in the current directory?
assistant: ls
</example>
<example>
user: what command should I run to watch files in the current directory?
assistant: [use the read tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
npm run dev
</example>
<example>
user: what files are in the directory src/?
assistant: [uses read and sees foo.c, bar.c, baz.c]
user: which file contains the implementation of foo?
assistant: src/foo.c
</example>
<example>
user: write tests for new feature
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
</example>
# Proactiveness
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
1. Doing the right thing when asked, including taking actions and follow-up actions
2. Not surprising the user with actions you take without asking
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
# Following conventions
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
# Code style
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
# Doing tasks
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
- Implement the solution using all tools available to you
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (e.g. npm run lint, npm run typecheck, ruff, etc.) with the shell tool if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
# Tool usage policy
- When doing file search, prefer to use the subagent tool in order to reduce context usage.
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple shell tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure.
# Code References
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
<example>
user: Where are errors from the client handled?
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
</example>
@@ -0,0 +1,14 @@
You are an AI agent powered by OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.
# Harness
- Responses are rendered as GitHub-flavored Markdown.
- `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.
${OPENCODE_TOOL_GUIDANCE}
# Communication
- Use clear file paths when referring to files.
- Keep responses clear and concise, and avoid unnecessary technical jargon.
# Working in codebases
- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.
- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.
@@ -0,0 +1,24 @@
export * as SessionSystemPrompt from "./system-prompt.js"
import PROMPT from "./runner/prompt/system.txt"
export function make(tools: string[]) {
const instructions: string[] = []
if (tools.includes("write")) {
instructions.push(
"- Use the write tool to create files or completely replace their content. Prefer using the edit tool for targeted changes.",
)
}
if (tools.includes("edit")) {
instructions.push(
"- Use the edit tool for targeted changes to existing text files. It replaces the exact text in `oldString` with `newString`, and the values must differ. By default, `oldString` must occur exactly once. If it occurs multiple times, include more surrounding context to make it unique or set `replaceAll` to true to replace every occurrence.",
)
}
// if (tools.includes("patch")) {
// // instructions.push(...)
// }
if (tools.includes("read")) {
instructions.push("- Prefer using the read tool rather than shell commands like `cat`.")
}
return PROMPT.replace("${OPENCODE_TOOL_GUIDANCE}", instructions.join("\n"))
}
+24 -10
View File
@@ -4,8 +4,8 @@ import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin
import { ToolFailure } from "@opencode-ai/ai"
import { Effect, Schema, Semaphore } from "effect"
import { HttpClientError } from "effect/unstable/http"
import { Config } from "../../config.js"
import { Form } from "../../form.js"
import { KV } from "../../kv.js"
import { Permission } from "../../permission.js"
import { WebSearch } from "../../websearch.js"
@@ -30,7 +30,7 @@ export const Plugin = {
effect: Effect.fn("WebSearchTool.Plugin")(function* (ctx: PluginContext) {
const permission = yield* Permission.Service
const forms = yield* Form.Service
const kv = yield* KV.Service
const config = yield* Config.Service
const websearch = yield* WebSearch.Service
yield* ctx.tool
@@ -65,7 +65,7 @@ export const Plugin = {
return providerSelectionLock
.withPermit(
Effect.gen(function* () {
if (yield* websearch.default()) return yield* Effect.void
if (yield* websearch.default()) return
const providers = (yield* ctx.websearch.providers()).data
const defaultProvider = providers[0]
if (!defaultProvider) return yield* new WebSearch.ProviderRequiredError()
@@ -83,7 +83,7 @@ export const Plugin = {
options: [
{
value: "allow",
label: `Allow web search via ${defaultProvider.name}`,
label: `Allow search via ${providers.map((provider) => provider.name).join(", ")}`,
},
{
value: "choose",
@@ -97,7 +97,9 @@ export const Plugin = {
if (response.status === "cancelled")
return yield* Effect.fail(new Error("Web search cancelled"))
if (response.answer.choice === "disable") {
yield* kv.set("websearch:provider", false)
yield* config.update((draft) => {
draft.websearch = false
})
return yield* new WebSearch.DisabledError()
}
const selection =
@@ -123,13 +125,19 @@ export const Plugin = {
: undefined
if (selection?.status === "cancelled")
return yield* Effect.fail(new Error("Web search cancelled"))
const providerID = selection?.answer.provider ?? defaultProvider.id
const providerID = selection?.answer.provider ?? "random"
if (
typeof providerID !== "string" ||
!providers.some((provider) => provider.id === providerID)
(providerID !== "random" && !providers.some((provider) => provider.id === providerID))
)
return yield* new WebSearch.ProviderRequiredError()
return yield* kv.set("websearch:provider", providerID)
yield* config.update((draft) => {
draft.websearch = {
provider: providerID === "random" ? "random" : WebSearch.ID.make(providerID),
}
})
if (providerID !== "random") return WebSearch.ID.make(providerID)
return providers[Math.floor(Math.random() * providers.length)]?.id
}),
)
.pipe(
@@ -137,7 +145,12 @@ export const Plugin = {
duration: "1 minute",
orElse: () => Effect.fail(new Error("Web search cancelled")),
}),
Effect.andThen(Effect.suspend(search)),
Effect.flatMap((providerID) => {
if (!providerID) return Effect.suspend(search)
return context
.progress({ provider: providerID })
.pipe(Effect.andThen(ctx.websearch.query({ ...input, providerID })))
}),
)
}),
)
@@ -193,7 +206,8 @@ export const Plugin = {
yield* ctx.session.hook("context", (event) =>
Effect.gen(function* () {
if ((yield* kv.get("websearch:provider")) === false) delete event.tools[name]
const disabled = Config.latest(yield* config.entries(), "websearch") === false
if (disabled) delete event.tools[name]
}),
)
}),
+12 -14
View File
@@ -4,7 +4,6 @@ import { WebSearch } from "@opencode-ai/schema/websearch"
import { Context, Effect, Layer, Schema } from "effect"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { Bus } from "./bus.js"
import { KV } from "./kv.js"
import { State } from "./state.js"
export const ID = WebSearch.ID
@@ -60,14 +59,14 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/We
type Data = {
readonly providers: Map<ID, ProviderImplementation>
defaultProviderID?: ID
selection?: ID | "random" | false
}
export type Draft = {
add: (provider: ProviderImplementation) => void
default: {
get: () => ID | undefined
set: (providerID: ID) => void
get: () => ID | "random" | false | undefined
set: (selection: ID | "random" | false) => void
}
}
@@ -75,15 +74,14 @@ const layer = Layer.effect(
Service,
Effect.gen(function* () {
const bus = yield* Bus.Service
const kv = yield* KV.Service
const decodeResults = Schema.decodeUnknownEffect(Schema.Array(Result))
const state = State.create<Data, Draft>({
initial: () => ({ providers: new Map() }),
draft: (draft) => ({
add: (provider) => draft.providers.set(provider.id, provider),
default: {
get: () => draft.defaultProviderID,
set: (providerID) => (draft.defaultProviderID = providerID),
get: () => draft.selection,
set: (selection) => (draft.selection = selection),
},
}),
finalize: () => bus.publish(WebSearch.Event.Updated, {}).pipe(Effect.asVoid),
@@ -96,12 +94,12 @@ const layer = Layer.effect(
const defaultProvider = Effect.fn("WebSearch.default")(function* () {
const data = state.get()
const configured = data.defaultProviderID ? data.providers.get(data.defaultProviderID) : undefined
if (configured) return configured
const stored = yield* kv.get("websearch:provider")
if (stored === false) return yield* new DisabledError()
if (typeof stored !== "string") return
return data.providers.get(ID.make(stored))
if (data.selection === false) return yield* new DisabledError()
if (data.selection === "random") {
const providers = Array.from(data.providers.values())
return providers[Math.floor(Math.random() * providers.length)]
}
return data.selection ? data.providers.get(data.selection) : undefined
})
const resolve = Effect.fn("WebSearch.resolve")(function* (input: Input) {
@@ -140,5 +138,5 @@ const layer = Layer.effect(
export const node = makeLocationNode({
service: Service,
layer,
deps: [Bus.node, KV.node],
deps: [Bus.node],
})
+53 -5
View File
@@ -72,6 +72,53 @@ const provider = {
}
describe("Config", () => {
it.live("updates the first file-backed document", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
).pipe(
Effect.flatMap((tmp) => {
const global = path.join(tmp.path, "global")
const project = path.join(tmp.path, "project")
const globalFile = path.join(global, "opencode.jsonc")
const projectFile = path.join(project, "opencode.json")
return Effect.promise(async () => {
await Promise.all([fs.mkdir(global, { recursive: true }), fs.mkdir(project, { recursive: true })])
await Promise.all([
fs.writeFile(globalFile, '{\n // Keep this comment.\n "shell": "global"\n}\n'),
fs.writeFile(projectFile, JSON.stringify({ shell: "project" })),
])
}).pipe(
Effect.andThen(
Effect.gen(function* () {
const config = yield* Config.Service
const updated = yield* config.update((draft) => {
draft.shell = "updated"
})
expect(updated.shell).toBe("updated")
expect(yield* Effect.promise(() => fs.readFile(globalFile, "utf8"))).toContain("// Keep this comment.")
expect(yield* Effect.promise(() => fs.readFile(globalFile, "utf8"))).toContain('"shell": "updated"')
expect(JSON.parse(yield* Effect.promise(() => fs.readFile(projectFile, "utf8")))).toEqual({
shell: "project",
})
}).pipe(Effect.provide(testLayer(project, global))),
),
)
}),
),
)
it.effect("fails updates when no file-backed document exists", () =>
Effect.gen(function* () {
const config = yield* Config.Service
const error = yield* config.update((draft) => void draft).pipe(Effect.flip)
expect(error.message).toBe("No editable config document found")
}).pipe(
Effect.provide(Config.testLayer([new Document({ type: "document", info: new Info({ shell: "virtual" }) })])),
),
)
it.live("loads explicit file and content overrides in priority order", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
@@ -858,7 +905,7 @@ describe("Config", () => {
expect(documents.map((document) => document.type)).toEqual(["document", "document"])
expect(documents.map((document) => document.info.$schema)).toEqual(["base", "last"])
expect(documents[0]).toBeInstanceOf(Document)
expect(documents[0]?.path).toBe(path.join(tmp.path, "opencode.json"))
expect(documents[0]?.path).toBe(AbsolutePath.make(path.join(tmp.path, "opencode.json")))
expect(documents[1]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info)
yield* Effect.promise(() =>
@@ -1405,9 +1452,14 @@ describe("Config", () => {
)
return yield* Effect.gen(function* () {
const config = yield* Config.Service
const watcher = yield* Watcher.Test
const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
expect(documents.map((document) => document.info.$schema)).toEqual(["base"])
expect(yield* watcher.subscriptions()).toContainEqual({
path: path.join(tmp.path, "opencode.jsonc"),
type: "file",
})
}).pipe(Effect.provide(testLayer(tmp.path)))
}),
),
@@ -1491,13 +1543,9 @@ describe("Config", () => {
"global",
AbsolutePath.make(global),
"outside",
AbsolutePath.make(path.join(tmp.path, "opencode.json")),
"root",
AbsolutePath.make(path.join(root, "opencode.json")),
"parent",
AbsolutePath.make(path.join(parent, "opencode.jsonc")),
"directory",
AbsolutePath.make(path.join(directory, "opencode.json")),
"root-dot",
AbsolutePath.make(path.join(root, ".opencode")),
"directory-dot",
+2 -1
View File
@@ -18,6 +18,7 @@ import { Provider } from "@opencode-ai/core/provider"
import { Reference } from "@opencode-ai/core/reference"
import { Skill } from "@opencode-ai/core/skill"
import { Effect, Schema } from "effect"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "../plugin/fixture"
@@ -79,7 +80,7 @@ describe("config plugin reloads", () => {
function config(name: string) {
return new Document({
type: "document",
path: document,
path: AbsolutePath.make(document),
info: decode({
agents: { [name]: { description: `${title(name)} agent`, mode: "subagent" } },
commands: { [name]: { template: `${title(name)} command`, description: `${title(name)} command` } },
+2 -11
View File
@@ -1,7 +1,7 @@
import fs from "fs/promises"
import path from "path"
import { describe, expect } from "bun:test"
import { Effect, Layer, Schema, Stream } from "effect"
import { Effect, Layer, Schema } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { Npm } from "@opencode-ai/util/npm"
@@ -27,16 +27,7 @@ function formatterLayer(directory: string, configured?: ConfigInput["formatter"]
}),
]
return AppNodeBuilder.build(Formatter.node, [
[
Config.node,
Layer.succeed(
Config.Service,
Config.Service.of({
entries: () => Effect.succeed(entries),
changes: () => Stream.empty,
}),
),
],
[Config.node, Config.testLayer(entries)],
[
Location.node,
Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(directory) }))),
+5 -1
View File
@@ -185,7 +185,11 @@ function resourceMcpLayer(
overrides?.entries
? Layer.succeed(
Config.Service,
Config.Service.of({ entries: overrides.entries, changes: () => Stream.never }),
Config.Service.of({
entries: overrides.entries,
update: () => Effect.die("unused config update"),
changes: () => Stream.never,
}),
)
: Config.testLayer([
new Document({
+4 -1
View File
@@ -388,7 +388,10 @@ export function webSearchHost(websearch: WebSearch.Interface): Plugin.Context["w
}),
default: {
get: draft.default.get,
set: (providerID) => draft.default.set(WebSearch.ID.make(providerID)),
set: (selection) =>
draft.default.set(
selection === false || selection === "random" ? selection : WebSearch.ID.make(selection),
),
},
})
}),
+88
View File
@@ -4,6 +4,7 @@ import { DateTime, Effect, Schema } from "effect"
import { Agent } from "@opencode-ai/core/agent"
import { Catalog } from "@opencode-ai/core/catalog"
import { Model } from "@opencode-ai/core/model"
import { Location } from "@opencode-ai/core/location"
import { Plugin } from "@opencode-ai/core/plugin"
import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { PluginHost } from "@opencode-ai/core/plugin/host"
@@ -14,7 +15,10 @@ import { SessionMessage } from "@opencode-ai/core/session/message"
import { SessionInbox } from "@opencode-ai/core/session/inbox"
import { Tool } from "@opencode-ai/core/tool"
import { Provider } from "@opencode-ai/core/provider"
import { Project } from "@opencode-ai/core/project"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { define } from "@opencode-ai/plugin/promise/plugin"
import { Money } from "@opencode-ai/schema/money"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -23,6 +27,53 @@ import { host as testHost } from "./host"
const it = testEffect(PluginTestLayer)
describe("fromPromise", () => {
it.effect("adapts session creation through the protocol schema", () =>
Effect.gen(function* () {
let seen: unknown
const host = testHost({
session: {
create: (input) => {
seen = input
return Effect.succeed(
Session.Info.make({
id: Session.ID.make("ses_protocol_adapter"),
projectID: Project.ID.make("project"),
cost: Money.USD.make(0),
tokens: { input: 1, output: 2, reasoning: 3, cache: { read: 4, write: 5 } },
time: { created: DateTime.makeUnsafe(10), updated: DateTime.makeUnsafe(20) },
title: input?.title,
location: Location.Ref.make({ directory: AbsolutePath.make("/workspace") }),
}),
)
},
},
})
yield* PluginPromise.fromPromise(
define({
id: "promise-session-create",
setup: async (ctx) => {
await expect(Reflect.apply(ctx.session.create, undefined, [{ title: 42 }])).rejects.toBeDefined()
const result = await ctx.session.create({
id: null,
title: "Promise title",
agent: null,
model: null,
location: null,
})
expect(result).toMatchObject({
id: "ses_protocol_adapter",
title: "Promise title",
time: { created: 10, updated: 20 },
})
},
}),
).effect(host)
expect(seen).toEqual({ title: "Promise title" })
}),
)
it.effect("forwards transient session generation", () =>
Effect.gen(function* () {
const host = testHost({
@@ -44,6 +95,42 @@ describe("fromPromise", () => {
}),
)
it.effect("preserves no-content and rejected Promise behavior", () =>
Effect.gen(function* () {
const seen: unknown[] = []
const host = testHost({
session: {
interrupt: (input) => {
if (input.sessionID === Session.ID.make("ses_failure")) {
return Effect.fail(new Error("interrupt failed"))
}
expect(input.continue).toBe(true)
return Effect.void
},
rename: (input) => Effect.sync(() => seen.push(input)),
wait: (input) => Effect.sync(() => seen.push(input)),
},
})
yield* PluginPromise.fromPromise(
define({
id: "promise-session-interrupt",
setup: async (ctx) => {
expect(await ctx.session.interrupt({ sessionID: "ses_success", continue: true })).toBeUndefined()
await expect(ctx.session.interrupt({ sessionID: "ses_failure" })).rejects.toThrow("interrupt failed")
expect(await ctx.session.rename({ sessionID: "ses_success", title: "Renamed" })).toBeUndefined()
expect(await ctx.session.wait({ sessionID: "ses_success" })).toBeUndefined()
},
}),
).effect(host)
expect(seen).toEqual([
{ sessionID: Session.ID.make("ses_success"), title: "Renamed" },
{ sessionID: Session.ID.make("ses_success") },
])
}),
)
it.effect("forwards synthetic session input", () =>
Effect.gen(function* () {
const input = {
@@ -114,6 +201,7 @@ describe("fromPromise", () => {
ctx.skill.list(),
])
seen.push(...results.map((result) => result.location.directory))
expect((await ctx.integration.get({ integrationID: "missing" })).data).toBeNull()
},
})
@@ -7,6 +7,7 @@ import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { SystemPromptPlugin } from "@opencode-ai/core/plugin/system-prompt"
import { Session } from "@opencode-ai/core/session"
import { SessionSystemPrompt } from "@opencode-ai/core/session/system-prompt"
import type { SessionHooks } from "@opencode-ai/plugin/effect/session"
import { Model } from "@opencode-ai/schema/model"
import { Provider } from "@opencode-ai/schema/provider"
@@ -14,10 +15,9 @@ import { Effect } from "effect"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
import PROMPT_META from "../../src/plugin/system-prompt/meta.txt"
import PROMPT_DEFAULT from "../../src/session/runner/prompt/base.txt"
const it = testEffect(PluginTestLayer)
const fallback = PROMPT_DEFAULT
const fallback = SessionSystemPrompt.make([])
const makeHost = Effect.gen(function* () {
const agents = yield* Agent.Service
const plugins = yield* Plugin.Service
@@ -74,7 +74,7 @@ describe("SystemPromptPlugin", () => {
["kimi-k2", "# Prompt and Tool Use"],
["trinity", "what command should I run to list files"],
["meta/muse-spark-1.1", "powered by Muse Spark"],
["llama-3.3", "You are opencode, an interactive CLI tool"],
["llama-3.3", fallback],
] as const
yield* Effect.forEach(
+2 -2
View File
@@ -71,6 +71,7 @@ import { InstructionDiscovery } from "@opencode-ai/core/instruction-discovery"
import { SkillInstructions } from "@opencode-ai/core/skill/instructions"
import { ReferenceInstructions } from "@opencode-ai/core/reference/instructions"
import { McpInstructions } from "@opencode-ai/core/mcp/instructions"
import { SessionSystemPrompt } from "@opencode-ai/core/session/system-prompt"
import { ID } from "@opencode-ai/core/model"
import { Location } from "@opencode-ai/core/location"
import { Provider } from "@opencode-ai/core/provider"
@@ -81,7 +82,6 @@ import { asc, desc, eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
import { permissionLayer } from "./lib/permission"
import { agentHost, catalogHost, host } from "./plugin/host"
import PROMPT_DEFAULT from "../src/session/runner/prompt/base.txt"
import { CodeModeInstructions } from "@opencode-ai/core/codemode/instructions"
let requests: LLMRequest[] = []
@@ -147,7 +147,7 @@ const modelTransport = Layer.succeed(
}),
)
const model = LanguageModel.make({ id: "fake-model", provider: "fake", route: OpenAIChat.route })
const defaultSystem = PROMPT_DEFAULT
const defaultSystem = SessionSystemPrompt.make([])
const replacementModel = LanguageModel.make({ id: "replacement", provider: "fake", route: OpenAIChat.route })
const compactModel = LanguageModel.make({
id: "compact",
@@ -0,0 +1,8 @@
import { expect, test } from "bun:test"
import { SessionSystemPrompt } from "@opencode-ai/core/session/system-prompt"
test("renders the default system prompt instructions", () => {
const prompt = SessionSystemPrompt.make(["edit", "read", "shell"])
expect(prompt).not.toContain("${OPENCODE_TOOL_GUIDANCE}")
expect(prompt).toContain("Use the edit tool for targeted changes to existing text files")
})
+2 -8
View File
@@ -1,6 +1,6 @@
import { describe, expect } from "bun:test"
import path from "path"
import { Effect, Layer, Stream } from "effect"
import { Effect } from "effect"
import { Config } from "@opencode-ai/core/config"
import { Document, Info } from "@opencode-ai/schema/config"
import { ConfigToolOutput } from "@opencode-ai/schema/config/tool-output"
@@ -20,13 +20,7 @@ const withStore = <A, E, R>(
Effect.acquireUseRelease(
Effect.promise(() => tmpdir()),
(tmp) => {
const config = Layer.succeed(
Config.Service,
Config.Service.of({
entries: () => Effect.succeed([new Document({ type: "document", info })]),
changes: () => Stream.empty,
}),
)
const config = Config.testLayer([new Document({ type: "document", info })])
const layer = AppNodeBuilder.build(LayerNode.group([ToolOutput.node, FSUtil.node]), [
[Config.node, config],
[Global.node, Global.layerWith({ data: tmp.path })],
+57 -26
View File
@@ -1,12 +1,13 @@
import { beforeEach, describe, expect } from "bun:test"
import { Deferred, Effect, Layer } from "effect"
import { Deferred, Effect, Layer, Stream } from "effect"
import { HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Permission } from "@opencode-ai/core/permission"
import { Config } from "@opencode-ai/core/config"
import { Form } from "@opencode-ai/core/form"
import { KV } from "@opencode-ai/core/kv"
import { WebSearch } from "@opencode-ai/core/websearch"
import { Document, Info } from "@opencode-ai/schema/config"
import { Session } from "@opencode-ai/core/session"
import { toSessionError } from "@opencode-ai/core/session/to-session-error"
import { Tool } from "@opencode-ai/core/tool"
@@ -18,6 +19,7 @@ import { imagePassthrough } from "./lib/image"
import { permissionLayer } from "./lib/permission"
import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool"
import { webSearchHost } from "./plugin/host"
import { produce } from "immer"
const webSearchToolNode = makeLocationNode({
name: "test/websearch-tool-plugin",
@@ -27,14 +29,14 @@ const webSearchToolNode = makeLocationNode({
yield* registerToolPlugin(WebSearchTool.Plugin, { websearch: webSearchHost(websearch) })
}),
),
deps: [Tool.node, Permission.node, WebSearch.node, Form.node, KV.node],
deps: [Tool.node, Permission.node, WebSearch.node, Form.node, Config.node],
})
const sessionID = Session.ID.make("ses_websearch_test")
const assertions: Permission.AssertInput[] = []
const queries: WebSearch.Input[] = []
const formRequests: Form.CreateInput[] = []
const values = new Map<string, KV.Value>()
let selection: WebSearch.ID | "random" | false | undefined
const providers = [
{ id: WebSearch.ID.make("exa"), name: "Exa" },
{ id: WebSearch.ID.make("parallel"), name: "Parallel" },
@@ -54,7 +56,7 @@ beforeEach(() => {
assertions.length = 0
queries.length = 0
formRequests.length = 0
values.clear()
selection = undefined
providerRequired = false
formResponse = { status: "cancelled" }
formResponses.length = 0
@@ -73,28 +75,39 @@ const permission = permissionLayer({
const websearch = Layer.succeed(
WebSearch.Service,
WebSearch.Service.of({
transform: () => Effect.die("unused"),
transform: (transform) =>
Effect.sync(() => {
transform({
add: () => undefined,
default: {
get: () => selection,
set: (next) => (selection = next),
},
})
return { dispose: Effect.void }
}),
reload: () => Effect.die("unused"),
providers: () => Effect.succeed(providers),
default: () =>
Effect.gen(function* () {
const stored = values.get("websearch:provider")
if (stored === false) return yield* new WebSearch.DisabledError()
return typeof stored === "string" ? providers.find((provider) => provider.id === stored) : undefined
if (selection === false) return yield* new WebSearch.DisabledError()
return selection ? providers.find((provider) => provider.id === selection) : undefined
}),
query: (input) =>
Effect.gen(function* () {
queries.push(input)
const stored = values.get("websearch:provider")
if (queryBarrier && synchronizedQueries < 5) {
synchronizedQueries++
if (synchronizedQueries === 5) yield* Deferred.succeed(queryBarrier, undefined)
yield* Deferred.await(queryBarrier)
}
if (queryError) return yield* queryError
if (providerRequired && typeof stored !== "string") return yield* new WebSearch.ProviderRequiredError()
if (typeof stored === "string")
return new WebSearch.Response({ providerID: WebSearch.ID.make(stored), results: result.results })
if (providerRequired && !selection) return yield* new WebSearch.ProviderRequiredError()
if (selection)
return new WebSearch.Response({
providerID: selection === "random" ? result.providerID : WebSearch.ID.make(selection),
results: result.results,
})
return result
}),
}),
@@ -115,12 +128,30 @@ const form = Layer.succeed(
cancel: () => Effect.die("unused"),
}),
)
const kv = Layer.succeed(
KV.Service,
KV.Service.of({
get: (key) => Effect.succeed(values.get(key)),
set: (key, value) => Effect.sync(() => values.set(key, value)).pipe(Effect.asVoid),
remove: (key) => Effect.sync(() => values.delete(key)).pipe(Effect.asVoid),
const config = Layer.succeed(
Config.Service,
Config.Service.of({
entries: () =>
Effect.succeed([
new Document({
type: "document",
info: new Info({
websearch: selection === undefined ? undefined : selection === false ? false : { provider: selection },
}),
}),
]),
update: (update) =>
Effect.sync(() => {
const info = produce(
new Info({
websearch: selection === undefined ? undefined : selection === false ? false : { provider: selection },
}),
update,
)
selection = info.websearch === false ? false : info.websearch?.provider
return info
}),
changes: () => Stream.never,
}),
)
const it = testEffect(
@@ -128,7 +159,7 @@ const it = testEffect(
[Permission.node, permission],
[WebSearch.node, websearch],
[Form.node, form],
[KV.node, kv],
[Config.node, config],
[Image.node, imagePassthrough],
]),
)
@@ -247,7 +278,7 @@ describe("WebSearchTool registration", () => {
call: { type: "tool-call", id: "call-enable", name: "websearch", input: { query: "effect" } },
}),
).toMatchObject({ status: "completed", metadata: { provider: "exa" } })
expect(values.get("websearch:provider")).toBe("exa")
expect(selection).toBe("random")
expect(queries).toHaveLength(2)
expect(formRequests).toEqual([
{
@@ -264,7 +295,7 @@ describe("WebSearchTool registration", () => {
options: [
{
value: "allow",
label: "Allow web search via Exa",
label: "Allow search via Exa, Parallel",
},
{
value: "choose",
@@ -305,7 +336,7 @@ describe("WebSearchTool registration", () => {
call: { type: "tool-call", id: "call-choose", name: "websearch", input: { query: "effect" } },
}),
).toMatchObject({ status: "completed", metadata: { provider: "parallel" } })
expect(values.get("websearch:provider")).toBe("parallel")
expect(selection).toBe(WebSearch.ID.make("parallel"))
expect(queries).toHaveLength(2)
expect(formRequests[1]).toEqual({
sessionID,
@@ -353,7 +384,7 @@ describe("WebSearchTool registration", () => {
expect(results.every((item) => item.status === "completed")).toBe(true)
expect(formRequests).toHaveLength(1)
expect(values.get("websearch:provider")).toBe("exa")
expect(selection).toBe("random")
}),
)
@@ -370,7 +401,7 @@ describe("WebSearchTool registration", () => {
call: { type: "tool-call", id: "call-disable", name: "websearch", input: { query: "effect" } },
}),
).toMatchObject({ status: "error" })
expect(values.get("websearch:provider")).toBe(false)
expect(selection).toBe(false)
expect(queries).toHaveLength(1)
}),
)
@@ -379,7 +410,7 @@ describe("WebSearchTool registration", () => {
Effect.gen(function* () {
const registry = yield* Tool.Service
const tools = yield* registry.snapshot()
values.set("websearch:provider", "exa")
selection = WebSearch.ID.make("exa")
yield* Effect.forEach(
[
+6 -11
View File
@@ -3,11 +3,10 @@ import { Effect, Exit, Scope } from "effect"
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
import { Bus } from "@opencode-ai/core/bus"
import { KV } from "@opencode-ai/core/kv"
import { WebSearch } from "@opencode-ai/core/websearch"
import { testEffect } from "./lib/effect"
const it = testEffect(AppNodeBuilder.build(LayerNode.group([WebSearch.node, Bus.node, KV.node])))
const it = testEffect(AppNodeBuilder.build(LayerNode.group([WebSearch.node, Bus.node])))
const register = (id: string) =>
Effect.gen(function* () {
@@ -81,16 +80,14 @@ describe("WebSearch", () => {
}),
)
it.effect("uses the provider stored in KV", () =>
it.effect("chooses a registered provider for random selection", () =>
Effect.gen(function* () {
yield* register("exa")
const parallel = yield* register("parallel")
yield* register("parallel")
const websearch = yield* WebSearch.Service
const kv = yield* KV.Service
yield* kv.set("websearch:provider", parallel.providerID)
yield* websearch.transform((draft) => draft.default.set("random"))
expect((yield* websearch.query({ query: "stored" })).providerID).toBe(parallel.providerID)
yield* kv.remove("websearch:provider")
expect(["exa", "parallel"]).toContain((yield* websearch.query({ query: "random" })).providerID)
}),
)
@@ -98,11 +95,9 @@ describe("WebSearch", () => {
Effect.gen(function* () {
yield* register("exa")
const websearch = yield* WebSearch.Service
const kv = yield* KV.Service
yield* kv.set("websearch:provider", false)
yield* websearch.transform((draft) => draft.default.set(false))
expect((yield* websearch.query({ query: "disabled" }).pipe(Effect.flip))._tag).toBe("WebSearch.Disabled")
yield* kv.remove("websearch:provider")
}),
)
+1
View File
@@ -23,6 +23,7 @@
"@ai-sdk/provider": "3.0.8",
"@opencode-ai/ai": "workspace:*",
"@opencode-ai/client": "workspace:*",
"@opencode-ai/protocol": "workspace:*",
"@opencode-ai/schema": "workspace:*",
"@opencode-ai/sdk": "1.18.5",
"@standard-schema/spec": "catalog:",
+2 -2
View File
@@ -17,7 +17,7 @@ export interface WebSearchDomain extends WebsearchApi<unknown> {
export interface WebSearchDraft {
add(definition: WebSearchDefinition): void
readonly default: {
get(): string | undefined
set(providerID: string): void
get(): string | false | undefined
set(selection: string | false): void
}
}
+324
View File
@@ -0,0 +1,324 @@
import { Tool } from "@opencode-ai/schema/tool"
import { Effect, Schema, SchemaAST, Scope, Stream } from "effect"
import { HttpApiEndpoint, HttpApiSchema } from "effect/unstable/httpapi"
import { define } from "../effect/plugin.js"
import type { Context, Plugin } from "./plugin.js"
import type { Info } from "./tool.js"
type HostRegistration = { readonly dispose: Effect.Effect<void> }
type Registration = { readonly dispose: () => Promise<void> }
type PromiseEvent = ReturnType<Context["event"]["subscribe"]> extends AsyncIterable<infer Event> ? Event : never
interface CompiledEndpoint {
readonly decode: ReadonlyArray<(input: unknown) => Effect.Effect<unknown, Schema.SchemaError>>
readonly encode: (output: unknown) => Effect.Effect<unknown, Schema.SchemaError>
readonly noContent: boolean
}
const compiledEndpoints = new WeakMap<object, CompiledEndpoint>()
function compileEndpoint(endpoint: HttpApiEndpoint.Top) {
const cached = compiledEndpoints.get(endpoint)
if (cached) return cached
const payloadSchemas = Array.from(endpoint.payload.values()).flatMap(({ schemas }) => schemas)
const successSchemas = Array.from(endpoint.success)
if (payloadSchemas.length > 1 || successSchemas.length > 1) {
throw new Error(`Unsupported API schema cardinality: ${endpoint.identifier}`)
}
const inputs = [
endpoint.params,
endpoint.query === undefined ? undefined : Schema.toType(endpoint.query),
endpoint.headers,
...payloadSchemas,
].filter((schema): schema is Schema.Top => schema !== undefined) as Array<RuntimeSchema>
const success = (successSchemas[0] ?? HttpApiSchema.NoContent) as RuntimeSchema
const noContent = HttpApiSchema.isNoContent(success.ast)
const type = Schema.toType(success).ast
const data = SchemaAST.isObjects(success.ast)
? success.ast.propertySignatures.find((property) => property.name === "data")
: undefined
const output =
!noContent &&
SchemaAST.isObjects(type) &&
type.indexSignatures.length === 0 &&
type.propertySignatures.length === 1 &&
type.propertySignatures[0]?.name === "data" &&
data !== undefined
? (Schema.make<Schema.Top>(data.type) as RuntimeSchema)
: success
const compiled = {
decode: inputs.map((schema) => Schema.decodeUnknownEffect(schema)),
encode: Schema.encodeUnknownEffect(output),
noContent,
} satisfies CompiledEndpoint
compiledEndpoints.set(endpoint, compiled)
return compiled
}
/**
* Adapts a Promise plugin into an Effect plugin so the existing Effect-only
* loader (`Plugin` / `PluginSupervisor`) can run it unchanged.
*
* Hook registrations created during the async `setup` attach to the plugin's
* scope, so unloading the plugin disposes them. The captured fiber context
* preserves boot-time batching, so Promise-plugin transforms still coalesce
* into one reload per domain.
*/
export function fromPromise(plugin: Plugin) {
return define({
id: plugin.id,
effect: (host) =>
Effect.gen(function* () {
const [{ ClientApi }, { OpenCodeEvent }] = yield* Effect.promise(() =>
Promise.all([import("@opencode-ai/protocol/client"), import("@opencode-ai/protocol/groups/event")]),
)
const AgentEndpoints = ClientApi.groups["server.agent"].endpoints
const CommandEndpoints = ClientApi.groups["server.command"].endpoints
const IntegrationEndpoints = ClientApi.groups["server.integration"].endpoints
const ModelEndpoints = ClientApi.groups["server.model"].endpoints
const PluginEndpoints = ClientApi.groups["server.plugin"].endpoints
const ProviderEndpoints = ClientApi.groups["server.provider"].endpoints
const ReferenceEndpoints = ClientApi.groups["server.reference"].endpoints
const SessionEndpoints = ClientApi.groups["server.session"].endpoints
const SkillEndpoints = ClientApi.groups["server.skill"].endpoints
const WebSearchEndpoints = ClientApi.groups["server.websearch"].endpoints
const scope = yield* Scope.Scope
const context = yield* Effect.context<Scope.Scope>()
// Run a hook registration on the plugin scope and resolve once it is registered.
const register = (effect: Effect.Effect<HostRegistration, never, Scope.Scope>): Promise<Registration> =>
Effect.runPromiseWith(context)(Scope.provide(scope)(effect)).then((registration) => ({
dispose: () => Effect.runPromiseWith(context)(registration.dispose),
}))
const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromiseWith(context)(effect)
const adaptApiMethod = <PromiseMethod>(
endpoint: HttpApiEndpoint.Top,
method: (input: never) => Effect.Effect<unknown, unknown>,
) => {
const compiled = compileEndpoint(endpoint)
return ((input?: unknown) =>
Effect.gen(function* () {
const decoded = yield* Effect.forEach(compiled.decode, (decode) => decode(input ?? {}))
const result = yield* method(Object.assign({}, ...decoded) as never)
if (compiled.noContent) return undefined
return yield* compiled.encode(result)
}).pipe(Effect.runPromiseWith(context))) as PromiseMethod
}
const transform =
<Draft>(domain: {
transform: (callback: (draft: Draft) => void) => Effect.Effect<HostRegistration, never, Scope.Scope>
}) =>
(callback: (draft: Draft) => void) =>
register(
domain.transform((draft) => {
callback(draft)
}),
)
const context2: Context = {
app: host.app,
options: host.options,
agent: {
get: adaptApiMethod(AgentEndpoints["agent.get"], host.agent.get),
list: adaptApiMethod(AgentEndpoints["agent.list"], host.agent.list),
transform: transform(host.agent),
reload: () => run(host.agent.reload()),
},
aisdk: {
hook: (name, callback) =>
register(host.aisdk.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
catalog: {
provider: {
list: adaptApiMethod(ProviderEndpoints["provider.list"], host.catalog.provider.list),
get: adaptApiMethod(ProviderEndpoints["provider.get"], host.catalog.provider.get),
},
model: {
list: adaptApiMethod(ModelEndpoints["model.list"], host.catalog.model.list),
default: adaptApiMethod(ModelEndpoints["model.default"], host.catalog.model.default),
},
transform: transform(host.catalog),
reload: () => run(host.catalog.reload()),
},
command: {
list: adaptApiMethod(CommandEndpoints["command.list"], host.command.list),
transform: transform(host.command),
reload: () => run(host.command.reload()),
},
event: {
subscribe: () =>
Stream.toAsyncIterable(
host.event.subscribe().pipe(
Stream.mapEffect((event) => Schema.encodeUnknownEffect(OpenCodeEvent)(event)),
Stream.map((event) => event as unknown as PromiseEvent),
),
),
},
integration: {
list: adaptApiMethod(IntegrationEndpoints["integration.list"], host.integration.list),
get: adaptApiMethod(IntegrationEndpoints["integration.get"], host.integration.get),
connect: {
key: adaptApiMethod(IntegrationEndpoints["integration.connect.key"], host.integration.connect.key),
},
oauth: {
connect: adaptApiMethod(
IntegrationEndpoints["integration.oauth.connect"],
host.integration.oauth.connect,
),
status: adaptApiMethod(IntegrationEndpoints["integration.oauth.status"], host.integration.oauth.status),
complete: adaptApiMethod(
IntegrationEndpoints["integration.oauth.complete"],
host.integration.oauth.complete,
),
cancel: adaptApiMethod(IntegrationEndpoints["integration.oauth.cancel"], host.integration.oauth.cancel),
},
command: {
connect: adaptApiMethod(
IntegrationEndpoints["integration.command.connect"],
host.integration.command.connect,
),
status: adaptApiMethod(
IntegrationEndpoints["integration.command.status"],
host.integration.command.status,
),
cancel: adaptApiMethod(
IntegrationEndpoints["integration.command.cancel"],
host.integration.command.cancel,
),
},
transform: (callback) =>
register(
host.integration.transform((draft) =>
callback({
list: draft.list,
get: draft.get,
update: draft.update,
remove: draft.remove,
method: {
list: draft.method.list,
update: (input) => {
if (!("authorize" in input)) return draft.method.update(input)
const refresh = input.refresh
draft.method.update({
...input,
authorize: (answer) =>
Effect.promise(() => input.authorize(answer)).pipe(
Effect.map((authorization) =>
authorization.mode === "auto"
? {
...authorization,
callback: Effect.promise(() => authorization.callback),
}
: {
...authorization,
callback: (code) => Effect.promise(() => authorization.callback(code)),
},
),
),
refresh:
refresh === undefined
? undefined
: (credential) => Effect.promise(() => refresh(credential)),
})
},
remove: draft.method.remove,
},
}),
),
),
reload: () => run(host.integration.reload()),
connection: {
active: (id) => Effect.runPromiseWith(context)(host.integration.connection.active(id)),
resolve: (connection) => Effect.runPromiseWith(context)(host.integration.connection.resolve(connection)),
},
},
plugin: {
list: adaptApiMethod(PluginEndpoints["plugin.list"], host.plugin.list),
},
reference: {
list: adaptApiMethod(ReferenceEndpoints["reference.list"], host.reference.list),
transform: transform(host.reference),
reload: () => run(host.reference.reload()),
},
skill: {
list: adaptApiMethod(SkillEndpoints["skill.list"], host.skill.list),
transform: transform(host.skill),
reload: () => run(host.skill.reload()),
},
tool: {
transform: (callback) =>
register(
host.tool.transform((draft) =>
callback({
add: (tool: Info) =>
draft.add({
...tool,
execute: (input, context) => executePromiseTool(tool, input, context),
}),
}),
),
),
hook: (name, callback) =>
register(host.tool.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
websearch: {
providers: adaptApiMethod(WebSearchEndpoints["websearch.providers"], host.websearch.providers),
query: adaptApiMethod(WebSearchEndpoints["websearch.query"], host.websearch.query),
reload: () => run(host.websearch.reload()),
transform: (callback) =>
register(
host.websearch.transform((draft) => {
callback({
add: (definition) =>
draft.add({
id: definition.id,
name: definition.name,
execute: (input) => attempt((signal) => definition.execute(input, { signal })),
}),
default: draft.default,
})
}),
),
},
session: {
hook: (name, callback) =>
register(host.session.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
create: adaptApiMethod(SessionEndpoints["session.create"], host.session.create),
get: adaptApiMethod(SessionEndpoints["session.get"], host.session.get),
prompt: adaptApiMethod(SessionEndpoints["session.prompt"], host.session.prompt),
generate: adaptApiMethod(SessionEndpoints["session.generate"], host.session.generate),
command: adaptApiMethod(SessionEndpoints["session.command"], host.session.command),
synthetic: adaptApiMethod(SessionEndpoints["session.synthetic"], host.session.synthetic),
interrupt: adaptApiMethod(SessionEndpoints["session.interrupt"], host.session.interrupt),
rename: adaptApiMethod(SessionEndpoints["session.rename"], host.session.rename),
wait: adaptApiMethod(SessionEndpoints["session.wait"], host.session.wait),
},
shell: {
hook: (name, callback) =>
register(host.shell.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
}
const cleanup = yield* Effect.promise(() => Promise.resolve(plugin.setup(context2)))
if (!cleanup) return
yield* Effect.addFinalizer(() => Effect.promise(() => Promise.resolve(cleanup())))
}),
})
}
function attempt<A>(evaluate: (signal: AbortSignal) => PromiseLike<A>) {
return Effect.tryPromise({ try: evaluate, catch: (cause) => cause })
}
type RuntimeSchema = Schema.Codec<unknown, unknown>
const executePromiseTool = (tool: Info, input: any, context: Tool.Context) =>
Effect.promise(() =>
tool.execute(input, {
...context,
progress: (update) => Effect.runPromise(context.progress(update)),
}),
)
+1 -1
View File
@@ -38,7 +38,7 @@ export interface SessionHooks {
export type SessionDomain = Pick<
SessionApi,
"create" | "get" | "prompt" | "generate" | "command" | "synthetic" | "interrupt"
"create" | "get" | "prompt" | "generate" | "command" | "synthetic" | "interrupt" | "rename" | "wait"
> & {
readonly hook: Hooks<SessionHooks>
}
+2 -2
View File
@@ -19,7 +19,7 @@ export interface WebSearchDomain extends WebSearchApi {
export interface WebSearchDraft {
add(definition: WebSearchDefinition): void
readonly default: {
get(): string | undefined
set(providerID: string): void
get(): string | false | undefined
set(selection: string | false): void
}
}
+28 -26
View File
@@ -10534,7 +10534,7 @@
"summary": "List references"
}
},
"/api/experimental/project/{projectID}/worktree": {
"/api/worktree/{projectID}": {
"get": {
"tags": ["worktree"],
"operationId": "v2.worktree.list",
@@ -10736,7 +10736,7 @@
}
}
},
"/api/experimental/project/{projectID}/worktree/refresh": {
"/api/worktree/{projectID}/refresh": {
"post": {
"tags": ["worktree"],
"operationId": "v2.worktree.refresh",
@@ -23517,6 +23517,24 @@
"required": ["path"],
"additionalProperties": false
},
"ConfigWebSearch.Info": {
"type": "object",
"properties": {
"provider": {
"anyOf": [
{
"type": "string",
"enum": ["random"]
},
{
"type": "string"
}
]
}
},
"required": ["provider"],
"additionalProperties": false
},
"Config.Plugin.Entry": {
"type": "object",
"properties": {
@@ -24035,14 +24053,15 @@
}
},
"websearch": {
"type": "object",
"properties": {
"provider": {
"type": "string"
"anyOf": [
{
"type": "boolean",
"enum": [false]
},
{
"$ref": "#/components/schemas/ConfigWebSearch.Info"
}
},
"required": ["provider"],
"additionalProperties": false
]
},
"plugins": {
"type": "array",
@@ -24145,20 +24164,6 @@
"required": ["type", "path"],
"additionalProperties": false
},
"Config.File": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["file"]
},
"path": {
"type": "string"
}
},
"required": ["type", "path"],
"additionalProperties": false
},
"Config.AgentsDirectory": {
"type": "object",
"properties": {
@@ -24195,9 +24200,6 @@
{
"$ref": "#/components/schemas/Config.Directory"
},
{
"$ref": "#/components/schemas/Config.File"
},
{
"$ref": "#/components/schemas/Config.AgentsDirectory"
},
+1 -1
View File
@@ -3,7 +3,7 @@ import { Worktree } from "@opencode-ai/schema/worktree"
import { Schema, Struct } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
const root = "/api/experimental/project/:projectID/worktree"
const root = "/api/worktree/:projectID"
export class WorktreeError extends Schema.ErrorClass<WorktreeError>("WorktreeError")(
{
+62 -30
View File
@@ -22,13 +22,24 @@ export namespace JsonRpc {
data: Schema.optional(Schema.Json),
})
export const Response = Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
id: JsonRpcID,
result: Schema.optional(Schema.Json),
error: Schema.optional(ErrorObject),
})
export interface Response extends Schema.Schema.Type<typeof Response> {}
export const Response = Schema.Union(
[
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
id: JsonRpcID,
result: Schema.Json,
error: Schema.optionalKey(Schema.Never),
}),
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
id: JsonRpcID,
result: Schema.optionalKey(Schema.Never),
error: ErrorObject,
}),
],
{ mode: "oneOf" },
)
export type Response = Schema.Schema.Type<typeof Response>
export const decodeRequest = Schema.decodeUnknownSync(Request)
@@ -49,6 +60,28 @@ export namespace JsonRpc {
}
}
export class SimulationRequestError extends Schema.TaggedErrorClass<SimulationRequestError>()(
"SimulationRequestError",
{
method: Schema.String,
code: Schema.Number,
message: Schema.String,
data: Schema.optionalKey(Schema.Json),
},
) {}
const request = <
const Tag extends string,
Payload extends Schema.Top | Schema.Struct.Fields = typeof Schema.Void,
Success extends Schema.Top = typeof Schema.Void,
>(
tag: Tag,
options?: {
readonly payload?: Payload
readonly success?: Success
},
) => Rpc.make(tag, { ...options, error: SimulationRequestError })
export namespace Handshake {
export const ProtocolVersion = Schema.Literal(1)
export type ProtocolVersion = Schema.Schema.Type<typeof ProtocolVersion>
@@ -81,7 +114,7 @@ export namespace Handshake {
protocolVersion: ProtocolVersion,
role: EndpointRole,
server: Identity,
capabilities: Schema.Array(Capability),
capabilities: Schema.Array(Capability).check(Schema.isUnique()),
})
export interface Response extends Schema.Schema.Type<typeof Response> {}
@@ -564,30 +597,29 @@ export namespace Backend {
matched: Schema.Boolean,
})
export interface NetworkLogEntry extends Schema.Schema.Type<typeof NetworkLogEntry> {}
export const Notification = Schema.Union([
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
method: Schema.Literal("llm.request"),
params: ProviderInvocation,
}),
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
method: Schema.Literal("tool.invocation"),
params: ToolInvocation,
}),
Schema.Struct({
jsonrpc: Schema.Literal("2.0"),
method: Schema.Literal("tool.cancel"),
params: ToolCancellation,
}),
])
export type Notification = Schema.Schema.Type<typeof Notification>
export const decodeNotification = Schema.decodeUnknownSync(Notification)
export const decodeNotificationEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Notification))
}
export class SimulationRequestError extends Schema.TaggedErrorClass<SimulationRequestError>()(
"SimulationRequestError",
{
method: Schema.String,
code: Schema.Number,
message: Schema.String,
data: Schema.optionalKey(Schema.Json),
},
) {}
const request = <
const Tag extends string,
Payload extends Schema.Top | Schema.Struct.Fields = typeof Schema.Void,
Success extends Schema.Top = typeof Schema.Void,
>(
tag: Tag,
options?: {
readonly payload?: Payload
readonly success?: Success
},
) => Rpc.make(tag, { ...options, error: SimulationRequestError })
export const UiRpcs = RpcGroup.make(
request("simulation.handshake", { payload: Handshake.Params, success: Handshake.Response }),
request("ui.state", { success: Frontend.State }),
+1 -1
View File
@@ -14,7 +14,7 @@
- Current contracts are unversioned: use names like `Session`, `Permission`, `Question`, and identifiers like `Permission.Request`.
- Legacy contracts retained for active compatibility, persistence, or migration are explicitly `V1`: use names like `SessionV1`, `PermissionV1`, and identifiers like `PermissionV1.Request`.
- Do not preserve `V2` as the permanent name for the replacement architecture. Remove `V2` from current namespaces, brands, and identifiers as the contracts are normalized.
- Retained V1 contracts should live under a dedicated `src/v1/` subtree once the V1 isolation PR runs. New/current code must not depend on that subtree.
- Retained V1 contracts live under `src/v1/`. New/current code must not depend on that subtree.
- V1 coexistence is temporary. Keep compatibility entrypoints only where migration requires them, and delete the V1 subtree when the legacy runtime is retired.
- `@opencode-ai/protocol` and `@opencode-ai/sdk-next` are current `/api/...` surfaces.
+3 -8
View File
@@ -94,7 +94,7 @@ export class Info extends Schema.Class<Info>("Config.Info")({
references: ConfigReference.Info.pipe(optional).annotate({
description: "Named local directories or Git repositories available as external context",
}),
websearch: ConfigWebSearch.Info.pipe(optional).annotate({
websearch: ConfigWebSearch.Selection.pipe(optional).annotate({
description: "Web search provider selection",
}),
plugins: ConfigPlugin.Plugins.pipe(optional).annotate({
@@ -109,7 +109,7 @@ export class Info extends Schema.Class<Info>("Config.Info")({
export class Document extends Schema.Class<Document>("Config.Document")({
type: Schema.Literal("document"),
path: Schema.String.pipe(optional),
path: AbsolutePath.pipe(optional),
info: Info,
}) {}
@@ -118,11 +118,6 @@ export class Directory extends Schema.Class<Directory>("Config.Directory")({
path: AbsolutePath,
}) {}
export class File extends Schema.Class<File>("Config.File")({
type: Schema.Literal("file"),
path: AbsolutePath,
}) {}
export class AgentsDirectory extends Schema.Class<AgentsDirectory>("Config.AgentsDirectory")({
type: Schema.Literal("agents"),
path: AbsolutePath,
@@ -133,7 +128,7 @@ export class ClaudeDirectory extends Schema.Class<ClaudeDirectory>("Config.Claud
path: AbsolutePath,
}) {}
export const Entry = Schema.Union([Document, Directory, File, AgentsDirectory, ClaudeDirectory]).annotate({
export const Entry = Schema.Union([Document, Directory, AgentsDirectory, ClaudeDirectory]).annotate({
identifier: "Config.Entry",
})
export type Entry = typeof Entry.Type
+4 -1
View File
@@ -4,5 +4,8 @@ import { Schema } from "effect"
import { WebSearch } from "../websearch.js"
export class Info extends Schema.Class<Info>("ConfigWebSearch.Info")({
provider: WebSearch.ID,
provider: Schema.Union([Schema.Literal("random"), WebSearch.ID]),
}) {}
export const Selection = Schema.Union([Schema.Literal(false), Info])
export type Selection = typeof Selection.Type
+11 -10
View File
@@ -6,13 +6,22 @@ import { ConfigMCP } from "../src/config/mcp.js"
import { ConfigProvider } from "../src/config/provider.js"
import { Mcp } from "../src/mcp.js"
import { AbsolutePath } from "../src/schema.js"
import { WebSearch } from "../src/websearch.js"
describe("Config.Entry", () => {
test("accepts disabled, fixed, and random web search selection", () => {
const decode = Schema.decodeUnknownSync(Config.Info)
expect(decode({ websearch: false }).websearch).toBe(false)
expect(decode({ websearch: { provider: "exa" } }).websearch).toEqual({ provider: WebSearch.ID.make("exa") })
expect(decode({ websearch: { provider: "random" } }).websearch).toEqual({ provider: "random" })
})
test("round-trips every configuration entry type", () => {
const entries = [
new Config.Document({
type: "document",
path: "/project/opencode.json",
path: AbsolutePath.make("/project/opencode.json"),
info: new Config.Info({
permissions: [
{ action: "shell", resource: "*", effect: "ask" },
@@ -22,7 +31,6 @@ describe("Config.Entry", () => {
}),
new Config.Document({ type: "document", info: new Config.Info({ shell: "/bin/zsh" }) }),
new Config.Directory({ type: "directory", path: AbsolutePath.make("/project/.opencode") }),
new Config.File({ type: "file", path: AbsolutePath.make("/project/opencode.json") }),
new Config.AgentsDirectory({ type: "agents", path: AbsolutePath.make("/project/.agents") }),
new Config.ClaudeDirectory({ type: "claude", path: AbsolutePath.make("/project/.claude") }),
]
@@ -33,14 +41,7 @@ describe("Config.Entry", () => {
expect(decoded).toEqual(entries)
expect(decoded[0]).toBeInstanceOf(Config.Document)
expect(decoded[1]).not.toHaveProperty("path")
expect(decoded.map((entry) => entry.type)).toEqual([
"document",
"document",
"directory",
"file",
"agents",
"claude",
])
expect(decoded.map((entry) => entry.type)).toEqual(["document", "document", "directory", "agents", "claude"])
expect(decoded[0]?.type === "document" ? decoded[0].info.permissions : undefined).toEqual([
{ action: "shell", resource: "*", effect: "ask" },
{ action: "shell", resource: "git status", effect: "allow" },
+2 -1
View File
@@ -7,6 +7,7 @@ import { HttpServer } from "effect/unstable/http"
import { tmpdir } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { ServerProcess } from "../src/process"
import { AbsolutePath } from "@opencode-ai/schema/schema"
it.live("returns ordered config entries for the requested directory", () =>
Effect.acquireUseRelease(
@@ -57,7 +58,7 @@ it.live("returns ordered config entries for the requested directory", () =>
{ action: "shell", resource: "*", effect: "ask" },
{ action: "shell", resource: "git status", effect: "allow" },
])
expect(entries.some((entry) => entry.type === "file" && entry.path === config)).toBe(true)
expect(document?.path).toBe(AbsolutePath.make(config))
if (!Array.isArray(body)) throw new Error("Expected a config entry array")
const raw = body.find((entry) => isRecord(entry) && entry["type"] === "document" && entry["path"] === config)
if (!isRecord(raw) || !isRecord(raw["info"])) throw new Error("Expected a config document")
+1 -1
View File
@@ -36,7 +36,7 @@ it.live("lists, creates, and removes worktrees by project ID", () =>
const resolved = yield* Effect.promise(() => fetch(location, { headers }).then((response) => response.json()))
if (!isRecord(resolved) || !isRecord(resolved.project) || typeof resolved.project.id !== "string")
throw new Error("Expected resolved project")
const url = new URL(`/api/experimental/project/${resolved.project.id}/worktree`, base)
const url = new URL(`/api/worktree/${resolved.project.id}`, base)
const initial = yield* Effect.promise(() => fetch(url, { headers }).then((response) => response.json()))
expect(initial).toEqual([{ directory: project }])
+59 -1
View File
@@ -1,6 +1,64 @@
import { describe, expect, test } from "bun:test"
import { Effect, Schema } from "effect"
import { Backend, Frontend, Handshake } from "../src/protocol"
import { Backend, Frontend, Handshake, JsonRpc } from "../src/protocol"
const successResponse: Schema.Schema.Type<typeof JsonRpc.Response> = { jsonrpc: "2.0", id: 1, result: null }
// @ts-expect-error responses require one outcome
const missingResponse: Schema.Schema.Type<typeof JsonRpc.Response> = { jsonrpc: "2.0", id: 1 }
// @ts-expect-error responses cannot contain both outcomes
const invalidResponse: Schema.Schema.Type<typeof JsonRpc.Response> = {
jsonrpc: "2.0",
id: 1,
result: null,
error: { code: -32600, message: "Invalid request" },
}
void [successResponse, missingResponse, invalidResponse]
test("normalizes an omitted finish reason", () => {
expect(Backend.decodeRequest({ jsonrpc: "2.0", id: 1, method: "llm.finish", params: { id: "inv_1" } })).toMatchObject(
{ params: { id: "inv_1", reason: "stop" } },
)
})
test("decodes typed backend notifications", () => {
expect(
Backend.decodeNotification({
jsonrpc: "2.0",
method: "tool.cancel",
params: { id: "tool_1", reason: "interrupted" },
}),
).toEqual({
jsonrpc: "2.0",
method: "tool.cancel",
params: { id: "tool_1", reason: "interrupted" },
})
expect(() =>
Backend.decodeNotification({
jsonrpc: "2.0",
method: "tool.cancel",
params: { id: "tool_1", reason: "unknown" },
}),
).toThrow()
})
test("requires exactly one JSON-RPC response outcome", () => {
const decode = Schema.decodeUnknownSync(JsonRpc.Response)
expect(decode({ jsonrpc: "2.0", id: 1, result: null })).toEqual({ jsonrpc: "2.0", id: 1, result: null })
expect(decode({ jsonrpc: "2.0", id: 1, error: { code: -32600, message: "Invalid request" } })).toEqual({
jsonrpc: "2.0",
id: 1,
error: { code: -32600, message: "Invalid request" },
})
expect(() => decode({ jsonrpc: "2.0", id: 1 })).toThrow()
expect(() =>
decode({
jsonrpc: "2.0",
id: 1,
result: null,
error: { code: -32600, message: "Invalid request" },
}),
).toThrow()
})
test("decodes ui.matches text params", () => {
expect(
@@ -83,7 +83,7 @@ test("streams a Drive-controlled provider response and removes the finished invo
jsonrpc: "2.0",
id: 3,
method: "llm.finish",
params: { id: params.id, reason: "stop" },
params: { id: params.id },
}),
)
expect(yield* Queue.take(messages)).toMatchObject({ id: 3, result: { ok: true } })
+12 -2
View File
@@ -345,6 +345,7 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
let rail: { screenX: number; screenY: number } | undefined
let scroll: ScrollBoxRenderable | undefined
let didDrag = false
let addPressed = false
// A captured drag ends with a synthetic up on its drop target; do not turn that into a click.
let suppressClick = false
@@ -760,7 +761,8 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
onMouseDown={(event: MouseEvent) => {
didDrag = false
setDragging(undefined)
if (event.button !== RIGHT_MOUSE_BUTTON) return
addPressed = event.button !== RIGHT_MOUSE_BUTTON
if (addPressed) return
if (!rail) return
setContextMenu({ x: event.x, y: event.y })
event.preventDefault()
@@ -769,8 +771,11 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
onMouseUp={(event: MouseEvent) => {
if (event.button === RIGHT_MOUSE_BUTTON) return
if (suppressClick) return
if (!addPressed) return
addPressed = false
if (!newTab()) tabs.add?.()
}}
onMouseDragEnd={() => (addPressed = false)}
>
<text
width={2}
@@ -837,6 +842,7 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
const [contextMenu, setContextMenu] = createSignal<TabContextMenuState>()
let strip: { screenX: number; screenY: number } | undefined
let didDrag = false
let addPressed = false
// A captured drag ends with a synthetic up on its drop target; do not turn that into a click.
let suppressClick = false
const hueStep = () => (mode() === "light" ? 800 : 200)
@@ -1203,7 +1209,8 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
onMouseDown={(event) => {
didDrag = false
setDragging(undefined)
if (event.button !== RIGHT_MOUSE_BUTTON) return
addPressed = event.button !== RIGHT_MOUSE_BUTTON
if (addPressed) return
setContextMenu({ x: event.x, y: event.y })
event.preventDefault()
event.stopPropagation()
@@ -1211,8 +1218,11 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
onMouseUp={(event) => {
if (event.button === RIGHT_MOUSE_BUTTON) return
if (suppressClick) return
if (!addPressed) return
addPressed = false
tabs.add?.()
}}
onMouseDragEnd={() => (addPressed = false)}
>
{" + "}
</text>
@@ -247,6 +247,12 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
onCleanup(event.on("session.execution.succeeded", (evt) => markUnread(evt.data.sessionID, "activity")))
onCleanup(event.on("session.execution.interrupted", (evt) => markUnread(evt.data.sessionID, "activity")))
onCleanup(event.on("session.execution.failed", (evt) => markUnread(evt.data.sessionID, "error")))
onCleanup(
event.on("session.moved", (evt) => {
if (!enabled() || !state().tabs.some((tab) => tab.sessionID === root(evt.data.sessionID))) return
void Promise.allSettled([data.location.syncInfo(evt.data.location), data.location.vcs.sync(evt.data.location)])
}),
)
onCleanup(
event.on("session.inbox.enqueued", (evt) => {
if (!enabled() || evt.data.item.type !== "user") return
@@ -0,0 +1,62 @@
/** @jsxImportSource @opentui/solid */
import { testRender } from "@opentui/solid"
import { expect, test } from "bun:test"
import { createSignal } from "solid-js"
import { ConfigProvider } from "../../src/config"
import { EMPTY_SESSION_TAB_STATUS, SessionTabs, type SessionTabsController } from "../../src/component/session-tabs"
import { ThemeProvider } from "../../src/context/theme"
import { emptyThemeSource } from "../fixture/fixture"
import { TestTuiContexts } from "../fixture/tui-environment"
import { createTuiResolvedConfig } from "../fixture/tui-runtime"
test("releasing a transcript selection over tab controls does not activate them", async () => {
const [active, setActive] = createSignal("first")
const [added, setAdded] = createSignal(0)
const controller = {
tabs: () => [
{ sessionID: "first", title: "First" },
{ sessionID: "second", title: "Second" },
],
current: active,
select: setActive,
close() {},
move() {},
add: () => setAdded((value) => value + 1),
status: () => EMPTY_SESSION_TAB_STATUS,
} satisfies SessionTabsController
const app = await testRender(
() => (
<TestTuiContexts>
<ConfigProvider config={createTuiResolvedConfig({ tabs: { enabled: true } })}>
<ThemeProvider mode="dark" source={emptyThemeSource}>
<box flexDirection="column">
<SessionTabs controller={controller} animations={false} />
<text>selectable transcript text</text>
</box>
</ThemeProvider>
</ConfigProvider>
</TestTuiContexts>
),
{ width: 60, height: 3 },
)
try {
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("Second"))
await app.mockMouse.pressDown(5, 1)
await app.mockMouse.release(40, 0)
expect(active()).toBe("first")
await app.mockMouse.click(40, 0)
expect(active()).toBe("second")
await app.mockMouse.pressDown(5, 1)
await app.mockMouse.release(58, 0)
expect(added()).toBe(0)
await app.mockMouse.click(58, 0)
expect(added()).toBe(1)
} finally {
app.renderer.destroy()
}
})
@@ -197,6 +197,32 @@ test("loads VCS metadata for each persisted tab location", async () => {
}
})
test("loads location metadata when an open session moves", async () => {
const destination = `${directory}/moved-worktree`
const setup = await renderSessionTabs("first")
try {
await wait(() => setup.locations.includes(directory) && setup.vcsLocations.includes(directory))
setup.emit({
id: "evt_moved",
created: 1,
type: "session.moved",
durable: { aggregateID: "first", seq: 1, version: 1 },
data: {
sessionID: "first",
location: { directory: destination },
projectID: "project",
},
})
await wait(() => setup.data.session.get("first")?.location.directory === destination)
await wait(() => setup.locations.includes(destination))
await wait(() => setup.vcsLocations.includes(destination))
} finally {
await setup.destroy()
}
})
test("stores session tabs for the current working directory by default", async () => {
const setup = await renderSessionTabs("first")
+2 -3
View File
@@ -107,13 +107,12 @@ export function createFetch(override?: FetchHandler, events?: ReturnType<typeof
})
if (url.pathname === "/api/project/current") return json({ id: "proj_test", directory: worktree })
if (url.pathname === "/api/project") return json([])
if (url.pathname === "/api/experimental/project/proj_test/worktree") {
if (url.pathname === "/api/worktree/proj_test") {
if (request.method === "GET") return json([{ directory: worktree }])
if (request.method === "POST") return json({ directory: `${worktree}/created` })
return new Response(null, { status: 204 })
}
if (url.pathname === "/api/experimental/project/proj_test/worktree/refresh")
return new Response(null, { status: 204 })
if (url.pathname === "/api/worktree/proj_test/refresh") return new Response(null, { status: 204 })
if (url.pathname === "/api/shell")
return json({
location: { directory, project: { id: "proj_test", directory: worktree, canonical: worktree } },
+1 -1
View File
@@ -9,7 +9,7 @@
- Use parenthesized content folders for sidebar groups that must not add a URL segment. Keep ungrouped top-level pages directly under `content/docs/`.
- Put static files in `public/` and reference them with root-relative paths.
- The API reference is generated from `openapi.json`; do not duplicate endpoint documentation as hand-written MDX.
- Keep documentation aligned with the V2 packages. Do not use `packages/opencode` as the source of truth unless the task explicitly concerns V1.
- Keep documentation aligned with the current packages.
## Local development
@@ -119,17 +119,18 @@ not included in model context.
## Compaction advances the instruction epoch
Conversation compaction and instruction synchronization are separate. Before
promoting pending input, V2 compares live instruction sources with the latest
admitted values. Ordinary changes become durable value deltas; their
model-facing System messages are derived during request assembly rather than
persisted.
each physical model attempt, V2 compares live instruction sources with the
latest admitted values, before delivering pending input for that attempt.
Ordinary changes become durable value deltas. Later changes freeze their
model-facing text when admitted and project it as chronological System messages;
request assembly renders only the epoch baseline from stored values.
Completed compaction advances the instruction epoch at the exact ended-event
sequence and makes the currently admitted values initial. It does not reread
sources or publish an instruction event. Session movement and committed revert
clear the instruction fold so the next safe boundary requires one complete
source read. See [Instructions](/instructions) for source ordering and update
behavior.
sources or publish an instruction event. Session movement retains instruction
state so destination changes become chronological updates. Committed revert
clears instruction state so the next model attempt requires one complete source
read. See [Instructions](/instructions) for source ordering and update behavior.
## Current limitations
@@ -102,8 +102,9 @@ than part of the initial instructions.
## Changes
Before promoting pending input, V2 compares live instruction sources with the
latest admitted source values:
Before each physical model attempt, V2 compares live instruction sources with
the latest admitted source values. This comparison happens before pending input
is delivered for that attempt:
- A new or changed ambient `AGENTS.md` aggregate is announced as a system update
that replaces the previous ambient aggregate.
@@ -115,10 +116,13 @@ latest admitted source values:
- Completed conversation compaction advances the instruction epoch, making the
currently admitted values initial without rereading sources or authoring an
instruction event.
- Moving a session or committing a revert clears the instruction fold. The next
safe boundary requires one complete source read before promoting input.
- Moving a session retains instruction state, so destination changes become
chronological updates. Committing a revert clears instruction state; the next
model attempt requires one complete source read before delivering input.
The durable event stores changed source keys and value hashes, not rendered
prose. During request assembly, OpenCode renders the epoch's initial values and
interleaves later changes as chronological System messages. Clients see changed
keys but never the privileged value bodies.
The durable event stores changed source keys and value hashes. Initial baseline
events contain no rendered prose. Later changes render once when admitted and
freeze that optional text in the event, which projects it as a chronological
System message. During request assembly, OpenCode renders the epoch's initial
values and reuses projected update messages verbatim. Clients see changed keys
but never the privileged value bodies.
+19 -10
View File
@@ -15,20 +15,29 @@ description: "Get started with OpenCode."
## Install
### Install script
<CodeGroup>
```bash
```bash npm
npm install -g @opencode-ai/cli@next
```
```bash bun
bun install -g --trust @opencode-ai/cli@next
```
```bash pnpm
pnpm add -g --allow-build=@opencode-ai/cli @opencode-ai/cli@next
```
```bash yarn
yarn global add @opencode-ai/cli@next
```
```bash curl
curl -fsSL https://raw.githubusercontent.com/anomalyco/opencode/v2/install | bash
```
You can also install it with the following package managers.
<Tabs>
<Tab title="npm">```bash npm install -g @opencode-ai/cli@next ```</Tab>
<Tab title="bun">```bash bun install -g --trust @opencode-ai/cli@next ```</Tab>
<Tab title="pnpm">```bash pnpm add -g --allow-build=@opencode-ai/cli @opencode-ai/cli@next ```</Tab>
<Tab title="Yarn">```bash yarn global add @opencode-ai/cli@next ```</Tab>
</Tabs>
</CodeGroup>
The package uses a trusted postinstall script to select the native `opencode2` binary for your platform. The Bun and pnpm
commands above explicitly allow that script to run.
+28 -26
View File
@@ -10534,7 +10534,7 @@
"summary": "List references"
}
},
"/api/experimental/project/{projectID}/worktree": {
"/api/worktree/{projectID}": {
"get": {
"tags": ["worktree"],
"operationId": "v2.worktree.list",
@@ -10736,7 +10736,7 @@
}
}
},
"/api/experimental/project/{projectID}/worktree/refresh": {
"/api/worktree/{projectID}/refresh": {
"post": {
"tags": ["worktree"],
"operationId": "v2.worktree.refresh",
@@ -23517,6 +23517,24 @@
"required": ["path"],
"additionalProperties": false
},
"ConfigWebSearch.Info": {
"type": "object",
"properties": {
"provider": {
"anyOf": [
{
"type": "string",
"enum": ["random"]
},
{
"type": "string"
}
]
}
},
"required": ["provider"],
"additionalProperties": false
},
"Config.Plugin.Entry": {
"type": "object",
"properties": {
@@ -24035,14 +24053,15 @@
}
},
"websearch": {
"type": "object",
"properties": {
"provider": {
"type": "string"
"anyOf": [
{
"type": "boolean",
"enum": [false]
},
{
"$ref": "#/components/schemas/ConfigWebSearch.Info"
}
},
"required": ["provider"],
"additionalProperties": false
]
},
"plugins": {
"type": "array",
@@ -24145,20 +24164,6 @@
"required": ["type", "path"],
"additionalProperties": false
},
"Config.File": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["file"]
},
"path": {
"type": "string"
}
},
"required": ["type", "path"],
"additionalProperties": false
},
"Config.AgentsDirectory": {
"type": "object",
"properties": {
@@ -24195,9 +24200,6 @@
{
"$ref": "#/components/schemas/Config.Directory"
},
{
"$ref": "#/components/schemas/Config.File"
},
{
"$ref": "#/components/schemas/Config.AgentsDirectory"
},
+28 -26
View File
@@ -10534,7 +10534,7 @@
"summary": "List references"
}
},
"/api/experimental/project/{projectID}/worktree": {
"/api/worktree/{projectID}": {
"get": {
"tags": ["worktree"],
"operationId": "v2.worktree.list",
@@ -10736,7 +10736,7 @@
}
}
},
"/api/experimental/project/{projectID}/worktree/refresh": {
"/api/worktree/{projectID}/refresh": {
"post": {
"tags": ["worktree"],
"operationId": "v2.worktree.refresh",
@@ -23517,6 +23517,24 @@
"required": ["path"],
"additionalProperties": false
},
"ConfigWebSearch.Info": {
"type": "object",
"properties": {
"provider": {
"anyOf": [
{
"type": "string",
"enum": ["random"]
},
{
"type": "string"
}
]
}
},
"required": ["provider"],
"additionalProperties": false
},
"Config.Plugin.Entry": {
"type": "object",
"properties": {
@@ -24035,14 +24053,15 @@
}
},
"websearch": {
"type": "object",
"properties": {
"provider": {
"type": "string"
"anyOf": [
{
"type": "boolean",
"enum": [false]
},
{
"$ref": "#/components/schemas/ConfigWebSearch.Info"
}
},
"required": ["provider"],
"additionalProperties": false
]
},
"plugins": {
"type": "array",
@@ -24145,20 +24164,6 @@
"required": ["type", "path"],
"additionalProperties": false
},
"Config.File": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["file"]
},
"path": {
"type": "string"
}
},
"required": ["type", "path"],
"additionalProperties": false
},
"Config.AgentsDirectory": {
"type": "object",
"properties": {
@@ -24195,9 +24200,6 @@
{
"$ref": "#/components/schemas/Config.Directory"
},
{
"$ref": "#/components/schemas/Config.File"
},
{
"$ref": "#/components/schemas/Config.AgentsDirectory"
},
-64
View File
@@ -1,64 +0,0 @@
## project
The goal is to let a single instance of OpenCode run sessions for multiple projects and different worktrees per project.
### api
```
GET /project -> Project[]
POST /project/init -> Project
GET /project/:projectID/session -> Session[]
GET /project/:projectID/session/:sessionID -> Session
POST /project/:projectID/session -> Session
{
id?: string
parentID?: string
directory: string
}
DELETE /project/:projectID/session/:sessionID
POST /project/:projectID/session/:sessionID/init
POST /project/:projectID/session/:sessionID/abort
POST /project/:projectID/session/:sessionID/share
DELETE /project/:projectID/session/:sessionID/share
POST /project/:projectID/session/:sessionID/compact
GET /project/:projectID/session/:sessionID/message -> { info: Message, parts: Part[] }[]
GET /project/:projectID/session/:sessionID/message/:messageID -> { info: Message, parts: Part[] }
POST /project/:projectID/session/:sessionID/message -> { info: Message, parts: Part[] }
POST /project/:projectID/session/:sessionID/revert -> Session
POST /project/:projectID/session/:sessionID/unrevert -> Session
POST /project/:projectID/session/:sessionID/permission/:permissionID -> Session
GET /project/:projectID/session/:sessionID/find/file -> string[]
GET /project/:projectID/session/:sessionID/file -> { type: "raw" | "patch", content: string }
GET /project/:projectID/session/:sessionID/file/status -> File[]
POST /log
// These are awkward
GET /provider?directory=<resolve path> -> Provider
GET /config?directory=<resolve path> -> Config // think only tui uses this?
GET /project/:projectID/agent?directory=<resolve path> -> Agent
GET /project/:projectID/find/file?directory=<resolve path> -> File
```
-145
View File
@@ -1,145 +0,0 @@
# Effect Drizzle SQLite Package
## Goal
Create a small workspace package that vendors the Drizzle `effect-sqlite` adapter shape for our repo. This is not an opencode storage abstraction. It is a local package that ports the Drizzle Effect SQLite implementation so we can use it before/independently of upstream release timing.
`packages/opencode` will use it internally, but the package itself should be generic: Drizzle + Effect + SQLite. No opencode paths, migrations, tables, transaction hooks, post-commit behavior, or domain language should live in this package.
## Package Shape
Add a package similar in style to `packages/http-recorder`:
- `packages/effect-drizzle-sqlite/package.json`
- `packages/effect-drizzle-sqlite/src/index.ts`
- `packages/effect-drizzle-sqlite/src/effect-sqlite/*`
- `packages/effect-drizzle-sqlite/src/sqlite-core/effect/*`
- `packages/effect-drizzle-sqlite/test/sqlite.test.ts`
Package name:
- `@opencode-ai/effect-drizzle-sqlite`
Initial exports:
```ts
export { EffectLogger } from "drizzle-orm/effect-core"
export * from "./effect-sqlite/driver"
export * from "./effect-sqlite/session"
export { migrate } from "./effect-sqlite/migrator"
export * as EffectDrizzleSqlite from "."
```
The package should follow Drizzle's adapter naming and semantics as closely as possible. Think of it as a vendored `drizzle-orm/effect-sqlite` package surface, not as a new storage service API.
## Upstream References
Use these as implementation references instead of inventing a custom API:
- Drizzle Effect Postgres current RC:
- `/Users/kit/code/open-source/drizzle-orm-rc4-pr/drizzle-orm/src/effect-core/query-effect.ts`
- `/Users/kit/code/open-source/drizzle-orm-rc4-pr/integration-tests/tests/pg/effect-sql.test.ts`
- SQLite Effect branch/reference:
- `/Users/kit/code/open-source/drizzle-orm-beta16/drizzle-orm/src/up-migrations/effect-sqlite.ts`
- `/Users/kit/code/open-source/drizzle-orm-beta16/integration-tests/tests/sqlite/effect-sql.test.ts`
- `/Users/kit/code/open-source/drizzle-orm-beta16/drizzle-orm/type-tests/sqlite/effect.ts`
- Effect SQLite client source of truth:
- `/Users/kit/code/open-source/effect-smol/packages/sql/sqlite-bun/src/SqliteClient.ts`
- `/Users/kit/code/open-source/effect-smol/packages/sql/sqlite-node/test/Client.test.ts`
- `/Users/kit/code/open-source/effect-smol/packages/sql/sqlite-node/test/SqliteMigrator.test.ts`
Important API patterns from those references:
- Drizzle queries are Effect-yieldable: `yield* db.select().from(table)`.
- Transactions are Effect values: `yield* db.transaction((tx) => Effect.gen(...), { behavior: "immediate" })`.
- SQLite clients come from Effect layers such as `SqliteClient.layer({ filename })`.
- Migrations can run through Effect SQL/SQLite migrator mechanisms or Drizzle's `effect-sqlite/migrator` when available.
## Public Surface
Do not invent an `Interface<TDatabase>` abstraction unless the Drizzle port already has one. The public surface should mirror Drizzle's Effect adapters:
```ts
const db = yield * EffectDrizzleSqlite.make({ relations }).pipe(Effect.provide(EffectDrizzleSqlite.DefaultServices))
yield * db.select().from(users)
yield *
db.transaction(
(tx) =>
Effect.gen(function* () {
yield* tx.insert(users).values({ name: "Ada" })
}),
{ behavior: "immediate" },
)
```
Notes:
- `make` / `makeWithDefaults` should match the Drizzle Effect SQLite branch as much as possible.
- `DefaultServices` should provide Drizzle's default logger/cache services, same as Effect Postgres.
- The package should depend on Effect SQL SQLite clients (`@effect/sql-sqlite-bun` and/or node) the same way the Drizzle branch does.
- Opencode-specific path/channel selection stays in `packages/opencode`.
## Opencode Adoption Notes
These are not package requirements, but they matter for the later opencode adoption PR.
The current `packages/opencode/src/storage/db.ts` has two non-obvious semantics that the opencode wrapper must preserve when it consumes this adapter:
- Nested `Database.use` inside `Database.transaction` sees the current transaction, not the root client.
- `Database.effect` queues post-commit side effects while inside a transaction, and runs immediately outside a transaction.
The opencode wrapper can implement that using Effect context instead of `LocalContext`:
- A private transaction context holding `{ tx, afterCommit }`.
- `withDb`/`db` methods read the current transaction context if present, otherwise use the root db.
- `transaction` installs a transaction context around the effect.
- Nested transactions can either reuse the existing tx initially, matching current behavior, or later use explicit savepoints if needed.
Do not remove this behavior while moving opencode to Effect SQLite. `SyncEvent.run` depends on transaction composability and `behavior: "immediate"` for sequencing correctness.
## Migration Strategy
1. Add `@opencode-ai/effect-drizzle-sqlite` with a minimal in-memory/file SQLite test schema.
2. Port the Drizzle Effect SQLite adapter from the SQLite branch into the package, preserving upstream names and API shape.
3. Test adapter-level guarantees:
- query builders are yieldable Effect values,
- `transaction(..., { behavior: "immediate" })` commits successful writes,
- failed transaction rolls back,
- migrations run once and in order,
- close finalizer closes the underlying SQLite database.
4. Add `@opencode-ai/effect-drizzle-sqlite` as a dependency of `packages/opencode`.
5. Port `packages/opencode/src/storage/db.ts` to be a thin compatibility wrapper over the adapter plus opencode-specific transaction/post-commit context.
6. Keep existing call sites working first:
- `Database.Client()`
- `Database.use(...)`
- `Database.transaction(...)`
- `Database.effect(...)`
7. After compatibility is stable, migrate call sites from callback-style `Database.use` to yielding Effect Drizzle queries directly.
8. Only then build domain stores like session/message/project stores on top of opencode's storage wrapper.
## Why This Is Cleaner Than Starting With SessionStorage
`SessionStorage` is a useful domain seam, but it does not answer the core adapter problem: how to make Drizzle SQLite Effect-native in this repo.
An Effect Drizzle SQLite package lets us vendor the adapter once. Then opencode can build its own storage wrapper on top, and `SessionStorage`, `MessageStorage`, event store, and projector writes can all share the same transaction and migration model.
## Open Questions
- Which client should the first package target: `@effect/sql-sqlite-bun`, `@effect/sql-sqlite-node`, or both behind separate layers?
- How much source should we copy from the Drizzle branch versus import from catalog `drizzle-orm` internals?
- What is the update path once Drizzle upstream ships `effect-sqlite`?
- Should `afterCommit` stay opencode-specific until event publishing moves? Default answer: yes.
- Should the compatibility wrapper preserve synchronous return types temporarily, or should the migration intentionally force Effect call sites?
- Do CLI/admin raw SQL and sqlite shell stay in `packages/opencode`, or does the storage package expose backend capabilities for them?
## Recommended First PR
Make the first PR package-only and intentionally boring:
- Add `packages/effect-drizzle-sqlite`.
- Use a tiny test schema, not opencode domain tables.
- Prove Effect Drizzle SQLite queries, transactions, and migrations.
- Do not migrate `packages/opencode` yet except possibly adding the dependency if needed for typechecking.
That gives us a focused place to validate the Effect SQLite approach before disturbing opencode's current database runtime.
-234
View File
@@ -1,234 +0,0 @@
# Remove `packages/opencode/src/storage/db.ts`
## Goal
Remove all production usages of the legacy `packages/opencode/src/storage/db.ts` module.
This means eliminating imports from `@/storage/db` or `./storage/db`, including:
- `Database.use(...)`
- `Database.transaction(...)`
- `Database.effect(...)`
- `Database.Client()`
- `Database.getPath()`
- `Database.TxOrDb` / `Database.Transaction`
- drizzle helpers re-exported from `@/storage/db`, such as `eq`
This does not mean removing SQLite or Drizzle everywhere in one step. The smaller target is deleting the opencode legacy wrapper by moving call sites onto deeper modules or onto the core/effect database adapter directly.
## Current Inventory
Production imports from `packages/opencode/src/storage/db.ts` are concentrated in 21 source files:
- `packages/opencode/src/account/repo.ts`
- `packages/opencode/src/cli/cmd/db.ts`
- `packages/opencode/src/cli/cmd/import.ts`
- `packages/opencode/src/cli/cmd/stats.ts`
- `packages/opencode/src/control-plane/workspace.ts`
- `packages/opencode/src/index.ts`
- `packages/opencode/src/node.ts`
- `packages/opencode/src/permission/index.ts`
- `packages/opencode/src/project/project.ts`
- `packages/opencode/src/server/projectors.ts`
- `packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts`
- `packages/opencode/src/server/shared/fence.ts`
- `packages/opencode/src/session/message-v2.ts`
- `packages/opencode/src/session/projectors.ts`
- `packages/opencode/src/session/prompt.ts`
- `packages/opencode/src/session/session.ts`
- `packages/opencode/src/share/share-next.ts`
- `packages/opencode/src/storage/db.ts`
- `packages/opencode/src/sync/index.ts`
- `packages/opencode/src/worktree/index.ts`
There are 63 direct API/type references in those files. The references fall into the groups below.
## Group 1: Database Runtime And Startup
Status: Completed. Startup, the public node export, and database CLI tooling no longer import the legacy opencode database wrapper; `packages/opencode/src/storage/db.ts` has been deleted.
Files:
- `packages/opencode/src/storage/db.ts`
- `packages/opencode/src/index.ts`
- `packages/opencode/src/node.ts`
- `packages/opencode/src/cli/cmd/db.ts`
Current usage:
- `storage/db.ts` opens the singleton database, applies pragmas, exposes callback-style access, holds ambient transaction context, and queues post-commit effects.
- `index.ts` no longer performs the removed JSON-to-SQLite migration during startup.
- `node.ts` publicly re-exports `Database` from the legacy module.
- `cli/cmd/db.ts` uses `Database.getPath()` to print the path, open a readonly Bun SQLite handle, run `sqlite3`, and vacuum.
Why this group comes first:
- These call sites define the seam currently used by every other group.
- Deleting `storage/db.ts` requires an explicit replacement for database path, client acquisition, migration startup, and close/finalization.
Target shape:
- Move database path and client startup behind the core/effect database module rather than the opencode wrapper.
- Replace `Database.Client()` with an Effect-provided database service or a narrow startup-only adapter.
- Replace the public `node.ts` re-export with either no export or a stable non-legacy database capability.
- Keep `cli/cmd/db.ts` as an admin/raw SQLite tool, but make it ask the replacement database path provider instead of importing `@/storage/db`.
## Group 2: Sync Event Transaction Boundary
Status: Completed. `SyncEvent` and the opencode projector boundary were removed; session/message event projection now lives in core EventV2/projector infrastructure.
Files:
- `packages/opencode/src/sync/index.ts`
- `packages/opencode/src/session/projectors.ts`
- `packages/opencode/src/server/projectors.ts`
Current usage:
- `SyncEvent.run` uses `Database.transaction(..., { behavior: "immediate" })` to allocate event sequence numbers safely.
- `SyncEvent.process` wraps projector execution, event sequence writes, event log writes, and post-commit publishing in `Database.transaction(...)`.
- `Database.effect(...)` queues publish side effects until after the transaction commits.
- Projector functions accept `Database.TxOrDb` so they can write through either a root client or the active transaction.
Why this group is critical:
- It depends on the most non-obvious legacy behavior: nested `Database.use` inside a transaction must see the active transaction, and `Database.effect` must not publish until commit.
- It is the central seam for session, message, permission, workspace, and server projection writes.
Target shape:
- Replace `Database.TxOrDb` with an explicit projector transaction type from the replacement database adapter.
- Move transaction context and after-commit behavior into an Effect-native sync event implementation.
- Preserve immediate transaction behavior for sequence allocation.
- Convert projector registration to accept the new transaction interface before converting every projector body.
Suggested first step:
- Create a narrow internal module for sync projection execution, then migrate `SyncEvent.project(...)` and projector type signatures to that module. Keep the implementation backed by the new database adapter until all projector users are moved.
## Group 3: Domain Repositories Already Behind Services
Status: Completed. These services no longer import the legacy opencode database wrapper.
Files:
- `packages/opencode/src/account/repo.ts`
- `packages/opencode/src/project/project.ts`
- `packages/opencode/src/control-plane/workspace.ts`
- `packages/opencode/src/share/share-next.ts`
Current usage:
- These modules already expose Effect services or Effect functions, but internally wrap `Database.use` with local `db(...)` helpers or `Effect.try`.
- `account/repo.ts` uses both `Database.use` and `Database.transaction` through a repository interface.
- `project/project.ts` has the largest mixed usage: Effect service methods use a local `db(...)` helper, while legacy top-level functions still call `Database.use` directly.
- `control-plane/workspace.ts` and `share/share-next.ts` have local Effect wrappers around `Database.use`.
Why this group is tractable:
- The public interfaces are already deeper than the database calls.
- Most callers should not need to know whether these modules use Drizzle, files, or core services internally.
Target shape:
- Inject the replacement database service into each Effect layer and yield Effect Drizzle queries directly.
- Replace local callback wrappers with direct Effect queries.
- Move remaining synchronous top-level helpers either behind the existing service interface or onto core modules.
Suggested order:
- Start with `account/repo.ts`; it has a clear repository interface and few call sites.
- Then migrate `share/share-next.ts` and `control-plane/workspace.ts` local wrappers.
- Leave `project/project.ts` for last in this group because it mixes project resolution, VCS, global bus emission, migration, and legacy top-level helpers.
## Group 4: Session And Message Read Models
Status: Completed. Session/message reads and projector writes have moved off the legacy opencode database wrapper.
Files:
- `packages/opencode/src/session/session.ts`
- `packages/opencode/src/session/message-v2.ts`
- `packages/opencode/src/session/prompt.ts`
- `packages/opencode/src/session/projectors.ts`
Current usage:
- `session/session.ts` uses `Database.use` for session reads, list queries, children, part lookup, and global list helpers.
- `session/message-v2.ts` uses `Database.use` to page messages, hydrate parts, fetch one message, and fetch parts.
- `session/prompt.ts` imports `eq` from `@/storage/db` and reads current prompt-related session/message rows directly.
- `session/projectors.ts` uses `TxOrDb` for session/message usage projection helpers.
Why this group should be split:
- Reads can move independently from projector writes.
- Message hydration is used by model prompt construction and session APIs, so changing it without a stable read module would spread query details across callers.
- Projector writes are tied to Group 2's transaction type.
Target shape:
- Create or use a session/message read module with Effect-native methods for `get`, `list`, `page`, `parts`, and prompt assembly reads.
- Convert `session/projectors.ts` only after Group 2 defines the replacement projector transaction type.
Suggested order:
- Migrate `session/message-v2.ts` reads first because the module already centralizes message pagination and hydration.
- Migrate `session/session.ts` read helpers next.
- Migrate `session/prompt.ts` after message/session reads exist, and import drizzle operators from `drizzle-orm` if any direct SQL remains temporarily.
## Group 5: Legacy CLI And One-Off Admin Reads
Status: Completed. Remaining one-off CLI/admin reads and writes now use core database services or domain services instead of the legacy opencode database wrapper.
Files:
- `packages/opencode/src/cli/cmd/import.ts`
- `packages/opencode/src/cli/cmd/stats.ts`
- `packages/opencode/src/server/shared/fence.ts`
- `packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts`
- `packages/opencode/src/worktree/index.ts`
- `packages/opencode/src/permission/index.ts`
Current usage:
- `cli/cmd/import.ts` writes imported sessions/messages/parts directly with `Database.use`.
- `cli/cmd/stats.ts` reads all sessions directly.
- `server/shared/fence.ts` queries sessions for fence context.
- `handlers/sync.ts` reads event rows for HTTP sync endpoints.
- `worktree/index.ts` looks up a project row for worktree behavior.
- `permission/index.ts` reads permission rows directly.
Why this group is mostly cleanup:
- Most usages are small and can either call an existing domain service or be given a narrow query function.
- They are not defining shared transaction semantics.
Target shape:
- Replace direct database reads with existing services where possible.
- For admin/import commands, prefer dedicated import/stat modules rather than direct database access from command handlers.
- For HTTP sync reads, move the event log query behind the sync event module.
- For permission and worktree reads, call the permission/project services if available; otherwise add narrow repository methods.
## Recommended Migration Sequence
All migration groups are complete or superseded. `packages/opencode/src/storage/db.ts` has been deleted.
## Superseded: Data Migrations
Status: Superseded. No opencode data-migration group remains.
The previous opencode `data-migration.ts` service only backfilled session usage from message rows. That work is now covered by core database migration `packages/core/src/database/migration/20260510033149_session_usage.ts`, so there is no separate opencode data-migration group.
## Invariants To Preserve
- Nested reads inside a transaction must use the active transaction, not the root client.
- `SyncEvent.run` sequence allocation must keep immediate transaction behavior.
- Post-commit publish effects must not run before the transaction commits.
- Existing schema ownership remains in `packages/core/src/**/*.sql.ts`; do not move table definitions back into `packages/opencode`.
## Verification Commands
- `rg "@/storage/db|./storage/db|Database\.(use|transaction|effect|Client|getPath)|\bTxOrDb\b|\bTransaction\b" packages/opencode/src`
- `bun typecheck` from `packages/opencode`
- Relevant package tests from `packages/opencode`, not the repo root
-641
View File
@@ -1,641 +0,0 @@
# TUI Package Extraction
## Goal
Move the canonical OpenCode terminal application from
`packages/opencode/src/cli/cmd/tui` into a self-contained workspace package while
the legacy CLI and the new CLI continue to use the same implementation.
Target package:
```text
packages/tui
name: @opencode-ai/tui
```
Target dependency graph:
```text
packages/opencode ---\
> @opencode-ai/tui -> @opencode-ai/sdk
packages/cli --------/
```
The TUI may directly depend on terminal and UI infrastructure such as
`@opentui/core`, `@opentui/solid`, `@opentui/keymap`, `solid-js`, Effect, and
generic presentation libraries. It must not depend on `packages/opencode`,
`packages/cli`, or `@opencode-ai/core`.
The SDK is the TUI's OpenCode boundary. Missing backend data or operations must
be added to the server API and generated SDK rather than imported from backend
implementation modules.
## Migration Rules
- Keep one canonical implementation of every TUI feature. Do not copy the full
TUI into `packages/cli` and synchronize two trees.
- Land each section below independently and commit it before starting the next
section.
- Keep each intermediate commit buildable and type-safe.
- Continue integrating team changes into whichever location is canonical for a
file at that point in the migration.
- Use temporary compatibility re-exports only when they materially reduce the
size or conflict risk of a section. Mark them for removal in a later section.
- Do not preserve private imports by creating aliases from `packages/tui` back
into `packages/opencode`.
- Do not replace private `packages/opencode` imports with `@opencode-ai/core`
imports merely to make the package compile.
- Keep tool rendering tolerant of unknown tools and wire-format changes. Local
checks over `unknown` input and metadata are acceptable; importing backend
tool implementations for type safety is not.
- Keep legacy CLI command parsing, server startup, worker management,
authentication, and config discovery outside `@opencode-ai/tui`.
## Ownership Boundary
### `@opencode-ai/tui` Owns
- OpenTUI renderer lifecycle shared by both CLI hosts
- Solid application composition
- Components, routes, dialogs, themes, keymaps, and UI primitives
- SDK client synchronization and event consumption
- Tool-call and tool-result presentation
- TUI-facing plugin contracts and presentation slots
- Resolved TUI configuration types, defaults, and pure validation
- Terminal behavior such as selection, clipboard integration, and local editor
launching when it is not host-specific
- TUI-local persistence such as prompt history, stash, frecency, selected model,
and selected theme
- Presentation utilities such as locale formatting, error display, record
checks, duration formatting, and layout helpers
### CLI Hosts Own
- Command definitions and argument parsing
- Starting, locating, and stopping servers and workers
- Authentication and transport construction
- Process-level signal policy
- Config file discovery, precedence, migration, and environment substitution
- Plugin package discovery, installation, and backend activation
- Upgrade checks and installation metadata
- Executable build wiring and worker path defines
### Server And SDK Own
- OpenCode domain data displayed by the TUI
- Session, message, workspace, file, provider, model, agent, and permission
operations
- Retry, revert, fork, share, and other backend actions
- Stable wire shapes for tool parts and plugin metadata
- Server capabilities needed to conditionally expose UI behavior
## Current Boundary
The canonical implementation currently lives under:
```text
packages/opencode/src/cli/cmd/tui
```
Its private dependency on `packages/opencode` is primarily expressed through
the `@/*` TypeScript alias, which resolves to `packages/opencode/src/*`.
`@tui/*` imports are internal to the TUI and are not themselves a package
boundary problem.
The main private dependency groups are:
- `@/util/*`: presentation helpers plus filesystem/process/RPC helpers
- `@/tool/*`: backend tool implementations used by renderers
- `@/session/*`, `@/provider/*`, and `@/reference/*`: backend data and actions
- `@/config/*`: config discovery, parsing, variables, and plugin resolution
- `@/plugin/*`: plugin loading and installation
- `@/cli/*`: yargs adapters, network setup, errors, and CLI presentation
- `@/server/*`: authentication and embedded server behavior
- `Global.Path`, `Flag`, and process environment reads
The initial extraction should reduce these dependencies in place before moving
the application root.
## Section 1: Create The Package Skeleton
Status: Completed. The private `@opencode-ai/tui` workspace package now has an
independent OpenTUI Solid JSX configuration, narrow root export, package-local
alias, and in-memory render smoke test. Neither CLI consumes the package yet.
Create `packages/tui` without moving the application root yet.
Tasks:
- Add `packages/tui/package.json` with the name `@opencode-ai/tui`.
- Add a package `tsconfig.json` configured for OpenTUI Solid JSX.
- Add `bunfig.toml` with the OpenTUI Solid preload for package-local development
and tests.
- Add package scripts for `typecheck` and package-local tests.
- Add direct dependencies used by the TUI. Do not rely on workspace hoisting.
- Add a narrow package export, initially only the package root and any explicit
testing entrypoint needed by migrated tests.
- Establish a package-local import convention. A local alias such as `@tui/*`
is acceptable, but it must resolve entirely inside `packages/tui`.
- Add a minimal package entrypoint and smoke test proving OpenTUI Solid TSX can
typecheck and render.
- Do not make either CLI consume the package yet.
Exit criteria:
- `packages/tui` typechecks independently.
- Its test command runs from `packages/tui`.
- The package has no dependency on `opencode`, `@opencode-ai/cli`, or
`@opencode-ai/core`.
Checkpoint commit:
```text
feat(tui): add standalone package skeleton
```
## Section 2: Move Presentation Utilities And Leaf UI
Status: Completed. Presentation utilities, bundled themes and their pure theme
engine, keybinding/keymap mechanics, and low-coupling border, link, and spinner
primitives now live in `@opencode-ai/tui`. The legacy host consumes explicit
package exports and retains only integration wrappers or compatibility
re-exports where backend and process concerns have not moved yet.
Move low-coupling code first so subsequent team changes land in the new package
without waiting for the application root migration.
Tasks:
- Move TUI presentation utilities into `packages/tui/src/util`, including the
portions of locale, error display, record checks, duration formatting, and
small functional helpers used by TUI code.
- Move pure TUI utilities already under the old TUI directory.
- Move themes and bundled theme JSON files.
- Move UI primitives and leaf components that have no private backend imports.
- Move pure keybinding schemas and keymap helpers that do not read host flags.
- Move related unit and snapshot tests.
- Update remaining old-tree consumers to import the new canonical modules.
- Use temporary compatibility re-exports from old TUI paths only if needed to
avoid a large unrelated import rewrite.
- Do not move `Filesystem`, `Process`, `Rpc`, worker startup, or config discovery
as generic utilities in this section.
Exit criteria:
- Moved files have no `@/...` imports.
- Tests for moved code run from `packages/tui`.
- Existing legacy TUI behavior and typecheck remain unchanged.
Checkpoint commit:
```text
refactor(tui): move presentation utilities and primitives
```
## Section 3: Remove Backend Tool Implementation Imports
Status: Completed. Legacy and V2 tool renderers now dispatch on SDK wire names,
accept `Record<string, unknown>` input and metadata, and use local guards for
nested presentation data. Web-search labels and structured metadata extraction
are TUI-owned, unknown tools retain the generic fallback, and no TUI source
imports backend tool implementations. The route components remain in the legacy
tree until the SDK state and route move in Section 6.
Make tool rendering depend only on SDK wire data and local presentation logic.
Tasks:
- Remove imports from `@/tool/*` in TUI routes and feature plugins.
- Key built-in renderers by SDK tool name strings such as `read`, `write`,
`edit`, `apply_patch`, `grep`, `glob`, `bash`, `question`, and `task`.
- Treat tool input, output metadata, and plugin-defined fields as `unknown` at
the package boundary.
- Add small local type guards only where a renderer needs a particular field.
- Preserve a generic fallback renderer for unknown and plugin-provided tools.
- Keep renderer failures local: malformed metadata must not crash the entire
session view.
- Replace backend-derived labels or IDs with TUI-owned presentation constants or
SDK-provided values.
- Move the affected tool presentation components and tests to `packages/tui`.
Exit criteria:
- No TUI source imports `@/tool/*`.
- Unknown tools render through the generic fallback.
- Existing built-in tool snapshots remain equivalent unless intentionally
updated and reviewed.
Checkpoint commit:
```text
refactor(tui): decouple tool rendering from backend tools
```
## Section 4: Make Runtime Inputs Explicit
Status: Completed for the shared runtime contract and legacy host. The TUI now
receives immutable launch-directory, path, capability, terminal/editor, startup,
and build inputs through `@opencode-ai/tui/runtime`. Movable app, component,
route, and feature-plugin code no longer reads OpenCode globals or process state;
command, config, plugin-loading, custom-theme discovery, editor/clipboard, and
Windows lifecycle adapters remain host-owned. `packages/cli` does not consume
this contract yet; that integration remains deferred to Section 9.
Replace process-global OpenCode state with resolved TUI inputs.
Define narrow inputs rather than one unstructured host object. Expected groups
include:
```ts
type TuiCapabilities = {
mouse: boolean
copyOnSelect: boolean
terminalTitle: boolean
workspaces: boolean
showTimeToFirstDraw: boolean
}
type TuiPaths = {
home: string
state: string
config: string
data: string
}
type TuiBuildInfo = {
version: string
channel?: string
}
```
Tasks:
- Inventory direct reads of `Flag`, `Global.Path`, and relevant environment
variables in movable TUI code.
- Pass resolved capabilities into the application/provider tree.
- Pass local path roots or a narrow TUI storage capability into persistence
contexts.
- Pass build/version information explicitly.
- Keep environment reads needed by legacy command or worker startup in
`packages/opencode` adapters.
- Give `packages/tui` sensible host-neutral defaults only when behavior is truly
local to a terminal client.
- Move contexts and components after their global dependencies are removed.
Exit criteria:
- Movable TUI code does not import `Flag` or `Global`.
- TUI tests can supply deterministic capabilities and storage paths.
- The legacy host constructs the required input through the public package API;
the new CLI integration remains deferred to Section 9.
Checkpoint commit:
```text
refactor(tui): make runtime capabilities explicit
```
## Section 5: Separate Resolved TUI Config From Host Config Loading
Status: Completed for the package config contract and legacy host adapter.
`@opencode-ai/tui/config` now owns schemas, defaults, keybind resolution, the
resolved config type, and the Solid config provider. The legacy host retains
file discovery, precedence, JSONC parsing, substitutions, migration,
source-relative sound paths, plugin origins, dependency installation, and
Effect services. `packages/cli` remains untouched until Section 9.
Move config semantics needed by rendering while retaining filesystem discovery
and migration in the legacy host.
Tasks:
- Move TUI config schemas, keybind schemas, defaults, and pure resolution to
`packages/tui`.
- Define the resolved config accepted by the public TUI entrypoint.
- Keep config path discovery, project/global precedence, migration, variable
expansion, and plugin package installation in `packages/opencode` initially.
- Make the legacy host produce the same resolved config shape.
- Add a new CLI adapter that can initially provide defaults or its own resolved
configuration.
- Update schema-generation imports to use the package's explicit config export
if schema generation still needs TUI schemas.
- Move pure config tests; retain discovery and migration integration tests in
`packages/opencode`.
Exit criteria:
- `packages/tui` does not import `@/config/*`.
- Config discovery can change without changing TUI rendering code.
- The old CLI still honors existing config precedence and migration behavior.
Checkpoint commit:
```text
refactor(tui): separate config resolution from loading
```
## Section 6: Move SDK State, Routes, And Backend Operations
Status: Completed for the SDK/domain boundary. SDK, project, event, legacy sync,
V2 sync, local model state, prompt persistence, and pure prompt helpers are now
canonical in `@opencode-ai/tui`. Configured references resolve through the new
generated `reference.list` SDK operation; prompt payloads rely on optional
server-assigned IDs; local attachment reads use the package platform contract.
Legacy route files remain in place until the plugin slot boundary and app-root
move, but their only private dependencies are plugin presentation or local host
adapters rather than OpenCode domain implementations.
Make the SDK the only OpenCode domain boundary used by the TUI.
Tasks:
- Move SDK client providers, event synchronization, routes, prompt UI, and
session views into `packages/tui`.
- Replace direct imports from `@/session/*`, `@/provider/*`, `@/reference/*`,
`@/lsp/*`, and other backend domains with SDK data or TUI-owned presentation
helpers.
- Replace direct backend actions such as retry with SDK calls.
- For each missing operation, add or adjust the server endpoint, regenerate the
JavaScript SDK with `./packages/sdk/js/script/build.ts`, and consume the
generated SDK API.
- Keep transport creation outside the package. Accept a base URL, headers,
custom fetch, event source, or constructed SDK client as appropriate.
- Keep local-only UI state in the TUI package rather than adding it to the
server API.
- Move affected tests and fixtures. Use real SDK/server integration where
practical instead of mocking backend modules.
Exit criteria:
- Domain-facing TUI code imports OpenCode data and operations only from
`@opencode-ai/sdk`.
- No TUI source imports private session, provider, reference, LSP, server, or
core domain implementations.
- SDK generation is clean after any API changes.
Checkpoint strategy:
This section may be split into multiple commits when an SDK gap is substantial.
Each commit must leave both the old TUI host and package tests working. Suggested
commit pattern:
```text
feat(sdk): expose <operation> for tui clients
refactor(tui): move <area> to sdk boundary
```
Final section checkpoint:
```text
refactor(tui): move sdk state and routes into package
```
## Section 7: Isolate Plugin Presentation From Plugin Loading
Status: Completed. Plugin slots, route registration, TUI-facing APIs, runtime
presentation state, and built-in feature plugins now live in
`@opencode-ai/tui`. The legacy host injects a narrow plugin host that retains
discovery, installation, manifest/config mutation, external module execution,
pure-mode filtering, and cleanup ownership. Missing or failing plugin hosts
degrade to the base TUI without blocking startup.
Keep plugin UI extensibility without importing the legacy plugin installer and
loader into the TUI package.
Tasks:
- Move plugin presentation slots, route contracts, and TUI-facing APIs into
`packages/tui` or the existing public plugin TUI contract package.
- Keep package discovery, installation, manifest resolution, backend activation,
and process lifecycle in the host.
- Define the serialized or runtime plugin presentation data the TUI requires.
- Prefer SDK-delivered plugin metadata when the behavior must also work for a
remote server.
- Make plugin absence or incompatibility degrade gracefully.
- Move plugin rendering tests to `packages/tui`; retain installation/loading
integration tests in `packages/opencode`.
Exit criteria:
- `packages/tui` does not import `@/plugin/*` or the old TUI plugin runtime.
- Remote and local TUI clients have a defined plugin behavior.
- Plugin UI failures cannot prevent the base TUI from starting.
Checkpoint commit:
```text
refactor(tui): separate plugin presentation from loading
```
## Section 8: Move The Application Root And Renderer Lifecycle
Status: Completed. `packages/tui` now owns the canonical application root,
provider composition, routes, components, parser presentation, renderer
configuration, and renderer lifecycle. Process mutation, Windows console
handling, backend worker startup, config loading, plugin loading, native audio,
and legacy platform implementations remain injected host adapters. Old source
paths are temporary compatibility re-exports for the legacy command host.
Move the canonical app composition after its dependencies have already crossed
the package boundary.
Tasks:
- Move `app.tsx`, remaining providers, routes, components, attention handling,
keymaps, and renderer lifecycle to `packages/tui`.
- Export a narrow public API such as:
```ts
export type TuiInput = {
url: string
directory?: string
headers?: RequestInit["headers"]
fetch?: typeof fetch
config: TuiConfig.Resolved
capabilities: TuiCapabilities
paths: TuiPaths
}
export function run(input: TuiInput): TuiHandle
export function createRenderer(config: TuiConfig.Resolved): Promise<CliRenderer>
```
- Preserve the existing lifecycle guarantees: readiness, waiting until exit,
idempotent cleanup, renderer destruction, SIGHUP handling where appropriate,
and terminal restoration.
- Keep Windows process adapters outside the package if they mutate host process
state; invoke them from CLI adapters around the package lifecycle.
- Keep OpenTUI parser-worker embedding in executable build scripts.
- Move app lifecycle and rendering tests to `packages/tui`.
Exit criteria:
- `packages/tui` contains the canonical application root.
- The package has no imports from `packages/opencode`, `packages/cli`, or
`@opencode-ai/core`.
- The package public API is sufficient for both old and new CLI adapters.
Checkpoint commit:
```text
refactor(tui): move application root into package
```
## Section 9: Convert Both CLIs To Thin Adapters
Status: Completed. The legacy thread and attach commands now lazily invoke the
public `@opencode-ai/tui` root while retaining worker/server/config/plugin and
process adapters. The new CLI default command launches the same package against
its authenticated daemon transport with a minimal local platform/host. Missing
legacy provider/config APIs currently degrade to the shared provider-connect
screen; source and compiled new-CLI behavior match, while named commands remain
outside the TUI path.
Make both executable packages consume the same TUI package.
Tasks:
- Keep the legacy yargs commands corresponding to current `thread.ts` and
`attach.ts` in `packages/opencode`.
- Keep the legacy embedded worker and server startup in `packages/opencode`.
- Change those adapters to load config, create transport inputs, and call the
public `@opencode-ai/tui` API.
- Change `packages/cli`'s default command handler to call the same public API.
- Remove the temporary `packages/cli/src/tui` shell after the shared package is
integrated.
- Remove duplicated OpenTUI lifecycle code from both hosts.
- Ensure non-TUI subcommands remain lazily isolated from OpenTUI startup.
- Update executable build scripts to bundle the shared package, parser worker,
assets, and any retained host worker.
Exit criteria:
- Both CLIs launch the same package implementation.
- There is no duplicate TUI source tree in `packages/cli`.
- Legacy attach and local-worker modes still work.
- Named non-TUI commands do not launch or eagerly initialize the TUI.
Checkpoint commit:
```text
refactor(cli): share tui package across command hosts
```
## Section 10: Remove Compatibility Paths And Finish Ownership
Status: Completed. Package source imports are self-contained, package exports
are narrowed to active host contracts, package-owned tests and snapshots live
under `packages/tui`, and the obsolete compatibility tree has been removed.
Legacy command, worker, config, plugin-loader, process, editor, audio, and event
adapters now live in explicit host-owned locations outside `src/cli/cmd/tui/`.
Delete migration scaffolding only after both hosts consume the package.
Tasks:
- Remove old TUI compatibility re-exports and the obsolete directory tree under
`packages/opencode/src/cli/cmd/tui`.
- Retain and relocate only true host adapters such as legacy commands, worker,
transport setup, and config loading.
- Remove obsolete `@tui/*` path mappings from `packages/opencode`.
- Remove stale test fixtures and update all imports to package exports.
- Narrow `@opencode-ai/tui` exports to intentional public entrypoints.
- Verify package manifests list every direct dependency and no accidental
dependency is supplied only by workspace hoisting.
- Update repository documentation describing TUI ownership and development.
Exit criteria:
- No production import references the old TUI source location.
- No source under `packages/tui` imports `@/...`, `@opencode-ai/core`, or either
executable package.
- The old TUI directory contains no canonical implementation files.
- The dependency graph has no cycle.
Checkpoint commit:
```text
refactor(tui): complete standalone package extraction
```
## Invariants To Preserve
- There is one canonical TUI implementation at every migration stage.
- Legacy TUI behavior remains available until its host is intentionally removed.
- The default new CLI command launches the TUI, while named subcommands continue
to route to their own handlers.
- Renderer cleanup restores the terminal on normal exit, interruption, startup
failure, and renderer destruction.
- TUI package imports do not reach into executable or backend implementation
packages.
- SDK wire data is treated as the source of truth for OpenCode domain state.
- Unknown tools and plugin data render safely without backend type imports.
- Remote-server use remains possible; the TUI must not require an in-process
backend implementation.
- TUI-local persistence remains local and does not become server state unless
there is an explicit product requirement.
- Team changes should be moved with their canonical file, not manually copied
between old and new implementations.
## Verification Gates
Run verification after every section, adding narrower tests for the area being
moved.
Package checks:
```text
cd packages/tui && bun typecheck
cd packages/tui && bun test
cd packages/opencode && bun typecheck
cd packages/cli && bun typecheck
```
Dependency checks:
```text
rg "from ['\"]@/" packages/tui/src
rg '@opencode-ai/core|packages/opencode|packages/cli' packages/tui
rg 'src/cli/cmd/tui|@tui/' packages/opencode/src packages/opencode/test
```
SDK checks when server APIs change:
```text
./packages/sdk/js/script/build.ts
git diff --check
```
Interactive smoke checks should run in `tmux` so the terminal can be captured
and cleaned up reliably:
- Start the legacy local TUI and confirm initial render.
- Start legacy attach mode against a server.
- Start the new CLI default command and confirm it renders the same package.
- Exit each mode with Ctrl-C and verify the process and terminal are restored.
- Run representative named commands in both CLIs and verify they do not launch
the TUI.
Compiled checks:
- Build the current-platform `packages/opencode` binary.
- Build the current-platform `packages/cli` binary.
- Run TUI and non-TUI smoke checks against both compiled binaries.
- Verify theme JSON, audio assets, OpenTUI parser worker, and retained backend
worker assets are included.
## Progress Tracking
- [x] Section 1: Create the package skeleton
- [x] Section 2: Move presentation utilities and leaf UI
- [x] Section 3: Remove backend tool implementation imports
- [x] Section 4: Make runtime inputs explicit
- [x] Section 5: Separate resolved TUI config from host config loading
- [x] Section 6: Move SDK state, routes, and backend operations
- [x] Section 7: Isolate plugin presentation from plugin loading
- [x] Section 8: Move the application root and renderer lifecycle
- [x] Section 9: Convert both CLIs to thin adapters
- [x] Section 10: Remove compatibility paths and finish ownership
Update each section's status and this checklist in the same commit that completes
the section.
+6 -7
View File
@@ -25,14 +25,13 @@ Generated clients follow the assembled public `HttpApi`. GitHub issues own activ
| [Session](./session.md) | Explain prompt admission, execution, instructions, compaction, and recovery boundaries. |
| [Tools](./tools.md) | Explain tool construction, registration, execution, and outcome laws. |
## Decisions And Proposals
## Decision Records
| Document | Status | Job |
| ----------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------- |
| [Event stream](./event-stream-architecture.md) | Accepted and implemented | Record why public events use one encoded feed with independent queues. |
| [Managed restart continuation](./session-restart-continuation.md) | Accepted and implemented | Record why graceful managed-service restart uses private Session suspension. |
| [Instruction sync](./instruction-sync-proposal.md) | Accepted and implemented | Record why instruction state is value deltas plus derived rendering. |
| [Provider policy](./provider-policy.md) | Proposed and unimplemented | Explore provider authorization independently from provider configuration. |
| Document | Status | Job |
| ----------------------------------------------------------------- | -------------------------- | --------------------------------------------------------------------------- |
| [Event stream](./event-stream-architecture.md) | Accepted and implemented | Record why public events use one encoded feed with independent queues. |
| [Managed restart continuation](./session-restart-continuation.md) | Superseded decision record | Preserve the graceful-only design replaced by write-ahead execution claims. |
| [Provider policy](./provider-policy.md) | Accepted and implemented | Record provider authorization independently from provider configuration. |
## Historical Context
-154
View File
@@ -1,154 +0,0 @@
# Instruction Sync: V2 Architecture
Status: implemented on `instruction-sync-v2` (2026-07-10).
## Principle
The model is a replica that OpenCode can write but cannot read or edit. The transcript is the one-way channel. Instruction sync keeps mutable privileged context (`AGENTS.md`, guidance, API entries, date, and environment) current over that channel without rewriting text that was already sent.
**The durable log stores only irreducible facts: which source values changed, and when. Everything else is a function of the log and current renderer code.**
## Durable Fact
```typescript
"session.instructions.updated.2" {
sessionID: Session.ID
delta: Record<Instructions.Key, Instructions.Hash | "removed">
}
```
A hash overwrites one source value. The literal `"removed"` removes it (chosen over JSON `null` because record-value nullability does not survive every client generator; it cannot collide with a 64-hex hash). The event stores no rendered text, mode, baseline, or snapshot.
Each hash body is canonical JSON stored once in the machine-local `instruction_blob` table. Hashes are local pointers, not cross-machine promises.
## Epochs And Folds
An instruction epoch is the span between completed compactions. `epochStart` is the sequence of the last `session.compaction.ended`, or the initial complete v2 delta when no epoch exists.
Folding deltas in durable sequence order derives:
```text
values through epochStart -> renderInitial -> initial instructions
each delta after epochStart -> renderUpdate -> chronological System message
final values -> next boundary comparison state
```
Completed compaction moves the epoch by copying current hashes to initial hashes at the exact ended-event sequence. It does not read sources or publish an instruction event.
Session movement and committed revert clear the fold. The next boundary must establish one complete delta before input promotion.
## Projection Cache
```text
instruction_state
session_id
epoch_start
through_seq
initial_values
current_values
```
This row is derived state. The boundary compares `through_seq` with the latest relevant durable sequence. A missing or stale row folds the log and rewrites the cache without publishing an event.
The relevant reducer inputs are:
- `session.instructions.updated.2`: apply the delta; the first one establishes an epoch, including an empty complete delta.
- `session.compaction.ended.1`: make current values initial and move `epochStart`.
- `session.moved.1`: clear values.
- `session.revert.committed.1`: clear values.
- `session.forked.2`: derive from parent ancestry through its frozen `parentSeq`.
## Sources
```typescript
interface Source {
readonly key: Key
readonly read: Effect<Json | Unavailable | Removed>
readonly initial: (value: Json) => string | undefined
readonly changed: (previous: Json, current: Json) => string | undefined
readonly removed: (previous: Json) => string | undefined
}
namespace Source {
interface Definition<A> {
readonly key: Key
readonly codec: Schema.Codec<A, Json>
readonly read: Effect<A | Unavailable | Removed>
readonly render: {
readonly initial: (value: A) => string
readonly changed: (previous: A, current: A) => string
readonly removed?: (previous: A) => string
}
}
}
type Instructions = ReadonlyArray<Source>
declare function make<A>(definition: Source.Definition<A>): Instructions
```
Producers author a typed `Source.Definition<A>`. `make` captures its codec and renderers in one JSON-level `Source`, the representation used for heterogeneous composition, durable values, and historical rendering. `Instructions` is an ordered collection of those sources; combining collections preserves order and rejects duplicate keys.
`read` runs once per source at the safe boundary, never at layer construction or request assembly. Codecs must be canonical: object keys are canonicalized by the hash function, while source-owned collections must have deterministic order and values must not contain observation timestamps.
`Unavailable` means the read failed temporarily. The initial complete delta blocks while any source is unavailable; later boundaries retain its prior hash silently.
`Removed` is an observed absence. If the key currently has a value, the next delta stores `"removed"` and assembly calls the source's removal renderer. A source that disappears from a software upgrade does not imply removal; its retained value becomes invisible while its renderer is absent.
## Safe Boundary
Once per physical attempt, before input promotion:
1. Load the selected agent and compose built-ins, discovery, skill guidance, reference guidance, MCP guidance, and API entries in fixed order.
2. Read every source concurrently exactly once.
3. Encode and hash values; compare with `instruction_state.current_values`.
4. At the initial v2 boundary, require a complete read and admit one complete delta, including `{}` for a truly empty set.
5. For later boundaries, insert new blobs and admit one delta only when a hash or explicit removal changed.
6. Promote pending input.
7. Read projected messages, epoch values, blobs, and post-epoch deltas in one database transaction.
8. Render initial instructions and interleave derived update messages by durable sequence.
`MoveSession` interrupts any active drain and awaits idle before publishing `session.moved`, matching the best-effort ordering used by Session removal.
The blob inserts, durable event, and fold-cache advance share the event transaction.
## Forks
`session.forked.2` carries `parentSeq`, the authoritative parent event cutoff. For a fork before message N, the cutoff is `message.seq - 1`, so instruction changes admitted immediately before that message are inherited while later parent state is not.
The child stores the cutoff as `session.fork_seq`. Its virtual instruction log is the parent's ancestry through that cutoff followed by child events. Child event sequence reservation begins after the cutoff, preserving chronological interleaving with copied message rows. Replay accepts the intentional fork gap because the fork projector reserves the inherited prefix before later child events replay.
## API Entries
Each visible entry is one `api/<key>` source. DELETE marks the row as a hidden tombstone rather than physically removing it, preserving the renderer needed to admit and narrate the removal; list responses hide tombstones. The nullable value column preserves JSON `null`, while the separate tombstone flag distinguishes removal. A later PUT revives the same source.
PUT measures encoded JSON in UTF-8 and rejects values larger than 8KB with `InstructionEntryValueTooLargeError` (HTTP 413). Values are never truncated.
## Content-Addressed Storage
The blob store grows by one row per distinct encoded value. No GC ships initially. This is an at-rest deduplication policy; deleting a Session does not remove values only that Session referenced, so clients must not put secrets in API entries.
If retention becomes necessary, add mark-and-sweep: walk live v2 deltas for referenced hashes and delete the rest. No schema change or eager reference counter is required.
The blob store is machine/tenant scoped and must never deduplicate across tenants.
**Storage format is not wire format.** Any future V2 sync, export, share, or workspace-transfer boundary must hydrate referenced values, verify each body against its hash on ingestion, and insert blobs before replaying the event. Current V2 has no cross-machine durable replay surface; hashes are sufficient for local event logs and key-only clients.
## Client Projection
Instruction deltas do not project `session_message` rows. The TUI derives a non-model-facing notice from event keys, for example `Instructions updated: core/date, api/plan`. Model-facing update prose exists only during runner assembly and is excluded from compaction summaries.
## Migration
Migration deletes pre-beta `session.instructions.updated.1` events and their event-derived System rows, then drops `instruction_checkpoint`. It leaves unrelated events and System messages intact. The next safe boundary establishes one complete v2 delta.
Existing `session.forked.1` rows migrate to v2 with the event prefix reserved by their original projection as `parentSeq`.
## Accepted Costs
- Renderer changes can change request bytes for identical stored values, causing one provider-cache miss. They do not create an instruction delta.
- Rendered text is not retained verbatim.
- Source additions or software removals are silent unless a source explicitly reads `Removed`.
- Clients display changed keys, not privileged prose.
- Blob GC is deferred.
- Pre-beta instruction events are deleted during migration; logs with resulting sequence gaps are not guaranteed to replay into a blank database.
+15 -2
View File
@@ -2,12 +2,25 @@
| Field | Value |
| -------------- | ------------------------------------------------------------ |
| Status | Accepted and implemented |
| Status | Superseded by write-ahead execution claims |
| Author | Kit Langton |
| Date | 2026-07-08 |
| Superseded | 2026-08-14 |
| Tracking issue | [#35646](https://github.com/anomalyco/opencode/issues/35646) |
## Summary
## Current Decision
Session execution now writes a durable claim when a process-local busy period starts. Success, failure, and user interruption release the claim. Shutdown interruption and process death preserve it, so graceful restart, crash, SIGKILL, and runtime eviction have the same durable recovery signature.
On startup, managed Node and fetch runtimes sweep claimed top-level Sessions. Recovery increments a durable attempt counter, appends a continuation instruction, and resumes from projected history. The claim remains until a terminal event releases it, so another process death remains recoverable. After ten automatic recovery attempts by default, the next sweep records terminal failure instead of creating a restart loop.
The historical `time_suspended` column now stores this execution claim, and `resume_attempts` counts automatic recovery attempts against the runtime's configured budget. A claim is a recovery marker, not live status, a lock, clustered ownership, or an exactly-once guarantee. Recovery fails stale running tool projections before further model work, but it cannot prove whether an interrupted provider request or external side effect already took effect.
See the current [Session contract](./session.md) and the implementation in `packages/core/src/session/execution.ts` and `packages/core/src/session/execution/restart.ts`.
## Original Summary
The remainder of this document records the graceful-only suspension design that first implemented issue #35646. It is retained as design history and does not describe the current recovery mechanism.
When the managed OpenCode server shuts down gracefully, active Sessions continue automatically the next time the managed server starts.
+18 -18
View File
@@ -1,12 +1,12 @@
# V2 Session Contract
Status: **Current semantic overview.** Protocol owns public operations, Schema owns public shapes and durable events, and Core owns execution and persistence behavior. [CONTEXT.md](../../CONTEXT.md) defines the canonical terms used here.
Status: **Current semantic overview.** Protocol owns public operations, Schema owns public shapes and durable events, and Core owns execution and persistence behavior.
## Prompt Admission Precedes Execution
`SessionV2.prompt(...)` records one durable `session.input.admitted` fact and one `session_pending` row before advisory execution begins. Pending input remains outside model-visible Session History until promotion. The promotion transaction publishes `session.input.promoted`, projects the visible message, and consumes the pending row atomically.
`Session.prompt(...)` publishes one durable `session.inbox.enqueued` fact whose projection inserts one `session_inbox` row before advisory execution begins. An inbox item remains outside model-visible Session History until delivery. The `session.inbox.delivered` projection consumes the row and inserts a visible user or synthetic message atomically; compaction and move control items are consumed without becoming transcript messages.
Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. A retry of an already-promoted input reconciles against projected history and its durable admission event.
Reusing a Session ID adopts the existing Session. While a user or synthetic item remains pending, reusing its ID reconciles only when Session, item type, complete payload, metadata, and delivery match; conflicting reuse fails. After delivery, retry reconciliation for those message-producing items uses the projected message and does not require enqueue history or the original delivery mode. Compaction and move controls retain operation-specific conflict behavior.
`resume` controls scheduling, not durability:
@@ -15,12 +15,12 @@ Reusing a Session ID adopts the existing Session. Reusing a prompt message ID re
Delivery is explicit:
- `steer` is the default. Steers promote together at the next Safe Step Boundary while the current Session Drain still requires continuation.
- `queue` remains pending while the Session can continue. When the Session would otherwise become idle, one queued input promotes; the runner then reevaluates continuation before promoting another.
- `steer` is the default. Steers deliver in enqueue order at the next Safe Step Boundary. Delivery stops before a compaction or move control item.
- `queue` remains pending while the Session can continue. At an idle boundary, steers still take priority; otherwise one queued item delivers, followed by any steers that arrived during delivery. The runner then reevaluates continuation before another queued item.
Promoting new user input resets the selected agent's step allowance. A batch of steers resets it once.
Manual compaction uses the same pending store as one coalesced barrier. The barrier blocks later input promotion until compaction ends or fails, then is consumed.
Manual compaction and Session movement use the same inbox as control items. Each request has its own inbox identity and delivery mode. A control item forms a delivery boundary so later steers do not cross it.
## Execution Is Process-Local
@@ -35,37 +35,37 @@ Manual compaction uses the same pending store as one coalesced barrier. The barr
The public interrupt operation verifies that the durable Session exists. An unknown Session fails with `SessionNotFoundError`; a known Session that is idle, settled, or not locally owned is a no-op.
`sessions.active()` snapshots foreground drains currently owned by this process. Durable execution events are historical observations, not liveness or ownership records.
`sessions.active()` snapshots busy periods currently owned by this process. Durable execution events and claims are historical and recovery records, not proof that this process is still live.
The managed server provides graceful restart continuity through private Session suspension. Shutdown marks active Sessions before interrupting them; the next managed server atomically consumes each suspension and schedules at most one resume. Hard-crash recovery and exactly-once provider or tool execution remain out of scope. See [Managed restart continuation](./session-restart-continuation.md).
Execution commits a write-ahead claim when a process-local busy period starts. Success, failure, and user interruption release the claim; shutdown interruption and unclean process death preserve it. On startup, managed Node and fetch runtimes resume claimed top-level Sessions, append a durable continuation instruction, and count recovery attempts. Recovery is bounded per claimed execution but does not guarantee exactly-once provider requests or tool effects. See [Session restart recovery](./session-restart-continuation.md).
## One Step Owns One Logical LLM Call
## One Step May Have Several Physical Attempts
Before each Step, the runner reloads Session History, resolves the selected agent and model, prepares instructions, and materializes tools. Most Steps make one Physical Attempt; overflow-triggered compaction recovery may rebuild the same Step for one additional provider request.
Before each Step, the runner reloads Session History, resolves the selected agent and model, prepares instructions, and materializes tools. Most Steps make one Physical Attempt. Generic retry, continuation-state rejection, incomplete-stream continuation, or overflow-triggered compaction may make another attempt without promoting input again.
Each complete local tool call is durable before side effects begin. Local calls start eagerly and may run concurrently, but terminal outcome publication remains serialized. Every local and hosted call reaches durable success or failure before the Step publishes its single terminal ended or failed event.
Tool calls belong to their assistant message. `callID` is unique only within that Step, so durable tool events also carry `assistantMessageID`.
Tool calls belong to their assistant message. A tool-call `id` is unique only within that Step, so durable tool events also carry `assistantMessageID`.
Before `runStep` assembles its provider request, orphan reconciliation fails tool calls still projected as streaming or running from an earlier process. It preserves the original assistant attribution and never replays ambiguous side effects.
At drain start, orphan reconciliation fails tool calls still projected as streaming or running from an earlier process before further model work. It preserves the original assistant attribution and never directly replays ambiguous side effects.
After a local outcome, continuation reloads projected history and begins a new Step. The runner never delegates orchestration to an in-memory tool loop.
## Retry Is Narrow And Observable
Core retries typed rate-limit, provider-internal, and transport failures only before durable assistant content, tool-call, tool-output, or tool-execution evidence exists. The initial request plus at most four retries use exponential backoff, increased when the provider supplies a longer retry delay.
Generic scheduled retry covers rate-limit and provider-internal failures, transport failures that are unsent or have unknown delivery, and provider output classified as an incomplete stream. The initial request plus at most four retries use jittered exponential backoff, increased when the provider supplies a longer retry delay.
Each retry attempt is a distinct Step, consumes the selected agent's allowance, and reuses the assistant message ID while no durable output exists. `session.retry.scheduled` records the next attempt and absolute retry time. A later Step start or terminal failure clears projected retry state. Surviving retry history never triggers post-crash recovery by itself.
Before durable output, generic retries retain the logical step number and assistant message ID and do not consume another agent-step allowance. An incomplete stream after durable output instead preserves the failed partial assistant, adds a synthetic continuation instruction, and continues with a new assistant message ID under the same retry budget. Provider continuation rejection permits one immediate full-context rebuild without a scheduled-retry event. `session.retry.scheduled` records generic backoff; later activity or a terminal execution event clears projected retry state.
A normalized content-filter finish fails the Step. Any partial streamed content remains visible.
## Instructions Are Value Deltas
Instruction sync persists values, never rendered privileged prose. The only durable fact is `session.instructions.updated { delta }`, mapping each changed source key to a SHA-256 content hash, with the literal `"removed"` for observed absence. Canonical JSON bodies live once in the machine-local `instruction_blob` store; `instruction_state` is a rebuildable fold cache, never primary state. The runner explicitly combines built-ins, ambient discovery, selected-agent skill guidance, references, MCP guidance, and API-managed instruction entries. There is no instruction registry.
Instruction sync persists content-addressed values and may freeze rendered chronological prose. `session.instructions.updated { delta, text? }` maps each changed source key to a SHA-256 content hash, with the literal `"removed"` for observed absence. Canonical JSON bodies live once in the machine-local `instruction_blob` store. The projected `instruction_state` row supplies current and epoch-initial values during normal boundary processing. The runner explicitly combines built-ins, ambient discovery, selected-agent skill guidance, references, MCP guidance, and API-managed instruction entries. There is no instruction registry.
At each Safe Step Boundary the runner reads every source concurrently exactly once, hashes encoded values, and admits one delta atomically with its new blobs before input promotion. The initial delta must be complete; an unavailable source blocks only that initial delta and otherwise silently retains the stored value. Initial instructions and chronological update messages are rendered from stored values during request assembly and are never persisted; clients display changed keys.
Before each Physical Attempt that reaches model execution, the runner reads every source concurrently exactly once, hashes encoded values, and admits one delta atomically with its new blobs before input delivery. The initial delta must be complete; it carries no update text. An unavailable source blocks only that initial delta and otherwise silently retains the stored value. Request assembly renders the epoch baseline from stored values. Later changes render once at admission, freeze optional `text` in the durable event, and project that text as a chronological System message; clients display changed keys rather than privileged prose.
An instruction epoch spans completed compactions. `session.compaction.ended` moves the epoch start to its exact sequence, making current values initial, without reading sources or authoring an instruction event. Session movement and committed revert clear the fold. Forks record an authoritative parent sequence and derive values from the parent's ancestry through that cutoff. Model selection affects request assembly but is not itself an instruction source. See the [instruction sync design](./instruction-sync-proposal.md).
An instruction epoch spans completed compactions. `session.compaction.ended` moves the epoch start to its exact sequence, making current values initial, without reading sources or authoring an instruction event. Session movement retains state so destination changes become chronological updates; committed revert clears state so the next boundary establishes a fresh baseline. A fork copies messages only through its selected boundary but adopts the parent's newest instruction values as its baseline. Model selection affects request assembly but is not itself an instruction source.
## Compaction Rebuilds Active History
@@ -85,6 +85,6 @@ There is no separate finite Session-history endpoint. Request/response consumers
## Recovery Boundaries Stay Explicit
An advisory wake does not infer that ambiguous provider work is safe to retry after input promotion. Explicit resume may continue from durable projected history, but automatic hard-crash continuation requires a separate design covering provider-dispatch ambiguity, tool idempotency, retry budgets, and future clustered ownership.
An advisory wake is not itself crash recovery. Crash recovery is driven by a write-ahead execution claim that survives without a releasing terminal. Startup recovery resumes claimed top-level Sessions from durable projected history with bounded attempt accounting. It fails stale running tool projections before continuing, but it cannot prove whether an interrupted external operation already took effect and does not guarantee exactly-once provider or tool behavior.
Event replay ownership is separate from Session execution ownership. Local execution remains process-owned until clustering introduces an explicit placement and fencing protocol.