Compare commits

..

77 Commits

Author SHA1 Message Date
Dax Raad 975b1132f1 refactor(plugin): use direct runtime registry 2026-06-22 20:10:29 -04:00
Dax Raad cd97de7391 refactor(plugin): consolidate internal registration 2026-06-22 19:49:00 -04:00
Dax Raad 23fd5907be fix(opencode): normalize CLI test line endings 2026-06-22 19:15:50 -04:00
opencode-agent[bot] 49d3f86802 chore: generate 2026-06-22 23:08:26 +00:00
Dax 909a1a6d78 feat(plugin): add namespaced hook API (#33416) 2026-06-22 19:06:57 -04:00
Kit Langton dc468bdcfd fix(core): reset steps for promoted prompts (#33452) 2026-06-22 19:01:14 -04:00
Kit Langton f48f24ec4e refactor(core): simplify session input promotion (#33443) 2026-06-22 17:51:49 -04:00
Aiden Cline 34b3d59a23 ignore: update agents.md (#33446) 2026-06-22 15:52:43 -05:00
Frank a0a500316e zen: new inference 2026-06-22 15:40:14 -04:00
Kit Langton 1787fa4261 refactor(core): drop legacy compaction event (#33404) 2026-06-22 21:39:41 +02:00
Kit Langton 130957288e fix(llm): preserve structured tool errors (#33405) 2026-06-22 13:43:07 -04:00
Aiden Cline c5a4a8288c fix: dont show gpt-5.5-pro when using codex oauth (#33400)
Co-authored-by: Devin Oldenburg <devin@logicplanes.com>
2026-06-22 11:47:02 -05:00
Adam 39d7394ede fix(stats): hide unique users tooltip total 2026-06-22 11:40:00 -05:00
opencode-agent[bot] 494123a875 chore: generate 2026-06-22 16:18:36 +00:00
Kit Langton fe840d42b8 refactor(core): simplify session run coordination (#33388) 2026-06-22 12:16:30 -04:00
Kit Langton f50e4accf3 test(opencode): synchronize shell cancellation (#33386) 2026-06-22 11:55:04 -04:00
Kit Langton 9bceb8eb7d test(opencode): synchronize websocket retry failures (#33387) 2026-06-22 11:54:49 -04:00
Kit Langton adebb87191 test(opencode): use EventV2 location contract (#33383) 2026-06-22 11:37:43 -04:00
opencode-agent[bot] 4d5efba5c9 chore: generate 2026-06-22 15:36:00 +00:00
Kit Langton c6ee511485 refactor(core): simplify session context epochs (#33378) 2026-06-22 11:34:03 -04:00
Kit Langton f9f2280452 fix(core): defer session model validation (#33377) 2026-06-22 11:07:27 -04:00
Tommy D. Rossi d5980b47e9 feat(llm): add video and audio media support to Gemini protocol (#31889)
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
2026-06-22 10:03:19 -05:00
Kit Langton 41d1279b6f fix(opencode): preserve request logger context (#33381) 2026-06-22 10:58:22 -04:00
Simon Klee 0d32d1f293 cli: add --mini (#33353) 2026-06-22 16:27:56 +02:00
Dax Raad cf31029350 fix(core): batch plugin shutdown 2026-06-22 09:04:29 -04:00
Dax Raad 79b55d4db8 fix(tui): use bridged event stream for data 2026-06-22 08:50:46 -04:00
Adam 36264ccf90 fix(stats): format market share tokens 2026-06-22 07:46:11 -05:00
Dax Raad 7b750a8f20 fix(ci): preserve test log groups 2026-06-22 08:35:40 -04:00
Dax Raad e50261e524 fix(core): format generated migrations 2026-06-22 08:23:25 -04:00
opencode-agent[bot] 639c94a375 chore: generate 2026-06-22 12:22:43 +00:00
Dax Raad b13a2d712a fix(server): isolate event schema types 2026-06-22 08:20:39 -04:00
Dax Raad 1b91b5df34 fix(core): constrain event schema services 2026-06-22 08:14:49 -04:00
Dax Raad 595cc91ddc feat(server): stream events across locations 2026-06-22 08:12:43 -04:00
Dax 57ce1b9ca8 fix(cli): increment ports from default (#33282) 2026-06-22 08:05:49 -04:00
opencode-agent[bot] 4ecc3ac653 chore: generate 2026-06-22 11:22:22 +00:00
Simon Klee c7efbe6fc0 run: inline files for attached servers (#33317) 2026-06-22 13:20:43 +02:00
opencode-agent[bot] cd292a4ecb chore: generate 2026-06-22 04:17:10 +00:00
Dax 2bb4311042 refactor(core): simplify integration test fixtures (#33292) 2026-06-22 04:15:34 +00:00
opencode-agent[bot] cdc6d01c5a chore: generate 2026-06-22 04:00:59 +00:00
Dax Raad 35b3fc85d0 feat(core): expose session switching endpoints 2026-06-21 23:59:22 -04:00
Aiden Cline 9dadc2455f fix(tui): render skill load errors inline (#33298) 2026-06-21 22:40:12 -05:00
opencode-agent[bot] 06dae383f7 chore: generate 2026-06-21 23:42:07 +00:00
Adam 7d204b5b57 feat(stats): show model unique users 2026-06-21 18:40:22 -05:00
Kit Langton 49593c1ec4 fix(core): settle interrupted assistant steps (#33266) 2026-06-21 20:22:09 +00:00
Kit Langton ff837fe949 fix(core): handle read file failures (#33260) 2026-06-21 20:12:42 +00:00
Adam 4c6750d464 fix(stats): unblock stats sync 2026-06-21 14:53:46 -05:00
Kit Langton 69f1ec22e3 fix(core): bound web tool failures (#33259) 2026-06-21 15:37:25 -04:00
Kit Langton 823d327401 fix(core): handle missing read paths (#33255) 2026-06-21 13:50:14 -04:00
opencode-agent[bot] 82d9cab48d chore: generate 2026-06-21 14:36:19 +00:00
Dax fb43c15f88 refactor(core): simplify event model (#33238) 2026-06-21 10:34:57 -04:00
opencode-agent[bot] ca006a2d20 chore: update nix node_modules hashes 2026-06-21 12:21:25 +00:00
Dax Raad 8396395f17 fix(stats): update defect schemas 2026-06-21 08:08:31 -04:00
Dax Raad 1b8bab3e35 fix(ci): avoid Playwright Chromium install hang 2026-06-21 08:08:31 -04:00
opencode-agent[bot] 02687b6324 chore: generate 2026-06-21 12:07:16 +00:00
Dax c780d7cee7 feat(plugin): add v2 effect host (#33111) 2026-06-21 08:05:49 -04:00
opencode-agent[bot] 7a9337da8a chore: generate 2026-06-21 11:49:50 +00:00
Adam f96e6aa6ed fix(stats): bypass worker runtime crash 2026-06-21 06:48:25 -05:00
Adam c6f719e153 fix(stats): restore worker data exports 2026-06-21 06:39:49 -05:00
Adam 1a111be494 fix(stats): run worker effects directly 2026-06-21 06:30:15 -05:00
Adam a0aee82be9 fix(stats): inline worker runtime import 2026-06-21 06:22:26 -05:00
Adam c0dc6e50a7 fix(stats): restore worker runtime 2026-06-21 06:16:02 -05:00
Adam 418a9e4e66 fix(stats): restore model page rendering 2026-06-21 05:58:39 -05:00
Adam bd8ce5e6a9 chore(stats): remove deploy migrations 2026-06-21 05:41:10 -05:00
Adam a97c6de9db fix(stats): support planetscale cli variants 2026-06-21 05:17:22 -05:00
opencode-agent[bot] 24ea4dd008 chore: generate 2026-06-21 10:03:16 +00:00
Adam ffcb7542e1 fix(stats): run production migration safely 2026-06-21 05:01:43 -05:00
opencode-agent[bot] d4d841bafd chore: generate 2026-06-21 09:40:15 +00:00
Adam 6f0e934573 fix(stats): make unique users migration idempotent 2026-06-21 04:38:47 -05:00
Adam 233d065dd5 feat(stats): show model users metric 2026-06-21 04:30:25 -05:00
Dax f12ac6f234 fix(tui): reduce noisy MCP autocomplete matches (#33176) 2026-06-20 22:24:59 -04:00
James Long d3bbfff826 test(opencode): simplify message pagination layer wiring (#33157) 2026-06-20 21:44:37 -04:00
James Long 468f425e76 test(opencode): simplify session retry layer wiring (#33155) 2026-06-20 21:44:02 -04:00
James Long d59619fffd test(opencode): simplify git layer wiring (#33156) 2026-06-20 21:43:03 -04:00
opencode-agent[bot] 5606d2bab9 chore: update nix node_modules hashes 2026-06-21 00:19:31 +00:00
opencode e84d94d998 sync release versions for v1.17.9 2026-06-21 00:03:08 +00:00
Kit Langton 4f1ae1604e chore: upgrade Effect to beta 83 (#32340) 2026-06-20 19:57:29 -04:00
Dax d99f86b28d fix(tui): separate subagent tool rows (#33158) 2026-06-20 18:58:27 -04:00
351 changed files with 17789 additions and 9012 deletions
+3 -2
View File
@@ -65,7 +65,7 @@ jobs:
- name: Run unit tests - name: Run unit tests
timeout-minutes: 20 timeout-minutes: 20
run: bun turbo test --output-logs=errors-only --log-order=grouped --log-prefix=task run: bun turbo test --output-logs=errors-only --log-order=grouped --log-prefix=none
env: env:
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: ${{ runner.os == 'Windows' && 'true' || 'false' }} OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: ${{ runner.os == 'Windows' && 'true' || 'false' }}
@@ -99,7 +99,8 @@ jobs:
- name: Setup Node - name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with: with:
node-version: "24" # Playwright 1.59 hangs while extracting Chromium with Node 24.16.
node-version: "24.15"
- name: Setup Bun - name: Setup Bun
uses: ./.github/actions/setup-bun uses: ./.github/actions/setup-bun
+3 -3
View File
@@ -137,7 +137,7 @@ const table = sqliteTable("session", {
## Testing ## Testing
- Avoid mocks as much as possible - Avoid mocks as much as possible, you shouldn't be using globalThis.\* at all unless it's the only option.
- Test actual implementation, do not duplicate logic into tests - Test actual implementation, do not duplicate logic into tests
- Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package dirs like `packages/opencode`. - Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package dirs like `packages/opencode`.
@@ -152,7 +152,7 @@ const table = sqliteTable("session", {
- 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; idle or missing interruption is a no-op.
- 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. - 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 provider turn 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 provider turn and reload projected history before durable continuation. 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 activity recovery requires a separate explicit design before it may retry provider work. - 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 coalesce into the active activity at the next safe provider-turn boundary. Explicit `queue` inputs open FIFO future activities one at a time after the active activity settles. - Keep delivery vocabulary explicit. Prompts steer by default and promote at the next safe provider-turn 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 provider-turn allowance; a batch of steers resets it once.
- Keep EventV2 replay owner claims separate from clustered Session execution ownership. - Keep EventV2 replay owner claims separate from clustered Session execution ownership.
- Keep the System Context algebra, registry, and built-ins in `src/system-context`; keep Context Source producers with their observed domains, and keep Session History selection plus Context Epoch persistence Session-owned. - Keep the System Context algebra, registry, and built-ins in `src/system-context`; keep Context Source producers with their observed domains, and keep Session History selection plus Context Epoch persistence Session-owned.
+23 -9
View File
@@ -24,7 +24,7 @@ A durable chronological instruction that tells the model the newly effective sta
_Avoid_: System update, system notification, raw text diff _Avoid_: System update, system notification, raw text diff
**Context Epoch**: **Context Epoch**:
The span during which one effective agent's initially rendered **System Context** remains immutable, ending at compaction or another baseline-replacing transition. The span during which one initially rendered **System Context** remains the immutable provider-cache baseline, ending at completed compaction, Session movement, or an incompatible context transition that requires a fresh baseline.
**Baseline System Context**: **Baseline System Context**:
The full **System Context** rendered at the start of a **Context Epoch**. The full **System Context** rendered at the start of a **Context Epoch**.
@@ -39,6 +39,18 @@ An expected temporary inability to observe a **Context Source** value; the runti
**Safe Provider-Turn Boundary**: **Safe Provider-Turn Boundary**:
The point immediately before a provider call, after durable input promotion and any required tool settlement, where context changes may be admitted chronologically. The point immediately before a provider call, after durable input promotion and any required tool settlement, where context changes may be admitted chronologically.
**Admitted Prompt**:
A durable user input accepted into the Session inbox but not yet included in **Session History**.
**Prompt Promotion**:
The durable transition that removes an **Admitted Prompt** from pending input and appends its user message to **Session History**.
**Provider Turn**:
One request to a model provider and the response projected from that request.
**Session Drain**:
One process-local execution span that promotes eligible input and runs required **Provider Turns** until no immediate continuation remains. A Session Drain has no durable identity or transcript boundary.
**Model Tool Output**: **Model Tool Output**:
The bounded projection of a Core-executed tool result persisted in Session history and replayed to the model. A tool may shape this projection semantically, but the Tool Registry enforces the final size limit. The bounded projection of a Core-executed tool result persisted in Session history and replayed to the model. A tool may shape this projection semantically, but the Tool Registry enforces the final size limit.
@@ -67,6 +79,11 @@ The host-supplied environment overlay applied by the server when creating a PTY,
- Changes from multiple **Context Sources** admitted at one safe boundary combine into one **Mid-Conversation System Message**. - Changes from multiple **Context Sources** admitted at one safe boundary combine into one **Mid-Conversation System Message**.
- Context changes are sampled and admitted lazily at a **Safe Provider-Turn Boundary**, never pushed asynchronously when their source changes. - Context changes are sampled and admitted lazily at a **Safe Provider-Turn Boundary**, never pushed asynchronously when their source changes.
- At a **Safe Provider-Turn Boundary**, newly promoted user input or settled tool results precede any combined **Mid-Conversation System Message**. - At a **Safe Provider-Turn Boundary**, newly promoted user input or settled tool results precede any combined **Mid-Conversation System Message**.
- An **Admitted Prompt** is replayable pending input, not yet model-visible **Session History**.
- **Prompt Promotion** atomically consumes the pending inbox entry and appends its model-visible user message.
- Steering prompts promote at the next **Safe Provider-Turn Boundary** while the current **Session Drain** still requires continuation. Promoting any newly admitted user input resets the selected agent's provider-turn allowance; multiple prompts promoted at one boundary reset it once.
- A queued prompt does not promote while the current **Session Drain** requires continuation. The runner promotes one queued prompt when the Session would otherwise become idle, then reevaluates continuation before promoting another.
- A **Session Drain** is process-local coordination rather than a durable domain entity. Durable recovery must reason from prompts, projected history, provider attempts, and tool state rather than inventing an enclosing execution identity.
- The first provider turn renders the latest complete **Baseline System Context** and initializes its **Context Snapshot** without emitting a redundant **Mid-Conversation System Message**; unavailable initial context blocks the turn instead of persisting an incomplete baseline. - The first provider turn renders the latest complete **Baseline System Context** and initializes its **Context Snapshot** without emitting a redundant **Mid-Conversation System Message**; unavailable initial context blocks the turn instead of persisting an incomplete baseline.
- Initial **System Context** preparation precedes the first durable input promotion so an unavailable baseline leaves that input pending and retryable; ordinary reconciliation remains after promotion. - Initial **System Context** preparation precedes the first durable input promotion so an unavailable baseline leaves that input pending and retryable; ordinary reconciliation remains after promotion.
- Compaction starts a new **Context Epoch** with a freshly rendered **Baseline System Context** and **Context Snapshot**; prior **Mid-Conversation System Messages** remain durable audit history but leave projected model history. - Compaction starts a new **Context Epoch** with a freshly rendered **Baseline System Context** and **Context Snapshot**; prior **Mid-Conversation System Messages** remain durable audit history but leave projected model history.
@@ -75,31 +92,28 @@ The host-supplied environment overlay applied by the server when creating a PTY,
- Each **Context Source** loader returns one coherent typed value. `SystemContext.make(...)` hides that value type so differently typed sources compose uniformly. Its codec compares and stores that value; its pure renderers produce model-visible baseline, update, and removal text only when needed. - Each **Context Source** loader returns one coherent typed value. `SystemContext.make(...)` hides that value type so differently typed sources compose uniformly. Its codec compares and stores that value; its pure renderers produce model-visible baseline, update, and removal text only when needed.
- `SystemContext.initialize(...)` observes a composed **System Context** once and produces a fresh **Baseline System Context** with its **Context Snapshot**. - `SystemContext.initialize(...)` observes a composed **System Context** once and produces a fresh **Baseline System Context** with its **Context Snapshot**.
- `SystemContext.reconcile(...)` observes a composed **System Context** once and returns exactly one next action: unchanged, updated, replacement ready, or replacement blocked. - `SystemContext.reconcile(...)` observes a composed **System Context** once and returns exactly one next action: unchanged, updated, replacement ready, or replacement blocked.
- `SystemContext.replace(...)` represents an explicit baseline-replacing transition such as compaction or model/provider switch; it either produces a fresh generation or reports that replacement is blocked by unavailable admitted context. - `SystemContext.replace(...)` renders a fresh generation after completed compaction or another baseline-replacing transition; it reports replacement blocked while previously admitted context is unavailable.
- Context Epoch preparation retries until stable after optimistic revision mismatches so concurrent replacement requests cannot terminate an otherwise valid safe-boundary run.
- **Unavailable Context** uses stale-while-revalidate semantics and is distinct from a successfully loaded absence, which may emit removal text. - **Unavailable Context** uses stale-while-revalidate semantics and is distinct from a successfully loaded absence, which may emit removal text.
- Ordinary **Context Source** loaders return values directly; loaders that intentionally use stale-while-revalidate may explicitly return **Unavailable Context**. - Ordinary **Context Source** loaders return values directly; loaders that intentionally use stale-while-revalidate may explicitly return **Unavailable Context**.
- Nested project instruction discovery after successful reads remains a follow-up; when implemented, discovered instructions must be admitted durably at the next **Safe Provider-Turn Boundary**. - Nested project instruction discovery after successful reads remains a follow-up; when implemented, discovered instructions must be admitted durably at the next **Safe Provider-Turn Boundary**.
- Location-scoped services naturally re-resolve effective context when a moved session next runs in its destination location. - Location-scoped services naturally re-resolve effective context when a moved session next runs in its destination location.
- Moving a Session clears its active **Context Epoch**, so the destination must initialize a complete baseline before another prompt can promote. - Moving a Session clears its active **Context Epoch**, so the destination must initialize a complete baseline before another prompt can promote.
- Context Epoch initialization is fenced against the authoritative Session Location, so an old-Location runner cannot recreate source context after a concurrent move.
- Instruction discovery, source identity, persistence, and file loading belong to the instruction service; the **System Context** abstraction only composes effectful producers and renders loaded values. - Instruction discovery, source identity, persistence, and file loading belong to the instruction service; the **System Context** abstraction only composes effectful producers and renders loaded values.
- The first instruction-service slice observes global and upward project `AGENTS.md` files as one ordered aggregate **Context Source** at each **Safe Provider-Turn Boundary**. - The first instruction-service slice observes global and upward project `AGENTS.md` files as one ordered aggregate **Context Source** at each **Safe Provider-Turn Boundary**.
- Built-in and instruction context producers register through the **System Context Registry** with stable contribution keys. Plugin-defined context registration and hot-reload lifecycle remain a follow-up built on the same scoped registry seam. - Built-in and instruction context producers register through the **System Context Registry** with stable contribution keys. Plugin-defined context registration and hot-reload lifecycle remain a follow-up built on the same scoped registry seam.
- Selected-agent available-skill guidance is a **Context Source** composed with Location-wide registry sources immediately before Context Epoch admission. It lists only names and descriptions permitted for that agent; skill bodies and locations are exposed only through the permission-checked `skill` tool. - Selected-agent available-skill guidance is a **Context Source** composed with Location-wide registry sources immediately before Context Epoch admission. It lists only names and descriptions permitted for that agent; skill bodies and locations are exposed only through the permission-checked `skill` tool.
- Switching the selected agent requests **Context Epoch** replacement. A switch admitted after the current **Safe Provider-Turn Boundary** applies to the next provider turn while leaving the already-prepared baseline durable. Epoch creation is fenced against the authoritative effective agent, and retries re-observe the current agent. - The selected agent and model are sampled when a provider turn starts. Changes admitted after that boundary apply to the next provider turn and do not restart the current turn.
- A cross-agent replacement must complete before another provider turn; unavailable admitted context blocks that replacement instead of exposing the previous agent's privileged baseline. - Selected-agent available-skill guidance remains a **Context Source**. An agent switch that changes that guidance produces a **Mid-Conversation System Message** while preserving the current baseline.
- Local tool authorization and pending permission requests retain the effective agent of the provider turn that issued the call; a later agent switch cannot change that call's policy. - Local tool authorization and pending permission requests retain the effective agent of the provider turn that issued the call; a later agent switch cannot change that call's policy.
- Context source changes never wake idle sessions; the next naturally scheduled **Safe Provider-Turn Boundary** loads and compares current values lazily. - Context source changes never wake idle sessions; the next naturally scheduled **Safe Provider-Turn Boundary** loads and compares current values lazily.
- Once admitted, a **Mid-Conversation System Message** remains durable even if the following provider attempt fails and is replayed unchanged on retry. - Once admitted, a **Mid-Conversation System Message** remains durable even if the following provider attempt fails and is replayed unchanged on retry.
- **Mid-Conversation System Messages** remain durable Session-message history; normal user-facing transcript surfaces may hide them. - **Mid-Conversation System Messages** remain durable Session-message history; normal user-facing transcript surfaces may hide them.
- The date **Context Source** initially preserves host-local calendar-date behavior; a configured user timezone may replace that default later. - The date **Context Source** initially preserves host-local calendar-date behavior; a configured user timezone may replace that default later.
- A **Context Epoch** begins with one immutable **Baseline System Context**. - A **Context Epoch** begins with one immutable **Baseline System Context**.
- A **Context Epoch** durably records the effective agent that owns its **Baseline System Context**.
- A **Baseline System Context** is stored durably and reused verbatim across process restarts within its **Context Epoch**. - A **Baseline System Context** is stored durably and reused verbatim across process restarts within its **Context Epoch**.
- A **Baseline System Context** durably preserves the exact joined text used for the active provider-cache prefix. - A **Baseline System Context** durably preserves the exact joined text used for the active provider-cache prefix.
- Compaction or a model/provider switch starts a new **Context Epoch** because the baseline can be replaced without preserving the prior provider cache. - Completed compaction starts a new **Context Epoch** on the next provider attempt, folding the current complete **System Context** into a fresh baseline and removing earlier **Mid-Conversation System Messages** from active model history.
- A model/provider switch always starts a new **Context Epoch** while preserving chronological conversation history. - A model/provider switch preserves the current **Context Epoch** and chronological conversation history; the new selection applies to the next provider turn.
- **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding. - **Model Request Options** remain provider-semantic through Catalog resolution. The Session runner maps them into the LLM package's provider-option namespace; the selected protocol adapter alone owns provider wire encoding.
- **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing. - **Generation Controls**, protocol-semantic **Model Request Options**, and compatibility request body fields are separate Catalog domains. A shared ingestion adapter partitions legacy and models.dev AI-SDK-shaped options before routing.
- The **PTY Environment** is a server concern rather than a Core PTY concern. PTY creation merges caller values, then the host overlay, then Core-forced terminal invariants such as `TERM` and `OPENCODE_TERMINAL`. - The **PTY Environment** is a server concern rather than a Core PTY concern. PTY creation merges caller values, then the host overlay, then Core-forced terminal invariants such as `TERM` and `OPENCODE_TERMINAL`.
+48 -38
View File
@@ -29,7 +29,7 @@
}, },
"packages/app": { "packages/app": {
"name": "@opencode-ai/app", "name": "@opencode-ai/app",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@kobalte/core": "catalog:", "@kobalte/core": "catalog:",
"@opencode-ai/core": "workspace:*", "@opencode-ai/core": "workspace:*",
@@ -86,7 +86,7 @@
}, },
"packages/cli": { "packages/cli": {
"name": "@opencode-ai/cli", "name": "@opencode-ai/cli",
"version": "1.17.8", "version": "1.17.9",
"bin": { "bin": {
"lildax": "./bin/lildax.cjs", "lildax": "./bin/lildax.cjs",
}, },
@@ -111,7 +111,7 @@
}, },
"packages/console/app": { "packages/console/app": {
"name": "@opencode-ai/console-app", "name": "@opencode-ai/console-app",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@cloudflare/vite-plugin": "1.15.2", "@cloudflare/vite-plugin": "1.15.2",
"@ibm/plex": "6.4.1", "@ibm/plex": "6.4.1",
@@ -147,7 +147,7 @@
}, },
"packages/console/core": { "packages/console/core": {
"name": "@opencode-ai/console-core", "name": "@opencode-ai/console-core",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@aws-sdk/client-sts": "3.782.0", "@aws-sdk/client-sts": "3.782.0",
"@jsx-email/render": "1.1.1", "@jsx-email/render": "1.1.1",
@@ -174,7 +174,7 @@
}, },
"packages/console/function": { "packages/console/function": {
"name": "@opencode-ai/console-function", "name": "@opencode-ai/console-function",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@ai-sdk/anthropic": "3.0.82", "@ai-sdk/anthropic": "3.0.82",
"@ai-sdk/openai": "3.0.48", "@ai-sdk/openai": "3.0.48",
@@ -196,7 +196,7 @@
}, },
"packages/console/mail": { "packages/console/mail": {
"name": "@opencode-ai/console-mail", "name": "@opencode-ai/console-mail",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@jsx-email/all": "2.2.3", "@jsx-email/all": "2.2.3",
"@jsx-email/cli": "1.4.3", "@jsx-email/cli": "1.4.3",
@@ -220,7 +220,7 @@
}, },
"packages/console/support": { "packages/console/support": {
"name": "@opencode-ai/console-support", "name": "@opencode-ai/console-support",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@cloudflare/vite-plugin": "1.15.2", "@cloudflare/vite-plugin": "1.15.2",
"@opencode-ai/console-core": "workspace:*", "@opencode-ai/console-core": "workspace:*",
@@ -240,7 +240,7 @@
}, },
"packages/core": { "packages/core": {
"name": "@opencode-ai/core", "name": "@opencode-ai/core",
"version": "1.17.8", "version": "1.17.9",
"bin": { "bin": {
"opencode": "./bin/opencode", "opencode": "./bin/opencode",
}, },
@@ -276,6 +276,7 @@
"@opencode-ai/effect-drizzle-sqlite": "workspace:*", "@opencode-ai/effect-drizzle-sqlite": "workspace:*",
"@opencode-ai/effect-sqlite-node": "workspace:*", "@opencode-ai/effect-sqlite-node": "workspace:*",
"@opencode-ai/llm": "workspace:*", "@opencode-ai/llm": "workspace:*",
"@opencode-ai/plugin": "workspace:*",
"@openrouter/ai-sdk-provider": "2.9.0", "@openrouter/ai-sdk-provider": "2.9.0",
"@opentelemetry/api": "1.9.0", "@opentelemetry/api": "1.9.0",
"@opentelemetry/context-async-hooks": "2.6.1", "@opentelemetry/context-async-hooks": "2.6.1",
@@ -331,7 +332,7 @@
}, },
"packages/desktop": { "packages/desktop": {
"name": "@opencode-ai/desktop", "name": "@opencode-ai/desktop",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@zip.js/zip.js": "2.7.62", "@zip.js/zip.js": "2.7.62",
"effect": "catalog:", "effect": "catalog:",
@@ -385,7 +386,7 @@
}, },
"packages/effect-drizzle-sqlite": { "packages/effect-drizzle-sqlite": {
"name": "@opencode-ai/effect-drizzle-sqlite", "name": "@opencode-ai/effect-drizzle-sqlite",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"drizzle-orm": "catalog:", "drizzle-orm": "catalog:",
"effect": "catalog:", "effect": "catalog:",
@@ -399,7 +400,7 @@
}, },
"packages/effect-sqlite-node": { "packages/effect-sqlite-node": {
"name": "@opencode-ai/effect-sqlite-node", "name": "@opencode-ai/effect-sqlite-node",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"effect": "catalog:", "effect": "catalog:",
}, },
@@ -411,7 +412,7 @@
}, },
"packages/enterprise": { "packages/enterprise": {
"name": "@opencode-ai/enterprise", "name": "@opencode-ai/enterprise",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@hono/standard-validator": "catalog:", "@hono/standard-validator": "catalog:",
"@opencode-ai/core": "workspace:*", "@opencode-ai/core": "workspace:*",
@@ -442,7 +443,7 @@
}, },
"packages/function": { "packages/function": {
"name": "@opencode-ai/function", "name": "@opencode-ai/function",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@octokit/auth-app": "8.0.1", "@octokit/auth-app": "8.0.1",
"@octokit/rest": "catalog:", "@octokit/rest": "catalog:",
@@ -458,10 +459,10 @@
}, },
"packages/http-recorder": { "packages/http-recorder": {
"name": "@opencode-ai/http-recorder", "name": "@opencode-ai/http-recorder",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@effect/platform-node": "4.0.0-beta.74", "@effect/platform-node": "4.0.0-beta.83",
"@effect/platform-node-shared": "4.0.0-beta.74", "@effect/platform-node-shared": "4.0.0-beta.83",
}, },
"devDependencies": { "devDependencies": {
"@tsconfig/node22": "catalog:", "@tsconfig/node22": "catalog:",
@@ -472,12 +473,12 @@
"typescript": "catalog:", "typescript": "catalog:",
}, },
"peerDependencies": { "peerDependencies": {
"effect": "4.0.0-beta.74", "effect": "4.0.0-beta.83",
}, },
}, },
"packages/llm": { "packages/llm": {
"name": "@opencode-ai/llm", "name": "@opencode-ai/llm",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@smithy/eventstream-codec": "4.2.14", "@smithy/eventstream-codec": "4.2.14",
"@smithy/util-utf8": "4.2.2", "@smithy/util-utf8": "4.2.2",
@@ -495,7 +496,7 @@
}, },
"packages/opencode": { "packages/opencode": {
"name": "opencode", "name": "opencode",
"version": "1.17.8", "version": "1.17.9",
"bin": { "bin": {
"opencode": "./bin/opencode", "opencode": "./bin/opencode",
}, },
@@ -623,8 +624,9 @@
}, },
"packages/plugin": { "packages/plugin": {
"name": "@opencode-ai/plugin", "name": "@opencode-ai/plugin",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@ai-sdk/provider": "3.0.8",
"@opencode-ai/sdk": "workspace:*", "@opencode-ai/sdk": "workspace:*",
"effect": "catalog:", "effect": "catalog:",
"zod": "catalog:", "zod": "catalog:",
@@ -661,7 +663,7 @@
}, },
"packages/sdk/js": { "packages/sdk/js": {
"name": "@opencode-ai/sdk", "name": "@opencode-ai/sdk",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"cross-spawn": "catalog:", "cross-spawn": "catalog:",
}, },
@@ -676,7 +678,7 @@
}, },
"packages/server": { "packages/server": {
"name": "@opencode-ai/server", "name": "@opencode-ai/server",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@opencode-ai/core": "workspace:*", "@opencode-ai/core": "workspace:*",
"drizzle-orm": "catalog:", "drizzle-orm": "catalog:",
@@ -690,7 +692,7 @@
}, },
"packages/slack": { "packages/slack": {
"name": "@opencode-ai/slack", "name": "@opencode-ai/slack",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@opencode-ai/sdk": "workspace:*", "@opencode-ai/sdk": "workspace:*",
"@slack/bolt": "^3.17.1", "@slack/bolt": "^3.17.1",
@@ -703,7 +705,7 @@
}, },
"packages/stats/app": { "packages/stats/app": {
"name": "@opencode-ai/stats-app", "name": "@opencode-ai/stats-app",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@ibm/plex": "6.4.1", "@ibm/plex": "6.4.1",
"@opencode-ai/stats-core": "workspace:*", "@opencode-ai/stats-core": "workspace:*",
@@ -736,7 +738,7 @@
}, },
"packages/stats/core": { "packages/stats/core": {
"name": "@opencode-ai/stats-core", "name": "@opencode-ai/stats-core",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@aws-sdk/client-athena": "3.933.0", "@aws-sdk/client-athena": "3.933.0",
"@planetscale/database": "1.19.0", "@planetscale/database": "1.19.0",
@@ -755,7 +757,7 @@
}, },
"packages/stats/server": { "packages/stats/server": {
"name": "@opencode-ai/stats-server", "name": "@opencode-ai/stats-server",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@aws-sdk/client-firehose": "3.933.0", "@aws-sdk/client-firehose": "3.933.0",
"@effect/platform-node": "catalog:", "@effect/platform-node": "catalog:",
@@ -795,7 +797,7 @@
}, },
"packages/tui": { "packages/tui": {
"name": "@opencode-ai/tui", "name": "@opencode-ai/tui",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@opencode-ai/core": "workspace:*", "@opencode-ai/core": "workspace:*",
"@opencode-ai/plugin": "workspace:*", "@opencode-ai/plugin": "workspace:*",
@@ -822,7 +824,7 @@
}, },
"packages/ui": { "packages/ui": {
"name": "@opencode-ai/ui", "name": "@opencode-ai/ui",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@kobalte/core": "catalog:", "@kobalte/core": "catalog:",
"@opencode-ai/core": "workspace:*", "@opencode-ai/core": "workspace:*",
@@ -871,7 +873,7 @@
}, },
"packages/web": { "packages/web": {
"name": "@opencode-ai/web", "name": "@opencode-ai/web",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@astrojs/cloudflare": "12.6.3", "@astrojs/cloudflare": "12.6.3",
"@astrojs/markdown-remark": "6.3.1", "@astrojs/markdown-remark": "6.3.1",
@@ -935,9 +937,9 @@
}, },
"catalog": { "catalog": {
"@cloudflare/workers-types": "4.20251008.0", "@cloudflare/workers-types": "4.20251008.0",
"@effect/opentelemetry": "4.0.0-beta.74", "@effect/opentelemetry": "4.0.0-beta.83",
"@effect/platform-node": "4.0.0-beta.74", "@effect/platform-node": "4.0.0-beta.83",
"@effect/sql-sqlite-bun": "4.0.0-beta.74", "@effect/sql-sqlite-bun": "4.0.0-beta.83",
"@hono/standard-validator": "0.2.0", "@hono/standard-validator": "0.2.0",
"@hono/zod-validator": "0.4.2", "@hono/zod-validator": "0.4.2",
"@kobalte/core": "0.13.11", "@kobalte/core": "0.13.11",
@@ -973,7 +975,7 @@
"dompurify": "3.3.1", "dompurify": "3.3.1",
"drizzle-kit": "1.0.0-rc.2", "drizzle-kit": "1.0.0-rc.2",
"drizzle-orm": "1.0.0-rc.2", "drizzle-orm": "1.0.0-rc.2",
"effect": "4.0.0-beta.74", "effect": "4.0.0-beta.83",
"fuzzysort": "3.1.0", "fuzzysort": "3.1.0",
"hono": "4.10.7", "hono": "4.10.7",
"hono-openapi": "1.1.2", "hono-openapi": "1.1.2",
@@ -1328,13 +1330,13 @@
"@drizzle-team/brocli": ["@drizzle-team/brocli@0.11.0", "", {}, "sha512-hD3pekGiPg0WPCCGAZmusBBJsDqGUR66Y452YgQsZOnkdQ7ViEPKuyP4huUGEZQefp8g34RRodXYmJ2TbCH+tg=="], "@drizzle-team/brocli": ["@drizzle-team/brocli@0.11.0", "", {}, "sha512-hD3pekGiPg0WPCCGAZmusBBJsDqGUR66Y452YgQsZOnkdQ7ViEPKuyP4huUGEZQefp8g34RRodXYmJ2TbCH+tg=="],
"@effect/opentelemetry": ["@effect/opentelemetry@4.0.0-beta.74", "", { "peerDependencies": { "@opentelemetry/api": "^1.9", "@opentelemetry/api-logs": ">=0.203.0 <0.300.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-logs": ">=0.203.0 <0.300.0", "@opentelemetry/sdk-metrics": "^2.0.0", "@opentelemetry/sdk-trace-base": "^2.0.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "@opentelemetry/sdk-trace-web": "^2.0.0", "@opentelemetry/semantic-conventions": "^1.33.0", "effect": "^4.0.0-beta.74" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/api-logs", "@opentelemetry/resources", "@opentelemetry/sdk-logs", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@opentelemetry/sdk-trace-web"] }, "sha512-flpyqLPyr+THSe6ZCGRZl6hi+FqxbIXNSkslKGiRJAjbPabam9mSp7R3aC8biIMt6xE4Fd0LNfo4p2GplUkm2Q=="], "@effect/opentelemetry": ["@effect/opentelemetry@4.0.0-beta.83", "", { "peerDependencies": { "@opentelemetry/api": "^1.9", "@opentelemetry/api-logs": ">=0.203.0 <0.300.0", "@opentelemetry/resources": "^2.0.0", "@opentelemetry/sdk-logs": ">=0.203.0 <0.300.0", "@opentelemetry/sdk-metrics": "^2.0.0", "@opentelemetry/sdk-trace-base": "^2.0.0", "@opentelemetry/sdk-trace-node": "^2.0.0", "@opentelemetry/sdk-trace-web": "^2.0.0", "@opentelemetry/semantic-conventions": "^1.33.0", "effect": "^4.0.0-beta.83" }, "optionalPeers": ["@opentelemetry/api", "@opentelemetry/api-logs", "@opentelemetry/resources", "@opentelemetry/sdk-logs", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@opentelemetry/sdk-trace-web"] }, "sha512-cPfCfp/ghu0itbX6Dqjdr4N0rbjng5ON4sUpnLHV5JJySG8zZpWmuOZLWIrfrNKT2ctYR1BYmp1aYCgkItaJLw=="],
"@effect/platform-node": ["@effect/platform-node@4.0.0-beta.74", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.74", "mime": "^4.1.0", "undici": "^8.2.0" }, "peerDependencies": { "effect": "^4.0.0-beta.74", "ioredis": "^5.7.0" } }, "sha512-/W16mKqxvhWINLjufzc0log1sl57exXQfwd+em398/zKCbmU3S7snXTDMN6w0ju2TtgK35qrsoGBXEochij6Sg=="], "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.83", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.83", "mime": "^4.1.0", "undici": "^8.2.0" }, "peerDependencies": { "effect": "^4.0.0-beta.83", "ioredis": "^5.7.0" } }, "sha512-RmpVGu/+X/Bif3/g1Rzj8oFzTOknoVB3yHCa0b179vytPpKe+Kj9ZwKNcAnKWqHUDkbSPBq1Ca60mvOHr2/+LQ=="],
"@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.74", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.74" } }, "sha512-C6C2hXixNcZXLaFF2u7B/FtOsqpdY7luaPuiGFBJza0P7EnYDkwaT3kB6lv7l/qctmkADc24qOsSCWIKRbC4jg=="], "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.83", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.83" } }, "sha512-+yr/+PJmKTgmJq1QOINSBPgLu7Cjc4CZcotBXnGjyDEizOmimFgTkN2B8PBJAKIKUWYWfobjXqC+58/VhhPKAw=="],
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.74", "", { "peerDependencies": { "effect": "^4.0.0-beta.74" } }, "sha512-RVMRVY7NhSoAp9cAAyy4TT6dt6NNZjOpWeqticoho9HNBukxQSUcu/kjcz4Iq9eoQfXadmepu8kZqtdZULM/fg=="], "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.83", "", { "peerDependencies": { "effect": "^4.0.0-beta.83" } }, "sha512-6OaxLsWffxkh9pXYUSyj/AxjVb9URY2rG9U6atjxClWy30Jx77R9Pm3Rrc7cQ63kQurePavEw1bQbzQ/SILiQQ=="],
"@electron/asar": ["@electron/asar@3.4.1", "", { "dependencies": { "commander": "^5.0.0", "glob": "^7.1.6", "minimatch": "^3.0.4" }, "bin": { "asar": "bin/asar.js" } }, "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA=="], "@electron/asar": ["@electron/asar@3.4.1", "", { "dependencies": { "commander": "^5.0.0", "glob": "^7.1.6", "minimatch": "^3.0.4" }, "bin": { "asar": "bin/asar.js" } }, "sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA=="],
@@ -3366,7 +3368,7 @@
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"effect": ["effect@4.0.0-beta.74", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-Yx+Kh12U+i2FmjwEfKs+ePFmpMd43RPD1oGqc/VraSS9bYzvF0Ff3PojwEFEVEewp8xc92Uxu28gTspU4qyvHA=="], "effect": ["effect@4.0.0-beta.83", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-0wsak8RtgGAr9UWSbVDgJHZcUqMSvicHcvaZv1MbMM7MCGgW4Rn/137J1MHQbwYPcwYGxT/IqehFd+UbYuj78w=="],
"ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="], "ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="],
@@ -5898,6 +5900,10 @@
"@solidjs/start/vite": ["vite@7.1.10", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-CmuvUBzVJ/e3HGxhg6cYk88NGgTnBoOo7ogtfJJ0fefUWAxN/WDSUa50o+oVBxuIhO8FoEZW0j2eW7sfjs5EtA=="], "@solidjs/start/vite": ["vite@7.1.10", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-CmuvUBzVJ/e3HGxhg6cYk88NGgTnBoOo7ogtfJJ0fefUWAxN/WDSUa50o+oVBxuIhO8FoEZW0j2eW7sfjs5EtA=="],
"@standard-community/standard-json/effect": ["effect@4.0.0-beta.74", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-Yx+Kh12U+i2FmjwEfKs+ePFmpMd43RPD1oGqc/VraSS9bYzvF0Ff3PojwEFEVEewp8xc92Uxu28gTspU4qyvHA=="],
"@standard-community/standard-openapi/effect": ["effect@4.0.0-beta.74", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-Yx+Kh12U+i2FmjwEfKs+ePFmpMd43RPD1oGqc/VraSS9bYzvF0Ff3PojwEFEVEewp8xc92Uxu28gTspU4qyvHA=="],
"@storybook/csf-plugin/unplugin": ["unplugin@2.3.11", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="], "@storybook/csf-plugin/unplugin": ["unplugin@2.3.11", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "acorn": "^8.15.0", "picomatch": "^4.0.3", "webpack-virtual-modules": "^0.6.2" } }, "sha512-5uKD0nqiYVzlmCRs01Fhs2BdkEgBS3SAVP6ndrBsuK42iC2+JHyxM05Rm9G8+5mkmRtzMZGY8Ct5+mliZxU/Ww=="],
"@tailwindcss/oxide/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "@tailwindcss/oxide/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
@@ -6700,6 +6706,10 @@
"@solidjs/start/shiki/@shikijs/types": ["@shikijs/types@1.29.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4" } }, "sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw=="], "@solidjs/start/shiki/@shikijs/types": ["@shikijs/types@1.29.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4" } }, "sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw=="],
"@standard-community/standard-json/effect/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@standard-community/standard-openapi/effect/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@storybook/csf-plugin/unplugin/webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], "@storybook/csf-plugin/unplugin/webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
"@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="], "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="],
+4 -4
View File
@@ -1,8 +1,8 @@
{ {
"nodeModules": { "nodeModules": {
"x86_64-linux": "sha256-LOxTad/iCquvJyonFOcz6/rDTPNDmwyBnykhWZJ5GC4=", "x86_64-linux": "sha256-oWSGu+SP66Aquy/0Vaq7Bgp8404ZdOWbQX+O7h3jxHU=",
"aarch64-linux": "sha256-iO+0vYhp+2x6ACmh5lQJ/2Ac4uZTqRZE/KhG3u0o6D8=", "aarch64-linux": "sha256-UsS0+c+GwtIukmWwQeFbY/3Oaz3t4Q7C6cFMGkmlyAY=",
"aarch64-darwin": "sha256-tpBydRbrJ+4QxmkGUt/BhME8q6ysCW/CXrsNshYgqDU=", "aarch64-darwin": "sha256-CArz92ewPmXO+ORFCBkCH8LzMpU/DjyaO4ic7QL0UpI=",
"x86_64-darwin": "sha256-QQcI6SK7WJ7dSkX6xZuSQPoUdwfoCaimVgoHCnrO0wY=" "x86_64-darwin": "sha256-rhnz9gmG6L06wIzfMhTaXDDEf6IbMD32CavqwXoqcUs="
} }
} }
+4 -4
View File
@@ -30,9 +30,9 @@
"packages/slack" "packages/slack"
], ],
"catalog": { "catalog": {
"@effect/opentelemetry": "4.0.0-beta.74", "@effect/opentelemetry": "4.0.0-beta.83",
"@effect/platform-node": "4.0.0-beta.74", "@effect/platform-node": "4.0.0-beta.83",
"@effect/sql-sqlite-bun": "4.0.0-beta.74", "@effect/sql-sqlite-bun": "4.0.0-beta.83",
"@npmcli/arborist": "9.4.0", "@npmcli/arborist": "9.4.0",
"@types/bun": "1.3.13", "@types/bun": "1.3.13",
"@types/cross-spawn": "6.0.6", "@types/cross-spawn": "6.0.6",
@@ -61,7 +61,7 @@
"dompurify": "3.3.1", "dompurify": "3.3.1",
"drizzle-kit": "1.0.0-rc.2", "drizzle-kit": "1.0.0-rc.2",
"drizzle-orm": "1.0.0-rc.2", "drizzle-orm": "1.0.0-rc.2",
"effect": "4.0.0-beta.74", "effect": "4.0.0-beta.83",
"ai": "6.0.168", "ai": "6.0.168",
"cross-spawn": "7.0.6", "cross-spawn": "7.0.6",
"hono": "4.10.7", "hono": "4.10.7",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@opencode-ai/app", "name": "@opencode-ai/app",
"version": "1.17.8", "version": "1.17.9",
"description": "", "description": "",
"type": "module", "type": "module",
"exports": { "exports": {
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://json.schemastore.org/package.json", "$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/cli", "name": "@opencode-ai/cli",
"version": "1.17.8", "version": "1.17.9",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
"bin": { "bin": {
+5 -3
View File
@@ -27,9 +27,11 @@ export default Runtime.handler(
function listen(hostname: string, port: Option.Option<number>, password: string) { function listen(hostname: string, port: Option.Option<number>, password: string) {
if (Option.isSome(port)) return bind(hostname, port.value, password) if (Option.isSome(port)) return bind(hostname, port.value, password)
// Preserve the familiar default when available, but let the OS choose a free const next = (port: number): ReturnType<typeof bind> =>
// port when another local server already owns 4096. bind(hostname, port, password).pipe(
return bind(hostname, 4096, password).pipe(Effect.catch(() => bind(hostname, 0, password))) Effect.catch((error) => (port === 65_535 ? Effect.fail(error) : next(port + 1))),
)
return next(4096)
} }
function bind(hostname: string, port: number, password: string) { function bind(hostname: string, port: number, password: string) {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@opencode-ai/console-app", "name": "@opencode-ai/console-app",
"version": "1.17.8", "version": "1.17.9",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
@@ -196,6 +196,13 @@ export async function handler(
Object.entries(providerInfo.headerMappings ?? {}).forEach(([k, v]) => { Object.entries(providerInfo.headerMappings ?? {}).forEach(([k, v]) => {
headers.set(k, headers.get(v)!) headers.set(k, headers.get(v)!)
}) })
Object.entries(providerInfo.headerModifier ?? {}).forEach(([k, v]) => {
if (v === "$ip") return headers.set(k, ip)
if (v === "$session") return headers.set(k, sessionId)
if (v === "$model") return headers.set(k, model)
if (v === "$request") return headers.set(k, requestId)
headers.set(k, v)
})
headers.delete("host") headers.delete("host")
headers.delete("content-length") headers.delete("content-length")
headers.delete("x-opencode-request") headers.delete("x-opencode-request")
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://json.schemastore.org/package.json", "$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/console-core", "name": "@opencode-ai/console-core",
"version": "1.17.8", "version": "1.17.9",
"private": true, "private": true,
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
+1
View File
@@ -53,6 +53,7 @@ export namespace ZenData {
apiKey: z.union([z.string(), z.record(z.string(), z.string())]), apiKey: z.union([z.string(), z.record(z.string(), z.string())]),
format: FormatSchema.optional(), format: FormatSchema.optional(),
headerMappings: z.record(z.string(), z.string()).optional(), headerMappings: z.record(z.string(), z.string()).optional(),
headerModifier: z.record(z.string(), z.any()).optional(),
payloadModifier: z.record(z.string(), z.any()).optional(), payloadModifier: z.record(z.string(), z.any()).optional(),
payloadMappings: z.record(z.string(), z.string()).optional(), payloadMappings: z.record(z.string(), z.string()).optional(),
adjustCacheUsage: z.boolean().optional(), adjustCacheUsage: z.boolean().optional(),
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@opencode-ai/console-function", "name": "@opencode-ai/console-function",
"version": "1.17.8", "version": "1.17.9",
"$schema": "https://json.schemastore.org/package.json", "$schema": "https://json.schemastore.org/package.json",
"private": true, "private": true,
"type": "module", "type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@opencode-ai/console-mail", "name": "@opencode-ai/console-mail",
"version": "1.17.8", "version": "1.17.9",
"dependencies": { "dependencies": {
"@jsx-email/all": "2.2.3", "@jsx-email/all": "2.2.3",
"@jsx-email/cli": "1.4.3", "@jsx-email/cli": "1.4.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@opencode-ai/console-support", "name": "@opencode-ai/console-support",
"version": "1.17.8", "version": "1.17.9",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
+2
View File
@@ -0,0 +1,2 @@
[test]
preload = ["./test/preload.ts"]
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"$schema": "https://json.schemastore.org/package.json", "$schema": "https://json.schemastore.org/package.json",
"version": "1.17.8", "version": "1.17.9",
"name": "@opencode-ai/core", "name": "@opencode-ai/core",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
@@ -91,6 +91,7 @@
"@opencode-ai/effect-drizzle-sqlite": "workspace:*", "@opencode-ai/effect-drizzle-sqlite": "workspace:*",
"@opencode-ai/effect-sqlite-node": "workspace:*", "@opencode-ai/effect-sqlite-node": "workspace:*",
"@opencode-ai/llm": "workspace:*", "@opencode-ai/llm": "workspace:*",
"@opencode-ai/plugin": "workspace:*",
"@opentelemetry/api": "1.9.0", "@opentelemetry/api": "1.9.0",
"@opentelemetry/context-async-hooks": "2.6.1", "@opentelemetry/context-async-hooks": "2.6.1",
"@opentelemetry/exporter-trace-otlp-http": "0.214.0", "@opentelemetry/exporter-trace-otlp-http": "0.214.0",
+2 -32
View File
@@ -1,8 +1,8 @@
{ {
"version": "7", "version": "7",
"dialect": "sqlite", "dialect": "sqlite",
"id": "169a0f0f-d58f-479f-b024-fa1c7b9a09db", "id": "f14a9b18-8207-487e-a3d3-227e629ba9ad",
"prevIds": ["abd2f920-b822-49af-b8a7-2e48367d424f"], "prevIds": ["169a0f0f-d58f-479f-b024-fa1c7b9a09db"],
"ddl": [ "ddl": [
{ {
"name": "workspace", "name": "workspace",
@@ -900,16 +900,6 @@
"entityType": "columns", "entityType": "columns",
"table": "session_context_epoch" "table": "session_context_epoch"
}, },
{
"type": "text",
"notNull": true,
"autoincrement": false,
"default": "'build'",
"generated": null,
"name": "agent",
"entityType": "columns",
"table": "session_context_epoch"
},
{ {
"type": "text", "type": "text",
"notNull": true, "notNull": true,
@@ -930,26 +920,6 @@
"entityType": "columns", "entityType": "columns",
"table": "session_context_epoch" "table": "session_context_epoch"
}, },
{
"type": "integer",
"notNull": false,
"autoincrement": false,
"default": null,
"generated": null,
"name": "replacement_seq",
"entityType": "columns",
"table": "session_context_epoch"
},
{
"type": "integer",
"notNull": true,
"autoincrement": false,
"default": "0",
"generated": null,
"name": "revision",
"entityType": "columns",
"table": "session_context_epoch"
},
{ {
"type": "text", "type": "text",
"notNull": false, "notNull": false,
+18 -4
View File
@@ -45,15 +45,17 @@ async function generate() {
if (await Bun.file(target).exists()) throw new Error(`Database migration already exists: ${name}`) if (await Bun.file(target).exists()) throw new Error(`Database migration already exists: ${name}`)
await Bun.write( await Bun.write(
target, target,
await formatTypescript(
renderMigration(name, await Bun.file(path.join(incremental, name, "migration.sql")).text()), renderMigration(name, await Bun.file(path.join(incremental, name, "migration.sql")).text()),
),
) )
await fs.copyFile(path.join(incremental, name, "snapshot.json"), snapshot) await fs.copyFile(path.join(incremental, name, "snapshot.json"), snapshot)
} }
await fs.mkdir(full) await fs.mkdir(full)
await drizzle(temporary, full, "schema") await drizzle(temporary, full, "schema")
await Bun.write(schema, renderSchema(await generatedSql(full))) await Bun.write(schema, await formatTypescript(renderSchema(await generatedSql(full))))
await Bun.write(registry, renderRegistry(await typescriptMigrations())) await Bun.write(registry, await formatTypescript(renderRegistry(await typescriptMigrations())))
} finally { } finally {
await fs.rm(temporary, { recursive: true, force: true }) await fs.rm(temporary, { recursive: true, force: true })
} }
@@ -76,12 +78,12 @@ async function check() {
await fs.mkdir(full) await fs.mkdir(full)
await drizzle(temporary, full, "schema") await drizzle(temporary, full, "schema")
if ((await Bun.file(schema).text()) !== renderSchema(await generatedSql(full))) { if ((await Bun.file(schema).text()) !== (await formatTypescript(renderSchema(await generatedSql(full))))) {
throw new Error("Current database schema is stale. Run `bun script/migration.ts` from packages/core.") throw new Error("Current database schema is stale. Run `bun script/migration.ts` from packages/core.")
} }
const migrations = await typescriptMigrations() const migrations = await typescriptMigrations()
if ((await Bun.file(registry).text()) !== renderRegistry(migrations)) { if ((await Bun.file(registry).text()) !== (await formatTypescript(renderRegistry(migrations)))) {
throw new Error("Database migration registry is stale. Run `bun script/migration.ts` from packages/core.") throw new Error("Database migration registry is stale. Run `bun script/migration.ts` from packages/core.")
} }
} finally { } finally {
@@ -170,6 +172,18 @@ function escapeTemplate(line: string) {
return line.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${") return line.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${")
} }
async function formatTypescript(input: string) {
const prettier = await import("prettier")
const typescript = await import("prettier/plugins/typescript")
const estree = await import("prettier/plugins/estree")
return prettier.format(input, {
parser: "typescript",
plugins: [typescript.default, estree.default],
semi: false,
printWidth: 120,
})
}
function renderRegistry(names: string[]) { function renderRegistry(names: string[]) {
return `import type { DatabaseMigration } from "./migration" return `import type { DatabaseMigration } from "./migration"
+4 -4
View File
@@ -35,19 +35,19 @@ export class Org extends Schema.Class<Org>("Org")({
export class AccountRepoError extends Schema.TaggedErrorClass<AccountRepoError>()("AccountRepoError", { export class AccountRepoError extends Schema.TaggedErrorClass<AccountRepoError>()("AccountRepoError", {
message: Schema.String, message: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export class AccountServiceError extends Schema.TaggedErrorClass<AccountServiceError>()("AccountServiceError", { export class AccountServiceError extends Schema.TaggedErrorClass<AccountServiceError>()("AccountServiceError", {
message: Schema.String, message: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export class AccountTransportError extends Schema.TaggedErrorClass<AccountTransportError>()("AccountTransportError", { export class AccountTransportError extends Schema.TaggedErrorClass<AccountTransportError>()("AccountTransportError", {
method: Schema.String, method: Schema.String,
url: Schema.String, url: Schema.String,
description: Schema.optional(Schema.String), description: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) { }) {
static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError { static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError {
return new AccountTransportError({ return new AccountTransportError({
@@ -94,7 +94,7 @@ export class PollExpired extends Schema.TaggedClass<PollExpired>()("PollExpired"
export class PollDenied extends Schema.TaggedClass<PollDenied>()("PollDenied", {}) {} export class PollDenied extends Schema.TaggedClass<PollDenied>()("PollDenied", {}) {}
export class PollError extends Schema.TaggedClass<PollError>()("PollError", { export class PollError extends Schema.TaggedClass<PollError>()("PollError", {
cause: Schema.Defect, cause: Schema.Defect(),
}) {} }) {}
export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError]) export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError])
+9 -14
View File
@@ -1,7 +1,6 @@
export * as AgentV2 from "./agent" export * as AgentV2 from "./agent"
import { Array, Context, Effect, Layer, Schema, Scope } from "effect" import { Array, Context, Effect, Layer, Schema, Scope, Types } from "effect"
import { castDraft, enableMapSet, type Draft } from "immer"
import { ModelV2 } from "./model" import { ModelV2 } from "./model"
import { PermissionSchema } from "./permission/schema" import { PermissionSchema } from "./permission/schema"
import { ProviderV2 } from "./provider" import { ProviderV2 } from "./provider"
@@ -49,21 +48,19 @@ export interface Selection {
} }
type Data = { type Data = {
agents: Map<ID, Info> agents: Map<ID, Types.DeepMutable<Info>>
default?: ID default?: ID
} }
export type Editor = { export type Draft = {
list: () => readonly Info[] list: () => readonly Info[]
get: (id: ID) => Info | undefined get: (id: ID) => Info | undefined
default: (id: ID | undefined) => void default: (id: ID | undefined) => void
update: (id: ID, fn: (agent: Draft<Info>) => void) => void update: (id: ID, fn: (agent: Types.DeepMutable<Info>) => void) => void
remove: (id: ID) => void remove: (id: ID) => void
} }
export interface Interface { export interface Interface extends State.Transformable<Draft> {
readonly transform: State.Interface<Data, Editor>["transform"]
readonly update: State.Interface<Data, Editor>["update"]
readonly get: (id: ID) => Effect.Effect<Info | undefined> readonly get: (id: ID) => Effect.Effect<Info | undefined>
readonly default: () => Effect.Effect<Info | undefined> readonly default: () => Effect.Effect<Info | undefined>
readonly resolve: (id?: ID | string) => Effect.Effect<Info | undefined> readonly resolve: (id?: ID | string) => Effect.Effect<Info | undefined>
@@ -73,21 +70,19 @@ export interface Interface {
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Agent") {} export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Agent") {}
enableMapSet()
export const layer = Layer.effect( export const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const state = State.create<Data, Editor>({ const state = State.create<Data, Draft>({
initial: () => ({ agents: new Map() }), initial: () => ({ agents: new Map() }),
editor: (draft) => ({ draft: (draft) => ({
list: () => Array.fromIterable(draft.agents.values()) as Info[], list: () => Array.fromIterable(draft.agents.values()) as Info[],
get: (id) => draft.agents.get(id), get: (id) => draft.agents.get(id),
default: (id) => { default: (id) => {
draft.default = id draft.default = id
}, },
update: (id, fn) => { update: (id, fn) => {
const current = draft.agents.get(id) ?? castDraft(Info.empty(id)) const current = draft.agents.get(id) ?? (Info.empty(id) as Types.DeepMutable<Info>)
if (!draft.agents.has(id)) draft.agents.set(id, current) if (!draft.agents.has(id)) draft.agents.set(id, current)
fn(current) fn(current)
current.id = id current.id = id
@@ -113,7 +108,7 @@ export const layer = Layer.effect(
return Service.of({ return Service.of({
transform: state.transform, transform: state.transform,
update: state.update, reload: state.reload,
get: Effect.fn("AgentV2.get")(function* (id) { get: Effect.fn("AgentV2.get")(function* (id) {
return state.get().agents.get(id) return state.get().agents.get(id)
}), }),
+75 -22
View File
@@ -1,14 +1,27 @@
export * as AISDK from "./aisdk" export * as AISDK from "./aisdk"
import type { LanguageModelV3 } from "@ai-sdk/provider" import type { LanguageModelV3 } from "@ai-sdk/provider"
import { Cause, Context, Effect, Layer, Schema } from "effect" import { Cause, Context, Effect, Layer, Schema, Scope } from "effect"
import { ModelV2 } from "./model" import { ModelV2 } from "./model"
import { EventV2 } from "./event"
import { PluginV2 } from "./plugin"
import { ProviderV2 } from "./provider" import { ProviderV2 } from "./provider"
import { State } from "./state"
type SDK = any type SDK = any
export interface SDKEvent {
readonly model: ModelV2.Info
readonly package: string
readonly options: Record<string, any>
sdk?: SDK
}
export interface LanguageEvent {
readonly model: ModelV2.Info
readonly sdk: SDK
readonly options: Record<string, any>
language?: LanguageModelV3
}
function wrapSSE(res: Response, ms: number, ctl: AbortController) { function wrapSSE(res: Response, ms: number, ctl: AbortController) {
if (typeof ms !== "number" || ms <= 0) return res if (typeof ms !== "number" || ms <= 0) return res
if (!res.body) return res if (!res.body) return res
@@ -109,7 +122,7 @@ function prepareOptions(model: ModelV2.Info, pkg: string) {
export class InitError extends Schema.TaggedErrorClass<InitError>()("AISDK.InitError", { export class InitError extends Schema.TaggedErrorClass<InitError>()("AISDK.InitError", {
providerID: ProviderV2.ID, providerID: ProviderV2.ID,
cause: Schema.Defect, cause: Schema.Defect(),
}) {} }) {}
function initError(providerID: ProviderV2.ID) { function initError(providerID: ProviderV2.ID) {
@@ -117,19 +130,70 @@ function initError(providerID: ProviderV2.ID) {
} }
export interface Interface { export interface Interface {
readonly hook: {
readonly sdk: (
callback: (event: SDKEvent) => Effect.Effect<void> | void,
) => Effect.Effect<State.Registration, never, Scope.Scope>
readonly language: (
callback: (event: LanguageEvent) => Effect.Effect<void> | void,
) => Effect.Effect<State.Registration, never, Scope.Scope>
}
readonly runSDK: (event: SDKEvent) => Effect.Effect<SDKEvent>
readonly runLanguage: (event: LanguageEvent) => Effect.Effect<LanguageEvent>
readonly language: (model: ModelV2.Info) => Effect.Effect<LanguageModelV3, InitError> readonly language: (model: ModelV2.Info) => Effect.Effect<LanguageModelV3, InitError>
} }
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/AISDK") {} export class Service extends Context.Service<Service, Interface>()("@opencode/v2/AISDK") {}
export const layer = Layer.effect( export const locationLayer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const plugin = yield* PluginV2.Service let sdkHooks: ((event: SDKEvent) => Effect.Effect<void> | void)[] = []
let languageHooks: ((event: LanguageEvent) => Effect.Effect<void> | void)[] = []
const languages = new Map<string, LanguageModelV3>() const languages = new Map<string, LanguageModelV3>()
const sdks = new Map<string, SDK>() const sdks = new Map<string, SDK>()
return Service.of({ const register = <Event>(
hooks: () => ((event: Event) => Effect.Effect<void> | void)[],
update: (hooks: ((event: Event) => Effect.Effect<void> | void)[]) => void,
) =>
Effect.fn("AISDK.hook")(function* (callback: (event: Event) => Effect.Effect<void> | void) {
const scope = yield* Scope.Scope
let active = true
update([...hooks(), callback])
const dispose = Effect.sync(() => {
if (!active) return
active = false
update(hooks().filter((item) => item !== callback))
})
yield* Scope.addFinalizer(scope, dispose)
return { dispose }
})
const run = Effect.fnUntraced(function* <Event>(
hooks: readonly ((event: Event) => Effect.Effect<void> | void)[],
event: Event,
) {
for (const hook of hooks) {
const result = hook(event)
if (Effect.isEffect(result)) yield* result
}
return event
})
const service = Service.of({
hook: {
sdk: register(
() => sdkHooks,
(next) => (sdkHooks = next),
),
language: register(
() => languageHooks,
(next) => (languageHooks = next),
),
},
runSDK: (event) => run(sdkHooks, event),
runLanguage: (event) => run(languageHooks, event),
language: Effect.fn("AISDK.language")(function* (model) { language: Effect.fn("AISDK.language")(function* (model) {
const key = `${model.providerID}/${model.id}/${model.request.variant ?? "default"}` const key = `${model.providerID}/${model.id}/${model.request.variant ?? "default"}`
const existing = languages.get(key) const existing = languages.get(key)
@@ -148,26 +212,14 @@ export const layer = Layer.effect(
}) })
const sdk = const sdk =
sdks.get(sdkKey) ?? sdks.get(sdkKey) ??
(yield* plugin (yield* service.runSDK({ model, package: model.api.package, options }).pipe(initError(model.providerID))).sdk
.trigger("aisdk.sdk", { model, package: model.api.package, options }, {})
.pipe(initError(model.providerID))).sdk
if (!sdk) if (!sdk)
return yield* new InitError({ return yield* new InitError({
providerID: model.providerID, providerID: model.providerID,
cause: new Error("No AISDK provider plugin returned an SDK"), cause: new Error("No AISDK provider plugin returned an SDK"),
}) })
sdks.set(sdkKey, sdk) sdks.set(sdkKey, sdk)
const result = yield* plugin const result = yield* service.runLanguage({ model, sdk, options }).pipe(initError(model.providerID))
.trigger(
"aisdk.language",
{
model,
sdk,
options,
},
{},
)
.pipe(initError(model.providerID))
const language = yield* Effect.sync(() => result.language ?? sdk.languageModel(model.api.id)).pipe( const language = yield* Effect.sync(() => result.language ?? sdk.languageModel(model.api.id)).pipe(
initError(model.providerID), initError(model.providerID),
) )
@@ -175,7 +227,8 @@ export const layer = Layer.effect(
return language return language
}), }),
}) })
return service
}), }),
) )
export const defaultLayer = layer.pipe(Layer.provide(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer)))) export const defaultLayer = locationLayer
+49 -96
View File
@@ -1,36 +1,21 @@
export * as Catalog from "./catalog" export * as Catalog from "./catalog"
import { Array, Context, Effect, Layer, Option, Order, pipe, Schema, Scope, Stream } from "effect" import { Array, Context, Effect, Layer, Option, Order, pipe, Schema } from "effect"
import { castDraft, enableMapSet, type Draft } from "immer"
import { ModelV2 } from "./model" import { ModelV2 } from "./model"
import { ModelRequest } from "./model-request" import { ModelRequest } from "./model-request"
import { PluginV2 } from "./plugin"
import { ProviderV2 } from "./provider" import { ProviderV2 } from "./provider"
import { Location } from "./location"
import { EventV2 } from "./event" import { EventV2 } from "./event"
import { Policy } from "./policy" import { Policy } from "./policy"
import { State } from "./state" import { State } from "./state"
import { Integration } from "./integration" import { Integration } from "./integration"
export type ProviderRecord = { export type ProviderRecord = {
provider: ProviderV2.Info provider: ProviderV2.MutableInfo
models: Map<ModelV2.ID, ModelV2.Info> models: Map<ModelV2.ID, ModelV2.MutableInfo>
} }
export type DefaultModel = { providerID: ProviderV2.ID; modelID: ModelV2.ID } export type DefaultModel = { providerID: ProviderV2.ID; modelID: ModelV2.ID }
export class ProviderNotFoundError extends Schema.TaggedErrorClass<ProviderNotFoundError>()(
"CatalogV2.ProviderNotFound",
{
providerID: ProviderV2.ID,
},
) {}
export class ModelNotFoundError extends Schema.TaggedErrorClass<ModelNotFoundError>()("CatalogV2.ModelNotFound", {
providerID: ProviderV2.ID,
modelID: ModelV2.ID,
}) {}
export const PolicyActions = Schema.Literals(["provider.use"]) export const PolicyActions = Schema.Literals(["provider.use"])
export const Event = { export const Event = {
@@ -42,16 +27,16 @@ type Data = {
defaultModel?: DefaultModel defaultModel?: DefaultModel
} }
export type Editor = { export type Draft = {
provider: { provider: {
list: () => readonly ProviderRecord[] list: () => readonly ProviderRecord[]
get: (providerID: ProviderV2.ID) => ProviderRecord | undefined get: (providerID: ProviderV2.ID) => ProviderRecord | undefined
update: (providerID: ProviderV2.ID, fn: (provider: Draft<ProviderV2.Info>) => void) => void update: (providerID: ProviderV2.ID, fn: (provider: ProviderV2.MutableInfo) => void) => void
remove: (providerID: ProviderV2.ID) => void remove: (providerID: ProviderV2.ID) => void
} }
model: { model: {
get: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => ModelV2.Info | undefined get: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => ModelV2.Info | undefined
update: (providerID: ProviderV2.ID, modelID: ModelV2.ID, fn: (model: Draft<ModelV2.Info>) => void) => void update: (providerID: ProviderV2.ID, modelID: ModelV2.ID, fn: (model: ModelV2.MutableInfo) => void) => void
remove: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => void remove: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => void
default: { default: {
get: () => DefaultModel | undefined get: () => DefaultModel | undefined
@@ -60,43 +45,34 @@ export type Editor = {
} }
} }
export interface Interface { export interface Interface extends State.Transformable<Draft> {
readonly transform: State.Interface<Data, Editor>["transform"]
readonly provider: { readonly provider: {
readonly get: (providerID: ProviderV2.ID) => Effect.Effect<ProviderV2.Info, ProviderNotFoundError> readonly get: (providerID: ProviderV2.ID) => Effect.Effect<ProviderV2.Info | undefined>
readonly all: () => Effect.Effect<ProviderV2.Info[]> readonly all: () => Effect.Effect<ProviderV2.Info[]>
readonly available: () => Effect.Effect<ProviderV2.Info[]> readonly available: () => Effect.Effect<ProviderV2.Info[]>
} }
readonly model: { readonly model: {
readonly get: ( readonly get: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => Effect.Effect<ModelV2.Info | undefined>
providerID: ProviderV2.ID,
modelID: ModelV2.ID,
) => Effect.Effect<ModelV2.Info, ProviderNotFoundError | ModelNotFoundError>
readonly all: () => Effect.Effect<ModelV2.Info[]> readonly all: () => Effect.Effect<ModelV2.Info[]>
readonly available: () => Effect.Effect<ModelV2.Info[]> readonly available: () => Effect.Effect<ModelV2.Info[]>
readonly default: () => Effect.Effect<Option.Option<ModelV2.Info>> readonly default: () => Effect.Effect<ModelV2.Info | undefined>
readonly small: (providerID: ProviderV2.ID) => Effect.Effect<Option.Option<ModelV2.Info>> readonly small: (providerID: ProviderV2.ID) => Effect.Effect<ModelV2.Info | undefined>
} }
} }
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Catalog") {} export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Catalog") {}
enableMapSet()
export const layer = Layer.effect( export const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const location = yield* Location.Service
const plugin = yield* PluginV2.Service
const events = yield* EventV2.Service const events = yield* EventV2.Service
const policy = yield* Policy.Service const policy = yield* Policy.Service
const integrations = yield* Integration.Service const integrations = yield* Integration.Service
const scope = yield* Scope.Scope
const available = (provider: ProviderV2.Info, integration: Integration.Info | undefined, connected: boolean) => { const available = (provider: ProviderV2.Info, integration: Integration.Info | undefined) => {
if (provider.disabled) return false if (provider.disabled) return false
if (typeof provider.request.body.apiKey === "string") return true if (typeof provider.request.body.apiKey === "string") return true
if (connected) return true if (integration?.connections.length) return true
return !integration return !integration
} }
@@ -120,32 +96,26 @@ export const layer = Layer.effect(
}) })
} }
function* getRecord(providerID: ProviderV2.ID) { const normalizeApi = (item: ProviderV2.MutableInfo | ModelV2.MutableInfo) => {
const match = state.get().providers.get(providerID)
if (!match) return yield* new ProviderNotFoundError({ providerID })
return match
}
const normalizeApi = (item: Draft<ProviderV2.Info> | Draft<ModelV2.Info>) => {
if (typeof item.request.body.baseURL !== "string") return if (typeof item.request.body.baseURL !== "string") return
item.api.url = item.request.body.baseURL item.api.url = item.request.body.baseURL
delete item.request.body.baseURL delete item.request.body.baseURL
} }
const state = State.create<Data, Editor>({ const state = State.create<Data, Draft>({
initial: () => ({ providers: new Map() }), initial: () => ({ providers: new Map() }),
editor: (draft) => { draft: (draft) => {
const result: Editor = { const result: Draft = {
provider: { provider: {
list: () => Array.fromIterable(draft.providers.values()) as ProviderRecord[], list: () => Array.fromIterable(draft.providers.values()) as ProviderRecord[],
get: (providerID) => draft.providers.get(providerID), get: (providerID) => draft.providers.get(providerID),
update: (providerID, fn) => { update: (providerID, fn) => {
let current = draft.providers.get(providerID) let current = draft.providers.get(providerID)
if (!current) { if (!current) {
current = castDraft({ current = {
provider: ProviderV2.Info.empty(providerID), provider: ProviderV2.Info.empty(providerID) as ProviderV2.MutableInfo,
models: new Map<ModelV2.ID, ModelV2.Info>(), models: new Map<ModelV2.ID, ModelV2.MutableInfo>(),
}) }
draft.providers.set(providerID, current) draft.providers.set(providerID, current)
} }
fn(current.provider) fn(current.provider)
@@ -160,13 +130,14 @@ export const layer = Layer.effect(
update: (providerID, modelID, fn) => { update: (providerID, modelID, fn) => {
let record = draft.providers.get(providerID) let record = draft.providers.get(providerID)
if (!record) { if (!record) {
record = castDraft({ record = {
provider: ProviderV2.Info.empty(providerID), provider: ProviderV2.Info.empty(providerID) as ProviderV2.MutableInfo,
models: new Map<ModelV2.ID, ModelV2.Info>(), models: new Map<ModelV2.ID, ModelV2.MutableInfo>(),
}) }
draft.providers.set(providerID, record) draft.providers.set(providerID, record)
} }
const model = record.models.get(modelID) ?? castDraft(ModelV2.Info.empty(providerID, modelID)) const model =
record.models.get(modelID) ?? (ModelV2.Info.empty(providerID, modelID) as ModelV2.MutableInfo)
if (!record.models.has(modelID)) record.models.set(modelID, model) if (!record.models.has(modelID)) record.models.set(modelID, model)
fn(model) fn(model)
model.id = modelID model.id = modelID
@@ -186,8 +157,7 @@ export const layer = Layer.effect(
} }
return result return result
}, },
finalize: Effect.fn("CatalogV2.finalize")(function* (catalog, reason) { finalize: Effect.fn("CatalogV2.finalize")(function* (catalog) {
if (reason !== "plugin.added") yield* plugin.trigger("catalog.transform", catalog, {}).pipe(Effect.asVoid)
if (policy.hasStatements()) { if (policy.hasStatements()) {
for (const record of [...catalog.provider.list()]) { for (const record of [...catalog.provider.list()]) {
if ((yield* policy.evaluate("provider.use", record.provider.id, "allow")) === "deny") { if ((yield* policy.evaluate("provider.use", record.provider.id, "allow")) === "deny") {
@@ -198,25 +168,13 @@ export const layer = Layer.effect(
yield* events.publish(Event.Updated, {}) yield* events.publish(Event.Updated, {})
}), }),
}) })
yield* events.subscribe(PluginV2.Event.Added).pipe(
// Plugin registries are location scoped even though the event bus is process scoped.
Stream.filter(
(event) =>
event.location?.directory === location.directory && event.location.workspaceID === location.workspaceID,
),
Stream.runForEach((event) =>
state.mutate((catalog) => plugin.triggerFor(event.data.id, "catalog.transform", catalog, {}), "plugin.added"),
),
Effect.forkIn(scope, { startImmediately: true }),
)
const result: Interface = { const result: Interface = {
transform: state.transform, transform: state.transform,
reload: state.reload,
provider: { provider: {
get: Effect.fn("CatalogV2.provider.get")(function* (providerID) { get: Effect.fn("CatalogV2.provider.get")(function* (providerID) {
const record = yield* getRecord(providerID) return state.get().providers.get(providerID)?.provider
return record.provider
}), }),
all: Effect.fn("CatalogV2.provider.all")(function* () { all: Effect.fn("CatalogV2.provider.all")(function* () {
@@ -225,23 +183,18 @@ export const layer = Layer.effect(
available: Effect.fn("CatalogV2.provider.available")(function* () { available: Effect.fn("CatalogV2.provider.available")(function* () {
const active = new Map((yield* integrations.list()).map((integration) => [integration.id, integration])) const active = new Map((yield* integrations.list()).map((integration) => [integration.id, integration]))
const connections = yield* integrations.connection.list()
return (yield* result.provider.all()).filter((provider) => return (yield* result.provider.all()).filter((provider) =>
available( available(provider, active.get(Integration.ID.make(provider.id))),
provider,
active.get(Integration.ID.make(provider.id)),
connections.has(Integration.ID.make(provider.id)),
),
) )
}), }),
}, },
model: { model: {
get: Effect.fn("CatalogV2.model.get")(function* (providerID, modelID) { get: Effect.fn("CatalogV2.model.get")(function* (providerID, modelID) {
const record = yield* getRecord(providerID) const record = state.get().providers.get(providerID)
if (!record) return
const model = record.models.get(modelID) const model = record.models.get(modelID)
if (!model) return yield* new ModelNotFoundError({ providerID, modelID }) return model && projectModel(model, record.provider)
return projectModel(model, record.provider)
}), }),
all: Effect.fn("CatalogV2.model.all")(function* () { all: Effect.fn("CatalogV2.model.all")(function* () {
@@ -250,7 +203,7 @@ export const layer = Layer.effect(
Array.flatMap((record) => { Array.flatMap((record) => {
return Array.fromIterable(record.models.values()).map((model) => projectModel(model, record.provider)) return Array.fromIterable(record.models.values()).map((model) => projectModel(model, record.provider))
}), }),
Array.sortWith((item) => item.time.released.epochMilliseconds, Order.flip(Order.Number)), Array.sortWith((item) => item.time.released, Order.flip(Order.Number)),
) )
}), }),
@@ -262,31 +215,30 @@ export const layer = Layer.effect(
default: Effect.fn("CatalogV2.model.default")(function* () { default: Effect.fn("CatalogV2.model.default")(function* () {
const defaultModel = state.get().defaultModel const defaultModel = state.get().defaultModel
if (defaultModel) { if (defaultModel) {
const provider = yield* result.provider.get(defaultModel.providerID).pipe(Effect.option) const provider = yield* result.provider.get(defaultModel.providerID)
if ( if (provider && (yield* result.provider.available()).some((item) => item.id === provider.id)) {
Option.isSome(provider) && const model = yield* result.model.get(defaultModel.providerID, defaultModel.modelID)
(yield* result.provider.available()).some((item) => item.id === provider.value.id) if (model?.enabled) return model
) {
const model = yield* result.model.get(defaultModel.providerID, defaultModel.modelID).pipe(Effect.option)
if (Option.isSome(model) && model.value.enabled) return model
} }
} }
return pipe( return Option.getOrUndefined(
pipe(
yield* result.model.available(), yield* result.model.available(),
Array.sortWith((item) => item.time.released.epochMilliseconds, Order.flip(Order.Number)), Array.sortWith((item) => item.time.released, Order.flip(Order.Number)),
Array.head, Array.head,
),
) )
}), }),
small: Effect.fn("CatalogV2.model.small")(function* (providerID) { small: Effect.fn("CatalogV2.model.small")(function* (providerID) {
const record = state.get().providers.get(providerID) const record = state.get().providers.get(providerID)
if (!record) return Option.none<ModelV2.Info>() if (!record) return
const provider = record.provider const provider = record.provider
if (providerID === ProviderV2.ID.opencode) { if (providerID === ProviderV2.ID.opencode) {
const gpt5Nano = record.models.get(ModelV2.ID.make("gpt-5-nano")) const gpt5Nano = record.models.get(ModelV2.ID.make("gpt-5-nano"))
if (gpt5Nano?.enabled && gpt5Nano.status === "active") return Option.some(projectModel(gpt5Nano, provider)) if (gpt5Nano?.enabled && gpt5Nano.status === "active") return projectModel(gpt5Nano, provider)
} }
const candidates = pipe( const candidates = pipe(
@@ -302,7 +254,7 @@ export const layer = Layer.effect(
Array.map((model) => ({ Array.map((model) => ({
model, model,
cost: model.cost[0] ? model.cost[0].input + model.cost[0].output : 999, cost: model.cost[0] ? model.cost[0].input + model.cost[0].output : 999,
age: (Date.now() - model.time.released.epochMilliseconds) / (1000 * 60 * 60 * 24 * 30), age: (Date.now() - model.time.released) / (1000 * 60 * 60 * 24 * 30),
small: SMALL_MODEL_RE.test(`${model.id} ${model.family ?? ""} ${model.name}`.toLowerCase()), small: SMALL_MODEL_RE.test(`${model.id} ${model.family ?? ""} ${model.name}`.toLowerCase()),
})), })),
Array.filter((item) => item.cost > 0 && item.age <= 18), Array.filter((item) => item.cost > 0 && item.age <= 18),
@@ -319,10 +271,12 @@ export const layer = Layer.effect(
) )
} }
return pipe( return Option.getOrUndefined(
pipe(
candidates, candidates,
Array.filter((item) => item.small), Array.filter((item) => item.small),
(items) => (items.length > 0 ? pick(items) : pick(candidates)), (items) => (items.length > 0 ? pick(items) : pick(candidates)),
),
) )
}), }),
}, },
@@ -336,6 +290,5 @@ const SMALL_MODEL_RE = /\b(nano|flash|lite|mini|haiku|small|fast)\b/
export const locationLayer = layer.pipe( export const locationLayer = layer.pipe(
Layer.provideMerge(Integration.locationLayer), Layer.provideMerge(Integration.locationLayer),
Layer.provideMerge(PluginV2.locationLayer),
Layer.provideMerge(Policy.locationLayer), Layer.provideMerge(Policy.locationLayer),
) )
+9 -12
View File
@@ -1,7 +1,6 @@
export * as CommandV2 from "./command" export * as CommandV2 from "./command"
import { Context, Effect, Layer, Schema } from "effect" import { Context, Effect, Layer, Schema, Types } from "effect"
import { castDraft, type Draft } from "immer"
import { ModelV2 } from "./model" import { ModelV2 } from "./model"
import { State } from "./state" import { State } from "./state"
@@ -15,19 +14,17 @@ export class Info extends Schema.Class<Info>("CommandV2.Info")({
}) {} }) {}
export type Data = { export type Data = {
commands: Map<string, Info> commands: Map<string, Types.DeepMutable<Info>>
} }
export type Editor = { export type Draft = {
list: () => readonly Info[] list: () => readonly Info[]
get: (name: string) => Info | undefined get: (name: string) => Info | undefined
update: (name: string, update: (command: Draft<Info>) => void) => void update: (name: string, update: (command: Types.DeepMutable<Info>) => void) => void
remove: (name: string) => void remove: (name: string) => void
} }
export interface Interface { export interface Interface extends State.Transformable<Draft> {
readonly transform: State.Interface<Data, Editor>["transform"]
readonly update: State.Interface<Data, Editor>["update"]
readonly get: (name: string) => Effect.Effect<Info | undefined> readonly get: (name: string) => Effect.Effect<Info | undefined>
readonly list: () => Effect.Effect<Info[]> readonly list: () => Effect.Effect<Info[]>
} }
@@ -37,13 +34,13 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/v2
export const layer = Layer.effect( export const layer = Layer.effect(
Service, Service,
Effect.sync(() => { Effect.sync(() => {
const state = State.create<Data, Editor>({ const state = State.create<Data, Draft>({
initial: () => ({ commands: new Map() }), initial: () => ({ commands: new Map() }),
editor: (draft) => ({ draft: (draft) => ({
list: () => Array.from(draft.commands.values()) as Info[], list: () => Array.from(draft.commands.values()) as Info[],
get: (name) => draft.commands.get(name), get: (name) => draft.commands.get(name),
update: (name, update) => { update: (name, update) => {
const current = draft.commands.get(name) ?? castDraft(new Info({ name, template: "" })) const current = draft.commands.get(name) ?? (new Info({ name, template: "" }) as Types.DeepMutable<Info>)
if (!draft.commands.has(name)) draft.commands.set(name, current) if (!draft.commands.has(name)) draft.commands.set(name, current)
update(current) update(current)
current.name = name current.name = name
@@ -55,7 +52,7 @@ export const layer = Layer.effect(
}) })
return Service.of({ return Service.of({
update: state.update, reload: state.reload,
transform: state.transform, transform: state.transform,
get: Effect.fn("CommandV2.get")(function* (name) { get: Effect.fn("CommandV2.get")(function* (name) {
return state.get().commands.get(name) return state.get().commands.get(name)
+14 -14
View File
@@ -1,5 +1,6 @@
export * as ConfigAgentPlugin from "./agent" export * as ConfigAgentPlugin from "./agent"
import { define } from "../../plugin/internal"
import path from "path" import path from "path"
import { Effect, Option, Schema } from "effect" import { Effect, Option, Schema } from "effect"
import { AgentV2 } from "../../agent" import { AgentV2 } from "../../agent"
@@ -8,7 +9,6 @@ import { ConfigAgent } from "../agent"
import { ConfigMarkdown } from "../markdown" import { ConfigMarkdown } from "../markdown"
import { FSUtil } from "../../fs-util" import { FSUtil } from "../../fs-util"
import { ModelV2 } from "../../model" import { ModelV2 } from "../../model"
import { PluginV2 } from "../../plugin"
import { ConfigAgentV1 } from "../../v1/config/agent" import { ConfigAgentV1 } from "../../v1/config/agent"
import { ConfigMigrateV1 } from "../../v1/config/migrate" import { ConfigMigrateV1 } from "../../v1/config/migrate"
@@ -33,12 +33,13 @@ const agentKeys = new Set([
"permissions", "permissions",
]) ])
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("config-agent"), id: "config-agent",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const agent = yield* AgentV2.Service
const config = yield* Config.Service const config = yield* Config.Service
const fs = yield* FSUtil.Service const fs = yield* FSUtil.Service
yield* ctx.agent.transform(
Effect.fn(function* (draft) {
const documents = yield* Effect.forEach(yield* config.entries(), (entry) => { const documents = yield* Effect.forEach(yield* config.entries(), (entry) => {
if (entry.type === "document") return Effect.succeed([entry]) if (entry.type === "document") return Effect.succeed([entry])
return Effect.gen(function* () { return Effect.gen(function* () {
@@ -55,25 +56,23 @@ export const Plugin = PluginV2.define({
) )
}) })
}).pipe(Effect.map((documents) => documents.flat())) }).pipe(Effect.map((documents) => documents.flat()))
yield* agent.update((editor) => {
const global = documents.flatMap((document) => document.info.permissions ?? []) const global = documents.flatMap((document) => document.info.permissions ?? [])
const configuredDefault = Config.latest(documents, "default_agent") const configuredDefault = Config.latest(documents, "default_agent")
if (configuredDefault !== undefined) editor.default(AgentV2.ID.make(configuredDefault)) if (configuredDefault !== undefined) draft.default(AgentV2.ID.make(configuredDefault))
for (const current of editor.list()) { for (const current of draft.list()) {
editor.update(current.id, (agent) => agent.permissions.push(...global)) draft.update(current.id, (agent) => agent.permissions.push(...global))
} }
for (const document of documents) { for (const document of documents) {
for (const [id, item] of Object.entries(document.info.agents ?? {})) { for (const [id, item] of Object.entries(document.info.agents ?? {})) {
const agentID = AgentV2.ID.make(id) const agentID = AgentV2.ID.make(id)
if (item.disabled) { if (item.disabled) {
editor.remove(agentID) draft.remove(agentID)
continue continue
} }
const exists = editor.get(agentID) !== undefined const exists = draft.get(agentID) !== undefined
editor.update(agentID, (agent) => { draft.update(agentID, (agent) => {
if (!exists) agent.permissions.push(...global) if (!exists) agent.permissions.push(...global)
if (item.model !== undefined) { if (item.model !== undefined) {
const model = ModelV2.parse(item.model) const model = ModelV2.parse(item.model)
@@ -96,7 +95,8 @@ export const Plugin = PluginV2.define({
}) })
} }
} }
}) }),
)
}), }),
}) })
+9 -10
View File
@@ -1,24 +1,24 @@
export * as ConfigCommandPlugin from "./command" export * as ConfigCommandPlugin from "./command"
import { define } from "../../plugin/internal"
import path from "path" import path from "path"
import { Effect, Option, Schema } from "effect" import { Effect, Option, Schema } from "effect"
import { CommandV2 } from "../../command" import { CommandV2 } from "../../command"
import { Config } from "../../config" import { Config } from "../../config"
import { FSUtil } from "../../fs-util" import { FSUtil } from "../../fs-util"
import { ModelV2 } from "../../model" import { ModelV2 } from "../../model"
import { PluginV2 } from "../../plugin"
import { ConfigCommand } from "../command" import { ConfigCommand } from "../command"
import { ConfigMarkdown } from "../markdown" import { ConfigMarkdown } from "../markdown"
const decodeCommand = Schema.decodeUnknownOption(ConfigCommand.Info) const decodeCommand = Schema.decodeUnknownOption(ConfigCommand.Info)
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("config-command"), id: "config-command",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const command = yield* CommandV2.Service
const config = yield* Config.Service const config = yield* Config.Service
const fs = yield* FSUtil.Service const fs = yield* FSUtil.Service
const transform = yield* command.transform() yield* ctx.command.transform(
Effect.fn(function* (draft) {
const documents = yield* Effect.forEach(yield* config.entries(), (entry) => { const documents = yield* Effect.forEach(yield* config.entries(), (entry) => {
if (entry.type === "document") return Effect.succeed([{ commands: entry.info.commands }]) if (entry.type === "document") return Effect.succeed([{ commands: entry.info.commands }])
return loadDirectory(fs, entry.path).pipe( return loadDirectory(fs, entry.path).pipe(
@@ -27,11 +27,9 @@ export const Plugin = PluginV2.define({
]), ]),
) )
}).pipe(Effect.map((documents) => documents.flat())) }).pipe(Effect.map((documents) => documents.flat()))
yield* transform((editor) => {
for (const document of documents) { for (const document of documents) {
for (const [name, command] of Object.entries(document.commands ?? {})) { for (const [name, command] of Object.entries(document.commands ?? {})) {
editor.update(name, (item) => { draft.update(name, (item) => {
item.template = command.template item.template = command.template
if (command.description !== undefined) item.description = command.description if (command.description !== undefined) item.description = command.description
if (command.agent !== undefined) item.agent = command.agent if (command.agent !== undefined) item.agent = command.agent
@@ -46,7 +44,8 @@ export const Plugin = PluginV2.define({
}) })
} }
} }
}) }),
)
}), }),
}) })
@@ -0,0 +1,91 @@
export * as ConfigExternalPlugin from "./external"
import type { Plugin as EffectPlugin } from "@opencode-ai/plugin/v2/effect"
import type { Plugin as PromisePlugin } from "@opencode-ai/plugin/v2/promise"
import { Effect, Schema } from "effect"
import path from "path"
import { fileURLToPath, pathToFileURL } from "url"
import { Config } from "../../config"
import { FSUtil } from "../../fs-util"
import { Location } from "../../location"
import { Npm } from "../../npm"
import { define } from "../../plugin/internal"
import { PluginPromise } from "../../plugin/promise"
const PluginModule = Schema.Struct({
default: Schema.Union([
Schema.Struct({
id: Schema.String,
effect: Schema.declare<EffectPlugin["effect"]>(
(input): input is EffectPlugin["effect"] => typeof input === "function",
),
}),
Schema.Struct({
id: Schema.String,
setup: Schema.declare<PromisePlugin["setup"]>(
(input): input is PromisePlugin["setup"] => typeof input === "function",
),
}),
]),
})
export const Plugin = define({
id: "config-plugin",
effect: Effect.fn(function* (ctx) {
const config = yield* Config.Service
const fs = yield* FSUtil.Service
const location = yield* Location.Service
const npm = yield* Npm.Service
yield* Effect.gen(function* () {
const configured: { package: string; options?: Record<string, any> }[] = []
for (const entry of yield* config.entries()) {
if (entry.type === "document") {
const directory = entry.path ? path.dirname(entry.path) : location.directory
for (const item of entry.info.plugins ?? []) {
const ref = typeof item === "string" ? { package: item } : item
const packageName = (() => {
if (ref.package.startsWith("file://")) return fileURLToPath(ref.package)
if (ref.package.startsWith("./") || ref.package.startsWith("../")) {
return path.resolve(directory, ref.package)
}
return ref.package
})()
configured.push({ package: packageName, options: ref.options })
}
}
if (entry.type === "directory") {
const files = yield* fs
.glob("{plugin,plugins}/*.{ts,js}", {
cwd: entry.path,
absolute: true,
include: "file",
dot: true,
symlink: true,
})
.pipe(Effect.orElseSucceed(() => []))
files.sort()
for (const file of files) configured.push({ package: file })
}
}
for (const ref of configured) {
yield* Effect.gen(function* () {
const entrypoint = path.isAbsolute(ref.package)
? pathToFileURL(ref.package).href
: (yield* npm.add(ref.package)).entrypoint
if (!entrypoint) return
const mod = yield* Effect.promise(() => import(entrypoint))
const value = (yield* Schema.decodeUnknownEffect(PluginModule)(mod)).default
const plugin = "effect" in value ? value : PluginPromise.fromPromise(value)
yield* ctx.plugin.add({
id: plugin.id,
effect: (host) => plugin.effect({ ...host, options: ref.options ?? {} }),
})
}).pipe(Effect.ignoreCause)
}
}).pipe(Effect.forkScoped({ startImmediately: true }))
}),
})
+21 -20
View File
@@ -1,33 +1,29 @@
export * as ConfigProviderPlugin from "./provider" export * as ConfigProviderPlugin from "./provider"
import { define } from "../../plugin/internal"
import { Effect } from "effect" import { Effect } from "effect"
import { Catalog } from "../../catalog"
import { Config } from "../../config" import { Config } from "../../config"
import { Integration } from "../../integration"
import { ModelV2 } from "../../model" import { ModelV2 } from "../../model"
import { ModelRequest } from "../../model-request" import { ModelRequest } from "../../model-request"
import { PluginV2 } from "../../plugin"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("config-provider"), id: "config-provider",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const catalog = yield* Catalog.Service
const config = yield* Config.Service const config = yield* Config.Service
const integrations = yield* Integration.Service yield* ctx.integration.transform(
const transform = yield* catalog.transform() Effect.fn(function* (integrations) {
const integrationTransform = yield* integrations.transform() const files = (yield* config.entries()).filter((entry): entry is Config.Document => entry.type === "document")
const entries = yield* config.entries()
const files = entries.filter((entry): entry is Config.Document => entry.type === "document")
const configuredIntegrations = new Set( const configuredIntegrations = new Set(
files.flatMap((file) => files.flatMap((file) =>
Object.entries(file.info.providers ?? {}).flatMap(([id, provider]) => (provider.env === undefined ? [] : [id])), Object.entries(file.info.providers ?? {}).flatMap(([id, provider]) =>
provider.env === undefined ? [] : [id],
),
), ),
) )
yield* integrationTransform((integrations) => {
for (const file of files) { for (const file of files) {
for (const [id, item] of Object.entries(file.info.providers ?? {})) { for (const [id, item] of Object.entries(file.info.providers ?? {})) {
const integrationID = Integration.ID.make(id) const integrationID = id
if (!configuredIntegrations.has(id) && !integrations.get(integrationID)) continue if (!configuredIntegrations.has(id) && !integrations.get(integrationID)) continue
integrations.update(integrationID, (integration) => { integrations.update(integrationID, (integration) => {
integration.name = item.name ?? integration.name integration.name = item.name ?? integration.name
@@ -40,9 +36,13 @@ export const Plugin = PluginV2.define({
} }
} }
} }
}) }),
)
yield* transform((catalog) => { yield* ctx.catalog.transform(
Effect.fn(function* (catalog) {
const entries = yield* config.entries()
const files = entries.filter((entry): entry is Config.Document => entry.type === "document")
const configuredDefault = Config.latest(entries, "model") const configuredDefault = Config.latest(entries, "model")
if (configuredDefault !== undefined) { if (configuredDefault !== undefined) {
const model = ModelV2.parse(configuredDefault) const model = ModelV2.parse(configuredDefault)
@@ -50,7 +50,7 @@ export const Plugin = PluginV2.define({
} }
for (const file of files) { for (const file of files) {
for (const [id, item] of Object.entries(file.info.providers ?? {})) { for (const [id, item] of Object.entries(file.info.providers ?? {})) {
const providerID = ProviderV2.ID.make(id) const providerID = id
catalog.provider.update(providerID, (provider) => { catalog.provider.update(providerID, (provider) => {
if (item.name !== undefined) provider.name = item.name if (item.name !== undefined) provider.name = item.name
if (item.api !== undefined) provider.api = { ...item.api } if (item.api !== undefined) provider.api = { ...item.api }
@@ -63,7 +63,7 @@ export const Plugin = PluginV2.define({
const providerPackage = providerApi?.type === "aisdk" ? providerApi.package : undefined const providerPackage = providerApi?.type === "aisdk" ? providerApi.package : undefined
for (const [id, config] of Object.entries(item.models ?? {})) { for (const [id, config] of Object.entries(item.models ?? {})) {
catalog.model.update(providerID, ModelV2.ID.make(id), (model) => { catalog.model.update(providerID, id, (model) => {
if (config.family !== undefined) model.family = config.family if (config.family !== undefined) model.family = config.family
if (config.name !== undefined) model.name = config.name if (config.name !== undefined) model.name = config.name
if (config.api !== undefined) model.api = { ...model.api, ...config.api } if (config.api !== undefined) model.api = { ...model.api, ...config.api }
@@ -118,6 +118,7 @@ export const Plugin = PluginV2.define({
} }
} }
} }
}) }),
)
}), }),
}) })
+13 -14
View File
@@ -1,23 +1,23 @@
export * as ConfigReferencePlugin from "./reference" export * as ConfigReferencePlugin from "./reference"
import { define } from "../../plugin/internal"
import path from "path" import path from "path"
import { Effect } from "effect" import { Effect } from "effect"
import { Config } from "../../config" import { Config } from "../../config"
import { ConfigReference } from "../reference" import { ConfigReference } from "../reference"
import { Global } from "../../global"
import { Location } from "../../location"
import { PluginV2 } from "../../plugin"
import { Reference } from "../../reference" import { Reference } from "../../reference"
import { AbsolutePath } from "../../schema" import { AbsolutePath } from "../../schema"
import { Global } from "../../global"
import { Location } from "../../location"
export const Plugin = { export const Plugin = define({
id: PluginV2.ID.make("core/config-reference"), id: "core/config-reference",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const config = yield* Config.Service const config = yield* Config.Service
const global = yield* Global.Service
const location = yield* Location.Service const location = yield* Location.Service
const references = yield* Reference.Service const global = yield* Global.Service
const update = yield* references.transform() yield* ctx.reference.transform(
Effect.fn(function* (draft) {
const entries = new Map<string, Reference.Source>() const entries = new Map<string, Reference.Source>()
for (const doc of (yield* config.entries()).filter( for (const doc of (yield* config.entries()).filter(
(entry): entry is Config.Document => entry.type === "document", (entry): entry is Config.Document => entry.type === "document",
@@ -46,12 +46,11 @@ export const Plugin = {
) )
} }
} }
for (const [name, source] of entries) draft.add(name, source)
yield* update((editor) => {
for (const [name, source] of entries) editor.add(name, source)
})
}), }),
} )
}),
})
function validAlias(name: string) { function validAlias(name: string) {
return name.length > 0 && !/[\/\s`,]/.test(name) return name.length > 0 && !/[\/\s`,]/.test(name)
+14 -15
View File
@@ -1,48 +1,47 @@
export * as ConfigSkillPlugin from "./skill" export * as ConfigSkillPlugin from "./skill"
import { define } from "../../plugin/internal"
import path from "path" import path from "path"
import { Effect } from "effect" import { Effect } from "effect"
import { Config } from "../../config" import { Config } from "../../config"
import { Global } from "../../global"
import { Location } from "../../location"
import { PluginV2 } from "../../plugin"
import { AbsolutePath } from "../../schema" import { AbsolutePath } from "../../schema"
import { SkillV2 } from "../../skill" import { SkillV2 } from "../../skill"
import { Global } from "../../global"
import { Location } from "../../location"
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("config-skill"), id: "config-skill",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const config = yield* Config.Service const config = yield* Config.Service
const global = yield* Global.Service const global = yield* Global.Service
const location = yield* Location.Service const location = yield* Location.Service
const skill = yield* SkillV2.Service yield* ctx.skill.transform(
const transform = yield* skill.transform() Effect.fn(function* (draft) {
const entries = yield* config.entries() const entries = yield* config.entries()
const directories = entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : [])) const directories = entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : []))
const items = entries.flatMap((entry) => (entry.type === "document" ? (entry.info.skills ?? []) : [])) const items = entries.flatMap((entry) => (entry.type === "document" ? (entry.info.skills ?? []) : []))
yield* transform((editor) => {
for (const directory of directories) { for (const directory of directories) {
editor.source( draft.source(
new SkillV2.DirectorySource({ type: "directory", path: AbsolutePath.make(path.join(directory, "skill")) }), new SkillV2.DirectorySource({ type: "directory", path: AbsolutePath.make(path.join(directory, "skill")) }),
) )
editor.source( draft.source(
new SkillV2.DirectorySource({ type: "directory", path: AbsolutePath.make(path.join(directory, "skills")) }), new SkillV2.DirectorySource({ type: "directory", path: AbsolutePath.make(path.join(directory, "skills")) }),
) )
} }
for (const item of items) { for (const item of items) {
if (URL.canParse(item) && /^(https?:)$/.test(new URL(item).protocol)) { if (URL.canParse(item) && /^(https?:)$/.test(new URL(item).protocol)) {
editor.source(new SkillV2.UrlSource({ type: "url", url: item })) draft.source(new SkillV2.UrlSource({ type: "url", url: item }))
continue continue
} }
const expanded = item.startsWith("~/") ? path.join(global.home, item.slice(2)) : item const expanded = item.startsWith("~/") ? path.join(global.home, item.slice(2)) : item
editor.source( draft.source(
new SkillV2.DirectorySource({ new SkillV2.DirectorySource({
type: "directory", type: "directory",
path: AbsolutePath.make(path.isAbsolute(expanded) ? expanded : path.join(location.directory, expanded)), path: AbsolutePath.make(path.isAbsolute(expanded) ? expanded : path.join(location.directory, expanded)),
}), }),
) )
} }
}) }),
)
}), }),
}) })
@@ -48,7 +48,7 @@ export class ResetSourceChangesError extends Schema.TaggedErrorClass<ResetSource
{ {
directory: AbsolutePath, directory: AbsolutePath,
message: Schema.String, message: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}, },
) {} ) {}
+14 -14
View File
@@ -29,33 +29,33 @@ export class Key extends Schema.Class<Key>("Credential.Key")({
metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)), metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)),
}) {} }) {}
export const Info = Schema.Union([OAuth, Key]) export const Value = Schema.Union([OAuth, Key])
.pipe(Schema.toTaggedUnion("type")) .pipe(Schema.toTaggedUnion("type"))
.annotate({ identifier: "Credential.Info" }) .annotate({ identifier: "Credential.Value" })
export type Info = Schema.Schema.Type<typeof Info> export type Value = Schema.Schema.Type<typeof Value>
export class Stored extends Schema.Class<Stored>("Credential.Stored")({ export class Info extends Schema.Class<Info>("Credential.Info")({
id: ID, id: ID,
integrationID: IntegrationSchema.ID, integrationID: IntegrationSchema.ID,
label: Schema.String, label: Schema.String,
value: Info, value: Value,
}) {} }) {}
export interface Interface { export interface Interface {
/** Returns every stored credential. */ /** Returns every stored credential. */
readonly all: () => Effect.Effect<Stored[]> readonly all: () => Effect.Effect<Info[]>
/** Returns stored credentials belonging to one integration. */ /** Returns stored credentials belonging to one integration. */
readonly list: (integrationID: IntegrationSchema.ID) => Effect.Effect<Stored[]> readonly list: (integrationID: IntegrationSchema.ID) => Effect.Effect<Info[]>
/** Returns one stored credential by ID. */ /** Returns one stored credential by ID. */
readonly get: (id: ID) => Effect.Effect<Stored | undefined> readonly get: (id: ID) => Effect.Effect<Info | undefined>
/** Replaces any credential for an integration and returns the new record. */ /** Replaces any credential for an integration and returns the new record. */
readonly create: (input: { readonly create: (input: {
readonly integrationID: IntegrationSchema.ID readonly integrationID: IntegrationSchema.ID
readonly value: Info readonly value: Value
readonly label?: string readonly label?: string
}) => Effect.Effect<Stored> }) => Effect.Effect<Info>
/** Updates the label or secret value of a stored credential. */ /** Updates the label or secret value of a stored credential. */
readonly update: (id: ID, updates: Partial<Pick<Stored, "label" | "value">>) => Effect.Effect<void> readonly update: (id: ID, updates: Partial<Pick<Info, "label" | "value">>) => Effect.Effect<void>
/** Removes a stored credential. */ /** Removes a stored credential. */
readonly remove: (id: ID) => Effect.Effect<void> readonly remove: (id: ID) => Effect.Effect<void>
} }
@@ -66,10 +66,10 @@ export const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const { db } = yield* Database.Service const { db } = yield* Database.Service
const decode = Schema.decodeUnknownSync(Info) const decode = Schema.decodeUnknownSync(Value)
const stored = (row: typeof CredentialTable.$inferSelect) => { const stored = (row: typeof CredentialTable.$inferSelect) => {
if (!row.integration_id) return if (!row.integration_id) return
return new Stored({ return new Info({
id: row.id, id: row.id,
integrationID: row.integration_id, integrationID: row.integration_id,
label: row.label, label: row.label,
@@ -106,7 +106,7 @@ export const layer = Layer.effect(
return row ? stored(row) : undefined return row ? stored(row) : undefined
}), }),
create: Effect.fn("Credential.create")(function* (input) { create: Effect.fn("Credential.create")(function* (input) {
const credential = new Stored({ const credential = new Info({
id: ID.create(), id: ID.create(),
integrationID: input.integrationID, integrationID: input.integrationID,
label: input.label ?? "default", label: input.label ?? "default",
+1 -1
View File
@@ -7,7 +7,7 @@ export const CredentialTable = sqliteTable("credential", {
id: text().$type<Credential.ID>().primaryKey(), id: text().$type<Credential.ID>().primaryKey(),
integration_id: text().$type<IntegrationSchema.ID>(), integration_id: text().$type<IntegrationSchema.ID>(),
label: text().notNull(), label: text().notNull(),
value: text({ mode: "json" }).$type<Credential.Info>().notNull(), value: text({ mode: "json" }).$type<Credential.Value>().notNull(),
connector_id: text(), connector_id: text(),
method_id: text(), method_id: text(),
active: integer({ mode: "boolean" }), active: integer({ mode: "boolean" }),
+3
View File
@@ -37,5 +37,8 @@ export const migrations = (
import("./migration/20260611035744_credential"), import("./migration/20260611035744_credential"),
import("./migration/20260611192811_lush_chimera"), import("./migration/20260611192811_lush_chimera"),
import("./migration/20260612174303_project_dir_strategy"), import("./migration/20260612174303_project_dir_strategy"),
import("./migration/20260622142730_simplify_session_context_epoch"),
import("./migration/20260622170816_reset_v2_session_state"),
import("./migration/20260622202450_simplify_session_input"),
]) ])
).map((module) => module.default) satisfies DatabaseMigration.Migration[] ).map((module) => module.default) satisfies DatabaseMigration.Migration[]
@@ -0,0 +1,13 @@
import { Effect } from "effect"
import type { DatabaseMigration } from "../migration"
export default {
id: "20260622142730_simplify_session_context_epoch",
up(tx) {
return Effect.gen(function* () {
yield* tx.run(`ALTER TABLE \`session_context_epoch\` DROP COLUMN \`agent\`;`)
yield* tx.run(`ALTER TABLE \`session_context_epoch\` DROP COLUMN \`replacement_seq\`;`)
yield* tx.run(`ALTER TABLE \`session_context_epoch\` DROP COLUMN \`revision\`;`)
})
},
} satisfies DatabaseMigration.Migration
@@ -0,0 +1,17 @@
import { Effect } from "effect"
import type { DatabaseMigration } from "../migration"
export default {
id: "20260622170816_reset_v2_session_state",
up(tx) {
return Effect.gen(function* () {
yield* tx.run(`DELETE FROM \`session_context_epoch\`;`)
yield* tx.run(`DELETE FROM \`session_input\`;`)
yield* tx.run(`DELETE FROM \`session_message\`;`)
yield* tx.run(`DELETE FROM \`event\`;`)
yield* tx.run(`DELETE FROM \`event_sequence\`;`)
yield* tx.run(`UPDATE \`session\` SET \`workspace_id\` = NULL WHERE \`workspace_id\` IS NOT NULL;`)
yield* tx.run(`DELETE FROM \`workspace\`;`)
})
},
} satisfies DatabaseMigration.Migration
@@ -0,0 +1,17 @@
import { Effect } from "effect"
import type { DatabaseMigration } from "../migration"
export default {
id: "20260622202450_simplify_session_input",
up(tx) {
return Effect.gen(function* () {
yield* tx.run(`DELETE FROM \`session_context_epoch\`;`)
yield* tx.run(`DELETE FROM \`session_input\`;`)
yield* tx.run(`DELETE FROM \`session_message\`;`)
yield* tx.run(`DELETE FROM \`event\`;`)
yield* tx.run(`DELETE FROM \`event_sequence\`;`)
yield* tx.run(`UPDATE \`session\` SET \`workspace_id\` = NULL WHERE \`workspace_id\` IS NOT NULL;`)
yield* tx.run(`DELETE FROM \`workspace\`;`)
})
},
} satisfies DatabaseMigration.Migration
-3
View File
@@ -149,11 +149,8 @@ export default {
CREATE TABLE \`session_context_epoch\` ( CREATE TABLE \`session_context_epoch\` (
\`session_id\` text PRIMARY KEY, \`session_id\` text PRIMARY KEY,
\`baseline\` text NOT NULL, \`baseline\` text NOT NULL,
\`agent\` text DEFAULT 'build' NOT NULL,
\`snapshot\` text NOT NULL, \`snapshot\` text NOT NULL,
\`baseline_seq\` integer NOT NULL, \`baseline_seq\` integer NOT NULL,
\`replacement_seq\` integer,
\`revision\` integer DEFAULT 0 NOT NULL,
CONSTRAINT \`fk_session_context_epoch_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE CONSTRAINT \`fk_session_context_epoch_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE
); );
`) `)
+141 -175
View File
@@ -5,7 +5,7 @@ import { and, asc, eq, gt } from "drizzle-orm"
import { Database } from "./database/database" import { Database } from "./database/database"
import { EventSequenceTable, EventTable } from "./event/sql" import { EventSequenceTable, EventTable } from "./event/sql"
import { Location } from "./location" import { Location } from "./location"
import { externalID, type ExternalID, NonNegativeInt, withStatics } from "./schema" import { externalID, type ExternalID, withStatics } from "./schema"
import { Identifier } from "./util/identifier" import { Identifier } from "./util/identifier"
import { LayerNode } from "./effect/layer-node" import { LayerNode } from "./effect/layer-node"
import { isDeepStrictEqual } from "node:util" import { isDeepStrictEqual } from "node:util"
@@ -19,16 +19,9 @@ export const ID = Schema.String.check(Schema.isStartsWith("evt_")).pipe(
) )
export type ID = typeof ID.Type export type ID = typeof ID.Type
/**
* Durable aggregate continuation position for embedded replay streams.
* TODO: Decide whether a future HTTP / SDK surface should expose an opaque cursor instead.
*/
export const Cursor = NonNegativeInt.pipe(Schema.brand("EventV2.Cursor"))
export type Cursor = typeof Cursor.Type
export type Definition<Type extends string = string, DataSchema extends Schema.Top = Schema.Top> = { export type Definition<Type extends string = string, DataSchema extends Schema.Top = Schema.Top> = {
readonly type: Type readonly type: Type
readonly sync?: { readonly durable?: {
readonly version: number readonly version: number
readonly aggregate: string readonly aggregate: string
} }
@@ -41,22 +34,31 @@ export type Payload<D extends Definition = Definition> = {
readonly id: ID readonly id: ID
readonly type: D["type"] readonly type: D["type"]
readonly data: Data<D> readonly data: Data<D>
/** Durable aggregate order, populated while synchronized events are projected. */ readonly durable?: {
readonly seq?: number readonly aggregateID: string
readonly version?: number readonly seq: number
readonly version: number
}
readonly location?: Location.Ref readonly location?: Location.Ref
readonly metadata?: Record<string, unknown> readonly metadata?: Record<string, unknown>
/** Internal replay marker for projectors that own non-replicated operational state. */
readonly replay?: boolean
} }
export type Projector<D extends Definition = Definition> = (event: Payload<D>) => Effect.Effect<void> export type Subscriber<D extends Definition = Definition> = (event: Payload<D>) => Effect.Effect<void>
type AnyProjector = (event: Payload) => Effect.Effect<void>
export type CommitGuard = (event: Payload) => Effect.Effect<void>
export type Listener = (event: Payload) => Effect.Effect<void>
export type Sync = (event: Payload) => Effect.Effect<void>
export type Unsubscribe = Effect.Effect<void> export type Unsubscribe = Effect.Effect<void>
export const latestSequence = Effect.fn("EventV2.latestSequence")(function* (
db: Database.Interface["db"],
aggregateID: string,
) {
const row = yield* db
.select({ seq: EventSequenceTable.seq })
.from(EventSequenceTable)
.where(eq(EventSequenceTable.aggregate_id, aggregateID))
.get()
.pipe(Effect.orDie)
return row?.seq ?? -1
})
export type SerializedEvent = { export type SerializedEvent = {
readonly id: ID readonly id: ID
readonly type: string readonly type: string
@@ -65,13 +67,8 @@ export type SerializedEvent = {
readonly data: Record<string, unknown> readonly data: Record<string, unknown>
} }
export type CursorEvent<E extends Payload = Payload> = { export class InvalidDurableEventError extends Schema.TaggedErrorClass<InvalidDurableEventError>()(
readonly cursor: Cursor "EventV2.InvalidDurableEvent",
readonly event: E
}
export class InvalidSyncEventError extends Schema.TaggedErrorClass<InvalidSyncEventError>()(
"EventV2.InvalidSyncEvent",
{ {
type: Schema.String, type: Schema.String,
message: Schema.String, message: Schema.String,
@@ -83,19 +80,11 @@ export function versionedType(type: string, version: number) {
} }
export const registry = new Map<string, Definition>() export const registry = new Map<string, Definition>()
type SyncDefinition = Definition & { const durableRegistry = new Map<string, Definition>()
readonly sync: NonNullable<Definition["sync"]>
readonly encode: (data: unknown) => unknown
readonly decode: (data: unknown) => unknown
}
const syncRegistry = new Map<string, SyncDefinition>()
// Synchronized events cross a JSON boundary, so their data schemas must encode and decode without services.
const syncCodec = (definition: Definition) => definition.data as Schema.Codec<unknown, unknown, never, never>
export function define<const Type extends string, Fields extends Schema.Struct.Fields>(input: { export function define<const Type extends string, Fields extends Schema.Struct.Fields>(input: {
readonly type: Type readonly type: Type
readonly sync?: { readonly durable?: {
readonly version: number readonly version: number
readonly aggregate: string readonly aggregate: string
} }
@@ -106,28 +95,25 @@ export function define<const Type extends string, Fields extends Schema.Struct.F
id: ID, id: ID,
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
type: Schema.Literal(input.type), type: Schema.Literal(input.type),
version: Schema.optional(Schema.Number), durable: Schema.optional(Schema.Struct({ aggregateID: Schema.String, seq: Schema.Number, version: Schema.Number })),
location: Schema.optional(Location.Ref), location: Schema.optional(Location.Ref),
data: Data, data: Data,
}).annotate({ identifier: input.type }) }).annotate({ identifier: input.type })
const definition = Object.assign(Payload, { const definition = Object.assign(Payload, {
type: input.type, type: input.type,
...(input.sync === undefined ? {} : { sync: input.sync }), ...(input.durable === undefined ? {} : { durable: input.durable }),
data: Data, data: Data,
}) })
const existing = registry.get(input.type) const existing = registry.get(input.type)
if (input.sync === undefined || existing?.sync === undefined || input.sync.version >= existing.sync.version) { if (
input.durable === undefined ||
existing?.durable === undefined ||
input.durable.version >= existing.durable.version
) {
registry.set(input.type, definition) registry.set(input.type, definition)
} }
if (input.sync) if (input.durable) durableRegistry.set(versionedType(input.type, input.durable.version), definition)
syncRegistry.set(
versionedType(input.type, input.sync.version),
Object.assign(definition, {
encode: Schema.encodeUnknownSync(syncCodec(definition)),
decode: Schema.decodeUnknownSync(syncCodec(definition)),
}) as SyncDefinition,
)
return definition as Schema.Schema<Payload<Definition<Type, Schema.Struct<Fields>>>> & return definition as Schema.Schema<Payload<Definition<Type, Schema.Struct<Fields>>>> &
Definition<Type, Schema.Struct<Fields>> Definition<Type, Schema.Struct<Fields>>
} }
@@ -140,7 +126,7 @@ export interface PublishOptions {
readonly id?: ID readonly id?: ID
readonly metadata?: Record<string, unknown> readonly metadata?: Record<string, unknown>
readonly location?: Location.Ref readonly location?: Location.Ref
/** Local operational projection committed atomically with a new synchronized event. Not replayed or serialized. */ /** Local operational projection committed atomically with a new durable event. Not replayed or serialized. */
readonly commit?: (seq: number) => Effect.Effect<void> readonly commit?: (seq: number) => Effect.Effect<void>
} }
@@ -152,14 +138,10 @@ export interface Interface {
) => Effect.Effect<Payload<D>> ) => Effect.Effect<Payload<D>>
readonly subscribe: <D extends Definition>(definition: D) => Stream.Stream<Payload<D>> readonly subscribe: <D extends Definition>(definition: D) => Stream.Stream<Payload<D>>
readonly all: () => Stream.Stream<Payload> readonly all: () => Stream.Stream<Payload>
readonly aggregateEvents: (input: { readonly durable: (input: { readonly aggregateID: string; readonly after?: number }) => Stream.Stream<Payload>
readonly aggregateID: string /** @deprecated Use `all()` and consume the returned stream. */
readonly after?: Cursor readonly listen: (listener: Subscriber) => Effect.Effect<Unsubscribe>
}) => Stream.Stream<CursorEvent> readonly project: <D extends Definition>(definition: D, projector: Subscriber<D>) => Effect.Effect<void>
readonly sync: (handler: Sync) => Effect.Effect<Unsubscribe>
readonly listen: (listener: Listener) => Effect.Effect<Unsubscribe>
readonly beforeCommit: (guard: CommitGuard) => Effect.Effect<void>
readonly project: <D extends Definition>(definition: D, projector: Projector<D>) => Effect.Effect<void>
readonly replay: ( readonly replay: (
event: SerializedEvent, event: SerializedEvent,
options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean }, options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean },
@@ -182,37 +164,37 @@ export const layerWith = (options?: LayerOptions) =>
Layer.effect( Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const all = yield* PubSub.unbounded<Payload>() const pubsub = {
const synchronized = new Map<string, Set<PubSub.PubSub<void>>>() all: yield* PubSub.unbounded<Payload>(),
const typed = new Map<string, PubSub.PubSub<Payload>>() durable: new Map<string, Set<PubSub.PubSub<void>>>(),
const projectors = new Map<string, AnyProjector[]>() typed: new Map<string, PubSub.PubSub<Payload>>(),
const commitGuards = new Array<CommitGuard>() }
const listeners = new Array<Listener>() const projectors = new Map<string, Subscriber[]>()
const syncHandlers = new Array<Sync>() const listeners = new Array<Subscriber>()
const { db } = yield* Database.Service const { db } = yield* Database.Service
const getOrCreate = (definition: Definition) => const getOrCreate = (definition: Definition) =>
Effect.gen(function* () { Effect.gen(function* () {
const existing = typed.get(definition.type) const existing = pubsub.typed.get(definition.type)
if (existing) return existing if (existing) return existing
const pubsub = yield* PubSub.unbounded<Payload>() const created = yield* PubSub.unbounded<Payload>()
typed.set(definition.type, pubsub) pubsub.typed.set(definition.type, created)
return pubsub return created
}) })
yield* Effect.addFinalizer(() => yield* Effect.addFinalizer(() =>
Effect.gen(function* () { Effect.gen(function* () {
yield* PubSub.shutdown(all) yield* PubSub.shutdown(pubsub.all)
yield* Effect.forEach( yield* Effect.forEach(
synchronized.values(), pubsub.durable.values(),
(pubsubs) => Effect.forEach(pubsubs, PubSub.shutdown, { discard: true }), (pubsubs) => Effect.forEach(pubsubs, PubSub.shutdown, { discard: true }),
{ discard: true }, { discard: true },
) )
yield* Effect.forEach(typed.values(), PubSub.shutdown, { discard: true }) yield* Effect.forEach(pubsub.typed.values(), PubSub.shutdown, { discard: true })
}), }),
) )
function commitSyncEvent( function commitDurableEvent(
event: Payload, event: Payload,
input?: { input?: {
readonly seq: number readonly seq: number
@@ -224,28 +206,20 @@ export const layerWith = (options?: LayerOptions) =>
) { ) {
return Effect.gen(function* () { return Effect.gen(function* () {
const definition = registry.get(event.type) const definition = registry.get(event.type)
const sync = definition?.sync const durable = definition?.durable
if (sync) { if (durable) {
if (event.version !== sync.version) { const aggregateID = (event.data as Record<string, unknown>)[durable.aggregate]
yield* Effect.die(
new InvalidSyncEventError({
type: event.type,
message: `Expected event version ${sync.version}, got ${event.version}`,
}),
)
}
const aggregateID = (event.data as Record<string, unknown>)[sync.aggregate]
if (typeof aggregateID !== "string") { if (typeof aggregateID !== "string") {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Expected string aggregate field ${sync.aggregate}`, message: `Expected string aggregate field ${durable.aggregate}`,
}), }),
) )
} else { } else {
if (input && input.aggregateID !== aggregateID) { if (input && input.aggregateID !== aggregateID) {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Aggregate mismatch: expected ${input.aggregateID}, got ${aggregateID}`, message: `Aggregate mismatch: expected ${input.aggregateID}, got ${aggregateID}`,
}), }),
@@ -265,12 +239,12 @@ export const layerWith = (options?: LayerOptions) =>
.get() .get()
.pipe(Effect.orDie) .pipe(Effect.orDie)
const latest = row?.seq ?? -1 const latest = row?.seq ?? -1
const encoded = syncRegistry const encoded = Schema.encodeUnknownSync(
.get(versionedType(definition.type, sync.version))! definition.data as Schema.Codec<unknown, unknown, never, never>,
.encode(event.data) as Record<string, unknown> )(event.data) as Record<string, unknown>
if (input?.strictOwner && row?.ownerID && row.ownerID !== input.ownerID) { if (input?.strictOwner && row?.ownerID && row.ownerID !== input.ownerID) {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Replay owner mismatch for aggregate ${aggregateID}: expected ${row.ownerID}, got ${input.ownerID ?? "none"}`, message: `Replay owner mismatch for aggregate ${aggregateID}: expected ${row.ownerID}, got ${input.ownerID ?? "none"}`,
}), }),
@@ -285,7 +259,7 @@ export const layerWith = (options?: LayerOptions) =>
.pipe(Effect.orDie) .pipe(Effect.orDie)
if ( if (
stored?.id === event.id && stored?.id === event.id &&
stored.type === versionedType(definition.type, sync.version) && stored.type === versionedType(definition.type, durable.version) &&
isDeepStrictEqual(stored.data, encoded) isDeepStrictEqual(stored.data, encoded)
) { ) {
if (input.ownerID && row?.ownerID == null) { if (input.ownerID && row?.ownerID == null) {
@@ -299,7 +273,7 @@ export const layerWith = (options?: LayerOptions) =>
return return
} }
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Replay diverged at aggregate ${aggregateID} sequence ${input.seq}`, message: `Replay diverged at aggregate ${aggregateID} sequence ${input.seq}`,
}), }),
@@ -311,7 +285,7 @@ export const layerWith = (options?: LayerOptions) =>
const seq = input?.seq ?? latest + 1 const seq = input?.seq ?? latest + 1
if (input && seq !== latest + 1) { if (input && seq !== latest + 1) {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Sequence mismatch for aggregate ${aggregateID}: expected ${latest + 1}, got ${seq}`, message: `Sequence mismatch for aggregate ${aggregateID}: expected ${latest + 1}, got ${seq}`,
}), }),
@@ -325,16 +299,17 @@ export const layerWith = (options?: LayerOptions) =>
.pipe(Effect.orDie) .pipe(Effect.orDie)
if (stored) if (stored)
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Event ${event.id} already exists at aggregate ${stored.aggregateID} sequence ${stored.seq}`, message: `Event ${event.id} already exists at aggregate ${stored.aggregateID} sequence ${stored.seq}`,
}), }),
) )
for (const guard of commitGuards) { const committed = {
yield* guard(event) ...event,
} durable: { aggregateID, seq, version: durable.version },
} as Payload
for (const projector of list) { for (const projector of list) {
yield* projector({ ...event, seq } as Payload) yield* projector(committed)
} }
if (commit) yield* commit(seq) if (commit) yield* commit(seq)
yield* db yield* db
@@ -356,7 +331,7 @@ export const layerWith = (options?: LayerOptions) =>
id: event.id, id: event.id,
aggregate_id: aggregateID, aggregate_id: aggregateID,
seq, seq,
type: versionedType(definition.type, sync.version), type: versionedType(definition.type, durable.version),
data: encoded, data: encoded,
}, },
]) ])
@@ -369,8 +344,8 @@ export const layerWith = (options?: LayerOptions) =>
.pipe(Effect.orDie) .pipe(Effect.orDie)
if (committed) { if (committed) {
yield* Effect.forEach( yield* Effect.forEach(
synchronized.get(committed.aggregateID) ?? [], pubsub.durable.get(committed.aggregateID) ?? [],
(pubsub) => PubSub.publish(pubsub, undefined), (wake) => PubSub.publish(wake, undefined),
{ discard: true }, { discard: true },
) )
} }
@@ -384,19 +359,25 @@ export const layerWith = (options?: LayerOptions) =>
function publishEvent<D extends Definition>(event: Payload<D>, commit?: PublishOptions["commit"]) { function publishEvent<D extends Definition>(event: Payload<D>, commit?: PublishOptions["commit"]) {
return Effect.gen(function* () { return Effect.gen(function* () {
const durable = registry.get(event.type)?.sync !== undefined const definition = registry.get(event.type)
if (!durable && commit) if (!definition?.durable && commit)
return yield* Effect.die( return yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: "Local commit hooks require a synchronized event", message: "Local commit hooks require a durable event",
}), }),
) )
if (durable) { if (definition?.durable) {
const committed = yield* commitSyncEvent(event as Payload, undefined, commit) const committed = yield* commitDurableEvent(event as Payload, undefined, commit)
if (committed) { if (committed) {
event = { ...event, seq: committed.seq } event = {
yield* Effect.forEach(syncHandlers, (sync) => observe(event as Payload, "sync", sync), { discard: true }) ...event,
durable: {
aggregateID: committed.aggregateID,
seq: committed.seq,
version: definition.durable.version,
},
}
yield* notify(event as Payload, true) yield* notify(event as Payload, true)
return event return event
} }
@@ -406,12 +387,11 @@ export const layerWith = (options?: LayerOptions) =>
}) })
} }
const observe = (event: Payload, kind: "sync" | "listener", observer: (event: Payload) => Effect.Effect<void>) => const observe = (event: Payload, observer: (event: Payload) => Effect.Effect<void>) =>
Effect.suspend(() => observer(event)).pipe( Effect.suspend(() => observer(event)).pipe(
Effect.catchCauseIf( Effect.catchCauseIf(
(cause) => !Cause.hasInterrupts(cause), (cause) => !Cause.hasInterrupts(cause),
(cause) => (cause) => Effect.logError("Event listener failed", { eventID: event.id, eventType: event.type, cause }),
Effect.logError("Event observer failed", { eventID: event.id, eventType: event.type, kind, cause }),
), ),
) )
@@ -419,12 +399,12 @@ export const layerWith = (options?: LayerOptions) =>
return Effect.gen(function* () { return Effect.gen(function* () {
yield* Effect.forEach( yield* Effect.forEach(
listeners, listeners,
(listener) => (isolateListeners ? observe(event, "listener", listener) : listener(event)), (listener) => (isolateListeners ? observe(event, listener) : listener(event)),
{ discard: true }, { discard: true },
) )
const pubsub = typed.get(event.type) const typed = pubsub.typed.get(event.type)
if (pubsub) yield* PubSub.publish(pubsub, event) if (typed) yield* PubSub.publish(typed, event)
yield* PubSub.publish(all, event) yield* PubSub.publish(pubsub.all, event)
}) })
} }
@@ -441,7 +421,6 @@ export const layerWith = (options?: LayerOptions) =>
id: options?.id ?? ID.create(), id: options?.id ?? ID.create(),
...(options?.metadata ? { metadata: options.metadata } : {}), ...(options?.metadata ? { metadata: options.metadata } : {}),
type: definition.type, type: definition.type,
...(definition.sync === undefined ? {} : { version: definition.sync.version }),
...(location ? { location } : {}), ...(location ? { location } : {}),
data, data,
} as Payload<D>, } as Payload<D>,
@@ -455,27 +434,37 @@ export const layerWith = (options?: LayerOptions) =>
options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean }, options?: { readonly publish?: boolean; readonly ownerID?: string; readonly strictOwner?: boolean },
) { ) {
return Effect.gen(function* () { return Effect.gen(function* () {
const definition = syncRegistry.get(event.type) const definition = durableRegistry.get(event.type)
if (!definition) { if (!definition?.durable) {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ type: event.type, message: `Unknown sync event type ${event.type}` }), new InvalidDurableEventError({ type: event.type, message: `Unknown durable event type ${event.type}` }),
) )
} else { } else {
const payload = { const payload = {
id: event.id, id: event.id,
type: definition.type, type: definition.type,
version: definition.sync.version, data: Schema.decodeUnknownSync(definition.data as Schema.Codec<unknown, unknown, never, never>)(
data: definition.decode(event.data), event.data,
replay: true, ),
} as Payload } as Payload
const committed = yield* commitSyncEvent(payload, { const committed = yield* commitDurableEvent(payload, {
seq: event.seq, seq: event.seq,
aggregateID: event.aggregateID, aggregateID: event.aggregateID,
ownerID: options?.ownerID, ownerID: options?.ownerID,
strictOwner: options?.strictOwner, strictOwner: options?.strictOwner,
}) })
if (committed && options?.publish) { if (committed && options?.publish) {
yield* notify({ ...payload, seq: committed.seq }, true) yield* notify(
{
...payload,
durable: {
aggregateID: committed.aggregateID,
seq: committed.seq,
version: definition.durable.version,
},
},
true,
)
} }
} }
}) })
@@ -490,7 +479,7 @@ export const layerWith = (options?: LayerOptions) =>
if (!source) return undefined if (!source) return undefined
if (events.some((event) => event.aggregateID !== source)) { if (events.some((event) => event.aggregateID !== source)) {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: events[0]?.type ?? "unknown", type: events[0]?.type ?? "unknown",
message: "Replay events must belong to the same aggregate", message: "Replay events must belong to the same aggregate",
}), }),
@@ -501,7 +490,7 @@ export const layerWith = (options?: LayerOptions) =>
const seq = start + index const seq = start + index
if (event.seq !== seq) { if (event.seq !== seq) {
yield* Effect.die( yield* Effect.die(
new InvalidSyncEventError({ new InvalidDurableEventError({
type: event.type, type: event.type,
message: `Replay sequence mismatch at index ${index}: expected ${seq}, got ${event.seq}`, message: `Replay sequence mismatch at index ${index}: expected ${seq}, got ${event.seq}`,
}), }),
@@ -540,22 +529,18 @@ export const layerWith = (options?: LayerOptions) =>
Stream.map((event) => event as Payload<D>), Stream.map((event) => event as Payload<D>),
) )
const streamAll = (): Stream.Stream<Payload> => Stream.fromPubSub(all) const streamAll = (): Stream.Stream<Payload> => Stream.fromPubSub(pubsub.all)
const decodeSerializedEvent = (event: SerializedEvent): CursorEvent => { const decodeSerializedEvent = (event: SerializedEvent): Payload => {
const definition = syncRegistry.get(event.type) const definition = durableRegistry.get(event.type)
if (!definition) { if (!definition?.durable) {
throw new InvalidSyncEventError({ type: event.type, message: `Unknown sync event type ${event.type}` }) throw new InvalidDurableEventError({ type: event.type, message: `Unknown durable event type ${event.type}` })
} }
return { return {
cursor: Cursor.make(event.seq),
event: {
id: event.id, id: event.id,
type: definition.type, type: definition.type,
version: definition.sync.version, durable: { aggregateID: event.aggregateID, seq: event.seq, version: definition.durable.version },
seq: event.seq, data: Schema.decodeUnknownSync(definition.data as Schema.Codec<unknown, unknown, never, never>)(event.data),
data: definition.decode(event.data),
},
} }
} }
@@ -583,43 +568,40 @@ export const layerWith = (options?: LayerOptions) =>
), ),
) )
const subscribeSynchronized = (aggregateID: string) => const subscribeDurable = (aggregateID: string) =>
Effect.gen(function* () { Effect.gen(function* () {
const pubsub = yield* PubSub.sliding<void>(1) const wake = yield* PubSub.sliding<void>(1)
const subscription = yield* PubSub.subscribe(pubsub) const subscription = yield* PubSub.subscribe(wake)
yield* Effect.acquireRelease( yield* Effect.acquireRelease(
Effect.sync(() => { Effect.sync(() => {
const pubsubs = synchronized.get(aggregateID) ?? new Set() const wakes = pubsub.durable.get(aggregateID) ?? new Set()
pubsubs.add(pubsub) wakes.add(wake)
synchronized.set(aggregateID, pubsubs) pubsub.durable.set(aggregateID, wakes)
}), }),
() => () =>
Effect.sync(() => { Effect.sync(() => {
const pubsubs = synchronized.get(aggregateID) const wakes = pubsub.durable.get(aggregateID)
pubsubs?.delete(pubsub) wakes?.delete(wake)
if (pubsubs?.size === 0) synchronized.delete(aggregateID) if (wakes?.size === 0) pubsub.durable.delete(aggregateID)
}).pipe(Effect.andThen(PubSub.shutdown(pubsub))), }).pipe(Effect.andThen(PubSub.shutdown(wake))),
) )
return subscription return subscription
}) })
const streamEvents = (input: { const durable = (input: { readonly aggregateID: string; readonly after?: number }): Stream.Stream<Payload> =>
readonly aggregateID: string
readonly after?: Cursor
}): Stream.Stream<CursorEvent> =>
Stream.unwrap( Stream.unwrap(
Effect.gen(function* () { Effect.gen(function* () {
const synchronized = yield* subscribeSynchronized(input.aggregateID) const wakes = yield* subscribeDurable(input.aggregateID)
let cursor = input.after ?? -1 let sequence = input.after ?? -1
const read = Effect.suspend(() => readAfter(input.aggregateID, cursor)).pipe( const read = Effect.suspend(() => readAfter(input.aggregateID, sequence)).pipe(
Effect.tap((events) => Effect.tap((events) =>
Effect.sync(() => { Effect.sync(() => {
cursor = events.at(-1)?.cursor ?? cursor sequence = events.at(-1)?.durable?.seq ?? sequence
}), }),
), ),
) )
const historical = yield* read const historical = yield* read
const live = Stream.fromSubscription(synchronized).pipe( const live = Stream.fromSubscription(wakes).pipe(
Stream.mapEffect(() => read), Stream.mapEffect(() => read),
Stream.flattenIterable, Stream.flattenIterable,
) )
@@ -627,7 +609,7 @@ export const layerWith = (options?: LayerOptions) =>
}), }),
) )
const listen = (listener: Listener): Effect.Effect<Unsubscribe> => const listen = (listener: Subscriber): Effect.Effect<Unsubscribe> =>
Effect.sync(() => { Effect.sync(() => {
listeners.push(listener) listeners.push(listener)
return Effect.sync(() => { return Effect.sync(() => {
@@ -636,21 +618,7 @@ export const layerWith = (options?: LayerOptions) =>
}) })
}) })
const sync = (handler: Sync): Effect.Effect<Unsubscribe> => const project = <D extends Definition>(definition: D, projector: Subscriber<D>): Effect.Effect<void> =>
Effect.sync(() => {
syncHandlers.push(handler)
return Effect.sync(() => {
const index = syncHandlers.indexOf(handler)
if (index >= 0) syncHandlers.splice(index, 1)
})
})
const beforeCommit = (guard: CommitGuard): Effect.Effect<void> =>
Effect.sync(() => {
commitGuards.push(guard)
})
const project = <D extends Definition>(definition: D, projector: Projector<D>): Effect.Effect<void> =>
Effect.sync(() => { Effect.sync(() => {
const list = projectors.get(definition.type) ?? [] const list = projectors.get(definition.type) ?? []
list.push((event) => projector(event as Payload<D>)) list.push((event) => projector(event as Payload<D>))
@@ -661,10 +629,8 @@ export const layerWith = (options?: LayerOptions) =>
publish, publish,
subscribe, subscribe,
all: streamAll, all: streamAll,
aggregateEvents: streamEvents, durable,
sync,
listen, listen,
beforeCommit,
project, project,
replay, replay,
replayAll, replayAll,
+1 -1
View File
@@ -123,6 +123,6 @@ const baseLayer = Layer.effect(
}), }),
) )
export const layer = baseLayer.pipe(Layer.provide(FileSystemSearch.defaultLayer), Layer.provide(FSUtil.defaultLayer)) export const layer = baseLayer.pipe(Layer.provide(FileSystemSearch.locationLayer), Layer.provide(FSUtil.defaultLayer))
export const locationLayer = layer export const locationLayer = layer
+1 -1
View File
@@ -232,6 +232,6 @@ export const fffLayer = Layer.effect(
}), }),
) )
export const defaultLayer = Layer.unwrap( export const locationLayer = Layer.unwrap(
Effect.sync(() => (Flag.OPENCODE_DISABLE_FFF || !Fff.available() ? ripgrepLayer : fffLayer)), Effect.sync(() => (Flag.OPENCODE_DISABLE_FFF || !Fff.available() ? ripgrepLayer : fffLayer)),
) )
+1 -1
View File
@@ -13,7 +13,7 @@ import { filesystem } from "./effect/layer-node-platform"
export namespace FSUtil { export namespace FSUtil {
export class FileSystemError extends Schema.TaggedErrorClass<FileSystemError>()("FileSystemError", { export class FileSystemError extends Schema.TaggedErrorClass<FileSystemError>()("FileSystemError", {
method: Schema.String, method: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export type Error = PlatformError | FileSystemError export type Error = PlatformError | FileSystemError
+2 -2
View File
@@ -32,14 +32,14 @@ export class WorktreeError extends Schema.TaggedErrorClass<WorktreeError>()("Git
message: Schema.String, message: Schema.String,
directory: Schema.optional(AbsolutePath), directory: Schema.optional(AbsolutePath),
forceRequired: Schema.optional(Schema.Boolean), forceRequired: Schema.optional(Schema.Boolean),
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export class PatchError extends Schema.TaggedErrorClass<PatchError>()("Git.PatchError", { export class PatchError extends Schema.TaggedErrorClass<PatchError>()("Git.PatchError", {
operation: Schema.Literals(["capture", "apply", "reset"]), operation: Schema.Literals(["capture", "apply", "reset"]),
directory: AbsolutePath, directory: AbsolutePath,
message: Schema.String, message: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export interface Interface { export interface Interface {
+65 -77
View File
@@ -1,7 +1,19 @@
export * as Integration from "./integration" export * as Integration from "./integration"
import { Cause, Clock, Context, Duration, Effect, Exit, Layer, Schedule, Schema, Scope, SynchronizedRef } from "effect" import {
import { castDraft, enableMapSet, type Draft } from "immer" Cause,
Clock,
Context,
Duration,
Effect,
Exit,
Layer,
Schedule,
Schema,
Scope,
SynchronizedRef,
Types,
} from "effect"
import { Credential } from "./credential" import { Credential } from "./credential"
import { IntegrationSchema } from "./integration/schema" import { IntegrationSchema } from "./integration/schema"
import { withStatics } from "./schema" import { withStatics } from "./schema"
@@ -42,13 +54,15 @@ export const SelectPrompt = Schema.Struct({
type: Schema.Literal("select"), type: Schema.Literal("select"),
key: Schema.String, key: Schema.String,
message: Schema.String, message: Schema.String,
options: Schema.Array( options: Schema.mutable(
Schema.Array(
Schema.Struct({ Schema.Struct({
label: Schema.String, label: Schema.String,
value: Schema.String, value: Schema.String,
hint: Schema.optional(Schema.String), hint: Schema.optional(Schema.String),
}), }),
), ),
),
when: Schema.optional(When), when: Schema.optional(When),
}).annotate({ identifier: "Integration.SelectPrompt" }) }).annotate({ identifier: "Integration.SelectPrompt" })
export type SelectPrompt = typeof SelectPrompt.Type export type SelectPrompt = typeof SelectPrompt.Type
@@ -60,7 +74,7 @@ export const OAuthMethod = Schema.Struct({
id: MethodID, id: MethodID,
type: Schema.Literal("oauth"), type: Schema.Literal("oauth"),
label: Schema.String, label: Schema.String,
prompts: Schema.optional(Schema.Array(Prompt)), prompts: Schema.optional(Schema.mutable(Schema.Array(Prompt))),
}).annotate({ identifier: "Integration.OAuthMethod" }) }).annotate({ identifier: "Integration.OAuthMethod" })
export type OAuthMethod = typeof OAuthMethod.Type export type OAuthMethod = typeof OAuthMethod.Type
@@ -72,7 +86,7 @@ export type KeyMethod = typeof KeyMethod.Type
export const EnvMethod = Schema.Struct({ export const EnvMethod = Schema.Struct({
type: Schema.Literal("env"), type: Schema.Literal("env"),
names: Schema.Array(Schema.String), names: Schema.mutable(Schema.Array(Schema.String)),
}).annotate({ identifier: "Integration.EnvMethod" }) }).annotate({ identifier: "Integration.EnvMethod" })
export type EnvMethod = typeof EnvMethod.Type export type EnvMethod = typeof EnvMethod.Type
@@ -82,8 +96,8 @@ export type Method = typeof Method.Type
export class Info extends Schema.Class<Info>("Integration.Info")({ export class Info extends Schema.Class<Info>("Integration.Info")({
id: ID, id: ID,
name: Schema.String, name: Schema.String,
methods: Schema.Array(Method), methods: Schema.mutable(Schema.Array(Method)),
connections: Schema.Array(IntegrationConnection.Info), connections: Schema.mutable(Schema.Array(IntegrationConnection.Info)),
}) {} }) {}
export type Inputs = Readonly<{ [key: string]: string }> export type Inputs = Readonly<{ [key: string]: string }>
@@ -94,11 +108,11 @@ export type OAuthAuthorization = {
} & ( } & (
| { | {
readonly mode: "auto" readonly mode: "auto"
readonly callback: Effect.Effect<Credential.Info, unknown> readonly callback: Effect.Effect<Credential.Value, unknown>
} }
| { | {
readonly mode: "code" readonly mode: "code"
readonly callback: (code: string) => Effect.Effect<Credential.Info, unknown> readonly callback: (code: string) => Effect.Effect<Credential.Value, unknown>
} }
) )
@@ -154,7 +168,7 @@ export class CodeRequiredError extends Schema.TaggedErrorClass<CodeRequiredError
}) {} }) {}
export class AuthorizationError extends Schema.TaggedErrorClass<AuthorizationError>()("Integration.Authorization", { export class AuthorizationError extends Schema.TaggedErrorClass<AuthorizationError>()("Integration.Authorization", {
cause: Schema.Defect, cause: Schema.Defect(),
}) {} }) {}
export type Error = CodeRequiredError | AuthorizationError export type Error = CodeRequiredError | AuthorizationError
@@ -172,19 +186,19 @@ export type Ref = {
} }
type Entry = { type Entry = {
ref: Ref ref: Types.DeepMutable<Ref>
methods: Method[] methods: Types.DeepMutable<Method>[]
implementations: Map<MethodID, OAuthImplementation> implementations: Map<MethodID, Types.DeepMutable<OAuthImplementation>>
} }
type Data = { type Data = {
integrations: Map<ID, Entry> integrations: Map<ID, Entry>
} }
export type Editor = { export type Draft = {
list: () => readonly Ref[] list: () => readonly Ref[]
get: (id: ID) => Ref | undefined get: (id: ID) => Ref | undefined
update: (id: ID, update: (integration: Draft<Ref>) => void) => void update: (id: ID, update: (integration: Types.DeepMutable<Ref>) => void) => void
remove: (id: ID) => void remove: (id: ID) => void
method: { method: {
list: (integrationID: ID) => readonly Method[] list: (integrationID: ID) => readonly Method[]
@@ -193,18 +207,13 @@ export type Editor = {
} }
} }
export interface Interface { export interface Interface extends State.Transformable<Draft> {
/** Registers a scoped transform over the integration registry. */ /** Registers a scoped transform over the integration registry. */
readonly transform: State.Interface<Data, Editor>["transform"]
/** Registers and immediately applies a scoped integration registry update. */
readonly update: State.Interface<Data, Editor>["update"]
/** Returns one integration with its methods and current connections. */ /** Returns one integration with its methods and current connections. */
readonly get: (id: ID) => Effect.Effect<Info | undefined> readonly get: (id: ID) => Effect.Effect<Info | undefined>
/** Returns all integrations with their methods and current connections. */ /** Returns all integrations with their methods and current connections. */
readonly list: () => Effect.Effect<Info[]> readonly list: () => Effect.Effect<Info[]>
readonly connection: { readonly connection: {
/** Returns active connections for every registered or credential-backed integration. */
readonly list: () => Effect.Effect<Map<ID, IntegrationConnection.Info>>
/** Returns the active connection for one integration. */ /** Returns the active connection for one integration. */
readonly forIntegration: (id: ID) => Effect.Effect<IntegrationConnection.Info | undefined> readonly forIntegration: (id: ID) => Effect.Effect<IntegrationConnection.Info | undefined>
/** Runs a key method and stores the resulting credential. */ /** Runs a key method and stores the resulting credential. */
@@ -230,7 +239,7 @@ export interface Interface {
/** Updates a stored credential exposed as a connection. */ /** Updates a stored credential exposed as a connection. */
readonly update: ( readonly update: (
credentialID: Credential.ID, credentialID: Credential.ID,
updates: Partial<Pick<Credential.Stored, "label">>, updates: Partial<Pick<Credential.Info, "label">>,
) => Effect.Effect<void> ) => Effect.Effect<void>
/** Removes a stored credential connection. */ /** Removes a stored credential connection. */
readonly remove: (credentialID: Credential.ID) => Effect.Effect<void> readonly remove: (credentialID: Credential.ID) => Effect.Effect<void>
@@ -252,8 +261,6 @@ export interface Interface {
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Integration") {} export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Integration") {}
enableMapSet()
const attemptLifetime = Duration.toMillis(Duration.minutes(10)) const attemptLifetime = Duration.toMillis(Duration.minutes(10))
const terminalRetention = Duration.toMillis(Duration.minutes(1)) const terminalRetention = Duration.toMillis(Duration.minutes(1))
const scrubInterval = Duration.seconds(30) const scrubInterval = Duration.seconds(30)
@@ -284,15 +291,17 @@ export const locationLayer = Layer.effect(
const events = yield* EventV2.Service const events = yield* EventV2.Service
const scope = yield* Scope.Scope const scope = yield* Scope.Scope
const attempts = SynchronizedRef.makeUnsafe(new Map<AttemptID, AttemptEntry>()) const attempts = SynchronizedRef.makeUnsafe(new Map<AttemptID, AttemptEntry>())
const state = State.create<Data, Editor>({ const state = State.create<Data, Draft>({
initial: () => ({ integrations: new Map<ID, Entry>() }), initial: () => ({ integrations: new Map<ID, Entry>() }),
editor: (draft) => ({ draft: (draft) => ({
list: () => Array.from(draft.integrations.values(), (entry) => entry.ref) as Ref[], list: () => Array.from(draft.integrations.values(), (entry) => entry.ref) as Ref[],
get: (id) => draft.integrations.get(id)?.ref as Ref | undefined, get: (id) => draft.integrations.get(id)?.ref as Ref | undefined,
update: (id, update) => { update: (id, update) => {
const current = const current = draft.integrations.get(id) ?? {
draft.integrations.get(id) ?? ref: { id, name: id },
castDraft({ ref: { id, name: id } as Ref, methods: [], implementations: new Map() }) methods: [],
implementations: new Map(),
}
if (!draft.integrations.has(id)) draft.integrations.set(id, current) if (!draft.integrations.has(id)) draft.integrations.set(id, current)
update(current.ref) update(current.ref)
current.ref.id = id current.ref.id = id
@@ -301,16 +310,14 @@ export const locationLayer = Layer.effect(
method: { method: {
list: (integrationID) => (draft.integrations.get(integrationID)?.methods as Method[] | undefined) ?? [], list: (integrationID) => (draft.integrations.get(integrationID)?.methods as Method[] | undefined) ?? [],
update: (implementation) => { update: (implementation) => {
const current = const current = draft.integrations.get(implementation.integrationID) ?? {
draft.integrations.get(implementation.integrationID) ??
castDraft({
ref: { ref: {
id: implementation.integrationID, id: implementation.integrationID,
name: implementation.integrationID, name: implementation.integrationID,
} as Ref, },
methods: [], methods: [],
implementations: new Map<MethodID, OAuthImplementation>(), implementations: new Map<MethodID, Types.DeepMutable<OAuthImplementation>>(),
}) }
if (!draft.integrations.has(implementation.integrationID)) { if (!draft.integrations.has(implementation.integrationID)) {
draft.integrations.set(implementation.integrationID, current) draft.integrations.set(implementation.integrationID, current)
} }
@@ -319,10 +326,13 @@ export const locationLayer = Layer.effect(
if (method.type !== "oauth" || implementation.method.type !== "oauth") return true if (method.type !== "oauth" || implementation.method.type !== "oauth") return true
return method.id === implementation.method.id return method.id === implementation.method.id
}) })
if (index === -1) current.methods.push(castDraft(implementation.method)) if (index === -1) current.methods.push(implementation.method as Types.DeepMutable<Method>)
else current.methods[index] = castDraft(implementation.method) else current.methods[index] = implementation.method as Types.DeepMutable<Method>
if (isOAuthImplementation(implementation)) { if (implementation.method.type === "oauth") {
current.implementations.set(implementation.method.id, castDraft(implementation)) current.implementations.set(
implementation.method.id,
implementation as Types.DeepMutable<OAuthImplementation>,
)
} }
}, },
remove: (integrationID, method) => { remove: (integrationID, method) => {
@@ -341,39 +351,27 @@ export const locationLayer = Layer.effect(
finalize: () => events.publish(Event.Updated, {}).pipe(Effect.asVoid), finalize: () => events.publish(Event.Updated, {}).pipe(Effect.asVoid),
}) })
const connections = (entry: Entry, saved: readonly Credential.Stored[]): IntegrationConnection.Info[] => { const resolveConnections = (entry: Entry | undefined, saved: readonly Credential.Info[]) => {
const connected = saved.map((credential) => ({ const credentials = saved
.map((credential) => ({
type: "credential" as const, type: "credential" as const,
id: credential.id, id: credential.id,
label: credential.label, label: credential.label,
})) }))
const detected = entry.methods .toReversed()
const env = (entry?.methods ?? [])
.filter((method) => method.type === "env") .filter((method) => method.type === "env")
.flatMap((method) => method.names.filter((name) => process.env[name])) .flatMap((method) => method.names.filter((name) => process.env[name]))
.map((name) => ({ type: "env" as const, name })) .map((name) => ({ type: "env" as const, name }))
return [...connected, ...detected] return [...credentials, ...env]
} }
const activeConnection = ( const project = (entry: Entry, connections: IntegrationConnection.Info[]) =>
entry: Entry | undefined,
saved: readonly Credential.Stored[],
): IntegrationConnection.Info | undefined => {
const credential = saved.at(-1)
if (credential) return { type: "credential", id: credential.id, label: credential.label }
if (!entry) return
const name = entry.methods
.filter((method) => method.type === "env")
.flatMap((method) => method.names)
.find((name) => process.env[name])
if (name) return { type: "env", name }
}
const project = (entry: Entry, saved: readonly Credential.Stored[]) =>
new Info({ new Info({
id: entry.ref.id, id: entry.ref.id,
name: entry.ref.name, name: entry.ref.name,
methods: entry.methods, methods: entry.methods,
connections: connections(entry, saved), connections,
}) })
const authorize = <A, E, R>(effect: Effect.Effect<A, E, R>) => const authorize = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
@@ -387,7 +385,7 @@ export const locationLayer = Layer.effect(
return error instanceof Error ? error.message : String(error) return error instanceof Error ? error.message : String(error)
} }
const settle = Effect.fnUntraced(function* (attemptID: AttemptID, exit: Exit.Exit<Credential.Info, unknown>) { const settle = Effect.fnUntraced(function* (attemptID: AttemptID, exit: Exit.Exit<Credential.Value, unknown>) {
const now = yield* Clock.currentTimeMillis const now = yield* Clock.currentTimeMillis
const result = yield* SynchronizedRef.modify(attempts, (current) => { const result = yield* SynchronizedRef.modify(attempts, (current) => {
const attempt = current.get(attemptID) const attempt = current.get(attemptID)
@@ -434,32 +432,22 @@ export const locationLayer = Layer.effect(
return Service.of({ return Service.of({
transform: state.transform, transform: state.transform,
update: state.update, reload: state.reload,
get: Effect.fn("Integration.get")(function* (id) { get: Effect.fn("Integration.get")(function* (id) {
const entry = state.get().integrations.get(id) const entry = state.get().integrations.get(id)
if (!entry) return undefined if (!entry) return undefined
return project(entry, yield* credentials.list(id)) return project(entry, resolveConnections(entry, yield* credentials.list(id)))
}), }),
list: Effect.fn("Integration.list")(function* () { list: Effect.fn("Integration.list")(function* () {
return (yield* Effect.forEach(state.get().integrations.values(), (entry) => const saved = Map.groupBy(yield* credentials.all(), (credential) => credential.integrationID)
Effect.gen(function* () { return Array.from(state.get().integrations.values(), (entry) =>
return project(entry, yield* credentials.list(entry.ref.id)) project(entry, resolveConnections(entry, saved.get(entry.ref.id) ?? [])),
}), ).toSorted((a, b) => a.name.localeCompare(b.name))
)).toSorted((a, b) => a.name.localeCompare(b.name))
}), }),
connection: { connection: {
list: Effect.fn("Integration.connection.list")(function* () {
const saved = Map.groupBy(yield* credentials.all(), (credential) => credential.integrationID)
return new Map(
new Set([...state.get().integrations.keys(), ...saved.keys()]).values().flatMap((id) => {
const connection = activeConnection(state.get().integrations.get(id), saved.get(id) ?? [])
return connection ? [[id, connection] as const] : []
}),
)
}),
forIntegration: Effect.fn("Integration.connection.forIntegration")(function* (id) { forIntegration: Effect.fn("Integration.connection.forIntegration")(function* (id) {
const entry = state.get().integrations.get(id) const entry = state.get().integrations.get(id)
return activeConnection(entry, yield* credentials.list(id)) return resolveConnections(entry, yield* credentials.list(id))[0]
}), }),
key: Effect.fn("Integration.connection.key")(function* (input) { key: Effect.fn("Integration.connection.key")(function* (input) {
const method = state const method = state
+2 -2
View File
@@ -7,7 +7,7 @@ import { Catalog } from "./catalog"
import { Integration } from "./integration" import { Integration } from "./integration"
import { CommandV2 } from "./command" import { CommandV2 } from "./command"
import { AgentV2 } from "./agent" import { AgentV2 } from "./agent"
import { PluginBoot } from "./plugin/boot" import { PluginInternal } from "./plugin/internal"
import { Project } from "./project" import { Project } from "./project"
import { ProjectCopy } from "./project/copy" import { ProjectCopy } from "./project/copy"
import { ProjectDirectories } from "./project/directories" import { ProjectDirectories } from "./project/directories"
@@ -65,7 +65,7 @@ export class LocationServiceMap extends LayerMap.Service<LocationServiceMap>()("
Integration.locationLayer, Integration.locationLayer,
CommandV2.locationLayer, CommandV2.locationLayer,
AgentV2.locationLayer, AgentV2.locationLayer,
PluginBoot.locationLayer, PluginInternal.locationLayer,
ProjectCopy.locationLayer, ProjectCopy.locationLayer,
FileSystem.locationLayer, FileSystem.locationLayer,
Watcher.locationLayer, Watcher.locationLayer,
+1 -1
View File
@@ -33,7 +33,7 @@ export type Request = typeof Request.Type
interface MutableRequest { interface MutableRequest {
headers: Record<string, string> headers: Record<string, string>
body: Record<string, unknown> body: Record<string, unknown>
generation?: Generation generation?: Record<string, unknown>
options?: Record<string, unknown> options?: Record<string, unknown>
} }
+11 -8
View File
@@ -1,5 +1,4 @@
import { DateTime, Schema } from "effect" import { Schema, Types } from "effect"
import { DateTimeUtcFromMillis } from "effect/Schema"
import { ProviderV2 } from "./provider" import { ProviderV2 } from "./provider"
import { ModelRequest } from "./model-request" import { ModelRequest } from "./model-request"
@@ -16,8 +15,8 @@ export type Family = typeof Family.Type
export const Capabilities = Schema.Struct({ export const Capabilities = Schema.Struct({
tools: Schema.Boolean, tools: Schema.Boolean,
// mime patterns, image, audio, video/*, text/* // mime patterns, image, audio, video/*, text/*
input: Schema.String.pipe(Schema.Array), input: Schema.String.pipe(Schema.Array, Schema.mutable),
output: Schema.String.pipe(Schema.Array), output: Schema.String.pipe(Schema.Array, Schema.mutable),
}) })
export type Capabilities = typeof Capabilities.Type export type Capabilities = typeof Capabilities.Type
@@ -67,11 +66,11 @@ export class Info extends Schema.Class<Info>("ModelV2.Info")({
variants: Schema.Struct({ variants: Schema.Struct({
id: VariantID, id: VariantID,
...ModelRequest.Request.fields, ...ModelRequest.Request.fields,
}).pipe(Schema.Array), }).pipe(Schema.Array, Schema.mutable),
time: Schema.Struct({ time: Schema.Struct({
released: DateTimeUtcFromMillis, released: Schema.Finite,
}), }),
cost: Cost.pipe(Schema.Array), cost: Cost.pipe(Schema.Array, Schema.mutable),
status: Schema.Literals(["alpha", "beta", "deprecated", "active"]), status: Schema.Literals(["alpha", "beta", "deprecated", "active"]),
enabled: Schema.Boolean, enabled: Schema.Boolean,
limit: Schema.Struct({ limit: Schema.Struct({
@@ -103,7 +102,7 @@ export class Info extends Schema.Class<Info>("ModelV2.Info")({
}, },
variants: [], variants: [],
time: { time: {
released: DateTime.makeUnsafe(0), released: 0,
}, },
cost: [], cost: [],
status: "active", status: "active",
@@ -116,6 +115,10 @@ export class Info extends Schema.Class<Info>("ModelV2.Info")({
} }
} }
export type MutableInfo = Omit<Types.DeepMutable<Info>, "api"> & {
api: ProviderV2.MutableApi<Api>
}
export function parse(input: string): { providerID: ProviderV2.ID; modelID: ID } { export function parse(input: string): { providerID: ProviderV2.ID; modelID: ID } {
const [providerID, ...modelID] = input.split("/") const [providerID, ...modelID] = input.split("/")
return { return {
+12 -16
View File
@@ -15,12 +15,12 @@ import { NpmConfig } from "./npm-config"
export class InstallFailedError extends Schema.TaggedErrorClass<InstallFailedError>()("NpmInstallFailedError", { export class InstallFailedError extends Schema.TaggedErrorClass<InstallFailedError>()("NpmInstallFailedError", {
add: Schema.Array(Schema.String).pipe(Schema.optional), add: Schema.Array(Schema.String).pipe(Schema.optional),
dir: Schema.String, dir: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export interface EntryPoint { export interface EntryPoint {
readonly directory: string readonly directory: string
readonly entrypoint: Option.Option<string> readonly entrypoint?: string
} }
export interface Interface { export interface Interface {
@@ -34,7 +34,7 @@ export interface Interface {
}[] }[]
}, },
) => Effect.Effect<void, EffectFlock.LockError | InstallFailedError> ) => Effect.Effect<void, EffectFlock.LockError | InstallFailedError>
readonly which: (pkg: string, bin?: string) => Effect.Effect<Option.Option<string>> readonly which: (pkg: string, bin?: string) => Effect.Effect<string | undefined>
} }
export class Service extends Context.Service<Service, Interface>()("@opencode/Npm") {} export class Service extends Context.Service<Service, Interface>()("@opencode/Npm") {}
@@ -47,12 +47,11 @@ export function sanitize(pkg: string) {
} }
const resolveEntryPoint = (name: string, dir: string): EntryPoint => { const resolveEntryPoint = (name: string, dir: string): EntryPoint => {
let entrypoint: Option.Option<string> let entrypoint: string | undefined
try { try {
const resolved = typeof Bun !== "undefined" ? import.meta.resolve(name, dir) : import.meta.resolve(dir) entrypoint = typeof Bun !== "undefined" ? import.meta.resolve(name, dir) : import.meta.resolve(dir)
entrypoint = Option.some(resolved)
} catch { } catch {
entrypoint = Option.none() entrypoint = undefined
} }
return { return {
directory: dir, directory: dir,
@@ -130,7 +129,7 @@ export const layer = Layer.effect(
const first = tree.edgesOut.values().next().value?.to const first = tree.edgesOut.values().next().value?.to
if (!first) { if (!first) {
const result = resolveEntryPoint(name, path.join(dir, "node_modules", name)) const result = resolveEntryPoint(name, path.join(dir, "node_modules", name))
if (Option.isSome(result.entrypoint)) return result if (result.entrypoint) return result
return yield* new InstallFailedError({ add: [pkg], dir }) return yield* new InstallFailedError({ add: [pkg], dir })
} }
return resolveEntryPoint(first.name, first.path) return resolveEntryPoint(first.name, first.path)
@@ -219,7 +218,8 @@ export const layer = Layer.effect(
return Option.some(files[0]) return Option.some(files[0])
}) })
return yield* Effect.gen(function* () { return Option.getOrUndefined(
yield* Effect.gen(function* () {
const bin = yield* pick() const bin = yield* pick()
if (Option.isSome(bin)) { if (Option.isSome(bin)) {
return Option.some(path.join(binDir, bin.value)) return Option.some(path.join(binDir, bin.value))
@@ -235,6 +235,7 @@ export const layer = Layer.effect(
}).pipe( }).pipe(
Effect.scoped, Effect.scoped,
Effect.orElseSucceed(() => Option.none<string>()), Effect.orElseSucceed(() => Option.none<string>()),
),
) )
}) })
@@ -261,14 +262,9 @@ export async function install(...args: Parameters<Interface["install"]>) {
} }
export async function add(...args: Parameters<Interface["add"]>) { export async function add(...args: Parameters<Interface["add"]>) {
const entry = await runPromise((svc) => svc.add(...args)) return runPromise((svc) => svc.add(...args))
return {
directory: entry.directory,
entrypoint: Option.getOrUndefined(entry.entrypoint),
}
} }
export async function which(...args: Parameters<Interface["which"]>) { export async function which(...args: Parameters<Interface["which"]>) {
const resolved = await runPromise((svc) => svc.which(...args)) return runPromise((svc) => svc.which(...args))
return Option.getOrUndefined(resolved)
} }
+1 -1
View File
@@ -12,5 +12,5 @@ export const Rule = Schema.Struct({
}).annotate({ identifier: "PermissionV2.Rule" }) }).annotate({ identifier: "PermissionV2.Rule" })
export type Rule = typeof Rule.Type export type Rule = typeof Rule.Type
export const Ruleset = Schema.Array(Rule).annotate({ identifier: "PermissionV2.Ruleset" }) export const Ruleset = Schema.mutable(Schema.Array(Rule)).annotate({ identifier: "PermissionV2.Ruleset" })
export type Ruleset = typeof Ruleset.Type export type Ruleset = typeof Ruleset.Type
+73 -147
View File
@@ -1,12 +1,18 @@
export * as PluginV2 from "./plugin" export * as PluginV2 from "./plugin"
import { createDraft, finishDraft, type Draft } from "immer"
import type { LanguageModelV3 } from "@ai-sdk/provider"
import { Context, Effect, Exit, Layer, Schema, Scope } from "effect" import { Context, Effect, Exit, Layer, Schema, Scope } from "effect"
import type { ModelV2 } from "./model" import type { Plugin } from "@opencode-ai/plugin/v2/effect"
import type { Catalog } from "./catalog" import { AgentV2 } from "./agent"
import { AISDK } from "./aisdk"
import { Catalog } from "./catalog"
import { CommandV2 } from "./command"
import { EventV2 } from "./event" import { EventV2 } from "./event"
import { Integration } from "./integration"
import { KeyedMutex } from "./effect/keyed-mutex" import { KeyedMutex } from "./effect/keyed-mutex"
import { PluginHost } from "./plugin/host"
import { Reference } from "./reference"
import { SkillV2 } from "./skill"
import { State } from "./state"
export const ID = Schema.String.pipe(Schema.brand("Plugin.ID")) export const ID = Schema.String.pipe(Schema.brand("Plugin.ID"))
export type ID = typeof ID.Type export type ID = typeof ID.Type
@@ -20,71 +26,9 @@ export const Event = {
}), }),
} }
type HookSpec = {
"catalog.transform": {
input: Catalog.Editor
output: {}
}
"aisdk.language": {
input: {
model: ModelV2.Info
sdk: any
options: Record<string, any>
}
output: {
language?: LanguageModelV3
}
}
"aisdk.sdk": {
input: {
model: ModelV2.Info
package: string
options: Record<string, any>
}
output: {
sdk?: any
}
}
}
export type Hooks = {
[Name in keyof HookSpec]: Readonly<HookSpec[Name]["input"]> & {
-readonly [Field in keyof HookSpec[Name]["output"]]: HookSpec[Name]["output"][Field] extends object
? Draft<HookSpec[Name]["output"][Field]>
: HookSpec[Name]["output"][Field]
}
}
export type HookFunctions = {
[key in keyof Hooks]?: (input: Hooks[key]) => Effect.Effect<void>
}
export type HookInput<Name extends keyof Hooks> = HookSpec[Name]["input"]
export type HookOutput<Name extends keyof Hooks> = HookSpec[Name]["output"]
export type Effect<R = never> = Effect.Effect<HookFunctions | void, never, R | Scope.Scope>
export function define<R>(input: { id: ID; effect: Effect.Effect<HookFunctions | void, never, R> }) {
return input
}
export interface Interface { export interface Interface {
readonly add: (input: { readonly add: (id: ID, effect: Plugin["effect"]) => Effect.Effect<void>
id: ID
effect: Effect.Effect<void | HookFunctions, never, Scope.Scope>
}) => Effect.Effect<void, never, never>
readonly remove: (id: ID) => Effect.Effect<void> readonly remove: (id: ID) => Effect.Effect<void>
readonly triggerFor: <Name extends keyof Hooks>(
id: ID,
name: Name,
input: HookInput<Name>,
output: HookOutput<Name>,
) => Effect.Effect<HookInput<Name> & HookOutput<Name>>
readonly trigger: <Name extends keyof Hooks>(
name: Name,
input: HookInput<Name>,
output: HookOutput<Name>,
) => Effect.Effect<HookInput<Name> & HookOutput<Name>>
} }
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Plugin") {} export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Plugin") {}
@@ -92,95 +36,77 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/v2
export const layer = Layer.effect( export const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
let hooks: {
id: ID
hooks: HookFunctions
scope: Scope.Closeable
}[] = []
const events = yield* EventV2.Service const events = yield* EventV2.Service
const scope = yield* Scope.Scope
const locks = KeyedMutex.makeUnsafe<ID>() const locks = KeyedMutex.makeUnsafe<ID>()
const scope = yield* Scope.make()
const active = new Map<ID, Scope.Closeable>()
const loading = new Set<ID>()
let host: Parameters<Plugin["effect"]>[0]
const svc = Service.of({ const add = Effect.fn("Plugin.add")(function* (id: ID, effect: Plugin["effect"]) {
add: Effect.fn("Plugin.add")(function* (input) { if (loading.has(id)) return yield* Effect.die(`Plugin load cycle detected for ${id}`)
yield* locks.withLock(input.id)(
Effect.gen(function* () {
const existing = hooks.find((item) => item.id === input.id)
if (existing) yield* Scope.close(existing.scope, Exit.void).pipe(Effect.ignore)
const childScope = yield* Scope.fork(scope)
const result = yield* input.effect.pipe(
Scope.provide(childScope),
Effect.withSpan("Plugin.load", {
attributes: {
"plugin.id": input.id,
},
}),
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(childScope, exit) : Effect.void)),
)
hooks = [
...hooks.filter((item) => item.id !== input.id),
{
id: input.id,
hooks: result ?? {},
scope: childScope,
},
]
yield* events.publish(Event.Added, { id: input.id })
}),
)
}),
trigger: Effect.fn("Plugin.trigger")(function* (name, input, output) {
return yield* svc.triggerFor(ID.make("*"), name, input, output)
}),
triggerFor: Effect.fn("Plugin.triggerFor")(function* (id, name, input, output) {
const draftEntries = new Map<string, ReturnType<typeof createDraft>>()
const event = {
...input,
...output,
} as Record<string, unknown>
for (const [field, value] of Object.entries(output)) {
if (value && typeof value === "object") {
draftEntries.set(field, createDraft(value))
event[field] = draftEntries.get(field)
}
}
for (const item of hooks) {
if (id !== ID.make("*") && item.id !== id) continue
const match = item.hooks[name]
if (!match) continue
yield* match(event as any).pipe(
Effect.withSpan(`Plugin.hook.${name}`, {
attributes: {
plugin: item.id,
hook: name,
},
}),
)
}
for (const [field, draft] of draftEntries) {
event[field] = finishDraft(draft)
}
return event as any
}),
remove: Effect.fn("Plugin.remove")(function* (id) {
yield* locks.withLock(id)( yield* locks.withLock(id)(
Effect.sync(() => loading.add(id)).pipe(
Effect.andThen(
State.batch(
Effect.gen(function* () { Effect.gen(function* () {
const existing = hooks.find((item) => item.id === id) const existing = active.get(id)
hooks = hooks.filter((item) => item.id !== id) active.delete(id)
if (existing) yield* Scope.close(existing.scope, Exit.void).pipe(Effect.ignore) if (existing) yield* Scope.close(existing, Exit.void).pipe(Effect.ignore)
const child = yield* Scope.fork(scope)
yield* effect(host).pipe(
Scope.provide(child),
Effect.withSpan("Plugin.load", { attributes: { "plugin.id": id } }),
Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(child, exit) : Effect.void)),
)
active.set(id, child)
yield* events.publish(Event.Added, { id })
}),
),
),
Effect.ensuring(Effect.sync(() => loading.delete(id))),
),
)
})
const remove = Effect.fn("Plugin.remove")(function* (id: ID) {
if (loading.has(id)) return yield* Effect.die(`Cannot remove plugin ${id} while it is loading`)
yield* locks.withLock(id)(
State.batch(
Effect.gen(function* () {
const current = active.get(id)
active.delete(id)
if (current) yield* Scope.close(current, Exit.void).pipe(Effect.ignore)
}),
),
)
})
yield* Effect.addFinalizer((exit) =>
Effect.gen(function* () {
active.clear()
yield* State.batch(Scope.close(scope, exit))
}), }),
) )
}),
const service = Service.of({
add,
remove,
}) })
return svc host = yield* PluginHost.make(service)
return service
}), }),
) )
export const locationLayer = layer export const locationLayer = layer.pipe(
Layer.provideMerge(AgentV2.locationLayer),
// opencode Layer.provideMerge(AISDK.locationLayer),
// sdcok Layer.provideMerge(Catalog.locationLayer),
Layer.provideMerge(CommandV2.locationLayer),
Layer.provideMerge(Integration.locationLayer),
Layer.provideMerge(Reference.locationLayer),
Layer.provideMerge(SkillV2.locationLayer),
)
+12 -13
View File
@@ -1,12 +1,12 @@
export * as AgentPlugin from "./agent" export * as AgentPlugin from "./agent"
import path from "path" import path from "path"
import { define } from "./internal"
import { Effect } from "effect" import { Effect } from "effect"
import { AgentV2 } from "../agent" import { AgentV2 } from "../agent"
import { Global } from "../global" import { Global } from "../global"
import { Location } from "../location" import { Location } from "../location"
import { PermissionV2 } from "../permission" import { PermissionV2 } from "../permission"
import { PluginV2 } from "../plugin"
const TRUNCATION_GLOB = path.join(Global.Path.data, "tool-output", "*") const TRUNCATION_GLOB = path.join(Global.Path.data, "tool-output", "*")
const BUILD_SYSTEM = const BUILD_SYSTEM =
@@ -97,10 +97,9 @@ Rules:
- If the conversation ends with an unanswered question to the user, preserve that exact question - If the conversation ends with an unanswered question to the user, preserve that exact question
- If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary` - If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary`
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("agent"), id: "agent",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const agent = yield* AgentV2.Service
const location = yield* Location.Service const location = yield* Location.Service
const worktree = location.directory const worktree = location.directory
const whitelistedDirs = [TRUNCATION_GLOB, path.join(Global.Path.tmp, "*")] const whitelistedDirs = [TRUNCATION_GLOB, path.join(Global.Path.tmp, "*")]
@@ -122,8 +121,8 @@ export const Plugin = PluginV2.define({
{ action: "read", resource: "*.env.example", effect: "allow" }, { action: "read", resource: "*.env.example", effect: "allow" },
] ]
yield* agent.update((editor) => { yield* ctx.agent.transform((draft) => {
editor.update(AgentV2.defaultID, (item) => { draft.update(AgentV2.defaultID, (item) => {
item.description = "The default agent. Executes tools based on configured permissions." item.description = "The default agent. Executes tools based on configured permissions."
item.system ??= BUILD_SYSTEM item.system ??= BUILD_SYSTEM
item.mode = "primary" item.mode = "primary"
@@ -135,7 +134,7 @@ export const Plugin = PluginV2.define({
) )
}) })
editor.update(AgentV2.ID.make("plan"), (item) => { draft.update(AgentV2.ID.make("plan"), (item) => {
item.description = "Plan mode. Disallows all edit tools." item.description = "Plan mode. Disallows all edit tools."
item.mode = "primary" item.mode = "primary"
item.permissions.push( item.permissions.push(
@@ -154,14 +153,14 @@ export const Plugin = PluginV2.define({
) )
}) })
editor.update(AgentV2.ID.make("general"), (item) => { draft.update(AgentV2.ID.make("general"), (item) => {
item.description = 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." "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.mode = "subagent"
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "todowrite", resource: "*", effect: "deny" }])) item.permissions.push(...PermissionV2.merge(defaults, [{ action: "todowrite", resource: "*", effect: "deny" }]))
}) })
editor.update(AgentV2.ID.make("explore"), (item) => { draft.update(AgentV2.ID.make("explore"), (item) => {
item.description = item.description =
'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.' 'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.'
item.system = PROMPT_EXPLORE item.system = PROMPT_EXPLORE
@@ -182,21 +181,21 @@ export const Plugin = PluginV2.define({
) )
}) })
editor.update(AgentV2.ID.make("compaction"), (item) => { draft.update(AgentV2.ID.make("compaction"), (item) => {
item.mode = "primary" item.mode = "primary"
item.hidden = true item.hidden = true
item.system = PROMPT_COMPACTION item.system = PROMPT_COMPACTION
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }])) item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }]))
}) })
editor.update(AgentV2.ID.make("title"), (item) => { draft.update(AgentV2.ID.make("title"), (item) => {
item.mode = "primary" item.mode = "primary"
item.hidden = true item.hidden = true
item.system = PROMPT_TITLE item.system = PROMPT_TITLE
item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }])) item.permissions.push(...PermissionV2.merge(defaults, [{ action: "*", resource: "*", effect: "deny" }]))
}) })
editor.update(AgentV2.ID.make("summary"), (item) => { draft.update(AgentV2.ID.make("summary"), (item) => {
item.mode = "primary" item.mode = "primary"
item.hidden = true item.hidden = true
item.system = PROMPT_SUMMARY item.system = PROMPT_SUMMARY
-135
View File
@@ -1,135 +0,0 @@
export * as PluginBoot from "./boot"
import { Context, Deferred, Effect, Layer } from "effect"
import { Credential } from "../credential"
import { Integration } from "../integration"
import { AgentV2 } from "../agent"
import { Catalog } from "../catalog"
import { CommandV2 } from "../command"
import { Config } from "../config"
import { ConfigAgentPlugin } from "../config/plugin/agent"
import { ConfigCommandPlugin } from "../config/plugin/command"
import { ConfigSkillPlugin } from "../config/plugin/skill"
import { ConfigReferencePlugin } from "../config/plugin/reference"
import { EventV2 } from "../event"
import { FSUtil } from "../fs-util"
import { Global } from "../global"
import { Location } from "../location"
import { ModelsDev } from "../models-dev"
import { Npm } from "../npm"
import { PluginV2 } from "../plugin"
import { AgentPlugin } from "./agent"
import { CommandPlugin } from "./command"
import { SkillPlugin } from "./skill"
import { ConfigProviderPlugin } from "../config/plugin/provider"
import { ModelsDevPlugin } from "./models-dev"
import { ProviderPlugins } from "./provider"
import { SkillV2 } from "../skill"
import { Reference } from "../reference"
type Plugin = {
id: PluginV2.ID
effect: PluginV2.Effect<
| Catalog.Service
| CommandV2.Service
| Credential.Service
| Integration.Service
| AgentV2.Service
| Npm.Service
| EventV2.Service
| FSUtil.Service
| Global.Service
| Location.Service
| PluginV2.Service
| Config.Service
| ModelsDev.Service
| SkillV2.Service
| Reference.Service
>
}
export interface Interface {
readonly wait: () => Effect.Effect<void>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/v2/PluginBoot") {}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const commands = yield* CommandV2.Service
const plugin = yield* PluginV2.Service
const credentials = yield* Credential.Service
const integrations = yield* Integration.Service
const agents = yield* AgentV2.Service
const config = yield* Config.Service
const location = yield* Location.Service
const modelsDev = yield* ModelsDev.Service
const npm = yield* Npm.Service
const events = yield* EventV2.Service
const fs = yield* FSUtil.Service
const global = yield* Global.Service
const skill = yield* SkillV2.Service
const references = yield* Reference.Service
const done = yield* Deferred.make<void>()
const add = Effect.fn("PluginBoot.add")(function* (input: Plugin) {
yield* plugin.add({
id: input.id,
effect: input.effect.pipe(
Effect.provideService(Catalog.Service, catalog),
Effect.provideService(CommandV2.Service, commands),
Effect.provideService(Credential.Service, credentials),
Effect.provideService(Integration.Service, integrations),
Effect.provideService(AgentV2.Service, agents),
Effect.provideService(Config.Service, config),
Effect.provideService(Location.Service, location),
Effect.provideService(ModelsDev.Service, modelsDev),
Effect.provideService(Npm.Service, npm),
Effect.provideService(EventV2.Service, events),
Effect.provideService(FSUtil.Service, fs),
Effect.provideService(Global.Service, global),
Effect.provideService(SkillV2.Service, skill),
Effect.provideService(Reference.Service, references),
Effect.provideService(PluginV2.Service, plugin),
),
})
})
const boot = Effect.gen(function* () {
yield* add(AgentPlugin.Plugin)
yield* add(CommandPlugin.Plugin)
yield* add(SkillPlugin.Plugin)
for (const item of ProviderPlugins) {
yield* add(item)
}
yield* add(ModelsDevPlugin)
yield* add(ConfigProviderPlugin.Plugin)
yield* add(ConfigAgentPlugin.Plugin)
yield* add(ConfigCommandPlugin.Plugin)
yield* add(ConfigSkillPlugin.Plugin)
yield* add(ConfigReferencePlugin.Plugin)
}).pipe(Effect.withSpan("PluginBoot.boot"))
yield* boot.pipe(
Effect.exit,
Effect.flatMap((exit) => Deferred.done(done, exit)),
Effect.forkScoped,
)
return Service.of({
wait: () => Deferred.await(done),
})
}),
)
export const locationLayer = layer.pipe(
Layer.provideMerge(Integration.locationLayer),
Layer.provideMerge(Catalog.locationLayer),
Layer.provideMerge(CommandV2.locationLayer),
Layer.provideMerge(Config.locationLayer),
Layer.provideMerge(AgentV2.locationLayer),
Layer.provideMerge(SkillV2.locationLayer),
Layer.provideMerge(Reference.locationLayer),
)
+7 -11
View File
@@ -1,25 +1,21 @@
export * as CommandPlugin from "./command" export * as CommandPlugin from "./command"
import { define } from "./internal"
import { Effect } from "effect" import { Effect } from "effect"
import { CommandV2 } from "../command"
import { Location } from "../location" import { Location } from "../location"
import { PluginV2 } from "../plugin"
import PROMPT_INITIALIZE from "./command/initialize.txt" import PROMPT_INITIALIZE from "./command/initialize.txt"
import PROMPT_REVIEW from "./command/review.txt" import PROMPT_REVIEW from "./command/review.txt"
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("command"), id: "command",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const command = yield* CommandV2.Service
const location = yield* Location.Service const location = yield* Location.Service
const transform = yield* command.transform() yield* ctx.command.transform((draft) => {
draft.update("init", (command) => {
yield* transform((editor) => {
editor.update("init", (command) => {
command.template = PROMPT_INITIALIZE.replace("${path}", location.project.directory) command.template = PROMPT_INITIALIZE.replace("${path}", location.project.directory)
command.description = "guided AGENTS.md setup" command.description = "guided AGENTS.md setup"
}) })
editor.update("review", (command) => { draft.update("review", (command) => {
command.template = PROMPT_REVIEW.replace("${path}", location.project.directory) command.template = PROMPT_REVIEW.replace("${path}", location.project.directory)
command.description = "review changes [commit|branch|pr], defaults to uncommitted" command.description = "review changes [commit|branch|pr], defaults to uncommitted"
command.subtask = true command.subtask = true
+154
View File
@@ -0,0 +1,154 @@
export * as PluginHost from "./host"
import type { PluginContext as Interface } from "@opencode-ai/plugin/v2/effect"
import { Effect, Schema } from "effect"
import { AgentV2 } from "../agent"
import { AISDK } from "../aisdk"
import { Catalog } from "../catalog"
import { CommandV2 } from "../command"
import { Integration } from "../integration"
import { ModelV2 } from "../model"
import { PluginV2 } from "../plugin"
import { ProviderV2 } from "../provider"
import { Reference } from "../reference"
import { SkillV2 } from "../skill"
export const make = Effect.fn("PluginHost.make")(function* (plugin: PluginV2.Interface) {
const agents = yield* AgentV2.Service
const aisdk = yield* AISDK.Service
const catalog = yield* Catalog.Service
const commands = yield* CommandV2.Service
const integration = yield* Integration.Service
const reference = yield* Reference.Service
const skill = yield* SkillV2.Service
return {
options: {},
agent: {
reload: agents.reload,
transform: (callback) =>
agents.transform((draft) =>
callback({
list: draft.list,
get: (id) => draft.get(AgentV2.ID.make(id)),
default: (id) => draft.default(id === undefined ? undefined : AgentV2.ID.make(id)),
update: (id, update) => draft.update(AgentV2.ID.make(id), update),
remove: (id) => draft.remove(AgentV2.ID.make(id)),
}),
),
},
aisdk: {
sdk: (callback) =>
aisdk.hook.sdk((event) => {
const output = {
model: event.model,
package: event.package,
options: event.options,
sdk: event.sdk,
}
const result = callback(output)
return Effect.suspend(() => (Effect.isEffect(result) ? result : Effect.void)).pipe(
Effect.tap(() => Effect.sync(() => (event.sdk = output.sdk))),
)
}),
language: (callback) =>
aisdk.hook.language((event) => {
const output = {
model: event.model,
sdk: event.sdk,
options: event.options,
language: event.language,
}
const result = callback(output)
return Effect.suspend(() => (Effect.isEffect(result) ? result : Effect.void)).pipe(
Effect.tap(() => Effect.sync(() => (event.language = output.language))),
)
}),
},
catalog: {
reload: catalog.reload,
transform: (callback) =>
catalog.transform((draft) =>
callback({
provider: {
list: draft.provider.list,
get: (id) => draft.provider.get(ProviderV2.ID.make(id)),
update: (id, update) => draft.provider.update(ProviderV2.ID.make(id), update),
remove: (id) => draft.provider.remove(ProviderV2.ID.make(id)),
},
model: {
get: (providerID, modelID) => draft.model.get(ProviderV2.ID.make(providerID), ModelV2.ID.make(modelID)),
update: (providerID, modelID, update) =>
draft.model.update(ProviderV2.ID.make(providerID), ModelV2.ID.make(modelID), update),
remove: (providerID, modelID) =>
draft.model.remove(ProviderV2.ID.make(providerID), ModelV2.ID.make(modelID)),
default: {
get: draft.model.default.get,
set: (providerID, modelID) =>
draft.model.default.set(ProviderV2.ID.make(providerID), ModelV2.ID.make(modelID)),
},
},
}),
),
},
command: {
reload: commands.reload,
transform: commands.transform,
},
integration: {
reload: integration.reload,
transform: (callback) =>
integration.transform((draft) =>
callback({
list: draft.list,
get: (id) => draft.get(Integration.ID.make(id)),
update: (id, update) => draft.update(Integration.ID.make(id), update),
remove: (id) => draft.remove(Integration.ID.make(id)),
method: {
list: (id) => draft.method.list(Integration.ID.make(id)),
update: (input) => {
if (input.method.type === "env") {
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: { type: "env", names: input.method.names },
})
return
}
draft.method.update({
integrationID: Integration.ID.make(input.integrationID),
method: { type: "key", label: input.method.label },
})
},
remove: (id, method) =>
draft.method.remove(Integration.ID.make(id), Schema.decodeUnknownSync(Integration.Method)(method)),
},
}),
),
},
plugin: {
add: (input) => plugin.add(PluginV2.ID.make(input.id), input.effect),
remove: (id) => plugin.remove(PluginV2.ID.make(id)),
},
reference: {
reload: reference.reload,
transform: (callback) =>
reference.transform((draft) =>
callback({
add: (name, source) => draft.add(name, Schema.decodeUnknownSync(Reference.Source)(source)),
remove: draft.remove,
list: draft.list,
}),
),
},
skill: {
reload: skill.reload,
transform: (callback) =>
skill.transform((draft) =>
callback({
source: (source) => draft.source(Schema.decodeUnknownSync(SkillV2.Source)(source)),
list: draft.list,
}),
),
},
} satisfies Interface
})
+118
View File
@@ -0,0 +1,118 @@
export * as PluginInternal from "./internal"
import type { PluginContext } from "@opencode-ai/plugin/v2/effect"
import { Effect, Layer, Scope } from "effect"
import { AgentV2 } from "../agent"
import { Catalog } from "../catalog"
import { CommandV2 } from "../command"
import { Config } from "../config"
import { ConfigAgentPlugin } from "../config/plugin/agent"
import { ConfigCommandPlugin } from "../config/plugin/command"
import { ConfigExternalPlugin } from "../config/plugin/external"
import { ConfigProviderPlugin } from "../config/plugin/provider"
import { ConfigReferencePlugin } from "../config/plugin/reference"
import { ConfigSkillPlugin } from "../config/plugin/skill"
import { EventV2 } from "../event"
import { FileSystem } from "../filesystem"
import { FSUtil } from "../fs-util"
import { Global } from "../global"
import { Integration } from "../integration"
import { Location } from "../location"
import { ModelsDev } from "../models-dev"
import { Npm } from "../npm"
import { PluginV2 } from "../plugin"
import { Reference } from "../reference"
import { SkillV2 } from "../skill"
import { AgentPlugin } from "./agent"
import { CommandPlugin } from "./command"
import { ModelsDevPlugin } from "./models-dev"
import { ProviderPlugins } from "./provider"
import { SkillPlugin } from "./skill"
export type Requirements =
| AgentV2.Service
| Catalog.Service
| CommandV2.Service
| Config.Service
| EventV2.Service
| FileSystem.Service
| FSUtil.Service
| Global.Service
| Integration.Service
| Location.Service
| ModelsDev.Service
| Npm.Service
| Reference.Service
| SkillV2.Service
export interface Plugin<R = never> {
readonly id: string
readonly effect: (context: PluginContext) => Effect.Effect<void, never, R | Scope.Scope>
}
export function define<R>(plugin: Plugin<R>) {
return plugin
}
export const locationLayer = Layer.effectDiscard(
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const commands = yield* CommandV2.Service
const plugin = yield* PluginV2.Service
const integration = yield* Integration.Service
const agents = yield* AgentV2.Service
const config = yield* Config.Service
const location = yield* Location.Service
const modelsDev = yield* ModelsDev.Service
const npm = yield* Npm.Service
const events = yield* EventV2.Service
const fs = yield* FSUtil.Service
const filesystem = yield* FileSystem.Service
const global = yield* Global.Service
const skill = yield* SkillV2.Service
const reference = yield* Reference.Service
const add = <R>(input: Plugin<R>) => {
const loaded = {
id: input.id,
effect: (context: PluginContext) =>
input
.effect(context)
.pipe(
Effect.provideService(Catalog.Service, catalog),
Effect.provideService(CommandV2.Service, commands),
Effect.provideService(Integration.Service, integration),
Effect.provideService(AgentV2.Service, agents),
Effect.provideService(Config.Service, config),
Effect.provideService(Location.Service, location),
Effect.provideService(ModelsDev.Service, modelsDev),
Effect.provideService(Npm.Service, npm),
Effect.provideService(EventV2.Service, events),
Effect.provideService(FSUtil.Service, fs),
Effect.provideService(FileSystem.Service, filesystem),
Effect.provideService(Global.Service, global),
Effect.provideService(SkillV2.Service, skill),
Effect.provideService(Reference.Service, reference),
),
}
return plugin.add(PluginV2.ID.make(loaded.id), loaded.effect)
}
yield* Effect.gen(function* () {
yield* add(AgentPlugin.Plugin)
yield* add(CommandPlugin.Plugin)
yield* add(SkillPlugin.Plugin)
yield* add(ModelsDevPlugin)
yield* add(ConfigProviderPlugin.Plugin)
yield* add(ConfigAgentPlugin.Plugin)
yield* add(ConfigCommandPlugin.Plugin)
yield* add(ConfigSkillPlugin.Plugin)
yield* add(ConfigReferencePlugin.Plugin)
for (const item of ProviderPlugins) yield* add(item)
yield* add(ConfigExternalPlugin.Plugin)
}).pipe(Effect.withSpan("PluginInternal.boot"), Effect.forkScoped({ startImmediately: true }))
}),
).pipe(
Layer.provideMerge(PluginV2.locationLayer),
Layer.provideMerge(Config.locationLayer),
Layer.provideMerge(FileSystem.locationLayer),
)
+17 -22
View File
@@ -1,16 +1,14 @@
import { DateTime, Effect, Scope, Stream } from "effect" import { define } from "./internal"
import { Catalog } from "../catalog" import { Effect, Stream } from "effect"
import { Integration } from "../integration"
import { EventV2 } from "../event" import { EventV2 } from "../event"
import { ModelV2 } from "../model" import { ModelV2 } from "../model"
import { ModelRequest } from "../model-request" import { ModelRequest } from "../model-request"
import { ModelsDev } from "../models-dev" import { ModelsDev } from "../models-dev"
import { PluginV2 } from "../plugin"
import { ProviderV2 } from "../provider" import { ProviderV2 } from "../provider"
function released(date: string) { function released(date: string) {
const time = Date.parse(date) const time = Date.parse(date)
return DateTime.makeUnsafe(Number.isFinite(time) ? time : 0) return Number.isFinite(time) ? time : 0
} }
function cost(input: ModelsDev.Model["cost"]) { function cost(input: ModelsDev.Model["cost"]) {
@@ -51,22 +49,17 @@ function variants(model: ModelsDev.Model, packageName?: string) {
}) })
} }
export const ModelsDevPlugin = PluginV2.define({ export const ModelsDevPlugin = define({
id: PluginV2.ID.make("models-dev"), id: "models-dev",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const catalog = yield* Catalog.Service
const integrations = yield* Integration.Service
const modelsDev = yield* ModelsDev.Service const modelsDev = yield* ModelsDev.Service
const events = yield* EventV2.Service const events = yield* EventV2.Service
const scope = yield* Scope.Scope yield* ctx.integration.transform(
const transform = yield* catalog.transform() Effect.fn(function* (integrations) {
const integrationTransform = yield* integrations.transform()
const refresh = Effect.fn("ModelsDevPlugin.refresh")(function* () {
const data = yield* modelsDev.get() const data = yield* modelsDev.get()
yield* integrationTransform((integrations) => {
for (const item of Object.values(data)) { for (const item of Object.values(data)) {
if (item.env.length === 0) continue if (item.env.length === 0) continue
const integrationID = Integration.ID.make(item.id) const integrationID = item.id
integrations.update(integrationID, (integration) => (integration.name = item.name)) integrations.update(integrationID, (integration) => (integration.name = item.name))
integrations.method.update({ integrations.method.update({
integrationID, integrationID,
@@ -77,8 +70,11 @@ export const ModelsDevPlugin = PluginV2.define({
method: { type: "env", names: [...item.env] }, method: { type: "env", names: [...item.env] },
}) })
} }
}) }),
yield* transform((catalog) => { )
yield* ctx.catalog.transform(
Effect.fn(function* (catalog) {
const data = yield* modelsDev.get()
for (const item of Object.values(data)) { for (const item of Object.values(data)) {
const providerID = ProviderV2.ID.make(item.id) const providerID = ProviderV2.ID.make(item.id)
catalog.provider.update(providerID, (provider) => { catalog.provider.update(providerID, (provider) => {
@@ -132,11 +128,10 @@ export const ModelsDevPlugin = PluginV2.define({
}) })
} }
} }
}) }),
}) )
yield* refresh()
yield* events.subscribe(ModelsDev.Event.Refreshed).pipe( yield* events.subscribe(ModelsDev.Event.Refreshed).pipe(
Stream.runForEach(() => refresh()), Stream.runForEach(() => ctx.integration.reload().pipe(Effect.andThen(ctx.catalog.reload()))),
Effect.forkScoped({ startImmediately: true }), Effect.forkScoped({ startImmediately: true }),
) )
}), }),
+89
View File
@@ -0,0 +1,89 @@
export * as PluginPromise from "./promise"
import { define } from "@opencode-ai/plugin/v2/effect"
import type { Plugin, PluginContext, Registration } from "@opencode-ai/plugin/v2/promise"
import { Effect, Scope } from "effect"
// The Effect host hands back this registration shape; mirror it structurally so
// we do not have to alias the Effect package's `Registration` against the Promise one.
type HostRegistration = { readonly dispose: Effect.Effect<void> }
/**
* Adapts a Promise plugin into an Effect plugin so the existing Effect-only
* loader (`PluginV2` / `PluginInternal`) can run it unchanged.
*
* Hook registrations created during the async `setup` attach to the plugin's
* scope, so unloading the plugin disposes them. The captured fiber context
* preserves boot-time batching, so Promise-plugin transforms still coalesce
* into one reload per domain.
*/
export function fromPromise(plugin: Plugin) {
return define({
id: plugin.id,
effect: (host) =>
Effect.gen(function* () {
const scope = yield* Scope.Scope
const context = yield* Effect.context<Scope.Scope>()
// Run a hook registration on the plugin scope and resolve once it is registered.
const register = (effect: Effect.Effect<HostRegistration, never, Scope.Scope>): Promise<Registration> =>
Effect.runPromiseWith(context)(Scope.provide(scope)(effect)).then((registration) => ({
dispose: () => Effect.runPromiseWith(context)(registration.dispose),
}))
const run = (effect: Effect.Effect<void>) => Effect.runPromiseWith(context)(effect)
const transform =
<Draft>(domain: {
transform: (
callback: (draft: Draft) => Effect.Effect<void> | void,
) => Effect.Effect<HostRegistration, never, Scope.Scope>
}) =>
(callback: (draft: Draft) => Promise<void> | void) =>
register(domain.transform((draft) => Effect.promise(() => Promise.resolve(callback(draft)))))
const context2: PluginContext = {
options: host.options,
agent: {
transform: transform(host.agent),
reload: () => run(host.agent.reload()),
},
aisdk: {
sdk: (callback) =>
register(host.aisdk.sdk((event) => Effect.promise(() => Promise.resolve(callback(event))))),
language: (callback) =>
register(host.aisdk.language((event) => Effect.promise(() => Promise.resolve(callback(event))))),
},
catalog: {
transform: transform(host.catalog),
reload: () => run(host.catalog.reload()),
},
command: {
transform: transform(host.command),
reload: () => run(host.command.reload()),
},
integration: {
transform: transform(host.integration),
reload: () => run(host.integration.reload()),
},
plugin: {
add: (input) => {
const child = fromPromise(input)
return run(host.plugin.add(child))
},
remove: (id) => run(host.plugin.remove(id)),
},
reference: {
transform: transform(host.reference),
reload: () => run(host.reference.reload()),
},
skill: {
transform: transform(host.skill),
reload: () => run(host.skill.reload()),
},
}
yield* Effect.promise(() => Promise.resolve(plugin.setup(context2)))
}),
})
}
+3 -1
View File
@@ -30,8 +30,10 @@ import { VercelPlugin } from "./provider/vercel"
import { VenicePlugin } from "./provider/venice" import { VenicePlugin } from "./provider/venice"
import { XAIPlugin } from "./provider/xai" import { XAIPlugin } from "./provider/xai"
import { ZenmuxPlugin } from "./provider/zenmux" import { ZenmuxPlugin } from "./provider/zenmux"
import type { PluginInternal } from "./internal"
import type { Scope } from "effect"
export const ProviderPlugins = [ export const ProviderPlugins: PluginInternal.Plugin<PluginInternal.Requirements | Scope.Scope>[] = [
AlibabaPlugin, AlibabaPlugin,
AmazonBedrockPlugin, AmazonBedrockPlugin,
AnthropicPlugin, AnthropicPlugin,
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const AlibabaPlugin = PluginV2.define({ export const AlibabaPlugin = define({
id: PluginV2.ID.make("alibaba"), id: "alibaba",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/alibaba") return if (evt.package !== "@ai-sdk/alibaba") return
const mod = yield* Effect.promise(() => import("@ai-sdk/alibaba")) const mod = yield* Effect.promise(() => import("@ai-sdk/alibaba"))
evt.sdk = mod.createAlibaba(evt.options) evt.sdk = mod.createAlibaba(evt.options)
}), }),
} )
}), }),
}) })
@@ -1,6 +1,6 @@
import { Effect } from "effect" import { Effect } from "effect"
import type { LanguageModelV3 } from "@ai-sdk/provider" import type { LanguageModelV3 } from "@ai-sdk/provider"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
type MantleSDK = { type MantleSDK = {
@@ -59,11 +59,11 @@ function selectMantleModel(sdk: MantleSDK, modelID: string) {
return sdk.responses(modelID) return sdk.responses(modelID)
} }
export const AmazonBedrockPlugin = PluginV2.define({ export const AmazonBedrockPlugin = define({
id: PluginV2.ID.make("amazon-bedrock"), id: "amazon-bedrock",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/amazon-bedrock") continue if (item.provider.api.package !== "@ai-sdk/amazon-bedrock") continue
@@ -77,7 +77,9 @@ export const AmazonBedrockPlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (!["@ai-sdk/amazon-bedrock", "@ai-sdk/amazon-bedrock/mantle"].includes(evt.package)) return if (!["@ai-sdk/amazon-bedrock", "@ai-sdk/amazon-bedrock/mantle"].includes(evt.package)) return
const options = { ...evt.options } const options = { ...evt.options }
const profile = typeof options.profile === "string" ? options.profile : process.env.AWS_PROFILE const profile = typeof options.profile === "string" ? options.profile : process.env.AWS_PROFILE
@@ -108,7 +110,9 @@ export const AmazonBedrockPlugin = PluginV2.define({
const mod = yield* Effect.promise(() => import("@ai-sdk/amazon-bedrock")) const mod = yield* Effect.promise(() => import("@ai-sdk/amazon-bedrock"))
evt.sdk = mod.createAmazonBedrock(options) evt.sdk = mod.createAmazonBedrock(options)
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.amazonBedrock) return if (evt.model.providerID !== ProviderV2.ID.amazonBedrock) return
if (evt.model.api.type === "aisdk" && evt.model.api.package === "@ai-sdk/amazon-bedrock/mantle") { if (evt.model.api.type === "aisdk" && evt.model.api.package === "@ai-sdk/amazon-bedrock/mantle") {
evt.language = selectMantleModel(evt.sdk, evt.model.api.id) evt.language = selectMantleModel(evt.sdk, evt.model.api.id)
@@ -117,6 +121,6 @@ export const AmazonBedrockPlugin = PluginV2.define({
const region = typeof evt.options.region === "string" ? evt.options.region : process.env.AWS_REGION const region = typeof evt.options.region === "string" ? evt.options.region : process.env.AWS_REGION
evt.language = evt.sdk.languageModel(resolveModelID(evt.model.api.id, region)) evt.language = evt.sdk.languageModel(resolveModelID(evt.model.api.id, region))
}), }),
} )
}), }),
}) })
+10 -8
View File
@@ -1,11 +1,11 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const AnthropicPlugin = PluginV2.define({ export const AnthropicPlugin = define({
id: PluginV2.ID.make("anthropic"), id: "anthropic",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/anthropic") continue if (item.provider.api.package !== "@ai-sdk/anthropic") continue
@@ -15,11 +15,13 @@ export const AnthropicPlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/anthropic") return if (evt.package !== "@ai-sdk/anthropic") return
const mod = yield* Effect.promise(() => import("@ai-sdk/anthropic")) const mod = yield* Effect.promise(() => import("@ai-sdk/anthropic"))
evt.sdk = mod.createAnthropic(evt.options) evt.sdk = mod.createAnthropic(evt.options)
}), }),
} )
}), }),
}) })
+22 -16
View File
@@ -1,5 +1,5 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
function selectLanguage(sdk: any, modelID: string, useChat: boolean) { function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
@@ -10,11 +10,11 @@ function selectLanguage(sdk: any, modelID: string, useChat: boolean) {
return sdk.languageModel(modelID) return sdk.languageModel(modelID)
} }
export const AzurePlugin = PluginV2.define({ export const AzurePlugin = define({
id: PluginV2.ID.make("azure"), id: "azure",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/azure") continue if (item.provider.api.package !== "@ai-sdk/azure") continue
@@ -27,7 +27,9 @@ export const AzurePlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/azure") return if (evt.package !== "@ai-sdk/azure") return
if (evt.model.providerID === ProviderV2.ID.azure) { if (evt.model.providerID === ProviderV2.ID.azure) {
if ( if (
@@ -43,19 +45,21 @@ export const AzurePlugin = PluginV2.define({
const mod = yield* Effect.promise(() => import("@ai-sdk/azure")) const mod = yield* Effect.promise(() => import("@ai-sdk/azure"))
evt.sdk = mod.createAzure(evt.options) evt.sdk = mod.createAzure(evt.options)
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.azure) return if (evt.model.providerID !== ProviderV2.ID.azure) return
evt.language = selectLanguage(evt.sdk, evt.model.api.id, Boolean(evt.options.useCompletionUrls)) evt.language = selectLanguage(evt.sdk, evt.model.api.id, Boolean(evt.options.useCompletionUrls))
}), }),
} )
}), }),
}) })
export const AzureCognitiveServicesPlugin = PluginV2.define({ export const AzureCognitiveServicesPlugin = define({
id: PluginV2.ID.make("azure-cognitive-services"), id: "azure-cognitive-services",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
const resourceName = process.env.AZURE_COGNITIVE_SERVICES_RESOURCE_NAME const resourceName = process.env.AZURE_COGNITIVE_SERVICES_RESOURCE_NAME
if (!resourceName) return if (!resourceName) return
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
@@ -67,10 +71,12 @@ export const AzureCognitiveServicesPlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.make("azure-cognitive-services")) return if (evt.model.providerID !== ProviderV2.ID.make("azure-cognitive-services")) return
evt.language = selectLanguage(evt.sdk, evt.model.api.id, Boolean(evt.options.useCompletionUrls)) evt.language = selectLanguage(evt.sdk, evt.model.api.id, Boolean(evt.options.useCompletionUrls))
}), }),
} )
}), }),
}) })
+12 -10
View File
@@ -1,24 +1,26 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const CerebrasPlugin = PluginV2.define({ export const CerebrasPlugin = define({
id: PluginV2.ID.make("cerebras"), id: "cerebras",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (ctx) { Effect.fn(function* (evt) {
for (const item of ctx.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/cerebras") continue if (item.provider.api.package !== "@ai-sdk/cerebras") continue
ctx.provider.update(item.provider.id, (provider) => { evt.provider.update(item.provider.id, (provider) => {
provider.request.headers["X-Cerebras-3rd-Party-Integration"] = "opencode" provider.request.headers["X-Cerebras-3rd-Party-Integration"] = "opencode"
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/cerebras") return if (evt.package !== "@ai-sdk/cerebras") return
const mod = yield* Effect.promise(() => import("@ai-sdk/cerebras")) const mod = yield* Effect.promise(() => import("@ai-sdk/cerebras"))
evt.sdk = mod.createCerebras(evt.options) evt.sdk = mod.createCerebras(evt.options)
}), }),
} )
}), }),
}) })
@@ -1,13 +1,13 @@
import os from "os" import os from "os"
import { InstallationVersion } from "../../installation/version" import { InstallationVersion } from "../../installation/version"
import { Effect, Option, Schema } from "effect" import { Effect, Option, Schema } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const CloudflareAIGatewayPlugin = PluginV2.define({ export const CloudflareAIGatewayPlugin = define({
id: PluginV2.ID.make("cloudflare-ai-gateway"), id: "cloudflare-ai-gateway",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "ai-gateway-provider") return if (evt.package !== "ai-gateway-provider") return
if (evt.options.baseURL) return if (evt.options.baseURL) return
@@ -31,7 +31,7 @@ export const CloudflareAIGatewayPlugin = PluginV2.define({
}, },
} }
}), }),
} )
}), }),
}) })
@@ -1,16 +1,16 @@
import os from "os" import os from "os"
import { InstallationVersion } from "../../installation/version" import { InstallationVersion } from "../../installation/version"
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
const providerID = ProviderV2.ID.make("cloudflare-workers-ai") const providerID = ProviderV2.ID.make("cloudflare-workers-ai")
export const CloudflareWorkersAIPlugin = PluginV2.define({ export const CloudflareWorkersAIPlugin = define({
id: PluginV2.ID.make("cloudflare-workers-ai"), id: "cloudflare-workers-ai",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
const item = evt.provider.get(providerID) const item = evt.provider.get(providerID)
if (!item) return if (!item) return
evt.provider.update(item.provider.id, (provider) => { evt.provider.update(item.provider.id, (provider) => {
@@ -20,7 +20,9 @@ export const CloudflareWorkersAIPlugin = PluginV2.define({
if (accountId) provider.api.url = workersEndpoint(accountId) if (accountId) provider.api.url = workersEndpoint(accountId)
}) })
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.model.providerID !== providerID) return if (evt.model.providerID !== providerID) return
if (evt.package !== "@ai-sdk/openai-compatible") return if (evt.package !== "@ai-sdk/openai-compatible") return
@@ -34,11 +36,13 @@ export const CloudflareWorkersAIPlugin = PluginV2.define({
}) as any, }) as any,
) )
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== providerID) return if (evt.model.providerID !== providerID) return
evt.language = evt.sdk.languageModel(evt.model.api.id) evt.language = evt.sdk.languageModel(evt.model.api.id)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const CoherePlugin = PluginV2.define({ export const CoherePlugin = define({
id: PluginV2.ID.make("cohere"), id: "cohere",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/cohere") return if (evt.package !== "@ai-sdk/cohere") return
const mod = yield* Effect.promise(() => import("@ai-sdk/cohere")) const mod = yield* Effect.promise(() => import("@ai-sdk/cohere"))
evt.sdk = mod.createCohere(evt.options) evt.sdk = mod.createCohere(evt.options)
}), }),
} )
}), }),
}) })
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const DeepInfraPlugin = PluginV2.define({ export const DeepInfraPlugin = define({
id: PluginV2.ID.make("deepinfra"), id: "deepinfra",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/deepinfra") return if (evt.package !== "@ai-sdk/deepinfra") return
const mod = yield* Effect.promise(() => import("@ai-sdk/deepinfra")) const mod = yield* Effect.promise(() => import("@ai-sdk/deepinfra"))
evt.sdk = mod.createDeepInfra(evt.options) evt.sdk = mod.createDeepInfra(evt.options)
}), }),
} )
}), }),
}) })
+10 -10
View File
@@ -1,19 +1,19 @@
import { Npm } from "../../npm" import { Effect } from "effect"
import { Effect, Option } from "effect"
import { pathToFileURL } from "url" import { pathToFileURL } from "url"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { Npm } from "../../npm"
export const DynamicProviderPlugin = PluginV2.define({ export const DynamicProviderPlugin = define({
id: PluginV2.ID.make("dynamic-provider"), id: "dynamic-provider",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const npm = yield* Npm.Service const npm = yield* Npm.Service
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.sdk) return if (evt.sdk) return
const installedPath = evt.package.startsWith("file://") const installedPath = evt.package.startsWith("file://")
? evt.package ? evt.package
: Option.getOrUndefined((yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint) : (yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint
if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`) if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`)
const mod = yield* Effect.promise(async () => { const mod = yield* Effect.promise(async () => {
@@ -26,6 +26,6 @@ export const DynamicProviderPlugin = PluginV2.define({
evt.sdk = mod[match](evt.options) evt.sdk = mod[match](evt.options)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const GatewayPlugin = PluginV2.define({ export const GatewayPlugin = define({
id: PluginV2.ID.make("gateway"), id: "gateway",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/gateway") return if (evt.package !== "@ai-sdk/gateway") return
const mod = yield* Effect.promise(() => import("@ai-sdk/gateway")) const mod = yield* Effect.promise(() => import("@ai-sdk/gateway"))
evt.sdk = mod.createGateway(evt.options) evt.sdk = mod.createGateway(evt.options)
}), }),
} )
}), }),
}) })
@@ -1,6 +1,6 @@
import { Effect } from "effect" import { Effect } from "effect"
import { ModelV2 } from "../../model" import { ModelV2 } from "../../model"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
function shouldUseResponses(modelID: string) { function shouldUseResponses(modelID: string) {
@@ -11,16 +11,29 @@ function shouldUseResponses(modelID: string) {
return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini") return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")
} }
export const GithubCopilotPlugin = PluginV2.define({ export const GithubCopilotPlugin = define({
id: PluginV2.ID.make("github-copilot"), id: "github-copilot",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
const item = evt.provider.get(ProviderV2.ID.githubCopilot)
if (!item || !item.models.has(ModelV2.ID.make("gpt-5-chat-latest"))) return
evt.model.update(item.provider.id, ModelV2.ID.make("gpt-5-chat-latest"), (model) => {
// This chat-only alias conflicts with the Copilot GPT-5 Responses route,
// so hide it only for Copilot rather than for every provider catalog.
model.enabled = false
})
}),
)
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/github-copilot") return if (evt.package !== "@ai-sdk/github-copilot") return
const mod = yield* Effect.promise(() => import("../../github-copilot/copilot-provider")) const mod = yield* Effect.promise(() => import("../../github-copilot/copilot-provider"))
evt.sdk = mod.createOpenaiCompatible(evt.options) evt.sdk = mod.createOpenaiCompatible(evt.options)
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.githubCopilot) return if (evt.model.providerID !== ProviderV2.ID.githubCopilot) return
if (evt.sdk.responses === undefined && evt.sdk.chat === undefined) { if (evt.sdk.responses === undefined && evt.sdk.chat === undefined) {
evt.language = evt.sdk.languageModel(evt.model.api.id) evt.language = evt.sdk.languageModel(evt.model.api.id)
@@ -30,15 +43,6 @@ export const GithubCopilotPlugin = PluginV2.define({
? evt.sdk.responses(evt.model.api.id) ? evt.sdk.responses(evt.model.api.id)
: evt.sdk.chat(evt.model.api.id) : evt.sdk.chat(evt.model.api.id)
}), }),
"catalog.transform": Effect.fn(function* (evt) { )
const item = evt.provider.get(ProviderV2.ID.githubCopilot)
if (!item || !item.models.has(ModelV2.ID.make("gpt-5-chat-latest"))) return
evt.model.update(item.provider.id, ModelV2.ID.make("gpt-5-chat-latest"), (model) => {
// This chat-only alias conflicts with the Copilot GPT-5 Responses route,
// so hide it only for Copilot rather than for every provider catalog.
model.enabled = false
})
}),
}
}), }),
}) })
+10 -8
View File
@@ -1,14 +1,14 @@
import os from "os" import os from "os"
import { InstallationVersion } from "../../installation/version" import { InstallationVersion } from "../../installation/version"
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
export const GitLabPlugin = PluginV2.define({ export const GitLabPlugin = define({
id: PluginV2.ID.make("gitlab"), id: "gitlab",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "gitlab-ai-provider") return if (evt.package !== "gitlab-ai-provider") return
const mod = yield* Effect.promise(() => import("gitlab-ai-provider")) const mod = yield* Effect.promise(() => import("gitlab-ai-provider"))
evt.sdk = mod.createGitLab({ evt.sdk = mod.createGitLab({
@@ -30,7 +30,9 @@ export const GitLabPlugin = PluginV2.define({
}, },
}) })
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.gitlab) return if (evt.model.providerID !== ProviderV2.ID.gitlab) return
const featureFlags = const featureFlags =
typeof evt.options.featureFlags === "object" && evt.options.featureFlags ? evt.options.featureFlags : {} typeof evt.options.featureFlags === "object" && evt.options.featureFlags ? evt.options.featureFlags : {}
@@ -58,6 +60,6 @@ export const GitLabPlugin = PluginV2.define({
featureFlags, featureFlags,
}) })
}), }),
} )
}), }),
}) })
@@ -1,5 +1,5 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
function resolveProject(options: Record<string, any>) { function resolveProject(options: Record<string, any>) {
@@ -54,11 +54,11 @@ function authFetch(fetchWithRuntimeOptions?: unknown) {
} }
} }
export const GoogleVertexPlugin = PluginV2.define({ export const GoogleVertexPlugin = define({
id: PluginV2.ID.make("google-vertex"), id: "google-vertex",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if ( if (
@@ -83,7 +83,9 @@ export const GoogleVertexPlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.model.providerID === ProviderV2.ID.googleVertex && evt.package.includes("@ai-sdk/openai-compatible")) { if (evt.model.providerID === ProviderV2.ID.googleVertex && evt.package.includes("@ai-sdk/openai-compatible")) {
evt.options.fetch = authFetch(evt.options.fetch) evt.options.fetch = authFetch(evt.options.fetch)
return return
@@ -100,19 +102,21 @@ export const GoogleVertexPlugin = PluginV2.define({
location, location,
}) })
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.googleVertex) return if (evt.model.providerID !== ProviderV2.ID.googleVertex) return
evt.language = evt.sdk.languageModel(String(evt.model.api.id).trim()) evt.language = evt.sdk.languageModel(String(evt.model.api.id).trim())
}), }),
} )
}), }),
}) })
export const GoogleVertexAnthropicPlugin = PluginV2.define({ export const GoogleVertexAnthropicPlugin = define({
id: PluginV2.ID.make("google-vertex-anthropic"), id: "google-vertex-anthropic",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/google-vertex/anthropic") continue if (item.provider.api.package !== "@ai-sdk/google-vertex/anthropic") continue
@@ -132,7 +136,9 @@ export const GoogleVertexAnthropicPlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/google-vertex/anthropic") return if (evt.package !== "@ai-sdk/google-vertex/anthropic") return
const mod = yield* Effect.promise(() => import("@ai-sdk/google-vertex/anthropic")) const mod = yield* Effect.promise(() => import("@ai-sdk/google-vertex/anthropic"))
const project = const project =
@@ -156,10 +162,12 @@ export const GoogleVertexAnthropicPlugin = PluginV2.define({
: {}), : {}),
}) })
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.make("google-vertex-anthropic")) return if (evt.model.providerID !== ProviderV2.ID.make("google-vertex-anthropic")) return
evt.language = evt.sdk.languageModel(String(evt.model.api.id).trim()) evt.language = evt.sdk.languageModel(String(evt.model.api.id).trim())
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const GooglePlugin = PluginV2.define({ export const GooglePlugin = define({
id: PluginV2.ID.make("google"), id: "google",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/google") return if (evt.package !== "@ai-sdk/google") return
const mod = yield* Effect.promise(() => import("@ai-sdk/google")) const mod = yield* Effect.promise(() => import("@ai-sdk/google"))
evt.sdk = mod.createGoogleGenerativeAI(evt.options) evt.sdk = mod.createGoogleGenerativeAI(evt.options)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const GroqPlugin = PluginV2.define({ export const GroqPlugin = define({
id: PluginV2.ID.make("groq"), id: "groq",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/groq") return if (evt.package !== "@ai-sdk/groq") return
const mod = yield* Effect.promise(() => import("@ai-sdk/groq")) const mod = yield* Effect.promise(() => import("@ai-sdk/groq"))
evt.sdk = mod.createGroq(evt.options) evt.sdk = mod.createGroq(evt.options)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,11 +1,11 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const KiloPlugin = PluginV2.define({ export const KiloPlugin = define({
id: PluginV2.ID.make("kilo"), id: "kilo",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue
@@ -16,6 +16,6 @@ export const KiloPlugin = PluginV2.define({
}) })
} }
}), }),
} )
}), }),
}) })
@@ -1,19 +1,19 @@
import { Effect } from "effect" import { Effect } from "effect"
import { define } from "../internal"
import { Integration } from "../../integration" import { Integration } from "../../integration"
import { PluginV2 } from "../../plugin"
export const LLMGatewayPlugin = PluginV2.define({ export const LLMGatewayPlugin = define({
id: PluginV2.ID.make("llmgateway"), id: "llmgateway",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const integrations = yield* Integration.Service const integrations = yield* Integration.Service
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.disabled) continue if (item.provider.disabled) continue
if (!(yield* integrations.get(Integration.ID.make(item.provider.id)))) continue
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue
if (item.provider.api.url !== "https://api.llmgateway.io/v1") continue if (item.provider.api.url !== "https://api.llmgateway.io/v1") continue
if (!(yield* integrations.get(Integration.ID.make(item.provider.id)))) continue
evt.provider.update(item.provider.id, (provider) => { evt.provider.update(item.provider.id, (provider) => {
provider.request.headers["HTTP-Referer"] = "https://opencode.ai/" provider.request.headers["HTTP-Referer"] = "https://opencode.ai/"
provider.request.headers["X-Title"] = "opencode" provider.request.headers["X-Title"] = "opencode"
@@ -21,6 +21,6 @@ export const LLMGatewayPlugin = PluginV2.define({
}) })
} }
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const MistralPlugin = PluginV2.define({ export const MistralPlugin = define({
id: PluginV2.ID.make("mistral"), id: "mistral",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/mistral") return if (evt.package !== "@ai-sdk/mistral") return
const mod = yield* Effect.promise(() => import("@ai-sdk/mistral")) const mod = yield* Effect.promise(() => import("@ai-sdk/mistral"))
evt.sdk = mod.createMistral(evt.options) evt.sdk = mod.createMistral(evt.options)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,11 +1,11 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const NvidiaPlugin = PluginV2.define({ export const NvidiaPlugin = define({
id: PluginV2.ID.make("nvidia"), id: "nvidia",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue
@@ -17,6 +17,6 @@ export const NvidiaPlugin = PluginV2.define({
}) })
} }
}), }),
} )
}), }),
}) })
@@ -1,17 +1,17 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const OpenAICompatiblePlugin = PluginV2.define({ export const OpenAICompatiblePlugin = define({
id: PluginV2.ID.make("openai-compatible"), id: "openai-compatible",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.sdk) return if (evt.sdk) return
if (!evt.package.includes("@ai-sdk/openai-compatible")) return if (!evt.package.includes("@ai-sdk/openai-compatible")) return
if (evt.options.includeUsage !== false) evt.options.includeUsage = true if (evt.options.includeUsage !== false) evt.options.includeUsage = true
const mod = yield* Effect.promise(() => import("@ai-sdk/openai-compatible")) const mod = yield* Effect.promise(() => import("@ai-sdk/openai-compatible"))
evt.sdk = mod.createOpenAICompatible(evt.options as any) evt.sdk = mod.createOpenAICompatible(evt.options as any)
}), }),
} )
}), }),
}) })
+23 -19
View File
@@ -1,29 +1,20 @@
import { Effect } from "effect" import { Effect } from "effect"
import { ModelV2 } from "../../model" import { ModelV2 } from "../../model"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
import { Integration } from "../../integration" import { Integration } from "../../integration"
import { browser, headless } from "./openai-auth" import { browser, headless } from "./openai-auth"
export const OpenAIPlugin = PluginV2.define({ export const OpenAIPlugin = define({
id: PluginV2.ID.make("openai"), id: "openai",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const integrations = yield* Integration.Service const integrations = yield* Integration.Service
yield* integrations.update((editor) => { yield* integrations.transform((draft) => {
editor.method.update(browser) draft.method.update(browser)
editor.method.update(headless) draft.method.update(headless)
}) })
return { yield* ctx.catalog.transform(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/openai") return
const mod = yield* Effect.promise(() => import("@ai-sdk/openai"))
evt.sdk = mod.createOpenAI(evt.options)
}),
"aisdk.language": Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.openai) return
evt.language = evt.sdk.responses(evt.model.api.id)
}),
"catalog.transform": Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/openai") continue if (item.provider.api.package !== "@ai-sdk/openai") continue
@@ -35,6 +26,19 @@ export const OpenAIPlugin = PluginV2.define({
}) })
} }
}), }),
} )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/openai") return
const mod = yield* Effect.promise(() => import("@ai-sdk/openai"))
evt.sdk = mod.createOpenAI(evt.options)
}),
)
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.openai) return
evt.language = evt.sdk.responses(evt.model.api.id)
}),
)
}), }),
}) })
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { Integration } from "../../integration" import { define } from "../internal"
import { PluginV2 } from "../../plugin"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
import { Integration } from "../../integration"
export const OpencodePlugin = PluginV2.define({ export const OpencodePlugin = define({
id: PluginV2.ID.make("opencode"), id: "opencode",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const integrations = yield* Integration.Service const integrations = yield* Integration.Service
let hasKey = false let hasKey = false
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
const item = evt.provider.get(ProviderV2.ID.opencode) const item = evt.provider.get(ProviderV2.ID.opencode)
if (!item) return if (!item) return
const integration = yield* integrations.get(Integration.ID.make(item.provider.id)) const integration = yield* integrations.get(Integration.ID.make(item.provider.id))
@@ -27,6 +27,6 @@ export const OpencodePlugin = PluginV2.define({
}) })
} }
}), }),
} )
}), }),
}) })
@@ -1,12 +1,12 @@
import { Effect } from "effect" import { Effect } from "effect"
import { ModelV2 } from "../../model" import { ModelV2 } from "../../model"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const OpenRouterPlugin = PluginV2.define({ export const OpenRouterPlugin = define({
id: PluginV2.ID.make("openrouter"), id: "openrouter",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@openrouter/ai-sdk-provider") continue if (item.provider.api.package !== "@openrouter/ai-sdk-provider") continue
@@ -24,11 +24,13 @@ export const OpenRouterPlugin = PluginV2.define({
} }
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@openrouter/ai-sdk-provider") return if (evt.package !== "@openrouter/ai-sdk-provider") return
const mod = yield* Effect.promise(() => import("@openrouter/ai-sdk-provider")) const mod = yield* Effect.promise(() => import("@openrouter/ai-sdk-provider"))
evt.sdk = mod.createOpenRouter(evt.options) evt.sdk = mod.createOpenRouter(evt.options)
}), }),
} )
}), }),
}) })
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const PerplexityPlugin = PluginV2.define({ export const PerplexityPlugin = define({
id: PluginV2.ID.make("perplexity"), id: "perplexity",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/perplexity") return if (evt.package !== "@ai-sdk/perplexity") return
const mod = yield* Effect.promise(() => import("@ai-sdk/perplexity")) const mod = yield* Effect.promise(() => import("@ai-sdk/perplexity"))
evt.sdk = mod.createPerplexity(evt.options) evt.sdk = mod.createPerplexity(evt.options)
}), }),
} )
}), }),
}) })
@@ -1,15 +1,15 @@
import { Npm } from "../../npm" import { Effect } from "effect"
import { Effect, Option } from "effect"
import { pathToFileURL } from "url" import { pathToFileURL } from "url"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { Npm } from "../../npm"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
export const SapAICorePlugin = PluginV2.define({ export const SapAICorePlugin = define({
id: PluginV2.ID.make("sap-ai-core"), id: "sap-ai-core",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const npm = yield* Npm.Service const npm = yield* Npm.Service
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.make("sap-ai-core")) return if (evt.model.providerID !== ProviderV2.ID.make("sap-ai-core")) return
const serviceKey = const serviceKey =
process.env.AICORE_SERVICE_KEY ?? process.env.AICORE_SERVICE_KEY ??
@@ -18,7 +18,7 @@ export const SapAICorePlugin = PluginV2.define({
const installedPath = evt.package.startsWith("file://") const installedPath = evt.package.startsWith("file://")
? evt.package ? evt.package
: Option.getOrUndefined((yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint) : (yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint
if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`) if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`)
const mod = yield* Effect.promise(async () => { const mod = yield* Effect.promise(async () => {
@@ -35,10 +35,12 @@ export const SapAICorePlugin = PluginV2.define({
: {}, : {},
) )
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.make("sap-ai-core")) return if (evt.model.providerID !== ProviderV2.ID.make("sap-ai-core")) return
evt.language = evt.sdk(evt.model.api.id) evt.language = evt.sdk(evt.model.api.id)
}), }),
} )
}), }),
}) })
@@ -1,5 +1,5 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
type FetchLike = (url: string | URL | Request, init?: RequestInit) => Promise<Response> type FetchLike = (url: string | URL | Request, init?: RequestInit) => Promise<Response>
@@ -64,11 +64,11 @@ export function cortexFetch(upstream: FetchLike = fetch) {
} }
} }
export const SnowflakeCortexPlugin = PluginV2.define({ export const SnowflakeCortexPlugin = define({
id: PluginV2.ID.make("snowflake-cortex"), id: "snowflake-cortex",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.make("snowflake-cortex")) return if (evt.model.providerID !== ProviderV2.ID.make("snowflake-cortex")) return
const token = const token =
process.env.SNOWFLAKE_CORTEX_TOKEN ?? process.env.SNOWFLAKE_CORTEX_TOKEN ??
@@ -84,6 +84,6 @@ export const SnowflakeCortexPlugin = PluginV2.define({
fetch: cortexFetch(upstream) as typeof fetch, fetch: cortexFetch(upstream) as typeof fetch,
} as any) } as any)
}), }),
} )
}), }),
}) })
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const TogetherAIPlugin = PluginV2.define({ export const TogetherAIPlugin = define({
id: PluginV2.ID.make("togetherai"), id: "togetherai",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/togetherai") return if (evt.package !== "@ai-sdk/togetherai") return
const mod = yield* Effect.promise(() => import("@ai-sdk/togetherai")) const mod = yield* Effect.promise(() => import("@ai-sdk/togetherai"))
evt.sdk = mod.createTogetherAI(evt.options) evt.sdk = mod.createTogetherAI(evt.options)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,15 +1,15 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const VenicePlugin = PluginV2.define({ export const VenicePlugin = define({
id: PluginV2.ID.make("venice"), id: "venice",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "venice-ai-sdk-provider") return if (evt.package !== "venice-ai-sdk-provider") return
const mod = yield* Effect.promise(() => import("venice-ai-sdk-provider")) const mod = yield* Effect.promise(() => import("venice-ai-sdk-provider"))
evt.sdk = mod.createVenice(evt.options) evt.sdk = mod.createVenice(evt.options)
}), }),
} )
}), }),
}) })
+10 -8
View File
@@ -1,11 +1,11 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const VercelPlugin = PluginV2.define({ export const VercelPlugin = define({
id: PluginV2.ID.make("vercel"), id: "vercel",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/vercel") continue if (item.provider.api.package !== "@ai-sdk/vercel") continue
@@ -15,11 +15,13 @@ export const VercelPlugin = PluginV2.define({
}) })
} }
}), }),
"aisdk.sdk": Effect.fn(function* (evt) { )
yield* ctx.aisdk.sdk(
Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/vercel") return if (evt.package !== "@ai-sdk/vercel") return
const mod = yield* Effect.promise(() => import("@ai-sdk/vercel")) const mod = yield* Effect.promise(() => import("@ai-sdk/vercel"))
evt.sdk = mod.createVercel(evt.options) evt.sdk = mod.createVercel(evt.options)
}), }),
} )
}), }),
}) })
+10 -8
View File
@@ -1,20 +1,22 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
import { ProviderV2 } from "../../provider" import { ProviderV2 } from "../../provider"
export const XAIPlugin = PluginV2.define({ export const XAIPlugin = define({
id: PluginV2.ID.make("xai"), id: "xai",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.aisdk.sdk(
"aisdk.sdk": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
if (evt.package !== "@ai-sdk/xai") return if (evt.package !== "@ai-sdk/xai") return
const mod = yield* Effect.promise(() => import("@ai-sdk/xai")) const mod = yield* Effect.promise(() => import("@ai-sdk/xai"))
evt.sdk = mod.createXai(evt.options) evt.sdk = mod.createXai(evt.options)
}), }),
"aisdk.language": Effect.fn(function* (evt) { )
yield* ctx.aisdk.language(
Effect.fn(function* (evt) {
if (evt.model.providerID !== ProviderV2.ID.make("xai")) return if (evt.model.providerID !== ProviderV2.ID.make("xai")) return
evt.language = evt.sdk.responses(evt.model.api.id) evt.language = evt.sdk.responses(evt.model.api.id)
}), }),
} )
}), }),
}) })
+7 -7
View File
@@ -1,11 +1,11 @@
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../../plugin" import { define } from "../internal"
export const ZenmuxPlugin = PluginV2.define({ export const ZenmuxPlugin = define({
id: PluginV2.ID.make("zenmux"), id: "zenmux",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
return { yield* ctx.catalog.transform(
"catalog.transform": Effect.fn(function* (evt) { Effect.fn(function* (evt) {
for (const item of evt.provider.list()) { for (const item of evt.provider.list()) {
if (item.provider.api.type !== "aisdk") continue if (item.provider.api.type !== "aisdk") continue
if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue if (item.provider.api.package !== "@ai-sdk/openai-compatible") continue
@@ -16,6 +16,6 @@ export const ZenmuxPlugin = PluginV2.define({
}) })
} }
}), }),
} )
}), }),
}) })
+6 -9
View File
@@ -2,22 +2,19 @@
export * as SkillPlugin from "./skill" export * as SkillPlugin from "./skill"
import { define } from "./internal"
import { Effect } from "effect" import { Effect } from "effect"
import { PluginV2 } from "../plugin"
import { AbsolutePath } from "../schema" import { AbsolutePath } from "../schema"
import { SkillV2 } from "../skill" import { SkillV2 } from "../skill"
import customizeOpencodeContent from "./skill/customize-opencode.md" with { type: "text" } import customizeOpencodeContent from "./skill/customize-opencode.md" with { type: "text" }
export const CustomizeOpencodeContent = customizeOpencodeContent export const CustomizeOpencodeContent = customizeOpencodeContent
export const Plugin = PluginV2.define({ export const Plugin = define({
id: PluginV2.ID.make("skill"), id: "skill",
effect: Effect.gen(function* () { effect: Effect.fn(function* (ctx) {
const skill = yield* SkillV2.Service yield* ctx.skill.transform((draft) => {
const transform = yield* skill.transform() draft.source(
yield* transform((editor) => {
editor.source(
new SkillV2.EmbeddedSource({ new SkillV2.EmbeddedSource({
type: "embedded", type: "embedded",
skill: new SkillV2.Info({ skill: new SkillV2.Info({
+1 -1
View File
@@ -9,7 +9,7 @@ export class AppProcessError extends Schema.TaggedErrorClass<AppProcessError>()(
command: Schema.String, command: Schema.String,
exitCode: Schema.optional(Schema.Number), exitCode: Schema.optional(Schema.Number),
stderr: Schema.optional(Schema.String), stderr: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export interface RunOptions { export interface RunOptions {
-3
View File
@@ -13,7 +13,6 @@ import { Slug } from "../util/slug"
import { EventV2 } from "../event" import { EventV2 } from "../event"
import { Database } from "../database/database" import { Database } from "../database/database"
import { Location } from "../location" import { Location } from "../location"
import { PluginBoot } from "../plugin/boot"
export const StrategyID = Schema.Trim.pipe(Schema.check(Schema.isNonEmpty()), Schema.brand("ProjectCopy.StrategyID")) export const StrategyID = Schema.Trim.pipe(Schema.check(Schema.isNonEmpty()), Schema.brand("ProjectCopy.StrategyID"))
export type StrategyID = typeof StrategyID.Type export type StrategyID = typeof StrategyID.Type
@@ -125,10 +124,8 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/Pr
export const refreshAfterBoot = Effect.gen(function* () { export const refreshAfterBoot = Effect.gen(function* () {
const location = yield* Location.Service const location = yield* Location.Service
const boot = yield* PluginBoot.Service
const copies = yield* Service const copies = yield* Service
yield* Effect.gen(function* () { yield* Effect.gen(function* () {
yield* boot.wait()
yield* Effect.logInfo("project copy refresh started", { projectID: location.project.id }) yield* Effect.logInfo("project copy refresh started", { projectID: location.project.id })
const result = yield* copies.refresh({ projectID: location.project.id }) const result = yield* copies.refresh({ projectID: location.project.id })
yield* Effect.logInfo("project copy refresh done", { yield* Effect.logInfo("project copy refresh done", {
+6 -1
View File
@@ -1,7 +1,7 @@
export * as ProviderV2 from "./provider" export * as ProviderV2 from "./provider"
import { withStatics } from "./schema" import { withStatics } from "./schema"
import { Schema } from "effect" import { Schema, Types } from "effect"
export const ID = Schema.String.pipe( export const ID = Schema.String.pipe(
Schema.brand("ProviderV2.ID"), Schema.brand("ProviderV2.ID"),
@@ -37,6 +37,9 @@ export const Native = Schema.Struct({
export const Api = Schema.Union([AISDK, Native]).pipe(Schema.toTaggedUnion("type")) export const Api = Schema.Union([AISDK, Native]).pipe(Schema.toTaggedUnion("type"))
export type Api = typeof Api.Type export type Api = typeof Api.Type
export type MutableApi<T extends Api = Api> = T extends Api
? Omit<Types.DeepMutable<T>, "settings"> & (undefined extends T["settings"] ? { settings?: any } : { settings: any })
: never
export const Request = Schema.Struct({ export const Request = Schema.Struct({
headers: Schema.Record(Schema.String, Schema.String), headers: Schema.Record(Schema.String, Schema.String),
@@ -66,3 +69,5 @@ export class Info extends Schema.Class<Info>("ProviderV2.Info")({
}) })
} }
} }
export type MutableInfo = Omit<Types.DeepMutable<Info>, "api"> & { api: MutableApi }
+5 -58
View File
@@ -1,11 +1,9 @@
export * as OpenCode from "./opencode" export * as OpenCode from "./opencode"
import { Context, Effect, Layer } from "effect" import { Context, Effect, Layer } from "effect"
import { Catalog } from "../catalog"
import { Database } from "../database/database" import { Database } from "../database/database"
import { EventV2 } from "../event" import { EventV2 } from "../event"
import { LocationServiceMap } from "../location-layer" import { LocationServiceMap } from "../location-layer"
import { PluginBoot } from "../plugin/boot"
import { ProjectV2 } from "../project" import { ProjectV2 } from "../project"
import { SessionV2 } from "../session" import { SessionV2 } from "../session"
import * as SessionExecutionLocal from "../session/execution/local" import * as SessionExecutionLocal from "../session/execution/local"
@@ -23,69 +21,22 @@ export interface Interface {
/** Intentional public native API for Effect applications embedding OpenCode. */ /** Intentional public native API for Effect applications embedding OpenCode. */
export class Service extends Context.Service<Service, Interface>()("@opencode/public/OpenCode") {} export class Service extends Context.Service<Service, Interface>()("@opencode/public/OpenCode") {}
class SessionModelValidation extends Context.Service< const SessionsLayer = SessionV2.layer.pipe(
SessionModelValidation,
{
readonly validate: (
input: Session.SwitchModelInput & { readonly location: Session.Info["location"] },
) => Effect.Effect<void, Session.ModelUnavailableError | Session.VariantUnavailableError>
}
>()("@opencode/public/OpenCode/SessionModelValidation") {}
const ApplicationToolsLayer = ApplicationTools.layer
const LocationServicesLayer = LocationServiceMap.layer.pipe(Layer.provide(ApplicationToolsLayer))
const SessionModelValidationLayer = Layer.effect(
SessionModelValidation,
Effect.gen(function* () {
const locations = yield* LocationServiceMap
return SessionModelValidation.of({
validate: Effect.fn("OpenCode.sessions.validateModel")(function* (input) {
yield* Effect.gen(function* () {
yield* (yield* PluginBoot.Service).wait()
const catalog = yield* Catalog.Service
const model = (yield* catalog.model.available()).find(
(model) => model.providerID === input.model.providerID && model.id === input.model.id,
)
if (!model)
return yield* new Session.ModelUnavailableError({
providerID: input.model.providerID,
modelID: input.model.id,
})
if (
input.model.variant !== undefined &&
input.model.variant !== "default" &&
!model.variants.some((variant) => variant.id === input.model.variant)
)
return yield* new Session.VariantUnavailableError({
providerID: input.model.providerID,
modelID: input.model.id,
variant: input.model.variant,
})
}).pipe(Effect.provide(locations.get(input.location)))
}),
})
}),
)
const SessionsLayer = Layer.merge(
SessionV2.layer.pipe(
Layer.provide(SessionProjector.layer), Layer.provide(SessionProjector.layer),
Layer.provide(SessionExecutionLocal.layer), Layer.provide(SessionExecutionLocal.layer),
Layer.provide(SessionStore.layer), Layer.provide(SessionStore.layer),
Layer.provide(EventV2.layer), Layer.provide(EventV2.layer),
Layer.provide(Database.defaultLayer), Layer.provide(Database.defaultLayer),
Layer.provide(ProjectV2.defaultLayer), Layer.provide(ProjectV2.defaultLayer),
Layer.provide(LocationServiceMap.layer.pipe(Layer.provide(ApplicationTools.layer))),
Layer.orDie, Layer.orDie,
), )
SessionModelValidationLayer,
).pipe(Layer.provide(LocationServicesLayer))
// TODO: Accept explicit storage so tests and embeddings can select disposable or application-owned persistence. // TODO: Accept explicit storage so tests and embeddings can select disposable or application-owned persistence.
export const layer = Layer.effect( export const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const sessions = yield* SessionV2.Service const sessions = yield* SessionV2.Service
const tools = yield* ApplicationTools.Service const tools = yield* ApplicationTools.Service
const validation = yield* SessionModelValidation
return Service.of({ return Service.of({
tools: { register: tools.register }, tools: { register: tools.register },
sessions: { sessions: {
@@ -98,11 +49,7 @@ export const layer = Layer.effect(
}), }),
get: sessions.get, get: sessions.get,
list: sessions.list, list: sessions.list,
switchModel: Effect.fn("OpenCode.sessions.switchModel")(function* (input) { switchModel: sessions.switchModel,
const session = yield* sessions.get(input.sessionID)
yield* validation.validate({ ...input, location: session.location })
yield* sessions.switchModel(input)
}),
interrupt: sessions.interrupt, interrupt: sessions.interrupt,
prompt: (input) => prompt: (input) =>
sessions.prompt({ sessions.prompt({
@@ -124,6 +71,6 @@ export const layer = Layer.effect(
}, },
}) })
}), }),
).pipe(Layer.provide(Layer.merge(ApplicationToolsLayer, SessionsLayer))) ).pipe(Layer.provide(Layer.merge(ApplicationTools.layer, SessionsLayer)))
// TODO: Add OpenCode.create(...) as the Promise facade over the same native API semantics. // TODO: Add OpenCode.create(...) as the Promise facade over the same native API semantics.
+4 -27
View File
@@ -1,8 +1,6 @@
export * as Session from "./session" export * as Session from "./session"
import { Effect, Schema, Stream } from "effect" import { Effect, Stream } from "effect"
import { EventV2 } from "../event"
import { ModelV2 } from "../model"
import { SessionV2 } from "../session" import { SessionV2 } from "../session"
import { MessageDecodeError } from "../session/error" import { MessageDecodeError } from "../session/error"
import { SessionEvent } from "../session/event" import { SessionEvent } from "../session/event"
@@ -34,9 +32,7 @@ export type Delivery = SessionInput.Delivery
export const ListInput = SessionV2.ListInput export const ListInput = SessionV2.ListInput
export type ListInput = SessionV2.ListInput export type ListInput = SessionV2.ListInput
export const EventCursor = EventV2.Cursor export type Event = SessionEvent.DurableEvent
export type EventCursor = EventV2.Cursor
export type Event = EventV2.CursorEvent<SessionEvent.DurableEvent>
export const NotFoundError = SessionV2.NotFoundError export const NotFoundError = SessionV2.NotFoundError
export type NotFoundError = SessionV2.NotFoundError export type NotFoundError = SessionV2.NotFoundError
@@ -44,23 +40,6 @@ export type NotFoundError = SessionV2.NotFoundError
export const PromptConflictError = SessionV2.PromptConflictError export const PromptConflictError = SessionV2.PromptConflictError
export type PromptConflictError = SessionV2.PromptConflictError export type PromptConflictError = SessionV2.PromptConflictError
export class ModelUnavailableError extends Schema.TaggedErrorClass<ModelUnavailableError>()(
"Session.ModelUnavailableError",
{
providerID: Model.Ref.fields.providerID,
modelID: Model.Ref.fields.id,
},
) {}
export class VariantUnavailableError extends Schema.TaggedErrorClass<VariantUnavailableError>()(
"Session.VariantUnavailableError",
{
providerID: Model.Ref.fields.providerID,
modelID: Model.Ref.fields.id,
variant: ModelV2.VariantID,
},
) {}
export { MessageDecodeError } export { MessageDecodeError }
export interface CreateInput { export interface CreateInput {
@@ -99,7 +78,7 @@ export interface MessageInput {
export interface EventsInput { export interface EventsInput {
readonly sessionID: ID readonly sessionID: ID
readonly after?: EventCursor readonly after?: number
} }
export interface Interface { export interface Interface {
@@ -107,9 +86,7 @@ export interface Interface {
readonly get: (sessionID: ID) => Effect.Effect<Info, NotFoundError> readonly get: (sessionID: ID) => Effect.Effect<Info, NotFoundError>
readonly list: (input?: ListInput) => Effect.Effect<Info[]> readonly list: (input?: ListInput) => Effect.Effect<Info[]>
readonly prompt: (input: PromptInput) => Effect.Effect<Admission, NotFoundError | PromptConflictError> readonly prompt: (input: PromptInput) => Effect.Effect<Admission, NotFoundError | PromptConflictError>
readonly switchModel: ( readonly switchModel: (input: SwitchModelInput) => Effect.Effect<void, NotFoundError>
input: SwitchModelInput,
) => Effect.Effect<void, NotFoundError | ModelUnavailableError | VariantUnavailableError>
/** Interrupt the active V2 execution chain for one Session on this process. Interrupting an idle or missing Session is a no-op. */ /** Interrupt the active V2 execution chain for one Session on this process. Interrupting an idle or missing Session is a no-op. */
readonly interrupt: (sessionID: ID) => Effect.Effect<void> readonly interrupt: (sessionID: ID) => Effect.Effect<void>
readonly messages: (input: MessagesInput) => Effect.Effect<Message[], NotFoundError | MessageDecodeError> readonly messages: (input: MessagesInput) => Effect.Effect<Message[], NotFoundError | MessageDecodeError>
+10 -11
View File
@@ -1,7 +1,6 @@
export * as Reference from "./reference" export * as Reference from "./reference"
import { Context, Effect, Layer, Schema, Scope } from "effect" import { Context, Effect, Layer, Schema, Scope, Types } from "effect"
import { castDraft } from "immer"
import { Global } from "./global" import { Global } from "./global"
import { EventV2 } from "./event" import { EventV2 } from "./event"
import { Repository } from "./repository" import { Repository } from "./repository"
@@ -40,17 +39,16 @@ export class Info extends Schema.Class<Info>("Reference.Info")({
}) {} }) {}
type Data = { type Data = {
sources: Map<string, Source> sources: Map<string, Types.DeepMutable<Source>>
} }
type Editor = { type Draft = {
add(name: string, source: Source): void add(name: string, source: Source): void
remove(name: string): void remove(name: string): void
list(): readonly [string, Source][] list(): readonly [string, Source][]
} }
export interface Interface { export interface Interface extends State.Transformable<Draft> {
readonly transform: State.Interface<Data, Editor>["transform"]
readonly list: () => Effect.Effect<Info[]> readonly list: () => Effect.Effect<Info[]>
} }
@@ -64,18 +62,18 @@ export const layer = Layer.effect(
const cache = yield* RepositoryCache.Service const cache = yield* RepositoryCache.Service
const scope = yield* Scope.Scope const scope = yield* Scope.Scope
const materialized = new Map<string, Info>() const materialized = new Map<string, Info>()
const state = State.create<Data, Editor>({ const state = State.create<Data, Draft>({
initial: () => ({ sources: new Map() }), initial: () => ({ sources: new Map() }),
editor: (draft) => ({ draft: (draft) => ({
add: (name, source) => draft.sources.set(name, castDraft(source)), add: (name, source) => draft.sources.set(name, source as Types.DeepMutable<Source>),
remove: (name) => draft.sources.delete(name), remove: (name) => draft.sources.delete(name),
list: () => Array.from(draft.sources.entries()) as [string, Source][], list: () => Array.from(draft.sources.entries()) as [string, Source][],
}), }),
finalize: (editor) => finalize: (draft) =>
Effect.gen(function* () { Effect.gen(function* () {
materialized.clear() materialized.clear()
const seen = new Map<string, string | undefined>() const seen = new Map<string, string | undefined>()
for (const [name, source] of editor.list()) { for (const [name, source] of draft.list()) {
if (source.type === "local") { if (source.type === "local") {
materialized.set( materialized.set(
name, name,
@@ -128,6 +126,7 @@ export const layer = Layer.effect(
return Service.of({ return Service.of({
transform: state.transform, transform: state.transform,
reload: state.reload,
list: Effect.fn("Reference.list")(function* () { list: Effect.fn("Reference.list")(function* () {
return Array.from(materialized.values()) return Array.from(materialized.values())
}), }),
-3
View File
@@ -1,7 +1,6 @@
export * as ReferenceGuidance from "./guidance" export * as ReferenceGuidance from "./guidance"
import { Context, Effect, Layer, Schema } from "effect" import { Context, Effect, Layer, Schema } from "effect"
import { PluginBoot } from "../plugin/boot"
import { Reference } from "../reference" import { Reference } from "../reference"
import { SystemContext } from "../system-context/index" import { SystemContext } from "../system-context/index"
@@ -34,12 +33,10 @@ export class Service extends Context.Service<Service, Interface>()("@opencode/v2
export const layer = Layer.effect( export const layer = Layer.effect(
Service, Service,
Effect.gen(function* () { Effect.gen(function* () {
const boot = yield* PluginBoot.Service
const references = yield* Reference.Service const references = yield* Reference.Service
return Service.of({ return Service.of({
load: Effect.fn("ReferenceGuidance.load")(function* () { load: Effect.fn("ReferenceGuidance.load")(function* () {
yield* boot.wait()
const available = (yield* references.list()) const available = (yield* references.list())
.filter((reference) => reference.description !== undefined) .filter((reference) => reference.description !== undefined)
.map((reference) => ({ .map((reference) => ({
+1 -1
View File
@@ -42,7 +42,7 @@ type RawMatchData = (typeof RawMatch.Type)["data"]
export class Error extends Schema.TaggedErrorClass<Error>()("Ripgrep.Error", { export class Error extends Schema.TaggedErrorClass<Error>()("Ripgrep.Error", {
message: Schema.String, message: Schema.String,
cause: Schema.optional(Schema.Defect), cause: Schema.optional(Schema.Defect()),
}) {} }) {}
export class InvalidPatternError extends Schema.TaggedErrorClass<InvalidPatternError>()("Ripgrep.InvalidPatternError", { export class InvalidPatternError extends Schema.TaggedErrorClass<InvalidPatternError>()("Ripgrep.InvalidPatternError", {

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