Compare commits

..

22 Commits

Author SHA1 Message Date
Kit Langton 7d277f931e fix(tui): keep global event routing unchanged 2026-07-10 12:17:59 -04:00
Kit Langton 1d11bf84c9 fix(tui): filter duplicate event work 2026-07-10 12:13:41 -04:00
Kit Langton cf5e0adf02 fix(core): simplify compaction semantics (#36267) 2026-07-10 11:36:29 -04:00
Kit Langton 41d0a9f010 fix(tui): hide editor context from transcript (#36264) 2026-07-10 11:33:04 -04:00
Dax Raad accaa792d8 docs: clarify opencode skill references 2026-07-10 11:24:03 -04:00
Dax Raad 76d7a11585 docs: expand opencode skill guidance 2026-07-10 11:23:20 -04:00
Dax Raad c867e66ab5 feat(plugin): add promise plugin cleanup 2026-07-10 11:23:20 -04:00
Kit Langton 278c510549 refactor(core): simplify session runner bookkeeping (#36200) 2026-07-10 09:46:34 -04:00
Dax Raad 0d6ccd2a50 docs: add build overview 2026-07-10 02:51:30 -04:00
Aiden Cline 39cceeb143 fix(codemode): return promises from combinators (#35782) 2026-07-10 00:33:21 -05:00
Aiden Cline a6449cb45c refactor(form): model links as fields (#36129) 2026-07-10 00:22:01 -05:00
Dax Raad 6a85f0d3db feat(client): add root promise entrypoint 2026-07-10 01:09:06 -04:00
Dax Raad fbb0fdf88a fix(plugin): select plugins by id 2026-07-10 00:44:43 -04:00
Dax Raad 2a4b298108 refactor(plugin): include name in promise tools 2026-07-10 00:22:45 -04:00
Dax Raad efeff63749 refactor(plugin): simplify promise tool declarations 2026-07-10 00:18:13 -04:00
Kit Langton d54038b9d2 docs(v2): consolidate specifications (#36186) 2026-07-09 22:47:37 -04:00
Dax Raad 8f04a09d1a refactor(plugin): remove protocol dependency 2026-07-09 22:25:38 -04:00
Dax Raad 761f37370f fix(plugin): restore package publishing 2026-07-09 22:18:58 -04:00
Kit Langton b452368b3b refactor(core): simplify tool admission flow (#36180) 2026-07-09 22:01:31 -04:00
Kit Langton 3785eddfa0 fix(core): preserve admitted tool generations (#36177) 2026-07-09 21:16:00 -04:00
Dax Raad 4a006b1210 refactor(core): derive config watches from entries 2026-07-09 21:12:15 -04:00
Aiden Cline 2db7ccb453 fix(core): restore resilient compaction (#36163) 2026-07-09 19:13:11 -05:00
111 changed files with 5663 additions and 5607 deletions
+3 -2
View File
@@ -27,6 +27,7 @@ Never bypass Git hooks. Do not use `--no-verify` or otherwise disable, skip, or
- Keep things in one function unless composable or reusable
- Do not extract single-use helpers preemptively. Inline the logic at the call site unless the helper is reused, hides a genuinely complex boundary, or has a clear independent name that improves the caller.
- Before adding complexity for a speculative or vanishingly unlikely race or security edge case, explain the concrete failure mode, likelihood, and complexity cost to the user and get their buy-in. Do not silently expand scope for theoretical robustness.
- Avoid `try`/`catch` where possible
- Avoid using the `any` type
- Use Bun APIs when possible, like `Bun.file()`
@@ -156,9 +157,9 @@ const table = sqliteTable("session", {
- Keep durable events minimal: record irreducible new facts and do not repeat state derivable by folding the ordered aggregate history. Enrich projections and read models with previous or derived state when consumers need self-contained views.
- Keep durable prompt admission separate from model execution. `SessionV2.prompt(...)` admits one durable `session_pending` row before scheduling advisory `SessionExecution.wake(sessionID)` unless `resume: false` requests admit-only behavior. The serialized runner promotes admitted inputs into visible user messages at safe boundaries, consuming the pending row in the same event transaction; `session_pending` stores only unconsumed work.
- Reusing a Session ID adopts the existing Session. Reusing a prompt message ID reconciles an exact retry only when Session, prompt, and delivery mode match; conflicting reuse fails. Retry of an already-promoted input reconciles against the projected message and the durable admitted event rather than a retained row.
- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; idle or missing interruption is a no-op.
- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; interruption of a known but idle or locally unowned Session is a no-op, while the public API rejects an unknown Session.
- Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics.
- Preserve one explicit `llm.stream(request)` call per step and reload projected history before durable continuation. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop.
- Preserve one explicit `llm.stream(request)` call per Physical Attempt and reload projected history before durable continuation. Most Steps have one Physical Attempt; overflow-triggered compaction recovery may rebuild one Step for a second attempt. Do not bridge through legacy `SessionPrompt.loop(...)` or delegate orchestration to an in-memory tool loop.
- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. Advisory wakes drain eligible durable inbox rows only; post-crash continuation recovery requires a separate explicit design before it may retry provider work. A drain has no durable identity or transcript boundary.
- Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe step boundary while the current drain requires continuation. An explicit `queue` input remains pending until the Session would otherwise become idle; promote one queued input at that boundary, then reevaluate continuation before promoting another. Promoting any new user input resets the selected agent's step allowance; a batch of steers resets it once.
- One step is one logical LLM call; its durable record covers only the model-visible span. Do not write "provider turn", and do not use bare "turn" for a single call: "turn" is reserved for the future assistant-turn unit containing all steps from prompt promotion until the session would go idle.
+5 -5
View File
@@ -182,12 +182,12 @@ _Avoid_: Response envelope
- SDK executes Server's assembled `HttpRouter` in memory. It opens no listener and performs no network I/O, while preserving Server routing, middleware, codecs, handlers, and errors.
- The Effect Client and SDK re-export their decoded datatype facade from Schema so callers do not depend on internal package locations or Core's versioned names.
- A capability intended for both networked and **Embedded OpenCode** belongs in the authoritative public `HttpApi`; embedded-only same-process capabilities extend **Embedded OpenCode** separately.
- `sessions.events({ sessionID, after })` is a public durable Session event stream. It verifies the Session, replays durable events after the optional aggregate sequence, continues with newly committed durable events, excludes live-only fragments, and is transported as SSE in both networked and embedded modes.
- `sessions.log({ sessionID, after, follow })` is the public durable Session event stream. It verifies the Session, replays durable events after the optional aggregate sequence, optionally continues with newly committed durable events, excludes live-only fragments, and is transported as SSE in both networked and embedded modes.
- `events.subscribe()` is a distinct public instance-wide live stream for Session and non-Session activity. It has no replay guarantee and includes connection, heartbeat, and instance-disposal lifecycle events; consumers recover from disconnection by refreshing authoritative state.
- A Session ID is not an optional filter on `events.subscribe()`: instance-wide live events and durable Session events have different schemas, replay guarantees, cursors, lifecycle events, and failure behavior.
- The initial common OpenCode Client does not expose server-global event aggregation. `events.subscribe()` is bounded to the connected OpenCode instance or workspace; any future cross-instance administrative stream requires a separately designed API.
- `events.subscribe()` does not automatically reconnect after transport loss. The live-only stream fails with `ClientError`; consumers refresh authoritative state before explicitly opening a new subscription because events missed during disconnection cannot be replayed.
- `sessions.events({ sessionID, after })` returns the generated HTTP client's cold durable event stream and does not build reconnection policy into the endpoint or client constructor. Transport loss fails the stream with `ClientError`. Callers may compose an explicit resuming stream above it by retaining the last observed durable sequence and opening a new subscription with `after`; any reusable resume helper remains a separate API design question.
- `sessions.log({ sessionID, after, follow })` returns the generated HTTP client's cold durable event stream and does not build reconnection policy into the endpoint or client constructor. Transport loss fails the stream with `ClientError`. Callers may compose an explicit resuming stream above it by retaining the last observed durable sequence and opening a new subscription with `after`; any reusable resume helper remains a separate API design question.
- The stable `sessions.list(...)` design returns a **Page** in both networked and **Embedded OpenCode**; embedded execution does not define a separate unbounded array-returning list operation. The beta client currently preserves the existing HTTP `{ data, cursor }` envelope until emitter-level Page projection is implemented.
- Session list cursors are opaque branded values carrying continuation query and ordering state. Consumers pass them back unchanged and do not inspect storage anchors or encoded filter fields.
- A Session list continuation accepts only its opaque cursor. Scope, filters, ordering, and page size are fixed by the initial query and carried by that cursor.
@@ -209,13 +209,13 @@ _Avoid_: Response envelope
- Oversized textual **Model Tool Output** retains a bounded preview in Session history while its complete text moves to managed tool-output storage. Arbitrary structured-result size is a separate concern.
- One tool settlement receives one aggregate textual limit, using the configured maximum lines or UTF-8 bytes, whichever is reached first. The limit is provider-independent; token pressure belongs to context assembly and compaction.
- Generic truncation preserves the beginning and end of textual output. Tools may apply a more meaningful strategy before the Tool Registry enforces the final limit.
- A truncated **Model Tool Output** identifies its complete text both in the bounded model-visible preview and as a typed managed output path. Managed output paths do not modify the tool's validated structured result.
- A truncated **Model Tool Output** identifies its complete text in the bounded model-visible preview. The Tool Registry also supplies managed paths as internal metadata to tool hooks; Session events do not expose a typed `outputPaths` field.
- A **Managed Tool Output File** is temporary and may expire after its retention period. The bounded **Model Tool Output**, not the file, is the durable replayable record.
- Failure to retain a **Managed Tool Output File** does not change a successful tool operation into a failed one. The Session records an explicitly lossy bounded output without a path, while operators receive diagnostics for the storage failure.
- Failure to retain a **Managed Tool Output File** fails settlement operationally. The Session never publishes a successful result whose complete output was lost during generic bounding.
- Once a tool operation succeeds, bounding its **Model Tool Output** and publishing its one durable settlement form an interruption-safe completion region. Raw oversized success is never published before a later correction.
- When a structured-only result would exceed the **Model Tool Output** limit, its validated structured value remains unchanged for Session consumers while model replay uses a bounded textual JSON preview and optional managed output path.
- Existing tool-managed output paths survive generic bounding. A fallback file retains exactly the complete projected text received by the Tool Registry and never claims to reconstruct output already discarded by tool-specific shaping.
- **Managed Tool Output Files** use globally unique names in one shared flat directory. Their absolute paths are readable and searchable by ordinary tools; other absolute paths remain outside Location-scoped filesystem authority.
- **Managed Tool Output Files** use globally unique names in one shared flat directory. They receive no special filesystem authority; each tool applies its ordinary external-path policy.
- Provider-executed tool results remain provider-native transcript facts outside generic Tool Registry bounding. Their context control requires provider-aware pruning or compaction because some providers require exact structured round-trip payloads.
## Client contract architecture
-2
View File
@@ -716,8 +716,6 @@
"dependencies": {
"@ai-sdk/provider": "3.0.8",
"@opencode-ai/client": "workspace:*",
"@opencode-ai/llm": "workspace:*",
"@opencode-ai/protocol": "workspace:*",
"@opencode-ai/schema": "workspace:*",
"@opencode-ai/sdk": "workspace:*",
"effect": "catalog:",
+1
View File
@@ -16,6 +16,7 @@
"dist"
],
"exports": {
".": "./src/promise/index.ts",
"./promise": "./src/promise/index.ts",
"./promise/api": "./src/promise/api.ts",
"./effect": "./src/effect/index.ts",
+1 -3
View File
@@ -550,9 +550,7 @@ export type Endpoint14_2Input = {
readonly id?: Endpoint14_2Request["payload"]["id"]
readonly title: Endpoint14_2Request["payload"]["title"]
readonly metadata?: Endpoint14_2Request["payload"]["metadata"]
readonly mode: Endpoint14_2Request["payload"]["mode"]
readonly fields?: Endpoint14_2Request["payload"]["fields"]
readonly url?: Endpoint14_2Request["payload"]["url"]
readonly fields: Endpoint14_2Request["payload"]["fields"]
}
export type Endpoint14_2Output = EffectValue<ReturnType<RawClient["server.form"]["session.form.create"]>>["data"]
export type FormCreateOperation<E = never> = (input: Endpoint14_2Input) => Effect.Effect<Endpoint14_2Output, E>
+2 -11
View File
@@ -655,21 +655,12 @@ type Endpoint14_2Input = {
readonly id?: Endpoint14_2Request["payload"]["id"]
readonly title: Endpoint14_2Request["payload"]["title"]
readonly metadata?: Endpoint14_2Request["payload"]["metadata"]
readonly mode: Endpoint14_2Request["payload"]["mode"]
readonly fields?: Endpoint14_2Request["payload"]["fields"]
readonly url?: Endpoint14_2Request["payload"]["url"]
readonly fields: Endpoint14_2Request["payload"]["fields"]
}
const Endpoint14_2 = (raw: RawClient["server.form"]) => (input: Endpoint14_2Input) =>
raw["session.form.create"]({
params: { sessionID: input["sessionID"] },
payload: {
id: input["id"],
title: input["title"],
metadata: input["metadata"],
mode: input["mode"],
fields: input["fields"],
url: input["url"],
},
payload: { id: input["id"], title: input["title"], metadata: input["metadata"], fields: input["fields"] },
}).pipe(
Effect.mapError(mapClientError),
Effect.map((value) => value.data),
@@ -1056,14 +1056,7 @@ export function make(options: ClientOptions) {
{
method: "POST",
path: `/api/session/${encodeURIComponent(input.sessionID)}/form`,
body: {
id: input["id"],
title: input["title"],
metadata: input["metadata"],
mode: input["mode"],
fields: input["fields"],
url: input["url"],
},
body: { id: input["id"], title: input["title"], metadata: input["metadata"], fields: input["fields"] },
successStatus: 200,
declaredStatuses: [404, 409, 400, 401],
empty: false,
File diff suppressed because it is too large Load Diff
@@ -12,7 +12,7 @@ const server = resolve(import.meta.dir, "../../server")
describe("public import boundaries", () => {
test("isolates each public entrypoint", async () => {
const root = await bundleInputs("@opencode-ai/client/promise", "browser")
const root = await bundleInputs("@opencode-ai/client", "browser")
expect(within(root, effect)).toEqual([])
expect(within(root, schema)).toEqual([])
+24 -20
View File
@@ -130,6 +130,7 @@ type Result = Success | Failure
interface Success {
readonly ok: true
readonly value: CodeMode.DataValue
readonly warnings?: ReadonlyArray<CodeMode.Diagnostic>
readonly logs?: ReadonlyArray<string>
readonly truncated?: boolean
readonly toolCalls: ReadonlyArray<CodeMode.ToolCall>
@@ -144,7 +145,7 @@ interface Failure {
}
```
`toolCalls` contains the names of calls admitted by the runtime in call order. It is retained on failure so hosts can audit partial execution without exposing inputs or host failures. `truncated` is present when the value or logs were cut to fit `maxOutputBytes` (see Execution Limits).
`toolCalls` contains the names of calls admitted by the runtime in call order. It is retained on failure so hosts can audit partial execution without exposing inputs or host failures. A successful execution may also contain `warnings`: runtime-authored, non-fatal diagnostics alongside a valid value - unhandled rejections from promises that failed, un-awaited, before the program returned, or background work interrupted by the timeout after the program returned. Anything still running when the program returns is interrupted - race losers and fire-and-forget calls alike - so a program must await every call whose completion matters. Failure has an `error`; success may have `warnings`; program-authored console output stays in `logs`. Keeping the value on an unhandled rejection is a deliberate divergence from Node's crash-on-unhandled-rejection default: the computed value and the background failure are independently useful to the model, so the result carries both. When warnings are cut by `maxOutputBytes`, a final `Truncated` diagnostic marks the omission in-band, and `truncated` marks any result, warning, or log truncation (see Execution Limits).
### Tool-call hooks
@@ -257,11 +258,11 @@ CodeMode is an orchestration language, not a general JavaScript runtime.
The limits are exactly three knobs:
| Limit | Default | Bounds |
| ---------------- | -------------------: | -------------------------------------------------------------------- |
| `timeoutMs` | none - no timeout | Wall-clock execution time. |
| `maxToolCalls` | none - unlimited | Tool calls admitted during the execution. |
| `maxOutputBytes` | none - no truncation | Model-facing output: the serialized result value plus captured logs. |
| Limit | Default | Bounds |
| ---------------- | -------------------: | ---------------------------------------------------- |
| `timeoutMs` | none - no timeout | Wall-clock execution time. |
| `maxToolCalls` | none - unlimited | Tool calls admitted during the execution. |
| `maxOutputBytes` | none - no truncation | Retained result value and logs; warnings separately. |
No limit has a default, on purpose: execution budgets are host policy, not library policy - a host that wants a bound sets one; a host that can interrupt the execution fiber (as OpenCode does on user cancel) may set no timeout, and a host with its own tool-output truncation (as OpenCode has) may leave `maxOutputBytes` unset. A host with neither should set `maxOutputBytes`, or oversized results silently flood model context.
@@ -279,9 +280,11 @@ const runtime = CodeMode.make({
Limits are safe integers. `timeoutMs` must be at least `1`; the others may be `0`. Invalid configuration throws a `RangeError` when `CodeMode.make` or `CodeMode.execute` is called. An explicitly `undefined` value is the same as leaving the limit unset.
Exceeding a configured `maxOutputBytes` never fails the execution. An oversized result value is replaced by its truncated serialized text plus an explanatory marker, logs are kept from the start until the remaining budget is exhausted (with a final marker line noting the cut), and the result carries `truncated: true`.
`maxOutputBytes` is a payload budget, not a strict byte cap on the final rendered tool message. It counts the serialized result value and retained log lines; warning diagnostics are bounded by a separate budget of the same size, so a large value never silences runtime diagnostics. Fixed truncation notices and framing added by a host when it renders the structured result are additional and may make the final message exceed the configured number.
When configured, the timeout interrupts in-flight tool Effects, including eagerly started calls the program has not awaited (their fibers are supervised by the execution). The interpreter yields cooperatively between steps, so the timeout also interrupts pure busy loops (`while (true) {}`) - no separate work budget exists. Tool implementations remain responsible for making their external operations interruptible or independently bounded.
Exceeding a configured `maxOutputBytes` never fails the execution. An oversized result value is replaced by its truncated serialized text plus an explanatory marker, logs are kept within the remaining budget, warnings are kept within their own budget, omitted entries receive a summary marker, and the result carries `truncated: true`.
When configured, the timeout interrupts in-flight tool Effects, including eagerly started calls the program has not awaited (their fibers are supervised by the execution). The interpreter yields cooperatively between steps, so the timeout also interrupts pure busy loops (`while (true) {}`) - no separate work budget exists. Tool implementations remain responsible for making their external operations interruptible or independently bounded: the timeout bounds when interruption begins, not when the result is delivered, which waits for tool interruption cleanup to finish. If the timeout fires after the program has already returned a valid value - while the runtime is interrupting leftover work and waiting for its cleanup - the result stays successful: the computed value is returned with a `TimeoutExceeded` warning instead of being discarded.
Two interpreter internals are fixed constants rather than knobs: at most 8 tool calls run concurrently, and values crossing a data boundary may nest at most 32 levels deep (deeper values fail as `InvalidDataValue`, which reads better than a native stack-overflow error). Neither is part of the public contract.
@@ -289,18 +292,19 @@ Two interpreter internals are fixed constants rather than knobs: at most 8 tool
Failures are data:
| Kind | Meaning |
| ----------------------- | -------------------------------------------------------------------------------------------------------- |
| `ParseError` | Source is empty or cannot be parsed. |
| `UnsupportedSyntax` | Parsed JavaScript is outside the supported subset. |
| `UnknownTool` | A program referenced a tool the host did not provide. |
| `InvalidToolInput` | Tool input failed schema decoding or safe-data copying. |
| `InvalidToolOutput` | Tool output failed schema decoding or safe-data copying. |
| `InvalidDataValue` | Program data violated the plain-data contract (depth, circularity, blocked properties, non-data values). |
| `ToolCallLimitExceeded` | Calls exceeded `maxToolCalls`. |
| `TimeoutExceeded` | Execution exceeded `timeoutMs`. |
| `ToolFailure` | A tool refused or failed. |
| `ExecutionFailure` | The program threw or another execution error occurred. |
| Kind | Meaning |
| ----------------------- | --------------------------------------------------------------------------------------------------------- |
| `ParseError` | Source is empty or cannot be parsed. |
| `UnsupportedSyntax` | Parsed JavaScript is outside the supported subset. |
| `UnknownTool` | A program referenced a tool the host did not provide. |
| `InvalidToolInput` | Tool input failed schema decoding or safe-data copying. |
| `InvalidToolOutput` | Tool output failed schema decoding or safe-data copying. |
| `InvalidDataValue` | Program data violated the plain-data contract (depth, circularity, blocked properties, non-data values). |
| `ToolCallLimitExceeded` | Calls exceeded `maxToolCalls`. |
| `TimeoutExceeded` | Execution exceeded `timeoutMs`; as a warning, background work was interrupted after the program returned. |
| `ToolFailure` | A tool refused or failed. |
| `ExecutionFailure` | The program threw or another execution error occurred. |
| `Truncated` | Warning-only marker: additional warnings were omitted by `maxOutputBytes`. |
Unknown host failures, defects, invalid outputs, and copying failures are sanitized. To return a safe operational refusal, fail with `toolError`:
+30 -18
View File
@@ -63,13 +63,24 @@ path lookup, namespace browsing, deterministic ranking, and pagination.
### Tool execution
Calling a tool starts its Effect eagerly on a supervised fiber. The returned sandbox promise is run-once and can be
awaited directly or through the supported `Promise` combinators. At most eight tool calls execute concurrently.
Unfinished calls are drained before successful program completion, and an unhandled call failure becomes a diagnostic.
Every sandbox promise starts eagerly on a run-once fiber owned by the whole CodeMode execution, including tool calls,
async functions, `Promise.all`, `Promise.allSettled`, `Promise.race`, `Promise.resolve`, and `Promise.reject`. Nested
functions therefore cannot end the lifetime of work they started. Independent aggregate batches overlap, and rejection
is observed at the eventual `await`. `Promise.race` uses native non-cancelling settlement semantics: its first result
wins while losers continue running. At normal completion CodeMode interrupts everything still running - race losers,
fail-fast `Promise.all` stragglers, and fire-and-forget calls alike: the program has returned, so no future await can
exist, and work whose completion matters must be awaited by the program. Waiting for any class of leftover instead
would let it hold the execution open, or deadlock it when queued work needs tool-call permits the leftovers occupy.
Rejections that settled un-awaited before the return become `Success.warnings` diagnostics. A fatal program failure or
host interruption closes the execution promise scope and interrupts its active fibers instead. A timeout does the
same, except that a value the program already returned is preserved alongside a `TimeoutExceeded` warning rather than
discarded. At most eight tool calls execute concurrently.
The public execution-policy knobs are `timeoutMs`, `maxToolCalls`, and `maxOutputBytes`. The package supplies no
defaults because budgets are host policy. The interpreter also enforces fixed internal boundaries for tool-call
concurrency and data nesting depth.
concurrency and data nesting depth. `maxOutputBytes` bounds retained payload bytes, not the complete rendered message;
warning diagnostics have an equal separate budget so a large value cannot starve them, and fixed truncation notices and
host-added framing are intentionally outside the budgets.
### Data, files, and failures
@@ -79,7 +90,7 @@ boundary.
Unknown host failures and invalid outputs are sanitized. `ToolError` is the explicit channel for a safe message that a
tool wants the model to see. Diagnostic categories distinguish parsing, unsupported syntax, unknown tools, invalid
data, tool failures, limits, timeouts, and execution failures.
data, tool failures, limits, timeouts, execution failures, and warning truncation.
Files and other attachment content stay outside the interpreter. A host may collect them while child tools execute and
attach them to the outer result, but the program receives only the structured tool output.
@@ -95,7 +106,8 @@ CodeMode is integrated into V2 through `packages/core/src/tool/registry.ts` and
normally.
- When visible deferred tools exist, Core reserves and materializes one `execute` tool. Grouped deferred tools become
CodeMode namespaces instead of flattened model-facing names.
- Each nested call checks that its captured registration is still current before dispatching it.
- Nested calls execute the registered `Tool` values captured for the model request; later registrations affect later
requests.
- Authorization and side-effect ordering remain responsibilities of the leaf tool. Catalog visibility is not execution
authorization.
- Structured child output enters the interpreter. File parts are collected host-side and attached to the outer result.
@@ -126,18 +138,18 @@ represent accurately rather than guessing semantics.
## Decisions and Rationale
| Decision | Rationale |
| --- | --- |
| Keep an owned tree-walking interpreter. | The product need is bounded tool orchestration, not arbitrary JavaScript. Owning the language surface keeps authority and behavior explicit. |
| Treat schemas as the model-facing interface. | Signatures drive correct calls; Effect Schema also provides the runtime validation boundary, while JSON Schema supports adapter interoperability. |
| Keep authority host-owned. | CodeMode can only confine programs to supplied tools. The host chooses those tools, and each tool enforces its own authorization and side-effect policy. |
| Use progressive catalog disclosure plus search. | Large tool sets should not consume the prompt, but every namespace must remain discoverable and speculative search calls should remain valid. |
| Start tool promises eagerly and supervise them. | This preserves normal call-time parallelism while giving each call run-once settlement and interruption safety. |
| Keep files outside the sandbox value space. | Models should compose structured data without routing binary payloads through generated code or context. |
| Treat `execute` as the model-facing invocation boundary. | Nested calls are implementation details of one orchestration program. Reusing the outer context and bounding only the final result preserves complete intermediate data without inventing durable child-call identities. |
| Return expected failures as data. | Models need actionable diagnostics without exposing private host causes; host interruption and defects must still propagate correctly. |
| Leave execution-limit defaults to hosts. | Appropriate budgets depend on the surrounding product and its own cancellation, retention, and output-bounding policies. |
| Skip unsupported OpenAPI operations. | Incorrect parameter encoding, authentication, or transport behavior is worse than a precise `skipped` reason. |
| Decision | Rationale |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Keep an owned tree-walking interpreter. | The product need is bounded tool orchestration, not arbitrary JavaScript. Owning the language surface keeps authority and behavior explicit. |
| Treat schemas as the model-facing interface. | Signatures drive correct calls; Effect Schema also provides the runtime validation boundary, while JSON Schema supports adapter interoperability. |
| Keep authority host-owned. | CodeMode can only confine programs to supplied tools. The host chooses those tools, and each tool enforces its own authorization and side-effect policy. |
| Use progressive catalog disclosure plus search. | Large tool sets should not consume the prompt, but every namespace must remain discoverable and speculative search calls should remain valid. |
| Start promises eagerly and supervise them for the execution. | This preserves normal call-time parallelism and run-once settlement while allowing pending work to be interrupted when the program returns. |
| Keep files outside the sandbox value space. | Models should compose structured data without routing binary payloads through generated code or context. |
| Treat `execute` as the model-facing invocation boundary. | Nested calls are implementation details of one orchestration program. Reusing the outer context and bounding only the final result preserves complete intermediate data without inventing durable child-call identities. |
| Return expected failures as data. | Models need actionable diagnostics without exposing private host causes; host interruption and defects must still propagate correctly. |
| Leave execution-limit defaults to hosts. | Appropriate budgets depend on the surrounding product and its own cancellation, retention, and output-bounding policies. |
| Skip unsupported OpenAPI operations. | Incorrect parameter encoding, authentication, or transport behavior is worse than a precise `skipped` reason. |
## Remaining Work
+8 -6
View File
@@ -111,13 +111,15 @@ ultimate source of truth.
- [x] `Promise.resolve` and `Promise.reject`.
- [x] `Promise.all`, `Promise.allSettled`, and `Promise.race` over supported collections containing promises and plain
values.
- [x] `Promise.all` preserves result order and rejects on the first observed failure.
- [x] `Promise.all` preserves result order and rejects on the first observed failure without cancelling siblings.
- [x] `Promise.allSettled` returns plain fulfilled/rejected outcome records.
- [x] `Promise.race` interrupts losing in-flight tool calls.
- [x] Un-awaited calls are drained before execution ends; unhandled failures become diagnostics.
- [x] `Promise.race` settles from the first result without cancelling losers at settlement time.
- [x] Real promise values from `Promise.all`, `Promise.allSettled`, and `Promise.race`; separately constructed
combinator batches overlap as in normal JavaScript.
- [x] All still-pending work (race losers, fail-fast `Promise.all` stragglers, and un-awaited calls alike) is
interrupted when the program returns; rejections that settled un-awaited become `Success.warnings`
diagnostics.
- [x] `try`/`catch` can handle awaited tool and promise failures.
- [ ] Real promise values from `Promise.all`, `Promise.allSettled`, and `Promise.race`. These calls currently settle
before returning, so separately constructed combinator batches do not overlap as normal JavaScript promises do.
- [ ] `Promise.any`.
- [ ] Promise chaining with `.then`, `.catch`, and `.finally`.
- [ ] Custom promise construction with `new Promise(...)`.
@@ -269,7 +271,7 @@ ultimate source of truth.
These are actionable implementation items. Check them off only when behavior and direct tests land.
- [ ] Return real promises from `Promise.all`, `Promise.allSettled`, and `Promise.race`.
- [x] Return real promises from `Promise.all`, `Promise.allSettled`, and `Promise.race`.
- [ ] Bound pending tool-call admission/allocation in addition to execution concurrency.
- [ ] Guarantee every advertised tool path is executable, including dotted and blocked path segments.
- [ ] Define safe outbound handling for non-finite numbers and `undefined` so invalid values cannot silently become
+12 -3
View File
@@ -13,11 +13,17 @@ export type { ToolCall, ToolCallEnded, ToolCallHooks, ToolCallStarted, ToolDescr
/** Resource budgets enforced independently during each CodeMode program execution. */
export type ExecutionLimits = {
/** Maximum wall-clock execution time in milliseconds. No default: absent means no timeout. */
/**
* Wall-clock milliseconds before execution is interrupted; result delivery additionally
* waits for tool interruption cleanup. No default: absent means no timeout.
*/
readonly timeoutMs?: number
/** Maximum number of tool calls admitted by the runtime. No default: absent means unlimited. */
readonly maxToolCalls?: number
/** Maximum UTF-8 bytes of model-facing output. No default: absent means no truncation. */
/**
* Maximum UTF-8 bytes retained from the result value and logs; warnings have a separate
* budget of the same size. Fixed truncation notices and host formatting are additional.
*/
readonly maxOutputBytes?: number
}
@@ -75,8 +81,9 @@ export const DiagnosticKind = Schema.Literals([
"TimeoutExceeded",
"ToolFailure",
"ExecutionFailure",
"Truncated",
])
/** Stable categories produced by program, schema, tool, and limit failures. */
/** Stable categories produced by program, schema, tool, limit, and truncation diagnostics. */
export type DiagnosticKind = typeof DiagnosticKind.Type
export const Diagnostic = Schema.Struct({
@@ -92,6 +99,8 @@ const ToolCallSchema = Schema.Struct({ name: Schema.String })
export const Success = Schema.Struct({
ok: Schema.Literal(true),
value: Schema.Json,
// Runtime-authored non-fatal diagnostics; program console output stays in `logs`.
warnings: Schema.optionalKey(Schema.Array(Diagnostic)),
logs: Schema.optionalKey(Schema.Array(Schema.String)),
truncated: Schema.optionalKey(Schema.Boolean),
toolCalls: Schema.Array(ToolCallSchema),
+289 -229
View File
@@ -1,5 +1,5 @@
import { parse } from "acorn"
import { Cause, Effect, Exit, Fiber, Semaphore } from "effect"
import { Cause, Effect, Exit, Fiber, Scope, Semaphore } from "effect"
import { DiagnosticCategory, ModuleKind, ScriptTarget, flattenDiagnosticMessageText, transpileModule } from "typescript"
import {
copyIn,
@@ -219,7 +219,7 @@ const normalizeError = (error: unknown): Diagnostic => {
}
}
// Shared by catch bindings, Promise.allSettled rejection reasons, and Promise.race losers.
// Shared by catch bindings and Promise.allSettled rejection reasons.
const caughtErrorValue = (thrown: unknown): unknown => {
if (thrown instanceof ProgramThrow) return thrown.value
if (thrown instanceof InterpreterRuntimeError) return createErrorValue(thrown.errorName, thrown.message)
@@ -611,6 +611,80 @@ const collectPatternNames = (pattern: AstNode, out: Array<string> = []): Array<s
return out
}
// Promise work lives until the program returns, while observation only controls whether a
// settled rejection is reported. Neither extends execution: completion interrupts all work.
class PromiseRuntime<R> {
private readonly active = new Set<SandboxPromise>()
private readonly ids = new WeakMap<SandboxPromise, number>()
private readonly observed = new WeakSet<SandboxPromise>()
private readonly failures = new Map<number, Diagnostic>()
private nextID = 0
constructor(private readonly scope: Scope.Scope) {}
create(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<SandboxPromise, never, R> {
return Effect.suspend(() => {
// Allocated at execution time (not construction) so re-run effects cannot share an id,
// and before the fork so diagnostics order by creation: a forked body that immediately
// creates promises of its own must sequence after its creator.
const id = this.nextID++
return Effect.map(Effect.forkIn(effect, this.scope, { startImmediately: true }), (fiber) => {
const promise = new SandboxPromise(fiber)
this.active.add(promise)
this.ids.set(promise, id)
fiber.addObserver((exit) => {
this.active.delete(promise)
if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause) || this.observed.has(promise)) {
this.ids.delete(promise)
return
}
const failure = normalizeError(Cause.squash(exit.cause))
this.failures.set(id, {
...failure,
message: `Unhandled rejection from an un-awaited promise: ${failure.message}`,
})
})
return promise
})
})
}
// Synchronous on purpose: JS makes a promise "handled" the moment a construct takes
// responsibility for it (await, or membership in a combinator call), not when the
// consuming fiber later runs. Call sites must invoke this at that moment.
markObserved(promise: SandboxPromise): void {
this.observed.add(promise)
const id = this.ids.get(promise)
this.ids.delete(promise)
if (id !== undefined) this.failures.delete(id)
}
// Pure settlement subscription: never re-runs work and never affects rejection reporting.
await(promise: SandboxPromise): Effect.Effect<Exit.Exit<unknown, unknown>> {
return Fiber.await(promise.fiber)
}
// Unobserved rejections that already settled, in creation order.
diagnostics(): Array<Diagnostic> {
return [...this.failures].sort(([left], [right]) => left - right).map(([, failure]) => failure)
}
// Normal-completion lifecycle: interrupts everything still running and reports the
// rejections that already settled un-awaited. interruptAll signals every fiber
// synchronously before awaiting termination, so no straggler can spawn new work between
// interrupts; the loop re-checks as a backstop because a straggler can create promises
// before its interrupt lands.
interrupt(): Effect.Effect<Array<Diagnostic>> {
const self = this
return Effect.gen(function* () {
while (self.active.size > 0) {
yield* Fiber.interruptAll([...self.active].map((promise) => promise.fiber))
}
return self.diagnostics()
})
}
}
class Interpreter<R> {
private scopes: Array<Map<string, Binding>>
private readonly invokeTool: (path: ReadonlyArray<string>, args: Array<unknown>) => Effect.Effect<unknown, unknown, R>
@@ -620,24 +694,22 @@ class Interpreter<R> {
private readonly logs: Array<string>
// Caps how many eagerly forked tool calls run at once (the parallel-call concurrency cap).
private readonly callPermits: Semaphore.Semaphore
// Fiber-backed promises whose settlement no program construct has observed yet. Successful
// program completion drains these (like a runtime waiting on in-flight work at exit) and
// surfaces a never-awaited failure as an unhandled-rejection diagnostic.
private readonly pendingSettlements: Set<SandboxPromise>
private readonly promises: PromiseRuntime<R>
constructor(
invokeTool: (path: ReadonlyArray<string>, args: Array<unknown>) => Effect.Effect<unknown, unknown, R>,
toolKeys: (path: ReadonlyArray<string>) => ReadonlyArray<string>,
promises: PromiseRuntime<R>,
logs: Array<string> = [],
shared?: { callPermits: Semaphore.Semaphore; pendingSettlements: Set<SandboxPromise> },
callPermits: Semaphore.Semaphore = Semaphore.makeUnsafe(TOOL_CALL_CONCURRENCY),
) {
const globalScope = new Map<string, Binding>()
this.scopes = [globalScope]
this.invokeTool = invokeTool
this.toolKeys = toolKeys
this.logs = logs
this.callPermits = shared?.callPermits ?? Semaphore.makeUnsafe(TOOL_CALL_CONCURRENCY)
this.pendingSettlements = shared?.pendingSettlements ?? new Set<SandboxPromise>()
this.callPermits = callPermits
this.promises = promises
globalScope.set("tools", { mutable: false, value: new ToolReference([]) })
globalScope.set("Promise", { mutable: false, value: new PromiseNamespace() })
globalScope.set("undefined", { mutable: false, value: undefined })
@@ -703,36 +775,12 @@ class Interpreter<R> {
// resolves before crossing the data boundary - `return tools.ns.tool(...)` works
// without an explicit await, exactly as in JS.
if (value instanceof SandboxPromise) value = yield* self.settlePromise(value)
yield* self.drainPendingSettlements()
return value
}).pipe(Effect.ensuring(Effect.sync(() => self.popScope())))
}
// Awaits every fiber-backed promise the program abandoned (fire-and-forget tool calls), so
// their work completes before the execution ends - mirroring a JS runtime waiting on
// in-flight I/O at exit. A failure nobody could have handled becomes an unhandled-rejection
// diagnostic (interrupted calls, e.g. Promise.race losers, are ignored).
private drainPendingSettlements(): Effect.Effect<void, unknown, never> {
const self = this
return Effect.gen(function* () {
while (self.pendingSettlements.size > 0) {
const promise = self.pendingSettlements.values().next().value
if (promise === undefined) break
const exit = yield* self.observePromise(promise)
if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) continue
const failure = normalizeError(Cause.squash(exit.cause))
throw new InterpreterRuntimeError(
`Unhandled rejection from an un-awaited promise: ${failure.message}`,
undefined,
failure.kind,
["Await promises so failures can be caught and handled."],
)
}
})
}
// Eagerly starts a tool call on a supervised child fiber (so the execution timeout and
// scope teardown interrupt it) gated by the concurrency semaphore, and wraps the fiber in a
// Eagerly starts a tool call in the execution's promise scope (so timeout and teardown
// interrupt it) gated by the concurrency semaphore, and wraps the fiber in a
// first-class promise value. `startImmediately` makes the runtime admit the call - charging
// the tool-call budget and firing onToolCallStart - at the call site, before any await.
private createToolCallPromise(
@@ -743,46 +791,20 @@ class Interpreter<R> {
}
private createPromise(effect: Effect.Effect<unknown, unknown, R>): Effect.Effect<SandboxPromise, never, R> {
return Effect.map(Effect.forkChild(effect, { startImmediately: true }), (fiber) => {
const promise = new SandboxPromise(fiber)
this.pendingSettlements.add(promise)
return promise
})
}
// The promise's settlement as an Exit, marking it observed for unhandled-rejection tracking.
// Fiber settlement is idempotent, so observing the same promise repeatedly (await twice,
// Promise.all([p, p])) never re-runs the underlying call.
private observePromise(promise: SandboxPromise): Effect.Effect<Exit.Exit<unknown, unknown>> {
this.pendingSettlements.delete(promise)
return promise.fiber !== undefined ? Fiber.await(promise.fiber) : Effect.exit(promise.immediate ?? Effect.void)
return this.promises.create(effect)
}
// `await promise`: succeed with the fulfilled value or re-raise the failure so try/catch
// observes it exactly like a synchronous throw at the await site.
private settlePromise(promise: SandboxPromise, node?: AstNode): Effect.Effect<unknown, unknown, never> {
const self = this
return Effect.flatMap(this.observePromise(promise), (exit) => self.unwrapPromiseExit(promise, exit, node))
}
private unwrapPromiseExit(
promise: SandboxPromise | undefined,
exit: Exit.Exit<unknown, unknown>,
node?: AstNode,
): Effect.Effect<unknown, unknown> {
if (Exit.isSuccess(exit)) return Effect.succeed(exit.value)
// A call Promise.race interrupted after losing settles as a catchable program failure;
// any other interruption is execution teardown (timeout/host) and must keep propagating
// as interruption rather than becoming program-visible data.
if (promise?.interrupted === true && Cause.hasInterruptsOnly(exit.cause)) {
return Effect.fail(
new InterpreterRuntimeError(
"This tool call was interrupted because another value settled a Promise.race first.",
node,
),
// observes it exactly like a synchronous throw at the await site. Settlement is idempotent
// (fiber exits replay), so awaiting the same promise repeatedly never re-runs the call.
private settlePromise(promise: SandboxPromise): Effect.Effect<unknown, unknown, never> {
const promises = this.promises
return Effect.suspend(() => {
promises.markObserved(promise)
return Effect.flatMap(promises.await(promise), (exit) =>
Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause),
)
}
return Effect.failCause(exit.cause)
})
}
private evaluateStatement(node: AstNode): Effect.Effect<StatementResult, unknown, R> {
@@ -1532,7 +1554,7 @@ class Interpreter<R> {
// matching real JS semantics for non-thenables.
const self = this
return Effect.flatMap(this.evaluateExpression(getNode(node, "argument")), (value) =>
value instanceof SandboxPromise ? self.settlePromise(value, node) : Effect.succeed(value),
value instanceof SandboxPromise ? self.settlePromise(value) : Effect.succeed(value),
)
}
case "NewExpression":
@@ -2199,145 +2221,116 @@ class Interpreter<R> {
// Promise.* over ordinary runtime values. Combinators accept ANY array (or spreadable
// collection) mixing promise values and plain data - built inline, beforehand, via spread,
// whatever - because tool calls already run eagerly on their own fibers; the combinators
// only observe settlements. Joining is therefore sequential (no extra fibers) without
// costing parallelism, and the concurrency cap stays where the work is: the fork semaphore.
// whatever - because tool calls already run eagerly on their own fibers. Each combinator
// returns a real promise whose join runs on its own scope-owned fiber, observing member
// settlements; the concurrency cap stays where the work is: the fork semaphore.
private invokePromiseMethod(
ref: PromiseMethodReference,
args: Array<unknown>,
node: AstNode,
): Effect.Effect<unknown, unknown, R> {
const self = this
if (ref.name === "resolve") {
// Promise.resolve of a promise is that promise (JS flattens); anything else is a
// promise already fulfilled with the value.
// promise already fulfilled with the value. Pre-settled values still fork a scope-owned
// fiber so every promise shares one lifecycle (an abandoned reject is reported, teardown
// is uniform).
const value = args[0]
return Effect.succeed(
value instanceof SandboxPromise ? value : new SandboxPromise(undefined, Effect.succeed(value)),
)
return value instanceof SandboxPromise ? Effect.succeed(value) : this.createPromise(Effect.succeed(value))
}
if (ref.name === "reject") {
return Effect.sync(() => new SandboxPromise(undefined, Effect.fail(new ProgramThrow(args[0]))))
return this.createPromise(Effect.fail(new ProgramThrow(args[0])))
}
const items = Array.isArray(args[0]) ? args[0] : spreadItems(args[0])
if (items === undefined) {
throw new InterpreterRuntimeError(
`Promise.${ref.name} expects an array of promises or plain values (e.g. Promise.${ref.name}(items.map((item) => tools.ns.tool(item)))).`,
node,
return this.createPromise(
Effect.fail(
new InterpreterRuntimeError(
`Promise.${ref.name} expects an array of promises or plain values (e.g. Promise.${ref.name}(items.map((item) => tools.ns.tool(item)))).`,
node,
),
),
)
}
// JS makes combinator members "handled" synchronously at the call - their rejections
// belong to the aggregate from this moment, even ones settling before it runs.
for (const item of items) {
if (item instanceof SandboxPromise) this.promises.markObserved(item)
}
switch (ref.name) {
case "all": {
// Mark every promise element observed up-front (Promise.all handles all of its
// members' failures, as in JS), race their settlements for fail-fast rejection, and
// preserve input order when they all fulfill. Rejected calls keep draining siblings.
const observations = items.map((item, index) =>
// Each observation re-raises its member's failure, so Effect.all rejects on the first
// failure without waiting for the rest and preserves input order when all fulfill.
// Its failure-time interruption only unsubscribes the sibling waiters: the underlying
// fibers stay execution-owned and keep running, as in JS.
const observations = items.map((item) =>
item instanceof SandboxPromise
? Effect.map(this.observePromise(item), (exit) => ({ index, item, exit }))
: Effect.succeed({ index, item: undefined, exit: Exit.succeed(item) }),
? Effect.flatMap(this.promises.await(item), (exit) =>
Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause),
)
: Effect.succeed(item),
)
return Effect.gen(function* () {
const remaining = [...observations]
const values: Array<unknown> = []
values.length = items.length
while (remaining.length > 0) {
const winner = yield* Effect.raceAll(remaining)
const position = remaining.indexOf(observations[winner.index])
if (position >= 0) remaining.splice(position, 1)
if (Exit.isSuccess(winner.exit)) {
values[winner.index] = winner.exit.value
continue
}
yield* self.createPromise(
Effect.asVoid(
Effect.forEach(
items,
(item) => (item instanceof SandboxPromise ? self.observePromise(item) : Effect.void),
{ concurrency: "unbounded" },
),
),
)
return yield* self.unwrapPromiseExit(winner.item, winner.exit, node)
}
return values
})
return this.createPromise(Effect.all(observations, { concurrency: "unbounded" }))
}
case "allSettled": {
const observations = items.map((item) =>
item instanceof SandboxPromise
? Effect.map(this.observePromise(item), (exit) => ({ promise: item as SandboxPromise | undefined, exit }))
: Effect.succeed({ promise: undefined as SandboxPromise | undefined, exit: Exit.succeed(item as unknown) }),
item instanceof SandboxPromise ? this.promises.await(item) : Effect.succeed(Exit.succeed(item as unknown)),
)
return Effect.gen(function* () {
const outcomes: Array<unknown> = []
for (const observation of observations) {
const { exit, promise } = yield* observation
if (Exit.isSuccess(exit)) {
outcomes.push(
Object.assign(Object.create(null) as SafeObject, { status: "fulfilled", value: exit.value }),
)
continue
}
const raceInterrupted = promise?.interrupted === true && Cause.hasInterruptsOnly(exit.cause)
if (Cause.hasInterruptsOnly(exit.cause) && !raceInterrupted) {
// Execution teardown (timeout/host interruption), not a program-level rejection.
return yield* Effect.failCause(exit.cause)
}
const thrown = raceInterrupted
? new InterpreterRuntimeError(
"This tool call was interrupted because another value settled a Promise.race first.",
node,
return this.createPromise(
Effect.gen(function* () {
const outcomes: Array<unknown> = []
for (const observation of observations) {
const exit = yield* observation
if (Exit.isSuccess(exit)) {
outcomes.push(
Object.assign(Object.create(null) as SafeObject, { status: "fulfilled", value: exit.value }),
)
: Cause.squash(exit.cause)
outcomes.push(
Object.assign(Object.create(null) as SafeObject, {
status: "rejected",
reason: caughtErrorValue(thrown),
}),
)
}
return outcomes
})
continue
}
if (Cause.hasInterruptsOnly(exit.cause)) {
// Execution teardown (timeout/host interruption), not a program-level rejection.
return yield* Effect.failCause(exit.cause)
}
outcomes.push(
Object.assign(Object.create(null) as SafeObject, {
status: "rejected",
reason: caughtErrorValue(Cause.squash(exit.cause)),
}),
)
}
return outcomes
}),
)
}
case "race": {
if (items.length === 0) {
throw new InterpreterRuntimeError(
"Promise.race([]) would never settle; provide at least one promise or value.",
node,
return this.createPromise(
Effect.fail(
new InterpreterRuntimeError(
"Promise.race([]) would never settle; provide at least one promise or value.",
node,
),
),
)
}
const observations = items.map((item, index) =>
item instanceof SandboxPromise
? Effect.map(this.observePromise(item), (exit) => ({ index, exit }))
: Effect.succeed({ index, exit: Exit.succeed(item as unknown) }),
const observations = items.map((item) =>
item instanceof SandboxPromise ? this.promises.await(item) : Effect.succeed(Exit.succeed(item as unknown)),
)
// First settlement (fulfilled OR rejected) wins; losing work stays execution-owned
// and is interrupted at normal completion (already observed) or by teardown.
return this.createPromise(
Effect.flatMap(Effect.raceAll(observations), (exit) =>
Exit.isSuccess(exit) ? Effect.succeed(exit.value) : Effect.failCause(exit.cause),
),
)
return Effect.gen(function* () {
// First settlement (fulfilled OR rejected) wins; the observations never fail, so
// racing them yields exactly that. Losing in-flight calls are then interrupted.
const winner = yield* Effect.raceAll(observations)
for (const [index, item] of items.entries()) {
if (index === winner.index || !(item instanceof SandboxPromise) || item.fiber === undefined) continue
item.interrupted = true
yield* Fiber.interrupt(item.fiber)
}
const winningItem = items[winner.index]
return yield* self.unwrapPromiseExit(
winningItem instanceof SandboxPromise ? winningItem : undefined,
winner.exit,
node,
)
})
}
}
}
private invokeFunction(fn: CodeModeFunction, args: Array<unknown>): Effect.Effect<unknown, unknown, R> {
const invocation = new Interpreter(this.invokeTool, this.toolKeys, this.logs, {
callPermits: this.callPermits,
pendingSettlements: this.pendingSettlements,
})
const invocation = new Interpreter(this.invokeTool, this.toolKeys, this.promises, this.logs, this.callPermits)
invocation.scopes = [...fn.capturedScopes, new Map<string, Binding>()]
const run = Effect.gen(function* () {
// Seed every parameter name into the scope as a TDZ slot first, so a default that
@@ -3484,68 +3477,109 @@ export const executeWithLimits = <const Tools extends Record<string, unknown>>(
limits: ResolvedExecutionLimits,
searchIndex: ToolRuntime.DiscoveryPlan["searchIndex"],
): Effect.Effect<Result, never, Services<Tools>> => {
const hooks = {
...(options.onToolCallStart === undefined ? {} : { onToolCallStart: options.onToolCallStart }),
...(options.onToolCallEnd === undefined ? {} : { onToolCallEnd: options.onToolCallEnd }),
}
const tools = ToolRuntime.make(
(options.tools ?? {}) as HostTools<Services<Tools>>,
limits.maxToolCalls,
searchIndex,
hooks,
)
const logs: Array<string> = []
const logged = () => (logs.length > 0 ? { logs: [...logs] } : {})
if (options.code.trim().length === 0) {
return Effect.succeed({
ok: false,
error: { kind: "ParseError", message: "Code cannot be empty." },
toolCalls: tools.calls,
toolCalls: [],
})
}
const operation = Effect.gen(function* () {
const program = parseProgram(options.code)
const interpreter = new Interpreter<Services<Tools>>(tools.invoke, tools.keys, logs)
const value = yield* interpreter.run(program)
const result = copyOut(copyIn(value, "Execution result"), true) as DataValue
return {
ok: true,
value: result,
...logged(),
toolCalls: tools.calls,
} satisfies Result
}).pipe((program) => {
const timeoutMs = limits.timeoutMs
if (timeoutMs === undefined) return program
return program.pipe(
Effect.timeoutOrElse({
duration: timeoutMs,
orElse: () =>
Effect.succeed({
ok: false,
error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` },
// Suspended so all per-execution state - tool-call admission budget and audit list, logs,
// and the timeout path's completed value - binds at run time: a reused Effect must start
// from a clean slate instead of observing a previous run's state.
return Effect.suspend(() => {
const hooks = {
...(options.onToolCallStart === undefined ? {} : { onToolCallStart: options.onToolCallStart }),
...(options.onToolCallEnd === undefined ? {} : { onToolCallEnd: options.onToolCallEnd }),
}
const tools = ToolRuntime.make(
(options.tools ?? {}) as HostTools<Services<Tools>>,
limits.maxToolCalls,
searchIndex,
hooks,
)
const logs: Array<string> = []
const logged = () => (logs.length > 0 ? { logs: [...logs] } : {})
// Set once the program body returned and its value crossed the data boundary, so a timeout
// firing during leftover interruption reports "completed with interrupted background work"
// instead of discarding the computed value as a plain timeout.
let returned: { value: DataValue; promises: PromiseRuntime<Services<Tools>> } | undefined
const base = Effect.acquireUseRelease(
Scope.make("parallel"),
(scope) =>
Effect.gen(function* () {
const program = parseProgram(options.code)
const promises = new PromiseRuntime<Services<Tools>>(scope)
const interpreter = new Interpreter<Services<Tools>>(tools.invoke, tools.keys, promises, logs)
const value = yield* interpreter.run(program)
// Validate the result first so an invalid value is a fatal completion that closes
// the promise scope directly instead of taking the normal-completion path.
const result = copyOut(copyIn(value, "Execution result"), true) as DataValue
returned = { value: result, promises }
const warnings = yield* promises.interrupt()
return {
ok: true,
value: result,
...(warnings.length > 0 ? { warnings } : {}),
...logged(),
toolCalls: tools.calls,
} satisfies Result),
}),
} satisfies Result
}),
(scope, exit) => Scope.close(scope, exit),
)
const timeoutMs = limits.timeoutMs
const operation =
timeoutMs === undefined
? base
: base.pipe(
Effect.timeoutOrElse({
duration: timeoutMs,
orElse: () =>
Effect.sync(() => {
if (returned === undefined) {
return {
ok: false,
error: { kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` },
...logged(),
toolCalls: tools.calls,
} satisfies Result
}
// The timeout warning leads so byte-budget truncation cuts it last.
return {
ok: true,
value: returned.value,
warnings: [
{
kind: "TimeoutExceeded",
message: `The program returned, but background work was still running at the ${timeoutMs}ms timeout and was interrupted. Await all started promises.`,
},
...returned.promises.diagnostics(),
],
...logged(),
toolCalls: tools.calls,
} satisfies Result
}),
}),
)
return operation.pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.interrupt
: Effect.succeed({
ok: false,
error: normalizeError(Cause.squash(cause)),
...logged(),
toolCalls: tools.calls,
} satisfies Result),
),
Effect.map((result) =>
limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes),
),
)
})
return operation.pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.interrupt
: Effect.succeed({
ok: false,
error: normalizeError(Cause.squash(cause)),
...logged(),
toolCalls: tools.calls,
} satisfies Result),
),
Effect.map((result) => (limits.maxOutputBytes === undefined ? result : boundOutput(result, limits.maxOutputBytes))),
)
}
const utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength
@@ -3560,9 +3594,10 @@ const utf8Truncate = (value: string, maxBytes: number): string => {
}
/**
* Bounds the model-facing output (serialized result value plus logs) to `maxOutputBytes`.
* Oversized values are replaced by their truncated serialized text with an explanatory marker,
* and logs are kept from the start until the remaining budget is exhausted. Truncation never
* Bounds retained program payload bytes (serialized result value and logs) to `maxOutputBytes`.
* Warning diagnostics are bounded by a separate budget of the same size so a large value can
* never starve runtime-authored diagnostics. Fixed truncation notices are added outside those
* budgets, as is any framing added when a host renders the structured result. Truncation never
* fails the execution; `truncated: true` marks affected results. Only runs when the host set
* `maxOutputBytes` - with the limit absent, output passes through unbounded.
*/
@@ -3584,6 +3619,23 @@ const boundOutput = (result: Result, maxOutputBytes: number): Result => {
}
}
const warnings = result.ok ? (result.warnings ?? []) : []
const keptWarnings: Array<Diagnostic> = []
let warningBytes = 0
for (const warning of warnings) {
const bytes = utf8ByteLength(JSON.stringify(warning)) + 1
if (warningBytes + bytes > maxOutputBytes) break
warningBytes += bytes
keptWarnings.push(warning)
}
if (keptWarnings.length < warnings.length) {
truncated = true
keptWarnings.push({
kind: "Truncated",
message: `${warnings.length - keptWarnings.length} additional warnings omitted by the output limit.`,
})
}
const logs = result.logs ?? []
const kept: Array<string> = []
const logBudget = Math.max(0, maxOutputBytes - valueBytes)
@@ -3600,8 +3652,16 @@ const boundOutput = (result: Result, maxOutputBytes: number): Result => {
}
if (!truncated) return result
const warningsPart = keptWarnings.length > 0 ? { warnings: keptWarnings } : {}
const logsPart = kept.length > 0 ? { logs: kept } : {}
return result.ok
? { ok: true, value, ...logsPart, truncated: true, toolCalls: result.toolCalls }
? {
ok: true,
value,
...warningsPart,
...logsPart,
truncated: true,
toolCalls: result.toolCalls,
}
: { ok: false, error: result.error, ...logsPart, truncated: true, toolCalls: result.toolCalls }
}
+1
View File
@@ -602,6 +602,7 @@ export const prepare = <R>(tools: HostTools<R>, catalogBudget = defaultCatalogBu
"- Filter, aggregate, and transform collections in code - never return them raw or call a tool per item across messages.",
"- A result typed `Promise<unknown>` may be structured data or text. Before reading fields, check that it is a non-null object and not an array; otherwise handle the returned text or primitive directly.",
'- Run independent calls in parallel: `await Promise.all(items.map((item) => tools.<namespace>.<tool>(item)))`, or use `tools.<namespace>["tool-name"](item)` when the listed signature uses bracket notation.',
"- Execution ends when the program returns; pending promises are interrupted, so await every call whose completion matters.",
"- `Object.keys(tools)` lists namespaces; `Object.keys(tools.<namespace>)` lists its tools; `for...in` works on both.",
...(complete
? []
+2 -6
View File
@@ -1,11 +1,7 @@
import type { Effect, Fiber } from "effect"
import type { Fiber } from "effect"
export class SandboxPromise {
interrupted = false
constructor(
readonly fiber: Fiber.Fiber<unknown, unknown> | undefined,
readonly immediate?: Effect.Effect<unknown, unknown>,
) {}
constructor(readonly fiber: Fiber.Fiber<unknown, unknown>) {}
}
export class SandboxDate {
+20
View File
@@ -506,6 +506,26 @@ describe("CodeMode public contract", () => {
expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(reusable)))).toStrictEqual(reusable)
})
test("a reused execution Effect starts from a clean slate", async () => {
const echo = Tool.make({
description: "echo",
input: Schema.Struct({}),
output: Schema.Number,
run: () => Effect.succeed(1),
})
const effect = CodeMode.execute({
tools: { host: { echo } },
code: `console.log("hi"); return await tools.host.echo({})`,
limits: { maxToolCalls: 1 },
})
const first = await Effect.runPromise(effect)
const second = await Effect.runPromise(effect)
// Per-execution state (tool-call budget and audit list, logs, timeout bookkeeping) must
// bind at run time, so the second run neither exhausts the budget nor leaks run 1's logs.
expect(first).toStrictEqual(second)
expect(second).toStrictEqual({ ok: true, value: 1, logs: ["hi"], toolCalls: [{ name: "host.echo" }] })
})
test("inlines a COMPLETE small catalog and keeps search registered but unadvertised", async () => {
const runtime = CodeMode.make({ tools })
expect(runtime.catalog()).toStrictEqual([
@@ -0,0 +1,906 @@
/*
* Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75.
* Every test names its upstream source; test.failing cases are executable conformance
* targets for intended Promise behavior that CodeMode does not implement yet.
*
* Copyright 2014 Cubane Canada, Inc. All rights reserved.
* Copyright 2015 Microsoft Corporation. All rights reserved.
* Copyright 2016 Microsoft, Inc. All rights reserved.
* Copyright 2017 Caitlin Potter. All rights reserved.
* Copyright (C) 2016-2020 the V8 project authors. All rights reserved.
* Copyright (C) 2018-2020 Rick Waldron. All rights reserved.
* Copyright (C) 2019 Leo Balter. All rights reserved.
* Test262 portions are governed by the BSD license in LICENSE.test262.
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { CodeMode } from "../src/index.js"
const execute = (code: string) =>
Effect.runPromise(CodeMode.execute({ code, tools: {}, limits: { timeoutMs: 1_000 } }))
const value = async (code: string) => {
const result = await execute(code)
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
return result.value
}
describe("Test262 Promise statics", () => {
test("statics are callable and return promises", async () => {
// Sources:
// test/built-ins/Promise/all/S25.4.4.1_A1.1_T1.js
// test/built-ins/Promise/allSettled/is-function.js
// test/built-ins/Promise/allSettled/returns-promise.js
// test/built-ins/Promise/race/S25.4.4.3_A1.1_T1.js
// test/built-ins/Promise/resolve/S25.4.4.5_A1.1_T1.js
// test/built-ins/Promise/reject/S25.4.4.4_A1.1_T1.js
expect(
await value(`
const values = [
Promise.all([]),
Promise.allSettled([]),
Promise.race([undefined]),
Promise.resolve(),
Promise.reject(),
]
const callable = [
typeof Promise.all,
typeof Promise.allSettled,
typeof Promise.race,
typeof Promise.resolve,
typeof Promise.reject,
]
try { await values[4] } catch {}
return [callable, values.map((item) => item instanceof Promise)]
`),
).toEqual([
["function", "function", "function", "function", "function"],
[true, true, true, true, true],
])
})
test("Promise.all returns fresh arrays for empty and settled inputs", async () => {
// Sources:
// test/built-ins/Promise/all/S25.4.4.1_A2.1_T1.js
// test/built-ins/Promise/all/S25.4.4.1_A2.3_T1.js
// test/built-ins/Promise/all/S25.4.4.1_A2.3_T2.js
// test/built-ins/Promise/all/S25.4.4.1_A2.3_T3.js
// test/built-ins/Promise/all/S25.4.4.1_A7.1_T1.js
expect(
await value(`
const input = []
const emptyPromise = Promise.all(input)
const empty = await emptyPromise
const onePromise = Promise.all([Promise.resolve(3)])
const one = await onePromise
return [
emptyPromise instanceof Promise,
empty instanceof Array,
empty.length,
empty !== input,
onePromise instanceof Promise,
one instanceof Array,
one.length,
one[0],
]
`),
).toEqual([true, true, 0, true, true, true, 1, 3])
})
test("Promise.all adopts values and preserves input order and identity", async () => {
// Sources:
// test/built-ins/Promise/all/resolve-non-thenable.js
// test/built-ins/Promise/all/S25.4.4.1_A8.2_T1.js
// test/built-ins/Promise/all/S25.4.4.1_A8.2_T2.js
const result = await value(`
const first = { id: 1 }
const second = { id: 2 }
const values = await Promise.all([Promise.resolve(3), first, Promise.resolve(second)])
const observe = async (promise) => {
try { await promise; return "fulfilled" } catch (reason) { return reason }
}
return [
values.length,
values[0],
values[1] === first,
values[2] === second,
await observe(Promise.all([Promise.reject(1), Promise.resolve(2)])),
await observe(Promise.all([Promise.resolve(1), Promise.reject(2)])),
]
`)
expect(result).toEqual([3, 3, true, true, 1, 2])
})
test("Promise.allSettled returns fresh arrays and ordered outcome records", async () => {
// Sources:
// test/built-ins/Promise/allSettled/resolves-empty-array.js
// test/built-ins/Promise/allSettled/resolves-to-array.js
// test/built-ins/Promise/allSettled/resolved-all-fulfilled.js
// test/built-ins/Promise/allSettled/resolved-all-rejected.js
// test/built-ins/Promise/allSettled/resolved-all-mixed.js
// test/built-ins/Promise/allSettled/resolve-non-thenable.js
expect(
await value(`
const input = []
const empty = await Promise.allSettled(input)
const reason = { id: 4 }
const object = { id: 5 }
const outcomes = await Promise.allSettled([
Promise.resolve(1),
Promise.reject(2),
3,
Promise.reject(reason),
object,
])
return [
empty instanceof Array,
empty.length,
empty !== input,
outcomes,
outcomes[4].value === object,
outcomes.map((item) => Object.keys(item)),
]
`),
).toEqual([
true,
0,
true,
[
{ status: "fulfilled", value: 1 },
{ status: "rejected", reason: 2 },
{ status: "fulfilled", value: 3 },
{ status: "rejected", reason: { id: 4 } },
{ status: "fulfilled", value: { id: 5 } },
],
true,
[
["status", "value"],
["status", "reason"],
["status", "value"],
["status", "reason"],
["status", "value"],
],
])
})
test("Promise.race preserves fulfillment, rejection, and iterable order", async () => {
// Sources:
// test/built-ins/Promise/race/S25.4.4.3_A6.2_T1.js
// test/built-ins/Promise/race/S25.4.4.3_A7.1_T1.js
// test/built-ins/Promise/race/S25.4.4.3_A7.2_T1.js
// test/built-ins/Promise/race/S25.4.4.3_A7.3_T1.js
// test/built-ins/Promise/race/S25.4.4.3_A7.3_T2.js
expect(
await value(`
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
return await Promise.all([
observe(Promise.race([23])),
observe(Promise.race([Promise.reject(7)])),
observe(Promise.race([Promise.resolve(1), Promise.resolve(2)])),
observe(Promise.race([Promise.reject(3), Promise.resolve(4)])),
])
`),
).toEqual([
["fulfilled", 23],
["rejected", 7],
["fulfilled", 1],
["rejected", 3],
])
})
test("combinators consume supported string iterables", async () => {
// Sources:
// test/built-ins/Promise/all/iter-arg-is-string-resolve.js
// test/built-ins/Promise/allSettled/iter-arg-is-string-resolve.js
// test/built-ins/Promise/race/iter-arg-is-string-resolve.js
expect(
await value(`
return [
await Promise.all("abc"),
await Promise.allSettled("ab"),
await Promise.race("abc"),
]
`),
).toEqual([
["a", "b", "c"],
[
{ status: "fulfilled", value: "a" },
{ status: "fulfilled", value: "b" },
],
"a",
])
})
test("Promise.resolve adopts values and preserves sandbox-promise identity", async () => {
// Sources:
// test/built-ins/Promise/resolve/S25.4.4.5_A2.1_T1.js
// test/built-ins/Promise/resolve/resolve-non-obj.js
// test/built-ins/Promise/resolve/resolve-non-thenable.js
expect(
await value(`
const object = { id: 1 }
const promise = Promise.resolve(1)
return [
await Promise.resolve(23),
await Promise.resolve(Promise.resolve(24)),
(await Promise.resolve(object)) === object,
[promise].includes(Promise.resolve(promise)),
]
`),
).toEqual([23, 24, true, true])
})
test("Promise.reject preserves primitive and object reasons", async () => {
// Sources:
// test/built-ins/Promise/reject/S25.4.4.4_A2.1_T1.js
const result = await value(`
const object = { reason: true }
const reasons = [undefined, null, false, true, 0, "", 42, object]
const observe = async (reason) => {
try { await Promise.reject(reason); return false } catch (caught) { return caught === reason }
}
return await Promise.all(reasons.map(observe))
`)
expect(result).toEqual([true, true, true, true, true, true, true, true])
})
test("Promise.all resolves duplicate members into every slot", async () => {
// Sources:
// test/built-ins/Promise/all/invoke-resolve-on-promises-every-iteration-of-promise.js
// test/built-ins/Promise/all/invoke-resolve-on-values-every-iteration-of-promise.js
// (adapted: CodeMode has no observable Promise.resolve hook, so per-iteration
// handling of a repeated member is asserted through the resolved slots)
expect(
await value(`
const settled = Promise.resolve(3)
const computed = (async () => "computed")()
return [
await Promise.all([settled, settled, settled]),
await Promise.all([computed, "plain", computed]),
]
`),
).toEqual([
[3, 3, 3],
["computed", "plain", "computed"],
])
})
test("Promise.allSettled records duplicate members independently", async () => {
// Source: test/built-ins/Promise/allSettled/invoke-resolve-on-promises-every-iteration-of-promise.js
// (adapted: per-iteration handling of a repeated member is asserted through the
// outcome records instead of a Promise.resolve hook)
expect(
await value(`
const good = Promise.resolve(1)
const bad = Promise.reject(2)
return await Promise.allSettled([good, bad, good, bad])
`),
).toEqual([
{ status: "fulfilled", value: 1 },
{ status: "rejected", reason: 2 },
{ status: "fulfilled", value: 1 },
{ status: "rejected", reason: 2 },
])
})
test("combinators adopt members that settled before the call", async () => {
// Sources:
// test/built-ins/Promise/all/reject-immed.js
// test/built-ins/Promise/allSettled/reject-immed.js
// test/built-ins/Promise/race/reject-immed.js
// (adapted: immediately-rejecting thenables become sandbox promises that settled,
// and were even observed, before the combinator call)
expect(
await value(`
const fulfilled = Promise.resolve("done")
const rejected = Promise.reject("failed")
try { await rejected } catch {}
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
return [
await observe(Promise.all([fulfilled, rejected])),
await Promise.allSettled([rejected, fulfilled]),
await observe(Promise.race([rejected, fulfilled])),
]
`),
).toEqual([
["rejected", "failed"],
[
{ status: "rejected", reason: "failed" },
{ status: "fulfilled", value: "done" },
],
["rejected", "failed"],
])
})
test("combinator results follow input order, not settlement order", async () => {
// Sources:
// test/built-ins/Promise/all/resolve-non-thenable.js
// test/built-ins/Promise/allSettled/resolved-all-mixed.js
// (adapted: members are created, and therefore settle, in reverse of input order;
// deferred settlement is not expressible without host-async work in this corpus)
expect(
await value(`
const third = Promise.resolve("c")
const failing = (async () => { throw "b" })()
try { await failing } catch {}
const second = (async () => "b")()
const first = Promise.resolve("a")
return [
await Promise.all([first, second, third]),
await Promise.allSettled([first, failing, third]),
]
`),
).toEqual([
["a", "b", "c"],
[
{ status: "fulfilled", value: "a" },
{ status: "rejected", reason: "b" },
{ status: "fulfilled", value: "c" },
],
])
})
test("Promise.race ignores a rejected loser once the first contender wins", async () => {
// Source: test/built-ins/Promise/race/reject-ignored-immed.js
// (adapted: the losing rejection comes from an async function instead of a thenable;
// the exact-equality check also asserts the loser leaves no unhandled-rejection warning)
expect(
await execute(`
const loser = (async () => { throw "lost" })()
return await Promise.race([Promise.resolve("won"), loser])
`),
).toEqual({ ok: true, value: "won", toolCalls: [] })
})
test("Promise.race([]) returns a promise whose CodeMode failure is catchable", async () => {
// Sources:
// test/built-ins/Promise/race/S25.4.4.3_A2.1_T1.js
// test/built-ins/Promise/race/S25.4.4.3_A5.1_T1.js
// (adapted: upstream requires Promise.race([]) to never settle; CodeMode intentionally
// rejects with a catchable diagnostic instead of hanging, so this asserts the sandbox
// divergence rather than the spec never-settles behavior)
expect(
await value(`
const empty = Promise.race([])
try {
await empty
return "settled"
} catch (error) {
return [empty instanceof Promise, error instanceof Error]
}
`),
).toEqual([true, true])
})
test("Promise.resolve passes the same sandbox promise through nested chains", async () => {
// Source: test/built-ins/Promise/resolve/S25.4.4.5_A2.2_T1.js
// (adapted: no executor construction, and identity is observed with Array includes
// because promises are not comparable data values in CodeMode)
expect(
await value(`
const promise = Promise.resolve({ id: 1 })
return [
[promise].includes(Promise.resolve(promise)),
[promise].includes(Promise.resolve(Promise.resolve(promise))),
(await Promise.resolve(Promise.resolve(promise))).id,
]
`),
).toEqual([true, true, 1])
})
test("Promise.resolve of a rejected promise preserves identity and reason", async () => {
// Source: test/built-ins/Promise/resolve/S25.4.4.5_A2.3_T1.js
// (adapted: the source promise is already rejected instead of rejected later)
expect(
await value(`
const rejected = Promise.reject("oops")
const adopted = Promise.resolve(rejected)
const identity = [rejected].includes(adopted)
try {
await adopted
return "fulfilled"
} catch (reason) {
return [identity, reason]
}
`),
).toEqual([true, "oops"])
})
test("Promise.reject uses a promise reason without flattening it", async () => {
// Sources:
// test/built-ins/Promise/reject-via-fn-immed.js
// test/built-ins/Promise/reject-via-fn-deferred.js
// (adapted: the promise reason goes through Promise.reject instead of executor reject)
expect(
await value(`
const observe = async (reason) => {
try {
await Promise.reject(reason)
return "fulfilled"
} catch (caught) {
const identity = [reason].includes(caught)
try { return [identity, caught instanceof Promise, await caught] }
catch (inner) { return [identity, caught instanceof Promise, "rethrew " + inner] }
}
}
return [await observe(Promise.resolve(1)), await observe(Promise.reject("inner"))]
`),
).toEqual([
[true, true, 1],
[true, true, "rethrew inner"],
])
})
})
describe("Test262 async functions and await", () => {
test("declaration, expression, and arrow forms return promises", async () => {
// Sources:
// test/language/statements/async-function/declaration-returns-promise.js
// test/language/expressions/async-function/expression-returns-promise.js
// test/language/expressions/async-arrow-function/arrow-returns-promise.js
expect(
await value(`
async function declaration() { return 1 }
const expression = async function() { return 2 }
const arrow = async () => 3
const promises = [declaration(), expression(), arrow()]
return [promises.map((item) => item instanceof Promise), await Promise.all(promises)]
`),
).toEqual([[true, true, true], [1, 2, 3]])
})
test("async bodies adopt returns and reject throws before and after await", async () => {
// Sources:
// test/language/statements/async-function/evaluation-body.js
// test/language/statements/async-function/evaluation-body-that-returns.js
// test/language/statements/async-function/evaluation-body-that-returns-after-await.js
// test/language/statements/async-function/evaluation-body-that-throws.js
// test/language/statements/async-function/evaluation-body-that-throws-after-await.js
expect(
await value(`
const order = []
const plain = async () => { order.push("body"); return 42 }
const afterAwait = async () => { await Promise.resolve(); return 43 }
const throwsBefore = async () => { throw 1 }
const throwsAfter = async () => { await Promise.resolve(); throw 2 }
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
const first = plain()
return [
order,
await observe(first),
await observe(afterAwait()),
await observe(throwsBefore()),
await observe(throwsAfter()),
]
`),
).toEqual([
["body"],
["fulfilled", 42],
["fulfilled", 43],
["rejected", 1],
["rejected", 2],
])
})
test("default-parameter throws reject instead of escaping the call", async () => {
// Source: test/language/statements/async-function/evaluation-default-that-throws.js
expect(
await value(`
const fail = () => { throw new Error("default") }
const run = async (value = fail()) => value
let returned = false
try {
const promise = run()
returned = promise instanceof Promise
await promise
return [returned, "fulfilled"]
} catch (error) {
return [returned, error.message]
}
`),
).toEqual([true, "default"])
})
test("async try/finally completion records override earlier completion", async () => {
// Sources: the try-{return,throw,reject}-finally-{return,throw,reject}.js matrix under
// test/language/statements/async-function, test/language/expressions/async-function,
// and test/language/expressions/async-arrow-function.
expect(
await value(`
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
const returnReturn = async () => { try { return "early" } finally { return await Promise.resolve("override") } }
const returnThrow = async () => { try { return "early" } finally { throw "override" } }
const returnReject = async () => { try { return "early" } finally { await Promise.reject("override") } }
const throwReturn = async () => { try { throw "early" } finally { return await Promise.resolve("override") } }
const throwThrow = async () => { try { throw "early" } finally { throw "override" } }
const throwReject = async () => { try { throw "early" } finally { await Promise.reject("override") } }
const rejectReturn = async () => { try { await Promise.reject("early") } finally { return await Promise.resolve("override") } }
const rejectThrow = async () => { try { await Promise.reject("early") } finally { throw "override" } }
const rejectReject = async () => { try { await Promise.reject("early") } finally { await Promise.reject("override") } }
return await Promise.all([
observe(returnReturn()), observe(returnThrow()), observe(returnReject()),
observe(throwReturn()), observe(throwThrow()), observe(throwReject()),
observe(rejectReturn()), observe(rejectThrow()), observe(rejectReject()),
])
`),
).toEqual([
["fulfilled", "override"],
["rejected", "override"],
["rejected", "override"],
["fulfilled", "override"],
["rejected", "override"],
["rejected", "override"],
["fulfilled", "override"],
["rejected", "override"],
["rejected", "override"],
])
})
test("await preserves an object whose then property is not callable", async () => {
// Source: test/language/expressions/await/await-awaits-thenable-not-callable.js
expect(
await value(`
const thenable = { then: 42 }
return (await thenable) === thenable
`),
).toBe(true)
})
test("await returns non-promise operands unchanged", async () => {
// Source: test/language/expressions/await/await-non-promise.js
// (adapted: only value pass-through is asserted here; the spec tick ordering around
// await of non-promises is covered by the failing interleaving test below)
expect(
await value(`
const object = { id: 1 }
const array = [1, 2]
return [
await 1,
await "text",
await true,
(await null) === null,
(await undefined) === undefined,
(await object) === object,
(await array) === array,
]
`),
).toEqual([1, "text", true, true, true, true, true])
})
})
describe("Test262 expected Promise conformance", () => {
for (const name of ["all", "allSettled", "race"] as const) {
test.failing(`Promise.${name} rejects invalid input with TypeError`, async () => {
// Sources:
// test/built-ins/Promise/all/S25.4.4.1_A3.1_T1.js
// test/built-ins/Promise/all/S25.4.4.1_A3.1_T2.js
// test/built-ins/Promise/allSettled/iter-arg-is-number-reject.js
// test/built-ins/Promise/race/iter-arg-is-number-reject.js
expect(
await value(`
try {
const promise = Promise.${name}(42)
const returned = promise instanceof Promise
await promise
return [returned, "fulfilled"]
} catch (error) {
return [true, error.name]
}
`),
).toEqual([true, "TypeError"])
})
}
test.failing("Promise.all consumes sparse positions as undefined", async () => {
// Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior)
expect(
await value(`
const input = []
input[1] = 1
const result = await Promise.all(input)
return [result.length, result[0] === undefined, result[1]]
`),
).toEqual([2, true, 1])
})
test.failing("Promise.allSettled consumes sparse positions as undefined", async () => {
// Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior)
expect(
await value(`
const input = []
input[1] = 1
const result = await Promise.allSettled(input)
return [result.length, result[0].status, result[0].value === undefined, result[1]]
`),
).toEqual([2, "fulfilled", true, { status: "fulfilled", value: 1 }])
})
test.failing("Promise.race consumes a sparse first position as undefined", async () => {
// Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior)
expect(
await value(`
const input = []
input[1] = 1
return (await Promise.race(input)) === undefined
`),
).toBe(true)
})
test.failing("Promise.all settles after reactions attached to its inputs", async () => {
// Sources:
// test/built-ins/Promise/all/S25.4.4.1_A7.2_T1.js
// test/built-ins/Promise/all/S25.4.4.1_A8.1_T1.js
expect(
await value(`
const sequence = [1]
const input = Promise.resolve(1)
const aggregate = Promise.all([input])
aggregate.then(() => sequence.push(4))
input.then(() => sequence.push(3)).then(() => sequence.push(5))
sequence.push(2)
await aggregate
await Promise.resolve()
return sequence
`),
).toEqual([1, 2, 3, 4, 5])
})
test.failing("Promise.allSettled settles after reactions attached to its inputs", async () => {
// Sources:
// test/built-ins/Promise/allSettled/resolved-sequence.js
// test/built-ins/Promise/allSettled/resolved-sequence-extra-ticks.js
// test/built-ins/Promise/allSettled/resolved-sequence-mixed.js
// test/built-ins/Promise/allSettled/resolved-sequence-with-rejections.js
expect(
await value(`
const sequence = [1]
const input = Promise.resolve(1)
const aggregate = Promise.allSettled([input])
aggregate.then(() => sequence.push(4))
input.then(() => sequence.push(3)).then(() => sequence.push(5))
sequence.push(2)
await aggregate
await Promise.resolve()
return sequence
`),
).toEqual([1, 2, 3, 4, 5])
})
test.failing("Promise.race settles in a reaction after its winning input", async () => {
// Sources:
// test/built-ins/Promise/race/S25.4.4.3_A6.1_T1.js
// test/built-ins/Promise/race/resolved-sequence-extra-ticks.js
expect(
await value(`
const sequence = [1]
const race = Promise.race([1])
race.then(() => sequence.push(4))
Promise.resolve().then(() => sequence.push(3)).then(() => sequence.push(5))
sequence.push(2)
await race
await Promise.resolve()
return sequence
`),
).toEqual([1, 2, 3, 4, 5])
})
test.failing("then reactions route and propagate fulfillment and rejection", async () => {
// Sources:
// test/built-ins/Promise/prototype/then/prfm-fulfilled.js
// test/built-ins/Promise/prototype/then/prfm-rejected.js
// test/built-ins/Promise/prototype/then/rxn-handler-identity.js
// test/built-ins/Promise/prototype/then/rxn-handler-thrower.js
// test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-normal.js
// test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-abrupt.js
// test/built-ins/Promise/prototype/then/rxn-handler-rejected-return-normal.js
// test/built-ins/Promise/prototype/then/rxn-handler-rejected-return-abrupt.js
expect(
await value(`
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
return await Promise.all([
observe(Promise.resolve(1).then((value) => value + 1)),
observe(Promise.reject(2).then(undefined, (reason) => reason + 1)),
observe(Promise.resolve(3).then(undefined)),
observe(Promise.reject(4).then(undefined)),
observe(Promise.resolve(5).then(() => { throw 6 })),
observe(Promise.reject(7).then(undefined, () => { throw 8 })),
])
`),
).toEqual([
["fulfilled", 2],
["fulfilled", 3],
["fulfilled", 3],
["rejected", 4],
["rejected", 6],
["rejected", 8],
])
})
test.failing("then reactions preserve breadth-first queue order", async () => {
// Source: test/built-ins/Promise/prototype/then/S25.4.4_A1.1_T1.js
expect(
await value(`
const sequence = [1]
const promise = Promise.resolve()
const first = promise.then(() => sequence.push(3)).then(() => sequence.push(5)).then(() => sequence.push(7))
const second = promise.then(() => sequence.push(4)).then(() => sequence.push(6)).then(() => sequence.push(8))
sequence.push(2)
await Promise.all([first, second])
return sequence
`),
).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
})
test.failing("then rejects direct self-resolution for fulfilled and rejected sources", async () => {
// Sources:
// test/built-ins/Promise/prototype/then/resolve-settled-fulfilled-self.js
// test/built-ins/Promise/prototype/then/resolve-settled-rejected-self.js
// test/built-ins/Promise/prototype/then/resolve-pending-fulfilled-self.js
// test/built-ins/Promise/prototype/then/resolve-pending-rejected-self.js
expect(
await value(`
const observe = async (promise) => {
try { await promise; return "fulfilled" } catch (reason) { return reason.name }
}
let fulfilled
let rejected
fulfilled = Promise.resolve().then(() => fulfilled)
rejected = Promise.reject().then(undefined, () => rejected)
return await Promise.all([observe(fulfilled), observe(rejected)])
`),
).toEqual(["TypeError", "TypeError"])
})
test.failing("catch delegates rejection handling and preserves fulfillment", async () => {
// Sources:
// test/built-ins/Promise/prototype/catch/S25.4.5.1_A2.1_T1.js
// test/built-ins/Promise/prototype/catch/S25.4.5.1_A3.1_T1.js
// test/built-ins/Promise/prototype/catch/S25.4.5.1_A3.1_T2.js
expect(
await value(`
return [
await Promise.resolve(1).catch(() => 2),
await Promise.reject(3).catch((reason) => reason + 1),
]
`),
).toEqual([1, 4])
})
test.failing("finally preserves or replaces the original settlement", async () => {
// Sources:
// test/built-ins/Promise/prototype/finally/resolution-value-no-override.js
// test/built-ins/Promise/prototype/finally/rejection-reason-no-fulfill.js
// test/built-ins/Promise/prototype/finally/rejection-reason-override-with-throw.js
expect(
await value(`
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
return await Promise.all([
observe(Promise.resolve(1).finally(() => 2)),
observe(Promise.reject(3).finally(() => 4)),
observe(Promise.reject(5).finally(() => { throw 6 })),
])
`),
).toEqual([
["fulfilled", 1],
["rejected", 3],
["rejected", 6],
])
})
test.failing("await always resumes in a later reaction and interleaves async functions", async () => {
// Sources:
// test/language/expressions/await/async-await-interleaved.js
// test/language/expressions/await/await-non-promise.js
expect(
await value(`
const sequence = []
const first = async () => { sequence.push("first:1"); await 0; sequence.push("first:2") }
const second = async () => { sequence.push("second:1"); await 0; sequence.push("second:2") }
await Promise.all([first(), second()])
return sequence
`),
).toEqual(["first:1", "second:1", "first:2", "second:2"])
})
test.failing("an async function rejects when it resolves with its own promise", async () => {
// Adapted from the self-resolution requirement represented by:
// test/built-ins/Promise/resolve-self.js
// test/built-ins/Promise/resolve/S25.4.4.5_A4.1_T1.js
expect(
await value(`
let promise
const run = async () => {
await Promise.resolve()
return promise
}
promise = run()
try {
await promise
return "fulfilled"
} catch (error) {
return error.name
}
`),
).toBe("TypeError")
})
test.failing("Promise.resolve recursively assimilates callable thenables", async () => {
// Source: test/built-ins/Promise/resolve/resolve-thenable.js
expect(
await value(`
const value = { id: 1 }
const nested = { then: (resolve) => resolve(value) }
const thenable = { then: (resolve) => resolve(nested) }
return (await Promise.resolve(thenable)) === value
`),
).toBe(true)
})
test.failing("Promise combinators assimilate callable thenable inputs", async () => {
// Sources:
// test/built-ins/Promise/all/reject-immed.js
// test/built-ins/Promise/all/reject-ignored-immed.js
// test/built-ins/Promise/allSettled/reject-ignored-immed.js
// test/built-ins/Promise/race/resolve-thenable.js
expect(
await value(`
const fulfills = { then: (resolve) => resolve(1) }
const rejects = { then: (_, reject) => reject(2) }
const resolvesFirst = { then: (resolve, reject) => { resolve(3); reject(4) } }
const observe = async (promise) => {
try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] }
}
return [
await observe(Promise.all([fulfills, rejects])),
await Promise.allSettled([fulfills, resolvesFirst]),
await observe(Promise.race([rejects])),
]
`),
).toEqual([
["rejected", 2],
[
{ status: "fulfilled", value: 1 },
{ status: "fulfilled", value: 3 },
],
["rejected", 2],
])
})
test.failing("await assimilates callable thenables", async () => {
// Source: test/language/expressions/await/await-awaits-thenables.js
expect(
await value(`
const thenable = { then: (resolve) => resolve(42) }
return await thenable
`),
).toBe(42)
})
test.failing("await rejects when a callable thenable throws", async () => {
// Source: test/language/expressions/await/await-awaits-thenables-that-throw.js
expect(
await value(`
const error = { id: 1 }
const thenable = { then: () => { throw error } }
try {
await thenable
return false
} catch (caught) {
return caught === error
}
`),
).toBe(true)
})
})
+454 -52
View File
@@ -48,6 +48,13 @@ const failingTool = Tool.make({
run: () => Effect.fail(toolError("Lookup refused")),
})
const interruptedTool = Tool.make({
description: "Interrupt this call",
input: Schema.Struct({}),
output: Schema.String,
run: () => Effect.interrupt,
})
const completedTool = (trace: Trace) =>
Tool.make({
description: "Return the number of completed sleepy calls",
@@ -56,6 +63,25 @@ const completedTool = (trace: Trace) =>
run: () => Effect.succeed(trace.completed),
})
/** Never settles, and holds interruption cleanup for `cleanupMs` so completion cleanup can outlast a timeout. */
const stubbornTool = (trace: Trace) =>
Tool.make({
description: "Never settle; clean up slowly when interrupted",
input: Schema.Struct({ cleanupMs: Schema.Number }),
output: Schema.Number,
run: ({ cleanupMs }) =>
Effect.never.pipe(
Effect.onInterrupt(() =>
Effect.andThen(
Effect.sleep(cleanupMs),
Effect.sync(() => {
trace.interrupted += 1
}),
),
),
),
})
const run = (
code: string,
options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {},
@@ -63,7 +89,15 @@ const run = (
const trace = options.trace ?? makeTrace()
return Effect.runPromise(
CodeMode.execute({
tools: { host: { sleepy: sleepyTool(trace), fail: failingTool, completed: completedTool(trace) } },
tools: {
host: {
sleepy: sleepyTool(trace),
fail: failingTool,
interrupt: interruptedTool,
completed: completedTool(trace),
stubborn: stubbornTool(trace),
},
},
code,
...(options.limits ? { limits: options.limits } : {}),
}),
@@ -174,8 +208,7 @@ describe("first-class promise values", () => {
})
test("an awaited failure is catchable exactly like a synchronous throw", async () => {
expect(
await value(`
const result = await run(`
const p = tools.host.fail({})
try {
await p
@@ -183,57 +216,195 @@ describe("first-class promise values", () => {
} catch (e) {
return e.message
}
`),
).toBe("Lookup refused")
`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("Lookup refused")
expect(result.warnings).toBeUndefined()
})
test("a fire-and-forget call completes before the execution ends", async () => {
test("a fire-and-forget call is interrupted when the program returns", async () => {
const trace = makeTrace()
const result = await value(
const result = await run(
`
tools.host.sleepy({ id: 1, ms: 30 })
return "done"
`,
{ trace },
)
expect(result).toBe("done")
expect(trace.completed).toBe(1)
expect(trace.interrupted).toBe(0)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toBeUndefined()
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("a never-awaited failing call surfaces as an unhandled-rejection diagnostic", async () => {
const diagnostic = await error(`
test("a never-awaited failing call preserves the result and reports the rejection", async () => {
const result = await run(`
tools.host.fail({})
return "done"
`)
expect(diagnostic.kind).toBe("ToolFailure")
expect(diagnostic.message).toContain("Unhandled rejection from an un-awaited promise")
expect(diagnostic.message).toContain("Lookup refused")
expect(diagnostic.suggestions?.join(" ")).toContain("Await promises")
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toStrictEqual([
{ kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" },
])
expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result)
})
test("a never-awaited failing async function surfaces as an unhandled promise rejection", async () => {
const diagnostic = await error(`
test("a never-awaited failing async function is reported with a successful result", async () => {
const result = await run(`
const fail = async () => { throw new Error("boom") }
fail()
return "done"
`)
expect(diagnostic.kind).toBe("ExecutionFailure")
expect(diagnostic.message).toContain("Unhandled rejection from an un-awaited promise")
expect(diagnostic.message).toContain("boom")
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toStrictEqual([
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: boom" },
])
})
test("drains promises started by an async function after an await", async () => {
const diagnostic = await error(`
const run = async () => {
await tools.host.sleepy({ id: 1 })
tools.host.fail({})
}
run()
test("output truncation bounds warning diagnostics with an in-band marker", async () => {
const result = await run(
`
for (let i = 0; i < 100; i += 1) Promise.reject(new Error("x".repeat(1_000)))
return "done"
`,
{ limits: { maxOutputBytes: 64 } },
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.truncated).toBe(true)
expect(result.warnings).toStrictEqual([
{ kind: "Truncated", message: "100 additional warnings omitted by the output limit." },
])
})
test("a budget-consuming value does not starve warnings", async () => {
const result = await run(
`
Promise.reject(new Error("boom"))
return "x".repeat(500)
`,
{ limits: { maxOutputBytes: 128 } },
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.truncated).toBe(true)
expect(typeof result.value).toBe("string")
expect(result.warnings).toStrictEqual([
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: boom" },
])
})
test("an un-awaited async function's pending chain is interrupted at the return", async () => {
const trace = makeTrace()
const result = await run(
`
const run = async () => {
await tools.host.sleepy({ id: 1, ms: 60000 })
tools.host.fail({})
}
run()
return "done"
`,
{ trace },
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toBeUndefined()
expect(trace.starts).toEqual([1])
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("reports every unhandled rejection in promise creation order", async () => {
const result = await run(`
Promise.reject(new Error("first"))
tools.host.fail({})
Promise.reject(new Error("third"))
return "done"
`)
expect(diagnostic.kind).toBe("ToolFailure")
expect(diagnostic.message).toContain("Lookup refused")
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.warnings).toStrictEqual([
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: first" },
{ kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" },
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: third" },
])
})
test("orders an async function rejection before promises created inside its body", async () => {
const result = await run(`
const outer = async () => {
Promise.reject(new Error("inner"))
throw new Error("outer")
}
outer()
return "done"
`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.warnings).toStrictEqual([
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: outer" },
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: inner" },
])
})
test("un-awaited interruptions settle without becoming rejections", async () => {
const result = await run(`
tools.host.interrupt({})
Promise.all([tools.host.interrupt({})])
return "done"
`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toBeUndefined()
})
test("a fatal program error cancels outstanding work without reporting unhandled rejections", async () => {
const trace = makeTrace()
const result = await run(
`
tools.host.sleepy({ id: 1, ms: 1_000 })
throw new Error("boom")
`,
{ trace },
)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.error.message).toBe("Uncaught: boom")
expect("warnings" in result).toBe(false)
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("async-function promises remain owned by the execution after the function returns", async () => {
const trace = makeTrace()
expect(
await value(
`
const launch = async () => {
tools.host.sleepy({ id: 1, ms: 60000 })
Promise.all([tools.host.sleepy({ id: 2, ms: 60000 })])
return "returned"
}
return await launch()
`,
{ trace },
),
).toBe("returned")
// Both calls outlive launch() itself - they belong to the execution, not the function -
// and are interrupted only when the whole program returns.
expect(trace.starts).toEqual([1, 2])
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(2)
})
})
@@ -251,6 +422,22 @@ describe("promises at data boundaries", () => {
expect(diagnostic.message).toContain("un-awaited Promise")
})
test("invalid returned data cancels pending work", async () => {
const trace = makeTrace()
const result = await run(
`
const pending = tools.host.sleepy({ id: 1, ms: 60_000 })
return { pending }
`,
{ trace, limits: { timeoutMs: 100 } },
)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.error.kind).toBe("InvalidDataValue")
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("passing an un-awaited promise as a tool argument is a clear diagnostic", async () => {
const diagnostic = await error(`return await tools.host.sleepy({ id: tools.host.sleepy({ id: 1 }) })`)
expect(diagnostic.kind).toBe("InvalidDataValue")
@@ -270,6 +457,59 @@ describe("promises at data boundaries", () => {
})
describe("Promise.all over arbitrary arrays", () => {
test("combinators return promises that can be assigned and awaited later", async () => {
expect(
await value(`
const all = Promise.all([Promise.resolve(1)])
const settled = Promise.allSettled([Promise.reject("no")])
const race = Promise.race([Promise.resolve(2)])
const promises = [all instanceof Promise, settled instanceof Promise, race instanceof Promise]
return [promises, await all, await settled, await race]
`),
).toEqual([[true, true, true], [1], [{ status: "rejected", reason: "no" }], 2])
})
test("separately-created aggregate batches overlap before either is awaited", async () => {
const trace = makeTrace()
expect(
await value(
`
const first = Promise.all([tools.host.sleepy({ id: 1, ms: 40 })])
const second = Promise.all([tools.host.sleepy({ id: 2, ms: 40 })])
return [await first, await second]
`,
{ trace },
),
).toEqual([[1], [2]])
expect(trace.starts).toEqual([1, 2])
expect(trace.maxActive).toBeGreaterThan(1)
})
test("an aggregate created before a try block rejects at its later await", async () => {
expect(
await value(`
const aggregate = Promise.all([tools.host.fail({})])
try {
await aggregate
return "no"
} catch (error) {
return error.message
}
`),
).toBe("Lookup refused")
})
test("awaiting an aggregate repeatedly does not rerun its members", async () => {
const result = await run(`
const aggregate = Promise.all([tools.host.sleepy({ id: 7 })])
return [await aggregate, await aggregate]
`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toEqual([[7], [7]])
expect(result.toolCalls).toStrictEqual([{ name: "host.sleepy" }])
})
test("mixes promises and plain values, preserving order", async () => {
expect(
await value(`
@@ -340,16 +580,18 @@ describe("Promise.all over arbitrary arrays", () => {
})
test("rejects with the first failure, catchable in-program", async () => {
expect(
await value(`
const result = await run(`
try {
await Promise.all([tools.host.sleepy({ id: 1 }), tools.host.fail({})])
return "no"
} catch (e) {
return e.message
}
`),
).toBe("Lookup refused")
`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("Lookup refused")
expect(result.warnings).toBeUndefined()
})
test("rejects before an earlier slow promise fulfills", async () => {
@@ -370,10 +612,55 @@ describe("Promise.all over arbitrary arrays", () => {
{ trace },
),
).toBe(0)
// The surviving member is observed (Promise.all handled it), so completion interrupts
// it instead of waiting for it.
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("fail-fast does not cancel a sibling the program still holds and awaits", async () => {
const trace = makeTrace()
expect(
await value(
`
const slow = tools.host.sleepy({ id: 1, ms: 40 })
try {
await Promise.all([slow, tools.host.fail({})])
return "no"
} catch {}
return await slow
`,
{ trace },
),
).toBe(1)
expect(trace.completed).toBe(1)
expect(trace.interrupted).toBe(0)
})
test("a slower observed sibling is interrupted at completion after failing fast", async () => {
const trace = makeTrace()
expect(
await value(
`
const failLater = async () => {
await tools.host.sleepy({ id: 1, ms: 40 })
throw new Error("later")
}
const aggregate = Promise.all([Promise.reject(new Error("first")), failLater()])
try {
await aggregate
return "no"
} catch (error) {
return error.message
}
`,
{ trace },
),
).toBe("first")
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("a non-collection argument is a clear error", async () => {
const diagnostic = await error(`return await Promise.all(42)`)
expect(diagnostic.message).toContain("Promise.all expects an array")
@@ -413,50 +700,64 @@ describe("Promise.allSettled", () => {
return settled.filter((s) => s.status === "rejected").length
`)
expect(result.ok).toBe(true)
if (result.ok) expect(result.value).toBe(2)
if (!result.ok) return
expect(result.value).toBe(2)
expect(result.warnings).toBeUndefined()
})
})
describe("Promise.race", () => {
test("first settlement wins and losers are interrupted", async () => {
test("first settlement wins and a direct loser is interrupted at completion", async () => {
const trace = makeTrace()
const result = await value(
`
const fast = tools.host.sleepy({ id: 1, ms: 10 })
const slow = tools.host.sleepy({ id: 2, ms: 5000 })
const slow = tools.host.sleepy({ id: 2, ms: 40 })
return await Promise.race([fast, slow])
`,
{ trace },
)
expect(result).toBe(1)
expect(trace.interrupted).toBe(1)
// The loser is observed (the race handled it), so the execution does not wait for it.
expect(trace.completed).toBe(1)
expect(trace.interrupted).toBe(1)
})
test("awaiting an interrupted loser afterwards is a catchable program failure", async () => {
test("a direct loser remains awaitable after the race settles", async () => {
expect(
await value(`
const fast = tools.host.sleepy({ id: 1, ms: 10 })
const slow = tools.host.sleepy({ id: 2, ms: 5000 })
const slow = tools.host.sleepy({ id: 2, ms: 40 })
const winner = await Promise.race([fast, slow])
try {
await slow
return "no"
} catch (e) {
return { winner, caught: e.message }
}
return { winner, loser: await slow }
`),
).toEqual({
winner: 1,
caught: "This tool call was interrupted because another value settled a Promise.race first.",
})
).toEqual({ winner: 1, loser: 2 })
})
test("a nested aggregate loser and its members are interrupted at completion", async () => {
const trace = makeTrace()
expect(
await value(
`
const nested = Promise.all([
tools.host.sleepy({ id: 1, ms: 40 }),
tools.host.sleepy({ id: 2, ms: 40 }),
])
return await Promise.race(["immediate", nested])
`,
{ trace },
),
).toBe("immediate")
// The nested aggregate and its members are all observed, so nothing waits for them.
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(2)
})
test("a rejection can win the race", async () => {
expect(
await value(`
try {
await Promise.race([tools.host.fail({}), tools.host.sleepy({ id: 1, ms: 5000 })])
await Promise.race([tools.host.fail({}), tools.host.sleepy({ id: 1, ms: 40 })])
return "no"
} catch (e) {
return e.message
@@ -468,11 +769,20 @@ describe("Promise.race", () => {
test("a plain value wins over pending promises", async () => {
const trace = makeTrace()
expect(
await value(`return await Promise.race([tools.host.sleepy({ id: 1, ms: 5000 }), "immediate"])`, { trace }),
await value(`return await Promise.race([tools.host.sleepy({ id: 1, ms: 40 }), "immediate"])`, { trace }),
).toBe("immediate")
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("a rejected race loser is observed by the aggregate", async () => {
const result = await run(`return await Promise.race(["winner", tools.host.fail({})])`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("winner")
expect(result.warnings).toBeUndefined()
})
test("an empty race is a clear error instead of hanging", async () => {
const diagnostic = await error(`return await Promise.race([])`)
expect(diagnostic.message).toContain("never settle")
@@ -484,6 +794,9 @@ describe("Promise.resolve / Promise.reject", () => {
expect(await value(`return await Promise.resolve(42)`)).toBe(42)
expect(await value(`return await Promise.resolve(Promise.resolve("nested"))`)).toBe("nested")
expect(await value(`return await Promise.resolve(tools.host.sleepy({ id: 3 }))`)).toBe(3)
expect(await value(`const promise = Promise.resolve(1); return [promise].includes(Promise.resolve(promise))`)).toBe(
true,
)
})
test("reject produces a promise whose await throws the reason", async () => {
@@ -498,6 +811,34 @@ describe("Promise.resolve / Promise.reject", () => {
`),
).toBe("nope")
})
test("a rejection observed after settlement is handled", async () => {
expect(
await value(`
const rejected = Promise.reject(new Error("handled"))
await tools.host.sleepy({ id: 1 })
try {
await rejected
return "no"
} catch (error) {
return error.message
}
`),
).toBe("handled")
})
test("an abandoned rejected promise is reported as unhandled", async () => {
const result = await run(`
Promise.reject(new Error("abandoned"))
return "done"
`)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toStrictEqual([
{ kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Uncaught: abandoned" },
])
})
})
describe("timeout interruption of forked calls", () => {
@@ -531,6 +872,67 @@ describe("timeout interruption of forked calls", () => {
expect(result.error.kind).toBe("TimeoutExceeded")
expect(trace.interrupted).toBe(2)
})
test("a non-settling race loser cannot hold the execution to the timeout", async () => {
const trace = makeTrace()
const result = await run(`return await Promise.race(["winner", tools.host.sleepy({ id: 1, ms: 60000 })])`, {
trace,
limits: { timeoutMs: 100 },
})
// Completion interrupts the observed loser immediately; the race result survives.
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("winner")
expect(result.warnings).toBeUndefined()
expect(trace.starts).toEqual([1])
expect(trace.completed).toBe(0)
expect(trace.interrupted).toBe(1)
})
test("a timeout during completion cleanup keeps the computed value and warns", async () => {
const trace = makeTrace()
const result = await run(
`
tools.host.stubborn({ cleanupMs: 400 })
return "done"
`,
{ trace, limits: { timeoutMs: 100 } },
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toStrictEqual([
{
kind: "TimeoutExceeded",
message:
"The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.",
},
])
expect(trace.interrupted).toBe(1)
expect(trace.completed).toBe(0)
})
test("a timeout during completion cleanup reports the timeout warning before settled rejections", async () => {
const result = await run(
`
tools.host.fail({})
tools.host.stubborn({ cleanupMs: 400 })
return "done"
`,
{ limits: { timeoutMs: 100 } },
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.value).toBe("done")
expect(result.warnings).toStrictEqual([
{
kind: "TimeoutExceeded",
message:
"The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.",
},
{ kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" },
])
})
})
describe("unsupported promise surface", () => {
-77
View File
@@ -1,77 +0,0 @@
# Test262 Array Coverage
The Array tests adapt Test262 at revision `250f204f23a9249ff204be2baec29600faae7b75`. They cover CodeMode's 35
exposed instance methods and three static methods using actual arrays, accepted argument types, deterministic behavior,
and CodeMode's materialized collection conventions. Each executable case names its exact upstream source path.
`LICENSE.test262` contains the upstream BSD terms.
This is coverage of CodeMode's bounded Array surface, not a claim of ECMAScript or Test262 conformance. One upstream
file may contain both adapted and inapplicable assertions, so a cited source means only that the represented assertions
were adapted.
## Inventory
The 38 relevant upstream API directories contain 2,837 files. The executable suite adapts assertions from 83 distinct
sources.
| API | Upstream files | Adapted sources |
| ------------------------------- | -------------: | --------------: |
| `Array.prototype.map` | 216 | 3 |
| `Array.prototype.filter` | 242 | 3 |
| `Array.prototype.find` | 23 | 4 |
| `Array.prototype.findIndex` | 23 | 3 |
| `Array.prototype.findLast` | 24 | 3 |
| `Array.prototype.findLastIndex` | 24 | 3 |
| `Array.prototype.some` | 219 | 2 |
| `Array.prototype.every` | 218 | 2 |
| `Array.prototype.includes` | 30 | 2 |
| `Array.prototype.join` | 23 | 2 |
| `Array.prototype.reduce` | 260 | 3 |
| `Array.prototype.reduceRight` | 260 | 3 |
| `Array.prototype.flatMap` | 24 | 2 |
| `Array.prototype.forEach` | 190 | 2 |
| `Array.prototype.sort` | 54 | 3 |
| `Array.prototype.toSorted` | 21 | 4 |
| `Array.prototype.slice` | 71 | 1 |
| `Array.prototype.concat` | 69 | 3 |
| `Array.prototype.indexOf` | 201 | 2 |
| `Array.prototype.lastIndexOf` | 198 | 2 |
| `Array.prototype.at` | 13 | 3 |
| `Array.prototype.flat` | 19 | 2 |
| `Array.prototype.reverse` | 18 | 1 |
| `Array.prototype.toReversed` | 17 | 2 |
| `Array.prototype.with` | 21 | 2 |
| `Array.prototype.push` | 24 | 1 |
| `Array.prototype.pop` | 23 | 1 |
| `Array.prototype.shift` | 20 | 1 |
| `Array.prototype.unshift` | 22 | 1 |
| `Array.prototype.splice` | 81 | 3 |
| `Array.prototype.fill` | 22 | 3 |
| `Array.prototype.copyWithin` | 39 | 2 |
| `Array.prototype.keys` | 12 | 1 |
| `Array.prototype.values` | 12 | 1 |
| `Array.prototype.entries` | 12 | 1 |
| `Array.from` | 47 | 3 |
| `Array.isArray` | 29 | 2 |
| `Array.of` | 16 | 1 |
## Exclusions
Assertions are not adapted when they test behavior outside CodeMode's documented Array surface:
- Function metadata, property descriptors, constructibility, prototype mutation, species constructors, or cross-realm
identity.
- Generic receivers, detached methods, `.call`, `.apply`, boxed values, custom coercion objects, Symbols, BigInts,
proxies, accessors, frozen arrays, typed arrays, or ArrayBuffers.
- `Array.from` mappers, custom iterables, constructor substitution, and iterator-closing behavior.
- Native iterator identity, `.next()`, completion records, or live iterator mutation. CodeMode deliberately materializes
`keys`, `values`, and `entries` as arrays.
- Sparse-array assertions that depend on literal elisions or inherited indexed properties. CodeMode's confined data
model does not preserve those prototype and hole semantics at every boundary.
- Argument coercions outside the accepted schema-like surface. Numeric positions must be numbers and `join` separators
must be strings.
- Exact native error brands where CodeMode exposes a safe runtime error instead.
- Async/effectful callbacks, circular-data rejection, sandbox-value identity, diagnostics, and host-boundary behavior.
Those remain covered by CodeMode-specific tests.
Handwritten tests remain where they specify CodeMode behavior rather than ordinary ECMAScript Array semantics.
-69
View File
@@ -1,69 +0,0 @@
# Test262 String Coverage
The String tests adapt Test262 at revision `250f204f23a9249ff204be2baec29600faae7b75`. They cover CodeMode's 32
exposed instance methods and two static methods using primitive receivers, accepted argument types, and deterministic
behavior. Each executable case names its exact upstream source path. `LICENSE.test262` contains the upstream BSD terms.
This is coverage of CodeMode's bounded String surface, not a claim of ECMAScript or Test262 conformance. One upstream
file may contain both adapted and inapplicable assertions, so a cited source means only that the represented assertions
were adapted.
## Inventory
The relevant upstream directories contain 1,048 files: 1,009 core built-in files, 29 Annex B files for exposed methods,
and 10 Intl `localeCompare` files. The executable suite adapts assertions from 298 distinct sources.
| API | Upstream files | Adapted sources |
| --- | ---: | ---: |
| `String.fromCharCode` | 17 | 6 |
| `String.fromCodePoint` | 11 | 4 |
| `String.prototype.at` | 11 | 5 |
| `String.prototype.charAt` | 30 | 9 |
| `String.prototype.charCodeAt` | 25 | 4 |
| `String.prototype.codePointAt` | 16 | 6 |
| `String.prototype.concat` | 22 | 1 |
| `String.prototype.endsWith` | 27 | 13 |
| `String.prototype.includes` | 27 | 12 |
| `String.prototype.indexOf` | 47 | 8 |
| `String.prototype.lastIndexOf` | 25 | 1 |
| `String.prototype.localeCompare` | 23 | 1 |
| `String.prototype.match` | 52 | 9 |
| `String.prototype.matchAll` | 26 | 1 |
| `String.prototype.normalize` | 14 | 3 |
| `String.prototype.padEnd` | 13 | 4 |
| `String.prototype.padStart` | 13 | 4 |
| `String.prototype.repeat` | 16 | 4 |
| `String.prototype.replace` | 56 | 16 |
| `String.prototype.replaceAll` | 46 | 12 |
| `String.prototype.search` | 44 | 10 |
| `String.prototype.slice` | 38 | 11 |
| `String.prototype.split` | 121 | 50 |
| `String.prototype.startsWith` | 21 | 7 |
| `String.prototype.substr` | 15 | 6 |
| `String.prototype.substring` | 46 | 12 |
| `String.prototype.toLowerCase` | 30 | 5 |
| `String.prototype.toString` | 7 | 1 |
| `String.prototype.toUpperCase` | 26 | 3 |
| `String.prototype.trim` | 129 | 66 |
| `String.prototype.trimEnd` | 23 | 2 |
| `String.prototype.trimLeft` | 4 | 0 |
| `String.prototype.trimRight` | 4 | 0 |
| `String.prototype.trimStart` | 23 | 2 |
## Exclusions
Assertions are not adapted when they test behavior outside CodeMode's documented String surface:
- Function metadata, property descriptors, constructibility, prototype mutation, or cross-realm identity.
- The `trimLeft`/`trimRight` Test262 files assert prototype function identity, which CodeMode does not expose. Their
supported call behavior remains covered by CodeMode-specific tests.
- Boxed strings, generic receivers, custom coercion objects, Symbols, BigInts, or argument types CodeMode rejects.
- Symbol-based RegExp dispatch, custom matchers, species constructors, or iterator protocol details. CodeMode materializes
`matchAll` results instead of exposing iterators.
- Locale selection and options. CodeMode deliberately uses the host default locale and ignores those arguments.
- Test262 harness behavior or setup syntax unavailable in the confined interpreter.
- Function-replacer behavior that is covered by CodeMode-specific tests for sequential callbacks, async tool calls,
result coercion, diagnostics, and sandbox boundaries.
- Assertions requiring an exact native error type when CodeMode deliberately exposes only its safe runtime error.
Handwritten tests remain where they specify CodeMode behavior rather than ordinary ECMAScript String semantics.
+29 -19
View File
@@ -119,6 +119,11 @@ export class Directory extends Schema.Class<Directory>("Config.Directory")({
path: AbsolutePath,
}) {}
export class File extends Schema.Class<File>("Config.File")({
type: Schema.Literal("file"),
path: AbsolutePath,
}) {}
export class AgentsDirectory extends Schema.Class<AgentsDirectory>("Config.AgentsDirectory")({
type: Schema.Literal("agents"),
path: AbsolutePath,
@@ -129,7 +134,7 @@ export class ClaudeDirectory extends Schema.Class<ClaudeDirectory>("Config.Claud
path: AbsolutePath,
}) {}
export type Entry = Document | Directory | AgentsDirectory | ClaudeDirectory
export type Entry = Document | Directory | File | AgentsDirectory | ClaudeDirectory
export function latest<K extends keyof Info>(entries: readonly Entry[], key: K): Info[K] | undefined {
return entries
@@ -138,7 +143,7 @@ export function latest<K extends keyof Info>(entries: readonly Entry[], key: K):
}
export interface Interface {
/** Returns location config documents and supplemental directories from lowest to highest priority. */
/** Returns location config documents and discovery sources from lowest to highest priority. */
readonly entries: () => Effect.Effect<Entry[]>
}
@@ -227,31 +232,36 @@ const layer = Layer.effect(
const directPaths = discovered
.filter((item) => ![".agents", ".claude", ".opencode"].includes(path.basename(item)))
.toReversed()
const direct = yield* Effect.forEach(directPaths, loadFile).pipe(
const direct = yield* Effect.forEach(directPaths, (filepath) =>
loadFile(filepath).pipe(
Effect.map((config) => [
...(config ? [config] : []),
new File({ type: "file", path: AbsolutePath.make(filepath) }),
]),
),
).pipe(
Effect.orDie,
Effect.map((configs) => configs.filter((config): config is Document => config !== undefined)),
Effect.map((entries) => entries.flat()),
)
const supplementary = yield* Effect.forEach(directories, loadDirectory).pipe(Effect.orDie)
return {
entries: [...claude, ...agents, ...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()],
directories: [...directories, ...claude.map((entry) => entry.path), ...agents.map((entry) => entry.path)],
files: directPaths,
}
return [...claude, ...agents, ...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()]
})
const initial = yield* discover()
let configs = initial.entries
let configs = initial
const updates = yield* PubSub.unbounded<Watcher.Update>()
const subscriptions = new Map<string, Effect.Effect<unknown>>()
const targets = (snapshot: typeof initial) => [
...snapshot.directories.map((path) => ({ path, type: "directory" as const })),
...snapshot.files
.filter((file) => !snapshot.directories.some((directory) => FSUtil.contains(directory, file)))
.map((path) => ({ path, type: "file" as const })),
]
const reconcile = Effect.fn("Config.reconcileWatches")(function* (snapshot: typeof initial) {
const next = new Map(targets(snapshot).map((target) => [JSON.stringify(target), target]))
const reconcile = Effect.fn("Config.reconcileWatches")(function* (entries: readonly Entry[]) {
const directories = entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : []))
const files = entries.flatMap((entry) => (entry.type === "file" ? [entry.path] : []))
const targets = [
...directories.map((path) => ({ path, type: "directory" as const })),
...files
.filter((file) => !directories.some((directory) => FSUtil.contains(directory, file)))
.map((path) => ({ path, type: "file" as const })),
]
const next = new Map(targets.map((target) => [JSON.stringify(target), target]))
for (const [key, stop] of subscriptions) {
if (next.has(key)) continue
yield* stop
@@ -272,7 +282,7 @@ const layer = Layer.effect(
Stream.runForEach((update) =>
Effect.gen(function* () {
const next = yield* discover()
configs = next.entries
configs = next
yield* reconcile(next)
yield* events.publish(ConfigSchema.Event.Updated, {})
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to reload config", { path: update.path, cause }))),
+1 -26
View File
@@ -15,7 +15,6 @@ import { PermissionV2 } from "../../permission"
import type { LocationMutation } from "../../location-mutation"
import type { ReadTool } from "../../tool/read"
import type { EditTool } from "../../tool/edit"
import { AgentPlugin } from "../../plugin/agent"
const legacySources = [
{ pattern: "{agent,agents}/**/*.md", primary: false },
@@ -77,31 +76,7 @@ export const Plugin = define({
const configuredDefault = Config.latest(loaded.documents, "default_agent")
if (configuredDefault !== undefined) draft.default(AgentV2.ID.make(configuredDefault))
for (const current of draft.list()) {
draft.update(current.id, (agent) => {
const defaults = AgentV2.Info.empty(AgentV2.ID.make(current.id)).permissions
const hasDefaults = defaults.every((rule, index) => {
const existing = agent.permissions[index]
return (
existing?.action === rule.action &&
existing.resource === rule.resource &&
existing.effect === rule.effect
)
})
const initial = hasDefaults ? defaults.length : 0
const hasBuiltInDefaults = hasDefaults && AgentPlugin.defaultPermissions.every((rule, index) => {
const existing = agent.permissions[initial + index]
return (
existing?.action === rule.action &&
existing.resource === rule.resource &&
existing.effect === rule.effect
)
})
agent.permissions.splice(
hasBuiltInDefaults ? initial + AgentPlugin.defaultPermissions.length : initial,
0,
...permissions,
)
})
draft.update(current.id, (agent) => agent.permissions.push(...permissions))
}
for (const document of loaded.documents) {
+25 -23
View File
@@ -16,6 +16,9 @@ export type Info = typeof Info.Type
export const Field = Form.Field
export type Field = Form.Field
export const Fields = Form.Fields
export type Fields = Form.Fields
export const When = Form.When
export type When = Form.When
@@ -64,9 +67,7 @@ export class InvalidFormError extends Schema.TaggedErrorClass<InvalidFormError>(
message: Schema.String,
}) {}
export type CreateInput =
| (Omit<Form.FormInfo, "id"> & { readonly id?: ID })
| (Omit<Form.UrlInfo, "id"> & { readonly id?: ID })
export type CreateInput = Omit<Form.Info, "id"> & { readonly id?: ID }
export interface ReplyInput {
readonly id: ID
@@ -74,7 +75,7 @@ export interface ReplyInput {
}
export interface ListInput {
readonly sessionID?: Form.FormInfo["sessionID"]
readonly sessionID?: Form.Info["sessionID"]
}
export interface Interface {
@@ -125,20 +126,15 @@ export const layer = Layer.effect(
const id = input.id ?? ID.create()
const existing = yield* Cache.getSuccess(forms, id)
if (Option.isSome(existing)) return yield* new AlreadyExistsError({ id })
if (input.mode === "form") {
const invalid = validateFields(input.fields)
if (invalid) return yield* new InvalidFormError({ message: invalid })
}
const base = {
const invalid = validateFields(input.fields)
if (invalid) return yield* new InvalidFormError({ message: invalid })
const form: Info = {
id,
sessionID: input.sessionID,
title: input.title,
...(input.metadata === undefined ? {} : { metadata: input.metadata }),
fields: input.fields,
}
const form: Info =
input.mode === "form"
? { ...base, mode: "form", fields: input.fields }
: { ...base, mode: "url", url: input.url }
const entry: Entry = {
form,
state: { status: "pending" },
@@ -228,16 +224,16 @@ export const locationLayer = layer
export const node = makeLocationNode({ service: Service, layer, deps: [EventV2.node] })
function validateAnswer(form: Info, answer: Answer) {
if (form.mode === "url") {
if (Object.keys(answer).length === 0) return
return "URL forms must be answered with an empty answer"
}
const fields = new Map(form.fields.map((field) => [field.key, field]))
const fields = new Map(form.fields.map((field) => [field.key, field] as const))
for (const key of Object.keys(answer)) {
if (!fields.has(key)) return `Unknown form field: ${key}`
}
for (const field of form.fields) {
const value = answer[field.key]
if (field.type === "external") {
if (value !== true) return `External form field must be acknowledged: ${field.key}`
continue
}
const active = isActive(field, answer)
if (value === undefined) {
if (field.required && active) return `Missing required form field: ${field.key}`
@@ -249,7 +245,9 @@ function validateAnswer(form: Info, answer: Answer) {
}
}
function isActive(field: Form.Field, answer: Answer) {
type InputField = Exclude<Form.Field, Form.ExternalField>
function isActive(field: InputField, answer: Answer) {
if (!field.when) return true
return field.when.every((when) => matches(when, answer[when.key]))
}
@@ -267,9 +265,13 @@ function matches(when: Form.When, value: Form.Value | undefined) {
// are closed. Rejecting these at creation surfaces authoring mistakes to the caller instead of
// silently never matching.
function validateFields(fields: ReadonlyArray<Form.Field>) {
const earlier = new Map<string, Form.Field>()
if (fields.length === 0) return "Form must have at least one field"
const earlier = new Map<string, InputField>()
const keys = new Set<string>()
for (const field of fields) {
if (earlier.has(field.key)) return `Duplicate form field key: ${field.key}`
if (keys.has(field.key)) return `Duplicate form field key: ${field.key}`
keys.add(field.key)
if (field.type === "external") continue
for (const when of field.when ?? []) {
const target = earlier.get(when.key)
if (!target) return `Form field condition must reference an earlier field: ${field.key} -> ${when.key}`
@@ -280,7 +282,7 @@ function validateFields(fields: ReadonlyArray<Form.Field>) {
}
}
function validateWhen(when: Form.When, target: Form.Field) {
function validateWhen(when: Form.When, target: InputField) {
if (target.type === "boolean") {
if (typeof when.value !== "boolean") return "Form field condition value must be a boolean"
return
@@ -297,7 +299,7 @@ function validateWhen(when: Form.When, target: Form.Field) {
}
}
function validateField(field: Form.Field, value: Form.Value): string | undefined {
function validateField(field: InputField, value: Form.Value): string | undefined {
if (field.type === "string") {
if (typeof value !== "string") return `Expected string for form field: ${field.key}`
if (field.required && value.length === 0) return `Missing required form field: ${field.key}`
+8 -7
View File
@@ -123,6 +123,7 @@ type ServerEntry = {
// MCP elicitations are Location-scoped, not Session-scoped: the server cannot attribute them to a
// persisted session row, so their forms are owned by this opaque sentinel session identifier.
const GLOBAL_ELICITATION_SESSION_ID = "global"
const URL_ELICITATION_FIELD_KEY = "elicitation"
export interface Interface {
readonly servers: () => Effect.Effect<ServerInfo[]>
@@ -311,8 +312,7 @@ export const layer = Layer.effect(
elicitationID: input.params.elicitationId,
message: input.params.message,
},
mode: "url",
url: input.params.url,
fields: [{ key: URL_ELICITATION_FIELD_KEY, type: "external", url: input.params.url }],
})
.pipe(
Effect.raceFirst(waitForAbort(input.signal)),
@@ -325,15 +325,16 @@ export const layer = Layer.effect(
)
}
const params = input.params
const [field, ...fields] = Object.entries(params.requestedSchema.properties).map(([key, property]) =>
toElicitationField(key, property, params.requestedSchema.required?.includes(key) === true),
)
if (!field) return { action: "accept", content: {} }
return yield* forms
.ask({
sessionID: GLOBAL_ELICITATION_SESSION_ID,
title: `${input.server} is requesting input`,
metadata: { kind: "mcp-elicitation", server: input.server, message: params.message },
mode: "form",
fields: Object.entries(params.requestedSchema.properties).map(([key, property]) =>
toElicitationField(key, property, params.requestedSchema.required?.includes(key) === true),
),
fields: [field, ...fields],
})
.pipe(
Effect.raceFirst(waitForAbort(input.signal)),
@@ -355,7 +356,7 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const formID = urlElicitations.get(input.server + "\u0000" + input.elicitationID)
if (!formID) return
yield* forms.reply({ id: formID, answer: {} }).pipe(Effect.ignore)
yield* forms.reply({ id: formID, answer: { [URL_ELICITATION_FIELD_KEY]: true } }).pipe(Effect.ignore)
}),
} satisfies MCPClient.ElicitationHandler
+25 -30
View File
@@ -13,21 +13,6 @@ import { PermissionV2 } from "../permission"
const SHELL_OUTPUT_GLOB = path.join(Global.Path.data, "shell", "*", "*")
const BUILD_SYSTEM =
"You are an AI coding agent. Help the user accomplish software engineering tasks by inspecting the workspace, making targeted changes, and using tools according to the configured permissions."
const readonlyExternalDirectory: PermissionV2.Ruleset = [
{ action: "external_directory", resource: "*", effect: "ask" },
{ action: "external_directory", resource: SHELL_OUTPUT_GLOB, effect: "allow" },
{ action: "external_directory", resource: path.join(Global.Path.tmp, "*"), effect: "allow" },
]
export const defaultPermissions: PermissionV2.Ruleset = [
...readonlyExternalDirectory.slice(1),
{ action: "question", resource: "*", effect: "deny" },
{ action: "plan_enter", resource: "*", effect: "deny" },
{ action: "plan_exit", resource: "*", effect: "deny" },
{ action: "read", resource: "*", effect: "allow" },
{ action: "read", resource: "*.env", effect: "ask" },
{ action: "read", resource: "*.env.*", effect: "ask" },
{ action: "read", resource: "*.env.example", effect: "allow" },
]
const PROMPT_EXPLORE = `You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
@@ -119,6 +104,24 @@ export const Plugin = define({
effect: Effect.fn(function* (ctx) {
const location = yield* Location.Service
const worktree = location.directory
const whitelistedDirs = [SHELL_OUTPUT_GLOB, path.join(Global.Path.tmp, "*")]
const readonlyExternalDirectory: PermissionV2.Ruleset = [
{ action: "external_directory", resource: "*", effect: "ask" },
...whitelistedDirs.map(
(resource): PermissionV2.Rule => ({ action: "external_directory", resource, effect: "allow" }),
),
]
const defaults: PermissionV2.Ruleset = [
{ action: "*", resource: "*", effect: "allow" },
...readonlyExternalDirectory,
{ action: "question", resource: "*", effect: "deny" },
{ action: "plan_enter", resource: "*", effect: "deny" },
{ action: "plan_exit", resource: "*", effect: "deny" },
{ action: "read", resource: "*", effect: "allow" },
{ action: "read", resource: "*.env", effect: "ask" },
{ action: "read", resource: "*.env.*", effect: "ask" },
{ action: "read", resource: "*.env.example", effect: "allow" },
]
yield* ctx.agent.transform((draft) => {
draft.update(AgentV2.defaultID, (item) => {
@@ -126,7 +129,7 @@ export const Plugin = define({
item.description = "The default agent. Executes tools based on configured permissions."
item.mode = "primary"
item.permissions.push(
...PermissionV2.merge(defaultPermissions, [
...PermissionV2.merge(defaults, [
{ action: "question", resource: "*", effect: "allow" },
{ action: "plan_enter", resource: "*", effect: "allow" },
]),
@@ -138,7 +141,7 @@ export const Plugin = define({
item.description = "Plan mode. Disallows all edit tools."
item.mode = "primary"
item.permissions.push(
...PermissionV2.merge(defaultPermissions, [
...PermissionV2.merge(defaults, [
{ action: "question", resource: "*", effect: "allow" },
{ action: "plan_exit", resource: "*", effect: "allow" },
{ action: "external_directory", resource: path.join(Global.Path.data, "plans", "*"), effect: "allow" },
@@ -158,9 +161,7 @@ export const Plugin = define({
item.description =
"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel."
item.mode = "subagent"
item.permissions.push(
...PermissionV2.merge(defaultPermissions, [{ action: "subagent", resource: "*", effect: "deny" }]),
)
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "subagent", resource: "*", effect: "deny" }]))
})
draft.update(AgentV2.ID.make("explore"), (item) => {
@@ -171,7 +172,7 @@ export const Plugin = define({
item.mode = "subagent"
item.permissions.push(
...PermissionV2.merge(
defaultPermissions,
defaults,
[
{ action: "*", resource: "*", effect: "deny" },
{ action: "grep", resource: "*", effect: "allow" },
@@ -191,9 +192,7 @@ export const Plugin = define({
item.mode = "primary"
item.hidden = true
item.system = PROMPT_COMPACTION
item.permissions.push(
...PermissionV2.merge(defaultPermissions, [{ action: "*", resource: "*", effect: "deny" }]),
)
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }]))
})
draft.update(AgentV2.ID.make("title"), (item) => {
@@ -201,9 +200,7 @@ export const Plugin = define({
item.mode = "primary"
item.hidden = true
item.system = PROMPT_TITLE
item.permissions.push(
...PermissionV2.merge(defaultPermissions, [{ action: "*", resource: "*", effect: "deny" }]),
)
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }]))
})
draft.update(AgentV2.ID.make("summary"), (item) => {
@@ -211,9 +208,7 @@ export const Plugin = define({
item.mode = "primary"
item.hidden = true
item.system = PROMPT_SUMMARY
item.permissions.push(
...PermissionV2.merge(defaultPermissions, [{ action: "*", resource: "*", effect: "deny" }]),
)
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }]))
})
})
}),
-2
View File
@@ -1,7 +1,6 @@
export * as PluginHooks from "./hooks"
import type { AISDKHooks } from "@opencode-ai/plugin/v2/effect/aisdk"
import type { SessionHooks } from "@opencode-ai/plugin/v2/effect/session"
import type { ToolHooks } from "@opencode-ai/plugin/v2/effect/tool"
import { Context, Effect, Layer, Scope } from "effect"
import { makeLocationNode } from "../effect/app-node"
@@ -9,7 +8,6 @@ import { State } from "../state"
export interface Domains {
readonly aisdk: AISDKHooks
readonly session: SessionHooks
readonly tool: ToolHooks
}
-1
View File
@@ -367,7 +367,6 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Int
},
},
session: {
hook: (name, callback) => hooks.register("session", name, callback),
create: (input) =>
runtime.session.create({
id: input?.id,
+25 -4
View File
@@ -1,7 +1,9 @@
export * as PluginPromise from "./promise"
import { Plugin } from "@opencode-ai/plugin/v2/effect"
import type { AnyTool } from "@opencode-ai/plugin/v2/tool"
import { Effect, Scope, Stream } from "effect"
import { Tool } from "../tool/tool"
type HostRegistration = { readonly dispose: Effect.Effect<void> }
type Registration = { readonly dispose: () => Promise<void> }
@@ -108,7 +110,14 @@ export function fromPromise(plugin: PromisePlugin) {
reload: () => run(host.skill.reload()),
},
tool: {
transform: transform(host.tool),
transform: (callback) =>
register(
host.tool.transform((draft) =>
callback({
add: (tool: AnyTool) => draft.add(tool.name, fromPromiseTool(tool), tool.options),
}),
),
),
hook: (name, callback) =>
register(host.tool.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
@@ -118,12 +127,24 @@ export function fromPromise(plugin: PromisePlugin) {
prompt: (input) => run(host.session.prompt(input)),
command: (input) => run(host.session.command(input)),
interrupt: (input) => run(host.session.interrupt(input)),
hook: (name, callback) =>
register(host.session.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
}
yield* Effect.promise(() => Promise.resolve(plugin.setup(context2)))
const cleanup = yield* Effect.promise(() => Promise.resolve(plugin.setup(context2)))
if (!cleanup) return
yield* Effect.addFinalizer(() => Effect.promise(() => Promise.resolve(cleanup())))
}),
})
}
function fromPromiseTool(tool: AnyTool) {
if ("jsonSchema" in tool)
return Tool.make({
...tool,
execute: (input, context) => Effect.promise(() => tool.execute(input, context)),
})
return Tool.make({
...tool,
execute: (input, context) => Effect.promise(() => tool.execute(input, context)),
})
}
+55 -24
View File
@@ -4,10 +4,14 @@ Use this guide as the starting point for work involving OpenCode itself. It
covers the core concepts needed to configure and customize OpenCode, extend it
with plugins, and build integrations with the OpenCode SDK, clients, and API.
Full documentation is available at <https://opencode.mintlify.site/>. Consult
it when this overview does not contain enough detail for the task.
Full documentation is available at <https://v2.opencode.ai/>. This overview is
only an index of core concepts. Before answering a question about a topic below,
fetch the URL named in that section and use the full page as the source of
truth. Follow links from that page when the question needs more detail. Fetch
<https://v2.opencode.ai/llms.txt> first when you need to discover the relevant
documentation page.
## Configuration
## [Configuration](https://v2.opencode.ai/config)
OpenCode configuration uses JSON or JSONC. Include the published schema so the
user's editor can validate fields and provide autocomplete:
@@ -23,8 +27,11 @@ to every project for that user. Project configuration can live in any directory
as `opencode.json(c)` or `.opencode/opencode.json(c)`, including nested packages
in a monorepo.
When OpenCode starts, it searches upward from the current directory for project
configuration and merges the files it finds with the global configuration.
When OpenCode starts, it searches from the current directory up to the project
root. It merges direct `opencode.json(c)` files from root to current directory,
then does the same for `.opencode/opencode.json(c)` files. This means every
`.opencode` config overrides every direct config. Global configuration has the
lowest precedence.
Common configuration fields include `model`, `default_agent`, `permissions`,
`agents`, `commands`, `plugins`, `providers`, `mcp`, `skills`, `instructions`,
@@ -34,34 +41,41 @@ Do not guess field names or shapes. Use
<https://opencode.ai/config.json> as the source of truth and preserve unrelated
settings when editing an existing file.
See the [full configuration guide](https://opencode.mintlify.site/config) for
See the [full configuration guide](https://v2.opencode.ai/config) for
every field, examples, config locations, and links to dedicated feature guides.
## V1 to V2 migration
## [V1 to V2 migration](https://v2.opencode.ai/migrate-v1)
For any request to migrate OpenCode configuration, agents, commands, skills,
plugins, integrations, or other behavior from V1 to V2, read the full
[migration guide](https://opencode.mintlify.site/migrate-v1) before acting. In
[migration guide](https://v2.opencode.ai/migrate-v1) before acting. In
the repository, its source is `packages/docs/migrate-v1.mdx`.
V1 config files and `.opencode/` definitions are intended to remain compatible.
The only intentional breaking changes are the server API and plugin API. Native
V2 config uses more ergonomic shapes, but conversion is optional. When the user
requests conversion, inspect the complete configuration, preserve behavior and
unrelated settings, and apply only the relevant migrations from the guide. If
the request includes a V1 plugin, explain that its API is not finalized and do
not attempt migration yet. Once the V2 plugin API is finalized, OpenCode should
be able to migrate most plugins. If non-API V1 functionality fails in V2, use
the `report` skill to file it as a compatibility bug.
unrelated settings, and apply only the relevant migrations from the guide. For
plugin migrations, fetch and follow both the migration guide and the full
[plugins guide](https://v2.opencode.ai/build/plugins). If non-API V1
functionality fails in V2, use the `report` skill to file it as a compatibility
bug.
## Service
## [Plugins](https://v2.opencode.ai/build/plugins)
For questions about creating, configuring, loading, publishing, or migrating
plugins, fetch the full [plugins guide](https://v2.opencode.ai/build/plugins)
before answering. This includes questions about the Effect plugin API, hooks,
transforms, tools, plugin context capabilities, and package entrypoints.
## [Service](https://v2.opencode.ai/troubleshooting#check-the-background-service)
OpenCode uses a client-server architecture. Interfaces such as the TUI connect
to a background OpenCode service, which owns sessions, configuration, plugins,
permissions, and tool execution.
Configuration and related files are typically watched and reloaded while the
service is running. If a change does not appear, restart the service:
OpenCode normally discovers or starts the shared background service
automatically. If the service is stuck or unhealthy, restart it:
```sh
opencode2 service restart
@@ -73,14 +87,15 @@ Check its status after restarting:
opencode2 service status
```
## API
## [API](https://v2.opencode.ai/api)
OpenCode exposes an HTTP API from its server. The API is described by an
OpenAPI document available from the running server at `/openapi.json`.
Use OpenCode's built-in `api` command for local requests. It discovers the same
background server used by the TUI, starts it when necessary, and applies the
server's authentication headers automatically.
Use OpenCode's built-in `api` command for local requests. It uses the same
discovery and authentication flow as the TUI and may start the background
service when no compatible healthy service is available. It accepts either an
HTTP method and path or an OpenAPI operation ID.
Call an endpoint with an HTTP method and path:
@@ -101,18 +116,34 @@ connected to an explicit server instead of its managed background service, use
the same configured server and authentication context rather than constructing
an unauthenticated request separately.
See the [full API reference](https://opencode.mintlify.site/api) for available
See the [full API reference](https://v2.opencode.ai/api) for available
endpoints, parameters, request bodies, and response schemas. The
raw [OpenAPI specification](https://opencode.mintlify.site/openapi.json) is also
raw [OpenAPI specification](https://v2.opencode.ai/openapi.json) is also
available for code generation and other tooling.
## Troubleshooting
## [Client](https://v2.opencode.ai/build/client)
For questions about connecting an application to OpenCode over the network,
fetch the full [client guide](https://v2.opencode.ai/build/client) before
answering.
`@opencode-ai/client` is the generated TypeScript client for the OpenCode HTTP
API. Its methods and types come from the same contract as the API reference.
The default entrypoint exposes Promise-based resource clients and async
iterables for streaming endpoints. The `@opencode-ai/client/effect` entrypoint
exposes typed Effects, Streams, and decoded OpenCode schema values. Its
`Service` API can discover, start, stop, and authenticate with the local
background service from a Node application.
## [Troubleshooting](https://v2.opencode.ai/troubleshooting)
OpenCode runs a client and a background server. Start by determining whether a
problem belongs to the client, the shared server, or one project.
- Check the service with `opencode2 service status` and verify the API with
`opencode2 api get /api/health`.
- Compare with `opencode2 --standalone`, which runs the TUI with a private
server, to isolate shared-service issues.
- Inspect `~/.local/share/opencode/log/opencode.log`. Filter `role=cli` for
client startup and `role=server` for sessions, providers, plugins,
permissions, and tools.
@@ -124,6 +155,6 @@ problem belongs to the client, the shared server, or one project.
- Redact API keys, authorization headers, prompts, file contents, and other
sensitive data before sharing diagnostics.
See the [full troubleshooting guide](https://opencode.mintlify.site/troubleshooting)
See the [full troubleshooting guide](https://v2.opencode.ai/troubleshooting)
for service lifecycle commands, API inspection, log locations, explicit server
connections, issue-reporting details, and local development paths.
+43 -81
View File
@@ -72,23 +72,6 @@ type Operation =
readonly target: string
}
type Candidate =
| {
readonly type: "definition"
readonly definition: Plugin
}
| {
readonly type: "package"
readonly specifier: string
readonly options: Record<string, unknown>
readonly mtime?: number
}
type ConfiguredPackage = {
readonly operation: Extract<Operation, { type: "add" }>
enabled: boolean
}
function parse(input: ConfigPlugin.Plugin): Operation {
if (typeof input !== "string") {
return { type: "add", target: input.package, options: input.options ?? {} }
@@ -109,13 +92,14 @@ const scan = Effect.fn("PluginSupervisor.scan")(function* (entries: readonly Con
.filter((entry): entry is Config.Document => entry.type === "document")
.flatMap((entry) =>
(entry.info.plugins ?? []).map(parse).map((operation) => {
if (operation.type === "remove") return operation
const directory = entry.path ? path.dirname(entry.path) : location.directory
const target = operation.target.startsWith("file://")
? fileURLToPath(operation.target)
: operation.target.startsWith("./") || operation.target.startsWith("../")
? path.resolve(directory, operation.target)
: operation.target
return operation.type === "add" ? { ...operation, target } : { type: "remove" as const, target }
return { ...operation, target }
}),
)
// Explicit config is applied last so it can remove auto-discovered packages.
@@ -136,88 +120,66 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
post: readonly Plugin[],
operations: readonly Operation[],
) {
const plan = apply(pre, post, operations)
return yield* load(plan)
})
function apply(pre: readonly Plugin[], post: readonly Plugin[], operations: readonly Operation[]) {
const matches = (selector: string, target: string) =>
selector === "*" || (selector.endsWith(".*") ? target.startsWith(selector.slice(0, -1)) : selector === target)
const plugins = [...pre, ...post]
const enabled = new Set(plugins.map((plugin) => plugin.id))
const packages = new Map<string, ConfiguredPackage>()
const definitions = [...pre, ...post]
const enabled = new Set(definitions.map((plugin) => plugin.id))
const packages = new Map<string, Plugin>()
const plugins = () => [...definitions, ...packages.values()]
for (const operation of operations) {
if (operation.type === "remove") {
plugins.filter((plugin) => matches(operation.target, plugin.id)).forEach((plugin) => enabled.delete(plugin.id))
packages.forEach((item, target) => {
if (matches(operation.target, target)) item.enabled = false
})
plugins()
.filter((plugin) => matches(operation.target, plugin.id))
.forEach((plugin) => enabled.delete(plugin.id))
continue
}
const matched = plugins.filter((plugin) => matches(operation.target, plugin.id))
const selectsDefinitions =
const matched = plugins().filter((plugin) => matches(operation.target, plugin.id))
const selectsPlugins =
matched.length > 0 ||
operation.target === "*" ||
operation.target.endsWith(".*") ||
operation.target.startsWith("opencode.")
if (selectsDefinitions) {
if (selectsPlugins) {
matched.forEach((plugin) => enabled.add(plugin.id))
packages.forEach((item, target) => {
if (matches(operation.target, target)) item.enabled = true
})
continue
}
packages.set(operation.target, { operation, enabled: true })
const plugin = yield* load(operation).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
if (!plugin) continue
const previous = packages.get(operation.target)
if (previous) enabled.delete(previous.id)
packages.set(operation.target, plugin)
enabled.add(plugin.id)
}
const definitions: Candidate[] = pre.flatMap((definition) =>
enabled.has(definition.id) ? [{ type: "definition", definition }] : [],
)
const configured: Candidate[] = Array.from(packages.values()).flatMap((item) =>
item.enabled
? [
{
type: "package",
specifier: item.operation.target,
options: item.operation.options,
...(item.operation.mtime === undefined ? {} : { mtime: item.operation.mtime }),
},
]
: [],
)
const posts: Candidate[] = post.flatMap((definition) =>
enabled.has(definition.id) ? [{ type: "definition", definition }] : [],
)
return [...definitions, ...configured, ...posts]
}
return [
...pre.filter((plugin) => enabled.has(plugin.id)),
...Array.from(packages.values()).filter((plugin) => enabled.has(plugin.id)),
...post.filter((plugin) => enabled.has(plugin.id)),
]
})
const load = Effect.fn("PluginSupervisor.load")(function* (plan: readonly Candidate[]) {
return yield* Effect.forEach(plan, (candidate) => {
if (candidate.type === "definition") return Effect.succeed(candidate.definition)
return Effect.gen(function* () {
const npm = yield* Npm.Service
const entrypoint = path.isAbsolute(candidate.specifier)
? pathToFileURL(candidate.specifier).href
: (yield* npm.add(candidate.specifier)).entrypoint
if (!entrypoint) return undefined
// Bun currently ignores query parameters when caching file:// imports.
const source =
candidate.mtime === undefined
? entrypoint
: `${candidate.specifier.replaceAll("\\", "/")}?mtime=${candidate.mtime}`
yield* Effect.log({ msg: "loading plugin", id: candidate.specifier, entrypoint: source })
const mod = yield* Effect.promise(() => import(source))
const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default
const plugin = "effect" in value ? value : PluginPromise.fromPromise(value)
return {
id: plugin.id,
effect: (host) => plugin.effect({ ...host, options: candidate.options }),
} satisfies Plugin
}).pipe(Effect.catchCause(() => Effect.succeed(undefined)))
}).pipe(Effect.map((plugins) => plugins.filter((plugin) => plugin !== undefined)))
const load = Effect.fn("PluginSupervisor.load")(function* (operation: Extract<Operation, { type: "add" }>) {
const npm = yield* Npm.Service
const entrypoint = path.isAbsolute(operation.target)
? pathToFileURL(operation.target).href
: (yield* npm.add(operation.target)).entrypoint
if (!entrypoint) return
// Bun currently ignores query parameters when caching file:// imports.
const source =
operation.mtime === undefined
? entrypoint
: `${operation.target.replaceAll("\\", "/")}?mtime=${operation.mtime}`
yield* Effect.log({ msg: "loading plugin", id: operation.target, entrypoint: source })
const mod = yield* Effect.promise(() => import(source))
const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default
const plugin = "effect" in value ? value : PluginPromise.fromPromise(value)
return {
id: plugin.id,
effect: (host) => plugin.effect({ ...host, options: operation.options }),
} satisfies Plugin
})
function discoverDirectory(fs: FSUtil.Interface, directory: string) {
+1 -1
View File
@@ -581,7 +581,7 @@ const layer = Layer.effect(
yield* shellLocks.withLock(input.sessionID)(
Effect.gen(function* () {
activeShells.add(input.sessionID)
if ((yield* execution.active).has(input.sessionID)) yield* execution.awaitIdle(input.sessionID)
yield* execution.awaitIdle(input.sessionID)
const started = yield* Effect.gen(function* () {
const shell = yield* Shell.Service
return yield* shell.create({ command: input.command, cwd: session.location.directory, timeout: 0 })
+153 -139
View File
@@ -1,7 +1,8 @@
export * as SessionCompaction from "./compaction"
import { LLM, LLMClient, LLMError, LLMEvent, Message, type LLMRequest, type Model } from "@opencode-ai/llm"
import { Context, DateTime, Effect, Layer, Stream } from "effect"
import { SessionError } from "@opencode-ai/schema/session-error"
import { Context, Effect, Layer, Stream } from "effect"
import { Config } from "../config"
import { EventV2 } from "../event"
import { makeLocationNode } from "../effect/app-node"
@@ -10,12 +11,12 @@ import { SessionEvent } from "./event"
import type { SessionMessage } from "./message"
import { SessionRunnerModel } from "./runner/model"
import { SessionSchema } from "./schema"
import { toSessionError } from "./to-session-error"
import { Token } from "../util/token"
const DEFAULT_BUFFER = 20_000
const DEFAULT_KEEP_TOKENS = 8_000
const TOOL_OUTPUT_MAX_CHARS = 2_000
const SUMMARY_OUTPUT_TOKENS = 4_096
const SUMMARY_TEMPLATE = `Output exactly the Markdown structure shown inside <template> and keep the section order unchanged. Do not include the <template> tags in your response.
<template>
## Objective
@@ -59,20 +60,14 @@ type Dependencies = {
readonly llm: {
readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMError>
}
readonly config: readonly Config.Entry[]
readonly models: SessionRunnerModel.Interface
readonly config: Settings
}
export type AutoInput = {
readonly sessionID: SessionSchema.ID
readonly messages: readonly SessionMessage.Info[]
readonly request: LLMRequest
}
type CompactInput = {
readonly sessionID: SessionSchema.ID
readonly messages: readonly SessionMessage.Info[]
readonly model: Model
readonly inputID?: SessionMessage.ID
}
export type ManualInput = {
@@ -81,16 +76,27 @@ export type ManualInput = {
readonly inputID: SessionMessage.ID
}
type Plan = {
readonly sessionID: SessionSchema.ID
readonly model: Model
readonly reason: SessionMessage.Compaction["reason"]
readonly prompt: string
readonly recent: string
readonly inputID?: SessionMessage.ID
}
export type Outcome =
| Pick<SessionMessage.CompactionCompleted, "status">
| Pick<SessionMessage.CompactionFailed, "status" | "error">
export interface Interface {
readonly compactIfNeeded: (input: AutoInput) => Effect.Effect<boolean>
readonly compactAfterOverflow: (input: AutoInput) => Effect.Effect<boolean>
readonly compactManual: (input: ManualInput) => Effect.Effect<boolean>
readonly required: (input: AutoInput) => boolean
readonly compact: (input: AutoInput) => Effect.Effect<Outcome>
readonly compactManual: (input: ManualInput) => Effect.Effect<Outcome>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/SessionCompaction") {}
const estimate = (value: unknown) => Token.estimate(JSON.stringify(value))
const truncate = (value: string) =>
value.length <= TOOL_OUTPUT_MAX_CHARS ? value : `${value.slice(0, TOOL_OUTPUT_MAX_CHARS)}\n[truncated]`
@@ -154,30 +160,33 @@ const select = (
): { readonly head: string; readonly recent: string } | undefined => {
const conversation = messages
.filter((message) => message.type !== "compaction")
.map(serialize)
.filter(Boolean)
.flatMap((message) => {
const text = serialize(message)
return text ? [{ message, text }] : []
})
if (conversation.length === 0) return undefined
let total = 0
let split = conversation.length
let splitPrefix = ""
let splitSuffix = ""
for (let index = conversation.length - 1; index >= 0; index--) {
const next = total + Token.estimate(conversation[index])
if (next > tokens) {
const remaining = Math.max(0, tokens - total) * 4
if (remaining > 0) {
splitPrefix = conversation[index].slice(0, -remaining)
splitSuffix = conversation[index].slice(-remaining)
split = index + 1
}
break
}
const next = total + Token.estimate(conversation[index].text)
if (split < conversation.length && next > tokens) break
total = next
split = index
}
while (split > 0 && conversation[split].message.type !== "user") split--
if (split === 0) {
const latestUser = conversation.findLastIndex((item) => item.message.type === "user")
if (latestUser > 0) split = latestUser
}
return {
head: [...conversation.slice(0, split), splitPrefix].filter(Boolean).join("\n\n"),
recent: [splitSuffix, ...conversation.slice(split)].filter(Boolean).join("\n\n"),
head: conversation
.slice(0, split)
.map((item) => item.text)
.join("\n\n"),
recent: conversation
.slice(split)
.map((item) => item.text)
.join("\n\n"),
}
}
@@ -190,146 +199,166 @@ export const buildPrompt = (input: { readonly previousSummary?: string; readonly
...input.context,
].join("\n\n")
const planContent = (messages: readonly SessionMessage.Info[], tokens: number) => {
const selected = select(messages, tokens)
if (!selected) return
const previousSummary = messages.findLast(
(message) => message.type === "compaction" && message.status === "completed",
)
const previousRecent = previousSummary?.type === "compaction" ? previousSummary.recent : ""
const summarizeRecent = !previousRecent && !selected.head
return {
prompt: buildPrompt({
previousSummary: previousSummary?.type === "compaction" ? previousSummary.summary : undefined,
context: summarizeRecent ? [selected.recent] : [previousRecent, selected.head].filter(Boolean),
}),
recent: summarizeRecent ? "" : selected.recent,
}
}
const make = (dependencies: Dependencies) => {
const config = settings(dependencies.config)
const compact = Effect.fn("SessionCompaction.compact")(function* (input: {
const config = dependencies.config
const failed = Effect.fnUntraced(function* (input: {
readonly sessionID: SessionSchema.ID
readonly model: Model
readonly reason: SessionMessage.Compaction["reason"]
readonly previousSummary?: string
readonly context: readonly string[]
readonly recent: string
readonly output?: number
readonly error: SessionError.Error
readonly inputID?: SessionMessage.ID
}) {
const context = input.model.route.defaults.limits?.context
if (context === undefined || context <= 0) return false
const output = input.output ?? input.model.route.defaults.limits?.output ?? 0
const summaryPrompt = buildPrompt({ previousSummary: input.previousSummary, context: input.context })
const summaryOutput = Math.min(output || SUMMARY_OUTPUT_TOKENS, SUMMARY_OUTPUT_TOKENS)
if (Token.estimate(summaryPrompt) > context - summaryOutput) return false
yield* dependencies.events.publish(SessionEvent.Compaction.Failed, input)
return { status: "failed" as const, error: input.error }
})
const execute = Effect.fn("SessionCompaction.execute")(function* (plan: Plan) {
yield* dependencies.events.publish(SessionEvent.Compaction.Started, {
sessionID: input.sessionID,
reason: input.reason,
recent: input.recent,
inputID: input.inputID,
sessionID: plan.sessionID,
reason: plan.reason,
recent: plan.recent,
inputID: plan.inputID,
})
const chunks: string[] = []
let failed = false
const summarized = yield* dependencies.llm
let failure: SessionError.Error | undefined
yield* dependencies.llm
.stream(
LLM.request({
model: input.model,
messages: [Message.user(summaryPrompt)],
model: plan.model,
messages: [Message.user(plan.prompt)],
tools: [],
generation: { maxTokens: summaryOutput },
}),
)
.pipe(
Stream.runForEach((event) => {
if (LLMEvent.is.providerError(event)) failed = true
if (LLMEvent.is.providerError(event))
failure = {
type: event.classification === "context-overflow" ? "provider.invalid-request" : "provider.error",
message: event.message,
}
if (LLMEvent.is.textDelta(event)) {
chunks.push(event.text)
return dependencies.events.publish(SessionEvent.Compaction.Delta, {
sessionID: input.sessionID,
sessionID: plan.sessionID,
text: event.text,
})
}
return Effect.void
}),
Effect.as(true),
Effect.catchTag("LLM.Error", () => Effect.succeed(false)),
Effect.catchTag("LLM.Error", (error) =>
Effect.sync(() => {
failure = toSessionError(error)
}),
),
Effect.onInterrupt(() =>
input.reason === "auto"
? dependencies.events.publish(SessionEvent.Compaction.Failed, {
sessionID: input.sessionID,
reason: input.reason,
plan.reason === "auto"
? failed({
sessionID: plan.sessionID,
reason: plan.reason,
error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
inputID: input.inputID,
})
inputID: plan.inputID,
}).pipe(Effect.asVoid)
: Effect.void,
),
)
const summary = chunks.join("")
if (!summarized || failed || !summary.trim()) {
yield* dependencies.events.publish(SessionEvent.Compaction.Failed, {
sessionID: input.sessionID,
reason: input.reason,
error: { type: "compaction.failed", message: "Compaction produced no summary" },
inputID: input.inputID,
if (failure || !summary.trim()) {
const error = failure ?? { type: "compaction.failed" as const, message: "Compaction produced no summary" }
return yield* failed({
sessionID: plan.sessionID,
reason: plan.reason,
error,
inputID: plan.inputID,
})
return false
}
yield* dependencies.events.publish(SessionEvent.Compaction.Ended, {
sessionID: input.sessionID,
reason: input.reason,
sessionID: plan.sessionID,
reason: plan.reason,
text: summary,
recent: input.recent,
recent: plan.recent,
})
return true
return { status: "completed" as const }
})
const compactAfterOverflow = Effect.fn("SessionCompaction.compactAfterOverflow")(function* (input: AutoInput) {
return yield* compactSelected({
const compact = Effect.fn("SessionCompaction.compact")(function* (input: AutoInput) {
const content = planContent(input.messages, config.tokens)
if (content)
return yield* execute({
sessionID: input.sessionID,
model: input.model,
reason: "auto",
...content,
})
const error = { type: "compaction.unavailable" as const, message: "Nothing to compact yet" }
return yield* failed({
sessionID: input.sessionID,
messages: input.messages,
model: input.request.model,
reason: "auto",
force: false,
output: input.request.generation?.maxTokens ?? input.request.model.route.defaults.limits?.output ?? 0,
error,
})
})
const compactSelected = Effect.fn("SessionCompaction.compactSelected")(function* (
input: CompactInput & {
readonly reason: SessionMessage.Compaction["reason"]
readonly force: boolean
readonly output?: number
},
) {
const required = (input: AutoInput) => {
if (!config.auto) return false
const context = input.model.route.defaults.limits?.context
if (context === undefined || context <= 0) return false
const selected = select(input.messages, config.tokens)
if (!selected) return false
const previousSummary = input.messages.find(
(message) => message.type === "compaction" && message.status === "completed",
const last = input.messages.findLast(
(message): message is SessionMessage.Assistant & { tokens: NonNullable<SessionMessage.Assistant["tokens"]> } =>
message.type === "assistant" && message.tokens !== undefined,
)
const hasHead = selected.head.length > 0
if (!hasHead && previousSummary?.type !== "compaction" && !input.force) return false
const forcedShortContext = input.force && !hasHead
const previousRecent = previousSummary?.type === "compaction" ? previousSummary.recent : ""
return yield* compact({
sessionID: input.sessionID,
model: input.model,
reason: input.reason,
previousSummary: previousSummary?.type === "compaction" ? previousSummary.summary : undefined,
context: (forcedShortContext ? [previousRecent, selected.recent] : [previousRecent, selected.head]).filter(
Boolean,
if (!last) return false
const output = input.model.route.defaults.limits?.output ?? 0
const used =
last.tokens.input + last.tokens.output + last.tokens.reasoning + last.tokens.cache.read + last.tokens.cache.write
if (used <= 0) return false
return used >= context - (output || config.buffer)
}
const compactManual = Effect.fn("SessionCompaction.compactManual")(function* (input: ManualInput) {
const content = planContent(input.messages, config.tokens)
if (!content)
return yield* failed({
sessionID: input.session.id,
reason: "manual",
error: { type: "compaction.unavailable", message: "Nothing to compact yet" },
inputID: input.inputID,
})
const resolved = yield* dependencies.models.resolve(input.session).pipe(
Effect.catch((cause) =>
failed({
sessionID: input.session.id,
reason: "manual",
error: toSessionError(cause),
inputID: input.inputID,
}),
),
recent: forcedShortContext ? "" : selected.recent,
output: input.output,
)
if ("status" in resolved) return resolved
return yield* execute({
sessionID: input.session.id,
model: resolved.model,
reason: "manual",
inputID: input.inputID,
...content,
})
})
const compactManual = Effect.fn("SessionCompaction.compactManual")(function* (input: CompactInput) {
return yield* compactSelected({ ...input, reason: "manual", force: true })
})
const compactIfNeeded = Effect.fn("SessionCompaction.compactIfNeeded")(function* (input: AutoInput) {
if (!config.auto) return false
const context = input.request.model.route.defaults.limits?.context
if (context === undefined || context <= 0) return false
const output = input.request.generation?.maxTokens ?? input.request.model.route.defaults.limits?.output ?? 0
if (
estimate({ system: input.request.system, messages: input.request.messages, tools: input.request.tools }) <=
context - Math.max(output, config.buffer)
)
return false
return yield* compactAfterOverflow(input)
})
return {
compactIfNeeded,
compactAfterOverflow,
return Service.of({
required,
compact,
compactManual,
}
})
}
export const layer = Layer.effect(
@@ -339,22 +368,7 @@ export const layer = Layer.effect(
const llm = yield* LLMClient.Service
const config = yield* Config.Service
const models = yield* SessionRunnerModel.Service
const compaction = make({ events, llm, config: yield* config.entries() })
return Service.of({
compactIfNeeded: compaction.compactIfNeeded,
compactAfterOverflow: compaction.compactAfterOverflow,
compactManual: Effect.fn("SessionCompaction.compactManual")(function* (input) {
const resolved = yield* models.resolve(input.session).pipe(Effect.catch(() => Effect.succeed(undefined)))
if (!resolved) return false
return yield* compaction.compactManual({
sessionID: input.session.id,
messages: input.messages,
model: resolved.model,
inputID: input.inputID,
})
}),
})
return make({ events, llm, models, config: settings(yield* config.entries()) })
}),
)
+6 -8
View File
@@ -28,7 +28,6 @@ type Execution<E, Reason> = {
owner?: Fiber.Fiber<void>
pendingWake: boolean
stopping: boolean
settling: boolean
interruptionReason?: Reason
}
@@ -74,7 +73,6 @@ export const make = <Key, E, Reason = never>(options: {
done: Deferred.makeUnsafe<void, E>(),
pendingWake: false,
stopping: false,
settling: false,
}
executions.set(key, execution)
// The leading yield lets `owner` be assigned before the drain can settle, and keeps
@@ -86,7 +84,7 @@ export const make = <Key, E, Reason = never>(options: {
Effect.andThen(loop(key, execution, force)),
Effect.onExit((exit) =>
Effect.sync(() => {
execution.settling = true
execution.owner = undefined
}).pipe(Effect.andThen(options.settled?.(key, exit, execution.interruptionReason) ?? Effect.void)),
),
Effect.onExit((exit) => Effect.sync(() => settle(key, execution, exit))),
@@ -106,14 +104,14 @@ export const make = <Key, E, Reason = never>(options: {
}
const run = (key: Key): Effect.Effect<void, E> =>
Effect.uninterruptibleMask((restore) => {
Effect.suspend(() => {
const execution = executions.get(key)
if (execution !== undefined) {
// A stopping execution refuses joiners: wait out its cleanup, then run fresh.
if (execution.stopping) return restore(Deferred.await(execution.done).pipe(Effect.andThen(run(key))))
return restore(Deferred.await(execution.done))
if (execution.stopping) return Deferred.await(execution.done).pipe(Effect.andThen(run(key)))
return Deferred.await(execution.done)
}
return restore(Deferred.await(start(key, true).done))
return Deferred.await(start(key, true).done)
})
const wake = (key: Key) =>
@@ -129,7 +127,7 @@ export const make = <Key, E, Reason = never>(options: {
const interrupt = (key: Key, reason?: Reason): Effect.Effect<void> =>
Effect.suspend(() => {
const execution = executions.get(key)
if (execution?.owner === undefined || execution.stopping || execution.settling) return Effect.void
if (execution?.owner === undefined || execution.stopping) return Effect.void
execution.stopping = true
execution.pendingWake = false
execution.interruptionReason = reason
+21 -125
View File
@@ -14,7 +14,6 @@ import { SessionError } from "@opencode-ai/schema/session-error"
import { Money } from "@opencode-ai/schema/money"
import { Cause, Effect, Exit, Fiber, FiberSet, Layer, Option, Semaphore, Stream } from "effect"
import { AgentV2 } from "../../agent"
import { Config } from "../../config"
import { Database } from "../../database/database"
import { EventV2 } from "../../event"
import { Location } from "../../location"
@@ -51,8 +50,6 @@ import { llmClient } from "../../effect/app-node-platform"
import { AgentNotFoundError, StepFailedError } from "../error"
import { toSessionError } from "../to-session-error"
import { SessionRunnerRetry } from "./retry"
import type { SessionHooks } from "@opencode-ai/plugin/v2/effect/session"
import { PluginHooks } from "../../plugin/hooks"
import { PluginSupervisor } from "../../plugin/supervisor"
type StepTokens = {
@@ -80,53 +77,8 @@ export function calculateCost(costs: ModelV2.Info["cost"], tokens: StepTokens) {
}
/**
* Runs one durable coding-agent Session until it settles.
*
* Keep this as orchestration over smaller collaborators rather than rebuilding the legacy
* `SessionPrompt` monolith. Implement the unchecked items in small reviewed slices:
*
* - Session ownership and controls
* - [x] Coordinate one local active drain per Session; explicit resumes join and prompt wakeups coalesce.
* - [ ] Replace local ownership with durable multi-node ownership when clustered.
* - [x] Publish durable historical execution lifecycle and bounded retry observations.
* - [ ] Honor interruption and reject stale work after runtime attachment replacement.
* - [x] Honor optional agent step limits.
* - [ ] Bound repeated identical tool calls (provider retries are bounded).
*
* - Runtime context assembly
* - Track V1 runtime-context parity canonically in `specs/v2/session.md`.
*
* - One step
* - [x] Translate every projected V2 Session message variant into canonical
* `@opencode-ai/llm` messages.
* - [ ] Resolve policy-filtered built-in, MCP, plugin, and structured-output tool definitions.
* - [x] Stream exactly one `llm.stream(request)` call per attempt.
* - [x] Persist assistant text and usage events incrementally as they arrive.
* - [ ] Persist snapshots, patches, and retry notices incrementally as they arrive.
* - [x] Persist reasoning, provider errors, and tool-call events incrementally as they arrive.
*
* - Tool settlement and continuation
* - [x] Durably record each tool call before side effects begin.
* - [x] Authorize and execute recorded local calls through a core-owned registry hook.
* - [x] Persist typed success, failure, and provider-executed tool outcomes.
* - [x] Start each recorded local call eagerly and await all settlements before continuation.
* - [ ] Add scoped runtime context, progress updates, attachment normalization,
* plugins, and cancellation settlement.
* - [x] Reload projected history and start the next explicit step after local tool results.
* - [x] Continue for durable user steering accepted during an active step.
* - [ ] Continue for compaction or another continuation condition when required.
*
* - Post-run maintenance
* - [ ] Settle final status and expose durable output events to replayable consumers.
* - [ ] Coalesce streamed deltas and add covering projected-history indexes.
* - [ ] Update title, summaries, compaction state, and cleanup in bounded background work.
*
* Use `llm.stream(request)` for each attempt. Keep tool execution and continuation here.
* Durable continuation recovery remains a separate future slice with an explicit retry policy.
*
* The current slice loads V2 history, translates it, resolves a model through a core service, and persists one
* step. Registry definitions are advertised, local tool calls are settled durably, and an
* explicit loop starts the next step after local settlement. Configured agent step limits bound the loop.
* Runs one durable coding-agent Session until it settles. Each step reloads projected history,
* materializes tools, makes one model request, and settles local calls before continuation.
*/
const layer = Layer.effect(
@@ -136,7 +88,6 @@ const layer = Layer.effect(
const llm = yield* LLMClient.Service
const agents = yield* AgentV2.Service
const tools = yield* ToolRegistry.Service
const hooks = yield* PluginHooks.Service
const models = yield* SessionRunnerModel.Service
const store = yield* SessionStore.Service
const location = yield* Location.Service
@@ -173,7 +124,7 @@ const layer = Layer.effect(
sessionID,
assistantMessageID: message.id,
callID: tool.id,
error: { type: "tool.stale", message: `Tool execution interrupted: ${tool.name}` },
error: { type: "aborted", message: `Tool execution interrupted: ${tool.name}` },
executed: tool.executed === true,
})
}
@@ -205,7 +156,7 @@ const layer = Layer.effect(
sessionID: SessionSchema.ID,
promotion: SessionPending.Delivery | undefined,
step: number,
recoverOverflow?: typeof compaction.compactAfterOverflow,
recoverOverflow?: typeof compaction.compact,
assistantMessageID?: SessionMessage.ID,
) {
const session = yield* getSession(sessionID)
@@ -238,10 +189,14 @@ const layer = Layer.effect(
const providerMetadataKey = model.route.providerMetadataKey ?? model.provider
const entries = yield* SessionHistory.entriesForRunner(db, session.id, checkpoint.baselineSeq)
const context = entries.map((entry) => entry.message)
const compactionInput = { sessionID: session.id, messages: context, model }
if (compaction.required(compactionInput) && !(yield* SessionPending.compaction(db, session.id))) {
const compacted = yield* compaction.compact(compactionInput)
if (compacted.status === "completed") return { _tag: "RestartAfterCompaction", step: currentStep } as const
return yield* new StepFailedError({ error: compacted.error })
}
const isLastStep = agentInfo.steps !== undefined && currentStep >= agentInfo.steps
const toolMaterialization = isLastStep
? undefined
: yield* tools.materialize({ permissions: agentInfo.permissions, model })
const toolMaterialization = isLastStep ? undefined : yield* tools.materialize(agentInfo.permissions)
const promptCacheKey = /^ses_[0-9a-f]{64}$/.test(session.id) ? session.id.slice(4) : session.id
const request = LLM.request({
model,
@@ -259,36 +214,6 @@ const layer = Layer.effect(
const toolFibers = yield* FiberSet.make<void, ToolOutputStore.Error>()
const ownedToolFibers: Array<Fiber.Fiber<void, ToolOutputStore.Error>> = []
let needsContinuation = false
const availableTools = new Map(request.tools.map((tool) => [tool.name, tool]))
const requestEvent: SessionHooks["request"] = {
sessionID: session.id,
agent: agent.id,
model: resolved.ref,
system: [...request.system],
messages: [...request.messages],
tools: Object.fromEntries(
request.tools.map((tool) => [tool.name, { description: tool.description, input: { ...tool.inputSchema } }]),
),
}
// Plugins may reshape the draft, but cannot advertise tools excluded earlier
// by permissions or registration state.
yield* hooks.trigger("session", "request", requestEvent)
const hookedRequest = LLM.updateRequest(request, {
system: requestEvent.system,
messages: requestEvent.messages,
tools: Object.entries(requestEvent.tools).flatMap(([name, tool]) => {
const registered = availableTools.get(name)
if (!registered) return []
return [{ ...registered, description: tool.description, inputSchema: tool.input }]
}),
})
const advertisedTools = new Set(hookedRequest.tools.map((tool) => tool.name))
// Automatic compaction completed; rebuild the request from compacted history.
if (
!(yield* SessionPending.compaction(db, session.id)) &&
(yield* compaction.compactIfNeeded({ sessionID: session.id, messages: context, request: hookedRequest }))
)
return { _tag: "RestartAfterCompaction", step: currentStep } as const
const startSnapshot = yield* snapshots.capture()
const publisher = createLLMEventPublisher(events, {
sessionID: session.id,
@@ -306,7 +231,7 @@ const layer = Layer.effect(
const serialized = <A, E, R>(effect: Effect.Effect<A, E, R>) => publication.withPermit(effect)
const publish = (event: LLMEvent, error?: SessionError.Error) => serialized(publisher.publish(event, error))
let overflowFailure: ProviderErrorEvent | undefined
const providerStream = llm.stream(hookedRequest).pipe(
const providerStream = llm.stream(request).pipe(
Stream.runForEach((event) =>
Effect.gen(function* () {
if (overflowFailure || publisher.hasProviderError()) return
@@ -327,21 +252,6 @@ const layer = Layer.effect(
)
return
}
// A request hook hid this registered tool from the current request. Fail only
// this call durably and continue so the model can react, instead of executing
// a tool that was not advertised. Unregistered tools flow through settle, which
// durably fails them as unknown.
if (!advertisedTools.has(event.name) && availableTools.has(event.name)) {
needsContinuation = true
yield* publish(
LLMEvent.toolError({
id: event.id,
name: event.name,
message: `Tool is not available for this request: ${event.name}`,
}),
)
return
}
needsContinuation = true
const assistantMessageID = yield* publisher.assistantMessageID(event.id)
ownedToolFibers.push(
@@ -416,7 +326,8 @@ const layer = Layer.effect(
recoverOverflow &&
!publisher.hasRetryEvidence() &&
isContextOverflowFailure(overflowFailure ?? streamFailure) &&
(yield* restore(recoverOverflow({ sessionID: session.id, messages: context, request })))
(yield* restore(recoverOverflow({ sessionID: session.id, messages: context, model }))).status ===
"completed"
)
return { _tag: "RestartAfterOverflowCompaction", step: currentStep } as const
@@ -457,8 +368,8 @@ const layer = Layer.effect(
const toolsInterrupted = settledCauses.some(Cause.hasInterrupts)
const userDeclined = settledCauses.some(isUserDeclined)
if (settled._tag === "Failure") yield* FiberSet.clear(toolFibers)
if (userDeclined || streamInterrupted || toolsInterrupted) {
yield* FiberSet.clear(toolFibers)
yield* serialized(publisher.failUnsettledTools({ type: "aborted", message: "Tool execution interrupted" }))
yield* serialized(publisher.failAssistant({ type: "aborted", message: "Step interrupted" }))
}
@@ -466,9 +377,7 @@ const layer = Layer.effect(
// implementation becomes a failed tool call the model can read, and the step still
// settles so the model may recover. A typed infrastructure failure (tool output
// could not be persisted) also fails the assistant and then fails the drain.
const settledFailure = settledCauses.find(
(cause) => !Cause.hasInterrupts(cause) && !isUserDeclined(cause),
)
const settledFailure = settledCauses.find((cause) => !Cause.hasInterrupts(cause) && !isUserDeclined(cause))
const infraError =
settledFailure === undefined ? undefined : Option.getOrUndefined(Cause.findErrorOption(settledFailure))
if (settledFailure !== undefined) {
@@ -511,9 +420,7 @@ const layer = Layer.effect(
const stepFailure = publisher.stepFailure()
const stepSettlement = publisher.stepSettlement()
const stepEndedCleanly =
!streamInterrupted && !toolsInterrupted && infraError === undefined && !providerFailed && !stepFailure
if (stepSettlement && stepEndedCleanly) yield* publishStepEnd(stepSettlement)
if (stepSettlement && !stepFailure) yield* publishStepEnd(stepSettlement)
if (stepFailure)
yield* serialized(publisher.publishStepFailure(stepSettlement ? stepUsage(stepSettlement) : undefined))
@@ -525,7 +432,7 @@ const layer = Layer.effect(
if (stepFailure) return yield* new StepFailedError({ error: stepFailure })
return {
_tag: "Completed",
needsContinuation: !providerFailed && needsContinuation,
needsContinuation,
step: currentStep,
} as const
}),
@@ -540,7 +447,7 @@ const layer = Layer.effect(
// Compaction restarts rebuild the request from compacted history without re-promoting.
// Overflow recovery is one-shot: a post-compaction attempt must not recover another
// overflow, so the recovery hook is dropped after it fires.
let recoverOverflow: typeof compaction.compactAfterOverflow | undefined = compaction.compactAfterOverflow
let recoverOverflow: typeof compaction.compact | undefined = compaction.compact
let currentPromotion = promotion
let currentStep = step
let assistantMessageID: SessionMessage.ID | undefined
@@ -580,7 +487,7 @@ const layer = Layer.effect(
sessionID: SessionSchema.ID,
) {
const pending = yield* SessionPending.compaction(db, sessionID)
if (!pending) return false
if (!pending) return
const session = yield* getSession(sessionID)
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
@@ -593,7 +500,7 @@ const layer = Layer.effect(
})
}),
).pipe(Effect.exit)
if (Exit.isSuccess(compacted) && compacted.value) return true
if (Exit.isSuccess(compacted)) return
if (Exit.isFailure(compacted)) {
const unsettled = yield* SessionPending.compaction(db, sessionID)
if (unsettled)
@@ -605,15 +512,6 @@ const layer = Layer.effect(
})
return yield* Effect.failCause(compacted.cause)
}
const unsettled = yield* SessionPending.compaction(db, sessionID)
if (unsettled)
yield* events.publish(SessionEvent.Compaction.Failed, {
sessionID,
reason: "manual",
error: { type: "compaction.failed", message: "Compaction could not start" },
inputID: unsettled.id,
})
return true
}),
)
})
@@ -675,7 +573,6 @@ export const node = makeLocationNode({
llmClient,
AgentV2.node,
ToolRegistry.node,
PluginHooks.node,
SessionRunnerModel.node,
SessionStore.node,
Location.node,
@@ -687,7 +584,6 @@ export const node = makeLocationNode({
InstructionEntry.node,
SessionCompaction.node,
SessionTitle.node,
Config.node,
Snapshot.node,
Database.node,
PluginSupervisor.node,
@@ -57,13 +57,12 @@ const settledOutput = (value: ToolOutput | undefined, result: ToolResultValue):
}
/** Persist one step without executing tools or starting a continuation step. */
export const createLLMEventPublisher = (events: EventV2.Interface, input: Input) => {
export const createLLMEventPublisher = (events: Pick<EventV2.Interface, "publish">, input: Input) => {
const tools = new Map<
string,
{
readonly assistantMessageID: SessionMessage.ID
readonly name: string
inputEnded: boolean
called: boolean
settled: boolean
providerExecuted: boolean
@@ -140,7 +139,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
const flush = Effect.fnUntraced(function* () {
for (const id of chunks.keys()) yield* end(id)
})
return { start, append, end, flush }
return { start, append, end, flush, has: (id: string) => chunks.has(id) }
}
const text = fragments(
@@ -180,7 +179,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
callID,
text: value,
})
tool.inputEnded = true
}),
)
@@ -196,7 +194,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
tools.set(event.id, {
assistantMessageID,
name: event.name,
inputEnded: false,
called: false,
settled: false,
providerExecuted: false,
@@ -215,7 +212,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
if (!tool) return yield* Effect.die(new Error(`Tool input end before start: ${event.id}`))
if (tool.name !== event.name)
return yield* Effect.die(new Error(`Tool input name changed for ${event.id}: ${tool.name} -> ${event.name}`))
if (tool.inputEnded) return yield* Effect.die(new Error(`Duplicate tool input end: ${event.id}`))
if (!toolInput.has(event.id)) return yield* Effect.die(new Error(`Duplicate tool input end: ${event.id}`))
yield* toolInput.end(event.id)
})
@@ -330,7 +327,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
if (!tool) return yield* Effect.die(new Error(`Tool input delta before start: ${event.id}`))
if (tool.name !== event.name)
return yield* Effect.die(new Error(`Tool input name changed for ${event.id}: ${tool.name} -> ${event.name}`))
if (tool.inputEnded) return yield* Effect.die(new Error(`Tool input delta after end: ${event.id}`))
if (!toolInput.has(event.id)) return yield* Effect.die(new Error(`Tool input delta after end: ${event.id}`))
yield* toolInput.append(event.id, event.text)
yield* events.publish(SessionEvent.Tool.Input.Delta, {
sessionID: input.sessionID,
@@ -347,7 +344,7 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
retryEvidence = true
if (!tools.has(event.id)) yield* startToolInput(event)
const tool = tools.get(event.id)!
if (!tool.inputEnded) yield* endToolInput(event)
if (toolInput.has(event.id)) yield* endToolInput(event)
if (tool.name !== event.name)
return yield* Effect.die(new Error(`Tool call name changed for ${event.id}: ${tool.name} -> ${event.name}`))
if (tool.called) return yield* Effect.die(new Error(`Duplicate tool call: ${event.id}`))
@@ -364,7 +361,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
return
}
case "tool-result": {
retryEvidence = true
const tool = tools.get(event.id)
if (!tool?.called) return yield* Effect.die(new Error(`Tool result before call: ${event.id}`))
if (tool.name !== event.name)
@@ -401,7 +397,6 @@ export const createLLMEventPublisher = (events: EventV2.Interface, input: Input)
return
}
case "tool-error": {
retryEvidence = true
const tool = tools.get(event.id)
if (!tool?.called) return yield* Effect.die(new Error(`Tool error before call: ${event.id}`))
if (tool.name !== event.name)
@@ -1,4 +1,5 @@
import { LLMError, ToolFailure } from "@opencode-ai/llm"
import { Tool } from "@opencode-ai/plugin/v2/effect/tool"
import { SessionError } from "@opencode-ai/schema/session-error"
import { PermissionV2 } from "../permission"
import { QuestionV2 } from "../question"
@@ -38,7 +39,7 @@ export function toSessionError(cause: unknown): SessionError.Error {
}
if (cause instanceof PermissionV2.BlockedError) return { type: "permission.rejected", message: cause.message }
if (cause instanceof QuestionV2.RejectedError) return { type: "aborted", message: cause.message }
if (cause instanceof ToolFailure)
if (cause instanceof ToolFailure || cause instanceof Tool.Failure)
return cause.error === undefined ? { type: "tool.execution", message: cause.message } : toSessionError(cause.error)
if (cause instanceof StepFailedError) return cause.error
if (cause instanceof AgentNotFoundError) return { type: "unknown", message: cause.message }
+1 -1
View File
@@ -35,7 +35,7 @@ Registrations are scoped:
- The latest active same-placement registration wins.
- Closing any registration removes only that registration and reveals the next active one.
- An invocation captures the effective tool once settlement starts.
- Each model request captures the effective tools it advertises; later registration changes affect later requests.
`ToolRegistry.Service` is Location-scoped. Do not make the registry process-global or construct a separate application-tool service for each Location.
+10 -14
View File
@@ -36,23 +36,19 @@ type CollectedFiles = {
readonly files: Array<typeof ExecuteFile.Type>
}
export interface Registration {
readonly identity: object
interface Registration {
readonly tool: AnyTool
readonly name: string
readonly group?: string
}
export const create = (options: {
readonly registrations: ReadonlyMap<string, Registration>
readonly current: (name: string) => Registration | undefined
}) => {
export const create = (registrations: ReadonlyMap<string, Registration>) => {
const runtime = (
invoke: (name: string, registration: Registration, input: unknown) => Effect.Effect<unknown, unknown>,
hooks?: CodeMode.ToolCallHooks,
) => {
const tools: Record<string, Tool.Definition<never> | Record<string, Tool.Definition<never>>> = {}
for (const [name, registration] of options.registrations) {
for (const [name, registration] of registrations) {
const child = definition(name, registration.tool)
const value = Tool.make({
description: child.description,
@@ -115,11 +111,8 @@ export const create = (options: {
(name, registration, input) =>
Effect.gen(function* () {
const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1)
const current = options.current(name)
if (!current || current.identity !== registration.identity)
return yield* Effect.fail(toolError(`Stale tool call: ${name}`))
const output = yield* settle(
current.tool,
registration.tool,
{ type: "tool-call", id: context.toolCallID, name, input },
{
sessionID: context.sessionID,
@@ -176,9 +169,12 @@ function formatResult(result: CodeMode.Result) {
: [result.error.message, ...(result.error.suggestions ?? []).filter((hint) => !result.error.message.includes(hint))]
.join("\n")
.trim()
if (!result.logs || result.logs.length === 0) return output
const logs = `Logs:\n${result.logs.join("\n")}`
return output === "" ? logs : `${output}\n\n${logs}`
const warnings =
result.ok && result.warnings && result.warnings.length > 0
? `Warnings:\n${result.warnings.map((item) => `- [${item.kind}] ${item.message}`).join("\n")}`
: undefined
const logs = result.logs && result.logs.length > 0 ? `Logs:\n${result.logs.join("\n")}` : undefined
return [output, warnings, logs].filter((part) => part !== undefined && part !== "").join("\n\n")
}
function formatValue(value: CodeMode.DataValue) {
-13
View File
@@ -194,19 +194,6 @@ export const Plugin = {
),
)
.pipe(Effect.orDie)
yield* ctx.session.hook("request", (event) =>
Effect.sync(() => {
const usePatch =
event.model.providerID.toLowerCase() === "openai" || event.model.id.toLowerCase().includes("gpt")
if (usePatch) {
delete event.tools.edit
delete event.tools.write
return
}
delete event.tools.patch
}),
)
}),
}
+20 -16
View File
@@ -22,7 +22,7 @@ Usage notes:
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`
export const Input = Schema.Struct({
questions: Schema.Array(QuestionV2.Prompt).annotate({ description: "Questions to ask" }),
questions: Schema.NonEmptyArray(QuestionV2.Prompt).annotate({ description: "Questions to ask" }),
})
export const Output = Schema.Struct({
@@ -86,21 +86,10 @@ export const Plugin = {
kind: "question",
tool: { messageID: context.assistantMessageID, callID: context.toolCallID },
},
mode: "form",
fields: input.questions.map(
(question, index): Form.Field => ({
key: `q${index}`,
title: question.header,
description: question.question,
type: question.multiple === true ? "multiselect" : "string",
options: question.options.map((option) => ({
value: option.label,
label: option.label,
description: option.description,
})),
custom: true,
}),
),
fields: [
toField(input.questions[0], 0),
...input.questions.slice(1).map((question, index) => toField(question, index + 1)),
],
})
.pipe(Effect.orDie),
),
@@ -122,3 +111,18 @@ export const Plugin = {
.pipe(Effect.orDie)
}),
}
function toField(question: QuestionV2.Prompt, index: number): Form.Field {
return {
key: `q${index}`,
title: question.header,
description: question.question,
type: question.multiple === true ? "multiselect" : "string",
options: question.options.map((option) => ({
value: option.label,
label: option.label,
description: option.description,
})),
custom: true,
}
}
+12 -39
View File
@@ -25,7 +25,7 @@ export type ExecuteInput = {
}
export interface Interface {
readonly materialize: (input: MaterializeInput) => Effect.Effect<Materialization>
readonly materialize: (permissions?: PermissionV2.Ruleset) => Effect.Effect<Materialization>
/** Internal registration capability exposed publicly only through Tools.Service. */
readonly register: (
tools: Readonly<Record<string, AnyTool>>,
@@ -33,11 +33,6 @@ export interface Interface {
) => Effect.Effect<void, RegistrationError, Scope.Scope>
}
export interface MaterializeInput {
readonly model: { readonly id: string; readonly provider: string }
readonly permissions?: PermissionV2.Ruleset
}
export interface Materialization {
readonly definitions: ReadonlyArray<ToolDefinition>
readonly settle: (input: ExecuteInput) => Effect.Effect<Settlement, ToolOutputStore.Error>
@@ -58,7 +53,6 @@ const registryLayer = Layer.effect(
const resources = yield* ToolOutputStore.Service
const toolHooks = yield* ToolHooks.Service
type Registration = {
readonly identity: object
readonly tool: AnyTool
readonly name: string
readonly group?: string
@@ -134,18 +128,6 @@ const registryLayer = Layer.effect(
}
})
const settleWith = Effect.fn("ToolRegistry.settle")(function* (input: ExecuteInput, advertised: object) {
const registration = local.get(input.call.name)?.at(-1)?.registration
if (!registration || registration.identity !== advertised) {
const message = `Stale tool call: ${input.call.name}`
return {
result: { type: "error" as const, value: message },
error: { type: "tool.stale" as const, message },
}
}
return yield* settleTool(input, registration.tool)
})
return Service.of({
register: Effect.fn("ToolRegistry.register")(function* (tools, options) {
const entries = registrationEntries(tools, options?.group)
@@ -164,7 +146,6 @@ const registryLayer = Layer.effect(
{
token,
registration: {
identity: {},
tool: entry.tool,
name: entry.name,
group: entry.group,
@@ -185,28 +166,20 @@ const registryLayer = Layer.effect(
}),
)
}),
materialize: Effect.fn("ToolRegistry.materialize")(function* (input) {
const registrations = new Map<string, Registration>()
materialize: Effect.fn("ToolRegistry.materialize")(function* (permissions) {
const direct = new Map<string, Registration>()
const deferred = new Map<string, Registration>()
const rules = permissions ?? []
for (const [name, entries] of local) {
const registration = entries.at(-1)?.registration
if (registration) registrations.set(name, registration)
if (!registration) continue
if (registration.deferred && !Flag.CODEMODE_ENABLED) continue
if (whollyDisabled(permission(registration.tool, name), rules)) continue
if (registration.deferred) deferred.set(name, registration)
else direct.set(name, registration)
}
for (const [name, registration] of registrations) {
if (
(registration.deferred && !Flag.CODEMODE_ENABLED) ||
whollyDisabled(permission(registration.tool, name), input.permissions ?? [])
)
registrations.delete(name)
}
const direct = new Map(Array.from(registrations).filter(([, registration]) => !registration.deferred))
const deferred = new Map(Array.from(registrations).filter(([, registration]) => registration.deferred))
const execute =
deferred.size > 0 && !whollyDisabled("execute", input.permissions ?? [])
? ExecuteTool.create({
registrations: deferred,
current: (name) => local.get(name)?.at(-1)?.registration,
})
: undefined
deferred.size > 0 && !whollyDisabled("execute", rules) ? ExecuteTool.create(deferred) : undefined
return {
definitions: [
...Array.from(direct, ([name, registration]) => definition(name, registration.tool)),
@@ -215,7 +188,7 @@ const registryLayer = Layer.effect(
settle: (input) => {
if (input.call.name === "execute" && execute) return settleTool(input, execute)
const registration = direct.get(input.call.name)
if (registration) return settleWith(input, registration.identity)
if (registration) return settleTool(input, registration.tool)
return Effect.succeed({
result: { type: "error", value: `Unknown tool: ${input.call.name}` },
error: { type: "tool.unknown", message: `Unknown tool: ${input.call.name}` },
-27
View File
@@ -192,32 +192,5 @@ export const Plugin = {
),
)
.pipe(Effect.orDie)
yield* ctx.session.hook("request", (event) =>
Effect.gen(function* () {
const tool = event.tools[name]
if (!tool) return
const selected = yield* agents.resolve(event.agent)
if (!selected) return
const available = (yield* agents.list())
.filter(
(agent) =>
agent.mode !== "primary" &&
!agent.hidden &&
PermissionV2.evaluate(name, agent.id, selected.permissions).effect !== "deny",
)
.toSorted((a, b) => a.id.localeCompare(b.id))
if (available.length === 0) return
tool.description = [
tool.description,
"",
"Available subagents:",
...available.map(
(agent) =>
`- ${agent.id}: ${agent.description ?? "This subagent should only be called when explicitly requested."}`,
),
].join("\n")
}),
)
}),
}
+5 -58
View File
@@ -9,12 +9,9 @@ import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { Global } from "@opencode-ai/core/global"
import { Location } from "@opencode-ai/core/location"
import { PermissionV2 } from "@opencode-ai/core/permission"
import { AgentPlugin } from "@opencode-ai/core/plugin/agent"
import { AbsolutePath } from "@opencode-ai/core/schema"
import { ConfigMigrateV1 } from "@opencode-ai/core/v1/config/migrate"
import { location } from "../fixture/location"
import { tmpdir } from "../fixture/tmpdir"
import { testEffect } from "../lib/effect"
import { agentHost, host } from "../plugin/host"
@@ -54,61 +51,16 @@ describe("ConfigAgentPlugin.Plugin", () => {
}),
)
it.effect("applies global permissions before built-in and configured agent rules", () =>
Effect.gen(function* () {
const agents = yield* AgentV2.Service
yield* AgentPlugin.Plugin.effect(host({ agent: agentHost(agents) })).pipe(
Effect.provideService(
Location.Service,
Location.Service.of(location({ directory: AbsolutePath.make("/project") })),
),
)
const config = Config.Service.of({
entries: () =>
Effect.succeed([
new Config.Document({
type: "document",
info: decode(
ConfigMigrateV1.migrate({
permission: {
bash: { "rm*": "ask", "git reset*": "ask" },
read: { "secret*": "deny" },
},
}),
),
}),
]),
})
yield* ConfigAgentPlugin.Plugin.effect(host({ agent: agentHost(agents) })).pipe(
Effect.provideService(Config.Service, config),
)
const build = yield* agents.get(AgentV2.defaultID)
const explore = yield* agents.get(AgentV2.ID.make("explore"))
if (!build || !explore) throw new Error("expected built-in agents")
expect(PermissionV2.evaluate("shell", "rm -rf tmp", build.permissions).effect).toBe("ask")
expect(PermissionV2.evaluate("shell", "rm -rf tmp", explore.permissions).effect).toBe("deny")
expect(PermissionV2.evaluate("shell", "ls", explore.permissions).effect).toBe("deny")
expect(PermissionV2.evaluate("read", "secret.txt", build.permissions).effect).toBe("deny")
expect(PermissionV2.evaluate("read", "secret.txt", explore.permissions).effect).toBe("allow")
}),
)
it.effect("applies all global permissions before agent-specific permissions", () =>
Effect.gen(function* () {
const agents = yield* AgentV2.Service
const build = AgentV2.ID.make("build")
const replacement = AgentV2.ID.make("replacement")
yield* agents.transform((editor) => {
yield* agents.transform((editor) =>
editor.update(build, (agent) => {
agent.mode = "primary"
agent.permissions.push({ action: "bash", resource: "*", effect: "allow" })
})
editor.update(replacement, (agent) => {
agent.permissions.splice(0, agent.permissions.length, { action: "bash", resource: "*", effect: "deny" })
})
})
}),
)
const config = Config.Service.of({
entries: () =>
@@ -158,18 +110,13 @@ describe("ConfigAgentPlugin.Plugin", () => {
if (!buildAgent) throw new Error("expected configured build agent")
expect(buildAgent.permissions).toEqual([
...defaultPermissions,
{ action: "bash", resource: "*", effect: "allow" },
{ action: "bash", resource: "*", effect: "ask" },
{ action: "read", resource: "*", effect: "allow" },
{ action: "bash", resource: "*", effect: "allow" },
{ action: "bash", resource: "git *", effect: "allow" },
])
expect(PermissionV2.evaluate("bash", "git status", buildAgent.permissions).effect).toBe("allow")
expect(PermissionV2.evaluate("bash", "bun test", buildAgent.permissions).effect).toBe("allow")
expect((yield* agents.get(replacement))?.permissions).toEqual([
{ action: "bash", resource: "*", effect: "ask" },
{ action: "read", resource: "*", effect: "allow" },
{ action: "bash", resource: "*", effect: "deny" },
])
expect(PermissionV2.evaluate("bash", "bun test", buildAgent.permissions).effect).toBe("ask")
const reviewer = yield* agents.get(AgentV2.ID.make("reviewer"))
if (!reviewer) throw new Error("expected configured reviewer agent")
+40
View File
@@ -254,6 +254,43 @@ describe("Config", () => {
),
)
it.live("does not watch ecosystem config roots", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
).pipe(
Effect.flatMap((tmp) =>
Effect.gen(function* () {
yield* Effect.promise(() =>
Promise.all([
fs.mkdir(path.join(tmp.path, ".claude", "skills"), { recursive: true }),
fs.mkdir(path.join(tmp.path, ".agents"), { recursive: true }),
]),
)
const targets: Watcher.WatchInput[] = []
const watcher = Layer.succeed(
Watcher.Service,
Watcher.Service.of({
subscribe: (input) => {
targets.push(input)
return Stream.never
},
}),
)
return yield* Effect.gen(function* () {
const config = yield* Config.Service
yield* config.entries()
expect(targets).toEqual([
{ type: "directory", path: AbsolutePath.make(path.join(tmp.path, "global")) },
])
}).pipe(Effect.provide(testLayer(tmp.path, undefined, undefined, undefined, watcher)))
}),
),
),
)
it.live("loads opencode JSON and JSONC files from lowest to highest priority", () =>
Effect.acquireRelease(
Effect.promise(() => tmpdir()),
@@ -915,8 +952,11 @@ describe("Config", () => {
"global",
AbsolutePath.make(global),
"root",
AbsolutePath.make(path.join(root, "opencode.json")),
"parent",
AbsolutePath.make(path.join(parent, "opencode.jsonc")),
"directory",
AbsolutePath.make(path.join(directory, "opencode.json")),
"root-dot",
AbsolutePath.make(path.join(root, ".opencode")),
"directory-dot",
+26
View File
@@ -63,6 +63,32 @@ describe("PluginSupervisor config", () => {
),
)
it.live("disables configured plugins by exported ID", () => {
const plugin = path.join(import.meta.dir, "../plugin/fixtures/config-promise-plugin.ts")
return withLocation(
{ plugins: [plugin, "-config-promise-plugin"] },
Effect.gen(function* () {
yield* ready()
const plugins = yield* PluginV2.Service
const agents = yield* AgentV2.Service
expect((yield* plugins.list()).map((item) => String(item.id))).not.toContain("config-promise-plugin")
expect(yield* agents.get(AgentV2.ID.make("configured"))).toBeUndefined()
}),
)
})
it.live("does not disable configured plugins by package target", () => {
const plugin = path.join(import.meta.dir, "../plugin/fixtures/config-promise-plugin.ts")
return withLocation(
{ plugins: [plugin, `-${plugin}`] },
Effect.gen(function* () {
yield* ready()
const plugins = yield* PluginV2.Service
expect((yield* plugins.list()).map((item) => String(item.id))).toContain("config-promise-plugin")
}),
)
})
it.live("loads configured Effect plugins with options", () =>
withLocation(
{
+71 -21
View File
@@ -15,7 +15,6 @@ const input = {
id: formID,
sessionID: SessionSchema.ID.make("ses_test"),
title: "Test form",
mode: "form",
fields: [{ key: "name", type: "string", required: true }],
} satisfies Form.CreateInput
@@ -47,7 +46,6 @@ describe("Form", () => {
const created = yield* service.create({
sessionID: "global",
title: "MCP input",
mode: "form",
fields: [{ key: "name", type: "string", required: true }],
})
expect(created.sessionID).toBe("global")
@@ -59,6 +57,14 @@ describe("Form", () => {
yield* service.reply({ id: created.id, answer: { name: "Ava" } })
expect(yield* service.state(created.id)).toEqual({ status: "answered", answer: { name: "Ava" } })
const externalOnly = yield* service.create({
sessionID: "global",
title: "External setup",
fields: [{ key: "setup", type: "external", url: "https://example.com/setup" }],
})
yield* service.reply({ id: externalOnly.id, answer: { setup: true } })
expect(yield* service.state(externalOnly.id)).toEqual({ status: "answered", answer: { setup: true } })
}),
)
@@ -68,15 +74,18 @@ describe("Form", () => {
const created = yield* service.create({
sessionID: "global",
title: "Conditional form",
mode: "form",
fields: [
{ key: "confirm", type: "boolean", required: true },
{ key: "reason", type: "string", required: true, when: [{ key: "confirm", op: "eq", value: false }] },
],
})
const inactive = yield* service.reply({ id: created.id, answer: { confirm: true, reason: "x" } }).pipe(Effect.flip)
expect(inactive).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: reason" }))
const inactive = yield* service
.reply({ id: created.id, answer: { confirm: true, reason: "x" } })
.pipe(Effect.flip)
expect(inactive).toEqual(
new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: reason" }),
)
const missing = yield* service.reply({ id: created.id, answer: { confirm: false } }).pipe(Effect.flip)
expect(missing).toEqual(
@@ -101,7 +110,6 @@ describe("Form", () => {
const created = yield* service.create({
sessionID: "global",
title: "Multiselect form",
mode: "form",
fields: [
{ key: "langs", type: "multiselect", options },
{ key: "goVersion", type: "string", required: true, when: [{ key: "langs", op: "eq", value: "go" }] },
@@ -124,7 +132,6 @@ describe("Form", () => {
const created = yield* service.create({
sessionID: "global",
title: "Dependent form",
mode: "form",
fields: [
{ key: "a", type: "boolean" },
{ key: "b", type: "boolean" },
@@ -142,7 +149,9 @@ describe("Form", () => {
})
const missingX = yield* service.reply({ id: created.id, answer: { a: true, b: true, z: "ok" } }).pipe(Effect.flip)
expect(missingX).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: x" }))
expect(missingX).toEqual(
new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: x" }),
)
const inactiveX = yield* service
.reply({ id: created.id, answer: { a: true, b: false, x: "nope", z: "ok" } })
@@ -150,7 +159,9 @@ describe("Form", () => {
expect(inactiveX).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: x" }))
const missingZ = yield* service.reply({ id: created.id, answer: { a: true, b: false } }).pipe(Effect.flip)
expect(missingZ).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: z" }))
expect(missingZ).toEqual(
new Form.InvalidAnswerError({ id: created.id, message: "Missing required form field: z" }),
)
yield* service.reply({ id: created.id, answer: { a: true, b: false, z: "ok" } })
expect(yield* service.state(created.id)).toEqual({ status: "answered", answer: { a: true, b: false, z: "ok" } })
@@ -167,7 +178,6 @@ describe("Form", () => {
const created = yield* service.create({
sessionID: "global",
title: "Selection form",
mode: "form",
fields: [
{ key: "langs", type: "multiselect", options },
{ key: "note", type: "string", required: true, when: [{ key: "langs", op: "neq", value: "go" }] },
@@ -186,7 +196,9 @@ describe("Form", () => {
)
const inactive = yield* service.reply({ id: created.id, answer: { langs: ["go"], note: "x" } }).pipe(Effect.flip)
expect(inactive).toEqual(new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: note" }))
expect(inactive).toEqual(
new Form.InvalidAnswerError({ id: created.id, message: "Form field is not active: note" }),
)
yield* service.reply({ id: created.id, answer: { langs: ["go"] } })
expect(yield* service.state(created.id)).toEqual({ status: "answered", answer: { langs: ["go"] } })
@@ -199,7 +211,6 @@ describe("Form", () => {
const created = yield* service.create({
sessionID: "global",
title: "Cascading form",
mode: "form",
fields: [
{ key: "a", type: "boolean" },
{ key: "b", type: "string", when: [{ key: "a", op: "eq", value: true }] },
@@ -220,14 +231,14 @@ describe("Form", () => {
it.effect("rejects invalid when definitions at creation", () =>
Effect.gen(function* () {
const service = yield* Form.Service
const flipCreate = (fields: ReadonlyArray<Form.Field>) =>
service.create({ sessionID: "global", title: "Invalid form", mode: "form", fields }).pipe(Effect.flip)
const flipCreate = (fields: Form.CreateInput["fields"]) =>
service.create({ sessionID: "global", title: "Invalid form", fields }).pipe(Effect.flip)
expect(
yield* flipCreate([
{ key: "b", type: "string", when: [{ key: "missing", op: "eq", value: "x" }] },
]),
).toEqual(new Form.InvalidFormError({ message: "Form field condition must reference an earlier field: b -> missing" }))
yield* flipCreate([{ key: "b", type: "string", when: [{ key: "missing", op: "eq", value: "x" }] }]),
).toEqual(
new Form.InvalidFormError({ message: "Form field condition must reference an earlier field: b -> missing" }),
)
expect(
yield* flipCreate([
@@ -236,14 +247,19 @@ describe("Form", () => {
]),
).toEqual(new Form.InvalidFormError({ message: "Duplicate form field key: a" }))
expect(
yield* flipCreate([
{ key: "a", type: "external", url: "https://example.com" },
{ key: "a", type: "string" },
]),
).toEqual(new Form.InvalidFormError({ message: "Duplicate form field key: a" }))
expect(
yield* flipCreate([
{ key: "a", type: "boolean" },
{ key: "b", type: "string", when: [{ key: "a", op: "eq", value: "yes" }] },
]),
).toEqual(
new Form.InvalidFormError({ message: "Form field condition value must be a boolean: b -> a" }),
)
).toEqual(new Form.InvalidFormError({ message: "Form field condition value must be a boolean: b -> a" }))
expect(
yield* flipCreate([
@@ -258,6 +274,40 @@ describe("Form", () => {
}),
)
it.effect("requires external field acknowledgements", () =>
Effect.gen(function* () {
const service = yield* Form.Service
const created = yield* service.create({
sessionID: "global",
title: "External setup",
fields: [
{ key: "authorization", type: "external", url: "https://example.com/setup", title: "Open setup" },
{ key: "name", type: "string", required: true },
],
})
const invalidAnswers: ReadonlyArray<Form.Answer> = [
{ name: "Ava" },
{ authorization: false, name: "Ava" },
{ authorization: "yes", name: "Ava" },
]
for (const answer of invalidAnswers) {
expect(yield* service.reply({ id: created.id, answer }).pipe(Effect.flip)).toEqual(
new Form.InvalidAnswerError({
id: created.id,
message: "External form field must be acknowledged: authorization",
}),
)
}
yield* service.reply({ id: created.id, answer: { authorization: true, name: "Ava" } })
expect(yield* service.state(created.id)).toEqual({
status: "answered",
answer: { authorization: true, name: "Ava" },
})
}),
)
it.effect("cleans up created forms when event publication fails", () =>
Effect.gen(function* () {
const service = yield* Form.Service
+6 -12
View File
@@ -13,14 +13,8 @@ export const toolIdentity = {
assistantMessageID: SessionMessage.ID.make("msg_tool_test"),
}
// Default fixture model: a non-OpenAI provider, so edit and write are the materialized edit tools.
export const testModel: ToolRegistry.MaterializeInput["model"] = { id: "claude-test", provider: "anthropic" }
export const toolDefinitions = (
registry: ToolRegistry.Interface,
permissions?: PermissionV2.Ruleset,
model = testModel,
) => registry.materialize({ permissions, model }).pipe(Effect.map((materialized) => materialized.definitions))
export const toolDefinitions = (registry: ToolRegistry.Interface, permissions?: PermissionV2.Ruleset) =>
registry.materialize(permissions).pipe(Effect.map((materialized) => materialized.definitions))
export function waitForTool(
registry: ToolRegistry.Interface,
@@ -76,8 +70,8 @@ export const registerToolPlugin = <R>(plugin: {
yield* plugin.effect(context)
})
export const settleTool = (registry: ToolRegistry.Interface, input: ToolRegistry.ExecuteInput, model = testModel) =>
registry.materialize({ model }).pipe(Effect.flatMap((materialized) => materialized.settle(input)))
export const settleTool = (registry: ToolRegistry.Interface, input: ToolRegistry.ExecuteInput) =>
registry.materialize().pipe(Effect.flatMap((materialized) => materialized.settle(input)))
export const executeTool = (registry: ToolRegistry.Interface, input: ToolRegistry.ExecuteInput, model = testModel) =>
settleTool(registry, input, model).pipe(Effect.map((settlement) => settlement.result))
export const executeTool = (registry: ToolRegistry.Interface, input: ToolRegistry.ExecuteInput) =>
settleTool(registry, input).pipe(Effect.map((settlement) => settlement.result))
+96 -8
View File
@@ -28,7 +28,7 @@ import { SessionV2 } from "@opencode-ai/core/session"
import { McpTool } from "@opencode-ai/core/tool/mcp"
import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
import { Deferred, Effect, Exit, Fiber, Layer, Stream } from "effect"
import { Deferred, Effect, Exit, Fiber, Layer, Schema, Stream } from "effect"
import { testEffect } from "./lib/effect"
import { location } from "./fixture/location"
import { settleTool, toolDefinitions, toolIdentity, waitForTool } from "./lib/tool"
@@ -47,7 +47,9 @@ type ResourceTemplatePage = {
nextCursor?: string
}
function resourceServer(input: { resources?: boolean; listChanged?: boolean } = {}) {
function resourceServer(
input: { resources?: boolean; listChanged?: boolean; emptyElicitation?: boolean; urlElicitation?: boolean } = {},
) {
return Effect.acquireRelease(
Effect.promise(async () => {
const state = {
@@ -71,7 +73,42 @@ function resourceServer(input: { resources?: boolean; listChanged?: boolean } =
},
},
)
protocol.setRequestHandler(ListToolsRequestSchema, () => Promise.resolve({ tools: [] }))
protocol.setRequestHandler(ListToolsRequestSchema, () =>
Promise.resolve({
tools: input.emptyElicitation
? [{ name: "empty-elicitation", inputSchema: { type: "object" as const, properties: {} } }]
: input.urlElicitation
? [{ name: "url-elicitation", inputSchema: { type: "object" as const, properties: {} } }]
: [],
}),
)
if (input.emptyElicitation) {
protocol.setRequestHandler(CallToolRequestSchema, async () => {
const result = await protocol.elicitInput({
mode: "form",
message: "Confirm",
requestedSchema: { type: "object", properties: {} },
})
return {
content: [{ type: "text", text: JSON.stringify(result) }],
structuredContent: result,
}
})
}
if (input.urlElicitation) {
protocol.setRequestHandler(CallToolRequestSchema, async () => {
const result = await protocol.elicitInput({
mode: "url",
message: "Authorize access",
url: "https://example.com/authorize",
elicitationId: "elicitation-test",
})
return {
content: [{ type: "text", text: JSON.stringify(result) }],
structuredContent: result,
}
})
}
if (input.resources !== false) {
protocol.setRequestHandler(ListResourcesRequestSchema, (request) => {
state.resourceLists += 1
@@ -98,6 +135,7 @@ function resourceServer(input: { resources?: boolean; listChanged?: boolean } =
state,
url: http.url.toString(),
sendResourceListChanged: () => protocol.sendResourceListChanged(),
completeElicitation: () => protocol.createElicitationCompletionNotifier("elicitation-test")(),
close: async () => {
await protocol.close().catch(() => {})
await http.stop(true)
@@ -108,10 +146,11 @@ function resourceServer(input: { resources?: boolean; listChanged?: boolean } =
)
}
function resourceMcpLayer(url: string) {
function resourceMcpLayer(url: string, onFormCreated?: (form: Form.Info) => Effect.Effect<void>) {
const directory = AbsolutePath.make(import.meta.dir)
const unusedIntegration = () => Effect.die("unused integration service")
return MCP.layer.pipe(
Layer.provideMerge(Form.layer),
Layer.provide(
Layer.mergeAll(
Layer.succeed(
@@ -133,14 +172,16 @@ function resourceMcpLayer(url: string) {
Layer.succeed(Location.Service, Location.Service.of(location({ directory }))),
Layer.mock(EventV2.Service, {
subscribe: () => Stream.never,
publish: (definition, data) =>
Effect.succeed({
publish: (definition, data) => {
const event = {
id: EventV2.ID.create(),
type: definition.type,
data,
} as EventV2.Payload<typeof definition>),
} as EventV2.Payload<typeof definition>
if (event.type !== Form.Event.Created.type || !onFormCreated) return Effect.succeed(event)
return onFormCreated(Schema.decodeUnknownSync(Form.Event.Created.data)(data).form).pipe(Effect.as(event))
},
}),
Layer.mock(Form.Service, {}),
Layer.mock(Integration.Service, {
connection: {
active: unusedIntegration,
@@ -490,6 +531,53 @@ test("skips MCP resource requests when the capability is absent", async () => {
)
})
test("accepts empty MCP elicitations without creating forms", async () => {
await Effect.runPromise(
Effect.scoped(
Effect.gen(function* () {
const server = yield* resourceServer({ resources: false, emptyElicitation: true })
const result = yield* Effect.gen(function* () {
const service = yield* MCP.Service
const forms = yield* Form.Service
const result = yield* service.callTool({ server: "resources", name: "empty-elicitation" })
expect(yield* forms.list()).toEqual([])
return result
}).pipe(Effect.provide(resourceMcpLayer(server.url)))
expect(result.structured).toEqual({ action: "accept", content: {} })
}),
),
)
})
test("acknowledges completed MCP URL elicitations without returning internal content", async () => {
await Effect.runPromise(
Effect.scoped(
Effect.gen(function* () {
const server = yield* resourceServer({ resources: false, urlElicitation: true })
const created = yield* Deferred.make<Form.Info>()
const result = yield* Effect.gen(function* () {
const service = yield* MCP.Service
const forms = yield* Form.Service
const call = yield* service.callTool({ server: "resources", name: "url-elicitation" }).pipe(Effect.forkScoped)
const form = yield* Deferred.await(created)
expect(form.fields).toEqual([{ key: "elicitation", type: "external", url: "https://example.com/authorize" }])
yield* Effect.promise(server.completeElicitation)
const result = yield* Fiber.join(call)
expect(yield* forms.state(form.id)).toEqual({ status: "answered", answer: { elicitation: true } })
return result
}).pipe(
Effect.provide(resourceMcpLayer(server.url, (form) => Deferred.succeed(created, form).pipe(Effect.asVoid))),
)
expect(result.structured).toEqual({ action: "accept" })
}),
),
)
})
test("loads and reads MCP resources", async () => {
await Effect.runPromise(
Effect.scoped(
-47
View File
@@ -1,47 +0,0 @@
import { describe, expect, it } from "bun:test"
import { Message, SystemPart } from "@opencode-ai/llm"
import { Agent } from "@opencode-ai/schema/agent"
import { Model } from "@opencode-ai/schema/model"
import { Provider } from "@opencode-ai/schema/provider"
import { Session } from "@opencode-ai/schema/session"
import { Effect, Layer } from "effect"
import { PluginHooks } from "../src/plugin/hooks"
describe("PluginHooks", () => {
it("registers scoped domain hooks and triggers them sequentially", async () => {
const seen: string[] = []
const program = Effect.gen(function* () {
const hooks = yield* PluginHooks.Service
yield* hooks.register("session", "request", (event) =>
Effect.sync(() => {
seen.push("first")
event.system.push(SystemPart.make("second"))
}),
)
yield* hooks.register("session", "request", (event) =>
Effect.sync(() => {
seen.push(event.system[1]?.text ?? "missing")
event.messages = [Message.user("changed")]
}),
)
const event = {
sessionID: Session.ID.make("ses_hooks"),
agent: Agent.ID.make("build"),
model: Model.Ref.make({ providerID: Provider.ID.make("test"), id: Model.ID.make("model") }),
system: [SystemPart.make("first")],
messages: [Message.user("original")],
tools: {},
}
expect(yield* hooks.trigger("session", "request", event)).toBe(event)
expect(seen).toEqual(["first", "second"])
expect(event.messages).toEqual([Message.user("changed")])
})
await Effect.runPromise(
Effect.scoped(program).pipe(
Effect.provide(PluginHooks.node.implementation as Layer.Layer<PluginHooks.Service>),
),
)
})
})
+4 -9
View File
@@ -12,7 +12,6 @@ import { SessionMessage } from "@opencode-ai/core/session/message"
import { Tool } from "@opencode-ai/core/tool/tool"
import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { testEffect } from "./lib/effect"
import { testModel } from "./lib/tool"
import { PluginTestLayer } from "./plugin/fixture"
const it = testEffect(PluginTestLayer)
@@ -255,14 +254,10 @@ describe("PluginV2", () => {
})
yield* plugins.activate([plugin])
expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toContain(
"plugin_tool",
)
expect((yield* registry.materialize()).definitions.map((tool) => tool.name)).toContain("plugin_tool")
yield* plugins.activate([])
expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).not.toContain(
"plugin_tool",
)
expect((yield* registry.materialize()).definitions.map((tool) => tool.name)).not.toContain("plugin_tool")
}),
)
@@ -291,7 +286,7 @@ describe("PluginV2", () => {
yield* plugins.activate([plugin])
expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toEqual([
expect((yield* registry.materialize()).definitions.map((tool) => tool.name)).toEqual([
"plain",
"context_7_look_up",
"execute",
@@ -350,7 +345,7 @@ describe("PluginV2", () => {
yield* plugins.activate([plugin])
const materialized = yield* registry.materialize({ model: testModel })
const materialized = yield* registry.materialize()
const settlement = yield* materialized.settle({
sessionID: SessionV2.ID.make("ses_hooks"),
agent: AgentV2.ID.make("build"),
-3
View File
@@ -83,9 +83,6 @@ export function host(overrides: Overrides = {}): PluginContext {
prompt: () => Effect.die("unused session.prompt"),
command: () => Effect.die("unused session.command"),
interrupt: () => Effect.die("unused session.interrupt"),
// Plugins register session hooks during setup, so a bare host accepts the
// registration; the callback only runs when a test triggers the request pipeline.
hook: () => Effect.succeed({ dispose: Effect.void }),
},
}
}
+66 -1
View File
@@ -1,9 +1,12 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { Effect, Schema } from "effect"
import { AgentV2 } from "@opencode-ai/core/agent"
import { PluginV2 } from "@opencode-ai/core/plugin"
import { PluginHost } from "@opencode-ai/core/plugin/host"
import { PluginPromise } from "@opencode-ai/core/plugin/promise"
import { SessionV2 } from "@opencode-ai/core/session"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { Plugin } from "@opencode-ai/plugin/v2"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
@@ -93,4 +96,66 @@ describe("fromPromise", () => {
expect(yield* agents.get(AgentV2.ID.make("temp"))).toBeUndefined()
}),
)
it.effect("runs the setup cleanup when the plugin scope closes", () =>
Effect.gen(function* () {
const plugin = yield* PluginV2.Service
const host = yield* PluginHost.make(plugin)
const events: string[] = []
const promisePlugin = Plugin.define({
id: "promise-cleanup",
setup: async () => {
events.push("setup")
return async () => {
await Promise.resolve()
events.push("cleanup")
}
},
})
yield* Effect.scoped(
Effect.gen(function* () {
yield* PluginPromise.fromPromise(promisePlugin).effect(host)
expect(events).toEqual(["setup"])
}),
)
expect(events).toEqual(["setup", "cleanup"])
}),
)
it.effect("constructs plain Promise tool declarations in the host", () =>
Effect.gen(function* () {
const plugins = yield* PluginV2.Service
const registry = yield* ToolRegistry.Service
const host = yield* PluginHost.make(plugins)
const promisePlugin = Plugin.define({
id: "promise-tool",
setup: async (ctx) => {
await ctx.tool.transform((tools) => {
tools.add({
name: "hello",
description: "Hello",
input: Schema.Struct({ name: Schema.String }),
output: Schema.String,
execute: async ({ name }) => `Hello, ${name}!`,
})
})
},
})
yield* PluginPromise.fromPromise(promisePlugin).effect(host)
const materialized = yield* registry.materialize()
expect(materialized.definitions).toContainEqual(expect.objectContaining({ name: "hello", description: "Hello" }))
expect(
yield* materialized.settle({
sessionID: SessionV2.ID.make("ses_promise_tool"),
agent: AgentV2.ID.make("build"),
assistantMessageID: SessionMessage.ID.make("msg_promise_tool"),
call: { type: "tool-call", id: "call_promise_tool", name: "hello", input: { name: "world" } },
}),
).toMatchObject({ result: { type: "text", value: "Hello, world!" } })
}),
)
})
@@ -147,10 +147,11 @@ it.effect("manual compaction summarizes short context instead of no-op", () =>
messages: [userMessage],
inputID: SessionMessage.ID.make("msg_manual_compaction"),
}),
).toBe(true)
).toEqual({ status: "completed" })
expect(Array.from(yield* Fiber.join(delta)).map((event) => event.data.text)).toEqual(["manual summary"])
expect(requests).toHaveLength(1)
expect(requests[0]?.generation).toBeUndefined()
expect(JSON.stringify(requests[0]?.messages)).toContain("Manual compaction should include this short conversation.")
expect(yield* store.context(sessionID)).toMatchObject([
{ type: "compaction", reason: "manual", summary: "manual summary", recent: "" },
+5
View File
@@ -16,6 +16,7 @@ import {
ToolFailure,
} from "@opencode-ai/llm"
import { PermissionV2 } from "@opencode-ai/core/permission"
import { Tool } from "@opencode-ai/plugin/v2/effect/tool"
import { toSessionError } from "@opencode-ai/core/session/to-session-error"
import { SessionRunnerRetry } from "@opencode-ai/core/session/runner/retry"
@@ -64,6 +65,10 @@ describe("toSessionError", () => {
type: "permission.rejected",
message: "Permission denied: external_directory",
})
expect(toSessionError(new Tool.Failure({ message: "failed" }))).toEqual({
type: "tool.execution",
message: "failed",
})
})
test("retries only rate limits, provider-internal failures, and transport failures", () => {
@@ -34,7 +34,7 @@ import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { tempLocationLayer } from "./fixture/location"
import { makeLocationNode } from "@opencode-ai/core/effect/app-node"
import { testEffect } from "./lib/effect"
import { registerToolPlugin, settleTool, testModel } from "./lib/tool"
import { registerToolPlugin, settleTool } from "./lib/tool"
const readToolNode = makeLocationNode({
name: "test/read-tool-plugin",
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test"
import { Effect, Schema, Stream } from "effect"
import { Effect, Schema } from "effect"
import { LLMEvent } from "@opencode-ai/llm"
import { Money } from "@opencode-ai/schema/money"
import { EventV2 } from "@opencode-ai/core/event"
@@ -16,7 +16,7 @@ const base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB"
const capture = (providerMetadataKey = "anthropic") => {
const published: Array<{ readonly type: string; readonly data: unknown }> = []
const events = EventV2.Service.of({
const events: Pick<EventV2.Interface, "publish"> = {
publish: (definition, data) =>
Effect.sync(() => {
const event = { id: EventV2.ID.create(), type: definition.type, data } as EventV2.Payload<typeof definition>
@@ -28,16 +28,7 @@ const capture = (providerMetadataKey = "anthropic") => {
})
return event
}),
subscribe: () => Stream.empty,
log: () => Stream.empty,
sequences: () => Effect.succeed(new Map()),
listen: () => Effect.succeed(Effect.void),
project: () => Effect.void,
replay: () => Effect.void,
replayAll: () => Effect.succeed(undefined),
remove: () => Effect.void,
claim: () => Effect.void,
})
}
return {
published,
publisher: createLLMEventPublisher(events, {
@@ -7,7 +7,7 @@ import { SessionV2 } from "@opencode-ai/core/session"
import { SessionMessage } from "@opencode-ai/core/session/message"
import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { executeTool, settleTool, testModel, toolDefinitions } from "./lib/tool"
import { executeTool, settleTool, toolDefinitions } from "./lib/tool"
import { Cause, Deferred, Effect, Exit, Fiber, Layer, Option, Schema, SchemaGetter, SchemaIssue, Scope } from "effect"
import { testEffect } from "./lib/effect"
@@ -52,6 +52,15 @@ const make = (permission?: string) => {
return permission ? Tool.withPermission(tool, permission) : tool
}
const constant = (text: string) =>
Tool.make({
description: "Return text",
input: Schema.Struct({ text: Schema.String }),
output: Schema.Struct({ text: Schema.String }),
execute: () => Effect.succeed({ text }),
toModelOutput: ({ output }) => [{ type: "text" as const, text: output.text }],
})
describe("ToolRegistry", () => {
it.effect("filters disabled tools with edit aliases and ordered wildcard precedence", () =>
Effect.gen(function* () {
@@ -82,30 +91,6 @@ describe("ToolRegistry", () => {
}),
)
it.effect("materializes all permission-eligible edit tools before request policy", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
yield* service.register({
read: make(),
edit: make("edit"),
write: make("edit"),
patch: make("edit"),
})
const names = (model: ToolRegistry.MaterializeInput["model"]) =>
service
.materialize({ model })
.pipe(Effect.map((materialized) => materialized.definitions.map((tool) => tool.name)))
expect(yield* names({ id: "gpt-5", provider: "openai" })).toEqual(["read", "edit", "write", "patch"])
expect(yield* names({ id: "claude-sonnet-4", provider: "anthropic" })).toEqual([
"read",
"edit",
"write",
"patch",
])
}),
)
it.effect("keeps permission decoration isolated between registrations", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
@@ -122,7 +107,7 @@ describe("ToolRegistry", () => {
}),
)
it.effect("reuses model definitions across provider turns", () =>
it.effect("reuses model definitions across requests", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
yield* service.register({ echo: make() })
@@ -201,7 +186,7 @@ describe("ToolRegistry", () => {
}),
})
expect(
yield* service.materialize({ model: testModel }).pipe(
yield* service.materialize().pipe(
Effect.flatMap((materialized) =>
materialized.settle({
sessionID,
@@ -219,7 +204,7 @@ describe("ToolRegistry", () => {
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
yield* service.register({ echo: make() })
const materialized = yield* service.materialize({ model: testModel })
const materialized = yield* service.materialize()
const exit = yield* materialized.settle(call("echo", "call-retention-failure")).pipe(Effect.exit)
expect(Exit.isFailure(exit)).toBe(true)
@@ -345,88 +330,77 @@ describe("ToolRegistry", () => {
}),
)
it.effect("executes the unchanged registration advertised for a provider turn", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
yield* service.register({ echo: make() })
const materialized = yield* service.materialize({ model: testModel })
expect((yield* materialized.settle(call("echo"))).result).toEqual({ type: "text", value: "echo" })
}),
)
it.effect("rejects a call when its advertised registration was removed", () =>
it.effect("executes the tool advertised in a model request", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
const scope = yield* Scope.make()
yield* service.register({ echo: make() }).pipe(Scope.provide(scope))
const materialized = yield* service.materialize({ model: testModel })
yield* service.register({ echo: constant("advertised") }).pipe(Scope.provide(scope))
const request = yield* service.materialize()
yield* Scope.close(scope, Exit.void)
yield* service.register({ echo: constant("replacement") })
expect((yield* materialized.settle(call("echo"))).result).toEqual({
type: "error",
value: "Stale tool call: echo",
})
expect((yield* request.settle(call("echo"))).result).toEqual({ type: "text", value: "advertised" })
expect(yield* executeTool(service, call("echo"))).toEqual({ type: "text", value: "replacement" })
}),
)
it.effect("rejects only the replaced name from a multi-tool provider turn", () =>
it.effect("reveals the previous registration after an overlay closes", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
yield* service.register({ first: make(), second: make() })
const materialized = yield* service.materialize({ model: testModel })
yield* service.register({ first: make() })
expect((yield* materialized.settle(call("first"))).result).toEqual({
type: "error",
value: "Stale tool call: first",
})
expect((yield* materialized.settle(call("second"))).result).toEqual({ type: "text", value: "second" })
}),
)
it.effect("treats revealing a previous overlay as stale", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
yield* service.register({ echo: make() })
yield* service.register({ echo: constant("base") })
const overlay = yield* Scope.make()
yield* service.register({ echo: make() }).pipe(Scope.provide(overlay))
const materialized = yield* service.materialize({ model: testModel })
yield* Scope.close(overlay, Exit.void)
yield* service.register({ echo: constant("overlay") }).pipe(Scope.provide(overlay))
expect((yield* materialized.settle(call("echo"))).result).toEqual({
type: "error",
value: "Stale tool call: echo",
})
expect(yield* executeTool(service, call("echo"))).toEqual({ type: "text", value: "overlay" })
yield* Scope.close(overlay, Exit.void)
expect(yield* executeTool(service, call("echo"))).toEqual({ type: "text", value: "base" })
}),
)
it.effect("keeps captured execution running after registration mutation", () =>
it.effect("executes deferred tools advertised in a model request", () =>
Effect.gen(function* () {
const service = yield* ToolRegistry.Service
const started = yield* Deferred.make<void>()
const release = yield* Deferred.make<void>()
const executed: string[] = []
const scope = yield* Scope.make()
yield* service
.register({
.register(
{
echo: Tool.make({
description: "Echo text",
input: Schema.Struct({ text: Schema.String }),
output: Schema.Struct({ text: Schema.String }),
execute: ({ text }) => Effect.sync(() => executed.push(`old:${text}`)).pipe(Effect.as({ text })),
}),
},
{ deferred: true },
)
.pipe(Scope.provide(scope))
const materialized = yield* service.materialize()
yield* Scope.close(scope, Exit.void)
yield* service.register(
{
echo: Tool.make({
description: "Echo text",
input: Schema.Struct({ text: Schema.String }),
output: Schema.Struct({ text: Schema.String }),
execute: ({ text }) =>
Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(release)), Effect.as({ text })),
toModelOutput: ({ output }) => [{ type: "text", text: output.text }],
execute: ({ text }) => Effect.sync(() => executed.push(`new:${text}`)).pipe(Effect.as({ text })),
}),
})
.pipe(Scope.provide(scope))
const materialized = yield* service.materialize({ model: testModel })
const settlement = yield* materialized.settle(call("echo")).pipe(Effect.forkChild)
yield* Deferred.await(started)
yield* Scope.close(scope, Exit.void)
yield* service.register({ echo: make() })
yield* Deferred.succeed(release, undefined)
},
{ deferred: true },
)
expect(yield* Fiber.join(settlement)).toMatchObject({ result: { type: "text", value: "echo" } })
const settlement = yield* materialized.settle({
...call("execute"),
call: {
type: "tool-call",
id: "call-execute",
name: "execute",
input: { code: 'return await tools.echo({ text: "request" })' },
},
})
expect(settlement.result).toMatchObject({ type: "text" })
expect(executed).toEqual(["old:request"])
}),
)
})
+234 -19
View File
@@ -62,7 +62,7 @@ import { McpGuidance } from "@opencode-ai/core/mcp/guidance"
import { ModelV2 } from "@opencode-ai/core/model"
import { Location } from "@opencode-ai/core/location"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Schema, Stream } from "effect"
import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Schema, Scope, Stream } from "effect"
import { TestClock } from "effect/testing"
import { asc, eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
@@ -113,6 +113,16 @@ const reply = {
LLMEvent.finish({ reason: "stop" }),
],
text: (text: string, id: string) => fragmentFixture("text", id, [text]).completeEvents,
textWithUsage: (text: string, id: string, inputTokens: number) =>
fragmentFixture("text", id, [text]).completeEvents.map((event) =>
LLMEvent.is.stepFinish(event)
? LLMEvent.stepFinish({
index: event.index,
reason: event.reason,
usage: { inputTokens, nonCachedInputTokens: inputTokens },
})
: event,
),
tool: (id: string, name: string, input: unknown) => [
LLMEvent.stepStart({ index: 0 }),
LLMEvent.toolCall({ id, name, input }),
@@ -128,6 +138,11 @@ const compactModel = Model.make({
provider: "fake",
route: OpenAIChat.route.with({ limits: { context: 4_000, output: 50 } }),
})
const undersizedContextModel = Model.make({
id: "undersized-context",
provider: "fake",
route: OpenAIChat.route.with({ limits: { context: 1, output: 1_000 } }),
})
const recoveryModel = Model.make({
id: "recovery",
provider: "fake",
@@ -783,7 +798,67 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("starts a real runner turn after default prompt recording", () =>
it.effect("executes the tool advertised before a registry reload", () =>
Effect.gen(function* () {
const session = yield* setup
const registry = yield* ToolRegistry.Service
const scope = yield* Scope.make()
const executions: string[] = []
yield* registry
.register({
reloaded: Tool.make({
description: "Record the advertised tool",
input: Schema.Struct({}),
output: Schema.Struct({ value: Schema.String }),
execute: () => Effect.sync(() => executions.push("advertised")).pipe(Effect.as({ value: "advertised" })),
}),
})
.pipe(Scope.provide(scope))
yield* admit(session, "Use the reloaded tool")
responses = [
[
LLMEvent.stepStart({ index: 0 }),
LLMEvent.toolCall({ id: "call-reloaded", name: "reloaded", input: {} }),
LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
LLMEvent.finish({ reason: "tool-calls" }),
],
[],
]
streamGate = yield* Deferred.make<void>()
streamStarted = yield* Deferred.make<void>()
const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
yield* Deferred.await(streamStarted)
yield* Scope.close(scope, Exit.void)
yield* registry.register({
reloaded: Tool.make({
description: "Record the replacement tool",
input: Schema.Struct({}),
output: Schema.Struct({ value: Schema.String }),
execute: () => Effect.sync(() => executions.push("replacement")).pipe(Effect.as({ value: "replacement" })),
}),
})
yield* Deferred.succeed(streamGate, undefined)
yield* Fiber.join(run)
expect(executions).toEqual(["advertised"])
expect(yield* session.context(sessionID)).toMatchObject([
{ type: "user", text: "Use the reloaded tool" },
{
type: "assistant",
content: [
{
type: "tool",
id: "call-reloaded",
state: { status: "completed", structured: { value: "advertised" } },
},
],
},
])
}),
)
it.effect("starts a real runner step after default prompt recording", () =>
Effect.gen(function* () {
const session = yield* setup
@@ -847,7 +922,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("retries the first provider turn after system context becomes available", () =>
it.effect("retries the first request after system context becomes available", () =>
Effect.gen(function* () {
const session = yield* setup
const { db } = yield* Database.Service
@@ -1518,11 +1593,12 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("settles an admitted manual compaction that cannot start", () =>
it.effect("explains when manual compaction has no history", () =>
Effect.gen(function* () {
yield* setup
const session = yield* SessionV2.Service
const compaction = yield* session.compact({ sessionID })
modelResolveHook = Effect.die("model resolution should not run")
yield* session.resume(sessionID)
@@ -1531,7 +1607,7 @@ describe("SessionRunnerLLM", () => {
type: "compaction",
status: "failed",
reason: "manual",
error: { message: "Compaction could not start" },
error: { type: "compaction.unavailable", message: "Nothing to compact yet" },
})
expect(
(yield* recordedEventTypes(sessionID)).filter(
@@ -1541,10 +1617,73 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("manually compacts when the model has no context limit", () =>
Effect.gen(function* () {
const session = yield* setup
response = reply.text("Earlier answer", "text-manual-unknown-history")
yield* admit(session, "Earlier question")
yield* session.resume(sessionID)
requests.length = 0
response = reply.text("Manual summary", "text-manual-unknown-summary")
const compaction = yield* session.compact({ sessionID })
yield* session.resume(sessionID)
expect(requests).toHaveLength(1)
expect(userTexts(requests[0])[0]).toContain("Earlier question")
expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
type: "compaction",
status: "completed",
summary: "Manual summary",
})
}),
)
it.effect("preserves provider errors from manual compaction", () =>
Effect.gen(function* () {
const session = yield* setup
response = reply.text("Earlier answer", "text-manual-provider-history")
yield* admit(session, "Earlier question")
yield* session.resume(sessionID)
response = [LLMEvent.providerError({ message: "summary unavailable" })]
const compaction = yield* session.compact({ sessionID })
yield* session.resume(sessionID)
expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
type: "compaction",
status: "failed",
error: { type: "provider.error", message: "summary unavailable" },
})
}),
)
it.effect("preserves typed provider failures from manual compaction", () =>
Effect.gen(function* () {
const session = yield* setup
response = reply.text("Earlier answer", "text-manual-failure-history")
yield* admit(session, "Earlier question")
yield* session.resume(sessionID)
responseStream = Stream.fail(providerUnavailable())
const compaction = yield* session.compact({ sessionID })
yield* session.resume(sessionID)
expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
type: "compaction",
status: "failed",
error: { type: "provider.transport", message: "Provider unavailable" },
})
}),
)
it.effect("settles an admitted manual compaction when pre-start resolution throws", () =>
Effect.gen(function* () {
yield* setup
const session = yield* SessionV2.Service
const session = yield* setup
response = reply.text("Earlier answer", "text-manual-resolution-history")
yield* admit(session, "Earlier question")
yield* session.resume(sessionID)
const compaction = yield* session.compact({ sessionID })
modelResolveHook = Effect.die("model resolution failed")
@@ -1567,7 +1706,7 @@ describe("SessionRunnerLLM", () => {
it.effect("automatically compacts into a completed summary and retained recent turn", () =>
Effect.gen(function* () {
const session = yield* setup
response = reply.text("Earlier answer", "text-first")
response = reply.textWithUsage("Earlier answer", "text-first", 3_950)
yield* admit(session, "Earlier question ".repeat(180))
yield* session.resume(sessionID)
@@ -1575,7 +1714,7 @@ describe("SessionRunnerLLM", () => {
requests.length = 0
responses = [
reply.text("## Objective\n- Preserve the task", "text-summary"),
reply.text("Continued", "text-final"),
reply.textWithUsage("Continued", "text-final", 3_950),
]
yield* admit(session, "Recent exact request ".repeat(180))
yield* session.resume(sessionID)
@@ -1614,6 +1753,35 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("stops after required automatic compaction fails", () =>
Effect.gen(function* () {
const session = yield* setup
response = reply.textWithUsage("Earlier answer", "text-before-failed-compaction", 3_950)
yield* admit(session, "Earlier question ".repeat(180))
yield* session.resume(sessionID)
currentModel = compactModel
requests.length = 0
responses = [
[LLMEvent.providerError({ message: "Unsupported parameter: max_output_tokens" })],
reply.text("Must not run", "text-after-failed-compaction"),
]
yield* admit(session, "Recent exact request ".repeat(180))
expect(yield* Effect.exit(session.resume(sessionID))).toMatchObject({ _tag: "Failure" })
expect(requests).toHaveLength(1)
expect(requests[0]?.generation).toBeUndefined()
expect(yield* session.context(sessionID)).toContainEqual(
expect.objectContaining({
type: "compaction",
status: "failed",
reason: "auto",
error: expect.objectContaining({ message: "Unsupported parameter: max_output_tokens" }),
}),
)
}),
)
it.effect("forces one compaction and retries after provider context overflow", () =>
Effect.gen(function* () {
const session = yield* setupOverflowRecovery
@@ -1643,6 +1811,46 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("recovers from provider context overflow without a configured context limit", () =>
Effect.gen(function* () {
const session = yield* setupOverflowRecovery
currentModel = model
responses = [
[LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
reply.text("## Objective\n- Recover unknown limit", "text-summary-unknown-limit"),
reply.text("Recovered", "text-final-unknown-limit"),
]
yield* admit(session, "Continue")
yield* session.resume(sessionID)
expect(requests).toHaveLength(3)
expect(yield* session.context(sessionID)).toMatchObject([
{ type: "compaction", summary: "## Objective\n- Recover unknown limit" },
{ type: "assistant", finish: "stop" },
])
}),
)
it.effect("recovers from provider context overflow despite an undersized configured context limit", () =>
Effect.gen(function* () {
const session = yield* setupOverflowRecovery
currentModel = undersizedContextModel
responses = [
[LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
reply.text("## Objective\n- Recover undersized limit", "text-summary-undersized-limit"),
reply.text("Recovered", "text-final-undersized-limit"),
]
yield* admit(session, "Continue")
yield* session.resume(sessionID)
expect(requests).toHaveLength(3)
expect(yield* session.context(sessionID)).toMatchObject([
{ type: "compaction", summary: "## Objective\n- Recover undersized limit" },
{ type: "assistant", finish: "stop" },
])
}),
)
it.effect("persists a second context overflow after one recovery", () =>
Effect.gen(function* () {
const session = yield* setupOverflowRecovery
@@ -1702,7 +1910,14 @@ describe("SessionRunnerLLM", () => {
expect(requests).toHaveLength(2)
const context = yield* session.context(sessionID)
expect(context).toContainEqual(expect.objectContaining({ type: "compaction", status: "failed", reason: "auto" }))
expect(context).toContainEqual(
expect.objectContaining({
type: "compaction",
status: "failed",
reason: "auto",
error: { type: "provider.error", message: "summary unavailable" },
}),
)
expect(context.slice(-3)).toMatchObject([
{ type: "user", text: "Continue" },
{ type: "compaction", status: "failed", reason: "auto" },
@@ -1910,7 +2125,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("reloads a model switch before a tool-driven continuation turn", () =>
it.effect("reloads a model switch before a tool-driven continuation step", () =>
Effect.gen(function* () {
const session = yield* setup
const events = yield* EventV2.Service
@@ -1939,7 +2154,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("restores durable reasoning provider metadata in a second-turn request", () =>
it.effect("restores durable reasoning provider metadata in the next request", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Think first")
@@ -2011,7 +2226,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("replays durable provider-executed tool results inline in a second-turn request", () =>
it.effect("replays durable provider-executed tool results inline in the next request", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Search first")
@@ -2223,7 +2438,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("steers an active provider turn with newly recorded prompts", () =>
it.effect("steers an active step with newly recorded prompts", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Start working")
@@ -2443,7 +2658,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("coalesces multiple active steering prompts into one continuation turn", () =>
it.effect("coalesces multiple active steering prompts into one continuation step", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Start working")
@@ -2470,7 +2685,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("runs steering input accepted while the active provider turn fails", () =>
it.effect("runs steering input accepted while the active step fails", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Start working")
@@ -2543,7 +2758,7 @@ describe("SessionRunnerLLM", () => {
id: "call-interrupted",
state: {
status: "error",
error: { type: "tool.stale", message: "Tool execution interrupted: echo" },
error: { type: "aborted", message: "Tool execution interrupted: echo" },
},
},
],
@@ -3107,7 +3322,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("durably fails blocked local tools when a provider turn is interrupted", () =>
it.effect("durably fails blocked local tools when a step is interrupted", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Interrupt blocked tool")
@@ -3163,7 +3378,7 @@ describe("SessionRunnerLLM", () => {
}),
)
it.effect("interrupts a blocked provider turn without local tool execution", () =>
it.effect("interrupts a blocked step without local tool execution", () =>
Effect.gen(function* () {
const session = yield* setup
yield* admit(session, "Interrupt provider")
+47
View File
@@ -0,0 +1,47 @@
import { expect, test } from "bun:test"
import { ExecuteTool } from "@opencode-ai/core/tool/execute"
import { Tool } from "@opencode-ai/core/tool/tool"
import { Agent } from "@opencode-ai/schema/agent"
import { Session } from "@opencode-ai/schema/session"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { Effect, Schema } from "effect"
test("execute preserves successful results with visible unhandled rejections", async () => {
const child = Tool.make({
description: "Always fail",
input: Schema.Struct({}),
output: Schema.String,
execute: () => Effect.fail(new Tool.Failure({ message: "Lookup refused" })),
})
const execute = ExecuteTool.create(new Map([["fail", { tool: child, name: "fail" }]]))
const result = await Effect.runPromise(
Tool.settle(
execute,
{
type: "tool-call",
id: "call_execute",
name: "execute",
input: { code: `tools.fail({}); return "done"` },
},
{
sessionID: Session.ID.make("ses_execute"),
agent: Agent.ID.make("build"),
assistantMessageID: SessionMessage.ID.make("msg_execute"),
toolCallID: "call_execute",
},
),
)
expect(result.structured).toEqual({ toolCalls: [{ tool: "fail", status: "error" }] })
expect(result.content).toEqual([
{
type: "text",
text: [
"done",
"",
"Warnings:",
"- [ToolFailure] Unhandled rejection from an un-awaited promise: Lookup refused",
].join("\n"),
},
])
})
+1 -15
View File
@@ -135,9 +135,6 @@ const call = (patchText: string, id = "call-patch") => ({
call: { type: "tool-call" as const, id, name: "patch", input: { patchText } },
})
// patch is only materialized for OpenAI/GPT models.
const model = { id: "gpt-5", provider: "openai" }
const exists = (target: string) =>
Effect.promise(() =>
fs.stat(target).then(
@@ -161,15 +158,12 @@ describe("PatchTool", () => {
Effect.andThen(
withTool(tmp.path, (registry) =>
Effect.gen(function* () {
expect((yield* toolDefinitions(registry, undefined, model)).map((tool) => tool.name)).toEqual([
"patch",
])
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["patch"])
const settled = yield* settleTool(
registry,
call(
"*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Update File: update.txt\n@@\n-before\n+after\n*** Delete File: remove.txt\n*** End Patch",
),
model,
)
expect(settled.result).toEqual({
type: "text",
@@ -239,7 +233,6 @@ describe("PatchTool", () => {
call(
"*** Begin Patch\n*** Add File: created.txt\n+created\n*** Update File: old.txt\n*** Move to: moved.txt\n@@\n-before\n+after\n*** End Patch",
),
model,
),
).toEqual({ type: "error", value: "patch moves are not supported yet" })
expect(yield* exists(path.join(tmp.path, "created.txt"))).toBe(false)
@@ -267,7 +260,6 @@ describe("PatchTool", () => {
yield* executeTool(
registry,
call(`*** Begin Patch\n*** Update File: ${target}\n@@\n-before\n+after\n*** End Patch`),
model,
),
).toMatchObject({ type: "text" })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
@@ -304,7 +296,6 @@ describe("PatchTool", () => {
call(
`*** Begin Patch\n*** Update File: ${first}\n@@\n-before\n+after\n*** Update File: ${second}\n@@\n-before\n+after\n*** End Patch`,
),
model,
),
).toMatchObject({ type: "text" })
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
@@ -336,7 +327,6 @@ describe("PatchTool", () => {
call(
"*** Begin Patch\n*** Add File: created.txt\n+created\n*** Update File: missing.txt\n@@\n-before\n+after\n*** End Patch",
),
model,
),
).toEqual({ type: "error", value: "Unable to apply patch at missing.txt" })
expect(yield* exists(path.join(tmp.path, "created.txt"))).toBe(false)
@@ -361,7 +351,6 @@ describe("PatchTool", () => {
yield* executeTool(
registry,
call("*** Begin Patch\n*** Add File: existing.txt\n+replacement\n*** End Patch"),
model,
),
).toEqual({ type: "error", value: "Unable to apply patch at existing.txt" })
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("sentinel\n")
@@ -387,7 +376,6 @@ describe("PatchTool", () => {
yield* executeTool(
registry,
call("*** Begin Patch\n*** Add File: appeared.txt\n+replacement\n*** End Patch"),
model,
),
).toEqual({ type: "error", value: "Unable to apply patch at appeared.txt" })
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("winner\n")
@@ -415,7 +403,6 @@ describe("PatchTool", () => {
yield* executeTool(
registry,
call("*** Begin Patch\n*** Delete File: first.txt\n*** Delete File: second.txt\n*** End Patch"),
model,
).pipe(Effect.exit),
),
).toBe(true)
@@ -447,7 +434,6 @@ describe("PatchTool", () => {
const run = yield* executeTool(
registry,
call("*** Begin Patch\n*** Delete File: first.txt\n*** Delete File: second.txt\n*** End Patch"),
model,
).pipe(Effect.forkChild)
yield* Deferred.await(removeStarted!)
const interrupt = yield* Fiber.interrupt(run).pipe(Effect.forkChild)
+23 -7
View File
@@ -18,6 +18,15 @@ let captured: Form.CreateInput | undefined
let reject = false
let deny = false
const capturedInput = () => captured
const questionInput = {
questions: [
{
question: "Continue?",
header: "Continue",
options: [{ label: "Yes", description: "Continue" }],
},
],
}
const permission = Layer.succeed(
PermissionV2.Service,
PermissionV2.Service.of({
@@ -79,7 +88,7 @@ const it = testEffect(
)
describe("QuestionTool", () => {
it.effect("omits a denied built-in question and terminally settles a stale call", () =>
it.effect("omits a catalog-denied question and enforces its leaf permission", () =>
Effect.gen(function* () {
captured = undefined
deny = true
@@ -90,7 +99,7 @@ describe("QuestionTool", () => {
yield* settleTool(registry, {
sessionID,
...toolIdentity,
call: { type: "tool-call", id: "call-question-denied", name: "question", input: { questions: [] } },
call: { type: "tool-call", id: "call-question-denied", name: "question", input: questionInput },
}),
).toEqual({
result: { type: "error", value: "Permission denied: question" },
@@ -158,7 +167,6 @@ describe("QuestionTool", () => {
sessionID,
title: "Questions",
metadata: { kind: "question", tool: { messageID: toolIdentity.assistantMessageID, callID: "call-question" } },
mode: "form",
fields: [
{
key: "q0",
@@ -199,14 +207,22 @@ describe("QuestionTool", () => {
yield* executeTool(registryService, {
sessionID,
...toolIdentity,
call: { type: "tool-call", id: "call-question", name: "question", input: { questions: [] } },
call: { type: "tool-call", id: "call-question", name: "question", input: questionInput },
})
expect(capturedInput()).toEqual({
sessionID,
title: "Questions",
metadata: { kind: "question", tool: { messageID: toolIdentity.assistantMessageID, callID: "call-question" } },
mode: "form",
fields: [],
fields: [
{
key: "q0",
title: "Continue",
description: "Continue?",
options: [{ value: "Yes", label: "Yes", description: "Continue" }],
custom: true,
type: "string",
},
],
})
}),
)
@@ -220,7 +236,7 @@ describe("QuestionTool", () => {
const fiber = yield* executeTool(registryService, {
sessionID,
...toolIdentity,
call: { type: "tool-call", id: "call-question", name: "question", input: { questions: [] } },
call: { type: "tool-call", id: "call-question", name: "question", input: questionInput },
}).pipe(Effect.forkScoped)
const exit = yield* Fiber.await(fiber)
+2 -4
View File
@@ -27,7 +27,7 @@ import { ToolRegistry } from "@opencode-ai/core/tool/registry"
import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
import { executeTool, settleTool, testModel, toolIdentity, waitForTool } from "./lib/tool"
import { executeTool, settleTool, toolIdentity, waitForTool } from "./lib/tool"
const childText = "child final response"
const childModel = ModelV2.Ref.make({ id: ModelV2.ID.make("child"), providerID: ProviderV2.ID.make("test") })
@@ -146,9 +146,7 @@ describe("SubagentTool", () => {
const locations = yield* LocationServiceMap.Service
const registry = yield* ToolRegistry.Service.pipe(Effect.provide(locations.get(parent.location)))
yield* waitForTool(registry, SubagentTool.name)
expect((yield* registry.materialize({ model: testModel })).definitions.map((tool) => tool.name)).toContain(
SubagentTool.name,
)
expect((yield* registry.materialize()).definitions.map((tool) => tool.name)).toContain(SubagentTool.name)
expect(
yield* executeTool(registry, {
sessionID: parent.id,
+68 -14
View File
@@ -16,22 +16,15 @@ network. Its types and methods are generated from the same contract as the
## Install
```sh
bun add @opencode-ai/client
bun add @opencode-ai/client@next
```
The package has two entrypoints:
- `@opencode-ai/client/promise` uses `fetch` and returns Promises or async
iterables. It has no Effect runtime dependency.
- `@opencode-ai/client/effect` returns Effects and Streams, decodes values into
the V2 schema types, and requires an `HttpClient` service from Effect.
## Promise client
## Create a client
Create a client with the server URL, then call methods grouped by API resource:
```ts
import { OpenCode } from "@opencode-ai/client/promise"
import { OpenCode } from "@opencode-ai/client"
const client = OpenCode.make({
baseUrl: "http://localhost:4096",
@@ -47,11 +40,28 @@ await client.session.prompt({
})
```
## Headers and requests
Pass default authentication or application headers to `OpenCode.make` with
`headers`. You can also supply a custom `fetch` implementation. Each operation
accepts request options as its final argument for an `AbortSignal` or
per-request headers.
```ts
const client = OpenCode.make({
baseUrl: "https://opencode.example.com",
headers: {
authorization: `Bearer ${process.env.OPENCODE_TOKEN}`,
},
})
await client.session.list(undefined, {
signal: AbortSignal.timeout(10_000),
})
```
## Stream events
Streaming endpoints return async iterables:
```ts
@@ -60,11 +70,17 @@ for await (const event of client.event.subscribe()) {
}
```
## Effect client
## Effect
Install the `effect` peer dependency when using the Effect entrypoint. The
client uses canonical V2 values such as `Location.Ref` and `Session.ID`, and
returns typed failures in the Effect error channel.
OpenCode provides a first-class Effect client through the
`@opencode-ai/client/effect` entrypoint. It returns typed Effects and Streams
and decodes responses into OpenCode schema values.
```sh
bun add @opencode-ai/client@next effect
```
### Create a client
```ts
import { AbsolutePath, Location, OpenCode } from "@opencode-ai/client/effect"
@@ -89,3 +105,41 @@ const session = await Effect.runPromise(
Streaming operations, including `client.event.subscribe()` and
`client.session.log(...)`, return Effect `Stream` values.
### Service
`Service` discovers and manages the local OpenCode background service from a
Node application:
- `Service.discover()` returns a healthy registered endpoint without starting
a process.
- `Service.start()` reuses a compatible service or starts one when needed.
- `Service.stop()` stops the registered service.
- `Service.headers(endpoint)` creates the authentication headers for a client.
```sh
bun add @effect/platform-node
```
```ts
import { NodeFileSystem } from "@effect/platform-node"
import { OpenCode, Service } from "@opencode-ai/client/effect"
import { Effect } from "effect"
import { FetchHttpClient } from "effect/unstable/http"
const program = Effect.gen(function* () {
const endpoint = yield* Service.start()
const client = yield* OpenCode.make({
baseUrl: endpoint.url,
headers: Service.headers(endpoint),
})
return yield* client.health.get()
})
const health = await Effect.runPromise(
program.pipe(
Effect.provide(FetchHttpClient.layer),
Effect.provide(NodeFileSystem.layer),
),
)
```
+24
View File
@@ -0,0 +1,24 @@
---
title: "Build"
description: "Build on the engine used by millions daily."
mode: "wide"
---
<CardGroup cols={1}>
<Card title="Extend OpenCode" href="/build/plugins">
Build plugins that add tools, integrations, commands, agents, and custom behavior while keeping the rest of OpenCode
intact.
</Card>
<Card title="Run it as a server" href="/build/client">
Connect to OpenCode with the same client used by the TUI and desktop app, then build any interface, workflow, or agent
experience around it.
</Card>
<Card title="Embed it" href="/build/sdk">
Embed OpenCode directly into your application and build a completely custom agent, interface, or developer product
around it.
</Card>
</CardGroup>
<Warning>
The plugin API, client, and SDK are still being finalized during beta and may change before OpenCode 2.0 is stable.
</Warning>
+171 -100
View File
@@ -5,20 +5,19 @@ description: "Extend OpenCode with plugins."
Plugins extend OpenCode in-process. They can transform agents, models, commands,
integrations, references, skills, and tools; intercept model requests and tool
execution; and call a location-scoped subset of the V2 client.
execution; and call a subset of the V2 client.
<Warning>
The V2 plugin API is beta. Entrypoints, hooks, draft shapes, and configuration
may change before the stable release. Use only the `/v2` exports described on
this page; the root `@opencode-ai/plugin` API is the legacy API.
may change before the stable release. Use the `/v2` exports described on this
page.
</Warning>
## Load plugins
Plugins can be loaded from npm packages, explicit local paths, or config
directories. Each module must have one default export containing a unique
plugin `id` and either a Promise `setup` function or an Effect `effect`
function.
plugin `id` and a `setup` function.
### Configuration
@@ -75,26 +74,25 @@ relative config entry.
### Enable and disable
A string beginning with `-` removes a previously selected target. `*` matches
everything, and a suffix of `.*` matches an ID or target prefix. Directives are
A string beginning with `-` disables plugins by their exported `id`. `*`
matches every ID, and a suffix of `.*` matches an ID prefix. Directives are
applied in order:
```jsonc title="opencode.jsonc"
{
"plugins": [
"./plugins/reviewer.ts",
"-acme.reviewer",
"-opencode.provider.*",
"opencode.provider.openai",
"-./plugins/old.ts",
"-*",
"./plugins/only-this-one.ts"
"opencode.provider.openai"
]
}
```
Use the same package specifier or resolved local target to remove an external
plugin. Built-in and embedded plugins can be selected by their plugin ID.
Explicit config directives run after local auto-discovery, so they can disable
discovered plugins.
Package specifiers and local paths locate plugin modules; they are not disable
selectors. Use the `id` from the plugin's default export to disable it. A later
ID entry re-enables a loaded or built-in plugin. Explicit config directives run
after local auto-discovery, so they can disable discovered plugins by ID.
User plugins are activated in configured order between OpenCode's internal
plugin phases. Hooks run sequentially in registration order, and later hooks
@@ -114,12 +112,10 @@ visible from the plugin file, for example:
```sh
cd .opencode
bun add @opencode-ai/plugin@1.17.15 effect@4.0.0-beta.83
bun add @opencode-ai/plugin@next
```
`effect` is required for Effect plugins and for the `Schema` values used by
typed tools. A Promise plugin that does not define tools may only need
`@opencode-ai/plugin`. Match these versions to the OpenCode release you target.
Match the plugin package version to the OpenCode release you target.
Configuration and discovered plugin files under watched config directories are
reloaded when they change. Reloading replaces the active plugin generation and
@@ -128,8 +124,7 @@ package version or a local dependency when no watched file changed.
## Create a plugin
The Promise API is the simplest option. Export the result of `Plugin.define`
as the module default:
Export the result of `Plugin.define` as the module default:
```ts title=".opencode/plugins/reviewer.ts"
import { Plugin } from "@opencode-ai/plugin/v2"
@@ -152,42 +147,33 @@ export default Plugin.define({
})
```
`setup` runs each time the plugin is activated for a Location. Register
long-lived behavior during setup; do not wait there on an infinite event
stream.
`setup` runs each time the plugin is activated. Register long-lived behavior
during setup; do not wait there on an infinite event stream. It may return a
synchronous or asynchronous cleanup function. OpenCode awaits that cleanup
when the plugin is disabled, reloaded, or shut down:
### Effect plugins
```ts
setup: async (ctx) => {
const controller = new AbortController()
const task = synchronize(ctx, controller.signal)
Use the Effect entrypoint when the implementation benefits from Effect
composition, fibers, or scoped resources:
```ts title=".opencode/plugins/reviewer-effect.ts"
import { Plugin } from "@opencode-ai/plugin/v2/effect"
import { Effect } from "effect"
export default Plugin.define({
id: "acme.reviewer-effect",
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.agent.transform((agents) => {
agents.update("reviewer", (agent) => {
agent.description = "Reviews code for regressions"
agent.mode = "subagent"
})
})
}),
})
return async () => {
controller.abort()
await task
}
}
```
The plugin effect is scoped. Finalizers, scoped fibers, and registrations are
released when the plugin reloads or unloads. OpenCode deliberately isolates the
effect from its private Core services; use only the public `ctx` capabilities.
Hook registrations are released automatically with the same plugin scope. Use
the returned cleanup for resources the plugin owns, such as timers, watchers,
connections, and background tasks.
## Context
### Context
Promise methods return Promises; the equivalent Effect methods return
`Effect`. Read and action methods use the same inputs and location-aware
responses as the V2 client APIs.
The plugin context is essentially an [OpenCode server client](/build/client).
Its read and action methods use the same inputs and responses as the client. It
adds plugin-only methods for transforms, runtime hooks, reloads, registrations,
and plugin options.
| Capability | Available operations |
| --- | --- |
@@ -206,16 +192,11 @@ responses as the V2 client APIs.
| `ctx.event` | `subscribe` to the current public server event stream |
| `ctx.options` | Readonly options from the matching config object |
Unlike the legacy API, V2 does not provide `$`, `directory`, `worktree`, or a
general SDK client on the context. A plugin is Location-scoped, and the exposed
domain clients apply that Location by default.
### Transform hooks
Transforms synchronously edit a draft whenever a stateful domain is built.
Registering or disposing a transform rebuilds the domain from fresh state and
runs all active transforms in order. Call the domain's `reload()` method when
external data captured by a transform changes.
Transform hooks let a plugin modify how OpenCode is configured. Use them to add
or remove definitions, override settings, choose defaults, and provide tools or
other sources.
| Transform | Draft operations |
| --- | --- |
@@ -227,10 +208,42 @@ external data captured by a transform changes.
| `skill.transform` | `source`, `list` |
| `tool.transform` | `add` |
Hook registrations are owned by the plugin scope. Transform and runtime hook
calls also return a `Registration` with `dispose` for explicit cleanup. Tool
contributions currently remain until the owning plugin scope closes, so prefer
scope cleanup for plugin-wide teardown while this API is beta.
Here's an example that keeps models synced from a remote source:
```js title=".opencode/plugins/remote-models.js"
import { Plugin } from "@opencode-ai/plugin/v2"
export default Plugin.define({
id: "acme.remote-models",
setup: async (ctx) => {
let models = []
await ctx.catalog.transform((catalog) => {
for (const model of models) {
catalog.model.update(model.providerID, model.id, (draft) => Object.assign(draft, model))
}
})
const refresh = async () => {
const response = await fetch("https://example.com/opencode/models.json", {
signal: AbortSignal.timeout(10_000),
})
if (!response.ok) return
models = await response.json()
await ctx.catalog.reload()
}
await refresh()
const timer = setInterval(() => void refresh().catch(console.error), 60_000)
return () => clearInterval(timer)
},
})
```
`ctx.catalog.reload()` replays every catalog transform to derive the new
catalog. Each plugin's logic remains composed with the others, so a later
plugin can still modify models added by an earlier one. The catalog updates
without restarting OpenCode.
### Runtime hooks
@@ -269,27 +282,39 @@ export default Plugin.define({
A hook failure fails the operation it intercepts. Keep runtime hooks fast and
handle expected errors inside the callback.
## Add a tool
## Examples
Use `Tool.make` with Effect schemas. Promise tools use async executors:
### Add a tool
```ts title=".opencode/plugins/greeting.ts"
Pass a tool declaration to `tools.add`. Define its input with JSON Schema and
use an async executor:
```js title=".opencode/plugins/greeting.js"
import { Plugin } from "@opencode-ai/plugin/v2"
import { Tool } from "@opencode-ai/plugin/v2/tool"
import { Schema } from "effect"
const greeting = Tool.make({
description: "Create a greeting",
input: Schema.Struct({ name: Schema.String }),
output: Schema.String,
execute: async ({ name }) => `Hello, ${name}!`,
})
export default Plugin.define({
id: "acme.greeting",
setup: async (ctx) => {
await ctx.tool.transform((tools) => {
tools.add("greeting", greeting)
tools.add({
name: "greeting",
description: "Create a greeting",
jsonSchema: {
type: "object",
properties: {
name: { type: "string" },
},
required: ["name"],
additionalProperties: false,
},
execute: async ({ name }) => {
const text = `Hello, ${name}!`
return {
structured: { greeting: text },
content: [{ type: "text", text }],
}
},
})
})
},
})
@@ -297,38 +322,48 @@ export default Plugin.define({
Unsupported characters in tool and group names are normalized to underscores.
The resulting exposed key must begin with a letter and contain at most 64
letters, digits, underscores, or hyphens. `tools.add` also accepts
`{ group, deferred }`:
letters, digits, underscores, or hyphens. Set `options` on the declaration to
configure registration with `{ group, deferred }`:
- `group` prefixes and groups the exposed tool name.
- `deferred: true` makes the tool available through the deferred `execute`
tool instead of exposing it directly.
The executor receives a second context argument containing `sessionID`,
`agent`, `assistantMessageID`, and `toolCallID`. Use
`Tool.withPermission(tool, "permission-name")` to assign a permission key.
Effect plugins import the helper from `@opencode-ai/plugin/v2/effect/tool` and
return an `Effect` from `execute`.
`agent`, `assistantMessageID`, and `toolCallID`.
## Types
### Add a command
`Plugin.define` infers the context and callbacks. The Promise root also
re-exports the canonical `Agent`, `Command`, `Connection`, `Credential`,
`Integration`, `Model`, `Provider`, `Reference`, and `Skill` schema namespaces.
Import narrower API types from their public subpaths when needed:
```js title=".opencode/plugins/review-command.js"
import { Plugin } from "@opencode-ai/plugin/v2"
```ts
import { Plugin, Model } from "@opencode-ai/plugin/v2"
import type { Context } from "@opencode-ai/plugin/v2/plugin"
import type { AgentDraft } from "@opencode-ai/plugin/v2/agent"
import type { ToolExecuteBeforeEvent } from "@opencode-ai/plugin/v2/tool"
export default Plugin.define({
id: "acme.review-command",
setup: async (ctx) => {
await ctx.command.transform((commands) => {
commands.update("review", (command) => {
command.description = "Review the current changes"
command.template = "Review the current changes for correctness and missing tests."
})
})
},
})
```
Effect equivalents live below `@opencode-ai/plugin/v2/effect`, such as
`@opencode-ai/plugin/v2/effect/plugin` and
`@opencode-ai/plugin/v2/effect/tool`. Avoid importing types or runtime values
from `@opencode-ai/core` or `@opencode-ai/server`; those are private host
implementation details.
### Set the default model
```js title=".opencode/plugins/default-model.js"
import { Plugin } from "@opencode-ai/plugin/v2"
export default Plugin.define({
id: "acme.default-model",
setup: async (ctx) => {
await ctx.catalog.transform((catalog) => {
catalog.model.default.set("anthropic", "claude-sonnet-4-5")
})
},
})
```
## Publish a package
@@ -342,8 +377,7 @@ manifest is:
"type": "module",
"exports": "./src/index.ts",
"dependencies": {
"@opencode-ai/plugin": "1.17.15",
"effect": "4.0.0-beta.83"
"@opencode-ai/plugin": "next"
}
}
```
@@ -355,7 +389,7 @@ change.
## Verify loading
List active plugin IDs for the current Location through the V2 API:
List active plugin IDs through the V2 API:
```sh
opencode2 api get /api/plugin
@@ -365,3 +399,40 @@ If a plugin is absent, check the server log described in
[Troubleshooting](/troubleshooting#read-logs). Invalid modules and setup failures are
logged; one failing package does not prevent unrelated valid packages from
being resolved.
## Effect
OpenCode provides a first-class Effect API for plugins through the
`@opencode-ai/plugin/v2/effect` entrypoint. Install `effect` alongside the
plugin package and export an `effect` function instead of `setup`:
```sh
bun add @opencode-ai/plugin@next effect
```
```ts title=".opencode/plugins/reviewer-effect.ts"
import { Plugin } from "@opencode-ai/plugin/v2/effect"
import { Effect } from "effect"
export default Plugin.define({
id: "acme.reviewer-effect",
effect: (ctx) =>
Effect.gen(function* () {
yield* ctx.agent.transform((agents) => {
agents.update("reviewer", (agent) => {
agent.description = "Reviews code for regressions"
agent.mode = "subagent"
})
})
}),
})
```
Context operations return Effects. The plugin effect is scoped, so finalizers,
fibers, and registrations are released when the plugin reloads or unloads.
OpenCode does not expose its private Core services to the plugin; use the
capabilities on `ctx`.
Typed tools can use `Schema` from `effect` and the contracts exported from
`@opencode-ai/plugin/v2/effect/tool`. Their executors return an Effect and may
fail with the typed tool failure channel.
@@ -4,7 +4,7 @@ description: "Embed an OpenCode host in an Effect application."
---
`@opencode-ai/sdk-next` is the Effect-native SDK for applications that need to
host OpenCode in-process. Unlike the [network client](/client), it assembles the
host OpenCode in-process. Unlike the [network client](/build/client), it assembles the
OpenCode server and routes API calls through its HTTP router in memory. It opens
no HTTP listener and adds no network hop between the client and server.
@@ -72,4 +72,4 @@ const active = await Effect.runPromise(
Call `opencode.plugin(...)` to register an embedded V2 plugin. Embedded plugins
use the same discovery and location-scoped activation path as configured
plugins. The SDK also exports `Tool` for plugin-defined tools. See the
[Plugins guide](/plugins) for the plugin shape and available hooks.
[Plugins guide](/build/plugins) for the plugin shape and available hooks.
+1 -1
View File
@@ -421,7 +421,7 @@ accepts options.
}
```
See the [plugins guide](/plugins) for plugin development and configuration.
See the [plugins guide](/build/plugins) for plugin development and configuration.
### Providers
+1 -6
View File
@@ -46,12 +46,7 @@
},
{
"tab": "Build",
"groups": [
{
"group": "Build with OpenCode",
"pages": ["plugins", "client", "sdk/index"]
}
]
"pages": ["build/index", "build/plugins", "build/client", "build/sdk"]
},
{
"tab": "API",
+1 -1
View File
@@ -501,7 +501,7 @@ plugin API is still being finalized during beta, and detailed plugin migration g
ready.
Once the V2 plugin API is finalized, OpenCode should be able to migrate the majority of V1 plugins while keeping related
local modules and dependencies together. See the current beta [Plugins guide](/plugins).
local modules and dependencies together. See the current beta [Plugins guide](/build/plugins).
## Server API and clients
+47 -48
View File
@@ -6,54 +6,53 @@ This file tracks the gap between the native `@opencode-ai/llm` package and the A
## Existing Status Sources
| File | What it tracks | Limitation |
| --- | --- | --- |
| `packages/llm/DESIGN.md` | Future clean-break API proposal, currently named `@opencode-ai/ai` in the draft. | Not a provider parity tracker. |
| `packages/llm/example/call-sites.md` | Route/value/provider-facade migration checklist and call-site sketches. | Architecture migration only; not AI SDK package parity. |
| `specs/v2/provider-model.md` | V2 catalog endpoint schema and current Session runner adaptation surface. | Runner-specific; not a native LLM package status matrix. |
| File | What it tracks | Limitation |
| ------------------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------- |
| `packages/llm/DESIGN.md` | Future clean-break API proposal, currently named `@opencode-ai/ai` in the draft. | Not a provider parity tracker. |
| `packages/llm/example/call-sites.md` | Route/value/provider-facade migration checklist and call-site sketches. | Architecture migration only; not AI SDK package parity. |
## Current Implementation Snapshot
| Native slice | Source | Current state | Main gaps |
| --- | --- | --- | --- |
| OpenAI Chat | `src/protocols/openai-chat.ts`, `src/providers/openai.ts` | Usable. Streams text, reasoning deltas, tool calls, usage, images, and common generation controls. | No typed structured-output / `response_format` path. Limited typed OpenAI option surface compared with SDK escape hatches. |
| OpenAI Responses HTTP | `src/protocols/openai-responses.ts`, `src/providers/openai.ts` | Usable. Supports hosted-tool event surfacing, reasoning replay metadata, GPT-5 defaults, and cache usage. | No explicit `previous_response_id` path. Typed options cover only a subset of Responses fields. Structured output is still mostly synthetic-tool based. |
| OpenAI Responses WebSocket | `src/protocols/openai-responses.ts`, `src/route/transport/websocket.ts` | Present as `OpenAI.responsesWebSocket(...)`. | Runner/catalog support explicitly must not downgrade WebSocket routes; broader runtime selection is not complete. |
| OpenAI-compatible Chat | `src/protocols/openai-compatible-chat.ts`, `src/providers/openai-compatible.ts` | Usable for generic Chat and several profiles: Baseten, Cerebras, DeepInfra, DeepSeek, Fireworks, Groq, TogetherAI. | No OpenAI-compatible Responses protocol/facade. Family quirks are mostly endpoint defaults, not full typed behavior. |
| Anthropic Messages | `src/protocols/anthropic-messages.ts`, `src/providers/anthropic.ts` | Usable. Supports tools, thinking, cache control, images, server-hosted tool events, and usage. | Provider option surface is small. Beta/header handling, metadata, and newer Messages fields need a typed parity pass. |
| Gemini Developer API | `src/protocols/gemini.ts`, `src/providers/google.ts` | Usable for Google API key flow. Supports text, images, tools, thinking signatures, and cache usage. | This is not Vertex. Typed provider options are narrow; many Gemini request fields currently require raw `http.body` overlays. |
| Bedrock Converse | `src/protocols/bedrock-converse.ts`, `src/providers/amazon-bedrock.ts` | Partial but real. Supports AWS event-stream framing, SigV4 with supplied credentials, bearer auth, tools, reasoning signatures, media, cache points, and recorded tests. | Native facade does not mirror the AI SDK plugin's default AWS credential chain/profile behavior. Runner/catalog mapping is missing. Guardrails, inference profiles, region-specific model ID fixes, and model-specific request fields need a parity pass. |
| Azure OpenAI | `src/providers/azure.ts` using OpenAI Chat/Responses protocols | Partial. Supports resource/base URL setup, API key auth, API version query, Chat, and Responses selectors. | Core runner does not map `@ai-sdk/azure` to this native facade. AAD/token auth and Azure-specific endpoint variants need review. |
| Cloudflare AI Gateway / Workers AI | `src/providers/cloudflare.ts` | Present via OpenAI-compatible Chat routes. | Useful but not part of the critical AI SDK replacement set yet. Needs per-product recorded coverage before relying on it broadly. |
| OpenRouter | `src/providers/openrouter.ts` | Present with OpenRouter-specific usage/reasoning/prompt-cache options over Chat. | Responses-style OpenRouter support is absent. |
| xAI | `src/providers/xai.ts` | Present with Responses and Chat selectors. | Needs package-parity review against the AI SDK xAI provider. |
| GitHub Copilot | `src/providers/github-copilot.ts` | Present as explicit-base-URL OpenAI Chat/Responses facade. | Runtime/catalog integration remains specialized and should stay separate from public OpenAI-compatible defaults. |
| Native slice | Source | Current state | Main gaps |
| ---------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OpenAI Chat | `src/protocols/openai-chat.ts`, `src/providers/openai.ts` | Usable. Streams text, reasoning deltas, tool calls, usage, images, and common generation controls. | No typed structured-output / `response_format` path. Limited typed OpenAI option surface compared with SDK escape hatches. |
| OpenAI Responses HTTP | `src/protocols/openai-responses.ts`, `src/providers/openai.ts` | Usable. Supports hosted-tool event surfacing, reasoning replay metadata, GPT-5 defaults, and cache usage. | No explicit `previous_response_id` path. Typed options cover only a subset of Responses fields. Structured output is still mostly synthetic-tool based. |
| OpenAI Responses WebSocket | `src/protocols/openai-responses.ts`, `src/route/transport/websocket.ts` | Present as `OpenAI.responsesWebSocket(...)`. | Runner/catalog support explicitly must not downgrade WebSocket routes; broader runtime selection is not complete. |
| OpenAI-compatible Chat | `src/protocols/openai-compatible-chat.ts`, `src/providers/openai-compatible.ts` | Usable for generic Chat and several profiles: Baseten, Cerebras, DeepInfra, DeepSeek, Fireworks, Groq, TogetherAI. | No OpenAI-compatible Responses protocol/facade. Family quirks are mostly endpoint defaults, not full typed behavior. |
| Anthropic Messages | `src/protocols/anthropic-messages.ts`, `src/providers/anthropic.ts` | Usable. Supports tools, thinking, cache control, images, server-hosted tool events, and usage. | Provider option surface is small. Beta/header handling, metadata, and newer Messages fields need a typed parity pass. |
| Gemini Developer API | `src/protocols/gemini.ts`, `src/providers/google.ts` | Usable for Google API key flow. Supports text, images, tools, thinking signatures, and cache usage. | This is not Vertex. Typed provider options are narrow; many Gemini request fields currently require raw `http.body` overlays. |
| Bedrock Converse | `src/protocols/bedrock-converse.ts`, `src/providers/amazon-bedrock.ts` | Partial but real. Supports AWS event-stream framing, SigV4 with supplied credentials, bearer auth, tools, reasoning signatures, media, cache points, and recorded tests. | Native facade does not mirror the AI SDK plugin's default AWS credential chain/profile behavior. Runner/catalog mapping is missing. Guardrails, inference profiles, region-specific model ID fixes, and model-specific request fields need a parity pass. |
| Azure OpenAI | `src/providers/azure.ts` using OpenAI Chat/Responses protocols | Partial. Supports resource/base URL setup, API key auth, API version query, Chat, and Responses selectors. | Core runner does not map `@ai-sdk/azure` to this native facade. AAD/token auth and Azure-specific endpoint variants need review. |
| Cloudflare AI Gateway / Workers AI | `src/providers/cloudflare.ts` | Present via OpenAI-compatible Chat routes. | Useful but not part of the critical AI SDK replacement set yet. Needs per-product recorded coverage before relying on it broadly. |
| OpenRouter | `src/providers/openrouter.ts` | Present with OpenRouter-specific usage/reasoning/prompt-cache options over Chat. | Responses-style OpenRouter support is absent. |
| xAI | `src/providers/xai.ts` | Present with Responses and Chat selectors. | Needs package-parity review against the AI SDK xAI provider. |
| GitHub Copilot | `src/providers/github-copilot.ts` | Present as explicit-base-URL OpenAI Chat/Responses facade. | Runtime/catalog integration remains specialized and should stay separate from public OpenAI-compatible defaults. |
## V2 Runner Status
`packages/core/src/session/runner/model.ts` currently resolves only this native subset from catalog `aisdk` metadata:
| Catalog API | Native route used today |
| --- | --- |
| `aisdk:@ai-sdk/openai` | `OpenAIResponses.route` |
| `aisdk:@ai-sdk/anthropic` | `AnthropicMessages.route` |
| Catalog API | Native route used today |
| --------------------------------------------------- | ---------------------------- |
| `aisdk:@ai-sdk/openai` | `OpenAIResponses.route` |
| `aisdk:@ai-sdk/anthropic` | `AnthropicMessages.route` |
| `aisdk:@ai-sdk/openai-compatible` with explicit URL | `OpenAICompatibleChat.route` |
Everything else currently fails with `SessionRunnerModel.UnsupportedApiError` when the V2 native runner tries to resolve it. This includes `@ai-sdk/google`, `@ai-sdk/google-vertex`, `@ai-sdk/google-vertex/anthropic`, `@ai-sdk/azure`, `@ai-sdk/amazon-bedrock`, and `@ai-sdk/amazon-bedrock/mantle`.
## AI SDK Package Parity Matrix
| AI SDK package | Intended native target | Status | Biggest gaps |
| --- | --- | --- | --- |
| `@ai-sdk/openai` | `OpenAI.chat`, `OpenAI.responses`, `OpenAI.responsesWebSocket` | Partial / usable | Add complete typed option coverage, structured output strategy, explicit Responses continuation support, and runner route selection between Chat/Responses/WebSocket. |
| `@ai-sdk/openai-compatible` | Generic OpenAI-compatible Chat plus future Responses | Partial | Add OpenAI-compatible Responses. Decide per-family namespace/profile behavior for providers that support Responses versus Chat only. |
| `@ai-sdk/anthropic` | `AnthropicMessages` | Partial / usable | Finish Messages API parity for headers/betas/metadata/newer fields and document hosted-tool continuation expectations. |
| `@ai-sdk/google` | Gemini Developer API | Partial / usable | Add typed options for safety, response schema/modalities, cached content, grounding/search/code execution, and non-text output modes where supported. |
| `@ai-sdk/google-vertex` | Vertex Gemini namespace/facade | Missing | Implement Vertex endpoint derivation, ADC/OAuth auth, project/location/env resolution, OpenAI-compatible Vertex endpoint handling, and runner/catalog mapping. |
| `@ai-sdk/google-vertex/anthropic` | Anthropic Messages over Vertex namespace/facade | Missing | Implement Vertex Anthropic endpoint/auth selection, regional endpoint behavior, and compatibility with Anthropic Messages lowering/parsing. |
| `@ai-sdk/azure` | Azure OpenAI Chat/Responses facade | Partial | Map runner/catalog metadata to native Azure, handle resourceName/baseURL/apiVersion variants, add AAD/token auth story, and verify Chat vs Responses deployment selection. |
| `@ai-sdk/amazon-bedrock` | Bedrock Converse | Partial | Add default AWS credential chain/profile support, region/inference-profile model ID handling, provider option parity via `additionalModelRequestFields`, guardrails/performance config, and runner/catalog mapping. |
| `@ai-sdk/amazon-bedrock/mantle` | Bedrock Mantle OpenAI-compatible Chat/Responses namespace | Missing | Decide native Mantle shape, likely separate from Converse because it uses OpenAI-compatible Chat/Responses semantics over Bedrock. Add package mapping and tests. |
| AI SDK package | Intended native target | Status | Biggest gaps |
| --------------------------------- | -------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `@ai-sdk/openai` | `OpenAI.chat`, `OpenAI.responses`, `OpenAI.responsesWebSocket` | Partial / usable | Add complete typed option coverage, structured output strategy, explicit Responses continuation support, and runner route selection between Chat/Responses/WebSocket. |
| `@ai-sdk/openai-compatible` | Generic OpenAI-compatible Chat plus future Responses | Partial | Add OpenAI-compatible Responses. Decide per-family namespace/profile behavior for providers that support Responses versus Chat only. |
| `@ai-sdk/anthropic` | `AnthropicMessages` | Partial / usable | Finish Messages API parity for headers/betas/metadata/newer fields and document hosted-tool continuation expectations. |
| `@ai-sdk/google` | Gemini Developer API | Partial / usable | Add typed options for safety, response schema/modalities, cached content, grounding/search/code execution, and non-text output modes where supported. |
| `@ai-sdk/google-vertex` | Vertex Gemini namespace/facade | Missing | Implement Vertex endpoint derivation, ADC/OAuth auth, project/location/env resolution, OpenAI-compatible Vertex endpoint handling, and runner/catalog mapping. |
| `@ai-sdk/google-vertex/anthropic` | Anthropic Messages over Vertex namespace/facade | Missing | Implement Vertex Anthropic endpoint/auth selection, regional endpoint behavior, and compatibility with Anthropic Messages lowering/parsing. |
| `@ai-sdk/azure` | Azure OpenAI Chat/Responses facade | Partial | Map runner/catalog metadata to native Azure, handle resourceName/baseURL/apiVersion variants, add AAD/token auth story, and verify Chat vs Responses deployment selection. |
| `@ai-sdk/amazon-bedrock` | Bedrock Converse | Partial | Add default AWS credential chain/profile support, region/inference-profile model ID handling, provider option parity via `additionalModelRequestFields`, guardrails/performance config, and runner/catalog mapping. |
| `@ai-sdk/amazon-bedrock/mantle` | Bedrock Mantle OpenAI-compatible Chat/Responses namespace | Missing | Decide native Mantle shape, likely separate from Converse because it uses OpenAI-compatible Chat/Responses semantics over Bedrock. Add package mapping and tests. |
## Highest-Risk Gaps
@@ -71,20 +70,20 @@ Everything else currently fails with `SessionRunnerModel.UnsupportedApiError` wh
These are implementation/API slices, not separate npm packages.
| API slice | Package-like entrypoint | Purpose |
| --- | --- | --- |
| OpenAI Chat | `@opencode-ai/llm/providers/openai/chat` | OpenAI `/chat/completions` semantics. |
| OpenAI Responses | `@opencode-ai/llm/providers/openai/responses` | OpenAI `/responses` semantics with HTTP/WebSocket selected through settings. |
| OpenAI-compatible Chat | `@opencode-ai/llm/providers/openai-compatible` | Generic OpenAI-compatible `/chat/completions`. |
| OpenAI-compatible Responses | Missing | Generic OpenAI-compatible `/responses`. |
| Anthropic Messages | `@opencode-ai/llm/providers/anthropic` | Anthropic Messages API. |
| Gemini Developer API | `@opencode-ai/llm/providers/google` | Google AI Studio Gemini API. |
| Vertex Gemini | Missing | Vertex Gemini API. |
| Vertex Anthropic Messages | Missing | Vertex-hosted Anthropic Messages API. |
| Bedrock Converse | `@opencode-ai/llm/providers/amazon-bedrock` | AWS Bedrock Converse API. |
| Bedrock Mantle | Missing | AWS Bedrock Mantle OpenAI-compatible APIs. |
| Azure OpenAI Chat | `@opencode-ai/llm/providers/azure/chat` | Azure specialization of OpenAI Chat. |
| Azure OpenAI Responses | `@opencode-ai/llm/providers/azure/responses` | Azure specialization of OpenAI Responses. |
| API slice | Package-like entrypoint | Purpose |
| --------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------- |
| OpenAI Chat | `@opencode-ai/llm/providers/openai/chat` | OpenAI `/chat/completions` semantics. |
| OpenAI Responses | `@opencode-ai/llm/providers/openai/responses` | OpenAI `/responses` semantics with HTTP/WebSocket selected through settings. |
| OpenAI-compatible Chat | `@opencode-ai/llm/providers/openai-compatible` | Generic OpenAI-compatible `/chat/completions`. |
| OpenAI-compatible Responses | Missing | Generic OpenAI-compatible `/responses`. |
| Anthropic Messages | `@opencode-ai/llm/providers/anthropic` | Anthropic Messages API. |
| Gemini Developer API | `@opencode-ai/llm/providers/google` | Google AI Studio Gemini API. |
| Vertex Gemini | Missing | Vertex Gemini API. |
| Vertex Anthropic Messages | Missing | Vertex-hosted Anthropic Messages API. |
| Bedrock Converse | `@opencode-ai/llm/providers/amazon-bedrock` | AWS Bedrock Converse API. |
| Bedrock Mantle | Missing | AWS Bedrock Mantle OpenAI-compatible APIs. |
| Azure OpenAI Chat | `@opencode-ai/llm/providers/azure/chat` | Azure specialization of OpenAI Chat. |
| Azure OpenAI Responses | `@opencode-ai/llm/providers/azure/responses` | Azure specialization of OpenAI Responses. |
## Suggested Next Work Slices
@@ -10,7 +10,12 @@ function ok<T>(data: T) {
}
function form(id: string, sessionID: string): FormInfo {
return { id, sessionID, title: "Input requested", mode: "form", fields: [] }
return {
id,
sessionID,
title: "Input requested",
fields: [{ key: "authorization", type: "external", url: "https://example.com/form" }],
}
}
function formCreated(info: FormInfo): V2Event {
@@ -838,13 +838,18 @@ const scenarios: Scenario[] = [
.at((ctx) => ({
path: route("/api/session/{sessionID}/form", { sessionID: ctx.state.id }),
headers: ctx.headers(),
body: { mode: "url", url: "https://example.com/form" },
body: {
title: "External form",
fields: [{ key: "authorization", type: "external", url: "https://example.com/form" }],
},
}))
.json(200, (body) => {
object(body)
object(body.data)
check(typeof body.data.id === "string", "form create should return an ID")
check(body.data.mode === "url", "form create should preserve URL mode")
array(body.data.fields)
object(body.data.fields[0])
check(body.data.fields[0].type === "external", "form create should preserve the external field")
}),
http.protected
.get("/api/session/{sessionID}/form/{formID}", "v2.session.form.get")
+1 -3
View File
@@ -7,7 +7,7 @@
"scripts": {
"test": "bun test --timeout 5000",
"typecheck": "tsgo --noEmit",
"build": "tsc"
"build": "tsc -p tsconfig.build.json"
},
"exports": {
".": "./src/index.ts",
@@ -24,8 +24,6 @@
"dependencies": {
"@ai-sdk/provider": "3.0.8",
"@opencode-ai/client": "workspace:*",
"@opencode-ai/llm": "workspace:*",
"@opencode-ai/protocol": "workspace:*",
"@opencode-ai/schema": "workspace:*",
"@opencode-ai/sdk": "workspace:*",
"effect": "catalog:",
+1 -1
View File
@@ -10,7 +10,7 @@ async function published(name: string, version: string) {
return (await $`npm view ${name}@${version} version`.nothrow()).exitCode === 0
}
await $`bun tsc`
await $`bun run build`
const originalText = await Bun.file("package.json").text()
const pkg = JSON.parse(originalText) as {
name: string
+1 -23
View File
@@ -1,25 +1,3 @@
import type { SessionApi } from "@opencode-ai/client/effect/api"
import type { Message, SystemPart } from "@opencode-ai/llm"
import type { Agent } from "@opencode-ai/schema/agent"
import type { Model } from "@opencode-ai/schema/model"
import type { Session } from "@opencode-ai/schema/session"
import type { JsonSchema } from "effect"
import type { Hooks } from "./registration.js"
export interface SessionRequestBeforeEvent {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
system: Array<SystemPart>
messages: Array<Message>
tools: Record<string, { description: string; input: JsonSchema.JsonSchema }>
}
export interface SessionHooks {
readonly request: SessionRequestBeforeEvent
}
export interface SessionDomain
extends Pick<SessionApi<unknown>, "create" | "get" | "prompt" | "command" | "interrupt"> {
readonly hook: Hooks<SessionHooks>
}
export type SessionDomain = Pick<SessionApi<unknown>, "create" | "get" | "prompt" | "command" | "interrupt">
+38 -12
View File
@@ -1,7 +1,7 @@
export * as Tool from "./tool.js"
import { ToolDefinition, ToolFailure, ToolOutput, type ToolCall, type ToolResultValue } from "@opencode-ai/llm"
import { Agent } from "@opencode-ai/schema/agent"
import type { LLM } from "@opencode-ai/schema/llm"
import { Session } from "@opencode-ai/schema/session"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { Effect, JsonSchema, Schema, type Scope } from "effect"
@@ -16,6 +16,29 @@ export interface Context {
export type SchemaType<A> = Schema.Codec<A, any>
type ToolDefinition = {
readonly name: string
readonly description: string
readonly inputSchema: JsonSchema.JsonSchema
readonly outputSchema?: JsonSchema.JsonSchema
}
type ToolCall = {
readonly input: unknown
readonly [key: string]: unknown
}
type ToolResultValue =
| { readonly type: "json"; readonly value: unknown }
| { readonly type: "text"; readonly value: unknown }
| { readonly type: "error"; readonly value: unknown }
| { readonly type: "content"; readonly value: ReadonlyArray<LLM.ToolContent> }
type ToolOutput = {
readonly structured: unknown
readonly content: ReadonlyArray<LLM.ToolContent>
}
declare const TypeId: unique symbol
export interface Definition<Input extends SchemaType<any>, Output extends SchemaType<any>> {
@@ -26,8 +49,11 @@ export interface Definition<Input extends SchemaType<any>, Output extends Schema
}
export type AnyTool = Definition<any, any>
export const Failure = ToolFailure
export type Failure = ToolFailure
export class Failure extends Schema.TaggedErrorClass<Failure>()("LLM.ToolFailure", {
message: Schema.String,
error: Schema.optional(Schema.Defect()),
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
}) {}
export class RegistrationError extends Schema.TaggedErrorClass<RegistrationError>()("Tool.RegistrationError", {
name: Schema.String,
@@ -54,7 +80,7 @@ type Config<
readonly execute: (
input: Schema.Schema.Type<Input>,
context: Context,
) => Effect.Effect<Schema.Schema.Type<Output>, ToolFailure>
) => Effect.Effect<Schema.Schema.Type<Output>, Failure>
readonly toModelOutput?: (input: {
readonly input: Schema.Schema.Type<Input>
readonly output: Output["Encoded"]
@@ -75,13 +101,13 @@ type DynamicConfig = {
readonly description: string
readonly jsonSchema: JsonSchema.JsonSchema
readonly outputSchema?: JsonSchema.JsonSchema
readonly execute: (input: unknown, context: Context) => Effect.Effect<DynamicOutput, ToolFailure>
readonly execute: (input: unknown, context: Context) => Effect.Effect<DynamicOutput, Failure>
}
type Runtime = {
readonly permission?: string
readonly definition: (name: string) => ToolDefinition
readonly settle: (call: ToolCall, context: Context) => Effect.Effect<ToolOutput, ToolFailure>
readonly settle: (call: ToolCall, context: Context) => Effect.Effect<ToolOutput, Failure>
}
const runtimes = new WeakMap<AnyTool, Runtime>()
@@ -108,18 +134,18 @@ function makeTyped<
definition: (name) => {
const cached = definitions.get(name)
if (cached) return cached
const definition = new ToolDefinition({
const definition: ToolDefinition = {
name,
description: config.description,
inputSchema: toJsonSchema(config.input),
outputSchema: toJsonSchema(config.structured ?? config.output),
})
}
definitions.set(name, definition)
return definition
},
settle: (call, context) =>
Schema.decodeUnknownEffect(config.input)(call.input).pipe(
Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
Effect.mapError((error) => new Failure({ message: `Invalid tool input: ${error.message}` })),
Effect.flatMap((input) =>
config.execute(input, context).pipe(
Effect.flatMap((output) =>
@@ -133,7 +159,7 @@ function makeTyped<
}),
Effect.mapError(
(error) =>
new ToolFailure({
new Failure({
message: `Tool returned an invalid value for its output schema: ${error.message}`,
}),
),
@@ -159,12 +185,12 @@ function makeDynamic(config: DynamicConfig): AnyTool {
definition: (name) => {
const cached = definitions.get(name)
if (cached) return cached
const definition = new ToolDefinition({
const definition: ToolDefinition = {
name,
description: config.description,
inputSchema: config.jsonSchema,
outputSchema: config.outputSchema,
})
}
definitions.set(name, definition)
return definition
},
+18 -9
View File
@@ -25,6 +25,15 @@ export default Plugin.define({
```
Plugin setup registers hooks imperatively through each domain's `hook` method.
It may return a synchronous or asynchronous cleanup function. OpenCode awaits
the cleanup when the plugin is unloaded or replaced:
```ts
setup: async (ctx) => {
const timer = setInterval(refresh, 60_000)
return () => clearInterval(timer)
}
```
Configuration supplied for the plugin is available as `ctx.options`.
@@ -85,20 +94,20 @@ await ctx.session.hook("request", (event) => {
})
```
Promise tools use the same schemas and registration model as Effect tools, with async executors:
Promise tools use plain object declarations with async executors:
```ts
import { Schema } from "effect"
import { Tool } from "@opencode-ai/plugin/v2/tool"
const echo = Tool.make({
description: "Echo text",
input: Schema.Struct({ text: Schema.String }),
output: Schema.Struct({ text: Schema.String }),
execute: async ({ text }) => ({ text }),
await ctx.tool.transform((tools) => {
tools.add({
name: "echo",
description: "Echo text",
input: Schema.Struct({ text: Schema.String }),
output: Schema.Struct({ text: Schema.String }),
execute: async ({ text }) => ({ text }),
})
})
await ctx.tool.transform((tools) => tools.add("echo", echo))
```
## Reloading A Domain
+3 -1
View File
@@ -26,9 +26,11 @@ export interface Context {
readonly tool: ToolDomain
}
export type Cleanup = () => Promise<void> | void
export interface Plugin {
readonly id: string
readonly setup: (context: Context) => Promise<void> | void
readonly setup: (context: Context) => Promise<Cleanup | void> | Cleanup | void
}
export function define(plugin: Plugin) {
+1 -22
View File
@@ -1,24 +1,3 @@
import type { SessionApi } from "@opencode-ai/client/promise/api"
import type { Message, SystemPart } from "@opencode-ai/llm"
import type { Agent } from "@opencode-ai/schema/agent"
import type { Model } from "@opencode-ai/schema/model"
import type { Session } from "@opencode-ai/schema/session"
import type { JsonSchema } from "effect"
import type { Hooks } from "./registration.js"
export interface SessionRequestBeforeEvent {
readonly sessionID: Session.ID
readonly agent: Agent.ID
readonly model: Model.Ref
system: Array<SystemPart>
messages: Array<Message>
tools: Record<string, { description: string; input: JsonSchema.JsonSchema }>
}
export interface SessionHooks {
readonly request: SessionRequestBeforeEvent
}
export interface SessionDomain extends Pick<SessionApi, "create" | "get" | "prompt" | "command" | "interrupt"> {
readonly hook: Hooks<SessionHooks>
}
export type SessionDomain = Pick<SessionApi, "create" | "get" | "prompt" | "command" | "interrupt">
+17 -35
View File
@@ -1,29 +1,22 @@
export * as Tool from "./tool.js"
import { Tool } from "../effect/tool.js"
import type { ToolOutput, ToolResultValue } from "@opencode-ai/llm"
import type { Tool } from "../effect/tool.js"
import type { Agent } from "@opencode-ai/schema/agent"
import type { Session } from "@opencode-ai/schema/session"
import type { SessionMessage } from "@opencode-ai/schema/session-message"
import { Effect, type JsonSchema, type Schema } from "effect"
import type { JsonSchema, Schema } from "effect"
import type { Hooks, Transform } from "./registration.js"
export type Context = Tool.Context
export type SchemaType<A> = Tool.SchemaType<A>
export type Definition<Input extends SchemaType<any>, Output extends SchemaType<any>> = Tool.Definition<Input, Output>
export type AnyTool = Tool.AnyTool
export const Failure = Tool.Failure
export type Failure = Tool.Failure
export const RegistrationError = Tool.RegistrationError
export type RegistrationError = Tool.RegistrationError
export type Content = Tool.Content
export type DynamicOutput = Tool.DynamicOutput
type Config<
export type Definition<
Input extends SchemaType<any>,
Output extends SchemaType<any>,
Structured extends SchemaType<any> = Output,
> = {
readonly name: string
readonly options?: RegisterOptions
readonly description: string
readonly input: Input
readonly output: Output
@@ -42,32 +35,16 @@ type Config<
}) => ReadonlyArray<Content>
}
type DynamicConfig = {
export type DynamicDefinition = {
readonly name: string
readonly options?: RegisterOptions
readonly description: string
readonly jsonSchema: JsonSchema.JsonSchema
readonly outputSchema?: JsonSchema.JsonSchema
readonly execute: (input: unknown, context: Context) => Promise<DynamicOutput>
}
export function make<
Input extends SchemaType<any>,
Output extends SchemaType<any>,
Structured extends SchemaType<any> = Output,
>(config: Config<Input, Output, Structured>): Definition<Input, Structured>
export function make(config: DynamicConfig): AnyTool
export function make(config: Config<any, any, any> | DynamicConfig): AnyTool {
if ("jsonSchema" in config)
return Tool.make({
...config,
execute: (input, context) => Effect.promise(() => config.execute(input, context)),
})
return Tool.make({
...config,
execute: (input, context) => Effect.promise(() => config.execute(input, context)),
})
}
export const withPermission = Tool.withPermission
export type AnyTool = Definition<any, any, any> | DynamicDefinition
export interface ToolExecuteBeforeEvent {
readonly tool: string
@@ -85,8 +62,8 @@ export interface ToolExecuteAfterEvent {
readonly assistantMessageID: SessionMessage.ID
readonly toolCallID: string
readonly input: unknown
result: ToolResultValue
output?: ToolOutput
result: Tool.ToolExecuteAfterEvent["result"]
output?: Tool.ToolExecuteAfterEvent["output"]
outputPaths?: ReadonlyArray<string>
}
@@ -96,7 +73,12 @@ export interface RegisterOptions {
}
export interface ToolDraft {
add(name: string, tool: AnyTool, options?: RegisterOptions): void
add<
Input extends SchemaType<any>,
Output extends SchemaType<any>,
Structured extends SchemaType<any> = Output,
>(tool: Definition<Input, Output, Structured>): void
add(tool: DynamicDefinition): void
}
export interface ToolHooks {
@@ -32,10 +32,9 @@ test.each([
"Credential",
"Integration",
"Model",
"Plugin",
"Provider",
"Reference",
"Skill",
...(name === "effect" ? ["Tool"] : []),
"define",
])
})
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "./tsconfig.json",
"compilerOptions": {
"allowImportingTsExtensions": false,
"noEmit": false
}
}
+3 -5
View File
@@ -14,11 +14,9 @@ import { LocationQuery, locationQueryOpenApi } from "./location.js"
const CreatePayload = Schema.Struct({
id: Form.ID.pipe(Schema.optional),
title: Form.FormInfo.fields.title,
metadata: Form.FormInfo.fields.metadata,
mode: Schema.Literals(["form", "url"]),
fields: Form.FormInfo.fields.fields.pipe(Schema.optional),
url: Form.UrlInfo.fields.url.pipe(Schema.optional),
title: Form.Info.fields.title,
metadata: Form.Info.fields.metadata,
fields: Form.Info.fields.fields,
}).annotate({ identifier: "Form.CreatePayload" })
export type CreatePayload = typeof CreatePayload.Type
+25 -19
View File
@@ -94,10 +94,27 @@ export const MultiselectField = Schema.Struct({
}).annotate({ identifier: "Form.MultiselectField" })
export interface MultiselectField extends Schema.Schema.Type<typeof MultiselectField> {}
export const Field = Schema.Union([StringField, NumberField, IntegerField, BooleanField, MultiselectField]).pipe(
Schema.toTaggedUnion("type"),
)
export type Field = StringField | NumberField | IntegerField | BooleanField | MultiselectField
export const ExternalField = Schema.Struct({
key: Schema.String,
type: Schema.Literal("external"),
url: Schema.String,
title: Schema.String.pipe(optional),
description: Schema.String.pipe(optional),
}).annotate({ identifier: "Form.ExternalField" })
export interface ExternalField extends Schema.Schema.Type<typeof ExternalField> {}
export const Field = Schema.Union([
StringField,
NumberField,
IntegerField,
BooleanField,
MultiselectField,
ExternalField,
]).pipe(Schema.toTaggedUnion("type"), Schema.annotate({ identifier: "Form.Field" }))
export type Field = StringField | NumberField | IntegerField | BooleanField | MultiselectField | ExternalField
export const Fields = Schema.NonEmptyArray(Field).annotate({ identifier: "Form.Fields" })
export type Fields = typeof Fields.Type
const InfoBase = {
id: ID,
@@ -110,22 +127,11 @@ const InfoBase = {
metadata: Metadata.pipe(optional),
}
export const FormInfo = Schema.Struct({
export const Info = Schema.Struct({
...InfoBase,
mode: Schema.Literal("form"),
fields: Schema.Array(Field),
}).annotate({ identifier: "Form.FormInfo" })
export interface FormInfo extends Schema.Schema.Type<typeof FormInfo> {}
export const UrlInfo = Schema.Struct({
...InfoBase,
mode: Schema.Literal("url"),
url: Schema.String,
}).annotate({ identifier: "Form.UrlInfo" })
export interface UrlInfo extends Schema.Schema.Type<typeof UrlInfo> {}
export const Info = Schema.Union([FormInfo, UrlInfo]).pipe(Schema.toTaggedUnion("mode"))
export type Info = FormInfo | UrlInfo
fields: Fields,
}).annotate({ identifier: "Form.Info" })
export interface Info extends Schema.Schema.Type<typeof Info> {}
export const Value = Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Array(Schema.String)]).annotate(
{
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
import { DateTime, Schema } from "effect"
import { Agent } from "../src/agent.js"
import { FileSystem } from "../src/filesystem.js"
import { Form } from "../src/form.js"
import { Mcp } from "../src/mcp.js"
import { Model } from "../src/model.js"
import { Project } from "../src/project.js"
@@ -47,6 +48,33 @@ describe("contract hygiene", () => {
).toEqual({ text: "completed" })
})
test("forms require at least one field", () => {
expect(() =>
Schema.decodeUnknownSync(Form.Info)({
id: Form.ID.create(),
sessionID: "global",
title: "Empty form",
fields: [],
}),
).toThrow()
expect(
Schema.decodeUnknownSync(Form.Info)({
id: Form.ID.create(),
sessionID: "global",
title: "External form",
fields: [{ key: "authorization", type: "external", url: "https://example.com" }],
}).fields,
).toHaveLength(1)
expect(() =>
Schema.decodeUnknownSync(Form.Info)({
id: Form.ID.create(),
sessionID: "global",
title: "External form",
fields: [{ type: "external", url: "https://example.com" }],
}),
).toThrow()
})
test("model defaults and provider overlays preserve public invariants", () => {
const id = Model.ID.make("model")
expect(Model.Info.empty(Provider.ID.make("provider"), id)).toMatchObject({ modelID: id, variants: [] })
@@ -69,6 +97,10 @@ describe("contract hygiene", () => {
const identifiers = [
Agent.Color,
FileSystem.Submatch,
Form.Field,
Form.Fields,
Form.Info,
Form.ExternalField,
Mcp.Resource,
Mcp.ResourceTemplate,
Mcp.ResourceCatalog,
+42 -48
View File
@@ -1408,7 +1408,7 @@ export type GlobalEvent = {
id: string
type: "form.created"
properties: {
form: FormFormInfo | FormUrlInfo
form: FormInfo
}
}
| {
@@ -3545,22 +3545,30 @@ export type FormMultiselectField = {
default?: Array<string>
}
export type FormFormInfo = {
id: string
sessionID: string
title: string
metadata?: FormMetadata
mode: "form"
fields: Array<FormStringField | FormNumberField | FormIntegerField | FormBooleanField | FormMultiselectField>
export type FormExternalField = {
key: string
type: "external"
url: string
title?: string
description?: string
}
export type FormUrlInfo = {
export type FormField =
| FormStringField
| FormNumberField
| FormIntegerField
| FormBooleanField
| FormMultiselectField
| FormExternalField
export type FormFields = Array<FormField>
export type FormInfo = {
id: string
sessionID: string
title: string
metadata?: FormMetadata
mode: "url"
url: string
fields: FormFields
}
export type FormValue =
@@ -5835,9 +5843,7 @@ export type FormCreatePayload = {
id?: string
title: string
metadata?: FormMetadata
mode: "form" | "url"
fields?: Array<FormStringField | FormNumberField | FormIntegerField | FormBooleanField | FormMultiselectField>
url?: string
fields: FormFields
}
export type FormState =
@@ -6558,7 +6564,7 @@ export type FormCreated = {
type: "form.created"
location?: LocationRef
data: {
form: FormFormInfo | FormUrlInfo
form: FormInfo
}
}
@@ -7830,7 +7836,7 @@ export type EventFormCreated = {
id: string
type: "form.created"
properties: {
form: FormFormInfo | FormUrlInfo
form: FormInfo
}
}
@@ -9888,33 +9894,21 @@ export type FormMultiselectFieldV2 = {
default?: Array<string>
}
export type FormFormInfoV2 = {
id: string
sessionID: string
title: string
metadata?: FormMetadata
mode: "form"
fields: Array<FormStringFieldV2 | FormNumberField | FormIntegerField | FormBooleanField | FormMultiselectFieldV2>
}
export type FormFieldsV2 = [FormField, FormField]
export type FormUrlInfoV2 = {
export type FormInfoV2 = {
id: string
sessionID: string
title: string
metadata?: FormMetadata
mode: "url"
url: string
fields: FormFieldsV2
}
export type FormCreatePayloadV2 = {
id?: string | null
title: string
metadata?: FormMetadata
mode: "form" | "url"
fields?: Array<
FormStringFieldV2 | FormNumberField | FormIntegerField | FormBooleanField | FormMultiselectFieldV2
> | null
url?: string | null
fields: FormFieldsV2
}
export type FormValueV2 =
@@ -10623,22 +10617,22 @@ export type FormMultiselectField1 = {
default?: Array<string>
}
export type FormFormInfo1 = {
id: string
sessionID: string
title: string
metadata?: FormMetadata1
mode: "form"
fields: Array<FormStringField1 | FormNumberField1 | FormIntegerField1 | FormBooleanField1 | FormMultiselectField1>
}
export type FormField1 =
| FormStringField1
| FormNumberField1
| FormIntegerField1
| FormBooleanField1
| FormMultiselectField1
| FormExternalField
export type FormUrlInfo1 = {
export type FormFields1 = [FormField1, FormField1]
export type FormInfo1 = {
id: string
sessionID: string
title: string
metadata?: FormMetadata1
mode: "url"
url: string
fields: FormFields1
}
export type FormCreatedV2 = {
@@ -10650,7 +10644,7 @@ export type FormCreatedV2 = {
type: "form.created"
location?: LocationRefV2
data: {
form: FormFormInfo1 | FormUrlInfo1
form: FormInfo1
}
}
@@ -17240,7 +17234,7 @@ export type V2FormRequestListResponses = {
*/
200: {
location: LocationInfoV2
data: Array<FormFormInfoV2 | FormUrlInfoV2>
data: Array<FormInfoV2>
}
}
@@ -17277,7 +17271,7 @@ export type V2SessionFormListResponses = {
* Success
*/
200: {
data: Array<FormFormInfoV2 | FormUrlInfoV2>
data: Array<FormInfoV2>
}
}
@@ -17318,7 +17312,7 @@ export type V2SessionFormCreateResponses = {
* Success
*/
200: {
data: FormFormInfoV2 | FormUrlInfoV2
data: FormInfoV2
}
}
@@ -17356,7 +17350,7 @@ export type V2SessionFormGetResponses = {
* Success
*/
200: {
data: FormFormInfoV2 | FormUrlInfoV2
data: FormInfoV2
}
}
+15 -23
View File
@@ -44,29 +44,21 @@ export const FormHandler = HttpApiBuilder.group(Api, "server.form", (handlers) =
"session.form.create",
Effect.fn(function* (ctx) {
const form = yield* Form.Service
const common = {
id: ctx.payload.id,
sessionID: ctx.params.sessionID,
title: ctx.payload.title,
metadata: ctx.payload.metadata,
}
const input = yield* (() => {
if (ctx.payload.mode === "form") {
if (!ctx.payload.fields) {
return new InvalidRequestError({ message: "Form fields are required", field: "fields" })
}
return Effect.succeed({ ...common, mode: "form" as const, fields: ctx.payload.fields })
}
if (!ctx.payload.url) return new InvalidRequestError({ message: "Form URL is required", field: "url" })
return Effect.succeed({ ...common, mode: "url" as const, url: ctx.payload.url })
})()
const created = yield* form.create(input).pipe(
Effect.catchTags({
"Form.AlreadyExistsError": (error) => new ConflictError({ resource: error.id, message: error.message }),
"Form.InvalidFormError": (error) => new InvalidRequestError({ message: error.message, field: "fields" }),
}),
)
const created = yield* form
.create({
id: ctx.payload.id,
sessionID: ctx.params.sessionID,
title: ctx.payload.title,
metadata: ctx.payload.metadata,
fields: ctx.payload.fields,
})
.pipe(
Effect.catchTags({
"Form.AlreadyExistsError": (error) => new ConflictError({ resource: error.id, message: error.message }),
"Form.InvalidFormError": (error) =>
new InvalidRequestError({ message: error.message, field: "fields" }),
}),
)
return { data: created }
}),
)
+2 -8
View File
@@ -196,9 +196,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
const api = OpenCode.make(options)
const directory = yield* Effect.tryPromise(() => api.file.list({ location: { directory: process.cwd() } })).pipe(
Effect.map((response) => response.location.directory),
Effect.catch(() =>
Effect.tryPromise(() => api.location.get()).pipe(Effect.map((response) => response.directory)),
),
Effect.catch(() => Effect.tryPromise(() => api.location.get()).pipe(Effect.map((response) => response.directory))),
)
const reconnectEndpoint = input.server.reconnect
const reconnect = reconnectEndpoint
@@ -411,11 +409,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
})
})
function App(props: {
onSnapshot?: () => Promise<string[]>
pluginHost: TuiPluginHost
pair?: DialogPairCredentials
}) {
function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPluginHost; pair?: DialogPairCredentials }) {
const log = useLog({ component: "app" })
const startup = useTuiStartup()
const tuiConfig = useTuiConfig()
+21 -19
View File
@@ -1044,22 +1044,7 @@ export function Prompt(props: PromptProps) {
// Capture mode before it gets reset
const currentMode = store.mode
const editorSelection = editorContext()
const editorParts =
editorSelection && editor.labelState() === "pending"
? [
{
type: "text" as const,
text: formatEditorContext(editorSelection),
synthetic: true,
metadata: {
kind: "editor_context",
source: editorSelection.source ?? "editor",
filePath: editorSelection.filePath,
ranges: editorSelection.ranges,
},
},
]
: []
const pendingEditorSelection = editorSelection && editor.labelState() === "pending" ? editorSelection : undefined
if (store.mode === "shell") {
move.startSubmit()
@@ -1135,10 +1120,27 @@ export function Prompt(props: PromptProps) {
return false
}
}
if (pendingEditorSelection) {
// Keep editor context hidden while admitting it before the corresponding user prompt.
const error = await sdk.api.session
.synthetic({
sessionID,
text: formatEditorContext(pendingEditorSelection),
resume: false,
})
.then(
() => undefined,
(error) => error,
)
if (error) {
toast.show({ title: "Failed to send editor context", message: errorMessage(error), variant: "error" })
return false
}
}
const error = await sdk.api.session
.prompt({
sessionID,
text: [...editorParts.map((part) => part.text), inputText].filter(Boolean).join("\n\n"),
text: inputText,
files: store.prompt.files,
agents: store.prompt.agents,
})
@@ -1150,7 +1152,7 @@ export function Prompt(props: PromptProps) {
toast.show({ title: "Failed to send prompt", message: errorMessage(error), variant: "error" })
return false
}
if (editorParts.length > 0) editor.markSelectionSent()
if (pendingEditorSelection) editor.markSelectionSent()
}
history.append({
...store.prompt,
@@ -1163,7 +1165,7 @@ export function Prompt(props: PromptProps) {
// temporary hack to make sure the message is sent
if (!props.sessionID) {
if (editorParts.length > 0) editor.preserveSelectionFromNewSession()
if (pendingEditorSelection) editor.preserveSelectionFromNewSession()
setTimeout(() => {
route.navigate({
type: "session",
+4 -5
View File
@@ -6,8 +6,7 @@
import type {
AgentInfo,
CommandInfo,
FormFormInfo,
FormUrlInfo,
FormInfo,
IntegrationInfo,
LocationRef,
McpServer,
@@ -38,7 +37,7 @@ const messageIDFromEvent = (eventID: string) => eventID.replace(/^evt_/, "msg_")
// Global MCP elicitations temporarily use "global" instead of a real session ID, so the
// server cannot recover their Location when settling them. Preserve the event Location
// until MCP elicitations carry session ownership.
export type FormInfo = (FormFormInfo | FormUrlInfo) & { readonly location?: LocationRef }
export type FormWithLocation = FormInfo & { readonly location?: LocationRef }
type LocationData = {
agent?: AgentInfo[]
@@ -66,7 +65,7 @@ type Data = {
input: Record<string, string[]>
permission: Record<string, PermissionV2Request[]>
// Pending forms keyed by owner: a session ID or the temporary "global" elicitation sentinel.
form: Record<string, FormInfo[]>
form: Record<string, FormWithLocation[]>
}
project: {
permission: Record<string, PermissionSavedInfo[]>
@@ -1033,7 +1032,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
directory: response.location.directory,
workspaceID: response.location.workspaceID,
}
const forms = response.data.reduce<Record<string, FormInfo[]>>(
const forms = response.data.reduce<Record<string, FormWithLocation[]>>(
(result, form) => ({
...result,
[form.sessionID]: [
-6
View File
@@ -92,12 +92,6 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
const event = await iterator.next()
if (abort.signal.aborted || controller.signal.aborted) return
if (event.done) return new Error("Event stream disconnected")
if ("durable" in event.value)
log.info("event", {
type: event.value.type,
aggregateID: event.value.durable.aggregateID,
seq: event.value.durable.seq,
})
events.emit(event.value.type, event.value)
}
})()
+303 -244
View File
@@ -4,19 +4,25 @@ import { useRenderer, useTerminalDimensions } from "@opentui/solid"
import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"
import open from "open"
import { selectedForeground, tint, useTheme } from "../../context/theme"
import type { FormFormInfo, FormValue } from "@opencode-ai/sdk/v2"
import type { FormInfo } from "../../context/data"
import type { FormField, FormValue } from "@opencode-ai/sdk/v2"
import type { FormWithLocation } from "../../context/data"
import { useSDK } from "../../context/sdk"
import { useClipboard } from "../../context/clipboard"
import { SplitBorder } from "../../ui/border"
import { useToast } from "../../ui/toast"
import { useTuiConfig } from "../../config"
import { useBindings, useOpencodeModeStack } from "../../keymap"
const FORM_MODE = "form"
type Field = FormFormInfo["fields"][number]
type Field = Exclude<FormField, { type: "external" }>
function fieldLabel(field: Field) {
return field.title ?? field.key
function isField(field: FormField): field is Field {
return field.type !== "external"
}
function fieldLabel(field: FormField) {
return field.title ?? (field.type === "external" ? field.url : field.key)
}
function truncate(label: string, max: number) {
@@ -24,7 +30,7 @@ function truncate(label: string, max: number) {
}
function validateText(field: Field, text: string): string | undefined {
if (field.type !== "string") return
if (field.type !== "string") return undefined
if (field.minLength !== undefined && text.length < field.minLength)
return `Must be at least ${field.minLength} characters`
if (field.maxLength !== undefined && text.length > field.maxLength)
@@ -50,17 +56,19 @@ function validateText(field: Field, text: string): string | undefined {
return "Expected a date (YYYY-MM-DD)"
}
if (field.format === "date-time" && Number.isNaN(new Date(text).getTime())) return "Expected a date and time"
return undefined
}
function validateSelection(field: Field, value: FormValue | undefined) {
if (field.type !== "multiselect" || value === undefined) return
function validateSelection(field: Field, value: FormValue | undefined): string | undefined {
if (field.type !== "multiselect" || value === undefined) return undefined
if (!Array.isArray(value)) return "Expected selections"
if (field.required && value.length === 0) return "Select at least one option"
if (field.minItems !== undefined && value.length < field.minItems) return `Select at least ${field.minItems}`
if (field.maxItems !== undefined && value.length > field.maxItems) return `Select at most ${field.maxItems}`
return undefined
}
function validateValue(field: Field, value: FormValue | undefined) {
function validateValue(field: Field, value: FormValue | undefined): string | undefined {
if (value === undefined) return field.required ? "Answer required" : undefined
if (field.required && (value === "" || (Array.isArray(value) && value.length === 0))) {
return field.type === "multiselect" ? "Select at least one option" : "Answer required"
@@ -72,14 +80,14 @@ function validateValue(field: Field, value: FormValue | undefined) {
if (field.options && !field.custom && !field.options.some((option) => option.value === value)) {
return "Select an available option"
}
return
return undefined
}
if (field.type === "number" || field.type === "integer") {
if (typeof value !== "number" || !Number.isFinite(value)) return "Expected a number"
if (field.type === "integer" && !Number.isInteger(value)) return "Expected an integer"
if (typeof field.minimum === "number" && value < field.minimum) return `Must be at least ${field.minimum}`
if (typeof field.maximum === "number" && value > field.maximum) return `Must be at most ${field.maximum}`
return
return undefined
}
if (field.type === "boolean") return typeof value === "boolean" ? undefined : "Expected yes or no"
const invalid = validateSelection(field, value)
@@ -91,6 +99,7 @@ function validateValue(field: Field, value: FormValue | undefined) {
) {
return "Select only available options"
}
return undefined
}
function fieldRows(field: Field): { value: FormValue; label: string; description?: string }[] {
@@ -117,11 +126,6 @@ function selectedRow(field: Field | undefined, value: FormValue | undefined) {
return 0
}
function customDefault(field: Field) {
if (field.type !== "string" || !field.options || !field.custom || typeof field.default !== "string") return
if (!field.options.some((option) => option.value === field.default)) return field.default
}
function display(field: Field, value: FormValue | undefined) {
if (value === undefined) return ""
const label = (item: string | number | boolean) =>
@@ -130,7 +134,7 @@ function display(field: Field, value: FormValue | undefined) {
return label(value)
}
function requestOptions(form: FormInfo) {
function requestOptions(form: FormWithLocation) {
if (form.sessionID !== "global" || !form.location) return undefined
return {
headers: {
@@ -140,107 +144,32 @@ function requestOptions(form: FormInfo) {
}
}
export function FormPrompt(props: { form: FormInfo }) {
return props.form.mode === "url" ? <UrlPrompt form={props.form} /> : <FieldsPrompt form={props.form} />
}
function UrlPrompt(props: { form: FormInfo & { mode: "url" } }) {
const sdk = useSDK()
const { theme } = useTheme()
const modeStack = useOpencodeModeStack()
const message = createMemo(() => {
const value = props.form.metadata?.["message"]
return typeof value === "string" ? value : undefined
})
onMount(() => onCleanup(modeStack.push(FORM_MODE)))
useBindings(() => ({
mode: FORM_MODE,
enabled: true,
commands: [
{
name: "app.exit",
title: "Dismiss form",
category: "Form",
run() {
void sdk.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
},
},
],
bindings: [
{
key: "return",
desc: "Open link",
group: "Form",
cmd: () => {
void open(props.form.url)
},
},
{
key: "escape",
desc: "Dismiss form",
group: "Form",
cmd: () => {
void sdk.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
},
},
],
}))
return (
<box
backgroundColor={theme.backgroundPanel}
border={["left"]}
borderColor={theme.accent}
customBorderChars={SplitBorder.customBorderChars}
>
<box gap={1} paddingLeft={2} paddingRight={3} paddingTop={1} paddingBottom={1}>
<text fg={theme.text}>{props.form.title}</text>
<Show when={message()}>
<text fg={theme.textMuted}>{message()}</text>
</Show>
<text fg={theme.secondary}>{props.form.url}</text>
</box>
<box flexDirection="row" flexShrink={0} gap={2} paddingLeft={2} paddingRight={3} paddingBottom={1}>
<text fg={theme.text}>
enter <span style={{ fg: theme.textMuted }}>open link</span>
</text>
<text fg={theme.text}>
esc <span style={{ fg: theme.textMuted }}>dismiss</span>
</text>
</box>
</box>
)
}
function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
export function FormPrompt(props: { form: FormWithLocation }) {
const sdk = useSDK()
const { theme } = useTheme()
const renderer = useRenderer()
const dimensions = useTerminalDimensions()
const tuiConfig = useTuiConfig()
const modeStack = useOpencodeModeStack()
const clipboard = useClipboard()
const toast = useToast()
const configuredFields = props.form.fields.filter(isField)
const [tabHover, setTabHover] = createSignal<number | "confirm" | null>(null)
const [store, setStore] = createStore({
tab: 0,
answers: Object.fromEntries(
props.form.fields.flatMap((field) => (field.default === undefined ? [] : [[field.key, field.default]])),
configuredFields.flatMap((field) => (field.default === undefined ? [] : [[field.key, field.default]])),
) as Record<string, FormValue | undefined>,
custom: Object.fromEntries(
props.form.fields.flatMap((field) => {
const value = customDefault(field)
return value === undefined ? [] : [[field.key, value]]
configuredFields.flatMap((field) => {
if (field.type !== "string" || !field.options || !field.custom || typeof field.default !== "string") return []
if (field.options.some((option) => option.value === field.default)) return []
return [[field.key, field.default]]
}),
) as Record<string, string>,
selected: selectedRow(props.form.fields[0], props.form.fields[0]?.default),
externalReady: {} as Record<string, boolean>,
selected: selectedRow(configuredFields[0], configuredFields[0]?.default),
editing: false,
error: "",
})
@@ -248,9 +177,14 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
let textarea: TextareaRenderable | undefined
let review: ScrollBoxRenderable | undefined
const message = createMemo(() => {
const value = props.form.metadata?.["message"]
return typeof value === "string" ? value : undefined
})
const fields = createMemo(() => {
const answers: Record<string, FormValue | undefined> = {}
return props.form.fields.filter((field) => {
if (field.type === "external") return true
const active = (field.when ?? []).every((when) => {
const value = answers[when.key]
if (value === undefined) return false
@@ -263,9 +197,9 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
})
const single = createMemo(() => {
const list = fields()
if (props.form.fields.length !== 1) return false
if (list.length !== 1) return false
const field = list[0]!
const field = list[0]
if (field.type === "external") return false
return field.type === "boolean" || (field.type === "string" && field.options !== undefined)
})
const tabs = createMemo(() => (single() ? 1 : fields().length + 1))
@@ -280,10 +214,18 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
return value !== undefined
}).length,
)
const field = createMemo(() => fields()[Math.min(store.tab, fields().length - 1)])
const field = createMemo(() => fields()[store.tab])
const answerField = createMemo(() => {
const current = field()
return current && isField(current) ? current : undefined
})
const externalField = createMemo(() => {
const current = field()
return current?.type === "external" ? current : undefined
})
const confirm = createMemo(() => !single() && store.tab >= fields().length)
const rows = createMemo(() => {
const current = field()
const current = answerField()
if (!current) return []
const configured = fieldRows(current)
const value = store.answers[current.key]
@@ -296,21 +238,32 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
})
const textual = createMemo(() => {
if (confirm()) return false
const current = field()
const current = answerField()
if (!current) return false
if (current.type === "number" || current.type === "integer") return true
return current.type === "string" && current.options === undefined
})
const custom = createMemo(() => {
const current = field()
const current = answerField()
if (!current) return false
if (current.type === "string" && current.options !== undefined) return current.custom === true
if (current.type === "multiselect") return current.custom === true
return false
})
const multi = createMemo(() => field()?.type === "multiselect")
const multi = createMemo(() => answerField()?.type === "multiselect")
const actionLabel = createMemo(() => {
if (confirm()) return "submit"
const external = externalField()
if (external) {
if (store.answers[external.key] === true) return "continue"
return store.externalReady[external.key] ? "I finished" : "open link"
}
if (multi()) return "toggle"
if (single()) return "submit"
return "confirm"
})
const placeholder = createMemo(() => {
const current = field()
const current = answerField()
if (current?.type === "string") {
if (current.placeholder) return current.placeholder
if (current.format === "email") return "name@example.com"
@@ -328,11 +281,11 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
return "Type your answer"
})
const other = createMemo(() => custom() && store.selected === rows().length)
const input = createMemo(() => store.custom[field()?.key ?? ""] ?? "")
const input = createMemo(() => store.custom[answerField()?.key ?? ""] ?? "")
const customPicked = createMemo(() => {
const value = input()
if (!value) return false
const answer = store.answers[field()?.key ?? ""]
const answer = store.answers[answerField()?.key ?? ""]
if (Array.isArray(answer)) return answer.includes(value)
return answer === value
})
@@ -363,7 +316,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
}
function pick(value: FormValue, customValue?: string) {
const current = field()
const current = answerField()
if (!current) return
const invalid = validateValue(current, value)
if (invalid) {
@@ -380,7 +333,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
}
function toggle(value: string) {
const current = field()
const current = answerField()
if (!current) return
const existing = store.answers[current.key]
const list = Array.isArray(existing) ? [...existing] : []
@@ -392,7 +345,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
function validateCurrent() {
if (confirm()) return true
const current = field()
const current = answerField()
if (!current) return true
const invalid = validateValue(current, store.answers[current.key])
if (!invalid) return true
@@ -404,7 +357,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
if (!confirm() && index > store.tab && !validateCurrent()) return
const next = fields()[index]
setStore("tab", index)
setStore("selected", selectedRow(next, next ? store.answers[next.key] : undefined))
setStore("selected", next && isField(next) ? selectedRow(next, store.answers[next.key]) : 0)
setStore("editing", false)
setStore("error", "")
}
@@ -433,7 +386,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
}
function commitInput(text: string) {
const current = field()
const current = answerField()
if (!current) return false
const isTextual = textual()
const isMulti = multi()
@@ -507,9 +460,9 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
if (!single()) selectTab((store.tab + direction + tabs()) % tabs())
}
function selectTabFromMouse(target?: Field) {
function selectTabFromMouse(target?: FormField) {
const targetIndex = () => {
const index = target ? fields().findIndex((field) => field.key === target.key) : fields().length
const index = target ? fields().findIndex((field) => field === target) : fields().length
return index === -1 ? fields().length : index
}
const move = () => selectTab(targetIndex())
@@ -524,6 +477,83 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
move()
}
function cancel() {
void sdk.api.form.cancel({ sessionID: props.form.sessionID, formID: props.form.id }, requestOptions(props.form))
}
function openExternal() {
const current = externalField()
if (!current) return
setStore("error", "")
void open(current.url)
.then(() => setStore("externalReady", { ...store.externalReady, [current.key]: true }))
.catch(() => setStore("error", "Could not open the browser. Copy the URL and continue manually."))
}
function copyExternal() {
const current = externalField()
if (!current || !clipboard.write) return
void clipboard
.write(current.url)
.then(() => {
setStore("externalReady", { ...store.externalReady, [current.key]: true })
toast.show({ message: "Copied URL to clipboard", variant: "info" })
})
.catch(toast.error)
}
function acknowledgeExternal() {
const current = externalField()
if (!current) return
if (store.answers[current.key] === true) {
selectTab(store.tab + 1)
return
}
if (!store.externalReady[current.key]) {
openExternal()
return
}
answer(current.key, true)
selectTab(store.tab + 1)
}
function submit() {
const unacknowledged = fields().find((field) => field.type === "external" && store.answers[field.key] !== true)
if (unacknowledged) {
setStore("error", `External action must be acknowledged: ${fieldLabel(unacknowledged)}`)
return
}
const invalid = fields()
.filter(isField)
.find((field) => validateValue(field, store.answers[field.key]))
if (invalid) {
setStore("error", validateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer")
return
}
sdk.api.form
.reply(
{
sessionID: props.form.sessionID,
formID: props.form.id,
answer: Object.fromEntries(
fields().flatMap((field) => {
const value = store.answers[field.key]
return value === undefined ? [] : [[field.key, value] as const]
}),
),
},
requestOptions(props.form),
)
.catch((error: unknown) => {
setStore(
"error",
typeof error === "object" && error !== null && "message" in error && typeof error.message === "string"
? error.message
: "Invalid answer",
)
})
}
onMount(() => onCleanup(modeStack.push(FORM_MODE)))
useBindings(() => ({
@@ -585,7 +615,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
group: "Form",
cmd: () => {
const text = textarea?.plainText?.trim() ?? ""
const current = field()
const current = answerField()
if (!current) return
if (textual()) {
submitInput(text)
@@ -606,6 +636,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
useBindings(() => {
const total = rows().length + (custom() ? 1 : 0)
const max = Math.min(total, 9)
const external = externalField()
return {
mode: FORM_MODE,
@@ -615,12 +646,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
name: "app.exit",
title: "Dismiss form",
category: "Form",
run() {
void sdk.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
},
run: cancel,
},
],
bindings: [
@@ -650,110 +676,86 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
group: "Form",
cmd: () => selectTab((store.tab - 1 + tabs()) % tabs()),
},
...(confirm()
...(external
? [
{
key: "return",
desc: "Submit form",
desc:
store.answers[external.key] === true
? "Continue"
: store.externalReady[external.key]
? "Confirm completion"
: "Open link",
group: "Form",
cmd: () => {
const invalid = fields().find((field) => validateValue(field, store.answers[field.key]))
if (invalid) {
setStore("error", validateValue(invalid, store.answers[invalid.key]) ?? "Invalid answer")
return
}
sdk.api.form
.reply(
{
sessionID: props.form.sessionID,
formID: props.form.id,
answer: Object.fromEntries(
fields().flatMap((field) => {
const value = store.answers[field.key]
return value === undefined ? [] : [[field.key, value] as const]
}),
),
},
requestOptions(props.form),
)
.catch((error: unknown) => {
setStore(
"error",
typeof error === "object" &&
error !== null &&
"message" in error &&
typeof error.message === "string"
? error.message
: "Invalid answer",
)
})
},
cmd: acknowledgeExternal,
},
{
key: "escape",
desc: "Dismiss form",
group: "Form",
cmd: () => {
void sdk.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
},
},
{ key: "up", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(-1) },
{ key: "k", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(-1) },
{ key: "down", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(1) },
{ key: "j", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(1) },
{ key: "c", desc: "Copy link", group: "Form", cmd: copyExternal },
{ key: "escape", desc: "Dismiss form", group: "Form", cmd: cancel },
...tuiConfig.keybinds.get("app.exit"),
]
: [
...Array.from({ length: max }, (_, index) => ({
key: String(index + 1),
desc: `Select answer ${index + 1}`,
group: "Form",
cmd: () => {
setStore("selected", index)
selectOption()
: confirm()
? [
{
key: "return",
desc: "Submit form",
group: "Form",
cmd: submit,
},
})),
{
key: "up",
desc: "Previous answer",
group: "Form",
cmd: () => setStore("selected", (store.selected - 1 + total) % total),
},
{
key: "k",
desc: "Previous answer",
group: "Form",
cmd: () => setStore("selected", (store.selected - 1 + total) % total),
},
{
key: "down",
desc: "Next answer",
group: "Form",
cmd: () => setStore("selected", (store.selected + 1) % total),
},
{
key: "j",
desc: "Next answer",
group: "Form",
cmd: () => setStore("selected", (store.selected + 1) % total),
},
{ key: "return", desc: "Select answer", group: "Form", cmd: () => selectOption() },
{
key: "escape",
desc: "Dismiss form",
group: "Form",
cmd: () => {
void sdk.api.form.cancel(
{ sessionID: props.form.sessionID, formID: props.form.id },
requestOptions(props.form),
)
{
key: "escape",
desc: "Dismiss form",
group: "Form",
cmd: cancel,
},
},
...tuiConfig.keybinds.get("app.exit"),
]),
{ key: "up", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(-1) },
{ key: "k", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(-1) },
{ key: "down", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(1) },
{ key: "j", desc: "Scroll review", group: "Form", cmd: () => review?.scrollBy(1) },
...tuiConfig.keybinds.get("app.exit"),
]
: [
...Array.from({ length: max }, (_, index) => ({
key: String(index + 1),
desc: `Select answer ${index + 1}`,
group: "Form",
cmd: () => {
setStore("selected", index)
selectOption()
},
})),
{
key: "up",
desc: "Previous answer",
group: "Form",
cmd: () => setStore("selected", (store.selected - 1 + total) % total),
},
{
key: "k",
desc: "Previous answer",
group: "Form",
cmd: () => setStore("selected", (store.selected - 1 + total) % total),
},
{
key: "down",
desc: "Next answer",
group: "Form",
cmd: () => setStore("selected", (store.selected + 1) % total),
},
{
key: "j",
desc: "Next answer",
group: "Form",
cmd: () => setStore("selected", (store.selected + 1) % total),
},
{ key: "return", desc: "Select answer", group: "Form", cmd: () => selectOption() },
{
key: "escape",
desc: "Dismiss form",
group: "Form",
cmd: cancel,
},
...tuiConfig.keybinds.get("app.exit"),
]),
],
}
})
@@ -769,14 +771,21 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
<box paddingLeft={1}>
<text fg={theme.textMuted}>{props.form.title}</text>
</box>
<Show when={message()}>
<box paddingLeft={1}>
<text fg={theme.text}>{message()}</text>
</box>
</Show>
<Show when={!single() && !tabbed()}>
<box flexDirection="row" gap={1} paddingLeft={1}>
<text fg={theme.textMuted}>
{confirm() ? "Review" : `Field ${Math.min(store.tab, fields().length - 1) + 1} of ${fields().length}`}
</text>
<text fg={theme.textMuted}>
· {answered()}/{fields().length} answered
</text>
<Show when={fields().length > 0}>
<text fg={theme.textMuted}>
· {answered()}/{fields().length} completed
</text>
</Show>
</box>
</Show>
<Show when={!single() && tabbed()}>
@@ -828,16 +837,45 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
</box>
</Show>
<Show when={!confirm() && field()}>
<Show when={!confirm() && externalField()}>
{(external) => (
<box paddingLeft={1} gap={1}>
<Show when={external().title}>
<text fg={theme.text}>{external().title}</text>
</Show>
<Show when={external().description}>
<text fg={theme.textMuted}>{external().description}</text>
</Show>
<text
fg={theme.primary}
onMouseUp={() => {
if (renderer.getSelection()?.getSelectedText()) return
openExternal()
}}
>
{external().url}
</text>
<text fg={store.answers[external().key] === true ? theme.success : theme.textMuted}>
{store.answers[external().key] === true
? "✓ Acknowledged"
: store.externalReady[external().key]
? "Complete the external action, then press enter to confirm."
: "Open or copy the URL, complete the external action, then confirm."}
</text>
</box>
)}
</Show>
<Show when={!confirm() && answerField()}>
<box paddingLeft={1} gap={1}>
<box>
<text fg={theme.text}>
{field()!.description ?? fieldLabel(field()!)}
{field()!.required ? " (required)" : ""}
{answerField()!.description ?? fieldLabel(answerField()!)}
{answerField()!.required ? " (required)" : ""}
{multi() ? " (select all that apply)" : ""}
</text>
</box>
<Show when={textual() ? field()!.key : undefined} keyed>
<Show when={textual() ? answerField()!.key : undefined} keyed>
<box paddingLeft={1}>
<textarea
ref={(val: TextareaRenderable) => {
@@ -848,7 +886,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
val.gotoLineEnd()
})
}}
initialValue={input() || display(field()!, store.answers[field()!.key])}
initialValue={input() || display(answerField()!, store.answers[answerField()!.key])}
placeholder={placeholder()}
placeholderColor={theme.textMuted}
minHeight={1}
@@ -865,7 +903,7 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
{(row, i) => {
const active = () => i() === store.selected
const picked = () => {
const value = store.answers[field()?.key ?? ""]
const value = store.answers[answerField()?.key ?? ""]
if (Array.isArray(value)) return value.includes(String(row.value))
return value === row.value
}
@@ -973,11 +1011,21 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
>
<For each={fields()}>
{(item) => {
const value = () => display(item, store.answers[item.key])
const answered = () => {
const value = store.answers[item.key]
return value !== undefined
if (item.type === "external") {
const acknowledged = () => store.answers[item.key] === true
return (
<box paddingLeft={1}>
<text>
<span style={{ fg: theme.textMuted }}>{truncate(fieldLabel(item), 40)}:</span>{" "}
<span style={{ fg: acknowledged() ? theme.success : theme.error }}>
{acknowledged() ? "Acknowledged" : "(acknowledgement required)"}
</span>
</text>
</box>
)
}
const value = () => display(item, store.answers[item.key])
const answered = () => store.answers[item.key] !== undefined
const missing = () => !answered() && item.required === true
const invalid = () => validateValue(item, store.answers[item.key])
return (
@@ -985,7 +1033,9 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
<text>
<span style={{ fg: theme.textMuted }}>{truncate(fieldLabel(item), 40)}:</span>{" "}
<span
style={{ fg: invalid() || missing() ? theme.error : answered() ? theme.text : theme.textMuted }}
style={{
fg: invalid() || missing() ? theme.error : answered() ? theme.text : theme.textMuted,
}}
>
{invalid() ?? (answered() ? value() : missing() ? "(required)" : "(not answered)")}
</span>
@@ -1012,23 +1062,32 @@ function FieldsPrompt(props: { form: FormInfo & { mode: "form" } }) {
{"⇆"} <span style={{ fg: theme.textMuted }}>tab</span>
</text>
</Show>
<Show when={!confirm() && !textual()}>
<Show when={!confirm() && !textual() && !externalField()}>
<text fg={theme.text}>
{"↑↓"} <span style={{ fg: theme.textMuted }}>select</span>
</text>
</Show>
<Show when={confirm()}>
<Show when={confirm() && fields().length > 0}>
<text fg={theme.text}>
{"↑↓"} <span style={{ fg: theme.textMuted }}>scroll</span>
</text>
</Show>
<text fg={theme.text}>
enter{" "}
<span style={{ fg: theme.textMuted }}>
{confirm() ? "submit" : multi() ? "toggle" : single() ? "submit" : "confirm"}
</span>
<text
fg={theme.text}
onMouseUp={() => {
if (renderer.getSelection()?.getSelectedText()) return
if (confirm()) submit()
if (externalField()) acknowledgeExternal()
}}
>
enter <span style={{ fg: theme.textMuted }}>{actionLabel()}</span>
</text>
<text fg={theme.text}>
<Show when={externalField() && clipboard.write}>
<text fg={theme.text} onMouseUp={copyExternal}>
c <span style={{ fg: theme.textMuted }}>copy</span>
</text>
</Show>
<text fg={theme.text} onMouseUp={cancel}>
esc <span style={{ fg: theme.textMuted }}>dismiss</span>
</text>
</box>
@@ -77,16 +77,12 @@ function question(id: string, sessionID = "session"): QuestionRequest {
}
}
function form(
id: string,
sessionID = "session",
): Extract<OpenCodeEvent, { type: "form.created" }>["data"]["form"] {
function form(id: string, sessionID = "session"): Extract<OpenCodeEvent, { type: "form.created" }>["data"]["form"] {
return {
id,
sessionID,
title: "Input requested",
mode: "form",
fields: [],
fields: [{ key: "authorization", type: "external", url: "https://example.com" }],
}
}
+19 -14
View File
@@ -12,6 +12,14 @@ import { createSessionRows, type SessionRow } from "../../../src/routes/session/
import { createApi, createClient, createEventStream, createFetch, directory, json } from "../../fixture/tui-sdk"
import { TestTuiContexts } from "../../fixture/tui-environment"
const formFields = [{ key: "authorization", type: "external", url: "https://example.com" }] satisfies [
{
key: string
type: "external"
url: string
},
]
async function wait(fn: () => boolean, timeout = 2000) {
const start = Date.now()
while (!fn()) {
@@ -1510,7 +1518,7 @@ test("adds, dismisses, and refreshes form requests", async () => {
const calls = createFetch((url) => {
if (url.pathname !== "/api/session/ses_1/form") return
return json({
data: [{ id: "frm_remote", sessionID: "ses_1", title: "Input requested", mode: "form", fields: [] }],
data: [{ id: "frm_remote", sessionID: "ses_1", title: "Input requested", fields: formFields }],
})
}, events)
let data!: ReturnType<typeof useData>
@@ -1540,13 +1548,13 @@ test("adds, dismisses, and refreshes form requests", async () => {
id: "evt_form_created_1",
created: 0,
type: "form.created",
data: { form: { id: "frm_1", sessionID: "ses_1", title: "Input requested", mode: "form", fields: [] } },
data: { form: { id: "frm_1", sessionID: "ses_1", title: "Input requested", fields: formFields } },
})
emitEvent(events, {
id: "evt_form_created_duplicate",
created: 1,
type: "form.created",
data: { form: { id: "frm_1", sessionID: "ses_1", title: "Input requested", mode: "form", fields: [] } },
data: { form: { id: "frm_1", sessionID: "ses_1", title: "Input requested", fields: formFields } },
})
await wait(() => data.session.form.list("ses_1")?.length === 1)
@@ -1562,7 +1570,7 @@ test("adds, dismisses, and refreshes form requests", async () => {
id: "evt_form_created_2",
created: 3,
type: "form.created",
data: { form: { id: "frm_2", sessionID: "ses_1", title: "Input requested", mode: "form", fields: [] } },
data: { form: { id: "frm_2", sessionID: "ses_1", title: "Input requested", fields: formFields } },
})
emitEvent(events, {
id: "evt_form_cancelled_2",
@@ -1612,7 +1620,7 @@ test("tracks global forms by location", async () => {
location: other,
type: "form.created",
data: {
form: { id: "frm_other", sessionID: "global", title: "Input requested", mode: "form", fields: [] },
form: { id: "frm_other", sessionID: "global", title: "Input requested", fields: formFields },
},
})
@@ -1625,7 +1633,7 @@ test("tracks global forms by location", async () => {
location: { directory },
type: "form.created",
data: {
form: { id: "frm_default", sessionID: "global", title: "Input requested", mode: "form", fields: [] },
form: { id: "frm_default", sessionID: "global", title: "Input requested", fields: formFields },
},
})
await wait(() => data.session.form.list("global", { directory })?.length === 1)
@@ -1664,8 +1672,7 @@ test("refreshes global forms for the requested location", async () => {
id: requestedDirectory === other.directory ? "frm_other" : "frm_default",
sessionID: "global",
title: "Input requested",
mode: "form",
fields: [],
fields: formFields,
},
],
})
@@ -1743,8 +1750,7 @@ test("refreshes global forms once per loaded location after reconnect", async ()
id: `frm_${requestedDirectory === other.directory ? "other" : "default"}_${count}`,
sessionID: "global",
title: "Input requested",
mode: "form",
fields: [],
fields: formFields,
},
],
})
@@ -1803,13 +1809,12 @@ test("refreshes global forms once per loaded location after reconnect", async ()
test("reconciles all pending form requests when the event stream reconnects", async () => {
const events = createEventStream()
let requests = [
{ id: "frm_old", sessionID: "ses_old", title: "Input requested", mode: "form" as const, fields: [] },
{ id: "frm_old", sessionID: "ses_old", title: "Input requested", fields: formFields },
{
id: "frm_keep",
sessionID: "ses_keep",
title: "Input requested",
mode: "url" as const,
url: "https://example.com",
fields: [{ key: "authorization", type: "external" as const, url: "https://example.com" }],
},
]
let calls = 0
@@ -1841,7 +1846,7 @@ test("reconciles all pending form requests when the event stream reconnects", as
await wait(() => data.session.form.list("ses_old")?.[0]?.id === "frm_old")
expect(data.session.form.list("ses_keep")?.[0]?.id).toBe("frm_keep")
requests = [{ id: "frm_new", sessionID: "ses_new", title: "Input requested", mode: "form" as const, fields: [] }]
requests = [{ id: "frm_new", sessionID: "ses_new", title: "Input requested", fields: formFields }]
events.disconnect()
await wait(() => calls === 2 && data.session.form.list("ses_new")?.[0]?.id === "frm_new")
+139
View File
@@ -0,0 +1,139 @@
/** @jsxImportSource @opentui/solid */
import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
import { testRender, useRenderer } from "@opentui/solid"
import { expect, test } from "bun:test"
import { mkdir } from "node:fs/promises"
import path from "node:path"
import { onCleanup } from "solid-js"
import { ClipboardProvider } from "../../../src/context/clipboard"
import type { FormWithLocation } from "../../../src/context/data"
import { KVProvider } from "../../../src/context/kv"
import { SDKProvider } from "../../../src/context/sdk"
import { ThemeProvider } from "../../../src/context/theme"
import { TuiConfigProvider } from "../../../src/config"
import { OpencodeKeymapProvider, registerOpencodeKeymap } from "../../../src/keymap"
import { ToastProvider } from "../../../src/ui/toast"
import { tmpdir } from "../../fixture/fixture"
import { TestTuiContexts } from "../../fixture/tui-environment"
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
import { createApi, createClient, createEventStream, createFetch } from "../../fixture/tui-sdk"
async function mountForm(root: string, width = 80) {
const state = path.join(root, "state")
await mkdir(state, { recursive: true })
await Bun.write(path.join(state, "kv.json"), "{}")
const replies: unknown[] = []
const copied: string[] = []
const events = createEventStream()
const transport = createFetch(
(url, request) =>
url.pathname === "/api/session/ses_test/form/frm_test/reply"
? request.json().then((answer) => {
replies.push(answer)
return new Response(null, { status: 204 })
})
: undefined,
events,
)
const config = createTuiResolvedConfig()
const form = {
id: "frm_test",
sessionID: "ses_test",
title: "Authorization required",
fields: [
{
key: "authorization",
type: "external",
url: "https://example.com/authorize",
title: "Authorize access",
},
],
} satisfies FormWithLocation
const { FormPrompt } = await import("../../../src/routes/session/form")
function Harness() {
const renderer = useRenderer()
const keymap = createDefaultOpenTuiKeymap(renderer)
const off = registerOpencodeKeymap(keymap, renderer, config)
onCleanup(off)
return (
<TestTuiContexts
directory={root}
paths={{
home: root,
state,
worktree: root,
}}
>
<ClipboardProvider
value={{
write(text) {
copied.push(text)
return Promise.resolve()
},
}}
>
<OpencodeKeymapProvider keymap={keymap}>
<TuiConfigProvider config={config}>
<SDKProvider client={createClient(transport.fetch)} api={createApi(transport.fetch)}>
<KVProvider>
<ThemeProvider mode="dark" source={{ discover: () => Promise.resolve({}) }}>
<ToastProvider>
<FormPrompt form={form} />
</ToastProvider>
</ThemeProvider>
</KVProvider>
</SDKProvider>
</TuiConfigProvider>
</OpencodeKeymapProvider>
</ClipboardProvider>
</TestTuiContexts>
)
}
const app = await testRender(() => <Harness />, { width, height: 20, kittyKeyboard: true })
app.renderer.start()
await app.waitForFrame((frame) => frame.includes("Authorization required"))
return { app, copied, replies }
}
test("requires explicit acknowledgement before submitting an external field", async () => {
await using tmp = await tmpdir()
const prompt = await mountForm(tmp.path)
try {
prompt.app.mockInput.pressKey("right")
await prompt.app.waitForFrame((frame) => frame.includes("(acknowledgement required)"))
prompt.app.mockInput.pressEnter()
await prompt.app.waitForFrame((frame) => frame.includes("External action must be acknowledged"))
expect(prompt.replies).toEqual([])
prompt.app.mockInput.pressKey("left")
prompt.app.mockInput.pressKey("c")
await prompt.app.waitForFrame((frame) => frame.includes("press enter to confirm"))
expect(prompt.copied).toEqual(["https://example.com/authorize"])
expect(prompt.replies).toEqual([])
prompt.app.mockInput.pressEnter()
await prompt.app.waitForFrame((frame) => frame.includes("Acknowledged"))
expect(prompt.replies).toEqual([])
prompt.app.mockInput.pressEnter()
await prompt.app.waitFor(() => prompt.replies.length === 1)
expect(prompt.replies).toEqual([{ answer: { authorization: true } }])
} finally {
prompt.app.renderer.destroy()
}
})
test("includes external acknowledgements in progress", async () => {
await using tmp = await tmpdir()
const prompt = await mountForm(tmp.path, 32)
try {
expect(prompt.app.captureCharFrame()).toContain("0/1")
expect(prompt.replies).toEqual([])
} finally {
prompt.app.renderer.destroy()
}
})
+3 -8
View File
@@ -112,7 +112,7 @@ function Probe(props: {
}
describe("useEvent", () => {
test("logs only durable events", async () => {
test("does not log individual events", async () => {
const logs: Array<{ message: string; tags: Readonly<Record<string, unknown>> }> = []
const { app, emit, seen } = await mount(undefined, (_level, message, tags) => {
if (message === "event") logs.push({ message, tags })
@@ -131,14 +131,9 @@ describe("useEvent", () => {
try {
emit(vcs("main"))
emit(durable)
await wait(() => seen.length === 2 && logs.length === 1)
await wait(() => seen.length === 2)
expect(logs).toEqual([
{
message: "event",
tags: { component: "sdk", type: "session.renamed", aggregateID: "ses_test", seq: 1 },
},
])
expect(logs).toEqual([])
} finally {
app.renderer.destroy()
}
+10 -6
View File
@@ -5,9 +5,11 @@ export const worktree = "/tmp/opencode"
export const directory = `${worktree}/packages/tui`
export function json(data: unknown, init?: ResponseInit) {
const headers = new Headers(init?.headers)
if (!headers.has("content-type")) headers.set("content-type", "application/json")
return new Response(JSON.stringify(data), {
...init,
headers: { "content-type": "application/json", ...(init?.headers ?? {}) },
headers,
})
}
@@ -63,14 +65,15 @@ export function createEventStream() {
}
}
export type FetchHandler = (url: URL) => Response | Promise<Response> | undefined
export type FetchHandler = (url: URL, request: Request) => Response | undefined | Promise<Response | undefined>
export function createFetch(override?: FetchHandler, events?: ReturnType<typeof createEventStream>) {
const session = [] as URL[]
const fetch = (async (input: RequestInfo | URL) => {
const url = new URL(input instanceof Request ? input.url : String(input))
async function fetch(input: RequestInfo | URL, init?: RequestInit) {
const request = input instanceof Request ? input : new Request(input, init)
const url = new URL(request.url)
if (url.pathname === "/session") session.push(url)
const overridden = await override?.(url)
const overridden = await override?.(url, request)
if (overridden) return overridden
if (url.pathname === "/api/event" && events) return events.v2()
@@ -122,7 +125,8 @@ export function createFetch(override?: FetchHandler, events?: ReturnType<typeof
if (url.pathname === "/session") return json([])
if (url.pathname === "/vcs") return json({ branch: "main" })
throw new Error(`unexpected request: ${url.pathname}`)
}) as typeof globalThis.fetch
}
fetch.preconnect = () => {}
return { fetch, session }
}
+3
View File
@@ -50,6 +50,9 @@ await $`bun ./packages/cli/script/publish.ts`
console.log("\n=== sdk ===\n")
await $`bun ./packages/sdk/js/script/publish.ts`
console.log("\n=== plugin ===\n")
await $`bun ./packages/plugin/script/publish.ts`
console.log("\n=== ui ===\n")
await $`bun ./packages/ui/script/publish.ts`
+42
View File
@@ -0,0 +1,42 @@
# V2 Specifications
These documents explain V2 behavior that is difficult to recover from one source file. They are not API reference or a backlog.
## Authority
Authority follows the concern:
| Concern | Owner |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| HTTP operations and transport errors | [Protocol](../../packages/protocol/src) endpoint definitions assembled by Server `HttpApi` |
| Public domain shapes and durable event payloads | [Schema](../../packages/schema/src) |
| Runtime behavior and persistence | [Core](../../packages/core/src) |
| Canonical vocabulary and cross-domain invariants | Root [CONTEXT.md](../../CONTEXT.md) |
| Contributor-critical regression guardrails | Root [AGENTS.md](../../AGENTS.md) |
Current specifications explain cross-module contracts without copying exact types. Decision records explain why a design was selected. Historical documents describe earlier states and may use obsolete names.
Generated clients follow the assembled public `HttpApi`. GitHub issues own active work; Git history preserves removed plans and scratchpads.
## Current Contracts
| Document | Job |
| ----------------------- | --------------------------------------------------------------------------------------- |
| [Session](./session.md) | Explain prompt admission, execution, instructions, compaction, and recovery boundaries. |
| [Tools](./tools.md) | Explain tool construction, registration, execution, and settlement laws. |
## Decisions And Proposals
| Document | Status | Job |
| ----------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------- |
| [Managed restart continuation](./session-restart-continuation.md) | Accepted and implemented | Record why graceful managed-service restart uses private Session suspension. |
| [Provider policy](./provider-policy.md) | Proposed and unimplemented | Explore provider authorization independently from provider configuration. |
## Historical Context
| Document | Job |
| ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| [Schema changelog](./schema-changelog.md) | Preserve the pre-release compatibility ledger. Names in older entries are intentionally historical. |
| [Catalog/config/plugin lifecycle](./catalog-config-plugin-lifecycle.md) | Preserve the option comparison that led to replayable Location-scoped catalog transforms. |
Do not add implementation checklists here. Put actionable work in GitHub issues and package-specific contributor guidance next to the code it governs.

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