fix: 修正 logo 中 N 和 G 字母造型
N 添加对角线笔画(█▄ █),G 添加内横杠(█ ▀█), 避免与 O 字母造型雷同。同步更新 ui.ts 中的硬编码 wordmark。
This commit is contained in:
235
packages/opencode/specs/effect/error-boundaries-plan.md
Normal file
235
packages/opencode/specs/effect/error-boundaries-plan.md
Normal file
@@ -0,0 +1,235 @@
|
||||
# Error Boundaries Plan
|
||||
|
||||
Plan for removing `NamedError` as connective tissue while keeping public
|
||||
wire contracts stable.
|
||||
|
||||
## Desired Shape
|
||||
|
||||
```text
|
||||
Domain/service error
|
||||
Schema.TaggedErrorClass
|
||||
- catchable with catchTag / catchTags
|
||||
- appears in service method error type
|
||||
- no HTTP status
|
||||
- no toObject()
|
||||
|
||||
HTTP public error
|
||||
Schema.ErrorClass / TaggedErrorClass with httpApiStatus
|
||||
- endpoint-declared public contract
|
||||
- owns legacy { name, data } only when that is the SDK wire shape
|
||||
|
||||
CLI/user rendering
|
||||
FormatError and small format helpers
|
||||
- converts domain errors to text
|
||||
- preserves useful structured fields
|
||||
|
||||
Session/model-visible error
|
||||
first-class session/message error schema or helper
|
||||
- owns { name, data } event/message shape
|
||||
- not a service error class
|
||||
```
|
||||
|
||||
The important rule: a service error should not also be the HTTP body, CLI
|
||||
formatter, and session event body. Each seam adapts the error into the
|
||||
shape it owns.
|
||||
|
||||
## Concrete Example: Provider Model Not Found
|
||||
|
||||
Before:
|
||||
|
||||
```ts
|
||||
export const ModelNotFoundError = NamedError.create("ProviderModelNotFoundError", {
|
||||
providerID: ProviderID,
|
||||
modelID: ModelID,
|
||||
suggestions: Schema.optional(Schema.Array(Schema.String)),
|
||||
})
|
||||
```
|
||||
|
||||
Problems:
|
||||
|
||||
- Throwing it inside `Effect.fn` made it behave like a defect unless a
|
||||
compatibility bridge caught it.
|
||||
- HTTP middleware knew that this one domain error should be a `400`.
|
||||
- Callers read `.data.*`, which couples them to the legacy `{ name, data }`
|
||||
wire shape.
|
||||
|
||||
After:
|
||||
|
||||
```ts
|
||||
export class ModelNotFoundError extends Schema.TaggedErrorClass<ModelNotFoundError>()("ProviderModelNotFoundError", {
|
||||
providerID: ProviderID,
|
||||
modelID: ModelID,
|
||||
suggestions: Schema.optional(Schema.Array(Schema.String)),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface Interface {
|
||||
readonly getModel: (providerID: ProviderID, modelID: ModelID) => Effect.Effect<Model, ModelNotFoundError>
|
||||
}
|
||||
```
|
||||
|
||||
Boundary adapters:
|
||||
|
||||
```text
|
||||
CLI
|
||||
└─ FormatError sees _tag ProviderModelNotFoundError -> nice text
|
||||
|
||||
Session prompt
|
||||
└─ catch ModelNotFoundError -> publish Session.Event.Error as message/session wire shape
|
||||
|
||||
HTTP route
|
||||
└─ catch ModelNotFoundError -> declared BadRequest public API error when the endpoint needs it
|
||||
|
||||
HTTP middleware
|
||||
└─ no Provider.ModelNotFoundError knowledge
|
||||
```
|
||||
|
||||
## Refining Known Promise Failures
|
||||
|
||||
Use `EffectPromise.refineRejection(...)` when a Promise boundary can reject
|
||||
with many unknown values, but only one or two rejection classes are expected
|
||||
domain failures. Unknown rejections stay defects; the helper maps only known
|
||||
rejection shapes to typed errors.
|
||||
|
||||
```ts
|
||||
const language =
|
||||
yield *
|
||||
EffectPromise.refineRejection(
|
||||
async () => loadFromProvider(),
|
||||
(cause) => (cause instanceof NoSuchModelError ? new ModelNotFoundError({ providerID, modelID, cause }) : undefined),
|
||||
)
|
||||
```
|
||||
|
||||
Use this when the Promise can genuinely reject and most rejection values are
|
||||
still defects for the current module. Use `Effect.tryPromise({ try, catch })`
|
||||
when every rejection should become the same expected error type. Use
|
||||
`Effect.promise(...)` only when rejection means a defect and you do not need
|
||||
to refine known rejection classes.
|
||||
|
||||
## Helper Modules We Probably Want
|
||||
|
||||
Add helpers only when repeated call sites prove the seam is real.
|
||||
|
||||
### HTTP API Errors
|
||||
|
||||
Likely location: `src/server/routes/instance/httpapi/errors.ts`.
|
||||
|
||||
Purpose:
|
||||
|
||||
- construct public HTTP error bodies
|
||||
- preserve legacy `{ name, data }` where needed
|
||||
- attach `httpApiStatus`
|
||||
|
||||
Good helpers:
|
||||
|
||||
```ts
|
||||
notFound(message)
|
||||
badRequest(message)
|
||||
unknown()
|
||||
```
|
||||
|
||||
Avoid:
|
||||
|
||||
```ts
|
||||
mapAnyDomainError(error)
|
||||
```
|
||||
|
||||
That recreates the giant middleware mapper problem.
|
||||
|
||||
### Session / Message Error Wire Helpers
|
||||
|
||||
Likely location: near `src/session/message-error.ts` or a new narrow
|
||||
module such as `src/session/event-error.ts`.
|
||||
|
||||
Purpose:
|
||||
|
||||
- construct the `{ name, data }` shape used by `Session.Event.Error` and
|
||||
assistant message errors
|
||||
- replace `new NamedError.Unknown(...).toObject()` call sites
|
||||
- keep model-visible error bodies separate from service/domain errors
|
||||
|
||||
Good helpers:
|
||||
|
||||
```ts
|
||||
unknown(message)
|
||||
agentNotFound(agent, available)
|
||||
commandNotFound(command, available)
|
||||
modelNotFound(error: Provider.ModelNotFoundError)
|
||||
```
|
||||
|
||||
### CLI Formatters
|
||||
|
||||
Likely location: `src/cli/error.ts` until repetition demands domain-local
|
||||
format helpers.
|
||||
|
||||
Purpose:
|
||||
|
||||
- produce human-readable terminal messages from typed errors
|
||||
- support old `{ name, data }` shapes only while compatibility is needed
|
||||
|
||||
## Migration Queue
|
||||
|
||||
### Remove Domain Knowledge From HTTP Middleware
|
||||
|
||||
- [x] Storage not found no longer maps through defect fallback.
|
||||
- [x] Worktree expected errors moved to typed errors.
|
||||
- [x] Provider auth expected errors moved to typed errors.
|
||||
- [x] Provider model not found no longer needs an HTTP middleware status
|
||||
special case.
|
||||
- [ ] Convert `Session.BusyError` and map it at route boundaries.
|
||||
- [ ] Delete the broad `NamedError` middleware branch once no route relies
|
||||
on defect-wrapped legacy domain errors.
|
||||
- [ ] Keep one final unknown-defect fallback that logs `Cause.pretty(cause)`
|
||||
and returns a safe `500` body.
|
||||
|
||||
### Remaining `NamedError.create(...)` Service Errors
|
||||
|
||||
These should become `Schema.TaggedErrorClass` when touched:
|
||||
|
||||
- [ ] `src/provider/provider.ts` — `ProviderInitError`.
|
||||
- [ ] `src/storage/db.ts` — database `NotFoundError`.
|
||||
- [ ] `src/mcp/index.ts` — `MCPFailed`.
|
||||
- [ ] `src/skill/index.ts` — `SkillInvalidError`,
|
||||
`SkillNameMismatchError`.
|
||||
- [ ] `src/lsp/client.ts` — `LSPInitializeError`.
|
||||
- [ ] `src/ide/index.ts` — install errors.
|
||||
- [ ] `src/config/error.ts`, `src/config/config.ts`,
|
||||
`src/config/markdown.ts` — config errors. These already render well
|
||||
in the CLI, so migrate carefully and preserve diagnostics.
|
||||
|
||||
### Session / Message Wire Errors
|
||||
|
||||
These are not ordinary service errors. They mostly build `{ name, data }`
|
||||
objects for model-visible/session-visible output.
|
||||
|
||||
- [ ] Add a first-class session/message error wire helper.
|
||||
- [ ] Replace `new NamedError.Unknown(...).toObject()` in
|
||||
`src/session/prompt.ts`.
|
||||
- [ ] Replace `new NamedError.Unknown(...).toObject()` in config/skill/plugin
|
||||
session event publishing.
|
||||
- [ ] Move `src/session/message-error.ts` and `src/session/message-v2.ts`
|
||||
away from `NamedError.create(...)` once the wire helper exists.
|
||||
- [ ] Update retry/message tests to assert the wire schema/helper output,
|
||||
not `NamedError` instances.
|
||||
|
||||
### CLI Rendering
|
||||
|
||||
- [x] Tagged config errors render with useful diagnostics.
|
||||
- [x] Provider model not found renders from both old `{ name, data }` and
|
||||
new `_tag` shapes.
|
||||
- [ ] Add typed render cases as more `NamedError.create(...)` domains move
|
||||
to `Schema.TaggedErrorClass`.
|
||||
- [ ] Eventually remove old-shape compatibility branches when no callers can
|
||||
produce them.
|
||||
|
||||
## PR Checklist
|
||||
|
||||
For each migrated error:
|
||||
|
||||
- [ ] Domain error is `Schema.TaggedErrorClass`.
|
||||
- [ ] Service method exposes the typed error in its error channel.
|
||||
- [ ] No service error has `toObject()` just for compatibility.
|
||||
- [ ] CLI, HTTP, and session/message adapters each own their output shape.
|
||||
- [ ] HTTP middleware gets smaller or stays unchanged.
|
||||
- [ ] Focused tests cover the domain error and any public rendering/wire
|
||||
shape touched by the PR.
|
||||
207
packages/opencode/specs/effect/errors.md
Normal file
207
packages/opencode/specs/effect/errors.md
Normal file
@@ -0,0 +1,207 @@
|
||||
# Typed Error Migration
|
||||
|
||||
This note expands the `ERR`, `RENDER`, and `HTTP` tracks from
|
||||
[`todo.md`](./todo.md). It is the current reference for expected failures,
|
||||
typed service errors, and HTTP error boundaries.
|
||||
|
||||
For the migration architecture and queue, see
|
||||
[`error-boundaries-plan.md`](./error-boundaries-plan.md).
|
||||
|
||||
## Goal
|
||||
|
||||
- Expected service failures live on the Effect error channel.
|
||||
- Service interfaces expose those failures in their return types.
|
||||
- Domain errors are authored with `Schema.TaggedErrorClass`.
|
||||
- `Effect.die(...)` is reserved for defects: bugs, impossible states,
|
||||
violated invariants, and final unknown-boundary fallbacks.
|
||||
- HTTP status codes and public wire bodies are handled at HTTP route
|
||||
boundaries, not inside service modules.
|
||||
- User-facing boundaries render useful structured error details instead of
|
||||
opaque `Error: SomeName` strings.
|
||||
|
||||
## Service Error Shape
|
||||
|
||||
```ts
|
||||
export class SessionBusyError extends Schema.TaggedErrorClass<SessionBusyError>()("SessionBusyError", {
|
||||
sessionID: SessionID,
|
||||
message: Schema.String,
|
||||
}) {}
|
||||
|
||||
export type Error = Storage.Error | SessionBusyError
|
||||
|
||||
export interface Interface {
|
||||
readonly get: (id: SessionID) => Effect.Effect<Info, Error>
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Use `Schema.TaggedErrorClass` for expected domain failures.
|
||||
- Export a domain-level `Error` union from each service module.
|
||||
- Put expected errors in service method signatures.
|
||||
- Use `yield* new DomainError(...)` for direct early failures in
|
||||
`Effect.gen` / `Effect.fn`.
|
||||
- Use `Schema.Defect` for unknown cause fields when preserving the cause is
|
||||
useful for logs or callers.
|
||||
- Use `Effect.try(...)`, `Effect.tryPromise(...)`, `Effect.mapError`,
|
||||
`Effect.catchTag`, and `Effect.catchTags` to translate external
|
||||
failures into domain errors.
|
||||
- Do not use `throw`, `Effect.die(...)`, or `catchDefect` for expected
|
||||
user, IO, validation, missing-resource, auth, provider, worktree, or
|
||||
busy-state failures.
|
||||
|
||||
## HTTP Boundary Shape
|
||||
|
||||
Service modules stay transport-agnostic. They should not import HTTP
|
||||
status codes, `HttpApiError`, `HttpServerResponse`, or route-specific
|
||||
error schemas.
|
||||
|
||||
HTTP handlers translate service errors into public endpoint errors:
|
||||
|
||||
```ts
|
||||
const get = Effect.fn("SessionHttpApi.get")(function* (ctx: { params: { sessionID: SessionID } }) {
|
||||
return yield* session
|
||||
.get(ctx.params.sessionID)
|
||||
.pipe(Effect.catchTag("StorageNotFoundError", () => notFound("Session not found")))
|
||||
})
|
||||
```
|
||||
|
||||
Endpoint definitions declare which public errors can be emitted. Public
|
||||
HTTP error schemas carry their response status with `httpApiStatus` or the
|
||||
equivalent HttpApi schema annotation.
|
||||
|
||||
Effect's own HttpApi examples follow this pattern:
|
||||
|
||||
```ts
|
||||
export class Unauthorized extends Schema.TaggedErrorClass<Unauthorized>()(
|
||||
"Unauthorized",
|
||||
{ message: Schema.String },
|
||||
{ httpApiStatus: 401 },
|
||||
) {}
|
||||
|
||||
export class Authorization extends HttpApiMiddleware.Service<
|
||||
Authorization,
|
||||
{
|
||||
provides: CurrentUser
|
||||
}
|
||||
>()("app/Authorization", {
|
||||
security: { bearer: HttpApiSecurity.bearer },
|
||||
error: Unauthorized,
|
||||
}) {}
|
||||
```
|
||||
|
||||
Endpoint-level errors use the same idea:
|
||||
|
||||
```ts
|
||||
export class ConfigApiError extends Schema.ErrorClass<ConfigApiError>("ConfigApiError")(
|
||||
{
|
||||
name: Schema.Union(Schema.Literal("ConfigInvalidError"), Schema.Literal("ConfigJsonError")),
|
||||
data: Schema.Struct({ message: Schema.optional(Schema.String), path: Schema.String }),
|
||||
},
|
||||
{ httpApiStatus: 400 },
|
||||
) {}
|
||||
|
||||
HttpApiEndpoint.get("get", "/config", {
|
||||
success: Config.Info,
|
||||
error: ConfigApiError,
|
||||
})
|
||||
```
|
||||
|
||||
The service error and HTTP error may be the same class only when the wire
|
||||
shape is intentionally public. Use separate HTTP error schemas when the
|
||||
service error contains internals, low-level causes, retry hints, or data
|
||||
that should not be exposed to API clients.
|
||||
|
||||
Do not map every domain error into one universal HTTP error class. Prefer a
|
||||
small public error vocabulary by route group: shared shapes like
|
||||
`ApiNotFoundError`, route-specific shapes like `ConfigApiError`, and built-in
|
||||
empty `HttpApiError.*` only when an empty/no-content body is the intended SDK
|
||||
contract.
|
||||
|
||||
## Mapping Guidance
|
||||
|
||||
- Keep one-off translations inline in the handler.
|
||||
- Extract tiny shared helpers when the same translation repeats across a
|
||||
route group.
|
||||
- Do not create one giant `unknown -> status` mapper.
|
||||
- Do not grow generic HTTP middleware into a registry of domain errors.
|
||||
- Preserve existing public `{ name, data }` bodies until a deliberate
|
||||
breaking API change.
|
||||
- Use built-in `HttpApiError.*` only when its generated body and SDK
|
||||
surface are intentionally the public contract.
|
||||
- Prefer `Schema.ErrorClass` for public HTTP error bodies whose wire shape is
|
||||
not the same as the internal domain error shape.
|
||||
- Prefer `Schema.TaggedErrorClass` for service/domain errors and middleware
|
||||
errors that are naturally tagged by `_tag`.
|
||||
- If preserving a legacy `{ name, data }` body, model that shape explicitly in
|
||||
the public API error schema instead of relying on `NamedError.toObject()` in
|
||||
generic middleware.
|
||||
|
||||
## User-Facing Rendering
|
||||
|
||||
HTTP serialization and user rendering are separate boundaries. The server
|
||||
should send structured public errors; CLI and TUI code should format those
|
||||
structures through one shared formatter.
|
||||
|
||||
For SDK calls using `{ throwOnError: true }`, the generated client may wrap the
|
||||
decoded response body in an `Error`. The original body should remain available
|
||||
under `error.cause.body`; `FormatError` is the right place to unwrap and render
|
||||
that body. TUI aggregation helpers should call `FormatError` first, then fall
|
||||
back to generic `Error.message` / string rendering.
|
||||
|
||||
When several parallel startup requests fail from the same underlying issue,
|
||||
group identical rendered messages and list the affected request names once.
|
||||
For example:
|
||||
|
||||
```text
|
||||
Configuration is invalid at /path/to/opencode.json
|
||||
↳ Expected object, got "not-object" provider.bad.options
|
||||
Affected startup requests: config.providers, provider.list, app.agents, config.get
|
||||
```
|
||||
|
||||
## Middleware Guidance
|
||||
|
||||
HTTP middleware should be cross-cutting: auth, context, schema decode
|
||||
formatting, routing, and final unknown-defect fallback.
|
||||
|
||||
The current compatibility middleware still knows about some legacy domain
|
||||
errors. As route groups declare expected errors and handlers map them, that
|
||||
middleware should shrink. It should not gain new name checks.
|
||||
|
||||
Unknown `500` responses should log full details server-side with
|
||||
`Cause.pretty(cause)` and return a safe public body.
|
||||
|
||||
The config startup regression in #27056 is the failure mode this rule is meant
|
||||
to avoid: a user-authored invalid `opencode.json` crossed the HttpApi boundary
|
||||
as a defect, so middleware replaced a useful `ConfigInvalidError` with a safe
|
||||
generic `UnknownError`. The compatibility fix is to preserve config parse and
|
||||
validation errors as client-visible `400`s. The target architecture is better:
|
||||
config loading should fail on the typed error channel, config HTTP handlers
|
||||
should map those errors to declared `ConfigApiError` responses, and the generic
|
||||
middleware should never see them.
|
||||
|
||||
## Migration Order
|
||||
|
||||
Prefer small vertical slices:
|
||||
|
||||
1. Fix rendering at one user-visible boundary.
|
||||
2. Convert one service domain to `Schema.TaggedErrorClass` errors.
|
||||
3. Map those errors at the affected HTTP handlers.
|
||||
4. Remove the corresponding name-based middleware branch if possible.
|
||||
5. Add or update focused tests for both service error tags and HTTP wire
|
||||
bodies.
|
||||
|
||||
Good early domains are storage not-found, worktree errors, and provider
|
||||
auth validation errors because they currently drive HTTP behavior.
|
||||
|
||||
Config parse and validation errors are also a good early slice because they
|
||||
are startup-blocking and must be rendered clearly in both CLI and TUI flows.
|
||||
|
||||
## Checklist For A PR
|
||||
|
||||
- [ ] Expected failures are typed errors, not defects.
|
||||
- [ ] Service method signatures expose the expected error union.
|
||||
- [ ] HTTP handlers translate domain errors at the boundary.
|
||||
- [ ] Public HTTP error bodies preserve existing wire contracts.
|
||||
- [ ] Generic middleware gets smaller or stays unchanged.
|
||||
- [ ] Focused tests cover the service error and any public HTTP response.
|
||||
218
packages/opencode/specs/effect/facades.md
Normal file
218
packages/opencode/specs/effect/facades.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# Facade removal checklist
|
||||
|
||||
Concrete inventory of the remaining `makeRuntime(...)`-backed facades in `packages/opencode`.
|
||||
|
||||
Current status on this branch:
|
||||
|
||||
- `src/` has 5 `makeRuntime(...)` call sites total.
|
||||
- 2 are intentionally excluded from this checklist: `src/bus/index.ts` and `src/effect/cross-spawn-spawner.ts`.
|
||||
- That leaves 2 live runtime-backed service facades still worth tracking here: `src/npm/index.ts` and `src/cli/cmd/tui/config/tui.ts`.
|
||||
|
||||
Recent progress:
|
||||
|
||||
- Wave 1 is merged: `Pty`, `Skill`, `Vcs`, `ToolRegistry`, `Auth`.
|
||||
- Wave 2 is merged: `Config`, `Provider`, `File`, `LSP`, `MCP`.
|
||||
|
||||
## Priority hotspots
|
||||
|
||||
- `src/cli/cmd/tui/config/tui.ts` still exports `makeRuntime(...)` plus async facade helpers for `get()` and `waitForDependencies()`.
|
||||
- `src/npm/index.ts` still exports `makeRuntime(...)` plus async facade helpers for `install()`, `add()`, `outdated()`, and `which()`.
|
||||
|
||||
## Completed Batches
|
||||
|
||||
Low-risk batch, all merged:
|
||||
|
||||
1. `src/pty/index.ts`
|
||||
2. `src/skill/index.ts`
|
||||
3. `src/project/vcs.ts`
|
||||
4. `src/tool/registry.ts`
|
||||
5. `src/auth/index.ts`
|
||||
|
||||
Caller-heavy batch, all merged:
|
||||
|
||||
1. `src/config/config.ts`
|
||||
2. `src/provider/provider.ts`
|
||||
3. `../core/src/filesystem.ts`
|
||||
4. `src/lsp/index.ts`
|
||||
5. `src/mcp/index.ts`
|
||||
|
||||
Shared pattern:
|
||||
|
||||
- one service file still exports `makeRuntime(...)` + async facades
|
||||
- one or two route or CLI entrypoints call those facades directly
|
||||
- tests call the facade directly and need to switch to `yield* svc.method(...)`
|
||||
- once callers are gone, delete `makeRuntime(...)`, remove async facade exports, and drop the `makeRuntime` import
|
||||
|
||||
## Done means
|
||||
|
||||
For each service in the low-risk batch, the work is complete only when all of these are true:
|
||||
|
||||
1. all production callers stop using `Namespace.method(...)` facade calls
|
||||
2. all direct test callers stop using the facade and instead yield the service from context
|
||||
3. the service file no longer has `makeRuntime(...)`
|
||||
4. the service file no longer exports runtime-backed facade helpers
|
||||
5. `grep` for the migrated facade methods only finds the service implementation itself or unrelated names
|
||||
|
||||
## Caller templates
|
||||
|
||||
### Route handlers
|
||||
|
||||
Use one `AppRuntime.runPromise(Effect.gen(...))` body and yield the service inside it.
|
||||
|
||||
```ts
|
||||
const value = await AppRuntime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const pty = yield* Pty.Service
|
||||
return yield* pty.list()
|
||||
}),
|
||||
)
|
||||
```
|
||||
|
||||
If two service calls are independent, keep them in the same effect body and use `Effect.all(...)`.
|
||||
|
||||
### Plain async CLI or script entrypoints
|
||||
|
||||
If the caller is not itself an Effect service yet, still prefer one contiguous `AppRuntime.runPromise(Effect.gen(...))` block for the whole unit of work.
|
||||
|
||||
```ts
|
||||
const skills = await AppRuntime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const auth = yield* Auth.Service
|
||||
const skill = yield* Skill.Service
|
||||
yield* auth.set(key, info)
|
||||
return yield* skill.all()
|
||||
}),
|
||||
)
|
||||
```
|
||||
|
||||
Only fall back to `AppRuntime.runPromise(Service.use(...))` for truly isolated one-off calls or awkward callback boundaries. Do not stack multiple tiny `runPromise(...)` calls in the same contiguous workflow.
|
||||
|
||||
This is the right intermediate state. Do not block facade removal on effectifying the whole CLI file.
|
||||
|
||||
### Bootstrap or fire-and-forget startup code
|
||||
|
||||
If the old facade call existed only to kick off initialization, call the service through the existing runtime for that file.
|
||||
|
||||
```ts
|
||||
void BootstrapRuntime.runPromise(Vcs.Service.use((svc) => svc.init()))
|
||||
```
|
||||
|
||||
Do not reintroduce a dedicated runtime in the service just for bootstrap.
|
||||
|
||||
### Tests
|
||||
|
||||
Convert facade tests to full effect style.
|
||||
|
||||
```ts
|
||||
it.effect("does the thing", () =>
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* Pty.Service
|
||||
const info = yield* svc.create({ command: "cat", title: "a" })
|
||||
yield* svc.remove(info.id)
|
||||
}).pipe(Effect.provide(Pty.defaultLayer)),
|
||||
)
|
||||
```
|
||||
|
||||
If the repo test already uses `testEffect(...)`, prefer `testEffect(Service.defaultLayer)` and `yield* Service.Service` inside the test body.
|
||||
|
||||
Do not route tests through `AppRuntime` unless the test is explicitly exercising the app runtime. For facade removal, tests should usually provide the specific service layer they need.
|
||||
|
||||
If the test uses `provideTmpdirInstance(...)`, remember that fixture needs a live `ChildProcessSpawner` layer. For services whose `defaultLayer` does not already provide that infra, prefer the repo-standard cross-spawn layer:
|
||||
|
||||
```ts
|
||||
const infra = CrossSpawnSpawner.defaultLayer
|
||||
|
||||
const it = testEffect(Layer.mergeAll(MyService.defaultLayer, infra))
|
||||
```
|
||||
|
||||
Without that extra layer, tests fail at runtime with `Service not found: effect/process/ChildProcessSpawner`.
|
||||
|
||||
## Questions already answered
|
||||
|
||||
### Do we need to effectify the whole caller first?
|
||||
|
||||
No.
|
||||
|
||||
- route files: compose the handler with `AppRuntime.runPromise(Effect.gen(...))`
|
||||
- CLI and scripts: use `AppRuntime.runPromise(Service.use(...))`
|
||||
- bootstrap: use the existing bootstrap runtime
|
||||
|
||||
Facade removal does not require a bigger refactor than that.
|
||||
|
||||
### Should tests keep calling the namespace from async test bodies?
|
||||
|
||||
No. Convert them now.
|
||||
|
||||
The end state is `yield* svc.method(...)`, not `await Namespace.method(...)` inside `async` tests.
|
||||
|
||||
### Should we keep `runPromise` exported for convenience?
|
||||
|
||||
No. For this batch the goal is to delete the service-local runtime entirely.
|
||||
|
||||
### What if a route has websocket callbacks or nested async handlers?
|
||||
|
||||
Keep the route shape, but replace each facade call with `AppRuntime.runPromise(Service.use(...))` or wrap the surrounding async section in one `Effect.gen(...)` when practical. Do not keep the service facade just because the route has callback-shaped code.
|
||||
|
||||
### Should we use one `runPromise` per service call?
|
||||
|
||||
No.
|
||||
|
||||
Default to one contiguous `AppRuntime.runPromise(Effect.gen(...))` block per handler, command, or workflow. Yield every service you need inside that block.
|
||||
|
||||
Multiple tiny `runPromise(...)` calls are only acceptable when the caller structure forces it, such as websocket lifecycle callbacks, external callback APIs, or genuinely unrelated one-off operations.
|
||||
|
||||
### Should we wrap a single service expression in `Effect.gen(...)`?
|
||||
|
||||
Usually no.
|
||||
|
||||
Prefer the direct form when there is only one expression:
|
||||
|
||||
```ts
|
||||
await Effect.runPromise(FileSystem.Service.use((svc) => svc.read({ path })))
|
||||
```
|
||||
|
||||
Use `Effect.gen(...)` when the workflow actually needs multiple yielded values or branching.
|
||||
|
||||
## Learnings
|
||||
|
||||
These were the recurring mistakes and useful corrections from the first two batches:
|
||||
|
||||
1. Tests should usually provide the specific service layer, not `AppRuntime`.
|
||||
2. If a test uses `provideTmpdirInstance(...)` and needs child processes, prefer `CrossSpawnSpawner.defaultLayer`.
|
||||
3. Location-scoped services may need both the service layer and the right location fixture. `FileSystem` tests, for example, provide `Location.Service` plus `FileSystem.locationLayer`.
|
||||
4. Do not wrap a single `Service.use(...)` call in `Effect.gen(...)` just to return it. Use the direct form.
|
||||
5. For CLI readability, extract file-local preload helpers when the handler starts doing config load + service load + batched effect fanout inline.
|
||||
6. When rebasing a facade branch after nearby merges, prefer the already-cleaned service/test version over older inline facade-era code.
|
||||
|
||||
## Remaining work
|
||||
|
||||
Most of the original facade-removal backlog is already done. The practical remaining work is narrower now:
|
||||
|
||||
1. remove the `Npm` runtime-backed facade from `src/npm/index.ts`
|
||||
2. remove the `TuiConfig` runtime-backed facade from `src/cli/cmd/tui/config/tui.ts`
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] `src/npm/index.ts` (`Npm`) - still exports runtime-backed async facade helpers on top of `Npm.Service`
|
||||
- [ ] `src/cli/cmd/tui/config/tui.ts` (`TuiConfig`) - still exports runtime-backed async facade helpers on top of `TuiConfig.Service`
|
||||
- [x] `src/session/session.ts` / `src/session/prompt.ts` / `src/session/revert.ts` / `src/session/summary.ts` - service-local facades removed
|
||||
- [x] `src/agent/agent.ts` (`Agent`) - service-local facades removed
|
||||
- [x] `src/permission/index.ts` (`Permission`) - service-local facades removed
|
||||
- [x] `src/worktree/index.ts` (`Worktree`) - service-local facades removed
|
||||
- [x] `src/plugin/index.ts` (`Plugin`) - service-local facades removed
|
||||
- [x] `src/snapshot/index.ts` (`Snapshot`) - service-local facades removed
|
||||
- [x] `../core/src/filesystem.ts` (`FileSystem`) - legacy opencode service removed
|
||||
- [x] `src/lsp/index.ts` (`LSP`) - facades removed and merged
|
||||
- [x] `src/mcp/index.ts` (`MCP`) - facades removed and merged
|
||||
- [x] `src/config/config.ts` (`Config`) - facades removed and merged
|
||||
- [x] `src/provider/provider.ts` (`Provider`) - facades removed and merged
|
||||
- [x] `src/pty/index.ts` (`Pty`) - facades removed and merged
|
||||
- [x] `src/skill/index.ts` (`Skill`) - facades removed and merged
|
||||
- [x] `src/project/vcs.ts` (`Vcs`) - facades removed and merged
|
||||
- [x] `src/tool/registry.ts` (`ToolRegistry`) - facades removed and merged
|
||||
- [x] `src/auth/index.ts` (`Auth`) - facades removed and merged
|
||||
|
||||
## Excluded `makeRuntime(...)` sites
|
||||
|
||||
- `src/bus/index.ts` - core bus plumbing, not a normal facade-removal target.
|
||||
- `src/effect/cross-spawn-spawner.ts` - runtime helper for `ChildProcessSpawner`, not a service namespace facade.
|
||||
247
packages/opencode/specs/effect/guide.md
Normal file
247
packages/opencode/specs/effect/guide.md
Normal file
@@ -0,0 +1,247 @@
|
||||
# Effect Guide
|
||||
|
||||
How we write Effect code in `packages/opencode`. The companion roadmap is
|
||||
[`todo.md`](./todo.md).
|
||||
|
||||
This guide describes the preferred shape for new work and migrations. If a
|
||||
legacy file differs, migrate it only when it is already in scope.
|
||||
|
||||
## Service Shape
|
||||
|
||||
Use one module per service: flat top-level exports, traced Effect methods,
|
||||
explicit layers, and a self-reexport at the bottom.
|
||||
|
||||
```ts
|
||||
export interface Interface {
|
||||
readonly get: (id: FooID) => Effect.Effect<FooInfo, FooError>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/Foo") {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const state = yield* InstanceState.make<State>(Effect.fn("Foo.state")(() => Effect.succeed({})))
|
||||
|
||||
const get = Effect.fn("Foo.get")(function* (id: FooID) {
|
||||
const s = yield* InstanceState.get(state)
|
||||
return yield* loadFoo(s, id)
|
||||
})
|
||||
|
||||
return Service.of({ get })
|
||||
}),
|
||||
)
|
||||
|
||||
export const defaultLayer = layer.pipe(Layer.provide(FooDep.defaultLayer))
|
||||
|
||||
export * as Foo from "./foo"
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Do not use `export namespace Foo { ... }`.
|
||||
- Use `Effect.fn("Foo.method")` for public service methods.
|
||||
- Use `Effect.fnUntraced` for small internal helpers that do not need a
|
||||
span.
|
||||
- Keep helpers as non-exported top-level declarations in the same file.
|
||||
- Self-reexport with `export * as Foo from "."` for `index.ts`, otherwise
|
||||
`export * as Foo from "./foo"`.
|
||||
- In `src/config`, keep the existing top-of-file self-export pattern.
|
||||
|
||||
## Runtime Boundaries
|
||||
|
||||
Most code should run through [`AppRuntime`](../../src/effect/app-runtime.ts).
|
||||
It hosts `AppLayer`, shares the global `memoMap`, and restores the current
|
||||
instance/workspace refs when crossing from non-Effect code.
|
||||
|
||||
Use `AppRuntime.runPromise(effect)` at app boundaries such as CLI commands,
|
||||
HTTP handlers, or plain async adapters.
|
||||
|
||||
`makeRuntime(...)` still exists for a few intentional service-local
|
||||
boundaries and migration leftovers. Do not add a new service-local runtime
|
||||
unless the service truly cannot live in `AppLayer`.
|
||||
|
||||
## Runtime Flags
|
||||
|
||||
Read opencode runtime flags through
|
||||
[`RuntimeFlags.Service`](../../src/effect/runtime-flags.ts), not through
|
||||
mutable `Flag` or late `process.env` reads.
|
||||
|
||||
Tests should vary behavior with explicit layer variants:
|
||||
|
||||
```ts
|
||||
const it = testEffect(MyService.defaultLayer.pipe(Layer.provide(RuntimeFlags.layer({ experimentalReferences: true }))))
|
||||
```
|
||||
|
||||
Do not mutate `process.env` or `Flag` after services/layers are built.
|
||||
|
||||
## Per-Instance State
|
||||
|
||||
Use [`InstanceState`](../../src/effect/instance-state.ts) when two open
|
||||
directories should not share one copy of a service's state. It is backed by
|
||||
a `ScopedCache`, keyed by directory, and disposed automatically when an
|
||||
instance is unloaded.
|
||||
|
||||
Put subscriptions, finalizers, and scoped background work inside the
|
||||
`InstanceState.make(...)` initializer:
|
||||
|
||||
```ts
|
||||
const cache =
|
||||
yield *
|
||||
InstanceState.make<State>(
|
||||
Effect.fn("Foo.state")(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
|
||||
yield* bus.subscribeAll().pipe(
|
||||
Stream.runForEach((event) => handleEvent(event)),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
|
||||
yield* Effect.acquireRelease(openResource, closeResource)
|
||||
|
||||
return yield* loadInitialState()
|
||||
}),
|
||||
)
|
||||
```
|
||||
|
||||
Do not add separate `started` flags on top of `InstanceState`. Let
|
||||
`ScopedCache` handle run-once and deduplication.
|
||||
|
||||
To make `init()` non-blocking, fork at the caller/bootstrap boundary. Do
|
||||
not fork inside `InstanceState.make(...)` just to return early with
|
||||
partially initialized state.
|
||||
|
||||
## Errors
|
||||
|
||||
Expected domain failures belong on the Effect error channel. Defects are
|
||||
for bugs, impossible states, and final unknown-boundary fallbacks.
|
||||
|
||||
```ts
|
||||
export class SessionBusyError extends Schema.TaggedErrorClass<SessionBusyError>()("SessionBusyError", {
|
||||
sessionID: SessionID,
|
||||
message: Schema.String,
|
||||
}) {}
|
||||
|
||||
export type Error = Storage.Error | SessionBusyError
|
||||
|
||||
export interface Interface {
|
||||
readonly get: (id: SessionID) => Effect.Effect<Info, Error>
|
||||
}
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Use `Schema.TaggedErrorClass` for new expected domain errors.
|
||||
- Export a domain-level `Error` union from service modules.
|
||||
- In `Effect.gen` / `Effect.fn`, prefer `yield* new MyError(...)` for
|
||||
direct expected failures.
|
||||
- Use `Schema.Defect` for unknown cause fields.
|
||||
- Use `Effect.try(...)`, `Effect.tryPromise(...)`, `Effect.mapError`,
|
||||
`Effect.catchTag`, and `Effect.catchTags` to translate external
|
||||
failures into domain errors.
|
||||
- Do not use `Effect.die(...)` for user, IO, validation, missing-resource,
|
||||
auth, provider, or busy-state failures.
|
||||
|
||||
## HTTP Error Boundaries
|
||||
|
||||
Service modules stay HTTP-agnostic. They should not import HTTP status
|
||||
codes, `HttpApiError`, `HttpServerResponse`, or route-specific error
|
||||
schemas.
|
||||
|
||||
HTTP handlers translate service errors into endpoint-declared public error
|
||||
schemas. Keep mappings inline when they are one-off; extract tiny shared
|
||||
helpers only when the same translation repeats.
|
||||
|
||||
Do not turn generic middleware into a registry of domain errors. Middleware
|
||||
should handle cross-cutting concerns and the final unknown-defect fallback.
|
||||
|
||||
Preserve legacy public wire shapes, such as `{ name, data }`, until a
|
||||
deliberate breaking API change.
|
||||
|
||||
## Schemas
|
||||
|
||||
Use Effect Schema as the source of truth.
|
||||
|
||||
- Use `Schema.Class` for exported data objects with a clear identity.
|
||||
- Use `Schema.Struct` for local shapes and simple nested objects.
|
||||
- Use `Schema.brand` for single-value IDs.
|
||||
- Reuse named refinements instead of re-spelling constraints.
|
||||
- Prefer narrow boundary helpers over generic Schema-to-Zod bridges.
|
||||
|
||||
Intentional boundaries:
|
||||
|
||||
- Public plugin tools still expose Zod through `tool.schema = z`.
|
||||
- Tool parameter JSON Schema is generated through tool-specific helpers.
|
||||
- Public config and TUI schemas are generated through the schema script.
|
||||
|
||||
## Preferred Services
|
||||
|
||||
In effectified code, yield existing services instead of dropping to ad hoc
|
||||
platform APIs.
|
||||
|
||||
- Use `FSUtil.Service` instead of raw `fs/promises` for app file IO.
|
||||
- Use `AppProcess.Service` instead of direct `ChildProcessSpawner.spawn` or
|
||||
legacy process helpers.
|
||||
- Use `HttpClient.HttpClient` instead of raw `fetch` inside Effect code.
|
||||
- Use `Path.Path`, `Config`, `Clock`, and `DateTime` when already inside
|
||||
Effect.
|
||||
- Use `Effect.callback` for callback-based APIs.
|
||||
- Use `Effect.void` instead of `Effect.succeed(undefined)`.
|
||||
- Use `Effect.cached` when concurrent callers should share one in-flight
|
||||
computation.
|
||||
|
||||
For background loops, use `Effect.repeat` or `Effect.schedule` with
|
||||
`Effect.forkScoped` in the owning layer/state scope.
|
||||
|
||||
## Promise And ALS Bridges
|
||||
|
||||
[`EffectBridge`](../../src/effect/bridge.ts) is the sanctioned helper for
|
||||
Promise/callback interop that needs to preserve instance/workspace context.
|
||||
It preserves explicit `InstanceRef` / `WorkspaceRef` context for effects run
|
||||
through the bridge. Plain JS callbacks that need instance data should receive
|
||||
that data explicitly.
|
||||
|
||||
## Testing
|
||||
|
||||
Detailed test migration rules live in
|
||||
[`test/EFFECT_TEST_MIGRATION.md`](../../test/EFFECT_TEST_MIGRATION.md).
|
||||
|
||||
Core pattern:
|
||||
|
||||
```ts
|
||||
const it = testEffect(Layer.mergeAll(MyService.defaultLayer))
|
||||
|
||||
describe("my service", () => {
|
||||
it.instance("does the thing", () =>
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* MyService.Service
|
||||
expect(yield* svc.run()).toEqual("ok")
|
||||
}),
|
||||
)
|
||||
})
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- Use `it.effect(...)` for TestClock/TestConsole tests.
|
||||
- Use `it.live(...)` for real timers, filesystem mtimes, child processes,
|
||||
git, locks, or other live integration behavior.
|
||||
- Use `it.instance(...)` for service tests that need a scoped instance.
|
||||
- Prefer Effect-aware fixtures from `test/fixture/fixture.ts`.
|
||||
- Avoid sleeps; wait for real events or deterministic state transitions.
|
||||
- Avoid mutable `process.env`, `Flag`, or module-global changes after
|
||||
layers are built.
|
||||
- Use `Layer.mock` for partial service stubs.
|
||||
- Avoid custom `ManagedRuntime`, `attach(...)`, or ad hoc `run(...)` test
|
||||
wrappers.
|
||||
|
||||
## Verification
|
||||
|
||||
From `packages/opencode`:
|
||||
|
||||
```bash
|
||||
bun run typecheck
|
||||
bun run test -- path/to/test.ts
|
||||
```
|
||||
|
||||
Do not run tests from the repo root; the repo has a guard for that.
|
||||
13
packages/opencode/specs/effect/instance-context.md
Normal file
13
packages/opencode/specs/effect/instance-context.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# Instance Context
|
||||
|
||||
Instance selection is now Effect-provided context.
|
||||
|
||||
Use these APIs:
|
||||
|
||||
- `InstanceRef` for the current project context.
|
||||
- `WorkspaceRef` for the current workspace id.
|
||||
- `InstanceState.context` / `InstanceState.directory` inside Effect services that require an instance.
|
||||
- `InstanceStore` at entry boundaries that need to load, reload, or dispose project contexts.
|
||||
- `EffectBridge` for native, plugin, or plain JavaScript callback boundaries that need to re-enter Effect with captured refs.
|
||||
|
||||
Do not add new ambient instance globals. Promise and callback boundaries should either stay in Effect, use `EffectBridge`, or pass the required context explicitly.
|
||||
30
packages/opencode/specs/effect/loose-ends.md
Normal file
30
packages/opencode/specs/effect/loose-ends.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Effect loose ends
|
||||
|
||||
Small follow-ups that do not fit neatly into the main facade, route, tool, or schema migration checklists.
|
||||
|
||||
## Config / TUI
|
||||
|
||||
- [ ] `cli/cmd/tui/config/tui.ts` - finish the internal Effect migration.
|
||||
Keep the current precedence and migration semantics intact while converting the remaining internal async helpers (`loadState`, `mergeFile`, `loadFile`, `load`) to `Effect.gen(...)` / `Effect.fn(...)`.
|
||||
- [ ] `cli/cmd/tui/config/tui.ts` callers - once the internal service is stable, migrate plain async callers to use `TuiConfig.Service` directly where that actually simplifies the code.
|
||||
Likely first callers: `cli/cmd/tui/attach.ts`, `cli/cmd/tui/thread.ts`, `cli/cmd/tui/plugin/runtime.ts`.
|
||||
- [x] `env/index.ts` - already uses `InstanceState.make(...)`.
|
||||
|
||||
## ConfigPaths
|
||||
|
||||
- [ ] `config/paths.ts` - split pure helpers from effectful helpers.
|
||||
Keep `fileInDirectory(...)` as a plain function.
|
||||
- [ ] `config/paths.ts` - add a `ConfigPaths.Service` for the effectful operations so callers do not inherit `FSUtil.Service` directly.
|
||||
Initial service surface should cover:
|
||||
- `projectFiles(...)`
|
||||
- `directories(...)`
|
||||
- `readFile(...)`
|
||||
- `parseText(...)`
|
||||
- [ ] `config/config.ts` - switch internal config loading from `Effect.promise(() => ConfigPaths.*(...))` to `yield* paths.*(...)` once the service exists.
|
||||
- [ ] `cli/cmd/tui/config/tui.ts` - switch TUI config loading from async `ConfigPaths.*` wrappers to the `ConfigPaths.Service` once that service exists.
|
||||
- [ ] `cli/cmd/tui/config/tui-migrate.ts` - decide whether to leave this as a plain async module using wrapper functions or effectify it fully after `ConfigPaths.Service` lands.
|
||||
|
||||
## Notes
|
||||
|
||||
- Prefer small, semantics-preserving config migrations. Config precedence, legacy key migration, and plugin origin tracking are easy to break accidentally.
|
||||
- When changing config loading internals, rerun the config and TUI suites first before broad package sweeps.
|
||||
62
packages/opencode/specs/effect/migration.md
Normal file
62
packages/opencode/specs/effect/migration.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# Effect Migration Patterns
|
||||
|
||||
This is the compact reference for moving code toward the current Effect
|
||||
shape. The high-level roadmap is [`todo.md`](./todo.md); examples and
|
||||
rules are in [`guide.md`](./guide.md).
|
||||
|
||||
## Default Shape
|
||||
|
||||
- Service methods return `Effect`.
|
||||
- Service methods are named with `Effect.fn("Domain.method")`.
|
||||
- Expected failures are typed errors on the error channel.
|
||||
- Dependencies are yielded once at layer construction and closed over by
|
||||
methods.
|
||||
- `defaultLayer` wires production dependencies; tests can use open layers
|
||||
when replacing dependencies.
|
||||
|
||||
## Instance State
|
||||
|
||||
Use `InstanceState` for per-directory state, subscriptions, scoped
|
||||
background work, and per-instance cleanup.
|
||||
|
||||
Do not add ad hoc `started` flags on top of `InstanceState`; the scoped
|
||||
cache handles run-once and concurrent deduplication.
|
||||
|
||||
## Runtime Boundaries
|
||||
|
||||
Prefer `AppRuntime` for crossing from non-Effect code into the shared app
|
||||
layer.
|
||||
|
||||
`makeRuntime(...)` exists for intentional service-local boundaries and
|
||||
legacy facades. Do not add new service-local runtimes unless the service is
|
||||
genuinely outside `AppLayer`.
|
||||
|
||||
## Platform Edges
|
||||
|
||||
- Use `FSUtil.Service` instead of raw filesystem APIs in
|
||||
effectified services.
|
||||
- Use `AppProcess.Service` instead of raw process wrappers.
|
||||
- Use `HttpClient.HttpClient` instead of raw `fetch` in Effect code.
|
||||
- Use `Effect.cached` for shared in-flight work.
|
||||
- Use `Effect.callback` for callback APIs.
|
||||
|
||||
## Tests During Migration
|
||||
|
||||
When migrating code, migrate touched tests toward
|
||||
[`test/EFFECT_TEST_MIGRATION.md`](../../test/EFFECT_TEST_MIGRATION.md):
|
||||
|
||||
- `testEffect(...)`
|
||||
- `it.effect`, `it.live`, or `it.instance`
|
||||
- explicit layers for behavior changes
|
||||
- deterministic waits instead of sleeps
|
||||
- no mutable env/global flags after layers are built
|
||||
|
||||
## Migration Checklist
|
||||
|
||||
- [ ] The code has a single Effect body instead of Promise wrappers around
|
||||
service calls.
|
||||
- [ ] Expected failures are typed errors, not thrown exceptions or defects.
|
||||
- [ ] Layer requirements are explicit.
|
||||
- [ ] Tests use Effect-aware fixtures and focused layers.
|
||||
- [ ] Public behavior and wire shapes are preserved unless intentionally
|
||||
changed.
|
||||
61
packages/opencode/specs/effect/routes.md
Normal file
61
packages/opencode/specs/effect/routes.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# HTTP Route Patterns
|
||||
|
||||
Current guidance for `packages/opencode/src/server/routes/instance/httpapi`.
|
||||
|
||||
## Handler Shape
|
||||
|
||||
Use `HttpApiBuilder.group(...)` for normal JSON and streaming HTTP API
|
||||
endpoints. Yield stable services once while building the handler layer,
|
||||
then close over those services in endpoint implementations.
|
||||
|
||||
```ts
|
||||
export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", (handlers) =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
|
||||
return handlers.handle("list", () => session.list())
|
||||
}),
|
||||
)
|
||||
```
|
||||
|
||||
Use raw `HttpRouter` only for routes that do not fit the request/response
|
||||
HttpApi model, such as WebSocket upgrades or catch-all fallback routes.
|
||||
|
||||
Do not rebuild stable layers inside request handlers. Provide stable
|
||||
services at the route/layer boundary and use request-level provisioning
|
||||
only for request-derived context.
|
||||
|
||||
## Error Boundaries
|
||||
|
||||
Expected service errors should be mapped at the handler boundary to
|
||||
endpoint-declared public HTTP errors. Keep one-off mappings inline. Extract
|
||||
small helpers when the same mapping repeats.
|
||||
|
||||
Generic middleware should not become a domain-error mapper. It should
|
||||
handle cross-cutting concerns and final unknown-defect fallback.
|
||||
|
||||
Public JSON errors should be explicit schema contracts declared on each
|
||||
endpoint or group. Built-in `HttpApiError.*` is fine only when its generated
|
||||
body is intentionally the public wire shape.
|
||||
|
||||
Preserve existing `{ name, data }` error bodies until a deliberate breaking
|
||||
API change.
|
||||
|
||||
## OpenAPI Compatibility
|
||||
|
||||
`public.ts` still owns SDK/OpenAPI compatibility transforms. Shrink those
|
||||
transforms by tightening source schemas one workaround at a time.
|
||||
|
||||
When an OpenAPI-visible source schema changes:
|
||||
|
||||
- verify the generated SDK diff is intentional
|
||||
- preserve legacy compatibility unless the PR explicitly changes it
|
||||
- prefer source-schema fixes over new post-processing rules
|
||||
|
||||
## Checklist For Route PRs
|
||||
|
||||
- [ ] Stable services are yielded at handler-layer construction.
|
||||
- [ ] Expected domain errors are translated at the route boundary.
|
||||
- [ ] Endpoint/group error schemas describe the public body and status.
|
||||
- [ ] Middleware does not gain new domain-specific name checks.
|
||||
- [ ] Raw routes are used only when HttpApi is the wrong abstraction.
|
||||
88
packages/opencode/specs/effect/schema.md
Normal file
88
packages/opencode/specs/effect/schema.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Schema Migration
|
||||
|
||||
Use Effect Schema as the source of truth for domain models, DTOs, IDs,
|
||||
inputs, outputs, and typed errors.
|
||||
|
||||
This is guidance, not an inventory. Do not use this file to track which
|
||||
schema modules are complete; verify current state with `git grep` before
|
||||
starting a migration.
|
||||
|
||||
## Preferred Shapes
|
||||
|
||||
Use `Schema.Class` for exported data objects with a clear domain identity:
|
||||
|
||||
```ts
|
||||
export class Info extends Schema.Class<Info>("Foo.Info")({
|
||||
id: FooID,
|
||||
name: Schema.String,
|
||||
enabled: Schema.Boolean,
|
||||
}) {}
|
||||
```
|
||||
|
||||
Use `Schema.Struct` for local shapes and simple nested objects:
|
||||
|
||||
```ts
|
||||
const Payload = Schema.Struct({
|
||||
id: FooID,
|
||||
value: Schema.String,
|
||||
})
|
||||
```
|
||||
|
||||
Use `Schema.TaggedErrorClass` for expected domain errors:
|
||||
|
||||
```ts
|
||||
export class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()("FooNotFoundError", {
|
||||
id: FooID,
|
||||
}) {}
|
||||
```
|
||||
|
||||
Use branded schema-backed IDs for single-value domain identifiers.
|
||||
|
||||
## Boundary Rule
|
||||
|
||||
Effect Schema should own the type. Boundaries should consume Effect Schema
|
||||
directly or use narrow boundary-specific helpers. Avoid reintroducing a
|
||||
generic Effect Schema -> Zod bridge.
|
||||
|
||||
Current intentional boundaries:
|
||||
|
||||
- Public plugin tools still expose Zod through `tool.schema = z`.
|
||||
- Tool parameters use tool-specific JSON Schema helpers.
|
||||
- Public config and TUI schema generation goes through the schema script.
|
||||
- AI SDK object generation uses Standard Schema / JSON Schema helpers.
|
||||
|
||||
When Zod must stay temporarily, leave a short note explaining the boundary
|
||||
or compatibility reason.
|
||||
|
||||
## Refinements
|
||||
|
||||
Reuse named refinements instead of re-spelling constraints:
|
||||
|
||||
```ts
|
||||
const PositiveInt = Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0))
|
||||
const NonNegativeInt = Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0))
|
||||
```
|
||||
|
||||
Prefer domain-named leaf schemas when the name improves callers or error
|
||||
messages. Avoid adding brands purely for novelty.
|
||||
|
||||
## Migration Order
|
||||
|
||||
For a domain that still has mixed schemas:
|
||||
|
||||
1. Shared leaf models and branded IDs.
|
||||
2. Exported `Info`, `Input`, `Output`, and event payload types.
|
||||
3. Expected domain errors.
|
||||
4. Service-local internal models.
|
||||
5. HTTP/tool/AI boundary validators.
|
||||
|
||||
Keep public wire shapes stable unless the PR is explicitly a breaking API
|
||||
change.
|
||||
|
||||
## Checklist For A PR
|
||||
|
||||
- [ ] There is one schema source of truth for each migrated type.
|
||||
- [ ] Remaining Zod is an intentional boundary choice.
|
||||
- [ ] Public JSON/OpenAPI output is unchanged or intentionally updated.
|
||||
- [ ] Derived helpers are narrow and boundary-specific.
|
||||
- [ ] Tests assert behavior, not duplicated schema implementation details.
|
||||
58
packages/opencode/specs/effect/server-package.md
Normal file
58
packages/opencode/specs/effect/server-package.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# Server Package Extraction
|
||||
|
||||
Practical reference for a future `packages/server` split after the opencode
|
||||
server moved to the Effect HttpApi backend.
|
||||
|
||||
## Current State
|
||||
|
||||
- The server still lives in `packages/opencode`.
|
||||
- The runtime and app layer are centralized in `src/effect/app-runtime.ts` and
|
||||
`src/effect/run-service.ts`.
|
||||
- The route tree lives under `src/server/routes/instance/httpapi` and is hosted
|
||||
from `src/server/server.ts`.
|
||||
- OpenAPI generation is based on the HttpApi contract plus compatibility
|
||||
translation in `src/server/routes/instance/httpapi/public.ts`.
|
||||
- There is no standalone `packages/server` workspace yet.
|
||||
|
||||
## Future State
|
||||
|
||||
Target package layout:
|
||||
|
||||
- `packages/core` - shared domain services and schemas
|
||||
- `packages/server` - HTTP contracts, handlers, OpenAPI generation, and an
|
||||
embeddable server API
|
||||
- `packages/cli` - TUI and CLI entrypoints
|
||||
- `packages/sdk` - generated from the server OpenAPI spec
|
||||
- `packages/plugin` - plugin authoring surface
|
||||
|
||||
## Extraction Rule
|
||||
|
||||
Do not create a package cycle.
|
||||
|
||||
Until enough shared service code lives outside `packages/opencode`, a future
|
||||
`packages/server` should either:
|
||||
|
||||
- own pure HttpApi contracts only, or
|
||||
- accept host-provided services/layers/callbacks from `packages/opencode`
|
||||
|
||||
It should not import `packages/opencode` services while `packages/opencode`
|
||||
imports it to host routes.
|
||||
|
||||
## Suggested PR Sequence
|
||||
|
||||
1. Keep shrinking OpenAPI compatibility shims in `httpapi/public.ts`.
|
||||
2. Move stable domain schemas into shared packages only when they no longer
|
||||
depend on opencode-local runtime modules.
|
||||
3. Extract pure HttpApi contract modules into `packages/server` once the contract
|
||||
can compile without importing `packages/opencode` implementation details.
|
||||
4. Extract handler factories after their service dependencies can be supplied by
|
||||
a host layer instead of imported directly.
|
||||
5. Move server hosting last, after package ownership is clear.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not revive the old dual-backend migration shape.
|
||||
- Do not split server hosting before service dependencies have a clean package
|
||||
boundary.
|
||||
- Do not switch SDK generation to a new package until generated output is known
|
||||
to remain compatible.
|
||||
241
packages/opencode/specs/effect/todo.md
Normal file
241
packages/opencode/specs/effect/todo.md
Normal file
@@ -0,0 +1,241 @@
|
||||
# Effect TODO
|
||||
|
||||
Short roadmap for Effect cleanup in `packages/opencode`.
|
||||
|
||||
Current patterns and examples live in [`guide.md`](./guide.md). Error
|
||||
boundary migration details live in
|
||||
[`error-boundaries-plan.md`](./error-boundaries-plan.md). Test migration rules live in
|
||||
[`test/EFFECT_TEST_MIGRATION.md`](../../test/EFFECT_TEST_MIGRATION.md).
|
||||
Older deep-dive notes in this directory may still be useful, but treat
|
||||
this roadmap and the guide as the current entry points.
|
||||
|
||||
This is a planning map, not a verified inventory. Before starting a task,
|
||||
re-run a targeted `git grep` from current `dev` and update this file if
|
||||
the inventory changed.
|
||||
|
||||
## Priorities
|
||||
|
||||
```text
|
||||
P0 ERR + RENDER + HTTP
|
||||
Make expected failures typed, render them well, and stop relying on
|
||||
generic HTTP error guesswork.
|
||||
|
||||
P1 TEST
|
||||
Convert touched tests to the ideal Effect test patterns from the guide.
|
||||
|
||||
P2 RF
|
||||
Move mutable runtime flags into typed runtime/config services.
|
||||
|
||||
P3 GLOBAL
|
||||
Make global paths explicit and remove import-time side effects.
|
||||
|
||||
P4 INST + BRIDGE
|
||||
Remove ambient Instance coupling while keeping Promise/callback interop.
|
||||
|
||||
P5 PROC + FS
|
||||
Replace raw process/filesystem edges with typed Effect services.
|
||||
|
||||
P6 OA
|
||||
Shrink OpenAPI compatibility shims as source schemas improve.
|
||||
```
|
||||
|
||||
## Work Paths
|
||||
|
||||
- `ERR` Typed errors — replace legacy `NamedError.create(...)` and
|
||||
`Effect.die(...)` for expected service failures with
|
||||
`Schema.TaggedErrorClass` errors on the Effect error channel.
|
||||
Shrinks: [`NamedError`](../../../core/src/util/error.ts) usage.
|
||||
- `RENDER` User-visible error rendering — preserve structured typed-error
|
||||
details at CLI, HTTP, and tool boundaries.
|
||||
Shrinks: opaque `Error: Name` rendering.
|
||||
- `HTTP` HTTP route cleanup — make route errors explicit instead of
|
||||
relying on generic middleware to guess status/body from error names.
|
||||
Shrinks: [`middleware/error.ts`](../../src/server/routes/instance/httpapi/middleware/error.ts)
|
||||
and route-level compatibility shims.
|
||||
- `TEST` Effect test migration — use `testEffect`, `it.live`, and
|
||||
`it.instance` with explicit layers.
|
||||
Shrinks: Promise-style tests, sleeps, mutable global test flags.
|
||||
- `RF` RuntimeFlags / Flag deletion — move mutable
|
||||
[`Flag`](../../../core/src/flag/flag.ts) reads into typed runtime/config
|
||||
services.
|
||||
Shrinks: [`flag.ts`](../../../core/src/flag/flag.ts),
|
||||
[`test/fixture/flag.ts`](../../test/fixture/flag.ts).
|
||||
- `GLOBAL` Global paths / import side effects — make global path state
|
||||
explicit and testable instead of mutable module state.
|
||||
Shrinks: [`global.ts`](../../../core/src/global.ts) import-time side
|
||||
effects, mutable `Global.Path` overrides, and its `Flag` dependency.
|
||||
- `INST` Instance context — keep project context explicit through Effect refs
|
||||
and bridge boundaries.
|
||||
- `BRIDGE` Promise/callback interop — keep bridge helpers, but reduce
|
||||
legacy ALS coupling.
|
||||
Shrinks: ad hoc Promise/callback re-entry code.
|
||||
- `PROC` AppProcess migration — prefer `AppProcess.Service` over raw
|
||||
process wrappers.
|
||||
Shrinks: direct spawn callsites and legacy process helpers.
|
||||
- `FS` FSUtil migration — prefer `FSUtil.Service` over raw
|
||||
filesystem APIs.
|
||||
Shrinks: direct `fs` / `Bun.file` service callsites where inappropriate.
|
||||
- `RT` Runtime/facade cleanup — remove service-local `makeRuntime`
|
||||
facades when not intentional.
|
||||
Shrinks: async facade exports around services and
|
||||
[`run-service.ts`](../../src/effect/run-service.ts) usage.
|
||||
- `OA` OpenAPI compatibility — tighten source schemas instead of
|
||||
post-processing generated OpenAPI.
|
||||
Shrinks: schema workaround blocks in
|
||||
[`public.ts`](../../src/server/routes/instance/httpapi/public.ts).
|
||||
|
||||
## P0: Errors, Rendering, And HTTP
|
||||
|
||||
This should be the next big cleanup theme. The codebase is moving toward
|
||||
typed Effect failures, but the user-facing boundaries still leak old
|
||||
shapes and sometimes collapse rich errors into opaque strings.
|
||||
|
||||
### Problems
|
||||
|
||||
- Some expected service failures still use `NamedError.create(...)` or
|
||||
collapse to `Effect.die(...)`. The storage/worktree/provider-auth
|
||||
conversions are done; an inventory sweep is needed for the rest.
|
||||
- HTTP error middleware still guesses status codes from error names —
|
||||
some entries (e.g. storage `NotFound`, provider auth) can now be
|
||||
removed, but the middleware overall has not shrunk.
|
||||
- Route handlers and route groups do not consistently declare the public
|
||||
error body they intend to expose.
|
||||
- Repeated route error translations do not yet have a clear home: some
|
||||
should stay inline, some deserve tiny shared mapper helpers.
|
||||
|
||||
### Target Shape
|
||||
|
||||
- Services define expected failures with `Schema.TaggedErrorClass`.
|
||||
- Services export an `Error` union and include it in method return types.
|
||||
- Expected failures stay on the Effect error channel.
|
||||
- `Effect.die(...)` is reserved for defects: bugs, impossible states,
|
||||
violated invariants, or final unknown-boundary fallbacks.
|
||||
- Inside `Effect.gen` / `Effect.fn`, use `yield* new MyError(...)` for
|
||||
direct expected failures.
|
||||
- Domain services do not import HTTP status codes, `HttpApiError`, or
|
||||
route-specific error schemas.
|
||||
- HTTP route groups make their public error contracts obvious.
|
||||
- Handlers map service errors to declared HTTP errors at the boundary.
|
||||
- Shared mapper helpers are only for repeated translations, not a giant
|
||||
central registry of every domain error.
|
||||
- Generic HTTP middleware should shrink; it should not accumulate more
|
||||
name-based domain knowledge.
|
||||
|
||||
### Recently completed
|
||||
|
||||
- [x] `RENDER-1` CLI tagged config error rendering (#27256, tests #27257).
|
||||
- [x] `ERR-1` [`storage/storage.ts`](../../src/storage/storage.ts) typed
|
||||
`NotFoundError` (#27265) and removal of the server defect fallback
|
||||
(#27287).
|
||||
- [x] `ERR-2` [`worktree/index.ts`](../../src/worktree/index.ts) typed
|
||||
errors (#27296).
|
||||
- [x] `ERR-3` [`provider/auth.ts`](../../src/provider/auth.ts) typed
|
||||
validation/oauth errors (#27301).
|
||||
- [x] `HTTP-1` Unknown-500 details no longer leaked (#27251); follow-up
|
||||
to stop exposing named defects (#27471).
|
||||
- [x] Session message reads typed and made effectful (#27269, #27275,
|
||||
#27280, #27291).
|
||||
- [x] Session HTTP error contracts tightened (#27308); busy-session
|
||||
mapping centralized (#27375, #27473).
|
||||
- [x] Provider init (#27484) and LSP init (#27494) errors typed.
|
||||
|
||||
### First PR Candidates
|
||||
|
||||
- [ ] `HTTP-2` Audit one route group for explicit error contracts and
|
||||
decide which mappings stay inline vs. shared helper.
|
||||
- [ ] `ERR-4` Sweep remaining `NamedError.create(...)` and
|
||||
`Effect.die(...)` callsites for expected failures — re-run `git
|
||||
grep` to build a current inventory.
|
||||
- [ ] `RENDER-2` Audit CLI and TUI surfaces for any remaining opaque
|
||||
`Error: Name` rendering of typed errors.
|
||||
|
||||
## P1: Tests
|
||||
|
||||
When touching tests, migrate them toward the ideal patterns in
|
||||
[`test/EFFECT_TEST_MIGRATION.md`](../../test/EFFECT_TEST_MIGRATION.md):
|
||||
|
||||
- Use `testEffect(...)` with explicit layers.
|
||||
- Prefer `it.instance(...)` for service tests that need an instance.
|
||||
- Prefer `it.live(...)` for real timers, filesystem mtimes, child
|
||||
processes, git, locks, or other live integration behavior.
|
||||
- Avoid sleeps; wait on real events or deterministic state transitions.
|
||||
- Do not mutate `process.env` or mutable globals after layers are built.
|
||||
- Use explicit layer variants, such as `RuntimeFlags.layer(...)`, for
|
||||
behavior changes.
|
||||
|
||||
## P2: RuntimeFlags / Flag Deletion
|
||||
|
||||
Recently completed:
|
||||
|
||||
- [x] Plugin/pure-mode flags moved to RuntimeFlags.
|
||||
- [x] Tool visibility flags moved to RuntimeFlags.
|
||||
- [x] Built-in websearch provider selection uses the same runtime flags as
|
||||
tool visibility.
|
||||
- [x] Removed global default-plugin disabling from test preload.
|
||||
- [x] `RF-1` Reference reads routed through runtime flags (#27318).
|
||||
- [x] `RF-2` Plan-mode prompt read routed through runtime flags (#27320).
|
||||
- [x] `RF-3` Event-system reads routed through runtime flags (#27323).
|
||||
- [x] `RF-4` Workspaces reads routed through runtime flags for session
|
||||
(#27335), sync (#27336), and control-plane (#27337).
|
||||
- [x] LLM client (#27368) and installation client (#27369) routed
|
||||
through runtime flags.
|
||||
- [x] TUI plugin runtime flags simplified (#27506).
|
||||
- [x] Background-subagents flag moved to RuntimeFlags, then removed
|
||||
(`refactor(task): use runtime flag for background subagents`,
|
||||
`refactor(flags): remove background subagents flag`).
|
||||
|
||||
Remaining cleanup:
|
||||
|
||||
- [ ] Sweep lingering `Flag.*` reads — many CLI/TUI/config/observability
|
||||
callsites still import [`flag.ts`](../../../core/src/flag/flag.ts).
|
||||
Decide per-callsite whether to route through RuntimeFlags, accept
|
||||
as legitimate env/config boundary, or migrate to typed `Config`.
|
||||
- [ ] Delete [`test/fixture/flag.ts`](../../test/fixture/flag.ts) once
|
||||
tests no longer mutate `Flag`.
|
||||
- [ ] Delete [`flag.ts`](../../../core/src/flag/flag.ts) once no packages
|
||||
import it.
|
||||
|
||||
## P3: Global Paths
|
||||
|
||||
[`global.ts`](../../../core/src/global.ts) is real connective tissue, not
|
||||
just cosmetic ugliness. It currently mixes path calculation, import-time
|
||||
directory creation, `Flock` setup, mutable exported `Path` state, and a
|
||||
`Flag` dependency.
|
||||
|
||||
Problems to reduce:
|
||||
|
||||
- Importing the module creates directories.
|
||||
- Tests override `Global.Path` by mutating exported module state.
|
||||
- Most callers use `Global.Path` directly instead of the Effect service.
|
||||
- `Global.make()` still reads mutable `Flag.OPENCODE_CONFIG_DIR`.
|
||||
|
||||
Next PR candidates:
|
||||
|
||||
- [ ] Replace mutable `Global.Path` test overrides with explicit test
|
||||
layers or scoped helpers.
|
||||
- [ ] Move directory creation and `Flock` setup behind an explicit init
|
||||
boundary where possible.
|
||||
- [ ] Remove the `Flag` dependency from global path resolution.
|
||||
|
||||
## P4: Instance And Bridge
|
||||
|
||||
Instance context migration is complete for the legacy sync shim. Promise and callback interop continues through [`effect/bridge.ts`](../../src/effect/bridge.ts).
|
||||
|
||||
Current rules:
|
||||
|
||||
- Effect services read instance data from `InstanceRef`, `WorkspaceRef`, `InstanceState`, or explicit arguments.
|
||||
- Plain JavaScript callback boundaries use `EffectBridge` or explicit context arguments.
|
||||
- Runtime entrypoints must provide refs explicitly when they are instance-scoped.
|
||||
|
||||
## Lower Priority Tracks
|
||||
|
||||
- `PROC` / `FS` — continue AppProcess and FSUtil migrations as
|
||||
focused PRs when touching relevant files.
|
||||
- `RT` — remove service-local runtime facades only when they are not an
|
||||
intentional boundary.
|
||||
- `OA` — shrink [`public.ts`](../../src/server/routes/instance/httpapi/public.ts)
|
||||
by tightening source schemas one workaround at a time.
|
||||
- `fetch` → `HttpClient` — migrate raw fetch callsites when the caller is
|
||||
already effectful or being effectified.
|
||||
- `Tools` — remaining tool cleanup is narrow: `webfetch` HTML extraction
|
||||
and `shell` raw stream/promise edges.
|
||||
88
packages/opencode/specs/effect/tools.md
Normal file
88
packages/opencode/specs/effect/tools.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Tool migration
|
||||
|
||||
Practical reference for the current tool-migration state in `packages/opencode`.
|
||||
|
||||
## Status
|
||||
|
||||
`Tool.Def.execute` and `Tool.Info.init` already return `Effect` on this branch, and the built-in tool surface is now largely on the target shape.
|
||||
|
||||
The current exported tools in `src/tool` all use `Tool.define(...)` with Effect-based initialization, and nearly all of them already build their tool body with `Effect.gen(...)` and `Effect.fn(...)`.
|
||||
|
||||
So the remaining work is no longer "convert tools to Effect at all". The remaining work is mostly:
|
||||
|
||||
1. remove Promise and raw platform bridges inside individual tool bodies
|
||||
2. swap tool internals to Effect-native services like `FSUtil`, `HttpClient`, and `ChildProcessSpawner`
|
||||
3. keep tests and callers aligned with `yield* info.init()` and real service graphs
|
||||
|
||||
## Current shape
|
||||
|
||||
`Tool.define(...)` is already the Effect-native helper here.
|
||||
|
||||
- `init` is an `Effect`
|
||||
- `info.init()` returns an `Effect`
|
||||
- `execute(...)` returns an `Effect`
|
||||
|
||||
That means a tool does not need a separate `Tool.defineEffect(...)` helper to count as migrated. A tool is effectively migrated when its init and execute path stay Effect-native, even if some internals still bridge to Promise-based or raw APIs.
|
||||
|
||||
## Tests
|
||||
|
||||
Tool tests should use the existing Effect helpers in `packages/opencode/test/lib/effect.ts`:
|
||||
|
||||
- Use `testEffect(...)` / `it.live(...)` instead of creating fake local wrappers around effectful tools.
|
||||
- Yield the real tool export, then initialize it: `const info = yield* ReadTool`, `const tool = yield* info.init()`.
|
||||
- Run tests inside a real instance with `provideTmpdirInstance(...)` or `provideInstance(tmpdirScoped(...))` so instance-scoped services resolve exactly as they do in production.
|
||||
|
||||
This keeps tool tests aligned with the production service graph and makes follow-up cleanup mostly mechanical.
|
||||
|
||||
## Exported tools
|
||||
|
||||
These exported tool definitions currently use `Tool.define(...)` in `src/tool`:
|
||||
|
||||
- [x] `apply_patch.ts`
|
||||
- [x] `bash.ts`
|
||||
- [x] `edit.ts`
|
||||
- [x] `glob.ts`
|
||||
- [x] `grep.ts`
|
||||
- [x] `invalid.ts`
|
||||
- [x] `lsp.ts`
|
||||
- [x] `plan.ts`
|
||||
- [x] `question.ts`
|
||||
- [x] `read.ts`
|
||||
- [x] `skill.ts`
|
||||
- [x] `task.ts`
|
||||
- [x] `todo.ts`
|
||||
- [x] `webfetch.ts`
|
||||
- [x] `websearch.ts`
|
||||
- [x] `write.ts`
|
||||
|
||||
Notes:
|
||||
|
||||
- There is no current `ls.ts` tool file on this branch.
|
||||
- `truncate.ts` is an Effect service used by tools, not a tool definition itself.
|
||||
- `mcp-exa.ts`, `external-directory.ts`, and `schema.ts` are support modules, not standalone tool definitions.
|
||||
|
||||
## Follow-up cleanup
|
||||
|
||||
Most exported tools are already on the intended Effect-native shape. The remaining cleanup is narrower than the old checklist implied.
|
||||
|
||||
Current spot cleanups worth tracking:
|
||||
|
||||
- [x] `read.ts` — streams through `FSUtil.Service.stream` with `Stream.splitLines`; the legacy Node stream / `readline` helper is gone
|
||||
- [ ] `bash.ts` — already uses Effect child-process primitives; only keep tracking shell-specific platform bridges and parser/loading details as they come up
|
||||
- [ ] `webfetch.ts` — already uses `HttpClient`; remaining work is limited to smaller boundary helpers like HTML text extraction
|
||||
- [ ] `file/ripgrep.ts` — adjacent to tool migration; still has raw fs/process usage that affects `grep.ts` and file-search routes
|
||||
- [x] `patch/index.ts` — apply path now returns `Effect` over `FSUtil.Service`; the parser and chunk replacer stay pure
|
||||
|
||||
Notable items that are already effectively on the target path and do not need separate migration bullets right now:
|
||||
|
||||
- `apply_patch.ts`
|
||||
- `grep.ts`
|
||||
- `write.ts`
|
||||
- `websearch.ts`
|
||||
- `edit.ts`
|
||||
|
||||
## Filesystem notes
|
||||
|
||||
Current raw fs users that still appear relevant here:
|
||||
|
||||
- `file/ripgrep.ts` — `fs/promises`
|
||||
204
packages/opencode/specs/openapi-translation-cleanup.md
Normal file
204
packages/opencode/specs/openapi-translation-cleanup.md
Normal file
@@ -0,0 +1,204 @@
|
||||
# OpenAPI Translation Cleanup Plan
|
||||
|
||||
## Goal
|
||||
|
||||
Trim `packages/opencode/src/server/routes/instance/httpapi/public.ts` until OpenAPI generation is mostly a direct projection of the `HttpApi` route declarations, without breaking the generated SDK surface.
|
||||
|
||||
The main failure mode to eliminate is spec-only behavior: anything that appears in `/doc` or the SDK but is not accepted by runtime `HttpApi` validation.
|
||||
|
||||
## Current Culprit
|
||||
|
||||
`public.ts` exports `PublicApi` with a large `OpenApi.annotations({ transform })` hook. That hook rewrites the generated spec for legacy SDK compatibility.
|
||||
|
||||
The highest-risk rewrite is `InstanceQueryParameters`, which injected `directory` and `workspace` into every instance route in OpenAPI even when the runtime query schema did not accept them. This caused the SDK and `/doc` to advertise calls that could fail with `400` at runtime.
|
||||
|
||||
## Non-Negotiables
|
||||
|
||||
- Do not break the generated JavaScript SDK without an explicit versioned migration plan.
|
||||
- Runtime route schemas are the source of truth for accepted params, payloads, and responses.
|
||||
- `/doc`, generated SDK types, and runtime validation must agree for every endpoint.
|
||||
- Prefer endpoint or schema annotations over post-generation spec surgery.
|
||||
- Remove one category of rewrite at a time, with focused compatibility checks.
|
||||
|
||||
## PR Checklist
|
||||
|
||||
Status legend: `[x]` done locally, `[~]` in progress locally, `[ ]` not started.
|
||||
|
||||
Current combined PR scope:
|
||||
|
||||
- `[x]` PR 1 drift tests: added OpenAPI/runtime query assertions and a negative fixture in `test/server/httpapi-query-schema-drift.test.ts`.
|
||||
- `[x]` PR 2 injection removal: removed broad `directory` / `workspace` post-generation injection from `public.ts` and replaced it with explicit runtime query schemas on affected routes.
|
||||
- `[ ]` PR 3+ cleanup: leave query override, path pattern, error shape, auth, and component-shape rewrites for later PRs.
|
||||
|
||||
### PR 1: Add OpenAPI/Runtime Query Drift Tests
|
||||
|
||||
- `[x]` Add or extend `packages/opencode/test/server/httpapi-query-schema-drift.test.ts`.
|
||||
- `[x]` Import `OpenApi.fromApi` and `PublicApi`.
|
||||
- `[x]` Generate the public spec in-process with `OpenApi.fromApi(PublicApi)`.
|
||||
- `[x]` Add a route inventory for the existing runtime reproducers: `session`, `file`, `experimental`, and `instance` routes.
|
||||
- `[x]` For each inventory entry, assert every OpenAPI query parameter is declared by the runtime query schema.
|
||||
- `[x]` Add a negative regression fixture that fails on spec-only `directory` / `workspace` params.
|
||||
- `[x]` Keep this part test-only.
|
||||
|
||||
Verification:
|
||||
|
||||
- `[x]` `bun test --timeout 5000 test/server/httpapi-query-schema-drift.test.ts` from `packages/opencode`.
|
||||
- `[x]` `bun typecheck` from `packages/opencode`.
|
||||
|
||||
### PR 2: Delete Spec-Only Workspace Query Injection
|
||||
|
||||
- `[x]` Edit `packages/opencode/src/server/routes/instance/httpapi/public.ts`.
|
||||
- `[x]` Delete `InstanceQueryParameters`.
|
||||
- `[x]` Delete the `isInstanceRoute` constant.
|
||||
- `[x]` Delete the branch that prepends `directory` and `workspace` to every instance operation.
|
||||
- `[x]` Keep `normalizeParameter(param, route)` for parameters that are actually produced by `HttpApi`.
|
||||
- `[x]` Add `WorkspaceRoutingQuery` / `WorkspaceRoutingQueryFields` to runtime query schemas for affected routes.
|
||||
- `[x]` Regenerate SDK and inspect diff. Result: no `directory` / `workspace` request-param removals; generated SDK diff is declaration ordering only.
|
||||
|
||||
Notes:
|
||||
|
||||
- Added `WorkspaceRoutingQuery` in `middleware/workspace-routing.ts` as the canonical runtime schema for middleware-consumed query params.
|
||||
- Replaced v2 union-query schemas with plain struct query schemas so `OpenApi.fromApi` emits their query params directly. This intentionally exposes the beta `/api/session` pagination/filter params in the SDK; cursor mutual-exclusion rules now live in the handlers, while `directory` / `workspace` remain allowed with cursors for routing.
|
||||
|
||||
Expected code shape:
|
||||
|
||||
```ts
|
||||
for (const param of operation.parameters ?? []) normalizeParameter(param, `${method.toUpperCase()} ${path}`)
|
||||
```
|
||||
|
||||
Verification:
|
||||
|
||||
- `[x]` `bun test --timeout 5000 test/server/httpapi-query-schema-drift.test.ts` from `packages/opencode`.
|
||||
- `[x]` `bun dev generate > /tmp/opencode-openapi.json` from `packages/opencode`.
|
||||
- `[x]` `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- `[x]` Inspect SDK diff for removed `directory` / `workspace` params. Result: none after explicit runtime schemas; v2 list/message now also expose their existing beta pagination/filter query params in the SDK.
|
||||
- `[x]` `bun typecheck` from `packages/opencode`.
|
||||
|
||||
### PR 3: Replace Broad Query Type Override Sets With Route-Level Helpers
|
||||
|
||||
- Edit `packages/opencode/src/server/routes/instance/httpapi/public.ts`.
|
||||
- Remove broad name-based assumptions from `QueryNumberParameters` and `QueryBooleanParameters` one field at a time.
|
||||
- Add shared query schema helpers near route group code if needed, for example in `groups/metadata.ts` or a new `groups/query.ts`.
|
||||
- Prefer route declarations like `Schema.NumberFromString.check(...)` and boolean string decoders like the existing `QueryBoolean` in `groups/session.ts`.
|
||||
- Keep only route-specific `QueryParameterSchemas` entries when SDK compatibility requires a public encoded type that Effect OpenAPI cannot emit yet.
|
||||
|
||||
Concrete first targets:
|
||||
|
||||
- `[x]` Consolidate `roots` / `archived` onto an explicit shared route schema helper. Keep `QueryBooleanParameters` until route-level schema metadata can preserve the SDK's `boolean | "true" | "false"` call shape without a global transform.
|
||||
- `[x]` Replace broad `QueryNumberParameters` reliance for `start` / `cursor` / `limit` with route-specific SDK compatibility schemas. Keep improving route-level constraints where behavior is intentionally stricter.
|
||||
- Keep `GET /find/file limit`, `GET /session/{sessionID}/diff messageID`, and `GET /session/{sessionID}/message limit` overrides until their route schemas generate identical SDK types directly.
|
||||
|
||||
Verification:
|
||||
|
||||
- Focused HTTP tests for changed query fields.
|
||||
- `bun dev generate > /tmp/opencode-openapi.json` from `packages/opencode`.
|
||||
- `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- Inspect generated SDK request param types before deleting each override.
|
||||
- `bun typecheck` from `packages/opencode`.
|
||||
|
||||
### PR 4: Move Path Parameter Patterns Into ID Schemas
|
||||
|
||||
- Audit `PathParameterSchemas` and `pathParameterSchema()` in `public.ts`.
|
||||
- Check source schemas in files like `packages/opencode/src/session/schema.ts`, `packages/opencode/src/permission/schema.ts`, and pty schema definitions.
|
||||
- Add or fix OpenAPI-compatible annotations on branded ID schemas so generated path params include the same patterns without `public.ts` overrides.
|
||||
- Delete one path override only after generated OpenAPI is unchanged for that param.
|
||||
|
||||
Concrete first targets:
|
||||
|
||||
- `[x]` `sessionID`
|
||||
- `[x]` `messageID`
|
||||
- `[x]` `partID`
|
||||
- `[x]` `permissionID`
|
||||
- `[x]` `ptyID`
|
||||
|
||||
- `[x]` Remove ambiguous workspace `id` path overrides once the endpoint source schema emits the `wrk` pattern.
|
||||
|
||||
Verification:
|
||||
|
||||
- `bun dev generate > /tmp/opencode-openapi.json` from `packages/opencode`.
|
||||
- `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- Inspect generated path param types and patterns.
|
||||
- `bun typecheck` from `packages/opencode`.
|
||||
|
||||
### PR 5: Replace Built-In Error Rewrites With Declared API Errors
|
||||
|
||||
- Edit route group files under `packages/opencode/src/server/routes/instance/httpapi/groups/`.
|
||||
- Replace SDK-visible `HttpApiError.BadRequest` / `HttpApiError.NotFound` with explicit error schemas from `packages/opencode/src/server/routes/instance/httpapi/errors.ts` or add new ones there.
|
||||
- Update handlers to fail with the declared API errors at the boundary.
|
||||
- Remove matching cases from `normalizeLegacyErrorResponses()` only after generated OpenAPI remains SDK-compatible.
|
||||
- Do this group by group, starting with one small route group.
|
||||
|
||||
Concrete first targets:
|
||||
|
||||
- `groups/config.ts` `PATCH /config` bad request.
|
||||
- `groups/session.ts` endpoints that already translate domain not-found errors.
|
||||
- `groups/file.ts` if any handler currently relies on built-in error shape.
|
||||
|
||||
Verification:
|
||||
|
||||
- Focused HTTP tests asserting response body shape for changed error paths.
|
||||
- `bun dev generate > /tmp/opencode-openapi.json` from `packages/opencode`.
|
||||
- `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- Inspect SDK error union diff.
|
||||
- `bun typecheck` from `packages/opencode`.
|
||||
|
||||
### PR 6: Remove Auth/Security Spec Rewrites If SDK Can Tolerate It
|
||||
|
||||
- Audit `delete operation.security`, `delete operation.responses?.["401"]`, and `delete spec.components?.securitySchemes` in `public.ts`.
|
||||
- Decide whether SDK should expose auth in generated operation metadata.
|
||||
- If preserving no-auth SDK surface is required, leave this rewrite and document it as intentional compatibility code.
|
||||
- If removing it, update SDK generation expectations and docs in the same PR.
|
||||
|
||||
Verification:
|
||||
|
||||
- `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- Inspect generated client call signatures and error unions.
|
||||
- Do not merge if auth churn changes normal SDK call ergonomics unintentionally.
|
||||
|
||||
### PR 7: Tackle Component Shape Rewrites One At A Time
|
||||
|
||||
- Audit these in `public.ts`: `normalizeComponentNames`, `collapseDuplicateComponents`, `applyLegacySchemaOverrides`, `normalizeComponentDescriptions`, `stripOptionalNull`, `fixSelfReferencingComponents`.
|
||||
- For each rewrite, make a tiny PR that removes or narrows only that rewrite.
|
||||
- If generated SDK type names churn broadly, stop and either keep the rewrite or fix `effect-smol` generation first.
|
||||
|
||||
Concrete first targets:
|
||||
|
||||
- Delete cosmetic `normalizeComponentDescriptions` if SDK output does not change materially.
|
||||
- Narrow `applyLegacySchemaOverrides` entries that correspond to schemas already fixed at the source.
|
||||
- Keep `stripOptionalNull` until there is an explicit SDK migration plan, because it likely affects many optional fields.
|
||||
|
||||
Verification:
|
||||
|
||||
- `bun dev generate > /tmp/opencode-openapi.json` from `packages/opencode`.
|
||||
- `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- Inspect generated SDK type-name and optionality diffs.
|
||||
|
||||
## Upstream Middleware Query Support
|
||||
|
||||
Long-term, `WorkspaceRoutingMiddleware` should declare the query fields it reads once, and `HttpApi` should use that declaration for both runtime validation and OpenAPI generation.
|
||||
|
||||
Target in `effect-smol`:
|
||||
|
||||
- Extend `HttpApiMiddleware.Service` config with optional query schema support, or add a dedicated middleware query annotation.
|
||||
- Make runtime request decoding include middleware query schemas.
|
||||
- Make `OpenApi.fromApi` emit middleware query params for endpoints using that middleware.
|
||||
|
||||
Once available, remove `WorkspaceRoutingQueryFields` spreads from route groups and declare `directory` / `workspace` only on `WorkspaceRoutingMiddleware`.
|
||||
|
||||
## Suggested PR Order
|
||||
|
||||
1. Add drift detection tests only.
|
||||
2. Remove `InstanceQueryParameters` spec injection; rely on `WorkspaceRoutingQueryFields` already present in runtime schemas.
|
||||
3. Convert query type overrides into route/schema-level helpers where possible.
|
||||
4. Convert path parameter overrides into schema annotations or upstream fixes.
|
||||
5. Replace built-in error response rewrites with explicit declared API errors by route group.
|
||||
6. Tackle component naming/nullability rewrites only after SDK compatibility snapshots are stable.
|
||||
|
||||
## Verification Checklist Per PR
|
||||
|
||||
- Focused HTTP tests for changed routes.
|
||||
- OpenAPI drift tests.
|
||||
- `bun dev generate > /tmp/opencode-openapi.json` from `packages/opencode`.
|
||||
- `./packages/sdk/js/script/build.ts` from repo root.
|
||||
- Inspect generated SDK diff for public API churn.
|
||||
- `bun typecheck` from `packages/opencode`.
|
||||
544
packages/opencode/specs/tui-plugins.md
Normal file
544
packages/opencode/specs/tui-plugins.md
Normal file
@@ -0,0 +1,544 @@
|
||||
# TUI plugins
|
||||
|
||||
Technical reference for the current TUI plugin system.
|
||||
|
||||
## Overview
|
||||
|
||||
- TUI plugin config lives in `tui.json`.
|
||||
- Author package entrypoint is `@opencode-ai/plugin/tui`.
|
||||
- Internal plugins load inside the CLI app the same way external TUI plugins do.
|
||||
- Package plugins can be installed from CLI or TUI.
|
||||
- v1 plugin modules are target-exclusive: a module can export `server` or `tui`, never both.
|
||||
- Server runtime keeps v0 legacy fallback (function exports / enumerated exports) after v1 parsing.
|
||||
- npm packages can be TUI theme-only via `package.json["oc-themes"]` without a `./tui` entrypoint.
|
||||
|
||||
## TUI config
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://opencode.ai/tui.json",
|
||||
"theme": "smoke-theme",
|
||||
"leader_timeout": 2000,
|
||||
"keybinds": {
|
||||
"leader": "ctrl+x",
|
||||
"command_list": "ctrl+p",
|
||||
"session_new": "<leader>n"
|
||||
},
|
||||
"plugin": ["@acme/opencode-plugin@1.2.3", ["./plugins/demo.tsx", { "label": "demo" }]],
|
||||
"plugin_enabled": {
|
||||
"acme.demo": false
|
||||
},
|
||||
"attention": {
|
||||
"enabled": true,
|
||||
"notifications": true,
|
||||
"sound": true,
|
||||
"volume": 0.4,
|
||||
"sound_pack": "opencode.default",
|
||||
"sounds": {
|
||||
"error": "/Users/me/sounds/error.mp3"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `plugin` entries can be either a string spec or `[spec, options]`.
|
||||
- Plugin specs can be npm specs, `file://` URLs, relative paths, or absolute paths.
|
||||
- Relative path specs are resolved relative to the config file that declared them.
|
||||
- A file module listed in `tui.json` must be a TUI module (`default export { id?, tui }`) and must not export `server`.
|
||||
- Duplicate npm plugins are deduped by package name; higher-precedence config wins.
|
||||
- Duplicate file plugins are deduped by exact resolved file spec. This happens while merging config, before plugin modules are loaded.
|
||||
- `plugin_enabled` is keyed by plugin id, not by plugin spec.
|
||||
- For file plugins, that id must come from the plugin module's exported `id`. For npm plugins, it is the exported `id` or the package name if `id` is omitted.
|
||||
- Plugins are enabled by default. `plugin_enabled` is only for explicit overrides, usually to disable a plugin with `false`.
|
||||
- Internal plugins can declare `enabled: false` to be registered but inactive by default; `plugin_enabled` and runtime KV can still enable them by id.
|
||||
- `plugin_enabled` is merged across config layers.
|
||||
- Runtime enable/disable state is also stored in KV under `plugin_enabled`; that KV state overrides config on startup.
|
||||
- `attention.enabled` defaults to `false`; when `false`, it disables all `api.attention.notify(...)` delivery.
|
||||
- `attention.notifications` and `attention.sound` independently control terminal-mediated desktop notifications and built-in sounds.
|
||||
- `attention.volume` sets the default built-in sound volume from `0` to `1`.
|
||||
- `attention.sound_pack` selects the initial semantic sound pack. Persisted runtime selection in KV can override it.
|
||||
- `attention.sounds` overrides individual semantic sound slots such as `error`, `done`, or `subagent_done`.
|
||||
- `leader_timeout` is a top-level TUI setting.
|
||||
- `keybinds` is a flat object keyed by command id; values are key binding values (`false`, `"none"`, a key string/object, a binding object, or an array of key strings/objects/binding objects).
|
||||
- `keybinds.leader` sets the key used by `<leader>` shortcuts.
|
||||
|
||||
## Author package shape
|
||||
|
||||
Package entrypoint:
|
||||
|
||||
- Import types from `@opencode-ai/plugin/tui`.
|
||||
- `@opencode-ai/plugin` exports `./tui` and declares optional peer deps on `@opentui/core` and `@opentui/solid`.
|
||||
|
||||
Minimal module shape:
|
||||
|
||||
```tsx
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
|
||||
|
||||
const tui: TuiPlugin = async (api, options, meta) => {
|
||||
api.keymap.registerLayer({
|
||||
commands: [
|
||||
{
|
||||
name: "demo.open",
|
||||
title: "Demo",
|
||||
category: "Plugin",
|
||||
namespace: "palette",
|
||||
slashName: "demo",
|
||||
run() {
|
||||
api.route.navigate("demo")
|
||||
},
|
||||
},
|
||||
],
|
||||
bindings: [{ key: "ctrl+shift+m", cmd: "demo.open", desc: "Open demo" }],
|
||||
})
|
||||
|
||||
api.route.register([
|
||||
{
|
||||
name: "demo",
|
||||
render: () => (
|
||||
<box>
|
||||
<text>demo</text>
|
||||
</box>
|
||||
),
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
const plugin: TuiPluginModule & { id: string } = {
|
||||
id: "acme.demo",
|
||||
tui,
|
||||
}
|
||||
|
||||
export default plugin
|
||||
```
|
||||
|
||||
- Loader only reads the module default export object. Named exports are ignored.
|
||||
- TUI shape is `default export { id?, tui }`; including `server` is rejected.
|
||||
- A single module cannot export both `server` and `tui`.
|
||||
- `tui` signature is `(api, options, meta) => Promise<void>`.
|
||||
- If package `exports` contains `./tui`, the loader resolves that entrypoint.
|
||||
- If package `exports` exists, loader only resolves `./tui` or `./server`; it never falls back to `exports["."]`.
|
||||
- For npm package specs, TUI does not use `package.json` `main` as a fallback entry.
|
||||
- `package.json` `main` is only used for server plugin entrypoint resolution.
|
||||
- If a configured TUI package has no `./tui` entrypoint and no valid `oc-themes`, it is skipped with a warning (not a load failure).
|
||||
- If a configured TUI package has no `./tui` entrypoint but has valid `oc-themes`, runtime creates a no-op module record and still loads it for theme sync and plugin state.
|
||||
- If a package supports both server and TUI, use separate files and package `exports` (`./server` and `./tui`) so each target resolves to a target-only module.
|
||||
- File/path plugins must export a non-empty `id`.
|
||||
- npm plugins may omit `id`; package `name` is used.
|
||||
- Runtime identity is the resolved plugin id. Later plugins with the same id are rejected, including collisions with internal plugin ids.
|
||||
- If a path spec points at a directory, server loading can use `package.json` `main`.
|
||||
- TUI path loading never uses `package.json` `main`.
|
||||
- Legacy compatibility: path specs like `./plugin` can resolve to `./plugin/index.ts` (or `index.js`) when `package.json` is missing.
|
||||
- The `./plugin -> ./plugin/index.*` fallback applies to both server and TUI v1 loading.
|
||||
- There is no directory auto-discovery for TUI plugins; they must be listed in `tui.json`.
|
||||
|
||||
## Package manifest and install
|
||||
|
||||
Install target detection is inferred from `package.json` entrypoints and theme metadata:
|
||||
|
||||
- `server` target when `exports["./server"]` exists or `main` is set.
|
||||
- `tui` target when `exports["./tui"]` exists.
|
||||
- `tui` target when `oc-themes` exists and resolves to a non-empty set of valid package-relative theme paths.
|
||||
|
||||
`oc-themes` rules:
|
||||
|
||||
- `oc-themes` is an array of relative paths.
|
||||
- Absolute paths and `file://` paths are rejected.
|
||||
- Resolved theme paths must stay inside the package directory.
|
||||
- Invalid `oc-themes` causes manifest read failure for install.
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "@acme/opencode-plugin",
|
||||
"type": "module",
|
||||
"main": "./dist/server.js",
|
||||
"exports": {
|
||||
"./server": {
|
||||
"import": "./dist/server.js",
|
||||
"config": { "custom": true }
|
||||
},
|
||||
"./tui": {
|
||||
"import": "./dist/tui.js",
|
||||
"config": { "compact": true }
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"opencode": "^1.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Version compatibility
|
||||
|
||||
npm plugins can declare a version compatibility range in `package.json` using the standard `engines` field:
|
||||
|
||||
```json
|
||||
{
|
||||
"engines": {
|
||||
"opencode": "^1.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- The value is a semver range checked against the running OpenCode version.
|
||||
- If the range is not satisfied, the plugin is skipped with a warning and a session error.
|
||||
- If `engines.opencode` is absent, no check is performed (backward compatible).
|
||||
- File plugins are never checked; only npm package plugins are validated.
|
||||
|
||||
- Install flow is shared by CLI and TUI in `src/plugin/install.ts`.
|
||||
- Shared helpers are `installPlugin`, `readPluginManifest`, and `patchPluginConfig`.
|
||||
- `opencode plugin <module>` and TUI install both run install → manifest read → config patch.
|
||||
- Alias: `opencode plug <module>`.
|
||||
- `-g` / `--global` writes into the global config dir.
|
||||
- Local installs resolve target dir inside `patchPluginConfig`.
|
||||
- For local scope, path is `<worktree>/.opencode` only when VCS is git and `worktree !== "/"`; otherwise `<directory>/.opencode`.
|
||||
- Root-worktree fallback (`worktree === "/"` uses `<directory>/.opencode`) is covered by regression tests.
|
||||
- `patchPluginConfig` applies all detected targets (`server` and/or `tui`) in one call.
|
||||
- `patchPluginConfig` returns structured result unions (`ok`, `code`, fields by error kind) instead of custom thrown errors.
|
||||
- `patchPluginConfig` serializes per-target config writes with `Flock.acquire(...)`.
|
||||
- `patchPluginConfig` uses targeted `jsonc-parser` edits, so existing JSONC comments are preserved when plugin entries are added or replaced.
|
||||
- npm plugin package installs are executed with `--ignore-scripts`, so package `install` / `postinstall` lifecycle scripts are not run.
|
||||
- `exports["./server"].config` and `exports["./tui"].config` can provide default plugin options written on first install.
|
||||
- Without `--force`, an already-configured npm package name is a no-op.
|
||||
- With `--force`, replacement matches by package name. If the existing row is `[spec, options]`, those tuple options are kept.
|
||||
- Explicit npm specs with a version suffix (for example `pkg@1.2.3`) are pinned. Runtime install requests that exact version and does not run stale/latest checks for newer registry versions.
|
||||
- Bare npm specs (`pkg`) are treated as `latest` and can refresh when the cached version is stale.
|
||||
- Tuple targets in `oc-plugin` provide default options written into config.
|
||||
- A package can target `server`, `tui`, or both.
|
||||
- If a package targets both, each target must still resolve to a separate target-only module. Do not export `{ server, tui }` from one module.
|
||||
- There is no uninstall, list, or update CLI command for external plugins.
|
||||
- Local file plugins are configured directly in `tui.json`.
|
||||
|
||||
When `plugin` entries exist in a writable `.opencode` dir or `OPENCODE_CONFIG_DIR`, OpenCode installs `@opencode-ai/plugin` into that dir and writes:
|
||||
|
||||
- `package.json`
|
||||
- `bun.lock`
|
||||
- `node_modules/`
|
||||
- `.gitignore`
|
||||
|
||||
That is what makes local config-scoped plugins able to import `@opencode-ai/plugin/tui`.
|
||||
|
||||
## TUI plugin API
|
||||
|
||||
Top-level API groups exposed to `tui(api, options, meta)`:
|
||||
|
||||
- `api.app.version`
|
||||
- `api.attention.notify(input)`
|
||||
- `api.keys.formatSequence(parts)`, `formatBindings(bindings)`
|
||||
- `api.keymap`
|
||||
- `api.mode.current()`, `api.mode.push(mode)`
|
||||
- `api.route.register(routes)` / `api.route.navigate(name, params?)` / `api.route.current`
|
||||
- `api.ui.Dialog`, `DialogAlert`, `DialogConfirm`, `DialogPrompt`, `DialogSelect`, `Slot`, `Prompt`, `ui.toast`, `ui.dialog`
|
||||
- `api.tuiConfig`
|
||||
- `api.kv.get`, `set`, `ready`
|
||||
- `api.state`
|
||||
- `api.theme.current`, `selected`, `has`, `set`, `install`, `mode`, `ready`
|
||||
- `api.client`
|
||||
- `api.event.on(type, handler)`
|
||||
- `api.renderer`
|
||||
- `api.slots.register(plugin)`
|
||||
- `api.plugins.list()`, `activate(id)`, `deactivate(id)`, `add(spec)`, `install(spec, options?)`
|
||||
- `api.lifecycle.signal`, `api.lifecycle.onDispose(fn)`
|
||||
|
||||
### Keymap
|
||||
|
||||
- `api.keymap` exposes the raw `Keymap<Renderable, KeyEvent>` instance from the host.
|
||||
- The host already installs the default OpenTUI bundle (`default keys`, metadata fields, and enabled fields) plus OpenCode's comma bindings, leader token, base layout fallback, pending-sequence helpers, and managed textarea layer.
|
||||
- Register commands with `api.keymap.registerLayer({ commands: [...] })`.
|
||||
- Register key bindings with `bindings: [{ key, cmd, desc }]` in the same layer or a separate layer.
|
||||
- Use `api.keymap.acquireResource(...)` for shared plugin addon setup that should ref-count against the host keymap.
|
||||
- To surface a command in the host command palette, set `namespace: "palette"` and provide metadata such as `title`, `category`, `desc`, `suggested`, `hidden`, `enabled`, `slashName`, and `slashAliases` on the command.
|
||||
- Use `api.keymap.dispatchCommand(name)` for user-style execution semantics and `api.keymap.runCommand(name)` only for forced programmatic execution.
|
||||
- Disposers returned by `api.keymap` registrations and `acquireResource(...)` are automatically cleaned up when the plugin deactivates. You do not need to add those disposers to `api.lifecycle.onDispose(...)` yourself.
|
||||
- Built-in which-key shortcuts are resolved from flat `keybinds` command ids such as `which_key_toggle`, not plugin options.
|
||||
|
||||
#### Mode-aware layers
|
||||
|
||||
OpenCode registers a `mode` layer field on the host keymap. Plugins can use it to keep bindings active only in the relevant UI state.
|
||||
|
||||
Built-in modes:
|
||||
|
||||
- `base`: normal app, route, and prompt interaction.
|
||||
- `modal`: host dialog stack is open, including dialogs rendered through `api.ui.dialog` and `api.ui.Dialog*` components.
|
||||
- `autocomplete`: host prompt autocomplete is open.
|
||||
- `api.mode.current()` returns the active top mode, or `base` when no pushed mode is active.
|
||||
|
||||
Example: register a command and shortcut that are active only in normal app mode:
|
||||
|
||||
```tsx
|
||||
api.keymap.registerLayer({
|
||||
mode: "base",
|
||||
commands: [
|
||||
{
|
||||
name: "demo.open",
|
||||
title: "Demo",
|
||||
category: "Plugin",
|
||||
namespace: "palette",
|
||||
run() {
|
||||
api.route.navigate("demo")
|
||||
},
|
||||
},
|
||||
],
|
||||
bindings: [{ key: "ctrl+shift+m", cmd: "demo.open", desc: "Open demo" }],
|
||||
})
|
||||
```
|
||||
|
||||
Layers without `mode` are not mode-gated and can remain active while dialogs or autocomplete are open. Use that only for intentionally global commands or low-level keymap extensions.
|
||||
|
||||
Plugins that own a full-screen route or modal-like UI can temporarily push a plugin-specific mode with `api.mode.push(...)`. Use a plugin-scoped mode name. The returned disposer pops that specific stack entry and is idempotent, so popping an older mode while a newer mode is on top leaves the newer mode active.
|
||||
|
||||
```tsx
|
||||
import { onCleanup } from "solid-js"
|
||||
|
||||
api.route.register([
|
||||
{
|
||||
name: "demo",
|
||||
render: () => {
|
||||
const popMode = api.mode.push("acme.demo")
|
||||
onCleanup(popMode)
|
||||
|
||||
return (
|
||||
<box>
|
||||
<text>demo</text>
|
||||
</box>
|
||||
)
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
api.keymap.registerLayer({
|
||||
mode: "acme.demo",
|
||||
bindings: [{ key: "escape", cmd: () => api.route.navigate("home"), desc: "Close demo" }],
|
||||
})
|
||||
```
|
||||
|
||||
Mode pushes are automatically tracked by the plugin runtime. If a plugin is disabled, fails during activation, or the TUI shuts down before the plugin calls the disposer, OpenCode pops the plugin's pushed modes during plugin cleanup. Calling the disposer yourself is still recommended for component lifetimes; cleanup remains idempotent.
|
||||
|
||||
### Keys
|
||||
|
||||
- `api.keys` exposes host-formatted shortcut display helpers for plugin UI.
|
||||
- `formatSequence(parts)` formats parsed key sequence parts using the host's display policy.
|
||||
- `formatBindings(bindings)` formats binding lists and returns `undefined` when there is nothing to show.
|
||||
- For generic config-to-bindings helpers, import `createBindingLookup` from `@opencode-ai/plugin/tui`.
|
||||
|
||||
### Attention
|
||||
|
||||
- `api.attention.notify({ title?, message, notification?, sound? })` requests user attention while keeping terminal focus, notifications, and audio owned by the host.
|
||||
- `message` is required; `title` defaults to `"opencode"`; `notification` defaults to enabled with `when: "blurred"`; `sound` defaults to enabled with `when: "always"`.
|
||||
- `when: "always"` requests delivery regardless of terminal focus state.
|
||||
- `when: "focused"` only requests delivery after the terminal is known focused; `when: "blurred"` only requests delivery after the terminal is known blurred.
|
||||
- Example: `notification: { when: "blurred" }, sound: { name: "question", when: "always" }` plays sound while focused but only triggers system notifications when blurred.
|
||||
- Semantic sound names are `"default"`, `"question"`, `"permission"`, `"error"`, `"done"`, and `"subagent_done"`.
|
||||
- `sound: true` plays the `"default"` sound; `sound: { name: "question" }` plays a named semantic sound.
|
||||
- `sound: { volume }` overrides volume for that call; `sound: false` disables sound for that call; `notification: false` disables system notification for that call.
|
||||
- `api.attention.soundboard.registerPack({ id, name?, sounds })` registers a sound pack and returns a disposer. Relative paths resolve from the plugin root and are cleaned up on plugin deactivation.
|
||||
- `api.attention.soundboard.activate(id, { persist })` selects the active pack. `persist: true` writes the selected pack id to TUI KV state, not `tui.json`.
|
||||
- `api.attention.soundboard.current()` and `list()` expose the active/registered packs for plugin UX.
|
||||
- Config `attention.sounds` overrides active-pack sounds by slot. Failed loads fall back to the active pack and then `opencode.default`.
|
||||
- The host strips ANSI/control characters and collapses newlines before sending text to the terminal notification API.
|
||||
- Terminal and OS settings decide whether a requested notification is visibly displayed.
|
||||
- Prefer privacy-safe messages such as `"A question needs your input"`; avoid full commands, paths, prompts, errors, secrets, or file contents unless the plugin intentionally exposes them.
|
||||
|
||||
### Routes
|
||||
|
||||
- Reserved route names: `home` and `session`.
|
||||
- Any other name is treated as a plugin route.
|
||||
- `api.route.current` returns one of:
|
||||
- `{ name: "home" }`
|
||||
- `{ name: "session", params: { sessionID, initialPrompt? } }`
|
||||
- `{ name: string, params?: Record<string, unknown> }`
|
||||
- `api.route.navigate("session", params)` only uses `params.sessionID`. It cannot set `initialPrompt`.
|
||||
- If multiple plugins register the same route name, the last registered route wins.
|
||||
- Unknown plugin routes render a fallback screen with a `go home` action.
|
||||
|
||||
### Dialogs and toast
|
||||
|
||||
- `ui.Dialog` is the base dialog wrapper.
|
||||
- `ui.DialogAlert`, `ui.DialogConfirm`, `ui.DialogPrompt`, `ui.DialogSelect` are built-in dialog components.
|
||||
- `ui.Slot` renders host or plugin-defined slots by name from plugin JSX.
|
||||
- `ui.Prompt` renders the same prompt component used by the host app and accepts `sessionID`, `workspaceID`, `ref`, and `right` for the prompt meta row's right side.
|
||||
- `ui.toast(...)` shows a toast.
|
||||
- `ui.dialog` exposes the host dialog stack:
|
||||
- `replace(render, onClose?)`
|
||||
- `clear()`
|
||||
- `setSize("medium" | "large" | "xlarge")`
|
||||
- readonly `size`, `depth`, `open`
|
||||
|
||||
### KV, state, client, events
|
||||
|
||||
- `api.kv` is the shared app KV store backed by `state/kv.json`. It is not plugin-namespaced.
|
||||
- `api.kv` exposes `ready`.
|
||||
- `api.tuiConfig` and `api.state` are live host objects/getters, not frozen snapshots.
|
||||
- `api.state` exposes synced TUI state:
|
||||
- `ready`
|
||||
- `config`
|
||||
- `provider`
|
||||
- `path.{state,config,worktree,directory}`
|
||||
- `vcs?.branch`
|
||||
- `session.count()`
|
||||
- `session.diff(sessionID)`
|
||||
- `session.todo(sessionID)`
|
||||
- `session.messages(sessionID)`
|
||||
- `session.status(sessionID)`
|
||||
- `session.permission(sessionID)`
|
||||
- `session.question(sessionID)`
|
||||
- `part(messageID)`
|
||||
- `lsp()`
|
||||
- `mcp()`
|
||||
- `api.client` always reflects the current runtime client.
|
||||
- `api.event.on(type, handler)` subscribes to the TUI event stream and returns an unsubscribe function.
|
||||
- `api.renderer` exposes the raw `CliRenderer`.
|
||||
|
||||
### Theme
|
||||
|
||||
- `api.theme.current` exposes the resolved current theme tokens.
|
||||
- `api.theme.selected` is the selected theme name.
|
||||
- `api.theme.has(name)` checks for an installed theme.
|
||||
- `api.theme.set(name)` switches theme and returns `boolean`.
|
||||
- `api.theme.mode()` returns `"dark" | "light"`.
|
||||
- `api.theme.install(jsonPath)` installs a theme JSON file.
|
||||
- `api.theme.ready` reports theme readiness.
|
||||
|
||||
Theme install behavior:
|
||||
|
||||
- Relative theme paths are resolved from the plugin root.
|
||||
- Theme name is the JSON basename.
|
||||
- `api.theme.install(...)` and `oc-themes` auto-sync share the same installer path.
|
||||
- Theme copy/write runs under cross-process lock key `tui-theme:<dest>`.
|
||||
- First install writes only when the destination file is missing.
|
||||
- If the theme name already exists, install is skipped unless plugin metadata state is `updated`.
|
||||
- On `updated`, host skips rewrite when tracked `mtime`/`size` is unchanged.
|
||||
- When a theme already exists and state is not `updated`, host can still persist theme metadata when destination already exists.
|
||||
- Local plugins persist installed themes under the local `.opencode/themes` area near the plugin config source.
|
||||
- Global plugins persist installed themes under the global `themes` dir.
|
||||
- Invalid or unreadable theme files are ignored.
|
||||
|
||||
### Slots
|
||||
|
||||
Current host slot names:
|
||||
|
||||
- `app`
|
||||
- `app_bottom`
|
||||
- `home_logo`
|
||||
- `home_prompt` with props `{ workspace_id?, ref? }`
|
||||
- `home_prompt_right` with props `{ workspace_id? }`
|
||||
- `session_prompt` with props `{ session_id, visible?, disabled?, on_submit?, ref? }`
|
||||
- `session_prompt_right` with props `{ session_id }`
|
||||
- `home_bottom`
|
||||
- `home_footer`
|
||||
- `sidebar_title` with props `{ session_id, title, share_url? }`
|
||||
- `sidebar_content` with props `{ session_id }`
|
||||
- `sidebar_footer` with props `{ session_id }`
|
||||
|
||||
Slot notes:
|
||||
|
||||
- Slot context currently exposes only `theme`.
|
||||
- `api.slots.register(plugin)` returns the host-assigned slot plugin id.
|
||||
- `api.slots.register(plugin)` does not return an unregister function.
|
||||
- Returned ids are `pluginId`, `pluginId:1`, `pluginId:2`, and so on.
|
||||
- Plugin-provided `id` is not allowed.
|
||||
- The current host renders `home_logo`, `home_prompt`, and `session_prompt` with `replace`, `home_footer`, `sidebar_title`, and `sidebar_footer` with `single_winner`, and `app`, `app_bottom`, `home_prompt_right`, `session_prompt_right`, `home_bottom`, and `sidebar_content` with the slot library default mode.
|
||||
- `app_bottom` is rendered in normal layout flow below the active route, while `app` is rendered afterward for global app-level UI.
|
||||
- Plugins can define custom slot names in `api.slots.register(...)` and render them from plugin UI with `ui.Slot`.
|
||||
|
||||
### Plugin control and lifecycle
|
||||
|
||||
- `api.plugins.list()` returns `{ id, source, spec, target, enabled, active }[]`.
|
||||
- `enabled` is the persisted desired state. `active` means the plugin is currently initialized.
|
||||
- `api.plugins.activate(id)` sets `enabled=true`, persists it into KV, and initializes the plugin.
|
||||
- `api.plugins.deactivate(id)` sets `enabled=false`, persists it into KV, and disposes the plugin scope.
|
||||
- `api.plugins.add(spec)` trims the input and returns `false` for an empty string.
|
||||
- `api.plugins.add(spec)` treats the input as the runtime plugin spec and loads it without re-reading `tui.json`.
|
||||
- `api.plugins.add(spec)` no-ops when that resolved spec (or resolved plugin id) is already loaded.
|
||||
- `api.plugins.add(spec)` assumes enabled and always attempts initialization (it does not consult config/KV enable state).
|
||||
- `api.plugins.add(spec)` can load theme-only packages (`oc-themes` with no `./tui`) as runtime entries.
|
||||
- `api.plugins.install(spec, { global? })` runs install -> manifest read -> config patch using the same helper flow as CLI install.
|
||||
- `api.plugins.install(...)` returns either `{ ok: false, message, missing? }` or `{ ok: true, dir, tui }`.
|
||||
- `api.plugins.install(...)` does not load plugins into the current session. Call `api.plugins.add(spec)` to load after install.
|
||||
- If activation fails, the plugin can remain `enabled=true` and `active=false`.
|
||||
- `api.lifecycle.signal` is aborted before cleanup runs.
|
||||
- `api.lifecycle.onDispose(fn)` registers cleanup and returns an unregister function.
|
||||
|
||||
## Plugin metadata
|
||||
|
||||
`meta` passed to `tui(api, options, meta)` contains:
|
||||
|
||||
- `state`: `first | updated | same`
|
||||
- `id`, `source`, `spec`, `target`
|
||||
- npm-only fields when available: `requested`, `version`
|
||||
- file-only field when available: `modified`
|
||||
- `first_time`, `last_time`, `time_changed`, `load_count`, `fingerprint`
|
||||
|
||||
Metadata is persisted by plugin id.
|
||||
|
||||
- File plugin fingerprint is `target|modified`.
|
||||
- npm plugin fingerprint is `target|requested|version`.
|
||||
- Internal plugins get synthetic metadata with `state: "same"`.
|
||||
|
||||
## Runtime behavior
|
||||
|
||||
- Internal TUI plugins load first.
|
||||
- External TUI plugins load from `tuiConfig.plugin`.
|
||||
- `--pure` / `OPENCODE_PURE` skips external TUI plugins only.
|
||||
- External plugin resolution and import are parallel.
|
||||
- Packages with no `./tui` entrypoint and valid `oc-themes` are loaded as synthetic no-op TUI plugin modules.
|
||||
- Theme-only packages loaded this way appear in `api.plugins.list()` and plugin manager rows like other external plugins.
|
||||
- Packages with no `./tui` entrypoint and no valid `oc-themes` are skipped with warning.
|
||||
- External plugin activation is sequential to keep command, route, and side-effect order deterministic.
|
||||
- Theme auto-sync from `oc-themes` runs before plugin `tui(...)` execution and only on metadata state `first` or `updated`.
|
||||
- File plugins that fail initially are retried once after waiting for config dependency installation.
|
||||
- Runtime add uses the same external loader path, including the file-plugin retry after dependency wait.
|
||||
- Runtime add skips duplicates by resolved spec and returns `true` when the spec is already loaded.
|
||||
- Runtime install and runtime add are separate operations.
|
||||
- Plugin init failure rolls back that plugin's tracked registrations and loading continues.
|
||||
- TUI runtime tracks and disposes:
|
||||
- command registrations
|
||||
- route registrations
|
||||
- event subscriptions
|
||||
- slot registrations
|
||||
- explicit `lifecycle.onDispose(...)` handlers
|
||||
- Cleanup runs in reverse order.
|
||||
- Cleanup is awaited.
|
||||
- Total cleanup budget per plugin is 5 seconds; timeout/error is logged and shutdown continues.
|
||||
|
||||
## Built-in plugins
|
||||
|
||||
- `internal:home-tips`
|
||||
- `internal:sidebar-context`
|
||||
- `internal:sidebar-mcp`
|
||||
- `internal:sidebar-lsp`
|
||||
- `internal:sidebar-todo`
|
||||
- `internal:sidebar-files`
|
||||
- `internal:sidebar-footer`
|
||||
- `internal:plugin-manager`
|
||||
|
||||
Sidebar content order is currently: context `100`, mcp `200`, lsp `300`, todo `400`, files `500`.
|
||||
|
||||
The plugin manager is exposed as a command with title `Plugins` and value `plugins.list`.
|
||||
|
||||
- Keybind name is `plugin_manager`.
|
||||
- Default keybind is `none`.
|
||||
- It lists both internal and external plugins.
|
||||
- It toggles based on `active`.
|
||||
- Its own row is disabled only inside the manager dialog.
|
||||
- It also exposes command `plugins.install` with title `Install plugin`.
|
||||
- Inside the Plugins dialog, key `shift+i` opens the install prompt.
|
||||
- Install prompt asks for npm package name.
|
||||
- Scope defaults to local, and `tab` toggles local/global.
|
||||
- Install is blocked until `api.state.path.directory` is available; current guard message is `Paths are still syncing. Try again in a moment.`.
|
||||
- Manager install uses `api.plugins.install(spec, { global })`.
|
||||
- If the installed package has no `tui` target (`tui=false`), manager reports that and does not expect a runtime load.
|
||||
- `tui` target detection includes `exports["./tui"]` and valid `oc-themes`.
|
||||
- If install reports `tui=true`, manager then calls `api.plugins.add(spec)`.
|
||||
- If runtime add fails, TUI shows a warning and restart remains the fallback.
|
||||
|
||||
## Current in-repo examples
|
||||
|
||||
- Local smoke plugin: `.opencode/plugins/tui-smoke.tsx`
|
||||
- Local vim plugin: `.opencode/plugins/tui-vim.tsx`
|
||||
- Local smoke config: `.opencode/tui.json`
|
||||
- Local smoke theme: `.opencode/plugins/smoke-theme.json`
|
||||
67
packages/opencode/specs/v2/api.ts
Normal file
67
packages/opencode/specs/v2/api.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
// @ts-nocheck
|
||||
|
||||
import { OpenCode } from "@opencode-ai/core"
|
||||
import { ReadTool } from "@opencode-ai/core/tools"
|
||||
|
||||
const opencode = OpenCode.make({})
|
||||
|
||||
opencode.tool.add(ReadTool)
|
||||
|
||||
opencode.tool.add({
|
||||
name: "bash",
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description: "The command to run.",
|
||||
},
|
||||
},
|
||||
required: ["command"],
|
||||
},
|
||||
execute(input, ctx) {},
|
||||
})
|
||||
|
||||
opencode.auth.add({
|
||||
provider: "openai",
|
||||
type: "api",
|
||||
value: process.env.OPENAI_API_KEY,
|
||||
})
|
||||
|
||||
opencode.agent.add({
|
||||
name: "build",
|
||||
permissions: [],
|
||||
model: {
|
||||
id: "gpt-5-5",
|
||||
provider: "openai",
|
||||
variant: "xhigh",
|
||||
},
|
||||
})
|
||||
|
||||
const sessionID = await opencode.session.create({
|
||||
agent: "build",
|
||||
})
|
||||
|
||||
opencode.subscribe((event) => {
|
||||
console.log(event)
|
||||
})
|
||||
|
||||
await opencode.session.prompt({
|
||||
sessionID,
|
||||
text: "hey what is up",
|
||||
})
|
||||
|
||||
await opencode.session.prompt({
|
||||
sessionID,
|
||||
text: "what is up with this",
|
||||
files: [
|
||||
{
|
||||
mime: "image/png",
|
||||
uri: "data:image/png;base64,xxxx",
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
await opencode.session.wait()
|
||||
|
||||
console.log(await opencode.session.messages(sessionID))
|
||||
136
packages/opencode/specs/v2/message-shape.md
Normal file
136
packages/opencode/specs/v2/message-shape.md
Normal file
@@ -0,0 +1,136 @@
|
||||
# Message Shape
|
||||
|
||||
Problem:
|
||||
|
||||
- stored messages need enough data to replay and resume a session later
|
||||
- prompt hooks often just want to append a synthetic user/assistant message
|
||||
- today that means faking ids, timestamps, and request metadata
|
||||
|
||||
## Option 1: Two Message Shapes
|
||||
|
||||
Keep `User` / `Assistant` for stored history, but clean them up.
|
||||
|
||||
```ts
|
||||
type User = {
|
||||
role: "user"
|
||||
time: { created: number }
|
||||
request: {
|
||||
agent: string
|
||||
model: ModelRef
|
||||
variant?: string
|
||||
format?: OutputFormat
|
||||
system?: string
|
||||
tools?: Record<string, boolean>
|
||||
}
|
||||
}
|
||||
|
||||
type Assistant = {
|
||||
role: "assistant"
|
||||
run: { agent: string; model: ModelRef; path: { cwd: string; root: string } }
|
||||
usage: { cost: number; tokens: Tokens }
|
||||
result: { finish?: string; error?: Error; structured?: unknown; kind: "reply" | "summary" }
|
||||
}
|
||||
```
|
||||
|
||||
Add a separate transient `PromptMessage` for prompt surgery.
|
||||
|
||||
```ts
|
||||
type PromptMessage = {
|
||||
role: "user" | "assistant"
|
||||
parts: PromptPart[]
|
||||
}
|
||||
```
|
||||
|
||||
Plugin hook example:
|
||||
|
||||
```ts
|
||||
prompt.push({
|
||||
role: "user",
|
||||
parts: [{ type: "text", text: "Summarize the tool output above and continue." }],
|
||||
})
|
||||
```
|
||||
|
||||
Tradeoff: prompt hooks get easy lightweight messages, but there are now two message shapes.
|
||||
|
||||
## Option 2: Prompt Mutators
|
||||
|
||||
Keep `User` / `Assistant` as the stored history model.
|
||||
|
||||
Prompt hooks do not build messages directly. The runtime gives them prompt mutators.
|
||||
|
||||
```ts
|
||||
type PromptEditor = {
|
||||
append(input: { role: "user" | "assistant"; parts: PromptPart[] }): void
|
||||
prepend(input: { role: "user" | "assistant"; parts: PromptPart[] }): void
|
||||
appendTo(target: "last-user" | "last-assistant", parts: PromptPart[]): void
|
||||
insertAfter(messageID: string, input: { role: "user" | "assistant"; parts: PromptPart[] }): void
|
||||
insertBefore(messageID: string, input: { role: "user" | "assistant"; parts: PromptPart[] }): void
|
||||
}
|
||||
```
|
||||
|
||||
Plugin hook examples:
|
||||
|
||||
```ts
|
||||
prompt.append({
|
||||
role: "user",
|
||||
parts: [{ type: "text", text: "Summarize the tool output above and continue." }],
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
prompt.appendTo("last-user", [{ type: "text", text: BUILD_SWITCH }])
|
||||
```
|
||||
|
||||
Tradeoff: avoids a second full message type and avoids fake ids/timestamps, but moves more magic into the hook API.
|
||||
|
||||
## Option 3: Separate Turn State
|
||||
|
||||
Move execution settings out of `User` and into a separate turn/request object.
|
||||
|
||||
```ts
|
||||
type Turn = {
|
||||
id: string
|
||||
request: {
|
||||
agent: string
|
||||
model: ModelRef
|
||||
variant?: string
|
||||
format?: OutputFormat
|
||||
system?: string
|
||||
tools?: Record<string, boolean>
|
||||
}
|
||||
}
|
||||
|
||||
type User = {
|
||||
role: "user"
|
||||
turnID: string
|
||||
time: { created: number }
|
||||
}
|
||||
|
||||
type Assistant = {
|
||||
role: "assistant"
|
||||
turnID: string
|
||||
usage: { cost: number; tokens: Tokens }
|
||||
result: { finish?: string; error?: Error; structured?: unknown; kind: "reply" | "summary" }
|
||||
}
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
```ts
|
||||
const turn = {
|
||||
request: {
|
||||
agent: "build",
|
||||
model: { providerID: "openai", modelID: "gpt-5" },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
const msg = {
|
||||
role: "user",
|
||||
turnID: turn.id,
|
||||
parts: [{ type: "text", text: "Summarize the tool output above and continue." }],
|
||||
}
|
||||
```
|
||||
|
||||
Tradeoff: stored messages get much smaller and cleaner, but replay now has to join messages with turn state and prompt hooks still need a way to pick which turn they belong to.
|
||||
13
packages/opencode/specs/v2/notifications.md
Normal file
13
packages/opencode/specs/v2/notifications.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# TUI Notifications Default
|
||||
|
||||
Problem:
|
||||
|
||||
- v1 defaults `attention.enabled` to `false`
|
||||
- users can opt in with `attention.enabled = true`
|
||||
- v2 should make core TUI notifications a default behavior
|
||||
|
||||
## v2 Target
|
||||
|
||||
Flip `attention.enabled` to `true` by default in v2.
|
||||
|
||||
Keep `attention.enabled = false` as the explicit opt-out.
|
||||
67
packages/opencode/specs/v2/tui-command-shim.md
Normal file
67
packages/opencode/specs/v2/tui-command-shim.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# TUI Command Shim Removal
|
||||
|
||||
Problem:
|
||||
|
||||
- v1 keeps a deprecated `api.command` TUI plugin shim so older plugins do not fail during initialization
|
||||
- v2 should expose only the keymap command API
|
||||
- tests and fixtures should not encode legacy command behavior as expected behavior
|
||||
|
||||
## Remove Public Types
|
||||
|
||||
In `packages/plugin/src/tui.ts`, remove:
|
||||
|
||||
- `TuiCommand`
|
||||
- `TuiCommandApi`
|
||||
- `TuiPluginApi.command`
|
||||
|
||||
Keep `api.keymap` as the only TUI command registration and execution surface.
|
||||
|
||||
## Remove Runtime Shim
|
||||
|
||||
Delete `packages/opencode/src/cli/cmd/tui/plugin/command-shim.ts`.
|
||||
|
||||
In `packages/opencode/src/cli/cmd/tui/plugin/api.tsx`, remove:
|
||||
|
||||
- the `createCommandShim` import
|
||||
- the `command: createCommandShim(...)` field from `createTuiApi(...)`
|
||||
|
||||
In `packages/opencode/src/cli/cmd/tui/plugin/runtime.ts`, remove:
|
||||
|
||||
- the `createCommandShim` import
|
||||
- the `command: createCommandShim(...)` field from `pluginApi(...)`
|
||||
|
||||
## Migration Target
|
||||
|
||||
Plugin authors should replace old calls with keymap calls:
|
||||
|
||||
```ts
|
||||
api.keymap.registerLayer({
|
||||
commands: [
|
||||
{
|
||||
name: "plugin.command",
|
||||
title: "Plugin Command",
|
||||
namespace: "palette",
|
||||
slashName: "plugin",
|
||||
run() {
|
||||
api.ui.dialog.clear()
|
||||
},
|
||||
},
|
||||
],
|
||||
bindings: [{ key: "ctrl+shift+p", cmd: "plugin.command" }],
|
||||
})
|
||||
```
|
||||
|
||||
Direct replacements:
|
||||
|
||||
- `api.command.register(cb)` -> `api.keymap.registerLayer({ commands, bindings })`
|
||||
- `api.command.trigger(name)` -> `api.keymap.dispatchCommand(name)`
|
||||
- `api.command.show()` -> `api.keymap.dispatchCommand("command.palette.show")`
|
||||
- `onSelect(dialog)` -> use `api.ui.dialog` from the plugin API closure
|
||||
|
||||
## Verification
|
||||
|
||||
After removal, run from package directories:
|
||||
|
||||
- `bun typecheck` in `packages/plugin`
|
||||
- `bun typecheck` in `packages/opencode`
|
||||
- TUI plugin loader tests in `packages/opencode` if runtime plugin API wiring changed
|
||||
Reference in New Issue
Block a user