Compare commits

...
439 changed files with 147726 additions and 1112 deletions
+49
View File
@@ -0,0 +1,49 @@
name: deploy-lab-catalog
on:
push:
branches: [v2]
paths:
- ".github/workflows/deploy-lab-catalog.yml"
- "bun.lock"
- "package.json"
- "packages/drive/**"
- "packages/protocol/src/simulation.ts"
- "packages/simulation/**"
- "packages/lab/catalog/**"
workflow_dispatch:
concurrency:
group: deploy-lab-catalog-${{ github.ref_name }}
cancel-in-progress: false
permissions:
contents: read
jobs:
deploy:
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'v2'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- uses: ./.github/actions/setup-bun
- name: Install ffmpeg
run: |
sudo apt-get update
sudo apt-get install --yes ffmpeg
- name: Validate
run: |
bun --cwd packages/protocol typecheck
bun --cwd packages/simulation typecheck
bun --cwd packages/drive run check
bun --cwd packages/drive run test
bun --cwd packages/lab/catalog run check
- name: Deploy
working-directory: packages/lab/catalog
run: bun run deploy
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+7 -1
View File
@@ -55,6 +55,12 @@ jobs:
git config --global user.email "bot@opencode.ai"
git config --global user.name "opencode"
- name: Install ffmpeg
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install --yes ffmpeg
- name: Cache Turbo
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
@@ -66,7 +72,7 @@ jobs:
- name: Run unit tests
timeout-minutes: 20
run: GITHUB_ACTIONS=false bun turbo test
run: GITHUB_ACTIONS=false bun turbo test ${{ runner.os == 'Windows' && '--filter=!opencode-drive' || '' }}
env:
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: ${{ runner.os == 'Windows' && 'true' || 'false' }}
+4 -4
View File
@@ -51,7 +51,7 @@ files. If the script is unsuccessful, automatically fix the script and run it ag
Scripts use one typed definition object. `setup` runs before OpenCode starts,
and `fs.writeFile` always writes inside the simulated project.
You can read the full typed API here: https://raw.githubusercontent.com/jlongster/opencode-drive/refs/heads/main/src/script/types.ts
You can read the full typed API here: https://raw.githubusercontent.com/anomalyco/opencode/v2/packages/drive/src/script/types.ts
```ts
import { defineScript } from "opencode-drive"
@@ -83,7 +83,7 @@ itself (this is extremely rare, do not use this unless explicitly asked). In thi
mode `ui` is typed as `null`; call `server.launch()` exactly
once before launching clients. Each `clients.launch(name)` result provides the
same UI methods as the automatic client. You can see an example of this API
here: https://raw.githubusercontent.com/jlongster/opencode-drive/refs/heads/main/examples/multiple-clients.ts
here: https://raw.githubusercontent.com/anomalyco/opencode/v2/packages/drive/examples/multiple-clients.ts
Use the exported `wait(milliseconds)` utility for an unconditional delay.
@@ -114,8 +114,8 @@ completion are automatic.
You can see some example scripts here:
- https://raw.githubusercontent.com/jlongster/opencode-drive/refs/heads/main/examples/simple.ts
- https://raw.githubusercontent.com/jlongster/opencode-drive/refs/heads/main/examples/serve.ts
- https://raw.githubusercontent.com/anomalyco/opencode/v2/packages/drive/examples/simple.ts
- https://raw.githubusercontent.com/anomalyco/opencode/v2/packages/drive/examples/serve.ts
## Prune
+855 -544
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -33,6 +33,7 @@
"packages": [
"packages/*",
"packages/console/*",
"packages/lab/*",
"packages/stats/*",
"packages/slack"
],
@@ -120,7 +121,8 @@
"prettier": "3.6.2",
"semver": "^7.6.0",
"sst": "catalog:",
"turbo": "2.10.2"
"turbo": "2.10.2",
"vitest": "4.1.10"
},
"dependencies": {
"@aws-sdk/client-s3": "3.933.0",
+9 -2
View File
@@ -1,6 +1,6 @@
export * as ShellParse from "./parse.js"
import { Effect } from "effect"
import { Effect, Exit } from "effect"
import { fileURLToPath } from "url"
import os from "os"
import path from "path"
@@ -153,8 +153,15 @@ const ARITY: Record<string, number> = {
}
export const scan = Effect.fn("ShellParse.scan")(function* (command: string, shell: string, cwd: string) {
const parsers = yield* Effect.promise(load)
const powershell = ShellSelect.ps(shell)
const loaded = yield* Effect.promise(load).pipe(Effect.exit)
// Workerd has no filesystem-backed tree-sitter assets. Preserve execution
// with one conservative permission resource instead of disabling shell.
if (Exit.isFailure(loaded)) {
const tokens = command.trim().split(/\s+/)
return { commands: [{ resource: command, save: `${prefix(tokens).join(" ")} *` }], directories: [] }
}
const parsers = loaded.value
const tree = (powershell ? parsers.ps : parsers.bash).parse(command)
if (!tree) return yield* Effect.fail(new Error("Failed to parse shell command"))
+89
View File
@@ -0,0 +1,89 @@
# opencode-drive
## 1.4.3
### Patch Changes
- 99561ad: Restore controlled tools against the current V2 plugin API and add typed runtime control for write calls.
## 1.4.2
### Patch Changes
- b524213: Render light box-drawing borders as continuous geometric primitives.
- a24a09d: Defer recording font initialization so source-checkout scripts can start without loading a duplicate renderer.
## 1.4.1
### Patch Changes
- 6a8d52b: Prevent concurrent detached launchers from stealing prepared instance ownership and spawning competing daemon processes.
- d71356f: Restore compatibility with current OpenCode V2 checkouts and packed Drive installations. Drive now uses V2's built-in simulation transport and provider shape, isolates scripted service ports and command forms, and compiles standalone scripts against the launching Drive toolchain without package installation or source-directory links.
## 1.4.0
### Minor Changes
- c20d147: Control arbitrary provider-backed tool lifecycles with dynamic registration, structured progress, success, failure, cancellation, and reconnect-safe replay.
## 1.3.0
### Minor Changes
- 7caebeb: Expose semantic UI snapshots, exact semantic node polling, and safe semantic-node clicks for compatible OpenCode endpoints.
## 1.2.0
### Minor Changes
- 4e0c002: Write screenshots and recordings beneath run- and restart-scoped media directories so named outputs cannot overwrite earlier runs.
## 1.1.0
### Minor Changes
- fad9f96: Allow scripts and library drivers to intercept declared tools and control concurrent invocations by call ID at runtime.
### Patch Changes
- 63d3464: Keep service and progress output out of visible TUI sessions and avoid reinstalling the OpenTUI preload package for development checkouts.
- fd45cfe: Allow Drive runs to select a durable OpenCode database with the Effect-configured `OPENCODE_DRIVE_DB` setting while retaining `:memory:` as the default.
- e66adc1: Preserve recorded frame timing during MP4 encoding and reduce work for dense or unchanged terminal output.
- e7dff5f: Render diagonal quadrant block glyphs as exact terminal cell geometry in screenshots, recordings, and catalog frames.
- 63d3464: Export recordings at 60 FPS by default and preserve the requested frame rate in generated MP4 files.
## 1.0.0
### Major Changes
- 1009394: Remove the Promise-based simulation clients. `SimulationClient`, `BackendSimulationClient`, `connectSimulation`, and `connectBackendSimulation` are gone, along with the `opencode-drive/experimental` entry point. The `opencode-drive/client` entry now exports only the canonical protocol schemas and default ports; the public API is Effect-only, as documented. The CLI drives instances through the Effect `SimulationConnector` directly.
### Minor Changes
- 9deab8d: Add the browser-safe `opencode-drive/frame` entry point: canonical cell geometry, OpenTUI text-attribute bits, the geometric block/bar glyph table, and baseline placement shared by the Drive PNG renderer and downstream canvas renderers. The PNG renderer now also draws the `┃` and `╹` structural bars geometrically instead of with fonts.
### Patch Changes
- 8481090: Settle simulated LLM responses cleanly when OpenCode terminates an invocation during interruption. Drive now uses the negotiated `llm.pending` capability to distinguish external termination from genuine response write failures.
## 0.6.0
### Minor Changes
- 58c4801: Return simulated background shells immediately, continue their handlers asynchronously, notify the session when they finish, and cancel them when Drive shuts down.
- b5e8dfe: Make the script API Effect-only. Script setup and run callbacks, UI, LLM, filesystem, server, and TUI operations now return Effects; LLM serve handlers return Streams; and script cancellation uses Effect interruption without a Promise compatibility shim.
- 775f799: Remove the tool handler `AbortSignal`. Foreground session interruption, transport disconnects, and Drive shutdown now surface uniformly as Effect interruption, and controller shutdown awaits handler finalizers. Detached background shell handlers remain active after launch and are interrupted during Drive shutdown.
- 8e51796: Add deterministic shell, web fetch, and web search handlers with progress, success, failure, and interruption simulation.
- 905f846: Add `opencode-drive script init` for generating an Effect-native starter script and show focused migration guidance when `check` finds Promise-style script callbacks.
- d1bba54: Add first-class tool call input streaming through `Llm.toolCall` stream options.
- 72f7aff: Expose the authenticated generated OpenCode SDK as `opencode` to drivers and scripts.
- 37b4cd1: Give capabilities precise typed errors, validate UI predicates in canonical `ui.waitFor`, expose concrete failures through `Errors`, and keep pure response constructors exclusively under `Llm`.
- 13ec474: Unify the Effect driver and `defineScript` around one canonical programmatic model. Both expose the generated SDK as `opencode`, the primary frontend as `tui`, additional frontends through `tuis`, and the primary UI as `ui`. Every `Tui` has the same `{ ui, close, recording }` shape and `{ recording, viewport }` options. Project setup now uses the shared `Project`, `Setup`, `SetupContext`, and `ProjectFileSystem` types. Remove duplicate script UI types, flattened frontend handles, partial settlement controls, root-level raw simulation exports, convenience CLI aliases, and the `wait` helper.
### Patch Changes
- c8f5b51: Attach one best-effort normalized terminal frame to UI polling timeout errors without retaining screenshot artifacts.
- c8f5b51: Render OpenCode's full UI symbol set with deterministic bundled fallback fonts instead of platform fonts or hand-drawn symbol exceptions.
- c8f5b51: Preserve the managed driver's `Scope.Scope` requirement when consumed from TypeScript workspace applications.
- 40d2241: Render the background completion arrow correctly in exported recordings.
- 11cbbfd: Preserve the canonical OpenCode UI command shapes for optional named screenshots and key presses.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 opencode-drive
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+565
View File
@@ -0,0 +1,565 @@
# opencode-drive
This project gives your agents control over OpenCode:
- Run it during development and let your agents see and poke at the running instance
- Allow your agents to run it in headless mode and drive it to test things
## Requirements
OpenCode Drive requires [Bun](https://bun.sh/) 1.3.14 or newer. MP4 recording export also requires `ffmpeg` on `PATH`.
Install dependencies with:
```sh
bun install
```
## Skill
```sh
npx skills add anomalyco/opencode --agent opencode --skill opencode-drive
```
## Effect programs
The primary way to automate OpenCode is a default-exported, fully provided
Effect. Drive type-checks the module contract, compiles the script and its local
imports against the launching Drive toolchain, then validates and runs the
export in an isolated Bun process:
```ts
// drive.ts
import { OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use(({ ui }) => ui.screenshot("home"))
```
```sh
opencode-drive run ./drive.ts
```
`run` accepts exactly one module path. It rejects `--command.*` flags, other
command flags, and application arguments after `--`. Backend and UI behavior
belongs in the Effect program.
`OpenCodeDriver.use` is the safe default. It owns the scope, observes backend
failure, settles queued LLM work, closes every TUI, and exports recordings
whether the program succeeds or fails:
```ts
import { Effect } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use(
{
project: {
git: true,
files: { "src/value.ts": "export const value = 1\n" },
},
},
({ ui, llm }) =>
Effect.gen(function* () {
yield* llm.queue(Llm.text("The value is 1."))
yield* ui.submit("Read src/value.ts")
yield* ui.waitFor("The value is 1.")
}),
)
```
Use `OpenCodeDriver.useReport` when the program also needs structured evidence.
It returns the program value plus a schema-validated report containing branded
artifact and recording paths, retention, and the negotiated or legacy
compatibility of every simulation endpoint:
```ts
const result = yield * OpenCodeDriver.useReport(options, program)
yield * Effect.log(result.report)
```
Drive prefers `simulation.handshake` and explicitly records legacy fallback.
Require negotiation when protocol skew must fail before the program runs:
```ts
OpenCodeDriver.use(
{
opencode: { compatibility: "required" },
},
program,
)
```
Additional TUIs share the same server and LLM controller:
```ts
import { Effect } from "effect"
import { OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use((oc) =>
Effect.gen(function* () {
const secondary = yield* oc.tuis.launch({
viewport: { cols: 120, rows: 40 },
})
yield* oc.ui.screenshot("primary")
yield* secondary.ui.screenshot("secondary")
}),
)
```
The generated OpenCode SDK client is exposed as `opencode`; launched frontend
processes are `tui` and `tuis`. This keeps SDK calls distinct from terminal UI
control:
```ts
const health = yield * opencode.health.get()
const frame = yield * tui.ui.capture()
```
Enable recording per TUI. Settlement finishes each timeline and exports its
video automatically:
```ts
import { Effect } from "effect"
import { OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use({ tui: { recording: true } }, (oc) =>
Effect.gen(function* () {
yield* oc.ui.screenshot("recorded-home")
yield* Effect.log(`recording will be exported to ${oc.tui.recording?.path}`)
}),
)
```
Settlement errors are program failures. For example, output after a terminal
LLM event fails the run while `use` still closes TUIs and attempts recording
export:
```ts
import { Effect } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use(({ ui, llm }) =>
Effect.gen(function* () {
yield* llm.queue(Llm.finish(), Llm.text("too late"))
yield* ui.submit("trigger a response")
}),
)
```
Use `OpenCodeDriver.make` only when the program needs explicit terminal
settlement. It requires a scope, and `driver.settle()` must run before leaving
that scope:
```ts
import { Effect } from "effect"
import { OpenCodeDriver } from "opencode-drive"
export default Effect.scoped(
Effect.gen(function* () {
const driver = yield* OpenCodeDriver.make()
yield* driver.ui.screenshot("home")
yield* driver.settle()
}),
)
```
Use `opencode-drive check ./drive.ts` and `start --script` for the Effect-native
`defineScript` workflow described below.
## OpenCode development
Run this:
```sh
OPENCODE_DRIVE=1 bun run dev
```
If you installed the skill file, OpenCode will be able to see and interact with the running instance.
## Using with agents
Install the skill file above and ask the agent to test various flows with the app. Start with `--record` when you want a video; `opencode-drive stop` then exports the complete session and prints its path.
Screenshots and videos are written beneath `<system temp>/opencode-drive/output/<run-id>/<generation-id>`, so named outputs cannot overwrite media from earlier runs or restarts. Set `OPENCODE_DRIVE_MEDIA_DIR` to use a different media root.
Captured frames use the official full Commit Mono v1.143 faces at 16px with bundled Noto Symbols, Symbols 2, and Math fallbacks in a fixed 10x20 cell grid. Set `OPENCODE_DRIVE_FONT` to a comma-separated list of font files (for example regular, bold, italic, and bold-italic faces) to use a different primary capture font without changing the symbol fallback or cell geometry.
## UI development
If you are doing UI development in OpenCode, you might want to run it in a simulated mode. This allows `opencode-drive` to drive it and always put it into a state that you want to see.
Run it in visible mode:
```sh
opencode-drive start --visible --dev ~/projects/opencode
```
Initialize first when you need to customize the isolated environment before OpenCode starts:
```sh
artifacts=$(opencode-drive init --name demo)
cp -R ./fixtures/home/. "$artifacts/"
cp -R ./fixtures/project/. "$artifacts/files/"
opencode-drive start --name demo --visible --dev ~/projects/opencode
```
`start` reuses the prepared artifacts for that name. If `init` was not run, `start` initializes them automatically.
Drive uses an in-memory OpenCode database by default. Set
`OPENCODE_DRIVE_DB` when a test restarts the OpenCode service and needs sessions
to survive the replacement process. Relative paths resolve inside the isolated
run's OpenCode data directory:
```sh
OPENCODE_DRIVE_DB=restart.sqlite \
opencode-drive start --name restart-demo --script ./restart.ts
```
Remove artifact directories left by sessions that are no longer active:
```sh
opencode-drive prune
```
Prune one inactive instance's artifacts by instance name, or force removal of all artifact directories:
```sh
opencode-drive prune --name demo
opencode-drive prune --force
```
While developing, you can run `opencode-drive restart` to restart only the UI (the server will persist as a separate process). Do this with agents, and they will always restart and get the UI where you want it to be automatically.
View the [skills file](https://github.com/anomalyco/opencode/blob/v2/.opencode/skills/opencode-drive/SKILL.md) for more details about the CLI.
## Effect script API
Scripted runs use one fully typed, Effect-only definition. `setup` and `run`
return Effects; Promise callbacks are not part of the API:
```sh
opencode-drive script init ./drive.ts
```
This creates a canonical starter without overwriting an existing file. The
generated script is ready for `opencode-drive check ./drive.ts` and
`start --script ./drive.ts`.
```ts
import { defineScript, Effect, Llm } from "opencode-drive"
export default defineScript({
config: {
autoupdate: false,
},
tuiConfig: {
theme: "system",
},
project: {
git: true,
files: {
"src/example.ts": "export const value = 1\n",
},
},
setup: ({ config, tuiConfig }) =>
Effect.sync(() => {
config.username = "Drive"
tuiConfig.scroll_speed = 1
}),
run: ({ ui, llm }) =>
Effect.gen(function* () {
yield* ui.submit("Read src/example.ts")
yield* llm.send(Llm.text("The value is 1."))
yield* ui.waitFor("The value is 1.")
}),
})
```
`project.files` seeds the isolated project before `setup` runs. With
`project.git: true`, Drive creates a fresh repository and commits the complete
pre-launch state, including files written in `setup`. A prepared repository is
never replaced; omit `project.git` when an `init` step supplies Git history.
Declared `config` and `tuiConfig` values are deeply merged over fixture
`.opencode/opencode.jsonc` and `.opencode/tui.jsonc` files. Arrays replace
instead of merging, and mutations made in `setup` take final precedence.
Attach arbitrary provider-backed tools at runtime with their JSON schemas, then
take and settle native OpenCode invocations by model call ID. `attach` replaces
the complete dynamic set atomically; it does not affect the built-in adapters
configured through the driver or script `tools` option.
```ts
import { Effect } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use(({ tools, llm, ui }) =>
Effect.gen(function* () {
yield* tools.attach({
tools: [
{
name: "lookup",
description: "Look up a value",
inputSchema: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
},
outputSchema: {
type: "object",
properties: { answer: { type: "number" } },
required: ["answer"],
},
options: { codemode: false },
},
],
})
yield* llm.queue(
Llm.toolCall({
index: 0,
id: "call_lookup",
name: "lookup",
input: { query: "meaning" },
}),
Llm.finish("tool-calls"),
)
yield* ui.submit("Look up the meaning")
const lookup = yield* tools.take("call_lookup")
yield* lookup.progress({
structured: { phase: "searching" },
content: [{ type: "text", text: "Searching" }],
})
yield* lookup.finish({
structured: { answer: 42 },
content: [{ type: "text", text: "42" }],
})
}),
)
```
Drive owns progress sequence numbers and retries uncertain operations without
rerunning a claimed call. `awaitCancelled()` completes when OpenCode interrupts
the native invocation before `finish` or `fail`. Dynamic registrations survive
the tool-only controller reconnecting; an intentional server generation change
cancels unresolved calls and reapplies the desired set after launch.
Declare which built-in tools Drive should intercept with `tools`, then control
their invocations inside `run`. Each tool controller accepts calls in arrival
order or by the stable call ID chosen in `Llm.toolCall`:
```ts
import { Effect } from "effect"
import { defineScript, Llm } from "opencode-drive"
export default defineScript({
tools: ["shell"],
run: ({ ui, llm, tools }) =>
Effect.gen(function* () {
const shells = yield* tools.control("shell")
yield* llm.queue(
Llm.toolCall({
index: 0,
id: "call_shell",
name: "shell",
input: { command: "deploy production" },
}),
Llm.finish("tool-calls"),
)
yield* ui.submit("Deploy production")
const shell = yield* shells.take("call_shell")
yield* shell.progress(`Running: ${shell.input.command}...\n`)
yield* shell.succeed({ output: "Controlled output\n", exit: 0 })
}),
})
```
Use `calls.take(id)` to coordinate known parallel calls independently, or
`calls.take()` to accept the next unclaimed invocation. A controlled call can
emit progress and then succeed or fail exactly once. `awaitInterrupted()`
observes OpenCode interruption or transport disconnection. Drive interrupts
all unresolved calls when it shuts down.
The original `tools(registry)` callback remains available for fixed handlers
that do not need orchestration from `run`. Foreground handler Effects are
interrupted when OpenCode interrupts the session, the transport disconnects,
or Drive shuts down. Detached background shell handlers continue after their
launch response and are interrupted when Drive shuts down.
Only declared or registered tools are replaced. Unhandled tools continue to
use OpenCode's real implementations. Each `progress` value replaces the
visible tool output; send accumulated output when earlier lines should remain
visible.
Supported adapters are `shell`, `webfetch`, and `websearch`; each handler
receives its canonical typed V2 input and maintains an independent call index.
When a shell call sets `background: true`, Drive returns immediately with the
OpenCode tool call ID as `shellID`, keeps the handler running, and injects the
terminal `completed`, `error`, or `cancelled` result into the session
automatically. Background handlers are cancelled when Drive shuts down.
Type-check every new or edited script before running it:
```sh
opencode-drive check ./drive.ts
```
Drive resolves its script API, Effect, Bun declarations, and `tsgo` from the
launching installation without installing packages or modifying the script's
directory. When it detects an old Promise-style `setup`, `run`, or `ui.waitFor`
callback, it prints the equivalent Effect shape after the TypeScript
diagnostics. Use `Effect.sleep(milliseconds)` for unconditional delays.
The `fs`, `ui`, `llm`, `tools`, `server`, and `tuis` capabilities expose
Effect-returning operations. Compose them with `yield*`, `Effect.flatMap`, or
other Effect operators. Scripts receive the same `Ui`, `Tui`, `Tuis`, and TUI
options as `OpenCodeDriver`; `defineScript` does not define a second
programmatic interface. Predicates passed to `ui.waitFor` may return a boolean
or an Effect. Set `launch: "manual"` to launch the shared OpenCode server and
every TUI explicitly:
```ts
import { Effect } from "effect"
import { defineScript } from "opencode-drive"
export default defineScript({
launch: "manual",
run: ({ ui, server, tuis }) =>
Effect.gen(function* () {
// ui is null in manual mode.
yield* server.launch()
const alice = yield* tuis.launch("alice")
const bob = yield* tuis.launch("bob")
yield* alice.ui.submit("Hello from Alice")
yield* bob.ui.screenshot("bob-view")
}),
})
```
Only one server may be launched per script. All TUIs share its LLM backend. TUI
processes and compiled script artifacts are cleaned up when the script ends.
`yield* server.kill()` stops the server so it can be launched again later.
`yield* tui.close()` closes a TUI, after which its name may be reused.
Pass `{ recording: true }` to record an individual TUI:
```ts
const alice = yield * tuis.launch("alice", { recording: true })
yield * alice.ui.submit("Hello")
yield * alice.close()
```
Recordings are exported when the script settles. Call
`alice.recording.finish()` only when the video is needed before settlement.
Background title requests receive `OpenCode Drive` by default and do not
consume `llm.queue`, `llm.send`, or `llm.serve` responses. Manual-launch
scripts can customize them before starting the server:
```ts
yield * llm.title(() => Effect.succeed("Custom title"))
yield * server.launch()
```
Use `yield* llm.send(...)` to wait for and complete the next request or `yield*
llm.queue(...)` to declare future responses upfront. For ongoing responses,
the handler passed to `llm.serve` returns an Effect `Stream`:
```ts
import { Stream } from "effect"
import { Llm } from "opencode-drive"
yield * llm.serve((_request, index) => Stream.make(Llm.text(`Response ${index + 1}`)))
```
The backend connection, default `finish("stop")`, and cleanup are automatic.
Cancellation is represented by Effect interruption: interrupting the script or
the fiber running an operation interrupts its in-flight work and runs scoped
finalizers. There is no Promise compatibility shim or separate cancellation
API. All public script types are canonically defined in
[`src/script/types.ts`](./src/script/types.ts), which can be provided directly
to an authoring agent.
`Llm.text()` streams text in randomized chunks. It defaults to a 2 ms delay and
a target chunk size of 15 characters, varied by plus or minus 5 per chunk:
```ts
Llm.text("A deliberately slower response", { delay: 20, chunkSize: 10 })
```
`Llm.reasoning()` accepts the same streaming options. Use
`Llm.pause(milliseconds)` to add timing between any two outputs.
`Llm.toolCall()` emits a complete call atomically by default. Pass the same
streaming options to expose partial JSON input while it is generated:
```ts
Llm.toolCall(
{
index: 0,
id: "call_patch",
name: "patch",
input: { patchText: "*** Begin Patch\n*** End Patch" },
},
{ delay: 40, chunkSize: 12 },
)
```
Finish a tool-calling response with `Llm.finish("tool-calls")`. Streamed calls
drive OpenCode's normal tool-input start, delta, and end lifecycle; `Llm.raw()`
remains available for provider-wire scenarios not covered by these helpers.
Current OpenCode simulation endpoints expose a semantic UI tree alongside
renderer state and terminal capture. Use `ui.snapshot()` for the complete
versioned tree or `ui.getNode()` to poll for one exact semantic match. Semantic
nodes carry stable IDs, optional occurrence identity, role, label, hierarchy,
component-owned state, and a transient element handle that `ui.click()` can
resolve safely:
```ts
const allow =
yield *
ui.getNode({
role: "option",
label: "Allow once",
selected: true,
disabled: false,
})
yield * ui.click(allow)
```
`ui.snapshot` and atomic semantic clicks are negotiated as optional
capabilities so ordinary operations remain compatible with older OpenCode
checkouts. Calling `ui.snapshot()`, `ui.getNode()`, or `ui.click(node)` when its
required capability is unavailable fails locally with `UiCapabilityError`.
Capability errors are typed and the concrete classes are grouped under
`Errors`. UI timeouts remain owner-fatal even when caught; recover locally
from errors for which the script has a truthful fallback:
Polling timeouts from `ui.waitFor`, `ui.getElement`, and `ui.getNode` make one
best-effort, bounded `ui.capture` request. When it succeeds, the resulting
normalized terminal frame is available as `error.frame` without creating or
retaining a screenshot file. RPC-level timeouts and failed diagnostic captures
leave `error.frame` undefined.
```ts
import { Effect } from "effect"
import { Errors } from "opencode-drive"
yield *
ui
.getElement({ editor: true })
.pipe(Effect.catchTag("UiElementAmbiguousError", (error) => Effect.logWarning(`Matched ${error.count} editors`)))
const isFileSystemError = (error: unknown) => error instanceof Errors.FileSystemError
```
## Release validation
Before publishing a release, run the non-publishing validation command to
check, test, and inspect the packed artifact:
```sh
bun run release:validate
```
+27
View File
@@ -0,0 +1,27 @@
# Releasing opencode-drive
`opencode-drive` keeps its own version line. OpenCode product releases must not rewrite its version.
The imported baseline is `1.4.3` and the workspace package remains `private` until release setup is complete.
Do not remove that guard or publish from this repository until both release gates are complete:
1. The versions of `@opencode-ai/client` and `@opencode-ai/protocol` written into the packed Drive manifest are available on npm, including the `@opencode-ai/protocol/simulation` export.
2. npm package administration and trusted publishing move from `anomalyco/opencode-drive` to `anomalyco/opencode`.
The npm package is currently maintained by `jlongster`, and its trusted publisher is the old repository's
`publish.yml`. James must add the destination release operator as an npm owner or update the trusted publisher
himself. Keep James as an owner through the first successful release from this repository.
The first destination release will be `1.4.4`, which contains the pending special-key fix after `1.4.3`. Use a
dedicated GitHub-hosted workflow named `publish-drive.yml` with Node 24, npm trusted publishing, and
`id-token: write`. Its tag must be `opencode-drive-v1.4.4`; bare `v1.4.4` already belongs to OpenCode.
Before enabling that workflow:
1. Pack Drive and inspect the rewritten `package.json` inside the tarball.
2. Install the tarball in a clean Bun consumer and import every public export.
3. Run the installed `opencode-drive` binary and one scripted flow.
4. Configure npm's trusted publisher for `anomalyco/opencode` and `publish-drive.yml`.
5. Publish the namespaced tag and verify npm provenance points at this repository and workflow.
After the first successful destination release, disable the old publish workflow and archive the old repository.
@@ -0,0 +1,90 @@
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
@@ -0,0 +1,93 @@
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bun
import "../src/cli/index.js"
+46
View File
@@ -0,0 +1,46 @@
import * as Effect from "effect/Effect"
import { OpenCodeDriver, Tool } from "../src/index.js"
import type { Frontend, Project, Tui, Tuis, Ui } from "../src/index.js"
import type { ScriptContext } from "../src/script/types.js"
type Equal<Left, Right> =
(<Value>() => Value extends Left ? 1 : 2) extends <Value>() => Value extends Right ? 1 : 2 ? true : false
type Assert<Value extends true> = Value
export type ScriptUiIsCanonical = Assert<Equal<ScriptContext["ui"], Ui>>
export type ScriptTuiIsCanonical = Assert<Equal<ScriptContext["tui"], Tui>>
export type ScriptTuisAreCanonical = Assert<Equal<ScriptContext["tuis"], Tuis>>
export type ScriptToolsAreCanonical = Assert<Equal<ScriptContext["tools"], Tool.Controls>>
export type DriverToolsAreCanonical = Assert<Equal<OpenCodeDriver.Driver["tools"], Tool.Controls>>
export type LaunchedTuiIsCanonical = Assert<Equal<Effect.Success<ReturnType<Tuis["launch"]>>, Tui>>
export type ResizeIsCanonicalAction = Assert<
Equal<
Extract<Frontend.Action, { readonly type: "ui.resize" }>,
{
readonly type: "ui.resize"
readonly cols: number
readonly rows: number
}
>
>
export type DriverProjectIsCanonical = Assert<Equal<NonNullable<OpenCodeDriver.Options["project"]>, Project>>
const zeroConfig = OpenCodeDriver.use(() => Effect.void)
export type ZeroConfigUseIsRunnable = Assert<Equal<Effect.Services<typeof zeroConfig>, never>>
const controlledOptions: OpenCodeDriver.Options = { tools: ["shell"] }
declare const controls: Tool.Controls
const shellCalls = controls.control("shell")
declare const dynamicTools: Tool.AttachParams
const attached = controls.attach(dynamicTools)
const dynamicCall = controls.take("call_lookup")
declare const toolName: Tool.Name
controls.control(toolName)
export type ShellControlIsTyped = Assert<
Equal<Effect.Success<typeof shellCalls>, Tool.ControlledCalls<Tool.ShellInput, Tool.ShellResult>>
>
export type DynamicAttachIsTyped = Assert<Equal<Effect.Success<typeof attached>, void>>
export type DynamicCallIsTyped = Assert<Equal<Effect.Success<typeof dynamicCall>, Tool.Invocation>>
const controlled = OpenCodeDriver.use(controlledOptions, ({ tools }) => tools.control("shell").pipe(Effect.asVoid))
export type ControlledUseIsRunnable = Assert<Equal<Effect.Services<typeof controlled>, never>>
+500
View File
@@ -0,0 +1,500 @@
# OpenCode Driver API
Status: exploratory implementation, settled call sites only
This document records interface shapes that have been accepted during design. It intentionally omits unresolved alternatives rather than presenting them as competing proposals.
Internal resource ownership and desugaring are documented in [OpenCode Driver Architecture](./open-code-driver-architecture.md).
## Run Effect programs from the CLI
`opencode-drive run <module>` is the primary CLI entrypoint. The module must
default-export an `Effect<_, _, never>`. Before importing the module, Drive
generates and type-checks a contract entrypoint that assigns its default export
to that fully provided Effect type. Drive then imports the module, verifies the
value with `Effect.isEffect`, and yields it directly from the command handler.
There is no nested runtime or detached owner.
```ts
import { OpenCodeDriver } from "opencode-drive"
export default OpenCodeDriver.use(({ ui }) => ui.screenshot("home"))
```
```sh
opencode-drive run ./drive.ts
```
The command accepts no flags and no arguments after `--`. Use the driver API in
the module for simulation control. `opencode-drive check` validates Effect-only
`defineScript` modules, and `start --script` executes them.
## `use` settles one scoped driver
`OpenCodeDriver.use(run)` is the zero-configuration top-level interface;
`OpenCodeDriver.use(options, run)` configures the same lifecycle. Both acquire
the driver returned by `make`, run the program, validate queued LLM work,
finish recordings, close TUIs, export videos, and then release the server
and project scope.
`OpenCodeDriver.useReport(run)` and `useReport(options, run)` have the same lifecycle semantics and
returns both the user value and a compact `RunReport`. The report contains
validated artifact and recording paths, retention, and endpoint compatibility.
Set `opencode.compatibility` to `"required"` or `"preferred"`;
the default is `"preferred"`, which negotiates when supported and reports an
explicit legacy profile otherwise.
```ts
import { NodeRuntime } from "@effect/platform-node"
import { Effect } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
const program = OpenCodeDriver.use(
{
project: {
git: true,
files: {
"src/example.ts": "export const value = 1\n",
},
},
config: {
autoupdate: false,
},
tui: {
viewport: {
cols: 96,
rows: 32,
},
recording: false,
},
},
({ ui, llm }) =>
Effect.gen(function* () {
yield* llm.queue(Llm.text("The value is 1."))
yield* ui.submit("Read src/example.ts")
yield* ui.waitFor("The value is 1.")
}),
)
NodeRuntime.runMain(program)
```
`OpenCodeDriver.make(...)` remains the lower-level scoped constructor for programs that need to control settlement explicitly. Call `driver.settle()` before leaving its scope. `settle()` is terminal: it rejects new TUIs and LLM responses, validates queued work, stops TUIs, and exports recordings.
```ts
const program = Effect.scoped(
Effect.gen(function* () {
const driver = yield* OpenCodeDriver.make(options)
yield* driver.ui.submit("Hello")
yield* driver.settle()
}),
)
```
Capture font size is not part of this interface. The current renderer uses a fixed 16px font in 10-by-20 cells; the terminal catalog's `OPENCODE_DRIVE_FONT_SIZE=14` environment variable is currently ignored.
The generated SDK client is `opencode`. The primary frontend process is `tui`,
its UI is also available directly as `ui`, and `tuis` launches more frontend
processes:
```ts
const health = yield * driver.opencode.health.get()
const frame = yield * driver.tui.ui.capture()
const secondary = yield * driver.tuis.launch()
```
## The driver has one primary TUI and optional additional TUIs
The `tui` section configures the primary frontend created by `make`. Its UI is exposed directly as `ui` for the common case.
Additional TUIs connect to the same server and expose their own UI:
```ts
const program = Effect.scoped(
Effect.gen(function* () {
const oc = yield* OpenCodeDriver.make({
tui: {
viewport: {
cols: 96,
rows: 32,
},
},
})
const secondary = yield* oc.tuis.launch({
viewport: {
cols: 120,
rows: 40,
},
recording: true,
})
yield* oc.ui.submit("Prompt from the primary TUI")
yield* secondary.ui.submit("Prompt from the secondary TUI")
yield* oc.settle()
}),
)
```
`tuis.launch(options)` generates an identity. Pass a name as the first argument
when a stable identity is useful for logs, recordings, or closing and
relaunching the same TUI: `tuis.launch(name, options)`.
```text
╭────────────────╮
│ OpenCodeDriver ├───────────────────────╮
╰────────┬───────╯ │
╭────────────────╰──────────────────╮ │
▼ ▼ │
╭────────────────────────╮ ╭────────────────────╮ │
│ Shared OpenCode Server │ │ Shared LLM Control │ │
╰────────────┬───────────╯ ╰────────────────────╯ │
╰───────────────────────────────╮ │
▼ ▼ │
╭────────────────╮ ╭────────────────────╮ │
│ Primary TUI │◀───────────│ Additional TUIs │◀─────╯
╰────────┬───────╯ ╰──────────┬─────────╯
╰───╮ ╭──────╯
▼ ▼
╭────╮ ╭───────────╮
│ ui │ │ tui.ui │
╰────╯ ╰───────────╯
```
## Common scripts destructure UI and LLM control
Scripts that only need the primary TUI should normally destructure the driver:
```ts
const driver = yield * OpenCodeDriver.make()
const { ui, llm } = driver
yield * llm.queue(Llm.text("Hello from the simulated model."))
yield * ui.submit("Hello")
yield * ui.waitFor("Hello from the simulated model.")
yield * driver.settle()
```
Keep the aggregate value only when driver-wide capabilities such as `tuis` are needed:
```ts
const oc = yield * OpenCodeDriver.make()
const secondary = yield * oc.tuis.launch()
yield * oc.ui.screenshot("primary")
yield * secondary.ui.screenshot("secondary")
yield * oc.settle()
```
## Runtime tool control uses statically declared adapters
Declare the built-in tool names Drive should intercept before OpenCode starts,
then control each invocation through the live `tools` capability. Undeclared
tools keep their real OpenCode implementations.
```ts
const program = OpenCodeDriver.use({ tools: ["shell"] }, ({ tools, llm, ui }) =>
Effect.gen(function* () {
const shells = yield* tools.control("shell")
yield* llm.queue(
Llm.toolCall({
index: 0,
id: "call_build",
name: "shell",
input: { command: "bun run build" },
}),
Llm.toolCall({
index: 1,
id: "call_test",
name: "shell",
input: { command: "bun run test" },
}),
Llm.finish("tool-calls"),
)
yield* ui.submit("Build and test")
const build = yield* shells.take("call_build")
const test = yield* shells.take("call_test")
yield* test.succeed({ output: "Tests passed\n", exit: 0 })
yield* build.succeed({ output: "Build passed\n", exit: 0 })
}),
)
```
`take(callID)` reserves and accepts one known invocation independently of
arrival order. `take()` accepts the oldest unclaimed invocation. Exact-ID
waiters take precedence over generic waiters, so parallel calls may settle in
any deliberate order. Each call may emit serialized progress and then succeed
or fail exactly once. `awaitInterrupted()` completes when transport or
controller interruption wins before terminal settlement.
The program must take and terminally settle every intercepted invocation it
expects. Driver scope closure fails blocked `take` operations, interrupts
unresolved calls, and waits for transport cleanup. The callback-style
`tools(registry)` configuration remains available
for fixed handlers; callback-controlled tools are not also available through
the runtime `tools.control` capability.
## Arbitrary tools use the provider-backed lifecycle
`tools.attach({ tools })` atomically replaces the complete dynamic registration
set for the current run. Registrations use OpenCode's canonical JSON Schema,
permission, namespace, and CodeMode options. Static `shell`, `webfetch`, and
`websearch` adapters remain installed separately.
```ts
yield *
tools.attach({
tools: [
{
name: "lookup",
description: "Look up a value",
inputSchema: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
},
options: { codemode: false },
},
],
})
const invocation = yield * tools.take("call_lookup")
yield *
invocation.progress({
structured: { phase: "searching" },
content: [{ type: "text", text: "Searching" }],
})
yield *
invocation.finish({
structured: { answer: 42 },
content: [{ type: "text", text: "42" }],
})
```
`take(callID)` matches `context.callID`, the model call ID supplied to
`Llm.toolCall`; `invocation.id` is the producer's transport identity. Drive
deduplicates invocation replay after a controller reconnect and retries
progress or terminal operations with the same producer identity and progress
sequence. `awaitCancelled()` observes OpenCode's native interruption. There is
no public cancel operation because cancellation flows from OpenCode to Drive.
Attaching a dynamic effective name that collides with a configured static
adapter fails locally. Calling `attach({ tools: [] })` clears the dynamic set.
Older OpenCode revisions remain compatible with static adapters and ordinary
LLM control; dynamic attachment fails with `Tool.LifecycleError` when the six
tool lifecycle capabilities are unavailable.
## LLM response description is separate from live LLM control
`Llm` is a pure data module. `llm` is the live capability that queues, sends, and serves responses.
```ts
yield *
llm.queue(
Llm.reasoning("Inspecting the file"),
Llm.pause(20),
Llm.text("The value is 1.", {
delay: 2,
chunkSize: 15,
}),
Llm.finish("stop"),
)
```
Each constructor returns an ordinary serializable value. Raw values with the same schema remain accepted.
Tool calls remain atomic when options are omitted. Supplying stream options
serializes the input to JSON and emits provider-neutral partial tool input when
the endpoint advertises that capability. Older endpoints retain the existing
OpenAI-compatible fallback:
```ts
Llm.toolCall(
{
index: 0,
id: "call_patch",
name: "patch",
input: { patchText: "*** Begin Patch\n*** End Patch" },
},
{ delay: 40, chunkSize: 12 },
)
```
The authoritative schema is a manual union of independently named variants:
```ts
export const Text = Schema.Struct({
type: Schema.Literal("text"),
text: Schema.String,
options: Schema.optionalKey(StreamOptions),
})
export interface Text extends Schema.Schema.Type<typeof Text> {}
export const Reasoning = Schema.Struct({
type: Schema.Literal("reasoning"),
text: Schema.String,
options: Schema.optionalKey(StreamOptions),
})
export interface Reasoning extends Schema.Schema.Type<typeof Reasoning> {}
export const Pause = Schema.Struct({
type: Schema.Literal("pause"),
milliseconds: NonNegativeMilliseconds,
})
export interface Pause extends Schema.Schema.Type<typeof Pause> {}
export const Finish = Schema.Struct({
type: Schema.Literal("finish"),
reason: Schema.optionalKey(FinishReason),
})
export interface Finish extends Schema.Schema.Type<typeof Finish> {}
export const Output = Schema.Union([Text, Reasoning, Pause, Finish, ToolCall, Raw, Disconnect])
export type Output = Schema.Schema.Type<typeof Output>
```
Pure constructors delegate to those individual schemas:
```ts
export const text = (text: string, options?: StreamOptions): Text =>
Text.make({
type: "text",
text,
...(options ? { options } : {}),
})
```
No `.cases` interface appears in userland.
## One `queue` call describes one future model response
Multiple outputs in one call are ordered events within one response:
```ts
yield *
llm.queue(
Llm.toolCall({
index: 0,
id: "call_permission_capture",
name: "patch",
input: {
patchText,
},
}),
Llm.finish("tool-calls"),
)
```
A second call queues a response for the next model request:
```ts
yield * llm.queue(Llm.text("The fixture was updated."))
```
Responses without an explicit terminal output finish with `"stop"`. Title requests remain separate and do not consume this queue.
## `defineScript` is Effect-only
`defineScript` does not provide a Promise adapter. Its `setup` and `run`
callbacks return Effects, as do operations on `fs`, `ui`, `llm`, `server`,
and `tuis`. Compose script operations in the same runtime with
`yield*` or Effect operators.
### Primary UI
```ts
import { Effect } from "effect"
import { defineScript, Llm } from "opencode-drive"
export default defineScript({
run: ({ ui, llm }) =>
Effect.gen(function* () {
yield* llm.queue(Llm.text("The value is 1."))
yield* ui.submit("Read src/example.ts")
yield* ui.waitFor("The value is 1.")
}),
})
```
`llm.serve` accepts a handler that returns an Effect `Stream`. The registration
itself is also an Effect:
```ts
import { Stream } from "effect"
import { Llm } from "opencode-drive"
yield * llm.serve((_request, index) => Stream.make(Llm.text(`Response ${index + 1}`)))
```
Predicates passed to `ui.waitFor` may return a boolean or an Effect.
Capability methods expose typed error channels. Concrete tagged errors are
available from the `Errors` namespace.
`ui.snapshot()` returns the endpoint's versioned semantic tree. `ui.getNode()`
polls for one exact match and fails with `UiNodeAmbiguousError` when more than
one node matches. Semantic snapshots and identity-checked semantic clicks are
optional during negotiation, so older OpenCode checkouts retain ordinary UI
control while unsupported semantic operations fail locally with
`UiCapabilityError`.
```ts
const option =
yield *
ui.getNode({
role: "option",
label: "Allow once",
selected: true,
})
yield * ui.click(option)
```
### Additional TUI
```ts
yield * server.launch()
const alice = yield * tuis.launch("alice")
const bob = yield * tuis.launch("bob")
yield * alice.ui.submit("Hello from Alice")
yield * bob.ui.screenshot("bob-view")
```
### TUI configuration
```ts
export default defineScript({
tui: {
viewport: {
cols: 118,
rows: 34,
},
},
run: ({ ui }) => ui.screenshot("home").pipe(Effect.asVoid),
})
```
Script cancellation uses Effect interruption. Interrupting the script or an
operation's fiber interrupts in-flight work and runs its scoped finalizers;
there is no `AbortSignal`, Promise cancellation convention, or compatibility
shim.
## Settled interface
- `OpenCodeDriver.use(run)` and `use(options, run)` are the safe top-level brackets and perform typed settlement.
- `OpenCodeDriver.make(options)` is the primary scoped constructor.
- `opencode` is the generated OpenCode SDK client.
- Programs that call `make` directly call terminal `driver.settle()` before leaving the scope.
- Direct library programs run the same Effect without any export convention.
- The `tui` section configures one primary TUI.
- The primary TUI's UI is exposed as `ui` and `oc.ui`.
- The common case destructures `{ ui, llm }`.
- `oc.tuis.launch(options?)` creates an additional TUI with a generated identity.
- `oc.tuis.launch(name, options?)` creates a TUI with a stable identity.
- Additional TUIs expose their UI as `tui.ui`.
- Drivers and scripts share the same `Tui`, `Tuis`, `Ui`, and option types.
- `Llm` exposes pure constructors over manually composed Effect Schemas.
- Raw schema-compatible LLM output objects remain accepted.
- One `llm.queue(...)` call describes one future model response.
@@ -0,0 +1,228 @@
# OpenCode Driver Architecture
This guide describes the current Effect-native architecture. The public call
sites are documented in [OpenCode Driver API](./open-code-driver-api.md).
## Domain Model
`OpenCodeDriver` composes these resources:
```text
OpenCodeDriver
project isolated files and configuration
opencode generated OpenCode SDK client
tui primary frontend process
tuis additional frontend process factory
ui convenience alias for tui.ui
llm shared simulated-model control
tools runtime control for static adapters and arbitrary tools
```
The names distinguish the two kinds of client involved:
- `opencode` is the generated `@opencode-ai/client` SDK value.
- `Tui` is a launched OpenCode frontend process with `ui`, `close`, and an
optional `recording`.
- `Tuis` launches and supervises additional frontend processes connected to
the same server.
- `tools.control` accepts independently controlled invocations for adapters
declared before OpenCode starts.
- `tools.attach` and `tools.take` control arbitrary native tools through the
canonical provider-backed lifecycle.
- Transport-level JSON-RPC clients remain private implementation details.
`defineScript` consumes these exact capabilities. It adds a branded module
contract, restart behavior, filesystem access, and explicit manual launch. It
does not define another UI, TUI, LLM, or project vocabulary.
## Ownership
```text
Effect Scope
OpenCodeProject
artifact root
isolated project files
OpenCodeInstance
server process
TUI processes
launch descriptors and logs
CLI script ToolController
controlled invocation exchanges
OpenCodeServer
backend simulation connection
reconnecting tool-only backend connection
LLM controller
dynamic ToolProducer
generated OpenCode SDK connection
TUI supervisor
primary TUI scope
additional TUI scopes
Library ToolController
controlled invocation exchanges
```
Library drivers create their ToolController before project preparation and
pass that controller into `OpenCodeInstance`. CLI scripts create the controller
inside `OpenCodeInstance`. Prepared drivers and script contexts combine the
instance's static controller with the server's dynamic producer. The static
controller that wrote plugin configuration remains the one exposed through
`tools.control`.
`OpenCodeDriver.make(options)` requires `Scope.Scope`. It returns once the
server, generated SDK client, primary TUI, and simulation connections are
ready. `OpenCodeDriver.use` supplies that scope and performs terminal
settlement even when the user program fails.
## Settlement
Settlement is one shared terminal operation. It runs in this order:
1. Validate that queued LLM work was consumed.
2. Validate that native dynamic-tool invocations were settled.
3. Shut down the LLM controller.
4. Finish active recording timelines.
5. Close all TUI scopes and processes.
6. Export completed recordings.
7. Decode the schema-validated `RunReport`.
`driver.settle()` is shared and idempotent. Once settlement starts, `tuis`
rejects new launches and `llm` rejects new responses. `OpenCodeDriver.use`
combines a user-program failure with a settlement failure rather than hiding
either cause.
## Tool Control Lifecycle
`ToolController` installs only statically declared or callback-registered
adapters into OpenCode's project configuration. Each runtime-controlled tool
owns one exchange that matches incoming requests to exact-ID or FIFO waiters.
Each accepted call owns a terminal Deferred, an interruption Deferred, and a
one-permit Semaphore that serializes progress with terminal commitment.
Controller scope release closes blocked waiters, marks unresolved calls
interrupted, aborts active HTTP transports, and waits for handler finalizers.
Terminal commitment uses a synchronous first-writer-wins Deferred completion;
Drive guarantees exactly-once acceptance inside the controller, not delivery
across a transport disconnect.
`ToolProducer` owns a separate backend socket because LLM chunks are not
idempotent and an LLM socket closure is terminal to `LlmController`. Dynamic
tool progress and terminal RPCs are idempotent by producer invocation ID and
sequence, so the tool-only connection may reconnect and replay pending
invocations safely. One ordered event stream preserves invocation-before-
cancellation order. The desired registration set survives reconnects and
manual server relaunches; invocation records are scoped to one server
generation because producer IDs may be reused by a new process.
Settlement first clears the dynamic registration set on OpenCode, then drains
the ordered local event stream before checking for unresolved invocations. The
clear acts as the server-side barrier that prevents a native invocation from
appearing after a successful settlement snapshot. Settlement is terminal for
dynamic attachment. Reconnects remain available while the clear is in flight;
the final connection gate drains any reconnect that landed during settlement
before preventing further backend creation. If the server generation has
already ended, its teardown has cleared the generation-scoped invocation
records, so settlement does not wait for a replacement backend.
## TUI Lifecycle
`Tuis.launch(options)` generates an internal identity. `Tuis.launch(name,
options)` uses a stable caller-supplied identity. Both return the same value:
```ts
interface Tui {
readonly ui: Ui
readonly close: () => Effect.Effect<void>
readonly recording?: Recording
}
```
Each TUI owns one frontend process, one negotiated UI connection, and
optionally one recording timeline. Closing a named TUI releases its identity
for reuse. An unexpected process exit fails the owning driver or script.
The primary TUI is not a special interface. `driver.tui` and values returned
by `driver.tuis` have exactly the same `Tui` type. `driver.ui` is only
`driver.tui.ui` exposed for the common single-TUI call site.
## OpenCode SDK
The server process writes an authenticated service registration into its
isolated state directory. `driver/opencode.ts` discovers that registration and
constructs the generated Effect SDK client with the project directory header.
Passwords and registration paths remain internal. The resulting value is
exposed as `driver.opencode` and `ScriptContext.opencode`.
## Canonical Protocol
`@opencode-ai/protocol/simulation` contains the single schema definition for OpenCode's
handshake, frontend, and backend simulation messages. `client/protocol.ts`
publishes those namespaces without redefining their data types.
```text
Frontend protocol schemas
-> driver/ui.ts Effect Ui capability
-> driver/client.ts Tui and Tuis lifecycle
-> driver/index.ts OpenCodeDriver aggregate
-> script/types.ts exact capability reuse
```
CLI `--command.ui.*` names are exhaustively checked against
`Frontend.Capabilities`. The Promise transport under `opencode-drive/client`
is separate from the Effect programmatic model but consumes the same protocol
schemas.
## Transport Seam
`SimulationConnector` owns WebSocket acquisition, handshake negotiation,
schema validation, request correlation, interruption, and connection failure.
The driver receives the connector through an Effect service and does not
expose it in userland.
The UI connection is request-response JSON-RPC. The LLM backend additionally
receives unsolicited `llm.request` notifications. The tool-only backend keeps
ordered `tool.invocation` and `tool.cancel` notifications on one validated
stream and does not call `llm.attach`.
## Project Setup
Neutral project contracts live in `src/project.ts` so neither the driver nor
scripts own the shared vocabulary:
```text
Project
Setup
SetupContext
ProjectFileSystem
OpenCodeConfig
OpenCodeTuiConfig
```
Configuration is applied in this order:
1. Write declared project files.
2. Read fixture `opencode.jsonc` and `tui.jsonc` values.
3. Deep-merge `config` and `tuiConfig`; arrays replace existing arrays.
4. Run Effect-only `setup`, which may mutate both merged objects.
5. Write normalized JSON and optionally commit the Git baseline.
## Dependency Direction
```text
project -> Effect and Schema
simulation -> canonical protocol and Effect RPC
driver -> project + simulation + instance + recording
script -> project + driver capabilities
cli -> script + driver + Promise transport
```
Lower-level modules do not import the package root or the driver/script
barrels. `script/types.ts` may reference driver capabilities; driver modules
must not reference script types.
## Public Entry Points
- `opencode-drive`: Effect driver, scripts, project contracts, LLM constructors.
- `opencode-drive/driver`: complete Effect driver namespace.
- `opencode-drive/script`: `defineScript` and script contracts.
- `opencode-drive/client`: Promise simulation transport.
- `opencode-drive/llm`: pure LLM output constructors and schemas.
- `opencode-drive/recording`: recording decode, replay, and export utilities.
@@ -0,0 +1,58 @@
import { Effect, Stream } from "effect"
import { defineScript, Llm } from "opencode-drive"
export default defineScript({
launch: "manual",
run: ({ server, tuis, llm }) =>
Effect.gen(function* () {
yield* server.launch()
yield* llm.serve((_request, index) => Stream.make(Llm.text(`Response for request ${index + 1}`)))
const [alice, bob] = yield* Effect.all(
[tuis.launch("alice", { recording: true }), tuis.launch("bob", { recording: true })],
{ concurrency: "unbounded" },
)
yield* Effect.all([alice.ui.submit("Reply to Alice"), bob.ui.submit("Reply to Bob")], {
concurrency: "unbounded",
})
yield* Effect.all(
[alice.ui.screenshot("multiple-clients-alice-submitted"), bob.ui.screenshot("multiple-clients-bob-submitted")],
{ concurrency: "unbounded" },
)
yield* Effect.all(
[
alice.ui.waitFor("Response for request", { timeout: 30_000 }),
bob.ui.waitFor("Response for request", { timeout: 30_000 }),
],
{ concurrency: "unbounded" },
)
yield* Effect.all(
[alice.ui.screenshot("multiple-clients-alice-complete"), bob.ui.screenshot("multiple-clients-bob-complete")],
{ concurrency: "unbounded" },
)
yield* server.kill()
yield* Effect.sleep(500)
yield* Effect.all(
[
alice.ui.screenshot("multiple-clients-alice-server-stopped"),
bob.ui.screenshot("multiple-clients-bob-server-stopped"),
],
{ concurrency: "unbounded" },
)
yield* server.launch()
yield* Effect.sleep(1000)
yield* Effect.all(
[
alice.ui.screenshot("multiple-clients-alice-server-relaunched"),
bob.ui.screenshot("multiple-clients-bob-server-relaunched"),
],
{ concurrency: "unbounded" },
)
}),
})
+43
View File
@@ -0,0 +1,43 @@
import { Effect, Stream } from "effect"
import { defineScript, Llm } from "opencode-drive"
export default defineScript({
setup: ({ fs }) =>
fs.writeFile(
"src/greeting.ts",
["export function greeting(name: string) {", " return `Welcome, ${name}!`", "}", ""].join("\n"),
),
run: ({ llm, ui }) =>
Effect.gen(function* () {
let turn = 0
yield* llm.title(() => Effect.succeed("Understanding the greeting"))
yield* llm.serve(() => {
if (turn++ === 0)
return Stream.make(
Llm.reasoning("I should read the implementation before explaining it."),
Llm.toolCall({
index: 0,
id: "call_read_greeting",
name: "read",
input: { filePath: "src/greeting.ts" },
}),
Llm.finish("tool-calls"),
)
return Stream.make(
Llm.text("The function accepts a name, "),
Llm.pause(150),
Llm.text("places it into a welcome message, "),
Llm.pause(150),
Llm.text("and adds an exclamation mark."),
Llm.pause(150),
Llm.finish("stop"),
)
})
yield* ui.submit("Read src/greeting.ts and explain what it does.")
yield* ui.waitFor("adds an exclamation mark")
}),
})
+32
View File
@@ -0,0 +1,32 @@
import { Effect } from "effect"
import { defineScript, Llm } from "opencode-drive"
export default defineScript({
setup: ({ fs }) => fs.writeFile("src/message.ts", 'export const message = "Hello from OpenCode Drive"\n'),
run: ({ llm, ui }) =>
Effect.gen(function* () {
yield* ui.waitFor((state) => state.focused.editor)
const editor = yield* ui.getElement({ editor: true, focused: true })
yield* ui.focus(editor)
yield* ui.submit("What does src/message.ts export?")
yield* llm.send(
Llm.reasoning("I should inspect the small source file first.", {
delay: 5,
chunkSize: 10,
}),
Llm.pause(100),
Llm.text('src/message.ts exports `message` with the value "Hello from OpenCode Drive".', {
delay: 10,
chunkSize: 12,
}),
)
yield* llm.send(Llm.text("Message export"))
yield* ui.waitFor("Hello from OpenCode Drive")
if (!(yield* ui.matches("OpenCode Drive"))) throw new Error("the expected response was not visible")
yield* ui.screenshot("simple-response")
}),
})
@@ -0,0 +1,43 @@
import { Effect } from "effect"
import { defineScript, Llm } from "opencode-drive"
export default defineScript({
tui: { viewport: { cols: 120, rows: 36 } },
setup: ({ fs }) => fs.writeFile("src/viewport.ts", `export const viewportSequence = ["120x36", "80x24", "50x18"]\n`),
run: ({ ui, llm }) =>
Effect.gen(function* () {
yield* ui.submit("Show a compact status report for the viewport resize demo.")
yield* llm.send(
Llm.text(
"Viewport demo: starting wide at 120 columns by 36 rows. The file src/viewport.ts lists the planned sequence. This first response should have plenty of horizontal room before the terminal narrows.",
),
)
yield* Effect.sleep(900)
yield* ui.resize({ cols: 80, rows: 24 })
yield* Effect.sleep(900)
yield* ui.submit("Now describe the medium viewport.")
yield* llm.send(
Llm.text(
"Medium viewport: resized to 80 columns by 24 rows. Lines should wrap sooner, the composer has less vertical breathing room, and the conversation should reflow without losing focus.",
),
)
yield* ui.waitFor("resized to 80 columns")
yield* Effect.sleep(900)
yield* ui.resize({ cols: 50, rows: 18 })
yield* Effect.sleep(900)
yield* ui.submit("Finish with the narrow viewport summary.")
yield* llm.send(
Llm.text(
"Narrow viewport: now 50 columns by 18 rows. This final state is intentionally cramped so modal, wrapping, and footer behavior are easy to inspect in the recording.",
),
)
yield* ui.waitFor("now 50 columns")
yield* Effect.sleep(1200)
}),
})
+80
View File
@@ -0,0 +1,80 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode-drive",
"version": "1.4.3",
"private": true,
"description": "Drive real and simulated OpenCode instances",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/anomalyco/opencode.git",
"directory": "packages/drive"
},
"homepage": "https://github.com/anomalyco/opencode/tree/v2/packages/drive#readme",
"bugs": "https://github.com/anomalyco/opencode/issues",
"type": "module",
"packageManager": "bun@1.3.14",
"engines": {
"bun": ">=1.3.14"
},
"bin": {
"opencode-drive": "bin/opencode-drive"
},
"exports": {
".": "./src/index.ts",
"./client": "./src/client/index.ts",
"./driver": "./src/driver/index.ts",
"./frame": "./src/frame/index.ts",
"./llm": "./src/llm/index.ts",
"./recording": "./src/recording/index.ts",
"./script": "./src/script/index.ts"
},
"files": [
"assets/fonts",
"bin/opencode-drive",
"docs",
"src/cli",
"src/client",
"src/driver",
"src/frame",
"src/instance",
"src/llm",
"src/log.ts",
"src/project.ts",
"src/recording",
"src/script",
"src/simulation",
"src/tool",
"src/index.ts",
"LICENSE",
"README.md"
],
"scripts": {
"drive": "bun run src/cli/index.ts",
"lint": "cd ../.. && bun run lint -- packages/drive/src",
"test": "bun run test:effect && bun run test:cli",
"test:effect": "bun run --bun vitest run",
"test:cli": "bun test test/cli/integration.test.ts",
"typecheck": "tsgo --noEmit",
"check": "bun run lint && bun run typecheck",
"release:validate": "bun run check && bun run test && bun pm pack --dry-run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@napi-rs/canvas": "1.0.2",
"@opencode-ai/client": "workspace:*",
"@opencode-ai/protocol": "workspace:*",
"@types/bun": "catalog:",
"@typescript/native-preview": "catalog:",
"@wterm/core": "0.3.0",
"@wterm/ghostty": "0.3.0",
"effect": "catalog:"
},
"devDependencies": {
"@effect/vitest": "4.0.0-beta.101",
"@tsconfig/bun": "catalog:",
"oxlint": "1.60.0",
"typescript": "catalog:",
"vitest": "4.1.10"
}
}
+74
View File
@@ -0,0 +1,74 @@
import { rm } from "node:fs/promises"
import { initializeInstance } from "../instance/instance.js"
import { checkScript } from "../script/tooling.js"
export async function check(file: string) {
const artifacts = await initializeInstance()
try {
try {
await checkScript(artifacts, file)
} catch (error) {
const source = await Bun.file(file)
.slice(0, 256 * 1024)
.text()
.catch(() => "")
const hint = effectScriptHint(source, message(error))
if (hint !== undefined) throw new Error(`${message(error)}\n\n${hint}`, { cause: error })
throw error
}
} finally {
await rm(artifacts, { recursive: true, force: true })
}
}
export function effectScriptHint(source: string, diagnostics: string) {
if (!/\bPromise(?:Like)?</.test(diagnostics)) return undefined
if (!/\bdefineScript\s*\(/.test(source)) return undefined
const relevant = diagnosticSource(source, diagnostics)
if (/\.waitFor\s*\(/.test(relevant))
return `${heading}
Instead of:
ui.waitFor(async (state) => state.focused.editor)
Use:
ui.waitFor((state) => Effect.succeed(state.focused.editor))`
if (/\bsetup\s*:|\basync\s+setup\s*\(/.test(relevant))
return `${heading}
Instead of:
setup: async ({ fs }) => {
await fs.writeFile("src/example.ts", "export {}")
}
Use:
setup: ({ fs }) => fs.writeFile("src/example.ts", "export {}")`
if (/\brun\s*:|\basync\s+run\s*\(/.test(relevant))
return `${heading}
Instead of:
run: async ({ ui }) => {
await ui.submit("Hello")
}
Use:
run: ({ ui }) =>
Effect.gen(function* () {
yield* ui.submit("Hello")
})`
return undefined
}
const heading = "OpenCode Drive scripts are Effect-only. Promise callbacks are not supported."
function diagnosticSource(source: string, diagnostics: string) {
const lines = source.split("\n")
const numbers = [...diagnostics.matchAll(/(?::(\d+):\d+|\((\d+),\d+\))/g)]
.map((match) => Number(match[1] ?? match[2]))
.filter((line) => Number.isInteger(line) && line > 0)
return numbers.length === 0 ? source : numbers.map((line) => lines[line - 1] ?? "").join("\n")
}
function message(error: unknown) {
return error instanceof Error ? error.message : String(error)
}
+204
View File
@@ -0,0 +1,204 @@
import * as Cause from "effect/Cause"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import { Frontend } from "../client/protocol.js"
import { recordLog } from "../log.js"
import * as SimulationConnector from "../simulation/connector.js"
import type { DriveCommand } from "./types.js"
export const commandInfo = {
"ui.type": { value: true, description: "Type text using JSON params" },
"ui.press": { value: true, description: "Press a key using JSON params" },
"ui.enter": { value: false, description: "Press Enter" },
"ui.arrow": {
value: true,
description: "Press an arrow key using JSON params",
},
"ui.focus": {
value: true,
description: "Focus an element using JSON params",
},
"ui.click": { value: true, description: "Click using JSON params" },
"ui.resize": {
value: true,
description: "Resize terminal viewport using JSON params",
},
"ui.screenshot": {
value: "optional",
description: "Take a screenshot with optional JSON params and return its path",
},
"ui.capture": {
value: false,
description: "Capture the terminal frame as JSON",
},
"ui.state": {
value: false,
description: "Return focus, elements, and available UI actions",
},
"ui.snapshot": {
value: false,
description: "Return the semantic UI tree as JSON",
},
"ui.matches": {
value: true,
description: "Check for literal screen text using JSON params",
},
"ui.recording.finish": {
value: false,
description: "Finish recording and return the timeline path",
},
} as const satisfies Record<
Exclude<Frontend.Capability, "ui.click.semantic">,
{ readonly value: boolean | "optional"; readonly description: string }
>
type CommandName = Exclude<Frontend.Capability, "ui.click.semantic">
export function isCommandName(operation: string): operation is CommandName {
return Object.hasOwn(commandInfo, operation)
}
export function commandAcceptsValue(operation: CommandName) {
return commandInfo[operation].value
}
export function commandNames() {
return Object.keys(commandInfo).sort()
}
export class SimulationError extends Error {
constructor(
message: string,
readonly method?: string,
) {
super(message)
this.name = "SimulationError"
}
}
export class CommandBatchError extends Error {
constructor(
readonly results: ReadonlyArray<{
readonly command: string
readonly result: unknown
}>,
readonly reason: unknown,
) {
super(reason instanceof Error ? reason.message : String(reason))
this.name = "CommandBatchError"
}
}
const callTimeout = 30_000
export async function executeCommands(endpoint: string, commands: ReadonlyArray<DriveCommand>) {
const exit = await Effect.runPromiseExit(Effect.scoped(executeBatch(endpoint, commands)))
if (Exit.isSuccess(exit)) return exit.value
const reason = Cause.squash(exit.cause)
throw reason instanceof CommandBatchError ? reason : new CommandBatchError([], reason)
}
const executeBatch = Effect.fn("DriveCli.executeBatch")(function* (
endpoint: string,
commands: ReadonlyArray<DriveCommand>,
) {
const connection = yield* SimulationConnector.ui(endpoint, {
connectTimeout: callTimeout,
}).pipe(
Effect.mapError(
(cause) => new SimulationError(cause instanceof Error ? cause.message : `cannot connect to ${endpoint}`),
),
)
const results: Array<{ readonly command: string; readonly result: unknown }> = []
for (const command of commands) {
const result = yield* execute(connection, command).pipe(
Effect.mapError((error) => new CommandBatchError(results, error)),
)
results.push({ command: command.operation, result })
}
return { results }
})
const execute = (
connection: SimulationConnector.UiConnection,
command: DriveCommand,
): Effect.Effect<unknown, SimulationError> =>
Effect.suspend(() => {
recordLog("INFO", `ui command ${command.operation} params=${command.value ?? "undefined"}`)
return dispatch(connection, decodeCommand(command))
}).pipe(
Effect.timeoutOrElse({
duration: callTimeout,
orElse: () => Effect.fail(new SimulationError(`timed out after ${callTimeout}ms`, command.operation)),
}),
Effect.mapError((cause) =>
cause instanceof SimulationError
? cause
: new SimulationError(cause instanceof Error ? cause.message : String(cause), command.operation),
),
Effect.tap(() => Effect.sync(() => recordLog("INFO", `ui command ${command.operation} completed`))),
Effect.tapError((error) =>
Effect.sync(() => recordLog("ERROR", `ui command ${command.operation} failed: ${error.message}`)),
),
)
function decodeCommand(command: DriveCommand): Frontend.Request {
if (command.value === undefined && commandInfo[command.operation].value === true)
throw new Error(`${command.operation} requires a value`)
return Frontend.decodeRequest(
{
jsonrpc: "2.0",
method: command.operation,
...(command.value === undefined ? {} : { params: JSON.parse(command.value) }),
},
{ onExcessProperty: "error" },
)
}
function dispatch(
connection: SimulationConnector.UiConnection,
request: Frontend.Request,
): Effect.Effect<unknown, unknown> {
if (
request.method === "ui.snapshot" &&
!SimulationConnector.supportsCapability(connection.compatibility, "ui.snapshot")
)
return Effect.fail(new SimulationError("ui.snapshot is not available on this OpenCode endpoint", request.method))
if (
request.method === "ui.click" &&
request.params.semantic !== undefined &&
!SimulationConnector.supportsCapability(connection.compatibility, "ui.click.semantic")
)
return Effect.fail(
new SimulationError("semantic ui.click is not available on this OpenCode endpoint", request.method),
)
switch (request.method) {
case "ui.type":
return connection.rpc["ui.type"](request.params)
case "ui.press":
return connection.rpc["ui.press"](request.params)
case "ui.enter":
return connection.rpc["ui.enter"]()
case "ui.arrow":
return connection.rpc["ui.arrow"](request.params)
case "ui.focus":
return connection.rpc["ui.focus"](request.params)
case "ui.click":
return connection.rpc["ui.click"](request.params)
case "ui.resize":
return connection.rpc["ui.resize"](request.params)
case "ui.screenshot":
return connection.rpc["ui.screenshot"](request.params)
case "ui.capture":
return connection.rpc["ui.capture"]()
case "ui.state":
return connection.rpc["ui.state"]()
case "ui.snapshot":
return connection.rpc["ui.snapshot"]()
case "ui.matches":
return connection.rpc["ui.matches"](request.params)
case "ui.recording.finish":
return connection.rpc["ui.recording.finish"]()
}
throw new Error(`unsupported UI method ${request.method}`)
}
+6
View File
@@ -0,0 +1,6 @@
import { resolveInstance } from "../instance/registry.js"
export async function dir(name?: string) {
const manifest = await resolveInstance(name)
console.log(manifest.artifacts)
}
+257
View File
@@ -0,0 +1,257 @@
#!/usr/bin/env bun
import * as NodeRuntime from "@effect/platform-node/NodeRuntime"
import * as NodeServices from "@effect/platform-node/NodeServices"
import { Effect, Option } from "effect"
import { Argument, Command, Flag } from "effect/unstable/cli"
import packageJson from "../../package.json" with { type: "json" }
import { extractCommands } from "./parse.js"
import { check } from "./check.js"
import { dir } from "./dir.js"
import { init } from "./init.js"
import { list } from "./list.js"
import { prune } from "./prune.js"
import { restart } from "./restart.js"
import { runProgram } from "./run.js"
import { send } from "./send.js"
import { initScript } from "./script-init.js"
import { start } from "./start.js"
import { stop } from "./stop.js"
import { logError } from "../log.js"
import type { DriveCommand, SendOptions, StartOptions } from "./types.js"
const extracted = extract()
const initName = Flag.string("name").pipe(Flag.withDescription("Instance name"))
const startName = Flag.string("name").pipe(
Flag.optional,
Flag.withDescription("Instance name (optional with --visible)"),
)
const name = Flag.string("name").pipe(
Flag.optional,
Flag.withDescription("Instance name (defaults to the visible instance)"),
)
const pruneName = Flag.string("name").pipe(Flag.optional, Flag.withDescription("Instance name"))
const initCommand = Command.make("init", { name: initName }, (config) => execute(() => init(config.name))).pipe(
Command.withDescription("Initialize an instance without launching OpenCode"),
Command.withExamples([
{
command: "opencode-drive init --name demo",
description: "Create an instance and print its artifact directory",
},
]),
)
const checkCommand = Command.make("check", { file: Argument.string("script") }, (config) =>
execute(() => check(config.file)),
).pipe(
Command.withDescription("Type-check an OpenCode Drive script"),
Command.withExamples([
{
command: "opencode-drive check ./drive.ts",
description: "Type-check a script with the bundled script API",
},
]),
)
const scriptInitCommand = Command.make("init", { file: Argument.string("file") }, (config) =>
execute(() => initScript(config.file)),
).pipe(
Command.withDescription("Create an Effect-native OpenCode Drive script"),
Command.withExamples([
{
command: "opencode-drive script init ./drive.ts",
description: "Create a type-checkable script without overwriting existing files",
},
]),
)
const scriptCommand = Command.make("script").pipe(
Command.withDescription("Create and manage OpenCode Drive scripts"),
Command.withSubcommands([scriptInitCommand]),
)
const runCommand = Command.make("run", { module: Argument.string("module") }, (config) =>
executeEffect(
Effect.try({
try: () => toRunModule(config.module, extracted.commands, extracted.app),
catch: (error) => error,
}).pipe(Effect.flatMap(runProgram), Effect.asVoid),
),
).pipe(
Command.withDescription("Type-check and run a fully provided Effect program"),
Command.withExamples([
{
command: "opencode-drive run ./drive.ts",
description: "Run a default-exported Effect program",
},
]),
)
const startCommand = Command.make(
"start",
{
name: startName,
daemon: Flag.boolean("daemon").pipe(Flag.withHidden, Flag.withDescription("Run as detached instance owner")),
script: Flag.string("script").pipe(
Flag.optional,
Flag.withDescription("JavaScript or TypeScript automation module"),
),
visible: Flag.boolean("visible").pipe(Flag.withDescription("Show OpenCode in the terminal")),
record: Flag.boolean("record").pipe(
Flag.withDescription("Record the complete headless session and export it on stop"),
),
dev: Flag.string("dev").pipe(Flag.optional, Flag.withDescription("Path to an OpenCode development checkout")),
},
(config) =>
executeEffect(
Effect.try({
try: () => toStartOptions(config, extracted.commands, extracted.app),
catch: (error) => error,
}).pipe(Effect.flatMap(start)),
),
).pipe(
Command.withDescription("Launch a local simulated OpenCode instance"),
Command.withExamples([
{
command: "opencode-drive start --name demo",
description: "Launch headless OpenCode on the default ports",
},
{
command: "opencode-drive start --visible",
description: "Launch visible OpenCode on the default ports",
},
{
command: "opencode-drive start --name demo --script ./drive.ts",
description: "Launch headless OpenCode and run a script",
},
]),
)
const sendCommand = Command.make("send", { name }, (config) =>
execute(() => send(toSendOptions(Option.getOrUndefined(config.name), extracted.commands, extracted.app))),
).pipe(
Command.withDescription("Send UI commands to OpenCode on the default port"),
Command.withExamples([
{
command: 'opencode-drive send --command.ui.type \'{"text":"hello"}\' --command.ui.state',
description: "Execute an ordered UI command batch",
},
]),
)
const restartCommand = Command.make("restart", { name }, (config) =>
execute(() => restart(Option.getOrUndefined(config.name))),
).pipe(Command.withDescription("Restart a named OpenCode instance and rerun its script"))
const stopCommand = Command.make("stop", { name }, (config) =>
execute(() => stop(Option.getOrUndefined(config.name))),
).pipe(Command.withDescription("Stop a named OpenCode instance"))
const dirCommand = Command.make("dir", { name }, (config) =>
execute(() => dir(Option.getOrUndefined(config.name))),
).pipe(Command.withDescription("Print the artifact directory for a named OpenCode instance"))
const listCommand = Command.make("list", {}, () => execute(list)).pipe(
Command.withDescription("List active OpenCode instances"),
)
const pruneCommand = Command.make(
"prune",
{
name: pruneName,
force: Flag.boolean("force").pipe(
Flag.withDescription("Delete all matching artifact directories, including active ones"),
),
},
(config) => execute(() => prune({ name: Option.getOrUndefined(config.name), force: config.force })),
).pipe(Command.withDescription("Delete artifact directories for inactive OpenCode instances"))
const root = Command.make("opencode-drive").pipe(
Command.withDescription("Drive real and simulated OpenCode instances"),
Command.withSubcommands([
initCommand,
scriptCommand,
checkCommand,
runCommand,
startCommand,
sendCommand,
listCommand,
pruneCommand,
dirCommand,
restartCommand,
stopCommand,
]),
)
Command.runWith(root, { version: packageJson.version })(extracted.args).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
)
function toStartOptions(
config: {
readonly script: Option.Option<string>
readonly name: Option.Option<string>
readonly daemon: boolean
readonly visible: boolean
readonly record: boolean
readonly dev: Option.Option<string>
},
commands: ReadonlyArray<DriveCommand>,
app: ReadonlyArray<string>,
): StartOptions {
if (commands.length > 0) throw new Error("start does not accept command flags; use send or --script")
const name = Option.getOrUndefined(config.name)
if (name === undefined && !config.visible) throw new Error("start requires --name unless --visible is passed")
const options = {
kind: "start" as const,
name: name ?? `visible-${process.pid}`,
daemon: config.daemon,
script: Option.getOrUndefined(config.script),
visible: config.visible,
record: config.record,
dev: Option.getOrUndefined(config.dev),
command: app,
}
if (options.dev !== undefined && app.length > 0) throw new Error("--dev cannot be combined with a command after --")
return options
}
function toRunModule(module: string, commands: ReadonlyArray<DriveCommand>, app: ReadonlyArray<string>) {
if (commands.length > 0) throw new Error("run does not accept command flags")
if (app.length > 0) throw new Error("run does not accept arguments after --")
return module
}
function toSendOptions(
name: string | undefined,
commands: ReadonlyArray<DriveCommand>,
app: ReadonlyArray<string>,
): SendOptions {
if (app.length > 0) throw new Error("send does not accept a command after --")
return { kind: "send", name, commands }
}
function execute(task: () => Promise<void>) {
return executeEffect(Effect.tryPromise({ try: task, catch: (error) => error }))
}
function executeEffect<R>(task: Effect.Effect<void, unknown, R>) {
return task.pipe(
Effect.catch((error) =>
Effect.sync(() => {
logError(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}),
),
)
}
function extract() {
try {
return extractCommands(process.argv.slice(2))
} catch (error) {
logError(error instanceof Error ? error.message : String(error))
return process.exit(1)
}
}
+10
View File
@@ -0,0 +1,10 @@
import { initializeInstance } from "../instance/instance.js"
import { initializeManifest } from "../instance/registry.js"
import { configureLogFile, logSuccess } from "../log.js"
export async function init(name: string) {
const manifest = await initializeManifest(name, process.cwd(), () => initializeInstance(name))
configureLogFile(manifest.artifacts)
logSuccess(`initialized ${name}`)
console.log(manifest.artifacts)
}
+6
View File
@@ -0,0 +1,6 @@
import { listManifests, manifestPath } from "../instance/registry.js"
export async function list() {
const instances = await listManifests()
console.log(instances.map((instance) => `${instance.name}: ${manifestPath(instance.name)}`).join("\n"))
}
+72
View File
@@ -0,0 +1,72 @@
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as Scope from "effect/Scope"
import * as Stream from "effect/Stream"
import type { Backend } from "../client/protocol.js"
import { logError } from "../log.js"
import * as SimulationConnector from "../simulation/connector.js"
import { generateResponse } from "./response-generator.js"
import type { createResponseSettings } from "./response-generator.js"
const connectTimeout = 30_000
export async function connectMockBackend(endpoint: string, responses: ReturnType<typeof createResponseSettings>) {
const scope = await Effect.runPromise(Scope.make())
const connect = Effect.gen(function* () {
const backend = yield* SimulationConnector.backend(endpoint, {
connectTimeout,
requestTimeout: connectTimeout,
attach: false,
})
yield* backend.requests.pipe(
Stream.runForEach((request) =>
respond(backend, request, responses).pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Effect.sync(() => logError(String(cause))),
onSuccess: () => Effect.void,
}),
Effect.forkIn(scope),
),
),
Effect.forkIn(scope),
)
yield* backend.attach()
})
try {
await Effect.runPromise(connect.pipe(Scope.provide(scope)))
} catch (cause) {
await Effect.runPromise(Scope.close(scope, Exit.void))
throw cause
}
return {
close() {
Effect.runFork(Scope.close(scope, Exit.void))
},
}
}
const respond = Effect.fn("DriveCli.mockRespond")(function* (
backend: SimulationConnector.BackendConnection,
request: Backend.ProviderInvocation,
responses: ReturnType<typeof createResponseSettings>,
) {
const response = generateResponse(responses.current(), request)
for (const item of response.items) {
if (item.type !== "textDelta" && item.type !== "reasoningDelta") {
yield* backend.rpc["llm.chunk"]({ id: request.id, items: [item] })
continue
}
for (const text of splitText(item.text)) {
yield* backend.rpc["llm.chunk"]({ id: request.id, items: [{ ...item, text }] })
yield* Effect.sleep(45 + Math.floor(Math.random() * 35))
}
}
yield* backend.rpc["llm.finish"]({ id: request.id, reason: response.finish })
})
export function splitText(text: string) {
const words = text.match(/\S+\s*/g) ?? [text]
return Array.from({ length: Math.ceil(words.length / 3) }, (_, index) =>
words.slice(index * 3, index * 3 + 3).join(""),
)
}
+28
View File
@@ -0,0 +1,28 @@
import { commandAcceptsValue, isCommandName } from "./commands.js"
import type { DriveCommand } from "./types.js"
export function extractCommands(args: ReadonlyArray<string>) {
const commands: DriveCommand[] = []
const remaining: string[] = []
const separator = args.indexOf("--")
const cli = separator === -1 ? args : args.slice(0, separator)
const app = separator === -1 ? [] : args.slice(separator + 1)
for (let index = 0; index < cli.length; index++) {
const flag = cli[index]!
if (!flag.startsWith("--command.")) {
remaining.push(flag)
continue
}
const operation = flag.slice("--command.".length)
if (!isCommandName(operation)) throw new Error(`unknown drive command "${operation}"`)
const valueMode = commandAcceptsValue(operation)
const next = cli[index + 1]
const takesValue = valueMode === true || (valueMode === "optional" && next !== undefined && !next.startsWith("--"))
const value = takesValue ? cli[++index] : undefined
if (valueMode === true && (value === undefined || value.startsWith("--")))
throw new Error(`${flag} requires a value`)
commands.push({ operation, ...(value === undefined ? {} : { value }) })
}
return { args: remaining, app, commands }
}
+41
View File
@@ -0,0 +1,41 @@
import { readdir, rm } from "node:fs/promises"
import { join, resolve } from "node:path"
import { artifactDirectory } from "../instance/instance.js"
import { listManifests, validateName } from "../instance/registry.js"
export async function prune(options: { readonly name?: string; readonly force?: boolean } = {}) {
if (options.name !== undefined) validateName(options.name)
const directory = artifactDirectory()
const entries = await readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
if (isNodeError(error) && error.code === "ENOENT") return []
throw error
})
const manifests = await listManifests()
const active = new Set(manifests.map((manifest) => resolve(manifest.artifacts)))
const manifestNames = new Map(manifests.map((manifest) => [resolve(manifest.artifacts), manifest.name]))
const artifacts = entries
.filter((entry) => entry.isDirectory() && entry.name.startsWith("run-"))
.map((entry) => join(directory, entry.name))
const matched = await Promise.all(
artifacts.map(async (artifacts) => {
if (options.name === undefined) return artifacts
const storedName = await Bun.file(join(artifacts, "drive", "name"))
.text()
.then((value) => value.trim())
.catch(() => undefined)
return storedName === options.name || manifestNames.get(resolve(artifacts)) === options.name
? artifacts
: undefined
}),
)
const pruned = matched
.filter((artifacts): artifacts is string => artifacts !== undefined)
.filter((artifacts) => options.force || !active.has(resolve(artifacts)))
await Promise.all(pruned.map((artifacts) => rm(artifacts, { recursive: true, force: true })))
console.log(pruned.length)
}
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error
}
@@ -0,0 +1,302 @@
import { Backend } from "../client/protocol.js"
import type { JsonValue } from "../project.js"
export const responseTypes = ["text", "reasoning", "tool", "diff"] as const
export type ResponseType = (typeof responseTypes)[number]
export interface ResponseConfiguration {
readonly types: ReadonlyArray<ResponseType>
readonly tools: ReadonlyArray<string>
}
export interface ResponseUpdate {
readonly types?: ReadonlyArray<string>
readonly tools?: ReadonlyArray<string>
}
const textResponses = [
"I took a careful look at the problem and followed it through the parts of the system that actually shape the behavior. The result is simpler than it first appeared: one clear boundary, one owner, and fewer opportunities for state to drift. There is a quiet satisfaction in watching the pieces settle into place.",
"The important path is working now, and the surrounding behavior remains intact. I kept the change focused, made the failure case visible, and checked the point where control passes from one process to another. It is a small adjustment, but it lets a little more daylight into the design.",
"I traced the request from its first input to its final effect and found the useful seam in between. The implementation now says what it means without asking the reader to remember hidden state. Nothing dramatic happened, which is often the nicest possible ending for this kind of work.",
"The pieces fit together cleanly after the change. Inputs are handled where they arrive, ownership stays explicit, and cleanup follows the same path every time. The code feels calmer now, like a room after someone has opened a window and put the books back in order.",
"I checked the current behavior, made the narrow change, and followed it through the edge cases that mattered. The result is direct enough to explain and ordinary enough to trust. Somewhere in the background, the event loop continues its patient little orbit.",
]
const reasoningResponses = [
"I should inspect the available context before choosing the smallest reliable path through this.",
"I need to preserve the working behavior while checking the boundary where ownership changes hands.",
"The request contains enough information to proceed, though the assumptions deserve one careful pass first.",
"I will separate the observed behavior from the implementation detail, then test the seam between them.",
"The safest approach is to validate the current state, make one deliberate change, and follow its effects.",
]
export function createResponseSettings() {
let configuration: ResponseConfiguration = {
types: ["text", "reasoning", "diff", "tool"],
tools: ["write", "apply_patch"],
}
return {
current: () => configuration,
update(input: ResponseUpdate) {
const updated = {
types: input.types ? parseTypes(input.types) : configuration.types,
tools: input.tools ? parseTools(input.tools) : configuration.tools,
}
if (
updated.types.includes("diff") &&
!updated.tools.includes("*") &&
!updated.tools.some((tool) => diffTools.has(tool))
)
throw new Error("diff responses require apply_patch, write, or edit in --tools")
configuration = updated
return configuration
},
}
}
export function generateResponse(
configuration: ResponseConfiguration,
request: Backend.ProviderInvocation,
): {
readonly items: ReadonlyArray<Backend.Item>
readonly finish: Backend.FinishReason
} {
if (hasToolResult(request.body)) return textResponse()
const tools = offeredTools(request.body).filter(
(tool) => configuration.tools.includes("*") || configuration.tools.includes(tool.name),
)
const available = configuration.types.filter(
(type) =>
(type !== "tool" || tools.length > 0) && (type !== "diff" || tools.some((tool) => diffTools.has(tool.name))),
)
const type = pick(available)
if (type === "reasoning")
return {
items: [
{ type: "reasoningDelta", text: pick(reasoningResponses) },
{ type: "textDelta", text: pick(textResponses) },
],
finish: "stop",
}
if (type === "tool") return toolResponse(tools.slice(0, 3), false)
if (type === "diff")
return toolResponse(
[
["apply_patch", "write", "edit"]
.map((name) => tools.find((tool) => tool.name === name))
.find((tool) => tool !== undefined)!,
],
true,
)
if (type === "text") return textResponse()
return {
items: [
{
type: "textDelta",
text: "No configured response type matched the tools offered by this request.",
},
],
finish: "stop",
}
}
function textResponse() {
return {
items: [{ type: "textDelta" as const, text: pick(textResponses) }],
finish: "stop" as const,
}
}
interface ToolDefinition {
readonly name: string
readonly parameters: unknown
}
const diffTools = new Set(["apply_patch", "edit", "write"])
let gardenExpanded = false
function toolResponse(tools: ReadonlyArray<ToolDefinition>, diff: boolean) {
return {
items: tools.map((tool, index) => ({
type: "toolCall" as const,
index,
id: `call_${crypto.randomUUID().replaceAll("-", "").slice(0, 16)}`,
name: tool.name,
input: toolInput(tool, diff),
})),
finish: "tool-calls" as const,
}
}
function offeredTools(body: unknown) {
if (!isRecord(body) || !Array.isArray(body.tools)) return []
return body.tools.flatMap((value): ToolDefinition[] => {
if (!isRecord(value)) return []
const definition = isRecord(value.function) ? value.function : value
if (typeof definition.name !== "string") return []
return [
{
name: definition.name,
parameters: definition.parameters ?? definition.inputSchema,
},
]
})
}
function toolInput(tool: ToolDefinition, diff: boolean) {
const generated = schemaValue(tool.parameters, "input")
const input = isJsonRecord(generated) ? generated : {}
const known = knownInput(tool.name, diff)
if (!isRecord(tool.parameters) || !isRecord(tool.parameters.properties)) return { ...input, ...known }
const properties = tool.parameters.properties
return {
...input,
...Object.fromEntries(
Object.entries(known).filter(([key, value]) => key in properties && acceptsValue(properties[key], value)),
),
}
}
function knownInput(name: string, diff: boolean): Record<string, JsonValue> {
const suffix = crypto.randomUUID().slice(0, 8)
if (name === "apply_patch")
return {
patchText: gardenPatch(),
}
if (name === "write")
return {
path: "src/garden.js",
filePath: "src/garden.js",
content:
'export function greet(name, punctuation = "!") {\n const visitor = name.trim() || "traveler"\n return `Hello, ${visitor}${punctuation}`\n}\n',
}
if (name === "edit")
return {
path: ".opencode/opencode.jsonc",
filePath: ".opencode/opencode.jsonc",
oldString: '"name": "Simulation"',
newString: `"name": "Simulation ${suffix}"`,
}
if (name === "read")
return { path: ".opencode/opencode.jsonc", filePath: ".opencode/opencode.jsonc", offset: 1, limit: 120 }
if (name === "glob") return { pattern: "**/*", path: ".", limit: 20 }
if (name === "grep") return { pattern: "simulation", path: ".opencode", include: "*.jsonc", limit: 20 }
if (name === "shell" || name === "bash")
return { command: diff ? "git diff --stat" : "pwd", description: "Inspect the workspace" }
return {}
}
function gardenPatch() {
const patch = gardenExpanded
? '*** Begin Patch\n*** Update File: src/garden.js\n@@\n-export function greet(name, punctuation = "!") {\n- const visitor = name.trim() || "traveler"\n- return `Hello, ${visitor}${punctuation}`\n+export function greet(name) {\n+ return `Hello, ${name}.`\n }\n*** End Patch'
: '*** Begin Patch\n*** Update File: src/garden.js\n@@\n-export function greet(name) {\n- return `Hello, ${name}.`\n+export function greet(name, punctuation = "!") {\n+ const visitor = name.trim() || "traveler"\n+ return `Hello, ${visitor}${punctuation}`\n }\n*** End Patch'
gardenExpanded = !gardenExpanded
return patch
}
function schemaValue(schema: unknown, key: string, root: unknown = schema): JsonValue {
if (!isRecord(schema)) return {}
if (typeof schema.$ref === "string" && schema.$ref.startsWith("#/$defs/")) {
const name = schema.$ref.slice("#/$defs/".length)
if (isRecord(root) && isRecord(root.$defs)) return schemaValue(root.$defs[name], key, root)
}
if ("const" in schema && isJson(schema.const)) return schema.const
if (Array.isArray(schema.enum) && schema.enum.length > 0 && isJson(schema.enum[0])) return schema.enum[0]
const alternative = Array.isArray(schema.anyOf)
? schema.anyOf[0]
: Array.isArray(schema.oneOf)
? schema.oneOf[0]
: undefined
if (alternative !== undefined) return schemaValue(alternative, key, root)
if (Array.isArray(schema.allOf) && schema.allOf.length > 0 && schema.type === undefined)
return schemaValue(schema.allOf[0], key, root)
if (schema.type === "object" || isRecord(schema.properties)) {
const properties = isRecord(schema.properties) ? schema.properties : {}
const required = Array.isArray(schema.required)
? schema.required.filter((value): value is string => typeof value === "string")
: []
return Object.fromEntries(required.map((name) => [name, schemaValue(properties[name], name, root)]))
}
if (schema.type === "array") {
const count = typeof schema.minItems === "number" ? Math.max(1, schema.minItems) : 1
return Array.from({ length: count }, () => schemaValue(schema.items, key, root))
}
if (schema.type === "boolean") return false
if (schema.type === "integer" || schema.type === "number") {
if (typeof schema.minimum === "number") return schema.minimum
if (typeof schema.exclusiveMinimum === "number") return schema.exclusiveMinimum + 1
return 1
}
if (schema.type === "null") return null
if (key.toLowerCase().includes("path")) return "."
if (key.toLowerCase().includes("pattern")) return "TODO"
if (key.toLowerCase().includes("command")) return "pwd"
if (key.toLowerCase().includes("content")) return "Generated by the simulated model."
const value = "sample"
return typeof schema.minLength === "number" ? value.padEnd(schema.minLength, "x") : value
}
function hasToolResult(body: unknown) {
if (!isRecord(body) || !Array.isArray(body.messages)) return false
const message = body.messages.at(-1)
if (!isRecord(message)) return false
if (message.role === "tool") return true
if (!Array.isArray(message.content)) return false
return message.content.some((part) => isRecord(part) && (part.type === "tool-result" || part.type === "tool"))
}
function acceptsValue(schema: unknown, value: JsonValue) {
if (!isRecord(schema)) return true
if (Array.isArray(schema.enum) && !schema.enum.some((item) => item === value)) return false
if (schema.type === "string") return typeof value === "string"
if (schema.type === "number" || schema.type === "integer") return typeof value === "number"
if (schema.type === "boolean") return typeof value === "boolean"
if (schema.type === "array") return Array.isArray(value)
if (schema.type === "object") return isJsonRecord(value)
return true
}
function parseTypes(values: ReadonlyArray<string>) {
const types = unique(values)
if (types.length === 0) throw new Error("responses requires at least one type")
const valid = types.filter(isResponseType)
const unknown = types.filter((value) => !isResponseType(value))
if (unknown.length > 0) throw new Error(`unknown response types: ${unknown.join(", ")}`)
return valid
}
function parseTools(values: ReadonlyArray<string>) {
const tools = unique(values)
if (tools.length === 0) throw new Error("responses requires at least one tool or *")
if (tools.some((tool) => tool !== "*" && !/^[a-zA-Z0-9_.:-]+$/.test(tool)))
throw new Error("tool names may contain only letters, numbers, dots, underscores, colons, or dashes")
return tools
}
function unique(values: ReadonlyArray<string>) {
return [...new Set(values.map((value) => value.trim()).filter(Boolean))]
}
function pick<T>(values: ReadonlyArray<T>) {
return values[Math.floor(Math.random() * values.length)]!
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
function isJsonRecord(value: JsonValue): value is { readonly [key: string]: JsonValue } {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
function isJson(value: unknown): value is JsonValue {
if (value === null) return true
if (["boolean", "number", "string"].includes(typeof value)) return true
if (Array.isArray(value)) return value.every(isJson)
if (!isRecord(value)) return false
return Object.values(value).every(isJson)
}
function isResponseType(value: string): value is ResponseType {
return responseTypes.some((type) => type === value)
}
+11
View File
@@ -0,0 +1,11 @@
import { request } from "../instance/control.js"
import { resolveInstance } from "../instance/registry.js"
import { configureLogFile, logSuccess } from "../log.js"
export async function restart(name?: string) {
const manifest = await resolveInstance(name)
configureLogFile(manifest.artifacts)
logSuccess(`restarting ${manifest.name}`)
const recording = await request(manifest.control, "restart")
console.log(recording ?? "success")
}
+31
View File
@@ -0,0 +1,31 @@
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join, resolve } from "node:path"
import * as Effect from "effect/Effect"
import * as Process from "../instance/process.js"
import { prepareProgram } from "../script/tooling.js"
export const runProgram = Effect.fn("Cli.runProgram")((file: string) =>
Effect.acquireUseRelease(
Effect.tryPromise({
try: () => mkdtemp(join(tmpdir(), "opencode-drive-run-")),
catch: (cause) => cause,
}),
(artifacts) =>
Effect.gen(function* () {
const runner = yield* Effect.tryPromise({
try: () => prepareProgram(artifacts, resolve(file)),
catch: (cause) => cause,
})
const result = yield* Process.run([process.execPath, runner], {
extendEnv: true,
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
})
if (result.status !== 0) return yield* Effect.fail(new Error(`program exited with status ${result.status}`))
return undefined
}),
(artifacts) => Effect.promise(() => rm(artifacts, { recursive: true, force: true })),
),
)
+44
View File
@@ -0,0 +1,44 @@
import { mkdir, open, rm } from "node:fs/promises"
import { dirname, resolve } from "node:path"
import { logSuccess } from "../log.js"
const template = `import { defineScript, Effect, Llm } from "opencode-drive"
export default defineScript({
project: {
files: {
"src/example.ts": "export const value = 1\\n",
},
},
run: ({ ui, llm }) =>
Effect.gen(function* () {
yield* llm.queue(Llm.text("The value is 1."))
yield* ui.submit("Read src/example.ts")
yield* ui.waitFor("The value is 1.")
yield* ui.screenshot("result")
}),
})
`
export async function initScript(path: string) {
const file = resolve(path)
await mkdir(dirname(file), { recursive: true })
const handle = await open(file, "wx").catch((error: unknown) => {
if (isAlreadyExists(error)) throw new Error(`script already exists: ${file}`, { cause: error })
throw error
})
try {
await handle.writeFile(template)
} catch (error) {
await handle.close().catch(() => undefined)
await rm(file, { force: true })
throw error
}
await handle.close()
logSuccess("created script")
console.log(file)
}
function isAlreadyExists(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error && error.code === "EEXIST"
}
+199
View File
@@ -0,0 +1,199 @@
import { join, resolve } from "node:path"
import { pathToFileURL } from "node:url"
import * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import * as Schema from "effect/Schema"
import * as OpenCodeDriver from "../driver/index.js"
import type * as OpenCodeTui from "../driver/client.js"
import * as OpenCodeUi from "../driver/ui.js"
import * as PreparedDriver from "../driver/prepared.js"
import type * as OpenCodeInstance from "../instance/runtime.js"
import { createScriptFileSystem } from "../script/filesystem.js"
import { hasGitMetadata } from "../script/project.js"
import { Names as ToolNames } from "../tool/types.js"
import type { AutomaticScriptDefinition, ScriptDefinition } from "../script/types.js"
export const loadScript = Effect.fn("DriveCli.loadScript")((file: string) =>
Effect.tryPromise({
try: async () => {
const module: unknown = await import(pathToFileURL(resolve(file)).href)
return isRecord(module) ? { default: module.default } : {}
},
catch: (cause) => cause,
}).pipe(
Effect.flatMap((module) =>
isScriptDefinition(module.default)
? Effect.succeed(module.default)
: Effect.fail(new Error("script must default-export defineScript(...)")),
),
),
)
export const runScript = Effect.fn("DriveCli.runScript")(function* (
script: ScriptDefinition,
instance: OpenCodeInstance.Instance,
onScreenshot?: (path: string) => void,
onRecording?: (path: string) => void,
onReady?: () => void,
) {
const prepared = yield* PreparedDriver.make(instance, {
visible: instance.visible,
launch: "launch" in script ? "manual" : "automatic",
tuiName: "default",
tui: script.tui,
})
const protectGit = yield* Effect.promise(() => hasGitMetadata(join(instance.artifacts, "files")))
const operationFailure = yield* Deferred.make<never, unknown>()
const runUi = <A, E>(effect: Effect.Effect<A, E>) =>
effect.pipe(
Effect.tapError((cause) =>
cause instanceof OpenCodeDriver.UiTimeoutError
? Deferred.fail(operationFailure, cause).pipe(Effect.asVoid)
: Effect.void,
),
)
const recordings = new Set<string>()
const reportRecording = (path: string) => {
if (recordings.has(path)) return
recordings.add(path)
onRecording?.(path)
}
const adaptUi = (ui: OpenCodeUi.Ui): OpenCodeUi.Ui => {
const transformed = OpenCodeUi.transform(ui, runUi)
return {
...transformed,
screenshot: (name) =>
transformed.screenshot(name).pipe(Effect.tap((path) => Effect.sync(() => onScreenshot?.(path)))),
}
}
const adaptTui = (tui: OpenCodeTui.Tui): OpenCodeTui.Tui => {
const recording = tui.recording
return {
ui: adaptUi(tui.ui),
close: tui.close,
...(recording === undefined
? {}
: {
recording: {
path: recording.path,
timeline: recording.timeline,
finish: () =>
runUi(recording.finish()).pipe(Effect.tap((path) => Effect.sync(() => reportRecording(path)))),
},
}),
}
}
const tuiOptions = (options?: OpenCodeTui.TuiOptions) => ({
...("launch" in script ? script.tui : undefined),
...options,
})
function launchTui(options?: OpenCodeTui.TuiOptions): ReturnType<OpenCodeTui.Tuis["launch"]>
function launchTui(name: string, options?: OpenCodeTui.TuiOptions): ReturnType<OpenCodeTui.Tuis["launch"]>
function launchTui(nameOrOptions?: string | OpenCodeTui.TuiOptions, options?: OpenCodeTui.TuiOptions) {
const launched =
typeof nameOrOptions === "string"
? prepared.tuis.launch(nameOrOptions, tuiOptions(options))
: prepared.tuis.launch(tuiOptions(nameOrOptions))
return launched.pipe(
Effect.tap(() => Effect.sync(() => onReady?.())),
Effect.map(adaptTui),
)
}
const tuis: OpenCodeTui.Tuis = { launch: launchTui }
const context = {
fs: createScriptFileSystem(join(instance.artifacts, "files"), {
git: protectGit,
}),
tuis,
server: {
launch: prepared.server.launch,
kill: prepared.server.kill,
},
llm: prepared.llm,
tools: prepared.tools,
artifacts: instance.artifacts,
}
const primaryTui = prepared.primary
const automatic = (definition: AutomaticScriptDefinition) => {
if (primaryTui === undefined || prepared.driver === undefined)
return Effect.fail(new Error("automatic script did not launch its primary TUI"))
const tui = adaptTui(primaryTui)
return definition.run({
...context,
opencode: prepared.driver.opencode,
tui,
ui: tui.ui,
})
}
const execution = "launch" in script ? script.run({ ...context, tui: null, ui: null }) : automatic(script)
if (!Effect.isEffect(execution)) return yield* Effect.fail(new Error("script run must return an Effect"))
if (primaryTui !== undefined) onReady?.()
yield* Effect.raceAllFirst([
execution,
Deferred.await(operationFailure),
prepared.failure.pipe(Effect.catchIf(isZeroStatusTuiExit, () => Effect.void)),
])
const report = yield* prepared.settle()
for (const path of report.recordings) reportRecording(path)
return undefined
})
function isZeroStatusTuiExit(cause: unknown) {
return (
cause instanceof OpenCodeDriver.OpenCodeDriverError &&
cause.operation === "tui.exit" &&
cause.message.endsWith("status 0")
)
}
function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
function isScriptDefinition(value: unknown): value is ScriptDefinition {
if (!isRecord(value)) return false
return (
value.kind === "opencode-drive/script" &&
typeof value.run === "function" &&
(value.project === undefined || isScriptProject(value.project)) &&
(value.config === undefined || isJsonObject(value.config)) &&
(value.tuiConfig === undefined || isJsonObject(value.tuiConfig)) &&
(value.setup === undefined || typeof value.setup === "function") &&
(value.tools === undefined || isToolConfiguration(value.tools)) &&
(value.tui === undefined || isTuiOptions(value.tui)) &&
(!("launch" in value) || value.launch === "manual")
)
}
function isToolConfiguration(value: unknown) {
return typeof value === "function" || Schema.is(ToolNames)(value)
}
function isTuiOptions(value: unknown) {
if (!isRecord(value)) return false
if (value.recording !== undefined && typeof value.recording !== "boolean") return false
if (value.viewport === undefined) return true
if (!isRecord(value.viewport)) return false
return (
typeof value.viewport.cols === "number" &&
Number.isFinite(value.viewport.cols) &&
typeof value.viewport.rows === "number" &&
Number.isFinite(value.viewport.rows)
)
}
function isJsonObject(value: unknown) {
if (!isRecord(value)) return false
const prototype = Object.getPrototypeOf(value)
return prototype === Object.prototype || prototype === null
}
function isScriptProject(value: unknown) {
if (!isRecord(value)) return false
if (value.git !== undefined && typeof value.git !== "boolean") return false
if (value.files === undefined) return true
if (!isRecord(value.files)) return false
const prototype = Object.getPrototypeOf(value.files)
if (prototype !== Object.prototype && prototype !== null) return false
return Object.values(value.files).every((contents) => typeof contents === "string" || contents instanceof Uint8Array)
}
+39
View File
@@ -0,0 +1,39 @@
import { executeCommands } from "./commands.js"
import type { SendOptions } from "./types.js"
import { defaultPort } from "../client/index.js"
import { resolveInstance, resolveVisibleInstance } from "../instance/registry.js"
import { configureLogFile } from "../log.js"
export async function send(options: SendOptions) {
if (options.commands.length === 0) throw new Error("send requires at least one --command.ui.* flag")
const result = await executeCommands(await resolveSendEndpoint(options.name), options.commands)
if (
options.commands.length === 1 &&
["ui.screenshot", "ui.matches", "ui.recording.finish"].includes(options.commands[0]?.operation ?? "")
) {
console.log(result.results[0]?.result)
return
}
if (
options.commands.length === 1 &&
["ui.state", "ui.snapshot", "ui.capture"].includes(options.commands[0]?.operation ?? "")
) {
console.log(JSON.stringify(result.results[0]?.result, undefined, 2))
return
}
console.log("success")
}
export async function resolveSendEndpoint(name?: string) {
if (name) {
const manifest = await resolveInstance(name)
configureLogFile(manifest.artifacts)
return manifest.endpoints.ui
}
const manifest = await resolveVisibleInstance()
if (manifest) {
configureLogFile(manifest.artifacts)
return manifest.endpoints.ui
}
return `ws://127.0.0.1:${defaultPort}`
}
+485
View File
@@ -0,0 +1,485 @@
import * as Effect from "effect/Effect"
import * as Cause from "effect/Cause"
import * as Exit from "effect/Exit"
import { toStringUnknown } from "effect/Inspectable"
import { initializeInstance } from "../instance/instance.js"
import * as DriveProcess from "../instance/process.js"
import * as OpenCodeInstance from "../instance/runtime.js"
import { mkdir, rm } from "node:fs/promises"
import { join } from "node:path"
import * as SimulationConnector from "../simulation/connector.js"
import { connectMockBackend } from "./mock-backend.js"
import { createResponseSettings } from "./response-generator.js"
import { loadScript, runScript } from "./script.js"
import type { ScriptDefinition } from "../script/types.js"
import { prepareScriptModule } from "../script/tooling.js"
import { finalizeRecording } from "../recording/finalize.js"
import { listenControl } from "../instance/control.js"
import { configureLogFile, logError, logReadyPaths, logSuccess } from "../log.js"
import {
controlPath,
markReady,
markStarting,
initializeManifest,
register,
registryDirectory,
resolveInstance,
unregister,
} from "../instance/registry.js"
import type { StartOptions } from "./types.js"
export const start = Effect.fn("DriveCli.start")((options: StartOptions) => Effect.scoped(startScoped(options)))
const startScoped = Effect.fn("DriveCli.startScoped")(function* (options: StartOptions) {
const initializerPid = Number.parseInt(options.daemon ? (process.env.OPENCODE_DRIVE_INITIALIZER_PID ?? "") : "", 10)
if (options.daemon) delete process.env.OPENCODE_DRIVE_INITIALIZER_PID
const initialized = yield* fromPromise(() =>
initializeManifest(options.name, process.cwd(), () => initializeInstance(options.name), {
temporary: true,
...(Number.isInteger(initializerPid) && initializerPid > 0 ? { adoptPid: initializerPid } : {}),
}),
)
configureLogFile(initialized.artifacts)
logSuccess(`starting ${options.name}`)
logSuccess(`using artifacts ${initialized.artifacts}`)
if (!options.visible && !options.script && !options.daemon)
return yield* startDetached(options, initialized.artifacts)
const scriptPath = options.script
const scriptModule = scriptPath
? yield* fromPromise(async () => {
logSuccess(`preparing script ${scriptPath}`)
return prepareScriptModule(initialized.artifacts, scriptPath)
})
: undefined
const script = scriptModule
? yield* loadScript(scriptModule).pipe(
Effect.tap(() => Effect.sync(() => logSuccess(`loading script ${scriptModule}`))),
)
: undefined
if (script && "launch" in script && options.record) {
return yield* Effect.fail(new Error("--record is not supported when launch is manual"))
}
const responses = createResponseSettings()
logSuccess("launching instance")
const log = options.visible ? (message: string) => logSuccess(message, { terminal: false }) : logSuccess
const instance = yield* OpenCodeInstance.make({
artifacts: initialized.artifacts,
name: options.name,
command: options.command,
dev: options.dev,
scripted: options.script !== undefined,
visible: options.visible,
record: options.record,
viewport: script?.tui?.viewport,
project: script?.project,
config: script?.config,
tui: script?.tuiConfig,
setup: script?.setup,
tools: script?.tools,
log,
})
yield* Effect.acquireRelease(
fromPromise(() =>
register({
version: 1,
name: options.name,
pid: process.pid,
startedAt: new Date().toISOString(),
cwd: process.cwd(),
artifacts: instance.artifacts,
visible: options.visible,
status: "starting",
endpoints: instance.endpoints,
control: controlPath(options.name),
}),
),
() => fromPromise(() => unregister(options.name, process.pid)).pipe(Effect.ignore),
)
return yield* lifecycle(options, instance, responses, script, log)
})
function lifecycle(
options: StartOptions,
instance: OpenCodeInstance.Instance,
responses: ReturnType<typeof createResponseSettings>,
script: ScriptDefinition | undefined,
log: (message: string) => void,
) {
return Effect.callback<void, unknown>((resume) => {
const abort = new AbortController()
const promise = runLifecycle(options, instance, responses, script, log, abort.signal)
void promise.then(
() => resume(Effect.void),
(error) => resume(Effect.fail(error)),
)
return Effect.gen(function* () {
abort.abort(new Error("opencode-drive interrupted"))
yield* Effect.promise(() => promise.catch(() => undefined))
})
})
}
async function runLifecycle(
options: StartOptions,
instance: OpenCodeInstance.Instance,
responses: ReturnType<typeof createResponseSettings>,
script: ScriptDefinition | undefined,
log: (message: string) => void,
signal: AbortSignal,
) {
let completed = false
let current: ReturnType<typeof run> | undefined
let restarting: Promise<string | undefined> | undefined
let stopping = false
const screenshots: string[] = []
const recordings: string[] = []
let driveReady = false
let recording: Promise<string | undefined> | undefined
const finishCurrentRecording = (onProgress?: (percent: number) => void) => {
if (!options.record || options.visible || !driveReady || options.script !== undefined)
return Promise.resolve(undefined)
recording ??= finishRecording(instance, onProgress)
return recording
}
const interrupt = () => {
stopping = true
current?.abort.abort(signal.reason)
if (!options.script) void stopInstance().catch((error) => logError(`failed to stop interrupted instance: ${error}`))
}
signal.addEventListener("abort", interrupt, { once: true })
const stopInstance = async (onProgress?: (percent: number) => void) => {
try {
const output = await finishCurrentRecording(onProgress)
return {
...(output ? { recording: output } : {}),
screenshots: [...screenshots],
}
} finally {
stopping = true
current?.abort.abort(new Error("opencode-drive stopped"))
await runEffect(instance.stop)
}
}
const completeScript = async () => {
completed = true
const result = await stopInstance()
for (const screenshot of result.screenshots) console.log(screenshot)
}
let closeControl: (() => Promise<void>) | undefined
let failure: unknown
try {
closeControl = await listenControl(controlPath(options.name), {
restart: () => {
if (restarting) return restarting
restarting = (async () => {
await markStarting(options.name, process.pid)
const output = await finishCurrentRecording()
const previous = current
const restartReason = new Error("script restarted")
previous?.abort.abort(restartReason)
await previous?.promise
driveReady = false
await runEffect(instance.restart)
recording = undefined
current = run(
options,
instance,
responses,
script,
(path) => screenshots.push(path),
(path) => recordings.push(path),
log,
)
await current.ready
driveReady = true
await markReady(options.name, process.pid)
await logReadyPaths(instance.artifacts, {
terminal: !options.visible,
})
return output
})().finally(() => {
restarting = undefined
})
return restarting
},
stop: stopInstance,
responses: async (input) => {
if (options.script) throw new Error("responses are unavailable when --script owns the simulation backend")
return responses.update(input)
},
})
if (signal.aborted) return
current = run(
options,
instance,
responses,
script,
(path) => screenshots.push(path),
(path) => recordings.push(path),
log,
)
await current.ready
driveReady = true
log(`ready ${options.name}`)
await markReady(options.name, process.pid)
await logReadyPaths(instance.artifacts, { terminal: !options.visible })
if (options.visible) {
while (true) {
const active: NonNullable<typeof current> = current
let result: { readonly script: true } | { readonly script: false; readonly status: number }
try {
result = options.script
? await Promise.race([
active.promise.then(() => ({ script: true as const })),
runEffect(instance.wait).then((status) => ({ script: false as const, status })),
])
: { script: false as const, status: await runEffect(instance.wait) }
} catch (error) {
if (stopping) return
if (restarting || active !== current) {
await restarting
continue
}
throw error
}
if (restarting || active !== current) {
await restarting
continue
}
if (result.script) {
await completeScript()
}
const status = result.script ? await runEffect(instance.wait) : result.status
if (status !== 0 && !stopping) process.exitCode = status
return
}
}
while (true) {
const active: NonNullable<typeof current> = current
try {
await active.promise
} catch (error) {
if (stopping) break
if (restarting || active !== current) {
await restarting
continue
}
throw error
}
if (stopping) break
if (restarting) {
await restarting
continue
}
if (active !== current) continue
if (options.script) {
await completeScript()
break
}
completed = true
break
}
} catch (error) {
failure = error
throw error
} finally {
signal.removeEventListener("abort", interrupt)
current?.abort.abort(new Error("opencode-drive stopped"))
let cleanupFailure: unknown
const recordingPath = await finishCurrentRecording().catch((error) => {
logError(`failed to export recording: ${error}`)
return undefined
})
await closeControl?.().catch((error) => {
cleanupFailure ??= error
logError(`failed to close control socket: ${error}`)
})
await runEffect(instance.stop).catch((error) => {
cleanupFailure ??= error
logError(`failed to stop OpenCode: ${error}`)
})
await unregister(options.name, process.pid).catch((error) => {
cleanupFailure ??= error
logError(`failed to unregister ${options.name}: ${error}`)
})
if (options.script && !options.visible) report(completed ? "completed" : undefined)
if (options.script && recordingPath) logSuccess(`recording ${recordingPath}`)
if (options.script) for (const output of recordings) logSuccess(`recording ${output}`)
if (shouldCleanArtifacts(options.script, completed, failure, cleanupFailure))
await rm(instance.artifacts, { recursive: true, force: true }).catch((error) => {
cleanupFailure ??= error
logError(`failed to clean artifacts ${instance.artifacts}: ${error}`)
})
if (options.script && failure !== undefined) {
logError(failure instanceof Error ? failure.message : toStringUnknown(failure))
process.exit(1)
}
if (failure === undefined && cleanupFailure !== undefined) process.exitCode = 1
}
}
function shouldCleanArtifacts(
script: string | undefined,
completed: boolean,
failure: unknown,
cleanupFailure: unknown,
) {
return (
script !== undefined &&
completed &&
failure === undefined &&
cleanupFailure === undefined &&
(process.exitCode === undefined || process.exitCode === 0) &&
process.env.OPENCODE_DRIVE_KEEP_ARTIFACTS !== "1"
)
}
async function finishRecording(instance: OpenCodeInstance.Instance, onProgress?: (percent: number) => void) {
const expected = await runEffect(instance.recording)
if (!expected) throw new Error("recording was not enabled for this instance")
let timeline: string
const process = await runEffect(instance.primary)
if (!(await runEffect(process.isRunning))) {
timeline = expected.timeline
} else {
timeline = await runEffect(
Effect.scoped(
SimulationConnector.ui(instance.endpoints.ui, {
connectTimeout: 60_000,
}).pipe(
Effect.flatMap((connection) => connection.rpc["ui.recording.finish"]()),
Effect.timeoutOrElse({
duration: 60_000,
orElse: () => Effect.fail(new Error("ui.recording.finish timed out")),
}),
),
),
)
}
return finalizeRecording(timeline, expected, { onProgress })
}
const startDetached = Effect.fn("DriveCli.startDetached")(function* (options: StartOptions, artifacts: string) {
const ownerLog = join(registryDirectory(), `${options.name}.log`)
yield* fromPromise(() => mkdir(registryDirectory(), { recursive: true }))
yield* fromPromise(() => rm(ownerLog, { force: true }))
logSuccess(`launching detached owner for ${options.name}`)
const child = yield* DriveProcess.spawn(
[
process.execPath,
process.argv[1]!,
"start",
"--daemon",
"--name",
options.name,
...(options.script ? ["--script", options.script] : []),
...(options.dev ? ["--dev", options.dev] : []),
...(options.record ? ["--record"] : []),
...(options.command.length ? ["--", ...options.command] : []),
],
{
cwd: process.cwd(),
env: {
...process.env,
OPENCODE_DRIVE_LOG: configureLogFile(artifacts),
OPENCODE_DRIVE_OWNER_LOG: ownerLog,
OPENCODE_DRIVE_INITIALIZER_PID: String(process.pid),
},
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
detached: true,
},
)
logSuccess(`waiting for ${options.name} to become ready`)
const deadline = Date.now() + 60_000
while (Date.now() < deadline) {
const manifest = yield* fromPromise(() => resolveInstance(options.name).catch(() => undefined))
if (manifest?.pid === child.pid) {
logSuccess(`ready ${options.name}`)
yield* fromPromise(() => logReadyPaths(manifest.artifacts))
yield* child.detach
return
}
if (!(yield* child.isRunning)) {
const status = yield* child.exitCode
yield* Effect.fail(new Error(`detached instance exited with status ${status}; see ${ownerLog}`))
}
yield* Effect.sleep(50)
}
yield* child.terminate
yield* Effect.fail(new Error(`timed out starting drive instance "${options.name}"; see ${ownerLog}`))
})
function run(
options: StartOptions,
instance: OpenCodeInstance.Instance,
responses: ReturnType<typeof createResponseSettings>,
driveScript: ScriptDefinition | undefined,
onScreenshot: (path: string) => void,
onRecording: (path: string) => void,
log: (message: string) => void,
) {
const abort = new AbortController()
const readiness = Promise.withResolvers<void>()
let markedReady = false
const ready = () => {
if (markedReady) return
markedReady = true
readiness.resolve()
}
const promise = (async () => {
if (!driveScript) {
log("waiting for OpenCode")
await runEffect(instance.waitForDrive("both"))
log("OpenCode ready")
}
if (driveScript) {
log("running script")
const exit = await Effect.runPromiseExit(
Effect.scoped(runScript(driveScript, instance, onScreenshot, onRecording, ready)),
{ signal: abort.signal },
)
if (Exit.isFailure(exit)) {
if (abort.signal.aborted && Cause.hasInterruptsOnly(exit.cause)) return
throw Cause.squash(exit.cause)
}
ready()
log("script completed")
return
}
const child = await runEffect(instance.primary)
const mock = await connectMockBackend(instance.endpoints.backend, responses)
ready()
abort.signal.addEventListener("abort", () => mock.close(), {
once: true,
})
const status = await Promise.race([
runEffect(child.exitCode),
new Promise<number>((resolve) =>
abort.signal.addEventListener("abort", () => resolve(0), {
once: true,
}),
),
])
mock.close()
if (status !== 0 && !abort.signal.aborted) process.exitCode = status
})().catch((error) => {
if (!markedReady) readiness.reject(error)
throw error
})
void promise.catch(() => undefined)
return {
abort,
ready: readiness.promise,
promise,
}
}
const runEffect = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect)
const fromPromise = <A>(task: () => Promise<A>) => Effect.tryPromise({ try: task, catch: (error) => error })
function report(status?: string) {
if (status) logSuccess(status)
}
+38
View File
@@ -0,0 +1,38 @@
import { rm } from "node:fs/promises"
import { basename, dirname, resolve } from "node:path"
import { artifactDirectory } from "../instance/instance.js"
import { requestStop } from "../instance/control.js"
import { manifestPath, resolveInstance } from "../instance/registry.js"
import { configureLogFile, logSuccess } from "../log.js"
export async function stop(name?: string) {
const manifest = await resolveInstance(name)
configureLogFile(manifest.artifacts)
const result = await requestStop(manifest.control, (percent) => {
logSuccess(`Rendering video: ${percent}%`)
})
const deadline = Date.now() + 5 * 60_000
while (Date.now() < deadline) {
const current: unknown = await Bun.file(manifestPath(manifest.name))
.json()
.catch(() => undefined)
if (typeof current !== "object" || current === null || !("pid" in current) || current.pid !== manifest.pid) {
for (const screenshot of result.screenshots) console.log(screenshot)
if (result.recording) {
logSuccess(`Video successfully created: ${result.recording}`)
} else if (result.screenshots.length === 0) {
console.log("success")
}
await pruneArtifacts(manifest.artifacts)
return
}
await Bun.sleep(25)
}
throw new Error(`timed out stopping drive instance "${manifest.name}"`)
}
async function pruneArtifacts(artifacts: string) {
const directory = resolve(artifacts)
if (dirname(directory) !== artifactDirectory() || !/^run-[^/\\]+$/.test(basename(directory))) return
await rm(directory, { recursive: true, force: true })
}
+25
View File
@@ -0,0 +1,25 @@
import type { Frontend } from "../client/index.js"
export interface DriveCommand {
readonly operation: Exclude<Frontend.Capability, "ui.click.semantic">
readonly value?: string
}
export interface StartOptions {
readonly kind: "start"
readonly name: string
readonly daemon: boolean
readonly script?: string
readonly visible: boolean
readonly record: boolean
readonly dev?: string
readonly command: ReadonlyArray<string>
}
export interface SendOptions {
readonly kind: "send"
readonly name?: string
readonly commands: ReadonlyArray<DriveCommand>
}
export type CliOptions = StartOptions | SendOptions
+11
View File
@@ -0,0 +1,11 @@
import type { Backend } from "./protocol.js"
/** Default port of the OpenCode UI simulation server. */
export const defaultPort = 40900
/** Default port of the OpenCode backend (LLM) simulation server. */
export const defaultBackendPort = 40950
export { Backend, Frontend, Handshake, JsonRpc, SimulationProtocol } from "./protocol.js"
export type BackendFinishReason = Backend.FinishReason
export type BackendItem = Backend.Item
export type OpenedExchange = Backend.ProviderInvocation
+4
View File
@@ -0,0 +1,4 @@
import { Backend, Frontend, Handshake, JsonRpc } from "@opencode-ai/protocol/simulation"
export { Backend, Frontend, Handshake, JsonRpc }
export const SimulationProtocol = { Backend, Frontend, Handshake, JsonRpc }
+277
View File
@@ -0,0 +1,277 @@
import * as Cause from "effect/Cause"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as Ref from "effect/Ref"
import * as Semaphore from "effect/Semaphore"
import * as Scope from "effect/Scope"
import * as Deferred from "effect/Deferred"
import type * as OpenCodeInstance from "../instance/runtime.js"
import type * as SimulationConnector from "../simulation/connector.js"
import type { Frontend } from "../client/protocol.js"
import { finalizeRecording } from "../recording/finalize.js"
import { error, type OpenCodeDriverError } from "./error.js"
import * as OpenCodeUi from "./ui.js"
import * as SharedEffect from "./shared.js"
export interface TuiOptions {
readonly recording?: boolean
readonly viewport?: Frontend.ResizeParams
}
export interface Tui {
readonly ui: OpenCodeUi.Ui
readonly recording?: Recording
readonly close: () => Effect.Effect<void>
}
export interface Recording {
readonly path: string
readonly timeline: string
readonly finish: () => Effect.Effect<string, OpenCodeDriverError | OpenCodeUi.OperationError>
}
interface ManagedTui extends Tui {
readonly compatibility: SimulationConnector.EndpointCompatibility
readonly _exitCode: Effect.Effect<number, OpenCodeDriverError>
readonly _recording?: {
readonly finishTimeline: Effect.Effect<string, OpenCodeDriverError | OpenCodeUi.OperationError>
readonly exportRecording: Effect.Effect<string, OpenCodeDriverError | OpenCodeUi.OperationError>
}
}
export const make = Effect.fn("OpenCodeTui.make")(function* (
instance: OpenCodeInstance.Instance,
visible: boolean,
identity: string,
options: TuiOptions,
connector: SimulationConnector.Interface,
compatibility?: SimulationConnector.CompatibilityPolicy,
) {
if (visible && options.recording)
return yield* Effect.fail(error("tui.launch", "recording requires a headless OpenCode TUI"))
const launched = yield* Effect.acquireRelease(
instance
.launchTui(identity, {
record: options.recording,
viewport: options.viewport,
})
.pipe(Effect.mapError((cause) => error("tui.launch", cause))),
(client) => client.close.pipe(Effect.catchCause((cause) => Effect.logError("OpenCode TUI cleanup failed", cause))),
)
const connection = yield* connector.ui(launched.endpoint, { compatibility })
const ui = OpenCodeUi.make(connection)
yield* ui.waitFor((state) => state.focused.editor, {
timeout: 30_000,
interval: 50,
})
const recording = launched.recording
let managedRecording: ManagedTui["_recording"]
if (recording !== undefined) {
const finishTimeline = yield* SharedEffect.make(
Effect.gen(function* () {
const timeline = yield* ui.finishRecording()
if (timeline !== recording.timeline)
return yield* Effect.fail(
error("recording.finish", `OpenCode returned an unexpected recording path: ${timeline}`),
)
return timeline
}),
)
const exportFinishedRecording = yield* SharedEffect.make(
Effect.flatMap(finishTimeline, (timeline) =>
Effect.tryPromise({
try: (signal) => finalizeRecording(timeline, recording, { signal }),
catch: (cause) => error("recording.export", cause),
}),
),
)
managedRecording = {
finishTimeline,
exportRecording: exportFinishedRecording,
}
yield* Effect.addFinalizer(() =>
finishTimeline.pipe(
Effect.asVoid,
Effect.catchCause((cause) => Effect.logError("OpenCode TUI recording finalization failed", cause)),
),
)
}
return {
ui,
compatibility: connection.compatibility,
close: () => Effect.void,
_exitCode: launched.process.exitCode.pipe(Effect.mapError((cause) => error("tui.exit", cause))),
...(recording === undefined || managedRecording === undefined
? {}
: {
recording: {
path: recording.video,
timeline: recording.timeline,
finish: () => managedRecording.exportRecording,
},
_recording: managedRecording,
}),
} satisfies ManagedTui
})
export interface Tuis {
readonly launch: {
(options?: TuiOptions): Effect.Effect<Tui, TuiLaunchError>
/** Launches a named TUI. The name is released when that TUI closes. */
(name: string, options?: TuiOptions): Effect.Effect<Tui, TuiLaunchError>
}
}
export type TuiLaunchError =
| OpenCodeDriverError
| SimulationConnector.SimulationCompatibilityError
| OpenCodeUi.OperationError
| OpenCodeUi.UiPredicateError
| OpenCodeUi.UiWaitOptionsError
export interface UnexpectedExit {
readonly name: string
readonly status: number
}
export interface Control extends Tuis {
readonly compatibility: Effect.Effect<ReadonlyArray<SimulationConnector.EndpointCompatibility>>
readonly unexpectedExit: Effect.Effect<UnexpectedExit>
readonly settle: () => Effect.Effect<ReadonlyArray<string>, OpenCodeDriverError | OpenCodeUi.OperationError>
}
export const makeTuis = Effect.fn("OpenCodeTuis.make")(function* (
instance: OpenCodeInstance.Instance,
visible: boolean,
connector: SimulationConnector.Interface,
compatibilityPolicy?: SimulationConnector.CompatibilityPolicy,
) {
const parentScope = yield* Scope.Scope
const tuisScope = yield* Scope.fork(parentScope, "parallel")
const lock = yield* Semaphore.make(1)
let closed = false
let recordings: ReadonlyArray<NonNullable<ManagedTui["_recording"]>> = []
const nextIdentity = yield* Ref.make(0)
let active: ReadonlyMap<string, Scope.Scope> = new Map()
const unexpectedExit = yield* Deferred.make<UnexpectedExit>()
let compatibility: ReadonlyArray<SimulationConnector.EndpointCompatibility> = []
const launchNamed = Effect.fn("OpenCodeTuis.launchNamed")(function* (identity: string, options: TuiOptions = {}) {
return yield* lock.withPermit(
Effect.gen(function* () {
if (closed) return yield* Effect.fail(error("tui.launch", "OpenCode TUIs are closed"))
if (active.has(identity))
return yield* Effect.fail(error("tui.launch", `TUI "${identity}" is already connected`))
const scope = yield* Scope.fork(tuisScope)
active = new Map(active).set(identity, scope)
const client = yield* make(instance, visible, identity, options, connector, compatibilityPolicy).pipe(
Scope.provide(scope),
Effect.onError(() =>
Effect.sync(() => {
const next = new Map(active)
next.delete(identity)
active = next
}).pipe(Effect.andThen(Scope.close(scope, Exit.void))),
),
)
compatibility = [...compatibility, client.compatibility]
const recording = client._recording
if (recording !== undefined) recordings = [...recordings, recording]
const claim = lock.withPermit(
Effect.sync(() => {
if (active.get(identity) !== scope) return false
const next = new Map(active)
next.delete(identity)
active = next
return true
}),
)
const release = claim.pipe(Effect.flatMap((owned) => (owned ? Scope.close(scope, Exit.void) : Effect.void)))
yield* client._exitCode.pipe(
Effect.flatMap((status) =>
claim.pipe(
Effect.flatMap((owned) =>
owned
? Deferred.succeed(unexpectedExit, {
name: identity,
status,
}).pipe(Effect.andThen(Scope.close(scope, Exit.void)))
: Effect.void,
),
),
),
Effect.catchCause(() => Effect.void),
Effect.forkIn(tuisScope),
)
const publicTui: Tui = {
ui: client.ui,
...(client.recording === undefined ? {} : { recording: client.recording }),
close: () => release,
}
return publicTui
}),
)
})
function launch(options?: TuiOptions): Effect.Effect<Tui, TuiLaunchError>
function launch(name: string, options?: TuiOptions): Effect.Effect<Tui, TuiLaunchError>
function launch(nameOrOptions: string | TuiOptions = {}, options: TuiOptions = {}) {
return typeof nameOrOptions === "string"
? launchNamed(nameOrOptions, options)
: Ref.getAndUpdate(nextIdentity, (value) => value + 1).pipe(
Effect.flatMap((identity) => launchNamed(String(identity), nameOrOptions)),
)
}
const finishTimelines = yield* SharedEffect.make(
Effect.gen(function* () {
const active = yield* lock.withPermit(
Effect.sync(() => {
closed = true
return recordings
}),
)
const finished = yield* Effect.forEach(active, (recording) => Effect.exit(recording.finishTimeline), {
concurrency: "unbounded",
})
yield* Scope.close(tuisScope, Exit.void)
return { active, finished }
}),
)
const settle = Effect.fn("OpenCodeTuis.settle")(function* () {
const { active, finished } = yield* finishTimelines
const exported = yield* Effect.forEach(
active,
(recording, index) =>
Exit.isSuccess(finished[index]!)
? Effect.exit(recording.exportRecording).pipe(
Effect.map(
(result): Exit.Exit<string | undefined, OpenCodeDriverError | OpenCodeUi.OperationError> => result,
),
)
: Effect.succeed(Exit.succeed<string | undefined>(undefined)),
{
concurrency: 2,
},
)
let failure: Cause.Cause<OpenCodeDriverError | OpenCodeUi.OperationError> | undefined
for (const result of [...finished, ...exported]) {
if (!Exit.isFailure(result)) continue
failure = failure === undefined ? result.cause : Cause.combine(failure, result.cause)
}
if (failure !== undefined) return yield* Effect.failCause(failure)
return exported.flatMap((result) => (Exit.isSuccess(result) && result.value !== undefined ? [result.value] : []))
})
return {
launch,
unexpectedExit: Deferred.await(unexpectedExit),
compatibility: Effect.sync(() => compatibility),
settle,
} satisfies Control
})
export * as OpenCodeTui from "./client.js"
+14
View File
@@ -0,0 +1,14 @@
import * as Schema from "effect/Schema"
export class OpenCodeDriverError extends Schema.TaggedErrorClass<OpenCodeDriverError>()("OpenCodeDriverError", {
operation: Schema.String,
message: Schema.String,
}) {}
export const error = (operation: string, cause: unknown) =>
cause instanceof OpenCodeDriverError
? cause
: new OpenCodeDriverError({
operation,
message: cause instanceof Error ? cause.message : String(cause),
})
+151
View File
@@ -0,0 +1,151 @@
import * as Effect from "effect/Effect"
import * as Cause from "effect/Cause"
import * as Exit from "effect/Exit"
import * as Layer from "effect/Layer"
import type * as Scope from "effect/Scope"
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as OpenCodeInstance from "../instance/runtime.js"
import * as SimulationConnector from "../simulation/connector.js"
import type { OpenCodeConfig, OpenCodeTuiConfig, Project, Setup } from "../project.js"
import * as OpenCodeTui from "./client.js"
import type * as OpenCodeSdk from "./opencode.js"
import { error, type OpenCodeDriverError } from "./error.js"
import type { LlmControllerError, LlmSettlementError } from "./llm-controller.js"
import * as OpenCodeProject from "./project.js"
import * as PreparedDriver from "./prepared.js"
import * as OpenCodeServer from "./server.js"
import type * as OpenCodeUi from "./ui.js"
import type { Llm } from "./llm.js"
import type { RunReport } from "./report.js"
import * as ToolController from "../tool/controller.js"
import type * as Tool from "../tool/index.js"
export interface Options {
readonly project?: Project
readonly config?: OpenCodeConfig
readonly tuiConfig?: OpenCodeTuiConfig
readonly setup?: Setup
readonly tools?: Tool.Configuration
readonly tui?: OpenCodeTui.TuiOptions
readonly opencode?: OpenCodeServer.Target
readonly keepArtifacts?: boolean
}
export interface Driver {
/** Generated SDK client connected to this driver's private OpenCode service. */
readonly opencode: OpenCodeSdk.OpenCode
readonly tui: OpenCodeTui.Tui
/** Convenience alias for the primary TUI's UI. */
readonly ui: OpenCodeUi.Ui
readonly llm: Llm
/** Runtime controls for tools declared by name in the driver options. */
readonly tools: Tool.Controls
readonly tuis: OpenCodeTui.Tuis
readonly artifacts: string
/** Validates queued LLM work, stops TUIs, and exports recordings. */
readonly settle: () => Effect.Effect<
RunReport,
LlmControllerError | LlmSettlementError | OpenCodeDriverError | OpenCodeUi.OperationError
>
}
const makeWithServices = Effect.fn("OpenCodeDriver.makeWithServices")(function* (options: Options = {}) {
const toolController = yield* ToolController.make(options.tools)
const project = yield* OpenCodeProject.make({
project: options.project,
config: options.config,
tui: options.tuiConfig,
setup: ToolController.composeSetup(toolController, options.setup),
keepArtifacts: options.keepArtifacts,
})
const instance = yield* OpenCodeInstance.make(
{
artifacts: project.artifacts,
name: `library-${crypto.randomUUID().slice(0, 12)}`,
scripted: true,
command: options.opencode?.command,
dev: options.opencode?.dev,
env: options.opencode?.env,
visible: options.opencode?.visible,
},
toolController,
).pipe(Effect.mapError((cause) => error("server.prepare", cause)))
const prepared = yield* PreparedDriver.makeWithServices(instance, {
visible: options.opencode?.visible,
tui: options.tui,
artifactsRetained: options.keepArtifacts ?? false,
compatibility: options.opencode?.compatibility,
})
if (prepared.driver === undefined) return yield* Effect.die(new Error("automatic driver did not launch a TUI"))
return { driver: prepared.driver, failure: prepared.failure }
})
type MakeWithServices = ReturnType<typeof makeWithServices>
const layer = Layer.merge(SimulationConnector.layer, NodeServices.layer)
const makeManaged = (
options: Options = {},
): Effect.Effect<Effect.Success<MakeWithServices>, Effect.Error<MakeWithServices>, Scope.Scope> =>
makeWithServices(options).pipe(Effect.provide(layer))
export const make = (options: Options = {}) => makeManaged(options).pipe(Effect.map(({ driver }) => driver))
type Program<A, E, R> = (driver: Driver) => Effect.Effect<A, E, R>
const runReport = <A, E, R>(options: Options, f: Program<A, E, R>) =>
Effect.scoped(
Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
const { driver, failure } = yield* makeManaged(options)
const useExit = yield* Effect.exit(restore(Effect.raceFirst(f(driver), failure)))
const settlement = yield* Effect.exit(driver.settle())
if (Exit.isFailure(useExit) && Exit.isFailure(settlement))
return yield* Effect.failCause(Cause.combine(useExit.cause, settlement.cause))
if (Exit.isFailure(useExit)) return yield* Effect.failCause(useExit.cause)
if (Exit.isFailure(settlement)) return yield* Effect.failCause(settlement.cause)
return { value: useExit.value, report: settlement.value }
}),
),
)
export function useReport<A, E, R>(f: Program<A, E, R>): ReturnType<typeof runReport<A, E, R>>
export function useReport<A, E, R>(options: Options, f: Program<A, E, R>): ReturnType<typeof runReport<A, E, R>>
export function useReport<A, E, R>(optionsOrProgram: Options | Program<A, E, R>, program?: Program<A, E, R>) {
if (typeof optionsOrProgram === "function") return runReport({}, optionsOrProgram)
if (program === undefined) return Effect.die(new Error("OpenCodeDriver.useReport requires a program"))
return runReport(optionsOrProgram, program)
}
const run = <A, E, R>(options: Options, program: Program<A, E, R>) =>
runReport(options, program).pipe(Effect.map(({ value }) => value))
export function use<A, E, R>(f: Program<A, E, R>): ReturnType<typeof run<A, E, R>>
export function use<A, E, R>(options: Options, f: Program<A, E, R>): ReturnType<typeof run<A, E, R>>
export function use<A, E, R>(optionsOrProgram: Options | Program<A, E, R>, program?: Program<A, E, R>) {
return typeof optionsOrProgram === "function"
? run({}, optionsOrProgram)
: program === undefined
? Effect.die(new Error("OpenCodeDriver.use requires a program"))
: run(optionsOrProgram, program)
}
export { OpenCodeDriverError } from "./error.js"
export { LlmControllerError, LlmModeError, LlmSettlementError } from "./llm-controller.js"
export {
UiCapabilityError,
UiElementAmbiguousError,
UiNodeAmbiguousError,
UiPredicateError,
UiTimeoutError,
UiWaitOptionsError,
} from "./ui.js"
export { SimulationRequestError } from "@opencode-ai/protocol/simulation"
export { SimulationCompatibilityError, SimulationConnectionError } from "../simulation/connector.js"
export type { CompatibilityPolicy, EndpointCompatibility } from "../simulation/connector.js"
export type { Recording, Tui, TuiLaunchError, TuiOptions, Tuis } from "./client.js"
export type { Llm } from "./llm.js"
export type { Target as OpenCodeTarget } from "./server.js"
export type { OpenCode } from "./opencode.js"
export type { Ui } from "./ui.js"
export type { Project, ProjectFileSystem, Setup, SetupContext } from "../project.js"
export * from "./report.js"
+409
View File
@@ -0,0 +1,409 @@
import type * as Cause from "effect/Cause"
import * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as FiberSet from "effect/FiberSet"
import * as Queue from "effect/Queue"
import * as Ref from "effect/Ref"
import * as Schema from "effect/Schema"
import * as Scope from "effect/Scope"
import * as Semaphore from "effect/Semaphore"
import * as Stream from "effect/Stream"
import * as Llm from "../llm/index.js"
import { isTitleRequest } from "../llm/internal.js"
import type { BackendConnection } from "../simulation/connector.js"
import { causeError, controllerError, LlmControllerError, LlmSettlementError } from "./llm-errors.js"
import * as LlmResponder from "./llm-responder.js"
import * as LlmState from "./llm-state.js"
/**
* The concurrency shell of the LLM controller. Decision logic lives in the
* pure `llm-state.ts` module; wire streaming lives in `llm-responder.ts`.
* This module owns the lock, the state ref, job fibers, and deferreds.
*/
export { LlmControllerError, LlmModeError, LlmSettlementError } from "./llm-errors.js"
export type { Response } from "./llm-responder.js"
export type { ServeHandler, TitleHandler } from "./llm-state.js"
export interface Options {
/** Per-backend-RPC timeout in milliseconds. Defaults to 30,000. */
readonly requestTimeout?: number
/** Time allowed for queued and active responses to settle. Defaults to 30,000. */
readonly settlementTimeout?: number
}
export interface Controller {
/** Attaches one backend generation while preserving response state. */
readonly attach: (backend: BackendConnection) => Effect.Effect<Attachment, LlmControllerError>
readonly queue: (...output: ReadonlyArray<Llm.Output>) => Effect.Effect<void, LlmState.RejectionError>
readonly send: (...output: ReadonlyArray<Llm.Output>) => Effect.Effect<void, LlmState.RejectionError>
readonly serve: (handler: LlmState.ServeHandler) => Effect.Effect<void, LlmState.RejectionError>
readonly title: (handler: LlmState.TitleHandler) => Effect.Effect<void, LlmState.RejectionError>
readonly settle: () => Effect.Effect<void, LlmControllerError | LlmSettlementError>
/** Interrupts request routing and response workers. Used by the driver coordinator. */
readonly shutdown: () => Effect.Effect<void>
/** Fails when request routing or the backend connection fails. */
readonly failure: Effect.Effect<never, LlmControllerError>
}
export interface Attachment {
readonly detach: () => Effect.Effect<void>
}
/** A committed normal job: its selection plus the shell-owned completion. */
interface NormalJob extends LlmState.NormalStart {
readonly completion: LlmState.Completion
}
const NonNegativeMilliseconds = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))
const decodeOutputs = Schema.decodeUnknownEffect(Schema.Array(Llm.Output))
export const make = Effect.fn("LlmController.make")(function* (
backendOrOptions?: BackendConnection | Options,
explicitOptions?: Options,
) {
const initialBackend = isBackendConnection(backendOrOptions) ? backendOrOptions : undefined
const options = isBackendConnection(backendOrOptions) ? explicitOptions : backendOrOptions
const requestTimeout = NonNegativeMilliseconds.make(options?.requestTimeout ?? 30_000)
const settlementTimeout = NonNegativeMilliseconds.make(options?.settlementTimeout ?? 30_000)
const responder = LlmResponder.make({ requestTimeout })
const state = yield* Ref.make(LlmState.initial)
const lock = yield* Semaphore.make(1)
const changes = yield* Queue.sliding<void>(1)
const failureSignal = yield* Deferred.make<never, LlmControllerError>()
const tasks = yield* FiberSet.make<void, never>()
const parentScope = yield* Scope.Scope
const attached = yield* Ref.make<{ readonly backend: BackendConnection; readonly scope: Scope.Scope } | undefined>(
undefined,
)
yield* Effect.addFinalizer(() => Queue.shutdown(changes))
const notify = Queue.offer(changes, undefined).pipe(Effect.asVoid)
const respondTo = (request: LlmState.AttachedRequest, output: LlmResponder.Response) =>
responder.respond(request.backend, request.request.id, output)
const failCompletions = (completions: ReadonlyArray<LlmState.Completion>, error: LlmControllerError) =>
Effect.forEach(completions, (completion) => Deferred.fail(completion, error), { discard: true })
/** Must run while holding the lock. */
const recordFailureLocked = Effect.fn("LlmController.recordFailureLocked")(function* (error: LlmControllerError) {
const current = yield* Ref.get(state)
const [next, { failure, isFirst }] = LlmState.recordFailure(current, error)
yield* Ref.set(state, next)
if (isFirst) yield* Deferred.fail(failureSignal, failure)
yield* failCompletions(current.sendCompletions, failure)
yield* notify
return failure
})
const completeNormal = Effect.fn("LlmController.completeNormal")(function* (
job: NormalJob,
error?: LlmControllerError,
) {
const sendCompletion = LlmState.NormalSource.$is("Queued")(job.source) ? job.source.response.completed : undefined
yield* lock.withPermit(
Effect.gen(function* () {
yield* Ref.update(state, (current) => LlmState.finishNormal(current, job.completion, sendCompletion))
if (error === undefined) {
yield* Deferred.succeed(job.completion, undefined)
if (sendCompletion !== undefined) yield* Deferred.succeed(sendCompletion, undefined)
} else {
yield* Deferred.fail(job.completion, error)
if (sendCompletion !== undefined) yield* Deferred.fail(sendCompletion, error)
yield* recordFailureLocked(error)
}
yield* notify
}),
)
})
const runNormal = (job: NormalJob): Effect.Effect<void> => {
const output = LlmState.NormalSource.$match(job.source, {
Queued: ({ response }) => respondTo(job.request, Stream.fromIterable(response.output)),
Served: ({ handler }) => Effect.suspend(() => respondTo(job.request, handler(job.request.request, job.index))),
})
return Effect.matchCauseEffect(output, {
onFailure: (cause) => completeNormal(job, causeError("respond", cause, job.request.request.id)),
onSuccess: () => completeNormal(job),
})
}
/** Starts every runnable normal job. Must run while holding the lock. */
const drainLocked = Effect.fn("LlmController.drainLocked")(function* () {
while (true) {
const current = yield* Ref.get(state)
const start = LlmState.nextNormal(current)
if (start === undefined) return
const completion = yield* Deferred.make<void, LlmControllerError>()
yield* Ref.set(state, LlmState.startNormal(current, start, completion))
yield* FiberSet.run(tasks, runNormal({ ...start, completion }))
yield* notify
}
})
const completeTitle = Effect.fn("LlmController.completeTitle")(function* (
completion: LlmState.Completion,
error?: LlmControllerError,
) {
yield* lock.withPermit(
Effect.gen(function* () {
yield* Ref.update(state, (current) => LlmState.finishTitle(current, completion))
if (error === undefined) yield* Deferred.succeed(completion, undefined)
else {
yield* Deferred.fail(completion, error)
yield* recordFailureLocked(error)
}
yield* notify
}),
)
})
/** Titles respond after in-flight normal jobs, outside request sequencing. */
const startTitleLocked = Effect.fn("LlmController.startTitleLocked")(function* (request: LlmState.AttachedRequest) {
const completion = yield* Deferred.make<void, LlmControllerError>()
const current = yield* Ref.get(state)
const [next, title] = LlmState.startTitle(current, completion)
yield* Ref.set(state, next)
const respond = Effect.gen(function* () {
yield* Effect.forEach(title.awaiting, Deferred.await, { discard: true })
const text = yield* Effect.suspend(() => title.handler(request.request, title.index))
yield* respondTo(request, Stream.make(Llm.text(text)))
})
yield* FiberSet.run(
tasks,
Effect.matchCauseEffect(respond, {
onFailure: (cause) => completeTitle(completion, causeError("title", cause, request.request.id)),
onSuccess: () => completeTitle(completion),
}),
)
yield* notify
})
const routeRequest = (request: LlmState.AttachedRequest) =>
lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (current.failure !== undefined || current.settled) return
if (isTitleRequest(request.request.body)) {
yield* startTitleLocked(request)
return
}
yield* Ref.set(state, LlmState.pushRequest(current, request))
yield* drainLocked()
yield* notify
}),
)
const recordRouterFailure = (cause: Cause.Cause<Schema.SchemaError>) =>
lock.withPermit(recordFailureLocked(causeError("route requests", cause))).pipe(Effect.asVoid)
const attach = Effect.fn("LlmController.attach")(function* (backend: BackendConnection) {
const scope = yield* lock.withPermit(
Effect.gen(function* () {
if ((yield* Ref.get(attached)) !== undefined)
return yield* Effect.fail(controllerError("attach", "LLM backend is already attached"))
const scope = yield* Scope.fork(parentScope)
yield* Ref.set(attached, { backend, scope })
return scope
}),
)
yield* backend.requests.pipe(
Stream.runForEach((request) => routeRequest({ request, backend })),
Effect.matchCauseEffect({
onFailure: recordRouterFailure,
onSuccess: () => Effect.void,
}),
Effect.forkIn(scope),
)
yield* backend.closed.pipe(
Effect.andThen(
lock.withPermit(
Effect.gen(function* () {
const active = yield* Ref.get(attached)
if (active?.backend !== backend) return
const current = yield* Ref.get(state)
if (current.settled) return
yield* recordFailureLocked(controllerError("backend", "backend connection closed"))
}),
),
),
Effect.forkIn(scope),
)
const detach = Effect.fn("LlmController.detach")(function* () {
const shouldClose = yield* lock.withPermit(
Effect.gen(function* () {
const active = yield* Ref.get(attached)
if (active?.backend !== backend) return false
yield* Ref.set(attached, undefined)
return true
}),
)
if (shouldClose) yield* Scope.close(scope, Exit.void)
})
return { detach } satisfies Attachment
})
const enqueue = Effect.fn("LlmController.enqueue")(function* (
operation: "queue" | "send",
output: ReadonlyArray<Llm.Output>,
completed?: LlmState.Completion,
) {
const decoded = yield* decodeOutputs(output).pipe(Effect.mapError((cause) => controllerError(operation, cause)))
yield* lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
const rejection = LlmState.rejectEnqueue(current, operation)
if (rejection !== undefined) return yield* Effect.fail(rejection)
yield* Ref.set(state, LlmState.enqueue(current, { output: decoded, completed }))
yield* drainLocked()
yield* notify
return undefined
}),
)
})
const queue = Effect.fn("LlmController.queue")((...output: ReadonlyArray<Llm.Output>) => enqueue("queue", output))
const send = Effect.fn("LlmController.send")(function* (...output: ReadonlyArray<Llm.Output>) {
const completed = yield* Deferred.make<void, LlmControllerError>()
yield* enqueue("send", output, completed)
yield* Deferred.await(completed).pipe(
Effect.onInterrupt(() =>
lock.withPermit(
Effect.gen(function* () {
yield* Ref.update(state, (current) => LlmState.abandonSend(current, completed))
yield* notify
}),
),
),
)
})
const serve = Effect.fn("LlmController.serve")((handler: LlmState.ServeHandler) =>
lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
const rejection = LlmState.rejectServe(current)
if (rejection !== undefined) return yield* Effect.fail(rejection)
yield* Ref.set(state, LlmState.serve(current, handler))
yield* drainLocked()
yield* notify
return undefined
}),
),
)
const title = Effect.fn("LlmController.title")((handler: LlmState.TitleHandler) =>
lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
const rejection = LlmState.rejectTitle(current)
if (rejection !== undefined) return yield* Effect.fail(rejection)
yield* Ref.set(state, LlmState.configureTitle(current, handler))
yield* notify
return undefined
}),
),
)
const inspectSettlement = lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
const settlement = LlmState.inspectSettlement(current)
if (LlmState.Settlement.$is("Done")(settlement)) yield* Ref.set(state, LlmState.markSettled(current))
return settlement
}),
)
const awaitSettlement = (): Effect.Effect<void, LlmControllerError | LlmSettlementError> =>
Effect.suspend(() =>
Effect.flatMap(
inspectSettlement,
LlmState.Settlement.$match({
Done: () => Effect.void,
Fail: ({ error }) => Effect.fail(error),
Wait: () => Effect.andThen(Queue.take(changes), awaitSettlement()),
}),
),
)
const failSettlementTimeout = lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
const error = LlmState.settlementTimeoutError(current)
const failure = controllerError("settle", error)
yield* Ref.set(
state,
LlmState.markSettled({
...current,
failure: current.failure ?? failure,
}),
)
yield* failCompletions(current.sendCompletions, failure)
yield* notify
return error
}),
)
const settle = Effect.fn("LlmController.settle")(function* () {
yield* Effect.yieldNow
yield* lock.withPermit(
Effect.gen(function* () {
yield* Ref.update(state, LlmState.beginSettling)
yield* drainLocked()
yield* notify
}),
)
yield* awaitSettlement().pipe(
Effect.timeoutOrElse({
duration: settlementTimeout,
orElse: () => Effect.flatMap(failSettlementTimeout, Effect.fail),
}),
Effect.tapError((error) => (error instanceof LlmSettlementError ? FiberSet.clear(tasks) : Effect.void)),
)
})
const shutdown = Effect.fn("LlmController.shutdown")(function* () {
const active = yield* Ref.get(attached)
if (active !== undefined) {
yield* Ref.set(attached, undefined)
yield* Scope.close(active.scope, Exit.void)
}
yield* lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
const failure = current.failure ?? controllerError("shutdown", "LLM controller is closed")
yield* Ref.set(state, LlmState.close(current, failure))
yield* failCompletions(current.sendCompletions, failure)
yield* notify
}),
)
yield* FiberSet.clear(tasks)
})
if (initialBackend !== undefined) yield* attach(initialBackend)
return {
attach,
queue,
send,
serve,
title,
settle,
shutdown,
failure: Deferred.await(failureSignal),
} satisfies Controller
})
/** Builds a response stream from output values. */
export const response = (...output: ReadonlyArray<Llm.Output>): LlmResponder.Response => Stream.fromIterable(output)
function isBackendConnection(value: BackendConnection | Options | undefined): value is BackendConnection {
return value !== undefined && "rpc" in value
}
export * as LlmController from "./llm-controller.js"
+41
View File
@@ -0,0 +1,41 @@
import * as Cause from "effect/Cause"
import * as Option from "effect/Option"
import * as Schema from "effect/Schema"
/** Rejection of an LLM control call made in an incompatible response mode. */
export class LlmModeError extends Schema.TaggedErrorClass<LlmModeError>()("LlmModeError", {
operation: Schema.Literals(["queue", "send", "serve", "title"]),
message: Schema.String,
}) {}
/** Failure of an LLM controller operation or its backend connection. */
export class LlmControllerError extends Schema.TaggedErrorClass<LlmControllerError>()("LlmControllerError", {
operation: Schema.String,
requestId: Schema.optionalKey(Schema.String),
message: Schema.String,
}) {}
/** Settlement ended with unused responses or unexpected requests. */
export class LlmSettlementError extends Schema.TaggedErrorClass<LlmSettlementError>()("LlmSettlementError", {
unusedResponses: Schema.Number,
unexpectedRequests: Schema.Number,
message: Schema.String,
}) {}
/** Coerces any cause into an `LlmControllerError`, preserving existing ones. */
export const controllerError = (operation: string, cause: unknown, requestId?: string): LlmControllerError => {
if (cause instanceof LlmControllerError) return cause
return new LlmControllerError({
operation,
...(requestId === undefined ? {} : { requestId }),
message: cause instanceof Error ? cause.message : String(cause),
})
}
/** Extracts the most useful failure from a cause and coerces it. */
export const causeError = (operation: string, cause: Cause.Cause<unknown>, requestId?: string): LlmControllerError => {
const failure = Cause.findErrorOption(cause)
return Option.isSome(failure)
? controllerError(operation, failure.value, requestId)
: controllerError(operation, Cause.squash(cause), requestId)
}
+235
View File
@@ -0,0 +1,235 @@
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as Schema from "effect/Schema"
import * as Stream from "effect/Stream"
import * as Llm from "../llm/index.js"
import { chunkText } from "../llm/internal.js"
import { supportsCapability, type BackendConnection } from "../simulation/connector.js"
import { controllerError, LlmControllerError } from "./llm-errors.js"
/**
* The wire layer of the LLM controller: plays one `Response` stream onto a
* backend connection as `llm.chunk` / `llm.finish` / `llm.disconnect` RPCs,
* chunking text with optional pacing and guaranteeing a terminal event.
*/
/** A stream of simulated model output for one LLM exchange. */
export type Response = Stream.Stream<Llm.Output, LlmControllerError>
export interface Options {
/** Per-backend-RPC timeout in milliseconds. */
readonly requestTimeout: number
}
export interface Responder {
/** Plays one response for one exchange, guaranteeing a terminal event. */
readonly respond: (
backend: BackendConnection,
requestId: string,
output: Response,
) => Effect.Effect<void, LlmControllerError>
}
class InvocationTerminated extends Schema.TaggedErrorClass<InvocationTerminated>()("InvocationTerminated", {}) {}
const decodeOutput = Schema.decodeUnknownEffect(Llm.Output)
export const make = ({ requestTimeout }: Options): Responder => {
const call = <A, E>(
backend: BackendConnection,
operation: string,
requestId: string,
effect: Effect.Effect<A, E>,
): Effect.Effect<A, LlmControllerError | InvocationTerminated> =>
Effect.timeoutOrElse(effect, {
duration: requestTimeout,
orElse: () =>
Effect.fail(
new LlmControllerError({
operation,
requestId,
message: `${operation} timed out after ${requestTimeout}ms`,
}),
),
}).pipe(
Effect.catch((error) => classifyWriteFailure(backend, requestId, error)),
Effect.mapError((cause) =>
cause instanceof InvocationTerminated ? cause : controllerError(operation, cause, requestId),
),
)
const classifyWriteFailure = <E>(
backend: BackendConnection,
requestId: string,
error: E,
): Effect.Effect<never, E | InvocationTerminated> =>
Effect.gen(function* () {
if (!supportsCapability(backend.compatibility, "llm.pending")) return yield* Effect.fail(error)
const pending = yield* Effect.exit(backend.rpc["llm.pending"]().pipe(Effect.timeout(requestTimeout)))
if (Exit.isFailure(pending)) return yield* Effect.fail(error)
if (pending.value.invocations.some((invocation) => invocation.id === requestId)) return yield* Effect.fail(error)
return yield* Effect.fail(new InvocationTerminated())
})
const streamDelta = Effect.fn("LlmResponder.streamDelta")(function* (
backend: BackendConnection,
id: string,
type: "textDelta" | "reasoningDelta",
text: string,
options: Llm.StreamOptions | undefined,
) {
const delay = options?.delay ?? 2
const chunkSize = options?.chunkSize ?? 15
const chunks = [...chunkText(text, chunkSize)]
for (let index = 0; index < chunks.length; index++) {
const chunk = chunks[index]
if (chunk === undefined) continue
yield* call(backend, "llm.chunk", id, backend.rpc["llm.chunk"]({ id, items: [{ type, text: chunk }] }))
if (index < chunks.length - 1 && delay > 0) yield* Effect.sleep(delay)
}
})
const streamToolCall = Effect.fn("LlmResponder.streamToolCall")(function* (
backend: BackendConnection,
requestId: string,
toolCall: Llm.ToolCall,
) {
const delay = toolCall.options?.delay ?? 2
const chunkSize = toolCall.options?.chunkSize ?? 15
const chunks = [...chunkText(JSON.stringify(toolCall.input), chunkSize)]
const providerNeutral = supportsCapability(backend.compatibility, "llm.tool-input-delta")
if (providerNeutral)
yield* call(
backend,
"llm.chunk",
requestId,
backend.rpc["llm.chunk"]({
id: requestId,
items: [
{
type: "toolInputStart",
index: toolCall.index,
id: toolCall.id,
name: toolCall.name,
},
],
}),
)
for (let index = 0; index < chunks.length; index++) {
const text = chunks[index]
if (text === undefined) continue
const item = providerNeutral
? { type: "toolInputDelta" as const, index: toolCall.index, text }
: {
type: "raw" as const,
chunk: {
choices: [
{
delta: {
tool_calls: [
index === 0
? {
index: toolCall.index,
id: toolCall.id,
function: { name: toolCall.name, arguments: text },
}
: {
index: toolCall.index,
function: { arguments: text },
},
],
},
},
],
},
}
yield* call(
backend,
"llm.chunk",
requestId,
backend.rpc["llm.chunk"]({
id: requestId,
items: [item],
}),
)
if (index < chunks.length - 1 && delay > 0) yield* Effect.sleep(delay)
}
})
const respond = Effect.fn("LlmResponder.respond")(function* (
backend: BackendConnection,
requestId: string,
output: Response,
) {
let terminal = false
yield* output.pipe(
Stream.mapEffect((value) => decodeOutput(value)),
Stream.runForEach((item) => {
if (terminal)
return Effect.fail(
new LlmControllerError({
operation: "respond",
requestId,
message: `LLM response ${requestId} emitted output after its terminal event`,
}),
)
switch (item.type) {
case "finish":
terminal = true
return call(
backend,
"llm.finish",
requestId,
backend.rpc["llm.finish"]({
id: requestId,
...(item.reason === undefined ? {} : { reason: item.reason }),
}),
).pipe(Effect.asVoid)
case "disconnect":
terminal = true
return call(backend, "llm.disconnect", requestId, backend.rpc["llm.disconnect"]({ id: requestId })).pipe(
Effect.asVoid,
)
case "text":
return streamDelta(backend, requestId, "textDelta", item.text, item.options)
case "reasoning":
return streamDelta(backend, requestId, "reasoningDelta", item.text, item.options)
case "pause":
return item.milliseconds === 0 ? Effect.void : Effect.sleep(item.milliseconds)
case "toolCall": {
if (item.options !== undefined) return streamToolCall(backend, requestId, item)
const { options: _, ...toolCall } = item
return call(
backend,
"llm.chunk",
requestId,
backend.rpc["llm.chunk"]({
id: requestId,
items: [toolCall],
}),
).pipe(Effect.asVoid)
}
case "raw":
return call(
backend,
"llm.chunk",
requestId,
backend.rpc["llm.chunk"]({ id: requestId, items: [item] }),
).pipe(Effect.asVoid)
}
return Effect.void
}),
Effect.catchTag("InvocationTerminated", () => {
terminal = true
return Effect.void
}),
Effect.mapError((cause) => controllerError("respond", cause, requestId)),
)
if (!terminal)
yield* call(backend, "llm.finish", requestId, backend.rpc["llm.finish"]({ id: requestId, reason: "stop" })).pipe(
Effect.catchTag("InvocationTerminated", () => Effect.void),
)
})
return { respond }
}
+299
View File
@@ -0,0 +1,299 @@
import * as Data from "effect/Data"
import type * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import type { Backend } from "../client/protocol.js"
import type * as Llm from "../llm/index.js"
import type { BackendConnection } from "../simulation/connector.js"
import { controllerError, LlmControllerError, LlmModeError, LlmSettlementError } from "./llm-errors.js"
import type { Response } from "./llm-responder.js"
/**
* Pure state and transitions for the LLM controller. The shell in
* `llm-controller.ts` owns all concurrency: it holds the lock, creates
* completions, runs jobs, and resolves deferreds. Completions appear here
* only as opaque tokens tracked for membership — nothing in this module
* awaits or completes them.
*/
/** Opaque token for one in-flight job, resolved by the shell. */
export type Completion = Deferred.Deferred<void, LlmControllerError>
export type ServeHandler = (request: Backend.ProviderInvocation, index: number) => Response
export type TitleHandler = (
request: Backend.ProviderInvocation,
index: number,
) => Effect.Effect<string, LlmControllerError>
export interface QueuedResponse {
readonly output: ReadonlyArray<Llm.Output>
readonly completed?: Completion
}
export interface AttachedRequest {
readonly request: Backend.ProviderInvocation
readonly backend: BackendConnection
}
/** How the controller answers normal (non-title) requests. */
export type Mode = Data.TaggedEnum<{
Unset: {}
Queue: {}
Serve: { readonly handler: ServeHandler }
}>
export const Mode = Data.taggedEnum<Mode>()
export interface State {
readonly mode: Mode
readonly titleHandler: TitleHandler
readonly titleConfigured: boolean
readonly requests: ReadonlyArray<AttachedRequest>
readonly responses: ReadonlyArray<QueuedResponse>
readonly activeNormal: ReadonlyArray<Completion>
readonly activeTitles: ReadonlyArray<Completion>
readonly sendCompletions: ReadonlyArray<Completion>
readonly requestIndex: number
readonly titleIndex: number
readonly failure: LlmControllerError | undefined
readonly settling: boolean
readonly settled: boolean
}
export const initial: State = {
mode: Mode.Unset(),
titleHandler: () => Effect.succeed("OpenCode Drive"),
titleConfigured: false,
requests: [],
responses: [],
activeNormal: [],
activeTitles: [],
sendCompletions: [],
requestIndex: 0,
titleIndex: 0,
failure: undefined,
settling: false,
settled: false,
}
// ─── Guards ──────────────────────────────────────────────────────────────────
/** Why a control call (queue/send/serve/title) was rejected. */
export type RejectionError = LlmModeError | LlmControllerError
const rejectWhileSettling = (state: State, operation: string) =>
state.settling || state.settled ? controllerError(operation, "LLM controller is settling") : undefined
/** Why a queue/send call must be rejected, or undefined to proceed. */
export const rejectEnqueue = (state: State, operation: "queue" | "send"): RejectionError | undefined => {
if (state.failure !== undefined) return state.failure
if (Mode.$is("Serve")(state.mode))
return new LlmModeError({
operation,
message: `llm.${operation} cannot be used after llm.serve`,
})
return rejectWhileSettling(state, operation)
}
/** Why a serve call must be rejected, or undefined to proceed. */
export const rejectServe = (state: State): RejectionError | undefined => {
if (state.failure !== undefined) return state.failure
if (!Mode.$is("Unset")(state.mode))
return new LlmModeError({
operation: "serve",
message: "llm.serve must be the only LLM response mode",
})
return rejectWhileSettling(state, "serve")
}
/** Why a title call must be rejected, or undefined to proceed. */
export const rejectTitle = (state: State): RejectionError | undefined => {
if (state.failure !== undefined) return state.failure
if (state.titleConfigured)
return new LlmModeError({
operation: "title",
message: "llm.title may only be configured once",
})
return rejectWhileSettling(state, "title")
}
// ─── Transitions ─────────────────────────────────────────────────────────────
export const enqueue = (state: State, response: QueuedResponse): State => ({
...state,
mode: Mode.Queue(),
responses: [...state.responses, response],
sendCompletions:
response.completed === undefined ? state.sendCompletions : [...state.sendCompletions, response.completed],
})
export const serve = (state: State, handler: ServeHandler): State => ({
...state,
mode: Mode.Serve({ handler }),
})
export const configureTitle = (state: State, handler: TitleHandler): State => ({
...state,
titleConfigured: true,
titleHandler: handler,
})
export const pushRequest = (state: State, request: AttachedRequest): State => ({
...state,
requests: [...state.requests, request],
})
/** Withdraws an interrupted send before it was matched to a request. */
export const abandonSend = (state: State, completed: Completion): State => ({
...state,
responses: state.responses.filter((response) => response.completed !== completed),
sendCompletions: state.sendCompletions.filter((candidate) => candidate !== completed),
})
/** Records the first failure; later failures preserve the original. */
export const recordFailure = (
state: State,
error: LlmControllerError,
): readonly [State, { readonly failure: LlmControllerError; readonly isFirst: boolean }] => {
const failure = state.failure ?? error
const isFirst = state.failure === undefined
return [isFirst ? { ...state, failure } : state, { failure, isFirst }]
}
// ─── Normal jobs ─────────────────────────────────────────────────────────────
/** Where a normal job's response comes from. */
export type NormalSource = Data.TaggedEnum<{
Queued: { readonly response: QueuedResponse }
Served: { readonly handler: ServeHandler }
}>
export const NormalSource = Data.taggedEnum<NormalSource>()
/** A runnable normal job selected by {@link nextNormal}. */
export interface NormalStart {
readonly request: AttachedRequest
readonly index: number
readonly source: NormalSource
}
/** Selects the next runnable normal job, or undefined when nothing can run. */
export const nextNormal = (state: State): NormalStart | undefined => {
if (state.failure !== undefined) return undefined
const request = state.requests[0]
if (request === undefined) return undefined
if (Mode.$is("Serve")(state.mode))
return {
request,
index: state.requestIndex,
source: NormalSource.Served({ handler: state.mode.handler }),
}
const response = state.responses[0]
if (response === undefined) return undefined
return {
request,
index: state.requestIndex,
source: NormalSource.Queued({ response }),
}
}
/** Commits a selected job: consumes its inputs and tracks its completion. */
export const startNormal = (state: State, start: NormalStart, completion: Completion): State => ({
...state,
requests: state.requests.slice(1),
responses: NormalSource.$is("Queued")(start.source) ? state.responses.slice(1) : state.responses,
activeNormal: [...state.activeNormal, completion],
requestIndex: state.requestIndex + 1,
})
/** Untracks a finished normal job and its optional send completion. */
export const finishNormal = (state: State, completion: Completion, sendCompletion: Completion | undefined): State => ({
...state,
activeNormal: state.activeNormal.filter((active) => active !== completion),
sendCompletions:
sendCompletion === undefined
? state.sendCompletions
: state.sendCompletions.filter((active) => active !== sendCompletion),
})
// ─── Title jobs ──────────────────────────────────────────────────────────────
/** A title job selected by {@link startTitle}. */
export interface TitleStart {
readonly handler: TitleHandler
readonly index: number
/** Normal jobs the title must wait for before responding. */
readonly awaiting: ReadonlyArray<Completion>
}
/** Tracks a title job; titles run outside normal request sequencing. */
export const startTitle = (state: State, completion: Completion): readonly [State, TitleStart] => [
{
...state,
activeTitles: [...state.activeTitles, completion],
titleIndex: state.titleIndex + 1,
},
{
handler: state.titleHandler,
index: state.titleIndex,
awaiting: state.activeNormal,
},
]
export const finishTitle = (state: State, completion: Completion): State => ({
...state,
activeTitles: state.activeTitles.filter((active) => active !== completion),
})
// ─── Settlement ──────────────────────────────────────────────────────────────
export type Settlement = Data.TaggedEnum<{
/** All work has drained; the controller is settled. */
Done: {}
/** Queued or active work remains; wait for the next change. */
Wait: {}
Fail: { readonly error: LlmControllerError | LlmSettlementError }
}>
export const Settlement = Data.taggedEnum<Settlement>()
/** Decides whether settlement is complete, failed, or must keep waiting. */
export const inspectSettlement = (state: State): Settlement => {
if (state.failure !== undefined) return Settlement.Fail({ error: state.failure })
if (Mode.$is("Queue")(state.mode) && state.requests.length > 0 && state.responses.length === 0)
return Settlement.Fail({
error: new LlmSettlementError({
unusedResponses: 0,
unexpectedRequests: state.requests.length,
message: `received ${state.requests.length} unexpected LLM request(s)`,
}),
})
if (state.responses.length > 0 || state.activeNormal.length > 0 || state.activeTitles.length > 0)
return Settlement.Wait()
return Settlement.Done()
}
/** The error reported when settlement times out. */
export const settlementTimeoutError = (state: State): LlmSettlementError =>
new LlmSettlementError({
unusedResponses: state.responses.length,
unexpectedRequests: state.requests.length,
message:
state.responses.length > 0
? `timed out with ${state.responses.length} unused LLM response(s)`
: "timed out waiting for active LLM responses",
})
export const beginSettling = (state: State): State => (state.settling ? state : { ...state, settling: true })
export const markSettled = (state: State): State => ({
...state,
settled: true,
})
/** Terminal shutdown: pending work is discarded and future calls fail. */
export const close = (state: State, failure: LlmControllerError): State => ({
...state,
requests: [],
responses: [],
failure,
settling: true,
settled: true,
})
+9
View File
@@ -0,0 +1,9 @@
import type * as OpenCodeServer from "./server.js"
/** Live control over the simulated model shared by every connected TUI. */
export interface Llm {
readonly queue: OpenCodeServer.Server["llm"]["queue"]
readonly send: OpenCodeServer.Server["llm"]["send"]
readonly serve: OpenCodeServer.Server["llm"]["serve"]
readonly title: OpenCodeServer.Server["llm"]["title"]
}
+55
View File
@@ -0,0 +1,55 @@
import { join } from "node:path"
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"
import { OpenCode as OpenCodeService, type OpenCodeClient } from "@opencode-ai/client/effect"
import * as Service from "@opencode-ai/client/effect/service"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http"
import { error, type OpenCodeDriverError } from "./error.js"
export type OpenCode = OpenCodeClient
const makeWithServices = Effect.fn("OpenCode.make")(function* (artifacts: string) {
const state = join(artifacts, "home", ".local", "state", "opencode")
const fs = yield* FileSystem.FileSystem
const discovered = yield* fs.readDirectory(state).pipe(Effect.catch(() => Effect.succeed([])))
const names = [
"service-local.json",
"service.json",
...discovered
.filter((name) => /^service-[^.]+\.json$/.test(name))
.sort()
.filter((name) => name !== "service-local.json"),
]
let endpoint: Service.Endpoint | undefined
for (const name of names) {
endpoint = yield* Service.discover({ file: join(state, name) })
if (endpoint !== undefined) break
}
if (endpoint === undefined)
return yield* Effect.fail(error("opencode.connect", "OpenCode service registration was not found"))
return yield* Effect.gen(function* () {
const base = yield* HttpClient.HttpClient
const located = base.pipe(
HttpClient.mapRequest(
HttpClientRequest.setHeader("x-opencode-directory", encodeURIComponent(join(artifacts, "files"))),
),
)
const http =
endpoint.auth === undefined
? located
: located.pipe(
HttpClient.mapRequest(HttpClientRequest.basicAuth(endpoint.auth.username, endpoint.auth.password)),
)
return yield* OpenCodeService.make({ baseUrl: endpoint.url }).pipe(
Effect.provideService(HttpClient.HttpClient, http),
)
}).pipe(
Effect.provide(FetchHttpClient.layer),
Effect.mapError((cause) => error("opencode.connect", cause)),
)
})
export const make = (artifacts: string): Effect.Effect<OpenCode, OpenCodeDriverError> =>
makeWithServices(artifacts).pipe(Effect.provide(NodeFileSystem.layer))
+121
View File
@@ -0,0 +1,121 @@
import * as Cause from "effect/Cause"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as OpenCodeInstance from "../instance/runtime.js"
import * as SimulationConnector from "../simulation/connector.js"
import * as OpenCodeTui from "./client.js"
import { error, type OpenCodeDriverError } from "./error.js"
import type { Driver, Llm } from "./index.js"
import type { LlmControllerError, LlmSettlementError } from "./llm-controller.js"
import * as OpenCodeServer from "./server.js"
import * as SharedEffect from "./shared.js"
import type * as OpenCodeUi from "./ui.js"
import { decodeRunReport } from "./report.js"
export interface Options {
readonly visible?: boolean
readonly tui?: OpenCodeTui.TuiOptions
readonly launch?: "automatic" | "manual"
readonly tuiName?: string
readonly artifactsRetained?: boolean
readonly compatibility?: SimulationConnector.CompatibilityPolicy
}
export interface Prepared {
readonly driver: Driver | undefined
readonly primary: OpenCodeTui.Tui | undefined
readonly llm: Llm
readonly tools: Driver["tools"]
readonly tuis: OpenCodeTui.Tuis
readonly server: Pick<OpenCodeServer.Server, "launch" | "kill">
readonly artifacts: string
readonly settle: Driver["settle"]
readonly failure: Effect.Effect<never, LlmControllerError | OpenCodeDriverError>
readonly unexpectedTuiExit: OpenCodeTui.Control["unexpectedExit"]
}
export const makeWithServices = Effect.fn("OpenCodeDriver.makePreparedWithServices")(function* (
instance: OpenCodeInstance.Instance,
options: Options,
) {
const server = yield* OpenCodeServer.make({
instance,
target: {
visible: options.visible,
compatibility: options.compatibility,
},
})
const opencode = (options.launch ?? "automatic") === "automatic" ? yield* server.launch() : undefined
const primary =
(options.launch ?? "automatic") === "automatic"
? options.tuiName === undefined
? yield* server.tuis.launch(options.tui)
: yield* server.tuis.launch(options.tuiName, options.tui)
: undefined
const complete = (tuis: Effect.Effect<ReadonlyArray<string>, OpenCodeDriverError | OpenCodeUi.OperationError>) =>
Effect.gen(function* () {
const llm = yield* Effect.exit(server.llm.settle())
const tools = yield* Effect.exit(
server.settleTools.pipe(Effect.mapError((cause) => error("tools.settle", cause))),
)
const shutdown = yield* Effect.exit(server.llm.shutdown())
const tuiExit = yield* Effect.exit(tuis)
let failure:
| Cause.Cause<LlmControllerError | LlmSettlementError | OpenCodeDriverError | OpenCodeUi.OperationError>
| undefined
if (Exit.isFailure(llm)) failure = llm.cause
if (Exit.isFailure(tools)) failure = failure === undefined ? tools.cause : Cause.combine(failure, tools.cause)
if (Exit.isFailure(shutdown))
failure = failure === undefined ? shutdown.cause : Cause.combine(failure, shutdown.cause)
if (Exit.isFailure(tuiExit))
failure = failure === undefined ? tuiExit.cause : Cause.combine(failure, tuiExit.cause)
if (failure !== undefined) return yield* Effect.failCause(failure)
const compatibility = [...(yield* server.compatibility), ...(yield* server.tuis.compatibility)]
const recordings = Exit.isSuccess(tuiExit) ? tuiExit.value : []
const report = yield* decodeRunReport({
artifacts: instance.artifacts,
retained: options.artifactsRetained ?? true,
recordings,
compatibility,
}).pipe(Effect.mapError((cause) => error("report.make", cause)))
return report
})
const settle = yield* SharedEffect.make(complete(server.tuis.settle()))
yield* Effect.addFinalizer(() => server.llm.shutdown())
const llm: Llm = server.llm
const driver: Driver | undefined =
primary === undefined || opencode === undefined
? undefined
: {
opencode,
tui: primary,
ui: primary.ui,
llm,
tools: server.tools,
tuis: server.tuis,
artifacts: instance.artifacts,
settle: () => settle,
}
return {
driver,
primary,
llm,
tools: server.tools,
tuis: server.tuis,
server,
artifacts: instance.artifacts,
settle: () => settle,
failure: Effect.raceFirst(
server.failure,
server.tuis.unexpectedExit.pipe(
Effect.flatMap(({ name, status }) =>
Effect.fail(error("tui.exit", `OpenCode TUI "${name}" exited with status ${status}`)),
),
),
),
unexpectedTuiExit: server.tuis.unexpectedExit,
} satisfies Prepared
})
export const make = (instance: OpenCodeInstance.Instance, options: Options) =>
makeWithServices(instance, options).pipe(Effect.provide(SimulationConnector.layer))
+44
View File
@@ -0,0 +1,44 @@
import { rm } from "node:fs/promises"
import * as Effect from "effect/Effect"
import { initializeInstance, prepareInstanceProject } from "../instance/instance.js"
import type { OpenCodeConfig, OpenCodeTuiConfig, Project as ProjectDefinition, Setup } from "../project.js"
import { error } from "./error.js"
export interface Options {
readonly project?: ProjectDefinition
readonly config?: OpenCodeConfig
readonly tui?: OpenCodeTuiConfig
readonly setup?: Setup
/** Retain the isolated artifact directory after the scope closes. */
readonly keepArtifacts?: boolean
}
export interface Project {
readonly artifacts: string
}
export const make = Effect.fn("OpenCodeProject.make")(function* (options: Options = {}) {
const artifacts = yield* Effect.acquireRelease(
Effect.tryPromise({
try: () => initializeInstance(),
catch: (cause) => error("project.initialize", cause),
}),
(directory) =>
options.keepArtifacts
? Effect.void
: Effect.tryPromise({
try: () => rm(directory, { recursive: true, force: true }),
catch: () => undefined,
}).pipe(Effect.ignore),
)
yield* prepareInstanceProject({
artifacts,
project: options.project,
config: options.config,
tui: options.tui,
setup: options.setup,
}).pipe(Effect.mapError((cause) => error("project.prepare", cause)))
return { artifacts }
})
export * as OpenCodeProject from "./project.js"
+30
View File
@@ -0,0 +1,30 @@
import * as Schema from "effect/Schema"
import { EndpointCompatibility } from "../simulation/connector.js"
const absolutePathCheck = Schema.makeFilter<string>((path) => isAbsolutePath(path), {
expected: "an absolute POSIX or Windows path without NUL bytes",
})
/** A fully rooted POSIX or Windows filesystem path. */
export const AbsolutePath = Schema.String.check(absolutePathCheck).pipe(Schema.brand("OpenCodeDrive.AbsolutePath"))
export type AbsolutePath = typeof AbsolutePath.Type
/** The compact evidence returned after a Drive run settles. */
export const RunReport = Schema.Struct({
artifacts: AbsolutePath,
retained: Schema.Boolean,
recordings: Schema.Array(AbsolutePath),
compatibility: Schema.Array(EndpointCompatibility),
})
export interface RunReport extends Schema.Schema.Type<typeof RunReport> {}
export const decodeAbsolutePath = Schema.decodeUnknownEffect(AbsolutePath)
export const decodeRunReport = Schema.decodeUnknownEffect(RunReport)
function isAbsolutePath(path: string): boolean {
if (path.length === 0 || path.includes("\0")) return false
if (path.startsWith("/")) return true
if (/^[A-Za-z]:[\\/]/.test(path)) return true
if (/^\\\\[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/.test(path)) return true
return /^\\\\[?.]\\(?:[A-Za-z]:\\|UNC\\[^\\]+\\[^\\]+(?:\\|$))/.test(path)
}
+228
View File
@@ -0,0 +1,228 @@
import * as Effect from "effect/Effect"
import * as Cause from "effect/Cause"
import * as Deferred from "effect/Deferred"
import * as Ref from "effect/Ref"
import * as Semaphore from "effect/Semaphore"
import * as Scope from "effect/Scope"
import * as Exit from "effect/Exit"
import { RpcClientError } from "effect/unstable/rpc"
import * as OpenCodeInstance from "../instance/runtime.js"
import * as SimulationConnector from "../simulation/connector.js"
import * as OpenCodeTui from "./client.js"
import * as OpenCodeSdk from "./opencode.js"
import { error, type OpenCodeDriverError } from "./error.js"
import * as LlmController from "./llm-controller.js"
import * as ToolProducer from "../tool/producer.js"
import type * as Tool from "../tool/index.js"
import { LifecycleError } from "../tool/types.js"
export interface Target {
readonly command?: ReadonlyArray<string>
readonly dev?: string
readonly env?: Readonly<Record<string, string>>
readonly visible?: boolean
readonly compatibility?: SimulationConnector.CompatibilityPolicy
}
export interface Options {
readonly instance: OpenCodeInstance.Instance
readonly target?: Target
}
export interface Server {
readonly llm: LlmController.Controller
readonly tools: Tool.Controls
readonly settleTools: ToolProducer.Controller["settle"]
readonly tuis: OpenCodeTui.Control
readonly launch: () => Effect.Effect<
OpenCodeSdk.OpenCode,
OpenCodeDriverError | LlmController.LlmControllerError | SimulationConnector.SimulationCompatibilityError
>
readonly kill: () => Effect.Effect<void, OpenCodeDriverError>
readonly failure: Effect.Effect<never, OpenCodeDriverError | LlmController.LlmControllerError>
readonly compatibility: Effect.Effect<ReadonlyArray<SimulationConnector.EndpointCompatibility>>
}
export const make = Effect.fn("OpenCodeServer.make")(function* (options: Options) {
const connector = yield* SimulationConnector.Service
const target = options.target ?? {}
const instance = options.instance
const llm = yield* LlmController.make()
const toolProducer = yield* ToolProducer.make(instance.toolNames)
const tools: Tool.Controls = {
...instance.tools,
...toolProducer.controls,
}
const tuis = yield* OpenCodeTui.makeTuis(instance, target.visible ?? false, connector, target.compatibility)
const parentScope = yield* Scope.Scope
const generation = yield* Ref.make<
| {
readonly scope: Scope.Scope
readonly attachment: LlmController.Attachment
readonly process: import("../instance/process.js").Running
}
| undefined
>(undefined)
const unexpectedExit = yield* Deferred.make<never, OpenCodeDriverError>()
const toolConnectionFailure = yield* Deferred.make<never, OpenCodeDriverError>()
const lifecycle = yield* Semaphore.make(1)
let compatibility: ReadonlyArray<SimulationConnector.EndpointCompatibility> = []
const launchGeneration = Effect.fn("OpenCodeServer.launch")(function* () {
if ((yield* Ref.get(generation)) !== undefined)
return yield* Effect.fail(error("server.launch", "the script server has already been launched"))
const scope = yield* Scope.fork(parentScope)
const launched = yield* instance.launchServer.pipe(
Effect.mapError((cause) => error("server.launch", cause)),
Effect.onError(() => Scope.close(scope, Exit.void)),
)
let llmAttachment: LlmController.Attachment | undefined
const rollbackLaunch = Effect.suspend(() =>
(llmAttachment?.detach() ?? Effect.void).pipe(
Effect.andThen(toolProducer.endGeneration),
Effect.andThen(Scope.close(scope, Exit.void)),
Effect.andThen(instance.killServer.pipe(Effect.ignore)),
),
)
const backend = yield* connector
.backend(launched.endpoint, {
compatibility: target.compatibility,
})
.pipe(
Scope.provide(scope),
Effect.mapError((cause) => error("server.connect", cause)),
Effect.onError(() => rollbackLaunch),
)
const connectTools = Effect.fn("OpenCodeServer.connectTools")(function* () {
const connectionScope = yield* Scope.fork(scope)
const connection = yield* toolProducer
.connectFrom(
connector
.backend(launched.endpoint, {
attach: false,
compatibility: target.compatibility,
})
.pipe(Scope.provide(connectionScope)),
)
.pipe(Effect.onError(() => Scope.close(connectionScope, Exit.void)))
return { ...connection, scope: connectionScope }
})
const failToolConnection = (cause: unknown) =>
toolProducer.shutdown.pipe(
Effect.andThen(Deferred.fail(toolConnectionFailure, error("tools.connect", cause))),
Effect.asVoid,
)
function reconnectTools(): Effect.Effect<void> {
return connectTools().pipe(
Effect.flatMap(superviseTools),
Effect.catchIf(isRetryableToolConnectionError, () => Effect.sleep(25).pipe(Effect.andThen(reconnectTools()))),
Effect.catchIf(isClosedToolConnectionError, () => Effect.void),
Effect.catch(failToolConnection),
Effect.catchCauseIf(
(cause) => !Cause.hasInterrupts(cause),
(cause) => failToolConnection(Cause.pretty(cause)),
),
)
}
function superviseTools(connection: Effect.Success<ReturnType<typeof connectTools>>): Effect.Effect<void> {
return connection.backend.closed.pipe(
Effect.ensuring(connection.attachment.detach().pipe(Effect.andThen(Scope.close(connection.scope, Exit.void)))),
Effect.andThen(Effect.sleep(25)),
Effect.andThen(reconnectTools()),
)
}
const toolConnection = yield* connectTools().pipe(
Effect.mapError((cause) => error("tools.connect", cause)),
Effect.onError(() => rollbackLaunch),
)
yield* superviseTools(toolConnection).pipe(Effect.forkIn(scope))
const attachment = yield* llm.attach(backend).pipe(Effect.onError(() => rollbackLaunch))
llmAttachment = attachment
const opencode = yield* OpenCodeSdk.make(instance.artifacts).pipe(Effect.onError(() => rollbackLaunch))
const process = yield* instance.primary.pipe(
Effect.mapError((cause) => error("server.launch", cause)),
Effect.onError(() => rollbackLaunch),
)
yield* Ref.set(generation, { scope, attachment, process })
compatibility = [...compatibility, backend.compatibility]
yield* process.exitCode.pipe(
Effect.tap(() => Effect.sleep(25)),
Effect.flatMap((status) =>
Ref.get(generation).pipe(
Effect.flatMap((active) =>
active?.process === process
? toolProducer.endGeneration.pipe(
Effect.andThen(
Deferred.fail(unexpectedExit, error("server.exit", `OpenCode server exited with status ${status}`)),
),
Effect.asVoid,
)
: Effect.void,
),
),
),
Effect.catchCause(() => Effect.void),
Effect.forkIn(scope),
)
return opencode
})
const killGeneration = Effect.fn("OpenCodeServer.kill")(function* () {
const active = yield* Ref.get(generation)
if (active === undefined) return yield* Effect.fail(error("server.kill", "the script server is not running"))
yield* Ref.set(generation, undefined)
yield* active.attachment.detach()
yield* toolProducer.endGeneration
yield* Scope.close(active.scope, Exit.void)
const stopped = yield* Effect.exit(
instance.killServer.pipe(Effect.mapError((cause) => error("server.kill", cause))),
)
if (Exit.isFailure(stopped)) return yield* Effect.failCause(stopped.cause)
return undefined
})
const launch = () => lifecycle.withPermit(launchGeneration())
const kill = () => lifecycle.withPermit(killGeneration())
return {
llm,
tools,
settleTools: toolProducer.settle,
tuis,
launch,
kill,
failure: Effect.raceFirst(
toolProducer.failure.pipe(Effect.mapError((cause) => error("tools", cause))),
Effect.raceFirst(
Deferred.await(toolConnectionFailure),
Effect.raceFirst(llm.failure, Deferred.await(unexpectedExit)),
),
).pipe(Effect.tapError(() => toolProducer.endGeneration)),
compatibility: Effect.sync(() => compatibility),
} satisfies Server
})
function isRetryableToolConnectionError(cause: unknown) {
return (
cause instanceof SimulationConnector.SimulationConnectionError ||
(cause instanceof RpcClientError.RpcClientError && isTransientRpcClientError(cause)) ||
(cause instanceof LifecycleError && cause.reason === "transport-interrupted")
)
}
function isClosedToolConnectionError(cause: unknown) {
return cause instanceof LifecycleError && cause.reason === "controller-closed"
}
function isTransientRpcClientError(error: RpcClientError.RpcClientError) {
if (error.reason._tag !== "RpcClientDefect") return true
const message = error.reason.message
return (
message.startsWith("cannot connect") ||
message === "connection closed" ||
message === "connection error" ||
message === "connection is not open" ||
message === "failed to send request"
)
}
export * as OpenCodeServer from "./server.js"
+26
View File
@@ -0,0 +1,26 @@
import * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import * as Ref from "effect/Ref"
import * as Scope from "effect/Scope"
import * as Semaphore from "effect/Semaphore"
/** Starts a terminal operation once in its owner's scope, independently of callers. */
export const make = Effect.fn("SharedEffect.make")(function* <A, E>(effect: Effect.Effect<A, E>) {
const scope = yield* Scope.Scope
const result = yield* Deferred.make<A, E>()
const started = yield* Ref.make(false)
const lock = yield* Semaphore.make(1)
return Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
yield* lock.withPermit(
Effect.gen(function* () {
if (yield* Ref.get(started)) return
yield* Ref.set(started, true)
yield* Deferred.complete(result, effect).pipe(Effect.asVoid, Effect.forkIn(scope, { uninterruptible: true }))
}),
)
return yield* restore(Deferred.await(result))
}),
)
})
+406
View File
@@ -0,0 +1,406 @@
import * as Effect from "effect/Effect"
import * as Schedule from "effect/Schedule"
import * as Schema from "effect/Schema"
import type { RpcClientError } from "effect/unstable/rpc"
import { supportsCapability, type UiConnection } from "../simulation/connector.js"
import { Frontend } from "../client/protocol.js"
import type { SimulationRequestError } from "@opencode-ai/protocol/simulation"
export interface WaitOptions {
/** Maximum wait in milliseconds. Defaults to 5,000. */
readonly timeout?: number
/** Poll interval in milliseconds. Defaults to 50. */
readonly interval?: number
}
export interface ElementQuery {
readonly id?: string
readonly num?: number
readonly focusable?: boolean
readonly focused?: boolean
readonly clickable?: boolean
readonly editor?: boolean
}
export type SemanticQuery = Partial<Frontend.SemanticNode>
export type Position = Pick<Frontend.ClickParams, "x" | "y">
export type Predicate = (state: Frontend.State) => boolean
export type EffectPredicate<E> = (state: Frontend.State) => Effect.Effect<boolean, E>
export class UiTimeoutError extends Schema.TaggedErrorClass<UiTimeoutError>()("UiTimeoutError", {
operation: Schema.String,
milliseconds: Schema.Number,
message: Schema.String,
frame: Schema.optionalKey(Frontend.CapturedFrame),
}) {}
export class UiElementAmbiguousError extends Schema.TaggedErrorClass<UiElementAmbiguousError>()(
"UiElementAmbiguousError",
{
count: Schema.Number,
},
) {
override get message() {
return `ui.getElement matched ${this.count} elements`
}
}
export class UiNodeAmbiguousError extends Schema.TaggedErrorClass<UiNodeAmbiguousError>()("UiNodeAmbiguousError", {
count: Schema.Number,
}) {
override get message() {
return `ui.getNode matched ${this.count} semantic nodes`
}
}
export class UiCapabilityError extends Schema.TaggedErrorClass<UiCapabilityError>()("UiCapabilityError", {
capability: Schema.Literals(["ui.snapshot", "ui.click.semantic"]),
message: Schema.String,
}) {}
export class UiWaitOptionsError extends Schema.TaggedErrorClass<UiWaitOptionsError>()("UiWaitOptionsError", {
field: Schema.Literals(["timeout", "interval"]),
value: Schema.Number,
message: Schema.String,
}) {}
export class UiPredicateError extends Schema.TaggedErrorClass<UiPredicateError>()("UiPredicateError", {
cause: Schema.Defect(),
message: Schema.String,
}) {}
export interface Options {
/** Per-RPC timeout in milliseconds. Defaults to 30,000. */
readonly requestTimeout?: number
}
const RequestTimeout = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))
export type WaitError = UiTimeoutError | UiWaitOptionsError
type RpcError = SimulationRequestError | RpcClientError.RpcClientError
export type OperationError = RpcError | UiTimeoutError
export type SemanticOperationError = OperationError | UiCapabilityError
export interface Ui {
readonly state: () => Effect.Effect<Frontend.State, OperationError>
readonly snapshot: () => Effect.Effect<Frontend.SemanticSnapshot, SemanticOperationError>
readonly capture: () => Effect.Effect<Frontend.CapturedFrame, OperationError>
readonly matches: (text: string) => Effect.Effect<boolean, OperationError>
readonly screenshot: (name?: string) => Effect.Effect<string, OperationError>
readonly type: (text: string) => Effect.Effect<Frontend.State, OperationError>
readonly press: (key: string, modifiers?: Frontend.KeyModifiers) => Effect.Effect<Frontend.State, OperationError>
readonly enter: () => Effect.Effect<Frontend.State, OperationError>
readonly arrow: (direction: Frontend.ArrowParams["direction"]) => Effect.Effect<Frontend.State, OperationError>
readonly focus: (target: number | Frontend.Element) => Effect.Effect<Frontend.State, OperationError>
readonly click: (
target: number | Frontend.Element | Frontend.SemanticNode,
position?: Position,
) => Effect.Effect<Frontend.State, OperationError | UiCapabilityError | UiElementAmbiguousError | UiWaitOptionsError>
readonly resize: (viewport: Frontend.ResizeParams) => Effect.Effect<Frontend.State, OperationError>
readonly submit: (text: string) => Effect.Effect<Frontend.State, OperationError>
readonly waitFor: <E = never>(
target: string | Predicate | EffectPredicate<E>,
options?: WaitOptions,
) => Effect.Effect<Frontend.State, OperationError | WaitError | UiPredicateError | E>
readonly getElement: (
target: number | string | ElementQuery,
options?: WaitOptions,
) => Effect.Effect<Frontend.Element, OperationError | WaitError | UiElementAmbiguousError>
readonly getNode: (
target: string | SemanticQuery,
options?: WaitOptions,
) => Effect.Effect<Frontend.SemanticNode, SemanticOperationError | WaitError | UiNodeAmbiguousError>
}
interface Control extends Ui {
readonly finishRecording: () => Effect.Effect<string, OperationError>
}
export interface Transform {
<A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E>
}
/** Applies one Effect transformation to every operation without changing the UI interface. */
export const transform = (ui: Ui, apply: Transform): Ui => ({
state: () => apply(ui.state()),
snapshot: () => apply(ui.snapshot()),
capture: () => apply(ui.capture()),
matches: (text) => apply(ui.matches(text)),
screenshot: (name) => apply(ui.screenshot(name)),
type: (text) => apply(ui.type(text)),
press: (key, modifiers) => apply(ui.press(key, modifiers)),
enter: () => apply(ui.enter()),
arrow: (direction) => apply(ui.arrow(direction)),
focus: (target) => apply(ui.focus(target)),
click: (target, position) => apply(ui.click(target, position)),
resize: (viewport) => apply(ui.resize(viewport)),
submit: (text) => apply(ui.submit(text)),
waitFor: (target, options) => apply(ui.waitFor(target, options)),
getElement: (target, options) => apply(ui.getElement(target, options)),
getNode: (target, options) => apply(ui.getNode(target, options)),
})
export const make = (connection: UiConnection, options?: Options): Control => {
const requestTimeout = RequestTimeout.make(options?.requestTimeout ?? 30_000)
const evidenceTimeout = Math.min(requestTimeout, 1_000)
const { rpc } = connection
const call = <A, E>(operation: string, effect: Effect.Effect<A, E>): Effect.Effect<A, E | UiTimeoutError> =>
Effect.timeoutOrElse(effect, {
duration: requestTimeout,
orElse: () =>
Effect.fail(
new UiTimeoutError({
operation,
milliseconds: requestTimeout,
message: `ui.${operation} timed out after ${requestTimeout}ms`,
}),
),
})
const state = Effect.fn("Ui.state")(() => call("state", rpc["ui.state"]()))
const snapshot = Effect.fn("Ui.snapshot")(function* () {
if (!supportsCapability(connection.compatibility, "ui.snapshot"))
return yield* Effect.fail(
new UiCapabilityError({
capability: "ui.snapshot",
message: "ui.snapshot is not available on this OpenCode endpoint",
}),
)
return yield* call("snapshot", rpc["ui.snapshot"]())
})
const capture = Effect.fn("Ui.capture")(() => call("capture", rpc["ui.capture"]()))
const matches = Effect.fn("Ui.matches")((text: string) => call("matches", rpc["ui.matches"]({ text })))
const screenshot = Effect.fn("Ui.screenshot")((name?: string) =>
call("screenshot", rpc["ui.screenshot"](name === undefined ? undefined : { name })),
)
const finishRecording = Effect.fn("Ui.finishRecording")(() => call("finishRecording", rpc["ui.recording.finish"]()))
const type = Effect.fn("Ui.type")((text: string) => call("type", rpc["ui.type"]({ text })))
const press = Effect.fn("Ui.press")((key: string, modifiers?: Frontend.KeyModifiers) =>
call("press", rpc["ui.press"](Frontend.pressParams(key, modifiers))),
)
const enter = Effect.fn("Ui.enter")(() => call("enter", rpc["ui.enter"]()))
const arrow = Effect.fn("Ui.arrow")((direction: Frontend.ArrowParams["direction"]) =>
call("arrow", rpc["ui.arrow"]({ direction })),
)
const focus = Effect.fn("Ui.focus")((target: number | Frontend.Element) =>
call(
"focus",
rpc["ui.focus"]({
target: typeof target === "number" ? target : target.num,
}),
),
)
const resize = Effect.fn("Ui.resize")((viewport: Frontend.ResizeParams) => call("resize", rpc["ui.resize"](viewport)))
const submit = Effect.fn("Ui.submit")(function* (text: string) {
yield* type(text)
return yield* enter()
})
const pollingTimeout = (operation: string, milliseconds: number, message: string) =>
rpc["ui.capture"]().pipe(
Effect.timeoutOrElse({
duration: evidenceTimeout,
orElse: () => Effect.succeed(undefined),
}),
Effect.catchCause(() => Effect.succeed(undefined)),
Effect.flatMap((frame) =>
Effect.fail(
new UiTimeoutError({
operation,
milliseconds,
message,
...(frame === undefined ? {} : { frame }),
}),
),
),
)
const poll = <A, E>(
operation: string,
read: Effect.Effect<A | undefined, E>,
options: WaitOptions | undefined,
message: string,
): Effect.Effect<A, E | WaitError> => {
const timeout = options?.timeout ?? 5_000
const interval = options?.interval ?? 50
const validate = Effect.gen(function* () {
if (!Number.isFinite(timeout) || timeout < 0) {
yield* Effect.fail(
new UiWaitOptionsError({
field: "timeout",
value: timeout,
message: "ui wait timeout must be a finite non-negative number",
}),
)
}
if (!Number.isFinite(interval) || interval <= 0) {
yield* Effect.fail(
new UiWaitOptionsError({
field: "interval",
value: interval,
message: "ui wait interval must be a finite positive number",
}),
)
}
})
return Effect.gen(function* () {
yield* validate
return yield* Effect.repeat(read, {
until: (value): value is A => value !== undefined,
schedule: Schedule.spaced(interval),
}).pipe(
Effect.timeoutOrElse({
duration: timeout,
orElse: () => pollingTimeout(operation, timeout, message),
}),
)
})
}
const waitFor = Effect.fn("Ui.waitFor")(<E>(target: string | Predicate | EffectPredicate<E>, options?: WaitOptions) =>
poll(
"waitFor",
typeof target === "string"
? Effect.gen(function* () {
if (!(yield* matches(target))) return undefined
return yield* state()
})
: Effect.flatMap(state(), (value) =>
predicateEffect(target, value).pipe(Effect.map((matches) => (matches ? value : undefined))),
),
options,
typeof target === "string"
? `timed out waiting for the UI to match ${JSON.stringify(target)}`
: "timed out waiting for the UI to match",
),
)
const getElement = Effect.fn("Ui.getElement")((target: number | string | ElementQuery, options?: WaitOptions) =>
poll(
"getElement",
Effect.flatMap(state(), (value) => {
const elements = value.elements.filter((element) =>
typeof target === "number"
? element.num === target
: typeof target === "string"
? element.id === target
: matchesQuery(element, target),
)
if (elements.length > 1) return Effect.fail(new UiElementAmbiguousError({ count: elements.length }))
return Effect.succeed(elements[0])
}),
options,
"timed out waiting for the UI element",
),
)
const getNode = Effect.fn("Ui.getNode")((target: string | SemanticQuery, options?: WaitOptions) =>
poll(
"getNode",
Effect.flatMap(snapshot(), (value) => {
const nodes = value.nodes.filter((node) =>
typeof target === "string" ? node.id === target : matchesQuery(node, target),
)
if (nodes.length > 1) return Effect.fail(new UiNodeAmbiguousError({ count: nodes.length }))
return Effect.succeed(nodes[0])
}),
options,
"timed out waiting for the semantic UI node",
),
)
const click = Effect.fn("Ui.click")(function* (
target: number | Frontend.Element | Frontend.SemanticNode,
position?: Position,
) {
if (typeof target !== "number" && "element" in target) {
if (!supportsCapability(connection.compatibility, "ui.click.semantic"))
return yield* Effect.fail(
new UiCapabilityError({
capability: "ui.click.semantic",
message: "semantic ui.click is not available on this OpenCode endpoint",
}),
)
const element =
position === undefined
? (yield* state()).elements.find((candidate) => candidate.num === target.element)
: undefined
return yield* call(
"click",
rpc["ui.click"]({
target: target.element,
x: position?.x ?? (element === undefined ? 0 : Math.floor(element.width / 2)),
y: position?.y ?? (element === undefined ? 0 : Math.floor(element.height / 2)),
semantic: {
id: target.id,
...(target.instance === undefined ? {} : { instance: target.instance }),
element: target.element,
},
}),
)
}
const element = typeof target === "number" ? yield* getElement(target) : target
return yield* call(
"click",
rpc["ui.click"]({
target: element.num,
x: position?.x ?? Math.floor(element.width / 2),
y: position?.y ?? Math.floor(element.height / 2),
}),
)
})
return {
state,
snapshot,
capture,
matches,
screenshot,
finishRecording,
type,
press,
enter,
arrow,
focus,
click,
resize,
submit,
waitFor,
getElement,
getNode,
}
}
function predicateEffect<E>(
predicate: Predicate | EffectPredicate<E>,
state: Frontend.State,
): Effect.Effect<boolean, E | UiPredicateError> {
return Effect.gen(function* () {
const result = yield* Effect.try({
try: () => predicate(state),
catch: (cause) =>
new UiPredicateError({
cause,
message: `ui.waitFor predicate failed: ${cause instanceof Error ? cause.message : String(cause)}`,
}),
})
const value: unknown = Effect.isEffect(result) ? yield* result : result
if (typeof value === "boolean") return value
return yield* Effect.fail(
new UiPredicateError({
cause: value,
message: "ui.waitFor predicate must return a boolean or Effect",
}),
)
})
}
function matchesQuery<Value extends object>(value: Value, query: Partial<Value>) {
return Object.entries(query).every(
([key, expected]) => expected === undefined || Reflect.get(value, key) === expected,
)
}
export * as OpenCodeUi from "./ui.js"
+162
View File
@@ -0,0 +1,162 @@
/**
* Renderer-neutral vocabulary for drawing captured terminal frames: the
* canonical cell geometry, OpenTUI text-attribute bits, geometric block/bar
* glyph primitives, and baseline placement. Both the Drive PNG renderer
* (`recording/render.ts`) and browser canvas renderers consume this module so
* their output stays synchronized by construction.
*
* This entry point must stay dependency-free and browser-safe.
*/
/** OpenTUI text-attribute bits carried on captured spans. */
export const TextStyle = {
bold: 1,
dim: 2,
italic: 4,
underline: 8,
blink: 16,
inverse: 32,
invisible: 64,
strikethrough: 128,
} as const
/** Canonical cell width in pixels. */
export const CellWidth = 10
/** Canonical cell height in pixels. */
export const CellHeight = 20
/** Canonical font size in pixels for cell text. */
export const FontSize = 16
/** Opacity applied to dim spans. */
export const DimAlpha = 0.55
/** Y offset of the underline stroke within a cell. */
export const UnderlineOffset = 17
/** Y offset of the strikethrough stroke within a cell. */
export const StrikethroughOffset = 10
/** A rectangle in pixels relative to a cell's top-left corner. */
export interface GlyphRect {
readonly x: number
readonly y: number
readonly width: number
readonly height: number
/** Whether the rectangle's width scales with the glyph's cell count. */
readonly stretch: boolean
}
/**
* Terminal cell primitives that renderers draw geometrically instead of with
* fonts: solid blocks and structural bars. Ordinary Unicode symbols belong in
* fallback fonts, not in this table.
*/
export const BlockGlyphs: Record<string, GlyphRect> = {
"█": { x: 0, y: 0, width: CellWidth, height: CellHeight, stretch: true },
"▀": { x: 0, y: 0, width: CellWidth, height: CellHeight / 2, stretch: true },
"▄": {
x: 0,
y: CellHeight / 2,
width: CellWidth,
height: CellHeight / 2,
stretch: true,
},
"┃": { x: CellWidth / 2 - 1, y: 0, width: 2, height: CellHeight, stretch: false },
"╹": { x: CellWidth / 2 - 1, y: 0, width: 2, height: CellHeight / 2, stretch: false },
}
const lightBoxGlyphs: Record<string, readonly [up: boolean, right: boolean, down: boolean, left: boolean]> = {
"─": [false, true, false, true],
"│": [true, false, true, false],
"┌": [false, true, true, false],
"┐": [false, false, true, true],
"└": [true, true, false, false],
"┘": [true, false, false, true],
"├": [true, true, true, false],
"┤": [true, false, true, true],
"┬": [false, true, true, true],
"┴": [true, true, false, true],
"┼": [true, true, true, true],
"╭": [false, true, true, false],
"╮": [false, false, true, true],
"╰": [true, true, false, false],
"╯": [true, false, false, true],
}
const diagonalBlockGlyphs: Record<string, ReadonlyArray<Omit<GlyphRect, "stretch">>> = {
"▚": [
{ x: 0, y: 0, width: CellWidth / 2, height: CellHeight / 2 },
{ x: CellWidth / 2, y: CellHeight / 2, width: CellWidth / 2, height: CellHeight / 2 },
],
"▞": [
{ x: CellWidth / 2, y: 0, width: CellWidth / 2, height: CellHeight / 2 },
{ x: 0, y: CellHeight / 2, width: CellWidth / 2, height: CellHeight / 2 },
],
}
/**
* Draws a block/bar glyph geometrically. Returns false when the character is
* not a geometric primitive and must be drawn with fonts instead.
*/
export const drawBlockGlyph = (
context: {
fillRect(x: number, y: number, width: number, height: number): void
},
char: string,
x: number,
y: number,
cells = 1,
): boolean => {
const glyph = BlockGlyphs[char]
if (glyph !== undefined) {
const width = glyph.stretch ? glyph.width + (cells - 1) * CellWidth : glyph.width
context.fillRect(x + glyph.x, y + glyph.y, width, glyph.height)
return true
}
const box = lightBoxGlyphs[char]
if (box !== undefined) {
const lineX = CellWidth / 2 - 1
const lineY = CellHeight / 2 - 1
const vertical = box[0] || box[2]
if (vertical) {
const top = box[0] ? 0 : lineY
const bottom = box[2] ? CellHeight : lineY + 1
context.fillRect(x + lineX, y + top, 1, bottom - top)
}
if (!vertical && (box[1] || box[3])) {
const left = box[3] ? 0 : lineX
const right = box[1] ? CellWidth : lineX + 1
context.fillRect(x + left, y + lineY, right - left, 1)
} else {
if (box[3]) context.fillRect(x, y + lineY, lineX, 1)
if (box[1]) context.fillRect(x + lineX + 1, y + lineY, CellWidth - lineX - 1, 1)
}
return true
}
const quadrants = diagonalBlockGlyphs[char]
if (quadrants === undefined) return false
for (const quadrant of quadrants) context.fillRect(x + quadrant.x, y + quadrant.y, quadrant.width, quadrant.height)
return true
}
/** The subset of a canvas 2D context needed to measure font baselines. */
export interface FontMeasurer {
measureText(text: string): {
readonly fontBoundingBoxAscent?: number
readonly fontBoundingBoxDescent?: number
}
}
const baselineCache = new Map<string, number>()
/**
* Alphabetic baseline that centers the font's bounding box in a cell. The
* context's font must already be set to `font`.
*/
export const baselineOffset = (context: FontMeasurer, font: string): number => {
const cached = baselineCache.get(font)
if (cached !== undefined) return cached
const metrics = context.measureText("Mg")
const ascent = metrics.fontBoundingBoxAscent ?? FontSize * 0.8
const descent = metrics.fontBoundingBoxDescent ?? FontSize * 0.2
const offset = (CellHeight - (ascent + descent)) / 2 + ascent
baselineCache.set(font, offset)
return offset
}
+3
View File
@@ -0,0 +1,3 @@
interface WebSocket {
terminate(): void
}
+8
View File
@@ -0,0 +1,8 @@
export * from "./script/index.js"
export * as Effect from "effect/Effect"
export * as Llm from "./llm/index.js"
export * as OpenCodeDriver from "./driver/index.js"
export * as Errors from "./script/errors.js"
export * as Tool from "./tool/index.js"
export { Frontend } from "./client/protocol.js"
export type { OpenCode, Recording, Tui, TuiLaunchError, TuiOptions, Tuis, Ui } from "./driver/index.js"
+162
View File
@@ -0,0 +1,162 @@
import { rm } from "node:fs/promises"
import { connect, createServer } from "node:net"
import type { ResponseConfiguration, ResponseUpdate } from "../cli/response-generator.js"
export interface StopResult {
readonly recording?: string
readonly screenshots: ReadonlyArray<string>
}
export async function listenControl(
path: string,
handlers: {
readonly restart: () => Promise<string | undefined>
readonly stop: (onProgress: (percent: number) => void) => Promise<StopResult>
readonly responses: (input: ResponseUpdate) => Promise<ResponseConfiguration>
},
) {
const server = createServer((socket) => {
let buffer = ""
socket.setEncoding("utf8")
socket.on("data", (data) => {
buffer += data
if (buffer.length > 64 * 1024) {
socket.removeAllListeners("data")
socket.end("error: control request exceeds 64 KiB\n")
return
}
if (!buffer.includes("\n")) return
socket.removeAllListeners("data")
const progress = (percent: number) => socket.write(`progress ${percent}\n`)
void handle(buffer.slice(0, buffer.indexOf("\n")), progress).then(
(result) => socket.end(`success${result === undefined ? "" : ` ${JSON.stringify(result)}`}\n`),
(error) => socket.end(`error: ${error instanceof Error ? error.message : String(error)}\n`),
)
})
})
const handle = async (input: string, onProgress: (percent: number) => void) => {
if (input === "restart") return handlers.restart()
if (input === "stop") return handlers.stop(onProgress)
if (input === "responses") return handlers.responses({})
if (input.startsWith("responses ")) return handlers.responses(parseResponseUpdate(input.slice("responses ".length)))
throw new Error("unknown control command")
}
await listen(server, path)
return async () => {
await new Promise<void>((resolve) => server.close(() => resolve()))
await rm(path, { force: true })
}
}
export async function request(path: string, command: "restart") {
const response = await send(path, command)
if (response === "success") return undefined
if (!response.startsWith("success ")) throw responseError(response)
const value: unknown = JSON.parse(response.slice("success ".length))
if (typeof value !== "string") throw new Error("instance returned an invalid recording path")
return value
}
export async function requestStop(path: string, onProgress?: (percent: number) => void) {
const response = await send(path, "stop", onProgress)
if (!response.startsWith("success ")) throw responseError(response)
const value: unknown = JSON.parse(response.slice("success ".length))
if (!isStopResult(value)) throw new Error("instance returned an invalid stop result")
return value
}
export async function requestResponses(path: string, input: ResponseUpdate) {
const response = await send(
path,
Object.keys(input).length === 0 ? "responses" : `responses ${JSON.stringify(input)}`,
)
if (!response.startsWith("success ")) throw responseError(response)
const value: unknown = JSON.parse(response.slice("success ".length))
if (!isResponseConfiguration(value)) throw new Error("instance returned an invalid response configuration")
return value
}
function send(path: string, command: string, onProgress?: (percent: number) => void) {
return new Promise<string>((resolve, reject) => {
const socket = connect(path)
let response = ""
let buffer = ""
const timer = setTimeout(() => {
socket.destroy()
reject(new Error("instance control request timed out"))
}, 5 * 60_000)
socket.setEncoding("utf8")
socket.on("connect", () => socket.write(`${command}\n`))
socket.on("data", (data) => {
buffer += data
while (buffer.includes("\n")) {
const index = buffer.indexOf("\n")
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 1)
if (line.startsWith("progress ")) {
const percent = Number(line.slice("progress ".length))
if (Number.isInteger(percent)) onProgress?.(percent)
continue
}
response += `${line}\n`
}
})
socket.on("end", () => {
clearTimeout(timer)
resolve(`${response}${buffer}`.trim())
})
socket.on("error", () => {
clearTimeout(timer)
reject(new Error("instance control socket is unavailable"))
})
})
}
function parseResponseUpdate(input: string): ResponseUpdate {
const value: unknown = JSON.parse(input)
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error("invalid responses configuration")
const types = "types" in value ? stringArray(value.types) : undefined
const tools = "tools" in value ? stringArray(value.tools) : undefined
return {
...(types === undefined ? {} : { types }),
...(tools === undefined ? {} : { tools }),
}
}
function stringArray(value: unknown) {
if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
throw new Error("response types and tools must be string arrays")
return value
}
function isResponseConfiguration(value: unknown): value is ResponseConfiguration {
if (typeof value !== "object" || value === null) return false
if (!("types" in value) || !stringArrayValue(value.types)) return false
return "tools" in value && stringArrayValue(value.tools)
}
function isStopResult(value: unknown): value is StopResult {
if (typeof value !== "object" || value === null) return false
if (!("screenshots" in value) || !stringArrayValue(value.screenshots)) return false
return !("recording" in value) || typeof value.recording === "string"
}
function stringArrayValue(value: unknown) {
return Array.isArray(value) && value.every((item) => typeof item === "string")
}
function responseError(response: string) {
return new Error(response.replace(/^error:\s*/, "") || "empty control response")
}
async function listen(server: ReturnType<typeof createServer>, path: string) {
await rm(path, { force: true })
await new Promise<void>((resolve, reject) => {
server.once("error", reject)
server.listen(path, () => {
server.off("error", reject)
resolve()
})
})
}
@@ -0,0 +1,34 @@
{
"model": "simulation/gpt-sim-model",
"snapshots": false,
"permissions": [
{
"action": "*",
"resource": "*",
"effect": "allow",
},
],
"providers": {
"simulation": {
"name": "Simulation",
"package": "@opencode-ai/ai/providers/openai/chat",
"settings": {
"apiKey": "sim-key",
},
"models": {
"gpt-sim-model": {
"name": "Simulated Model",
"capabilities": {
"tools": true,
"input": ["text"],
"output": ["text"],
},
"limit": {
"context": 128000,
"output": 16000,
},
},
},
},
},
}
+37
View File
@@ -0,0 +1,37 @@
import { mkdir, rm, symlink } from "node:fs/promises"
import { join, resolve } from "node:path"
import * as Effect from "effect/Effect"
import { instanceError } from "./error.js"
/**
* Prepares an OpenCode development checkout for launch: verifies the CLI
* entrypoint and reuses its installed `@opentui/solid` preload.
*/
export const prepareDev = Effect.fn("OpenCodeInstance.prepareDev")(function* (artifacts: string, directory: string) {
const root = resolve(directory)
const entrypoint = join(root, "packages", "cli", "src", "index.ts")
const solid = join(root, "packages", "tui", "node_modules", "@opentui", "solid")
const standalone = yield* Effect.tryPromise({
try: async () => {
if (!(await Bun.file(entrypoint).exists()))
throw new Error(`OpenCode development entrypoint not found: ${entrypoint}`)
if (!(await Bun.file(join(solid, "package.json")).exists()))
throw new Error(`OpenCode development dependency not found: ${solid}; run bun install in ${root}`)
const preload = join(artifacts, "node_modules", "@opentui", "solid")
await mkdir(join(artifacts, "node_modules", "@opentui"), {
recursive: true,
})
await rm(preload, { recursive: true, force: true })
await symlink(solid, preload, "dir")
return Bun.file(join(root, "packages", "cli", "src", "services", "standalone.ts")).exists()
},
catch: (cause) => instanceError("prepare development checkout", cause),
})
const preloads = ["--conditions=browser", `--preload=${join(solid, "scripts", "preload.js")}`]
const base = [process.execPath, ...preloads, entrypoint]
return {
command: [...base, ...(standalone ? ["--standalone"] : [])],
scriptedCommand: base,
preloads,
}
})
+15
View File
@@ -0,0 +1,15 @@
import * as Schema from "effect/Schema"
export class OpenCodeInstanceError extends Schema.TaggedErrorClass<OpenCodeInstanceError>()("OpenCodeInstanceError", {
operation: Schema.String,
message: Schema.String,
}) {}
/** Coerces any cause into an `OpenCodeInstanceError`, preserving existing ones. */
export function instanceError(operation: string, cause: unknown) {
if (cause instanceof OpenCodeInstanceError) return cause
return new OpenCodeInstanceError({
operation,
message: cause instanceof Error ? cause.message : String(cause),
})
}
+114
View File
@@ -0,0 +1,114 @@
import { mkdir } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join, resolve } from "node:path"
import * as Effect from "effect/Effect"
import { createScriptFileSystem } from "../script/filesystem.js"
import { commitScriptProject, hasGitMetadata, initializeScriptProject } from "../script/project.js"
import type { OpenCodeConfig, OpenCodeTuiConfig, Project, Setup } from "../project.js"
export function artifactDirectory() {
return resolve(join(tmpdir(), "opencode-drive"))
}
export async function initializeInstance(name?: string) {
const artifacts = resolve(join(artifactDirectory(), `run-${crypto.randomUUID()}`))
const logs = join(artifacts, "logs")
const drive = join(artifacts, "drive")
await Promise.all([
mkdir(logs, { recursive: true }),
mkdir(drive, { recursive: true }),
mkdir(join(artifacts, "home", ".cache"), { recursive: true }),
mkdir(join(artifacts, "home", ".config"), { recursive: true }),
mkdir(join(artifacts, "home", ".local", "share"), { recursive: true }),
mkdir(join(artifacts, "home", ".local", "state"), { recursive: true }),
])
const files = join(artifacts, "files")
const defaultConfig = await Bun.file(new URL("./default-config.jsonc", import.meta.url)).text()
await Promise.all([
mkdir(join(files, ".git"), { recursive: true }),
mkdir(join(files, ".opencode"), { recursive: true }),
mkdir(join(files, "src"), { recursive: true }),
])
await Promise.all([
Bun.write(join(files, ".opencode", "opencode.jsonc"), defaultConfig),
Bun.write(join(files, "src", "garden.js"), "export function greet(name) {\n return `Hello, ${name}.`\n}\n"),
...(name ? [Bun.write(join(drive, "name"), `${name}\n`)] : []),
])
return artifacts
}
export const prepareInstanceProject = Effect.fn("OpenCodeInstance.prepareProject")(function* (options: {
readonly artifacts: string
readonly project?: Project
readonly config?: OpenCodeConfig
readonly tui?: OpenCodeTuiConfig
readonly setup?: Setup
}) {
const files = join(resolve(options.artifacts), "files")
const configPath = join(files, ".opencode", "opencode.jsonc")
const tuiPath = join(files, ".opencode", "tui.jsonc")
const project = options.project
if (project) yield* promise(() => initializeScriptProject(files, project))
const [config, tui] = yield* Effect.all(
[promise(() => readConfig(configPath, "opencode.jsonc")), promise(() => readConfig(tuiPath, "tui.jsonc", {}))],
{ concurrency: "unbounded" },
)
deepMerge(config, options.config)
deepMerge(tui, options.tui)
if (options.setup !== undefined) {
const protectGit = Boolean(options.project?.git) || (yield* promise(() => hasGitMetadata(files)))
const setup: Effect.Effect<void, unknown> = options.setup({
fs: createScriptFileSystem(files, { git: protectGit }),
config,
tuiConfig: tui,
})
if (!Effect.isEffect(setup)) return yield* Effect.fail(new Error("setup must return an Effect"))
yield* setup
}
yield* Effect.all(
[
promise(() => Bun.write(configPath, `${JSON.stringify(config, undefined, 2)}\n`)),
promise(() => Bun.write(tuiPath, `${JSON.stringify(tui, undefined, 2)}\n`)),
],
{ concurrency: "unbounded" },
)
if (options.project?.git) yield* promise(() => commitScriptProject(files))
return undefined
})
const promise = <A>(evaluate: () => PromiseLike<A>) =>
Effect.tryPromise({
try: evaluate,
catch: (cause) => (cause instanceof Error ? cause : new Error(String(cause))),
})
async function readConfig(path: string, name: string, fallback?: OpenCodeConfig): Promise<OpenCodeConfig> {
const file = Bun.file(path)
let value: unknown
try {
value = (await file.exists())
? Bun.JSONC.parse(await file.text())
: (fallback ?? Bun.JSONC.parse(await Bun.file(new URL("./default-config.jsonc", import.meta.url)).text()))
} catch (cause) {
throw new Error(`invalid .opencode/${name}`, { cause })
}
if (!isJsonObject(value)) throw new Error(`invalid .opencode/${name}: expected a JSON object`)
return value
}
function deepMerge(target: OpenCodeConfig, source: OpenCodeConfig | undefined) {
if (source === undefined) return target
for (const [key, value] of Object.entries(source)) {
const existing = target[key]
if (isJsonObject(existing) && isJsonObject(value)) {
deepMerge(existing, value)
} else {
target[key] = structuredClone(value)
}
}
return target
}
function isJsonObject(value: unknown): value is OpenCodeConfig {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
+9
View File
@@ -0,0 +1,9 @@
import { basename, join, resolve } from "node:path"
import { artifactDirectory } from "./instance.js"
export function mediaDirectory() {
return resolve(process.env.OPENCODE_DRIVE_MEDIA_DIR ?? join(artifactDirectory(), "output"))
}
export const runMediaDirectory = (artifacts: string, generation: number) =>
join(mediaDirectory(), basename(resolve(artifacts)), `generation-${generation}`)
+228
View File
@@ -0,0 +1,228 @@
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as FileSystem from "effect/FileSystem"
import * as Fiber from "effect/Fiber"
import * as Option from "effect/Option"
import * as Ref from "effect/Ref"
import type * as Scope from "effect/Scope"
import * as Scope_ from "effect/Scope"
import * as Schema from "effect/Schema"
import * as Stream from "effect/Stream"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
export class ProcessError extends Schema.TaggedErrorClass<ProcessError>()("ProcessError", {
operation: Schema.String,
command: Schema.Array(Schema.String),
message: Schema.String,
}) {}
export interface SpawnOptions {
readonly cwd?: string
readonly env?: Readonly<Record<string, string>>
readonly extendEnv?: boolean
readonly stdin?: "inherit" | "ignore"
readonly stdout?: "inherit" | "ignore" | { readonly path: string }
readonly stderr?: "inherit" | "ignore" | { readonly path: string }
readonly detached?: boolean
}
export interface Running {
readonly pid: number
readonly exitCode: Effect.Effect<number, ProcessError>
readonly isRunning: Effect.Effect<boolean, ProcessError>
readonly terminate: Effect.Effect<void, ProcessError>
readonly detach: Effect.Effect<void, ProcessError>
}
export interface Output {
readonly status: number
readonly stdout: string
readonly stderr: string
}
type RunOutputMode = "capture" | "inherit" | "ignore"
export interface RunOptions extends Omit<SpawnOptions, "stdout" | "stderr" | "detached"> {
readonly stdout?: RunOutputMode
readonly stderr?: RunOutputMode
readonly stdoutLimit?: number
readonly stderrLimit?: number
}
export const spawn = Effect.fn("Process.spawn")(function* (command: ReadonlyArray<string>, options: SpawnOptions = {}) {
const executable = command[0]
if (executable === undefined)
return yield* Effect.fail(processError("spawn", command, "cannot spawn an empty command"))
const parentScope = yield* Scope_.Scope
const processScope = yield* Scope_.fork(parentScope)
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
const fileSystem = yield* FileSystem.FileSystem
const handle = yield* spawner
.spawn(
ChildProcess.make(executable, command.slice(1), {
cwd: options.cwd,
env: options.env,
extendEnv: options.extendEnv ?? false,
stdin: options.stdin ?? "ignore",
stdout: outputMode(options.stdout),
stderr: outputMode(options.stderr),
detached: options.detached,
killSignal: "SIGKILL",
}),
)
.pipe(
Scope_.provide(processScope),
Effect.mapError((cause) => processError("spawn", command, cause)),
Effect.onError(() => Scope_.close(processScope, Exit.void)),
)
const drains: Array<Fiber.Fiber<void, ProcessError>> = []
if (typeof options.stdout === "object")
drains.push(
yield* Stream.run(handle.stdout, fileSystem.sink(options.stdout.path)).pipe(
Effect.mapError((cause) => processError("stdout", command, cause)),
Effect.forkIn(processScope),
),
)
if (typeof options.stderr === "object")
drains.push(
yield* Stream.run(handle.stderr, fileSystem.sink(options.stderr.path)).pipe(
Effect.mapError((cause) => processError("stderr", command, cause)),
Effect.forkIn(processScope),
),
)
const exitCode = handle.exitCode.pipe(
Effect.map(Number),
Effect.catch(() => Effect.succeed(1)),
Effect.tap(() =>
Effect.forEach(drains, Fiber.join, {
concurrency: "unbounded",
discard: true,
}),
),
)
const detached = yield* Ref.make(false)
const terminate = Effect.uninterruptible(
Effect.gen(function* () {
const running = yield* handle.isRunning.pipe(Effect.mapError((cause) => processError("status", command, cause)))
if (!running) {
yield* Scope_.close(processScope, Exit.void)
return undefined
}
const graceful = yield* handle.kill({ killSignal: "SIGTERM" }).pipe(
Effect.timeoutOption(1_000),
Effect.mapError((cause) => processError("terminate", command, cause)),
)
if (Option.isNone(graceful))
yield* handle
.kill({ killSignal: "SIGKILL" })
.pipe(Effect.mapError((cause) => processError("kill", command, cause)))
yield* exitCode
yield* Scope_.close(processScope, Exit.void)
return undefined
}),
)
yield* Effect.addFinalizer(() =>
Ref.get(detached).pipe(Effect.flatMap((isDetached) => (isDetached ? Effect.void : terminate.pipe(Effect.ignore)))),
)
yield* Effect.exit(exitCode).pipe(Effect.andThen(Scope_.close(processScope, Exit.void)), Effect.forkIn(parentScope))
const detach = handle.unref.pipe(
Effect.asVoid,
Effect.mapError((cause) => processError("detach", command, cause)),
Effect.andThen(Ref.set(detached, true)),
Effect.andThen(Scope_.close(processScope, Exit.void)),
)
return {
pid: Number(handle.pid),
exitCode,
isRunning: handle.isRunning.pipe(Effect.mapError((cause) => processError("status", command, cause))),
terminate,
detach,
} satisfies Running
})
export const run = Effect.fn("Process.run")(function* (command: ReadonlyArray<string>, options: RunOptions = {}) {
const executable = command[0]
if (executable === undefined) return yield* Effect.fail(processError("run", command, "cannot run an empty command"))
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
return yield* Effect.scoped(
Effect.gen(function* () {
const handle = yield* spawner
.spawn(
ChildProcess.make(executable, command.slice(1), {
cwd: options.cwd,
env: options.env,
extendEnv: options.extendEnv ?? false,
stdin: options.stdin ?? "ignore",
stdout: captureMode(options.stdout),
stderr: captureMode(options.stderr),
killSignal: "SIGKILL",
}),
)
.pipe(Effect.mapError((cause) => processError("spawn", command, cause)))
const stdout = yield* collectOutput(handle.stdout, options.stdout, options.stdoutLimit).pipe(
Effect.mapError((cause) => processError("stdout", command, cause)),
Effect.forkChild,
)
const stderr = yield* collectOutput(handle.stderr, options.stderr, options.stderrLimit).pipe(
Effect.mapError((cause) => processError("stderr", command, cause)),
Effect.forkChild,
)
const status = yield* handle.exitCode.pipe(
Effect.map(Number),
Effect.mapError((cause) => processError("wait", command, cause)),
)
return {
status,
stdout: yield* Fiber.join(stdout),
stderr: yield* Fiber.join(stderr),
} satisfies Output
}),
)
})
function outputMode(output: SpawnOptions["stdout"] | SpawnOptions["stderr"]) {
return typeof output === "object" ? "pipe" : (output ?? "ignore")
}
function captureMode(output: RunOutputMode | undefined) {
return output === undefined || output === "capture" ? "pipe" : output
}
function collectOutput(
stream: Stream.Stream<Uint8Array, unknown>,
mode: RunOutputMode | undefined,
limit: number | undefined,
) {
if (mode === "inherit" || mode === "ignore") return Effect.succeed("")
if (limit === undefined) return stream.pipe(Stream.decodeText(), Stream.mkString)
return Effect.gen(function* () {
let output = ""
yield* stream.pipe(
Stream.decodeText(),
Stream.runForEach((chunk) =>
Effect.sync(() => {
output = `${output}${chunk}`.slice(-limit)
}),
),
)
return output
})
}
function processError(operation: string, command: ReadonlyArray<string>, cause: unknown) {
return new ProcessError({
operation,
command: [...command],
message: cause instanceof Error ? cause.message : String(cause),
})
}
export type Requirements = Scope.Scope | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
export * as Process from "./process.js"
+68
View File
@@ -0,0 +1,68 @@
import * as Effect from "effect/Effect"
import * as Schedule from "effect/Schedule"
import type * as Process from "./process.js"
import { instanceError, type OpenCodeInstanceError } from "./error.js"
/** Allocates a free localhost port by briefly binding an ephemeral server. */
export const freePort = Effect.tryPromise({
try: async () => {
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch: () => new Response(),
})
const port = server.port
await server.stop(true)
if (port === undefined) throw new Error("ephemeral server did not expose a port")
return port
},
catch: (cause) => instanceError("allocate port", cause),
})
/**
* Polls a WebSocket endpoint until it accepts connections, failing early when
* the owning process exits or the timeout elapses.
*/
export const waitForWebSocket = Effect.fn("OpenCodeInstance.waitForWebSocket")(
(url: string, process: Process.Running, timeout: number) =>
Effect.raceFirst(
open(url).pipe(Effect.retry(Schedule.spaced(50))),
process.exitCode.pipe(
Effect.flatMap((status) =>
Effect.fail(
instanceError("wait for endpoint", `OpenCode exited with status ${status} before ${url} became ready`),
),
),
),
).pipe(
Effect.timeoutOrElse({
duration: timeout,
orElse: () => Effect.fail(instanceError("wait for endpoint", `timed out waiting for drive endpoint ${url}`)),
}),
),
)
const open = (url: string) =>
Effect.callback<void, OpenCodeInstanceError>((resume) => {
const socket = new WebSocket(url)
const onOpen = () => {
cleanup()
socket.terminate()
resume(Effect.void)
}
const onError = () => {
cleanup()
socket.terminate()
resume(Effect.fail(instanceError("connect", `cannot connect to ${url}`)))
}
const cleanup = () => {
socket.removeEventListener("open", onOpen)
socket.removeEventListener("error", onError)
}
socket.addEventListener("open", onOpen)
socket.addEventListener("error", onError)
return Effect.sync(() => {
cleanup()
socket.terminate()
})
})
+317
View File
@@ -0,0 +1,317 @@
import { mkdir, open, readdir, rename, rm } from "node:fs/promises"
import { homedir } from "node:os"
import { basename, join } from "node:path"
export interface InstanceManifest {
readonly version: 1
readonly name: string
readonly pid: number
readonly startedAt: string
readonly cwd: string
readonly artifacts: string
readonly visible: boolean
readonly status: "starting" | "ready"
readonly endpoints: { readonly ui: string; readonly backend: string }
readonly control: string
}
export interface InitializedManifest {
readonly version: 1
readonly name: string
readonly createdAt: string
readonly cwd: string
readonly artifacts: string
readonly status: "initialized"
readonly temporary?: boolean
readonly pid?: number
}
export type Manifest = InstanceManifest | InitializedManifest
export function registryDirectory() {
return (
process.env.DRIVE_REGISTRY_DIR ??
join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "opencode-drive", "instances")
)
}
export function manifestPath(name: string) {
return join(registryDirectory(), `${validateName(name)}.json`)
}
export function controlPath(name: string) {
return join(registryDirectory(), `${validateName(name)}.sock`)
}
export async function initializeManifest(
name: string,
cwd: string,
create: () => Promise<string>,
options: {
readonly temporary?: boolean
readonly adoptPid?: number
} = {},
) {
let initialized: InitializedManifest | undefined
await withLock(name, false, async () => {
let existing = await read(manifestPath(name))
if (existing?.status === "initialized") {
if (options.temporary && options.adoptPid !== undefined && existing.pid === options.adoptPid) {
initialized = { ...existing, pid: process.pid }
await write(initialized)
return
}
if (!keepInitialized(existing)) {
await Promise.all([rm(manifestPath(name), { force: true }), rm(controlPath(name), { force: true })])
existing = undefined
} else {
let available = existing
if (existing.pid !== undefined && existing.pid !== process.pid) {
if (isProcessAlive(existing.pid)) throw new Error(`drive instance "${name}" is already starting`)
const { pid: _, ...released } = existing
available = released
}
if (options.temporary && available.pid === undefined) {
initialized = { ...available, pid: process.pid }
} else {
initialized = available
}
if (initialized !== existing) await write(initialized)
return
}
}
if (existing && isProcessAlive(existing.pid)) throw new Error(`drive instance "${name}" is already running`)
initialized = {
version: 1,
name,
createdAt: new Date().toISOString(),
cwd,
artifacts: await create(),
status: "initialized",
...(options.temporary ? { temporary: true, pid: process.pid } : {}),
}
await Promise.all([rm(manifestPath(name), { force: true }), rm(controlPath(name), { force: true })])
await write(initialized)
})
if (!initialized) throw new Error(`failed to initialize drive instance "${name}"`)
return initialized
}
export async function register(manifest: InstanceManifest) {
if (manifest.visible) {
const visible = (await listInstances()).find((instance) => instance.visible)
if (visible) throw new Error(`visible drive instance "${visible.name}" is already running`)
}
await withLock(manifest.name, false, async () => {
const existing = await read(manifestPath(manifest.name))
if (existing?.status === "initialized" && existing.pid !== undefined && existing.pid !== manifest.pid)
throw new Error(`drive instance "${manifest.name}" changed ownership`)
if (existing && existing.status !== "initialized" && isProcessAlive(existing.pid))
throw new Error(`drive instance "${manifest.name}" is already running`)
await Promise.all([
rm(manifestPath(manifest.name), { force: true }),
rm(controlPath(manifest.name), { force: true }),
])
await write(manifest)
})
}
export async function markReady(name: string, pid: number) {
await markStatus(name, pid, "ready")
}
export async function markStarting(name: string, pid: number) {
await markStatus(name, pid, "starting")
}
async function markStatus(name: string, pid: number, status: InstanceManifest["status"]) {
await withLock(name, true, async () => {
const manifest = await read(manifestPath(name))
if (!manifest || manifest.status === "initialized" || manifest.pid !== pid)
throw new Error(`drive instance "${name}" changed ownership`)
await write({ ...manifest, status })
})
}
export async function resolveInstance(name?: string, options: { readonly ready?: boolean } = {}) {
const instances = await listInstances()
const manifest = name ? instances.find((item) => item.name === name) : instances.find((item) => item.visible)
if (!manifest) {
if (!name && instances.length > 0)
throw new Error(
`no visible drive instance is running; pass --name (${instances.map((item) => item.name).join(", ")})`,
)
throw new Error(name ? `drive instance "${name}" was not found` : "no drive instances are running")
}
if (options.ready !== false && manifest.status !== "ready")
throw new Error(`drive instance "${manifest.name}" is still starting`)
return manifest
}
export async function resolveVisibleInstance(options: { readonly ready?: boolean } = {}) {
const manifest = (await listInstances()).find((instance) => instance.visible)
if (manifest && options.ready !== false && manifest.status !== "ready")
throw new Error(`drive instance "${manifest.name}" is still starting`)
return manifest
}
export async function listInstances() {
return (await listManifests()).filter((manifest): manifest is InstanceManifest => manifest.status !== "initialized")
}
export async function listManifests() {
await mkdir(registryDirectory(), { recursive: true })
const files = await readdir(registryDirectory())
const manifests = await Promise.all(
files
.filter((file) => file.endsWith(".json"))
.map(async (file) => {
const name = basename(file, ".json")
if (!isValidName(name)) {
await rm(join(registryDirectory(), file), { force: true })
return undefined
}
const manifest = await read(join(registryDirectory(), file))
if (manifest?.name === name) {
if (manifest.status === "initialized" && keepInitialized(manifest)) return manifest
if (manifest.status !== "initialized" && isProcessAlive(manifest.pid)) return manifest
}
await prune(name, manifest?.status === "initialized" ? undefined : manifest?.pid)
return undefined
}),
)
const active = manifests.filter((manifest): manifest is Manifest => manifest !== undefined)
const names = new Set(active.map((manifest) => manifest.name))
await Promise.all(
files
.filter((file) => file.endsWith(".sock"))
.flatMap((file) => {
const name = basename(file, ".sock")
if (!isValidName(name)) return [rm(join(registryDirectory(), file), { force: true })]
if (!names.has(name)) return [prune(name)]
return []
}),
)
return active.sort((a, b) => a.name.localeCompare(b.name))
}
export async function unregister(name: string, pid: number) {
await withLock(name, true, async () => {
const manifest = await read(manifestPath(name))
if (!manifest || manifest.status === "initialized" || manifest.pid !== pid) return
await Promise.all([rm(manifestPath(name), { force: true }), rm(controlPath(name), { force: true })])
})
}
async function prune(name: string, pid?: number) {
await withLock(name, true, async () => {
const manifest = await read(manifestPath(name))
if (manifest?.status === "initialized") {
if (keepInitialized(manifest)) return
await Promise.all([rm(manifestPath(name), { force: true }), rm(controlPath(name), { force: true })])
return
}
if (manifest && (manifest.pid !== pid || isProcessAlive(manifest.pid))) return
await Promise.all([rm(manifestPath(name), { force: true }), rm(controlPath(name), { force: true })])
})
}
function keepInitialized(manifest: InitializedManifest) {
if (!manifest.temporary) return !legacyVisibleInitialized(manifest.name)
return manifest.pid !== undefined && isProcessAlive(manifest.pid)
}
function legacyVisibleInitialized(name: string) {
return /^visible-\d+$/.test(name)
}
async function write(manifest: Manifest) {
const file = manifestPath(manifest.name)
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`
try {
await Bun.write(temporary, `${JSON.stringify(manifest, undefined, 2)}\n`)
await rename(temporary, file)
} finally {
await rm(temporary, { force: true })
}
}
async function read(file: string): Promise<Manifest | undefined> {
const value: unknown = await Bun.file(file)
.json()
.catch(() => undefined)
if (isManifest(value)) return value
return undefined
}
async function withLock(name: string, wait: boolean, task: () => Promise<void>) {
await mkdir(registryDirectory(), { recursive: true })
const lock = `${manifestPath(name)}.lock`
const deadline = Date.now() + 10_000
while (true) {
const handle = await open(lock, "wx").catch((error: unknown) => {
if (isNodeError(error) && error.code === "EEXIST") return undefined
throw error
})
if (handle) {
try {
await handle.writeFile(`${process.pid}\n`)
await task()
return
} finally {
await handle.close()
await rm(lock, { force: true })
}
}
if (await staleLock(lock)) {
await rm(lock, { force: true })
continue
}
if (!wait) throw new Error(`drive instance "${name}" is already starting`)
if (Date.now() >= deadline) throw new Error(`timed out updating drive instance "${name}"`)
await Bun.sleep(10)
}
}
async function staleLock(file: string) {
const pid = Number.parseInt(
await Bun.file(file)
.text()
.catch(() => ""),
10,
)
return Number.isInteger(pid) && !isProcessAlive(pid)
}
function isManifest(value: unknown): value is Manifest {
if (typeof value !== "object" || value === null) return false
const manifest = value as Partial<Manifest>
if (typeof manifest.name !== "string") return false
if (manifest.status === "initialized") return typeof manifest.artifacts === "string"
const instance = value as Partial<InstanceManifest>
const endpoints = instance.endpoints
return typeof instance.pid === "number" && typeof endpoints?.ui === "string" && typeof endpoints.backend === "string"
}
export function validateName(name: string) {
if (!isValidName(name))
throw new Error("instance names must contain 1-64 letters, numbers, dots, underscores, or dashes")
return name
}
export function isValidName(name: string) {
return /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(name)
}
export function isProcessAlive(pid: number) {
try {
process.kill(pid, 0)
return true
} catch {
return false
}
}
function isNodeError(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error
}
+531
View File
@@ -0,0 +1,531 @@
import { join, resolve } from "node:path"
import * as Config from "effect/Config"
import * as Data from "effect/Data"
import * as Effect from "effect/Effect"
import * as Exit from "effect/Exit"
import * as FileSystem from "effect/FileSystem"
import * as Ref from "effect/Ref"
import * as Semaphore from "effect/Semaphore"
import * as Scope from "effect/Scope"
import { ChildProcessSpawner } from "effect/unstable/process"
import { prepareDev } from "./dev.js"
import { instanceError, OpenCodeInstanceError } from "./error.js"
import { runMediaDirectory } from "./media.js"
import { prepareInstanceProject } from "./instance.js"
import * as Process from "./process.js"
import { freePort, waitForWebSocket } from "./readiness.js"
import { isValidName } from "./registry.js"
import { stopService } from "./service.js"
import type { RecordingPaths } from "../recording/finalize.js"
import { stripGitEnvironment } from "../script/project.js"
import * as ToolController from "../tool/controller.js"
import type * as Tool from "../tool/index.js"
import type { Frontend } from "../client/protocol.js"
import type { OpenCodeConfig, OpenCodeTuiConfig, Project, Setup } from "../project.js"
type Viewport = Frontend.ResizeParams
export { OpenCodeInstanceError } from "./error.js"
export interface Options {
readonly artifacts: string
readonly name: string
readonly command?: ReadonlyArray<string>
readonly dev?: string
readonly scripted?: boolean
readonly visible?: boolean
readonly record?: boolean
readonly viewport?: Viewport
readonly env?: Readonly<Record<string, string>>
readonly project?: Project
readonly config?: OpenCodeConfig
readonly tui?: OpenCodeTuiConfig
readonly setup?: Setup
readonly tools?: Tool.Configuration
readonly log?: (message: string) => void
}
export interface TuiProcess {
readonly endpoint: string
readonly process: Process.Running
readonly recording?: RecordingPaths
readonly close: Effect.Effect<void, OpenCodeInstanceError>
}
export interface Instance {
readonly artifacts: string
readonly logs: string
readonly visible: boolean
readonly endpoints: {
readonly ui: string
readonly backend: string
}
readonly tools: Tool.StaticControls
readonly toolNames: ReadonlySet<string>
readonly recording: Effect.Effect<RecordingPaths | undefined>
readonly primary: Effect.Effect<Process.Running, OpenCodeInstanceError>
readonly launchServer: Effect.Effect<{ readonly endpoint: string }, OpenCodeInstanceError>
readonly killServer: Effect.Effect<void, OpenCodeInstanceError>
readonly launchTui: (
name: string,
options?: { readonly record?: boolean; readonly viewport?: Viewport },
) => Effect.Effect<TuiProcess, OpenCodeInstanceError>
readonly waitForDrive: (
requirement?: "ui" | "backend" | "both",
timeout?: number,
) => Effect.Effect<void, OpenCodeInstanceError>
readonly restart: Effect.Effect<void, OpenCodeInstanceError>
readonly wait: Effect.Effect<number, OpenCodeInstanceError>
readonly stop: Effect.Effect<void, OpenCodeInstanceError>
}
interface StateFields {
readonly recording?: RecordingPaths
readonly server?: Process.Running
readonly pendingServer?: Process.Running
readonly primary?: Process.Running
readonly tuis: ReadonlyMap<string, Process.Running>
readonly pendingTuis: ReadonlyMap<string, Process.Running>
}
type State = Data.TaggedEnum<{
readonly Running: StateFields
readonly Stopping: StateFields
readonly Stopped: StateFields
}>
const State = Data.taggedEnum<State>()
export const make = Effect.fn("OpenCodeInstance.make")(function* (
options: Options,
configuredTools?: ToolController.Controller,
) {
const artifacts = resolve(options.artifacts)
const logs = join(artifacts, "logs")
const drive = join(artifacts, "drive")
const files = join(artifacts, "files")
let mediaGeneration = 0
let media = runMediaDirectory(artifacts, mediaGeneration)
const uiPort = yield* freePort
const endpoints = {
ui: `ws://127.0.0.1:${uiPort}`,
backend: `ws://127.0.0.1:${yield* distinctPort(uiPort)}`,
}
const toolController = configuredTools ?? (yield* ToolController.make(options.tools))
const database = yield* Config.string("OPENCODE_DRIVE_DB").pipe(Config.withDefault(":memory:"))
const setup =
configuredTools === undefined ? ToolController.composeSetup(toolController, options.setup) : options.setup
if (options.project !== undefined || options.config !== undefined || options.tui !== undefined || setup !== undefined)
yield* prepareInstanceProject({
artifacts,
project: options.project,
config: options.config,
tui: options.tui,
setup,
}).pipe(Effect.mapError((cause) => instanceError("prepare project", cause)))
const dev = options.dev !== undefined ? yield* prepareDev(artifacts, options.dev) : undefined
const environment = stripGitEnvironment({
...process.env,
...options.env,
BUN_OPTIONS:
dev === undefined
? (options.env?.BUN_OPTIONS ?? process.env.BUN_OPTIONS)
: [options.env?.BUN_OPTIONS ?? process.env.BUN_OPTIONS, ...dev.preloads].filter(Boolean).join(" "),
OPENCODE_SIMULATE: "1",
OPENCODE_DRIVE_SCRIPTED: options.scripted ? "1" : undefined,
DRIVE_REGISTRY_DIR: drive,
OPENCODE_DRIVE_RENDERER: options.visible ? "visible" : "headless",
OPENCODE_DRIVE_DEV: options.dev,
OPENCODE_CONFIG_DIR: join(files, ".opencode"),
OPENCODE_DB: database,
OPENCODE_LOG_LEVEL: !options.visible ? "DEBUG" : process.env.OPENCODE_LOG_LEVEL,
OPENCODE_TEST_HOME: artifacts,
XDG_CACHE_HOME: join(artifacts, "home", ".cache"),
XDG_CONFIG_HOME: join(artifacts, "home", ".config"),
XDG_DATA_HOME: logs,
XDG_STATE_HOME: join(artifacts, "home", ".local", "state"),
})
const command = dev !== undefined ? dev.command : options.command?.length ? [...options.command] : ["opencode2"]
const scriptedCommand = dev?.scriptedCommand ?? command
const initialRecording = options.record ? recordingPaths(media) : undefined
const processSpawner = yield* ChildProcessSpawner.ChildProcessSpawner
const fileSystem = yield* FileSystem.FileSystem
const state = yield* Ref.make<State>(
State.Running({
recording: initialRecording,
tuis: new Map(),
pendingTuis: new Map(),
}),
)
const lock = yield* Semaphore.make(1)
const instanceScope = yield* Scope.Scope
const writeManifest = Effect.fn("OpenCodeInstance.writeManifest")(function* (
name: string,
manifestEndpoints: { readonly ui: string; readonly backend: string },
recording?: RecordingPaths,
viewport?: Viewport,
) {
yield* Effect.tryPromise({
try: () =>
Bun.write(
join(drive, `${name}.json`),
`${JSON.stringify(
{
endpoints: manifestEndpoints,
...(viewport ? { viewport } : {}),
...(recording ? { recording: { timeline: recording.timeline } } : {}),
},
undefined,
2,
)}\n`,
),
catch: (cause) => instanceError("write manifest", cause),
})
})
const spawn = Effect.fn("OpenCodeInstance.spawn")(function* (
driveName: string,
appCommand: ReadonlyArray<string>,
logName: string,
visible: boolean,
) {
options.log?.(`launching ${logName}`)
return yield* Process.spawn(appCommand, {
cwd: files,
env: {
...environment,
OPENCODE_DRIVE: driveName,
OPENCODE_DRIVE_MEDIA_DIR: media,
},
stdin: visible ? "inherit" : "ignore",
stdout: visible ? "inherit" : { path: join(logs, `${logName}.stdout.log`) },
stderr: visible ? "inherit" : { path: join(logs, `${logName}.stderr.log`) },
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, processSpawner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Scope.provide(instanceScope),
Effect.mapError((cause) => instanceError(`launch ${logName}`, cause)),
)
})
const launchDefault = Effect.fn("OpenCodeInstance.launchDefault")(function* (recording: RecordingPaths | undefined) {
yield* writeManifest(options.name, endpoints, recording, options.viewport)
options.log?.("launching OpenCode")
return yield* spawn(options.name, command, "opencode", options.visible ?? false)
})
if (!options.scripted) {
const primary = yield* launchDefault(initialRecording)
yield* Ref.update(state, (current) => ({ ...current, primary }))
}
const launchServer = Effect.gen(function* () {
const server = yield* lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (!options.scripted)
return yield* Effect.fail(instanceError("launch server", "server launch requires scripted mode"))
if (current._tag !== "Running")
return yield* Effect.fail(instanceError("launch server", "the instance is stopping"))
if (current.server !== undefined || current.pendingServer !== undefined)
return yield* Effect.fail(instanceError("launch server", "the script server has already been launched"))
const name = processDriveName(options.name, "service")
const serverCommand = [...scriptedCommand, "serve", "--service", "--port", String(yield* freePort)]
yield* writeManifest(name, {
ui: `ws://127.0.0.1:${yield* freePort}`,
backend: endpoints.backend,
})
options.log?.("launching script server")
const server = yield* spawn(name, serverCommand, "service", false)
yield* Ref.update(state, (value) => ({ ...value, pendingServer: server }))
return server
}),
)
const removePending = lock.withPermit(
Ref.update(state, (value) => (value.pendingServer === server ? { ...value, pendingServer: undefined } : value)),
)
yield* waitForWebSocket(endpoints.backend, server, 60_000).pipe(
Effect.onError(() => removePending.pipe(Effect.andThen(server.terminate), Effect.ignore)),
Effect.mapError((cause) => instanceError("wait for server", cause)),
)
const committed = yield* lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (current._tag !== "Running" || current.pendingServer !== server) return false
yield* Ref.set(state, {
...current,
pendingServer: undefined,
server,
primary: server,
})
return true
}),
)
if (!committed) {
yield* server.terminate.pipe(Effect.ignore)
return yield* Effect.fail(instanceError("launch server", "the instance is stopping"))
}
yield* server.exitCode.pipe(
Effect.ignore,
Effect.andThen(Ref.update(state, (value) => (value.server === server ? { ...value, server: undefined } : value))),
Effect.forkIn(instanceScope),
)
options.log?.("script server ready")
return { endpoint: endpoints.backend }
})
const killServer = lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (!options.scripted)
return yield* Effect.fail(instanceError("kill server", "server kill requires scripted mode"))
if (current.server === undefined)
return yield* Effect.fail(instanceError("kill server", "the script server is not running"))
options.log?.("stopping script server")
yield* current.server.terminate.pipe(Effect.mapError((cause) => instanceError("kill server", cause)))
yield* Ref.update(state, (value) => ({
...value,
server: undefined,
primary: value.primary === current.server ? undefined : value.primary,
}))
return undefined
}),
)
const launchTui = Effect.fn("OpenCodeInstance.launchTui")(function* (
name: string,
tuiOptions: { readonly record?: boolean; readonly viewport?: Viewport } = {},
) {
const pending = yield* lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (!options.scripted)
return yield* Effect.fail(instanceError("launch TUI", "TUI launch requires scripted mode"))
if (current._tag !== "Running")
return yield* Effect.fail(instanceError("launch TUI", "the instance is stopping"))
if (current.server === undefined)
return yield* Effect.fail(instanceError("launch TUI", "launch the script server before launching TUIs"))
if (!isValidName(name)) return yield* Effect.fail(instanceError("launch TUI", `invalid TUI name: ${name}`))
if (current.tuis.has(name) || current.pendingTuis.has(name))
return yield* Effect.fail(instanceError("launch TUI", `TUI "${name}" is already running`))
if (options.visible && current.tuis.size + current.pendingTuis.size > 0)
return yield* Effect.fail(instanceError("launch TUI", "multiple TUIs require headless scripted mode"))
const primary = current.tuis.size + current.pendingTuis.size === 0
const tuiEndpoints = {
ui: primary ? endpoints.ui : `ws://127.0.0.1:${yield* freePort}`,
backend: endpoints.backend,
}
const driveName = processDriveName(options.name, `tui-${name}`)
const recording = tuiOptions.record ? recordingPaths(media) : primary ? current.recording : undefined
yield* writeManifest(driveName, tuiEndpoints, recording, tuiOptions.viewport ?? options.viewport)
options.log?.(`launching TUI ${name}`)
const tui = yield* spawn(driveName, scriptedCommand, `tui-${name}`, options.visible ?? false)
yield* Ref.update(state, (value) => ({
...value,
pendingTuis: new Map(value.pendingTuis).set(name, tui),
}))
return { tui, tuiEndpoints, primary, recording }
}),
)
const { tui, tuiEndpoints, primary, recording } = pending
const removePending = lock.withPermit(
Ref.update(state, (value) => {
if (value.pendingTuis.get(name) !== tui) return value
const pendingTuis = new Map(value.pendingTuis)
pendingTuis.delete(name)
return { ...value, pendingTuis }
}),
)
yield* waitForWebSocket(tuiEndpoints.ui, tui, 60_000).pipe(
Effect.onError(() => removePending.pipe(Effect.andThen(tui.terminate), Effect.ignore)),
Effect.mapError((cause) => instanceError("wait for TUI", cause)),
)
const committed = yield* lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (current._tag !== "Running" || current.pendingTuis.get(name) !== tui) return false
const pendingTuis = new Map(current.pendingTuis)
pendingTuis.delete(name)
yield* Ref.set(state, {
...current,
primary: primary ? tui : current.primary,
tuis: new Map(current.tuis).set(name, tui),
pendingTuis,
})
return true
}),
)
if (!committed) {
yield* tui.terminate.pipe(Effect.ignore)
return yield* Effect.fail(instanceError("launch TUI", "the instance is stopping"))
}
yield* tui.exitCode.pipe(
Effect.ignore,
Effect.andThen(
Ref.update(state, (value) => {
if (value.tuis.get(name) !== tui) return value
const tuis = new Map(value.tuis)
tuis.delete(name)
return { ...value, tuis }
}),
),
Effect.forkIn(instanceScope),
)
options.log?.(`TUI ${name} ready`)
const close = Effect.gen(function* () {
yield* Ref.update(state, (value) => {
if (value.tuis.get(name) !== tui) return value
const tuis = new Map(value.tuis)
tuis.delete(name)
return { ...value, tuis }
})
yield* tui.terminate.pipe(Effect.mapError((cause) => instanceError("close TUI", cause)))
})
return {
endpoint: tuiEndpoints.ui,
process: tui,
recording,
close,
} satisfies TuiProcess
})
const waitForDrive = Effect.fn("OpenCodeInstance.waitForDrive")(function* (
requirement: "ui" | "backend" | "both" = "both",
timeout = 60_000,
) {
const current = yield* Ref.get(state)
const process = current.primary
if (process === undefined)
return yield* Effect.fail(instanceError("wait for drive", "no OpenCode process has been launched"))
const urls = requirement === "both" ? [endpoints.ui, endpoints.backend] : [endpoints[requirement]]
yield* Effect.forEach(urls, (url) => waitForWebSocket(url, process, timeout), {
concurrency: "unbounded",
discard: true,
}).pipe(Effect.mapError((cause) => instanceError("wait for drive", cause)))
return undefined
})
const restart = lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (current._tag !== "Running") return yield* Effect.fail(instanceError("restart", "the instance is stopping"))
options.log?.("restarting OpenCode")
const processes = new Set([...current.tuis.values(), ...current.pendingTuis.values()])
if (current.server !== undefined) processes.add(current.server)
if (current.pendingServer !== undefined) processes.add(current.pendingServer)
if (!options.scripted && current.primary !== undefined) processes.add(current.primary)
const exits = yield* Effect.forEach(processes, (process) => Effect.exit(process.terminate), {
concurrency: "unbounded",
})
const combined = Exit.asVoidAll(exits)
if (Exit.isFailure(combined))
return yield* Effect.failCause(combined.cause).pipe(Effect.mapError((cause) => instanceError("restart", cause)))
media = runMediaDirectory(artifacts, ++mediaGeneration)
const recording = options.record ? recordingPaths(media) : undefined
yield* Ref.set(
state,
State.Running({
recording,
tuis: new Map(),
pendingTuis: new Map(),
}),
)
if (!options.scripted) {
const primary = yield* launchDefault(recording)
yield* Ref.update(state, (value) => ({ ...value, primary }))
yield* waitForDrive("both")
options.log?.("OpenCode ready")
}
return undefined
}),
)
const wait: Effect.Effect<number, OpenCodeInstanceError> = Effect.suspend(() =>
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (current.primary === undefined)
return yield* Effect.fail(instanceError("wait", "no OpenCode process has been launched"))
const active = current.primary
const status = yield* active.exitCode.pipe(Effect.mapError((cause) => instanceError("wait", cause)))
const next = yield* Ref.get(state)
if (next.primary !== active && next._tag === "Running") return yield* wait
return status
}),
)
const stop = lock.withPermit(
Effect.gen(function* () {
const current = yield* Ref.get(state)
if (current._tag === "Stopped") return undefined
yield* Ref.set(state, State.Stopping(current))
options.log?.("stopping OpenCode")
const processes = new Set(current.tuis.values())
for (const process of current.pendingTuis.values()) processes.add(process)
if (current.server !== undefined) processes.add(current.server)
if (current.pendingServer !== undefined) processes.add(current.pendingServer)
if (!options.scripted && current.primary !== undefined) processes.add(current.primary)
const exits = yield* Effect.forEach(processes, (process) => Effect.exit(process.terminate), {
concurrency: "unbounded",
})
const serviceExit = yield* Effect.exit(stopService(join(artifacts, "home", ".local", "state")))
yield* Ref.set(
state,
State.Stopped({
recording: current.recording,
tuis: new Map(),
pendingTuis: new Map(),
}),
)
const combined = Exit.asVoidAll([...exits, serviceExit])
if (Exit.isFailure(combined))
return yield* Effect.failCause(combined.cause).pipe(Effect.mapError((cause) => instanceError("stop", cause)))
return undefined
}),
)
yield* Effect.addFinalizer(() =>
stop.pipe(Effect.catchCause((cause) => Effect.logError("OpenCode instance cleanup failed", cause))),
)
return {
artifacts,
logs,
visible: options.visible ?? false,
endpoints,
tools: toolController.controls,
toolNames: toolController.names,
recording: Ref.get(state).pipe(Effect.map((current) => current.recording)),
primary: Ref.get(state).pipe(
Effect.flatMap((current) =>
current.primary === undefined
? Effect.fail(instanceError("primary", "no OpenCode process has been launched"))
: Effect.succeed(current.primary),
),
),
launchServer,
killServer,
launchTui,
waitForDrive,
restart,
wait,
stop,
} satisfies Instance
})
function processDriveName(instance: string, role: string) {
const suffix = crypto.randomUUID().slice(0, 8)
return `${instance.slice(0, 36)}-${role.slice(0, 17)}-${suffix}`
}
function recordingPaths(directory: string): RecordingPaths {
const id = crypto.randomUUID()
return {
timeline: join(directory, `recording-${id}.jsonl`),
video: join(directory, `recording-${id}.mp4`),
}
}
export * as OpenCodeInstance from "./runtime.js"
const distinctPort = (excluded: number): Effect.Effect<number, OpenCodeInstanceError> =>
freePort.pipe(Effect.flatMap((port) => (port === excluded ? distinctPort(excluded) : Effect.succeed(port))))
+53
View File
@@ -0,0 +1,53 @@
import { join } from "node:path"
import * as Effect from "effect/Effect"
import * as Schedule from "effect/Schedule"
import { instanceError } from "./error.js"
import { isProcessAlive } from "./registry.js"
/**
* Terminates any OpenCode managed services discovered through the instance's
* private state directory, escalating from SIGTERM to SIGKILL.
*/
export const stopService = Effect.fn("OpenCodeInstance.stopService")(function* (state: string) {
const files = [
join(state, "opencode", "server.json"),
join(state, "opencode", "service-local.json"),
join(state, "opencode", "service.json"),
]
const info = yield* Effect.tryPromise({
try: () =>
Promise.all(
files.map((file) =>
Bun.file(file)
.json()
.catch(() => undefined),
),
),
catch: (cause) => instanceError("read service state", cause),
})
yield* Effect.forEach(
info,
(value) => {
if (!isServiceInfo(value)) return Effect.void
return Effect.gen(function* () {
yield* Effect.sync(() => {
try {
process.kill(value.pid, "SIGTERM")
} catch {
return
}
})
yield* Effect.suspend(() => (isProcessAlive(value.pid) ? Effect.fail(undefined) : Effect.void)).pipe(
Effect.retry(Schedule.spaced(25).pipe(Schedule.upTo({ times: 39 }))),
Effect.catch(() => Effect.void),
)
if (isProcessAlive(value.pid)) yield* Effect.sync(() => process.kill(value.pid, "SIGKILL"))
})
},
{ concurrency: "unbounded", discard: true },
)
})
function isServiceInfo(value: unknown): value is { readonly pid: number } {
return typeof value === "object" && value !== null && "pid" in value && typeof value.pid === "number"
}
+100
View File
@@ -0,0 +1,100 @@
import * as Schema from "effect/Schema"
const NonNegativeMilliseconds = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))
const PositiveInteger = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))
const NonNegativeInteger = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
export const StreamOptions = Schema.Struct({
delay: Schema.optionalKey(NonNegativeMilliseconds),
chunkSize: Schema.optionalKey(PositiveInteger),
})
export interface StreamOptions extends Schema.Schema.Type<typeof StreamOptions> {}
export const Text = Schema.Struct({
type: Schema.Literal("text"),
text: Schema.String,
options: Schema.optionalKey(StreamOptions),
})
export interface Text extends Schema.Schema.Type<typeof Text> {}
export const Reasoning = Schema.Struct({
type: Schema.Literal("reasoning"),
text: Schema.String,
options: Schema.optionalKey(StreamOptions),
})
export interface Reasoning extends Schema.Schema.Type<typeof Reasoning> {}
export const Pause = Schema.Struct({
type: Schema.Literal("pause"),
milliseconds: NonNegativeMilliseconds,
})
export interface Pause extends Schema.Schema.Type<typeof Pause> {}
export const ToolCall = Schema.Struct({
type: Schema.Literal("toolCall"),
index: NonNegativeInteger,
id: Schema.String,
name: Schema.String,
input: Schema.Json,
options: Schema.optionalKey(StreamOptions),
})
export interface ToolCall extends Schema.Schema.Type<typeof ToolCall> {}
export type ToolCallInput = Omit<ToolCall, "type" | "options">
export const Raw = Schema.Struct({
type: Schema.Literal("raw"),
chunk: Schema.Json,
})
export interface Raw extends Schema.Schema.Type<typeof Raw> {}
export const FinishReason = Schema.Literals(["stop", "tool-calls", "length", "content-filter"])
export type FinishReason = Schema.Schema.Type<typeof FinishReason>
export const Finish = Schema.Struct({
type: Schema.Literal("finish"),
reason: Schema.optionalKey(FinishReason),
})
export interface Finish extends Schema.Schema.Type<typeof Finish> {}
export const Disconnect = Schema.Struct({
type: Schema.Literal("disconnect"),
})
export interface Disconnect extends Schema.Schema.Type<typeof Disconnect> {}
export const Output = Schema.Union([Text, Reasoning, Pause, ToolCall, Raw, Finish, Disconnect])
export type Output = Schema.Schema.Type<typeof Output>
export const text = (text: string, options?: StreamOptions): Text =>
Text.make({
type: "text",
text,
...(options === undefined ? {} : { options }),
})
export const reasoning = (text: string, options?: StreamOptions): Reasoning =>
Reasoning.make({
type: "reasoning",
text,
...(options === undefined ? {} : { options }),
})
export const pause = (milliseconds: number): Pause => Pause.make({ type: "pause", milliseconds })
export const toolCall = (call: ToolCallInput, options?: StreamOptions): ToolCall =>
ToolCall.make({
...call,
type: "toolCall",
...(options === undefined ? {} : { options }),
})
export const raw = (chunk: Schema.Json): Raw => Raw.make({ type: "raw", chunk })
export const finish = (reason?: FinishReason): Finish =>
Finish.make({
type: "finish",
...(reason === undefined ? {} : { reason }),
})
export const disconnect = (): Disconnect => Disconnect.make({ type: "disconnect" })
+40
View File
@@ -0,0 +1,40 @@
export function isTitleRequest(body: unknown) {
if (!isRecord(body) || !Array.isArray(body.messages)) return false
const first = body.messages.find(isMessageObject)
const firstContent = messageContent(first)
if (first?.role === "user" && firstContent?.startsWith("Generate a title for this conversation:")) return true
const system = body.messages.find((message) => isMessageObject(message) && message.role === "system")
return messageContent(system)?.startsWith("You are a title generator.") ?? false
}
export function* chunkText(text: string, chunkSize: number) {
const characters = Array.from(text)
for (let index = 0; index < characters.length; ) {
const size = Math.max(1, chunkSize + Math.floor(Math.random() * 11) - 5)
const end = Math.min(characters.length, index + size)
yield characters.slice(index, end).join("")
index = end
}
}
function isMessageObject(value: unknown) {
return isRecord(value) && typeof value.role === "string"
}
function messageContent(message: unknown): string | undefined {
if (!isRecord(message)) return undefined
const content = message.content
if (typeof content === "string") return content
if (!Array.isArray(content)) return undefined
return content
.map((part) => {
if (typeof part === "string") return part
if (isRecord(part) && typeof part.text === "string") return part.text
return ""
})
.join("")
}
function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
+72
View File
@@ -0,0 +1,72 @@
import { appendFileSync, mkdirSync } from "node:fs"
import { readdir } from "node:fs/promises"
import { dirname, join } from "node:path"
const prefix = "opencode-drive"
let currentLogFile = process.env.OPENCODE_DRIVE_LOG
export function driveLogFile(artifacts: string) {
return join(artifacts, "logs", "opencode-drive.log")
}
export async function opencodeLogFile(artifacts: string) {
const directory = join(artifacts, "logs", "opencode", "log")
const pattern = join(directory, "opencode*.log")
try {
const matches = (await readdir(directory))
.filter((entry) => /^opencode.*\.log$/.test(entry))
.sort()
.map((entry) => join(directory, entry))
return matches.at(-1) ?? pattern
} catch {
return pattern
}
}
export async function logReadyPaths(artifacts: string, options?: { readonly terminal?: boolean }) {
logSuccess(`opencode instance logs: ${await opencodeLogFile(artifacts)}`, options)
logSuccess(`current run script logs: ${driveLogFile(artifacts)}`, options)
}
export function configureLogFile(artifacts: string) {
currentLogFile = driveLogFile(artifacts)
process.env.OPENCODE_DRIVE_LOG = currentLogFile
return currentLogFile
}
export function logSuccess(message: string, options: { readonly terminal?: boolean } = {}) {
const line = `${prefix}: ${message}`
if (options.terminal !== false) console.error(process.stderr.isTTY ? `\x1b[32m${line}\x1b[0m` : line)
append("INFO", message)
}
export function logError(message: string) {
const line = `error: ${message}`
console.error(process.stderr.isTTY ? `\x1b[31m${line}\x1b[0m` : line)
append("ERROR", message)
appendOwner(message)
}
function appendOwner(message: string) {
const ownerLog = process.env.OPENCODE_DRIVE_OWNER_LOG
if (!ownerLog) return
appendBestEffort(ownerLog, `${message}\n`)
}
export function recordLog(level: "INFO" | "ERROR", message: string) {
append(level, message)
}
function append(level: "INFO" | "ERROR", message: string) {
if (!currentLogFile) return
appendBestEffort(currentLogFile, `[${new Date().toISOString()}] ${level} ${message}\n`)
}
function appendBestEffort(path: string, contents: string) {
try {
mkdirSync(dirname(path), { recursive: true })
appendFileSync(path, contents)
} catch {
// Logging must not change CLI behavior.
}
}
+46
View File
@@ -0,0 +1,46 @@
import type * as Effect from "effect/Effect"
import * as Schema from "effect/Schema"
export type JsonValue =
| null
| boolean
| number
| string
| ReadonlyArray<JsonValue>
| { readonly [key: string]: JsonValue }
export type JsonObject = { [key: string]: JsonValue }
/** OpenCode's semantic project configuration, written to opencode.jsonc. */
export interface OpenCodeConfig extends JsonObject {}
/** OpenCode's semantic TUI configuration, written to tui.jsonc. */
export interface OpenCodeTuiConfig extends JsonObject {}
export class FileSystemError extends Schema.TaggedErrorClass<FileSystemError>()("FileSystemError", {
path: Schema.String,
cause: Schema.Defect(),
message: Schema.String,
}) {}
export interface ProjectFileSystem {
/** Writes inside the isolated project and creates parent directories. */
writeFile(path: string, contents: string | Uint8Array): Effect.Effect<void, FileSystemError>
}
export interface SetupContext {
readonly fs: ProjectFileSystem
/** The current OpenCode config object. Mutate it to customize the run. */
readonly config: OpenCodeConfig
/** The current OpenCode TUI config object. Mutate it to customize the run. */
readonly tuiConfig: OpenCodeTuiConfig
}
export interface Project {
/** Files written into the isolated project before setup runs. */
readonly files?: Readonly<Record<string, string | Uint8Array>>
/** Initializes the project as a Git repository and commits its pre-launch state. */
readonly git?: boolean
}
export type Setup = (context: SetupContext) => Effect.Effect<void, unknown>
+109
View File
@@ -0,0 +1,109 @@
import { createReadStream } from "node:fs"
import type { TimelineHeader, TimelineOutput, TimelineRecord, TimelineResize } from "./types.js"
function fail(line: number, message: string): never {
throw new Error(`Invalid recording timeline at line ${line}: ${message}`)
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
function hasExactKeys(value: Record<string, unknown>, expected: string[]) {
const actual = Object.keys(value).sort()
return actual.length === expected.length && actual.every((key, index) => key === expected[index])
}
function positiveInteger(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
}
function nonnegativeInteger(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0
}
function canonicalBase64(value: string) {
if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
return false
}
return Buffer.from(value, "base64").toString("base64") === value
}
function parseRecord(text: string, line: number, first: boolean, previousAt: number): TimelineRecord {
let value: unknown
try {
value = JSON.parse(text)
} catch {
fail(line, "line is not valid JSON")
}
if (!isObject(value)) fail(line, "record must be an object")
if (first) {
if (!hasExactKeys(value, ["cols", "encoding", "rows", "type", "version"])) fail(line, "invalid header fields")
if (value.type !== "header" || value.version !== 1 || value.encoding !== "base64") {
fail(line, "unsupported or missing header")
}
if (!positiveInteger(value.cols) || !positiveInteger(value.rows))
fail(line, "cols and rows must be positive integers")
return {
type: "header",
version: 1,
cols: value.cols,
rows: value.rows,
encoding: "base64",
} satisfies TimelineHeader
}
if (!nonnegativeInteger(value.at_ms)) fail(line, "at_ms must be a nonnegative integer")
if (value.at_ms < previousAt) fail(line, "event timestamps must be nondecreasing")
if (value.type === "output") {
if (!hasExactKeys(value, ["at_ms", "data", "type"])) fail(line, "invalid output fields")
if (typeof value.data !== "string" || !canonicalBase64(value.data)) fail(line, "data must be canonical base64")
return { type: "output", at_ms: value.at_ms, data: value.data } satisfies TimelineOutput
}
if (value.type === "resize") {
if (!hasExactKeys(value, ["at_ms", "cols", "rows", "type"])) fail(line, "invalid resize fields")
if (!positiveInteger(value.cols) || !positiveInteger(value.rows))
fail(line, "cols and rows must be positive integers")
return { type: "resize", at_ms: value.at_ms, cols: value.cols, rows: value.rows } satisfies TimelineResize
}
return fail(line, "invalid event type")
}
/** Decodes and validates a timeline without loading the complete file into memory. */
export async function* decodeTimeline(path: string): AsyncGenerator<TimelineRecord> {
const decoder = new TextDecoder("utf-8", { fatal: true })
let buffered = ""
let line = 0
let records = 0
let previousAt = -1
const consume = (raw: string) => {
line++
const text = raw.endsWith("\r") ? raw.slice(0, -1) : raw
if (text.length === 0) fail(line, "empty lines are not allowed")
const record = parseRecord(text, line, records === 0, previousAt)
records++
if (record.type !== "header") previousAt = record.at_ms
return record
}
try {
for await (const chunk of createReadStream(path)) {
buffered += decoder.decode(chunk, { stream: true })
let newline: number
while ((newline = buffered.indexOf("\n")) !== -1) {
const raw = buffered.slice(0, newline)
buffered = buffered.slice(newline + 1)
yield consume(raw)
}
}
buffered += decoder.decode()
} catch (error) {
if (error instanceof TypeError) fail(line + 1, "file is not valid UTF-8")
throw error
}
if (buffered.length > 0) yield consume(buffered)
if (records === 0) fail(1, "missing header")
}
+98
View File
@@ -0,0 +1,98 @@
import { createHash } from "node:crypto"
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { dirname, join } from "node:path"
import { runFfmpeg } from "./ffmpeg.js"
import { resolveFps } from "./frame-rate.js"
export interface ImageFrame {
readonly atMs: number
readonly key: string
readonly render: () => Buffer | Promise<Buffer>
}
export interface EncodeOptions {
readonly ffmpegPath?: string
readonly fps?: number
readonly onProgress?: (percent: number) => void
readonly signal?: AbortSignal
}
export async function encodeFrames(frames: ReadonlyArray<ImageFrame>, output: string, options: EncodeOptions = {}) {
const final = frames.at(-1)
if (!final) throw new Error("recording has no frames")
const fps = resolveFps(options.fps)
const frameIntervalMs = 1000 / fps
await mkdir(dirname(output), { recursive: true })
const directory = await mkdtemp(join(tmpdir(), "opencode-drive-recording-"))
const progress = progressReporter(options.onProgress)
try {
const unique = new Map<string, string>()
const renderedFrames: string[] = []
for (const [index, frame] of frames.entries()) {
options.signal?.throwIfAborted()
let rendered = unique.get(frame.key)
if (!rendered) {
const hash = createHash("sha256").update(frame.key).digest("hex")
rendered = `unique-${hash}.png`
await writeFile(join(directory, rendered), await frame.render(), { signal: options.signal })
unique.set(frame.key, rendered)
}
renderedFrames.push(rendered)
progress(((index + 1) / frames.length) * 90)
}
const concat = join(directory, "frames.ffconcat")
const firstAtMs = frames[0]!.atMs
const lastFrameIndex = Math.max(0, Math.ceil((final.atMs - firstAtMs) / frameIntervalMs - 1e-9))
const entries: string[] = []
let sourceIndex = 0
for (let index = 0; index <= lastFrameIndex; index++) {
const atMs = firstAtMs + index * frameIntervalMs
while (frames[sourceIndex + 1] && frames[sourceIndex + 1]!.atMs <= atMs + 1e-9) sourceIndex++
entries.push(`file ${renderedFrames[sourceIndex]!}`)
}
await writeFile(concat, `ffconcat version 1.0\n${entries.join("\n")}\n`, {
signal: options.signal,
})
await runFfmpeg(
options.ffmpegPath ?? "ffmpeg",
[
"-y",
"-r",
String(fps),
"-safe",
"0",
"-f",
"concat",
"-i",
concat,
"-c:v",
"libx264",
"-crf",
"0",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
"-fps_mode",
"cfr",
output,
],
options.signal,
)
progress(100)
} finally {
await rm(directory, { recursive: true, force: true })
}
}
function progressReporter(onProgress?: (percent: number) => void) {
let reported = 0
return (percent: number) => {
const target = Math.min(100, Math.floor(percent / 10) * 10)
while (reported < target) {
reported += 10
onProgress?.(reported)
}
}
}
+87
View File
@@ -0,0 +1,87 @@
import { createHash } from "node:crypto"
import { mkdir, writeFile } from "node:fs/promises"
import { dirname, extname } from "node:path"
import { encodeFrames } from "./encode.js"
import { replayRecording, type ReplayOptions } from "./replay.js"
import { CellHeight, CellWidth, renderFrame } from "./render.js"
export interface ExportRecordingOptions extends ReplayOptions {
ffmpegPath?: string
header?: string | ((atMs: number) => string)
onProgress?: (percent: number) => void
signal?: AbortSignal
}
export interface ExportRecordingResult {
frames: number
durationMs: number
width: number
height: number
}
export async function exportRecording(
timelinePath: string,
outputPath: string,
options: ExportRecordingOptions = {},
): Promise<ExportRecordingResult> {
options.signal?.throwIfAborted()
const frames = await replayRecording(timelinePath, options)
options.signal?.throwIfAborted()
const final = frames.at(-1)!
let cols = 0
let rows = 0
for (const sample of frames) {
cols = Math.max(cols, sample.frame.cols)
rows = Math.max(rows, sample.frame.rows)
}
const extension = extname(outputPath).toLowerCase()
const header = (atMs: number) => (typeof options.header === "function" ? options.header(atMs) : options.header)
const progress = progressReporter(options.onProgress)
await mkdir(dirname(outputPath), { recursive: true })
if (extension === ".png") {
await writeFile(outputPath, renderFrame(final.frame, { cols, rows, header: header(final.atMs) }), {
signal: options.signal,
})
progress(100)
} else if (extension === ".mp4") {
const frameKeys = new WeakMap<object, string>()
await encodeFrames(
frames.map((sample) => {
const label = header(sample.atMs)
let frameKey = frameKeys.get(sample.frame)
if (frameKey === undefined) {
frameKey = createHash("sha256").update(JSON.stringify(sample.frame)).digest("hex")
frameKeys.set(sample.frame, frameKey)
}
return {
atMs: sample.atMs,
key: JSON.stringify([frameKey, label]),
render: () => renderFrame(sample.frame, { cols, rows, header: label }),
}
}),
outputPath,
options,
)
} else {
throw new Error(`Unsupported recording output extension: ${extension || "(none)"}`)
}
return {
frames: frames.length,
durationMs: final.atMs,
width: cols * CellWidth,
height: rows * CellHeight + (options.header ? 40 : 0),
}
}
function progressReporter(onProgress?: (percent: number) => void) {
let reported = 0
return (percent: number) => {
const target = Math.min(100, Math.floor(percent / 10) * 10)
while (reported < target) {
reported += 10
onProgress?.(reported)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as Effect from "effect/Effect"
import * as Process from "../instance/process.js"
export const ffmpeg = Effect.fn("Recording.ffmpeg")(function* (command: string, args: string[]) {
const output = yield* Process.run([command, ...args], {
stdout: "ignore",
stderrLimit: 16_384,
})
if (output.status !== 0)
return yield* Effect.fail(new Error(`ffmpeg exited with code ${output.status}: ${output.stderr.trim()}`))
return undefined
})
export function runFfmpeg(command: string, args: string[], signal?: AbortSignal) {
return Effect.runPromise(ffmpeg(command, args).pipe(Effect.provide(NodeServices.layer)), { signal }).then(
() => {
if (signal?.aborted) throw signal.reason ?? new Error("recording export aborted")
},
(cause) => {
throw signal?.aborted ? (signal.reason ?? new Error("recording export aborted")) : cause
},
)
}
+14
View File
@@ -0,0 +1,14 @@
import type { ExportRecordingOptions } from "./export.js"
export interface RecordingPaths {
readonly timeline: string
readonly video: string
}
export async function finalizeRecording(timeline: string, expected: RecordingPaths, options?: ExportRecordingOptions) {
if (timeline !== expected.timeline) throw new Error(`OpenCode returned an unexpected recording path: ${timeline}`)
if (!(await Bun.file(timeline).exists())) throw new Error(`OpenCode recording timeline was not created: ${timeline}`)
const { exportRecording } = await import("./export.js")
await exportRecording(timeline, expected.video, options)
return expected.video
}
@@ -0,0 +1,6 @@
const DefaultFps = 60
export function resolveFps(fps = DefaultFps) {
if (!Number.isFinite(fps) || fps <= 0) throw new Error("fps must be a positive finite number")
return fps
}
+14
View File
@@ -0,0 +1,14 @@
export { decodeTimeline } from "./decode.js"
export { encodeFrames, type EncodeOptions, type ImageFrame } from "./encode.js"
export { exportRecording, type ExportRecordingOptions, type ExportRecordingResult } from "./export.js"
export { joinFrames, renderFrame } from "./render.js"
export { replayRecording, type ReplayOptions } from "./replay.js"
export type {
CapturedFrame,
CapturedLine,
CapturedSpan,
SampledFrame,
TimelineHeader,
TimelineOutput,
TimelineRecord,
} from "./types.js"
+143
View File
@@ -0,0 +1,143 @@
import { fileURLToPath } from "node:url"
import { GlobalFonts, createCanvas, loadImage } from "@napi-rs/canvas"
import {
CellHeight,
CellWidth,
DimAlpha,
FontSize,
StrikethroughOffset,
TextStyle,
UnderlineOffset,
baselineOffset,
drawBlockGlyph,
} from "../frame/index.js"
import type { CapturedFrame } from "./types.js"
export { CellHeight, CellWidth } from "../frame/index.js"
const FontFamily = "OpenCode Mono"
const SymbolFontFamily = "OpenCode Symbols"
const SymbolFontFamily2 = "OpenCode Symbols 2"
const MathFontFamily = "OpenCode Math"
const FontStack = `"${FontFamily}", "${SymbolFontFamily}", "${SymbolFontFamily2}", "${MathFontFamily}"`
const fontOverride = process.env["OPENCODE_DRIVE_FONT"]
const fontFiles = fontOverride
? fontOverride
.split(",")
.map((file) => file.trim())
.filter(Boolean)
: [
"CommitMono-400-Regular.otf",
"CommitMono-700-Regular.otf",
"CommitMono-400-Italic.otf",
"CommitMono-700-Italic.otf",
].map((file) => fileURLToPath(new URL(`../../assets/fonts/commit-mono/${file}`, import.meta.url)))
if (fontFiles.length === 0) throw new Error("OPENCODE_DRIVE_FONT must contain at least one font file")
for (const file of fontFiles) {
if (!GlobalFonts.registerFromPath(file, FontFamily)) throw new Error(`Failed to register capture font: ${file}`)
}
for (const [file, family] of [
["NotoSansSymbols.ttf", SymbolFontFamily],
["NotoSansSymbols2-Regular.ttf", SymbolFontFamily2],
["NotoSansMath-Regular.ttf", MathFontFamily],
] as const) {
const path = fileURLToPath(new URL(`../../assets/fonts/noto/${file}`, import.meta.url))
if (!GlobalFonts.registerFromPath(path, family)) throw new Error(`Failed to register capture symbol font: ${path}`)
}
function color(rgb: number, alpha = 1) {
return `rgba(${(rgb >> 16) & 255}, ${(rgb >> 8) & 255}, ${rgb & 255}, ${alpha})`
}
export interface RenderFrameOptions {
readonly cols?: number
readonly rows?: number
readonly header?: string
}
export function renderFrame(frame: CapturedFrame, options: RenderFrameOptions = {}): Buffer {
const cols = Math.max(frame.cols, options.cols ?? frame.cols)
const rows = Math.max(frame.rows, options.rows ?? frame.rows)
const headerHeight = options.header ? 40 : 0
const canvas = createCanvas(cols * CellWidth, rows * CellHeight + headerHeight)
const context = canvas.getContext("2d")
context.fillStyle = "#080808"
context.fillRect(0, 0, canvas.width, canvas.height)
if (options.header) {
context.fillStyle = "#151515"
context.fillRect(0, 0, canvas.width, headerHeight)
context.font = `700 ${FontSize}px ${FontStack}`
context.fillStyle = "#d8d8d8"
context.textBaseline = "middle"
context.textAlign = "left"
context.fillText(options.header, 16, headerHeight / 2, canvas.width - 32)
}
context.textBaseline = "alphabetic"
context.textAlign = "center"
frame.lines.forEach((line, row) => {
let column = 0
for (const span of line.spans) {
const inverse = Boolean(span.attributes & TextStyle.inverse)
const hidden = Boolean(span.attributes & TextStyle.invisible)
const foreground = inverse ? span.bg : span.fg
const background = inverse ? span.fg : span.bg
const y = headerHeight + row * CellHeight
context.fillStyle = color(background)
context.fillRect(column * CellWidth, y, span.width * CellWidth, CellHeight)
if (hidden) {
column += span.width
continue
}
const italic = span.attributes & TextStyle.italic ? "italic " : ""
const weight = span.attributes & TextStyle.bold ? "700 " : "400 "
const font = `${italic}${weight}${FontSize}px ${FontStack}`
context.font = font
context.fillStyle = color(foreground, span.attributes & TextStyle.dim ? DimAlpha : 1)
const baseline = baselineOffset(context, font)
let remaining = span.width
for (const char of span.text) {
const cells = Math.min(Math.max(1, Bun.stringWidth(char)), remaining)
const x = column * CellWidth
if (!drawBlockGlyph(context, char, x, y, cells))
context.fillText(char, x + (cells * CellWidth) / 2, y + baseline, cells * CellWidth)
if (span.attributes & TextStyle.underline) {
context.fillRect(x, y + UnderlineOffset, cells * CellWidth, 1)
}
if (span.attributes & TextStyle.strikethrough) {
context.fillRect(x, y + StrikethroughOffset, cells * CellWidth, 1)
}
column += cells
remaining -= cells
}
if (remaining > 0) {
column += remaining
}
}
})
if (frame.cursor.visible && frame.cursor.row >= 0 && frame.cursor.row < frame.rows) {
context.strokeStyle = "#d8d8d8"
context.lineWidth = 2
context.strokeRect(
frame.cursor.col * CellWidth + 1,
headerHeight + frame.cursor.row * CellHeight + 1,
CellWidth - 2,
CellHeight - 2,
)
}
return canvas.toBuffer("image/png")
}
export async function joinFrames(left: Buffer, right: Buffer): Promise<Buffer> {
const [leftImage, rightImage] = await Promise.all([loadImage(left), loadImage(right)])
if (leftImage.height !== rightImage.height)
throw new Error(`comparison recordings must have the same height: ${leftImage.height} !== ${rightImage.height}`)
const canvas = createCanvas(leftImage.width + rightImage.width, leftImage.height)
const context = canvas.getContext("2d")
context.drawImage(leftImage, 0, 0)
context.drawImage(rightImage, leftImage.width, 0)
return canvas.toBuffer("image/png")
}
+99
View File
@@ -0,0 +1,99 @@
import { decodeTimeline } from "./decode.js"
import { resolveFps } from "./frame-rate.js"
import { createTerminalParser, type TerminalParserFactory } from "./terminal.js"
import type { SampledFrame, TimelineHeader } from "./types.js"
export interface ReplayOptions {
fps?: number
signal?: AbortSignal
startAtMs?: number
durationMs?: number
}
interface InternalReplayOptions extends ReplayOptions {
terminalFactory?: TerminalParserFactory
}
export async function replayRecording(path: string, options: ReplayOptions = {}): Promise<SampledFrame[]> {
return replay(path, options)
}
export async function replay(path: string, options: InternalReplayOptions = {}): Promise<SampledFrame[]> {
options.signal?.throwIfAborted()
const interval = 1000 / resolveFps(options.fps)
if (options.startAtMs !== undefined && (!Number.isFinite(options.startAtMs) || options.startAtMs < 0))
throw new Error("startAtMs must be a non-negative finite number")
if (options.durationMs !== undefined && (!Number.isFinite(options.durationMs) || options.durationMs < 0))
throw new Error("durationMs must be a non-negative finite number")
const records = decodeTimeline(path)[Symbol.asyncIterator]()
const first = await records.next()
options.signal?.throwIfAborted()
if (first.done || first.value.type !== "header") throw new Error("Recording timeline is missing its header")
const header: TimelineHeader = first.value
const terminal = await (options.terminalFactory ?? createTerminalParser)(header.cols, header.rows)
options.signal?.throwIfAborted()
const frames: SampledFrame[] = []
const startAt = options.startAtMs ?? 0
const endAt = options.durationMs === undefined ? Number.POSITIVE_INFINITY : startAt + options.durationMs
let nextSample = startAt
let finalAt = 0
let snapshot: SampledFrame["frame"] | undefined
let dirty = true
const currentSnapshot = () => {
if (dirty || !snapshot) {
snapshot = terminal.snapshot()
dirty = false
}
return snapshot
}
for (;;) {
const next = await records.next()
options.signal?.throwIfAborted()
if (next.done) break
const event = next.value
if (event.type === "header") throw new Error("Recording timeline contains a second header")
if (event.at_ms > endAt) {
finalAt = endAt
break
}
while (nextSample < event.at_ms && nextSample <= endAt) {
frames.push({ atMs: nextSample, frame: currentSnapshot() })
nextSample += interval
}
if (event.type === "output") {
const data = Buffer.from(event.data, "base64")
terminal.write(data)
if (data.length > 0) dirty = true
} else {
terminal.resize(event.cols, event.rows)
dirty = true
}
finalAt = event.at_ms
}
if (terminal.finish()) dirty = true
const targetFinal = options.durationMs === undefined ? Math.max(startAt, finalAt) : endAt
while (nextSample <= targetFinal) {
frames.push({ atMs: nextSample, frame: currentSnapshot() })
nextSample += interval
}
const final = frames.at(-1)
if (final && Math.abs(final.atMs - targetFinal) < 0.000_001) {
frames[frames.length - 1] = { ...final, atMs: targetFinal }
} else {
frames.push({ atMs: targetFinal, frame: currentSnapshot() })
}
if (options.startAtMs !== undefined) {
return frames.map((sample) => ({ ...sample, atMs: sample.atMs - startAt }))
}
const firstVisible = frames.findIndex((sample) =>
sample.frame.lines.some((line) => line.spans.some((span) => span.text.trim().length > 0)),
)
if (firstVisible < 0) {
const final = frames.at(-1)
return final ? [{ ...final, atMs: 0 }] : []
}
const start = frames[firstVisible]!.atMs
return frames.slice(firstVisible).map((sample) => ({ ...sample, atMs: sample.atMs - start }))
}
+120
View File
@@ -0,0 +1,120 @@
import type { TerminalCore } from "@wterm/core"
import { GhosttyCore } from "@wterm/ghostty"
import type { CapturedFrame, CapturedSpan } from "./types.js"
const DefaultForeground = 0xd8d8d8
const DefaultBackground = 0x080808
const SyncStart = Buffer.from("\x1b[?2026h")
const SyncEnd = Buffer.from("\x1b[?2026l")
export interface TerminalParser {
write(data: Uint8Array): void
finish(): boolean
resize(cols: number, rows: number): void
snapshot(): CapturedFrame
}
export type TerminalParserFactory = (cols: number, rows: number) => Promise<TerminalParser>
function characterWidth(char: string) {
return Math.max(1, Bun.stringWidth(char))
}
function capture(core: TerminalCore): CapturedFrame {
const cols = core.getCols()
const rows = core.getRows()
const lines = Array.from({ length: rows }, (_, row) => {
const spans: CapturedSpan[] = []
for (let col = 0; col < cols; ) {
const cell = core.getCell(row, col)
const text = String.fromCodePoint(cell.char || 32)
const width = Math.min(characterWidth(text), cols - col)
const next = {
text,
width,
fg: cell.fgRgb ?? DefaultForeground,
bg: cell.bgRgb ?? DefaultBackground,
attributes: cell.flags,
}
const previous = spans.at(-1)
if (previous && previous.fg === next.fg && previous.bg === next.bg && previous.attributes === next.attributes) {
previous.text += next.text
previous.width += width
} else {
spans.push(next)
}
col += width
}
return { spans }
})
return { cols, rows, cursor: core.getCursor(), lines }
}
class GhosttyTerminal implements TerminalParser {
private synchronized = false
private stable?: CapturedFrame
private pending = Buffer.alloc(0)
constructor(private readonly core: TerminalCore) {}
write(data: Uint8Array) {
const input = this.pending.length ? Buffer.concat([this.pending, data]) : Buffer.from(data)
this.pending = Buffer.alloc(0)
let offset = 0
while (offset < input.length) {
const start = input.indexOf(SyncStart, offset)
const end = input.indexOf(SyncEnd, offset)
const marker = start === -1 ? end : end === -1 ? start : Math.min(start, end)
if (marker === -1) {
const keep = partialMarkerLength(input.subarray(offset))
const boundary = input.length - keep
if (boundary > offset) this.core.writeRaw(input.subarray(offset, boundary))
if (keep) this.pending = input.subarray(boundary)
return
}
if (marker > offset) this.core.writeRaw(input.subarray(offset, marker))
if (marker === start) {
if (!this.synchronized) this.stable = capture(this.core)
this.synchronized = true
this.core.writeRaw(SyncStart)
offset = marker + SyncStart.length
} else {
this.core.writeRaw(SyncEnd)
this.synchronized = false
this.stable = undefined
offset = marker + SyncEnd.length
}
}
}
finish() {
if (!this.pending.length) return false
this.core.writeRaw(this.pending)
this.pending = Buffer.alloc(0)
return true
}
resize(cols: number, rows: number) {
this.core.resize(cols, rows)
if (this.synchronized) this.stable = capture(this.core)
}
snapshot() {
return this.synchronized && this.stable ? structuredClone(this.stable) : capture(this.core)
}
}
function partialMarkerLength(input: Uint8Array) {
const limit = Math.min(input.length, Math.max(SyncStart.length, SyncEnd.length) - 1)
for (let length = limit; length > 0; length--) {
const suffix = input.subarray(input.length - length)
if (SyncStart.subarray(0, length).equals(suffix) || SyncEnd.subarray(0, length).equals(suffix)) return length
}
return 0
}
export const createTerminalParser: TerminalParserFactory = async (cols, rows) => {
const core: TerminalCore = await GhosttyCore.load()
core.init(cols, rows)
return new GhosttyTerminal(core)
}
+48
View File
@@ -0,0 +1,48 @@
export { TextStyle } from "../frame/index.js"
export interface CapturedSpan {
text: string
width: number
fg: number
bg: number
attributes: number
}
export interface CapturedLine {
spans: CapturedSpan[]
}
export interface CapturedFrame {
cols: number
rows: number
cursor: { row: number; col: number; visible: boolean }
lines: CapturedLine[]
}
export interface SampledFrame {
atMs: number
frame: CapturedFrame
}
export interface TimelineHeader {
type: "header"
version: 1
cols: number
rows: number
encoding: "base64"
}
export interface TimelineOutput {
type: "output"
at_ms: number
data: string
}
export interface TimelineResize {
type: "resize"
at_ms: number
cols: number
rows: number
}
export type TimelineRecord = TimelineHeader | TimelineOutput | TimelineResize
+19
View File
@@ -0,0 +1,19 @@
import { RpcClientError as RpcClientErrors } from "effect/unstable/rpc"
export const RpcClientError = RpcClientErrors.RpcClientError
export type RpcClientError = RpcClientErrors.RpcClientError
export { FileSystemError } from "../project.js"
export { OpenCodeDriverError } from "../driver/error.js"
export { LlmControllerError, LlmModeError } from "../driver/llm-controller.js"
export {
UiCapabilityError,
UiElementAmbiguousError,
UiNodeAmbiguousError,
UiPredicateError,
UiTimeoutError,
UiWaitOptionsError,
} from "../driver/ui.js"
export { SimulationCompatibilityError } from "../simulation/connector.js"
export { SimulationRequestError } from "@opencode-ai/protocol/simulation"
+97
View File
@@ -0,0 +1,97 @@
import { lstat, mkdir, writeFile } from "node:fs/promises"
import { dirname, isAbsolute, relative, resolve, sep } from "node:path"
import * as Effect from "effect/Effect"
import { FileSystemError, type ProjectFileSystem } from "../project.js"
interface FileSystemOptions {
readonly git?: boolean
}
export function createScriptFileSystem(directory: string, options: FileSystemOptions = {}): ProjectFileSystem {
const root = resolve(directory)
return {
writeFile: (path, contents) =>
Effect.tryPromise({
try: async () => {
const destination = await resolveFile(root, path, options)
await mkdir(dirname(destination), { recursive: true })
await writeFile(destination, contents)
},
catch: (cause) =>
new FileSystemError({
path,
cause,
message: cause instanceof Error ? cause.message : String(cause),
}),
}),
}
}
export async function writeScriptFiles(
directory: string,
files: Readonly<Record<string, string | Uint8Array>>,
options: FileSystemOptions = {},
) {
const root = resolve(directory)
const entries = await Promise.all(
Object.entries(files).map(async ([path, contents]) => ({
contents,
destination: await resolveFile(root, path, options),
})),
)
const destinations = new Set<string>()
for (const entry of entries) {
const destination = entry.destination.toLowerCase()
if (destinations.has(destination)) throw new Error("project.files paths must resolve to unique files")
destinations.add(destination)
}
for (const destination of destinations) {
let parent = dirname(destination)
while (parent !== dirname(parent)) {
if (destinations.has(parent)) throw new Error("project.files paths must not contain file and directory conflicts")
parent = dirname(parent)
}
}
await Promise.all(
entries.map(async ({ contents, destination }) => {
await mkdir(dirname(destination), { recursive: true })
await writeFile(destination, contents)
}),
)
}
async function resolveFile(root: string, path: string, options: FileSystemOptions) {
if (isAbsolute(path)) throw new Error("fs.writeFile path must be relative")
const destination = resolve(root, path)
const resolved = relative(root, destination)
if (resolved === "") throw new Error("fs.writeFile path must name a file")
if (resolved === ".." || resolved.startsWith(`..${sep}`))
throw new Error("fs.writeFile path must stay inside the simulated project")
if (options.git && resolved.split(sep)[0]?.toLowerCase() === ".git")
throw new Error("fs.writeFile path must not modify Git metadata")
await rejectSymlinks(root, destination)
const stats = await lstat(destination).catch((error: unknown) => {
if (isMissing(error)) return undefined
throw error
})
if (stats?.isDirectory()) throw new Error("fs.writeFile path must not be a directory")
return destination
}
async function rejectSymlinks(root: string, destination: string) {
const parts = relative(root, destination).split(sep)
let current = root
for (const part of parts) {
current = resolve(current, part)
const stats = await lstat(current).catch((error: unknown) => {
if (isMissing(error)) return undefined
throw error
})
if (stats === undefined) return
if (stats.isSymbolicLink()) throw new Error("fs.writeFile path must not contain symbolic links")
}
}
function isMissing(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error && error.code === "ENOENT"
}
+18
View File
@@ -0,0 +1,18 @@
import type {
AutomaticScriptDefinition,
ManualScriptDefinition,
ScriptDefinition,
ScriptDefinitionInput,
} from "./types.js"
type Defined<Definition> = Definition & {
readonly kind: "opencode-drive/script"
}
export function defineScript(script: ManualScriptDefinition): Defined<ManualScriptDefinition>
export function defineScript(script: AutomaticScriptDefinition): Defined<AutomaticScriptDefinition>
export function defineScript(script: ScriptDefinitionInput): ScriptDefinition {
return { ...script, kind: "opencode-drive/script" }
}
export type * from "./types.js"
+72
View File
@@ -0,0 +1,72 @@
import { lstat, readdir, rm } from "node:fs/promises"
import { join } from "node:path"
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as Effect from "effect/Effect"
import * as Process from "../instance/process.js"
import { writeScriptFiles } from "./filesystem.js"
import type { Project } from "./types.js"
export async function initializeScriptProject(root: string, project: Project) {
if (project.git) await assertGitPlaceholder(root)
await writeScriptFiles(root, project.files ?? {}, { git: true })
}
export async function commitScriptProject(root: string) {
await assertGitPlaceholder(root)
const metadata = join(root, ".git")
await rm(metadata, { recursive: true, force: true })
await git(root, ["init", "--quiet", "--initial-branch=main"])
await git(root, ["add", "--force", "--all"])
await git(root, [
"-c",
"user.name=OpenCode Drive",
"-c",
"user.email=drive@opencode.ai",
"commit",
"--quiet",
"--message=Initial commit",
])
}
async function assertGitPlaceholder(root: string) {
if (await hasGitMetadata(root)) throw new Error("project.git cannot replace existing Git metadata")
}
export async function hasGitMetadata(root: string) {
const metadata = join(root, ".git")
const stats = await lstat(metadata).catch((error: unknown) => {
if (isMissing(error)) return undefined
throw error
})
if (!stats) return false
return !stats.isDirectory() || (await readdir(metadata)).length > 0
}
async function git(cwd: string, args: ReadonlyArray<string>) {
const output = await Effect.runPromise(
Process.run(["git", ...args], {
cwd,
env: {
...stripGitEnvironment(Bun.env),
GIT_CONFIG_GLOBAL: "/dev/null",
GIT_CONFIG_NOSYSTEM: "1",
GIT_AUTHOR_DATE: "2000-01-01T00:00:00Z",
GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z",
},
}).pipe(Effect.provide(NodeServices.layer)),
)
if (output.status === 0) return
throw new Error(`git ${args[0]} failed: ${output.stderr.trim()}`)
}
export function stripGitEnvironment(env: Readonly<Record<string, string | undefined>>) {
return Object.fromEntries(
Object.entries(env).filter(
(entry): entry is [string, string] => entry[1] !== undefined && !entry[0].startsWith("GIT_"),
),
)
}
function isMissing(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && "code" in error && error.code === "ENOENT"
}
+158
View File
@@ -0,0 +1,158 @@
import { mkdir, rm, symlink } from "node:fs/promises"
import { createRequire } from "node:module"
import { dirname, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"
const packageRoot = resolve(fileURLToPath(new URL("../..", import.meta.url)))
const requireFromDrive = createRequire(join(packageRoot, "package.json"))
const effectRoot = dirname(requireFromDrive.resolve("effect/package.json"))
const compilerRoot = dirname(requireFromDrive.resolve("@typescript/native-preview/package.json"))
const bunTypesRoot = dirname(requireFromDrive.resolve("@types/bun/package.json"))
const requireFromBunTypes = createRequire(join(bunTypesRoot, "package.json"))
const bunRuntimeTypesRoot = dirname(requireFromBunTypes.resolve("bun-types/package.json"))
type Contract = "program" | "script"
export async function prepareScriptModule(artifacts: string, script: string) {
const source = await resolveSource(script, "script")
const root = await prepareRuntimeRoot(artifacts)
return compileScript(root, source)
}
export async function prepareProgram(artifacts: string, script: string) {
const source = await resolveSource(script, "program")
const root = await prepareRuntimeRoot(artifacts)
await typecheck(root, source, "program")
const program = await compileScript(root, source)
const runner = join(root, "program-runner.ts")
await Bun.write(
runner,
[
'import * as Effect from "effect/Effect"',
`import program from ${JSON.stringify(program)}`,
'if (!Effect.isEffect(program)) throw new Error("program must default-export a fully provided Effect")',
"await Effect.runPromise(program)",
"",
].join("\n"),
)
return runner
}
export async function checkScript(artifacts: string, script: string) {
const source = await resolveSource(script, "script")
const root = await prepareRuntimeRoot(artifacts)
await typecheck(root, source, "script")
}
async function resolveSource(script: string, contract: Contract) {
const source = resolve(script)
if (!(await Bun.file(source).exists())) throw new Error(`${contract} not found: ${source}`)
return source
}
async function compileScript(root: string, source: string) {
const entry = join(root, "script-entry.ts")
const output = join(root, "compiled")
await Bun.write(entry, `export { default } from ${JSON.stringify(source)}\n`)
const result = await Bun.build({
entrypoints: [entry],
outdir: output,
target: "bun",
packages: "bundle",
external: ["opencode-drive", "opencode-drive/*", "effect", "effect/*"],
sourcemap: "inline",
})
if (!result.success) {
const diagnostics = result.logs.map((log) => log.message).join("\n")
throw new Error(diagnostics || `failed to compile script: ${source}`)
}
const file = result.outputs.find((item) => item.kind === "entry-point")?.path
if (!file) throw new Error(`script compilation produced no entry point: ${source}`)
return file
}
async function typecheck(root: string, source: string, contract: Contract) {
const contractFile = join(root, `${contract}-contract.ts`)
const tsconfig = join(root, `${contract}-tsconfig.json`)
await Bun.write(
contractFile,
contract === "program"
? [
'import type * as Effect from "effect/Effect"',
`import program from ${JSON.stringify(source)}`,
"const checked: Effect.Effect<unknown, unknown, never> = program",
"void checked",
"",
].join("\n")
: [
'import type { ScriptDefinition } from "opencode-drive/script"',
`import script from ${JSON.stringify(source)}`,
"const checked: ScriptDefinition = script",
"void checked",
"",
].join("\n"),
)
await Bun.write(
tsconfig,
`${JSON.stringify(
{
compilerOptions: {
strict: true,
noEmit: true,
allowJs: true,
checkJs: true,
lib: ["ESNext"],
target: "ESNext",
module: "Preserve",
moduleResolution: "Bundler",
allowImportingTsExtensions: true,
skipLibCheck: true,
types: ["bun"],
paths: {
"opencode-drive": [join(packageRoot, "src", "index.ts")],
"opencode-drive/*": [join(packageRoot, "src", "*")],
effect: [join(effectRoot, "dist", "index.d.ts")],
"effect/*": [join(effectRoot, "dist", "*.d.ts")],
},
},
files: [contractFile],
},
undefined,
2,
)}\n`,
)
const capture = contract === "script"
const child = Bun.spawn([process.execPath, join(compilerRoot, "bin", "tsgo.js"), "-p", tsconfig], {
cwd: root,
stdin: "ignore",
stdout: capture ? "pipe" : "inherit",
stderr: capture ? "pipe" : "inherit",
})
const [status, stdout, stderr] = await Promise.all([
child.exited,
capture ? new Response(child.stdout).text() : "",
capture ? new Response(child.stderr).text() : "",
])
if (status === 0) return
const diagnostics = [stdout, stderr]
.map((value) => value.trim())
.filter(Boolean)
.join("\n")
throw new Error(diagnostics || `${contract} type check failed with status ${status}`)
}
async function prepareRuntimeRoot(artifacts: string) {
const root = join(resolve(artifacts), "script-runtime")
const modules = join(root, "node_modules")
await rm(root, { recursive: true, force: true })
await mkdir(join(modules, "@types"), { recursive: true })
await Promise.all([
symlink(packageRoot, join(modules, "opencode-drive"), linkType),
symlink(effectRoot, join(modules, "effect"), linkType),
symlink(bunTypesRoot, join(modules, "@types", "bun"), linkType),
symlink(bunRuntimeTypesRoot, join(modules, "bun-types"), linkType),
])
return root
}
const linkType = process.platform === "win32" ? "junction" : "dir"
+83
View File
@@ -0,0 +1,83 @@
import type * as Effect from "effect/Effect"
import type * as Tool from "../tool/index.js"
import type * as OpenCodeUi from "../driver/ui.js"
import type * as OpenCodeTui from "../driver/client.js"
import type { Llm } from "../driver/llm.js"
import type * as OpenCodeServer from "../driver/server.js"
import type * as OpenCodeSdk from "../driver/opencode.js"
import type { OpenCodeConfig, OpenCodeTuiConfig, Project, ProjectFileSystem, Setup } from "../project.js"
export type * from "../project.js"
export type ScriptServerLaunchError = Effect.Error<ReturnType<OpenCodeServer.Server["launch"]>>
export type ScriptServerKillError = Effect.Error<ReturnType<OpenCodeServer.Server["kill"]>>
export interface ScriptServer {
/** Launches the one shared OpenCode server for this script. */
launch(): Effect.Effect<OpenCodeSdk.OpenCode, ScriptServerLaunchError>
/** Stops the shared server. It may be launched again afterward. */
kill(): Effect.Effect<void, ScriptServerKillError>
}
export interface ScriptContext {
/** Generated SDK client connected to this script's private OpenCode service. */
readonly opencode: OpenCodeSdk.OpenCode
readonly fs: ProjectFileSystem
readonly tui: OpenCodeTui.Tui
/** Convenience alias for the primary TUI's UI. */
readonly ui: OpenCodeUi.Ui
readonly tuis: OpenCodeTui.Tuis
readonly server: ScriptServer
readonly llm: Llm
/** Runtime controls for tools declared by name on the script. */
readonly tools: Tool.Controls
readonly artifacts: string
}
export interface ManualScriptContext extends Omit<ScriptContext, "opencode" | "tui" | "ui"> {
readonly tui: null
readonly ui: null
}
export type ScriptRun = (context: ScriptContext) => Effect.Effect<void, unknown>
export type ManualScriptRun = (context: ManualScriptContext) => Effect.Effect<void, unknown>
export interface AutomaticScriptDefinition {
/** Declares the isolated project OpenCode runs against. */
readonly project?: Project
/** OpenCode configuration merged over project fixture configuration. */
readonly config?: OpenCodeConfig
/** OpenCode TUI configuration merged over project fixture configuration. */
readonly tuiConfig?: OpenCodeTuiConfig
/** Runs once before OpenCode starts. */
readonly setup?: Setup
/** Declares runtime-controlled tool names or fixed replacements before OpenCode starts. */
readonly tools?: Tool.Configuration
/** Configures the automatically launched primary TUI. */
readonly tui?: OpenCodeTui.TuiOptions
/** Runs after the UI and LLM connections are ready, and again after restart. */
readonly run: ScriptRun
}
export interface ManualScriptDefinition {
/** The server and every TUI are launched explicitly by the script. */
readonly launch: "manual"
/** Declares the isolated project OpenCode runs against. */
readonly project?: Project
/** OpenCode configuration merged over project fixture configuration. */
readonly config?: OpenCodeConfig
/** OpenCode TUI configuration merged over project fixture configuration. */
readonly tuiConfig?: OpenCodeTuiConfig
/** Runs once before OpenCode starts. */
readonly setup?: Setup
/** Declares runtime-controlled tool names or fixed replacements before OpenCode starts. */
readonly tools?: Tool.Configuration
/** Defaults for TUIs launched by the script. */
readonly tui?: OpenCodeTui.TuiOptions
/** Runs after the shared service and LLM connection are ready. */
readonly run: ManualScriptRun
}
export type ScriptDefinitionInput = AutomaticScriptDefinition | ManualScriptDefinition
export type ScriptDefinition = ScriptDefinitionInput & {
readonly kind: "opencode-drive/script"
}
+349
View File
@@ -0,0 +1,349 @@
import * as Context from "effect/Context"
import * as Cause from "effect/Cause"
import * as Deferred from "effect/Deferred"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import * as Queue from "effect/Queue"
import * as Schema from "effect/Schema"
import * as Stream from "effect/Stream"
import { RpcClient, RpcClientError } from "effect/unstable/rpc"
import {
Backend as BackendProtocol,
BackendRpcs,
Frontend as FrontendProtocol,
Handshake,
SimulationRequestError,
UiRpcs,
} from "@opencode-ai/protocol/simulation"
import packageJson from "../../package.json" with { type: "json" }
import * as OpenCodeRpcProtocol from "./opencode-protocol.js"
export class SimulationConnectionError extends Schema.TaggedErrorClass<SimulationConnectionError>()(
"SimulationConnectionError",
{
endpoint: Schema.String,
operation: Schema.String,
message: Schema.String,
},
) {}
export class SimulationCompatibilityError extends Schema.TaggedErrorClass<SimulationCompatibilityError>()(
"SimulationCompatibilityError",
{
endpoint: Schema.String,
role: Handshake.EndpointRole,
message: Schema.String,
},
) {}
export class SimulationEventStreamError extends Schema.TaggedErrorClass<SimulationEventStreamError>()(
"SimulationEventStreamError",
{
endpoint: Schema.String,
message: Schema.String,
},
) {}
export const EndpointCompatibility = Schema.TaggedUnion({
Negotiated: {
endpoint: Schema.String,
role: Handshake.EndpointRole,
protocolVersion: Handshake.ProtocolVersion,
server: Handshake.Identity,
capabilities: Schema.Array(Handshake.Capability),
},
Legacy: {
endpoint: Schema.String,
role: Handshake.EndpointRole,
profile: Schema.Literal("opencode-simulation-jsonrpc-v0"),
reason: Schema.String,
},
})
export type EndpointCompatibility = typeof EndpointCompatibility.Type
export function supportsCapability(compatibility: EndpointCompatibility, capability: Handshake.Capability) {
return compatibility._tag === "Negotiated" && compatibility.capabilities.includes(capability)
}
export type CompatibilityPolicy = "required" | "preferred"
export interface Options {
readonly connectTimeout?: number
readonly requestTimeout?: number
readonly attach?: boolean
readonly compatibility?: CompatibilityPolicy
}
export type UiClient = RpcClient.FromGroup<typeof UiRpcs, RpcClientError.RpcClientError>
export type BackendClient = RpcClient.FromGroup<typeof BackendRpcs, RpcClientError.RpcClientError>
export interface UiConnection {
readonly endpoint: string
readonly rpc: UiClient
readonly compatibility: EndpointCompatibility
}
export type ToolEvent =
| { readonly type: "invocation"; readonly invocation: BackendProtocol.ToolInvocation }
| { readonly type: "cancellation"; readonly cancellation: BackendProtocol.ToolCancellation }
| { readonly type: "barrier"; readonly completed: Deferred.Deferred<void> }
export interface BackendConnection {
readonly endpoint: string
readonly rpc: BackendClient
readonly compatibility: EndpointCompatibility
readonly requests: Stream.Stream<BackendProtocol.ProviderInvocation, Schema.SchemaError>
readonly toolEvents: Stream.Stream<ToolEvent, Schema.SchemaError>
readonly flushToolEvents: () => Effect.Effect<void, SimulationEventStreamError>
readonly closed: Effect.Effect<void>
readonly attach: () => Effect.Effect<
{ readonly attached: true },
SimulationConnectionError | RpcClientError.RpcClientError | SimulationRequestError
>
readonly attachTools: (
tools: ReadonlyArray<BackendProtocol.ToolRegistration>,
) => Effect.Effect<
{ readonly attached: true },
SimulationCompatibilityError | SimulationConnectionError | RpcClientError.RpcClientError | SimulationRequestError
>
readonly updateTool: (
params: BackendProtocol.ToolUpdateParams,
) => Effect.Effect<
{ readonly ok: true },
SimulationConnectionError | RpcClientError.RpcClientError | SimulationRequestError
>
readonly finishTool: (
params: BackendProtocol.ToolFinishParams,
) => Effect.Effect<
{ readonly ok: true },
SimulationConnectionError | RpcClientError.RpcClientError | SimulationRequestError
>
readonly failTool: (
params: BackendProtocol.ToolFailParams,
) => Effect.Effect<
{ readonly ok: true },
SimulationConnectionError | RpcClientError.RpcClientError | SimulationRequestError
>
}
const toolCapabilities = [
"tool.attach",
"tool.update",
"tool.finish",
"tool.fail",
"tool.invocation",
"tool.cancel",
] as const satisfies ReadonlyArray<Handshake.Capability>
const toolCapabilitySet: ReadonlySet<Handshake.Capability> = new Set(toolCapabilities)
export const ui = Effect.fn("SimulationConnector.ui")(function* (endpoint: string, options?: Options) {
const protocol = yield* OpenCodeRpcProtocol.make(endpoint, {
connectTimeout: options?.connectTimeout,
firstWireId: 0,
})
const rpc = yield* RpcClient.make(UiRpcs).pipe(Effect.provideService(RpcClient.Protocol, protocol))
const required = FrontendProtocol.Capabilities.filter(
(capability) => capability !== "ui.snapshot" && capability !== "ui.click.semantic",
)
const compatibility = yield* negotiate(
endpoint,
"ui",
required,
rpc["simulation.handshake"]({
client: { name: "opencode-drive", version: packageJson.version },
expectedRole: "ui",
offeredVersions: [1],
requiredCapabilities: required,
optionalCapabilities: ["ui.snapshot", "ui.click.semantic"],
}),
options?.compatibility,
)
return { endpoint, rpc, compatibility } satisfies UiConnection
})
export const backend = Effect.fn("SimulationConnector.backend")(function* (endpoint: string, options?: Options) {
const requests = yield* Queue.unbounded<BackendProtocol.ProviderInvocation, Schema.SchemaError>()
const toolEvents = yield* Queue.unbounded<ToolEvent, Schema.SchemaError>()
const closed = yield* Deferred.make<void>()
const close = Effect.all(
[Deferred.succeed(closed, undefined), Queue.shutdown(requests), Queue.shutdown(toolEvents)],
{ discard: true },
)
yield* Effect.addFinalizer(() => close)
const protocol = yield* OpenCodeRpcProtocol.make(endpoint, {
connectTimeout: options?.connectTimeout,
firstWireId: 0,
onClose: () => close,
onNotification: ({ method, params }) => {
switch (method) {
case "llm.request":
return Effect.matchEffect(Schema.decodeUnknownEffect(BackendProtocol.ProviderInvocation)(params), {
onFailure: (error) => Queue.fail(requests, error).pipe(Effect.asVoid),
onSuccess: (request) => Queue.offer(requests, request).pipe(Effect.asVoid),
})
case "tool.invocation":
return Effect.matchEffect(Schema.decodeUnknownEffect(BackendProtocol.ToolInvocation)(params), {
onFailure: (error) => Queue.fail(toolEvents, error).pipe(Effect.asVoid),
onSuccess: (invocation) => Queue.offer(toolEvents, { type: "invocation", invocation }).pipe(Effect.asVoid),
})
case "tool.cancel":
return Effect.matchEffect(Schema.decodeUnknownEffect(BackendProtocol.ToolCancellation)(params), {
onFailure: (error) => Queue.fail(toolEvents, error).pipe(Effect.asVoid),
onSuccess: (cancellation) =>
Queue.offer(toolEvents, { type: "cancellation", cancellation }).pipe(Effect.asVoid),
})
default:
return Effect.void
}
},
})
const rpc = yield* RpcClient.make(BackendRpcs).pipe(Effect.provideService(RpcClient.Protocol, protocol))
const required = BackendProtocol.Capabilities.filter(
(capability) =>
capability !== "llm.pending" && capability !== "llm.tool-input-delta" && !toolCapabilitySet.has(capability),
)
const compatibility = yield* negotiate(
endpoint,
"backend",
required,
rpc["simulation.handshake"]({
client: { name: "opencode-drive", version: packageJson.version },
expectedRole: "backend",
offeredVersions: [1],
requiredCapabilities: required,
optionalCapabilities: ["llm.pending", "llm.tool-input-delta", ...toolCapabilities],
}),
options?.compatibility,
)
const attach = Effect.fn("SimulationConnector.attach")(() =>
rpc["llm.attach"]().pipe(
Effect.timeoutOrElse({
duration: options?.requestTimeout ?? 30_000,
orElse: () =>
Effect.fail(
new SimulationConnectionError({
endpoint,
operation: "llm.attach",
message: `llm.attach timed out after ${options?.requestTimeout ?? 30_000}ms`,
}),
),
}),
),
)
if (options?.attach !== false) yield* attach()
const withTimeout = <A, E>(operation: string, effect: Effect.Effect<A, E>) =>
effect.pipe(
Effect.timeoutOrElse({
duration: options?.requestTimeout ?? 30_000,
orElse: () =>
Effect.fail(
new SimulationConnectionError({
endpoint,
operation,
message: `${operation} timed out after ${options?.requestTimeout ?? 30_000}ms`,
}),
),
}),
)
const attachTools: BackendConnection["attachTools"] = (tools) => {
const missing = toolCapabilities.filter((capability) => !supportsCapability(compatibility, capability))
if (missing.length > 0)
return Effect.fail(
new SimulationCompatibilityError({
endpoint,
role: "backend",
message: `Simulation endpoint is missing required capabilities: ${missing.join(", ")}`,
}),
)
return withTimeout("tool.attach", rpc["tool.attach"]({ tools }))
}
const updateTool: BackendConnection["updateTool"] = (params) => withTimeout("tool.update", rpc["tool.update"](params))
const finishTool: BackendConnection["finishTool"] = (params) => withTimeout("tool.finish", rpc["tool.finish"](params))
const failTool: BackendConnection["failTool"] = (params) => withTimeout("tool.fail", rpc["tool.fail"](params))
const flushToolEvents = Effect.fn("SimulationConnector.flushToolEvents")(function* () {
const completed = yield* Deferred.make<void>()
const offered = yield* Queue.offer(toolEvents, { type: "barrier", completed })
if (!offered)
return yield* Effect.fail(
new SimulationEventStreamError({
endpoint,
message: "Dynamic tool event stream is unavailable",
}),
)
yield* Deferred.await(completed)
return undefined
})
return {
endpoint,
rpc,
compatibility,
requests: Stream.fromQueue(requests),
toolEvents: Stream.fromQueue(toolEvents),
flushToolEvents,
closed: Deferred.await(closed),
attach,
attachTools,
updateTool,
finishTool,
failTool,
} satisfies BackendConnection
})
export interface Interface {
readonly ui: typeof ui
readonly backend: typeof backend
}
export class Service extends Context.Service<Service, Interface>()("opencode-drive/SimulationConnector") {}
export const layer = Layer.succeed(Service, Service.of({ ui, backend }))
const negotiate = Effect.fn("SimulationConnector.negotiate")(function* (
endpoint: string,
role: Handshake.EndpointRole,
required: ReadonlyArray<Handshake.Capability>,
handshake: Effect.Effect<Handshake.Response, unknown>,
policy: CompatibilityPolicy = "preferred",
) {
const legacy = (reason: string): EndpointCompatibility =>
EndpointCompatibility.cases.Legacy.make({
endpoint,
role,
profile: "opencode-simulation-jsonrpc-v0",
reason,
})
const result = yield* Effect.exit(handshake)
if (result._tag === "Success") {
const missing = required.filter((capability) => !result.value.capabilities.includes(capability))
if (result.value.role !== role || missing.length > 0)
return yield* Effect.fail(
new SimulationCompatibilityError({
endpoint,
role,
message:
result.value.role !== role
? `Expected ${role} simulation endpoint, received ${result.value.role}`
: `Simulation endpoint is missing required capabilities: ${missing.join(", ")}`,
}),
)
return EndpointCompatibility.cases.Negotiated.make({
endpoint,
role: result.value.role,
protocolVersion: result.value.protocolVersion,
server: result.value.server,
capabilities: result.value.capabilities,
})
}
const cause = result.cause
const message = Cause.pretty(cause)
if (policy === "preferred" && isHandshakeUnavailable(cause)) return legacy(message)
return yield* Effect.fail(new SimulationCompatibilityError({ endpoint, role, message }))
})
function isHandshakeUnavailable(cause: Cause.Cause<unknown>) {
const failure = Cause.findErrorOption(cause)
return Option.isSome(failure) && failure.value instanceof SimulationRequestError && failure.value.code === -32601
}
export * as SimulationConnector from "./connector.js"
@@ -0,0 +1,336 @@
import * as Effect from "effect/Effect"
import * as Option from "effect/Option"
import * as Queue from "effect/Queue"
import * as Schema from "effect/Schema"
import { RpcClient, RpcClientError, type RpcMessage } from "effect/unstable/rpc"
import { JsonRpc, SimulationRequestError } from "@opencode-ai/protocol/simulation"
interface PendingRequest {
readonly clientId: number
readonly method: string
readonly requestId: string | number
}
type TransportEvent =
| { readonly _tag: "Message"; readonly data: string }
| { readonly _tag: "Close" }
| { readonly _tag: "Error"; readonly cause: unknown }
export interface Notification {
readonly method: string
readonly params: unknown
}
export interface Options {
readonly connectTimeout?: number
readonly firstWireId?: number
readonly onClose?: () => Effect.Effect<void>
readonly onNotification?: (notification: Notification) => Effect.Effect<void>
}
const decodeResponse = Schema.decodeUnknownOption(JsonRpc.Response)
const encodeRequestError = Schema.encodeSync(Schema.toCodecJson(SimulationRequestError))
export const make = Effect.fn("OpenCodeRpcProtocol.make")(function* (endpoint: string, options?: Options) {
const connectTimeout = options?.connectTimeout ?? 30_000
let closing = false
const socket = yield* Effect.acquireRelease(
open(endpoint).pipe(
Effect.timeoutOrElse({
duration: connectTimeout,
orElse: () =>
Effect.fail(
protocolError(
`cannot connect to ${endpoint}: timed out after ${connectTimeout}ms`,
new Error("WebSocket connection timed out"),
),
),
}),
),
(socket) =>
Effect.sync(() => {
closing = true
socket.terminate()
}),
)
return yield* RpcClient.Protocol.make((write, clientIds) =>
Effect.gen(function* () {
const events = yield* Queue.unbounded<TransportEvent>()
const pending = new Map<number, PendingRequest>()
const wireIds = new Map<number, Map<string | number, number>>()
let nextWireId = options?.firstWireId ?? 1
let currentError: RpcClientError.RpcClientError | undefined
const removePending = (wireId: number) => {
const request = pending.get(wireId)
if (request === undefined) return undefined
pending.delete(wireId)
const clientWireIds = wireIds.get(request.clientId)
clientWireIds?.delete(request.requestId)
if (clientWireIds?.size === 0) wireIds.delete(request.clientId)
return request
}
const failAll = (message: string, cause: unknown) =>
Effect.gen(function* () {
if (closing || currentError !== undefined) return
const error = protocolError(message, cause)
currentError = error
pending.clear()
wireIds.clear()
yield* Effect.forEach(clientIds, (clientId) =>
write(clientId, {
_tag: "ClientProtocolError",
error,
}),
)
if (socket.readyState === WebSocket.OPEN) socket.terminate()
})
const handleMessage = (data: string): Effect.Effect<void> => {
let value: unknown
try {
value = JSON.parse(data)
} catch (cause) {
return failAll("received invalid JSON", cause)
}
if (isRecord(value) && typeof value.method === "string") {
if (value.jsonrpc !== "2.0" || "id" in value)
return failAll("received an invalid JSON-RPC notification", value)
return (
options?.onNotification?.({
method: value.method,
params: "params" in value ? value.params : undefined,
}) ?? Effect.void
)
}
if (!isRecord(value)) return failAll("received an invalid JSON-RPC response", value)
const hasResult = Object.hasOwn(value, "result")
const hasError = Object.hasOwn(value, "error")
if (hasResult === hasError) return failAll("JSON-RPC response must contain result or error", value)
const decoded = decodeResponse(value)
if (Option.isNone(decoded)) return failAll("received an invalid JSON-RPC response", value)
const response = decoded.value
if (typeof response.id !== "number") return failAll("received an invalid JSON-RPC response ID", response.id)
const request = removePending(response.id)
if (request === undefined) return Effect.void
if (response.error !== undefined) {
const error = new SimulationRequestError({
method: request.method,
code: response.error.code,
message: response.error.message,
...(response.error.data === undefined ? {} : { data: response.error.data }),
})
return write(request.clientId, {
_tag: "Exit",
requestId: request.requestId,
exit: {
_tag: "Failure",
cause: [{ _tag: "Fail", error: encodeRequestError(error) }],
},
})
}
return write(request.clientId, {
_tag: "Exit",
requestId: request.requestId,
exit: { _tag: "Success", value: response.result },
})
}
const handleEvent = (event: TransportEvent) => {
switch (event._tag) {
case "Message":
return handleMessage(event.data)
case "Close":
return Effect.andThen(
options?.onClose?.() ?? Effect.void,
failAll("connection closed", new Error("connection closed")),
)
case "Error":
return Effect.andThen(options?.onClose?.() ?? Effect.void, failAll("connection error", event.cause))
}
return Effect.void
}
yield* Queue.take(events).pipe(Effect.flatMap(handleEvent), Effect.forever, Effect.forkScoped)
const onMessage = (event: MessageEvent) =>
Queue.offerUnsafe(events, {
_tag: "Message",
data: String(event.data),
})
const onClose = () => Queue.offerUnsafe(events, { _tag: "Close" })
const onError = (cause: Event) => Queue.offerUnsafe(events, { _tag: "Error", cause })
socket.addEventListener("message", onMessage)
socket.addEventListener("close", onClose)
socket.addEventListener("error", onError)
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
socket.removeEventListener("message", onMessage)
socket.removeEventListener("close", onClose)
socket.removeEventListener("error", onError)
}).pipe(Effect.andThen(Queue.shutdown(events))),
)
const send = (clientId: number, message: RpcMessage.FromClientEncoded) =>
Effect.suspend(() => {
if (currentError !== undefined) return Effect.fail(currentError)
if (message._tag === "Interrupt") {
const clientWireIds = wireIds.get(clientId)
const wireId = clientWireIds?.get(message.requestId)
if (wireId !== undefined) removePending(wireId)
return Effect.void
}
if (message._tag !== "Request") return Effect.void
if (socket.readyState !== WebSocket.OPEN)
return Effect.fail(protocolError("connection is not open", new Error("connection is not open")))
let clientWireIds = wireIds.get(clientId)
if (clientWireIds === undefined) {
clientWireIds = new Map()
wireIds.set(clientId, clientWireIds)
}
if (clientWireIds.has(message.id))
return Effect.fail(protocolError("duplicate RPC request ID", new Error(String(message.id))))
const wireId = nextWireId++
const payload = message.tag === "ui.press" ? encodePressPayload(message.payload) : message.payload
pending.set(wireId, {
clientId,
method: message.tag,
requestId: message.id,
})
clientWireIds.set(message.id, wireId)
return Effect.try({
try: () => {
socket.send(
JSON.stringify({
jsonrpc: "2.0",
id: wireId,
method: message.tag,
...(payload === undefined || payload === null ? {} : { params: payload }),
}),
)
},
catch: (cause) => {
removePending(wireId)
return protocolError("failed to send request", cause)
},
})
})
return {
send,
supportsAck: false,
supportsTransferables: false,
}
}),
)
})
const arrows = {
up: { final: "A", kitty: 57_352 },
down: { final: "B", kitty: 57_353 },
right: { final: "C", kitty: 57_351 },
left: { final: "D", kitty: 57_350 },
} as const
function encodePressPayload(payload: unknown) {
if (typeof payload !== "object" || payload === null) return payload
const key = Reflect.get(payload, "key")
if (typeof key !== "string") return payload
const modifiers = Reflect.get(payload, "modifiers")
const modifier = modifierMask(modifiers)
const named = key.toLowerCase()
const arrowName = named.startsWith("arrow_") ? named.slice(6) : named
const arrow =
arrowName === "up"
? arrows.up
: arrowName === "down"
? arrows.down
: arrowName === "right"
? arrows.right
: arrowName === "left"
? arrows.left
: undefined
if (arrow !== undefined) {
if (modifier & 24) return { key: kittySequence(arrow.kitty, modifier) }
return {
key: modifier === 0 ? `\u001b[${arrow.final}` : `\u001b[1;${modifier + 1}${arrow.final}`,
}
}
if (named === "tab" && modifier !== 0) return { key: kittySequence(9, modifier) }
return payload
}
function modifierMask(value: unknown) {
if (typeof value !== "object" || value === null) return 0
return (
(Reflect.get(value, "shift") === true ? 1 : 0) |
(Reflect.get(value, "meta") === true ? 2 : 0) |
(Reflect.get(value, "ctrl") === true ? 4 : 0) |
(Reflect.get(value, "super") === true ? 8 : 0) |
(Reflect.get(value, "hyper") === true ? 16 : 0)
)
}
function kittySequence(codepoint: number, modifier: number) {
return `\u001b[${codepoint};${modifier + 1}u`
}
function open(endpoint: string) {
return Effect.callback<WebSocket, RpcClientError.RpcClientError>((resume) => {
let socket: WebSocket
try {
socket = new WebSocket(endpoint)
} catch (cause) {
resume(Effect.fail(protocolError(`cannot connect to ${endpoint}`, cause)))
return Effect.void
}
let settled = false
const complete = (effect: Effect.Effect<WebSocket, RpcClientError.RpcClientError>) => {
if (settled) return
settled = true
cleanup()
resume(effect)
}
const onOpen = () => complete(Effect.succeed(socket))
const onError = (cause: Event) => {
complete(Effect.fail(protocolError(`cannot connect to ${endpoint}`, cause)))
socket.terminate()
}
const onClose = () => {
complete(
Effect.fail(protocolError(`cannot connect to ${endpoint}`, new Error("connection closed before opening"))),
)
}
const cleanup = () => {
socket.removeEventListener("open", onOpen)
socket.removeEventListener("error", onError)
socket.removeEventListener("close", onClose)
}
socket.addEventListener("open", onOpen)
socket.addEventListener("error", onError)
socket.addEventListener("close", onClose)
return Effect.sync(() => {
cleanup()
socket.terminate()
})
})
}
function protocolError(message: string, cause: unknown) {
return new RpcClientError.RpcClientError({
reason: new RpcClientError.RpcClientDefect({ message, cause }),
})
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}

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