diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000000..b6d8d73512ff --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +.git +.opencode +.sst +.turbo +.wrangler +node_modules +**/node_modules +**/.output +**/dist +**/.turbo +**/.vite +**/coverage diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index 96234eb25d9a..da82bde2e12d 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -1,5 +1,5 @@ name: Bug report -description: Report an issue that should be fixed +description: Report an issue that should be fixed (avoid pasting giant AI generated summaries or your issue may be closed/ignored) body: - type: textarea id: description diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 68f00dd4a4f4..18e6cf7acb44 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -9,9 +9,15 @@ on: concurrency: ${{ github.workflow }}-${{ github.ref }} +permissions: + contents: read + id-token: write + jobs: deploy: + if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'production') runs-on: ubuntu-latest + environment: ${{ github.ref_name }} steps: - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 @@ -21,6 +27,12 @@ jobs: with: node-version: "24" + - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 + with: + role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }} + role-session-name: opencode-${{ github.run_id }} + aws-region: us-east-1 + - run: bun sst deploy --stage=${{ github.ref_name }} env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index 0ae2fbe26bc4..7f07577f8c2f 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -2,6 +2,9 @@ "$schema": "https://opencode.ai/config.json", "provider": {}, "permission": {}, + "reference": { + "effect": "github.com/Effect-TS/effect-smol", + }, "mcp": {}, "tools": { "github-triage": false, diff --git a/.opencode/skills/improve-codebase-architecture/DEEPENING.md b/.opencode/skills/improve-codebase-architecture/DEEPENING.md deleted file mode 100644 index c52fdfd99f35..000000000000 --- a/.opencode/skills/improve-codebase-architecture/DEEPENING.md +++ /dev/null @@ -1,37 +0,0 @@ -# Deepening - -How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**. - -## Dependency categories - -When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. - -### 1. In-process - -Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed. - -### 2. Local-substitutable - -Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. - -### 3. Remote but owned (Ports & Adapters) - -Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. - -Recommendation shape: _"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."_ - -### 4. True external (Mock) - -Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. - -## Seam discipline - -- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. -- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. - -## Testing strategy: replace, don't layer - -- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them. -- Write new tests at the deepened module's interface. The **interface is the test surface**. -- Tests assert on observable outcomes through the interface, not internal state. -- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.opencode/skills/improve-codebase-architecture/INTERFACE-DESIGN.md b/.opencode/skills/improve-codebase-architecture/INTERFACE-DESIGN.md deleted file mode 100644 index 3197723a0d04..000000000000 --- a/.opencode/skills/improve-codebase-architecture/INTERFACE-DESIGN.md +++ /dev/null @@ -1,44 +0,0 @@ -# Interface Design - -When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best. - -Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**. - -## Process - -### 1. Frame the problem space - -Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: - -- The constraints any new interface would need to satisfy -- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) -- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete - -Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. - -### 2. Spawn sub-agents - -Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module. - -Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: - -- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point." -- Agent 2: "Maximise flexibility — support many use cases and extension." -- Agent 3: "Optimise for the most common caller — make the default case trivial." -- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." - -Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. - -Each sub-agent outputs: - -1. Interface (types, methods, params — plus invariants, ordering, error modes) -2. Usage example showing how callers use it -3. What the implementation hides behind the seam -4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) -5. Trade-offs — where leverage is high, where it's thin - -### 3. Present and compare - -Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. - -After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu. diff --git a/.opencode/skills/improve-codebase-architecture/LANGUAGE.md b/.opencode/skills/improve-codebase-architecture/LANGUAGE.md deleted file mode 100644 index dd9b60fea072..000000000000 --- a/.opencode/skills/improve-codebase-architecture/LANGUAGE.md +++ /dev/null @@ -1,53 +0,0 @@ -# Language - -Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. - -## Terms - -**Module** -Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice. -_Avoid_: unit, component, service. - -**Interface** -Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. -_Avoid_: API, signature (too narrow — those refer only to the type-level surface). - -**Implementation** -What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. - -**Depth** -Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation. - -**Seam** _(from Michael Feathers)_ -A place where you can alter behaviour without editing in that place. The _location_ at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it. -_Avoid_: boundary (overloaded with DDD's bounded context). - -**Adapter** -A concrete thing that satisfies an interface at a seam. Describes _role_ (what slot it fills), not substance (what's inside). - -**Leverage** -What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests. - -**Locality** -What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere. - -## Principles - -- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. -- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep. -- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test _past_ the interface, the module is probably the wrong shape. -- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. - -## Relationships - -- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). -- **Depth** is a property of a **Module**, measured against its **Interface**. -- A **Seam** is where a **Module**'s **Interface** lives. -- An **Adapter** sits at a **Seam** and satisfies the **Interface**. -- **Depth** produces **Leverage** for callers and **Locality** for maintainers. - -## Rejected framings - -- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. -- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know. -- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. diff --git a/.opencode/skills/improve-codebase-architecture/SKILL.md b/.opencode/skills/improve-codebase-architecture/SKILL.md deleted file mode 100644 index 05984a609682..000000000000 --- a/.opencode/skills/improve-codebase-architecture/SKILL.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -name: improve-codebase-architecture -description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable. ---- - -# Improve Codebase Architecture - -Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. - -## Glossary - -Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md). - -- **Module** — anything with an interface and an implementation (function, class, package, slice). -- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature. -- **Implementation** — the code inside. -- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation. -- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.") -- **Adapter** — a concrete thing satisfying an interface at a seam. -- **Leverage** — what callers get from depth. -- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place. - -Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list): - -- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. -- **The interface is the test surface.** -- **One adapter = hypothetical seam. Two adapters = real seam.** - -This skill is _informed_ by the project's domain model. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate. - -## Process - -### 1. Explore - -Read the project's domain glossary and any ADRs in the area you're touching first. - -Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction: - -- Where does understanding one concept require bouncing between many small modules? -- Where are modules **shallow** — interface nearly as complex as the implementation? -- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? -- Where do tightly-coupled modules leak across their seams? -- Which parts of the codebase are untested, or hard to test through their current interface? - -Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. - -### 2. Present candidates - -Present a numbered list of deepening opportunities. For each candidate: - -- **Files** — which files/modules are involved -- **Problem** — why the current architecture is causing friction -- **Solution** — plain English description of what would change -- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve - -**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service." - -**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. - -Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?" - -### 3. Grilling loop - -Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. - -Side effects happen inline as decisions crystallize: - -- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/grill-with-docs` (see [CONTEXT-FORMAT.md](../grill-with-docs/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist. -- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there. -- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../grill-with-docs/ADR-FORMAT.md). -- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md). diff --git a/AGENTS.md b/AGENTS.md index 8e7ff342b5d2..1ee5be8b0f23 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,8 +1,6 @@ - To regenerate the JavaScript SDK, run `./packages/sdk/js/script/build.ts`. -- ALWAYS USE PARALLEL TOOLS WHEN APPLICABLE. - The default branch in this repo is `dev`. - Local `main` ref may not exist; use `dev` or `origin/dev` for diffs. -- Prefer automation: execute requested actions without confirmation unless blocked by missing info or safety/irreversibility. ## Commits and PR Titles @@ -49,6 +47,12 @@ obj.b const { a, b } = obj ``` +### Imports + +- Never alias imports. Do not use `import { foo as bar } from "..."` or renamed imports like `resolve as pathResolve`. +- Never use star imports. Do not use `import * as Foo from "..."` or `import type * as Foo from "..."`. +- If a namespace-style value is needed, import the module's own exported namespace by name, for example `import { Project } from "@opencode-ai/core/project"`, then reference `Project.ID`. + ### Variables Prefer `const` over `let`. Use ternaries or early returns instead of reassignment. diff --git a/bun.lock b/bun.lock index 45b3aa10c631..52b42c7fbaeb 100644 --- a/bun.lock +++ b/bun.lock @@ -23,7 +23,7 @@ "oxlint-tsgolint": "0.21.0", "prettier": "3.6.2", "semver": "^7.6.0", - "sst": "4.13.1", + "sst": "catalog:", "turbo": "2.8.13", }, }, @@ -83,6 +83,23 @@ "vite-plugin-solid": "catalog:", }, }, + "packages/cli": { + "name": "@opencode-ai/cli", + "version": "1.15.13", + "bin": { + "opencode": "./src/index.ts", + }, + "dependencies": { + "@effect/platform-node": "catalog:", + "@opencode-ai/core": "workspace:*", + "effect": "catalog:", + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:", + }, + }, "packages/console/app": { "name": "@opencode-ai/console-app", "version": "1.7.13", @@ -192,9 +209,29 @@ "cloudflare": "5.2.0", }, }, + "packages/console/support": { + "name": "@opencode-ai/console-support", + "version": "1.15.13", + "dependencies": { + "@cloudflare/vite-plugin": "1.15.2", + "@opencode-ai/console-core": "workspace:*", + "@solidjs/meta": "catalog:", + "@solidjs/router": "catalog:", + "@solidjs/start": "catalog:", + "nitro": "3.0.1-alpha.1", + "solid-js": "catalog:", + "vite": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:", + "typescript": "catalog:", + "wrangler": "4.50.0", + }, + }, "packages/core": { "name": "@opencode-ai/core", - "version": "1.15.10", + "version": "1.15.13", "bin": { "opencode": "./bin/opencode", }, @@ -207,8 +244,8 @@ "@ai-sdk/cohere": "3.0.27", "@ai-sdk/deepinfra": "2.0.41", "@ai-sdk/gateway": "3.0.104", - "@ai-sdk/google": "3.0.75", - "@ai-sdk/google-vertex": "4.0.131", + "@ai-sdk/google": "3.0.73", + "@ai-sdk/google-vertex": "4.0.128", "@ai-sdk/groq": "3.0.31", "@ai-sdk/mistral": "3.0.27", "@ai-sdk/openai": "3.0.53", @@ -222,8 +259,11 @@ "@aws-sdk/credential-providers": "3.993.0", "@effect/opentelemetry": "catalog:", "@effect/platform-node": "catalog:", + "@effect/sql-sqlite-bun": "catalog:", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", + "@opencode-ai/effect-drizzle-sqlite": "workspace:*", + "@opencode-ai/effect-sqlite-node": "workspace:*", "@openrouter/ai-sdk-provider": "2.8.1", "@opentelemetry/api": "1.9.0", "@opentelemetry/context-async-hooks": "2.6.1", @@ -231,11 +271,13 @@ "@opentelemetry/sdk-trace-base": "2.6.1", "ai-gateway-provider": "3.1.2", "cross-spawn": "catalog:", + "drizzle-orm": "catalog:", "effect": "catalog:", - "gitlab-ai-provider": "6.7.0", + "gitlab-ai-provider": "6.8.0", "glob": "13.0.5", "google-auth-library": "10.5.0", "immer": "11.1.4", + "jsonc-parser": "3.3.1", "mime-types": "3.0.2", "minimatch": "10.2.5", "npm-package-arg": "13.0.2", @@ -251,6 +293,7 @@ "@types/npm-package-arg": "6.1.4", "@types/npmcli__arborist": "6.3.3", "@types/semver": "catalog:", + "drizzle-kit": "catalog:", }, }, "packages/desktop": { @@ -292,12 +335,12 @@ "zod-openapi": "5.4.6", }, "optionalDependencies": { - "@lydell/node-pty-darwin-arm64": "1.2.0-beta.10", - "@lydell/node-pty-darwin-x64": "1.2.0-beta.10", - "@lydell/node-pty-linux-arm64": "1.2.0-beta.10", - "@lydell/node-pty-linux-x64": "1.2.0-beta.10", - "@lydell/node-pty-win32-arm64": "1.2.0-beta.10", - "@lydell/node-pty-win32-x64": "1.2.0-beta.10", + "@lydell/node-pty-darwin-arm64": "1.2.0-beta.12", + "@lydell/node-pty-darwin-x64": "1.2.0-beta.12", + "@lydell/node-pty-linux-arm64": "1.2.0-beta.12", + "@lydell/node-pty-linux-x64": "1.2.0-beta.12", + "@lydell/node-pty-win32-arm64": "1.2.0-beta.12", + "@lydell/node-pty-win32-x64": "1.2.0-beta.12", "@parcel/watcher-darwin-arm64": "2.5.1", "@parcel/watcher-darwin-x64": "2.5.1", "@parcel/watcher-linux-arm64-glibc": "2.5.1", @@ -310,7 +353,7 @@ }, "packages/effect-drizzle-sqlite": { "name": "@opencode-ai/effect-drizzle-sqlite", - "version": "1.15.10", + "version": "1.15.13", "dependencies": { "drizzle-orm": "catalog:", "effect": "catalog:", @@ -322,6 +365,18 @@ "@typescript/native-preview": "catalog:", }, }, + "packages/effect-sqlite-node": { + "name": "@opencode-ai/effect-sqlite-node", + "version": "1.15.10", + "dependencies": { + "effect": "catalog:", + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/node": "catalog:", + "@typescript/native-preview": "catalog:", + }, + }, "packages/enterprise": { "name": "@opencode-ai/enterprise", "version": "1.7.13", @@ -370,7 +425,7 @@ }, "packages/http-recorder": { "name": "@opencode-ai/http-recorder", - "version": "1.15.10", + "version": "1.15.13", "dependencies": { "@effect/platform-node": "catalog:", "effect": "catalog:", @@ -383,7 +438,7 @@ }, "packages/llm": { "name": "@opencode-ai/llm", - "version": "1.15.10", + "version": "1.15.13", "dependencies": { "@smithy/eventstream-codec": "4.2.14", "@smithy/util-utf8": "4.2.2", @@ -417,8 +472,8 @@ "@ai-sdk/cohere": "3.0.27", "@ai-sdk/deepinfra": "2.0.41", "@ai-sdk/gateway": "3.0.104", - "@ai-sdk/google": "3.0.75", - "@ai-sdk/google-vertex": "4.0.131", + "@ai-sdk/google": "3.0.73", + "@ai-sdk/google-vertex": "4.0.128", "@ai-sdk/groq": "3.0.31", "@ai-sdk/mistral": "3.0.27", "@ai-sdk/openai": "3.0.53", @@ -458,6 +513,7 @@ "@solid-primitives/event-bus": "1.1.2", "@solid-primitives/scheduled": "1.5.2", "@standard-schema/spec": "1.0.0", + "@types/ws": "8.18.1", "@zip.js/zip.js": "2.7.62", "ai": "catalog:", "ai-gateway-provider": "3.1.2", @@ -471,7 +527,7 @@ "drizzle-orm": "catalog:", "effect": "catalog:", "fuzzysort": "3.1.0", - "gitlab-ai-provider": "6.7.0", + "gitlab-ai-provider": "6.8.0", "glob": "13.0.5", "google-auth-library": "10.5.0", "gray-matter": "4.0.3", @@ -498,6 +554,7 @@ "vscode-jsonrpc": "8.2.1", "web-tree-sitter": "0.25.10", "which": "6.0.1", + "ws": "8.21.0", "xdg-basedir": "5.1.0", "yargs": "18.0.0", "zod": "catalog:", @@ -528,7 +585,6 @@ "@types/which": "3.0.4", "@types/yargs": "17.0.33", "@typescript/native-preview": "catalog:", - "drizzle-kit": "catalog:", "drizzle-orm": "catalog:", "prettier": "3.6.2", "typescript": "catalog:", @@ -554,9 +610,9 @@ "typescript": "catalog:", }, "peerDependencies": { - "@opentui/core": ">=0.2.15", - "@opentui/keymap": ">=0.2.15", - "@opentui/solid": ">=0.2.15", + "@opentui/core": ">=0.3.1", + "@opentui/keymap": ">=0.3.1", + "@opentui/solid": ">=0.3.1", }, "optionalPeers": [ "@opentui/core", @@ -602,6 +658,68 @@ "typescript": "catalog:", }, }, + "packages/stats/app": { + "name": "@opencode-ai/stats-app", + "version": "1.15.13", + "dependencies": { + "@ibm/plex": "6.4.1", + "@opencode-ai/stats-core": "workspace:*", + "@opencode-ai/ui": "workspace:*", + "@solidjs/meta": "catalog:", + "@solidjs/router": "catalog:", + "@solidjs/start": "catalog:", + "d3-scale": "4.0.2", + "effect": "catalog:", + "nitro": "3.0.1-alpha.1", + "solid-js": "catalog:", + "sst": "catalog:", + "vite": "catalog:", + }, + "devDependencies": { + "@cloudflare/workers-types": "catalog:", + "@types/bun": "catalog:", + "@types/d3-scale": "4.0.9", + "@typescript/native-preview": "catalog:", + "typescript": "catalog:", + }, + }, + "packages/stats/core": { + "name": "@opencode-ai/stats-core", + "version": "1.15.13", + "dependencies": { + "@aws-sdk/client-athena": "3.933.0", + "@planetscale/database": "1.19.0", + "drizzle-orm": "catalog:", + "effect": "catalog:", + "sst": "catalog:", + }, + "devDependencies": { + "@tsconfig/node22": "catalog:", + "@types/bun": "catalog:", + "@types/node": "catalog:", + "@typescript/native-preview": "catalog:", + "drizzle-kit": "catalog:", + "typescript": "catalog:", + }, + }, + "packages/stats/server": { + "name": "@opencode-ai/stats-server", + "version": "1.15.13", + "dependencies": { + "@aws-sdk/client-firehose": "3.933.0", + "@effect/platform-node": "catalog:", + "@opencode-ai/stats-core": "workspace:*", + "effect": "catalog:", + "sst": "catalog:", + }, + "devDependencies": { + "@tsconfig/node22": "catalog:", + "@types/bun": "catalog:", + "@types/node": "catalog:", + "@typescript/native-preview": "catalog:", + "typescript": "catalog:", + }, + }, "packages/storybook": { "name": "@opencode-ai/storybook", "devDependencies": { @@ -718,10 +836,10 @@ ], "patchedDependencies": { "solid-js@1.9.10": "patches/solid-js@1.9.10.patch", - "@ai-sdk/xai@3.0.82": "patches/@ai-sdk%2Fxai@3.0.82.patch", "virtua@0.49.1": "patches/virtua@0.49.1.patch", + "gcp-metadata@8.1.2": "patches/gcp-metadata@8.1.2.patch", + "@ai-sdk/xai@3.0.82": "patches/@ai-sdk%2Fxai@3.0.82.patch", "@standard-community/standard-openapi@0.2.9": "patches/@standard-community%2Fstandard-openapi@0.2.9.patch", - "@npmcli/agent@4.0.0": "patches/@npmcli%2Fagent@4.0.0.patch", "@silvia-odwyer/photon-node@0.3.4": "patches/@silvia-odwyer%2Fphoton-node@0.3.4.patch", }, "overrides": { @@ -738,13 +856,13 @@ "@effect/sql-sqlite-bun": "4.0.0-beta.66", "@hono/zod-validator": "0.4.2", "@kobalte/core": "0.13.11", - "@lydell/node-pty": "1.2.0-beta.10", + "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", "@octokit/rest": "22.0.0", "@openauthjs/openauth": "0.0.0-20250322224806", - "@opentui/core": "0.2.15", - "@opentui/keymap": "0.2.15", - "@opentui/solid": "0.2.15", + "@opentui/core": "0.3.1", + "@opentui/keymap": "0.3.1", + "@opentui/solid": "0.3.1", "@pierre/diffs": "1.1.0-beta.18", "@playwright/test": "1.59.1", "@sentry/solid": "10.36.0", @@ -782,6 +900,7 @@ "shiki": "3.20.0", "solid-js": "1.9.10", "solid-list": "0.3.0", + "sst": "4.13.1", "tailwindcss": "4.1.11", "typescript": "5.8.2", "ulid": "3.0.1", @@ -805,7 +924,7 @@ "@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="], - "@adobe/css-tools": ["@adobe/css-tools@4.4.4", "", {}, "sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg=="], + "@adobe/css-tools": ["@adobe/css-tools@4.5.0", "", {}, "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q=="], "@agentclientprotocol/sdk": ["@agentclientprotocol/sdk@0.21.0", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-ONj+Q8qOdNQp5XbH5jnMwzT9IKZJsSN0p0lkceS4GtUtNOPVLpNzSS8gqQdGMKfBvA0ESbkL8BTaSN1Rc9miEw=="], @@ -821,21 +940,21 @@ "@ai-sdk/cohere": ["@ai-sdk/cohere@3.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OqcCq2PiFY1dbK/0Ck45KuvE8jfdxRuuAE9Y5w46dAk6U+9vPOeg1CDcmR+ncqmrYrhRl3nmyDttyDahyjCzAw=="], - "@ai-sdk/deepgram": ["@ai-sdk/deepgram@2.0.29", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OqzitR171deAOWTmdqkP6okGrOvDzdDxqLnW7040OjdfsuyhtR26iL6v+zPGUtmVukwWrJnKklNbomui8y7+mw=="], + "@ai-sdk/deepgram": ["@ai-sdk/deepgram@2.0.33", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-VscTV68g6sXRY4O1yl72/O8y6+tBDvSQax6bqX06hRKWBGxsJ8Jr3LZsNmZnK9Od5Icx565ijK0QgrlNaN4TdQ=="], "@ai-sdk/deepinfra": ["@ai-sdk/deepinfra@2.0.41", "", { "dependencies": { "@ai-sdk/openai-compatible": "2.0.37", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-y6RoOP7DGWmDSiSxrUSt5p18sbz+Ixe5lMVPmdE7x+Tr5rlrzvftyHhjWHfqlAtoYERZTGFbP6tPW1OfQcrb4A=="], - "@ai-sdk/deepseek": ["@ai-sdk/deepseek@2.0.29", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-cn4+xV0menm/4JKEDElnVGiUilHvi6AD4ZK/sY7DXP/Wb7Yb3Vr86NyYM6mGBE/Shk3mWHoHbzggVnF5x0uMEA=="], + "@ai-sdk/deepseek": ["@ai-sdk/deepseek@2.0.35", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-9DhYurbAvcurOEGN6u2myYDybrrzGfcrkG8hwmFjwTrePW6KCMggm0YxP7e8RkLYcQKqCEMgFlyEB4BM6EmiKg=="], - "@ai-sdk/elevenlabs": ["@ai-sdk/elevenlabs@2.0.29", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-l4t+kgOtDav2P2BJ50gZfhOYbKcGblnD0U8jXOF3WH3dczYmYfTC7JGH1/MTheurSy6UnhLw7ee4wL6StCTQ+w=="], + "@ai-sdk/elevenlabs": ["@ai-sdk/elevenlabs@2.0.33", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-EtvsWfGrqx3OhzJdoi82qH+4yzEPPKZr2utyQ+w8cHKoFeg0+8Lou9Z3uixy73WEwz8Z1+AR8QT9fZ64AWGYPA=="], - "@ai-sdk/fireworks": ["@ai-sdk/fireworks@2.0.46", "", { "dependencies": { "@ai-sdk/openai-compatible": "2.0.41", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-XRKR0zgRyegdmtK5CDUEjlyRp0Fo+XVCdoG+301U1SGtgRIAYG3ObVtgzVJBVpJdHFSLHuYeLTnNiQoUxD7+FQ=="], + "@ai-sdk/fireworks": ["@ai-sdk/fireworks@2.0.53", "", { "dependencies": { "@ai-sdk/openai-compatible": "2.0.48", "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-HjeiGsdxSzrCkOf2l2V+K+opzlqxBtduBq6BCiohAdgQk2KdZmI/67SMkBM6Kdze/BjUXiZlv0d7zNICPhxVDA=="], "@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.104", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ZKX5n74io8VIRlhIMSLWVlvT3sXC8Z7cZ9GHuWBWZDVi96+62AIsWuLGvMfcBA1STYuSoDrp6rIziZmvrTq0TA=="], - "@ai-sdk/google": ["@ai-sdk/google@3.0.75", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-XAm31ftiOrzlb8NjDzT7kw0xw+4lmgFdGFn1QKM73nXFFKyN1kWLESBV75UGNfjXP8X1YJ0YydnMVqO0jaPghw=="], + "@ai-sdk/google": ["@ai-sdk/google@3.0.73", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-o2MuIeyvZrFIeIbnbA8Thrr63irdyUBh0uWBZ2lY6yFeXuE/tcwyXF74bDKS4KvTu84uFpQfpbS/LXHGKKXz+g=="], - "@ai-sdk/google-vertex": ["@ai-sdk/google-vertex@4.0.131", "", { "dependencies": { "@ai-sdk/anthropic": "3.0.78", "@ai-sdk/google": "3.0.75", "@ai-sdk/openai-compatible": "2.0.47", "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27", "google-auth-library": "^10.5.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Oj1X8p0rVgvEoR5OOSxWi6XgzJ3QDlE/n30MZVtpKkCiToYYDyvlvVDGXz3IqhMyUev2JhlcuUk1brScKT01kA=="], + "@ai-sdk/google-vertex": ["@ai-sdk/google-vertex@4.0.128", "", { "dependencies": { "@ai-sdk/anthropic": "3.0.77", "@ai-sdk/google": "3.0.73", "@ai-sdk/openai-compatible": "2.0.47", "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27", "google-auth-library": "^10.5.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-jK8fixb4km2yfgvb9DUFQRpV/jiDB0v9gyxHoHfPydaQvz+CpAz8DTt1quyaM+Wg9G2R8Zo68CYmHbIkUqW2AA=="], "@ai-sdk/groq": ["@ai-sdk/groq@3.0.31", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-XbbugpnFmXGu2TlXiq8KUJskP6/VVbuFcnFIGDzDIB/Chg6XHsNnqrTF80Zxkh0Pd3+NvbM+2Uqrtsndk6bDAg=="], @@ -873,7 +992,7 @@ "@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.7.1", "", {}, "sha512-7dwEVigz9vUWDw3nRwLQ/yH/xYovlUA0ZD86xoeKEBmkz9O6iELG1yri67PgAPW6VLL/xInA4t7H0CK6VmtkKQ=="], - "@astrojs/language-server": ["@astrojs/language-server@2.16.6", "", { "dependencies": { "@astrojs/compiler": "^2.13.1", "@astrojs/yaml2ts": "^0.2.3", "@jridgewell/sourcemap-codec": "^1.5.5", "@volar/kit": "~2.4.28", "@volar/language-core": "~2.4.28", "@volar/language-server": "~2.4.28", "@volar/language-service": "~2.4.28", "muggle-string": "^0.4.1", "tinyglobby": "^0.2.15", "volar-service-css": "0.0.70", "volar-service-emmet": "0.0.70", "volar-service-html": "0.0.70", "volar-service-prettier": "0.0.70", "volar-service-typescript": "0.0.70", "volar-service-typescript-twoslash-queries": "0.0.70", "volar-service-yaml": "0.0.70", "vscode-html-languageservice": "^5.6.2", "vscode-uri": "^3.1.0" }, "peerDependencies": { "prettier": "^3.0.0", "prettier-plugin-astro": ">=0.11.0" }, "optionalPeers": ["prettier", "prettier-plugin-astro"], "bin": { "astro-ls": "bin/nodeServer.js" } }, "sha512-N990lu+HSFiG57owR0XBkr02BYMgiLCshLf+4QG4v6jjSWkBeQGnzqi+E1L08xFPPJ7eEeXnxPXGLaVv5pa4Ug=="], + "@astrojs/language-server": ["@astrojs/language-server@2.16.10", "", { "dependencies": { "@astrojs/compiler": "^2.13.1", "@astrojs/yaml2ts": "^0.2.4", "@jridgewell/sourcemap-codec": "^1.5.5", "@volar/kit": "~2.4.28", "@volar/language-core": "~2.4.28", "@volar/language-server": "~2.4.28", "@volar/language-service": "~2.4.28", "muggle-string": "^0.4.1", "tinyglobby": "^0.2.16", "volar-service-css": "0.0.70", "volar-service-emmet": "0.0.70", "volar-service-html": "0.0.70", "volar-service-prettier": "0.0.70", "volar-service-typescript": "0.0.70", "volar-service-typescript-twoslash-queries": "0.0.70", "volar-service-yaml": "0.0.70", "vscode-html-languageservice": "^5.6.2", "vscode-uri": "^3.1.0" }, "peerDependencies": { "prettier": "^3.0.0", "prettier-plugin-astro": ">=0.11.0" }, "optionalPeers": ["prettier", "prettier-plugin-astro"], "bin": { "astro-ls": "./bin/nodeServer.js" } }, "sha512-87VQ/5GSdHlRnUA+hGuerYyIGAj+9RbZmATyuKLEUePinUXhQ5YkRnRrHhOD9sSi5JOErLjrLkHnfZFEvGrV8w=="], "@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.1", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/prism": "3.2.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.1.0", "js-yaml": "^4.1.0", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.1", "remark-smartypants": "^3.0.2", "shiki": "^3.0.0", "smol-toml": "^1.3.1", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.1", "vfile": "^6.0.3" } }, "sha512-c5F5gGrkczUaTVgmMW9g1YMJGzOtRvjjhw6IfGuxarM6ct09MpwysP10US729dy07gg8y+ofVifezvP3BNsWZg=="], @@ -881,7 +1000,7 @@ "@astrojs/prism": ["@astrojs/prism@3.2.0", "", { "dependencies": { "prismjs": "^1.29.0" } }, "sha512-GilTHKGCW6HMq7y3BUv9Ac7GMe/MO9gi9GW62GzKtth0SwukCu/qp2wLiGpEujhY+VVhaG9v7kv/5vFzvf4NYw=="], - "@astrojs/sitemap": ["@astrojs/sitemap@3.7.2", "", { "dependencies": { "sitemap": "^9.0.0", "stream-replace-string": "^2.0.0", "zod": "^4.3.6" } }, "sha512-PqkzkcZTb5ICiyIR8VoKbIAP/laNRXi5tw616N1Ckk+40oNB8Can1AzVV56lrbC5GKSZFCyJYUVYqVivMisvpA=="], + "@astrojs/sitemap": ["@astrojs/sitemap@3.7.3", "", { "dependencies": { "sitemap": "^9.0.0", "stream-replace-string": "^2.0.0", "zod": "^4.3.6" } }, "sha512-f8euLVsyeAmAkSm/1M2Kb8sL8byQmfgbvBNaHFItCheTj/IpiJYSEWVcqDHZ/yEHxiS7+w87mQkzwZaPHmk5GA=="], "@astrojs/solid-js": ["@astrojs/solid-js@5.1.0", "", { "dependencies": { "vite": "^6.3.5", "vite-plugin-solid": "^2.11.6" }, "peerDependencies": { "solid-devtools": "^0.30.1", "solid-js": "^1.8.5" }, "optionalPeers": ["solid-devtools"] }, "sha512-VmPHOU9k7m6HHCT2Y1mNzifilUnttlowBM36frGcfj5wERJE9Ci0QtWJbzdf6AlcoIirb7xVw+ByupU011Di9w=="], @@ -891,7 +1010,7 @@ "@astrojs/underscore-redirects": ["@astrojs/underscore-redirects@1.0.0", "", {}, "sha512-qZxHwVnmb5FXuvRsaIGaqWgnftjCuMY+GSbaVZdBmE4j8AfgPqKPxYp8SUERyJcjpKCEmO4wD6ybuGH8A2kVRQ=="], - "@astrojs/yaml2ts": ["@astrojs/yaml2ts@0.2.3", "", { "dependencies": { "yaml": "^2.8.2" } }, "sha512-PJzRmgQzUxI2uwpdX2lXSHtP4G8ocp24/t+bZyf5Fy0SZLSF9f9KXZoMlFM/XCGue+B0nH/2IZ7FpBYQATBsCg=="], + "@astrojs/yaml2ts": ["@astrojs/yaml2ts@0.2.4", "", { "dependencies": { "yaml": "^2.8.3" } }, "sha512-8oddpOae35pJsXPQXhTkM0ypfKPskVsh2bCxRtbf7e+/Epw2nReakFYpLKjZMEr75CsoF203PMnCocpfz0s69A=="], "@aws-crypto/crc32": ["@aws-crypto/crc32@5.2.0", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg=="], @@ -907,9 +1026,13 @@ "@aws-crypto/util": ["@aws-crypto/util@5.2.0", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="], + "@aws-sdk/client-athena": ["@aws-sdk/client-athena@3.933.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.932.0", "@aws-sdk/credential-provider-node": "3.933.0", "@aws-sdk/middleware-host-header": "3.930.0", "@aws-sdk/middleware-logger": "3.930.0", "@aws-sdk/middleware-recursion-detection": "3.933.0", "@aws-sdk/middleware-user-agent": "3.932.0", "@aws-sdk/region-config-resolver": "3.930.0", "@aws-sdk/types": "3.930.0", "@aws-sdk/util-endpoints": "3.930.0", "@aws-sdk/util-user-agent-browser": "3.930.0", "@aws-sdk/util-user-agent-node": "3.932.0", "@smithy/config-resolver": "^4.4.3", "@smithy/core": "^3.18.2", "@smithy/fetch-http-handler": "^5.3.6", "@smithy/hash-node": "^4.2.5", "@smithy/invalid-dependency": "^4.2.5", "@smithy/middleware-content-length": "^4.2.5", "@smithy/middleware-endpoint": "^4.3.9", "@smithy/middleware-retry": "^4.4.9", "@smithy/middleware-serde": "^4.2.5", "@smithy/middleware-stack": "^4.2.5", "@smithy/node-config-provider": "^4.3.5", "@smithy/node-http-handler": "^4.4.5", "@smithy/protocol-http": "^5.3.5", "@smithy/smithy-client": "^4.9.5", "@smithy/types": "^4.9.0", "@smithy/url-parser": "^4.2.5", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.8", "@smithy/util-defaults-mode-node": "^4.2.11", "@smithy/util-endpoints": "^3.2.5", "@smithy/util-middleware": "^4.2.5", "@smithy/util-retry": "^4.2.5", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-9eMUCu1Ay3C9ojo+dJcynSdpbxuwDVtZUt/Xhce+c2+mgDsmvRzjww+wfLpZwRNWxBWmeauQQAZk52tCwQgXsQ=="], + "@aws-sdk/client-cognito-identity": ["@aws-sdk/client-cognito-identity@3.993.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.11", "@aws-sdk/credential-provider-node": "^3.972.10", "@aws-sdk/middleware-host-header": "^3.972.3", "@aws-sdk/middleware-logger": "^3.972.3", "@aws-sdk/middleware-recursion-detection": "^3.972.3", "@aws-sdk/middleware-user-agent": "^3.972.11", "@aws-sdk/region-config-resolver": "^3.972.3", "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-endpoints": "3.993.0", "@aws-sdk/util-user-agent-browser": "^3.972.3", "@aws-sdk/util-user-agent-node": "^3.972.9", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.23.2", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.16", "@smithy/middleware-retry": "^4.4.33", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.10", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.11.5", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.32", "@smithy/util-defaults-mode-node": "^4.2.35", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-7Ne3Yk/bgQPVebAkv7W+RfhiwTRSbfER9BtbhOa2w/+dIr902LrJf6vrZlxiqaJbGj2ALx8M+ZK1YIHVxSwu9A=="], - "@aws-sdk/client-lambda": ["@aws-sdk/client-lambda@3.1048.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/credential-provider-node": "^3.972.42", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-ryEYNVdilyWkKsOs/7Xy/l7+qjtSz4sll8NpcWD6AtONxjG/5OMaAhxxDkQb4iBoNMKnISxsARzQAp/Wa8pXIg=="], + "@aws-sdk/client-firehose": ["@aws-sdk/client-firehose@3.933.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.932.0", "@aws-sdk/credential-provider-node": "3.933.0", "@aws-sdk/middleware-host-header": "3.930.0", "@aws-sdk/middleware-logger": "3.930.0", "@aws-sdk/middleware-recursion-detection": "3.933.0", "@aws-sdk/middleware-user-agent": "3.932.0", "@aws-sdk/region-config-resolver": "3.930.0", "@aws-sdk/types": "3.930.0", "@aws-sdk/util-endpoints": "3.930.0", "@aws-sdk/util-user-agent-browser": "3.930.0", "@aws-sdk/util-user-agent-node": "3.932.0", "@smithy/config-resolver": "^4.4.3", "@smithy/core": "^3.18.2", "@smithy/fetch-http-handler": "^5.3.6", "@smithy/hash-node": "^4.2.5", "@smithy/invalid-dependency": "^4.2.5", "@smithy/middleware-content-length": "^4.2.5", "@smithy/middleware-endpoint": "^4.3.9", "@smithy/middleware-retry": "^4.4.9", "@smithy/middleware-serde": "^4.2.5", "@smithy/middleware-stack": "^4.2.5", "@smithy/node-config-provider": "^4.3.5", "@smithy/node-http-handler": "^4.4.5", "@smithy/protocol-http": "^5.3.5", "@smithy/smithy-client": "^4.9.5", "@smithy/types": "^4.9.0", "@smithy/url-parser": "^4.2.5", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.8", "@smithy/util-defaults-mode-node": "^4.2.11", "@smithy/util-endpoints": "^3.2.5", "@smithy/util-middleware": "^4.2.5", "@smithy/util-retry": "^4.2.5", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-tDrtgczN2lQsflLDPYu/wdOoyCZLVYtgzmWnYzSEOBWd/cp2AbuQ7D+FemSwUTzyoMTuhhIevyEJKzqsF+QYxA=="], + + "@aws-sdk/client-lambda": ["@aws-sdk/client-lambda@3.1053.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.13", "@aws-sdk/credential-provider-node": "^3.972.44", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.3", "@smithy/fetch-http-handler": "^5.4.3", "@smithy/node-http-handler": "^4.7.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-rIauaabLL/2C/5GYW6r/j4ptULlsTw2D/81leZ0nrjQVu9LSuAUZBJYLJpMsQobhDon4gfkdMIObOxQY1AHhRA=="], "@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.933.0", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.932.0", "@aws-sdk/credential-provider-node": "3.933.0", "@aws-sdk/middleware-bucket-endpoint": "3.930.0", "@aws-sdk/middleware-expect-continue": "3.930.0", "@aws-sdk/middleware-flexible-checksums": "3.932.0", "@aws-sdk/middleware-host-header": "3.930.0", "@aws-sdk/middleware-location-constraint": "3.930.0", "@aws-sdk/middleware-logger": "3.930.0", "@aws-sdk/middleware-recursion-detection": "3.933.0", "@aws-sdk/middleware-sdk-s3": "3.932.0", "@aws-sdk/middleware-ssec": "3.930.0", "@aws-sdk/middleware-user-agent": "3.932.0", "@aws-sdk/region-config-resolver": "3.930.0", "@aws-sdk/signature-v4-multi-region": "3.932.0", "@aws-sdk/types": "3.930.0", "@aws-sdk/util-endpoints": "3.930.0", "@aws-sdk/util-user-agent-browser": "3.930.0", "@aws-sdk/util-user-agent-node": "3.932.0", "@smithy/config-resolver": "^4.4.3", "@smithy/core": "^3.18.2", "@smithy/eventstream-serde-browser": "^4.2.5", "@smithy/eventstream-serde-config-resolver": "^4.3.5", "@smithy/eventstream-serde-node": "^4.2.5", "@smithy/fetch-http-handler": "^5.3.6", "@smithy/hash-blob-browser": "^4.2.6", "@smithy/hash-node": "^4.2.5", "@smithy/hash-stream-node": "^4.2.5", "@smithy/invalid-dependency": "^4.2.5", "@smithy/md5-js": "^4.2.5", "@smithy/middleware-content-length": "^4.2.5", "@smithy/middleware-endpoint": "^4.3.9", "@smithy/middleware-retry": "^4.4.9", "@smithy/middleware-serde": "^4.2.5", "@smithy/middleware-stack": "^4.2.5", "@smithy/node-config-provider": "^4.3.5", "@smithy/node-http-handler": "^4.4.5", "@smithy/protocol-http": "^5.3.5", "@smithy/smithy-client": "^4.9.5", "@smithy/types": "^4.9.0", "@smithy/url-parser": "^4.2.5", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.8", "@smithy/util-defaults-mode-node": "^4.2.11", "@smithy/util-endpoints": "^3.2.5", "@smithy/util-middleware": "^4.2.5", "@smithy/util-retry": "^4.2.5", "@smithy/util-stream": "^4.5.6", "@smithy/util-utf8": "^4.2.0", "@smithy/util-waiter": "^4.2.5", "tslib": "^2.6.2" } }, "sha512-KxwZvdxdCeWK6o8mpnb+kk7Kgb8V+8AjTwSXUWH1UAD85B0tjdo1cSfE5zoR5fWGol4Ml5RLez12a6LPhsoTqA=="], @@ -919,23 +1042,23 @@ "@aws-sdk/core": ["@aws-sdk/core@3.932.0", "", { "dependencies": { "@aws-sdk/types": "3.930.0", "@aws-sdk/xml-builder": "3.930.0", "@smithy/core": "^3.18.2", "@smithy/node-config-provider": "^4.3.5", "@smithy/property-provider": "^4.2.5", "@smithy/protocol-http": "^5.3.5", "@smithy/signature-v4": "^5.3.5", "@smithy/smithy-client": "^4.9.5", "@smithy/types": "^4.9.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.5", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-AS8gypYQCbNojwgjvZGkJocC2CoEICDx9ZJ15ILsv+MlcCVLtUJSRSx3VzJOUY2EEIaGLRrPNlIqyn/9/fySvA=="], - "@aws-sdk/credential-provider-cognito-identity": ["@aws-sdk/credential-provider-cognito-identity@3.972.22", "", { "dependencies": { "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-ih6ORpme4i2qJqGckOQ9Lt2iiZ+5tm3bnfsT5TwoPyFnuDURXv3OdhYa3Nr/m0iJr38biqKYKdGKb5GR1KB2hw=="], + "@aws-sdk/credential-provider-cognito-identity": ["@aws-sdk/credential-provider-cognito-identity@3.972.38", "", { "dependencies": { "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-OHkK6xOx/IHkSbQdDWxnVCLU+j28EFl8wyWgBILQDFAPY8n240C/O4gjmFx+zFU12lL8njgJQ5GWAIWq88CnSQ=="], - "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.25", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6QfI0wv4jpG5CrdO/AO0JfZ2ux+tKwJPrUwmvxXF50vI5KIypKVGNF6b4vlkYEnKumDTI1NX2zUBi8JoU5QU3A=="], + "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-n1EbJ98yvPWWdHZZv8bRBMqqDQJrtgtxyJ4xLy2Uqrh25BCOZQ7nnS1CsFXvuH8r0b0KVHDZEGEH5FxmEMP8jg=="], - "@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.27", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/node-http-handler": "^4.5.2", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-stream": "^4.5.22", "tslib": "^2.6.2" } }, "sha512-3V3Usj9Gs93h865DqN4M2NWJhC5kXU9BvZskfN3+69omuYlE3TZxOEcVQtBGLOloJB7BVfJKXVLqeNhOzHqSlQ=="], + "@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.43", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-TT76RN1NkI9WoyZqCNxOw6/WBMF7pYOTJcXbMokNFU+euSG40Kaf/t/FhDACVZWP+43wEM6ZynIPIkzS1wR1iA=="], - "@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/credential-provider-env": "^3.972.25", "@aws-sdk/credential-provider-http": "^3.972.27", "@aws-sdk/credential-provider-login": "^3.972.29", "@aws-sdk/credential-provider-process": "^3.972.25", "@aws-sdk/credential-provider-sso": "^3.972.29", "@aws-sdk/credential-provider-web-identity": "^3.972.29", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-SiBuAnXecCbT/OpAf3vqyI/AVE3mTaYr9ShXLybxZiPLBiPCCOIWSGAtYYGQWMRvobBTiqOewaB+wcgMMZI2Aw=="], + "@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.45", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/credential-provider-env": "^3.972.41", "@aws-sdk/credential-provider-http": "^3.972.43", "@aws-sdk/credential-provider-login": "^3.972.45", "@aws-sdk/credential-provider-process": "^3.972.41", "@aws-sdk/credential-provider-sso": "^3.972.45", "@aws-sdk/credential-provider-web-identity": "^3.972.45", "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/credential-provider-imds": "^4.3.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-sJe5ZWibO4s7RWjFQ8Zol76KxoJcIYyEZH1/wxQSBMSIAAxzaJ8cS/ITAaIHWUQvDKQdt18+cJAHKWB7n1Jmrg=="], - "@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-OGOslTbOlxXexKMqhxCEbBQbUIfuhGxU5UXw3Fm56ypXHvrXH4aTt/xb5Y884LOoteP1QST1lVZzHfcTnWhiPQ=="], + "@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.45", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-MZQv4SNjByk1iOKmrqmzcUF/uCB05wjvEHyXKxmGQTUANTIVayX6HPUF0bzkWLvtnkH7sAn9kUCfkXbSpj9sDA=="], "@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.933.0", "", { "dependencies": { "@aws-sdk/credential-provider-env": "3.932.0", "@aws-sdk/credential-provider-http": "3.932.0", "@aws-sdk/credential-provider-ini": "3.933.0", "@aws-sdk/credential-provider-process": "3.932.0", "@aws-sdk/credential-provider-sso": "3.933.0", "@aws-sdk/credential-provider-web-identity": "3.933.0", "@aws-sdk/types": "3.930.0", "@smithy/credential-provider-imds": "^4.2.5", "@smithy/property-provider": "^4.2.5", "@smithy/shared-ini-file-loader": "^4.4.0", "@smithy/types": "^4.9.0", "tslib": "^2.6.2" } }, "sha512-L2dE0Y7iMLammQewPKNeEh1z/fdJyYEU+/QsLBD9VEh+SXcN/FIyTi21Isw8wPZN6lMB9PDVtISzBnF8HuSFrw=="], - "@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.25", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HR7ynNRdNhNsdVCOCegy1HsfsRzozCOPtD3RzzT1JouuaHobWyRfJzCBue/3jP7gECHt+kQyZUvwg/cYLWurNQ=="], + "@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-7I/n1zkysouLOWvkEhjNEP4vMnD2v4kzzr3/3QBdrripEpn7ap1/I5DF3Hou1SUqkKWo1f3oPGMyFAA1FAMvsQ=="], - "@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/token-providers": "3.1026.0", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HWv4SEq3jZDYPlwryZVef97+U8CxxRos5mK8sgGO1dQaFZpV5giZLzqGE5hkDmh2csYcBO2uf5XHjPTpZcJlig=="], + "@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.45", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/token-providers": "3.1056.0", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-oHgbz/eFD8IKiksqDsz9ZMU4A59BpQq4QwJedBnGD80ZqYcHPPHZBwjBnxLVkB7iRVVHWpDclR8yWdD2PkQIUA=="], - "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-PdMBza1WEKEUPFEmMGCfnU2RYCz9MskU2e8JxjyUOsMKku7j9YaDKvbDi2dzC0ihFoM6ods2SbhfAAro+Gwlew=="], + "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.45", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-CDhzKdb2onv5bpnjn/acgdNmJOQthPDLsPizU7rZflsEcgMMp8Mlri+U5hdxf8ldvZJpvM3vLU6D56vfJm5AMQ=="], "@aws-sdk/credential-providers": ["@aws-sdk/credential-providers@3.993.0", "", { "dependencies": { "@aws-sdk/client-cognito-identity": "3.993.0", "@aws-sdk/core": "^3.973.11", "@aws-sdk/credential-provider-cognito-identity": "^3.972.3", "@aws-sdk/credential-provider-env": "^3.972.9", "@aws-sdk/credential-provider-http": "^3.972.11", "@aws-sdk/credential-provider-ini": "^3.972.9", "@aws-sdk/credential-provider-login": "^3.972.9", "@aws-sdk/credential-provider-node": "^3.972.10", "@aws-sdk/credential-provider-process": "^3.972.9", "@aws-sdk/credential-provider-sso": "^3.972.9", "@aws-sdk/credential-provider-web-identity": "^3.972.9", "@aws-sdk/nested-clients": "3.993.0", "@aws-sdk/types": "^3.973.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.23.2", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-1M/nukgPSLqe9krzOKHnE8OylUaKAiokAV3xRLdeExVHcRE7WG5uzCTKWTj1imKvPjDqXq/FWhlbbdWIn7xIwA=="], @@ -965,7 +1088,7 @@ "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.932.0", "", { "dependencies": { "@aws-sdk/middleware-sdk-s3": "3.932.0", "@aws-sdk/types": "3.930.0", "@smithy/protocol-http": "^5.3.5", "@smithy/signature-v4": "^5.3.5", "@smithy/types": "^4.9.0", "tslib": "^2.6.2" } }, "sha512-NCIRJvoRc9246RZHIusY1+n/neeG2yGhBGdKhghmrNdM+mLLN6Ii7CKFZjx3DhxtpHMpl1HWLTMhdVrGwP2upw=="], - "@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1026.0", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/nested-clients": "^3.996.19", "@aws-sdk/types": "^3.973.7", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-Ieq/HiRrbEtrYP387Nes0XlR7H1pJiJOZKv+QyQzMYpvTiDs0VKy2ZB3E2Zf+aFovWmeE7lRE4lXyF7dYM6GgA=="], + "@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1056.0", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "@aws-sdk/nested-clients": "^3.997.13", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-81duvlltQlsfn5K+o8zILcystBRdbT1G2JJYVCML5NZHBz4CL/zf+sAemCtBh/uh6RQUMyInGeZLQ7/8igZhbA=="], "@aws-sdk/types": ["@aws-sdk/types@3.930.0", "", { "dependencies": { "@smithy/types": "^4.9.0", "tslib": "^2.6.2" } }, "sha512-we/vaAgwlEFW7IeftmCLlLMw+6hFs3DzZPJw7lVHbj/5HJ0bz9gndxEsS2lQoeJ1zhiiLqAqvXxmM43s0MBg0A=="], @@ -985,8 +1108,6 @@ "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.2.4", "", {}, "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ=="], - "@azure-rest/core-client": ["@azure-rest/core-client@2.6.0", "", { "dependencies": { "@azure/abort-controller": "^2.1.2", "@azure/core-auth": "^1.10.0", "@azure/core-rest-pipeline": "^1.22.0", "@azure/core-tracing": "^1.3.0", "@typespec/ts-http-runtime": "^0.3.0", "tslib": "^2.6.2" } }, "sha512-iuFKDm8XPzNxPfRjhyU5/xKZmcRDzSuEghXDHHk4MjBV/wFL34GmYVBZnn9wmuoLBeS1qAw9ceMdaeJBPcB1QQ=="], - "@azure/abort-controller": ["@azure/abort-controller@2.1.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA=="], "@azure/core-auth": ["@azure/core-auth@1.10.1", "", { "dependencies": { "@azure/abort-controller": "^2.1.2", "@azure/core-util": "^1.13.0", "tslib": "^2.6.2" } }, "sha512-ykRMW8PjVAn+RS6ww5cmK9U2CyH9p4Q88YJwvUslfuMmN98w/2rdGRLPqJYObapBCdzBVeDgYWdJnFPFb7qzpg=="], @@ -1009,91 +1130,79 @@ "@azure/core-xml": ["@azure/core-xml@1.5.1", "", { "dependencies": { "fast-xml-parser": "^5.5.9", "tslib": "^2.8.1" } }, "sha512-xcNRHqCoSp4AunOALEae6A8f3qATb83gSrm31Iqb01OzblvC3/W/bfXozcq78EzIdzZzuH1bZ2NvRR0TdX709w=="], - "@azure/identity": ["@azure/identity@4.13.1", "", { "dependencies": { "@azure/abort-controller": "^2.0.0", "@azure/core-auth": "^1.9.0", "@azure/core-client": "^1.9.2", "@azure/core-rest-pipeline": "^1.17.0", "@azure/core-tracing": "^1.0.0", "@azure/core-util": "^1.11.0", "@azure/logger": "^1.0.0", "@azure/msal-browser": "^5.5.0", "@azure/msal-node": "^5.1.0", "open": "^10.1.0", "tslib": "^2.2.0" } }, "sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw=="], - - "@azure/keyvault-common": ["@azure/keyvault-common@2.1.0", "", { "dependencies": { "@azure-rest/core-client": "^2.3.3", "@azure/abort-controller": "^2.0.0", "@azure/core-auth": "^1.3.0", "@azure/core-rest-pipeline": "^1.8.0", "@azure/core-tracing": "^1.0.0", "@azure/core-util": "^1.10.0", "@azure/logger": "^1.1.4", "tslib": "^2.2.0" } }, "sha512-aCDidWuKY06LWQ4x7/8TIXK6iRqTaRWRL3t7T+LC+j1b07HtoIsOxP/tU90G4jCSBn5TAyUTCtA4MS/y5Hudaw=="], - - "@azure/keyvault-keys": ["@azure/keyvault-keys@4.10.0", "", { "dependencies": { "@azure-rest/core-client": "^2.3.3", "@azure/abort-controller": "^2.1.2", "@azure/core-auth": "^1.9.0", "@azure/core-http-compat": "^2.2.0", "@azure/core-lro": "^2.7.2", "@azure/core-paging": "^1.6.2", "@azure/core-rest-pipeline": "^1.19.0", "@azure/core-tracing": "^1.2.0", "@azure/core-util": "^1.11.0", "@azure/keyvault-common": "^2.0.0", "@azure/logger": "^1.1.4", "tslib": "^2.8.1" } }, "sha512-eDT7iXoBTRZ2n3fLiftuGJFD+yjkiB1GNqzU2KbY1TLYeXeSPVTVgn2eJ5vmRTZ11978jy2Kg2wI7xa9Tyr8ag=="], - "@azure/logger": ["@azure/logger@1.3.0", "", { "dependencies": { "@typespec/ts-http-runtime": "^0.3.0", "tslib": "^2.6.2" } }, "sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA=="], - "@azure/msal-browser": ["@azure/msal-browser@5.6.3", "", { "dependencies": { "@azure/msal-common": "16.4.1" } }, "sha512-sTjMtUm+bJpENU/1WlRzHEsgEHppZDZ1EtNyaOODg/sQBtMxxJzGB+MOCM+T2Q5Qe1fKBrdxUmjyRxm0r7Ez9w=="], - - "@azure/msal-common": ["@azure/msal-common@16.4.1", "", {}, "sha512-Bl8f+w37xkXsYh7QRkAKCFGYtWMYuOVO7Lv+BxILrvGz3HbIEF22Pt0ugyj0QPOl6NLrHcnNUQ9yeew98P/5iw=="], - - "@azure/msal-node": ["@azure/msal-node@5.1.2", "", { "dependencies": { "@azure/msal-common": "16.4.1", "jsonwebtoken": "^9.0.0", "uuid": "^8.3.0" } }, "sha512-DoeSJ9U5KPAIZoHsPywvfEj2MhBniQe0+FSpjLUTdWoIkI999GB5USkW6nNEHnIaLVxROHXvprWA1KzdS1VQ4A=="], - "@azure/storage-blob": ["@azure/storage-blob@12.31.0", "", { "dependencies": { "@azure/abort-controller": "^2.1.2", "@azure/core-auth": "^1.9.0", "@azure/core-client": "^1.9.3", "@azure/core-http-compat": "^2.2.0", "@azure/core-lro": "^2.2.0", "@azure/core-paging": "^1.6.2", "@azure/core-rest-pipeline": "^1.19.1", "@azure/core-tracing": "^1.2.0", "@azure/core-util": "^1.11.0", "@azure/core-xml": "^1.4.5", "@azure/logger": "^1.1.4", "@azure/storage-common": "^12.3.0", "events": "^3.0.0", "tslib": "^2.8.1" } }, "sha512-DBgNv10aCSxopt92DkTDD0o9xScXeBqPKGmR50FPZQaEcH4JLQ+GEOGEDv19V5BMkB7kxr+m4h6il/cCDPvmHg=="], "@azure/storage-common": ["@azure/storage-common@12.3.0", "", { "dependencies": { "@azure/abort-controller": "^2.1.2", "@azure/core-auth": "^1.9.0", "@azure/core-http-compat": "^2.2.0", "@azure/core-rest-pipeline": "^1.19.1", "@azure/core-tracing": "^1.2.0", "@azure/core-util": "^1.11.0", "@azure/logger": "^1.1.4", "events": "^3.3.0", "tslib": "^2.8.1" } }, "sha512-/OFHhy86aG5Pe8dP5tsp+BuJ25JOAl9yaMU3WZbkeoiFMHFtJ7tu5ili7qEdBXNW9G5lDB19trwyI6V49F/8iQ=="], - "@babel/code-frame": ["@babel/code-frame@7.29.0", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="], + "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], - "@babel/compat-data": ["@babel/compat-data@7.29.0", "", {}, "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg=="], + "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], "@babel/core": ["@babel/core@7.28.4", "", { "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.3", "@babel/helper-compilation-targets": "^7.27.2", "@babel/helper-module-transforms": "^7.28.3", "@babel/helpers": "^7.28.4", "@babel/parser": "^7.28.4", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.4", "@babel/types": "^7.28.4", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA=="], - "@babel/generator": ["@babel/generator@7.29.1", "", { "dependencies": { "@babel/parser": "^7.29.0", "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw=="], + "@babel/generator": ["@babel/generator@7.29.7", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="], - "@babel/helper-annotate-as-pure": ["@babel/helper-annotate-as-pure@7.27.3", "", { "dependencies": { "@babel/types": "^7.27.3" } }, "sha512-fXSwMQqitTGeHLBC08Eq5yXz2m37E4pJX1qAU1+2cNedz/ifv/bVXft90VeSav5nFO61EcNgwr0aJxbyPaWBPg=="], + "@babel/helper-annotate-as-pure": ["@babel/helper-annotate-as-pure@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw=="], - "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.28.6", "", { "dependencies": { "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA=="], + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.7", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="], - "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@7.28.6", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", "@babel/helper-member-expression-to-functions": "^7.28.5", "@babel/helper-optimise-call-expression": "^7.27.1", "@babel/helper-replace-supers": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", "@babel/traverse": "^7.28.6", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-dTOdvsjnG3xNT9Y0AUg1wAl38y+4Rl4sf9caSQZOXdNqVn+H+HbbJ4IyyHaIqNR6SW9oJpA/RuRjsjCw2IdIow=="], + "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@7.29.7", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/traverse": "^7.29.7", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg=="], - "@babel/helper-globals": ["@babel/helper-globals@7.28.0", "", {}, "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw=="], + "@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], - "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@7.28.5", "", { "dependencies": { "@babel/traverse": "^7.28.5", "@babel/types": "^7.28.5" } }, "sha512-cwM7SBRZcPCLgl8a7cY0soT1SptSzAlMH39vwiRpOQkJlh53r5hdHwLSCZpQdVLT39sZt+CRpNwYG4Y2v77atg=="], + "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg=="], - "@babel/helper-module-imports": ["@babel/helper-module-imports@7.28.6", "", { "dependencies": { "@babel/traverse": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw=="], + "@babel/helper-module-imports": ["@babel/helper-module-imports@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="], - "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.28.6", "", { "dependencies": { "@babel/helper-module-imports": "^7.28.6", "@babel/helper-validator-identifier": "^7.28.5", "@babel/traverse": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA=="], + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.7", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="], - "@babel/helper-optimise-call-expression": ["@babel/helper-optimise-call-expression@7.27.1", "", { "dependencies": { "@babel/types": "^7.27.1" } }, "sha512-URMGH08NzYFhubNSGJrpUEphGKQwMQYBySzat5cAByY1/YgIRkULnIy3tAMeszlL/so2HbeilYloUmSpd7GdVw=="], + "@babel/helper-optimise-call-expression": ["@babel/helper-optimise-call-expression@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong=="], - "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.28.6", "", {}, "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug=="], + "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.29.7", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="], - "@babel/helper-replace-supers": ["@babel/helper-replace-supers@7.28.6", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.28.5", "@babel/helper-optimise-call-expression": "^7.27.1", "@babel/traverse": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-mq8e+laIk94/yFec3DxSjCRD2Z0TAjhVbEJY3UQrlwVo15Lmt7C2wAUbK4bjnTs4APkwsYLTahXRraQXhb1WCg=="], + "@babel/helper-replace-supers": ["@babel/helper-replace-supers@7.29.7", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ=="], - "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@7.27.1", "", { "dependencies": { "@babel/traverse": "^7.27.1", "@babel/types": "^7.27.1" } }, "sha512-Tub4ZKEXqbPjXgWLl2+3JpQAYBJ8+ikpQ2Ocj/q/r0LwE3UhENh7EUabyHjz2kCEsrRY83ew2DQdHluuiDQFzg=="], + "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], - "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], - "@babel/helper-validator-option": ["@babel/helper-validator-option@7.27.1", "", {}, "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg=="], + "@babel/helper-validator-option": ["@babel/helper-validator-option@7.29.7", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="], - "@babel/helpers": ["@babel/helpers@7.29.2", "", { "dependencies": { "@babel/template": "^7.28.6", "@babel/types": "^7.29.0" } }, "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw=="], + "@babel/helpers": ["@babel/helpers@7.29.7", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg=="], - "@babel/parser": ["@babel/parser@7.29.2", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA=="], + "@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], - "@babel/plugin-syntax-jsx": ["@babel/plugin-syntax-jsx@7.28.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w=="], + "@babel/plugin-syntax-jsx": ["@babel/plugin-syntax-jsx@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A=="], - "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.28.6", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A=="], + "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="], - "@babel/plugin-transform-arrow-functions": ["@babel/plugin-transform-arrow-functions@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-8Z4TGic6xW70FKThA5HYEKKyBpOOsucTOD1DjU3fZxDg+K3zBJcXMFnt/4yQiZnf5+MiOMSXQ9PaEK/Ilh1DeA=="], + "@babel/plugin-transform-arrow-functions": ["@babel/plugin-transform-arrow-functions@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-N7zArUXWzAMzm+/N0uPBeVB3Fam5lMxtUwMmDK5f/IBBS7a7p1qeUoxd/6CckXoxUdgsntq1Dh8xNW06maZbDQ=="], - "@babel/plugin-transform-modules-commonjs": ["@babel/plugin-transform-modules-commonjs@7.28.6", "", { "dependencies": { "@babel/helper-module-transforms": "^7.28.6", "@babel/helper-plugin-utils": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-jppVbf8IV9iWWwWTQIxJMAJCWBuuKx71475wHwYytrRGQ2CWiDvYlADQno3tcYpS/T2UUWFQp3nVtYfK/YBQrA=="], + "@babel/plugin-transform-modules-commonjs": ["@babel/plugin-transform-modules-commonjs@7.29.7", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ=="], - "@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw=="], + "@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw=="], - "@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw=="], + "@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q=="], - "@babel/plugin-transform-typescript": ["@babel/plugin-transform-typescript@7.28.6", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", "@babel/helper-create-class-features-plugin": "^7.28.6", "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", "@babel/plugin-syntax-typescript": "^7.28.6" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-0YWL2RFxOqEm9Efk5PvreamxPME8OyY0wM5wh5lHjF+VtVhdneCWGzZeSqzOfiobVqQaNCd2z0tQvnI9DaPWPw=="], + "@babel/plugin-transform-typescript": ["@babel/plugin-transform-typescript@7.29.7", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/plugin-syntax-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw=="], "@babel/preset-typescript": ["@babel/preset-typescript@7.27.1", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1", "@babel/helper-validator-option": "^7.27.1", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-transform-modules-commonjs": "^7.27.1", "@babel/plugin-transform-typescript": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-l7WfQfX0WK4M0v2RudjuQK4u99BS6yLHYEmdtVPP7lKV013zr9DygFuWNlnbvQ9LR+LS0Egz/XAvGx5U9MX0fQ=="], - "@babel/runtime": ["@babel/runtime@7.29.2", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="], + "@babel/runtime": ["@babel/runtime@7.29.7", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="], - "@babel/template": ["@babel/template@7.28.6", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ=="], + "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], - "@babel/traverse": ["@babel/traverse@7.29.0", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/types": "^7.29.0", "debug": "^4.3.1" } }, "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA=="], + "@babel/traverse": ["@babel/traverse@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/types": "^7.29.7", "debug": "^4.3.1" } }, "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw=="], - "@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="], + "@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], - "@bufbuild/protobuf": ["@bufbuild/protobuf@2.11.0", "", {}, "sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ=="], + "@bufbuild/protobuf": ["@bufbuild/protobuf@2.12.0", "", {}, "sha512-B/XlCaFIP8LOwzo+bz5uFzATYokcwCKQcghqnlfwSmM5eX/qTkvDBnDPs+gXtX/RyjxJ4DRikECcPJbyALA8FA=="], - "@bufbuild/protoplugin": ["@bufbuild/protoplugin@2.11.0", "", { "dependencies": { "@bufbuild/protobuf": "2.11.0", "@typescript/vfs": "^1.6.2", "typescript": "5.4.5" } }, "sha512-lyZVNFUHArIOt4W0+dwYBe5GBwbKzbOy8ObaloEqsw9Mmiwv2O48TwddDoHN4itylC+BaEGqFdI1W8WQt2vWJQ=="], + "@bufbuild/protoplugin": ["@bufbuild/protoplugin@2.12.0", "", { "dependencies": { "@bufbuild/protobuf": "2.12.0", "@typescript/vfs": "^1.6.2", "typescript": "5.4.5" } }, "sha512-ORlDITp8AFUXzIhLRoMCG+ud+D3MPKWb5HQXBoskMMnjeyEjE1H1qLonVNPyOr8lkx3xSfYUo8a0dvOZJVAzow=="], "@capsizecss/unpack": ["@capsizecss/unpack@2.4.0", "", { "dependencies": { "blob-to-buffer": "^1.2.8", "cross-fetch": "^3.0.4", "fontkit": "^2.0.2" } }, "sha512-GrSU71meACqcmIUxPYOJvGKF0yryjN/L1aCuE9DViCTJI7bfkjgYDPD1zbNDcINJwSSP6UaBZY9GAbYDO7re0Q=="], @@ -1135,7 +1244,7 @@ "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.66", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.66", "mime": "^4.1.0", "undici": "^8.0.2" }, "peerDependencies": { "effect": "^4.0.0-beta.66", "ioredis": "^5.7.0" } }, "sha512-s/0RgaQFuszzdorRnX1PwEQNnSOi+JgMJo3zEe9O2NR3sosMhTr0Uk+1AF6bUOI9uJ2CPT3KpTIIU7q5/TpOkg=="], - "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.66", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.66" } }, "sha512-+ymrhBnESv/hmn5SKTe2//IY9Ox/hGPeoogEWhW47ZGyhFI5eMYFxdEUBa+3IAV05rrBzrxON9lynu68n0DM7w=="], + "@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/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.66", "", { "peerDependencies": { "effect": "^4.0.0-beta.66" } }, "sha512-UYsrAb/5T0ZRypeN9Kmv3/ZInibGCjM6dtoiAWtfG+xKyuq8N05wmuVCXB0+XgVmUBxDWjw/S1fu4ivS0vZVuw=="], @@ -1149,7 +1258,7 @@ "@electron/osx-sign": ["@electron/osx-sign@1.3.3", "", { "dependencies": { "compare-version": "^0.1.2", "debug": "^4.3.4", "fs-extra": "^10.0.0", "isbinaryfile": "^4.0.8", "minimist": "^1.2.6", "plist": "^3.0.5" }, "bin": { "electron-osx-flat": "bin/electron-osx-flat.js", "electron-osx-sign": "bin/electron-osx-sign.js" } }, "sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg=="], - "@electron/rebuild": ["@electron/rebuild@4.0.3", "", { "dependencies": { "@malept/cross-spawn-promise": "^2.0.0", "debug": "^4.1.1", "detect-libc": "^2.0.1", "got": "^11.7.0", "graceful-fs": "^4.2.11", "node-abi": "^4.2.0", "node-api-version": "^0.2.1", "node-gyp": "^11.2.0", "ora": "^5.1.0", "read-binary-file-arch": "^1.0.6", "semver": "^7.3.5", "tar": "^7.5.6", "yargs": "^17.0.1" }, "bin": { "electron-rebuild": "lib/cli.js" } }, "sha512-u9vpTHRMkOYCs/1FLiSVAFZ7FbjsXK+bQuzviJZa+lG7BHZl1nz52/IcGvwa3sk80/fc3llutBkbCq10Vh8WQA=="], + "@electron/rebuild": ["@electron/rebuild@4.0.4", "", { "dependencies": { "@malept/cross-spawn-promise": "^2.0.0", "debug": "^4.1.1", "node-abi": "^4.2.0", "node-api-version": "^0.2.1", "node-gyp": "^12.2.0", "read-binary-file-arch": "^1.0.6" }, "bin": { "electron-rebuild": "lib/cli.js" } }, "sha512-Rzc39XPdk/+/wBG8MfwAHohXflep0ITUfulb6Rgz3R0NeSB1noE+E9/M/cb8ftCAiyDD9PPhLuuWgE1GaInbKg=="], "@electron/universal": ["@electron/universal@2.0.3", "", { "dependencies": { "@electron/asar": "^3.3.1", "@malept/cross-spawn-promise": "^2.0.0", "debug": "^4.3.1", "dir-compare": "^4.2.0", "fs-extra": "^11.1.1", "minimatch": "^9.0.3", "plist": "^3.1.0" } }, "sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g=="], @@ -1283,9 +1392,7 @@ "@hey-api/types": ["@hey-api/types@0.1.2", "", {}, "sha512-uNNtiVAWL7XNrV/tFXx7GLY9lwaaDazx1173cGW3+UEaw4RUPsHEmiB4DSpcjNxMIcrctfz2sGKLnVx5PBG2RA=="], - "@hono/node-server": ["@hono/node-server@1.19.11", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g=="], - - "@hono/standard-validator": ["@hono/standard-validator@0.1.5", "", { "peerDependencies": { "@standard-schema/spec": "1.0.0", "hono": ">=3.9.0" } }, "sha512-EIyZPPwkyLn6XKwFj5NBEWHXhXbgmnVh2ceIFo5GO7gKI9WmzTjPDKnppQB0KrqKeAkq3kpoW4SIbu5X1dgx3w=="], + "@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="], "@ibm/plex": ["@ibm/plex@6.4.1", "", { "dependencies": { "@ibm/telemetry-js": "^1.5.1" } }, "sha512-fnsipQywHt3zWvsnlyYKMikcVI7E2fEwpiPnIHFqlbByXVfQfANAAeJk1IV4mNnxhppUIDlhU0TzwYwL++Rn2g=="], @@ -1329,11 +1436,11 @@ "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.33.5", "", { "os": "win32", "cpu": "x64" }, "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg=="], - "@internationalized/date": ["@internationalized/date@3.12.1", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-6IedsVWXyq4P9Tj+TxuU8WGWM70hYLl12nbYU8jkikVpa6WXapFazPUcHUMDMoWftIDE2ILDkFFte6W2nFCkRQ=="], + "@internationalized/date": ["@internationalized/date@3.12.2", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-FY1Y+H64NDs+HAF6omlnWxm3mEpfgaCSWtL5l551ZZfImA+kGjPFgrnJrGjH6lfmLL0g8Z/mBu1R3kufeCp6Jw=="], - "@internationalized/number": ["@internationalized/number@3.6.6", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-iFgmQaXHE0vytNfpLZWOC2mEJCBRzcUxt53Xf/yCXG93lRvqas237i3r7X4RKMwO3txiyZD4mQjKAByFv6UGSQ=="], + "@internationalized/number": ["@internationalized/number@3.6.7", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-3ji1fcrT+FPAK86UqEhB/psHixYo6niWPJtt7+qRaYFynt/BaJG8GhAPimtWUpEiVSTq8ZM8L5psMxGquiB/Vg=="], - "@ioredis/commands": ["@ioredis/commands@1.5.1", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="], + "@ioredis/commands": ["@ioredis/commands@1.10.0", "", {}, "sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q=="], "@isaacs/balanced-match": ["@isaacs/balanced-match@4.0.1", "", {}, "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ=="], @@ -1359,8 +1466,6 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], - "@js-joda/core": ["@js-joda/core@5.7.0", "", {}, "sha512-WBu4ULVVxySLLzK1Ppq+OdfP+adRS4ntmDQT915rzDJ++i95gc2jZkM5B6LWEAwN3lGXpfie3yPABozdD3K3Vg=="], - "@js-temporal/polyfill": ["@js-temporal/polyfill@0.5.1", "", { "dependencies": { "jsbi": "^4.3.0" } }, "sha512-hloP58zRVCRSpgDxmqCWJNlizAlUgJFqG2ypq79DCvyv9tHjRYMDOcPFjzfl/A1/YxDvRCZz8wvZvmapQnKwFQ=="], "@jsdevtools/ono": ["@jsdevtools/ono@7.1.3", "", {}, "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg=="], @@ -1417,19 +1522,19 @@ "@lukeed/ms": ["@lukeed/ms@2.0.2", "", {}, "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA=="], - "@lydell/node-pty": ["@lydell/node-pty@1.2.0-beta.10", "", { "optionalDependencies": { "@lydell/node-pty-darwin-arm64": "1.2.0-beta.10", "@lydell/node-pty-darwin-x64": "1.2.0-beta.10", "@lydell/node-pty-linux-arm64": "1.2.0-beta.10", "@lydell/node-pty-linux-x64": "1.2.0-beta.10", "@lydell/node-pty-win32-arm64": "1.2.0-beta.10", "@lydell/node-pty-win32-x64": "1.2.0-beta.10" } }, "sha512-Fv+A3+MZVA8qhkBIZsM1E6dCdHNMyXXz22mAYiMWd03LlyK///F3OH6CKPX9mj4id7LUlxpr45yPzyBVy9aDPw=="], + "@lydell/node-pty": ["@lydell/node-pty@1.2.0-beta.12", "", { "optionalDependencies": { "@lydell/node-pty-darwin-arm64": "1.2.0-beta.12", "@lydell/node-pty-darwin-x64": "1.2.0-beta.12", "@lydell/node-pty-linux-arm64": "1.2.0-beta.12", "@lydell/node-pty-linux-x64": "1.2.0-beta.12", "@lydell/node-pty-win32-arm64": "1.2.0-beta.12", "@lydell/node-pty-win32-x64": "1.2.0-beta.12" } }, "sha512-qIK890UwPupoj07osVvgOIa++1mxeHbcGry4PKRHhNVNs81V2SCG34eJr46GybiOmBtc8Sj5PB1/GGM5PL549g=="], - "@lydell/node-pty-darwin-arm64": ["@lydell/node-pty-darwin-arm64@1.2.0-beta.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-C+eqDyRNHRYvx7RaHj6VVCx6nCpRBPuuxhTcc3JH3GuBMoxTsYeY4GkWH2XOktrgbAq1BG8e/Y8bu/wNQreCEw=="], + "@lydell/node-pty-darwin-arm64": ["@lydell/node-pty-darwin-arm64@1.2.0-beta.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-tqaifcY9Cr41SblO1+FLzh8oxxtkNhuW9Dhl22lKme9BreYvKvxEZcdPIXTuqkJc5tagOEC4QHShKmJjLyLXLQ=="], - "@lydell/node-pty-darwin-x64": ["@lydell/node-pty-darwin-x64@1.2.0-beta.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-aZoIK6HtJO5BiT4ELm683U4dyHtt8b7wNgq3NJqYAQwSXrcPv576Z8vY3BIulVxfcFkht/SPLKou9TtdFXdNpg=="], + "@lydell/node-pty-darwin-x64": ["@lydell/node-pty-darwin-x64@1.2.0-beta.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-4LrS5pCJwqHKDVf1zS2gyNV0m4hKAXch+XZNhbZ6LY8uwVL8BhchzQBO40Os5anuRxRCWzHpw4Sp64Ie8q7E4Q=="], - "@lydell/node-pty-linux-arm64": ["@lydell/node-pty-linux-arm64@1.2.0-beta.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-0cKX2iMyXFNBE4fGtGK6B7IkdXcDMZajyEDoGMOgQQs/DDtoI5tSPcBcqNY9VitVrsRQA8+gFt6eKYU9Ye/lUA=="], + "@lydell/node-pty-linux-arm64": ["@lydell/node-pty-linux-arm64@1.2.0-beta.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-Sx+A71x5BDGHt9ansfrtGxwq2VFVDWvJUAdlUL0Hv0qeiJUfts+hgopx+CgT4PSwahKjdEgtu0+FAfY9rICKRw=="], - "@lydell/node-pty-linux-x64": ["@lydell/node-pty-linux-x64@1.2.0-beta.10", "", { "os": "linux", "cpu": "x64" }, "sha512-J9HnxvSzEeMH748+Ul1VrmCLWMo7iCVJy9EGijRR62+YO/Yk5GaCydUTZ+KzlH0/X5aTrgt5cfiof4vx45tRRg=="], + "@lydell/node-pty-linux-x64": ["@lydell/node-pty-linux-x64@1.2.0-beta.12", "", { "os": "linux", "cpu": "x64" }, "sha512-bJzs94njofYhGg/UDqW1nj0dtvvu+2OvxMY+RlLS1T17VgcktKoIR6PuenTwE5HJ/D6StCPADmXcT0nNsCKmIQ=="], - "@lydell/node-pty-win32-arm64": ["@lydell/node-pty-win32-arm64@1.2.0-beta.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-PlDJpJX/pnKyy6OmADKzhf+INZDDnzTBGaI0LT4laVNc6NblZNqUSkCMjLFWbeakeuQp0VG37M49WQSN9FDfeA=="], + "@lydell/node-pty-win32-arm64": ["@lydell/node-pty-win32-arm64@1.2.0-beta.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-p7POgjVEiFaBC3/y+AKuV1FzePCsJ6HmZDv2XK+jBZSfwP8+uBAw181ZiKYN1YuRa/XpmBGaWezcI8hZkbW++g=="], - "@lydell/node-pty-win32-x64": ["@lydell/node-pty-win32-x64@1.2.0-beta.10", "", { "os": "win32", "cpu": "x64" }, "sha512-ExFgWrzyldNAMi45U9PLIOu+g/RatP+f0c/dZxaooifME6yLW32BoHveH26/TtoAjZyJrc2iL0u48pgnR1fzmg=="], + "@lydell/node-pty-win32-x64": ["@lydell/node-pty-win32-x64@1.2.0-beta.12", "", { "os": "win32", "cpu": "x64" }, "sha512-IDFa00g7qUDGUYgByrUBJtC+mOjYVt/8KYyWivCg5JjGOHbBUACUQZLl0jTWmnr+tld/UyTpX90a2PY6oTVtRw=="], "@malept/cross-spawn-promise": ["@malept/cross-spawn-promise@2.0.0", "", { "dependencies": { "cross-spawn": "^7.0.1" } }, "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg=="], @@ -1455,21 +1560,21 @@ "@motionone/utils": ["@motionone/utils@10.18.0", "", { "dependencies": { "@motionone/types": "^10.17.1", "hey-listen": "^1.0.8", "tslib": "^2.3.1" } }, "sha512-3XVF7sgyTSI2KWvTf6uLlBJ5iAgRgmvp3bpuOiQJvInd4nZ19ET8lX5unn30SlmRH7hXbBbH+Gxd0m0klJ3Xtw=="], - "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="], + "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="], - "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="], + "@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="], - "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.3", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="], + "@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="], - "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="], + "@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="], - "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.3", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="], + "@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="], - "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.3", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="], + "@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="], - "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-xK9sGVbJWYb08+mTJt3/YV24WxvxpXcXtP6B172paPZ+Ts69Re9dAr7lKwJoeIx8OoeuimEiRZ7umkiUVClmmQ=="], + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.4", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow=="], - "@nodable/entities": ["@nodable/entities@2.1.0", "", {}, "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA=="], + "@nodable/entities": ["@nodable/entities@2.1.1", "", {}, "sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg=="], "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], @@ -1479,7 +1584,7 @@ "@npm/types": ["@npm/types@1.0.2", "", {}, "sha512-KXZccTDEnWqNrrx6JjpJKU/wJvNeg9BDgjS0XhmlZab7br921HtyVbsYzJr4L+xIvjdJ20Wh9dgxgCI2a5CEQw=="], - "@npmcli/agent": ["@npmcli/agent@4.0.0", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-kAQTcEN9E8ERLVg5AsGwLNoFb+oEG6engbqAU2P43gD4JEIkNGMHdVQ096FsOAAYpZPB0RSt0zgInKIAS1l5QA=="], + "@npmcli/agent": ["@npmcli/agent@4.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^11.2.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-EUEuWAxnL07Sp5/iC/1X6Xj+XThUvnbei9zfRWZdEXa7lss9RTHMhAHBeg+MZ5To9s/gGaSI+UwZTPdYMvKSeg=="], "@npmcli/arborist": ["@npmcli/arborist@9.4.0", "", { "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", "@npmcli/fs": "^5.0.0", "@npmcli/installed-package-contents": "^4.0.0", "@npmcli/map-workspaces": "^5.0.0", "@npmcli/metavuln-calculator": "^9.0.2", "@npmcli/name-from-folder": "^4.0.0", "@npmcli/node-gyp": "^5.0.0", "@npmcli/package-json": "^7.0.0", "@npmcli/query": "^5.0.0", "@npmcli/redact": "^4.0.0", "@npmcli/run-script": "^10.0.0", "bin-links": "^6.0.0", "cacache": "^20.0.1", "common-ancestor-path": "^2.0.0", "hosted-git-info": "^9.0.0", "json-stringify-nice": "^1.1.4", "lru-cache": "^11.2.1", "minimatch": "^10.0.3", "nopt": "^9.0.0", "npm-install-checks": "^8.0.0", "npm-package-arg": "^13.0.0", "npm-pick-manifest": "^11.0.1", "npm-registry-fetch": "^19.0.0", "pacote": "^21.0.2", "parse-conflict-json": "^5.0.1", "proc-log": "^6.0.0", "proggy": "^4.0.0", "promise-all-reject-late": "^1.0.0", "promise-call-limit": "^3.0.1", "semver": "^7.3.7", "ssri": "^13.0.0", "treeverse": "^3.0.0", "walk-up-path": "^4.0.0" }, "bin": { "arborist": "bin/index.js" } }, "sha512-4Bm8hNixJG/sii1PMnag0V9i/sGOX9VRzFrUiZMSBJpGlLR38f+Btl85d07G9GL56xO0l0OZjvrGNYsDYp0xKA=="], @@ -1555,6 +1660,8 @@ "@opencode-ai/app": ["@opencode-ai/app@workspace:packages/app"], + "@opencode-ai/cli": ["@opencode-ai/cli@workspace:packages/cli"], + "@opencode-ai/console-app": ["@opencode-ai/console-app@workspace:packages/console/app"], "@opencode-ai/console-core": ["@opencode-ai/console-core@workspace:packages/console/core"], @@ -1565,12 +1672,16 @@ "@opencode-ai/console-resource": ["@opencode-ai/console-resource@workspace:packages/console/resource"], + "@opencode-ai/console-support": ["@opencode-ai/console-support@workspace:packages/console/support"], + "@opencode-ai/core": ["@opencode-ai/core@workspace:packages/core"], "@opencode-ai/desktop": ["@opencode-ai/desktop@workspace:packages/desktop"], "@opencode-ai/effect-drizzle-sqlite": ["@opencode-ai/effect-drizzle-sqlite@workspace:packages/effect-drizzle-sqlite"], + "@opencode-ai/effect-sqlite-node": ["@opencode-ai/effect-sqlite-node@workspace:packages/effect-sqlite-node"], + "@opencode-ai/enterprise": ["@opencode-ai/enterprise@workspace:packages/enterprise"], "@opencode-ai/function": ["@opencode-ai/function@workspace:packages/function"], @@ -1587,6 +1698,12 @@ "@opencode-ai/slack": ["@opencode-ai/slack@workspace:packages/slack"], + "@opencode-ai/stats-app": ["@opencode-ai/stats-app@workspace:packages/stats/app"], + + "@opencode-ai/stats-core": ["@opencode-ai/stats-core@workspace:packages/stats/core"], + + "@opencode-ai/stats-server": ["@opencode-ai/stats-server@workspace:packages/stats/server"], + "@opencode-ai/storybook": ["@opencode-ai/storybook@workspace:packages/storybook"], "@opencode-ai/ui": ["@opencode-ai/ui@workspace:packages/ui"], @@ -1619,25 +1736,25 @@ "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.6.1", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.6.1", "@opentelemetry/core": "2.6.1", "@opentelemetry/sdk-trace-base": "2.6.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-Hh2i4FwHWRFhnO2Q/p6svMxy8MPsNCG0uuzUY3glqm0rwM0nQvbTO1dXSp9OqQoTKXcQzaz9q1f65fsurmOhNw=="], - "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.40.0", "", {}, "sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw=="], + "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.41.1", "", {}, "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA=="], - "@opentui/core": ["@opentui/core@0.2.15", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.15", "@opentui/core-darwin-x64": "0.2.15", "@opentui/core-linux-arm64": "0.2.15", "@opentui/core-linux-x64": "0.2.15", "@opentui/core-win32-arm64": "0.2.15", "@opentui/core-win32-x64": "0.2.15" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-YGHttdZWScMcSvtYgZkLR6VhUO1OoUiQzwYjZgIusf5eCkPLD8PapH+PTMVqAiX16CHO6JxfMlkHv5qDiHAccQ=="], + "@opentui/core": ["@opentui/core@0.3.1", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.3.1", "@opentui/core-darwin-x64": "0.3.1", "@opentui/core-linux-arm64": "0.3.1", "@opentui/core-linux-x64": "0.3.1", "@opentui/core-win32-arm64": "0.3.1", "@opentui/core-win32-x64": "0.3.1" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-kQFSsSCgtlasSqTigCgKmM67xaquGvTg+vwimDnFSZtcBEt4E3dz7qLrbeh5FVvTA+RMbwe+Bozq03PW+SgjXw=="], - "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.2.15", "", { "os": "darwin", "cpu": "arm64" }, "sha512-s25f9GmZd6wxNM5ExRmwwnLT+NLCKxnTWuO9aObOlqsXfLMGHQZrb6YwgAn/PSTua98KmH7GJCVWdPgZ/P+0RQ=="], + "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.3.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-krvVfiBpeBY+727R8yogdqIcxkK3RUVcI97bqjl8jTeDMcWOkFFfHezssRMPmbR5x++1tX669Fz3fuxoe7XUIg=="], - "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.2.15", "", { "os": "darwin", "cpu": "x64" }, "sha512-GyaipN+nOcEr8rcTO2mqKTGmOBk0C300I69fLtubD3BadHcMI1DVNlQrcf/J1mkQEuMYbmBTi/1hT1ybWGr2Mw=="], + "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.3.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-D/6ec5H8SPpSBMr01/sqgSddIl1Qc1QMKsDl/wV5MpbxYc7Qvie9qlNvvoSsWNfAXAbafLRb1jQBzouk41cp1w=="], - "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.2.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-h+uyufselGT4afKMP8Lg4yUl5Kp+DJBlhu3XpWXhphE5Pnq5+f0uGBr4P+34CNcWxMsDnvagSQLFRCS4rGrOWA=="], + "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.3.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-E/FFBoAsWJyS/EO/cF7h7DuEENYa9nAdSv1W/TIyKXpBisN6K3U1Xgbk528TkfWjrwJjhGs+9OMYdXuAHd5LTw=="], - "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.2.15", "", { "os": "linux", "cpu": "x64" }, "sha512-jx+NImPq4wSp3Apfe7tlixiEJNnRyECTRJRWhGF6ZJz4PwFfgK2UHZKYR0DZHbV8nYawoDNQPJDXEWcoZShnMg=="], + "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.3.1", "", { "os": "linux", "cpu": "x64" }, "sha512-Btb7Q4BOC55Aj2qCs0VoxGuj87DNfUEaSx0z89oeU4npTN+6SpJApyGZTCNNeSe2sdmOGeh/8eAR4X96ORjcKg=="], - "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.2.15", "", { "os": "win32", "cpu": "arm64" }, "sha512-2SQQLvf3sgmToxrNika9AdcccKrjPJEn5jW6sSv0oEixNBzUzW41vSZZG4LM/V3lL8eg0LoYDnRZeKLB4gwSqQ=="], + "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.3.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-+lt24u3KwEPG69oXDOLz9N484wPcAHvrPbDNU77OT6DvWew+StAjh40eY+Zeu0TkTNDWfj7qnQKV0GKWtFA3cw=="], - "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.2.15", "", { "os": "win32", "cpu": "x64" }, "sha512-SVMVgnC7LVEm+yVZKdmmhRBj/xAT94PanT+UCcHxaCWK+OLmv/AX+ohHq2m0odup6iXcEqj+7mAltO9fgJLFIg=="], + "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.3.1", "", { "os": "win32", "cpu": "x64" }, "sha512-eVkKMYirYgpn92lI0YT/GKru4J+UiXjzwyzNRFX+P59OHXvL3GFdqJMcJmX4/zvyjg4c8HDnU79YLnyG+TlXLw=="], - "@opentui/keymap": ["@opentui/keymap@0.2.15", "", { "dependencies": { "@opentui/core": "0.2.15" }, "peerDependencies": { "@opentui/react": "0.2.15", "@opentui/solid": "0.2.15", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-wqQp6y7P2jZZJiOMwupxjGryuSWCs+njjglwW/xny9J17gomBmUvTIcIIWNG0Jv+EGO9ScBzCScGlwBHFhHyYw=="], + "@opentui/keymap": ["@opentui/keymap@0.3.1", "", { "dependencies": { "@opentui/core": "0.3.1" }, "peerDependencies": { "@opentui/react": "0.3.1", "@opentui/solid": "0.3.1", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-BTj+ggsarO2uyvd6CWzvgfsekA8c4aEclbAPKPZGVjBI3Fo5+KAHUrXvteFO5qpGMANfEJTtVHoRu5cic1Nlaw=="], - "@opentui/solid": ["@opentui/solid@0.2.15", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.2.15", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-CViepAjsCWXwrLndMt+qlLo7cooVX7DXwSJHNizw7mfrRJtOPzSYJZCIk1vF4IJTWffCHygoYMe3uSeKvzAcbw=="], + "@opentui/solid": ["@opentui/solid@0.3.1", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.3.1", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-2R6wEijfMub9COTBCm8IKVj2y7+Sc4fZZjJawxk8sE6+++mzeUaokKNJTlYhZXpMju4LKMv6j9CjWkG8JYfbcg=="], "@oslojs/asn1": ["@oslojs/asn1@1.0.0", "", { "dependencies": { "@oslojs/binary": "1.0.0" } }, "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA=="], @@ -1679,6 +1796,86 @@ "@oxc-minify/binding-win32-x64-msvc": ["@oxc-minify/binding-win32-x64-msvc@0.96.0", "", { "os": "win32", "cpu": "x64" }, "sha512-T2ijfqZLpV2bgGGocXV4SXTuMoouqN0asYTIm+7jVOLvT5XgDogf3ZvCmiEnSWmxl21+r5wHcs8voU2iUROXAg=="], + "@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.127.0", "", { "os": "android", "cpu": "arm" }, "sha512-0LC7ye4hvqbIKxAzThzvswgHLFu2AURKzYLeSVvLdu2TBOYWQDmHnTqPLeA597BcUCxiLqLsS4CJ5uoI5WYWCQ=="], + + "@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.127.0", "", { "os": "android", "cpu": "arm64" }, "sha512-b5jtVTH6AU5CJXHNdj7Jj9IEiR9yVjjnwHzPJhGyHGPdcsZSzBCkS9GBbV33niRMvKthDwQRFRJfI4a+k4PvYg=="], + + "@oxc-parser/binding-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.127.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-obCE8B7ISKkJidjlhv9xRGJPOSDG2Yu6PRga9Ruaz35uintHxbp1Ki/Yc71wx4rj3Edrm0a1kzG1TAwit0wFpg=="], + + "@oxc-parser/binding-darwin-x64": ["@oxc-parser/binding-darwin-x64@0.127.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-JL6Xb5IwPQT8rUzlpsX7E+AgfcdNklXNPFp8pjCQQ5MQOQo5rtEB2ui+3Hgg9Sn7Y9Egj6YOLLiHhLpdAe12Aw=="], + + "@oxc-parser/binding-freebsd-x64": ["@oxc-parser/binding-freebsd-x64@0.127.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-SDQ/3MQFw58fqQz3Z1PhSKFF3JoCF4gmlNjziDm8X02tTahCw0qJbd7FGPDKw1i4VTBZene9JPyC3mHtSvi+wA=="], + + "@oxc-parser/binding-linux-arm-gnueabihf": ["@oxc-parser/binding-linux-arm-gnueabihf@0.127.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Av+D1MIqzV0YMGPT9we2SIZaMKD7Cxs4CvXSx/yxaWHewZjYEjScpOf5igc8IILASViw4WTnjlwUdI1KzVtDHQ=="], + + "@oxc-parser/binding-linux-arm-musleabihf": ["@oxc-parser/binding-linux-arm-musleabihf@0.127.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Cs2fdJ8cPpFdeebj6p4dag8A4+56hPvZ0AhQQzlaLswGz1tz7bXt1nETLeorrM9+AMcWFFkqxcXwDGfTVidY8g=="], + + "@oxc-parser/binding-linux-arm64-gnu": ["@oxc-parser/binding-linux-arm64-gnu@0.127.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-qdOfTcT6SY8gsJrrV92uyEUyjqMGPpIB5JZUG6QN5dukYd+7/j0kX6MwK1DgQj39jtUYixxPiaRUiEN1+0CXgQ=="], + + "@oxc-parser/binding-linux-arm64-musl": ["@oxc-parser/binding-linux-arm64-musl@0.127.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-EoTCZneNFU/P2qrpEM+RHmQwt+CvDkyGESG6qhr7KaegXLZwePfbrkCDfAk8/rhxbDUVGsZILX+2tqPzFtoFWA=="], + + "@oxc-parser/binding-linux-ppc64-gnu": ["@oxc-parser/binding-linux-ppc64-gnu@0.127.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-zALjmZYgxFLHjXeudcDF0xFGNydTAtkAeXAr2EuC17ywCyFxcmQra4w0BMde0Yi/re4Bi4iwEoEXtYN7l6eBLQ=="], + + "@oxc-parser/binding-linux-riscv64-gnu": ["@oxc-parser/binding-linux-riscv64-gnu@0.127.0", "", { "os": "linux", "cpu": "none" }, "sha512-fPP8M6zQLS7Jz7o9d5ArUSuAuSK3e+WCYVrCpdzeCOejidtZExJ9tjhDrAd3HEPqARBCPmdpqxESPFqy44vkBQ=="], + + "@oxc-parser/binding-linux-riscv64-musl": ["@oxc-parser/binding-linux-riscv64-musl@0.127.0", "", { "os": "linux", "cpu": "none" }, "sha512-7IcC4Ao02oGpfnjt+X/oF4U2mllo2qoSkw5xxiXNKL9MCTsTiAC6616beOuehdxGcnz1bRoPC1RQ2f1GQDdN+g=="], + + "@oxc-parser/binding-linux-s390x-gnu": ["@oxc-parser/binding-linux-s390x-gnu@0.127.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-pbXIhiNFHoqWeqDNLiJ9JkpHz1IM9k4DXa66x+1GTWMG7iLxtkXgE53iiuKSXwmk3zIYmaPVfBvgcAhS583K4Q=="], + + "@oxc-parser/binding-linux-x64-gnu": ["@oxc-parser/binding-linux-x64-gnu@0.127.0", "", { "os": "linux", "cpu": "x64" }, "sha512-MYCguB9RvBvlSd6gbuNI7QwiLoCCAlGnlRJFPrzLI6U1/9wkC/WK6LtBAUln55H1Ctqw45PWmqrobKoMhsYQzQ=="], + + "@oxc-parser/binding-linux-x64-musl": ["@oxc-parser/binding-linux-x64-musl@0.127.0", "", { "os": "linux", "cpu": "x64" }, "sha512-5eY0B/bxf1xIUxb4NOTvOI3KWtBQfPWYyKAzgcrCt0mDibSZygVpO1Pz8bkeiSZ5Jj9+M09dkggG3H8I5d0Uyg=="], + + "@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.127.0", "", { "os": "none", "cpu": "arm64" }, "sha512-Gld0ajrFTUXNtdw20fVBuTQx66FA75nIVg+//pPfR3sXkuABB4mTBhl3r9JNzrJpgW//qiwxf0nWXUWGJSL3UQ=="], + + "@oxc-parser/binding-wasm32-wasi": ["@oxc-parser/binding-wasm32-wasi@0.127.0", "", { "dependencies": { "@emnapi/core": "1.9.2", "@emnapi/runtime": "1.9.2", "@napi-rs/wasm-runtime": "^1.1.4" }, "cpu": "none" }, "sha512-T6KVD7rhLzFlwGRXMnxUFfkCZD8FHnb968wVXW1mXzgRFc5RNXOBY2mPPDZ77x5Ln76ltLMgtPg0cOkU1NSrEQ=="], + + "@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.127.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-Ujvw4X+LD1CCGULcsQcvb4YNVoBGqt+JHgNNzGGaCImELiZLk477ifUH53gIbE7EKd933NdTi25JWEr9K2HwXw=="], + + "@oxc-parser/binding-win32-ia32-msvc": ["@oxc-parser/binding-win32-ia32-msvc@0.127.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-0cwxKO7KHQQQfo4Uf4B2SQrhgm+cJaP9OvFFhx52Tkg4bezsacu83GB2/In5bC415Ueeym+kXdnge/57rbSfTw=="], + + "@oxc-parser/binding-win32-x64-msvc": ["@oxc-parser/binding-win32-x64-msvc@0.127.0", "", { "os": "win32", "cpu": "x64" }, "sha512-rOrnSQSCbhI2kowr9XxE7m9a8oQXnBHjnS6j95LxxAnEZ0+Fz20WlRXG4ondQb+ejjt2KOsa65sE6++L6kUd+w=="], + + "@oxc-project/types": ["@oxc-project/types@0.127.0", "", {}, "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ=="], + + "@oxc-resolver/binding-android-arm-eabi": ["@oxc-resolver/binding-android-arm-eabi@11.20.0", "", { "os": "android", "cpu": "arm" }, "sha512-IjfWOXRgJFNdORDl+Uf1aibNgZY2guOD3zmOhx1BGVb/MIiqlFTdmjpQNplSN58lhWehnX4UNqC3QwpUo8pjJg=="], + + "@oxc-resolver/binding-android-arm64": ["@oxc-resolver/binding-android-arm64@11.20.0", "", { "os": "android", "cpu": "arm64" }, "sha512-QqslZAuFQG8Q9xm7JuIn8JUbvywhSBMVhuQHtYW+auirZJloS41oxUUaBXk7uUhZJgp44c5zQLeVvmFaDQB+2Q=="], + + "@oxc-resolver/binding-darwin-arm64": ["@oxc-resolver/binding-darwin-arm64@11.20.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-MUcavykj2ewlR+kc5arpg4tC2RvzJkUxWtNv74pf7lcNk00GpIpN43vXMj+j6r4eMmfZhlb8hueKoIb8e9kAGQ=="], + + "@oxc-resolver/binding-darwin-x64": ["@oxc-resolver/binding-darwin-x64@11.20.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-BGB16nRUK5Etiv//ihPyzj8Lj1px0mhh4YIfe0FDf045ywknfSm0GEbiRESpr6Q4K82AvnyaRIhhluHByvS4bg=="], + + "@oxc-resolver/binding-freebsd-x64": ["@oxc-resolver/binding-freebsd-x64@11.20.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JZgtePaqj3qmD5XFHJaSLWzHRxQu0LaPkdoM1KJXYADvAaa83ijXHclV3ej3CueeW0wxfIAbGCZVP45J0CA7uQ=="], + + "@oxc-resolver/binding-linux-arm-gnueabihf": ["@oxc-resolver/binding-linux-arm-gnueabihf@11.20.0", "", { "os": "linux", "cpu": "arm" }, "sha512-hOQ/p3ry3v3SchUBXicrrnszaI/UmYzM4wtS4RGfwgVUX7a+HbyQSzJ5aOzu+o6XZkFkS3ZXN4PZAzhOb77OSg=="], + + "@oxc-resolver/binding-linux-arm-musleabihf": ["@oxc-resolver/binding-linux-arm-musleabihf@11.20.0", "", { "os": "linux", "cpu": "arm" }, "sha512-2ArPksaw0AqeuGBfoS715VF+JvJQAhD2niWgjE5hVO+L+nAfikVQopvngCMX9x4BD8itWoQ3dnikrQyl5Ho5Jg=="], + + "@oxc-resolver/binding-linux-arm64-gnu": ["@oxc-resolver/binding-linux-arm64-gnu@11.20.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-0bJnmYFp62JdZ4nVMDUZ/C58BCZOCcqgKtnUlp7L9Ojf/czIN+3j72YlLPeWLkzlr6SlYvIQA4SGV/HyO0d+qg=="], + + "@oxc-resolver/binding-linux-arm64-musl": ["@oxc-resolver/binding-linux-arm64-musl@11.20.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-wKHHzPKZo7Ufhv/Bt6yxT7FOgnIgW4gwXcJUipkShGp68W3wGVqvr1Sr0fY65lN0Oy6y41+g2kIDvkgZaMMUkw=="], + + "@oxc-resolver/binding-linux-ppc64-gnu": ["@oxc-resolver/binding-linux-ppc64-gnu@11.20.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-RN8goF7Ie0B79L4i4G6OeBocTgSC56vJbQ65VJje+oXnldVpLnOU7j/AQ/dP94TcCS+Yh6WG8u3Qt4ETteXFNQ=="], + + "@oxc-resolver/binding-linux-riscv64-gnu": ["@oxc-resolver/binding-linux-riscv64-gnu@11.20.0", "", { "os": "linux", "cpu": "none" }, "sha512-5l1yU6/xQEqLZRzxqmMxJfWPslpwCmBsdDGaBvABPehxquCXDC7dd7oraNdKSJUMDXSM7VvVj8H2D2FTjU7oWw=="], + + "@oxc-resolver/binding-linux-riscv64-musl": ["@oxc-resolver/binding-linux-riscv64-musl@11.20.0", "", { "os": "linux", "cpu": "none" }, "sha512-xHEvkbgz6UC+A3JOyDQy76LkUaxsNSfIr3/GV8slwZsnuooJiIB34gzJfsyvR4JdCYNUUPsRJc/w/oWkODu+hg=="], + + "@oxc-resolver/binding-linux-s390x-gnu": ["@oxc-resolver/binding-linux-s390x-gnu@11.20.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-aWPDUUmSeyHvlW+SoEUd+JIJsQhVhu6a5tBpDRMu058naPAchTgAVGCFy35zjbnFlt0i8hLWziff6HX0D3LU4g=="], + + "@oxc-resolver/binding-linux-x64-gnu": ["@oxc-resolver/binding-linux-x64-gnu@11.20.0", "", { "os": "linux", "cpu": "x64" }, "sha512-x2YeSimvhJjKLVD8KSu8f/rqU1potcdEMkApIPJqjZWN7c2Fpt4g2X32WDg1p+XDAmyT7nuQGe0vnhvXeLbH+g=="], + + "@oxc-resolver/binding-linux-x64-musl": ["@oxc-resolver/binding-linux-x64-musl@11.20.0", "", { "os": "linux", "cpu": "x64" }, "sha512-kcRLEIxpZefeYfLChjpgFf3ilBzRDZ+yobMrpRsQlSrxuFGtm3U6PMU7AaEpMqo3NfDGVyJJseAjnRLzMFHjwQ=="], + + "@oxc-resolver/binding-openharmony-arm64": ["@oxc-resolver/binding-openharmony-arm64@11.20.0", "", { "os": "none", "cpu": "arm64" }, "sha512-HHcfnApSZGtKhTiHqe8OZruOZe5XuFQH5/E0Yhj3u8fnFvzkM4/k6WjacUf4SvA0SPEAbfbgYmVPuo0VX/fIBQ=="], + + "@oxc-resolver/binding-wasm32-wasi": ["@oxc-resolver/binding-wasm32-wasi@11.20.0", "", { "dependencies": { "@emnapi/core": "1.10.0", "@emnapi/runtime": "1.10.0", "@napi-rs/wasm-runtime": "^1.1.4" }, "cpu": "none" }, "sha512-Tn0y1XOFYHNfK1wp1Z5QK8Rcld/bsOwRISQXfqAZ5IBpv8Gz1IvV39fUWNprqNdRizgcvFhOzWwFun2zkJsyBg=="], + + "@oxc-resolver/binding-win32-arm64-msvc": ["@oxc-resolver/binding-win32-arm64-msvc@11.20.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-qPi25YNPe4YenS8MgsQU2+bIFHxxpLx1LVna2444cEHqNPhNjvWf9zqj4aWE43H9LpAsTmkkAlA3eL5ElBU3mA=="], + + "@oxc-resolver/binding-win32-x64-msvc": ["@oxc-resolver/binding-win32-x64-msvc@11.20.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Wb14jWEW8huH6It9F6sXd9vrYmIS7pMrgkU6sxpLxkP+9z+wRgs71hUEhRpcn8FOXAFa27FVWfY2tRpbfTzfLw=="], + "@oxc-transform/binding-android-arm64": ["@oxc-transform/binding-android-arm64@0.96.0", "", { "os": "android", "cpu": "arm64" }, "sha512-wOm+ZsqFvyZ7B9RefUMsj0zcXw77Z2pXA51nbSQyPXqr+g0/pDGxriZWP8Sdpz/e4AEaKPA9DvrwyOZxu7GRDQ=="], "@oxc-transform/binding-darwin-arm64": ["@oxc-transform/binding-darwin-arm64@0.96.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-td1sbcvzsyuoNRiNdIRodPXRtFFwxzPpC/6/yIUtRRhKn30XQcizxupIvQQVpJWWchxkphbBDh6UN+u+2CJ8Zw=="], @@ -1833,21 +2030,21 @@ "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="], - "@protobufjs/codegen": ["@protobufjs/codegen@2.0.4", "", {}, "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg=="], + "@protobufjs/codegen": ["@protobufjs/codegen@2.0.5", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="], - "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.0", "", {}, "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q=="], + "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.1", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="], - "@protobufjs/fetch": ["@protobufjs/fetch@1.1.0", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1", "@protobufjs/inquire": "^1.1.0" } }, "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ=="], + "@protobufjs/fetch": ["@protobufjs/fetch@1.1.1", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="], "@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="], - "@protobufjs/inquire": ["@protobufjs/inquire@1.1.0", "", {}, "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q=="], + "@protobufjs/inquire": ["@protobufjs/inquire@1.1.2", "", {}, "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw=="], "@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="], "@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="], - "@protobufjs/utf8": ["@protobufjs/utf8@1.1.0", "", {}, "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw=="], + "@protobufjs/utf8": ["@protobufjs/utf8@1.1.1", "", {}, "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg=="], "@radix-ui/colors": ["@radix-ui/colors@1.0.1", "", {}, "sha512-xySw8f0ZVsAEP+e7iLl3EvcBXX7gsIlC1Zso/sPBW9gIWerBTgz6axrjU+MZ39wD+WFi5h5zdWpsg3+hwt2Qsg=="], @@ -1915,57 +2112,57 @@ "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.27", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="], - "@rollup/pluginutils": ["@rollup/pluginutils@5.3.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-5EdhGZtnu3V88ces7s53hhfK5KSASnJZv8Lulpc04cWO3REESroJXg73DFsOmgbU2BhwV0E20bu2IDZb3VKW4Q=="], + "@rollup/pluginutils": ["@rollup/pluginutils@5.4.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg=="], - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.60.1", "", { "os": "android", "cpu": "arm" }, "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA=="], + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.60.4", "", { "os": "android", "cpu": "arm" }, "sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ=="], - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.60.1", "", { "os": "android", "cpu": "arm64" }, "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA=="], + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.60.4", "", { "os": "android", "cpu": "arm64" }, "sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw=="], - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.60.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw=="], + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.60.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA=="], - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.60.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew=="], + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.60.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg=="], - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.60.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w=="], + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.60.4", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g=="], - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.60.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g=="], + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.60.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw=="], - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.60.1", "", { "os": "linux", "cpu": "arm" }, "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g=="], + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.60.4", "", { "os": "linux", "cpu": "arm" }, "sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA=="], - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.60.1", "", { "os": "linux", "cpu": "arm" }, "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg=="], + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.60.4", "", { "os": "linux", "cpu": "arm" }, "sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w=="], - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.60.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ=="], + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.60.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg=="], - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.60.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA=="], + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.60.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A=="], - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ=="], + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.60.4", "", { "os": "linux", "cpu": "none" }, "sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ=="], - "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw=="], + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.60.4", "", { "os": "linux", "cpu": "none" }, "sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw=="], - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.60.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw=="], + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.60.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg=="], - "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.60.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg=="], + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.60.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A=="], - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg=="], + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.60.4", "", { "os": "linux", "cpu": "none" }, "sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA=="], - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg=="], + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.60.4", "", { "os": "linux", "cpu": "none" }, "sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw=="], - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.60.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ=="], + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.60.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ=="], - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.60.1", "", { "os": "linux", "cpu": "x64" }, "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg=="], + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.60.4", "", { "os": "linux", "cpu": "x64" }, "sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ=="], - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.60.1", "", { "os": "linux", "cpu": "x64" }, "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w=="], + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.60.4", "", { "os": "linux", "cpu": "x64" }, "sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg=="], - "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.60.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw=="], + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.60.4", "", { "os": "openbsd", "cpu": "x64" }, "sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA=="], - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.60.1", "", { "os": "none", "cpu": "arm64" }, "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA=="], + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.60.4", "", { "os": "none", "cpu": "arm64" }, "sha512-IPOsh5aRYuLv/nkU51X10Bf75Bsf6+gZdx1X+QP5QM6lIJFHHqbHLG0uJn/hWthzo13UAc2umiUorqZy3axoZg=="], - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.60.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g=="], + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.60.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-4QzE9E81OohJ/HKzHhsqU+zcYYojVOXlFMs1DdyMT6qXl/niOH7AVElmmEdUNHHS/oRkc++d5k6Vy85zFs0DEw=="], - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.60.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg=="], + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.60.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-zTPgT1YuHHcd+Tmx7h8aml0FWFVelV5N54oHow9SLj+GfoDy/huQ+UV396N/C7KpMDMiPspRktzM1/0r1usYEA=="], - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.60.1", "", { "os": "win32", "cpu": "x64" }, "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg=="], + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.60.4", "", { "os": "win32", "cpu": "x64" }, "sha512-DRS4G7mi9lJxqEDezIkKCaUIKCrLUUDCUaCsTPCi/rtqaC6D/jjwslMQyiDU50Ka0JKpeXeRBFBAXwArY52vBw=="], - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.60.1", "", { "os": "win32", "cpu": "x64" }, "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ=="], + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.60.4", "", { "os": "win32", "cpu": "x64" }, "sha512-QVTUovf40zgTqlFVrKA1uXMVvU2QWEFWfAH8Wdc48IxLvrJMQVMBRjuQyUpzZCDkakImib9eVazbWlC6ksWtJw=="], "@selderee/plugin-htmlparser2": ["@selderee/plugin-htmlparser2@0.11.0", "", { "dependencies": { "domhandler": "^5.0.3", "selderee": "^0.11.0" } }, "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ=="], @@ -1983,23 +2180,23 @@ "@sentry/bundler-plugin-core": ["@sentry/bundler-plugin-core@4.6.0", "", { "dependencies": { "@babel/core": "^7.18.5", "@sentry/babel-plugin-component-annotate": "4.6.0", "@sentry/cli": "^2.57.0", "dotenv": "^16.3.1", "find-up": "^5.0.0", "glob": "^9.3.2", "magic-string": "0.30.8", "unplugin": "1.0.1" } }, "sha512-Fub2XQqrS258jjS8qAxLLU1k1h5UCNJ76i8m4qZJJdogWWaF8t00KnnTyp9TEDJzrVD64tRXS8+HHENxmeUo3g=="], - "@sentry/cli": ["@sentry/cli@2.58.5", "", { "dependencies": { "https-proxy-agent": "^5.0.0", "node-fetch": "^2.6.7", "progress": "^2.0.3", "proxy-from-env": "^1.1.0", "which": "^2.0.2" }, "optionalDependencies": { "@sentry/cli-darwin": "2.58.5", "@sentry/cli-linux-arm": "2.58.5", "@sentry/cli-linux-arm64": "2.58.5", "@sentry/cli-linux-i686": "2.58.5", "@sentry/cli-linux-x64": "2.58.5", "@sentry/cli-win32-arm64": "2.58.5", "@sentry/cli-win32-i686": "2.58.5", "@sentry/cli-win32-x64": "2.58.5" }, "bin": { "sentry-cli": "bin/sentry-cli" } }, "sha512-tavJ7yGUZV+z3Ct2/ZB6mg339i08sAk6HDkgqmSRuQEu2iLS5sl9HIvuXfM6xjv8fwlgFOSy++WNABNAcGHUbg=="], + "@sentry/cli": ["@sentry/cli@2.58.6", "", { "dependencies": { "https-proxy-agent": "^5.0.0", "node-fetch": "^2.6.7", "progress": "^2.0.3", "proxy-from-env": "^1.1.0", "which": "^2.0.2" }, "optionalDependencies": { "@sentry/cli-darwin": "2.58.6", "@sentry/cli-linux-arm": "2.58.6", "@sentry/cli-linux-arm64": "2.58.6", "@sentry/cli-linux-i686": "2.58.6", "@sentry/cli-linux-x64": "2.58.6", "@sentry/cli-win32-arm64": "2.58.6", "@sentry/cli-win32-i686": "2.58.6", "@sentry/cli-win32-x64": "2.58.6" }, "bin": { "sentry-cli": "bin/sentry-cli" } }, "sha512-baBcNPLLfUi9WuL+Tpri9BFaAdvugZIKelC5X0tt0Zdy+K0K+PCVSrnNmwMWU/HyaF/SEv6b6UHnXIdqanBlcg=="], - "@sentry/cli-darwin": ["@sentry/cli-darwin@2.58.5", "", { "os": "darwin" }, "sha512-lYrNzenZFJftfwSya7gwrHGxtE+Kob/e1sr9lmHMFOd4utDlmq0XFDllmdZAMf21fxcPRI1GL28ejZ3bId01fQ=="], + "@sentry/cli-darwin": ["@sentry/cli-darwin@2.58.6", "", { "os": "darwin" }, "sha512-udAVvcyfNa0R+95GvPz/+43/N3TC0TYKdkQ7D7jhPSzbcMc7l2fxRNN5yB3UpCA5fWFnW4toeaqwDBhb/Wh3LA=="], - "@sentry/cli-linux-arm": ["@sentry/cli-linux-arm@2.58.5", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "arm" }, "sha512-KtHweSIomYL4WVDrBrYSYJricKAAzxUgX86kc6OnlikbyOhoK6Fy8Vs6vwd52P6dvWPjgrMpUYjW2M5pYXQDUw=="], + "@sentry/cli-linux-arm": ["@sentry/cli-linux-arm@2.58.6", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "arm" }, "sha512-pD0LAt5PcUzAinBwvDqc66x9+2CabHEv486yP0gRjWO7SakbaxmfVq/EXd8VLq/Tzi39LAu422UYK1lpW3MILw=="], - "@sentry/cli-linux-arm64": ["@sentry/cli-linux-arm64@2.58.5", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "arm64" }, "sha512-/4gywFeBqRB6tR/iGMRAJ3HRqY6Z7Yp4l8ZCbl0TDLAfHNxu7schEw4tSnm2/Hh9eNMiOVy4z58uzAWlZXAYBQ=="], + "@sentry/cli-linux-arm64": ["@sentry/cli-linux-arm64@2.58.6", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "arm64" }, "sha512-q8mEcNNmeXMy5i+jWT30TVpH7LcP4HD21CD5XRSPAd/a912HF6EpK0ybf/1USO14WOhoXbAGi9txwaWabSe33g=="], - "@sentry/cli-linux-i686": ["@sentry/cli-linux-i686@2.58.5", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "ia32" }, "sha512-G7261dkmyxqlMdyvyP06b+RTIVzp1gZNgglj5UksxSouSUqRd/46W/2pQeOMPhloDYo9yLtCN2YFb3Mw4aUsWw=="], + "@sentry/cli-linux-i686": ["@sentry/cli-linux-i686@2.58.6", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "ia32" }, "sha512-q8vNJi1eOV/4vxAFWBsEwLHoSYapaZHIf4j76KJGJXFKTkEbsjCOOsKbwUIBTQQhRgV4DFWh3ryfsPS/que4Kg=="], - "@sentry/cli-linux-x64": ["@sentry/cli-linux-x64@2.58.5", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "x64" }, "sha512-rP04494RSmt86xChkQ+ecBNRYSPbyXc4u0IA7R7N1pSLCyO74e5w5Al+LnAq35cMfVbZgz5Sm0iGLjyiUu4I1g=="], + "@sentry/cli-linux-x64": ["@sentry/cli-linux-x64@2.58.6", "", { "os": [ "linux", "android", "freebsd", ], "cpu": "x64" }, "sha512-DZu956Mhi3ZRjTBe1WdbGV46ldVbA8d2rgp/fh51GsI25zjBHah4wZnPTSzpc+YqxU6pJpg579B/r3jrIK530Q=="], - "@sentry/cli-win32-arm64": ["@sentry/cli-win32-arm64@2.58.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-AOJ2nCXlQL1KBaCzv38m3i2VmSHNurUpm7xVKd6yAHX+ZoVBI8VT0EgvwmtJR2TY2N2hNCC7UrgRmdUsQ152bA=="], + "@sentry/cli-win32-arm64": ["@sentry/cli-win32-arm64@2.58.6", "", { "os": "win32", "cpu": "arm64" }, "sha512-nj0Ff/kmAB73EPDhR8B4O9r+NUHK5GkPCkGWC+kXVemqAJWL5jcJ5KdxG0l/S0z6RoEoltID8/43/B+TaMlT7A=="], - "@sentry/cli-win32-i686": ["@sentry/cli-win32-i686@2.58.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-EsuboLSOnlrN7MMPJ1eFvfMDm+BnzOaSWl8eYhNo8W/BIrmNgpRUdBwnWn9Q2UOjJj5ZopukmsiMYtU/D7ml9g=="], + "@sentry/cli-win32-i686": ["@sentry/cli-win32-i686@2.58.6", "", { "os": "win32", "cpu": "ia32" }, "sha512-WNZiDzPbgsEMQWq4avsQ391v/xWKJDIWWWo9GYl+N/w5qcYKkoDW7wQG7T9FasI6ENn68phChTOAPXXxbfAdOg=="], - "@sentry/cli-win32-x64": ["@sentry/cli-win32-x64@2.58.5", "", { "os": "win32", "cpu": "x64" }, "sha512-IZf+XIMiQwj+5NzqbOQfywlOitmCV424Vtf9c+ep61AaVScUFD1TSrQbOcJJv5xGxhlxNOMNgMeZhdexdzrKZg=="], + "@sentry/cli-win32-x64": ["@sentry/cli-win32-x64@2.58.6", "", { "os": "win32", "cpu": "x64" }, "sha512-R35WJ17oF4D2eqI1DR2sQQqr0fjRTt5xoP16WrTu91XM2lndRMFsnjh+/GttbxapLCBNlrjzia99MJ0PZHZpgA=="], "@sentry/core": ["@sentry/core@10.36.0", "", {}, "sha512-EYJjZvofI+D93eUsPLDIUV0zQocYqiBRyXS6CCV6dHz64P/Hob5NJQOwPa8/v6nD+UvJXvwsFfvXOHhYZhZJOQ=="], @@ -2025,7 +2222,7 @@ "@sigstore/bundle": ["@sigstore/bundle@4.0.0", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A=="], - "@sigstore/core": ["@sigstore/core@3.2.0", "", {}, "sha512-kxHrDQ9YgfrWUSXU0cjsQGv8JykOFZQ9ErNKbFPWzk3Hgpwu8x2hHrQ9IdA8yl+j9RTLTC3sAF3Tdq1IQCP4oA=="], + "@sigstore/core": ["@sigstore/core@3.2.1", "", {}, "sha512-qRsxPnCrbC/puegGxKuynfnxgLiHqWStrSjxkoB4YKqq3Z3s4cyZyj42ZdWFAEblNP65C+rBH8EuREHIXoi83g=="], "@sigstore/protobuf-specs": ["@sigstore/protobuf-specs@0.5.1", "", {}, "sha512-/ScWUhhoFasJsSRGTVBwId1loQjjnjAfE4djL6ZhrXRpNCmPTnUKF5Jokd58ILseOMjzET3UrMOtJPS9sYeI0g=="], @@ -2033,7 +2230,7 @@ "@sigstore/tuf": ["@sigstore/tuf@4.0.2", "", { "dependencies": { "@sigstore/protobuf-specs": "^0.5.0", "tuf-js": "^4.1.0" } }, "sha512-TCAzTy0xzdP79EnxSjq9KQ3eaR7+FmudLC6eRKknVKZbV7ZNlGLClAAQb/HMNJ5n2OBNk2GT1tEmU0xuPr+SLQ=="], - "@sigstore/verify": ["@sigstore/verify@3.1.0", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.1.0", "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-mNe0Iigql08YupSOGv197YdHpPPr+EzDZmfCgMc7RPNaZTw5aLN01nBl6CHJOh3BGtnMIj83EeN4butBchc8Ag=="], + "@sigstore/verify": ["@sigstore/verify@3.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0" } }, "sha512-qv7+G3J2cc6wwFj3yKvXOamzqhMwSk1ogPGmhpS8iXllcPrJaIIBA+4HbttlHVu1pqWTdmaCH/WE7UOC51kdoA=="], "@silvia-odwyer/photon-node": ["@silvia-odwyer/photon-node@0.3.4", "", {}, "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA=="], @@ -2047,109 +2244,93 @@ "@slack/socket-mode": ["@slack/socket-mode@1.3.6", "", { "dependencies": { "@slack/logger": "^3.0.0", "@slack/web-api": "^6.12.1", "@types/node": ">=12.0.0", "@types/ws": "^7.4.7", "eventemitter3": "^5", "finity": "^0.5.4", "ws": "^7.5.3" } }, "sha512-G+im7OP7jVqHhiNSdHgv2VVrnN5U7KY845/5EZimZkrD4ZmtV0P3BiWkgeJhPtdLuM7C7i6+M6h6Bh+S4OOalA=="], - "@slack/types": ["@slack/types@2.20.1", "", {}, "sha512-eWX2mdt1ktpn8+40iiMc404uGrih+2fxiky3zBcPjtXKj6HLRdYlmhrPkJi7JTJm8dpXR6BWVWEDBXtaWMKD6A=="], + "@slack/types": ["@slack/types@2.21.1", "", {}, "sha512-I8vmSjNYWsaxuWPx6dz4yeh0h7vRBWbgAMK14LEmblbZ404BtrPbXs6jDPx4cYgGf8msDGF4A9opLZBu21FViQ=="], "@slack/web-api": ["@slack/web-api@6.13.0", "", { "dependencies": { "@slack/logger": "^3.0.0", "@slack/types": "^2.11.0", "@types/is-stream": "^1.1.0", "@types/node": ">=12.0.0", "axios": "^1.7.4", "eventemitter3": "^3.1.0", "form-data": "^2.5.0", "is-electron": "2.2.2", "is-stream": "^1.1.0", "p-queue": "^6.6.1", "p-retry": "^4.0.0" } }, "sha512-dv65crIgdh9ZYHrevLU6XFHTQwTyDmNqEqzuIrV+Vqe/vgiG6w37oex5ePDU1RGm2IJ90H8iOvHFvzdEO/vB+g=="], - "@smithy/chunked-blob-reader": ["@smithy/chunked-blob-reader@5.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-St+kVicSyayWQca+I1rGitaOEH6uKgE8IUWoYnnEX26SWdWQcL6LvMSD19Lg+vYHKdT9B2Zuu7rd3i6Wnyb/iw=="], + "@smithy/config-resolver": ["@smithy/config-resolver@4.5.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-HehAZr4sq2m+4zHgEqDvtWENy/B5yywMKA8Pl4gBcU3F4ekelpZqDLDxQHdJlguaKNyTq31cZYjLWomzdujQrA=="], - "@smithy/chunked-blob-reader-native": ["@smithy/chunked-blob-reader-native@4.2.3", "", { "dependencies": { "@smithy/util-base64": "^4.3.2", "tslib": "^2.6.2" } }, "sha512-jA5k5Udn7Y5717L86h4EIv06wIr3xn8GM1qHRi/Nf31annXcXHJjBKvgztnbn2TxH3xWrPBfgwHsOwZf0UmQWw=="], + "@smithy/core": ["@smithy/core@3.24.5", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-Kt8phUg45M15EjhYAbZ+fFikYneijLu9Liugz8ZsYz2i8j0hzGv27LWKpEHYRfvj+LyCOSijpcR/2i8RouV+cA=="], - "@smithy/config-resolver": ["@smithy/config-resolver@4.4.15", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "@smithy/util-endpoints": "^3.4.0", "@smithy/util-middleware": "^4.2.13", "tslib": "^2.6.2" } }, "sha512-BJdMBY5YO9iHh+lPLYdHv6LbX+J8IcPCYMl1IJdBt2KDWNHwONHrPVHk3ttYBqJd9wxv84wlbN0f7GlQzcQtNQ=="], - - "@smithy/core": ["@smithy/core@3.23.14", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-stream": "^4.5.22", "@smithy/util-utf8": "^4.2.2", "@smithy/uuid": "^1.1.2", "tslib": "^2.6.2" } }, "sha512-vJ0IhpZxZAkFYOegMKSrxw7ujhhT2pass/1UEcZ4kfl5srTAqtPU5I7MdYQoreVas3204ykCiNhY1o7Xlz6Yyg=="], - - "@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.2.13", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "tslib": "^2.6.2" } }, "sha512-wboCPijzf6RJKLOvnjDAiBxGSmSnGXj35o5ZAWKDaHa/cvQ5U3ZJ13D4tMCE8JG4dxVAZFy/P0x/V9CwwdfULQ=="], + "@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.3.6", "", { "dependencies": { "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-tHhdiWZfG1ZIh2YcRfPJmY2gHcBmqbAzqm3ER4TIDFYsSEqTD5tICT7cgQ/kI8LRakxp12myOYyK68XPn7MnHw=="], "@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.2.7", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.11.0", "@smithy/util-hex-encoding": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-DrpkEoM3j9cBBWhufqBwnbbn+3nf1N9FP6xuVJ+e220jbactKuQgaZwjwP5CP1t+O94brm2JgVMD2atMGX3xIQ=="], - "@smithy/eventstream-serde-browser": ["@smithy/eventstream-serde-browser@4.2.13", "", { "dependencies": { "@smithy/eventstream-serde-universal": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-wwybfcOX0tLqCcBP378TIU9IqrDuZq/tDV48LlZNydMpCnqnYr+hWBAYbRE+rFFf/p7IkDJySM3bgiMKP2ihPg=="], - - "@smithy/eventstream-serde-config-resolver": ["@smithy/eventstream-serde-config-resolver@4.3.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-ied1lO559PtAsMJzg2TKRlctLnEi1PfkNeMMpdwXDImk1zV9uvS/Oxoy/vcy9uv1GKZAjDAB5xT6ziE9fzm5wA=="], - - "@smithy/eventstream-serde-node": ["@smithy/eventstream-serde-node@4.2.13", "", { "dependencies": { "@smithy/eventstream-serde-universal": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-hFyK+ORJrxAN3RYoaD6+gsGDQjeix8HOEkosoajvXYZ4VeqonM3G4jd9IIRm/sWGXUKmudkY9KdYjzosUqdM8A=="], - - "@smithy/eventstream-serde-universal": ["@smithy/eventstream-serde-universal@4.2.13", "", { "dependencies": { "@smithy/eventstream-codec": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-kRrq4EKLGeOxhC2CBEhRNcu1KSzNJzYY7RK3S7CxMPgB5dRrv55WqQOtRwQxQLC04xqORFLUgnDlc6xrNUULaA=="], - - "@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.3.16", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/querystring-builder": "^4.2.13", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "tslib": "^2.6.2" } }, "sha512-nYDRUIvNd4mFmuXraRWt6w5UsZTNqtj4hXJA/iiOD4tuseIdLP9Lq38teH/SZTcIFCa2f+27o7hYpIsWktJKEQ=="], - - "@smithy/hash-blob-browser": ["@smithy/hash-blob-browser@4.2.14", "", { "dependencies": { "@smithy/chunked-blob-reader": "^5.2.2", "@smithy/chunked-blob-reader-native": "^4.2.3", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-rtQ5es8r/5v4rav7q5QTsfx9CtCyzrz/g7ZZZBH2xtMmd6G/KQrLOWfSHTvFOUPlVy59RQvxeBYJaLRoybMEyA=="], + "@smithy/eventstream-serde-browser": ["@smithy/eventstream-serde-browser@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-M9rMkTar7JcRrvUHsK1271AuWDmrISIPQpQ4TSHmYZ4KMisGnMH0gfjCWnBwdndR7skvvp/UheHhZGvO3Cr8/g=="], - "@smithy/hash-node": ["@smithy/hash-node@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-buffer-from": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-4/oy9h0jjmY80a2gOIo75iLl8TOPhmtx4E2Hz+PfMjvx/vLtGY4TMU/35WRyH2JHPfT5CVB38u4JRow7gnmzJA=="], + "@smithy/eventstream-serde-config-resolver": ["@smithy/eventstream-serde-config-resolver@4.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-lUwPPu7DNNVJjeS+gV7g2rDHbW9X1wSRQIsIyzOgBtP7KDMefLhz0kz42AWAxZIFPcOO3pUbtq76LSkVcxLKRw=="], - "@smithy/hash-stream-node": ["@smithy/hash-stream-node@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-WdQ7HwUjINXETeh6dqUeob1UHIYx8kAn9PSp1HhM2WWegiZBYVy2WXIs1lB07SZLan/udys9SBnQGt9MQbDpdg=="], + "@smithy/eventstream-serde-node": ["@smithy/eventstream-serde-node@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-QydEYKqvdiS6dJb0tOfDiogt12FzzImt2FnL7gMD72hNrkiUAUKqtStRmkTrdzDKFJ46abe3yH94luCuhtnCkQ=="], - "@smithy/invalid-dependency": ["@smithy/invalid-dependency@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-jvC0RB/8BLj2SMIkY0Npl425IdnxZJxInpZJbu563zIRnVjpDMXevU3VMCRSabaLB0kf/eFIOusdGstrLJ8IDg=="], + "@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-SK3VMeH0fibgdTg2QeB+O4p7Yy/2E5HBOHJeC58FshkDdeuX8lOgO7PfjYfLyPLP1ch55j91cQqKBzDS0mRjSQ=="], - "@smithy/is-array-buffer": ["@smithy/is-array-buffer@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow=="], + "@smithy/hash-blob-browser": ["@smithy/hash-blob-browser@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-DNInwxNX32WtmhiKVrplzFtkKk5ePNHitJYPCnsPrD2EHm06iWJKQo8F8eq5ss94yp/xSfmojYD7nFBsgzrHHQ=="], - "@smithy/md5-js": ["@smithy/md5-js@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-cNm7I9NXolFxtS20ojROddOEpSAeI1Obq6pd1Kj5HtHws3s9Fkk8DdHDfQSs5KuxCewZuVK6UqrJnfJmiMzDuQ=="], + "@smithy/hash-node": ["@smithy/hash-node@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-/tUIDaB36qjLq/CIhMRIiFXCT7rVGBGAhFmMA9PbC/iW2u3QPNATZuFSdK0JBO3qeSPoHBeudFMmsbFq2Mf5EQ=="], - "@smithy/middleware-content-length": ["@smithy/middleware-content-length@4.2.13", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-IPMLm/LE4AZwu6qiE8Rr8vJsWhs9AtOdySRXrOM7xnvclp77Tyh7hMs/FRrMf26kgIe67vFJXXOSmVxS7oKeig=="], + "@smithy/hash-stream-node": ["@smithy/hash-stream-node@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-dLboKYf5ezU+b8SDDzVNjSHWHYPiU9aTI7IfIh9GhUpvCkwfdw1zUtK6dAGFHOrI5l1nVmsEWZrcAHophlNKug=="], - "@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.29", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/middleware-serde": "^4.2.17", "@smithy/node-config-provider": "^4.3.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-middleware": "^4.2.13", "tslib": "^2.6.2" } }, "sha512-R9Q/58U+qBiSARGWbAbFLczECg/RmysRksX6Q8BaQEpt75I7LI6WGDZnjuC9GXSGKljEbA7N118LhGaMbfrTXw=="], + "@smithy/invalid-dependency": ["@smithy/invalid-dependency@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-c8C1GzrU4PcY1QT/HP0ILCTLutyVONT93kPSisOyHoZaXlKQZtV6+RKqolhBtPolGULf59vq2yseagU6+WY82w=="], - "@smithy/middleware-retry": ["@smithy/middleware-retry@4.5.1", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/protocol-http": "^5.3.13", "@smithy/service-error-classification": "^4.2.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.1", "@smithy/uuid": "^1.1.2", "tslib": "^2.6.2" } }, "sha512-/zY+Gp7Qj2D2hVm3irkCyONER7E9MiX3cUUm/k2ZmhkzZkrPgwVS4aJ5NriZUEN/M0D1hhjrgjUmX04HhRwdWA=="], + "@smithy/is-array-buffer": ["@smithy/is-array-buffer@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-AzWk7NstKv+z3h0GmZlQkDdgcnh3tvBWnBr0zoBY/agV/zaMqEBnpqgF1S+sJAy5yfE1b2KZqiz+uHHV70vOYg=="], - "@smithy/middleware-serde": ["@smithy/middleware-serde@4.2.17", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-0T2mcaM6v9W1xku86Dk0bEW7aEseG6KenFkPK98XNw0ZhOqOiD1MrMsdnQw9QsL3/Oa85T53iSMlm0SZdSuIEQ=="], + "@smithy/md5-js": ["@smithy/md5-js@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-U/zFWFDuNFspkLAtUbatmpevrRjXwQkoGPJTg1hapUsjLKK+aN3u4seX4+aSBzLom+RnZSdWncfSIgG100vsGg=="], - "@smithy/middleware-stack": ["@smithy/middleware-stack@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-g72jN/sGDLyTanrCLH9fhg3oysO3f7tQa6eWWsMyn2BiYNCgjF24n4/I9wff/5XidFvjj9ilipAoQrurTUrLvw=="], + "@smithy/middleware-content-length": ["@smithy/middleware-content-length@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-lzOzJ4c0t3vkBut02CjdWNgduN3mUWjc1WK9TPr75KVV6OgVWico9wMDn9ZnQN97VJPYfweBW6Dm5CElvQl8BQ=="], - "@smithy/node-config-provider": ["@smithy/node-config-provider@4.3.13", "", { "dependencies": { "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-iGxQ04DsKXLckbgnX4ipElrOTk+IHgTyu0q0WssZfYhDm9CQWHmu6cOeI5wmWRxpXbBDhIIfXMWz5tPEtcVqbw=="], + "@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.5.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-8DnkSoUMQAcuT/DHdigsFPti8M/Dm6TPCAsrIQ/bUDGxRkrgGuI++3dXRr8CoUyc9r0kGSCcZHjJje407ydgBQ=="], - "@smithy/node-http-handler": ["@smithy/node-http-handler@4.5.2", "", { "dependencies": { "@smithy/protocol-http": "^5.3.13", "@smithy/querystring-builder": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-/oD7u8M0oj2ZTFw7GkuuHWpIxtWdLlnyNkbrWcyVYhd5RJNDuczdkb0wfnQICyNFrVPlr8YHOhamjNy3zidhmA=="], + "@smithy/middleware-retry": ["@smithy/middleware-retry@4.6.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-fumMIfh5xOFjirylbSzmBX9bgQtrWFtQrosPfkjsJSBzqXVbQMNDGIC8oJBz4V3bokIm2F0CL3bziLtbXR7cbA=="], - "@smithy/property-provider": ["@smithy/property-provider@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-bGzUCthxRmezuxkbu9wD33wWg9KX3hJpCXpQ93vVkPrHn9ZW6KNNdY5xAUWNuRCwQ+VyboFuWirG1lZhhkcyRQ=="], + "@smithy/middleware-serde": ["@smithy/middleware-serde@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-+7glfRrb7byruZCPAM53TvmK8cx/ghzAThB4EvPzHynAYobtISl0g+DzzSVEC0NQob5BunP9gC9GP+Fcz6H9yw=="], - "@smithy/protocol-http": ["@smithy/protocol-http@5.3.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-+HsmuJUF4u8POo6s8/a2Yb/AQ5t/YgLovCuHF9oxbocqv+SZ6gd8lC2duBFiCA/vFHoHQhoq7QjqJqZC6xOxxg=="], + "@smithy/middleware-stack": ["@smithy/middleware-stack@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-Yj4wjBQZXHePRIy9cBIKfCOn/kPjRlgDPGlr7DjIhwrnz8kWu7Ux7UwPr51P/wcug5oq4nWdBXSY4TV5afBdew=="], - "@smithy/querystring-builder": ["@smithy/querystring-builder@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "@smithy/util-uri-escape": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-tG4aOYFCZdPMjbgfhnIQ322H//ojujldp1SrHPHpBSb3NqgUp3dwiUGRJzie87hS1DYwWGqDuPaowoDF+rYCbQ=="], + "@smithy/node-config-provider": ["@smithy/node-config-provider@4.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-c2G9QJ4xVZLwAkAf+WQESSSCkKbtt33ytje1klGvTcBn6cKuqV28E+62wbRPHwuTikkB3LQ7CBnNrayCoJur5A=="], - "@smithy/querystring-parser": ["@smithy/querystring-parser@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-hqW3Q4P+CDzUyQ87GrboGMeD7XYNMOF+CuTwu936UQRB/zeYn3jys8C3w+wMkDfY7CyyyVwZQ5cNFoG0x1pYmA=="], + "@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-3dA9TQ+ybRSZ/m0wnbZhiBy4Dezjgq1Ib/ZZrYTpJDBgpoLLU/SDzZc/g0x0MNAdOJe1wPcM+x2PBRmoOur+Sw=="], - "@smithy/service-error-classification": ["@smithy/service-error-classification@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0" } }, "sha512-a0s8XZMfOC/qpqq7RCPvJlk93rWFrElH6O++8WJKz0FqnA4Y7fkNi/0mnGgSH1C4x6MFsuBA8VKu4zxFrMe5Vw=="], + "@smithy/property-provider": ["@smithy/property-provider@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-QNc22/FgfEm/9/rkefShfQUVckH3HWiQ2RPs+40hwAdY65hbg88gombeHwkfMzmVDZjolcyQeyOjnxZRmpavIA=="], - "@smithy/shared-ini-file-loader": ["@smithy/shared-ini-file-loader@4.4.8", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-VZCZx2bZasxdqxVgEAhREvDSlkatTPnkdWy1+Kiy8w7kYPBosW0V5IeDwzDUMvWBt56zpK658rx1cOBFOYaPaw=="], + "@smithy/protocol-http": ["@smithy/protocol-http@5.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-jOD+4WNWQLntiLJn3r82C7BLheEbRCKTbU5U5bskZmT7nwRiGkh0IghuHwHRZ1ZEFXpHltQxxp9/koOPsdluJg=="], - "@smithy/signature-v4": ["@smithy/signature-v4@5.3.13", "", { "dependencies": { "@smithy/is-array-buffer": "^4.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-hex-encoding": "^4.2.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-uri-escape": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-YpYSyM0vMDwKbHD/JA7bVOF6kToVRpa+FM5ateEVRpsTNu564g1muBlkTubXhSKKYXInhpADF46FPyrZcTLpXg=="], + "@smithy/shared-ini-file-loader": ["@smithy/shared-ini-file-loader@4.5.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-W7IPDXj8AZdyH5EWEXmOvN7ao8iN0JKJ0FNLpGcqj08HZc0MmqGcJnGgh3DfUdGYtzrPIEudxs+ovq/EWZgLjg=="], - "@smithy/smithy-client": ["@smithy/smithy-client@4.12.9", "", { "dependencies": { "@smithy/core": "^3.23.14", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-stack": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-stream": "^4.5.22", "tslib": "^2.6.2" } }, "sha512-ovaLEcTU5olSeHcRXcxV6viaKtpkHZumn6Ps0yn7dRf2rRSfy794vpjOtrWDO0d1auDSvAqxO+lyhERSXQ03EQ=="], + "@smithy/signature-v4": ["@smithy/signature-v4@5.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-QBJKWGqIknH0dc9LWpfH1mkdokAx6iXYN3UcQ3eY6uIEyScuoQAhfl94ge7ozUy9WgFUdE8xsvwBjaYBbWmPNA=="], - "@smithy/types": ["@smithy/types@4.14.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-OWgntFLW88kx2qvf/c/67Vno1yuXm/f9M7QFAtVkkO29IJXGBIg0ycEaBTH0kvCtwmvZxRujrgP5a86RvsXJAQ=="], + "@smithy/smithy-client": ["@smithy/smithy-client@4.13.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-pg9QRQESz3m/5HgAW/z9lA3ln8MSsCWNWc82MX40Djlxpcj/+7DZQ0yIk7tGWYJCVZog/9LBdNl1uEVRAhqm5Q=="], - "@smithy/url-parser": ["@smithy/url-parser@4.2.13", "", { "dependencies": { "@smithy/querystring-parser": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-2G03yoboIRZlZze2+PT4GZEjgwQsJjUgn6iTsvxA02bVceHR6vp4Cuk7TUnPFWKF+ffNUk3kj4COwkENS2K3vw=="], + "@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], - "@smithy/util-base64": ["@smithy/util-base64@4.3.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-XRH6b0H/5A3SgblmMa5ErXQ2XKhfbQB+Fm/oyLZ2O2kCUrwgg55bU0RekmzAhuwOjA9qdN5VU2BprOvGGUkOOQ=="], + "@smithy/url-parser": ["@smithy/url-parser@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-f7kUYrRdLiAHz10WXQXiUkuBFaL2c2ZBD2kSwZyQBh73lWFTvXwdpS9l5irQ/uldk8YMJpm66BozmqCg/3uZvA=="], - "@smithy/util-body-length-browser": ["@smithy/util-body-length-browser@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-JKCrLNOup3OOgmzeaKQwi4ZCTWlYR5H4Gm1r2uTMVBXoemo1UEghk5vtMi1xSu2ymgKVGW631e2fp9/R610ZjQ=="], + "@smithy/util-base64": ["@smithy/util-base64@4.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-2J8l+DoX3IIiP75X5SYkJ3mIgOkxW29MxOs7oPjbXLuInQ7UL6zLw2IJHbQ44+eKDBBhTjvt+GgwsTTNBGt8zA=="], - "@smithy/util-body-length-node": ["@smithy/util-body-length-node@4.2.3", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-ZkJGvqBzMHVHE7r/hcuCxlTY8pQr1kMtdsVPs7ex4mMU+EAbcXppfo5NmyxMYi2XU49eqaz56j2gsk4dHHPG/g=="], + "@smithy/util-body-length-browser": ["@smithy/util-body-length-browser@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-nQtYwXg4spM6uc0Luq3yck+WXZ1VPfrYkC2SqkQ+YOGks0qR2bKKlSCjidSqfpq+VAY/RJe1O5V+CtBmnT63KQ=="], - "@smithy/util-buffer-from": ["@smithy/util-buffer-from@4.2.2", "", { "dependencies": { "@smithy/is-array-buffer": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-FDXD7cvUoFWwN6vtQfEta540Y/YBe5JneK3SoZg9bThSoOAC/eGeYEua6RkBgKjGa/sz6Y+DuBZj3+YEY21y4Q=="], + "@smithy/util-body-length-node": ["@smithy/util-body-length-node@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-BAsAed9yWExECwNIi61Le6D8ZTY71MFEFrf3d4L2+uzcbTjFAWxOtymkA1vCV8bNZQN9TGgZo4c68JDsnjNShA=="], - "@smithy/util-config-provider": ["@smithy/util-config-provider@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-dWU03V3XUprJwaUIFVv4iOnS1FC9HnMHDfUrlNDSh4315v0cWyaIErP8KiqGVbf5z+JupoVpNM7ZB3jFiTejvQ=="], + "@smithy/util-buffer-from": ["@smithy/util-buffer-from@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-CthqHx5VTlNIsS5rJni+pIfkGgYPnVFsy9qYiv8e+hMQDPemZod5wTa+2DkrI+vubX51sD6qqcgH3UHqdTf2bw=="], - "@smithy/util-defaults-mode-browser": ["@smithy/util-defaults-mode-browser@4.3.45", "", { "dependencies": { "@smithy/property-provider": "^4.2.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-ag9sWc6/nWZAuK3Wm9KlFJUnRkXLrXn33RFjIAmCTFThqLHY+7wCst10BGq56FxslsDrjhSie46c8OULS+BiIw=="], + "@smithy/util-config-provider": ["@smithy/util-config-provider@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-7yflDiFlO+bVXjI7BJe3B8jx5HyGCI146xrkZRwK9pO2ParfgWzgGfPGK3KsXkxcU+EBzIz1kFnX7fJRxAMbQA=="], - "@smithy/util-defaults-mode-node": ["@smithy/util-defaults-mode-node@4.2.50", "", { "dependencies": { "@smithy/config-resolver": "^4.4.15", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-xpjncL5XozFA3No7WypTsPU1du0fFS8flIyO+Wh2nhCy7bpEapvU7BR55Bg+wrfw+1cRA+8G8UsTjaxgzrMzXg=="], + "@smithy/util-defaults-mode-browser": ["@smithy/util-defaults-mode-browser@4.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-LbE6AGHhQOunqIN5UyWDMgpPwmUHUzrV2NtUOQ+lt6Stpipzo6S7uDyeGtO0GGgUD1balEPCNu8Xfl1AQNiruQ=="], - "@smithy/util-endpoints": ["@smithy/util-endpoints@3.4.0", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-QQHGPKkw6NPcU6TJ1rNEEa201srPtZiX4k61xL163vvs9sTqW/XKz+UEuJ00uvPqoN+5Rs4Ka1UJ7+Mp03IXJw=="], + "@smithy/util-defaults-mode-node": ["@smithy/util-defaults-mode-node@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-72gNpNDQ2iIGbaNmeaF9I58shWsEuD5tNI7my5uXlm1CSPH5i8IKI/nzU50qqB8y+kgw/qTLGgsf0We5qeM/aA=="], - "@smithy/util-hex-encoding": ["@smithy/util-hex-encoding@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-Qcz3W5vuHK4sLQdyT93k/rfrUwdJ8/HZ+nMUOyGdpeGA1Wxt65zYwi3oEl9kOM+RswvYq90fzkNDahPS8K0OIg=="], + "@smithy/util-endpoints": ["@smithy/util-endpoints@3.5.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-NJhe8KmNjeZ7V+gJsQR5xw0IN47N8pBKosed40xfhelDuYkg8VQ5CVGDcHTEuJq3e3zQb21vnoOOReQothejhA=="], - "@smithy/util-middleware": ["@smithy/util-middleware@4.2.13", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-GTooyrlmRTqvUen4eK7/K1p6kryF7bnDfq6XsAbIsf2mo51B/utaH+XThY6dKgNCWzMAaH/+OLmqaBuLhLWRow=="], + "@smithy/util-hex-encoding": ["@smithy/util-hex-encoding@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-+ip3QrXGjDOzV/ciNWPTm6bhJuXjmzugMR19ouXgA26QqhEo0zuXM7pvYE9S4VfX13YmPgSYDPkF4+2bPqIwAg=="], - "@smithy/util-retry": ["@smithy/util-retry@4.3.1", "", { "dependencies": { "@smithy/service-error-classification": "^4.2.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-FwmicpgWOkP5kZUjN3y+3JIom8NLGqSAJBeoIgK0rIToI817TEBHCrd0A2qGeKQlgDeP+Jzn4i0H/NLAXGy9uQ=="], + "@smithy/util-middleware": ["@smithy/util-middleware@4.3.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-N1IR4bMHIDbqO3GxkJHgqNGsnrd7MNrj+EVqhFqKeRqSBV5I3KCjNllKfnbF9KV0YteGhfLqcMR5CYsPLJqpqw=="], - "@smithy/util-stream": ["@smithy/util-stream@4.5.22", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.16", "@smithy/node-http-handler": "^4.5.2", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-buffer-from": "^4.2.2", "@smithy/util-hex-encoding": "^4.2.2", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-3H8iq/0BfQjUs2/4fbHZ9aG9yNzcuZs24LPkcX1Q7Z+qpqaGM8+qbGmE8zo9m2nCRgamyvS98cHdcWvR6YUsew=="], + "@smithy/util-retry": ["@smithy/util-retry@4.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-W9Ovy9i02yGqtLlpqZNQuXNxXc5OPfXujnembxN/FxyBtGjJd8vKY0PQYEJ8FNybTOcXG+ZxsSsX23HOb3zQzg=="], - "@smithy/util-uri-escape": ["@smithy/util-uri-escape@4.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-2kAStBlvq+lTXHyAZYfJRb/DfS3rsinLiwb+69SstC9Vb0s9vNWkRwpnj918Pfi85mzi42sOqdV72OLxWAISnw=="], + "@smithy/util-stream": ["@smithy/util-stream@4.6.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-PFzBVEBP5k8R+mK/c+VAKmtpUTL+KzBIXWJ6oM0GWOb31K+QgymXV9IW03XLPM1wtkC7oAb9ZBN2aswSSVbNFg=="], "@smithy/util-utf8": ["@smithy/util-utf8@4.2.0", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw=="], - "@smithy/util-waiter": ["@smithy/util-waiter@4.2.15", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-oUt9o7n8hBv3BL56sLSneL0XeigZSuem0Hr78JaoK33D9oKieyCvVP8eTSe3j7g2mm/S1DvzxKieG7JEWNJUNg=="], - - "@smithy/uuid": ["@smithy/uuid@1.1.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-O/IEdcCUKkubz60tFbGA7ceITTAJsty+lBjNoorP4Z6XRqaFb/OjQjZODophEcuq68nKm6/0r+6/lLQ+XVpk8g=="], + "@smithy/util-waiter": ["@smithy/util-waiter@4.4.5", "", { "dependencies": { "@smithy/core": "^3.24.5", "tslib": "^2.6.2" } }, "sha512-EYviebytZE6vplW0AGwZ2Rc3sNuVR83lfUCNZu11VchUiKhMwJqrRWy7iVDTNEwG/vEwItno591Iad6/prj6Bw=="], "@socket.io/component-emitter": ["@socket.io/component-emitter@3.1.2", "", {}, "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="], @@ -2209,29 +2390,29 @@ "@standard-schema/spec": ["@standard-schema/spec@1.0.0", "", {}, "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA=="], - "@storybook/addon-a11y": ["@storybook/addon-a11y@10.3.5", "", { "dependencies": { "@storybook/global": "^5.0.0", "axe-core": "^4.2.0" }, "peerDependencies": { "storybook": "^10.3.5" } }, "sha512-5k6lpgfIeLxvNhE8v3wEzdiu73ONKjF4gmH1AHvfqYd8kIVzQJai0KCDxgvqNncXHQhIWkaf1fg6+9hKaYJyaw=="], + "@storybook/addon-a11y": ["@storybook/addon-a11y@10.4.1", "", { "dependencies": { "@storybook/global": "^5.0.0", "axe-core": "^4.2.0" }, "peerDependencies": { "storybook": "^10.4.1" } }, "sha512-MGft/IXjJ20a9KbaSVG9bHTAAoanbucKrgEiJJRNqpim8DsXA01+XTdSk17LmiOCB203Rrq9mWgdQ6+79cc8iA=="], - "@storybook/addon-docs": ["@storybook/addon-docs@10.3.5", "", { "dependencies": { "@mdx-js/react": "^3.0.0", "@storybook/csf-plugin": "10.3.5", "@storybook/icons": "^2.0.1", "@storybook/react-dom-shim": "10.3.5", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "ts-dedent": "^2.0.0" }, "peerDependencies": { "storybook": "^10.3.5" } }, "sha512-WuHbxia/o5TX4Rg/IFD0641K5qId/Nk0dxhmAUNoFs5L0+yfZUwh65XOBbzXqrkYmYmcVID4v7cgDRmzstQNkA=="], + "@storybook/addon-docs": ["@storybook/addon-docs@10.4.1", "", { "dependencies": { "@mdx-js/react": "^3.0.0", "@storybook/csf-plugin": "10.4.1", "@storybook/icons": "^2.0.2", "@storybook/react-dom-shim": "10.4.1", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "ts-dedent": "^2.0.0" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.4.1" }, "optionalPeers": ["@types/react"] }, "sha512-IYqUdjoZe4VO2LFZlKL/gwy7DsQSWCq6hX+zc1MBmZo04yycDASk1tte57n9pdlW3ajw9yYMF/+lVBi+xQjyvw=="], - "@storybook/addon-links": ["@storybook/addon-links@10.3.5", "", { "dependencies": { "@storybook/global": "^5.0.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.3.5" }, "optionalPeers": ["react"] }, "sha512-Xe2wCGZ+hpZ0cDqAIBHk+kPc8nODNbu585ghd5bLrlYJMDVXoNM/fIlkrLgjIDVbfpgeJLUEg7vldJrn+FyOLw=="], + "@storybook/addon-links": ["@storybook/addon-links@10.4.1", "", { "dependencies": { "@storybook/global": "^5.0.0" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.4.1" }, "optionalPeers": ["@types/react", "react"] }, "sha512-h/5D23GwMuHA55sB7XDyhByF9psF7UFmaQOn72pjNAarew5eOpue5A+jXk3AKEYokHbvgQaoz+FrvWo9GEfSKQ=="], - "@storybook/addon-onboarding": ["@storybook/addon-onboarding@10.3.5", "", { "peerDependencies": { "storybook": "^10.3.5" } }, "sha512-s3/gIy9Tqxji27iclLY+KSk8kGeow1JxXMl1lPLyu8n6XVvv+tFrUPhAvUTs+fVenG6JQEWc0uzpYBdFRWbMtw=="], + "@storybook/addon-onboarding": ["@storybook/addon-onboarding@10.4.1", "", { "peerDependencies": { "storybook": "^10.4.1" } }, "sha512-XJ3vaPeXLc8GRrnYKoi0zmAMyT34XTnD6SZNcSV0ceEQrmfZKpLbn6wei1e4oqQRctkRH2QFl/ha7SqqB3yYmQ=="], - "@storybook/addon-vitest": ["@storybook/addon-vitest@10.3.5", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/icons": "^2.0.1" }, "peerDependencies": { "@vitest/browser": "^3.0.0 || ^4.0.0", "@vitest/browser-playwright": "^4.0.0", "@vitest/runner": "^3.0.0 || ^4.0.0", "storybook": "^10.3.5", "vitest": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@vitest/browser", "@vitest/browser-playwright", "@vitest/runner", "vitest"] }, "sha512-PQDeeMwoF55kvzlhFqVKOryBJskkVk71AbDh7F0y8PdRRxlGbTvIUkKXktHZWBdESo0dV6BkeVxGQ4ZpiFxirg=="], + "@storybook/addon-vitest": ["@storybook/addon-vitest@10.4.1", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/icons": "^2.0.2" }, "peerDependencies": { "@vitest/browser": "^3.0.0 || ^4.0.0", "@vitest/browser-playwright": "^4.0.0", "@vitest/runner": "^3.0.0 || ^4.0.0", "storybook": "^10.4.1", "vitest": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@vitest/browser", "@vitest/browser-playwright", "@vitest/runner", "vitest"] }, "sha512-ymrX9EOou1x3d21iDhjP3j3XfhOAiflhlPZWKcipULBoJCq/aZPbV68EghzovkJNuGRl9ezMYxbbKxwrMmCmGg=="], - "@storybook/builder-vite": ["@storybook/builder-vite@10.3.5", "", { "dependencies": { "@storybook/csf-plugin": "10.3.5", "ts-dedent": "^2.0.0" }, "peerDependencies": { "storybook": "^10.3.5", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-i4KwCOKbhtlbQIbhm53+Kk7bMnxa0cwTn1pxmtA/x5wm1Qu7FrrBQV0V0DNjkUqzcSKo1CjspASJV/HlY0zYlw=="], + "@storybook/builder-vite": ["@storybook/builder-vite@10.4.1", "", { "dependencies": { "@storybook/csf-plugin": "10.4.1", "ts-dedent": "^2.0.0" }, "peerDependencies": { "storybook": "^10.4.1", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-/oyQrXoNOqN8SW5hNnYP+I1uvgFxKxWXj/EP6NXYzc5SQwImofgru+D2+6gDhL0+Q//+Hx05DJoQO2omvUJ8bQ=="], - "@storybook/csf-plugin": ["@storybook/csf-plugin@10.3.5", "", { "dependencies": { "unplugin": "^2.3.5" }, "peerDependencies": { "esbuild": "*", "rollup": "*", "storybook": "^10.3.5", "vite": "*", "webpack": "*" }, "optionalPeers": ["esbuild", "rollup", "vite", "webpack"] }, "sha512-qlEzNKxOjq86pvrbuMwiGD/bylnsXk1dg7ve0j77YFjEEchqtl7qTlrXvFdNaLA89GhW6D/EV6eOCu/eobPDgw=="], + "@storybook/csf-plugin": ["@storybook/csf-plugin@10.4.1", "", { "dependencies": { "unplugin": "^2.3.5" }, "peerDependencies": { "esbuild": "*", "rollup": "*", "storybook": "^10.4.1", "vite": "*", "webpack": "*" }, "optionalPeers": ["esbuild", "rollup", "vite", "webpack"] }, "sha512-WdPepGBxDGOUDjYd8KxMtcf+us/2PAcnBczl77XtrnxxHNs0jWesxKkiJ9yiuGrge4BPhDeAj6rxjbBoaHxLBA=="], "@storybook/global": ["@storybook/global@5.0.0", "", {}, "sha512-FcOqPAXACP0I3oJ/ws6/rrPT9WGhu915Cg8D02a9YxLo0DE9zI+a9A5gRGvmQ09fiWPukqI8ZAEoQEdWUKMQdQ=="], - "@storybook/icons": ["@storybook/icons@2.0.1", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-/smVjw88yK3CKsiuR71vNgWQ9+NuY2L+e8X7IMrFjexjm6ZR8ULrV2DRkTA61aV6ryefslzHEGDInGpnNeIocg=="], + "@storybook/icons": ["@storybook/icons@2.0.2", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-KZBCpXsshAIjczYNXR/rlxEtCUX/eAbpFNwKi8bcOomrLA4t/SyPz5RF+lVPO2oZBUE4sAkt43mfJUevQDSEEw=="], - "@storybook/react-dom-shim": ["@storybook/react-dom-shim@10.3.5", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.3.5" } }, "sha512-Gw8R7XZm0zSUH0XAuxlQJhmizsLzyD6x00KOlP6l7oW9eQHXGfxg3seNDG3WrSAcW07iP1/P422kuiriQlOv7g=="], + "@storybook/react-dom-shim": ["@storybook/react-dom-shim@10.4.1", "", { "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "storybook": "^10.4.1" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-6QFqfDNH4DMrt7yHKRfpqRopsVUc/Az+sXIdJ39IetYnHUxL3nW4NVaPc6uy/8Qi8urzUyEXL/nn7cpSIP2aPQ=="], "@stripe/stripe-js": ["@stripe/stripe-js@8.6.1", "", {}, "sha512-UJ05U2062XDgydbUcETH1AoRQLNhigQ2KmDn1BG8sC3xfzu6JKg95Qt6YozdzFpxl1Npii/02m2LEWFt1RYjVA=="], - "@swc/helpers": ["@swc/helpers@0.5.21", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg=="], + "@swc/helpers": ["@swc/helpers@0.5.23", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="], "@szmarczak/http-timer": ["@szmarczak/http-timer@4.0.6", "", { "dependencies": { "defer-to-connect": "^2.0.0" } }, "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w=="], @@ -2275,12 +2456,6 @@ "@tanstack/solid-query": ["@tanstack/solid-query@5.91.4", "", { "dependencies": { "@tanstack/query-core": "5.91.2" }, "peerDependencies": { "solid-js": "^1.6.0" } }, "sha512-oCEgn8iT7WnF/7ISd7usBpUK1C9EdvQfg8ZUpKNKZ4edVClICZrCX6f3/Bp8ZlwQnL21KLc2rp+CejEuehlRxg=="], - "@tauri-apps/api": ["@tauri-apps/api@2.10.1", "", {}, "sha512-hKL/jWf293UDSUN09rR69hrToyIXBb8CjGaWC7gfinvnQrBVvnLr08FeFi38gxtugAVyVcTa5/FD/Xnkb1siBw=="], - - "@tauri-apps/plugin-store": ["@tauri-apps/plugin-store@2.4.2", "", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-0ClHS50Oq9HEvLPhNzTNFxbWVOqoAp3dRvtewQBeqfIQ0z5m3JRnOISIn2ZVPCrQC0MyGyhTS9DWhHjpigQE7A=="], - - "@tediousjs/connection-string": ["@tediousjs/connection-string@0.5.0", "", {}, "sha512-7qSgZbincDDDFyRweCIEvZULFAw5iz/DeunhvuxpL31nfntX3P4Yd4HkHBRg9H8CdqY1e5WFN1PZIz/REL9MVQ=="], - "@testing-library/dom": ["@testing-library/dom@10.4.1", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg=="], "@testing-library/jest-dom": ["@testing-library/jest-dom@6.9.1", "", { "dependencies": { "@adobe/css-tools": "^4.4.0", "aria-query": "^5.0.0", "css.escape": "^1.5.1", "dom-accessibility-api": "^0.6.3", "picocolors": "^1.1.1", "redent": "^3.0.0" } }, "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA=="], @@ -2297,7 +2472,7 @@ "@tufjs/models": ["@tufjs/models@4.1.0", "", { "dependencies": { "@tufjs/canonical-json": "2.0.0", "minimatch": "^10.1.1" } }, "sha512-Y8cK9aggNRsqJVaKUlEYs4s7CvQ1b1ta2DVPyAimb0I2qhzjNk+A+mxvll/klL0RlfuIUei8BF7YWiua4kQqww=="], - "@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="], + "@tybys/wasm-util": ["@tybys/wasm-util@0.10.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="], "@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="], @@ -2325,6 +2500,10 @@ "@types/cross-spawn": ["@types/cross-spawn@6.0.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA=="], + "@types/d3-scale": ["@types/d3-scale@4.0.9", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="], + + "@types/d3-time": ["@types/d3-time@3.0.4", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], @@ -2373,8 +2552,6 @@ "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], - "@types/mssql": ["@types/mssql@9.1.11", "", { "dependencies": { "@types/node": "*", "tarn": "^3.0.1", "tedious": "*" } }, "sha512-vcujgrDbDezCxNDO4KY6gjwduLYOKfrexpRUwhoysRvcXZ3+IgZ/PMYFDgh8c3cQIxZ6skAwYo+H6ibMrBWPjQ=="], - "@types/nlcst": ["@types/nlcst@2.0.3", "", { "dependencies": { "@types/unist": "*" } }, "sha512-vSYNSDe6Ix3q+6Z7ri9lyWqgGhJTmzRjZRqyq15N0Z/1/UnVsno9G/N40NBijoYx2seFDIl0+B2mgAb9mezUCA=="], "@types/node": ["@types/node@24.12.2", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g=="], @@ -2399,14 +2576,12 @@ "@types/prop-types": ["@types/prop-types@15.7.15", "", {}, "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw=="], - "@types/qs": ["@types/qs@6.15.0", "", {}, "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow=="], + "@types/qs": ["@types/qs@6.15.1", "", {}, "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw=="], "@types/range-parser": ["@types/range-parser@1.2.7", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="], "@types/react": ["@types/react@18.0.25", "", { "dependencies": { "@types/prop-types": "*", "@types/scheduler": "*", "csstype": "^3.0.2" } }, "sha512-xD6c0KDT4m7n9uD4ZHi02lzskaiqcBxf4zi+tXZY98a04wvc0hi/TcCPC2FOESZi51Nd7tlUeOJY8RofL799/g=="], - "@types/readable-stream": ["@types/readable-stream@4.0.23", "", { "dependencies": { "@types/node": "*" } }, "sha512-wwXrtQvbMHxCbBgjHaMGEmImFTQxxpfMOR/ZoQnXxB1woqkUbdLGFDgauo00Py9IudiaqSeiBiulSV9i6XIPig=="], - "@types/responselike": ["@types/responselike@1.0.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="], "@types/retry": ["@types/retry@0.12.0", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="], @@ -2467,7 +2642,7 @@ "@typespec/ts-http-runtime": ["@typespec/ts-http-runtime@0.3.5", "", { "dependencies": { "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.0", "tslib": "^2.6.2" } }, "sha512-yURCknZhvywvQItHMMmFSo+fq5arCUIyz/CVk7jD89MSai7dkaX8ufjCWp3NttLojoTVbcE72ri+be/TnEbMHw=="], - "@ungap/structured-clone": ["@ungap/structured-clone@1.3.0", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="], + "@ungap/structured-clone": ["@ungap/structured-clone@1.3.1", "", {}, "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ=="], "@upstash/redis": ["@upstash/redis@1.38.0", "", { "dependencies": { "uncrypto": "^0.1.3" } }, "sha512-wu+dZBptlLy0+MCUEoHmzrY/TnmgDey3+c7EbIGwrLqAvkP8yi5MWZHYGIFtAygmL4Bkz2TdFu+eU0vFPncIcg=="], @@ -2479,17 +2654,17 @@ "@vitest/expect": ["@vitest/expect@3.2.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.4", "@vitest/utils": "3.2.4", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig=="], - "@vitest/mocker": ["@vitest/mocker@4.1.4", "", { "dependencies": { "@vitest/spy": "4.1.4", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-R9HTZBhW6yCSGbGQnDnH3QHfJxokKN4KB+Yvk9Q1le7eQNYwiCyKxmLmurSpFy6BzJanSLuEUDrD+j97Q+ZLPg=="], + "@vitest/mocker": ["@vitest/mocker@4.1.7", "", { "dependencies": { "@vitest/spy": "4.1.7", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-vY7nuamKgfvpA1Koa3oYIw/k7D6kZnpGyNMZW8loow2bsBYla1TFdqTaXncWdRn4pgwNs+90RhnXhJScDwQeJA=="], - "@vitest/pretty-format": ["@vitest/pretty-format@4.1.4", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-ddmDHU0gjEUyEVLxtZa7xamrpIefdEETu3nZjWtHeZX4QxqJ7tRxSteHVXJOcr8jhiLoGAhkK4WJ3WqBpjx42A=="], + "@vitest/pretty-format": ["@vitest/pretty-format@4.1.7", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-umgCarTOYQWIaDMvGDRZij+6b9oVeLIyJzfN+AS88e0ZOU3QTgNNSTtjQOpcvWr3np1N0j4WgZj+sb3oYBDscw=="], - "@vitest/runner": ["@vitest/runner@4.1.4", "", { "dependencies": { "@vitest/utils": "4.1.4", "pathe": "^2.0.3" } }, "sha512-xTp7VZ5aXP5ZJrn15UtJUWlx6qXLnGtF6jNxHepdPHpMfz/aVPx+htHtgcAL2mDXJgKhpoo2e9/hVJsIeFbytQ=="], + "@vitest/runner": ["@vitest/runner@4.1.7", "", { "dependencies": { "@vitest/utils": "4.1.7", "pathe": "^2.0.3" } }, "sha512-BapjmAQ2aI78WdMEfeUWivnfVzB+VPGwWRQcJE0OUq7qEeEcBsCSf+0T5iREBNE5nBb4wA5Ya0W6IA+sghdEFw=="], - "@vitest/snapshot": ["@vitest/snapshot@4.1.4", "", { "dependencies": { "@vitest/pretty-format": "4.1.4", "@vitest/utils": "4.1.4", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-MCjCFgaS8aZz+m5nTcEcgk/xhWv0rEH4Yl53PPlMXOZ1/Ka2VcZU6CJ+MgYCZbcJvzGhQRjVrGQNZqkGPttIKw=="], + "@vitest/snapshot": ["@vitest/snapshot@4.1.7", "", { "dependencies": { "@vitest/pretty-format": "4.1.7", "@vitest/utils": "4.1.7", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-ZacLzja+TmJeZ1h14xW2FB/WpeimUD3haBXQPyJqxvo8jQTmfeA8zv58mtjN2C7EHXZDYVcVYdYmAxjkWVvKCw=="], "@vitest/spy": ["@vitest/spy@3.2.4", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw=="], - "@vitest/utils": ["@vitest/utils@4.1.4", "", { "dependencies": { "@vitest/pretty-format": "4.1.4", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw=="], + "@vitest/utils": ["@vitest/utils@4.1.7", "", { "dependencies": { "@vitest/pretty-format": "4.1.7", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-T532WBu791cBxJlCl6SO+J14l81DQx6uQHm1bQbmCDY7nqlEIgkza/UFnSBNaUtSf41unldDFjdOBYEQC4b5Hw=="], "@volar/kit": ["@volar/kit@2.4.28", "", { "dependencies": { "@volar/language-service": "2.4.28", "@volar/typescript": "2.4.28", "typesafe-path": "^0.2.2", "vscode-languageserver-textdocument": "^1.0.11", "vscode-uri": "^3.0.8" }, "peerDependencies": { "typescript": "*" } }, "sha512-cKX4vK9dtZvDRaAzeoUdaAJEew6IdxHNCRrdp5Kvcl6zZOqb6jTOfk3kXkIkG3T7oTFXguEMt5+9ptyqYR84Pg=="], @@ -2511,7 +2686,7 @@ "@webgpu/types": ["@webgpu/types@0.1.54", "", {}, "sha512-81oaalC8LFrXjhsczomEQ0u3jG+TqE6V9QHLA8GNZq/Rnot0KDugu3LhSYSlie8tSdooAN1Hov05asrUUp9qgg=="], - "@xmldom/xmldom": ["@xmldom/xmldom@0.8.12", "", {}, "sha512-9k/gHF6n/pAi/9tqr3m3aqkuiNosYTurLLUtc7xQ9sxB/wm7WPygCv8GYa6mS0fLJEHhqMC1ATYhz++U/lRHqg=="], + "@xmldom/xmldom": ["@xmldom/xmldom@0.8.13", "", {}, "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw=="], "@zip.js/zip.js": ["@zip.js/zip.js@2.7.62", "", {}, "sha512-OaLvZ8j4gCkLn048ypkZu29KX30r8/OfFF2w4Jo5WXFr+J04J+lzJ5TKZBVgFXhlvSkqNFQdfnY1Q8TMTCyBVA=="], @@ -2537,7 +2712,7 @@ "ai-gateway-provider": ["ai-gateway-provider@3.1.2", "", { "optionalDependencies": { "@ai-sdk/amazon-bedrock": "^4.0.62", "@ai-sdk/anthropic": "^3.0.46", "@ai-sdk/azure": "^3.0.31", "@ai-sdk/cerebras": "^2.0.34", "@ai-sdk/cohere": "^3.0.21", "@ai-sdk/deepgram": "^2.0.20", "@ai-sdk/deepseek": "^2.0.20", "@ai-sdk/elevenlabs": "^2.0.20", "@ai-sdk/fireworks": "^2.0.34", "@ai-sdk/google": "^3.0.30", "@ai-sdk/google-vertex": "^4.0.61", "@ai-sdk/groq": "^3.0.24", "@ai-sdk/mistral": "^3.0.20", "@ai-sdk/openai": "^3.0.30", "@ai-sdk/perplexity": "^3.0.19", "@ai-sdk/xai": "^3.0.57", "@openrouter/ai-sdk-provider": "^2.2.3" }, "peerDependencies": { "@ai-sdk/openai-compatible": "^2.0.0", "@ai-sdk/provider": "^3.0.0", "@ai-sdk/provider-utils": "^4.0.0", "ai": "^6.0.0" } }, "sha512-krGNnJSoO/gJ7Hbe5nQDlsBpDUGIBGtMQTRUaW7s1MylsfvLduba0TLWzQaGtOmNRkP0pGhtGlwsnS6FNQMlyw=="], - "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], + "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "ajv-draft-04": ["ajv-draft-04@1.0.0", "", { "peerDependencies": { "ajv": "^8.5.0" }, "optionalPeers": ["ajv"] }, "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw=="], @@ -2553,7 +2728,7 @@ "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - "ansis": ["ansis@4.2.0", "", {}, "sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig=="], + "ansis": ["ansis@4.3.0", "", {}, "sha512-44mvgtPvohuU/70DdY5Oz2AIrLJ9k6/5x4KmoSvPwO+5Moijo0+N9D0fKbbYZQWP1hNm5CpOf+E01jhxG/r8xg=="], "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], @@ -2627,17 +2802,17 @@ "aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="], - "axe-core": ["axe-core@4.11.3", "", {}, "sha512-zBQouZixDTbo3jMGqHKyePxYxr1e5W8UdTmBQ7sNtaA9M2bE32daxxPLS/jojhKOHxQ7LWwPjfiwf/fhaJWzlg=="], + "axe-core": ["axe-core@4.11.4", "", {}, "sha512-KunSNx+TVpkAw/6ULfhnx+HWRecjqZGTOyquAoWHYLRSdK1tB5Ihce1ZW+UY3fj33bYAFWPu7W/GRSmmrCGuxA=="], - "axios": ["axios@1.15.0", "", { "dependencies": { "follow-redirects": "^1.15.11", "form-data": "^4.0.5", "proxy-from-env": "^2.1.0" } }, "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q=="], + "axios": ["axios@1.16.1", "", { "dependencies": { "follow-redirects": "^1.16.0", "form-data": "^4.0.5", "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, "sha512-caYkukvroVPO8KrzuJEb50Hm07KwfBZPEC3VeFHTsqWHvKTsy54hjJz9BS/cdaypROE2rH6xvm9mHX4fgWkr3A=="], "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], - "b4a": ["b4a@1.8.0", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-qRuSmNSkGQaHwNbM7J78Wwy+ghLEYF1zNrSeMxj4Kgw6y33O3mXcQ6Ie9fRvfU/YnxWkOchPXbaLb73TkIsfdg=="], + "b4a": ["b4a@1.8.1", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], - "babel-plugin-jsx-dom-expressions": ["babel-plugin-jsx-dom-expressions@0.40.6", "", { "dependencies": { "@babel/helper-module-imports": "7.18.6", "@babel/plugin-syntax-jsx": "^7.18.6", "@babel/types": "^7.20.7", "html-entities": "2.3.3", "parse5": "^7.1.2" }, "peerDependencies": { "@babel/core": "^7.20.12" } }, "sha512-v3P1MW46Lm7VMpAkq0QfyzLWWkC8fh+0aE5Km4msIgDx5kjenHU0pF2s+4/NH8CQn/kla6+Hvws+2AF7bfV5qQ=="], + "babel-plugin-jsx-dom-expressions": ["babel-plugin-jsx-dom-expressions@0.40.7", "", { "dependencies": { "@babel/helper-module-imports": "7.18.6", "@babel/plugin-syntax-jsx": "^7.18.6", "@babel/types": "^7.20.7", "html-entities": "2.3.3", "parse5": "^7.1.2" }, "peerDependencies": { "@babel/core": "^7.20.12" } }, "sha512-/O6JWUmjv03OI9lL2ry9bUjpD5S3PclM55RRJEyCdcFZ5W2SEA/59d+l2hNsk3gI6kiWRdRPdOtqZmsQzFN1pQ=="], "babel-plugin-module-resolver": ["babel-plugin-module-resolver@5.0.2", "", { "dependencies": { "find-babel-config": "^2.1.1", "glob": "^9.3.3", "pkg-up": "^3.1.0", "reselect": "^4.1.7", "resolve": "^1.22.8" } }, "sha512-9KtaCazHee2xc0ibfqsDeamwDps6FZNo5S0Q81dUqEuFzVwPhcT4J5jOqIVvgCA3Q/wO9hKYxN/Ds3tIsp5ygg=="], @@ -2647,23 +2822,23 @@ "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], - "bare-events": ["bare-events@2.8.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ=="], + "bare-events": ["bare-events@2.8.3", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-HdUm8EMQBLaJvGUdidNNbqpA1kYkwNcb+MYxkxCLAPJGQzlv9J0C24h8V65Z4c5GLd/JEALDvpFCQgpLJqc0zw=="], - "bare-fs": ["bare-fs@4.7.0", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-xzqKsCFxAek9aezYhjJuJRXBIaYlg/0OGDTZp+T8eYmYMlm66cs6cYko02drIyjN2CBbi+I6L7YfXyqpqtKRXA=="], + "bare-fs": ["bare-fs@4.7.1", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-WDRsyVN52eAx/lBamKD6uyw8H4228h/x0sGGGegOamM2cd7Pag88GfMQalobXI+HaEUxpCkbKQUDOQqt9wawRw=="], - "bare-os": ["bare-os@3.8.7", "", {}, "sha512-G4Gr1UsGeEy2qtDTZwL7JFLo2wapUarz7iTMcYcMFdS89AIQuBoyjgXZz0Utv7uHs3xA9LckhVbeBi8lEQrC+w=="], + "bare-os": ["bare-os@3.9.1", "", {}, "sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ=="], "bare-path": ["bare-path@3.0.0", "", { "dependencies": { "bare-os": "^3.0.1" } }, "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw=="], - "bare-stream": ["bare-stream@2.13.0", "", { "dependencies": { "streamx": "^2.25.0", "teex": "^1.0.1" }, "peerDependencies": { "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "optionalPeers": ["bare-abort-controller", "bare-buffer", "bare-events"] }, "sha512-3zAJRZMDFGjdn+RVnNpF9kuELw+0Fl3lpndM4NcEOhb9zwtSo/deETfuIwMSE5BXanA0FrN1qVjffGwAg2Y7EA=="], + "bare-stream": ["bare-stream@2.13.1", "", { "dependencies": { "streamx": "^2.25.0", "teex": "^1.0.1" }, "peerDependencies": { "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "optionalPeers": ["bare-abort-controller", "bare-buffer", "bare-events"] }, "sha512-Vp0cnjYyrEC4whYTymQ+YZi6pBpfiICZO3cfRG8sy67ZNWe951urv1x4eW1BKNngw3U+3fPYb5JQvHbCtxH7Ow=="], - "bare-url": ["bare-url@2.4.0", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-NSTU5WN+fy/L0DDenfE8SXQna4voXuW0FHM7wH8i3/q9khUSchfPbPezO4zSFMnDGIf9YE+mt/RWhZgNRKRIXA=="], + "bare-url": ["bare-url@2.4.3", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-Kccpc7ACfXaxfeInfqKcZtW4pT5YBn1mesc4sCsun6sRwtbJ4h+sNOaksUpYEJUKfN65YWC6Bw2OJEFiKxq8nQ=="], "base-64": ["base-64@1.0.0", "", {}, "sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg=="], "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], - "baseline-browser-mapping": ["baseline-browser-mapping@2.10.19", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.10.32", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-wbPvpyjJPC0zdfdKXxqEL3Ea+bOMD/87X4lftiJkkaBiuG6ALQy1SLmEd7BSmVCuwCQsBrCamgBoLyfFDD1EPg=="], "bcp-47": ["bcp-47@2.1.0", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-9IIS3UPrvIa1Ej+lVDdDwO7zLehjqsaByECw0bu2RRGP73jALm6FYbzI5gWbgHLvNdkvfXB5YrSbocZdOS0c0w=="], @@ -2673,19 +2848,17 @@ "bignumber.js": ["bignumber.js@9.3.1", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="], - "bin-links": ["bin-links@6.0.0", "", { "dependencies": { "cmd-shim": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "proc-log": "^6.0.0", "read-cmd-shim": "^6.0.0", "write-file-atomic": "^7.0.0" } }, "sha512-X4CiKlcV2GjnCMwnKAfbVWpHa++65th9TuzAEYtZoATiOE2DQKhSp4CJlyLoTqdhBKlXjpXjCTYPNNFS33Fi6w=="], + "bin-links": ["bin-links@6.0.2", "", { "dependencies": { "cmd-shim": "^8.0.0", "npm-normalize-package-bin": "^5.0.0", "proc-log": "^6.0.0", "read-cmd-shim": "^6.0.0", "write-file-atomic": "^7.0.0" } }, "sha512-frE1t78WOwJ45PKV2cF2tNPjTcs9L1J9s6VkrV59wanRP4GlaomuxYPVma7BwthMg8WnfSory4w5PTE6FZZ81w=="], "binary": ["binary@0.3.0", "", { "dependencies": { "buffers": "~0.1.1", "chainsaw": "~0.1.0" } }, "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg=="], "binary-extensions": ["binary-extensions@2.3.0", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="], - "bl": ["bl@6.1.6", "", { "dependencies": { "@types/readable-stream": "^4.0.0", "buffer": "^6.0.3", "inherits": "^2.0.4", "readable-stream": "^4.2.0" } }, "sha512-jLsPgN/YSvPUg9UX0Kd73CXpm2Psg9FxMeCSXnk3WBO3CMT10JMwijubhGfHCnFu6TPn1ei3b975dxv7K2pWVg=="], - "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], "blob-to-buffer": ["blob-to-buffer@1.2.9", "", {}, "sha512-BF033y5fN6OCofD3vgHmNtwZWRcq9NLyyxyILx9hfMy1sXYy4ojFl765hJ2lP0YaN2fuxPaLO2Vzzoxy0FLFFA=="], - "body-parser": ["body-parser@1.20.4", "", { "dependencies": { "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "~1.2.0", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", "qs": "~6.14.0", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" } }, "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA=="], + "body-parser": ["body-parser@1.20.5", "", { "dependencies": { "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "~1.2.0", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", "qs": "~6.15.1", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" } }, "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA=="], "bonjour-service": ["bonjour-service@1.3.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "multicast-dns": "^7.2.5" } }, "sha512-3YuAUiSkWykd+2Azjgyxei8OWf8thdn8AITIog2M4UICzoqfjlqr64WIjEXZllf/W6vK1goqleSR6brGomxQqA=="], @@ -2699,7 +2872,7 @@ "boxen": ["boxen@8.0.1", "", { "dependencies": { "ansi-align": "^3.0.1", "camelcase": "^8.0.0", "chalk": "^5.3.0", "cli-boxes": "^3.0.0", "string-width": "^7.2.0", "type-fest": "^4.21.0", "widest-line": "^5.0.0", "wrap-ansi": "^9.0.0" } }, "sha512-F3PH5k5juxom4xktynS7MoFY+NUWH5LC4CnH11YB8NPew+HLpmBLCybSAEyb2F+4pRXhuhWqFesoQd6DAyc2hw=="], - "brace-expansion": ["brace-expansion@5.0.5", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ=="], + "brace-expansion": ["brace-expansion@5.0.6", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g=="], "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], @@ -2753,7 +2926,7 @@ "camelcase-css": ["camelcase-css@2.0.1", "", {}, "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA=="], - "caniuse-lite": ["caniuse-lite@1.0.30001788", "", {}, "sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ=="], + "caniuse-lite": ["caniuse-lite@1.0.30001793", "", {}, "sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA=="], "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], @@ -2795,8 +2968,6 @@ "cli-boxes": ["cli-boxes@3.0.0", "", {}, "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g=="], - "cli-cursor": ["cli-cursor@3.1.0", "", { "dependencies": { "restore-cursor": "^3.1.0" } }, "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw=="], - "cli-spinners": ["cli-spinners@3.4.0", "", {}, "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw=="], "cli-truncate": ["cli-truncate@4.0.0", "", { "dependencies": { "slice-ansi": "^5.0.0", "string-width": "^7.0.0" } }, "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA=="], @@ -2813,7 +2984,7 @@ "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], - "cluster-key-slot": ["cluster-key-slot@1.1.2", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="], + "cluster-key-slot": ["cluster-key-slot@1.1.1", "", {}, "sha512-rwHwUfXL40Chm1r08yrhU3qpUvdVlgkKNeyeGPOxnW8/SyVDvgRaed/Uz54AqWNaTCAThlj6QAs3TZcKI0xDEw=="], "cmd-shim": ["cmd-shim@8.0.0", "", {}, "sha512-Jk/BK6NCapZ58BKUxlSI+ouKRbjH1NLZCgJkYoab+vEHUY3f6OzpNBN9u7HFSv9J6TRDGs4PLOHezoKGaFRSCA=="], @@ -2897,6 +3068,20 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "d3-array": ["d3-array@3.2.4", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="], + + "d3-color": ["d3-color@3.1.0", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="], + + "d3-format": ["d3-format@3.1.2", "", {}, "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg=="], + + "d3-interpolate": ["d3-interpolate@3.0.1", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="], + + "d3-scale": ["d3-scale@4.0.2", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="], + + "d3-time": ["d3-time@3.1.0", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="], + + "d3-time-format": ["d3-time-format@4.1.0", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="], + "data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="], "data-view-buffer": ["data-view-buffer@1.0.2", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ=="], @@ -2925,8 +3110,6 @@ "default-browser-id": ["default-browser-id@5.0.1", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="], - "defaults": ["defaults@1.0.4", "", { "dependencies": { "clone": "^1.0.2" } }, "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A=="], - "defer-to-connect": ["defer-to-connect@2.0.1", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="], "define-data-property": ["define-data-property@1.1.4", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="], @@ -2959,7 +3142,7 @@ "deterministic-object-hash": ["deterministic-object-hash@2.0.2", "", { "dependencies": { "base-64": "^1.0.0" } }, "sha512-KxektNH63SrbfUyDiwXqRb1rLwKt33AmMv+5Nhsw1kqZ13SJBRTgZHtGbE+hH3a1mVW1cz+4pqSWVPAtLVXTzQ=="], - "devalue": ["devalue@5.7.1", "", {}, "sha512-MUbZ586EgQqdRnC4yDrlod3BEdyvE4TapGYHMW2CiaW+KkkFmWEFqBUaLltEZCGi0iFXCEjRF0OjF0DV2QHjOA=="], + "devalue": ["devalue@5.8.1", "", {}, "sha512-4CXDYRBGqN+57wVJkuXBYmpAVUSg3L6JAQa/DFqm238G73E1wuyc/JhGQJzN7vUf/CMphYau2zXbfWzDR5aTEw=="], "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], @@ -3035,13 +3218,13 @@ "electron-is-dev": ["electron-is-dev@3.0.1", "", {}, "sha512-8TjjAh8Ec51hUi3o4TaU0mD3GMTOESi866oRNavj9A3IQJ7pmv+MJVmdZBFGw4GFT36X7bkqnuDNYvkQgvyI8Q=="], - "electron-log": ["electron-log@5.4.3", "", {}, "sha512-sOUsM3LjZdugatazSQ/XTyNcw8dfvH1SYhXWiJyfYodAAKOZdHs0txPiLDXFzOZbhXgAgshQkshH2ccq0feyLQ=="], + "electron-log": ["electron-log@5.4.4", "", {}, "sha512-istWgaXjBfURBSS8LWVW9C3jsc6+ac+tY1lXrQEOTp0lVj+a4OlO1Tmqb36GgnEUDv92DGC9VI1HNXwJinWpgA=="], "electron-publish": ["electron-publish@26.8.1", "", { "dependencies": { "@types/fs-extra": "^9.0.11", "builder-util": "26.8.1", "builder-util-runtime": "9.5.1", "chalk": "^4.1.2", "form-data": "^4.0.5", "fs-extra": "^10.1.0", "lazy-val": "^1.0.5", "mime": "^2.5.2" } }, "sha512-q+jrSTIh/Cv4eGZa7oVR+grEJo/FoLMYBAnSL5GCtqwUpr1T+VgKB/dn1pnzxIxqD8S/jP1yilT9VrwCqINR4w=="], "electron-store": ["electron-store@10.1.0", "", { "dependencies": { "conf": "^14.0.0", "type-fest": "^4.41.0" } }, "sha512-oL8bRy7pVCLpwhmXy05Rh/L6O93+k9t6dqSw0+MckIc3OmCTZm6Mp04Q4f/J0rtu84Ky6ywkR8ivtGOmrq+16w=="], - "electron-to-chromium": ["electron-to-chromium@1.5.336", "", {}, "sha512-AbH9q9J455r/nLmdNZes0G0ZKcRX73FicwowalLs6ijwOmCJSRRrLX63lcAlzy9ux3dWK1w1+1nsBJEWN11hcQ=="], + "electron-to-chromium": ["electron-to-chromium@1.5.364", "", {}, "sha512-G/dYE3+AYhyHwzTwg8UbnXf7zqMERYh7l2jJ3QujhFsH8agSYwtnGAR2aZ7f0AakIKJXd5En/Hre4igIUrdlYw=="], "electron-updater": ["electron-updater@6.8.3", "", { "dependencies": { "builder-util-runtime": "9.5.1", "fs-extra": "^10.1.0", "js-yaml": "^4.1.0", "lazy-val": "^1.0.5", "lodash.escaperegexp": "^4.1.2", "lodash.isequal": "^4.5.0", "semver": "~7.7.3", "tiny-typed-emitter": "^2.1.0" } }, "sha512-Z6sgw3jgbikWKXei1ENdqFOxBP0WlXg3TtKfz0rgw2vIZFJUyI4pD7ZN7jrkm7EoMK+tcm/qTnPUdqfZukBlBQ=="], @@ -3059,15 +3242,13 @@ "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], - "encoding": ["encoding@0.1.13", "", { "dependencies": { "iconv-lite": "^0.6.2" } }, "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A=="], - "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], - "engine.io-client": ["engine.io-client@6.6.4", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1", "engine.io-parser": "~5.2.1", "ws": "~8.18.3", "xmlhttprequest-ssl": "~2.1.1" } }, "sha512-+kjUJnZGwzewFDw951CDWcwj35vMNf2fcj7xQWOctq1F2i1jkDdVvdFG9kM/BEChymCH36KgjnW0NsL58JYRxw=="], + "engine.io-client": ["engine.io-client@6.6.5", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1", "engine.io-parser": "~5.2.1", "ws": "~8.20.1", "xmlhttprequest-ssl": "~2.1.1" } }, "sha512-QCwxUDULPlXv8F6tqMMKx5dNkTe6OaBYRMPYeXKBlyOoKvAmE0ac6pW7fFhSscJ/5SI7666/U/B+MElbsrJlIg=="], "engine.io-parser": ["engine.io-parser@5.2.3", "", {}, "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q=="], - "enhanced-resolve": ["enhanced-resolve@5.20.1", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.0" } }, "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA=="], + "enhanced-resolve": ["enhanced-resolve@5.22.1", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-6QEuw3zoX1SJQc7b87aBXke/no+mG2bTBgw29gWMQonLmpEkWoCAVkl+M49e48AZlWzxiDzDZzYdp6kobcyLww=="], "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], @@ -3091,7 +3272,7 @@ "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], - "es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="], + "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], @@ -3143,7 +3324,7 @@ "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], - "eventsource-parser": ["eventsource-parser@3.0.6", "", {}, "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg=="], + "eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="], "execa": ["execa@8.0.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^8.0.1", "human-signals": "^5.0.0", "is-stream": "^3.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^5.1.0", "onetime": "^6.0.0", "signal-exit": "^4.1.0", "strip-final-newline": "^3.0.0" } }, "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg=="], @@ -3153,9 +3334,9 @@ "exponential-backoff": ["exponential-backoff@3.1.3", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="], - "express": ["express@4.22.1", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "~1.20.3", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.3.1", "fresh": "~0.5.2", "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", "qs": "~6.14.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", "serve-static": "~1.16.2", "setprototypeof": "1.2.0", "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g=="], + "express": ["express@4.22.2", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "~1.20.5", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.3.1", "fresh": "~0.5.2", "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", "qs": "~6.15.1", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", "serve-static": "~1.16.2", "setprototypeof": "1.2.0", "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q=="], - "express-rate-limit": ["express-rate-limit@8.3.2", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg=="], + "express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="], "expressive-code": ["expressive-code@0.41.7", "", { "dependencies": { "@expressive-code/core": "^0.41.7", "@expressive-code/plugin-frames": "^0.41.7", "@expressive-code/plugin-shiki": "^0.41.7", "@expressive-code/plugin-text-markers": "^0.41.7" } }, "sha512-2wZjC8OQ3TaVEMcBtYY4Va3lo6J+Ai9jf3d4dbhURMJcU4Pbqe6EcHe424MIZI0VHUA1bR6xdpoHYi3yxokWqA=="], @@ -3173,9 +3354,7 @@ "extsprintf": ["extsprintf@1.4.1", "", {}, "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA=="], - "fast-check": ["fast-check@4.6.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-h7H6Dm0Fy+H4ciQYFxFjXnXkzR2kr9Fb22c0UBpHnm59K2zpr2t13aPTHlltFiNT6zuxp6HMPAVVvgur4BLdpA=="], - - "fast-content-type-parse": ["fast-content-type-parse@3.0.0", "", {}, "sha512-ZvLdcY8P+N8mGQJahJV5G4U88CSvT1rP8ApL6uETe88MBXrBHAkZlSEySdUlyztF7ccb+Znos3TFqaepHxdhBg=="], + "fast-check": ["fast-check@4.8.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-GOJ158CUMnN6cSahsv4+ExARvIDuzzinFjkp0E9WtiBa5zcVeLozVkWaE4IzFcc+Y48Wp1EDlUZsXRyAztQcSg=="], "fast-decode-uri-component": ["fast-decode-uri-component@1.0.1", "", {}, "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg=="], @@ -3187,13 +3366,13 @@ "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], - "fast-json-stringify": ["fast-json-stringify@6.3.0", "", { "dependencies": { "@fastify/merge-json-schemas": "^0.2.0", "ajv": "^8.12.0", "ajv-formats": "^3.0.1", "fast-uri": "^3.0.0", "json-schema-ref-resolver": "^3.0.0", "rfdc": "^1.2.0" } }, "sha512-oRCntNDY/329HJPlmdNLIdogNtt6Vyjb1WuT01Soss3slIdyUp8kAcDU3saQTOquEK8KFVfwIIF7FebxUAu+yA=="], + "fast-json-stringify": ["fast-json-stringify@6.4.0", "", { "dependencies": { "@fastify/merge-json-schemas": "^0.2.0", "ajv": "^8.12.0", "ajv-formats": "^3.0.1", "fast-uri": "^3.0.0", "json-schema-ref-resolver": "^3.0.0", "rfdc": "^1.2.0" } }, "sha512-ibRCQ0GZKJIQ+P3Et1h0LhPgp3PMTYk0MH8O+kW3lNYsvmaQww5Nn3f1jf73Q0jR1Yz3a1CDP4/NZD3vOajWJQ=="], "fast-querystring": ["fast-querystring@1.1.2", "", { "dependencies": { "fast-decode-uri-component": "^1.0.1" } }, "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg=="], - "fast-uri": ["fast-uri@3.1.0", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="], + "fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="], - "fast-xml-builder": ["fast-xml-builder@1.1.4", "", { "dependencies": { "path-expression-matcher": "^1.1.3" } }, "sha512-f2jhpN4Eccy0/Uz9csxh3Nu6q4ErKxf0XIsasomfOihuSUa3/xw6w8dnOtCDgEItQFJG8KyXPzQXzcODDrrbOg=="], + "fast-xml-builder": ["fast-xml-builder@1.2.0", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q=="], "fast-xml-parser": ["fast-xml-parser@4.4.1", "", { "dependencies": { "strnum": "^1.0.5" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-xkjOecfnKGkSsOwtZ5Pz7Us/T6mrbPQrq0nh+aCO5V9nk5NLWmasAHumTKjiPJPWANe+kAZ84Jc8ooJkzZ88Sw=="], @@ -3217,7 +3396,7 @@ "find-babel-config": ["find-babel-config@2.1.2", "", { "dependencies": { "json5": "^2.2.3" } }, "sha512-ZfZp1rQyp4gyuxqt1ZqjFGVeVBvmpURMqdIWXbPRfB97Bf6BzdK/xSIbylEINzQ0kB5tlDQfn9HkNXXWsqTqLg=="], - "find-my-way": ["find-my-way@9.5.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-VW2RfnmscZO5KgBY5XVyKREMW5nMZcxDy+buTOsL+zIPnBlbKm+00sgzoQzq1EVh4aALZLfKdwv6atBGcjvjrQ=="], + "find-my-way": ["find-my-way@9.6.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-Zf4Xve4RymLl7NgaavNebZ01joJ8MfVerOG43wy7SHLO+r+K0C6d/SE0BiR7AV5V1VOCFlOP7ecdo+I4qmiHrQ=="], "find-my-way-ts": ["find-my-way-ts@0.1.6", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="], @@ -3281,7 +3460,7 @@ "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], - "get-east-asian-width": ["get-east-asian-width@1.5.0", "", {}, "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA=="], + "get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="], "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], @@ -3295,7 +3474,7 @@ "get-symbol-description": ["get-symbol-description@1.1.0", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6" } }, "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg=="], - "get-tsconfig": ["get-tsconfig@4.13.8", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-J87BxkLXykmisLQ+KA4x2+O6rVf+PJrtFUO8lGyiRg4lyxJLJ8/v0sRAKdVZQOy6tR6lMRAF1NqzCf9BQijm0w=="], + "get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="], "ghostty-web": ["ghostty-web@github:anomalyco/ghostty-web#20bd361", {}, "anomalyco-ghostty-web-20bd361", "sha512-dW0nwaiBBcun9y5WJSvm3HxDLe5o9V0xLCndQvWonRVubU8CS1PHxZpLffyPt1YujPWC13ez03aWxcuKBPYYGQ=="], @@ -3303,7 +3482,7 @@ "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], - "gitlab-ai-provider": ["gitlab-ai-provider@6.7.0", "", { "dependencies": { "@anthropic-ai/sdk": "^0.71.0", "@anycable/core": "^0.9.2", "graphql-request": "^6.1.0", "isomorphic-ws": "^5.0.0", "openai": "^6.16.0", "socket.io-client": "^4.8.1", "vscode-jsonrpc": "^8.2.1", "zod": "^3.25.76" }, "peerDependencies": { "@ai-sdk/provider": ">=3.0.0", "@ai-sdk/provider-utils": ">=4.0.0" } }, "sha512-J7apROAmDwDJcLPcbQ9YQiPhyFN1Vvt/f3ugsePaUnzh3sedfHCHGETgG0Mm0dJCB2rC7DYwmV/sgxLQcQ/sjw=="], + "gitlab-ai-provider": ["gitlab-ai-provider@6.8.0", "", { "dependencies": { "@anthropic-ai/sdk": "^0.71.0", "@anycable/core": "^0.9.2", "graphql-request": "^6.1.0", "isomorphic-ws": "^5.0.0", "openai": "^6.16.0", "socket.io-client": "^4.8.1", "vscode-jsonrpc": "^8.2.1", "zod": "^3.25.76" }, "peerDependencies": { "@ai-sdk/provider": ">=3.0.0", "@ai-sdk/provider-utils": ">=4.0.0" } }, "sha512-KwHASXkHtDcgrzTXZVp9Dyx6t8m9nK0R2fCm47MWcxxQ1kOBt3f2LZugtu1kOby8i4Sbd+kvBSYM66PGkDclng=="], "glob": ["glob@13.0.5", "", { "dependencies": { "minimatch": "^10.2.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-BzXxZg24Ibra1pbQ/zE7Kys4Ua1ks7Bn6pKLkVPZ9FZe4JQS6/Q7ef3LG1H+k7lUf5l4T3PLSyYyYJVYUvfgTw=="], @@ -3327,7 +3506,7 @@ "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], - "graphql": ["graphql@16.13.2", "", {}, "sha512-5bJ+nf/UCpAjHM8i06fl7eLyVC9iuNAjm9qzkiu2ZGhM0VscSvS6WDPfAwkdkBuoXGM9FJSbKl6wylMwP9Ktig=="], + "graphql": ["graphql@16.14.0", "", {}, "sha512-BBvQ/406p+4CZbTpCbVPSxfzrZrbnuWSP1ELYgyS6B+hNeKzgrdB4JczCa5VZUBQrDa9hUngm0KnexY6pJRN5Q=="], "graphql-request": ["graphql-request@6.1.0", "", { "dependencies": { "@graphql-typed-document-node/core": "^3.2.0", "cross-fetch": "^3.1.5" }, "peerDependencies": { "graphql": "14 - 16" } }, "sha512-p+XPfS4q7aIpKVcgmnZKhMNqhltk20hfXtkaIkTfjjmiKMJ5xrt5c743cL03y/K7y1rg3WrIC49xGiEQ4mxdNw=="], @@ -3351,7 +3530,7 @@ "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], - "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], "hast-util-embedded": ["hast-util-embedded@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-is-element": "^3.0.0" } }, "sha512-naH8sld4Pe2ep03qqULEtvYr7EjrLK2QHY8KJR6RJkTUjPGObe1vnx585uzem2hGra+s1q08DZZpfgDVYRbaXA=="], @@ -3405,7 +3584,7 @@ "hono-openapi": ["hono-openapi@1.1.2", "", { "peerDependencies": { "@hono/standard-validator": "^0.2.0", "@standard-community/standard-json": "^0.3.5", "@standard-community/standard-openapi": "^0.2.9", "@types/json-schema": "^7.0.15", "hono": "^4.8.3", "openapi-types": "^12.1.3" }, "optionalPeers": ["@hono/standard-validator", "hono"] }, "sha512-toUcO60MftRBxqcVyxsHNYs2m4vf4xkQaiARAucQx3TiBPDtMNNkoh+C4I1vAretQZiGyaLOZNWn1YxfSyUA5g=="], - "hosted-git-info": ["hosted-git-info@9.0.2", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-M422h7o/BR3rmCQ8UHi7cyyMqKltdP9Uo+J2fXK+RSAY+wTcKOIRyhTuKv4qn+DJf3g+PL890AzId5KZpX+CBg=="], + "hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], "html-entities": ["html-entities@2.3.3", "", {}, "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA=="], @@ -3457,8 +3636,6 @@ "import-meta-resolve": ["import-meta-resolve@4.2.0", "", {}, "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg=="], - "imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="], - "indent-string": ["indent-string@4.0.0", "", {}, "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg=="], "inflight": ["inflight@1.0.6", "", { "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA=="], @@ -3471,9 +3648,11 @@ "internal-slot": ["internal-slot@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="], - "ioredis": ["ioredis@5.10.1", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA=="], + "internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="], + + "ioredis": ["ioredis@5.11.0", "", { "dependencies": { "@ioredis/commands": "1.10.0", "cluster-key-slot": "1.1.1", "debug": "4.4.3", "denque": "2.1.0", "redis-errors": "1.2.0", "redis-parser": "3.0.0", "standard-as-callback": "2.1.0" } }, "sha512-EZBErytyVovD8f6pDfG3Kb37N6Y3lmDA9NNj+4+IP13CzzHGeX+OyeRM2Um13khRzoBSzzL+5lVnCX8V2RLeMg=="], - "ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="], + "ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="], "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], @@ -3501,7 +3680,7 @@ "is-callable": ["is-callable@1.2.7", "", {}, "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA=="], - "is-core-module": ["is-core-module@2.16.1", "", { "dependencies": { "hasown": "^2.0.2" } }, "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w=="], + "is-core-module": ["is-core-module@2.16.2", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA=="], "is-data-view": ["is-data-view@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "get-intrinsic": "^1.2.6", "is-typed-array": "^1.1.13" } }, "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw=="], @@ -3531,8 +3710,6 @@ "is-inside-container": ["is-inside-container@1.0.0", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="], - "is-interactive": ["is-interactive@1.0.0", "", {}, "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w=="], - "is-map": ["is-map@2.0.3", "", {}, "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw=="], "is-negative-zero": ["is-negative-zero@2.0.3", "", {}, "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw=="], @@ -3561,8 +3738,6 @@ "is-typed-array": ["is-typed-array@1.1.15", "", { "dependencies": { "which-typed-array": "^1.1.16" } }, "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ=="], - "is-unicode-supported": ["is-unicode-supported@0.1.0", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="], - "is-weakmap": ["is-weakmap@2.0.2", "", {}, "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w=="], "is-weakref": ["is-weakref@1.1.1", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew=="], @@ -3593,7 +3768,7 @@ "jake": ["jake@10.9.4", "", { "dependencies": { "async": "^3.2.6", "filelist": "^1.0.4", "picocolors": "^1.1.1" }, "bin": { "jake": "bin/cli.js" } }, "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA=="], - "jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="], + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], "jose": ["jose@6.0.11", "", {}, "sha512-QxG7EaliDARm1O1S8BGakqncGT9s25bKL1WSf6/oa17Tkqwi8D2ZNglqCF+DsYF88/rV66Q/Q2mFAy697E1DUg=="], @@ -3601,9 +3776,7 @@ "js-beautify": ["js-beautify@1.15.4", "", { "dependencies": { "config-chain": "^1.1.13", "editorconfig": "^1.0.4", "glob": "^10.4.2", "js-cookie": "^3.0.5", "nopt": "^7.2.1" }, "bin": { "css-beautify": "js/bin/css-beautify.js", "html-beautify": "js/bin/html-beautify.js", "js-beautify": "js/bin/js-beautify.js" } }, "sha512-9/KXeZUKKJwqCXUdBxFJ3vPh467OCckSBmYDwSK/EtV090K+iMJ7zx2S3HLVDIWFQdqMIsZWbnaGiba18aWhaA=="], - "js-cookie": ["js-cookie@3.0.5", "", {}, "sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw=="], - - "js-md4": ["js-md4@0.3.2", "", {}, "sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA=="], + "js-cookie": ["js-cookie@3.0.8", "", {}, "sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw=="], "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], @@ -3709,14 +3882,10 @@ "lodash": ["lodash@4.18.1", "", {}, "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="], - "lodash.defaults": ["lodash.defaults@4.2.0", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="], - "lodash.escaperegexp": ["lodash.escaperegexp@4.1.2", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="], "lodash.includes": ["lodash.includes@4.3.0", "", {}, "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="], - "lodash.isarguments": ["lodash.isarguments@3.1.0", "", {}, "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg=="], - "lodash.isboolean": ["lodash.isboolean@3.0.3", "", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="], "lodash.isequal": ["lodash.isequal@4.5.0", "", {}, "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ=="], @@ -3731,8 +3900,6 @@ "lodash.once": ["lodash.once@4.1.1", "", {}, "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="], - "log-symbols": ["log-symbols@4.1.0", "", { "dependencies": { "chalk": "^4.1.0", "is-unicode-supported": "^0.1.0" } }, "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg=="], - "loglevelnext": ["loglevelnext@6.0.0", "", {}, "sha512-FDl1AI2sJGjHHG3XKJd6sG3/6ncgiGCQ0YkW46nxe7SfqQq6hujd9CvFXIXtkGBUN83KPZ2KSOJK8q5P0bSSRQ=="], "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], @@ -3747,7 +3914,7 @@ "lowercase-keys": ["lowercase-keys@2.0.0", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="], - "lru-cache": ["lru-cache@11.3.5", "", {}, "sha512-NxVFwLAnrd9i7KUBxC4DrUhmgjzOs+1Qm50D3oF1/oL+r1NpZ4gA7xvG0/zJ8evR7zIKn4vLf7qTNduWFtCrRw=="], + "lru-cache": ["lru-cache@11.5.1", "", {}, "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A=="], "lru.min": ["lru.min@1.1.4", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="], @@ -3761,7 +3928,7 @@ "magicast": ["magicast@0.3.5", "", { "dependencies": { "@babel/parser": "^7.25.4", "@babel/types": "^7.25.4", "source-map-js": "^1.2.0" } }, "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ=="], - "make-fetch-happen": ["make-fetch-happen@15.0.5", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" } }, "sha512-uCbIa8jWWmQZt4dSnEStkVC6gdakiinAm4PiGsywIkguF0eWMdcjDz0ECYhUolFU3pFLOev9VNPCEygydXnddg=="], + "make-fetch-happen": ["make-fetch-happen@15.0.6", "", { "dependencies": { "@gar/promise-retry": "^1.0.0", "@npmcli/agent": "^4.0.0", "@npmcli/redact": "^4.0.0", "cacache": "^20.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^5.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^6.0.0", "ssri": "^13.0.0" } }, "sha512-Je0fLJ0F5atA7F+eIlLzk+Wkcl57JDf4kf+EW8xiP5E31xOQxkIxTbgf1Oi1Lw9tRI9UEMRdI5Vz2xTzoNU1Jw=="], "markdown-extensions": ["markdown-extensions@2.0.0", "", {}, "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q=="], @@ -3951,11 +4118,9 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "msgpackr": ["msgpackr@1.11.9", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-FkoAAyyA6HM8wL882EcEyFZ9s7hVADSwG9xrVx3dxxNQAtgADTrJoEWivID82Iv1zWDsv/OtbrrcZAzGzOMdNw=="], - - "msgpackr-extract": ["msgpackr-extract@3.0.3", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="], + "msgpackr": ["msgpackr@1.11.12", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-RBdJ1Un7yGlXWajrkxcSa93nvQ0w4zBf60c0yYv7YtBelP8H2FA7XsfBbMHtXKXUMUxH7zV3Zuozh+kUQWhHvg=="], - "mssql": ["mssql@11.0.1", "", { "dependencies": { "@tediousjs/connection-string": "^0.5.0", "commander": "^11.0.0", "debug": "^4.3.3", "rfdc": "^1.3.0", "tarn": "^3.0.2", "tedious": "^18.2.1" }, "bin": { "mssql": "bin/mssql" } }, "sha512-KlGNsugoT90enKlR8/G36H0kTxPthDhmtNUCwEHvgRza5Cjpjoj+P2X6eMpFUDN7pFrJZsKadL4x990G8RBE1w=="], + "msgpackr-extract": ["msgpackr-extract@3.0.4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="], "muggle-string": ["muggle-string@0.4.1", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="], @@ -3973,9 +4138,7 @@ "nanoevents": ["nanoevents@7.0.1", "", {}, "sha512-o6lpKiCxLeijK4hgsqfR6CNToPyRU3keKyyI6uwuHRvpRTbZ0wXw51WRgyldVugZqoJfkGFrjrIenYH3bfEO3Q=="], - "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], - - "native-duplexpair": ["native-duplexpair@1.0.0", "", {}, "sha512-E7QQoM+3jvNtlmyfqRZ0/U75VFgCls+fSkbml2MpgWkWyz3ox8Y58gNhfuziuQYGNNQAbFZJQck55LHCnCK6CA=="], + "nanoid": ["nanoid@3.3.12", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ=="], "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], @@ -3989,7 +4152,7 @@ "no-case": ["no-case@3.0.4", "", { "dependencies": { "lower-case": "^2.0.2", "tslib": "^2.0.3" } }, "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg=="], - "node-abi": ["node-abi@4.28.0", "", { "dependencies": { "semver": "^7.6.3" } }, "sha512-Qfp5XZL1cJDOabOT8H5gnqMTmM4NjvYzHp4I/Kt/Sl76OVkOBBHRFlPspGV0hYvMoqQsypFjT/Yp7Km0beXW9g=="], + "node-abi": ["node-abi@4.31.0", "", { "dependencies": { "semver": "^7.6.3" } }, "sha512-Erq5w/t3syw3s4sDsUaX4QttIdBPsGKTT1DTRsCkTonGggczhlDKm/wDX3o+HPJpQ41EjXCbcmXf0tgr5YZJXw=="], "node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="], @@ -4001,7 +4164,7 @@ "node-fetch-native": ["node-fetch-native@1.6.7", "", {}, "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q=="], - "node-gyp": ["node-gyp@12.2.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "make-fetch-happen": "^15.0.0", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "which": "^6.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-q23WdzrQv48KozXlr0U1v9dwO/k59NHeSzn6loGcasyf0UnSrtzs8kRxM+mfwJSf0DkX0s43hcqgnSO4/VNthQ=="], + "node-gyp": ["node-gyp@12.3.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "nopt": "^9.0.0", "proc-log": "^6.0.0", "semver": "^7.3.5", "tar": "^7.5.4", "tinyglobby": "^0.2.12", "undici": "^6.25.0", "which": "^6.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-QNcUWM+HgJplcPzBvFBZ9VXacyGZ4+VTOb80PwWR+TlVzoHbRKULNEzpRsnaoxG3Wzr7Qh7BYxGDU3CbKib2Yg=="], "node-gyp-build": ["node-gyp-build@4.8.4", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ=="], @@ -4011,7 +4174,7 @@ "node-mock-http": ["node-mock-http@1.0.4", "", {}, "sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ=="], - "node-releases": ["node-releases@2.0.37", "", {}, "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg=="], + "node-releases": ["node-releases@2.0.46", "", {}, "sha512-GYVXHE2KnrzAfsAjl4uP++evGFCrAU1jta4ubEjIG7YWt/64Gqv66a30yKwWczVjA6j3bM4nBwH7Pk1JmDHaxQ=="], "nopt": ["nopt@9.0.0", "", { "dependencies": { "abbrev": "^4.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw=="], @@ -4037,7 +4200,7 @@ "nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="], - "nypm": ["nypm@0.6.5", "", { "dependencies": { "citty": "^0.2.0", "pathe": "^2.0.3", "tinyexec": "^1.0.2" }, "bin": { "nypm": "dist/cli.mjs" } }, "sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ=="], + "nypm": ["nypm@0.6.6", "", { "dependencies": { "citty": "^0.2.2", "pathe": "^2.0.3", "tinyexec": "^1.1.1" }, "bin": { "nypm": "dist/cli.mjs" } }, "sha512-vRyr0r4cbBapw07Xw8xrj9Teq3o7MUD35rSaTcanDbW+aK2XHDgJFiU6ZTj2GBw7Q12ysdsyFss+Vdz4hQ0Y6Q=="], "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], @@ -4065,9 +4228,9 @@ "onetime": ["onetime@6.0.0", "", { "dependencies": { "mimic-fn": "^4.0.0" } }, "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ=="], - "oniguruma-parser": ["oniguruma-parser@0.12.1", "", {}, "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w=="], + "oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="], - "oniguruma-to-es": ["oniguruma-to-es@4.3.5", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="], + "oniguruma-to-es": ["oniguruma-to-es@4.3.6", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="], "open": ["open@10.1.2", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "is-wsl": "^3.1.0" } }, "sha512-cxN6aIDPz6rm8hbebcP7vrQNhvRcveZoJU72Y7vskh4oIm+BZwBECnx5nTmrlres1Qapvx27Qo1Auukpf8PKXw=="], @@ -4085,12 +4248,14 @@ "opentui-spinner": ["opentui-spinner@0.0.6", "", { "dependencies": { "cli-spinners": "^3.3.0" }, "peerDependencies": { "@opentui/core": "^0.1.49", "@opentui/react": "^0.1.49", "@opentui/solid": "^0.1.49", "typescript": "^5" }, "optionalPeers": ["@opentui/react", "@opentui/solid"] }, "sha512-xupLOeVQEAXEvVJCvHkfX6fChDWmJIPHe5jyUrVb8+n4XVTX8mBNhitFfB9v2ZbkC1H2UwPab/ElePHoW37NcA=="], - "ora": ["ora@5.4.1", "", { "dependencies": { "bl": "^4.1.0", "chalk": "^4.1.0", "cli-cursor": "^3.1.0", "cli-spinners": "^2.5.0", "is-interactive": "^1.0.0", "is-unicode-supported": "^0.1.0", "log-symbols": "^4.1.0", "strip-ansi": "^6.0.0", "wcwidth": "^1.0.1" } }, "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ=="], - "own-keys": ["own-keys@1.0.1", "", { "dependencies": { "get-intrinsic": "^1.2.6", "object-keys": "^1.1.1", "safe-push-apply": "^1.0.0" } }, "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg=="], "oxc-minify": ["oxc-minify@0.96.0", "", { "optionalDependencies": { "@oxc-minify/binding-android-arm64": "0.96.0", "@oxc-minify/binding-darwin-arm64": "0.96.0", "@oxc-minify/binding-darwin-x64": "0.96.0", "@oxc-minify/binding-freebsd-x64": "0.96.0", "@oxc-minify/binding-linux-arm-gnueabihf": "0.96.0", "@oxc-minify/binding-linux-arm-musleabihf": "0.96.0", "@oxc-minify/binding-linux-arm64-gnu": "0.96.0", "@oxc-minify/binding-linux-arm64-musl": "0.96.0", "@oxc-minify/binding-linux-riscv64-gnu": "0.96.0", "@oxc-minify/binding-linux-s390x-gnu": "0.96.0", "@oxc-minify/binding-linux-x64-gnu": "0.96.0", "@oxc-minify/binding-linux-x64-musl": "0.96.0", "@oxc-minify/binding-wasm32-wasi": "0.96.0", "@oxc-minify/binding-win32-arm64-msvc": "0.96.0", "@oxc-minify/binding-win32-x64-msvc": "0.96.0" } }, "sha512-dXeeGrfPJJ4rMdw+NrqiCRtbzVX2ogq//R0Xns08zql2HjV3Zi2SBJ65saqfDaJzd2bcHqvGWH+M44EQCHPAcA=="], + "oxc-parser": ["oxc-parser@0.127.0", "", { "dependencies": { "@oxc-project/types": "^0.127.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.127.0", "@oxc-parser/binding-android-arm64": "0.127.0", "@oxc-parser/binding-darwin-arm64": "0.127.0", "@oxc-parser/binding-darwin-x64": "0.127.0", "@oxc-parser/binding-freebsd-x64": "0.127.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.127.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.127.0", "@oxc-parser/binding-linux-arm64-gnu": "0.127.0", "@oxc-parser/binding-linux-arm64-musl": "0.127.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.127.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.127.0", "@oxc-parser/binding-linux-riscv64-musl": "0.127.0", "@oxc-parser/binding-linux-s390x-gnu": "0.127.0", "@oxc-parser/binding-linux-x64-gnu": "0.127.0", "@oxc-parser/binding-linux-x64-musl": "0.127.0", "@oxc-parser/binding-openharmony-arm64": "0.127.0", "@oxc-parser/binding-wasm32-wasi": "0.127.0", "@oxc-parser/binding-win32-arm64-msvc": "0.127.0", "@oxc-parser/binding-win32-ia32-msvc": "0.127.0", "@oxc-parser/binding-win32-x64-msvc": "0.127.0" } }, "sha512-bkgD4qHlN7WxLdX8bLXdaU54TtQtAIg/ZBAfm0aje/mo3MRDo3P0hZSgr4U7O3xfX+fQmR5AP04JS/TGcZLcFA=="], + + "oxc-resolver": ["oxc-resolver@11.20.0", "", { "optionalDependencies": { "@oxc-resolver/binding-android-arm-eabi": "11.20.0", "@oxc-resolver/binding-android-arm64": "11.20.0", "@oxc-resolver/binding-darwin-arm64": "11.20.0", "@oxc-resolver/binding-darwin-x64": "11.20.0", "@oxc-resolver/binding-freebsd-x64": "11.20.0", "@oxc-resolver/binding-linux-arm-gnueabihf": "11.20.0", "@oxc-resolver/binding-linux-arm-musleabihf": "11.20.0", "@oxc-resolver/binding-linux-arm64-gnu": "11.20.0", "@oxc-resolver/binding-linux-arm64-musl": "11.20.0", "@oxc-resolver/binding-linux-ppc64-gnu": "11.20.0", "@oxc-resolver/binding-linux-riscv64-gnu": "11.20.0", "@oxc-resolver/binding-linux-riscv64-musl": "11.20.0", "@oxc-resolver/binding-linux-s390x-gnu": "11.20.0", "@oxc-resolver/binding-linux-x64-gnu": "11.20.0", "@oxc-resolver/binding-linux-x64-musl": "11.20.0", "@oxc-resolver/binding-openharmony-arm64": "11.20.0", "@oxc-resolver/binding-wasm32-wasi": "11.20.0", "@oxc-resolver/binding-win32-arm64-msvc": "11.20.0", "@oxc-resolver/binding-win32-x64-msvc": "11.20.0" } }, "sha512-CblytBiV/a/ZXY34dsVU2NxhIOxMXst8CvDCtyBelVITgd7PLrKzbEbA6oKLdPjvDKDzCiW48qzmzZ+mYaqn+g=="], + "oxc-transform": ["oxc-transform@0.96.0", "", { "optionalDependencies": { "@oxc-transform/binding-android-arm64": "0.96.0", "@oxc-transform/binding-darwin-arm64": "0.96.0", "@oxc-transform/binding-darwin-x64": "0.96.0", "@oxc-transform/binding-freebsd-x64": "0.96.0", "@oxc-transform/binding-linux-arm-gnueabihf": "0.96.0", "@oxc-transform/binding-linux-arm-musleabihf": "0.96.0", "@oxc-transform/binding-linux-arm64-gnu": "0.96.0", "@oxc-transform/binding-linux-arm64-musl": "0.96.0", "@oxc-transform/binding-linux-riscv64-gnu": "0.96.0", "@oxc-transform/binding-linux-s390x-gnu": "0.96.0", "@oxc-transform/binding-linux-x64-gnu": "0.96.0", "@oxc-transform/binding-linux-x64-musl": "0.96.0", "@oxc-transform/binding-wasm32-wasi": "0.96.0", "@oxc-transform/binding-win32-arm64-msvc": "0.96.0", "@oxc-transform/binding-win32-x64-msvc": "0.96.0" } }, "sha512-dQPNIF+gHpSkmC0+Vg9IktNyhcn28Y8R3eTLyzn52UNymkasLicl3sFAtz7oEVuFmCpgGjaUTKkwk+jW2cHpDQ=="], "oxlint": ["oxlint@1.60.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.60.0", "@oxlint/binding-android-arm64": "1.60.0", "@oxlint/binding-darwin-arm64": "1.60.0", "@oxlint/binding-darwin-x64": "1.60.0", "@oxlint/binding-freebsd-x64": "1.60.0", "@oxlint/binding-linux-arm-gnueabihf": "1.60.0", "@oxlint/binding-linux-arm-musleabihf": "1.60.0", "@oxlint/binding-linux-arm64-gnu": "1.60.0", "@oxlint/binding-linux-arm64-musl": "1.60.0", "@oxlint/binding-linux-ppc64-gnu": "1.60.0", "@oxlint/binding-linux-riscv64-gnu": "1.60.0", "@oxlint/binding-linux-riscv64-musl": "1.60.0", "@oxlint/binding-linux-s390x-gnu": "1.60.0", "@oxlint/binding-linux-x64-gnu": "1.60.0", "@oxlint/binding-linux-x64-musl": "1.60.0", "@oxlint/binding-openharmony-arm64": "1.60.0", "@oxlint/binding-win32-arm64-msvc": "1.60.0", "@oxlint/binding-win32-ia32-msvc": "1.60.0", "@oxlint/binding-win32-x64-msvc": "1.60.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.18.0" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-tnRzTWiWJ9pg3ftRWnD0+Oqh78L6ZSwcEudvCZaER0PIqiAnNyXj5N1dPwjmNpDalkKS9m/WMLN1CTPUBPmsgw=="], @@ -4197,7 +4362,7 @@ "pkg-dir": ["pkg-dir@4.2.0", "", { "dependencies": { "find-up": "^4.0.0" } }, "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ=="], - "pkg-types": ["pkg-types@2.3.0", "", { "dependencies": { "confbox": "^0.2.2", "exsolve": "^1.0.7", "pathe": "^2.0.3" } }, "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig=="], + "pkg-types": ["pkg-types@2.3.1", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="], "pkg-up": ["pkg-up@3.1.0", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="], @@ -4207,11 +4372,11 @@ "plist": ["plist@3.1.0", "", { "dependencies": { "@xmldom/xmldom": "^0.8.8", "base64-js": "^1.5.1", "xmlbuilder": "^15.1.1" } }, "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ=="], - "poe-oauth": ["poe-oauth@0.0.6", "", {}, "sha512-dI8xrVl7RSFh0B+cb4GGuCjIfGtDT9VpbpVkP0UKcunpXF0eFw+6GencoJ7k+E02ZYqopBQApMVWGq70/GP69w=="], + "poe-oauth": ["poe-oauth@0.0.8", "", {}, "sha512-zlaRVLR6vuxBIYUkZoTIVo3f8h3qd27gv9Ms+kmGiYEiiV4TdccddTdNcGyI0DnuJ9tVi+5LP3Bvzez59IFbjw=="], "possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="], - "postcss": ["postcss@8.5.9", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw=="], + "postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="], "postcss-css-variables": ["postcss-css-variables@0.18.0", "", { "dependencies": { "balanced-match": "^1.0.0", "escape-string-regexp": "^1.0.3", "extend": "^3.0.1" }, "peerDependencies": { "postcss": "^8.2.6" } }, "sha512-lYS802gHbzn1GI+lXvy9MYIYDuGnl1WB4FTKoqMQqJ3Mab09A7a/1wZvGTkCEZJTM8mSbIyb1mJYn8f0aPye0Q=="], @@ -4269,7 +4434,7 @@ "proto-list": ["proto-list@1.2.4", "", {}, "sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA=="], - "protobufjs": ["protobufjs@7.5.4", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.4", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.0", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.0", "@types/node": ">=13.7.0", "long": "^5.0.0" } }, "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg=="], + "protobufjs": ["protobufjs@7.6.1", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/inquire": "^1.1.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-4K0myLaWL5EteuSAro91EGFgcfVgxb64Jx+7oDAY6GOkXD4M69yuSEljNcInGVCA5sOPxmZ/EqDLj2x0Q0+Ygg=="], "proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="], @@ -4283,7 +4448,7 @@ "pure-rand": ["pure-rand@8.4.0", "", {}, "sha512-IoM8YF/jY0hiugFo/wOWqfmarlE6J0wc6fDK1PhftMk7MGhVZl88sZimmqBBFomLOCSmcCCpsfj7wXASCpvK9A=="], - "qs": ["qs@6.15.1", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg=="], + "qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="], "quansync": ["quansync@0.2.11", "", {}, "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA=="], @@ -4419,8 +4584,6 @@ "responselike": ["responselike@2.0.1", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="], - "restore-cursor": ["restore-cursor@3.1.0", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA=="], - "restructure": ["restructure@3.0.2", "", {}, "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw=="], "ret": ["ret@0.5.0", "", {}, "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw=="], @@ -4443,7 +4606,7 @@ "roarr": ["roarr@2.15.4", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="], - "rollup": ["rollup@4.60.1", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.60.1", "@rollup/rollup-android-arm64": "4.60.1", "@rollup/rollup-darwin-arm64": "4.60.1", "@rollup/rollup-darwin-x64": "4.60.1", "@rollup/rollup-freebsd-arm64": "4.60.1", "@rollup/rollup-freebsd-x64": "4.60.1", "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", "@rollup/rollup-linux-arm-musleabihf": "4.60.1", "@rollup/rollup-linux-arm64-gnu": "4.60.1", "@rollup/rollup-linux-arm64-musl": "4.60.1", "@rollup/rollup-linux-loong64-gnu": "4.60.1", "@rollup/rollup-linux-loong64-musl": "4.60.1", "@rollup/rollup-linux-ppc64-gnu": "4.60.1", "@rollup/rollup-linux-ppc64-musl": "4.60.1", "@rollup/rollup-linux-riscv64-gnu": "4.60.1", "@rollup/rollup-linux-riscv64-musl": "4.60.1", "@rollup/rollup-linux-s390x-gnu": "4.60.1", "@rollup/rollup-linux-x64-gnu": "4.60.1", "@rollup/rollup-linux-x64-musl": "4.60.1", "@rollup/rollup-openbsd-x64": "4.60.1", "@rollup/rollup-openharmony-arm64": "4.60.1", "@rollup/rollup-win32-arm64-msvc": "4.60.1", "@rollup/rollup-win32-ia32-msvc": "4.60.1", "@rollup/rollup-win32-x64-gnu": "4.60.1", "@rollup/rollup-win32-x64-msvc": "4.60.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w=="], + "rollup": ["rollup@4.60.4", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.60.4", "@rollup/rollup-android-arm64": "4.60.4", "@rollup/rollup-darwin-arm64": "4.60.4", "@rollup/rollup-darwin-x64": "4.60.4", "@rollup/rollup-freebsd-arm64": "4.60.4", "@rollup/rollup-freebsd-x64": "4.60.4", "@rollup/rollup-linux-arm-gnueabihf": "4.60.4", "@rollup/rollup-linux-arm-musleabihf": "4.60.4", "@rollup/rollup-linux-arm64-gnu": "4.60.4", "@rollup/rollup-linux-arm64-musl": "4.60.4", "@rollup/rollup-linux-loong64-gnu": "4.60.4", "@rollup/rollup-linux-loong64-musl": "4.60.4", "@rollup/rollup-linux-ppc64-gnu": "4.60.4", "@rollup/rollup-linux-ppc64-musl": "4.60.4", "@rollup/rollup-linux-riscv64-gnu": "4.60.4", "@rollup/rollup-linux-riscv64-musl": "4.60.4", "@rollup/rollup-linux-s390x-gnu": "4.60.4", "@rollup/rollup-linux-x64-gnu": "4.60.4", "@rollup/rollup-linux-x64-musl": "4.60.4", "@rollup/rollup-openbsd-x64": "4.60.4", "@rollup/rollup-openharmony-arm64": "4.60.4", "@rollup/rollup-win32-arm64-msvc": "4.60.4", "@rollup/rollup-win32-ia32-msvc": "4.60.4", "@rollup/rollup-win32-x64-gnu": "4.60.4", "@rollup/rollup-win32-x64-msvc": "4.60.4", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g=="], "rou3": ["rou3@0.7.12", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="], @@ -4455,7 +4618,7 @@ "s-js": ["s-js@0.4.9", "", {}, "sha512-RtpOm+cM6O0sHg6IA70wH+UC3FZcND+rccBZpBAHzlUgNO2Bm5BN+FnM8+OBxzXdwpKWFwX11JGF0MFRkhSoIQ=="], - "safe-array-concat": ["safe-array-concat@1.1.3", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.2", "get-intrinsic": "^1.2.6", "has-symbols": "^1.1.0", "isarray": "^2.0.5" } }, "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q=="], + "safe-array-concat": ["safe-array-concat@1.1.4", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "has-symbols": "^1.1.0", "isarray": "^2.0.5" } }, "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg=="], "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], @@ -4463,7 +4626,7 @@ "safe-regex-test": ["safe-regex-test@1.1.0", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-regex": "^1.2.1" } }, "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw=="], - "safe-regex2": ["safe-regex2@5.1.0", "", { "dependencies": { "ret": "~0.5.0" }, "bin": { "safe-regex2": "bin/safe-regex2.js" } }, "sha512-pNHAuBW7TrcleFHsxBr5QMi/Iyp0ENjUKz7GCcX1UO7cMh+NmVK6HxQckNL1tJp1XAJVjG6B8OKIPqodqj9rtw=="], + "safe-regex2": ["safe-regex2@5.1.1", "", { "dependencies": { "ret": "~0.5.0" }, "bin": { "safe-regex2": "bin/safe-regex2.js" } }, "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA=="], "safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="], @@ -4481,7 +4644,7 @@ "selderee": ["selderee@0.11.0", "", { "dependencies": { "parseley": "^0.12.0" } }, "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA=="], - "semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="], + "semver": ["semver@7.8.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg=="], "semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="], @@ -4529,7 +4692,7 @@ "signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], - "sigstore": ["sigstore@4.1.0", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.1.0", "@sigstore/protobuf-specs": "^0.5.0", "@sigstore/sign": "^4.1.0", "@sigstore/tuf": "^4.0.1", "@sigstore/verify": "^3.1.0" } }, "sha512-/fUgUhYghuLzVT/gaJoeVehLCgZiUxPCPMcyVNY0lIf/cTCz58K/WTI7PefDarXxp9nUKpEwg1yyz3eSBMTtgA=="], + "sigstore": ["sigstore@4.1.1", "", { "dependencies": { "@sigstore/bundle": "^4.0.0", "@sigstore/core": "^3.2.1", "@sigstore/protobuf-specs": "^0.5.0", "@sigstore/sign": "^4.1.1", "@sigstore/tuf": "^4.0.2", "@sigstore/verify": "^3.1.1" } }, "sha512-endqECJkfhozrXMK5ngu/UAA0xVcVEFdnHJCElGaExypjW+HK5i6zu3NteLoaX/iFbRUbC3+DjttQs0GARr+5w=="], "simple-swizzle": ["simple-swizzle@0.2.4", "", { "dependencies": { "is-arrayish": "^0.3.1" } }, "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw=="], @@ -4551,7 +4714,7 @@ "socket.io-parser": ["socket.io-parser@4.2.6", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1" } }, "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg=="], - "socks": ["socks@2.8.7", "", { "dependencies": { "ip-address": "^10.0.1", "smart-buffer": "^4.2.0" } }, "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A=="], + "socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="], "socks-proxy-agent": ["socks-proxy-agent@8.0.5", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw=="], @@ -4591,7 +4754,7 @@ "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], - "sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="], + "sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], "sqlstring": ["sqlstring@2.3.3", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="], @@ -4627,19 +4790,19 @@ "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], - "std-env": ["std-env@4.0.0", "", {}, "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ=="], + "std-env": ["std-env@4.1.0", "", {}, "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ=="], "stop-iteration-iterator": ["stop-iteration-iterator@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "internal-slot": "^1.1.0" } }, "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ=="], "stoppable": ["stoppable@1.1.0", "", {}, "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw=="], - "storybook": ["storybook@10.3.5", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/icons": "^2.0.1", "@testing-library/jest-dom": "^6.9.1", "@testing-library/user-event": "^14.6.1", "@vitest/expect": "3.2.4", "@vitest/spy": "3.2.4", "@webcontainer/env": "^1.1.1", "esbuild": "^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0", "open": "^10.2.0", "recast": "^0.23.5", "semver": "^7.7.3", "use-sync-external-store": "^1.5.0", "ws": "^8.18.0" }, "peerDependencies": { "prettier": "^2 || ^3" }, "optionalPeers": ["prettier"], "bin": "./dist/bin/dispatcher.js" }, "sha512-uBSZu/GZa9aEIW3QMGvdQPMZWhGxSe4dyRWU8B3/Vd47Gy/XLC7tsBxRr13txmmPOEDHZR94uLuq0H50fvuqBw=="], + "storybook": ["storybook@10.4.1", "", { "dependencies": { "@storybook/global": "^5.0.0", "@storybook/icons": "^2.0.2", "@testing-library/jest-dom": "^6.9.1", "@testing-library/user-event": "^14.6.1", "@vitest/expect": "3.2.4", "@vitest/spy": "3.2.4", "@webcontainer/env": "^1.1.1", "esbuild": "^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0", "open": "^10.2.0", "oxc-parser": "^0.127.0", "oxc-resolver": "^11.19.1", "recast": "^0.23.5", "semver": "^7.7.3", "use-sync-external-store": "^1.5.0", "ws": "^8.18.0" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "prettier": "^2 || ^3", "vite-plus": "^0.1.15" }, "optionalPeers": ["@types/react", "prettier", "vite-plus"], "bin": "./dist/bin/dispatcher.js" }, "sha512-V1Zd2e+gBFufqAQVZ1JR8KLqALsEZ3JYSBnWwQbKa6zCfWWanR6AFMyuOkLt2gZOgGp3h2Riuz88pGNVTQSG0A=="], - "storybook-solidjs-vite": ["storybook-solidjs-vite@10.0.12", "", { "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "^0.7.0", "@storybook/builder-vite": "^10.3.1", "@storybook/global": "^5.0.0", "vite-plugin-solid": "^2.11.11" }, "peerDependencies": { "solid-js": "^1.9.0", "storybook": "^0.0.0-0 || ^10.0.0", "typescript": "^4.0.0 || ^5.0.0 || ^6.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["typescript"] }, "sha512-KfKhJRdxbhFLHkBzLKSEk5sO2M/+KV9cdpki5Xdl5pwNP8kcoQnZ3b/okZk8dMRV6x19j86bKc7zDfc5bPSMwA=="], + "storybook-solidjs-vite": ["storybook-solidjs-vite@10.1.1", "", { "dependencies": { "@joshwooding/vite-plugin-react-docgen-typescript": "^0.7.0", "@storybook/builder-vite": "^10.4.0", "@storybook/global": "^5.0.0", "semver": "7.8.1" }, "peerDependencies": { "@solidjs/web": "^2.0.0-0", "solid-js": "^1.8.0-0 || ^2.0.0-0", "storybook": "^0.0.0-0 || ^10.0.0", "typescript": "^4.0.0 || ^5.0.0 || ^6.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vite-plugin-solid": "^2.0.0-0 || ^3.0.0-0" }, "optionalPeers": ["@solidjs/web", "typescript"] }, "sha512-4acj1yxVPM3PieEGFPJukPeIXmpboJprewiX0KMrdYvtAZy8zbkZ7QBf8iENyKNJOayeXWzMm+z7hWBQDUirYg=="], "stream-replace-string": ["stream-replace-string@2.0.0", "", {}, "sha512-TlnjJ1C0QrmxRNrON00JvaFFlNh5TTG00APw23j74ET7gkQpTASi6/L2fuiav8pzK715HXtUeClpBTw2NPSn6w=="], - "streamx": ["streamx@2.25.0", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg=="], + "streamx": ["streamx@2.26.0", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-VvNG1K72Po/xwJzxZFnZ++Tbrv4lwSptsbkFuzXCJAYZvCK5nnxsvXU6ajqkv7chyiI1Y0YXq2Jh8Iy8Y7NF/A=="], "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], @@ -4693,15 +4856,11 @@ "tailwindcss": ["tailwindcss@4.1.11", "", {}, "sha512-2E9TBm6MDD/xKYe+dvJZAmg3yxIEDNRc0jwlNyDg/4Fil2QcSLjFKGVff0lAf1jjeaArlG/M75Ey/EYr/OJtBA=="], - "tapable": ["tapable@2.3.2", "", {}, "sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA=="], - - "tar": ["tar@7.5.13", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng=="], + "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], - "tar-stream": ["tar-stream@3.1.8", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-U6QpVRyCGHva435KoNWy9PRoi2IFYCgtEhq9nmrPPpbRacPs9IH4aJ3gbrFC8dPcXvdSZ4XXfXT5Fshbp2MtlQ=="], + "tar": ["tar@7.5.15", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ=="], - "tarn": ["tarn@3.0.2", "", {}, "sha512-51LAVKUSZSVfI05vjPESNc5vwqqZpbXCsU+/+wxlOrUjk2SnFTt97v9ZgQrD4YmxYW1Px6w2KjaDitCfkvgxMQ=="], - - "tedious": ["tedious@19.2.1", "", { "dependencies": { "@azure/core-auth": "^1.7.2", "@azure/identity": "^4.2.1", "@azure/keyvault-keys": "^4.4.0", "@js-joda/core": "^5.6.5", "@types/node": ">=18", "bl": "^6.1.4", "iconv-lite": "^0.7.0", "js-md4": "^0.3.2", "native-duplexpair": "^1.0.0", "sprintf-js": "^1.1.3" } }, "sha512-pk1Q16Yl62iocuQB+RWbg6rFUFkIyzqOFQ6NfysCltRvQqKwfurgj8v/f2X+CKvDhSL4IJ0cCOfCHDg9PWEEYA=="], + "tar-stream": ["tar-stream@3.2.0", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg=="], "teex": ["teex@1.0.1", "", { "dependencies": { "streamx": "^2.12.5" } }, "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg=="], @@ -4711,7 +4870,7 @@ "terracotta": ["terracotta@1.1.0", "", { "dependencies": { "solid-use": "^0.9.1" }, "peerDependencies": { "solid-js": "^1.8" } }, "sha512-kfQciWUBUBgYkXu7gh3CK3FAJng/iqZslAaY08C+k1Hdx17aVEpcFFb/WPaysxAfcupNH3y53s/pc53xxZauww=="], - "terser": ["terser@5.46.1", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": { "terser": "bin/terser" } }, "sha512-vzCjQO/rgUuK9sf8VJZvjqiqiHFaZLnOiimmUuOKODxWL8mm/xua7viT7aqX7dgPY60otQjUotzFMmCB4VdmqQ=="], + "terser": ["terser@5.48.0", "", { "dependencies": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, "bin": { "terser": "bin/terser" } }, "sha512-J/9An6vs9Us6wKRriSFXBWdRZapREHqFzdNUKk0pmu804EMR6dr6winwo7e5JDxN4xahxQsuysyYFwlwj4XN/Q=="], "text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="], @@ -4719,7 +4878,7 @@ "thenify-all": ["thenify-all@1.6.0", "", { "dependencies": { "thenify": ">= 3.1.0 < 4" } }, "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA=="], - "thread-stream": ["thread-stream@4.0.0", "", { "dependencies": { "real-require": "^0.2.0" } }, "sha512-4iMVL6HAINXWf1ZKZjIPcz5wYaOdPhtO8ATvZ+Xqp3BTdaqtAwQkNmKORqcIo5YkQqGXq5cwfswDwMqqQNrpJA=="], + "thread-stream": ["thread-stream@4.2.0", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ=="], "thunky": ["thunky@1.1.0", "", {}, "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA=="], @@ -4743,13 +4902,13 @@ "titleize": ["titleize@4.0.0", "", {}, "sha512-ZgUJ1K83rhdu7uh7EHAC2BgY5DzoX8V5rTvoWI4vFysggi6YjLe5gUXABPWAU7VkvGP7P/0YiWq+dcPeYDsf1g=="], - "tmp": ["tmp@0.2.5", "", {}, "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow=="], + "tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="], "tmp-promise": ["tmp-promise@3.0.3", "", { "dependencies": { "tmp": "^0.2.0" } }, "sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ=="], "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], - "toad-cache": ["toad-cache@3.7.0", "", {}, "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw=="], + "toad-cache": ["toad-cache@3.7.1", "", {}, "sha512-5DXWzE4Vz7xNHsv+xQ+MGfJYyC78Aok3tEr0MNwHoRf7vZnga1mQXZ4/Nsodld4VR6Wd+VhfmqnNrsRJyYPfrQ=="], "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], @@ -4817,7 +4976,7 @@ "typed-array-byte-offset": ["typed-array-byte-offset@1.0.4", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "for-each": "^0.3.3", "gopd": "^1.2.0", "has-proto": "^1.2.0", "is-typed-array": "^1.1.15", "reflect.getprototypeof": "^1.0.9" } }, "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ=="], - "typed-array-length": ["typed-array-length@1.0.7", "", { "dependencies": { "call-bind": "^1.0.7", "for-each": "^0.3.3", "gopd": "^1.0.1", "is-typed-array": "^1.1.13", "possible-typed-array-names": "^1.0.0", "reflect.getprototypeof": "^1.0.6" } }, "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg=="], + "typed-array-length": ["typed-array-length@1.0.8", "", { "dependencies": { "call-bind": "^1.0.9", "for-each": "^0.3.5", "gopd": "^1.2.0", "is-typed-array": "^1.1.15", "possible-typed-array-names": "^1.1.0", "reflect.getprototypeof": "^1.0.10" } }, "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g=="], "typesafe-path": ["typesafe-path@0.2.2", "", {}, "sha512-OJabfkAg1WLZSqJAJ0Z6Sdt3utnbzr/jh+NAHoyWHJe8CMSy79Gm085094M9nvTPy22KzTVn5Zq5mbapCI/hPA=="], @@ -4825,7 +4984,7 @@ "typescript-auto-import-cache": ["typescript-auto-import-cache@0.3.6", "", { "dependencies": { "semver": "^7.3.8" } }, "sha512-RpuHXrknHdVdK7wv/8ug3Fr0WNsNi5l5aB8MYYuXhq2UH5lnEB1htJ1smhtD5VeCsGr2p8mUDtd83LCQDFVgjQ=="], - "ufo": ["ufo@1.6.3", "", {}, "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q=="], + "ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="], "uint8array-extras": ["uint8array-extras@1.5.0", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="], @@ -4837,7 +4996,7 @@ "uncrypto": ["uncrypto@0.1.3", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="], - "undici": ["undici@7.25.0", "", {}, "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ=="], + "undici": ["undici@8.3.0", "", {}, "sha512-TkUDgb6tl7KOGZ+7e8E3d2FYgUQgF6z5YypqjWmixVQSQERFcVrVg0ySADm2LVLRh5ljAaHTCR5Fmz3Q34rB7Q=="], "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="], @@ -4851,10 +5010,6 @@ "unifont": ["unifont@0.5.2", "", { "dependencies": { "css-tree": "^3.0.0", "ofetch": "^1.4.1", "ohash": "^2.0.0" } }, "sha512-LzR4WUqzH9ILFvjLAUU7dK3Lnou/qd5kD+IakBtBK4S15/+x2y9VX+DcWQv6s551R6W+vzwgVS6tFg3XggGBgg=="], - "unique-filename": ["unique-filename@4.0.0", "", { "dependencies": { "unique-slug": "^5.0.0" } }, "sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ=="], - - "unique-slug": ["unique-slug@5.0.0", "", { "dependencies": { "imurmurhash": "^0.1.4" } }, "sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg=="], - "unist-util-find-after": ["unist-util-find-after@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ=="], "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="], @@ -4907,9 +5062,9 @@ "utils-merge": ["utils-merge@1.0.1", "", {}, "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="], - "uuid": ["uuid@13.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="], + "uuid": ["uuid@13.0.2", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-vzi9uRZ926x4XV73S/4qQaTwPXM2JBj6/6lI/byHH1jOpCzb0zDbfytgA9LcN/hzb2l7WQSQnxITOVx5un/wGw=="], - "valibot": ["valibot@1.3.1", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-sfdRir/QFM0JaF22hqTroPc5xy4DimuGQVKFrzF1YfGwaS1nJot3Y8VqMdLO2Lg27fMzat2yD3pY5PbAYO39Gg=="], + "valibot": ["valibot@1.4.1", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-klCmFTz2jeDluy9RwX+F884TCiogtdBJ/YaxSx1EOBYXa3NXNWj8kR1jjN8rzluwojJVWWaHJ4r1U5LfICnM3g=="], "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], @@ -4937,7 +5092,7 @@ "vitefu": ["vitefu@1.1.3", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="], - "vitest": ["vitest@4.1.4", "", { "dependencies": { "@vitest/expect": "4.1.4", "@vitest/mocker": "4.1.4", "@vitest/pretty-format": "4.1.4", "@vitest/runner": "4.1.4", "@vitest/snapshot": "4.1.4", "@vitest/spy": "4.1.4", "@vitest/utils": "4.1.4", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.4", "@vitest/browser-preview": "4.1.4", "@vitest/browser-webdriverio": "4.1.4", "@vitest/coverage-istanbul": "4.1.4", "@vitest/coverage-v8": "4.1.4", "@vitest/ui": "4.1.4", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-tFuJqTxKb8AvfyqMfnavXdzfy3h3sWZRWwfluGbkeR7n0HUev+FmNgZ8SDrRBTVrVCjgH5cA21qGbCffMNtWvg=="], + "vitest": ["vitest@4.1.7", "", { "dependencies": { "@vitest/expect": "4.1.7", "@vitest/mocker": "4.1.7", "@vitest/pretty-format": "4.1.7", "@vitest/runner": "4.1.7", "@vitest/snapshot": "4.1.7", "@vitest/spy": "4.1.7", "@vitest/utils": "4.1.7", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.7", "@vitest/browser-preview": "4.1.7", "@vitest/browser-webdriverio": "4.1.7", "@vitest/coverage-istanbul": "4.1.7", "@vitest/coverage-v8": "4.1.7", "@vitest/ui": "4.1.7", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-flYyaFd2CgoCoU+0UKt3pxksgC+S02iTDN0n3LtqaMeXsI9SBcdNujc2k0DeFLzUn/0k538yNjOSdwgCqcrwJA=="], "volar-service-css": ["volar-service-css@0.0.70", "", { "dependencies": { "vscode-css-languageservice": "^6.3.0", "vscode-languageserver-textdocument": "^1.0.11", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-K1qyOvBpE3rzdAv3e4/6Rv5yizrYPy5R/ne3IWCAzLBuMO4qBMV3kSqWzj6KUVe6S0AnN6wxF7cRkiaKfYMYJw=="], @@ -4975,8 +5130,6 @@ "walk-up-path": ["walk-up-path@4.0.0", "", {}, "sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A=="], - "wcwidth": ["wcwidth@1.0.1", "", { "dependencies": { "defaults": "^1.0.3" } }, "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg=="], - "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], "web-streams-polyfill": ["web-streams-polyfill@4.0.0-beta.3", "", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="], @@ -4985,7 +5138,7 @@ "webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], - "webpack-sources": ["webpack-sources@3.4.0", "", {}, "sha512-gHwIe1cgBvvfLeu1Yz/dcFpmHfKDVxxyqI+kzqmuxZED81z2ChxpyqPaWcNqigPywhaEke7AjSGga+kxY55gjQ=="], + "webpack-sources": ["webpack-sources@3.5.0", "", {}, "sha512-HPuy+uuoTCaaoEoI1LQ3JN9+vrPBvEesnnX1jADHy728cHSMlq4wUc4afYqahq2B1mhQVZxCXOkNTnXltr+2vQ=="], "webpack-virtual-modules": ["webpack-virtual-modules@0.5.0", "", {}, "sha512-kyDivFZ7ZM0BVOUteVbDFhlRt7Ah/CSPwJdi8hBpkK7QLumUqdLtVfm/PX/hkcnrvr0i77fO5+TjZ94Pe+C9iw=="], @@ -5005,7 +5158,7 @@ "which-pm-runs": ["which-pm-runs@1.1.0", "", {}, "sha512-n1brCuqClxfFfq/Rb0ICg9giSZqCS+pLtccdag6C2HyufBrh3fBOiy9nb6ggRMvWOVH5GrdJskj5iGTZNxd7SA=="], - "which-typed-array": ["which-typed-array@1.1.20", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg=="], + "which-typed-array": ["which-typed-array@1.1.21", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.9", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-zbRA8cVm6io/d5W8uIe2hblzN76/Wm3v/yiythQvr+dpBWeqhPSWIDNj4zOyHi4zKbMK6DN34Xsr9jPHJERAEw=="], "why-is-node-running": ["why-is-node-running@3.2.2", "", { "bin": { "why-is-node-running": "cli.js" } }, "sha512-NKUzAelcoCXhXL4dJzKIwXeR8iEVqsA0Lq6Vnd0UXvgaKbzVo4ZTHROF2Jidrv+SgxOQ03fMinnNhzZATxOD3A=="], @@ -5023,7 +5176,7 @@ "write-file-atomic": ["write-file-atomic@7.0.1", "", { "dependencies": { "signal-exit": "^4.0.1" } }, "sha512-OTIk8iR8/aCRWBqvxrzxR0hgxWpnYBblY1S5hDWBQfk/VFmJwzmJgQFN3WsoUKHISv2eAwe+PpbUzyL1CKTLXg=="], - "ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="], + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], "wsl-utils": ["wsl-utils@0.3.1", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="], @@ -5031,7 +5184,7 @@ "xml-naming": ["xml-naming@0.1.0", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="], - "xml2js": ["xml2js@0.6.2", "", { "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" } }, "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA=="], + "xml2js": ["xml2js@0.5.0", "", { "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" } }, "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA=="], "xmlbuilder": ["xmlbuilder@11.0.1", "", {}, "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA=="], @@ -5043,7 +5196,7 @@ "yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], - "yaml": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="], + "yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="], "yaml-language-server": ["yaml-language-server@1.20.0", "", { "dependencies": { "@vscode/l10n": "^0.0.18", "ajv": "^8.17.1", "ajv-draft-04": "^1.0.0", "prettier": "^3.5.0", "request-light": "^0.5.7", "vscode-json-languageservice": "4.1.8", "vscode-languageserver": "^9.0.0", "vscode-languageserver-textdocument": "^1.0.1", "vscode-languageserver-types": "^3.16.0", "vscode-uri": "^3.0.2", "yaml": "2.7.1" }, "bin": { "yaml-language-server": "bin/yaml-language-server" } }, "sha512-qhjK/bzSRZ6HtTvgeFvjNPJGWdZ0+x5NREV/9XZWFjIGezew2b4r5JPy66IfOhd5OA7KeFwk1JfmEbnTvev0cA=="], @@ -5071,7 +5224,7 @@ "zod-openapi": ["zod-openapi@5.4.6", "", { "peerDependencies": { "zod": "^3.25.74 || ^4.0.0" } }, "sha512-P2jsOOBAq/6hCwUsMCjUATZ8szkMsV5VAwZENfyxp2Hc/XPJQpVwAgevWZc65xZauCwWB9LAn7zYeiCJFAEL+A=="], - "zod-to-json-schema": ["zod-to-json-schema@3.24.5", "", { "peerDependencies": { "zod": "^3.24.1" } }, "sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g=="], + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], "zod-to-ts": ["zod-to-ts@1.2.0", "", { "peerDependencies": { "typescript": "^4.9.4 || ^5.0.2", "zod": "^3" } }, "sha512-x30XE43V+InwGpvTySRNz9kB7qFU8DlyEy7BsSTCHPH1R0QasMmHWZDCzYm6bVXtj/9NNJAZF3jW8rzFvH5OFA=="], @@ -5089,7 +5242,7 @@ "@actions/github/undici": ["undici@5.29.0", "", { "dependencies": { "@fastify/busboy": "^2.0.0" } }, "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg=="], - "@actions/http-client/undici": ["undici@6.25.0", "", {}, "sha512-ZgpWDC5gmNiuY9CnLVXEH8rl50xhRCuLNA97fAUnKi8RRuV4E6KG31pDTsLVUKnohJE0I3XDrTeEydAXRw47xg=="], + "@actions/http-client/undici": ["undici@6.26.0", "", {}, "sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A=="], "@ai-sdk/alibaba/@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@2.0.41", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-kNAGINk71AlOXx10Dq/PXw4t/9XjdK8uxfpVElRwtSFMdeSiLVt58p9TPx4/FJD+hxZuVhvxYj9r42osxWq79g=="], @@ -5111,15 +5264,31 @@ "@ai-sdk/cohere/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="], + "@ai-sdk/deepgram/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="], + + "@ai-sdk/deepgram/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="], + "@ai-sdk/deepinfra/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="], - "@ai-sdk/fireworks/@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@2.0.41", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-kNAGINk71AlOXx10Dq/PXw4t/9XjdK8uxfpVElRwtSFMdeSiLVt58p9TPx4/FJD+hxZuVhvxYj9r42osxWq79g=="], + "@ai-sdk/deepseek/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="], + + "@ai-sdk/deepseek/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="], + + "@ai-sdk/elevenlabs/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="], + + "@ai-sdk/elevenlabs/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="], + + "@ai-sdk/fireworks/@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@2.0.48", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-z9MC6M4Oh/yUY/F/eszOtO8wc2nMz99XmZQKd2gWTtyIfe716xTfrKe3aYZKg20NZDtyjqPPKPSR+wqz7q1T7Q=="], + + "@ai-sdk/fireworks/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="], + + "@ai-sdk/fireworks/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="], "@ai-sdk/google/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="], "@ai-sdk/google/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="], - "@ai-sdk/google-vertex/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.78", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-0OY12G20cUt6iU6htpEA1491Oz++NVxZxlmWGX4B7rSbeZ5pnDmOu6YtW9BKzdZlNx5Gn23i6WMxyZFoMKNcgA=="], + "@ai-sdk/google-vertex/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.77", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ML8C2M1YvPA1ulEx4TiyF0k1xvC2ikEiPBIC1PPQ0a5xELUGrO2lAaEzsTEoJ+eCeDd8PSBuFJjs+r+9yIwQXA=="], "@ai-sdk/google-vertex/@ai-sdk/openai-compatible": ["@ai-sdk/openai-compatible@2.0.47", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Enm5UlL0zUCrW3792opk5h7hRWxZOZzDe6eQYVFqX9LUOGGCe1h8MZWAGim765nwzgnjlpeYOsuzZmLtRsTPlg=="], @@ -5155,67 +5324,63 @@ "@astrojs/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], - "@astrojs/sitemap/zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="], + "@astrojs/sitemap/zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], "@astrojs/solid-js/vite": ["vite@6.4.2", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "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-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ=="], - "@astrojs/solid-js/vite-plugin-solid": ["vite-plugin-solid@2.11.12", "", { "dependencies": { "@babel/core": "^7.23.3", "@types/babel__core": "^7.20.4", "babel-preset-solid": "^1.8.4", "merge-anything": "^5.1.7", "solid-refresh": "^0.6.3", "vitefu": "^1.0.4" }, "peerDependencies": { "@testing-library/jest-dom": "^5.16.6 || ^5.17.0 || ^6.*", "solid-js": "^1.7.2", "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@testing-library/jest-dom"] }, "sha512-FgjPcx2OwX9h6f28jli7A4bG7PP3te8uyakE5iqsmpq3Jqi1TWLgSroC9N6cMfGRU2zXsl4Q6ISvTr2VL0QHpA=="], + "@aws-crypto/crc32/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-crypto/crc32/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-crypto/crc32c/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-crypto/crc32c/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], - - "@aws-crypto/sha1-browser/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-crypto/sha1-browser/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-crypto/sha1-browser/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], - "@aws-crypto/sha256-browser/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-crypto/sha256-browser/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-crypto/sha256-browser/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], - "@aws-crypto/sha256-js/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-crypto/sha256-js/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-crypto/util/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-crypto/util/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-crypto/util/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/client-athena/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + + "@aws-sdk/client-cognito-identity/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.30", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.25", "@aws-sdk/credential-provider-http": "^3.972.27", "@aws-sdk/credential-provider-ini": "^3.972.29", "@aws-sdk/credential-provider-process": "^3.972.25", "@aws-sdk/credential-provider-sso": "^3.972.29", "@aws-sdk/credential-provider-web-identity": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-FMnAnWxc8PG+ZrZ2OBKzY4luCUJhe9CG0B9YwYr4pzrYGLXBS2rl+UoUvjGbAwiptxRL6hyA3lFn03Bv1TLqTw=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.46", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.41", "@aws-sdk/credential-provider-http": "^3.972.43", "@aws-sdk/credential-provider-ini": "^3.972.45", "@aws-sdk/credential-provider-process": "^3.972.41", "@aws-sdk/credential-provider-sso": "^3.972.45", "@aws-sdk/credential-provider-web-identity": "^3.972.45", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/credential-provider-imds": "^4.3.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-cS4w0jzDRb1jOlkiJS3y80OxddHzkky/MN9k3NYs5jganNKVLjF0lpvjlwS118oGMr3cdAfOlVdo8gLurTSE7w=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.16", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-DcDXAl32I/YZnJ9LyX/XpRXOtoTYIwgmYxoNMGkyvtomdjPpkXPGhz93VJyzKFFNffz/SZwEkoAuWOkeOzo90Q=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.15", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-4Org8yUew+Y1+buTcH5A39unAdkVRnQxcOp3XexvFAVctbtznDytk3UKbkXq8FYWEVdz1ycxnAqHaKHePyGQEg=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.17", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-T/FpIr0OcR1kad/u5ZTDE2ziFG7QM6pq1MN8atHBmyyOJgqWjGez9TQ0W2WCixS7EE9fsUQKWn70l5M+e+O/qg=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.45", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-sWd7bGH+thMsNGYdqPdLuH7SDEkpplWCDKSCWhjkMPXwz3o/9BK3ZNrd5JGUB8y+cPbs3rXIe3Ah7iSlKXj5FQ=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.19", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-ol9yhY2nzPTrQoKX9WZ8cps2JABcDt0Dlhr59FRYYW/2S5h07PFrhfZZzD8sXZ8XpYfObTIJ+evmbcz41m1SJQ=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-sdk/client-cognito-identity/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.993.0", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-j6vioBeRZ4eHX4SWGvGPpwGg/xSOcK7f1GL0VM+rdf3ZFTIsUEhCFmD78B+5r2PgztcECSzEfvHQX01k8dPQPw=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.16", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-h4VTGl6lxJkM/odeRPzXB5YZbkxVr5FnJ2Bwv78+IY9Ah7QsXSBhefvvz1CQDoQNzOLYsNMQ3PhMQM7i6tpoPQ=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.31", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-hYTWRlhOnhs2tYCYgNK30jaQKyl4FvXQl0AK9tKRZq8sunS9ygi+USYiG6LCb7DuqT0Gl3jONP9jtb4D4NYhHw=="], "@aws-sdk/client-cognito-identity/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/client-lambda/@aws-sdk/core": ["@aws-sdk/core@3.974.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.8", "@aws-sdk/xml-builder": "^3.972.24", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.2", "@smithy/signature-v4": "^5.4.2", "@smithy/types": "^4.14.1", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-QpnINq5FZH6EOaDEkmHdT7eUunbvD27pDNQypaWjFyYz7Zl1q3UCMQErBZxpmfGfI7MvI2TlK8KTkgNpv8b1ug=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.42", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.37", "@aws-sdk/credential-provider-http": "^3.972.39", "@aws-sdk/credential-provider-ini": "^3.972.41", "@aws-sdk/credential-provider-process": "^3.972.37", "@aws-sdk/credential-provider-sso": "^3.972.41", "@aws-sdk/credential-provider-web-identity": "^3.972.41", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/credential-provider-imds": "^4.3.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-D4oon2zbqqsWOJUM99Gm3/ZyJ0IJvTXVN3PyloGb3kQEyI36fjCZheZj422lAgTWWd6TSHgiImLt3RIaLdv3dQ=="], - - "@aws-sdk/client-lambda/@aws-sdk/types": ["@aws-sdk/types@3.973.8", "", { "dependencies": { "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-gjlAdtHMbtR9X5iIhVUvbVcy55KnznpC6bkDUWW9z915bi0ckdUr5cjf16Kp6xq0bP5HBD2xzgbL9F9Quv5vUw=="], + "@aws-sdk/client-firehose/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/client-lambda/@smithy/core": ["@smithy/core@3.24.3", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-Ep/7tPamGY8mgESE3LyLKtxJyy6U52WWAqr/3wial47Sj4u3PiIF73AOGI27UyLy9duTkhZbgzodOfLV4TduZg=="], + "@aws-sdk/client-lambda/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/client-lambda/@smithy/fetch-http-handler": ["@smithy/fetch-http-handler@5.4.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-F+DRf8IJazRJgYog2A/yJK7eYVc0rqTlRzO+5ZxjJd4WkZoKz0IJRncf7G6t1pdVT3kryJcwuTFhN1c5m6N47A=="], + "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.46", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.41", "@aws-sdk/credential-provider-http": "^3.972.43", "@aws-sdk/credential-provider-ini": "^3.972.45", "@aws-sdk/credential-provider-process": "^3.972.41", "@aws-sdk/credential-provider-sso": "^3.972.45", "@aws-sdk/credential-provider-web-identity": "^3.972.45", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/credential-provider-imds": "^4.3.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-cS4w0jzDRb1jOlkiJS3y80OxddHzkky/MN9k3NYs5jganNKVLjF0lpvjlwS118oGMr3cdAfOlVdo8gLurTSE7w=="], - "@aws-sdk/client-lambda/@smithy/node-http-handler": ["@smithy/node-http-handler@4.7.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA=="], + "@aws-sdk/client-lambda/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/client-lambda/@smithy/types": ["@smithy/types@4.14.1", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg=="], + "@aws-sdk/client-s3/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], "@aws-sdk/client-sso/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], @@ -5241,31 +5406,33 @@ "@aws-sdk/client-sts/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.782.0", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "3.782.0", "@aws-sdk/types": "3.775.0", "@smithy/node-config-provider": "^4.0.2", "@smithy/types": "^4.2.0", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-dMFkUBgh2Bxuw8fYZQoH/u3H4afQ12VSkzEi//qFiDTwbKYq+u+RYjc8GLDM6JSK1BShMu5AVR7HD4ap1TYUnA=="], + "@aws-sdk/client-sts/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + "@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-provider-env/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-env/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-env/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-env/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-provider-http/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-http/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-http/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-http/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-provider-ini/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="], - "@aws-sdk/credential-provider-ini/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-provider-login/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-login/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="], + "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="], - "@aws-sdk/credential-provider-login/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-login/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.932.0", "", { "dependencies": { "@aws-sdk/core": "3.932.0", "@aws-sdk/types": "3.930.0", "@smithy/property-provider": "^4.2.5", "@smithy/types": "^4.9.0", "tslib": "^2.6.2" } }, "sha512-ozge/c7NdHUDyHqro6+P5oHt8wfKSUBN+olttiVfBe9Mw3wBMpPa3gQ0pZnG+gwBkKskBuip2bMR16tqYvUSEA=="], @@ -5279,59 +5446,59 @@ "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.933.0", "", { "dependencies": { "@aws-sdk/core": "3.932.0", "@aws-sdk/nested-clients": "3.933.0", "@aws-sdk/types": "3.930.0", "@smithy/property-provider": "^4.2.5", "@smithy/shared-ini-file-loader": "^4.4.0", "@smithy/types": "^4.9.0", "tslib": "^2.6.2" } }, "sha512-c7Eccw2lhFx2/+qJn3g+uIDWRuWi2A6Sz3PVvckFUEzPsP0dPUo19hlvtarwP5GzrsXn0yEPRVhpewsIaSCGaQ=="], - "@aws-sdk/credential-provider-process/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-process/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-process/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-process/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-provider-web-identity/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="], - "@aws-sdk/credential-provider-web-identity/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], - "@aws-sdk/credential-providers/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/credential-providers/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-providers/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.30", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.25", "@aws-sdk/credential-provider-http": "^3.972.27", "@aws-sdk/credential-provider-ini": "^3.972.29", "@aws-sdk/credential-provider-process": "^3.972.25", "@aws-sdk/credential-provider-sso": "^3.972.29", "@aws-sdk/credential-provider-web-identity": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/credential-provider-imds": "^4.2.13", "@smithy/property-provider": "^4.2.13", "@smithy/shared-ini-file-loader": "^4.4.8", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-FMnAnWxc8PG+ZrZ2OBKzY4luCUJhe9CG0B9YwYr4pzrYGLXBS2rl+UoUvjGbAwiptxRL6hyA3lFn03Bv1TLqTw=="], + "@aws-sdk/credential-providers/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.46", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.41", "@aws-sdk/credential-provider-http": "^3.972.43", "@aws-sdk/credential-provider-ini": "^3.972.45", "@aws-sdk/credential-provider-process": "^3.972.41", "@aws-sdk/credential-provider-sso": "^3.972.45", "@aws-sdk/credential-provider-web-identity": "^3.972.45", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/credential-provider-imds": "^4.3.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-cS4w0jzDRb1jOlkiJS3y80OxddHzkky/MN9k3NYs5jganNKVLjF0lpvjlwS118oGMr3cdAfOlVdo8gLurTSE7w=="], - "@aws-sdk/credential-providers/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/credential-providers/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-sdk/middleware-flexible-checksums/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], "@aws-sdk/middleware-sdk-s3/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/nested-clients/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/nested-clients/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], + "@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.16", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-DcDXAl32I/YZnJ9LyX/XpRXOtoTYIwgmYxoNMGkyvtomdjPpkXPGhz93VJyzKFFNffz/SZwEkoAuWOkeOzo90Q=="], - "@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], + "@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.15", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-4Org8yUew+Y1+buTcH5A39unAdkVRnQxcOp3XexvFAVctbtznDytk3UKbkXq8FYWEVdz1ycxnAqHaKHePyGQEg=="], - "@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], + "@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.17", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-T/FpIr0OcR1kad/u5ZTDE2ziFG7QM6pq1MN8atHBmyyOJgqWjGez9TQ0W2WCixS7EE9fsUQKWn70l5M+e+O/qg=="], - "@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], + "@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.45", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-sWd7bGH+thMsNGYdqPdLuH7SDEkpplWCDKSCWhjkMPXwz3o/9BK3ZNrd5JGUB8y+cPbs3rXIe3Ah7iSlKXj5FQ=="], - "@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], + "@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.19", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-ol9yhY2nzPTrQoKX9WZ8cps2JABcDt0Dlhr59FRYYW/2S5h07PFrhfZZzD8sXZ8XpYfObTIJ+evmbcz41m1SJQ=="], - "@aws-sdk/nested-clients/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/nested-clients/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.993.0", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-j6vioBeRZ4eHX4SWGvGPpwGg/xSOcK7f1GL0VM+rdf3ZFTIsUEhCFmD78B+5r2PgztcECSzEfvHQX01k8dPQPw=="], - "@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], + "@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.16", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-h4VTGl6lxJkM/odeRPzXB5YZbkxVr5FnJ2Bwv78+IY9Ah7QsXSBhefvvz1CQDoQNzOLYsNMQ3PhMQM7i6tpoPQ=="], - "@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], + "@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.31", "", { "dependencies": { "@aws-sdk/core": "^3.974.15", "tslib": "^2.6.2" } }, "sha512-hYTWRlhOnhs2tYCYgNK30jaQKyl4FvXQl0AK9tKRZq8sunS9ygi+USYiG6LCb7DuqT0Gl3jONP9jtb4D4NYhHw=="], "@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/token-providers/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], + "@aws-sdk/token-providers/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/token-providers/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.996.19", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.27", "@aws-sdk/middleware-host-header": "^3.972.9", "@aws-sdk/middleware-logger": "^3.972.9", "@aws-sdk/middleware-recursion-detection": "^3.972.10", "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/region-config-resolver": "^3.972.11", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@aws-sdk/util-user-agent-browser": "^3.972.9", "@aws-sdk/util-user-agent-node": "^3.973.15", "@smithy/config-resolver": "^4.4.14", "@smithy/core": "^3.23.14", "@smithy/fetch-http-handler": "^5.3.16", "@smithy/hash-node": "^4.2.13", "@smithy/invalid-dependency": "^4.2.13", "@smithy/middleware-content-length": "^4.2.13", "@smithy/middleware-endpoint": "^4.4.29", "@smithy/middleware-retry": "^4.5.0", "@smithy/middleware-serde": "^4.2.17", "@smithy/middleware-stack": "^4.2.13", "@smithy/node-config-provider": "^4.3.13", "@smithy/node-http-handler": "^4.5.2", "@smithy/protocol-http": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-base64": "^4.3.2", "@smithy/util-body-length-browser": "^4.2.2", "@smithy/util-body-length-node": "^4.2.3", "@smithy/util-defaults-mode-browser": "^4.3.45", "@smithy/util-defaults-mode-node": "^4.2.49", "@smithy/util-endpoints": "^3.3.4", "@smithy/util-middleware": "^4.2.13", "@smithy/util-retry": "^4.3.0", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-uFkmCDXvmQYLanlYdOFS0+MQWkrj9wPMt/ZCc/0J0fjPim6F5jBVBmEomvGY/j77ILW6GTPwN22Jc174Mhkw6Q=="], + "@aws-sdk/token-providers/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.13", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.15", "@aws-sdk/signature-v4-multi-region": "^3.996.30", "@aws-sdk/types": "^3.973.9", "@smithy/core": "^3.24.5", "@smithy/fetch-http-handler": "^5.4.5", "@smithy/node-http-handler": "^4.7.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg=="], - "@aws-sdk/token-providers/@aws-sdk/types": ["@aws-sdk/types@3.973.7", "", { "dependencies": { "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-reXRwoJ6CfChoqAsBszUYajAF8Z2LRE+CRcKocvFSMpIiLOtYU3aJ9trmn6VVPAzbbY5LXF+FfmUslbXk1SYFg=="], + "@aws-sdk/token-providers/@aws-sdk/types": ["@aws-sdk/types@3.973.9", "", { "dependencies": { "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg=="], "@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.2.5", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ=="], @@ -5341,13 +5508,7 @@ "@azure/core-http/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], - "@azure/core-http/xml2js": ["xml2js@0.5.0", "", { "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" } }, "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA=="], - - "@azure/core-xml/fast-xml-parser": ["fast-xml-parser@5.5.12", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-nUR0q8PPfoA/svPM43Gup7vLOZWppaNrYgGmrVqrAVJa7cOH4hMG6FX9M4mQ8dZA1/ObGZHzES7Ed88hxEBSJg=="], - - "@azure/identity/open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], - - "@azure/msal-node/uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="], + "@azure/core-xml/fast-xml-parser": ["fast-xml-parser@5.8.0", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.2.0", "path-expression-matcher": "^1.5.0", "strnum": "^2.3.0", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-6bIM7fsJxeo3uXv7OncQYsBAMPJ7V16Slahl/6M98C/i2q+vB1+4a0MtrvYwDFEUrwDSbAmeLDRXsOBwrL7yAg=="], "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -5361,16 +5522,14 @@ "@cloudflare/kv-asset-handler/mime": ["mime@3.0.0", "", { "bin": { "mime": "cli.js" } }, "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A=="], + "@cloudflare/vite-plugin/ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="], + "@cspotcode/source-map-support/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], - "@develar/schema-utils/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], + "@develar/schema-utils/ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], "@dot/log/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], - "@effect/platform-node/undici": ["undici@8.1.0", "", {}, "sha512-E9MkTS4xXLnRPYqxH2e6Hr2/49e7WFDKczKcCaFH4VaZs2iNvHMqeIkyUAD9vM8kujy9TjVrRlQ5KkdEJxB2pw=="], - - "@effect/platform-node-shared/ws": ["ws@8.20.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="], - "@electron/asar/commander": ["commander@5.1.0", "", {}, "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg=="], "@electron/asar/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], @@ -5389,28 +5548,22 @@ "@electron/osx-sign/isbinaryfile": ["isbinaryfile@4.0.10", "", {}, "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw=="], - "@electron/rebuild/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - - "@electron/rebuild/node-gyp": ["node-gyp@11.5.0", "", { "dependencies": { "env-paths": "^2.2.0", "exponential-backoff": "^3.1.1", "graceful-fs": "^4.2.6", "make-fetch-happen": "^14.0.3", "nopt": "^8.0.0", "proc-log": "^5.0.0", "semver": "^7.3.5", "tar": "^7.4.3", "tinyglobby": "^0.2.12", "which": "^5.0.0" }, "bin": { "node-gyp": "bin/node-gyp.js" } }, "sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ=="], - - "@electron/rebuild/yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="], - - "@electron/universal/fs-extra": ["fs-extra@11.3.4", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA=="], + "@electron/universal/fs-extra": ["fs-extra@11.3.5", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg=="], "@electron/universal/minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="], - "@electron/windows-sign/fs-extra": ["fs-extra@11.3.4", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA=="], + "@electron/windows-sign/fs-extra": ["fs-extra@11.3.5", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg=="], "@expressive-code/plugin-shiki/shiki": ["shiki@3.23.0", "", { "dependencies": { "@shikijs/core": "3.23.0", "@shikijs/engine-javascript": "3.23.0", "@shikijs/engine-oniguruma": "3.23.0", "@shikijs/langs": "3.23.0", "@shikijs/themes": "3.23.0", "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-55Dj73uq9ZXL5zyeRPzHQsK7Nbyt6Y10k5s7OjuFZGMhpp4r/rsLBH0o/0fstIzX1Lep9VxefWljK/SKCzygIA=="], - "@fastify/proxy-addr/ipaddr.js": ["ipaddr.js@2.3.0", "", {}, "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg=="], - - "@gitlab/opencode-gitlab-auth/open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], + "@fastify/proxy-addr/ipaddr.js": ["ipaddr.js@2.4.0", "", {}, "sha512-9VGk3HGanVE6JoZXHiCpnGy5X0jYDnN4EA4lntFPj+1vIWlFhIylq2CrrCOJH9EAhc5CYhq18F2Av2tgoAPsYQ=="], "@hey-api/openapi-ts/open": ["open@11.0.0", "", { "dependencies": { "default-browser": "^5.4.0", "define-lazy-prop": "^3.0.0", "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", "powershell-utils": "^0.1.0", "wsl-utils": "^0.3.0" } }, "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw=="], "@hey-api/openapi-ts/semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="], + "@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], + "@jsx-email/cli/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "@jsx-email/cli/esbuild": ["esbuild@0.19.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.19.12", "@esbuild/android-arm": "0.19.12", "@esbuild/android-arm64": "0.19.12", "@esbuild/android-x64": "0.19.12", "@esbuild/darwin-arm64": "0.19.12", "@esbuild/darwin-x64": "0.19.12", "@esbuild/freebsd-arm64": "0.19.12", "@esbuild/freebsd-x64": "0.19.12", "@esbuild/linux-arm": "0.19.12", "@esbuild/linux-arm64": "0.19.12", "@esbuild/linux-ia32": "0.19.12", "@esbuild/linux-loong64": "0.19.12", "@esbuild/linux-mips64el": "0.19.12", "@esbuild/linux-ppc64": "0.19.12", "@esbuild/linux-riscv64": "0.19.12", "@esbuild/linux-s390x": "0.19.12", "@esbuild/linux-x64": "0.19.12", "@esbuild/netbsd-x64": "0.19.12", "@esbuild/openbsd-x64": "0.19.12", "@esbuild/sunos-x64": "0.19.12", "@esbuild/win32-arm64": "0.19.12", "@esbuild/win32-ia32": "0.19.12", "@esbuild/win32-x64": "0.19.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg=="], @@ -5423,33 +5576,33 @@ "@malept/flatpak-bundler/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="], + "@mdx-js/mdx/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "@mdx-js/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], "@modelcontextprotocol/sdk/express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="], - "@modelcontextprotocol/sdk/hono": ["hono@4.12.12", "", {}, "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q=="], + "@modelcontextprotocol/sdk/hono": ["hono@4.12.23", "", {}, "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA=="], - "@modelcontextprotocol/sdk/jose": ["jose@6.2.2", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="], + "@modelcontextprotocol/sdk/jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="], "@modelcontextprotocol/sdk/raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], - "@modelcontextprotocol/sdk/zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], - "@npmcli/query/postcss-selector-parser": ["postcss-selector-parser@7.1.1", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg=="], - "@octokit/auth-app/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/auth-app/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/auth-app/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], - "@octokit/auth-oauth-app/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/auth-oauth-app/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/auth-oauth-app/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], - "@octokit/auth-oauth-device/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/auth-oauth-device/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/auth-oauth-device/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], - "@octokit/auth-oauth-user/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/auth-oauth-user/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/auth-oauth-user/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], @@ -5463,11 +5616,11 @@ "@octokit/endpoint/universal-user-agent": ["universal-user-agent@6.0.1", "", {}, "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ=="], - "@octokit/graphql/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/graphql/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/graphql/@octokit/types": ["@octokit/types@15.0.2", "", { "dependencies": { "@octokit/openapi-types": "^26.0.0" } }, "sha512-rR+5VRjhYSer7sC51krfCctQhVTmjyUMAaShfPB8mscVa8tSoLyon3coxQmXu0ahJoLVWl8dSGD/3OGZlFV44Q=="], - "@octokit/oauth-methods/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/oauth-methods/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/oauth-methods/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], @@ -5523,6 +5676,10 @@ "@oslojs/jwt/@oslojs/encoding": ["@oslojs/encoding@0.4.1", "", {}, "sha512-hkjo6MuIK/kQR5CrGNdAPZhS01ZCXuWDRJ187zh6qqF2+yMHZpD9fAYpX8q2bOO6Ryhl3XpCT6kUX76N8hhm4Q=="], + "@oxc-resolver/binding-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="], + + "@oxc-resolver/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], + "@pierre/diffs/@shikijs/transformers": ["@shikijs/transformers@3.20.0", "", { "dependencies": { "@shikijs/core": "3.20.0", "@shikijs/types": "3.20.0" } }, "sha512-PrHHMRr3Q5W1qB/42kJW6laqFyWdhrPF2hNR9qjOm1xcSiAO3hAHo7HaVyHE6pMyevmy3i51O8kuGGXC78uK3g=="], "@pierre/diffs/diff": ["diff@8.0.3", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="], @@ -5533,6 +5690,8 @@ "@protobuf-ts/plugin/typescript": ["typescript@3.9.10", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q=="], + "@rollup/pluginutils/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "@rollup/pluginutils/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], "@sentry/bundler-plugin-core/glob": ["glob@9.3.5", "", { "dependencies": { "fs.realpath": "^1.0.0", "minimatch": "^8.0.2", "minipass": "^4.2.4", "path-scurry": "^1.6.1" } }, "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q=="], @@ -5561,7 +5720,7 @@ "@slack/socket-mode/@types/ws": ["@types/ws@7.4.7", "", { "dependencies": { "@types/node": "*" } }, "sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww=="], - "@slack/socket-mode/ws": ["ws@7.5.10", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ=="], + "@slack/socket-mode/ws": ["ws@7.5.11", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA=="], "@slack/web-api/@slack/logger": ["@slack/logger@3.0.0", "", { "dependencies": { "@types/node": ">=12.0.0" } }, "sha512-DTuBFbqu4gGfajREEMrkq5jBhcnskinhr4+AnfJEk48zhVeEv3XnUKGIX98B74kxhYsIMfApGGySTn7V3b5yBA=="], @@ -5571,41 +5730,19 @@ "@slack/web-api/p-queue": ["p-queue@6.6.2", "", { "dependencies": { "eventemitter3": "^4.0.4", "p-timeout": "^3.2.0" } }, "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ=="], - "@smithy/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@smithy/eventstream-serde-universal/@smithy/eventstream-codec": ["@smithy/eventstream-codec@4.2.13", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.14.0", "@smithy/util-hex-encoding": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-vYahwBAtRaAcFbOmE9aLr12z7RiHYDSLcnogSdxfm7kKfsNa3wH+NU5r7vTeB5rKvLsWyPjVX8iH94brP7umiQ=="], - - "@smithy/hash-node/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@smithy/hash-stream-node/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@smithy/md5-js/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@smithy/signature-v4/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@smithy/util-base64/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@smithy/util-stream/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@solidjs/start/path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], "@solidjs/start/shiki": ["shiki@1.29.2", "", { "dependencies": { "@shikijs/core": "1.29.2", "@shikijs/engine-javascript": "1.29.2", "@shikijs/engine-oniguruma": "1.29.2", "@shikijs/langs": "1.29.2", "@shikijs/themes": "1.29.2", "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4" } }, "sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg=="], "@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-plugin-solid": ["vite-plugin-solid@2.11.12", "", { "dependencies": { "@babel/core": "^7.23.3", "@types/babel__core": "^7.20.4", "babel-preset-solid": "^1.8.4", "merge-anything": "^5.1.7", "solid-refresh": "^0.6.3", "vitefu": "^1.0.4" }, "peerDependencies": { "@testing-library/jest-dom": "^5.16.6 || ^5.17.0 || ^6.*", "solid-js": "^1.7.2", "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@testing-library/jest-dom"] }, "sha512-FgjPcx2OwX9h6f28jli7A4bG7PP3te8uyakE5iqsmpq3Jqi1TWLgSroC9N6cMfGRU2zXsl4Q6ISvTr2VL0QHpA=="], - - "@standard-community/standard-json/effect": ["effect@4.0.0-beta.48", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.6.0", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.9", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^13.0.0", "yaml": "^2.8.3" } }, "sha512-MMAM/ZabuNdNmgXiin+BAanQXK7qM8mlt7nfXDoJ/Gn9V8i89JlCq+2N0AiWmqFLXjGLA0u3FjiOjSOYQk5uMw=="], - - "@standard-community/standard-openapi/effect": ["effect@4.0.0-beta.48", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.6.0", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.9", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^13.0.0", "yaml": "^2.8.3" } }, "sha512-MMAM/ZabuNdNmgXiin+BAanQXK7qM8mlt7nfXDoJ/Gn9V8i89JlCq+2N0AiWmqFLXjGLA0u3FjiOjSOYQk5uMw=="], - "@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-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.9.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="], + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="], - "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.9.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="], + "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="], @@ -5625,13 +5762,15 @@ "@testing-library/dom/dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="], + "@types/estree-jsx/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "@types/plist/xmlbuilder": ["xmlbuilder@15.1.1", "", {}, "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg=="], "@vitest/expect/@vitest/utils": ["@vitest/utils@3.2.4", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="], "@vitest/expect/tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], - "@vitest/mocker/@vitest/spy": ["@vitest/spy@4.1.4", "", {}, "sha512-XxNdAsKW7C+FLydqFJLb5KhJtl3PGCMmYwFRfhvIgxJvLSXhhVI1zM8f1qD3Zg7RCjTSzDVyct6sghs9UEgBEQ=="], + "@vitest/mocker/@vitest/spy": ["@vitest/spy@4.1.7", "", {}, "sha512-kbkI5LMWakyuTIvs6fUJ5qdIVb1XVKsYJAT4OJ938cHMROYMSfmoQdZy0aaAnjbbc8F61vkoTqz/Az+/HiIu5Q=="], "@vscode/emmet-helper/jsonc-parser": ["jsonc-parser@2.3.1", "", {}, "sha512-H8jvkz1O50L3dMZCsLqiuB2tA7muqbSg1AtGEkN0leAqGjsUzDJir3Zwr02BhqdcITPg3ei3mZ+HjMocAknhhg=="], @@ -5639,19 +5778,11 @@ "accepts/negotiator": ["negotiator@0.6.3", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="], - "ai-gateway-provider/@ai-sdk/amazon-bedrock": ["@ai-sdk/amazon-bedrock@4.0.93", "", { "dependencies": { "@ai-sdk/anthropic": "3.0.69", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23", "@smithy/eventstream-codec": "^4.0.1", "@smithy/util-utf8": "^4.0.0", "aws4fetch": "^1.0.20" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-hcXDU8QDwpAzLVTuY932TQVlIij9+iaVTxc5mPGY6yb//JMAAC5hMVhg93IrxlrxWLvMgjezNgoZGwquR+SGnw=="], - - "ai-gateway-provider/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.69", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-LshR7X3pFugY0o41G2VKTmg1XoGpSl7uoYWfzk6zjVZLhCfeFiwgpOga+eTV4XY1VVpZwKVqRnkDbIL7K2eH5g=="], + "ai-gateway-provider/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.78", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.27" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-0OY12G20cUt6iU6htpEA1491Oz++NVxZxlmWGX4B7rSbeZ5pnDmOu6YtW9BKzdZlNx5Gn23i6WMxyZFoMKNcgA=="], - "ai-gateway-provider/@ai-sdk/google": ["@ai-sdk/google@3.0.53", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-uz8tIlkDgQJG9Js2Wh9JHzd4kI9+hYJqf9XXJLx60vyN5mRIqhr49iwR5zGP5Gl8odp2PeR3Gh2k+5bh3Z1HHw=="], + "ai-gateway-provider/@ai-sdk/openai": ["@ai-sdk/openai@3.0.53", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-Wld+Rbc05KaUn08uBt06eEuwcgalcIFtIl32Yp+GxuZXUQwOb6YeAuq+C6da4ch6BurFoqEaLemJVwjBb7x+PQ=="], - "ai-gateway-provider/@ai-sdk/google-vertex": ["@ai-sdk/google-vertex@4.0.95", "", { "dependencies": { "@ai-sdk/anthropic": "3.0.64", "@ai-sdk/google": "3.0.53", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21", "google-auth-library": "^10.5.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-xL44fHlTtDM7RLkMTgyqMfkfthA38JS91bbMaHItObIhte1PAIY936ZV1PLl/Z9A/oBAXjHWbXo5xDoHzB7LEg=="], - - "ai-gateway-provider/@ai-sdk/xai": ["@ai-sdk/xai@3.0.75", "", { "dependencies": { "@ai-sdk/openai-compatible": "2.0.37", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-V8UKK4fNpI9cnrtsZBvUp9O9J6Y9fTKBRoSLyEaNGPirACewixmLDbXsSgAeownPVWiWpK34bFysd+XouI5Ywg=="], - - "ai-gateway-provider/@openrouter/ai-sdk-provider": ["@openrouter/ai-sdk-provider@2.5.1", "", { "peerDependencies": { "ai": "^6.0.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-r1fJL1Cb3gQDa2MpWH/sfx1BsEW0uzlRriJM6eihaKqbtKDmZoBisF32VcVaQYassighX7NGCkF68EsrZA43uQ=="], - - "ajv-keywords/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], + "ajv-keywords/ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], "ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], @@ -5663,6 +5794,8 @@ "app-builder-lib/hosted-git-info": ["hosted-git-info@4.1.0", "", { "dependencies": { "lru-cache": "^6.0.0" } }, "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA=="], + "app-builder-lib/semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="], + "app-builder-lib/which": ["which@5.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ=="], "archiver-utils/glob": ["glob@10.5.0", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg=="], @@ -5681,6 +5814,8 @@ "astro/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "axios/https-proxy-agent": ["https-proxy-agent@5.0.1", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="], + "babel-plugin-jsx-dom-expressions/@babel/helper-module-imports": ["@babel/helper-module-imports@7.18.6", "", { "dependencies": { "@babel/types": "^7.18.6" } }, "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA=="], "babel-plugin-module-resolver/glob": ["glob@9.3.5", "", { "dependencies": { "fs.realpath": "^1.0.0", "minimatch": "^8.0.2", "minipass": "^4.2.4", "path-scurry": "^1.6.1" } }, "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q=="], @@ -5689,8 +5824,6 @@ "body-parser/iconv-lite": ["iconv-lite@0.4.24", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3" } }, "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA=="], - "body-parser/qs": ["qs@6.14.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q=="], - "builder-util/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "c12/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], @@ -5713,17 +5846,13 @@ "cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], - "db0/drizzle-orm": ["drizzle-orm@1.0.0-beta.19-d95b7a4", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@effect/sql": "^0.48.5", "@effect/sql-pg": "^0.49.7", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@sinclair/typebox": ">=0.34.8", "@sqlitecloud/drivers": ">=1.0.653", "@tidbcloud/serverless": "*", "@tursodatabase/database": ">=0.2.1", "@tursodatabase/database-common": ">=0.2.1", "@tursodatabase/database-wasm": ">=0.2.1", "@types/better-sqlite3": "*", "@types/mssql": "^9.1.4", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "arktype": ">=2.0.0", "better-sqlite3": ">=9.3.0", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "mssql": "^11.0.1", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5", "typebox": ">=1.0.0", "valibot": ">=1.0.0-beta.7", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@effect/sql", "@effect/sql-pg", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@sinclair/typebox", "@sqlitecloud/drivers", "@tidbcloud/serverless", "@tursodatabase/database", "@tursodatabase/database-common", "@tursodatabase/database-wasm", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "arktype", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "mysql2", "pg", "postgres", "sql.js", "sqlite3", "typebox", "valibot", "zod"] }, "sha512-bZZKKeoRKrMVU6zKTscjrSH0+WNb1WEi3N0Jl4wEyQ7aQpTgHzdYY6IJQ1P0M74HuSJVeX4UpkFB/S6dtqLEJg=="], - - "defaults/clone": ["clone@1.0.4", "", {}, "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg=="], - "dir-compare/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], "dir-compare/p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], "dmg-builder/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], - "dmg-license/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], + "dmg-license/ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], @@ -5743,18 +5872,24 @@ "electron-publish/mime": ["mime@2.6.0", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="], - "electron-winstaller/fs-extra": ["fs-extra@7.0.1", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw=="], + "electron-updater/semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="], - "encoding/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], + "electron-winstaller/fs-extra": ["fs-extra@7.0.1", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw=="], - "engine.io-client/ws": ["ws@8.18.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="], + "engine.io-client/ws": ["ws@8.20.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w=="], "esbuild-plugin-copy/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "esbuild-plugin-copy/chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="], + "estree-util-attach-comments/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "estree-util-scope/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "estree-util-to-js/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], + "estree-walker/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "execa/get-stream": ["get-stream@8.0.1", "", {}, "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA=="], "execa/is-stream": ["is-stream@3.0.0", "", {}, "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA=="], @@ -5765,8 +5900,6 @@ "express/path-to-regexp": ["path-to-regexp@0.1.13", "", {}, "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA=="], - "express/qs": ["qs@6.14.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q=="], - "fetch-blob/web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="], "filelist/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], @@ -5775,11 +5908,11 @@ "form-data/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], - "fs-extra/jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="], + "fs-extra/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], "gaxios/node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], - "gitlab-ai-provider/openai": ["openai@6.34.0", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-yEr2jdGf4tVFYG6ohmr3pF6VJuveP0EA/sS8TBx+4Eq5NT10alu5zg2dmxMXMgqpihRDQlFGpRt2XwsGj+Fyxw=="], + "gitlab-ai-provider/openai": ["openai@6.39.1", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"], "bin": { "openai": "bin/cli" } }, "sha512-z3dO9fEWOXBzlXynVb/xZ/tujzUjFWQWn3C0n0mw6Vo0zJTbEkaN4b2cLWjhJ6haJQx8LlREoafHRl+Gu/Hl+A=="], "gitlab-ai-provider/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], @@ -5787,7 +5920,9 @@ "gray-matter/js-yaml": ["js-yaml@3.14.2", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg=="], - "happy-dom/ws": ["ws@8.20.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="], + "hast-util-to-estree/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "hast-util-to-jsx-runtime/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], "html-minifier-terser/commander": ["commander@10.0.1", "", {}, "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug=="], @@ -5811,31 +5946,41 @@ "lightningcss/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "log-symbols/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], - "matcher/escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], "md-to-react-email/marked": ["marked@7.0.4", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-t8eP0dXRJMtMvBojtkcsA7n48BkauktUKzfkPSCq85ZMTJ0v76Rke4DYz01omYpPTUh4p/f7HePgRo3ebG8+QQ=="], + "micromark-extension-mdx-expression/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "micromark-extension-mdx-jsx/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "micromark-extension-mdxjs-esm/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "micromark-factory-mdx-expression/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "micromark-util-events-to-acorn/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], "miniflare/acorn": ["acorn@8.14.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="], "miniflare/undici": ["undici@7.14.0", "", {}, "sha512-Vqs8HTzjpQXZeXdpsfChQTlafcMQaaIwnGwLam1wudSSjlJeQ3bw1j+TLPePgrCnCpUXx7Ba5Pdpf5OBih62NQ=="], + "miniflare/ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="], + "miniflare/zod": ["zod@3.22.3", "", {}, "sha512-EjIevzuJRiRPbVH4mGc8nApb/lVLKVpmUhAaR5R5doKGfAnGJ6Gr3CViAVjP+4FWSxCsybeWQdcgCtbX+7oZug=="], "minipass-flush/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], "minipass-pipeline/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], - "motion/framer-motion": ["framer-motion@12.38.0", "", { "dependencies": { "motion-dom": "^12.38.0", "motion-utils": "^12.36.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g=="], + "motion/framer-motion": ["framer-motion@12.40.0", "", { "dependencies": { "motion-dom": "^12.40.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-uaBd3qC1v3KQqBEjwTUd183K6PbS+j0yR9w9VmEOLWA/tnUcSn8Xa3uck7t4dgpDoUss8xQTcj8W2L07lrnLFg=="], - "mssql/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], + "nitro/h3": ["h3@2.0.1-rc.5", "", { "dependencies": { "rou3": "^0.7.9", "srvx": "^0.9.1" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"] }, "sha512-qkohAzCab0nLzXNm78tBjZDvtKMTmtygS8BJLT3VPczAQofdqlFXDPkXdLMJN4r05+xqneG8snZJ0HgkERCZTg=="], - "mssql/tedious": ["tedious@18.6.2", "", { "dependencies": { "@azure/core-auth": "^1.7.2", "@azure/identity": "^4.2.1", "@azure/keyvault-keys": "^4.4.0", "@js-joda/core": "^5.6.1", "@types/node": ">=18", "bl": "^6.0.11", "iconv-lite": "^0.6.3", "js-md4": "^0.3.2", "native-duplexpair": "^1.0.0", "sprintf-js": "^1.1.3" } }, "sha512-g7jC56o3MzLkE3lHkaFe2ZdOVFBahq5bsB60/M4NYUbocw/MCrS89IOEQUFr+ba6pb8ZHczZ/VqCyYeYq0xBAg=="], + "nitro/undici": ["undici@7.26.0", "", {}, "sha512-3O9Tf67pGhgOv9jM35AbhkXAKi13f3oy3aE4CSgr+TckGeY+/iu97ZXN+J7DpHPzLbVApFd1IFhcnBjREYXYcg=="], - "nitro/h3": ["h3@2.0.1-rc.5", "", { "dependencies": { "rou3": "^0.7.9", "srvx": "^0.9.1" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"] }, "sha512-qkohAzCab0nLzXNm78tBjZDvtKMTmtygS8BJLT3VPczAQofdqlFXDPkXdLMJN4r05+xqneG8snZJ0HgkERCZTg=="], + "node-gyp/undici": ["undici@6.26.0", "", {}, "sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A=="], "node-gyp-build-optional-packages/detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], @@ -5843,7 +5988,7 @@ "nypm/citty": ["citty@0.2.2", "", {}, "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w=="], - "nypm/tinyexec": ["tinyexec@1.1.1", "", {}, "sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg=="], + "nypm/tinyexec": ["tinyexec@1.2.2", "", {}, "sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g=="], "opencode/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.71", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.23" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-bUWOzrzR0gJKJO/PLGMR4uH2dqEgqGhrsCV+sSpk4KtOEnUQlfjZI/F7BFlqSvVpFbjdgYRRLysAeEZpJ6S1lg=="], @@ -5855,22 +6000,10 @@ "opencode/minimatch": ["minimatch@10.0.3", "", { "dependencies": { "@isaacs/brace-expansion": "^5.0.0" } }, "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw=="], - "opencode-gitlab-auth/open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], - - "opencode-poe-auth/open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], - "openid-client/jose": ["jose@4.15.9", "", {}, "sha512-1vUQX+IdDMVPj4k8kOxgUqlcK518yluMuGZwqlr44FS1ppZB/5GWh4rZG89erpOBOJjU/OBsnCVFfapsRz6nEA=="], "openid-client/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], - "ora/bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="], - - "ora/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], - - "ora/cli-spinners": ["cli-spinners@2.9.2", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="], - - "ora/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - "p-locate/p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], "p-retry/retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], @@ -5907,12 +6040,18 @@ "readdir-glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], - "restore-cursor/onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="], + "recma-build-jsx/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "recma-parse/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], - "restore-cursor/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], + "recma-stringify/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "rehype-recma/@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], "rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], + "roarr/sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="], + "router/path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], "send/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], @@ -5939,8 +6078,6 @@ "storybook/open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], - "storybook-solidjs-vite/vite-plugin-solid": ["vite-plugin-solid@2.11.12", "", { "dependencies": { "@babel/core": "^7.23.3", "@types/babel__core": "^7.20.4", "babel-preset-solid": "^1.8.4", "merge-anything": "^5.1.7", "solid-refresh": "^0.6.3", "vitefu": "^1.0.4" }, "peerDependencies": { "@testing-library/jest-dom": "^5.16.6 || ^5.17.0 || ^6.*", "solid-js": "^1.7.2", "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@testing-library/jest-dom"] }, "sha512-FgjPcx2OwX9h6f28jli7A4bG7PP3te8uyakE5iqsmpq3Jqi1TWLgSroC9N6cMfGRU2zXsl4Q6ISvTr2VL0QHpA=="], - "string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], "string-width-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], @@ -5953,9 +6090,11 @@ "terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], + "thread-stream/real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="], + "tiny-async-pool/semver": ["semver@5.7.2", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="], - "tree-sitter-bash/node-addon-api": ["node-addon-api@8.7.0", "", {}, "sha512-9MdFxmkKaOYVTV+XVRG8ArDwwQ77XIgIPyKASB1k3JPq3M8fGQQQE3YpMOrKm6g//Ktx8ivZr8xo1Qmtqub+GA=="], + "tree-sitter-bash/node-addon-api": ["node-addon-api@8.8.0", "", {}, "sha512-c5Ko1fZJIJmzhFIkhRN76WTq+fC6tWnGy9CXA0fA+XygsWZmEwG8vmbkNqxMyoaa0Tin4djul49NzdVcJJcjeA=="], "tw-to-css/postcss": ["postcss@8.4.31", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="], @@ -5977,13 +6116,13 @@ "vite-plugin-icons-spritesheet/glob": ["glob@11.1.0", "", { "dependencies": { "foreground-child": "^3.3.1", "jackspeak": "^4.1.1", "minimatch": "^10.1.1", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^2.0.0" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw=="], - "vitest/@vitest/expect": ["@vitest/expect@4.1.4", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.4", "@vitest/utils": "4.1.4", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-iPBpra+VDuXmBFI3FMKHSFXp3Gx5HfmSCE8X67Dn+bwephCnQCaB7qWK2ldHa+8ncN8hJU8VTMcxjPpyMkUjww=="], + "vitest/@vitest/expect": ["@vitest/expect@4.1.7", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.7", "@vitest/utils": "4.1.7", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-1R+tw0ortHEbZDGMymm+pN7/AFQ/RkFFdtd7EN+VBpynKmLbP8A3rpEXdshBJ7+8hQ9zBJh/i1s0yKNtxAnU7w=="], - "vitest/@vitest/spy": ["@vitest/spy@4.1.4", "", {}, "sha512-XxNdAsKW7C+FLydqFJLb5KhJtl3PGCMmYwFRfhvIgxJvLSXhhVI1zM8f1qD3Zg7RCjTSzDVyct6sghs9UEgBEQ=="], + "vitest/@vitest/spy": ["@vitest/spy@4.1.7", "", {}, "sha512-kbkI5LMWakyuTIvs6fUJ5qdIVb1XVKsYJAT4OJ938cHMROYMSfmoQdZy0aaAnjbbc8F61vkoTqz/Az+/HiIu5Q=="], - "vitest/es-module-lexer": ["es-module-lexer@2.0.0", "", {}, "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw=="], + "vitest/es-module-lexer": ["es-module-lexer@2.1.0", "", {}, "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ=="], - "vitest/tinyexec": ["tinyexec@1.1.1", "", {}, "sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg=="], + "vitest/tinyexec": ["tinyexec@1.2.2", "", {}, "sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g=="], "vitest/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=="], @@ -6007,8 +6146,6 @@ "yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="], - "zod-to-json-schema/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - "zod-to-ts/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], "@actions/artifact/@actions/core/@actions/exec": ["@actions/exec@2.0.0", "", { "dependencies": { "@actions/io": "^2.0.0" } }, "sha512-k8ngrX2voJ/RIN6r9xB82NVqKpnMRtxDoiO+g3olkIUpQNqjArXrCQceduQZCQj3P3xm32pChRLqRrtXTlqhIw=="], @@ -6021,10 +6158,6 @@ "@ai-sdk/amazon-bedrock/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@ai-sdk/amazon-bedrock/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="], - - "@ai-sdk/amazon-bedrock/@smithy/eventstream-codec/@smithy/types": ["@smithy/types@4.14.1", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg=="], - "@ai-sdk/anthropic/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], "@ai-sdk/azure/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], @@ -6033,15 +6166,19 @@ "@ai-sdk/cohere/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "@ai-sdk/deepgram/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "@ai-sdk/deepinfra/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@ai-sdk/google-vertex/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "@ai-sdk/deepseek/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@ai-sdk/google-vertex/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="], + "@ai-sdk/elevenlabs/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@ai-sdk/google/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "@ai-sdk/fireworks/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@ai-sdk/google/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="], + "@ai-sdk/google-vertex/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + + "@ai-sdk/google/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], "@ai-sdk/groq/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], @@ -6073,39 +6210,9 @@ "@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/client-cognito-identity/@aws-sdk/middleware-user-agent/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], - - "@aws-sdk/client-lambda/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.24", "", { "dependencies": { "@nodable/entities": "2.1.0", "@smithy/types": "^4.14.1", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-V8z5YcDPfsvzrBlj0xR1vhRtocblhYbqdreCJB/voGd4Sr5zjNAeWxexbnqVtskTJe0vFb5KMqbSL++ePl+zRw=="], - - "@aws-sdk/client-lambda/@aws-sdk/core/@smithy/signature-v4": ["@smithy/signature-v4@5.4.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g=="], - - "@aws-sdk/client-lambda/@aws-sdk/core/@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.37", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-/jpPvEh6f7ntmIzf7dNxoNX6Q8vt8UpesCjbW6mFfk4V1NW6bIy9qxcQ6WbA8As5yQhsZOe+xeNd4xHX8kdY2Q=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.39", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-pIgTpisWyWg7X1bUbzSjuUYosYTD0Ghz2M0hkSTmb3a6i3qV3uU+NYJPI/E2XSC0HcsZh5rsLPzeXrkb2DS0Cg=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/credential-provider-env": "^3.972.37", "@aws-sdk/credential-provider-http": "^3.972.39", "@aws-sdk/credential-provider-login": "^3.972.41", "@aws-sdk/credential-provider-process": "^3.972.37", "@aws-sdk/credential-provider-sso": "^3.972.41", "@aws-sdk/credential-provider-web-identity": "^3.972.41", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/credential-provider-imds": "^4.3.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-u2tyjaxJJzW8UtW4SM1ZcPMDwO6y+kV+llvou+Adts0FAKyzes5jG4izQN+KX3yE8ZROpS5y1LJ//xL2iSf76w=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.37", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-7nVaHBUaWIddASYfVaA9O4D5ZVjewU3sCol9WqZPGfW0nR+0WqE0xHZnD/U2L33PlOB8KNXGKZ6wOES/QijKzg=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/token-providers": "3.1048.0", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-IOWAWEHe5LkjSKkkUUX9ciV6Y1scHTsnfEkdt5yyC4Slrc7AGbkLPrpntjqh18ksJAMOaVhoBsO8p2WyTcY2wQ=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-mbACk9Yypa8nm4iGZLs0PofOXEcTDOUw6wDnsPXNDNSd2WNXs1tSo+6nc/fh0jLYdfVZThhBL98PHW4aXFsG5A=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.3.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-I2Bti0DKFo2IJyN28ijCsx51BAumEYR4/1yZ1FXyBygy9MqbnMqCev4JPth/MbpRfBSRAX35hITSnAdJRo1u5w=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], - - "@aws-sdk/client-lambda/@aws-sdk/types/@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], - - "@aws-sdk/client-lambda/@smithy/core/@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], - - "@aws-sdk/client-lambda/@smithy/fetch-http-handler/@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], - - "@aws-sdk/client-lambda/@smithy/node-http-handler/@smithy/types": ["@smithy/types@4.14.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw=="], + "@aws-sdk/client-lambda/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.775.0", "", { "dependencies": { "@aws-sdk/core": "3.775.0", "@aws-sdk/types": "3.775.0", "@smithy/property-provider": "^4.0.2", "@smithy/types": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-6ESVxwCbGm7WZ17kY1fjmxQud43vzJFoLd4bmlR+idQSWdqlzGDYdcfzpjDKTcivdtNrVYmFvcH1JBUwCRAZhw=="], @@ -6119,77 +6226,21 @@ "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.782.0", "", { "dependencies": { "@aws-sdk/core": "3.775.0", "@aws-sdk/nested-clients": "3.782.0", "@aws-sdk/types": "3.775.0", "@smithy/property-provider": "^4.0.2", "@smithy/types": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-xCna0opVPaueEbJoclj5C6OpDNi0Gynj+4d7tnuXGgQhTHPyAz8ZyClkVqpi5qvHTgxROdUEDxWqEO5jqRHZHQ=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core": ["@aws-sdk/core@3.973.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws-sdk/xml-builder": "^3.972.17", "@smithy/core": "^3.23.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/property-provider": "^4.2.13", "@smithy/protocol-http": "^5.3.13", "@smithy/signature-v4": "^5.3.13", "@smithy/smithy-client": "^4.12.9", "@smithy/types": "^4.14.0", "@smithy/util-base64": "^4.3.2", "@smithy/util-middleware": "^4.2.13", "@smithy/util-utf8": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-CUZ5m8hwMCH6OYI4Li/WgMfIEx10Q2PLI9Y3XOUTPGZJ53aZ0007jCv+X/ywsaERyKPdw5MRZWk877roQksQ4A=="], - - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], - - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core": ["@aws-sdk/core@3.974.15", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@aws-sdk/xml-builder": "^3.972.26", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.5", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-UpA0rTGW/tHGITcCqHisbuuEPraYg9GG+mWmXjY5+RxZBMLGe6aL9oe0ix50LztwAcPIkGZLH0yWdMIkCM10hw=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], + "@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], + "@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], + "@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-provider-env/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-provider-http/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], - - "@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + "@aws-sdk/credential-provider-login/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="], "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.933.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.932.0", "@aws-sdk/middleware-host-header": "3.930.0", "@aws-sdk/middleware-logger": "3.930.0", "@aws-sdk/middleware-recursion-detection": "3.933.0", "@aws-sdk/middleware-user-agent": "3.932.0", "@aws-sdk/region-config-resolver": "3.930.0", "@aws-sdk/types": "3.930.0", "@aws-sdk/util-endpoints": "3.930.0", "@aws-sdk/util-user-agent-browser": "3.930.0", "@aws-sdk/util-user-agent-node": "3.932.0", "@smithy/config-resolver": "^4.4.3", "@smithy/core": "^3.18.2", "@smithy/fetch-http-handler": "^5.3.6", "@smithy/hash-node": "^4.2.5", "@smithy/invalid-dependency": "^4.2.5", "@smithy/middleware-content-length": "^4.2.5", "@smithy/middleware-endpoint": "^4.3.9", "@smithy/middleware-retry": "^4.4.9", "@smithy/middleware-serde": "^4.2.5", "@smithy/middleware-stack": "^4.2.5", "@smithy/node-config-provider": "^4.3.5", "@smithy/node-http-handler": "^4.4.5", "@smithy/protocol-http": "^5.3.5", "@smithy/smithy-client": "^4.9.5", "@smithy/types": "^4.9.0", "@smithy/url-parser": "^4.2.5", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.8", "@smithy/util-defaults-mode-node": "^4.2.11", "@smithy/util-endpoints": "^3.2.5", "@smithy/util-middleware": "^4.2.5", "@smithy/util-retry": "^4.2.5", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-o1GX0+IPlFi/D8ei9y/jj3yucJWNfPnbB5appVBWevAyUdZA5KzQ2nK/hDxiu9olTZlFEFpf1m1Rn3FaGxHqsw=="], @@ -6197,119 +6248,45 @@ "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.933.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.932.0", "@aws-sdk/middleware-host-header": "3.930.0", "@aws-sdk/middleware-logger": "3.930.0", "@aws-sdk/middleware-recursion-detection": "3.933.0", "@aws-sdk/middleware-user-agent": "3.932.0", "@aws-sdk/region-config-resolver": "3.930.0", "@aws-sdk/types": "3.930.0", "@aws-sdk/util-endpoints": "3.930.0", "@aws-sdk/util-user-agent-browser": "3.930.0", "@aws-sdk/util-user-agent-node": "3.932.0", "@smithy/config-resolver": "^4.4.3", "@smithy/core": "^3.18.2", "@smithy/fetch-http-handler": "^5.3.6", "@smithy/hash-node": "^4.2.5", "@smithy/invalid-dependency": "^4.2.5", "@smithy/middleware-content-length": "^4.2.5", "@smithy/middleware-endpoint": "^4.3.9", "@smithy/middleware-retry": "^4.4.9", "@smithy/middleware-serde": "^4.2.5", "@smithy/middleware-stack": "^4.2.5", "@smithy/node-config-provider": "^4.3.5", "@smithy/node-http-handler": "^4.4.5", "@smithy/protocol-http": "^5.3.5", "@smithy/smithy-client": "^4.9.5", "@smithy/types": "^4.9.0", "@smithy/url-parser": "^4.2.5", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.8", "@smithy/util-defaults-mode-node": "^4.2.11", "@smithy/util-endpoints": "^3.2.5", "@smithy/util-middleware": "^4.2.5", "@smithy/util-retry": "^4.2.5", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-o1GX0+IPlFi/D8ei9y/jj3yucJWNfPnbB5appVBWevAyUdZA5KzQ2nK/hDxiu9olTZlFEFpf1m1Rn3FaGxHqsw=="], - "@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-provider-process/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + "@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], + "@aws-sdk/credential-providers/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], + "@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], + "@aws-sdk/token-providers/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], + "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.30", "", { "dependencies": { "@aws-sdk/types": "^3.973.9", "@smithy/signature-v4": "^5.4.5", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-HULDLMVzkmTSEv6//7kx2kRevp/VYUpm8hJNNFbmhxDn0fUiGTxVcM9yg31TukvTq8nyOBDUN2gH0o5IRbKjdw=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], + "@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], - - "@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-providers/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/credential-providers/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], - - "@aws-sdk/token-providers/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], - - "@aws-sdk/token-providers/@aws-sdk/core/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-je5vRdNw4SkuTnmRbFZLdye4sQ0faLt8kwka5wnnSU30q1mHO4X+idGEJOOE+Tn1ME7Oryn05xxkDvIb3UaLaQ=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-HsVgDrruhqI28RkaXALm8grJ7Agc1wF6Et0xh6pom8NdO2VdO/SD9U/tPwUjewwK/pVoka+EShBxyCvgsPCtog=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-RVQQbq5orQ/GHUnXvqEOj2HHPBJm+mM+ySwZKS5UaLBwra5ugRtiH09PLUoOZRl7a1YzaOzXSuGbn9iD5j60WQ=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.29", "", { "dependencies": { "@aws-sdk/core": "^3.973.27", "@aws-sdk/types": "^3.973.7", "@aws-sdk/util-endpoints": "^3.996.6", "@smithy/core": "^3.23.14", "@smithy/protocol-http": "^5.3.13", "@smithy/types": "^4.14.0", "@smithy/util-retry": "^4.3.0", "tslib": "^2.6.2" } }, "sha512-f/sIRzuTfEjg6NsbMYvye2VsmnQoNgntntleQyx5uGacUYzszbfIlO3GcI6G6daWUmTm0IDZc11qMHWwF0o0mQ=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.11", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/config-resolver": "^4.4.14", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "tslib": "^2.6.2" } }, "sha512-6Q8B1dcx6BBqUTY1Mc/eROKA0FImEEY5VPSd6AGPEUf0ErjExz4snVqa9kNJSoVDV1rKaNf3qrWojgcKW+SdDg=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.996.6", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "@smithy/url-parser": "^4.2.13", "@smithy/util-endpoints": "^3.3.4", "tslib": "^2.6.2" } }, "sha512-2nUQ+2ih7CShuKHpGSIYvvAIOHy52dOZguYG36zptBukhw6iFwcvGfG0tes0oZFWQqEWvgZe9HLWaNlvXGdOrg=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.9", "", { "dependencies": { "@aws-sdk/types": "^3.973.7", "@smithy/types": "^4.14.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-sn/LMzTbGjYqCCF24390WxPd6hkpoSptiUn5DzVp4cD71yqw+yGEGm1YCxyEoPXyc8qciM8UzLJcZBFslxo5Uw=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.973.15", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.29", "@aws-sdk/types": "^3.973.7", "@smithy/node-config-provider": "^4.3.13", "@smithy/types": "^4.14.0", "@smithy/util-config-provider": "^4.2.2", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-fYn3s9PtKdgQkczGZCFMgkNEe8aq1JCVbnRqjqN9RSVW43xn2RV9xdcZ3z01a48Jpkuh/xCmBKJxdLOo4Ozg7w=="], - - "@aws-sdk/token-providers/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@azure/core-xml/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@azure/identity/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], + "@azure/core-xml/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], "@babel/helper-compilation-targets/lru-cache/yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], "@develar/schema-utils/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], - "@electron/asar/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], + "@electron/asar/minimatch/brace-expansion": ["brace-expansion@1.1.15", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="], - "@electron/fuses/fs-extra/jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="], + "@electron/fuses/fs-extra/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], "@electron/get/fs-extra/universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="], - "@electron/notarize/fs-extra/jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="], - - "@electron/rebuild/node-gyp/make-fetch-happen": ["make-fetch-happen@14.0.3", "", { "dependencies": { "@npmcli/agent": "^3.0.0", "cacache": "^19.0.1", "http-cache-semantics": "^4.1.1", "minipass": "^7.0.2", "minipass-fetch": "^4.0.0", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "negotiator": "^1.0.0", "proc-log": "^5.0.0", "promise-retry": "^2.0.1", "ssri": "^12.0.0" } }, "sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ=="], - - "@electron/rebuild/node-gyp/nopt": ["nopt@8.1.0", "", { "dependencies": { "abbrev": "^3.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A=="], - - "@electron/rebuild/node-gyp/proc-log": ["proc-log@5.0.0", "", {}, "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ=="], - - "@electron/rebuild/node-gyp/which": ["which@5.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ=="], - - "@electron/rebuild/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], + "@electron/notarize/fs-extra/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], - "@electron/rebuild/yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + "@electron/universal/fs-extra/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], - "@electron/universal/fs-extra/jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="], + "@electron/universal/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], - "@electron/universal/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], - - "@electron/windows-sign/fs-extra/jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="], + "@electron/windows-sign/fs-extra/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], "@expressive-code/plugin-shiki/shiki/@shikijs/core": ["@shikijs/core@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA=="], @@ -6323,8 +6300,6 @@ "@expressive-code/plugin-shiki/shiki/@shikijs/types": ["@shikijs/types@3.23.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="], - "@gitlab/opencode-gitlab-auth/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - "@jsx-email/cli/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.19.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA=="], "@jsx-email/cli/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.19.12", "", { "os": "android", "cpu": "arm" }, "sha512-qg/Lj1mu3CdQlDEEiWrlC4eaPZ1KztwGJ9B6J+/6G+/4ewxJg7gqj8eVYWvao1bXrqGiW2rsBZFSX3q2lcW05w=="], @@ -6385,7 +6360,7 @@ "@jsx-email/doiuse-email/htmlparser2/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], - "@malept/flatpak-bundler/fs-extra/jsonfile": ["jsonfile@6.2.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg=="], + "@malept/flatpak-bundler/fs-extra/jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], "@modelcontextprotocol/sdk/express/accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], @@ -6407,30 +6382,38 @@ "@modelcontextprotocol/sdk/express/serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], - "@modelcontextprotocol/sdk/express/type-is": ["type-is@2.0.1", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="], + "@modelcontextprotocol/sdk/express/type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], "@octokit/auth-app/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], "@octokit/auth-app/@octokit/request/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], + "@octokit/auth-app/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/auth-app/@octokit/request-error/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], "@octokit/auth-oauth-app/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], "@octokit/auth-oauth-app/@octokit/request/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], + "@octokit/auth-oauth-app/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/auth-oauth-app/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/auth-oauth-device/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], "@octokit/auth-oauth-device/@octokit/request/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], + "@octokit/auth-oauth-device/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/auth-oauth-device/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/auth-oauth-user/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], "@octokit/auth-oauth-user/@octokit/request/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], + "@octokit/auth-oauth-user/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/auth-oauth-user/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/core/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@24.2.0", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="], @@ -6443,17 +6426,21 @@ "@octokit/graphql/@octokit/request/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], + "@octokit/graphql/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/graphql/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@26.0.0", "", {}, "sha512-7AtcfKtpo77j7Ts73b4OWhOZHTKo/gGY8bB3bNBQz4H+GRSWqx2yvj8TXRsbdTE0eRmYmXOEY66jM7mJ7LzfsA=="], "@octokit/oauth-methods/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], + "@octokit/oauth-methods/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/oauth-methods/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/plugin-paginate-rest/@octokit/core/@octokit/auth-token": ["@octokit/auth-token@6.0.0", "", {}, "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w=="], "@octokit/plugin-paginate-rest/@octokit/core/@octokit/graphql": ["@octokit/graphql@9.0.3", "", { "dependencies": { "@octokit/request": "^10.0.6", "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA=="], - "@octokit/plugin-paginate-rest/@octokit/core/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/plugin-paginate-rest/@octokit/core/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/plugin-paginate-rest/@octokit/core/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], @@ -6467,7 +6454,7 @@ "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/graphql": ["@octokit/graphql@9.0.3", "", { "dependencies": { "@octokit/request": "^10.0.6", "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA=="], - "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], @@ -6487,7 +6474,7 @@ "@octokit/rest/@octokit/core/@octokit/graphql": ["@octokit/graphql@9.0.3", "", { "dependencies": { "@octokit/request": "^10.0.6", "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.0" } }, "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA=="], - "@octokit/rest/@octokit/core/@octokit/request": ["@octokit/request@10.0.8", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "fast-content-type-parse": "^3.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-SJZNwY9pur9Agf7l87ywFi14W+Hd9Jg6Ifivsd33+/bGUQIjNujdFiXII2/qSlN2ybqUHfp5xpekMEjIBTjlSw=="], + "@octokit/rest/@octokit/core/@octokit/request": ["@octokit/request@10.0.10", "", { "dependencies": { "@octokit/endpoint": "^11.0.3", "@octokit/request-error": "^7.0.2", "@octokit/types": "^16.0.0", "content-type": "^2.0.0", "json-with-bigint": "^3.5.3", "universal-user-agent": "^7.0.2" } }, "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w=="], "@octokit/rest/@octokit/core/@octokit/request-error": ["@octokit/request-error@7.1.0", "", { "dependencies": { "@octokit/types": "^16.0.0" } }, "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw=="], @@ -6497,8 +6484,6 @@ "@opencode-ai/desktop/@actions/artifact/@actions/http-client": ["@actions/http-client@2.2.3", "", { "dependencies": { "tunnel": "^0.0.6", "undici": "^5.25.4" } }, "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA=="], - "@opencode-ai/llm/@smithy/eventstream-codec/@smithy/types": ["@smithy/types@4.14.1", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg=="], - "@opencode-ai/web/@shikijs/transformers/@shikijs/core": ["@shikijs/core@3.20.0", "", { "dependencies": { "@shikijs/types": "3.20.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-f2ED7HYV4JEk827mtMDwe/yQ25pRiXZmtHjWF8uzZKuKiEsJR7Ce1nuQ+HhV9FzDcbIo4ObBCD9GPTzNuy9S1g=="], "@opencode-ai/web/@shikijs/transformers/@shikijs/types": ["@shikijs/types@3.20.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-lhYAATn10nkZcBQ0BlzSbJA3wcmL5MXUUF8d2Zzon6saZDlToKaiRX60n2+ZaHJCmXEcZRWNzn+k9vplr8Jhsw=="], @@ -6537,25 +6522,17 @@ "@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=="], - "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="], + "@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=="], "@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/pretty-format@3.2.4", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="], "accepts/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], - "ai-gateway-provider/@ai-sdk/google/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="], + "ai-gateway-provider/@ai-sdk/anthropic/@ai-sdk/provider": ["@ai-sdk/provider@3.0.10", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="], - "ai-gateway-provider/@ai-sdk/google-vertex/@ai-sdk/anthropic": ["@ai-sdk/anthropic@3.0.64", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.21" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-rwLi/Rsuj2pYniQXIrvClHvXDzgM4UQHHnvHTWEF14efnlKclG/1ghpNC+adsRujAbCTr6gRsSbDE2vEqriV7g=="], - - "ai-gateway-provider/@ai-sdk/google-vertex/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="], - - "ai-gateway-provider/@ai-sdk/xai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.21", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.6" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-MtFUYI1/8mgDvRmaBDjbLJPFFrMG777AvSgyIFQtZHIMzm88R/12vYBBpnk7pfiWLFE1DSZzY4WDYzGbKAcmiw=="], + "ai-gateway-provider/@ai-sdk/anthropic/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.27", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw=="], "ajv-keywords/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], @@ -6583,6 +6560,8 @@ "astro/unstorage/ofetch": ["ofetch@1.5.1", "", { "dependencies": { "destr": "^2.0.5", "node-fetch-native": "^1.6.7", "ufo": "^1.6.1" } }, "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA=="], + "axios/https-proxy-agent/agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], + "babel-plugin-module-resolver/glob/minimatch": ["minimatch@8.0.7", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-V+1uQNdzybxa14e/p00HZnQNNcTjnRJjDxg2V8wtkjFctq4M7hXFws4oekyTP0Jebeq7QYtpFyOeBAjc88zvYg=="], "babel-plugin-module-resolver/glob/minipass": ["minipass@4.2.8", "", {}, "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ=="], @@ -6595,13 +6574,13 @@ "cross-spawn/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], - "dir-compare/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], + "dir-compare/minimatch/brace-expansion": ["brace-expansion@1.1.15", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="], "dir-compare/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], "dmg-license/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], - "editorconfig/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "editorconfig/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "electron-builder/yargs/cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], @@ -6613,7 +6592,7 @@ "express/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], - "filelist/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "filelist/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "finalhandler/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], @@ -6633,29 +6612,15 @@ "js-beautify/nopt/abbrev": ["abbrev@2.0.0", "", {}, "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ=="], - "lazystream/readable-stream/core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], - "lazystream/readable-stream/isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], "lazystream/readable-stream/safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="], "lazystream/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], - "motion/framer-motion/motion-dom": ["motion-dom@12.38.0", "", { "dependencies": { "motion-utils": "^12.36.0" } }, "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA=="], - - "motion/framer-motion/motion-utils": ["motion-utils@12.36.0", "", {}, "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg=="], - - "mssql/tedious/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], - - "opencode-gitlab-auth/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - - "opencode-poe-auth/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - - "ora/bl/buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="], + "motion/framer-motion/motion-dom": ["motion-dom@12.40.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-HxU3ZaBwNPVQUBQf1xxgq+7JrPNZvjLVxgbpEZL7RrWJnsxOf0/OM+yrHG9ogLQ31Do/r57Oz2gQWPK+6q62mg=="], - "ora/bl/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], - - "ora/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + "motion/framer-motion/motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="], "p-locate/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], @@ -6663,9 +6628,7 @@ "pkg-up/find-up/locate-path": ["locate-path@3.0.0", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="], - "readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], - - "restore-cursor/onetime/mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], + "readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "rimraf/glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], @@ -6683,7 +6646,7 @@ "tw-to-css/tailwindcss/object-hash": ["object-hash@3.0.0", "", {}, "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw=="], - "tw-to-css/tailwindcss/postcss": ["postcss@8.5.9", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw=="], + "tw-to-css/tailwindcss/postcss": ["postcss@8.5.15", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A=="], "type-is/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], @@ -6691,8 +6654,6 @@ "venice-ai-sdk-provider/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "venice-ai-sdk-provider/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="], - "vitest/@vitest/expect/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], "vitest/@vitest/expect/chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], @@ -6783,20 +6744,10 @@ "@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], "@aws-sdk/client-lambda/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.41", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-0LBitxXiAiaE5nlFPfpNIww/8FRY/I7WIndWsc9GmNFOM7cE1wNpVNQEGEk9Outg5l8xl+3vybxFyUy4l9q/LQ=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.9", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/signature-v4-multi-region": "^3.996.27", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-jPR3rnmRI4hWYyzfmTGBr7NblMp8QYYeflHXba1H6+7CGrWVqWKQzaXFQ4qbExqPRsXN3T3L3JxFhr6aouXUGQ=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.9", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/signature-v4-multi-region": "^3.996.27", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-jPR3rnmRI4hWYyzfmTGBr7NblMp8QYYeflHXba1H6+7CGrWVqWKQzaXFQ4qbExqPRsXN3T3L3JxFhr6aouXUGQ=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.1048.0", "", { "dependencies": { "@aws-sdk/core": "^3.974.11", "@aws-sdk/nested-clients": "^3.997.9", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.997.9", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.11", "@aws-sdk/signature-v4-multi-region": "^3.996.27", "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/fetch-http-handler": "^5.4.2", "@smithy/node-http-handler": "^4.7.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-jPR3rnmRI4hWYyzfmTGBr7NblMp8QYYeflHXba1H6+7CGrWVqWKQzaXFQ4qbExqPRsXN3T3L3JxFhr6aouXUGQ=="], - "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.782.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.775.0", "@aws-sdk/middleware-host-header": "3.775.0", "@aws-sdk/middleware-logger": "3.775.0", "@aws-sdk/middleware-recursion-detection": "3.775.0", "@aws-sdk/middleware-user-agent": "3.782.0", "@aws-sdk/region-config-resolver": "3.775.0", "@aws-sdk/types": "3.775.0", "@aws-sdk/util-endpoints": "3.782.0", "@aws-sdk/util-user-agent-browser": "3.775.0", "@aws-sdk/util-user-agent-node": "3.782.0", "@smithy/config-resolver": "^4.1.0", "@smithy/core": "^3.2.0", "@smithy/fetch-http-handler": "^5.0.2", "@smithy/hash-node": "^4.0.2", "@smithy/invalid-dependency": "^4.0.2", "@smithy/middleware-content-length": "^4.0.2", "@smithy/middleware-endpoint": "^4.1.0", "@smithy/middleware-retry": "^4.1.0", "@smithy/middleware-serde": "^4.0.3", "@smithy/middleware-stack": "^4.0.2", "@smithy/node-config-provider": "^4.0.2", "@smithy/node-http-handler": "^4.0.4", "@smithy/protocol-http": "^5.1.0", "@smithy/smithy-client": "^4.2.0", "@smithy/types": "^4.2.0", "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", "@smithy/util-defaults-mode-browser": "^4.0.8", "@smithy/util-defaults-mode-node": "^4.0.8", "@smithy/util-endpoints": "^3.0.2", "@smithy/util-middleware": "^4.0.2", "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" } }, "sha512-QOYC8q7luzHFXrP0xYAqBctoPkynjfV0r9dqntFu4/IWMTyC1vlo1UTxFAjIPyclYw92XJyEkVCVg9v/nQnsUA=="], "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/client-sso": ["@aws-sdk/client-sso@3.782.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.775.0", "@aws-sdk/middleware-host-header": "3.775.0", "@aws-sdk/middleware-logger": "3.775.0", "@aws-sdk/middleware-recursion-detection": "3.775.0", "@aws-sdk/middleware-user-agent": "3.782.0", "@aws-sdk/region-config-resolver": "3.775.0", "@aws-sdk/types": "3.775.0", "@aws-sdk/util-endpoints": "3.782.0", "@aws-sdk/util-user-agent-browser": "3.775.0", "@aws-sdk/util-user-agent-node": "3.782.0", "@smithy/config-resolver": "^4.1.0", "@smithy/core": "^3.2.0", "@smithy/fetch-http-handler": "^5.0.2", "@smithy/hash-node": "^4.0.2", "@smithy/invalid-dependency": "^4.0.2", "@smithy/middleware-content-length": "^4.0.2", "@smithy/middleware-endpoint": "^4.1.0", "@smithy/middleware-retry": "^4.1.0", "@smithy/middleware-serde": "^4.0.3", "@smithy/middleware-stack": "^4.0.2", "@smithy/node-config-provider": "^4.0.2", "@smithy/node-http-handler": "^4.0.4", "@smithy/protocol-http": "^5.1.0", "@smithy/smithy-client": "^4.2.0", "@smithy/types": "^4.2.0", "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", "@smithy/util-defaults-mode-browser": "^4.0.8", "@smithy/util-defaults-mode-node": "^4.0.8", "@smithy/util-endpoints": "^3.0.2", "@smithy/util-middleware": "^4.0.2", "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" } }, "sha512-5GlJBejo8wqMpSSEKb45WE82YxI2k73YuebjLH/eWDNQeE6VI5Bh9lA1YQ7xNkLLH8hIsb0pSfKVuwh0VEzVrg=="], @@ -6805,15 +6756,15 @@ "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.782.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.775.0", "@aws-sdk/middleware-host-header": "3.775.0", "@aws-sdk/middleware-logger": "3.775.0", "@aws-sdk/middleware-recursion-detection": "3.775.0", "@aws-sdk/middleware-user-agent": "3.782.0", "@aws-sdk/region-config-resolver": "3.775.0", "@aws-sdk/types": "3.775.0", "@aws-sdk/util-endpoints": "3.782.0", "@aws-sdk/util-user-agent-browser": "3.775.0", "@aws-sdk/util-user-agent-node": "3.782.0", "@smithy/config-resolver": "^4.1.0", "@smithy/core": "^3.2.0", "@smithy/fetch-http-handler": "^5.0.2", "@smithy/hash-node": "^4.0.2", "@smithy/invalid-dependency": "^4.0.2", "@smithy/middleware-content-length": "^4.0.2", "@smithy/middleware-endpoint": "^4.1.0", "@smithy/middleware-retry": "^4.1.0", "@smithy/middleware-serde": "^4.0.3", "@smithy/middleware-stack": "^4.0.2", "@smithy/node-config-provider": "^4.0.2", "@smithy/node-http-handler": "^4.0.4", "@smithy/protocol-http": "^5.1.0", "@smithy/smithy-client": "^4.2.0", "@smithy/types": "^4.2.0", "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", "@smithy/util-defaults-mode-browser": "^4.0.8", "@smithy/util-defaults-mode-node": "^4.0.8", "@smithy/util-endpoints": "^3.0.2", "@smithy/util-middleware": "^4.0.2", "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" } }, "sha512-QOYC8q7luzHFXrP0xYAqBctoPkynjfV0r9dqntFu4/IWMTyC1vlo1UTxFAjIPyclYw92XJyEkVCVg9v/nQnsUA=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.17", "", { "dependencies": { "@smithy/types": "^4.14.0", "fast-xml-parser": "5.5.8", "tslib": "^2.6.2" } }, "sha512-Ra7hjqAZf1OXRRMueB13qex7mFJRDK/pgCvdSFemXBT8KCGnQDPoKzHY1SjN+TjJVmnpSF14W5tJ1vDamFu+Gg=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.26", "", { "dependencies": { "@smithy/types": "^4.14.2", "fast-xml-parser": "5.7.3", "tslib": "^2.6.2" } }, "sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g=="], - "@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], @@ -6821,40 +6772,20 @@ "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/token-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/token-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], "@electron/asar/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - "@electron/rebuild/node-gyp/make-fetch-happen/@npmcli/agent": ["@npmcli/agent@3.0.0", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^10.0.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache": ["cacache@19.0.1", "", { "dependencies": { "@npmcli/fs": "^4.0.0", "fs-minipass": "^3.0.0", "glob": "^10.2.2", "lru-cache": "^10.0.1", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^12.0.0", "tar": "^7.4.3", "unique-filename": "^4.0.0" } }, "sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/minipass-fetch": ["minipass-fetch@4.0.1", "", { "dependencies": { "minipass": "^7.0.3", "minipass-sized": "^1.0.3", "minizlib": "^3.0.1" }, "optionalDependencies": { "encoding": "^0.1.13" } }, "sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/ssri": ["ssri@12.0.0", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ=="], - - "@electron/rebuild/node-gyp/nopt/abbrev": ["abbrev@3.0.1", "", {}, "sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg=="], - - "@electron/rebuild/node-gyp/which/isexe": ["isexe@3.1.5", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="], - - "@electron/rebuild/yargs/cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - - "@electron/rebuild/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], - - "@electron/rebuild/yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "@electron/rebuild/yargs/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], - "@electron/universal/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], "@jsx-email/cli/tailwindcss/chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], @@ -6905,6 +6836,8 @@ "@jsx-email/cli/vite/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="], + "@modelcontextprotocol/sdk/express/type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@modelcontextprotocol/sdk/express/type-is/media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="], "@octokit/auth-app/@octokit/request-error/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], @@ -6915,19 +6848,25 @@ "@octokit/plugin-paginate-rest/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], + "@octokit/plugin-paginate-rest/@octokit/core/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/plugin-paginate-rest/@octokit/core/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], + "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/plugin-rest-endpoint-methods/@octokit/core/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/rest/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/endpoint@11.0.3", "", { "dependencies": { "@octokit/types": "^16.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag=="], + "@octokit/rest/@octokit/core/@octokit/request/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + "@octokit/rest/@octokit/core/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@opencode-ai/desktop/@actions/artifact/@actions/http-client/undici": ["undici@5.29.0", "", { "dependencies": { "@fastify/busboy": "^2.0.0" } }, "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg=="], - "@sentry/bundler-plugin-core/glob/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "@sentry/bundler-plugin-core/glob/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "@sentry/bundler-plugin-core/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -6937,11 +6876,7 @@ "@solidjs/start/shiki/@shikijs/engine-javascript/oniguruma-to-es": ["oniguruma-to-es@2.3.0", "", { "dependencies": { "emoji-regex-xs": "^1.0.0", "regex": "^5.1.1", "regex-recursion": "^5.1.1" } }, "sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g=="], - "ai-gateway-provider/@ai-sdk/google-vertex/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - - "ai-gateway-provider/@ai-sdk/google/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - - "ai-gateway-provider/@ai-sdk/xai/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "ai-gateway-provider/@ai-sdk/anthropic/@ai-sdk/provider-utils/@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], "ansi-align/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], @@ -6949,7 +6884,7 @@ "archiver-utils/glob/jackspeak/@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], - "archiver-utils/glob/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "archiver-utils/glob/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "archiver-utils/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -6959,7 +6894,7 @@ "astro/unstorage/h3/crossws": ["crossws@0.3.5", "", { "dependencies": { "uncrypto": "^0.1.3" } }, "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA=="], - "babel-plugin-module-resolver/glob/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "babel-plugin-module-resolver/glob/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "babel-plugin-module-resolver/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -6981,15 +6916,13 @@ "filelist/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - "gray-matter/js-yaml/argparse/sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], - "iconv-corefoundation/cli-truncate/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], "iconv-corefoundation/cli-truncate/string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], "js-beautify/glob/jackspeak/@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], - "js-beautify/glob/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "js-beautify/glob/minimatch/brace-expansion": ["brace-expansion@2.1.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA=="], "js-beautify/glob/path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -7001,7 +6934,7 @@ "readdir-glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - "rimraf/glob/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], + "rimraf/glob/minimatch/brace-expansion": ["brace-expansion@1.1.15", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg=="], "tw-to-css/tailwindcss/chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], @@ -7013,63 +6946,35 @@ "@astrojs/check/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - "@aws-sdk/client-cognito-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@aws-sdk/client-lambda/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/fast-xml-builder": ["fast-xml-builder@1.2.0", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q=="], - - "@aws-sdk/client-lambda/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/client-cognito-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/signature-v4": "^5.4.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/signature-v4": "^5.4.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.996.27", "", { "dependencies": { "@aws-sdk/types": "^3.973.8", "@smithy/core": "^3.24.2", "@smithy/signature-v4": "^5.4.2", "@smithy/types": "^4.14.1", "tslib": "^2.6.2" } }, "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg=="], - - "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/client-sso/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + "@aws-sdk/client-lambda/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.782.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "3.775.0", "@aws-sdk/middleware-host-header": "3.775.0", "@aws-sdk/middleware-logger": "3.775.0", "@aws-sdk/middleware-recursion-detection": "3.775.0", "@aws-sdk/middleware-user-agent": "3.782.0", "@aws-sdk/region-config-resolver": "3.775.0", "@aws-sdk/types": "3.775.0", "@aws-sdk/util-endpoints": "3.782.0", "@aws-sdk/util-user-agent-browser": "3.775.0", "@aws-sdk/util-user-agent-node": "3.782.0", "@smithy/config-resolver": "^4.1.0", "@smithy/core": "^3.2.0", "@smithy/fetch-http-handler": "^5.0.2", "@smithy/hash-node": "^4.0.2", "@smithy/invalid-dependency": "^4.0.2", "@smithy/middleware-content-length": "^4.0.2", "@smithy/middleware-endpoint": "^4.1.0", "@smithy/middleware-retry": "^4.1.0", "@smithy/middleware-serde": "^4.0.3", "@smithy/middleware-stack": "^4.0.2", "@smithy/node-config-provider": "^4.0.2", "@smithy/node-http-handler": "^4.0.4", "@smithy/protocol-http": "^5.1.0", "@smithy/smithy-client": "^4.2.0", "@smithy/types": "^4.2.0", "@smithy/url-parser": "^4.0.2", "@smithy/util-base64": "^4.0.0", "@smithy/util-body-length-browser": "^4.0.0", "@smithy/util-body-length-node": "^4.0.0", "@smithy/util-defaults-mode-browser": "^4.0.8", "@smithy/util-defaults-mode-node": "^4.0.8", "@smithy/util-endpoints": "^3.0.2", "@smithy/util-middleware": "^4.0.2", "@smithy/util-retry": "^4.0.2", "@smithy/util-utf8": "^4.0.0", "tslib": "^2.6.2" } }, "sha512-QOYC8q7luzHFXrP0xYAqBctoPkynjfV0r9dqntFu4/IWMTyC1vlo1UTxFAjIPyclYw92XJyEkVCVg9v/nQnsUA=="], - "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.7.3", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.1.7", "path-expression-matcher": "^1.5.0", "strnum": "^2.2.3" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg=="], - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.5.8", "", { "dependencies": { "fast-xml-builder": "^1.1.4", "path-expression-matcher": "^1.2.0", "strnum": "^2.2.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ=="], + "@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/credential-provider-env/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/credential-provider-http/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/credential-provider-ini/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-provider-login/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], "@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - "@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-provider-process/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/credential-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-provider-sso/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-provider-web-identity/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@aws-sdk/token-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], + "@aws-sdk/credential-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@electron/rebuild/node-gyp/make-fetch-happen/@npmcli/agent/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], + "@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/@npmcli/fs": ["@npmcli/fs@4.0.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob": ["glob@10.5.0", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/minipass-fetch/minipass-sized": ["minipass-sized@1.0.3", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g=="], - - "@electron/rebuild/yargs/cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - - "@electron/rebuild/yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + "@aws-sdk/token-providers/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], "@jsx-email/cli/tailwindcss/chokidar/readdirp/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], @@ -7107,23 +7012,7 @@ "tw-to-css/tailwindcss/chokidar/readdirp/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.4.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.4.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g=="], - - "@aws-sdk/client-lambda/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients/@aws-sdk/signature-v4-multi-region/@smithy/signature-v4": ["@smithy/signature-v4@5.4.3", "", { "dependencies": { "@smithy/core": "^3.24.3", "@smithy/types": "^4.14.2", "tslib": "^2.6.2" } }, "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g=="], - - "@aws-sdk/client-sts/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers/@aws-sdk/nested-clients/@smithy/util-utf8": ["@smithy/util-utf8@4.2.2", "", { "dependencies": { "@smithy/util-buffer-from": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw=="], - - "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.2.3", "", {}, "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/minipass-fetch/minipass-sized/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + "@aws-sdk/credential-provider-cognito-identity/@aws-sdk/nested-clients/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], "archiver-utils/glob/jackspeak/@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], @@ -7132,19 +7021,5 @@ "js-beautify/glob/jackspeak/@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], "js-beautify/glob/jackspeak/@isaacs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/jackspeak/@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/jackspeak/@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/jackspeak/@isaacs/cliui/wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/jackspeak/@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], - - "@electron/rebuild/node-gyp/make-fetch-happen/cacache/glob/jackspeak/@isaacs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], } } diff --git a/bunfig.toml b/bunfig.toml index 47c4ac53965b..546f04843e89 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -2,7 +2,7 @@ exact = true # Only install newly resolved package versions published at least 3 days ago. minimumReleaseAge = 259200 -minimumReleaseAgeExcludes = ["@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-x64", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid"] +minimumReleaseAgeExcludes = ["@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-x64", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "gitlab-ai-provider"] [test] root = "./do-not-run-tests-from-root" diff --git a/infra/app.ts b/infra/app.ts index 2ede5a1f4a29..7b532bcb23f3 100644 --- a/infra/app.ts +++ b/infra/app.ts @@ -30,7 +30,7 @@ export const api = new sst.cloudflare.Worker("Api", { transform: { worker: (args) => { args.logpush = true - if ($app.stage === "vimtor") return + if ($app.stage === "vimtor" || $app.stage === "adam") return args.bindings = $resolve(args.bindings).apply((bindings) => [ ...bindings, { diff --git a/infra/console.ts b/infra/console.ts index cf1fba823728..0a304a7be309 100644 --- a/infra/console.ts +++ b/infra/console.ts @@ -1,7 +1,9 @@ -import { domain } from "./stage" +import { deployAws, domain } from "./stage" import { EMAILOCTOPUS_API_KEY } from "./app" import { SECRET } from "./secret" +const lake = deployAws ? await import("./lake") : undefined + //////////////// // DATABASE //////////////// @@ -240,7 +242,7 @@ const SALESFORCE_INSTANCE_URL = new sst.Secret("SALESFORCE_INSTANCE_URL") const logProcessor = new sst.cloudflare.Worker("LogProcessor", { handler: "packages/console/function/src/log-processor.ts", - link: [new sst.Secret("HONEYCOMB_API_KEY")], + link: [SECRET.HoneycombApiKey, ...(lake?.lakeIngest ? [lake.lakeIngest] : [])], }) new sst.cloudflare.x.SolidStart("Console", { diff --git a/infra/lake.ts b/infra/lake.ts new file mode 100644 index 000000000000..c62bb155668d --- /dev/null +++ b/infra/lake.ts @@ -0,0 +1,322 @@ +import { domain } from "./stage" + +const current = aws.getCallerIdentityOutput({}) +const partition = aws.getPartitionOutput({}) +const region = aws.getRegionOutput({}) + +const tableBucketName = `opencode-${$app.stage}-lake` +const glueCatalogName = "s3tablescatalog" +const glueCatalogArn = $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:catalog` +const glueS3TablesCatalogArn = $interpolate`${glueCatalogArn}/${glueCatalogName}` +const glueS3TablesChildCatalogArn = $interpolate`${glueS3TablesCatalogArn}/${tableBucketName}` +const glueS3TablesDatabaseWildcardArn = $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:database/${glueCatalogName}/${tableBucketName}/*` +const glueS3TablesTableWildcardArn = $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:table/${glueCatalogName}/${tableBucketName}/*/*` +const s3TablesBucketWildcardArn = $interpolate`arn:${partition.partition}:s3tables:${region.region}:${current.accountId}:bucket/*` + +export const tableBucket = new aws.s3tables.TableBucket("LakeTableBucket", { + name: tableBucketName, + forceDestroy: $app.stage !== "production", +}) + +const s3TablesCatalog = new aws.cloudcontrol.Resource( + "LakeS3TablesCatalog", + { + typeName: "AWS::Glue::Catalog", + desiredState: $jsonStringify({ + Name: glueCatalogName, + Description: "Federated catalog for S3 Tables", + FederatedCatalog: { + Identifier: s3TablesBucketWildcardArn, + ConnectionName: "aws:s3tables", + }, + CreateDatabaseDefaultPermissions: [ + { + Principal: { + DataLakePrincipalIdentifier: "IAM_ALLOWED_PRINCIPALS", + }, + Permissions: ["ALL"], + }, + ], + CreateTableDefaultPermissions: [ + { + Principal: { + DataLakePrincipalIdentifier: "IAM_ALLOWED_PRINCIPALS", + }, + Permissions: ["ALL"], + }, + ], + AllowFullTableExternalDataAccess: "True", + }), + }, + { dependsOn: [tableBucket] }, +) + +const athenaResultsBucket = new aws.s3.Bucket("LakeAthenaResults", { + bucket: `opencode-${$app.stage}-lake-athena-results`, + forceDestroy: $app.stage !== "production", +}) + +const firehoseErrorBucket = new aws.s3.Bucket("LakeFirehoseErrors", { + bucket: `opencode-${$app.stage}-lake-firehose-errors`, + forceDestroy: $app.stage !== "production", +}) + +const athenaWorkgroup = new aws.athena.Workgroup("LakeAthenaWorkgroup", { + name: `opencode-${$app.stage}-lake-workgroup`, + forceDestroy: $app.stage !== "production", + configuration: { + enforceWorkgroupConfiguration: true, + publishCloudwatchMetricsEnabled: true, + resultConfiguration: { + outputLocation: $interpolate`s3://${athenaResultsBucket.bucket}/`, + }, + }, +}) + +const firehoseRole = new aws.iam.Role("LakeFirehoseRole", { + assumeRolePolicy: aws.iam.getPolicyDocumentOutput({ + statements: [ + { + effect: "Allow", + actions: ["sts:AssumeRole"], + principals: [ + { + type: "Service", + identifiers: ["firehose.amazonaws.com"], + }, + ], + }, + ], + }).json, +}) + +const firehosePolicy = new aws.iam.RolePolicy("LakeFirehosePolicy", { + role: firehoseRole.id, + policy: aws.iam.getPolicyDocumentOutput({ + statements: [ + { + effect: "Allow", + actions: [ + "s3tables:ListTableBuckets", + "s3tables:GetTableBucket", + "s3tables:GetNamespace", + "s3tables:GetTable", + "s3tables:GetTableData", + "s3tables:GetTableMetadataLocation", + "s3tables:ListNamespaces", + "s3tables:ListTables", + "s3tables:PutTableData", + "s3tables:UpdateTableMetadataLocation", + ], + resources: ["*"], + }, + { + effect: "Allow", + actions: [ + "glue:GetCatalog", + "glue:GetCatalogs", + "glue:GetDatabase", + "glue:GetDatabases", + "glue:GetTable", + "glue:GetTables", + "glue:UpdateTable", + ], + resources: [ + glueCatalogArn, + glueS3TablesCatalogArn, + $interpolate`${glueS3TablesCatalogArn}/*`, + glueS3TablesDatabaseWildcardArn, + glueS3TablesTableWildcardArn, + $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:database/*`, + $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:table/*/*`, + $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:table/${glueCatalogName}/*`, + ], + }, + { + effect: "Allow", + actions: [ + "s3:AbortMultipartUpload", + "s3:GetBucketLocation", + "s3:GetObject", + "s3:ListBucket", + "s3:ListBucketMultipartUploads", + "s3:PutObject", + ], + resources: [firehoseErrorBucket.arn, $interpolate`${firehoseErrorBucket.arn}/*`], + }, + { + effect: "Allow", + actions: ["lakeformation:GetDataAccess"], + resources: ["*"], + }, + ], + }).json, +}) + +const firehose = new aws.kinesis.FirehoseDeliveryStream( + "LakeFirehose", + { + name: `opencode-${$app.stage}-lake-ingest`, + destination: "iceberg", + icebergConfiguration: { + appendOnly: true, + bufferingInterval: 60, + bufferingSize: 1, + catalogArn: glueS3TablesChildCatalogArn, + processingConfiguration: { + enabled: true, + processors: [ + { + type: "MetadataExtraction", + parameters: [ + { parameterName: "JsonParsingEngine", parameterValue: "JQ-1.6" }, + { + parameterName: "MetadataExtractionQuery", + parameterValue: + '{destinationDatabaseName:._lake_database,destinationTableName:._lake_table,operation:(._lake_operation // "insert")}', + }, + ], + }, + ], + }, + roleArn: firehoseRole.arn, + s3BackupMode: "FailedDataOnly", + s3Configuration: { + roleArn: firehoseRole.arn, + bucketArn: firehoseErrorBucket.arn, + errorOutputPrefix: "errors/!{firehose:error-output-type}/", + }, + }, + }, + { dependsOn: [s3TablesCatalog, firehosePolicy] }, +) + +export const lakeVpc = new sst.aws.Vpc("LakeVpc") +export const lakeCluster = new sst.aws.Cluster("LakeCluster", { vpc: lakeVpc }) +export const lakeRegion = region.region +export const lakeCatalog = $interpolate`${glueCatalogName}/${tableBucket.name}` +export const lakeAthenaWorkgroup = athenaWorkgroup + +const ingestSecret = new random.RandomPassword("LakeIngestSecret", { length: 32 }) + +const ingestConfig = new sst.Linkable("LakeIngestConfig", { + properties: { + streamName: firehose.name, + secret: ingestSecret.result, + }, +}) + +const ingestService = new sst.aws.Service("LakeIngestService", { + cluster: lakeCluster, + architecture: "arm64", + cpu: "1 vCPU", + memory: "4 GB", + image: { + context: ".", + dockerfile: "packages/stats/server/Dockerfile", + }, + link: [ingestConfig], + permissions: [ + { + actions: ["firehose:PutRecord", "firehose:PutRecordBatch"], + resources: [firehose.arn], + }, + ], + scaling: { + min: $app.stage === "production" ? 2 : 1, + max: $app.stage === "production" ? 32 : 4, + cpuUtilization: 60, + memoryUtilization: 70, + }, + loadBalancer: { + domain: { + name: `lake.${domain}`, + dns: sst.cloudflare.dns(), + }, + rules: [ + { listen: "80/http", redirect: "443/https" }, + { listen: "443/https", forward: "3000/http" }, + ], + health: { + "3000/http": { + path: "/ready", + successCodes: "200-299", + }, + }, + }, + health: { + command: [ + "CMD-SHELL", + "bun --eval \"fetch('http://localhost:3000/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))\"", + ], + interval: "30 seconds", + retries: 3, + startPeriod: "30 seconds", + timeout: "5 seconds", + }, + dev: { + command: "bun run start", + directory: "packages/stats/server", + url: "http://localhost:3000", + }, + wait: $app.stage === "production", +}) + +export const lakeIngest = new sst.Linkable("LakeIngest", { + properties: { + url: ingestService.url, + secret: ingestSecret.result, + }, +}) + +export const lakeQueryPermissions = [ + { + actions: ["athena:StartQueryExecution", "athena:GetQueryExecution", "athena:GetQueryResults"], + resources: [athenaWorkgroup.arn], + }, + { + actions: [ + "glue:GetCatalog", + "glue:GetCatalogs", + "glue:GetDatabase", + "glue:GetDatabases", + "glue:GetTable", + "glue:GetTables", + "glue:GetPartitions", + ], + resources: [ + glueCatalogArn, + glueS3TablesCatalogArn, + $interpolate`${glueS3TablesCatalogArn}/*`, + glueS3TablesDatabaseWildcardArn, + glueS3TablesTableWildcardArn, + $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:database/*`, + $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:table/*/*`, + $interpolate`arn:${partition.partition}:glue:${region.region}:${current.accountId}:table/${glueCatalogName}/*`, + ], + }, + { + actions: ["s3:GetBucketLocation", "s3:ListBucket"], + resources: [athenaResultsBucket.arn], + }, + { + actions: ["s3:GetObject", "s3:PutObject", "s3:AbortMultipartUpload", "s3:ListBucketMultipartUploads"], + resources: [$interpolate`${athenaResultsBucket.arn}/*`], + }, + { + actions: [ + "s3tables:GetTableBucket", + "s3tables:GetNamespace", + "s3tables:GetTable", + "s3tables:GetTableData", + "s3tables:GetTableMetadataLocation", + "s3tables:ListNamespaces", + "s3tables:ListTables", + ], + resources: ["*"], + }, + { + actions: ["lakeformation:GetDataAccess"], + resources: ["*"], + }, +] diff --git a/infra/secret.ts b/infra/secret.ts index eafbd91ed293..65ada2f1f64d 100644 --- a/infra/secret.ts +++ b/infra/secret.ts @@ -7,6 +7,7 @@ sst.Linkable.wrap(random.RandomPassword, (resource) => ({ export const SECRET = { R2AccessKey: new sst.Secret("R2AccessKey", "unknown"), R2SecretKey: new sst.Secret("R2SecretKey", "unknown"), + HoneycombApiKey: new sst.Secret("HONEYCOMB_API_KEY"), HoneycombWebhookSecret: new random.RandomPassword("HoneycombWebhookSecret", { length: 24 }), UpstashRedisRestUrl: new sst.Secret("UpstashRedisRestUrl"), UpstashRedisRestToken: new sst.Secret("UpstashRedisRestToken"), diff --git a/infra/stage.ts b/infra/stage.ts index f9a6fd75529c..8d80eefed880 100644 --- a/infra/stage.ts +++ b/infra/stage.ts @@ -5,6 +5,8 @@ export const domain = (() => { })() export const zoneID = "430ba34c138cfb5360826c4909f99be8" +export const awsStage = $app.stage === "production" ? "production" : "dev" +export const deployAws = $app.stage === awsStage new cloudflare.RegionalHostname("RegionalHostname", { hostname: domain, diff --git a/infra/stats.ts b/infra/stats.ts new file mode 100644 index 000000000000..107e8b9f2335 --- /dev/null +++ b/infra/stats.ts @@ -0,0 +1,208 @@ +import { lakeAthenaWorkgroup, lakeCatalog, lakeCluster, lakeQueryPermissions, lakeRegion, tableBucket } from "./lake" +import { EMAILOCTOPUS_API_KEY } from "./app" + +const domain = (() => { + if ($app.stage === "production") return "stats.opencode.ai" + if ($app.stage === "dev") return "stats.dev.opencode.ai" + return `stats.${$app.stage}.dev.opencode.ai` +})() + +//////////////// +// LAKE +//////////////// + +const inferenceNamespace = new aws.s3tables.Namespace("LakeInferenceNamespace", { + namespace: "inference", + tableBucketArn: tableBucket.arn, +}) + +const inferenceEventTable = new aws.s3tables.Table( + "LakeInferenceEventTable", + { + name: "event", + namespace: inferenceNamespace.namespace, + tableBucketArn: inferenceNamespace.tableBucketArn, + format: "ICEBERG", + metadata: { + iceberg: { + schema: { + fields: [ + { name: "event_timestamp", type: "string", required: false }, + { name: "event_date", type: "string", required: false }, + { name: "event_type", type: "string", required: false }, + { name: "dataset", type: "string", required: false }, + { name: "cf_continent", type: "string", required: false }, + { name: "cf_country", type: "string", required: false }, + { name: "cf_city", type: "string", required: false }, + { name: "cf_region", type: "string", required: false }, + { name: "cf_latitude", type: "double", required: false }, + { name: "cf_longitude", type: "double", required: false }, + { name: "cf_timezone", type: "string", required: false }, + { name: "duration", type: "double", required: false }, + { name: "request_length", type: "long", required: false }, + { name: "status", type: "int", required: false }, + { name: "ip", type: "string", required: false }, + { name: "is_stream", type: "boolean", required: false }, + { name: "session", type: "string", required: false }, + { name: "request", type: "string", required: false }, + { name: "client", type: "string", required: false }, + { name: "user_agent", type: "string", required: false }, + { name: "model_variant", type: "string", required: false }, + { name: "source", type: "string", required: false }, + { name: "provider", type: "string", required: false }, + { name: "provider_model", type: "string", required: false }, + { name: "model", type: "string", required: false }, + { name: "llm_error_code", type: "int", required: false }, + { name: "llm_error_message", type: "string", required: false }, + { name: "error_response", type: "string", required: false }, + { name: "error_type", type: "string", required: false }, + { name: "error_message", type: "string", required: false }, + { name: "error_cause", type: "string", required: false }, + { name: "error_cause2", type: "string", required: false }, + { name: "api_key", type: "string", required: false }, + { name: "workspace", type: "string", required: false }, + { name: "is_subscription", type: "boolean", required: false }, + { name: "subscription", type: "string", required: false }, + { name: "response_length", type: "long", required: false }, + { name: "time_to_first_byte", type: "long", required: false }, + { name: "timestamp_first_byte", type: "long", required: false }, + { name: "timestamp_last_byte", type: "long", required: false }, + { name: "tokens_input", type: "long", required: false }, + { name: "tokens_output", type: "long", required: false }, + { name: "tokens_reasoning", type: "long", required: false }, + { name: "tokens_cache_read", type: "long", required: false }, + { name: "tokens_cache_write_5m", type: "long", required: false }, + { name: "tokens_cache_write_1h", type: "long", required: false }, + { name: "cost_input_microcents", type: "long", required: false }, + { name: "cost_output_microcents", type: "long", required: false }, + { name: "cost_cache_read_microcents", type: "long", required: false }, + { name: "cost_cache_write_microcents", type: "long", required: false }, + { name: "cost_total_microcents", type: "long", required: false }, + { name: "cost_input", type: "long", required: false }, + { name: "cost_output", type: "long", required: false }, + { name: "cost_cache_read", type: "long", required: false }, + { name: "cost_cache_write_5m", type: "long", required: false }, + { name: "cost_cache_write_1h", type: "long", required: false }, + { name: "cost_total", type: "long", required: false }, + ], + }, + }, + }, + }, + { deleteBeforeReplace: $app.stage !== "production" }, +) + +export const inferenceEvent = new sst.Linkable("InferenceEvent", { + properties: { + region: lakeRegion, + catalog: lakeCatalog, + database: inferenceNamespace.namespace, + table: inferenceEventTable.name, + tableBucket: tableBucket.name, + workgroup: lakeAthenaWorkgroup.name, + }, +}) + +//////////////// +// DATABASE +//////////////// + +const cluster = planetscale.getDatabaseOutput({ + name: "opencode-stats", + organization: "anomalyco", +}) + +const branch = + $app.stage === "production" + ? planetscale.getBranchOutput({ + name: "production", + organization: cluster.organization, + database: cluster.name, + }) + : new planetscale.Branch("StatsDatabaseBranch", { + database: cluster.name, + organization: cluster.organization, + name: $app.stage, + parentBranch: "production", + }) + +const password = new planetscale.Password("StatsDatabasePassword", { + name: $app.stage, + database: cluster.name, + organization: cluster.organization, + branch: branch.name, +}) + +const databaseUrl = $interpolate`mysql://${password.username.apply(encodeURIComponent)}:${password.plaintext.apply( + encodeURIComponent, +)}@${password.accessHostUrl}/${cluster.name}` + +export const database = new sst.Linkable("StatsDatabase", { + properties: { + host: password.accessHostUrl, + database: cluster.name, + username: password.username, + password: password.plaintext, + port: 3306, + url: databaseUrl, + }, +}) + +new sst.x.DevCommand("StatsStudio", { + link: [database], + environment: { + DATABASE_URL: databaseUrl, + }, + dev: { + command: "bun db:studio", + directory: "packages/stats/core", + autostart: false, + }, +}) + +//////////////// +// APP +//////////////// + +export const app = new sst.cloudflare.x.SolidStart("Stats", { + path: "packages/stats/app", + buildCommand: "bun run build", + domain, + link: [database, EMAILOCTOPUS_API_KEY], + environment: { + PUBLIC_URL: `https://${domain}/stats`, + }, +}) + +//////////////// +// SERVICES +//////////////// + +const statsSyncConfig = new sst.Linkable("StatsSyncConfig", { + properties: { + dataset: "zen", + }, +}) + +export const statSync = new sst.aws.Service("StatsSyncService", { + cluster: lakeCluster, + architecture: "arm64", + cpu: "0.25 vCPU", + memory: "0.5 GB", + image: { + context: ".", + dockerfile: "packages/stats/server/Dockerfile", + }, + command: ["bun", "src/stat-sync.ts"], + link: [database, inferenceEvent, statsSyncConfig], + permissions: lakeQueryPermissions, + scaling: { + min: 1, + max: 1, + }, + dev: { + command: "bun src/stat-sync.ts", + directory: "packages/stats/server", + autostart: false, + }, +}) diff --git a/nix/hashes.json b/nix/hashes.json index 8578dab16a33..c4fa68084530 100644 --- a/nix/hashes.json +++ b/nix/hashes.json @@ -1,8 +1,8 @@ { "nodeModules": { - "x86_64-linux": "sha256-Wdo61RItv595JUIh3ElBXtj0B4y2KpsAJ2WbNNBsO1E=", - "aarch64-linux": "sha256-lVNN5fqBj+qxmxN/NiDxZF3kaJ4wDD1ZCylh7yuS1PA=", - "aarch64-darwin": "sha256-1NXdnraknHeLyzSCSKYyG4W86KLwn8hCqHkaLfhLdzM=", - "x86_64-darwin": "sha256-UVupTsKwLnJ2E0IBx9/JraBJ4U6O1obI/OR3RE64/jU=" + "x86_64-linux": "sha256-51jxaHLvv2Staz9NN9N4EYoNmr2fZeDvfKZ5enf/Wx0=", + "aarch64-linux": "sha256-oGMMlgSJx7Yw5qN6LOquCD/K8GPLy4kDo34AOJGmcso=", + "aarch64-darwin": "sha256-j7IvnyY8Cj4a509D85i+FgfsyQiBstxagvVWMp6y5hI=", + "x86_64-darwin": "sha256-Dd36AN6LopLNV79d7i9lGz5kKOuv6mk1YyBlmdcIhZY=" } } diff --git a/package.json b/package.json index b17d55b3f198..8f156a0b2538 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "dev:desktop": "bun --cwd packages/desktop dev", "dev:web": "bun --cwd packages/app dev", "dev:console": "ulimit -n 10240 2>/dev/null; bun run --cwd packages/console/app dev", + "dev:stats": "bun sst shell --stage=production -- bun run --cwd packages/stats/app dev", "dev:storybook": "bun --cwd packages/storybook storybook", "lint": "oxlint", "typecheck": "bun turbo typecheck", @@ -19,12 +20,14 @@ "random": "echo 'Random script'", "hello": "echo 'Hello World!'", "release": "OPENCODE_CHANNEL=latest OPENCODE_VERSION=$(npm view lashcode version 2>/dev/null | awk -F. '{print $1\".\"$2\".\"$3+1}') bun run script/release-lash.ts", + "sso": "aws sso login --sso-session=opencode --no-browser", "test": "echo 'do not run tests from root' && exit 1" }, "workspaces": { "packages": [ "packages/*", "packages/console/*", + "packages/stats/*", "packages/sdk/js", "packages/slack" ], @@ -37,9 +40,9 @@ "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@hono/zod-validator": "0.4.2", - "@opentui/core": "0.2.15", - "@opentui/keymap": "0.2.15", - "@opentui/solid": "0.2.15", + "@opentui/core": "0.3.1", + "@opentui/keymap": "0.3.1", + "@opentui/solid": "0.3.1", "ulid": "3.0.1", "@kobalte/core": "0.13.11", "@types/luxon": "3.7.1", @@ -73,6 +76,7 @@ "@typescript/native-preview": "7.0.0-dev.20251207.1", "zod": "4.1.8", "remeda": "2.26.0", + "sst": "4.13.1", "shiki": "3.20.0", "solid-list": "0.3.0", "tailwindcss": "4.1.11", @@ -85,7 +89,7 @@ "@sentry/vite-plugin": "4.6.0", "solid-js": "1.9.10", "vite-plugin-solid": "2.11.10", - "@lydell/node-pty": "1.2.0-beta.10" + "@lydell/node-pty": "1.2.0-beta.12" } }, "devDependencies": { @@ -99,7 +103,7 @@ "oxlint-tsgolint": "0.21.0", "prettier": "3.6.2", "semver": "^7.6.0", - "sst": "4.13.1", + "sst": "catalog:", "turbo": "2.8.13" }, "dependencies": { @@ -142,7 +146,8 @@ "@standard-community/standard-openapi@0.2.9": "patches/@standard-community%2Fstandard-openapi@0.2.9.patch", "solid-js@1.9.10": "patches/solid-js@1.9.10.patch", "virtua@0.49.1": "patches/virtua@0.49.1.patch", - "@ai-sdk/xai@3.0.82": "patches/@ai-sdk%2Fxai@3.0.82.patch" + "@ai-sdk/xai@3.0.82": "patches/@ai-sdk%2Fxai@3.0.82.patch", + "gcp-metadata@8.1.2": "patches/gcp-metadata@8.1.2.patch" }, "funding": [ { diff --git a/packages/app/e2e/regression/session-list-path-loading.spec.ts b/packages/app/e2e/regression/session-list-path-loading.spec.ts new file mode 100644 index 000000000000..1dbc0575f15b --- /dev/null +++ b/packages/app/e2e/regression/session-list-path-loading.spec.ts @@ -0,0 +1,40 @@ +import { expect, test } from "@playwright/test" +import { fixture, pageMessages } from "../smoke/session-timeline.fixture" +import { mockOpenCodeServer } from "../utils/mock-server" + +test("shows loaded sessions before the directory path request resolves", async ({ page }) => { + await mockOpenCodeServer(page, { + sessions: fixture.sessions, + provider: fixture.provider, + directory: fixture.directory, + project: fixture.project, + pageMessages, + }) + + let releasePath!: () => void + const pathBlocked = new Promise((resolve) => { + releasePath = resolve + }) + await page.route("**/path?*", async (route) => { + if (!new URL(route.request().url()).searchParams.has("directory")) return route.fallback() + await pathBlocked + return route.fallback() + }) + + await page.addInitScript((directory) => { + localStorage.setItem( + "opencode.global.dat:server", + JSON.stringify({ + projects: { local: [{ worktree: directory, expanded: true }] }, + lastProject: { local: directory }, + }), + ) + }, fixture.directory) + + await page.goto("/") + try { + await expect(page.getByText(fixture.expected.sourceTitle).first()).toBeVisible({ timeout: 5_000 }) + } finally { + releasePath() + } +}) diff --git a/packages/app/e2e/regression/session-timeline-collapse-state.spec.ts b/packages/app/e2e/regression/session-timeline-collapse-state.spec.ts index db191d2575fd..88b140a61dba 100644 --- a/packages/app/e2e/regression/session-timeline-collapse-state.spec.ts +++ b/packages/app/e2e/regression/session-timeline-collapse-state.spec.ts @@ -1,4 +1,5 @@ -import { expect, test, type Locator, type Page, type Route } from "@playwright/test" +import { expect, test, type Locator, type Page } from "@playwright/test" +import { mockOpenCodeServer } from "../utils/mock-server" const directory = "C:/OpenCode/TimelineStateRegression" const projectID = "proj_timeline_state_regression" @@ -299,39 +300,13 @@ function readExpanded(element: Element) { } async function mockServer(page: Page, events: EventPayload[]) { - await page.route("**/*", async (route) => { - const url = new URL(route.request().url()) - const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096" - if (url.port !== targetPort) return route.fallback() - - const path = url.pathname - if (path === "/global/event") return sse(route, events.splice(0)) - if ( - path === "/global/config" || - path === "/config" || - path === "/provider/auth" || - path === "/mcp" || - path === "/session/status" - ) - return json(route, {}) - if ( - ["/skill", "/command", "/lsp", "/formatter", "/permission", "/question", "/vcs/status", "/vcs/diff"].includes( - path, - ) - ) - return json(route, []) - if (path === "/provider") return json(route, provider()) - if (path === "/path") - return json(route, { state: directory, config: directory, worktree: directory, directory, home: "C:/OpenCode" }) - if (path === "/project") return json(route, [project()]) - if (path === "/project/current") return json(route, project()) - if (path === "/agent") return json(route, [{ name: "build", mode: "primary" }]) - if (path === "/vcs") return json(route, { branch: "main", default_branch: "main" }) - if (path === "/session") return json(route, [session()]) - if (path === `/session/${sessionID}`) return json(route, session()) - if (/^\/session\/[^/]+\/(children|todo|diff)$/.test(path)) return json(route, []) - if (path === `/session/${sessionID}/message`) return json(route, [userMessage, assistantMessage]) - return json(route, {}) + await mockOpenCodeServer(page, { + directory, + project: project(), + provider: provider(), + sessions: [session()], + pageMessages: () => ({ items: [userMessage, assistantMessage] }), + events: () => events.splice(0), }) } @@ -372,24 +347,6 @@ function provider() { } } -function json(route: Route, body: unknown, headers?: Record) { - return route.fulfill({ - status: 200, - contentType: "application/json", - headers: { "access-control-allow-origin": "*", "access-control-expose-headers": "x-next-cursor", ...headers }, - body: JSON.stringify(body ?? null), - }) -} - -function sse(route: Route, events: EventPayload[]) { - return route.fulfill({ - status: 200, - contentType: "text/event-stream", - headers: { "access-control-allow-origin": "*" }, - body: events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), - }) -} - function base64Encode(value: string) { return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "") } diff --git a/packages/app/e2e/regression/session-timeline-context-resize.spec.ts b/packages/app/e2e/regression/session-timeline-context-resize.spec.ts index 98f34b2b9ca6..dc72e24f0df9 100644 --- a/packages/app/e2e/regression/session-timeline-context-resize.spec.ts +++ b/packages/app/e2e/regression/session-timeline-context-resize.spec.ts @@ -1,4 +1,5 @@ -import { expect, test, type Page, type Route } from "@playwright/test" +import { expect, test, type Page } from "@playwright/test" +import { mockOpenCodeServer } from "../utils/mock-server" const directory = "C:/OpenCode/ContextResizeRegression" const projectID = "proj_context_resize_regression" @@ -207,33 +208,12 @@ function contextTool(partID: string, messageID: string, tool: string, input: Rec } async function mockServer(page: Page) { - await page.route("**/*", async (route) => { - const url = new URL(route.request().url()) - const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096" - if (url.port !== targetPort) return route.fallback() - - const path = url.pathname - if (path === "/global/event" || path === "/event") return sse(route) - if (["/global/config", "/config", "/provider/auth", "/mcp", "/session/status"].includes(path)) - return json(route, {}) - if ( - ["/skill", "/command", "/lsp", "/formatter", "/permission", "/question", "/vcs/status", "/vcs/diff"].includes( - path, - ) - ) - return json(route, []) - if (path === "/provider") return json(route, provider()) - if (path === "/path") - return json(route, { state: directory, config: directory, worktree: directory, directory, home: "C:/OpenCode" }) - if (path === "/project") return json(route, [project()]) - if (path === "/project/current") return json(route, project()) - if (path === "/agent") return json(route, [{ name: "build", mode: "primary" }]) - if (path === "/vcs") return json(route, { branch: "main", default_branch: "main" }) - if (path === "/session") return json(route, [session()]) - if (path === `/session/${sessionID}`) return json(route, session()) - if (/^\/session\/[^/]+\/(children|todo|diff)$/.test(path)) return json(route, []) - if (path === `/session/${sessionID}/message`) return json(route, messages) - return json(route, {}) + await mockOpenCodeServer(page, { + directory, + project: project(), + provider: provider(), + sessions: [session()], + pageMessages: () => ({ items: messages }), }) } @@ -282,19 +262,6 @@ function provider() { } } -function json(route: Route, body: unknown, headers?: Record) { - return route.fulfill({ - status: 200, - contentType: "application/json", - headers: { "access-control-allow-origin": "*", "access-control-expose-headers": "x-next-cursor", ...headers }, - body: JSON.stringify(body ?? null), - }) -} - -function sse(route: Route) { - return route.fulfill({ status: 200, contentType: "text/event-stream", body: ": ok\n\n" }) -} - function base64Encode(value: string) { return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "") } diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index b89f46deea61..9a03a9d5adb1 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -18,6 +18,7 @@ export interface MockServerConfig { project: unknown sessions: ({ id: string } & Record)[] pageMessages: (sessionId: string, limit: number, before?: string) => { items: unknown[]; cursor?: string } + events?: () => unknown[] } export async function mockOpenCodeServer(page: Page, config: MockServerConfig) { @@ -43,7 +44,8 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) { if (url.port !== targetPort) return route.fallback() const path = url.pathname - if (path === "/global/event" || path === "/event") return sse(route) + if (path === "/global/event" || path === "/event") return sse(route, config.events?.()) + if (path === "/global/health") return json(route, { healthy: true }) if (emptyObject.has(path)) return json(route, {}) if (emptyList.has(path)) return json(route, []) if (path in staticRoutes) return json(route, staticRoutes[path]) @@ -81,6 +83,10 @@ function json(route: Route, body: unknown, headers?: Record) { }) } -function sse(route: Route) { - return route.fulfill({ status: 200, contentType: "text/event-stream", body: ": ok\n\n" }) +function sse(route: Route, events?: unknown[]) { + return route.fulfill({ + status: 200, + contentType: "text/event-stream", + body: events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n", + }) } diff --git a/packages/app/public/assets/Inter.ttf b/packages/app/public/assets/Inter.ttf new file mode 100644 index 000000000000..e31b51e3e938 Binary files /dev/null and b/packages/app/public/assets/Inter.ttf differ diff --git a/packages/app/src/app.tsx b/packages/app/src/app.tsx index 339cda8edfbd..9554a6363112 100644 --- a/packages/app/src/app.tsx +++ b/packages/app/src/app.tsx @@ -14,6 +14,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/solid-query" import { Effect } from "effect" import { type Component, + createEffect, createMemo, createResource, createSignal, @@ -40,12 +41,13 @@ import { NotificationProvider } from "@/context/notification" import { PermissionProvider } from "@/context/permission" import { PromptProvider } from "@/context/prompt" import { ServerConnection, ServerProvider, serverName, useServer } from "@/context/server" -import { SettingsProvider } from "@/context/settings" +import { SettingsProvider, useSettings } from "@/context/settings" import { TerminalProvider } from "@/context/terminal" import DirectoryLayout from "@/pages/directory-layout" import Layout from "@/pages/layout" import { ErrorPage } from "./pages/error" import { useCheckServerHealth } from "./utils/server-health" +import { ServersProvider } from "./context/servers" const HomeRoute = lazy(() => import("@/pages/home")) const Session = lazy(() => import("@/pages/session")) @@ -91,9 +93,26 @@ function QueryProvider(props: ParentProps) { return {props.children} } +function BodyDesignClass() { + const settings = useSettings() + + createEffect(() => { + if (typeof document === "undefined") return + + const enabled = settings.general.newLayoutDesigns() + document.body.classList.toggle("text-12-regular", !enabled) + document.body.classList.toggle("font-(family-name:--font-family-text)", enabled) + document.body.classList.toggle("text-[13px]", enabled) + document.body.classList.toggle("font-[440]", enabled) + }) + + return null +} + function AppShellProviders(props: ParentProps) { return ( + @@ -296,31 +315,29 @@ export function AppInterface(props: { disableHealthCheck?: boolean }) { return ( - - - - - - - {routerProps.children}} - > - - - } /> - - - - - - - - + + + + + + + + {routerProps.children}} + > + + + } /> + + + + + + + + + ) } diff --git a/packages/app/src/components/prompt-input.tsx b/packages/app/src/components/prompt-input.tsx index a087c366e726..84fe7495f874 100644 --- a/packages/app/src/components/prompt-input.tsx +++ b/packages/app/src/components/prompt-input.tsx @@ -4,6 +4,8 @@ import { createEffect, on, Component, + splitProps, + For, Show, onCleanup, createMemo, @@ -11,7 +13,10 @@ import { createResource, Switch, Match, + type ComponentProps, + type JSX, } from "solid-js" +import { Popover as KobaltePopover } from "@kobalte/core/popover" import { createStore } from "solid-js/store" import { useLocal } from "@/context/local" import { selectionFromLines, type SelectedLineRange, useFile } from "@/context/file" @@ -26,12 +31,14 @@ import { FileAttachmentPart, } from "@/context/prompt" import { useLayout } from "@/context/layout" +import { useNavigate } from "@solidjs/router" import { useSDK } from "@/context/sdk" +import { useServer } from "@/context/server" import { useSync } from "@/context/sync" import { useComments } from "@/context/comments" import { Button } from "@opencode-ai/ui/button" import { DockShellForm, DockTray } from "@opencode-ai/ui/dock-surface" -import { Icon } from "@opencode-ai/ui/icon" +import { Icon, type IconProps } from "@opencode-ai/ui/icon" import { ProviderIcon } from "@opencode-ai/ui/provider-icon" import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip" import { IconButton } from "@opencode-ai/ui/icon-button" @@ -44,6 +51,7 @@ import { Persist, persisted } from "@/utils/persist" import { usePermission } from "@/context/permission" import { useLanguage } from "@/context/language" import { usePlatform } from "@/context/platform" +import { useSettings } from "@/context/settings" import { useSessionLayout } from "@/pages/session/session-layout" import { createSessionTabs } from "@/pages/session/helpers" import { createTextFragment, getCursorPosition, setCursorPosition, setRangeEdge } from "./prompt-input/editor-dom" @@ -68,14 +76,14 @@ import { ImagePreview } from "@opencode-ai/ui/image-preview" import { useQueries } from "@tanstack/solid-query" import { useQueryOptions } from "@/context/server-sync" import { pathKey } from "@/utils/path-key" -import { getFilename } from "@opencode-ai/core/util/path" +import { base64Encode } from "@opencode-ai/core/util/encode" +import { displayName } from "@/pages/layout/helpers" interface PromptInputProps { class?: string variant?: "dock" | "new-session" ref?: (el: HTMLDivElement) => void newSessionWorktree?: string - onNewSessionWorktreeChange?: (worktree: string) => void onNewSessionWorktreeReset?: () => void edit?: { id: string; prompt: Prompt; context: FollowupDraft["context"] } onEditLoaded?: () => void @@ -113,11 +121,9 @@ const EXAMPLES = [ "prompt.example.25", ] as const -const MAIN_WORKTREE = "main" -const CREATE_WORKTREE = "create" - export const PromptInput: Component = (props) => { const sdk = useSDK() + const navigate = useNavigate() const queryOptions = useQueryOptions() const sync = useSync() @@ -125,6 +131,7 @@ export const PromptInput: Component = (props) => { const files = useFile() const prompt = usePrompt() const layout = useLayout() + const server = useServer() const comments = useComments() const dialog = useDialog() const providers = useProviders() @@ -132,11 +139,13 @@ export const PromptInput: Component = (props) => { const permission = usePermission() const language = useLanguage() const platform = usePlatform() + const settings = useSettings() const { params, tabs, view } = useSessionLayout() let editorRef!: HTMLDivElement let fileInputRef: HTMLInputElement | undefined let scrollRef!: HTMLDivElement let slashPopoverRef!: HTMLDivElement + let projectSearchRef: HTMLInputElement | undefined const mirror = { input: false } const inset = 56 @@ -277,6 +286,10 @@ export const PromptInput: Component = (props) => { mode: "normal", applyingHistory: false, }) + const [picker, setPicker] = createStore({ + projectOpen: false, + projectSearch: "", + }) const buttonsSpring = useSpring(() => (store.mode === "normal" ? 1 : 0), { visualDuration: 0.2, bounce: 0 }) const motion = (value: number) => ({ @@ -1303,91 +1316,124 @@ export const PromptInput: Component = (props) => { return "Ask anything, / for commands, @ for context..." } - const modelControl = () => ( - - 0} - fallback={ - - - - } - > - - - - - - {local.model.current()?.name ?? language.t("dialog.model.select.title")} - - - - - - ) + const modelControlState = createMemo(() => ({ + loading: providersLoading(), + paid: providers.paid().length > 0, + title: language.t("command.model.choose"), + keybind: command.keybind("model.choose"), + model: local.model, + providerID: local.model.current()?.provider?.id, + modelName: local.model.current()?.name ?? language.t("dialog.model.select.title"), + style: control(), + onClose: restoreFocus, + onUnpaidClick: () => { + void import("@/components/dialog-select-model-unpaid").then((x) => { + dialog.show(() => ) + }) + }, + })) const newSession = () => props.variant === "new-session" - const worktrees = createMemo(() => [MAIN_WORKTREE, ...(sync.project?.sandboxes ?? []), CREATE_WORKTREE]) - const currentWorktree = createMemo(() => { - if (worktrees().includes(props.newSessionWorktree ?? MAIN_WORKTREE)) - return props.newSessionWorktree ?? MAIN_WORKTREE - return MAIN_WORKTREE + const projects = createMemo(() => layout.projects.list()) + const projectForDirectory = (directory: string | undefined) => { + if (!directory) return + const key = pathKey(directory) + return projects().find( + (project) => pathKey(project.worktree) === key || project.sandboxes?.some((sandbox) => pathKey(sandbox) === key), + ) + } + const selectedProject = createMemo(() => projectForDirectory(sdk.directory)) + const projectResults = createMemo(() => { + const search = picker.projectSearch.trim().toLowerCase() + if (!search) return projects() + return projects().filter((project) => displayName(project).toLowerCase().includes(search)) }) - const worktreeLabel = (value: string) => { - if (value === MAIN_WORKTREE) return MAIN_WORKTREE - if (value === CREATE_WORKTREE) return language.t("session.new.worktree.create") - return getFilename(value) + const showAgentControl = createMemo(() => settings.general.showCustomAgents() && agentNames().length > 0) + const selectProject = (worktree: string) => { + setPicker({ + projectOpen: false, + projectSearch: "", + }) + if (pathKey(worktree) === pathKey(selectedProject()?.worktree ?? "")) { + restoreFocus() + return + } + layout.projects.open(worktree) + server.projects.touch(worktree) + navigate(`/${base64Encode(worktree)}/session`) + } + const addProject = async () => { + const select = (result: string | string[] | null) => { + const directory = Array.isArray(result) ? result[0] : result + if (!directory) return + selectProject(directory) + } + if (platform.openDirectoryPickerDialog && server.isLocal()) { + select(await platform.openDirectoryPickerDialog({ title: language.t("command.project.open") })) + return + } + void import("@/components/dialog-select-directory").then((x) => { + dialog.show( + () => , + () => select(null), + ) + }) } - const USE_V2_INPUT = import.meta.env.VITE_OPENCODE_CHANNEL !== "prod" + const projectPickerState = createMemo(() => ({ + open: picker.projectOpen, + trigger: { + action: "prompt-project", + icon: "folder", + label: selectedProject() ? displayName(selectedProject()!) : language.t("session.new.project.new"), + class: "max-w-[203px]", + style: control(), + onPress: () => setPicker("projectOpen", true), + }, + search: picker.projectSearch, + searchPlaceholder: language.t("session.new.project.search"), + clearLabel: language.t("common.clear"), + items: projectResults().map((project) => ({ + icon: "folder", + label: displayName(project), + selected: selectedProject()?.worktree === project.worktree, + onSelect: () => selectProject(project.worktree), + })), + action: { + icon: "plus", + label: language.t("session.new.project.add"), + onSelect: () => { + setPicker("projectOpen", false) + void addProject() + }, + }, + onOpenChange: (open) => { + setPicker("projectOpen", open) + if (open) requestAnimationFrame(() => projectSearchRef?.focus()) + }, + onSearchInput: (value) => setPicker("projectSearch", value), + onSearchClear: () => setPicker("projectSearch", ""), + searchRef: (el) => (projectSearchRef = el), + })) + const agentControlState = createMemo(() => ({ + title: language.t("command.agent.cycle"), + keybind: command.keybind("agent.cycle"), + options: agentNames(), + current: local.agent.current()?.name ?? "", + style: control(), + onSelect: (value) => { + local.agent.set(value) + restoreFocus() + }, + })) + const newProjectTriggerState = createMemo(() => ({ + action: "prompt-project", + icon: "folder-add-left", + label: language.t("session.new.project.new"), + class: "max-w-[160px]", + style: control(), + onPress: () => void addProject(), + })) return (
@@ -1408,155 +1454,146 @@ export const PromptInput: Component = (props) => { t={(key) => language.t(key as Parameters[0])} /> - - - - { - const active = comments.active() - return !!item.commentID && item.commentID === active?.id && item.path === active?.file - }} - openComment={openComment} - remove={(item) => { - if (item.commentID) comments.remove(item.path, item.commentID) - prompt.context.remove(item.key) - }} - t={(key) => language.t(key as Parameters[0])} - /> - - dialog.show(() => ) - } - onRemove={removeAttachment} - removeLabel={language.t("prompt.attachment.remove")} - /> -
{ - const target = e.target - if (!(target instanceof HTMLElement)) return - if (target.closest('[data-action="prompt-attach"], [data-action="prompt-submit"]')) return - editorRef?.focus() + +
+ -
(scrollRef = el)}> -
{ - editorRef = el - props.ref?.(el) - }} - role="textbox" - aria-multiline="true" - aria-label={designPlaceholder()} - contenteditable="true" - autocapitalize={store.mode === "normal" ? "sentences" : "off"} - autocorrect={store.mode === "normal" ? "on" : "off"} - spellcheck={store.mode === "normal"} - inputMode="text" - // @ts-expect-error - autocomplete="off" - onInput={handleInput} - onPaste={handlePaste} - onCompositionStart={handleCompositionStart} - onCompositionEnd={handleCompositionEnd} - onBlur={handleBlur} - onKeyDown={handleKeyDown} - classList={{ - "select-text": true, - "min-h-[52px] w-full px-4 pt-4 pb-2 focus:outline-none whitespace-pre-wrap leading-5 text-[13px] font-[440] text-v2-text-text-faint [font-family:Inter,var(--font-family-sans)]": true, - "[&_[data-type=file]]:text-syntax-property": true, - "[&_[data-type=agent]]:text-syntax-type": true, - "font-mono!": store.mode === "shell", - }} - /> -
- {designPlaceholder()} + + { + const active = comments.active() + return !!item.commentID && item.commentID === active?.id && item.path === active?.file + }} + openComment={openComment} + remove={(item) => { + if (item.commentID) comments.remove(item.path, item.commentID) + prompt.context.remove(item.key) + }} + t={(key) => language.t(key as Parameters[0])} + /> + + dialog.show(() => ) + } + onRemove={removeAttachment} + removeLabel={language.t("prompt.attachment.remove")} + /> +
{ + const target = e.target + if (!(target instanceof HTMLElement)) return + if (target.closest('[data-action^="prompt-"]')) return + editorRef?.focus() + }} + > +
(scrollRef = el)}> +
{ + editorRef = el + props.ref?.(el) + }} + role="textbox" + aria-multiline="true" + aria-label={designPlaceholder()} + contenteditable="true" + autocapitalize={store.mode === "normal" ? "sentences" : "off"} + autocorrect={store.mode === "normal" ? "on" : "off"} + spellcheck={store.mode === "normal"} + inputMode="text" + // @ts-expect-error + autocomplete="off" + onInput={handleInput} + onPaste={handlePaste} + onCompositionStart={handleCompositionStart} + onCompositionEnd={handleCompositionEnd} + onBlur={handleBlur} + onKeyDown={handleKeyDown} + classList={{ + "select-text": true, + "min-h-[52px] w-full px-4 pt-4 pb-2 focus:outline-none whitespace-pre-wrap leading-5 text-[13px] font-[440] text-v2-text-text-base": true, + "[&_[data-type=file]]:text-syntax-property": true, + "[&_[data-type=agent]]:text-syntax-type": true, + "font-mono!": store.mode === "shell", + }} + /> +
+ {designPlaceholder()} +
-
-
-
- {fileAttachmentInput()} - +
+
+ {fileAttachmentInput()} + + + + + + + + + + +
+ - - -
-
- -
- props.state.onSearchInput(event.currentTarget.value)} + /> + + + +
+ {(item) => } +
+
+
+ +
+ + + + ) +} + +function ComposerAgentControl(props: { state: ComposerAgentControlState }) { + return ( +
+
+ +
+ + -
-
- -
- diff --git a/packages/console/app/src/routes/zen/util/handler.ts b/packages/console/app/src/routes/zen/util/handler.ts index 0434f9100baf..4438688c22fe 100644 --- a/packages/console/app/src/routes/zen/util/handler.ts +++ b/packages/console/app/src/routes/zen/util/handler.ts @@ -47,6 +47,7 @@ import { i18n, type Key } from "~/i18n" import { localeFromRequest } from "~/lib/language" import { createModelTpmLimiter } from "./modelTpmLimiter" import { createModelTpsLimiter } from "./modelTpsLimiter" +import { accumulateUsage, HOT_WORKSPACES } from "./usageBatcher" type ZenData = Awaited> type RetryOptions = { @@ -478,9 +479,9 @@ export async function handler( stickyId: string, trialProviders: string[] | undefined, retry: RetryOptions, - stickyProvider: string | undefined, + stickyProviderId: string | undefined, modelTpmLimits: Record | undefined, - modelTpsLimits: Record | undefined, + modelTpsLimits: Record | undefined, ) { const modelProvider = (() => { // Byok is top priority b/c if user set their own API key, we should use it @@ -489,22 +490,18 @@ export async function handler( return modelInfo.providers.find((provider) => provider.id === modelInfo.byokProvider) } - // Always use the same provider for the same session - if (stickyProvider) { - const provider = modelInfo.providers.find((provider) => provider.id === stickyProvider) - if (provider) return provider - } - + // Prioritize trial providers + let allProviders = modelInfo.providers.filter((provider) => !provider.disabled) if (trialProviders) { - const trialProvider = trialProviders[Math.floor(Math.random() * trialProviders.length)] - const provider = modelInfo.providers.find((provider) => provider.id === trialProvider) - if (provider) return provider + allProviders = allProviders.map((provider) => ({ + ...provider, + priority: trialProviders.includes(provider.id) ? 0 : provider.priority, + })) } if (retry.retryCount !== MAX_FAILOVER_RETRIES) { let topPriority = Infinity - const providers = modelInfo.providers - .filter((provider) => !provider.disabled) + const providers = allProviders .filter((provider) => provider.weight !== 0) .filter((provider) => !retry.excludeProviders.includes(provider.id)) .filter((provider) => { @@ -514,7 +511,11 @@ export async function handler( }) .filter((provider) => { if (!provider.tpsGoal) return true - const isLowTps = modelTpsLimits?.[`${provider.id}/${provider.model}/${provider.tpsGoal}`] ?? false + const tps = modelTpsLimits?.[`${provider.id}/${provider.model}/${provider.tpsGoal}`] ?? { + qualify: 0, + unqualify: 0, + } + const isLowTps = tps.qualify + tps.unqualify > 10 && tps.qualify < tps.unqualify return !isLowTps }) .map((provider) => { @@ -532,11 +533,27 @@ export async function handler( } const index = (h >>> 0) % providers.length // make unsigned + range 0..length-1 const provider = providers[index || 0] - if (provider) return provider + + // sticky provider does not exist => use selected provider + if (!stickyProviderId) return provider + const stickProvider = allProviders.find((provider) => provider.id === stickyProviderId) + if (!stickProvider) return provider + + // stick provider exists + selected provider is API type => use sticky provider + if (!provider.tpsGoal) return stickProvider + + // stick provier exists + selected provider is GPU type + GPU not idle => use selected provider + const tps = modelTpsLimits?.[`${provider.id}/${provider.model}/${provider.tpsGoal}`] ?? { + qualify: 0, + unqualify: 0, + } + if (tps.qualify <= tps.unqualify * 3) return stickProvider + + return provider } // fallback provider - return modelInfo.providers.find((provider) => provider.id === modelInfo.fallbackProvider) + return allProviders.find((provider) => provider.id === modelInfo.fallbackProvider) })() if (!modelProvider) throw new ModelError(t("zen.api.error.noProviderAvailable")) @@ -965,6 +982,19 @@ export async function handler( authInfo = authInfo! const cost = centsToMicroCents(totalCostInCent) + + // For hot workspaces, batch balance/usage updates through Redis to avoid + // row-level lock contention on BillingTable/UserTable. Returns the amount + // to flush this request, or null to skip the DB writes entirely. + const balanceFlush = await (async () => { + if (billingSource !== "subscription" && billingSource !== "lite" && HOT_WORKSPACES.has(authInfo.workspaceID)) { + const workspaceCost = billingSource === "free" || billingSource === "byok" ? 0 : cost + const flush = await accumulateUsage(authInfo.workspaceID, authInfo.user.id, workspaceCost, cost) + return { batched: true as const, flush } + } + return { batched: false as const, flush: null } + })() + await Database.use((db) => Promise.all([ db.insert(UsageTable).values({ @@ -988,10 +1018,6 @@ export async function handler( return undefined })(), }), - db - .update(KeyTable) - .set({ timeUsed: sql`now()` }) - .where(and(eq(KeyTable.workspaceID, authInfo.workspaceID), eq(KeyTable.id, authInfo.apiKeyId))), ...(() => { if (billingSource === "subscription") { const plan = authInfo.billing.subscription!.plan @@ -1070,18 +1096,22 @@ export async function handler( ] } + // Batched hot workspace: skip DB writes unless this request is the flush. + if (balanceFlush.batched && !balanceFlush.flush) return [] + + const workspaceDelta = balanceFlush.flush?.workspaceCost ?? cost + const userDelta = balanceFlush.flush?.userCost ?? cost + const balanceDelta = billingSource === "free" || billingSource === "byok" ? 0 : workspaceDelta + return [ db .update(BillingTable) .set({ - balance: - billingSource === "free" || billingSource === "byok" - ? sql`${BillingTable.balance} - ${0}` - : sql`${BillingTable.balance} - ${cost}`, + balance: sql`${BillingTable.balance} - ${balanceDelta}`, monthlyUsage: sql` CASE - WHEN MONTH(${BillingTable.timeMonthlyUsageUpdated}) = MONTH(now()) AND YEAR(${BillingTable.timeMonthlyUsageUpdated}) = YEAR(now()) THEN ${BillingTable.monthlyUsage} + ${cost} - ELSE ${cost} + WHEN MONTH(${BillingTable.timeMonthlyUsageUpdated}) = MONTH(now()) AND YEAR(${BillingTable.timeMonthlyUsageUpdated}) = YEAR(now()) THEN ${BillingTable.monthlyUsage} + ${workspaceDelta} + ELSE ${workspaceDelta} END `, timeMonthlyUsageUpdated: sql`now()`, @@ -1092,8 +1122,8 @@ export async function handler( .set({ monthlyUsage: sql` CASE - WHEN MONTH(${UserTable.timeMonthlyUsageUpdated}) = MONTH(now()) AND YEAR(${UserTable.timeMonthlyUsageUpdated}) = YEAR(now()) THEN ${UserTable.monthlyUsage} + ${cost} - ELSE ${cost} + WHEN MONTH(${UserTable.timeMonthlyUsageUpdated}) = MONTH(now()) AND YEAR(${UserTable.timeMonthlyUsageUpdated}) = YEAR(now()) THEN ${UserTable.monthlyUsage} + ${userDelta} + ELSE ${userDelta} END `, timeMonthlyUsageUpdated: sql`now()`, diff --git a/packages/console/app/src/routes/zen/util/ipRateLimiter.ts b/packages/console/app/src/routes/zen/util/ipRateLimiter.ts index 81f73a4e5ab3..7461fa631355 100644 --- a/packages/console/app/src/routes/zen/util/ipRateLimiter.ts +++ b/packages/console/app/src/routes/zen/util/ipRateLimiter.ts @@ -1,5 +1,3 @@ -import { Database, eq, and, sql, inArray } from "@opencode-ai/console-core/drizzle/index.js" -import { IpRateLimitTable } from "@opencode-ai/console-core/schema/ip.sql.js" import { FreeUsageLimitError } from "./error" import { logger } from "./logger" import { buildRateLimitKey, getRedis } from "./redis" @@ -22,7 +20,6 @@ export function createRateLimiter(modelId: string, rateLimit: number | undefined const ip = !rawIp.length ? "unknown" : rawIp const now = Date.now() - const lifetimeInterval = "" const dailyInterval = rateLimit ? `${buildYYYYMMDD(now)}${modelId.substring(0, 2)}` : buildYYYYMMDD(now) const retryAfter = getRetryAfterDay(now) const redis = getRedis() @@ -32,33 +29,12 @@ export function createRateLimiter(modelId: string, rateLimit: number | undefined return { check: async () => { - const [counts, rows] = await Promise.all([ - redis.mget<(string | number | null)[]>(isDefaultModel ? [lifetimeKey, dailyKey] : [dailyKey]).catch(() => []), - Database.use((tx) => - tx - .select({ interval: IpRateLimitTable.interval, count: IpRateLimitTable.count }) - .from(IpRateLimitTable) - .where( - and( - eq(IpRateLimitTable.ip, ip), - isDefaultModel - ? inArray(IpRateLimitTable.interval, [lifetimeInterval, dailyInterval]) - : inArray(IpRateLimitTable.interval, [dailyInterval]), - ), - ), - ), - ]) - const redisLifetimeCount = isDefaultModel ? Number(counts[0] ?? 0) : 0 - const redisDailyCount = Number(counts[isDefaultModel ? 1 : 0] ?? 0) - const databaseLifetimeCount = rows.find((r) => r.interval === lifetimeInterval)?.count ?? 0 - const databaseDailyCount = rows.find((r) => r.interval === dailyInterval)?.count ?? 0 - const lifetimeCount = Math.max(redisLifetimeCount, databaseLifetimeCount) - const dailyCount = Math.max(redisDailyCount, databaseDailyCount) + const counts = await redis.mget<(string | number | null)[]>(isDefaultModel ? [lifetimeKey, dailyKey] : [dailyKey]) + const lifetimeCount = isDefaultModel ? Number(counts[0] ?? 0) : 0 + const dailyCount = Number(counts[isDefaultModel ? 1 : 0] ?? 0) logger.debug(`rate limit lifetime: ${lifetimeCount}, daily: ${dailyCount}`) isNew = isDefaultModel && lifetimeCount < dailyLimit * 7 - if (isDefaultModel && databaseLifetimeCount > redisLifetimeCount) - await redis.set(lifetimeKey, databaseLifetimeCount).catch(() => {}) if ((isNew && dailyCount >= dailyLimit * 2) || (!isNew && dailyCount >= dailyLimit)) throw new FreeUsageLimitError(dict["zen.api.error.rateLimitExceeded"], retryAfter) @@ -68,18 +44,7 @@ export function createRateLimiter(modelId: string, rateLimit: number | undefined pipeline.incr(dailyKey) pipeline.expire(dailyKey, retryAfter) if (isNew) pipeline.incr(lifetimeKey) - await Promise.all([ - pipeline.exec().catch(() => {}), - Database.use((tx) => - tx - .insert(IpRateLimitTable) - .values([ - { ip, interval: dailyInterval, count: 1 }, - ...(isNew ? [{ ip, interval: lifetimeInterval, count: 1 }] : []), - ]) - .onDuplicateKeyUpdate({ set: { count: sql`${IpRateLimitTable.count} + 1` } }), - ), - ]) + await pipeline.exec() }, } } diff --git a/packages/console/app/src/routes/zen/util/keyRateLimiter.ts b/packages/console/app/src/routes/zen/util/keyRateLimiter.ts index c8cc413a8667..fdf5925299e5 100644 --- a/packages/console/app/src/routes/zen/util/keyRateLimiter.ts +++ b/packages/console/app/src/routes/zen/util/keyRateLimiter.ts @@ -1,6 +1,5 @@ -import { Database, eq, and, sql } from "@opencode-ai/console-core/drizzle/index.js" -import { KeyRateLimitTable } from "@opencode-ai/console-core/schema/ip.sql.js" import { RateLimitError } from "./error" +import { buildRateLimitKey, getRedis } from "./redis" import { i18n } from "~/i18n" import { localeFromRequest } from "~/lib/language" @@ -19,26 +18,20 @@ export function createRateLimiter( .replace(/[^0-9]/g, "") .substring(0, 12) const interval = `${modelId.substring(0, 27)}-${yyyyMMddHHmm}` + const redis = getRedis() + const key = buildRateLimitKey("key", zenApiKey, interval) return { check: async () => { - const rows = await Database.use((tx) => - tx - .select({ interval: KeyRateLimitTable.interval, count: KeyRateLimitTable.count }) - .from(KeyRateLimitTable) - .where(and(eq(KeyRateLimitTable.key, zenApiKey), eq(KeyRateLimitTable.interval, interval))), - ).then((rows) => rows[0]) - const count = rows?.count ?? 0 + const count = Number((await redis.mget<(string | number | null)[]>([key]))[0] ?? 0) if (count >= LIMIT) throw new RateLimitError(dict["zen.api.error.rateLimitExceeded"], 60) }, track: async () => { - await Database.use((tx) => - tx - .insert(KeyRateLimitTable) - .values({ key: zenApiKey, interval, count: 1 }) - .onDuplicateKeyUpdate({ set: { count: sql`${KeyRateLimitTable.count} + 1` } }), - ) + const pipeline = redis.pipeline() + pipeline.incr(key) + pipeline.expire(key, 60) + await pipeline.exec() }, } } diff --git a/packages/console/app/src/routes/zen/util/modelTpsLimiter.ts b/packages/console/app/src/routes/zen/util/modelTpsLimiter.ts index 477d08ce6829..3ff63f7d4976 100644 --- a/packages/console/app/src/routes/zen/util/modelTpsLimiter.ts +++ b/packages/console/app/src/routes/zen/util/modelTpsLimiter.ts @@ -37,7 +37,7 @@ export function createModelTpsLimiter(providers: { id: string; model: string; tp ) // convert to map of model to summed count across current and previous intervals - const result = data.reduce( + return data.reduce( (acc, curr) => { const existing = acc[curr.id] ?? { qualify: 0, unqualify: 0 } acc[curr.id] = { @@ -48,13 +48,6 @@ export function createModelTpsLimiter(providers: { id: string; model: string; tp }, {} as Record, ) - - return Object.fromEntries( - Object.entries(result).map(([id, { qualify, unqualify }]) => { - const isLowTps = qualify + unqualify > 10 && qualify < unqualify - return [id, isLowTps] - }), - ) }, track: async ( provider: string, diff --git a/packages/console/app/src/routes/zen/util/usageBatcher.ts b/packages/console/app/src/routes/zen/util/usageBatcher.ts new file mode 100644 index 000000000000..315ce0a2ebb0 --- /dev/null +++ b/packages/console/app/src/routes/zen/util/usageBatcher.ts @@ -0,0 +1,31 @@ +import { Resource } from "@opencode-ai/console-resource" +import { getRedis } from "./redis" + +// Workspaces whose balance/usage updates should be batched in Redis to avoid +// row-level lock contention on BillingTable / UserTable. +export const HOT_WORKSPACES = new Set([ + "wrk_01KJ8PX5CH50Y4YNGNS9ZR8YDC", // invoice +]) + +// Probability that a given request flushes the accumulated totals to the DB. +// Lower = fewer DB writes, more staleness. ~1 in 100 -> ~1% of requests write. +const FLUSH_PROBABILITY = 1 / 100 + +export async function accumulateUsage(workspaceID: string, userID: string, workspaceCost: number, userCost: number) { + const redis = getRedis() + const wKey = `${Resource.App.stage}:usage:wrk:${workspaceID}` + const uKey = `${Resource.App.stage}:usage:usr:${workspaceID}:${userID}` + + await Promise.all([redis.incrby(wKey, workspaceCost), redis.incrby(uKey, userCost)]) + + if (Math.random() > FLUSH_PROBABILITY) return null + + // Atomically take the current totals and reset to 0 + const [workspaceTotal, userTotal] = await Promise.all([redis.getdel(wKey), redis.getdel(uKey)]) + + const workspaceFlush = Number(workspaceTotal ?? 0) + const userFlush = Number(userTotal ?? 0) + if (workspaceFlush === 0 && userFlush === 0) return null + + return { workspaceCost: workspaceFlush, userCost: userFlush } +} diff --git a/packages/console/app/vite.config.ts b/packages/console/app/vite.config.ts index 951c9a4276c0..33455acc5edb 100644 --- a/packages/console/app/vite.config.ts +++ b/packages/console/app/vite.config.ts @@ -9,7 +9,7 @@ export default defineConfig({ }) as PluginOption, nitro({ compatibilityDate: "2024-09-19", - preset: "cloudflare_module", + preset: "cloudflare-module", cloudflare: { nodeCompat: true, }, @@ -17,6 +17,7 @@ export default defineConfig({ ], server: { allowedHosts: true, + port: 3001, }, build: { rollupOptions: { diff --git a/packages/console/core/package.json b/packages/console/core/package.json index 14dce567f7c9..fdc87e456fc5 100644 --- a/packages/console/core/package.json +++ b/packages/console/core/package.json @@ -37,6 +37,7 @@ "update-limits": "script/update-limits.ts", "promote-limits-to-dev": "script/promote-limits.ts dev", "promote-limits-to-prod": "script/promote-limits.ts production", + "referral-backfill": "script/referral-backfill.ts", "typecheck": "tsgo --noEmit" }, "devDependencies": { diff --git a/packages/console/core/script/create-api-key.ts b/packages/console/core/script/create-api-key.ts new file mode 100644 index 000000000000..dba2ee946c40 --- /dev/null +++ b/packages/console/core/script/create-api-key.ts @@ -0,0 +1,146 @@ +import { Resource } from "@opencode-ai/console-resource" +import { and, Database, eq, isNull } from "../src/drizzle/index.js" +import { Identifier } from "../src/identifier.js" +import { AccountTable } from "../src/schema/account.sql.js" +import { AuthTable } from "../src/schema/auth.sql.js" +import { BillingTable } from "../src/schema/billing.sql.js" +import { KeyTable } from "../src/schema/key.sql.js" +import { UserTable } from "../src/schema/user.sql.js" +import { WorkspaceTable } from "../src/schema/workspace.sql.js" +import { centsToMicroCents } from "../src/util/price.js" + +const args = parseArgs(process.argv.slice(2)) +if (!args.email) { + console.error( + "Usage: bun script/create-api-key.ts --email [--workspace-id ] [--workspace-name ] [--key-name ] [--balance-dollars ] [--allow-production]", + ) + process.exit(1) +} +if (Resource.App.stage === "production" && !args.allowProduction) { + throw new Error("Refusing to create a production API key without --allow-production") +} + +const result = await Database.transaction(async (tx) => { + const auth = await tx + .select() + .from(AuthTable) + .where(and(eq(AuthTable.provider, "email"), eq(AuthTable.subject, args.email))) + .then((rows) => rows[0]) + const accountID = auth?.accountID ?? Identifier.create("account") + if (!auth) { + await tx.insert(AccountTable).values({ id: accountID }) + await tx.insert(AuthTable).values({ + id: Identifier.create("auth"), + provider: "email", + subject: args.email, + accountID, + }) + } + + const workspace = args.workspaceID + ? await tx + .select() + .from(WorkspaceTable) + .where(eq(WorkspaceTable.id, args.workspaceID)) + .then((rows) => rows[0]) + : await tx + .select({ workspace: WorkspaceTable }) + .from(UserTable) + .innerJoin(WorkspaceTable, eq(WorkspaceTable.id, UserTable.workspaceID)) + .where(and(eq(UserTable.accountID, accountID), isNull(UserTable.timeDeleted))) + .then((rows) => rows[0]?.workspace) + if (args.workspaceID && !workspace) throw new Error(`Workspace not found: ${args.workspaceID}`) + const workspaceID = workspace?.id ?? Identifier.create("workspace") + if (!workspace) { + await tx.insert(WorkspaceTable).values({ + id: workspaceID, + slug: null, + name: args.workspaceName ?? `${args.email} manual`, + }) + } + + const user = await tx + .select() + .from(UserTable) + .where( + and(eq(UserTable.workspaceID, workspaceID), eq(UserTable.accountID, accountID), isNull(UserTable.timeDeleted)), + ) + .then((rows) => rows[0]) + const userID = user?.id ?? Identifier.create("user") + if (!user) { + await tx.insert(UserTable).values({ + id: userID, + workspaceID, + accountID, + email: args.email, + name: args.email, + role: "admin", + }) + } + + const balance = centsToMicroCents(args.balanceDollars * 100) + const billing = await tx + .select() + .from(BillingTable) + .where(eq(BillingTable.workspaceID, workspaceID)) + .then((rows) => rows[0]) + if (!billing) { + await tx.insert(BillingTable).values({ + id: Identifier.create("billing"), + workspaceID, + balance, + }) + } else if (billing.balance < balance) { + await tx.update(BillingTable).set({ balance }).where(eq(BillingTable.workspaceID, workspaceID)) + } + + const secretKey = createSecretKey() + const keyID = Identifier.create("key") + await tx.insert(KeyTable).values({ + id: keyID, + workspaceID, + userID, + name: args.keyName ?? "Manual API Key", + key: secretKey, + timeUsed: null, + }) + + return { accountID, workspaceID, userID, keyID, secretKey } +}) + +console.log(JSON.stringify({ stage: Resource.App.stage, ...result }, null, 2)) + +function createSecretKey() { + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + const values = new Uint32Array(64) + crypto.getRandomValues(values) + return `sk-${Array.from(values, (value) => chars[value % chars.length]).join("")}` +} + +function parseArgs(argv: string[]) { + const parsed = { + email: "", + workspaceID: "", + workspaceName: "", + keyName: "", + balanceDollars: 100, + allowProduction: false, + } + for (let index = 0; index < argv.length; index++) { + const arg = argv[index] + if (arg === "--email") parsed.email = requiredValue(argv, ++index, arg) + if (arg === "--workspace-id") parsed.workspaceID = requiredValue(argv, ++index, arg) + if (arg === "--workspace-name") parsed.workspaceName = requiredValue(argv, ++index, arg) + if (arg === "--key-name") parsed.keyName = requiredValue(argv, ++index, arg) + if (arg === "--balance-dollars") parsed.balanceDollars = Number(requiredValue(argv, ++index, arg)) + if (arg === "--allow-production") parsed.allowProduction = true + } + if (!Number.isFinite(parsed.balanceDollars) || parsed.balanceDollars < 0) throw new Error("Invalid --balance-dollars") + return parsed +} + +function requiredValue(argv: string[], index: number, arg: string) { + const value = argv[index] + if (!value || value.startsWith("--")) throw new Error(`Missing value for ${arg}`) + return value +} diff --git a/packages/console/core/script/referral-backfill.ts b/packages/console/core/script/referral-backfill.ts new file mode 100644 index 000000000000..c3062ad78eab --- /dev/null +++ b/packages/console/core/script/referral-backfill.ts @@ -0,0 +1,153 @@ +import { and, Database, eq, inArray, isNull } from "../src/drizzle/index.js" +import { Identifier } from "../src/identifier.js" +import { Referral } from "../src/referral.js" +import { LiteTable } from "../src/schema/billing.sql.js" +import { ReferralRewardTable, ReferralTable } from "../src/schema/referral.sql.js" +import { UserTable } from "../src/schema/user.sql.js" +import { WorkspaceTable } from "../src/schema/workspace.sql.js" + +const backfills = [ + { + inviterWorkspaceID: "wrk_00000000000000000000000000", + inviteeWorkspaceID: "wrk_00000000000000000000000000", + inviteeAccountID: "acc_00000000000000000000000000", + }, +] + +console.log(`Backfilling ${backfills.length} referrals`) + +for (const [index, backfill] of backfills.entries()) { + console.log(`[${index + 1}/${backfills.length}] ${backfill.inviterWorkspaceID} -> ${backfill.inviteeWorkspaceID}`) + console.log(` invitee account: ${backfill.inviteeAccountID}`) + + const result = await Database.transaction(async (tx) => { + if (backfill.inviterWorkspaceID === backfill.inviteeWorkspaceID) throw new Error("Self-referral workspace mismatch") + + const inviterWorkspace = await tx + .select({ id: WorkspaceTable.id }) + .from(WorkspaceTable) + .where(and(eq(WorkspaceTable.id, backfill.inviterWorkspaceID), isNull(WorkspaceTable.timeDeleted))) + .then((rows) => rows[0]) + if (!inviterWorkspace) throw new Error(`Inviter workspace not found: ${backfill.inviterWorkspaceID}`) + + const inviteeWorkspace = await tx + .select({ id: WorkspaceTable.id }) + .from(WorkspaceTable) + .where(and(eq(WorkspaceTable.id, backfill.inviteeWorkspaceID), isNull(WorkspaceTable.timeDeleted))) + .then((rows) => rows[0]) + if (!inviteeWorkspace) throw new Error(`Invitee workspace not found: ${backfill.inviteeWorkspaceID}`) + + const inviteeUser = await tx + .select({ id: UserTable.id }) + .from(UserTable) + .where( + and( + eq(UserTable.workspaceID, backfill.inviteeWorkspaceID), + eq(UserTable.accountID, backfill.inviteeAccountID), + eq(UserTable.role, "admin"), + isNull(UserTable.timeDeleted), + ), + ) + .then((rows) => rows[0]) + if (!inviteeUser) throw new Error(`Invitee workspace owner not found: ${backfill.inviteeAccountID}`) + + const inviterUser = await tx + .select({ id: UserTable.id }) + .from(UserTable) + .where( + and( + eq(UserTable.workspaceID, backfill.inviterWorkspaceID), + eq(UserTable.accountID, backfill.inviteeAccountID), + isNull(UserTable.timeDeleted), + ), + ) + .then((rows) => rows[0]) + if (inviterUser) throw new Error(`Self-referral is not allowed: ${backfill.inviteeAccountID}`) + + const lite = await tx + .select({ id: LiteTable.id }) + .from(LiteTable) + .where( + and( + eq(LiteTable.workspaceID, backfill.inviteeWorkspaceID), + eq(LiteTable.userID, inviteeUser.id), + isNull(LiteTable.timeDeleted), + ), + ) + .then((rows) => rows[0]) + if (!lite) throw new Error(`Invitee Lite subscription not found: ${backfill.inviteeWorkspaceID}`) + + const existingReferral = await tx + .select({ id: ReferralTable.id, workspaceID: ReferralTable.workspaceID }) + .from(ReferralTable) + .where(and(eq(ReferralTable.inviteeAccountID, backfill.inviteeAccountID), isNull(ReferralTable.timeDeleted))) + .then((rows) => rows[0]) + if (existingReferral && existingReferral.workspaceID !== backfill.inviterWorkspaceID) { + throw new Error(`Referral already belongs to ${existingReferral.workspaceID}: ${existingReferral.id}`) + } + + const referralID = existingReferral?.id ?? Identifier.create("referral") + if (!existingReferral) { + await tx.insert(ReferralTable).ignore().values({ + workspaceID: backfill.inviterWorkspaceID, + id: referralID, + inviteeAccountID: backfill.inviteeAccountID, + }) + + const referral = await tx + .select({ id: ReferralTable.id }) + .from(ReferralTable) + .where(and(eq(ReferralTable.inviteeAccountID, backfill.inviteeAccountID), isNull(ReferralTable.timeDeleted))) + .then((rows) => rows[0]) + if (!referral) throw new Error(`Referral not created: ${backfill.inviteeAccountID}`) + if (referral.id !== referralID) throw new Error(`Referral already redeemed: ${referral.id}`) + } + + const rewardInsert = await tx + .insert(ReferralRewardTable) + .ignore() + .values([ + { + workspaceID: backfill.inviterWorkspaceID, + referralID, + amount: Referral.REWARD_AMOUNT, + }, + { + workspaceID: backfill.inviteeWorkspaceID, + referralID, + amount: Referral.REWARD_AMOUNT, + }, + ]) + + const rewards = await tx + .select({ workspaceID: ReferralRewardTable.workspaceID, amount: ReferralRewardTable.amount }) + .from(ReferralRewardTable) + .where( + and( + eq(ReferralRewardTable.referralID, referralID), + inArray(ReferralRewardTable.workspaceID, [backfill.inviterWorkspaceID, backfill.inviteeWorkspaceID]), + isNull(ReferralRewardTable.timeDeleted), + ), + ) + if (rewards.length !== 2) throw new Error(`Referral rewards not created: ${referralID}`) + if (rewards.some((reward) => reward.amount !== Referral.REWARD_AMOUNT)) { + throw new Error(`Referral reward amount mismatch: ${referralID}`) + } + + return { + referralID, + createdReferral: !existingReferral, + createdRewards: rewardInsert.rowsAffected, + inviteeUserID: inviteeUser.id, + liteID: lite.id, + rewardWorkspaces: rewards.map((reward) => reward.workspaceID), + } + }) + + console.log(` invitee user: ${result.inviteeUserID}`) + console.log(` lite: ${result.liteID}`) + console.log(` referral: ${result.referralID} (${result.createdReferral ? "created" : "existing"})`) + console.log(` rewards: ${result.rewardWorkspaces.join(", ")} (${result.createdRewards} inserted)`) +} + +console.log("Referral backfill complete") diff --git a/packages/console/core/src/referral.ts b/packages/console/core/src/referral.ts index 9fb4ed38f990..9f781df858a9 100644 --- a/packages/console/core/src/referral.ts +++ b/packages/console/core/src/referral.ts @@ -1,8 +1,8 @@ import { z } from "zod" -import { and, asc, eq, isNull, sql, Database } from "./drizzle" +import { and, asc, eq, inArray, isNull, sql, Database } from "./drizzle" import { Actor } from "./actor" import { Identifier } from "./identifier" -import { LiteTable } from "./schema/billing.sql" +import { LiteTable, PaymentTable } from "./schema/billing.sql" import { ReferralCodeTable, ReferralRewardTable, ReferralTable } from "./schema/referral.sql" import { AuthTable } from "./schema/auth.sql" import { UserTable } from "./schema/user.sql" @@ -318,6 +318,33 @@ export namespace Referral { .then((rows) => rows[0]) if (selfReferral) throw new Error("Self-referral is not allowed") + const workspaceIDs = await tx + .select({ workspaceID: UserTable.workspaceID }) + .from(UserTable) + .where(and(eq(UserTable.accountID, input.accountID), isNull(UserTable.timeDeleted))) + .then((rows) => rows.map((row) => row.workspaceID)) + if (workspaceIDs.length === 0) return + + const activeLite = await tx + .select({ id: LiteTable.id }) + .from(LiteTable) + .where(and(inArray(LiteTable.workspaceID, workspaceIDs), isNull(LiteTable.timeDeleted))) + .then((rows) => rows[0]) + if (activeLite) return + + const litePayment = await tx + .select({ id: PaymentTable.id }) + .from(PaymentTable) + .where( + and( + inArray(PaymentTable.workspaceID, workspaceIDs), + isNull(PaymentTable.timeDeleted), + sql`JSON_UNQUOTE(JSON_EXTRACT(${PaymentTable.enrichment}, '$.type')) = 'lite'`, + ), + ) + .then((rows) => rows[0]) + if (litePayment) return + const referralID = Identifier.create("referral") await tx.insert(ReferralTable).ignore().values({ workspaceID: code.workspaceID, @@ -357,23 +384,30 @@ export namespace Referral { .then((rows) => rows[0]) if (!referral) return - const result = await tx - .insert(ReferralRewardTable) - .ignore() - .values([ - { - workspaceID: referral.workspaceID, - referralID: referral.id, - amount: REWARD_AMOUNT, - }, - { - workspaceID: input.workspaceID, - referralID: referral.id, - amount: REWARD_AMOUNT, - }, - ]) - - if (result.rowsAffected === 0) throw new Error("Referral already completed") + await tx.insert(ReferralRewardTable).ignore().values({ + workspaceID: referral.workspaceID, + referralID: referral.id, + amount: REWARD_AMOUNT, + }) + + const existingInviteeReward = await tx + .select({ workspaceID: ReferralRewardTable.workspaceID }) + .from(ReferralRewardTable) + .where( + and( + eq(ReferralRewardTable.referralID, referral.id), + sql`${ReferralRewardTable.workspaceID} <> ${referral.workspaceID}`, + isNull(ReferralRewardTable.timeDeleted), + ), + ) + .then((rows) => rows[0]) + if (existingInviteeReward) return + + await tx.insert(ReferralRewardTable).ignore().values({ + workspaceID: input.workspaceID, + referralID: referral.id, + amount: REWARD_AMOUNT, + }) }) } diff --git a/packages/console/function/src/log-processor.ts b/packages/console/function/src/log-processor.ts index 2bb741b7aa34..b499a2c874d3 100644 --- a/packages/console/function/src/log-processor.ts +++ b/packages/console/function/src/log-processor.ts @@ -21,7 +21,8 @@ export default { ) continue - let data = { + const ip = event.event.request.headers["x-real-ip"] + let data: Record = { "cf.continent": event.event.request.cf?.continent, "cf.country": event.event.request.cf?.country, "cf.city": event.event.request.cf?.city, @@ -32,33 +33,177 @@ export default { duration: event.wallTime, request_length: parseInt(event.event.request.headers["content-length"] ?? "0"), status: event.event.response?.status ?? 0, - ip: event.event.request.headers["x-real-ip"], + ip, + "ip.prefix": ipPrefix(ip), } const time = new Date(event.eventTimestamp ?? Date.now()).toISOString() - const events = [] - for (const log of event.logs) { - for (const message of log.message) { - if (!message.startsWith("_metric:")) continue - const json = JSON.parse(message.slice(8)) - data = { ...data, ...json } - if ("llm.error.code" in json) { - events.push({ time, data: { ...data, event_type: "llm.error" } }) - } - } - } - events.push({ time, data: { ...data, event_type: "completions" } }) + const events = [ + ...event.logs.flatMap((log) => + log.message.flatMap((message: string) => { + if (!message.startsWith("_metric:")) return [] + const json = JSON.parse(message.slice(8)) as Record + data = { ...data, ...json } + if ("llm.error.code" in json) { + return [{ time, data: { ...data, event_type: "llm.error" } }] + } + return [] + }), + ), + { time, data: { ...data, event_type: "completions" } }, + ] console.log(JSON.stringify(data, null, 2)) - const ret = await fetch("https://api.honeycomb.io/1/batch/zen", { - method: "POST", - headers: { - "Content-Type": "application/json", - "X-Honeycomb-Team": Resource.HONEYCOMB_API_KEY.value, - }, - body: JSON.stringify(events), - }) - console.log(ret.status) - console.log(await ret.text()) + const lakeIngest = getLakeIngest() + const [honeycomb, lake] = await Promise.all([ + fetch("https://api.honeycomb.io/1/batch/zen", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Honeycomb-Team": Resource.HONEYCOMB_API_KEY.value, + }, + body: JSON.stringify(events), + }), + ...(lakeIngest + ? [ + fetch(lakeIngest.url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${lakeIngest.secret}`, + }, + body: JSON.stringify({ events: events.map((event) => toLakeEvent(event.time, event.data)) }), + }), + ] + : []), + ]) + console.log(honeycomb.status) + console.log(await honeycomb.text()) + if (lake) { + console.log(lake.status) + console.log(await lake.text()) + } } }, } + +function getLakeIngest(): { url: string; secret: string } | undefined { + try { + return Resource.LakeIngest + } catch { + return undefined + } +} + +function toLakeEvent(time: string, data: Record) { + return { + _datalake_key: "inference.event", + event_timestamp: time, + event_date: time.slice(0, 10), + event_type: string(data, "event_type"), + dataset: "zen", + cf_continent: string(data, "cf.continent"), + cf_country: string(data, "cf.country"), + cf_city: string(data, "cf.city"), + cf_region: string(data, "cf.region"), + cf_latitude: number(data, "cf.latitude"), + cf_longitude: number(data, "cf.longitude"), + cf_timezone: string(data, "cf.timezone"), + duration: number(data, "duration"), + request_length: integer(data, "request_length"), + status: integer(data, "status"), + ip: string(data, "ip"), + ip_prefix: string(data, "ip.prefix"), + is_stream: boolean(data, "is_stream"), + session: string(data, "session"), + request: string(data, "request"), + client: string(data, "client"), + user_agent: string(data, "user_agent"), + model_variant: string(data, "model.variant"), + source: string(data, "source"), + provider: string(data, "provider"), + provider_model: string(data, "provider.model"), + model: string(data, "model"), + llm_error_code: integer(data, "llm.error.code"), + llm_error_message: string(data, "llm.error.message"), + error_response: string(data, "error.response"), + error_type: string(data, "error.type"), + error_message: string(data, "error.message"), + error_cause: string(data, "error.cause"), + error_cause2: string(data, "error.cause2"), + api_key: string(data, "api_key"), + workspace: string(data, "workspace"), + is_subscription: boolean(data, "isSubscription"), + subscription: string(data, "subscription"), + response_length: integer(data, "response_length"), + time_to_first_byte: integer(data, "time_to_first_byte"), + timestamp_first_byte: integer(data, "timestamp.first_byte"), + timestamp_last_byte: integer(data, "timestamp.last_byte"), + tokens_input: integer(data, "tokens.input"), + tokens_output: integer(data, "tokens.output"), + tokens_reasoning: integer(data, "tokens.reasoning"), + tokens_cache_read: integer(data, "tokens.cache_read"), + tokens_cache_write_5m: integer(data, "tokens.cache_write_5m"), + tokens_cache_write_1h: integer(data, "tokens.cache_write_1h"), + cost_input_microcents: integer(data, "cost.input.microcents"), + cost_output_microcents: integer(data, "cost.output.microcents"), + cost_cache_read_microcents: integer(data, "cost.cache_read.microcents"), + cost_cache_write_microcents: integer(data, "cost.cache_write.microcents"), + cost_total_microcents: integer(data, "cost.total.microcents"), + } +} + +// Returns a stable lookup key for an IP address. +// IPv4: full address as /32 (e.g. "203.0.113.45/32"). +// IPv6: the /64 network prefix (e.g. "2001:db8:abcd:1234::/64"). ISPs commonly +// rotate the lower 64 host bits via SLAAC privacy extensions (RFC 8981), so +// grouping by /64 collapses those rotations into one key. +function ipPrefix(ip: string | undefined) { + if (!ip) return undefined + if (ip.includes(".") && !ip.includes(":")) return `${ip}/32` + if (!ip.includes(":")) return undefined + + // Expand "::" to its full form, then keep the first 4 hextets. + const [head, tail] = ip.split("::") as [string, string | undefined] + const headParts = head ? head.split(":") : [] + const tailParts = tail !== undefined ? tail.split(":") : [] + const missing = 8 - headParts.length - tailParts.length + if (missing < 0) return undefined + const full = [...headParts, ...new Array(missing).fill("0"), ...tailParts] + if (full.length !== 8) return undefined + + const prefix = full + .slice(0, 4) + .map((part) => part.toLowerCase().replace(/^0+(?=.)/, "")) + .join(":") + return `${prefix}::/64` +} + +function string(data: Record, key: string) { + const value = data[key] + if (typeof value === "string") return value + if (typeof value === "number" || typeof value === "boolean") return String(value) + return undefined +} + +function boolean(data: Record, key: string) { + const value = data[key] + if (typeof value === "boolean") return value + if (typeof value === "string") return value === "true" ? true : value === "false" ? false : undefined + return undefined +} + +function integer(data: Record, key: string) { + const value = number(data, key) + if (value === undefined) return undefined + return Math.round(value) +} + +function number(data: Record, key: string) { + const value = data[key] + if (typeof value === "number") return Number.isFinite(value) ? value : undefined + if (typeof value === "string") { + const parsed = Number(value) + return Number.isFinite(parsed) ? parsed : undefined + } + return undefined +} diff --git a/packages/console/resource/resource.node.ts b/packages/console/resource/resource.node.ts index 1470bacf2652..ce11abcc4469 100644 --- a/packages/console/resource/resource.node.ts +++ b/packages/console/resource/resource.node.ts @@ -11,6 +11,7 @@ export const Resource = new Proxy( { get(_target, prop: keyof typeof ResourceBase) { const value = ResourceBase[prop] + const secrets = ResourceBase as unknown as Record if ("type" in value) { // @ts-ignore if (value.type === "sst.cloudflare.Bucket") { @@ -21,11 +22,11 @@ export const Resource = new Proxy( // @ts-ignore if (value.type === "sst.cloudflare.Kv") { const client = new Cloudflare({ - apiToken: ResourceBase.CLOUDFLARE_API_TOKEN.value, + apiToken: secrets.CLOUDFLARE_API_TOKEN.value, }) // @ts-ignore const namespaceId = value.namespaceId - const accountId = ResourceBase.CLOUDFLARE_DEFAULT_ACCOUNT_ID.value + const accountId = secrets.CLOUDFLARE_DEFAULT_ACCOUNT_ID.value return { get: (k: string | string[]) => { const isMulti = Array.isArray(k) diff --git a/packages/console/support/package.json b/packages/console/support/package.json new file mode 100644 index 000000000000..1c1064169e52 --- /dev/null +++ b/packages/console/support/package.json @@ -0,0 +1,29 @@ +{ + "name": "@opencode-ai/console-support", + "version": "1.15.13", + "type": "module", + "license": "MIT", + "scripts": { + "typecheck": "tsgo --noEmit", + "dev": "sst shell --stage production -- vite dev" + }, + "dependencies": { + "@cloudflare/vite-plugin": "1.15.2", + "@opencode-ai/console-core": "workspace:*", + "@solidjs/meta": "catalog:", + "@solidjs/router": "catalog:", + "@solidjs/start": "catalog:", + "nitro": "3.0.1-alpha.1", + "solid-js": "catalog:", + "vite": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "@typescript/native-preview": "catalog:", + "typescript": "catalog:", + "wrangler": "4.50.0" + }, + "engines": { + "node": ">=22" + } +} diff --git a/packages/console/support/src/app.css b/packages/console/support/src/app.css new file mode 100644 index 000000000000..895d8091abdb --- /dev/null +++ b/packages/console/support/src/app.css @@ -0,0 +1,133 @@ +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + background: #0d0d0d; + color: #e6e6e6; +} + +main[data-page="support"] { + max-width: 1400px; + margin: 0 auto; + padding: 2rem; +} + +main[data-page="support"] h1 { + margin: 0 0 1rem; + font-size: 1.25rem; + font-weight: 500; +} + +form[data-component="lookup"] { + display: flex; + gap: 0.5rem; + margin-bottom: 2rem; + align-items: center; + flex-wrap: wrap; +} + +form[data-component="lookup"] input[type="text"] { + flex: 1; + min-width: 280px; + padding: 0.6rem 0.75rem; + border: 1px solid #2a2a2a; + background: #161616; + color: #e6e6e6; + border-radius: 4px; + font: inherit; +} + +form[data-component="lookup"] label { + display: inline-flex; + align-items: center; + gap: 0.4rem; + color: #b0b0b0; +} + +form[data-component="lookup"] button { + padding: 0.6rem 1rem; + border: 1px solid #3a3a3a; + background: #1f1f1f; + color: #e6e6e6; + border-radius: 4px; + font: inherit; + cursor: pointer; +} + +form[data-component="lookup"] button:hover { + background: #2a2a2a; +} + +form[data-component="lookup"] button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +[data-component="error"] { + color: #ff6b6b; + background: #2a1414; + border: 1px solid #4a1f1f; + padding: 0.75rem 1rem; + border-radius: 4px; + margin-bottom: 1rem; +} + +[data-component="section"] { + margin-bottom: 2rem; +} + +[data-component="section"] h2 { + margin: 0 0 0.5rem; + font-size: 1rem; + font-weight: 500; + color: #b0b0b0; + border-bottom: 1px solid #2a2a2a; + padding-bottom: 0.4rem; +} + +[data-component="section"] h3 { + margin: 1.75rem 0 0.5rem; + font-size: 0.875rem; + font-weight: 500; + color: #888; +} + +[data-component="section"] h3:first-of-type { + margin-top: 0; +} + +[data-component="section"] table { + width: 100%; + border-collapse: collapse; + font-size: 0.8125rem; +} + +[data-component="section"] th, +[data-component="section"] td { + text-align: left; + padding: 0.4rem 0.6rem; + border-bottom: 1px solid #1f1f1f; + vertical-align: top; + white-space: nowrap; +} + +[data-component="section"] th { + color: #888; + font-weight: 500; + background: #141414; +} + +[data-component="section"] td a { + color: #6ea8fe; +} + +[data-component="section"] [data-empty] { + color: #666; + font-style: italic; + padding: 0.4rem 0; +} diff --git a/packages/console/support/src/app.tsx b/packages/console/support/src/app.tsx new file mode 100644 index 000000000000..9ae229d04bf5 --- /dev/null +++ b/packages/console/support/src/app.tsx @@ -0,0 +1,21 @@ +import { MetaProvider, Title } from "@solidjs/meta" +import { Router } from "@solidjs/router" +import { FileRoutes } from "@solidjs/start/router" +import { Suspense } from "solid-js" +import "./app.css" + +export default function App() { + return ( + ( + + opencode support + {props.children} + + )} + > + + + ) +} diff --git a/packages/console/support/src/component/result.tsx b/packages/console/support/src/component/result.tsx new file mode 100644 index 000000000000..3800a2c95eed --- /dev/null +++ b/packages/console/support/src/component/result.tsx @@ -0,0 +1,119 @@ +import { For, Show } from "solid-js" +import type { LookupResult, WorkspaceSection } from "~/lib/lookup" + +export function Result(props: { data: LookupResult }) { + return ( + <> + + {(auth) => ( +
+

Auth

+ +
+ )} +
+ + + {(workspaces) => ( +
+

Workspaces

+ +
+ )} +
+ + {(ws) => } + + ) +} + +function WorkspaceView(props: { section: WorkspaceSection }) { + return ( +
+

{props.section.title}

+ +

Users

+ + +

Billing

+ + +

GO

+ + +

Payments

+ + +

28-Day Usage

+ + +

Disabled Models

+ +
+ ) +} + +function DataTable(props: { rows: Record[] }) { + const columns = () => { + const cols = new Set() + for (const row of props.rows) { + for (const key of Object.keys(row)) cols.add(key) + } + return [...cols] + } + + return ( + 0} fallback={
(no data)
}> + + + + {(col) => } + + + + + {(row) => ( + + {(col) => } + + )} + + +
{col}
{renderCell(row[col])}
+
+ ) +} + +function renderCell(value: unknown) { + if (value === null || value === undefined) return "" + if (typeof value === "string" && value.startsWith("https://")) { + return ( + + {value} + + ) + } + if (isLinkCell(value)) { + const external = value.__link.startsWith("http") + return ( + + {value.label} + + ) + } + if (typeof value === "object") return JSON.stringify(value) + return String(value) +} + +function isLinkCell(value: unknown): value is { __link: string; label: string } { + return ( + typeof value === "object" && + value !== null && + "__link" in value && + typeof (value as { __link: unknown }).__link === "string" + ) +} diff --git a/packages/console/support/src/entry-client.tsx b/packages/console/support/src/entry-client.tsx new file mode 100644 index 000000000000..642deacf73cc --- /dev/null +++ b/packages/console/support/src/entry-client.tsx @@ -0,0 +1,4 @@ +// @refresh reload +import { mount, StartClient } from "@solidjs/start/client" + +mount(() => , document.getElementById("app")!) diff --git a/packages/console/support/src/entry-server.tsx b/packages/console/support/src/entry-server.tsx new file mode 100644 index 000000000000..752f8522f78c --- /dev/null +++ b/packages/console/support/src/entry-server.tsx @@ -0,0 +1,26 @@ +// @refresh reload +import { createHandler, StartServer } from "@solidjs/start/server" + +export default createHandler( + () => ( + ( + + + + + + {assets} + + +
{children}
+ {scripts} + + + )} + /> + ), + { + mode: "async", + }, +) diff --git a/packages/console/support/src/global.d.ts b/packages/console/support/src/global.d.ts new file mode 100644 index 000000000000..dc6f10c226c0 --- /dev/null +++ b/packages/console/support/src/global.d.ts @@ -0,0 +1 @@ +/// diff --git a/packages/console/support/src/lib/lookup.ts b/packages/console/support/src/lib/lookup.ts new file mode 100644 index 000000000000..5bf2b06f6b7b --- /dev/null +++ b/packages/console/support/src/lib/lookup.ts @@ -0,0 +1,479 @@ +"use server" + +import { Database, and, eq, isNull, sql } from "@opencode-ai/console-core/drizzle/index.js" +import { AuthTable } from "@opencode-ai/console-core/schema/auth.sql.js" +import { UserTable } from "@opencode-ai/console-core/schema/user.sql.js" +import { + BillingTable, + PaymentTable, + SubscriptionTable, + BlackPlans, + UsageTable, + LiteTable, +} from "@opencode-ai/console-core/schema/billing.sql.js" +import { WorkspaceTable } from "@opencode-ai/console-core/schema/workspace.sql.js" +import { KeyTable } from "@opencode-ai/console-core/schema/key.sql.js" +import { ModelTable } from "@opencode-ai/console-core/schema/model.sql.js" +import { BlackData } from "@opencode-ai/console-core/black.js" +import { LiteData } from "@opencode-ai/console-core/lite.js" +import { Subscription } from "@opencode-ai/console-core/subscription.js" +import { centsToMicroCents } from "@opencode-ai/console-core/util/price.js" +import { getWeekBounds } from "@opencode-ai/console-core/util/date.js" + +export type LookupResult = { + identifier: string + auth?: Record[] + accountWorkspaces?: Record[] + workspaces: WorkspaceSection[] +} + +export type WorkspaceSection = { + workspaceID: string + title: string + users: Record[] + billing: Record | null + go: Record[] + payments: Record[] + usage: Record[] + disabledModels: Record[] +} + +export async function lookup(identifier: string): Promise { + if (!identifier) throw new Error("Identifier is required") + + if (identifier.startsWith("wrk_")) { + const workspace = await loadWorkspace(identifier) + return { identifier, workspaces: [workspace] } + } + + if (identifier.startsWith("key_")) { + const key = await Database.use((tx) => + tx + .select() + .from(KeyTable) + .where(eq(KeyTable.id, identifier)) + .then((rows) => rows[0]), + ) + if (!key) throw new Error("API key not found") + const workspace = await loadWorkspace(key.workspaceID) + return { identifier, workspaces: [workspace] } + } + + if (identifier.startsWith("sk-")) { + const key = await Database.use((tx) => + tx + .select() + .from(KeyTable) + .where(eq(KeyTable.key, identifier)) + .then((rows) => rows[0]), + ) + if (!key) throw new Error("API key not found") + const workspace = await loadWorkspace(key.workspaceID) + return { identifier, workspaces: [workspace] } + } + + // Treat as email + const authData = await Database.use((tx) => tx.select().from(AuthTable).where(eq(AuthTable.subject, identifier))) + if (authData.length === 0) throw new Error("Email not found") + + const accountID = authData[0].accountID + const auth = await Database.use((tx) => tx.select().from(AuthTable).where(eq(AuthTable.accountID, accountID))) + + const accountWorkspaces = await Database.use((tx) => + tx + .select({ + userID: UserTable.id, + workspaceID: UserTable.workspaceID, + workspaceName: WorkspaceTable.name, + balance: BillingTable.balance, + role: UserTable.role, + black: SubscriptionTable.timeCreated, + lite: LiteTable.timeCreated, + }) + .from(UserTable) + .rightJoin(WorkspaceTable, eq(WorkspaceTable.id, UserTable.workspaceID)) + .leftJoin(BillingTable, eq(BillingTable.workspaceID, WorkspaceTable.id)) + .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id)) + .leftJoin(LiteTable, eq(LiteTable.userID, UserTable.id)) + .where(eq(UserTable.accountID, accountID)) + .then((rows) => + rows.map((row) => ({ + workspaceName: row.workspaceID + ? { __link: `#workspace-${row.workspaceID}`, label: row.workspaceName } + : row.workspaceName, + userID: row.userID, + workspaceID: row.workspaceID, + balance: formatMicroCents(row.balance) ?? "$0.00", + role: row.role, + black: formatDate(row.black), + lite: formatDate(row.lite), + })), + ), + ) + + const workspaces: WorkspaceSection[] = [] + for (const w of accountWorkspaces) { + if (!w.workspaceID) continue + workspaces.push(await loadWorkspace(w.workspaceID)) + } + + return { + identifier, + auth: auth.map((row) => ({ + provider: row.provider, + subject: row.subject, + accountID: row.accountID, + })), + accountWorkspaces, + workspaces, + } +} + +async function loadWorkspace(workspaceID: string): Promise { + const workspace = await Database.use((tx) => + tx + .select() + .from(WorkspaceTable) + .where(eq(WorkspaceTable.id, workspaceID)) + .then((rows) => rows[0]), + ) + if (!workspace) throw new Error(`Workspace ${workspaceID} not found`) + + const users = await Database.use((tx) => + tx + .select({ + authEmail: AuthTable.subject, + inviteEmail: UserTable.email, + role: UserTable.role, + timeSeen: UserTable.timeSeen, + monthlyLimit: UserTable.monthlyLimit, + monthlyUsage: UserTable.monthlyUsage, + timeDeleted: UserTable.timeDeleted, + fixedUsage: SubscriptionTable.fixedUsage, + rollingUsage: SubscriptionTable.rollingUsage, + timeFixedUpdated: SubscriptionTable.timeFixedUpdated, + timeRollingUpdated: SubscriptionTable.timeRollingUpdated, + timeSubscriptionCreated: SubscriptionTable.timeCreated, + subscription: BillingTable.subscription, + }) + .from(UserTable) + .innerJoin(BillingTable, eq(BillingTable.workspaceID, workspace.id)) + .leftJoin(AuthTable, and(eq(UserTable.accountID, AuthTable.accountID), eq(AuthTable.provider, "email"))) + .leftJoin(SubscriptionTable, eq(SubscriptionTable.userID, UserTable.id)) + .where(eq(UserTable.workspaceID, workspace.id)) + .then((rows) => + rows.map((row) => { + const subStatus = getSubscriptionStatus(row) + return { + email: (row.timeDeleted ? "[deleted] " : "") + (row.authEmail ?? row.inviteEmail), + role: row.role, + timeSeen: formatDate(row.timeSeen), + monthly: formatMonthlyUsage(row.monthlyUsage, row.monthlyLimit), + subscribed: formatDate(row.timeSubscriptionCreated), + subWeekly: subStatus.weekly, + subRolling: subStatus.rolling, + rateLimited: subStatus.rateLimited, + retryIn: subStatus.retryIn, + } + }), + ), + ) + + const billing = await Database.use((tx) => + tx + .select({ + balance: BillingTable.balance, + customerID: BillingTable.customerID, + reload: BillingTable.reload, + blackSubscriptionID: BillingTable.subscriptionID, + blackSubscription: { + plan: BillingTable.subscriptionPlan, + booked: BillingTable.timeSubscriptionBooked, + enrichment: BillingTable.subscription, + }, + timeBlackSubscriptionSelected: BillingTable.timeSubscriptionSelected, + liteSubscriptionID: BillingTable.liteSubscriptionID, + }) + .from(BillingTable) + .where(eq(BillingTable.workspaceID, workspace.id)) + .then( + (rows) => + rows.map((row) => ({ + balance: `$${(row.balance / 100000000).toFixed(2)}`, + reload: row.reload ? "yes" : "no", + customerID: row.customerID, + GO: row.liteSubscriptionID, + Black: row.blackSubscriptionID + ? [ + `Black ${row.blackSubscription.enrichment!.plan}`, + row.blackSubscription.enrichment!.seats > 1 + ? `X ${row.blackSubscription.enrichment!.seats} seats` + : "", + row.blackSubscription.enrichment!.coupon + ? `(coupon: ${row.blackSubscription.enrichment!.coupon})` + : "", + `(ref: ${row.blackSubscriptionID})`, + ].join(" ") + : row.blackSubscription.booked + ? `Waitlist ${row.blackSubscription.plan} plan${row.timeBlackSubscriptionSelected ? " (selected)" : ""}` + : undefined, + }))[0] ?? null, + ), + ) + + const liteLimits = LiteData.getLimits() + const go = await Database.use((tx) => + tx + .select({ + userID: LiteTable.userID, + userEmail: UserTable.email, + authEmail: AuthTable.subject, + rollingUsage: LiteTable.rollingUsage, + weeklyUsage: LiteTable.weeklyUsage, + monthlyUsage: LiteTable.monthlyUsage, + timeRollingUpdated: LiteTable.timeRollingUpdated, + timeWeeklyUpdated: LiteTable.timeWeeklyUpdated, + timeMonthlyUpdated: LiteTable.timeMonthlyUpdated, + timeCreated: LiteTable.timeCreated, + useBalance: BillingTable.lite, + }) + .from(LiteTable) + .innerJoin(BillingTable, eq(BillingTable.workspaceID, LiteTable.workspaceID)) + .leftJoin(UserTable, eq(UserTable.id, LiteTable.userID)) + .leftJoin(AuthTable, and(eq(UserTable.accountID, AuthTable.accountID), eq(AuthTable.provider, "email"))) + .where(and(eq(LiteTable.workspaceID, workspace.id), isNull(LiteTable.timeDeleted))) + .then((rows) => + rows.map((row) => { + const rolling = Subscription.analyzeRollingUsage({ + limit: liteLimits.rollingLimit, + window: liteLimits.rollingWindow, + usage: row.rollingUsage ?? 0, + timeUpdated: row.timeRollingUpdated ?? new Date(), + }) + const weekly = Subscription.analyzeWeeklyUsage({ + limit: liteLimits.weeklyLimit, + usage: row.weeklyUsage ?? 0, + timeUpdated: row.timeWeeklyUpdated ?? new Date(), + }) + const monthly = Subscription.analyzeMonthlyUsage({ + limit: liteLimits.monthlyLimit, + usage: row.monthlyUsage ?? 0, + timeUpdated: row.timeMonthlyUpdated ?? new Date(), + timeSubscribed: row.timeCreated, + }) + return { + email: row.authEmail ?? row.userEmail ?? row.userID, + subscribed: formatDate(row.timeCreated), + useBalance: row.useBalance?.useBalance ? "yes" : "no", + rolling: formatLiteUsage(rolling), + weekly: formatLiteUsage(weekly), + monthly: formatLiteUsage(monthly), + } + }), + ), + ) + + const payments = await Database.use((tx) => + tx + .select({ + amount: PaymentTable.amount, + paymentID: PaymentTable.paymentID, + invoiceID: PaymentTable.invoiceID, + customerID: PaymentTable.customerID, + timeCreated: PaymentTable.timeCreated, + timeRefunded: PaymentTable.timeRefunded, + }) + .from(PaymentTable) + .where(eq(PaymentTable.workspaceID, workspace.id)) + .orderBy(sql`${PaymentTable.timeCreated} DESC`) + .limit(100) + .then((rows) => + rows.map((row) => ({ + amount: `$${(row.amount / 100000000).toFixed(2)}`, + paymentID: row.paymentID + ? `https://dashboard.stripe.com/acct_1RszBH2StuRr0lbX/payments/${row.paymentID}` + : null, + invoiceID: row.invoiceID, + customerID: row.customerID, + timeCreated: formatDate(row.timeCreated), + timeRefunded: formatDate(row.timeRefunded), + })), + ), + ) + + const planExpr = sql`JSON_UNQUOTE(JSON_EXTRACT(${UsageTable.enrichment}, '$.plan'))` + const usage = await Database.use((tx) => + tx + .select({ + date: sql`DATE(${UsageTable.timeCreated})`.as("date"), + freeRequests: sql`SUM(CASE WHEN ${UsageTable.cost} = 0 THEN 1 ELSE 0 END)`.as("free_requests"), + goRequests: sql`SUM(CASE WHEN ${planExpr} = 'lite' THEN 1 ELSE 0 END)`.as("go_requests"), + goCost: sql`SUM(CASE WHEN ${planExpr} = 'lite' THEN ${UsageTable.cost} ELSE 0 END)`.as("go_cost"), + apiRequests: sql`SUM(CASE WHEN ${planExpr} IS NULL AND ${UsageTable.cost} > 0 THEN 1 ELSE 0 END)`.as( + "api_requests", + ), + apiCost: + sql`SUM(CASE WHEN ${planExpr} IS NULL AND ${UsageTable.cost} > 0 THEN ${UsageTable.cost} ELSE 0 END)`.as( + "api_cost", + ), + }) + .from(UsageTable) + .where( + and( + eq(UsageTable.workspaceID, workspace.id), + sql`${UsageTable.timeCreated} >= DATE_SUB(NOW(), INTERVAL 28 DAY)`, + ), + ) + .groupBy(sql`DATE(${UsageTable.timeCreated})`) + .orderBy(sql`DATE(${UsageTable.timeCreated}) DESC`) + .then((rows) => { + const totals = rows.reduce( + (acc, r) => ({ + freeRequests: acc.freeRequests + Number(r.freeRequests), + goRequests: acc.goRequests + Number(r.goRequests), + goCost: acc.goCost + Number(r.goCost), + apiRequests: acc.apiRequests + Number(r.apiRequests), + apiCost: acc.apiCost + Number(r.apiCost), + }), + { freeRequests: 0, goRequests: 0, goCost: 0, apiRequests: 0, apiCost: 0 }, + ) + const mapped: Record[] = rows.map((row) => ({ + date: row.date, + freeRequests: Number(row.freeRequests), + goRequests: Number(row.goRequests), + goCost: formatMicroCents(Number(row.goCost)) ?? "$0.00", + apiRequests: Number(row.apiRequests), + apiCost: formatMicroCents(Number(row.apiCost)) ?? "$0.00", + })) + if (mapped.length > 0) { + mapped.push({ + date: "TOTAL", + freeRequests: totals.freeRequests, + goRequests: totals.goRequests, + goCost: formatMicroCents(totals.goCost) ?? "$0.00", + apiRequests: totals.apiRequests, + apiCost: formatMicroCents(totals.apiCost) ?? "$0.00", + }) + } + return mapped + }), + ) + + const disabledModels = await Database.use((tx) => + tx + .select({ + model: ModelTable.model, + timeCreated: ModelTable.timeCreated, + }) + .from(ModelTable) + .where(eq(ModelTable.workspaceID, workspace.id)) + .orderBy(sql`${ModelTable.timeCreated} DESC`) + .then((rows) => + rows.map((row) => ({ + model: row.model, + timeCreated: formatDate(row.timeCreated), + })), + ), + ) + + return { + workspaceID: workspace.id, + title: `Workspace "${workspace.name}" (${workspace.id})`, + users, + billing, + go, + payments, + usage, + disabledModels, + } +} + +function formatLiteUsage(usage: { status: "ok" | "rate-limited"; usagePercent: number; resetInSec: number }) { + const reset = formatResetTime(usage.resetInSec) + const status = usage.status === "rate-limited" ? " [limited]" : "" + return `${usage.usagePercent}% (resets in ${reset})${status}` +} + +function formatResetTime(seconds: number) { + if (seconds <= 0) return "now" + const days = Math.floor(seconds / 86400) + if (days >= 1) return `${days}d` + const hours = Math.floor(seconds / 3600) + if (hours >= 1) { + const minutes = Math.floor((seconds % 3600) / 60) + return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h` + } + const minutes = Math.max(1, Math.ceil(seconds / 60)) + return `${minutes}m` +} + +function formatMicroCents(value: number | null | undefined) { + if (value === null || value === undefined) return null + return `$${(value / 100000000).toFixed(2)}` +} + +function formatDate(value: Date | null | undefined) { + if (!value) return null + return value.toISOString().split("T")[0] +} + +function formatMonthlyUsage(usage: number | null | undefined, limit: number | null | undefined) { + const usageText = formatMicroCents(usage) ?? "$0.00" + if (limit === null || limit === undefined) return `${usageText} / no limit` + return `${usageText} / $${limit.toFixed(2)}` +} + +function formatRetryTime(seconds: number) { + const days = Math.floor(seconds / 86400) + if (days >= 1) return `${days} day${days > 1 ? "s" : ""}` + const hours = Math.floor(seconds / 3600) + const minutes = Math.ceil((seconds % 3600) / 60) + if (hours >= 1) return `${hours}hr ${minutes}min` + return `${minutes}min` +} + +function getSubscriptionStatus(row: { + subscription: { + plan: (typeof BlackPlans)[number] + } | null + timeSubscriptionCreated: Date | null + fixedUsage: number | null + rollingUsage: number | null + timeFixedUpdated: Date | null + timeRollingUpdated: Date | null +}) { + if (!row.timeSubscriptionCreated || !row.subscription) { + return { weekly: null, rolling: null, rateLimited: null, retryIn: null } + } + + const black = BlackData.getLimits({ plan: row.subscription.plan }) + const now = new Date() + const week = getWeekBounds(now) + + const fixedLimit = black.fixedLimit ? centsToMicroCents(black.fixedLimit * 100) : null + const rollingLimit = black.rollingLimit ? centsToMicroCents(black.rollingLimit * 100) : null + const rollingWindowMs = (black.rollingWindow ?? 5) * 3600 * 1000 + + const currentWeekly = + row.fixedUsage && row.timeFixedUpdated && row.timeFixedUpdated >= week.start ? row.fixedUsage : 0 + + const windowStart = new Date(now.getTime() - rollingWindowMs) + const currentRolling = + row.rollingUsage && row.timeRollingUpdated && row.timeRollingUpdated >= windowStart ? row.rollingUsage : 0 + + const isWeeklyLimited = fixedLimit !== null && currentWeekly >= fixedLimit + const isRollingLimited = rollingLimit !== null && currentRolling >= rollingLimit + + const retryIn = isWeeklyLimited + ? formatRetryTime(Math.ceil((week.end.getTime() - now.getTime()) / 1000)) + : isRollingLimited && row.timeRollingUpdated + ? formatRetryTime(Math.ceil((row.timeRollingUpdated.getTime() + rollingWindowMs - now.getTime()) / 1000)) + : null + + return { + weekly: fixedLimit !== null ? `${formatMicroCents(currentWeekly)} / $${black.fixedLimit}` : null, + rolling: rollingLimit !== null ? `${formatMicroCents(currentRolling)} / $${black.rollingLimit}` : null, + rateLimited: isWeeklyLimited || isRollingLimited ? "yes" : "no", + retryIn, + } +} diff --git a/packages/console/support/src/routes/index.tsx b/packages/console/support/src/routes/index.tsx new file mode 100644 index 000000000000..8038788ce3e6 --- /dev/null +++ b/packages/console/support/src/routes/index.tsx @@ -0,0 +1,22 @@ +import { Title } from "@solidjs/meta" + +export default function SupportPage() { + return ( +
+ opencode support — lookup user +

Lookup user

+ +
+ + +
+
+ ) +} diff --git a/packages/console/support/src/routes/lookup.tsx b/packages/console/support/src/routes/lookup.tsx new file mode 100644 index 000000000000..7e977b7f9506 --- /dev/null +++ b/packages/console/support/src/routes/lookup.tsx @@ -0,0 +1,39 @@ +import { Title } from "@solidjs/meta" +import { createAsync, query, useSearchParams, type RouteDefinition } from "@solidjs/router" +import { Show } from "solid-js" +import { ErrorBoundary } from "solid-js" +import { Result } from "~/component/result" +import { lookup } from "~/lib/lookup" + +const getLookup = query(async (identifier: string) => { + "use server" + return lookup(identifier) +}, "support.lookup") + +export const route: RouteDefinition = { + preload: ({ location }) => { + const identifier = new URLSearchParams(location.search).get("identifier")?.trim() + if (identifier) void getLookup(identifier) + }, +} + +export default function LookupPage() { + const [params] = useSearchParams() + const identifier = () => String(params.identifier ?? "").trim() + const data = createAsync(() => (identifier() ? getLookup(identifier()) : Promise.resolve(undefined))) + + return ( +
+ opencode support — {identifier() || "lookup"} +

Lookup: {identifier() || "(no identifier)"}

+ + Provide an `identifier` query parameter.
}> +
{(err as Error).message}
}> + Loading...
}> + {(result) => } + + + + + ) +} diff --git a/packages/console/support/sst-env.d.ts b/packages/console/support/sst-env.d.ts new file mode 100644 index 000000000000..301538ccb214 --- /dev/null +++ b/packages/console/support/sst-env.d.ts @@ -0,0 +1,10 @@ +/* This file is auto-generated by SST. Do not edit. */ +/* tslint:disable */ +/* eslint-disable */ +/* deno-fmt-ignore-file */ +/* biome-ignore-all lint: auto-generated */ + +/// + +import "sst" +export {} \ No newline at end of file diff --git a/packages/console/support/tsconfig.json b/packages/console/support/tsconfig.json new file mode 100644 index 000000000000..0f96f182cee8 --- /dev/null +++ b/packages/console/support/tsconfig.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowJs": true, + "strict": true, + "noEmit": true, + "types": ["vite/client", "bun"], + "isolatedModules": true, + "paths": { + "~/*": ["./src/*"] + } + } +} diff --git a/packages/console/support/vite.config.ts b/packages/console/support/vite.config.ts new file mode 100644 index 000000000000..3b013e990119 --- /dev/null +++ b/packages/console/support/vite.config.ts @@ -0,0 +1,25 @@ +import { defineConfig, PluginOption } from "vite" +import { solidStart } from "@solidjs/start/config" +import { nitro } from "nitro/vite" + +export default defineConfig({ + plugins: [ + solidStart() as PluginOption, + nitro({ + compatibilityDate: "2024-09-19", + preset: "cloudflare_module", + cloudflare: { + nodeCompat: true, + }, + }), + ], + server: { + allowedHosts: true, + }, + build: { + rollupOptions: { + external: ["cloudflare:workers"], + }, + minify: false, + }, +}) diff --git a/packages/opencode/drizzle.config.ts b/packages/core/drizzle.config.ts similarity index 79% rename from packages/opencode/drizzle.config.ts rename to packages/core/drizzle.config.ts index 1b4fd556e9cb..a90ac4e2fe3c 100644 --- a/packages/opencode/drizzle.config.ts +++ b/packages/core/drizzle.config.ts @@ -2,7 +2,7 @@ import { defineConfig } from "drizzle-kit" export default defineConfig({ dialect: "sqlite", - schema: "./src/**/*.sql.ts", + schema: ["./src/**/*.sql.ts", "./src/**/sql.ts"], out: "./migration", dbCredentials: { url: "/home/thdxr/.local/share/opencode/opencode.db", diff --git a/packages/opencode/migration/20260127222353_familiar_lady_ursula/migration.sql b/packages/core/migration/20260127222353_familiar_lady_ursula/migration.sql similarity index 100% rename from packages/opencode/migration/20260127222353_familiar_lady_ursula/migration.sql rename to packages/core/migration/20260127222353_familiar_lady_ursula/migration.sql diff --git a/packages/opencode/migration/20260127222353_familiar_lady_ursula/snapshot.json b/packages/core/migration/20260127222353_familiar_lady_ursula/snapshot.json similarity index 100% rename from packages/opencode/migration/20260127222353_familiar_lady_ursula/snapshot.json rename to packages/core/migration/20260127222353_familiar_lady_ursula/snapshot.json diff --git a/packages/opencode/migration/20260211171708_add_project_commands/migration.sql b/packages/core/migration/20260211171708_add_project_commands/migration.sql similarity index 100% rename from packages/opencode/migration/20260211171708_add_project_commands/migration.sql rename to packages/core/migration/20260211171708_add_project_commands/migration.sql diff --git a/packages/opencode/migration/20260211171708_add_project_commands/snapshot.json b/packages/core/migration/20260211171708_add_project_commands/snapshot.json similarity index 100% rename from packages/opencode/migration/20260211171708_add_project_commands/snapshot.json rename to packages/core/migration/20260211171708_add_project_commands/snapshot.json diff --git a/packages/opencode/migration/20260213144116_wakeful_the_professor/migration.sql b/packages/core/migration/20260213144116_wakeful_the_professor/migration.sql similarity index 100% rename from packages/opencode/migration/20260213144116_wakeful_the_professor/migration.sql rename to packages/core/migration/20260213144116_wakeful_the_professor/migration.sql diff --git a/packages/opencode/migration/20260213144116_wakeful_the_professor/snapshot.json b/packages/core/migration/20260213144116_wakeful_the_professor/snapshot.json similarity index 100% rename from packages/opencode/migration/20260213144116_wakeful_the_professor/snapshot.json rename to packages/core/migration/20260213144116_wakeful_the_professor/snapshot.json diff --git a/packages/opencode/migration/20260225215848_workspace/migration.sql b/packages/core/migration/20260225215848_workspace/migration.sql similarity index 100% rename from packages/opencode/migration/20260225215848_workspace/migration.sql rename to packages/core/migration/20260225215848_workspace/migration.sql diff --git a/packages/opencode/migration/20260225215848_workspace/snapshot.json b/packages/core/migration/20260225215848_workspace/snapshot.json similarity index 100% rename from packages/opencode/migration/20260225215848_workspace/snapshot.json rename to packages/core/migration/20260225215848_workspace/snapshot.json diff --git a/packages/opencode/migration/20260227213759_add_session_workspace_id/migration.sql b/packages/core/migration/20260227213759_add_session_workspace_id/migration.sql similarity index 100% rename from packages/opencode/migration/20260227213759_add_session_workspace_id/migration.sql rename to packages/core/migration/20260227213759_add_session_workspace_id/migration.sql diff --git a/packages/opencode/migration/20260227213759_add_session_workspace_id/snapshot.json b/packages/core/migration/20260227213759_add_session_workspace_id/snapshot.json similarity index 100% rename from packages/opencode/migration/20260227213759_add_session_workspace_id/snapshot.json rename to packages/core/migration/20260227213759_add_session_workspace_id/snapshot.json diff --git a/packages/opencode/migration/20260228203230_blue_harpoon/migration.sql b/packages/core/migration/20260228203230_blue_harpoon/migration.sql similarity index 100% rename from packages/opencode/migration/20260228203230_blue_harpoon/migration.sql rename to packages/core/migration/20260228203230_blue_harpoon/migration.sql diff --git a/packages/opencode/migration/20260228203230_blue_harpoon/snapshot.json b/packages/core/migration/20260228203230_blue_harpoon/snapshot.json similarity index 100% rename from packages/opencode/migration/20260228203230_blue_harpoon/snapshot.json rename to packages/core/migration/20260228203230_blue_harpoon/snapshot.json diff --git a/packages/opencode/migration/20260303231226_add_workspace_fields/migration.sql b/packages/core/migration/20260303231226_add_workspace_fields/migration.sql similarity index 100% rename from packages/opencode/migration/20260303231226_add_workspace_fields/migration.sql rename to packages/core/migration/20260303231226_add_workspace_fields/migration.sql diff --git a/packages/opencode/migration/20260303231226_add_workspace_fields/snapshot.json b/packages/core/migration/20260303231226_add_workspace_fields/snapshot.json similarity index 100% rename from packages/opencode/migration/20260303231226_add_workspace_fields/snapshot.json rename to packages/core/migration/20260303231226_add_workspace_fields/snapshot.json diff --git a/packages/opencode/migration/20260309230000_move_org_to_state/migration.sql b/packages/core/migration/20260309230000_move_org_to_state/migration.sql similarity index 100% rename from packages/opencode/migration/20260309230000_move_org_to_state/migration.sql rename to packages/core/migration/20260309230000_move_org_to_state/migration.sql diff --git a/packages/opencode/migration/20260309230000_move_org_to_state/snapshot.json b/packages/core/migration/20260309230000_move_org_to_state/snapshot.json similarity index 100% rename from packages/opencode/migration/20260309230000_move_org_to_state/snapshot.json rename to packages/core/migration/20260309230000_move_org_to_state/snapshot.json diff --git a/packages/opencode/migration/20260312043431_session_message_cursor/migration.sql b/packages/core/migration/20260312043431_session_message_cursor/migration.sql similarity index 100% rename from packages/opencode/migration/20260312043431_session_message_cursor/migration.sql rename to packages/core/migration/20260312043431_session_message_cursor/migration.sql diff --git a/packages/opencode/migration/20260312043431_session_message_cursor/snapshot.json b/packages/core/migration/20260312043431_session_message_cursor/snapshot.json similarity index 100% rename from packages/opencode/migration/20260312043431_session_message_cursor/snapshot.json rename to packages/core/migration/20260312043431_session_message_cursor/snapshot.json diff --git a/packages/opencode/migration/20260323234822_events/migration.sql b/packages/core/migration/20260323234822_events/migration.sql similarity index 100% rename from packages/opencode/migration/20260323234822_events/migration.sql rename to packages/core/migration/20260323234822_events/migration.sql diff --git a/packages/opencode/migration/20260323234822_events/snapshot.json b/packages/core/migration/20260323234822_events/snapshot.json similarity index 100% rename from packages/opencode/migration/20260323234822_events/snapshot.json rename to packages/core/migration/20260323234822_events/snapshot.json diff --git a/packages/opencode/migration/20260410174513_workspace-name/migration.sql b/packages/core/migration/20260410174513_workspace-name/migration.sql similarity index 100% rename from packages/opencode/migration/20260410174513_workspace-name/migration.sql rename to packages/core/migration/20260410174513_workspace-name/migration.sql diff --git a/packages/opencode/migration/20260410174513_workspace-name/snapshot.json b/packages/core/migration/20260410174513_workspace-name/snapshot.json similarity index 100% rename from packages/opencode/migration/20260410174513_workspace-name/snapshot.json rename to packages/core/migration/20260410174513_workspace-name/snapshot.json diff --git a/packages/opencode/migration/20260413175956_chief_energizer/migration.sql b/packages/core/migration/20260413175956_chief_energizer/migration.sql similarity index 100% rename from packages/opencode/migration/20260413175956_chief_energizer/migration.sql rename to packages/core/migration/20260413175956_chief_energizer/migration.sql diff --git a/packages/opencode/migration/20260413175956_chief_energizer/snapshot.json b/packages/core/migration/20260413175956_chief_energizer/snapshot.json similarity index 100% rename from packages/opencode/migration/20260413175956_chief_energizer/snapshot.json rename to packages/core/migration/20260413175956_chief_energizer/snapshot.json diff --git a/packages/opencode/migration/20260423070820_add_icon_url_override/migration.sql b/packages/core/migration/20260423070820_add_icon_url_override/migration.sql similarity index 100% rename from packages/opencode/migration/20260423070820_add_icon_url_override/migration.sql rename to packages/core/migration/20260423070820_add_icon_url_override/migration.sql diff --git a/packages/opencode/migration/20260423070820_add_icon_url_override/snapshot.json b/packages/core/migration/20260423070820_add_icon_url_override/snapshot.json similarity index 100% rename from packages/opencode/migration/20260423070820_add_icon_url_override/snapshot.json rename to packages/core/migration/20260423070820_add_icon_url_override/snapshot.json diff --git a/packages/opencode/migration/20260427172553_slow_nightmare/migration.sql b/packages/core/migration/20260427172553_slow_nightmare/migration.sql similarity index 100% rename from packages/opencode/migration/20260427172553_slow_nightmare/migration.sql rename to packages/core/migration/20260427172553_slow_nightmare/migration.sql diff --git a/packages/opencode/migration/20260427172553_slow_nightmare/snapshot.json b/packages/core/migration/20260427172553_slow_nightmare/snapshot.json similarity index 100% rename from packages/opencode/migration/20260427172553_slow_nightmare/snapshot.json rename to packages/core/migration/20260427172553_slow_nightmare/snapshot.json diff --git a/packages/opencode/migration/20260428004200_add_session_path/migration.sql b/packages/core/migration/20260428004200_add_session_path/migration.sql similarity index 100% rename from packages/opencode/migration/20260428004200_add_session_path/migration.sql rename to packages/core/migration/20260428004200_add_session_path/migration.sql diff --git a/packages/opencode/migration/20260428004200_add_session_path/snapshot.json b/packages/core/migration/20260428004200_add_session_path/snapshot.json similarity index 100% rename from packages/opencode/migration/20260428004200_add_session_path/snapshot.json rename to packages/core/migration/20260428004200_add_session_path/snapshot.json diff --git a/packages/opencode/migration/20260501142318_next_venus/migration.sql b/packages/core/migration/20260501142318_next_venus/migration.sql similarity index 100% rename from packages/opencode/migration/20260501142318_next_venus/migration.sql rename to packages/core/migration/20260501142318_next_venus/migration.sql diff --git a/packages/opencode/migration/20260501142318_next_venus/snapshot.json b/packages/core/migration/20260501142318_next_venus/snapshot.json similarity index 100% rename from packages/opencode/migration/20260501142318_next_venus/snapshot.json rename to packages/core/migration/20260501142318_next_venus/snapshot.json diff --git a/packages/opencode/migration/20260504145000_add_sync_owner/migration.sql b/packages/core/migration/20260504145000_add_sync_owner/migration.sql similarity index 100% rename from packages/opencode/migration/20260504145000_add_sync_owner/migration.sql rename to packages/core/migration/20260504145000_add_sync_owner/migration.sql diff --git a/packages/opencode/migration/20260504145000_add_sync_owner/snapshot.json b/packages/core/migration/20260504145000_add_sync_owner/snapshot.json similarity index 100% rename from packages/opencode/migration/20260504145000_add_sync_owner/snapshot.json rename to packages/core/migration/20260504145000_add_sync_owner/snapshot.json diff --git a/packages/opencode/migration/20260507164347_add_workspace_time/migration.sql b/packages/core/migration/20260507164347_add_workspace_time/migration.sql similarity index 100% rename from packages/opencode/migration/20260507164347_add_workspace_time/migration.sql rename to packages/core/migration/20260507164347_add_workspace_time/migration.sql diff --git a/packages/opencode/migration/20260507164347_add_workspace_time/snapshot.json b/packages/core/migration/20260507164347_add_workspace_time/snapshot.json similarity index 100% rename from packages/opencode/migration/20260507164347_add_workspace_time/snapshot.json rename to packages/core/migration/20260507164347_add_workspace_time/snapshot.json diff --git a/packages/opencode/migration/20260510033149_session_usage/migration.sql b/packages/core/migration/20260510033149_session_usage/migration.sql similarity index 100% rename from packages/opencode/migration/20260510033149_session_usage/migration.sql rename to packages/core/migration/20260510033149_session_usage/migration.sql diff --git a/packages/opencode/migration/20260510033149_session_usage/snapshot.json b/packages/core/migration/20260510033149_session_usage/snapshot.json similarity index 100% rename from packages/opencode/migration/20260510033149_session_usage/snapshot.json rename to packages/core/migration/20260510033149_session_usage/snapshot.json diff --git a/packages/opencode/migration/20260511000411_data_migration_state/migration.sql b/packages/core/migration/20260511000411_data_migration_state/migration.sql similarity index 100% rename from packages/opencode/migration/20260511000411_data_migration_state/migration.sql rename to packages/core/migration/20260511000411_data_migration_state/migration.sql diff --git a/packages/opencode/migration/20260511000411_data_migration_state/snapshot.json b/packages/core/migration/20260511000411_data_migration_state/snapshot.json similarity index 100% rename from packages/opencode/migration/20260511000411_data_migration_state/snapshot.json rename to packages/core/migration/20260511000411_data_migration_state/snapshot.json diff --git a/packages/core/migration/20260511173437_session-metadata/migration.sql b/packages/core/migration/20260511173437_session-metadata/migration.sql new file mode 100644 index 000000000000..1f8fcaf64a70 --- /dev/null +++ b/packages/core/migration/20260511173437_session-metadata/migration.sql @@ -0,0 +1 @@ +ALTER TABLE `session` ADD `metadata` text; diff --git a/packages/core/migration/20260511173437_session-metadata/snapshot.json b/packages/core/migration/20260511173437_session-metadata/snapshot.json new file mode 100644 index 000000000000..8c979997ca85 --- /dev/null +++ b/packages/core/migration/20260511173437_session-metadata/snapshot.json @@ -0,0 +1,1560 @@ +{ + "version": "7", + "dialect": "sqlite", + "id": "bf93c73b-5a48-4d63-9909-3c36a79b9788", + "prevIds": ["be5eae31-b7f8-4292-8827-c36a524abd1b", "fdfcccee-fb3a-481f-b801-b9835fa30d5d"], + "ddl": [ + { + "name": "workspace", + "entityType": "tables" + }, + { + "name": "data_migration", + "entityType": "tables" + }, + { + "name": "account_state", + "entityType": "tables" + }, + { + "name": "account", + "entityType": "tables" + }, + { + "name": "control_account", + "entityType": "tables" + }, + { + "name": "event_sequence", + "entityType": "tables" + }, + { + "name": "event", + "entityType": "tables" + }, + { + "name": "project", + "entityType": "tables" + }, + { + "name": "message", + "entityType": "tables" + }, + { + "name": "part", + "entityType": "tables" + }, + { + "name": "permission", + "entityType": "tables" + }, + { + "name": "session_message", + "entityType": "tables" + }, + { + "name": "session", + "entityType": "tables" + }, + { + "name": "todo", + "entityType": "tables" + }, + { + "name": "session_share", + "entityType": "tables" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "''", + "generated": null, + "name": "name", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "branch", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "directory", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "extra", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_used", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "name", + "entityType": "columns", + "table": "data_migration" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_completed", + "entityType": "columns", + "table": "data_migration" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "account_state" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "active_account_id", + "entityType": "columns", + "table": "account_state" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "active_org_id", + "entityType": "columns", + "table": "account_state" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "email", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "url", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "access_token", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "refresh_token", + "entityType": "columns", + "table": "account" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "token_expiry", + "entityType": "columns", + "table": "account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "email", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "url", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "access_token", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "refresh_token", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "token_expiry", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "active", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "aggregate_id", + "entityType": "columns", + "table": "event_sequence" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "seq", + "entityType": "columns", + "table": "event_sequence" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "owner_id", + "entityType": "columns", + "table": "event_sequence" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "aggregate_id", + "entityType": "columns", + "table": "event" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "seq", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "worktree", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "vcs", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "name", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "icon_url", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "icon_url_override", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "icon_color", + "entityType": "columns", + "table": "project" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "project" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "project" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_initialized", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "sandboxes", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "commands", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "message" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "message_id", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "part" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "part" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "permission" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "permission" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "permission" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "permission" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "workspace_id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "parent_id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "slug", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "directory", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "path", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "title", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "version", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "share_url", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_additions", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_deletions", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_files", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_diffs", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "metadata", + "entityType": "columns", + "table": "session" + }, + { + "type": "real", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "name": "cost", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "name": "tokens_input", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "name": "tokens_output", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "name": "tokens_reasoning", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "name": "tokens_cache_read", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "name": "tokens_cache_write", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "revert", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "permission", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "agent", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "model", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_compacting", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_archived", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "content", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "status", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "priority", + "entityType": "columns", + "table": "todo" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "position", + "entityType": "columns", + "table": "todo" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "todo" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "secret", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "url", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "session_share" + }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_workspace_project_id_project_id_fk", + "entityType": "fks", + "table": "workspace" + }, + { + "columns": ["active_account_id"], + "tableTo": "account", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "nameExplicit": false, + "name": "fk_account_state_active_account_id_account_id_fk", + "entityType": "fks", + "table": "account_state" + }, + { + "columns": ["aggregate_id"], + "tableTo": "event_sequence", + "columnsTo": ["aggregate_id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_event_aggregate_id_event_sequence_aggregate_id_fk", + "entityType": "fks", + "table": "event" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_message_session_id_session_id_fk", + "entityType": "fks", + "table": "message" + }, + { + "columns": ["message_id"], + "tableTo": "message", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_part_message_id_message_id_fk", + "entityType": "fks", + "table": "part" + }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_permission_project_id_project_id_fk", + "entityType": "fks", + "table": "permission" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_message_session_id_session_id_fk", + "entityType": "fks", + "table": "session_message" + }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_project_id_project_id_fk", + "entityType": "fks", + "table": "session" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_todo_session_id_session_id_fk", + "entityType": "fks", + "table": "todo" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_share_session_id_session_id_fk", + "entityType": "fks", + "table": "session_share" + }, + { + "columns": ["email", "url"], + "nameExplicit": false, + "name": "control_account_pk", + "entityType": "pks", + "table": "control_account" + }, + { + "columns": ["session_id", "position"], + "nameExplicit": false, + "name": "todo_pk", + "entityType": "pks", + "table": "todo" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "workspace_pk", + "table": "workspace", + "entityType": "pks" + }, + { + "columns": ["name"], + "nameExplicit": false, + "name": "data_migration_pk", + "table": "data_migration", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "account_state_pk", + "table": "account_state", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "account_pk", + "table": "account", + "entityType": "pks" + }, + { + "columns": ["aggregate_id"], + "nameExplicit": false, + "name": "event_sequence_pk", + "table": "event_sequence", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "event_pk", + "table": "event", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "project_pk", + "table": "project", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "message_pk", + "table": "message", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "part_pk", + "table": "part", + "entityType": "pks" + }, + { + "columns": ["project_id"], + "nameExplicit": false, + "name": "permission_pk", + "table": "permission", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "session_message_pk", + "table": "session_message", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "session_pk", + "table": "session", + "entityType": "pks" + }, + { + "columns": ["session_id"], + "nameExplicit": false, + "name": "session_share_pk", + "table": "session_share", + "entityType": "pks" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + }, + { + "value": "time_created", + "isExpression": false + }, + { + "value": "id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "message_session_time_created_id_idx", + "entityType": "indexes", + "table": "message" + }, + { + "columns": [ + { + "value": "message_id", + "isExpression": false + }, + { + "value": "id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "part_message_id_id_idx", + "entityType": "indexes", + "table": "part" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "part_session_idx", + "entityType": "indexes", + "table": "part" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_message_session_idx", + "entityType": "indexes", + "table": "session_message" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + }, + { + "value": "type", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_message_session_type_idx", + "entityType": "indexes", + "table": "session_message" + }, + { + "columns": [ + { + "value": "time_created", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_message_time_created_idx", + "entityType": "indexes", + "table": "session_message" + }, + { + "columns": [ + { + "value": "project_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_project_idx", + "entityType": "indexes", + "table": "session" + }, + { + "columns": [ + { + "value": "workspace_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_workspace_idx", + "entityType": "indexes", + "table": "session" + }, + { + "columns": [ + { + "value": "parent_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_parent_idx", + "entityType": "indexes", + "table": "session" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "todo_session_idx", + "entityType": "indexes", + "table": "todo" + } + ], + "renames": [] +} diff --git a/packages/core/package.json b/packages/core/package.json index 738e4d80bf48..1c3f2a3f0024 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,11 +1,13 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "1.15.10", + "version": "1.15.13", "name": "@opencode-ai/core", "type": "module", "license": "MIT", "private": true, "scripts": { + "db": "bun drizzle-kit", + "migration": "bun run script/migration.ts", "test": "bun test", "test:ci": "mkdir -p .artifacts/unit && bun test --timeout 30000 --reporter=junit --reporter-outfile=.artifacts/unit/junit.xml", "typecheck": "tsgo --noEmit" @@ -16,14 +18,21 @@ "exports": { "./*": "./src/*.ts" }, - "imports": {}, + "imports": { + "#sqlite": { + "bun": "./src/database/sqlite.bun.ts", + "node": "./src/database/sqlite.node.ts", + "default": "./src/database/sqlite.bun.ts" + } + }, "devDependencies": { "@tsconfig/bun": "catalog:", "@types/bun": "catalog:", "@types/cross-spawn": "catalog:", "@types/npm-package-arg": "6.1.4", "@types/npmcli__arborist": "6.3.3", - "@types/semver": "catalog:" + "@types/semver": "catalog:", + "drizzle-kit": "catalog:" }, "dependencies": { "@ai-sdk/alibaba": "1.0.17", @@ -34,8 +43,8 @@ "@ai-sdk/cohere": "3.0.27", "@ai-sdk/deepinfra": "2.0.41", "@ai-sdk/gateway": "3.0.104", - "@ai-sdk/google": "3.0.75", - "@ai-sdk/google-vertex": "4.0.131", + "@ai-sdk/google": "3.0.73", + "@ai-sdk/google-vertex": "4.0.128", "@ai-sdk/groq": "3.0.31", "@ai-sdk/mistral": "3.0.27", "@ai-sdk/openai": "3.0.53", @@ -49,8 +58,11 @@ "@aws-sdk/credential-providers": "3.993.0", "@effect/opentelemetry": "catalog:", "@effect/platform-node": "catalog:", + "@effect/sql-sqlite-bun": "catalog:", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", + "@opencode-ai/effect-drizzle-sqlite": "workspace:*", + "@opencode-ai/effect-sqlite-node": "workspace:*", "@opentelemetry/api": "1.9.0", "@opentelemetry/context-async-hooks": "2.6.1", "@opentelemetry/exporter-trace-otlp-http": "0.214.0", @@ -58,11 +70,13 @@ "@openrouter/ai-sdk-provider": "2.8.1", "ai-gateway-provider": "3.1.2", "cross-spawn": "catalog:", + "drizzle-orm": "catalog:", "effect": "catalog:", - "gitlab-ai-provider": "6.7.0", + "gitlab-ai-provider": "6.8.0", "glob": "13.0.5", "google-auth-library": "10.5.0", "immer": "11.1.4", + "jsonc-parser": "3.3.1", "mime-types": "3.0.2", "minimatch": "10.2.5", "npm-package-arg": "13.0.2", diff --git a/packages/core/script/migration.ts b/packages/core/script/migration.ts new file mode 100644 index 000000000000..5a8fb6451fad --- /dev/null +++ b/packages/core/script/migration.ts @@ -0,0 +1,122 @@ +#!/usr/bin/env bun + +import { $ } from "bun" +import fs from "fs/promises" +import os from "os" +import path from "path" +import { pathToFileURL } from "url" + +const root = path.resolve(import.meta.dirname, "../../..") +const sqlDir = path.join(root, "packages/core/migration") +const tsDir = path.join(root, "packages/core/src/database/migration") +const registry = path.join(root, "packages/core/src/database/migration.gen.ts") + +if (Bun.argv.includes("--check")) { + await check() + process.exit(0) +} + +await $`bun drizzle-kit generate`.cwd(path.join(root, "packages/core")) + +const sqlMigrations = (await Array.fromAsync(new Bun.Glob("*/migration.sql").scan({ cwd: sqlDir }))) + .map((file) => file.split("/")[0]) + .filter((name) => name !== undefined) + .sort() + +for (const name of sqlMigrations) { + if (await Bun.file(path.join(tsDir, `${name}.ts`)).exists()) continue + await Bun.write( + path.join(tsDir, `${name}.ts`), + renderMigration(name, await Bun.file(path.join(sqlDir, name, "migration.sql")).text()), + ) +} + +await Bun.write(registry, renderRegistry(sqlMigrations)) + +async function check() { + const temporary = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-core-migration-check-")) + const output = path.join(temporary, "migration") + try { + await fs.cp(sqlDir, output, { recursive: true }) + const config = path.join(temporary, "drizzle.config.ts") + await Bun.write( + config, + `import config from ${JSON.stringify(pathToFileURL(path.join(root, "packages/core/drizzle.config.ts")).href)} + +export default { ...config, out: ${JSON.stringify(output)} } +`, + ) + const before = await snapshot(output) + await $`bun drizzle-kit generate --config ${config}`.cwd(path.join(root, "packages/core")) + const after = await snapshot(output) + if (JSON.stringify(after) !== JSON.stringify(before)) { + throw new Error( + "Core schema has ungenerated database migrations. Run `bun script/migration.ts` from packages/core.", + ) + } + + const migrations = before + .map((entry) => entry.path.split("/")[0]) + .filter((name, index, all) => name !== undefined && all.indexOf(name) === index) + .sort() + for (const name of migrations) { + if (await Bun.file(path.join(tsDir, `${name}.ts`)).exists()) continue + throw new Error( + `Database migration TypeScript wrapper is missing for ${name}. Run \`bun script/migration.ts\` from packages/core.`, + ) + } + if ((await Bun.file(registry).text()) !== renderRegistry(migrations)) { + throw new Error("Database migration registry is stale. Run `bun script/migration.ts` from packages/core.") + } + } finally { + await fs.rm(temporary, { recursive: true, force: true }) + } +} + +async function snapshot(directory: string) { + const files = await Array.fromAsync(new Bun.Glob("**/*").scan({ cwd: directory, onlyFiles: true })) + return Promise.all( + files.sort().map(async (file) => ({ path: file, contents: await Bun.file(path.join(directory, file)).text() })), + ) +} + +function renderMigration(name: string, sql: string) { + return `import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: ${JSON.stringify(name)}, + up(tx) { + return Effect.gen(function* () { +${sql + .split("--> statement-breakpoint") + .map((statement) => statement.trim()) + .filter((statement) => statement.length > 0) + .map(renderRun) + .join("\n")} + }) + }, +} satisfies DatabaseMigration.Migration +` +} + +function renderRun(statement: string) { + const lines = statement.replaceAll("\t", " ").split("\n") + if (lines.length === 1) return ` yield* tx.run(\`${escapeTemplate(lines[0])}\`)` + return ` yield* tx.run(\`\n${lines.map((line) => ` ${escapeTemplate(line)}`).join("\n")}\n \`)` +} + +function escapeTemplate(line: string) { + return line.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${") +} + +function renderRegistry(names: string[]) { + return `import type { DatabaseMigration } from "./migration" + +export const migrations = ( + await Promise.all([ +${names.map((name) => ` import("./migration/${name}"),`).join("\n")} + ]) +).map((module) => module.default) satisfies DatabaseMigration.Migration[] +` +} diff --git a/packages/core/src/account.ts b/packages/core/src/account.ts index a124a9a15811..4de8176e4bc8 100644 --- a/packages/core/src/account.ts +++ b/packages/core/src/account.ts @@ -1,319 +1,101 @@ -import path from "path" -import { Effect, Layer, Option, Schema, Context, SynchronizedRef } from "effect" -import { Identifier } from "./util/identifier" -import { NonNegativeInt, withStatics } from "./schema" -import { Global } from "./global" -import { AppFileSystem } from "./filesystem" -import { EventV2 } from "./event" +export * as AccountV2 from "./account" -export const ID = Schema.String.pipe( - Schema.brand("AccountV2.ID"), - withStatics((schema) => ({ create: () => schema.make("acc_" + Identifier.ascending()) })), -) -export type ID = typeof ID.Type +import { Schema } from "effect" +import type * as HttpClientError from "effect/unstable/http/HttpClientError" -export const ServiceID = Schema.String.pipe(Schema.brand("ServiceID")) -export type ServiceID = typeof ServiceID.Type +export const ID = Schema.String.pipe(Schema.brand("AccountID")) +export type ID = Schema.Schema.Type -export class OAuthCredential extends Schema.Class("AccountV2.OAuthCredential")({ - type: Schema.Literal("oauth"), - refresh: Schema.String, - access: Schema.String, - expires: NonNegativeInt, -}) {} +export const OrgID = Schema.String.pipe(Schema.brand("OrgID")) +export type OrgID = Schema.Schema.Type -export class ApiKeyCredential extends Schema.Class("AccountV2.ApiKeyCredential")({ - type: Schema.Literal("api"), - key: Schema.String, - metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)), -}) {} +export const AccessToken = Schema.String.pipe(Schema.brand("AccessToken")) +export type AccessToken = Schema.Schema.Type -export const Credential = Schema.Union([OAuthCredential, ApiKeyCredential]) - .pipe(Schema.toTaggedUnion("type")) - .annotate({ - identifier: "AccountV2.Credential", - }) -export type Credential = Schema.Schema.Type +export const RefreshToken = Schema.String.pipe(Schema.brand("RefreshToken")) +export type RefreshToken = Schema.Schema.Type -export class Info extends Schema.Class("AccountV2.Info")({ +export const DeviceCode = Schema.String.pipe(Schema.brand("DeviceCode")) +export type DeviceCode = Schema.Schema.Type + +export const UserCode = Schema.String.pipe(Schema.brand("UserCode")) +export type UserCode = Schema.Schema.Type + +export class Info extends Schema.Class("Account")({ id: ID, - serviceID: ServiceID, - description: Schema.String, - credential: Credential, + email: Schema.String, + url: Schema.String, + active_org_id: Schema.NullOr(OrgID), }) {} -export class FileWriteError extends Schema.TaggedErrorClass()("AccountV2.FileWriteError", { - operation: Schema.Union([Schema.Literal("migrate"), Schema.Literal("write")]), - cause: Schema.Defect, +export class Org extends Schema.Class("Org")({ + id: OrgID, + name: Schema.String, }) {} -export type Error = FileWriteError - -export const Event = { - Added: EventV2.define({ - type: "account.added", - schema: { - account: Info, - }, - }), - Removed: EventV2.define({ - type: "account.removed", - schema: { - account: Info, - }, - }), - Switched: EventV2.define({ - type: "account.switched", - schema: { - serviceID: ServiceID, - from: Schema.optional(ID), - to: Schema.optional(ID), - }, - }), -} - -interface Writable { - version: 2 - accounts: Record - active: Record -} +export class AccountRepoError extends Schema.TaggedErrorClass()("AccountRepoError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect), +}) {} -const decodeV1 = Schema.decodeUnknownOption(Schema.Record(Schema.String, Credential)) +export class AccountServiceError extends Schema.TaggedErrorClass()("AccountServiceError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect), +}) {} -function migrate(old: Record): Writable { - const accounts: Record = {} - const active: Record = {} - for (const [serviceID, value] of Object.entries(old)) { - const decoded = Option.getOrElse(decodeV1({ [serviceID]: value }), () => ({})) - const parsed = (decoded as Record)[serviceID] - if (!parsed) continue - const id = Identifier.ascending() - const account = ID.make(id) - const brandedServiceID = ServiceID.make(serviceID) - accounts[id] = new Info({ - id: account, - serviceID: brandedServiceID, - description: "default", - credential: parsed, +export class AccountTransportError extends Schema.TaggedErrorClass()("AccountTransportError", { + method: Schema.String, + url: Schema.String, + description: Schema.optional(Schema.String), + cause: Schema.optional(Schema.Defect), +}) { + static fromHttpClientError(error: HttpClientError.TransportError): AccountTransportError { + return new AccountTransportError({ + method: error.request.method, + url: error.request.url, + description: error.description, + cause: error.cause, }) - active[brandedServiceID] = account } - return { version: 2, accounts, active } -} -export interface Interface { - readonly get: (id: ID) => Effect.Effect - readonly all: () => Effect.Effect - readonly create: (input: { - serviceID: ServiceID - credential: Credential - description?: string - }) => Effect.Effect - readonly update: (id: ID, updates: Partial>) => Effect.Effect - readonly remove: (id: ID) => Effect.Effect - readonly activate: (id: ID) => Effect.Effect - readonly active: (serviceID: ServiceID) => Effect.Effect - readonly forService: (serviceID: ServiceID) => Effect.Effect + override get message(): string { + return [ + `Could not reach ${this.method} ${this.url}.`, + `This failed before the server returned an HTTP response.`, + this.description, + `Check your network, proxy, or VPN configuration and try again.`, + ] + .filter(Boolean) + .join("\n") + } } -export class Service extends Context.Service()("@opencode/v2/Account") {} - -export const layer = Layer.effect( - Service, - Effect.gen(function* () { - const fsys = yield* AppFileSystem.Service - const global = yield* Global.Service - const events = yield* EventV2.Service - const file = path.join(global.data, "account.json") - const legacyFile = path.join(global.data, "auth.json") - - const writeMigrated = Effect.fnUntraced(function* (raw: Record) { - const migrated = migrate(raw) - yield* fsys - .writeJson(file, migrated, 0o600) - .pipe(Effect.mapError((cause) => new FileWriteError({ operation: "migrate", cause }))) - return migrated - }) - - const parseAuthContent = () => { - try { - return JSON.parse(process.env.OPENCODE_AUTH_CONTENT ?? "") - } catch {} - } - - const load: () => Effect.Effect = Effect.fnUntraced(function* () { - if (process.env.OPENCODE_AUTH_CONTENT) { - const raw = parseAuthContent() - if (raw && typeof raw === "object") { - if ("version" in raw && raw.version === 2) return raw as Writable - return yield* writeMigrated(raw as Record) - } - return { version: 2, accounts: {}, active: {} } - } - - const legacy = yield* fsys.readJson(legacyFile).pipe(Effect.orElseSucceed(() => null)) - if (legacy && typeof legacy === "object") return yield* writeMigrated(legacy as Record) - - const raw = yield* fsys.readJson(file).pipe(Effect.orElseSucceed(() => null)) +export type AccountError = AccountRepoError | AccountServiceError | AccountTransportError - if (raw && typeof raw === "object") { - if ("version" in raw && raw.version === 2) return raw as Writable - return yield* writeMigrated(raw as Record) - } - - return { version: 2, accounts: {}, active: {} } - }) - - const write = (data: Writable) => - fsys - .writeJson(file, data, 0o600) - .pipe(Effect.mapError((cause) => new FileWriteError({ operation: "write", cause }))) - - const state = SynchronizedRef.makeUnsafe( - yield* load().pipe(Effect.orElseSucceed((): Writable => ({ version: 2, accounts: {}, active: {} }))), - ) - - const activate = Effect.fn("AccountV2.activate")(function* (id: ID) { - const data = yield* SynchronizedRef.get(state) - const account = data.accounts[id] - if (!account) return - const activated = yield* SynchronizedRef.modifyEffect( - state, - Effect.fnUntraced(function* (data) { - const nextAccount = data.accounts[id] - if (!nextAccount) return [undefined, data] as const - - const next = { ...data, active: { ...data.active, [nextAccount.serviceID]: id } } - yield* write(next) - return [{ serviceID: nextAccount.serviceID, from: data.active[nextAccount.serviceID], to: id }, next] as const - }), - ) - if (activated) yield* events.publish(Event.Switched, activated) - }) - - const result: Interface = { - get: Effect.fn("AccountV2.get")(function* (id) { - return (yield* SynchronizedRef.get(state)).accounts[id] - }), - - all: Effect.fn("AccountV2.all")(function* () { - return Object.values((yield* SynchronizedRef.get(state)).accounts) - }), - - active: Effect.fn("AccountV2.active")(function* (serviceID) { - const data = yield* SynchronizedRef.get(state) - return ( - data.accounts[data.active[serviceID]] ?? Object.values(data.accounts).find((a) => a.serviceID === serviceID) - ) - }), - - forService: Effect.fn("AccountV2.list")(function* (serviceID) { - return Object.values((yield* SynchronizedRef.get(state)).accounts).filter((a) => a.serviceID === serviceID) - }), - - create: Effect.fn("AccountV2.add")(function* (input) { - const id = ID.make(Identifier.ascending()) - const account = new Info({ - id, - serviceID: input.serviceID, - description: input.description ?? "default", - credential: input.credential, - }) - const added = yield* SynchronizedRef.modifyEffect( - state, - Effect.fnUntraced(function* (data) { - const next = { - ...data, - accounts: { ...data.accounts, [account.id]: account }, - active: { ...data.active, [account.serviceID]: account.id }, - } - - yield* write(next) - return [ - { - account, - switched: { serviceID: account.serviceID, from: data.active[account.serviceID], to: account.id }, - }, - next, - ] as const - }), - ) - yield* events.publish(Event.Added, { account: added.account }) - yield* events.publish(Event.Switched, added.switched) - return added.account - }), - - update: Effect.fn("AccountV2.update")(function* (id, updates) { - const existing = (yield* SynchronizedRef.get(state)).accounts[id] - if (!existing) return - yield* SynchronizedRef.modifyEffect( - state, - Effect.fnUntraced(function* (data) { - if (!data.accounts[id]) return [undefined, data] as const - - const next = { - ...data, - accounts: { - ...data.accounts, - [id]: new Info({ - id, - serviceID: existing.serviceID, - description: updates.description ?? existing.description, - credential: updates.credential ?? existing.credential, - }), - }, - } +export class Login extends Schema.Class("Login")({ + code: DeviceCode, + user: UserCode, + url: Schema.String, + server: Schema.String, + expiry: Schema.Duration, + interval: Schema.Duration, +}) {} - yield* write(next) - return [undefined, next] as const - }), - ) - }), +export class PollSuccess extends Schema.TaggedClass()("PollSuccess", { + email: Schema.String, +}) {} - remove: Effect.fn("AccountV2.remove")(function* (id) { - const removed = yield* SynchronizedRef.modifyEffect( - state, - Effect.fnUntraced(function* (data) { - const accounts = { ...data.accounts } - const active = { ...data.active } - const removed = accounts[id] - if (!removed) return [undefined, data] as const - const wasActive = active[removed.serviceID] === id - delete accounts[id] - const replacement = Object.values(accounts).find((account) => account.serviceID === removed.serviceID) - if (wasActive) { - if (replacement) active[removed.serviceID] = replacement.id - else delete active[removed.serviceID] - } +export class PollPending extends Schema.TaggedClass()("PollPending", {}) {} - const next = { ...data, accounts, active } - yield* write(next) - return [ - { - account: removed, - switched: wasActive ? { serviceID: removed.serviceID, from: id, to: replacement?.id } : undefined, - }, - next, - ] as const - }), - ) - if (removed) { - yield* events.publish(Event.Removed, { account: removed.account }) - if (removed.switched) yield* events.publish(Event.Switched, removed.switched) - } - }), +export class PollSlow extends Schema.TaggedClass()("PollSlow", {}) {} - activate, - } +export class PollExpired extends Schema.TaggedClass()("PollExpired", {}) {} - return Service.of(result) - }), -) +export class PollDenied extends Schema.TaggedClass()("PollDenied", {}) {} -export const defaultLayer = layer.pipe( - Layer.provide(AppFileSystem.defaultLayer), - Layer.provide(Global.defaultLayer), - Layer.provide(EventV2.defaultLayer), -) +export class PollError extends Schema.TaggedClass()("PollError", { + cause: Schema.Defect, +}) {} -export * as AccountV2 from "./account" +export const PollResult = Schema.Union([PollSuccess, PollPending, PollSlow, PollExpired, PollDenied, PollError]) +export type PollResult = Schema.Schema.Type diff --git a/packages/opencode/src/account/account.sql.ts b/packages/core/src/account/sql.ts similarity index 61% rename from packages/opencode/src/account/account.sql.ts rename to packages/core/src/account/sql.ts index 35bfd1e3ed4c..4f45651d78ec 100644 --- a/packages/opencode/src/account/account.sql.ts +++ b/packages/core/src/account/sql.ts @@ -1,14 +1,14 @@ import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core" -import { type AccessToken, type AccountID, type OrgID, type RefreshToken } from "./schema" -import { Timestamps } from "../storage/schema.sql" +import { AccountV2 } from "../account" +import { Timestamps } from "../database/schema.sql" export const AccountTable = sqliteTable("account", { - id: text().$type().primaryKey(), + id: text().$type().primaryKey(), email: text().notNull(), url: text().notNull(), - access_token: text().$type().notNull(), - refresh_token: text().$type().notNull(), + access_token: text().$type().notNull(), + refresh_token: text().$type().notNull(), token_expiry: integer(), ...Timestamps, }) @@ -16,9 +16,9 @@ export const AccountTable = sqliteTable("account", { export const AccountStateTable = sqliteTable("account_state", { id: integer().primaryKey(), active_account_id: text() - .$type() + .$type() .references(() => AccountTable.id, { onDelete: "set null" }), - active_org_id: text().$type(), + active_org_id: text().$type(), }) // LEGACY @@ -27,8 +27,8 @@ export const ControlAccountTable = sqliteTable( { email: text().notNull(), url: text().notNull(), - access_token: text().$type().notNull(), - refresh_token: text().$type().notNull(), + access_token: text().$type().notNull(), + refresh_token: text().$type().notNull(), token_expiry: integer(), active: integer({ mode: "boolean" }) .notNull() diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts index 7f4456c59f06..c4971b2721cc 100644 --- a/packages/core/src/agent.ts +++ b/packages/core/src/agent.ts @@ -1,147 +1,107 @@ export * as AgentV2 from "./agent" -import { Context, Effect, HashMap, Layer, Option, Order, pipe, Schema, Array } from "effect" -import { produce, type Draft } from "immer" +import { Array, Context, Effect, Layer, Schema, Scope } from "effect" +import { castDraft, enableMapSet, type Draft } from "immer" import { ModelV2 } from "./model" import { PermissionV2 } from "./permission" -import { PluginV2 } from "./plugin" import { ProviderV2 } from "./provider" +import { PositiveInt } from "./schema" +import { State } from "./state" export const ID = Schema.String.pipe(Schema.brand("AgentV2.ID")) export type ID = typeof ID.Type -export const Mode = Schema.Literals(["subagent", "primary", "all"]).annotate({ identifier: "AgentV2.Mode" }) -export type Mode = typeof Mode.Type +export const Color = Schema.Union([ + Schema.String.check(Schema.isPattern(/^#[0-9a-fA-F]{6}$/)), + Schema.Literals(["primary", "secondary", "accent", "success", "warning", "error", "info"]), +]) -export const Info = Schema.Struct({ - name: ID, - description: Schema.optional(Schema.String), - mode: Mode, - hidden: Schema.Boolean.pipe(Schema.optional), - color: Schema.String.pipe(Schema.optional), - permission: PermissionV2.Ruleset, +export class Info extends Schema.Class("AgentV2.Info")({ + id: ID, model: ModelV2.Ref.pipe(Schema.optional), + options: ProviderV2.Options, system: Schema.String.pipe(Schema.optional), - options: ProviderV2.Options.pipe(Schema.optional), - steps: Schema.Int.pipe(Schema.optional), -}).annotate({ identifier: "AgentV2.Info" }) -export type Info = typeof Info.Type - -export class NotFoundError extends Schema.TaggedErrorClass()("AgentV2.NotFound", { - agent: ID, -}) {} + description: Schema.String.pipe(Schema.optional), + mode: Schema.Literals(["subagent", "primary", "all"]), + hidden: Schema.Boolean, + color: Color.pipe(Schema.optional), + steps: PositiveInt.pipe(Schema.optional), + permissions: PermissionV2.Ruleset, +}) { + static empty(id: ID) { + return new Info({ + id, + options: { + headers: {}, + body: {}, + aisdk: { + provider: {}, + request: {}, + }, + }, + mode: "all", + hidden: false, + permissions: [], + }) + } +} -export class InvalidDefaultError extends Schema.TaggedErrorClass()("AgentV2.InvalidDefault", { - agent: ID, - reason: Schema.Literals(["missing", "subagent", "hidden"]), -}) {} +type Data = { + agents: Map +} -export class NoDefaultError extends Schema.TaggedErrorClass()("AgentV2.NoDefault", {}) {} +export type Editor = { + list: () => readonly Info[] + get: (id: ID) => Info | undefined + update: (id: ID, fn: (agent: Draft) => void) => void + remove: (id: ID) => void +} export interface Interface { - readonly get: (agent: ID) => Effect.Effect - readonly list: () => Effect.Effect - readonly update: (agent: ID, fn: (agent: Draft) => void) => Effect.Effect - readonly remove: (agent: ID) => Effect.Effect - readonly defaultInfo: () => Effect.Effect - readonly defaultAgent: () => Effect.Effect - readonly setDefault: (agent: ID) => Effect.Effect + readonly transform: State.Interface["transform"] + readonly update: (update: State.Transform) => Effect.Effect + readonly get: (id: ID) => Effect.Effect + readonly all: () => Effect.Effect } export class Service extends Context.Service()("@opencode/v2/Agent") {} +enableMapSet() + export const layer = Layer.effect( Service, Effect.gen(function* () { - const plugin = yield* PluginV2.Service - let agents = HashMap.empty() - let defaultAgent: ID | undefined - - const result: Interface = { - get: Effect.fn("AgentV2.get")(function* (agent) { - const match = HashMap.get(agents, agent) - if (!match.valueOrUndefined) return yield* new NotFoundError({ agent }) - return match.value - }), - - list: Effect.fn("AgentV2.list")(function* () { - return pipe( - HashMap.toValues(agents), - Array.sortWith((agent) => agent.name, Order.String), - ) + const state = State.create({ + initial: () => ({ agents: new Map() }), + editor: (draft) => ({ + list: () => Array.fromIterable(draft.agents.values()) as Info[], + get: (id) => draft.agents.get(id), + update: (id, fn) => { + const current = draft.agents.get(id) ?? castDraft(Info.empty(id)) + if (!draft.agents.has(id)) draft.agents.set(id, current) + fn(current) + current.id = id + }, + remove: (id) => { + draft.agents.delete(id) + }, }), + }) - update: Effect.fnUntraced(function* (agent, fn) { - const next = produce( - HashMap.get(agents, agent).pipe( - Option.getOrElse( - () => - ({ - name: agent, - mode: "all", - permission: [], - options: { - headers: {}, - body: {}, - aisdk: { - provider: {}, - request: {}, - }, - }, - }) satisfies Info, - ), - ), - fn, - ) - const updated = yield* plugin.trigger("agent.update", {}, { agent: next, cancel: false }) - if (updated.cancel) return - agents = HashMap.set(agents, agent, { ...updated.agent, name: agent }) + return Service.of({ + transform: state.transform, + update: Effect.fn("AgentV2.update")(function* (update) { + const transform = yield* state.transform() + yield* transform(update) }), - - remove: Effect.fn("AgentV2.remove")(function* (agent) { - const existing = Option.getOrUndefined(HashMap.get(agents, agent)) - if (!existing) return - if ((yield* plugin.trigger("agent.remove", { agent: existing }, { cancel: false })).cancel) return - agents = HashMap.remove(agents, agent) - if (defaultAgent === agent) defaultAgent = undefined - }), - - defaultInfo: Effect.fn("AgentV2.defaultInfo")(function* () { - const updated = yield* plugin.trigger("agent.default", {}, { agent: defaultAgent }) - const selected = updated.agent - if (selected) { - const agent = yield* result - .get(selected) - .pipe( - Effect.catchTag("AgentV2.NotFound", () => - Effect.fail(new InvalidDefaultError({ agent: selected, reason: "missing" })), - ), - ) - if (agent.mode === "subagent") return yield* new InvalidDefaultError({ agent: selected, reason: "subagent" }) - if (agent.hidden === true) return yield* new InvalidDefaultError({ agent: selected, reason: "hidden" }) - return agent - } - - const visible = pipe( - yield* result.list(), - Array.findFirst((agent) => agent.mode !== "subagent" && agent.hidden !== true), - ) - if (Option.isSome(visible)) return visible.value - return yield* new NoDefaultError() + get: Effect.fn("AgentV2.get")(function* (id) { + return state.get().agents.get(id) }), - - defaultAgent: Effect.fn("AgentV2.defaultAgent")(function* () { - return (yield* result.defaultInfo()).name - }), - - setDefault: Effect.fn("AgentV2.setDefault")(function* (agent) { - yield* result.get(agent) - defaultAgent = agent + all: Effect.fn("AgentV2.all")(function* () { + return Array.fromIterable(state.get().agents.values()) }), - } - - return Service.of(result) + }) }), ) -export const defaultLayer = layer.pipe(Layer.provide(PluginV2.defaultLayer)) +export const locationLayer = layer diff --git a/packages/core/src/aisdk.ts b/packages/core/src/aisdk.ts index 5fa2294309c7..f3d39f3ac0c7 100644 --- a/packages/core/src/aisdk.ts +++ b/packages/core/src/aisdk.ts @@ -3,6 +3,7 @@ export * as AISDK from "./aisdk" import type { LanguageModelV3 } from "@ai-sdk/provider" import { Cause, Context, Effect, Layer, Schema } from "effect" import { ModelV2 } from "./model" +import { EventV2 } from "./event" import { PluginV2 } from "./plugin" import { ProviderV2 } from "./provider" @@ -169,4 +170,4 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(PluginV2.defaultLayer)) +export const defaultLayer = layer.pipe(Layer.provide(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer)))) diff --git a/packages/core/src/auth.ts b/packages/core/src/auth.ts new file mode 100644 index 000000000000..a3c97bc8e559 --- /dev/null +++ b/packages/core/src/auth.ts @@ -0,0 +1,340 @@ +export * as Auth from "./auth" + +import path from "path" +import { Effect, Layer, Option, Schema, Context, SynchronizedRef } from "effect" +import { Identifier } from "./util/identifier" +import { NonNegativeInt, withStatics } from "./schema" +import { Global } from "./global" +import { AppFileSystem } from "./filesystem" +import { EventV2 } from "./event" + +export const ID = Schema.String.pipe( + Schema.brand("Auth.ID"), + withStatics((schema) => ({ create: () => schema.make("acc_" + Identifier.ascending()) })), +) +export type ID = typeof ID.Type + +export const ServiceID = Schema.String.pipe(Schema.brand("ServiceID")) +export type ServiceID = typeof ServiceID.Type + +export const OrgID = Schema.String.pipe(Schema.brand("OrgID")) +export type OrgID = typeof OrgID.Type +export const AccessToken = Schema.String.pipe(Schema.brand("AccessToken")) +export type AccessToken = typeof AccessToken.Type +export const RefreshToken = Schema.String.pipe(Schema.brand("RefreshToken")) +export type RefreshToken = typeof RefreshToken.Type + +export class OAuthCredential extends Schema.Class("Auth.OAuthCredential")({ + type: Schema.Literal("oauth"), + refresh: Schema.String, + access: Schema.String, + expires: NonNegativeInt, +}) {} + +export class ApiKeyCredential extends Schema.Class("Auth.ApiKeyCredential")({ + type: Schema.Literal("api"), + key: Schema.String, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}) {} + +export const Credential = Schema.Union([OAuthCredential, ApiKeyCredential]) + .pipe(Schema.toTaggedUnion("type")) + .annotate({ + identifier: "Auth.Credential", + }) +export type Credential = Schema.Schema.Type + +export class Info extends Schema.Class("Auth.Info")({ + id: ID, + serviceID: ServiceID, + description: Schema.String, + credential: Credential, +}) {} + +export class FileWriteError extends Schema.TaggedErrorClass()("Auth.FileWriteError", { + operation: Schema.Union([Schema.Literal("migrate"), Schema.Literal("write")]), + cause: Schema.Defect, +}) {} + +export type Error = FileWriteError + +export const Event = { + Added: EventV2.define({ + type: "account.added", + schema: { + account: Info, + }, + }), + Removed: EventV2.define({ + type: "account.removed", + schema: { + account: Info, + }, + }), + Switched: EventV2.define({ + type: "account.switched", + schema: { + serviceID: ServiceID, + from: Schema.optional(ID), + to: Schema.optional(ID), + }, + }), +} + +interface Writable { + version: 2 + accounts: Record + active: Record +} + +const decodeV1 = Schema.decodeUnknownOption(Schema.Record(Schema.String, Credential)) + +function migrate(old: Record): Writable { + const accounts: Record = {} + const active: Record = {} + for (const [serviceID, value] of Object.entries(old)) { + const decoded = Option.getOrElse(decodeV1({ [serviceID]: value }), () => ({})) + const parsed = (decoded as Record)[serviceID] + if (!parsed) continue + const id = Identifier.ascending() + const account = ID.make(id) + const brandedServiceID = ServiceID.make(serviceID) + accounts[id] = new Info({ + id: account, + serviceID: brandedServiceID, + description: "default", + credential: parsed, + }) + active[brandedServiceID] = account + } + return { version: 2, accounts, active } +} + +export interface Interface { + readonly get: (id: ID) => Effect.Effect + readonly all: () => Effect.Effect + readonly create: (input: { + serviceID: ServiceID + credential: Credential + description?: string + }) => Effect.Effect + readonly update: (id: ID, updates: Partial>) => Effect.Effect + readonly remove: (id: ID) => Effect.Effect + readonly activate: (id: ID) => Effect.Effect + readonly active: (serviceID: ServiceID) => Effect.Effect + readonly activeAll: () => Effect.Effect, Error> + readonly forService: (serviceID: ServiceID) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/v2/Account") {} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const fsys = yield* AppFileSystem.Service + const global = yield* Global.Service + const events = yield* EventV2.Service + const file = path.join(global.data, "account.json") + const legacyFile = path.join(global.data, "auth.json") + + const writeMigrated = Effect.fnUntraced(function* (raw: Record) { + const migrated = migrate(raw) + yield* fsys + .writeJson(file, migrated, 0o600) + .pipe(Effect.mapError((cause) => new FileWriteError({ operation: "migrate", cause }))) + return migrated + }) + + const parseAuthContent = () => { + try { + return JSON.parse(process.env.OPENCODE_AUTH_CONTENT ?? "") + } catch {} + } + + const load: () => Effect.Effect = Effect.fnUntraced(function* () { + if (process.env.OPENCODE_AUTH_CONTENT) { + const raw = parseAuthContent() + if (raw && typeof raw === "object") { + if ("version" in raw && raw.version === 2) return raw as Writable + return yield* writeMigrated(raw as Record) + } + return { version: 2, accounts: {}, active: {} } + } + + const legacy = yield* fsys.readJson(legacyFile).pipe(Effect.orElseSucceed(() => null)) + if (legacy && typeof legacy === "object") return yield* writeMigrated(legacy as Record) + + const raw = yield* fsys.readJson(file).pipe(Effect.orElseSucceed(() => null)) + + if (raw && typeof raw === "object") { + if ("version" in raw && raw.version === 2) return raw as Writable + return yield* writeMigrated(raw as Record) + } + + return { version: 2, accounts: {}, active: {} } + }) + + const write = (data: Writable) => + fsys + .writeJson(file, data, 0o600) + .pipe(Effect.mapError((cause) => new FileWriteError({ operation: "write", cause }))) + + const state = SynchronizedRef.makeUnsafe( + yield* load().pipe(Effect.orElseSucceed((): Writable => ({ version: 2, accounts: {}, active: {} }))), + ) + + const activate = Effect.fn("Auth.activate")(function* (id: ID) { + const data = yield* SynchronizedRef.get(state) + const account = data.accounts[id] + if (!account) return + const activated = yield* SynchronizedRef.modifyEffect( + state, + Effect.fnUntraced(function* (data) { + const nextAccount = data.accounts[id] + if (!nextAccount) return [undefined, data] as const + + const next = { ...data, active: { ...data.active, [nextAccount.serviceID]: id } } + yield* write(next) + return [{ serviceID: nextAccount.serviceID, from: data.active[nextAccount.serviceID], to: id }, next] as const + }), + ) + if (activated) yield* events.publish(Event.Switched, activated) + }) + + const result: Interface = { + get: Effect.fn("Auth.get")(function* (id) { + return (yield* SynchronizedRef.get(state)).accounts[id] + }), + + all: Effect.fn("Auth.all")(function* () { + return Object.values((yield* SynchronizedRef.get(state)).accounts) + }), + + active: Effect.fn("Auth.active")(function* (serviceID) { + const data = yield* SynchronizedRef.get(state) + return ( + data.accounts[data.active[serviceID]] ?? Object.values(data.accounts).find((a) => a.serviceID === serviceID) + ) + }), + + activeAll: Effect.fn("Auth.activeAll")(function* () { + const data = yield* SynchronizedRef.get(state) + const result = new Map() + for (const account of Object.values(data.accounts)) { + if (!result.has(account.serviceID)) result.set(account.serviceID, account) + } + for (const [serviceID, id] of Object.entries(data.active)) { + const account = data.accounts[id] + if (account) result.set(ServiceID.make(serviceID), account) + } + return result + }), + + forService: Effect.fn("Auth.list")(function* (serviceID) { + return Object.values((yield* SynchronizedRef.get(state)).accounts).filter((a) => a.serviceID === serviceID) + }), + + create: Effect.fn("Auth.add")(function* (input) { + const id = ID.make(Identifier.ascending()) + const account = new Info({ + id, + serviceID: input.serviceID, + description: input.description ?? "default", + credential: input.credential, + }) + const added = yield* SynchronizedRef.modifyEffect( + state, + Effect.fnUntraced(function* (data) { + const next = { + ...data, + accounts: { ...data.accounts, [account.id]: account }, + active: { ...data.active, [account.serviceID]: account.id }, + } + + yield* write(next) + return [ + { + account, + switched: { serviceID: account.serviceID, from: data.active[account.serviceID], to: account.id }, + }, + next, + ] as const + }), + ) + yield* events.publish(Event.Added, { account: added.account }) + yield* events.publish(Event.Switched, added.switched) + return added.account + }), + + update: Effect.fn("Auth.update")(function* (id, updates) { + const existing = (yield* SynchronizedRef.get(state)).accounts[id] + if (!existing) return + yield* SynchronizedRef.modifyEffect( + state, + Effect.fnUntraced(function* (data) { + if (!data.accounts[id]) return [undefined, data] as const + + const next = { + ...data, + accounts: { + ...data.accounts, + [id]: new Info({ + id, + serviceID: existing.serviceID, + description: updates.description ?? existing.description, + credential: updates.credential ?? existing.credential, + }), + }, + } + + yield* write(next) + return [undefined, next] as const + }), + ) + }), + + remove: Effect.fn("Auth.remove")(function* (id) { + const removed = yield* SynchronizedRef.modifyEffect( + state, + Effect.fnUntraced(function* (data) { + const accounts = { ...data.accounts } + const active = { ...data.active } + const removed = accounts[id] + if (!removed) return [undefined, data] as const + const wasActive = active[removed.serviceID] === id + delete accounts[id] + const replacement = Object.values(accounts).find((account) => account.serviceID === removed.serviceID) + if (wasActive) { + if (replacement) active[removed.serviceID] = replacement.id + else delete active[removed.serviceID] + } + + const next = { ...data, accounts, active } + yield* write(next) + return [ + { + account: removed, + switched: wasActive ? { serviceID: removed.serviceID, from: id, to: replacement?.id } : undefined, + }, + next, + ] as const + }), + ) + if (removed) { + yield* events.publish(Event.Removed, { account: removed.account }) + if (removed.switched) yield* events.publish(Event.Switched, removed.switched) + } + }), + + activate, + } + + return Service.of(result) + }), +) + +export const defaultLayer = layer.pipe( + Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(Global.defaultLayer), + Layer.provide(EventV2.defaultLayer), +) diff --git a/packages/core/src/catalog.ts b/packages/core/src/catalog.ts index 8fd548501e62..5b53b92bd81b 100644 --- a/packages/core/src/catalog.ts +++ b/packages/core/src/catalog.ts @@ -1,18 +1,22 @@ export * as Catalog from "./catalog" -import { Context, Effect, HashMap, Layer, Option, Order, pipe, Schema, Array, Scope, Semaphore, Stream } from "effect" -import { produce, type Draft } from "immer" +import { Context, Effect, Layer, Option, Order, pipe, Schema, Array, Scope, Stream } from "effect" +import { castDraft, enableMapSet, type Draft } from "immer" import { ModelV2 } from "./model" import { PluginV2 } from "./plugin" import { ProviderV2 } from "./provider" import { Location } from "./location" import { EventV2 } from "./event" +import { Policy } from "./policy" +import { State } from "./state" export type ProviderRecord = { provider: ProviderV2.Info models: Map } +export type DefaultModel = { providerID: ProviderV2.ID; modelID: ModelV2.ID } + export class ProviderNotFoundError extends Schema.TaggedErrorClass()( "CatalogV2.ProviderNotFound", { @@ -25,6 +29,8 @@ export class ModelNotFoundError extends Schema.TaggedErrorClass) => void) => void - updateModel: (providerID: ProviderV2.ID, modelID: ModelV2.ID, fn: (model: Draft) => void) => void +type Data = { + providers: Map + defaultModel?: DefaultModel +} + +export type Editor = { provider: { + list: () => readonly ProviderRecord[] + get: (providerID: ProviderV2.ID) => ProviderRecord | undefined update: (providerID: ProviderV2.ID, fn: (provider: Draft) => void) => void remove: (providerID: ProviderV2.ID) => void } model: { + get: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => ModelV2.Info | undefined update: (providerID: ProviderV2.ID, modelID: ModelV2.ID, fn: (model: Draft) => void) => void remove: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => void + default: { + get: () => DefaultModel | undefined + set: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => void + } } } -export type Loader = (update: (ctx: Context) => void) => Effect.Effect - export interface Interface { - readonly loader: () => Effect.Effect + readonly transform: State.Interface["transform"] readonly provider: { readonly get: (providerID: ProviderV2.ID) => Effect.Effect readonly all: () => Effect.Effect @@ -65,29 +78,25 @@ export interface Interface { readonly all: () => Effect.Effect readonly available: () => Effect.Effect readonly default: () => Effect.Effect> - readonly setDefault: ( - providerID: ProviderV2.ID, - modelID: ModelV2.ID, - ) => Effect.Effect readonly small: (providerID: ProviderV2.ID) => Effect.Effect> } } export class Service extends Context.Service()("@opencode/v2/Catalog") {} +enableMapSet() + export const layer = Layer.effect( Service, Effect.gen(function* () { - yield* Location.Service - let records = HashMap.empty() - let loaders: { update: (ctx: Context) => void }[] = [] - let defaultModel: { providerID: ProviderV2.ID; modelID: ModelV2.ID } | undefined + const location = yield* Location.Service const plugin = yield* PluginV2.Service const events = yield* EventV2.Service + const policy = yield* Policy.Service const scope = yield* Scope.Scope const resolve = (model: ModelV2.Info) => { - const provider = Option.getOrThrow(HashMap.get(records, model.providerID)).provider + const provider = state.get().providers.get(model.providerID)!.provider const endpoint = model.endpoint.type === "unknown" ? provider.endpoint @@ -120,9 +129,9 @@ export const layer = Layer.effect( } function* getRecord(providerID: ProviderV2.ID) { - const match = HashMap.get(records, providerID) - if (!match.valueOrUndefined) return yield* new ProviderNotFoundError({ providerID }) - return match.value + const match = state.get().providers.get(providerID) + if (!match) return yield* new ProviderNotFoundError({ providerID }) + return match } const normalizeEndpoint = (item: Draft | Draft) => { @@ -131,119 +140,85 @@ export const layer = Layer.effect( delete item.options.aisdk.provider.baseURL } - const clone = (input: HashMap.HashMap) => - HashMap.fromIterable( - HashMap.toEntries(input).map(([key, value]) => [key, { ...value, models: new Map(value.models) }] as const), - ) - - const context = (draft: { - records: HashMap.HashMap - data: ProviderRecord[] - }): Context => { - const result: Context = { - data: draft.data, - updateProvider: (providerID, fn) => result.provider.update(providerID, fn), - updateModel: (providerID, modelID, fn) => result.model.update(providerID, modelID, fn), - provider: { - update: (providerID, fn) => { - const current = Option.getOrUndefined(HashMap.get(draft.records, providerID)) - const provider = produce(current?.provider ?? ProviderV2.Info.empty(providerID), (draft) => { - fn(draft) - normalizeEndpoint(draft) - }) - const next = { - provider, - models: current?.models ?? new Map(), - } - draft.records = HashMap.set(draft.records, providerID, next) - const index = draft.data.findIndex((item) => item.provider.id === providerID) - if (index === -1) draft.data.push(next) - else draft.data[index] = next - }, - remove: (providerID) => { - draft.records = HashMap.remove(draft.records, providerID) - const index = draft.data.findIndex((item) => item.provider.id === providerID) - if (index !== -1) draft.data.splice(index, 1) - }, - }, - model: { - update: (providerID, modelID, fn) => { - const current = Option.getOrThrow(HashMap.get(draft.records, providerID)) - const model = produce(current.models.get(modelID) ?? ModelV2.Info.empty(providerID, modelID), (draft) => { - fn(draft) - normalizeEndpoint(draft) - }) - const next = { - provider: current.provider, - models: new Map(current.models).set(modelID, new ModelV2.Info({ ...model, id: modelID, providerID })), - } - draft.records = HashMap.set(draft.records, providerID, next) - const index = draft.data.findIndex((item) => item.provider.id === providerID) - if (index === -1) draft.data.push(next) - else draft.data[index] = next + const state = State.create({ + initial: () => ({ providers: new Map() }), + editor: (draft) => { + const result: Editor = { + provider: { + list: () => Array.fromIterable(draft.providers.values()) as ProviderRecord[], + get: (providerID) => draft.providers.get(providerID), + update: (providerID, fn) => { + let current = draft.providers.get(providerID) + if (!current) { + current = castDraft({ + provider: ProviderV2.Info.empty(providerID), + models: new Map(), + }) + draft.providers.set(providerID, current) + } + fn(current.provider) + normalizeEndpoint(current.provider) + }, + remove: (providerID) => { + draft.providers.delete(providerID) + }, }, - remove: (providerID, modelID) => { - const current = Option.getOrUndefined(HashMap.get(draft.records, providerID)) - if (!current) return - const next = { - provider: current.provider, - models: new Map(current.models), - } - next.models.delete(modelID) - draft.records = HashMap.set(draft.records, providerID, next) - const index = draft.data.findIndex((item) => item.provider.id === providerID) - if (index !== -1) draft.data[index] = next + model: { + get: (providerID, modelID) => draft.providers.get(providerID)?.models.get(modelID), + update: (providerID, modelID, fn) => { + let record = draft.providers.get(providerID) + if (!record) { + record = castDraft({ + provider: ProviderV2.Info.empty(providerID), + models: new Map(), + }) + draft.providers.set(providerID, record) + } + const model = record.models.get(modelID) ?? castDraft(ModelV2.Info.empty(providerID, modelID)) + if (!record.models.has(modelID)) record.models.set(modelID, model) + fn(model) + model.id = modelID + model.providerID = providerID + normalizeEndpoint(model) + }, + remove: (providerID, modelID) => { + draft.providers.get(providerID)?.models.delete(modelID) + }, + default: { + get: () => draft.defaultModel, + set: (providerID, modelID) => { + draft.defaultModel = { providerID, modelID } + }, + }, }, - }, - } - return result - } - - const transform = Effect.fn("CatalogV2.transform")(function* () { - const draft = { records: clone(records), data: HashMap.toValues(records) } - yield* plugin.trigger("catalog.transform", context(draft), {}) - records = draft.records - }) - - const rebuildSemaphore = Semaphore.makeUnsafe(1) - const rebuild = Effect.fn("CatalogV2.rebuild")(function* () { - yield* rebuildSemaphore.withPermits(1)( - Effect.gen(function* () { - const draft = { records: HashMap.empty(), data: [] as ProviderRecord[] } - for (const loader of loaders) loader.update(context(draft)) - yield* plugin.trigger("catalog.transform", context(draft), {}) - records = draft.records - }), - ) + } + return result + }, + finalize: Effect.fn("CatalogV2.finalize")(function* (catalog, reason) { + if (reason !== "plugin.added") yield* plugin.trigger("catalog.transform", catalog, {}).pipe(Effect.asVoid) + if (!policy.hasStatements()) return + for (const record of [...catalog.provider.list()]) { + if ((yield* policy.evaluate("provider.use", record.provider.id, "allow")) === "deny") { + catalog.provider.remove(record.provider.id) + } + } + }), }) - yield* plugin.added().pipe( - Stream.runForEach((id) => - Effect.gen(function* () { - const draft = { records: clone(records), data: HashMap.toValues(records) } - yield* plugin.triggerFor(id, "catalog.transform", context(draft), {}) - records = draft.records - }), + 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.update((catalog) => plugin.triggerFor(event.data.id, "catalog.transform", catalog, {}), "plugin.added"), ), Effect.forkIn(scope, { startImmediately: true }), ) const result: Interface = { - loader: Effect.fn("CatalogV2.loader")(function* () { - const loader = { update: (_ctx: Context) => {} } - loaders = [...loaders, loader] - const scope = yield* Scope.Scope - yield* Scope.addFinalizer( - scope, - Effect.sync(() => { - loaders = loaders.filter((item) => item !== loader) - }).pipe(Effect.andThen(rebuild())), - ) - return Effect.fnUntraced(function* (update) { - loader.update = update - yield* rebuild() - }) - }), + transform: state.transform, provider: { get: Effect.fn("CatalogV2.provider.get")(function* (providerID) { @@ -252,11 +227,11 @@ export const layer = Layer.effect( }), all: Effect.fn("CatalogV2.provider.all")(function* () { - return globalThis.Array.from(HashMap.values(records)).map((record) => record.provider) + return Array.fromIterable(state.get().providers.values()).map((record) => record.provider) }), available: Effect.fn("CatalogV2.provider.available")(function* () { - return globalThis.Array.from(HashMap.values(records)) + return Array.fromIterable(state.get().providers.values()) .map((record) => record.provider) .filter((provider) => provider.enabled) }), @@ -272,9 +247,8 @@ export const layer = Layer.effect( all: Effect.fn("CatalogV2.model.all")(function* () { return pipe( - records, - HashMap.toValues, - Array.flatMap((record) => globalThis.Array.from(record.models.values())), + Array.fromIterable(state.get().providers.values()), + Array.flatMap((record) => Array.fromIterable(record.models.values())), Array.map(resolve), Array.sortWith((item) => item.time.released.epochMilliseconds, Order.flip(Order.Number)), ) @@ -282,12 +256,13 @@ export const layer = Layer.effect( available: Effect.fn("CatalogV2.model.available")(function* () { return (yield* result.model.all()).filter((model) => { - const record = Option.getOrUndefined(HashMap.get(records, model.providerID)) + const record = state.get().providers.get(model.providerID) return record?.provider.enabled !== false && model.enabled }) }), default: Effect.fn("CatalogV2.model.default")(function* () { + const defaultModel = state.get().defaultModel if (defaultModel) { const model = yield* result.model.get(defaultModel.providerID, defaultModel.modelID).pipe(Effect.option) if (Option.isSome(model) && model.value.enabled) return model @@ -300,13 +275,8 @@ export const layer = Layer.effect( ) }), - setDefault: Effect.fn("CatalogV2.model.setDefault")(function* (providerID, modelID) { - yield* result.model.get(providerID, modelID) - defaultModel = { providerID, modelID } - }), - small: Effect.fn("CatalogV2.model.small")(function* (providerID) { - const record = Option.getOrUndefined(HashMap.get(records, providerID)) + const record = state.get().providers.get(providerID) if (!record) return Option.none() if (providerID === ProviderV2.ID.opencode) { @@ -315,7 +285,7 @@ export const layer = Layer.effect( } const candidates = pipe( - globalThis.Array.from(record.models.values()), + Array.fromIterable(record.models.values()), Array.filter( (model) => model.providerID === providerID && @@ -359,4 +329,7 @@ export const layer = Layer.effect( const SMALL_MODEL_RE = /\b(nano|flash|lite|mini|haiku|small|fast)\b/ -export const defaultLayer = layer.pipe(Layer.provide(EventV2.defaultLayer), Layer.provide(PluginV2.defaultLayer)) +export const locationLayer = layer.pipe( + Layer.provideMerge(PluginV2.locationLayer), + Layer.provideMerge(Policy.locationLayer), +) diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts new file mode 100644 index 000000000000..d5f7bfdffcac --- /dev/null +++ b/packages/core/src/config.ts @@ -0,0 +1,203 @@ +export * as Config from "./config" + +import path from "path" +import { type ParseError, parse } from "jsonc-parser" +import { Context, Effect, Layer, Option, Schema } from "effect" +import { AppFileSystem } from "./filesystem" +import { Global } from "./global" +import { Location } from "./location" +import { PermissionV2 } from "./permission" +import { Policy } from "./policy" +import { AbsolutePath } from "./schema" +import { ConfigAgent } from "./config/agent" +import { ConfigAttachments } from "./config/attachments" +import { ConfigCompaction } from "./config/compaction" +import { ConfigExperimental } from "./config/experimental" +import { ConfigFormatter } from "./config/formatter" +import { ConfigLSP } from "./config/lsp" +import { ConfigMCP } from "./config/mcp" +import { ConfigPlugin } from "./config/plugin" +import { ConfigProvider } from "./config/provider" +import { ConfigReference } from "./config/reference" +import { ConfigToolOutput } from "./config/tool-output" +import { ConfigWatcher } from "./config/watcher" + +export class Info extends Schema.Class("Config.Info")({ + $schema: Schema.optional(Schema.String).annotate({ + description: "JSON schema reference for configuration validation", + }), + shell: Schema.String.pipe(Schema.optional).annotate({ + description: "Default shell to use for terminal and shell tool execution", + }), + model: Schema.String.pipe(Schema.optional).annotate({ + description: "Default model to use when no session or agent model is selected", + }), + autoupdate: Schema.Union([Schema.Boolean, Schema.Literal("notify")]) + .pipe(Schema.optional) + .annotate({ + description: "Automatically update or notify when a new version is available", + }), + share: Schema.Literals(["manual", "auto", "disabled"]).pipe(Schema.optional).annotate({ + description: "Control whether sessions may be shared manually, automatically, or not at all", + }), + enterprise: Schema.Struct({ + url: Schema.String.pipe(Schema.optional), + }) + .pipe(Schema.optional) + .annotate({ + description: "Enterprise sharing service configuration", + }), + username: Schema.String.pipe(Schema.optional).annotate({ + description: "Username displayed in conversations and used for telemetry identity", + }), + permissions: PermissionV2.Ruleset.pipe(Schema.optional).annotate({ + description: "Ordered tool permission rules applied to agent tool use", + }), + agents: Schema.Record(Schema.String, ConfigAgent.Info).pipe(Schema.optional).annotate({ + description: "Named built-in agent overrides and custom agent definitions", + }), + snapshots: Schema.Boolean.pipe(Schema.optional).annotate({ + description: "Enable snapshots used for undo and revert behavior", + }), + watcher: ConfigWatcher.Info.pipe(Schema.optional).annotate({ + description: "Filesystem watcher configuration", + }), + formatter: ConfigFormatter.Info.pipe(Schema.optional).annotate({ + description: "Enable built-in formatters or configure formatter overrides", + }), + lsp: ConfigLSP.Info.pipe(Schema.optional).annotate({ + description: "Enable built-in language servers or configure server overrides", + }), + attachments: ConfigAttachments.Info.pipe(Schema.optional).annotate({ + description: "Attachment processing configuration", + }), + tool_output: ConfigToolOutput.Info.pipe(Schema.optional).annotate({ + description: "Tool output truncation thresholds", + }), + mcp: ConfigMCP.Info.pipe(Schema.optional).annotate({ + description: "MCP server configuration", + }), + compaction: ConfigCompaction.Info.pipe(Schema.optional).annotate({ + description: "Conversation compaction behavior", + }), + skills: Schema.String.pipe(Schema.Array, Schema.optional).annotate({ + description: "Additional paths or URLs to discover skills from", + }), + instructions: Schema.String.pipe(Schema.Array, Schema.optional).annotate({ + description: "Additional paths or URLs supplying ambient instructions", + }), + references: ConfigReference.Info.pipe(Schema.optional).annotate({ + description: "Named local directories or Git repositories available as external context", + }), + plugins: ConfigPlugin.Plugins.pipe(Schema.optional).annotate({ + description: "Ordered external plugin packages to load", + }), + experimental: ConfigExperimental.Experimental.pipe(Schema.optional), + providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(Schema.optional), +}) {} + +export const FileSource = Schema.Struct({ + type: Schema.Literal("file"), + path: Schema.String, +}).annotate({ identifier: "Config.FileSource" }) +export type FileSource = typeof FileSource.Type + +export const MemorySource = Schema.Struct({ + type: Schema.Literal("memory"), +}).annotate({ identifier: "Config.MemorySource" }) +export type MemorySource = typeof MemorySource.Type + +export const Source = Schema.Union([FileSource, MemorySource]).pipe(Schema.toTaggedUnion("type")) +export type Source = typeof Source.Type + +export class Loaded extends Schema.Class("Config.Loaded")({ + source: Source, + info: Info, +}) {} + +export interface Interface { + /** Returns supplemental config directories from lowest to highest priority. */ + readonly directories: () => Effect.Effect + /** Loads location config files from lowest to highest priority. */ + readonly get: () => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/v2/Config") {} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + const global = yield* Global.Service + const location = yield* Location.Service + const policy = yield* Policy.Service + const names = ["config.json", "opencode.json", "opencode.jsonc"] + + const loadFile = Effect.fnUntraced(function* (filepath: string) { + const text = yield* fs.readFileStringSafe(filepath) + if (!text) return + + const errors: ParseError[] = [] + const input: unknown = parse(text, errors, { allowTrailingComma: true }) + if (errors.length) return + + // Accept legacy fields while v2 is migrated incrementally; recognized + // fields still have to satisfy the v2 schema. + const info = Option.getOrUndefined( + Schema.decodeUnknownOption(Info)(input, { errors: "all", onExcessProperty: "ignore" }), + ) + if (!info) return + return new Loaded({ source: { type: "file", path: filepath }, info }) + }) + + const loadDirectory = Effect.fnUntraced(function* (directory: AbsolutePath) { + return yield* Effect.forEach(names, (file) => loadFile(path.join(directory, file))).pipe( + Effect.map((configs) => configs.filter((config): config is Loaded => config !== undefined)), + ) + }) + + const globalDirectory = AbsolutePath.make(global.config) + const locationIsGlobal = path.resolve(location.directory) === path.resolve(global.config) + // Read configuration once when this location opens. Later calls reuse these + // values until the location is reopened. + const directories = locationIsGlobal + ? [globalDirectory] + : [ + globalDirectory, + ...(yield* fs + .up({ targets: [".opencode"], start: location.directory, stop: location.project.directory }) + .pipe(Effect.orDie)) + .toReversed() + .map((directory) => AbsolutePath.make(directory)), + ] + // A config closer to the opened directory should win over one higher up. + // Search starts nearby, so reverse the results before applying them. + const directPaths = locationIsGlobal + ? [] + : (yield* fs + .up({ targets: names.toReversed(), start: location.directory, stop: location.project.directory }) + .pipe(Effect.orDie)).toReversed() + const direct = yield* Effect.forEach(directPaths, loadFile).pipe( + Effect.orDie, + Effect.map((configs) => configs.filter((config): config is Loaded => config !== undefined)), + ) + const supplementary = yield* Effect.forEach(directories, loadDirectory).pipe(Effect.orDie) + // Apply general settings first and more specific settings last: + // global config, project files, then `.opencode` files. + const configs = [...(supplementary[0] ?? []), ...direct, ...supplementary.slice(1).flat()] + // Rules use the opposite order so a user-global rule can override a + // repository rule. Statement order inside each file stays unchanged. + yield* policy.load(configs.toReversed().flatMap((config) => config.info.experimental?.policies ?? [])) + + return Service.of({ + directories: Effect.fn("Config.directories")(function* () { + return directories + }), + get: Effect.fn("Config.get")(function* () { + return configs + }), + }) + }), +) + +export const locationLayer = layer.pipe(Layer.provideMerge(Policy.locationLayer)) diff --git a/packages/core/src/config/agent.ts b/packages/core/src/config/agent.ts new file mode 100644 index 000000000000..40d2bc94b589 --- /dev/null +++ b/packages/core/src/config/agent.ts @@ -0,0 +1,25 @@ +export * as ConfigAgent from "./agent" + +import { Schema } from "effect" +import { PermissionV2 } from "../permission" +import { ConfigProvider } from "./provider" +import { PositiveInt } from "../schema" + +export const Color = Schema.Union([ + Schema.String.check(Schema.isPattern(/^#[0-9a-fA-F]{6}$/)), + Schema.Literals(["primary", "secondary", "accent", "success", "warning", "error", "info"]), +]) + +export class Info extends Schema.Class("ConfigV2.Agent")({ + model: Schema.String.pipe(Schema.optional), + variant: Schema.String.pipe(Schema.optional), + options: ConfigProvider.Options.pipe(Schema.optional), + system: Schema.String.pipe(Schema.optional), + description: Schema.String.pipe(Schema.optional), + mode: Schema.Literals(["subagent", "primary", "all"]).pipe(Schema.optional), + hidden: Schema.Boolean.pipe(Schema.optional), + color: Color.pipe(Schema.optional), + steps: PositiveInt.pipe(Schema.optional), + disabled: Schema.Boolean.pipe(Schema.optional), + permissions: PermissionV2.Ruleset.pipe(Schema.optional), +}) {} diff --git a/packages/core/src/config/attachments.ts b/packages/core/src/config/attachments.ts new file mode 100644 index 000000000000..f14775ff3f7d --- /dev/null +++ b/packages/core/src/config/attachments.ts @@ -0,0 +1,15 @@ +export * as ConfigAttachments from "./attachments" + +import { Schema } from "effect" +import { PositiveInt } from "../schema" + +export class Image extends Schema.Class("ConfigV2.Attachments.Image")({ + auto_resize: Schema.Boolean.pipe(Schema.optional), + max_width: PositiveInt.pipe(Schema.optional), + max_height: PositiveInt.pipe(Schema.optional), + max_base64_bytes: PositiveInt.pipe(Schema.optional), +}) {} + +export class Info extends Schema.Class("ConfigV2.Attachments")({ + image: Image.pipe(Schema.optional), +}) {} diff --git a/packages/core/src/config/compaction.ts b/packages/core/src/config/compaction.ts new file mode 100644 index 000000000000..eef67ee26a06 --- /dev/null +++ b/packages/core/src/config/compaction.ts @@ -0,0 +1,16 @@ +export * as ConfigCompaction from "./compaction" + +import { Schema } from "effect" +import { NonNegativeInt } from "../schema" + +export class Keep extends Schema.Class("ConfigV2.Compaction.Keep")({ + turns: NonNegativeInt.pipe(Schema.optional), + tokens: NonNegativeInt.pipe(Schema.optional), +}) {} + +export class Info extends Schema.Class("ConfigV2.Compaction")({ + auto: Schema.Boolean.pipe(Schema.optional), + prune: Schema.Boolean.pipe(Schema.optional), + keep: Keep.pipe(Schema.optional), + buffer: NonNegativeInt.pipe(Schema.optional), +}) {} diff --git a/packages/core/src/config/experimental.ts b/packages/core/src/config/experimental.ts new file mode 100644 index 000000000000..12a02635db65 --- /dev/null +++ b/packages/core/src/config/experimental.ts @@ -0,0 +1,18 @@ +export * as ConfigExperimental from "./experimental" + +import { Schema } from "effect" +import { Catalog } from "../catalog" +import { Policy as PolicyV2 } from "../policy" + +// Each core domain exports the policy actions it supports. Adding an action to +// this union makes it valid in authored config while keeping Policy generic. +export const PolicyAction = Schema.Union([Catalog.PolicyActions]) + +export class Policy extends Schema.Class("ConfigV2.Experimental.Policy")({ + ...PolicyV2.Info.fields, + action: PolicyAction, +}) {} + +export class Experimental extends Schema.Class("ConfigV2.Experimental")({ + policies: Policy.pipe(Schema.Array, Schema.optional), +}) {} diff --git a/packages/core/src/config/formatter.ts b/packages/core/src/config/formatter.ts new file mode 100644 index 000000000000..e1f90302d1a9 --- /dev/null +++ b/packages/core/src/config/formatter.ts @@ -0,0 +1,12 @@ +export * as ConfigFormatter from "./formatter" + +import { Schema } from "effect" + +export class Entry extends Schema.Class("ConfigV2.Formatter.Entry")({ + disabled: Schema.Boolean.pipe(Schema.optional), + command: Schema.String.pipe(Schema.Array, Schema.optional), + environment: Schema.Record(Schema.String, Schema.String).pipe(Schema.optional), + extensions: Schema.String.pipe(Schema.Array, Schema.optional), +}) {} + +export const Info = Schema.Union([Schema.Boolean, Schema.Record(Schema.String, Entry)]) diff --git a/packages/core/src/config/lsp.ts b/packages/core/src/config/lsp.ts new file mode 100644 index 000000000000..651597befdde --- /dev/null +++ b/packages/core/src/config/lsp.ts @@ -0,0 +1,18 @@ +export * as ConfigLSP from "./lsp" + +import { Schema } from "effect" + +export const Disabled = Schema.Struct({ + disabled: Schema.Literal(true), +}) + +export class Server extends Schema.Class("ConfigV2.LSP.Server")({ + command: Schema.String.pipe(Schema.Array), + extensions: Schema.String.pipe(Schema.Array, Schema.optional), + disabled: Schema.Boolean.pipe(Schema.optional), + env: Schema.Record(Schema.String, Schema.String).pipe(Schema.optional), + initialization: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), +}) {} + +export const Entry = Schema.Union([Disabled, Server]) +export const Info = Schema.Union([Schema.Boolean, Schema.Record(Schema.String, Entry)]) diff --git a/packages/core/src/config/mcp.ts b/packages/core/src/config/mcp.ts new file mode 100644 index 000000000000..fce853815b43 --- /dev/null +++ b/packages/core/src/config/mcp.ts @@ -0,0 +1,36 @@ +export * as ConfigMCP from "./mcp" + +import { Schema } from "effect" +import { PositiveInt } from "../schema" + +export class Local extends Schema.Class("ConfigV2.MCP.Local")({ + type: Schema.Literal("local"), + command: Schema.String.pipe(Schema.Array), + environment: Schema.Record(Schema.String, Schema.String).pipe(Schema.optional), + disabled: Schema.Boolean.pipe(Schema.optional), + timeout: PositiveInt.pipe(Schema.optional), +}) {} + +export class OAuth extends Schema.Class("ConfigV2.MCP.OAuth")({ + client_id: Schema.String.pipe(Schema.optional), + client_secret: Schema.String.pipe(Schema.optional), + scope: Schema.String.pipe(Schema.optional), + callback_port: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })).pipe(Schema.optional), + redirect_uri: Schema.String.pipe(Schema.optional), +}) {} + +export class Remote extends Schema.Class("ConfigV2.MCP.Remote")({ + type: Schema.Literal("remote"), + url: Schema.String, + headers: Schema.Record(Schema.String, Schema.String).pipe(Schema.optional), + oauth: Schema.Union([OAuth, Schema.Literal(false)]).pipe(Schema.optional), + disabled: Schema.Boolean.pipe(Schema.optional), + timeout: PositiveInt.pipe(Schema.optional), +}) {} + +export const Server = Schema.Union([Local, Remote]).pipe(Schema.toTaggedUnion("type")) + +export class Info extends Schema.Class("ConfigV2.MCP")({ + timeout: PositiveInt.pipe(Schema.optional), + servers: Schema.Record(Schema.String, Server).pipe(Schema.optional), +}) {} diff --git a/packages/core/src/config/plugin.ts b/packages/core/src/config/plugin.ts new file mode 100644 index 000000000000..e5fd6661ff52 --- /dev/null +++ b/packages/core/src/config/plugin.ts @@ -0,0 +1,13 @@ +export * as ConfigPlugin from "./plugin" + +import { Schema } from "effect" + +export class Entry extends Schema.Class("ConfigV2.Plugin.Entry")({ + package: Schema.String, + options: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), +}) {} + +export const Plugin = Schema.Union([Schema.String, Entry]) +export type Plugin = typeof Plugin.Type + +export const Plugins = Plugin.pipe(Schema.Array) diff --git a/packages/core/src/config/plugin/agent.ts b/packages/core/src/config/plugin/agent.ts new file mode 100644 index 000000000000..c05b0a578f0c --- /dev/null +++ b/packages/core/src/config/plugin/agent.ts @@ -0,0 +1,65 @@ +export * as ConfigAgentPlugin from "./agent" + +import { Effect } from "effect" +import { AgentV2 } from "../../agent" +import { Config } from "../../config" +import { ModelV2 } from "../../model" +import { PermissionV2 } from "../../permission" +import { PluginV2 } from "../../plugin" + +export const Plugin = PluginV2.define({ + id: PluginV2.ID.make("config-agent"), + effect: Effect.gen(function* () { + const agent = yield* AgentV2.Service + const config = yield* Config.Service + const files = yield* config.get() + + yield* agent.update((editor) => { + const permissions = new Map() + + for (const file of files) { + for (const [id, item] of Object.entries(file.info.agents ?? {})) { + const agentID = AgentV2.ID.make(id) + if (item.disabled) { + editor.remove(agentID) + permissions.delete(agentID) + continue + } + + editor.update(agentID, (agent) => { + if (item.model !== undefined) { + const model = ModelV2.parse(item.model) + agent.model = { id: model.modelID, providerID: model.providerID, variant: agent.model?.variant } + } + if (item.variant !== undefined && agent.model !== undefined) { + agent.model.variant = ModelV2.VariantID.make(item.variant) + } + if (item.options !== undefined) { + Object.assign(agent.options.headers, item.options.headers ?? {}) + Object.assign(agent.options.body, item.options.body ?? {}) + Object.assign(agent.options.aisdk.provider, item.options.aisdk?.provider ?? {}) + Object.assign(agent.options.aisdk.request, item.options.aisdk?.request ?? {}) + } + if (item.system !== undefined) agent.system = item.system + if (item.description !== undefined) agent.description = item.description + if (item.mode !== undefined) agent.mode = item.mode + if (item.hidden !== undefined) agent.hidden = item.hidden + if (item.color !== undefined) agent.color = item.color + if (item.steps !== undefined) agent.steps = item.steps + }) + + if (item.permissions !== undefined) { + permissions.set(agentID, [...(permissions.get(agentID) ?? []), ...item.permissions]) + } + } + } + + const global = files.flatMap((file) => file.info.permissions ?? []) + for (const current of editor.list()) { + editor.update(current.id, (agent) => { + agent.permissions.push(...global, ...(permissions.get(current.id) ?? [])) + }) + } + }) + }), +}) diff --git a/packages/core/src/config/plugin/provider.ts b/packages/core/src/config/plugin/provider.ts new file mode 100644 index 000000000000..fca2e53302e3 --- /dev/null +++ b/packages/core/src/config/plugin/provider.ts @@ -0,0 +1,95 @@ +export * as ConfigProviderPlugin from "./provider" + +import { Effect } from "effect" +import { Catalog } from "../../catalog" +import { Config } from "../../config" +import { ModelV2 } from "../../model" +import { PluginV2 } from "../../plugin" +import { ProviderV2 } from "../../provider" + +export const Plugin = PluginV2.define({ + id: PluginV2.ID.make("config-provider"), + effect: Effect.gen(function* () { + const catalog = yield* Catalog.Service + const config = yield* Config.Service + const transform = yield* catalog.transform() + const files = yield* config.get() + + yield* transform((catalog) => { + for (const file of files) { + for (const [id, item] of Object.entries(file.info.providers ?? {})) { + const providerID = ProviderV2.ID.make(id) + catalog.provider.update(providerID, (provider) => { + if (item.name !== undefined) provider.name = item.name + if (item.env !== undefined) provider.env = [...item.env] + provider.enabled = { via: "custom", data: {} } + if (item.endpoint !== undefined) provider.endpoint = { ...item.endpoint } + if (item.options !== undefined) { + Object.assign(provider.options.headers, item.options.headers ?? {}) + Object.assign(provider.options.body, item.options.body ?? {}) + Object.assign(provider.options.aisdk.provider, item.options.aisdk?.provider ?? {}) + Object.assign(provider.options.aisdk.request, item.options.aisdk?.request ?? {}) + } + }) + + for (const [id, config] of Object.entries(item.models ?? {})) { + catalog.model.update(providerID, ModelV2.ID.make(id), (model) => { + if (config.api_id !== undefined) model.apiID = config.api_id + if (config.family !== undefined) model.family = config.family + if (config.name !== undefined) model.name = config.name + if (config.endpoint !== undefined) model.endpoint = { ...config.endpoint } + if (config.capabilities !== undefined) { + model.capabilities = { + tools: config.capabilities.tools, + input: [...config.capabilities.input], + output: [...config.capabilities.output], + } + } + if (config.options !== undefined) { + Object.assign(model.options.headers, config.options.headers ?? {}) + Object.assign(model.options.body, config.options.body ?? {}) + Object.assign(model.options.aisdk.provider, config.options.aisdk?.provider ?? {}) + Object.assign(model.options.aisdk.request, config.options.aisdk?.request ?? {}) + if (config.options.variant !== undefined) model.options.variant = config.options.variant + } + if (config.variants !== undefined) { + for (const variant of config.variants) { + let existing = model.variants.find((item) => item.id === variant.id) + if (!existing) { + existing = { + id: variant.id, + headers: {}, + body: {}, + aisdk: { + provider: {}, + request: {}, + }, + } + model.variants.push(existing) + } + Object.assign(existing.headers, variant.headers ?? {}) + Object.assign(existing.body, variant.body ?? {}) + Object.assign(existing.aisdk.provider, variant.aisdk?.provider ?? {}) + Object.assign(existing.aisdk.request, variant.aisdk?.request ?? {}) + } + } + if (config.cost !== undefined) { + model.cost = (Array.isArray(config.cost) ? config.cost : [config.cost]).map((cost) => ({ + tier: cost.tier && { ...cost.tier }, + input: cost.input, + output: cost.output, + cache: { + read: cost.cache?.read ?? 0, + write: cost.cache?.write ?? 0, + }, + })) + } + if (config.disabled !== undefined) model.enabled = !config.disabled + if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit } + }) + } + } + } + }) + }), +}) diff --git a/packages/core/src/config/provider.ts b/packages/core/src/config/provider.ts new file mode 100644 index 000000000000..fbb0e1c3ef23 --- /dev/null +++ b/packages/core/src/config/provider.ts @@ -0,0 +1,62 @@ +export * as ConfigProvider from "./provider" + +import { Schema } from "effect" +import { ProviderV2 } from "../provider" +import { ModelV2 } from "../model" + +export class Options extends Schema.Class("ConfigV2.Provider.Options")({ + headers: Schema.Record(Schema.String, Schema.String).pipe(Schema.optional), + body: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), + aisdk: Schema.Struct({ + provider: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), + request: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), + }).pipe(Schema.optional), +}) {} + +class Cache extends Schema.Class("ConfigV2.Model.Cost.Cache")({ + read: Schema.Finite.pipe(Schema.optional), + write: Schema.Finite.pipe(Schema.optional), +}) {} + +class Cost extends Schema.Class("ConfigV2.Model.Cost")({ + tier: Schema.Struct({ + type: Schema.Literal("context"), + size: Schema.Int, + }).pipe(Schema.optional), + input: Schema.Finite, + output: Schema.Finite, + cache: Cache.pipe(Schema.optional), +}) {} + +class Limit extends Schema.Class("ConfigV2.Model.Limit")({ + context: Schema.Int.pipe(Schema.optional), + input: Schema.Int.pipe(Schema.optional), + output: Schema.Int.pipe(Schema.optional), +}) {} + +class Model extends Schema.Class("ConfigV2.Model")({ + api_id: ModelV2.ID.pipe(Schema.optional), + family: ModelV2.Family.pipe(Schema.optional), + name: Schema.String.pipe(Schema.optional), + endpoint: ProviderV2.Endpoint.pipe(Schema.optional), + capabilities: ModelV2.Capabilities.pipe(Schema.optional), + options: Schema.Struct({ + ...Options.fields, + variant: Schema.String.pipe(Schema.optional), + }).pipe(Schema.optional), + variants: Schema.Struct({ + id: ModelV2.VariantID, + ...Options.fields, + }).pipe(Schema.Array, Schema.optional), + cost: Schema.Union([Cost, Cost.pipe(Schema.Array)]).pipe(Schema.optional), + disabled: Schema.Boolean.pipe(Schema.optional), + limit: Limit.pipe(Schema.optional), +}) {} + +export class Info extends Schema.Class("ConfigV2.Provider")({ + name: Schema.String.pipe(Schema.optional), + env: Schema.String.pipe(Schema.Array, Schema.optional), + endpoint: ProviderV2.Endpoint.pipe(Schema.optional), + options: Options.pipe(Schema.optional), + models: Schema.Record(Schema.String, Model).pipe(Schema.optional), +}) {} diff --git a/packages/core/src/config/reference.ts b/packages/core/src/config/reference.ts new file mode 100644 index 000000000000..dc9042e6f760 --- /dev/null +++ b/packages/core/src/config/reference.ts @@ -0,0 +1,17 @@ +export * as ConfigReference from "./reference" + +import { Schema } from "effect" + +export class Git extends Schema.Class("ConfigV2.Reference.Git")({ + repository: Schema.String, + branch: Schema.String.pipe(Schema.optional), +}) {} + +export class Local extends Schema.Class("ConfigV2.Reference.Local")({ + path: Schema.String, +}) {} + +export const Entry = Schema.Union([Schema.String, Git, Local]) +export type Entry = typeof Entry.Type + +export const Info = Schema.Record(Schema.String, Entry) diff --git a/packages/core/src/config/tool-output.ts b/packages/core/src/config/tool-output.ts new file mode 100644 index 000000000000..53e4d4d088b7 --- /dev/null +++ b/packages/core/src/config/tool-output.ts @@ -0,0 +1,9 @@ +export * as ConfigToolOutput from "./tool-output" + +import { Schema } from "effect" +import { PositiveInt } from "../schema" + +export class Info extends Schema.Class("ConfigV2.ToolOutput")({ + max_lines: PositiveInt.pipe(Schema.optional), + max_bytes: PositiveInt.pipe(Schema.optional), +}) {} diff --git a/packages/core/src/config/watcher.ts b/packages/core/src/config/watcher.ts new file mode 100644 index 000000000000..2df6c876bfc6 --- /dev/null +++ b/packages/core/src/config/watcher.ts @@ -0,0 +1,7 @@ +export * as ConfigWatcher from "./watcher" + +import { Schema } from "effect" + +export class Info extends Schema.Class("ConfigV2.Watcher")({ + ignore: Schema.String.pipe(Schema.Array, Schema.optional), +}) {} diff --git a/packages/opencode/src/control-plane/workspace.sql.ts b/packages/core/src/control-plane/workspace.sql.ts similarity index 66% rename from packages/opencode/src/control-plane/workspace.sql.ts rename to packages/core/src/control-plane/workspace.sql.ts index 1afaf7cbc9f3..ef5195216acf 100644 --- a/packages/opencode/src/control-plane/workspace.sql.ts +++ b/packages/core/src/control-plane/workspace.sql.ts @@ -1,17 +1,17 @@ import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core" -import { ProjectTable } from "../project/project.sql" -import type { ProjectID } from "../project/schema" -import type { WorkspaceID } from "./schema" +import { ProjectTable } from "../project/sql" +import { ProjectV2 } from "../project" +import { WorkspaceV2 } from "../workspace" export const WorkspaceTable = sqliteTable("workspace", { - id: text().$type().primaryKey(), + id: text().$type().primaryKey(), type: text().notNull(), name: text().notNull().default(""), branch: text(), directory: text(), extra: text({ mode: "json" }), project_id: text() - .$type() + .$type() .notNull() .references(() => ProjectTable.id, { onDelete: "cascade" }), time_used: integer() diff --git a/packages/opencode/src/data-migration.sql.ts b/packages/core/src/data-migration.sql.ts similarity index 100% rename from packages/opencode/src/data-migration.sql.ts rename to packages/core/src/data-migration.sql.ts diff --git a/packages/core/src/database/database.ts b/packages/core/src/database/database.ts new file mode 100644 index 000000000000..ba7aa91b0ee0 --- /dev/null +++ b/packages/core/src/database/database.ts @@ -0,0 +1,60 @@ +export * as Database from "./database" + +import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite" +import { layer as sqliteLayer } from "#sqlite" +import { Context, Effect, Layer } from "effect" +import { Global } from "../global" +import { Flag } from "../flag/flag" +import { isAbsolute, join } from "path" +import { DatabaseMigration } from "./migration" +import { InstallationChannel } from "../installation/version" + +const makeDatabase = EffectDrizzleSqlite.makeWithDefaults() +type DatabaseShape = Effect.Success + +export interface Interface { + db: DatabaseShape +} + +export class Service extends Context.Service()("@opencode/v2/storage/Database") {} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const db = yield* makeDatabase + + yield* db.run("PRAGMA journal_mode = WAL") + yield* db.run("PRAGMA synchronous = NORMAL") + yield* db.run("PRAGMA busy_timeout = 5000") + yield* db.run("PRAGMA cache_size = -64000") + yield* db.run("PRAGMA foreign_keys = ON") + yield* db.run("PRAGMA wal_checkpoint(PASSIVE)") + yield* DatabaseMigration.apply(db) + + return { db } + }).pipe(Effect.orDie), +) + +export function layerFromPath(filename: string) { + return layer.pipe(Layer.provide(sqliteLayer({ filename }))) +} + +export function path() { + if (Flag.OPENCODE_DB) { + if (Flag.OPENCODE_DB === ":memory:" || isAbsolute(Flag.OPENCODE_DB)) return Flag.OPENCODE_DB + return join(Global.Path.data, Flag.OPENCODE_DB) + } + if ( + ["latest", "beta", "prod"].includes(InstallationChannel) || + process.env.OPENCODE_DISABLE_CHANNEL_DB === "1" || + process.env.OPENCODE_DISABLE_CHANNEL_DB === "true" + ) + return join(Global.Path.data, "opencode.db") + return join(Global.Path.data, `opencode-${InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`) +} + +export const defaultLayer = Layer.unwrap( + Effect.gen(function* () { + return layerFromPath(path()) + }), +).pipe(Layer.provide(Global.defaultLayer)) diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts new file mode 100644 index 000000000000..ee76318488b1 --- /dev/null +++ b/packages/core/src/database/migration.gen.ts @@ -0,0 +1,27 @@ +import type { DatabaseMigration } from "./migration" + +export const migrations = ( + await Promise.all([ + import("./migration/20260127222353_familiar_lady_ursula"), + import("./migration/20260211171708_add_project_commands"), + import("./migration/20260213144116_wakeful_the_professor"), + import("./migration/20260225215848_workspace"), + import("./migration/20260227213759_add_session_workspace_id"), + import("./migration/20260228203230_blue_harpoon"), + import("./migration/20260303231226_add_workspace_fields"), + import("./migration/20260309230000_move_org_to_state"), + import("./migration/20260312043431_session_message_cursor"), + import("./migration/20260323234822_events"), + import("./migration/20260410174513_workspace-name"), + import("./migration/20260413175956_chief_energizer"), + import("./migration/20260423070820_add_icon_url_override"), + import("./migration/20260427172553_slow_nightmare"), + import("./migration/20260428004200_add_session_path"), + import("./migration/20260501142318_next_venus"), + import("./migration/20260504145000_add_sync_owner"), + import("./migration/20260507164347_add_workspace_time"), + import("./migration/20260510033149_session_usage"), + import("./migration/20260511000411_data_migration_state"), + import("./migration/20260511173437_session-metadata"), + ]) +).map((module) => module.default) satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration.ts b/packages/core/src/database/migration.ts new file mode 100644 index 000000000000..f0a03014426d --- /dev/null +++ b/packages/core/src/database/migration.ts @@ -0,0 +1,58 @@ +export * as DatabaseMigration from "./migration" + +import { sql } from "drizzle-orm" +import { Effect } from "effect" +import type { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite" +import { migrations } from "./migration.gen" + +type Database = EffectDrizzleSqlite.EffectSQLiteDatabase +type Transaction = Parameters[0]>[0] + +export type Migration = { + id: string + up: (tx: Transaction) => Effect.Effect +} + +export function apply(db: Database) { + return applyOnly(db, migrations) +} + +export function applyOnly(db: Database, input: Migration[]) { + return Effect.gen(function* () { + yield* db.run( + sql`CREATE TABLE IF NOT EXISTS ${sql.identifier("migration")} (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`, + ) + let completed = new Set( + (yield* db.all<{ id: string }>(sql`SELECT id FROM ${sql.identifier("migration")}`)).map((row) => row.id), + ) + if (completed.size === 0) { + // Existing installs used Drizzle's migration journal. Seed the new + // journal once so TypeScript migrations don't replay old SQL. + if ( + yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${"__drizzle_migrations"}`) + ) { + yield* db.run(sql` + INSERT OR IGNORE INTO ${sql.identifier("migration")} (id, time_completed) + SELECT name, ${Date.now()} + FROM ${sql.identifier("__drizzle_migrations")} + WHERE name IS NOT NULL + `) + completed = new Set( + (yield* db.all<{ id: string }>(sql`SELECT id FROM ${sql.identifier("migration")}`)).map((row) => row.id), + ) + } + } + + for (const migration of input) { + if (completed.has(migration.id)) continue + yield* db.transaction((tx) => + Effect.gen(function* () { + if (!process.env.OPENCODE_SKIP_MIGRATIONS) yield* migration.up(tx) + yield* tx.run( + sql`INSERT INTO ${sql.identifier("migration")} (id, time_completed) VALUES (${migration.id}, ${Date.now()})`, + ) + }), + ) + } + }) +} diff --git a/packages/core/src/database/migration/20260127222353_familiar_lady_ursula.ts b/packages/core/src/database/migration/20260127222353_familiar_lady_ursula.ts new file mode 100644 index 000000000000..468a7103fb3d --- /dev/null +++ b/packages/core/src/database/migration/20260127222353_familiar_lady_ursula.ts @@ -0,0 +1,107 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260127222353_familiar_lady_ursula", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`project\` ( + \`id\` text PRIMARY KEY, + \`worktree\` text NOT NULL, + \`vcs\` text, + \`name\` text, + \`icon_url\` text, + \`icon_color\` text, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`time_initialized\` integer, + \`sandboxes\` text NOT NULL + ); + `) + yield* tx.run(` + CREATE TABLE \`message\` ( + \`id\` text PRIMARY KEY, + \`session_id\` text NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`data\` text NOT NULL, + CONSTRAINT \`fk_message_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + CREATE TABLE \`part\` ( + \`id\` text PRIMARY KEY, + \`message_id\` text NOT NULL, + \`session_id\` text NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`data\` text NOT NULL, + CONSTRAINT \`fk_part_message_id_message_id_fk\` FOREIGN KEY (\`message_id\`) REFERENCES \`message\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + CREATE TABLE \`permission\` ( + \`project_id\` text PRIMARY KEY, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`data\` text NOT NULL, + CONSTRAINT \`fk_permission_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + CREATE TABLE \`session\` ( + \`id\` text PRIMARY KEY, + \`project_id\` text NOT NULL, + \`parent_id\` text, + \`slug\` text NOT NULL, + \`directory\` text NOT NULL, + \`title\` text NOT NULL, + \`version\` text NOT NULL, + \`share_url\` text, + \`summary_additions\` integer, + \`summary_deletions\` integer, + \`summary_files\` integer, + \`summary_diffs\` text, + \`revert\` text, + \`permission\` text, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`time_compacting\` integer, + \`time_archived\` integer, + CONSTRAINT \`fk_session_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + CREATE TABLE \`todo\` ( + \`session_id\` text NOT NULL, + \`content\` text NOT NULL, + \`status\` text NOT NULL, + \`priority\` text NOT NULL, + \`position\` integer NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + CONSTRAINT \`todo_pk\` PRIMARY KEY(\`session_id\`, \`position\`), + CONSTRAINT \`fk_todo_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + CREATE TABLE \`session_share\` ( + \`session_id\` text PRIMARY KEY, + \`id\` text NOT NULL, + \`secret\` text NOT NULL, + \`url\` text NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + CONSTRAINT \`fk_session_share_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(`CREATE INDEX \`message_session_idx\` ON \`message\` (\`session_id\`);`) + yield* tx.run(`CREATE INDEX \`part_message_idx\` ON \`part\` (\`message_id\`);`) + yield* tx.run(`CREATE INDEX \`part_session_idx\` ON \`part\` (\`session_id\`);`) + yield* tx.run(`CREATE INDEX \`session_project_idx\` ON \`session\` (\`project_id\`);`) + yield* tx.run(`CREATE INDEX \`session_parent_idx\` ON \`session\` (\`parent_id\`);`) + yield* tx.run(`CREATE INDEX \`todo_session_idx\` ON \`todo\` (\`session_id\`);`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260211171708_add_project_commands.ts b/packages/core/src/database/migration/20260211171708_add_project_commands.ts new file mode 100644 index 000000000000..d31a533db3c3 --- /dev/null +++ b/packages/core/src/database/migration/20260211171708_add_project_commands.ts @@ -0,0 +1,11 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260211171708_add_project_commands", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`project\` ADD \`commands\` text;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260213144116_wakeful_the_professor.ts b/packages/core/src/database/migration/20260213144116_wakeful_the_professor.ts new file mode 100644 index 000000000000..8077182d9398 --- /dev/null +++ b/packages/core/src/database/migration/20260213144116_wakeful_the_professor.ts @@ -0,0 +1,23 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260213144116_wakeful_the_professor", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`control_account\` ( + \`email\` text NOT NULL, + \`url\` text NOT NULL, + \`access_token\` text NOT NULL, + \`refresh_token\` text NOT NULL, + \`token_expiry\` integer, + \`active\` integer NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + CONSTRAINT \`control_account_pk\` PRIMARY KEY(\`email\`, \`url\`) + ); + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260225215848_workspace.ts b/packages/core/src/database/migration/20260225215848_workspace.ts new file mode 100644 index 000000000000..cc816951ef97 --- /dev/null +++ b/packages/core/src/database/migration/20260225215848_workspace.ts @@ -0,0 +1,19 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260225215848_workspace", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`workspace\` ( + \`id\` text PRIMARY KEY, + \`branch\` text, + \`project_id\` text NOT NULL, + \`config\` text NOT NULL, + CONSTRAINT \`fk_workspace_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE + ); + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260227213759_add_session_workspace_id.ts b/packages/core/src/database/migration/20260227213759_add_session_workspace_id.ts new file mode 100644 index 000000000000..430407156dfd --- /dev/null +++ b/packages/core/src/database/migration/20260227213759_add_session_workspace_id.ts @@ -0,0 +1,12 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260227213759_add_session_workspace_id", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`session\` ADD \`workspace_id\` text;`) + yield* tx.run(`CREATE INDEX \`session_workspace_idx\` ON \`session\` (\`workspace_id\`);`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260228203230_blue_harpoon.ts b/packages/core/src/database/migration/20260228203230_blue_harpoon.ts new file mode 100644 index 000000000000..83e2978f707a --- /dev/null +++ b/packages/core/src/database/migration/20260228203230_blue_harpoon.ts @@ -0,0 +1,30 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260228203230_blue_harpoon", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`account\` ( + \`id\` text PRIMARY KEY, + \`email\` text NOT NULL, + \`url\` text NOT NULL, + \`access_token\` text NOT NULL, + \`refresh_token\` text NOT NULL, + \`token_expiry\` integer, + \`selected_org_id\` text, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL + ); + `) + yield* tx.run(` + CREATE TABLE \`account_state\` ( + \`id\` integer PRIMARY KEY NOT NULL, + \`active_account_id\` text, + FOREIGN KEY (\`active_account_id\`) REFERENCES \`account\`(\`id\`) ON UPDATE no action ON DELETE set null + ); + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260303231226_add_workspace_fields.ts b/packages/core/src/database/migration/20260303231226_add_workspace_fields.ts new file mode 100644 index 000000000000..380e9cc68bf9 --- /dev/null +++ b/packages/core/src/database/migration/20260303231226_add_workspace_fields.ts @@ -0,0 +1,15 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260303231226_add_workspace_fields", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`workspace\` ADD \`type\` text NOT NULL;`) + yield* tx.run(`ALTER TABLE \`workspace\` ADD \`name\` text;`) + yield* tx.run(`ALTER TABLE \`workspace\` ADD \`directory\` text;`) + yield* tx.run(`ALTER TABLE \`workspace\` ADD \`extra\` text;`) + yield* tx.run(`ALTER TABLE \`workspace\` DROP COLUMN \`config\`;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260309230000_move_org_to_state.ts b/packages/core/src/database/migration/20260309230000_move_org_to_state.ts new file mode 100644 index 000000000000..bf39f3e5bf68 --- /dev/null +++ b/packages/core/src/database/migration/20260309230000_move_org_to_state.ts @@ -0,0 +1,15 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260309230000_move_org_to_state", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`account_state\` ADD \`active_org_id\` text;`) + yield* tx.run( + `UPDATE \`account_state\` SET \`active_org_id\` = (SELECT \`selected_org_id\` FROM \`account\` WHERE \`account\`.\`id\` = \`account_state\`.\`active_account_id\`);`, + ) + yield* tx.run(`ALTER TABLE \`account\` DROP COLUMN \`selected_org_id\`;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260312043431_session_message_cursor.ts b/packages/core/src/database/migration/20260312043431_session_message_cursor.ts new file mode 100644 index 000000000000..1603c3fa739e --- /dev/null +++ b/packages/core/src/database/migration/20260312043431_session_message_cursor.ts @@ -0,0 +1,16 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260312043431_session_message_cursor", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`DROP INDEX IF EXISTS \`message_session_idx\`;`) + yield* tx.run(`DROP INDEX IF EXISTS \`part_message_idx\`;`) + yield* tx.run( + `CREATE INDEX \`message_session_time_created_id_idx\` ON \`message\` (\`session_id\`,\`time_created\`,\`id\`);`, + ) + yield* tx.run(`CREATE INDEX \`part_message_id_id_idx\` ON \`part\` (\`message_id\`,\`id\`);`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260323234822_events.ts b/packages/core/src/database/migration/20260323234822_events.ts new file mode 100644 index 000000000000..2b1996fbacc8 --- /dev/null +++ b/packages/core/src/database/migration/20260323234822_events.ts @@ -0,0 +1,26 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260323234822_events", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`event_sequence\` ( + \`aggregate_id\` text PRIMARY KEY, + \`seq\` integer NOT NULL + ); + `) + yield* tx.run(` + CREATE TABLE \`event\` ( + \`id\` text PRIMARY KEY, + \`aggregate_id\` text NOT NULL, + \`seq\` integer NOT NULL, + \`type\` text NOT NULL, + \`data\` text NOT NULL, + CONSTRAINT \`fk_event_aggregate_id_event_sequence_aggregate_id_fk\` FOREIGN KEY (\`aggregate_id\`) REFERENCES \`event_sequence\`(\`aggregate_id\`) ON DELETE CASCADE + ); + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260410174513_workspace-name.ts b/packages/core/src/database/migration/20260410174513_workspace-name.ts new file mode 100644 index 000000000000..18483e1cf089 --- /dev/null +++ b/packages/core/src/database/migration/20260410174513_workspace-name.ts @@ -0,0 +1,29 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260410174513_workspace-name", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`PRAGMA foreign_keys=OFF;`) + yield* tx.run(` + CREATE TABLE \`__new_workspace\` ( + \`id\` text PRIMARY KEY, + \`type\` text NOT NULL, + \`name\` text DEFAULT '' NOT NULL, + \`branch\` text, + \`directory\` text, + \`extra\` text, + \`project_id\` text NOT NULL, + CONSTRAINT \`fk_workspace_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run( + `INSERT INTO \`__new_workspace\`(\`id\`, \`type\`, \`branch\`, \`name\`, \`directory\`, \`extra\`, \`project_id\`) SELECT \`id\`, \`type\`, \`branch\`, \`name\`, \`directory\`, \`extra\`, \`project_id\` FROM \`workspace\`;`, + ) + yield* tx.run(`DROP TABLE \`workspace\`;`) + yield* tx.run(`ALTER TABLE \`__new_workspace\` RENAME TO \`workspace\`;`) + yield* tx.run(`PRAGMA foreign_keys=ON;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260413175956_chief_energizer.ts b/packages/core/src/database/migration/20260413175956_chief_energizer.ts new file mode 100644 index 000000000000..a03477e09e38 --- /dev/null +++ b/packages/core/src/database/migration/20260413175956_chief_energizer.ts @@ -0,0 +1,24 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260413175956_chief_energizer", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`session_entry\` ( + \`id\` text PRIMARY KEY, + \`session_id\` text NOT NULL, + \`type\` text NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`data\` text NOT NULL, + CONSTRAINT \`fk_session_entry_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(`CREATE INDEX \`session_entry_session_idx\` ON \`session_entry\` (\`session_id\`);`) + yield* tx.run(`CREATE INDEX \`session_entry_session_type_idx\` ON \`session_entry\` (\`session_id\`,\`type\`);`) + yield* tx.run(`CREATE INDEX \`session_entry_time_created_idx\` ON \`session_entry\` (\`time_created\`);`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260423070820_add_icon_url_override.ts b/packages/core/src/database/migration/20260423070820_add_icon_url_override.ts new file mode 100644 index 000000000000..20b1f9163a41 --- /dev/null +++ b/packages/core/src/database/migration/20260423070820_add_icon_url_override.ts @@ -0,0 +1,14 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260423070820_add_icon_url_override", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + ALTER TABLE \`project\` ADD \`icon_url_override\` text; + UPDATE \`project\` SET \`icon_url_override\` = \`icon_url\` WHERE \`icon_url\` IS NOT NULL; + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260427172553_slow_nightmare.ts b/packages/core/src/database/migration/20260427172553_slow_nightmare.ts new file mode 100644 index 000000000000..32e67decf3a7 --- /dev/null +++ b/packages/core/src/database/migration/20260427172553_slow_nightmare.ts @@ -0,0 +1,30 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260427172553_slow_nightmare", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`session_message\` ( + \`id\` text PRIMARY KEY, + \`session_id\` text NOT NULL, + \`type\` text NOT NULL, + \`time_created\` integer NOT NULL, + \`time_updated\` integer NOT NULL, + \`data\` text NOT NULL, + CONSTRAINT \`fk_session_message_session_id_session_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(`DROP INDEX IF EXISTS \`session_entry_session_idx\`;`) + yield* tx.run(`DROP INDEX IF EXISTS \`session_entry_session_type_idx\`;`) + yield* tx.run(`DROP INDEX IF EXISTS \`session_entry_time_created_idx\`;`) + yield* tx.run(`CREATE INDEX \`session_message_session_idx\` ON \`session_message\` (\`session_id\`);`) + yield* tx.run( + `CREATE INDEX \`session_message_session_type_idx\` ON \`session_message\` (\`session_id\`,\`type\`);`, + ) + yield* tx.run(`CREATE INDEX \`session_message_time_created_idx\` ON \`session_message\` (\`time_created\`);`) + yield* tx.run(`DROP TABLE \`session_entry\`;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260428004200_add_session_path.ts b/packages/core/src/database/migration/20260428004200_add_session_path.ts new file mode 100644 index 000000000000..a60ef377fc2b --- /dev/null +++ b/packages/core/src/database/migration/20260428004200_add_session_path.ts @@ -0,0 +1,11 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260428004200_add_session_path", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`session\` ADD \`path\` text;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260501142318_next_venus.ts b/packages/core/src/database/migration/20260501142318_next_venus.ts new file mode 100644 index 000000000000..6c5b078f8fa8 --- /dev/null +++ b/packages/core/src/database/migration/20260501142318_next_venus.ts @@ -0,0 +1,12 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260501142318_next_venus", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`session\` ADD \`agent\` text;`) + yield* tx.run(`ALTER TABLE \`session\` ADD \`model\` text;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260504145000_add_sync_owner.ts b/packages/core/src/database/migration/20260504145000_add_sync_owner.ts new file mode 100644 index 000000000000..33e855491452 --- /dev/null +++ b/packages/core/src/database/migration/20260504145000_add_sync_owner.ts @@ -0,0 +1,11 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260504145000_add_sync_owner", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`event_sequence\` ADD \`owner_id\` text;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260507164347_add_workspace_time.ts b/packages/core/src/database/migration/20260507164347_add_workspace_time.ts new file mode 100644 index 000000000000..df7e90fc9313 --- /dev/null +++ b/packages/core/src/database/migration/20260507164347_add_workspace_time.ts @@ -0,0 +1,11 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260507164347_add_workspace_time", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`workspace\` ADD \`time_used\` integer NOT NULL DEFAULT 0;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260510033149_session_usage.ts b/packages/core/src/database/migration/20260510033149_session_usage.ts new file mode 100644 index 000000000000..5dcd1f658e76 --- /dev/null +++ b/packages/core/src/database/migration/20260510033149_session_usage.ts @@ -0,0 +1,56 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260510033149_session_usage", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(`ALTER TABLE \`session\` ADD \`cost\` real DEFAULT 0 NOT NULL;`) + yield* tx.run(`ALTER TABLE \`session\` ADD \`tokens_input\` integer DEFAULT 0 NOT NULL;`) + yield* tx.run(`ALTER TABLE \`session\` ADD \`tokens_output\` integer DEFAULT 0 NOT NULL;`) + yield* tx.run(`ALTER TABLE \`session\` ADD \`tokens_reasoning\` integer DEFAULT 0 NOT NULL;`) + yield* tx.run(`ALTER TABLE \`session\` ADD \`tokens_cache_read\` integer DEFAULT 0 NOT NULL;`) + yield* tx.run(`ALTER TABLE \`session\` ADD \`tokens_cache_write\` integer DEFAULT 0 NOT NULL;`) + yield* tx.run(` + UPDATE session + SET + cost = coalesce(( + SELECT sum(coalesce(json_extract(message.data, '$.cost'), 0)) + FROM message + WHERE message.session_id = session.id + AND json_extract(message.data, '$.role') = 'assistant' + ), 0), + tokens_input = coalesce(( + SELECT sum(coalesce(json_extract(message.data, '$.tokens.input'), 0)) + FROM message + WHERE message.session_id = session.id + AND json_extract(message.data, '$.role') = 'assistant' + ), 0), + tokens_output = coalesce(( + SELECT sum(coalesce(json_extract(message.data, '$.tokens.output'), 0)) + FROM message + WHERE message.session_id = session.id + AND json_extract(message.data, '$.role') = 'assistant' + ), 0), + tokens_reasoning = coalesce(( + SELECT sum(coalesce(json_extract(message.data, '$.tokens.reasoning'), 0)) + FROM message + WHERE message.session_id = session.id + AND json_extract(message.data, '$.role') = 'assistant' + ), 0), + tokens_cache_read = coalesce(( + SELECT sum(coalesce(json_extract(message.data, '$.tokens.cache.read'), 0)) + FROM message + WHERE message.session_id = session.id + AND json_extract(message.data, '$.role') = 'assistant' + ), 0), + tokens_cache_write = coalesce(( + SELECT sum(coalesce(json_extract(message.data, '$.tokens.cache.write'), 0)) + FROM message + WHERE message.session_id = session.id + AND json_extract(message.data, '$.role') = 'assistant' + ), 0) + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260511000411_data_migration_state.ts b/packages/core/src/database/migration/20260511000411_data_migration_state.ts new file mode 100644 index 000000000000..7ff0b6618911 --- /dev/null +++ b/packages/core/src/database/migration/20260511000411_data_migration_state.ts @@ -0,0 +1,16 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260511000411_data_migration_state", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`data_migration\` ( + \`name\` text PRIMARY KEY, + \`time_completed\` integer NOT NULL + ); + `) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/migration/20260511173437_session-metadata.ts b/packages/core/src/database/migration/20260511173437_session-metadata.ts new file mode 100644 index 000000000000..413f086671d3 --- /dev/null +++ b/packages/core/src/database/migration/20260511173437_session-metadata.ts @@ -0,0 +1,16 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260511173437_session-metadata", + up(tx) { + return Effect.gen(function* () { + // This column briefly shipped again under 20260530232709_lovely_romulus. + if ( + (yield* tx.all<{ name: string }>(`PRAGMA table_info(\`session\`)`)).some((column) => column.name === "metadata") + ) + return + yield* tx.run(`ALTER TABLE \`session\` ADD \`metadata\` text;`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/opencode/src/storage/schema.sql.ts b/packages/core/src/database/schema.sql.ts similarity index 100% rename from packages/opencode/src/storage/schema.sql.ts rename to packages/core/src/database/schema.sql.ts diff --git a/packages/core/src/database/sqlite.bun.ts b/packages/core/src/database/sqlite.bun.ts new file mode 100644 index 000000000000..5dda2cd2c6e8 --- /dev/null +++ b/packages/core/src/database/sqlite.bun.ts @@ -0,0 +1,182 @@ +import { Database } from "bun:sqlite" +import { drizzle } from "drizzle-orm/bun-sqlite" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Fiber from "effect/Fiber" +import { identity } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Scope from "effect/Scope" +import * as Semaphore from "effect/Semaphore" +import * as Stream from "effect/Stream" +import * as Reactivity from "effect/unstable/reactivity/Reactivity" +import * as Client from "effect/unstable/sql/SqlClient" +import type { Connection } from "effect/unstable/sql/SqlConnection" +import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError" +import * as Statement from "effect/unstable/sql/Statement" +import { Sqlite } from "./sqlite" + +const ATTR_DB_SYSTEM_NAME = "db.system.name" + +const TypeId = "~@opencode-ai/core/database/SqliteBun" as const +type TypeId = typeof TypeId + +interface SqliteClient extends Client.SqlClient { + readonly [TypeId]: TypeId + readonly config: Config + readonly export: Effect.Effect + readonly loadExtension: (path: string) => Effect.Effect + readonly updateValues: never +} + +interface Config { + readonly filename: string + readonly readonly?: boolean + readonly create?: boolean + readonly readwrite?: boolean + readonly disableWAL?: boolean + readonly spanAttributes?: Record + readonly transformResultNames?: (str: string) => string + readonly transformQueryNames?: (str: string) => string +} + +interface SqliteConnection extends Connection { + readonly export: Effect.Effect + readonly loadExtension: (path: string) => Effect.Effect +} + +const make = (options: Config) => + Effect.gen(function* () { + const native = (yield* Sqlite.Native) as Database + + const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) + const transformRows = options.transformResultNames + ? Statement.defaultTransforms(options.transformResultNames).array + : undefined + + const run = (query: string, params: ReadonlyArray = []) => + Effect.withFiber>, SqlError>((fiber) => { + const statement = native.query(query) + // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627 + statement.safeIntegers(Context.get(fiber.context, Client.SafeIntegers)) + try { + return Effect.succeed((statement.all(...(params as any)) ?? []) as Array>) + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }), + }), + ) + } + }) + + const runValues = (query: string, params: ReadonlyArray = []) => + Effect.withFiber, SqlError>((fiber) => { + const statement = native.query(query) + // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627 + statement.safeIntegers(Context.get(fiber.context, Client.SafeIntegers)) + try { + return Effect.succeed((statement.values(...(params as any)) ?? []) as Array) + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }), + }), + ) + } + }) + + const connection = identity({ + execute(query, params, transformRows) { + return transformRows ? Effect.map(run(query, params), transformRows) : run(query, params) + }, + executeRaw(query, params) { + return run(query, params) + }, + executeValues(query, params) { + return runValues(query, params) + }, + executeUnprepared(query, params, transformRows) { + return this.execute(query, params, transformRows) + }, + executeStream() { + return Stream.die("executeStream not implemented") + }, + export: Effect.try({ + try: () => native.serialize(), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to export database", operation: "export" }), + }), + }), + loadExtension: (path) => + Effect.try({ + try: () => native.loadExtension(path), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to load extension", operation: "loadExtension" }), + }), + }), + }) + + const semaphore = yield* Semaphore.make(1) + const acquirer = semaphore.withPermits(1)(Effect.succeed(connection)) + const transactionAcquirer = Effect.uninterruptibleMask((restore) => { + const fiber = Fiber.getCurrent()! + const scope = Context.getUnsafe(fiber.context, Scope.Scope) + return Effect.as( + Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), + connection, + ) + }) + + const client = Object.assign( + (yield* Client.make({ + acquirer, + compiler, + transactionAcquirer, + spanAttributes: [ + ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), + [ATTR_DB_SYSTEM_NAME, "sqlite"], + ], + transformRows, + })) as SqliteClient, + { + [TypeId]: TypeId, + config: options, + export: Effect.flatMap(acquirer, (_) => _.export), + loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path)), + }, + ) + + return client + }) + +const nativeLayer = (config: Config) => + Layer.effect( + Sqlite.Native, + Effect.gen(function* () { + const native = new Database(config.filename, { + readonly: config.readonly, + readwrite: config.readwrite ?? true, + create: config.create ?? true, + }) + yield* Effect.addFinalizer(() => Effect.sync(() => native.close())) + if (config.disableWAL !== true) native.run("PRAGMA journal_mode = WAL;") + return native + }), + ) + +const sqliteLayer = (config: Config) => Layer.effect(Client.SqlClient, make(config)) + +const drizzleLayer = Layer.effect( + Sqlite.Drizzle, + Effect.gen(function* () { + return drizzle({ client: (yield* Sqlite.Native) as Database }) + }), +) + +export const layer = (config: Config) => + Layer.merge( + nativeLayer(config), + Layer.merge(sqliteLayer(config), drizzleLayer).pipe(Layer.provide(nativeLayer(config))), + ).pipe(Layer.provide(Reactivity.layer)) diff --git a/packages/core/src/database/sqlite.node.ts b/packages/core/src/database/sqlite.node.ts new file mode 100644 index 000000000000..d7471a440114 --- /dev/null +++ b/packages/core/src/database/sqlite.node.ts @@ -0,0 +1,177 @@ +import { DatabaseSync, type SQLInputValue } from "node:sqlite" +import { drizzle } from "drizzle-orm/node-sqlite" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Fiber from "effect/Fiber" +import { identity } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Scope from "effect/Scope" +import * as Semaphore from "effect/Semaphore" +import * as Stream from "effect/Stream" +import * as Reactivity from "effect/unstable/reactivity/Reactivity" +import * as Client from "effect/unstable/sql/SqlClient" +import type { Connection } from "effect/unstable/sql/SqlConnection" +import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError" +import * as Statement from "effect/unstable/sql/Statement" +import { Sqlite } from "./sqlite" + +const ATTR_DB_SYSTEM_NAME = "db.system.name" + +const TypeId = "~@opencode-ai/core/database/SqliteNode" as const +type TypeId = typeof TypeId + +interface SqliteClient extends Client.SqlClient { + readonly [TypeId]: TypeId + readonly config: Config + readonly loadExtension: (path: string) => Effect.Effect + readonly updateValues: never +} + +interface Config { + readonly filename: string + readonly readonly?: boolean + readonly create?: boolean + readonly readwrite?: boolean + readonly disableWAL?: boolean + readonly timeout?: number + readonly allowExtension?: boolean + readonly spanAttributes?: Record + readonly transformResultNames?: (str: string) => string + readonly transformQueryNames?: (str: string) => string +} + +interface SqliteConnection extends Connection { + readonly loadExtension: (path: string) => Effect.Effect +} + +const make = (options: Config) => + Effect.gen(function* () { + const native = (yield* Sqlite.Native) as DatabaseSync + + const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) + const transformRows = options.transformResultNames + ? Statement.defaultTransforms(options.transformResultNames).array + : undefined + + const run = (query: string, params: ReadonlyArray = []) => + Effect.withFiber>, SqlError>((fiber) => { + const statement = native.prepare(query) + statement.setReadBigInts(Context.get(fiber.context, Client.SafeIntegers)) + try { + return Effect.succeed(statement.all(...(params as SQLInputValue[])) as Array>) + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }), + }), + ) + } + }) + + const runValues = (query: string, params: ReadonlyArray = []) => + Effect.withFiber>, SqlError>((fiber) => { + const statement = native.prepare(query) + statement.setReadBigInts(Context.get(fiber.context, Client.SafeIntegers)) + statement.setReturnArrays(true) + try { + return Effect.succeed( + statement.all(...(params as SQLInputValue[])) as unknown as ReadonlyArray>, + ) + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }), + }), + ) + } + }) + + const connection = identity({ + execute(query, params, transformRows) { + return transformRows ? Effect.map(run(query, params), transformRows) : run(query, params) + }, + executeRaw(query, params) { + return run(query, params) + }, + executeValues(query, params) { + return runValues(query, params) + }, + executeUnprepared(query, params, transformRows) { + return this.execute(query, params, transformRows) + }, + executeStream() { + return Stream.die("executeStream not implemented") + }, + loadExtension: (path) => + Effect.try({ + try: () => native.loadExtension(path), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to load extension", operation: "loadExtension" }), + }), + }), + }) + + const semaphore = yield* Semaphore.make(1) + const acquirer = semaphore.withPermits(1)(Effect.succeed(connection)) + const transactionAcquirer = Effect.uninterruptibleMask((restore) => { + const fiber = Fiber.getCurrent()! + const scope = Context.getUnsafe(fiber.context, Scope.Scope) + return Effect.as( + Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), + connection, + ) + }) + + const client = Object.assign( + (yield* Client.make({ + acquirer, + compiler, + transactionAcquirer, + spanAttributes: [ + ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), + [ATTR_DB_SYSTEM_NAME, "sqlite"], + ], + transformRows, + })) as SqliteClient, + { + [TypeId]: TypeId, + config: options, + loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path)), + }, + ) + + return client + }) + +const nativeLayer = (config: Config) => + Layer.effect( + Sqlite.Native, + Effect.gen(function* () { + const native = new DatabaseSync(config.filename, { + readOnly: config.readonly, + timeout: config.timeout, + allowExtension: config.allowExtension, + enableForeignKeyConstraints: true, + open: true, + }) + yield* Effect.addFinalizer(() => Effect.sync(() => native.close())) + if (config.disableWAL !== true && config.readonly !== true) native.exec("PRAGMA journal_mode = WAL;") + return native + }), + ) + +const sqliteLayer = (config: Config) => Layer.effect(Client.SqlClient, make(config)) + +const drizzleLayer = Layer.effect( + Sqlite.Drizzle, + Effect.gen(function* () { + return drizzle({ client: (yield* Sqlite.Native) as DatabaseSync }) as unknown as Sqlite.DrizzleClient + }), +) + +export const layer = (config: Config) => + Layer.merge( + nativeLayer(config), + Layer.merge(sqliteLayer(config), drizzleLayer).pipe(Layer.provide(nativeLayer(config))), + ).pipe(Layer.provide(Reactivity.layer)) diff --git a/packages/core/src/database/sqlite.ts b/packages/core/src/database/sqlite.ts new file mode 100644 index 000000000000..d2304a54737a --- /dev/null +++ b/packages/core/src/database/sqlite.ts @@ -0,0 +1,8 @@ +export * as Sqlite from "./sqlite" + +import { Context } from "effect" +import type { drizzle } from "drizzle-orm/bun-sqlite" + +export type DrizzleClient = ReturnType +export class Native extends Context.Service()("@opencode-ai/core/database/SqliteNative") {} +export class Drizzle extends Context.Service()("@opencode-ai/core/database/SqliteDrizzle") {} diff --git a/packages/core/src/event.ts b/packages/core/src/event.ts index a4a5dd859515..0be8c64ef6b8 100644 --- a/packages/core/src/event.ts +++ b/packages/core/src/event.ts @@ -1,6 +1,9 @@ export * as EventV2 from "./event" import { Context, Effect, Layer, Option, PubSub, Schema, Stream } from "effect" +import { eq } from "drizzle-orm" +import { Database } from "./database/database" +import { EventSequenceTable, EventTable } from "./event/sql" import { Location } from "./location" import { withStatics } from "./schema" import { Identifier } from "./util/identifier" @@ -13,8 +16,10 @@ export type ID = typeof ID.Type export type Definition = { readonly type: Type - readonly version?: number - readonly aggregate?: string + readonly sync?: { + readonly version: number + readonly aggregate: string + } readonly data: DataSchema } @@ -29,14 +34,41 @@ export type Payload = { readonly metadata?: Record } +export type Projector = (event: Payload) => Effect.Effect +type AnyProjector = (event: Payload) => Effect.Effect +export type Listener = (event: Payload) => Effect.Effect export type Sync = (event: Payload) => Effect.Effect +export type Unsubscribe = Effect.Effect + +export type SerializedEvent = { + readonly id: ID + readonly type: string + readonly seq: number + readonly aggregateID: string + readonly data: Record +} + +export class InvalidSyncEventError extends Schema.TaggedErrorClass()( + "EventV2.InvalidSyncEvent", + { + type: Schema.String, + message: Schema.String, + }, +) {} + +export function versionedType(type: string, version: number) { + return `${type}.${version}` +} export const registry = new Map() +const syncRegistry = new Map }>() export function define(input: { readonly type: Type - readonly version?: number - readonly aggregate?: string + readonly sync?: { + readonly version: number + readonly aggregate: string + } readonly schema: Fields }): Schema.Schema>>> & Definition> { const Data = Schema.Struct(input.schema) @@ -51,11 +83,18 @@ export function define= existing.sync.version) { + registry.set(input.type, definition) + } + if (input.sync) + syncRegistry.set( + versionedType(input.type, input.sync.version), + definition as Definition & { readonly sync: NonNullable }, + ) return definition as Schema.Schema>>> & Definition> } @@ -67,20 +106,30 @@ export function definitions() { export interface PublishOptions { readonly id?: ID readonly metadata?: Record + readonly location?: Location.Ref } -export type Unsubscribe = Effect.Effect - export interface Interface { readonly publish: ( definition: D, data: Data, options?: PublishOptions, ) => Effect.Effect> - readonly publishEvent: (event: Payload) => Effect.Effect> readonly subscribe: (definition: D) => Stream.Stream> readonly all: () => Stream.Stream readonly sync: (handler: Sync) => Effect.Effect + readonly listen: (listener: Listener) => Effect.Effect + readonly project: (definition: D, projector: Projector) => Effect.Effect + readonly replay: ( + event: SerializedEvent, + options?: { readonly publish?: boolean; readonly ownerID?: string }, + ) => Effect.Effect + readonly replayAll: ( + events: SerializedEvent[], + options?: { readonly publish?: boolean; readonly ownerID?: string }, + ) => Effect.Effect + readonly remove: (aggregateID: string) => Effect.Effect + readonly claim: (aggregateID: string, ownerID: string) => Effect.Effect } export class Service extends Context.Service()("@opencode/Event") {} @@ -90,7 +139,10 @@ export const layer = Layer.effect( Effect.gen(function* () { const all = yield* PubSub.unbounded() const typed = new Map>() + const projectors = new Map() + const listeners = new Array() const syncHandlers = new Array() + const { db } = yield* Database.Service const getOrCreate = (definition: Definition) => Effect.gen(function* () { @@ -108,11 +160,97 @@ export const layer = Layer.effect( }), ) + function commitSyncEvent( + event: Payload, + input?: { readonly seq: number; readonly aggregateID: string; readonly ownerID?: string }, + ) { + return Effect.gen(function* () { + const definition = registry.get(event.type) + const sync = definition?.sync + if (sync) { + if (event.version !== sync.version) { + yield* Effect.die( + new InvalidSyncEventError({ + type: event.type, + message: `Expected event version ${sync.version}, got ${event.version}`, + }), + ) + } + const aggregateID = (event.data as Record)[sync.aggregate] + if (typeof aggregateID !== "string") { + yield* Effect.die( + new InvalidSyncEventError({ + type: event.type, + message: `Expected string aggregate field ${sync.aggregate}`, + }), + ) + } else { + const list = projectors.get(event.type) ?? [] + yield* db + .transaction( + () => + Effect.gen(function* () { + const row = yield* db + .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) + .from(EventSequenceTable) + .where(eq(EventSequenceTable.aggregate_id, aggregateID)) + .get() + .pipe(Effect.orDie) + const latest = row?.seq ?? -1 + if (input && input.seq <= latest) return + if (input && row?.ownerID && row.ownerID !== input.ownerID) return + const seq = input?.seq ?? latest + 1 + if (input && seq !== latest + 1) { + yield* Effect.die( + new InvalidSyncEventError({ + type: event.type, + message: `Sequence mismatch for aggregate ${aggregateID}: expected ${latest + 1}, got ${seq}`, + }), + ) + } + for (const projector of list) { + yield* projector(event as Payload) + } + yield* db + .insert(EventSequenceTable) + .values([{ aggregate_id: aggregateID, seq, owner_id: input?.ownerID }]) + .onConflictDoUpdate({ + target: EventSequenceTable.aggregate_id, + set: { seq }, + }) + .run() + .pipe(Effect.orDie) + yield* db + .insert(EventTable) + .values([ + { + id: event.id, + aggregate_id: aggregateID, + seq, + type: versionedType(definition.type, sync.version), + data: event.data as Record, + }, + ]) + .run() + .pipe(Effect.orDie) + }), + { behavior: "immediate" }, + ) + .pipe(Effect.orDie) + } + } + }) + } + function publishEvent(event: Payload) { return Effect.gen(function* () { for (const sync of syncHandlers) { yield* sync(event as Payload) } + yield* commitSyncEvent(event as Payload) + for (const listener of listeners) { + yield* listener(event as Payload) + } const pubsub = typed.get(event.type) if (pubsub) yield* PubSub.publish(pubsub, event as Payload) yield* PubSub.publish(all, event as Payload) @@ -122,25 +260,117 @@ export const layer = Layer.effect( function publish(definition: D, data: Data, options?: PublishOptions) { return Effect.gen(function* () { - const location = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service)) - const event = { + const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service)) + const location = + options?.location ?? + (serviceLocation + ? { directory: serviceLocation.directory, workspaceID: serviceLocation.workspaceID } + : undefined) + return yield* publishEvent({ id: options?.id ?? ID.create(), ...(options?.metadata ? { metadata: options.metadata } : {}), type: definition.type, - ...(definition.version === undefined ? {} : { version: definition.version }), + ...(definition.sync === undefined ? {} : { version: definition.sync.version }), ...(location ? { location } : {}), data, - } as Payload - return yield* publishEvent(event) + } as Payload) + }) + } + + function replay(event: SerializedEvent, options?: { readonly publish?: boolean; readonly ownerID?: string }) { + return Effect.gen(function* () { + const definition = syncRegistry.get(event.type) + if (!definition) { + yield* Effect.die( + new InvalidSyncEventError({ type: event.type, message: `Unknown sync event type ${event.type}` }), + ) + } else { + const payload = { + id: event.id, + type: definition.type, + version: definition.sync.version, + data: event.data, + } as Payload + yield* commitSyncEvent(payload, { seq: event.seq, aggregateID: event.aggregateID, ownerID: options?.ownerID }) + if (options?.publish) { + for (const listener of listeners) { + yield* listener(payload) + } + const pubsub = typed.get(payload.type) + if (pubsub) yield* PubSub.publish(pubsub, payload) + yield* PubSub.publish(all, payload) + } + } }) } + function replayAll(events: SerializedEvent[], options?: { readonly publish?: boolean; readonly ownerID?: string }) { + return Effect.gen(function* () { + const source = events[0]?.aggregateID + if (!source) return undefined + if (events.some((event) => event.aggregateID !== source)) { + yield* Effect.die( + new InvalidSyncEventError({ + type: events[0]?.type ?? "unknown", + message: "Replay events must belong to the same aggregate", + }), + ) + } + const start = events[0]?.seq ?? 0 + for (const [index, event] of events.entries()) { + const seq = start + index + if (event.seq !== seq) { + yield* Effect.die( + new InvalidSyncEventError({ + type: event.type, + message: `Replay sequence mismatch at index ${index}: expected ${seq}, got ${event.seq}`, + }), + ) + } + } + for (const event of events) { + yield* replay(event, options) + } + return source + }) + } + + function remove(aggregateID: string) { + return db + .transaction(() => + Effect.gen(function* () { + yield* db.delete(EventSequenceTable).where(eq(EventSequenceTable.aggregate_id, aggregateID)).run() + yield* db.delete(EventTable).where(eq(EventTable.aggregate_id, aggregateID)).run() + }), + ) + .pipe(Effect.orDie) + } + + function claim(aggregateID: string, ownerID: string) { + return db + .update(EventSequenceTable) + .set({ owner_id: ownerID }) + .where(eq(EventSequenceTable.aggregate_id, aggregateID)) + .run() + .pipe(Effect.orDie) + } + const subscribe = (definition: D): Stream.Stream> => Stream.unwrap(getOrCreate(definition).pipe(Effect.map((pubsub) => Stream.fromPubSub(pubsub)))).pipe( Stream.map((event) => event as Payload), ) const streamAll = (): Stream.Stream => Stream.fromPubSub(all) + + const listen = (listener: Listener): Effect.Effect => + Effect.sync(() => { + listeners.push(listener) + return Effect.sync(() => { + const index = listeners.indexOf(listener) + if (index >= 0) listeners.splice(index, 1) + }) + }) + const sync = (handler: Sync): Effect.Effect => Effect.sync(() => { syncHandlers.push(handler) @@ -150,8 +380,15 @@ export const layer = Layer.effect( }) }) - return Service.of({ publish, publishEvent, subscribe, all: streamAll, sync }) + const project = (definition: D, projector: Projector): Effect.Effect => + Effect.sync(() => { + const list = projectors.get(definition.type) ?? [] + list.push((event) => projector(event as Payload)) + projectors.set(definition.type, list) + }) + + return Service.of({ publish, subscribe, all: streamAll, sync, listen, project, replay, replayAll, remove, claim }) }), ) -export const defaultLayer = layer +export const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer)) diff --git a/packages/opencode/src/sync/event.sql.ts b/packages/core/src/event/sql.ts similarity index 86% rename from packages/opencode/src/sync/event.sql.ts rename to packages/core/src/event/sql.ts index 547a80f0f345..6bccc0fbb9db 100644 --- a/packages/opencode/src/sync/event.sql.ts +++ b/packages/core/src/event/sql.ts @@ -1,4 +1,5 @@ import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core" +import type { EventV2 } from "../event" export const EventSequenceTable = sqliteTable("event_sequence", { aggregate_id: text().notNull().primaryKey(), @@ -7,7 +8,7 @@ export const EventSequenceTable = sqliteTable("event_sequence", { }) export const EventTable = sqliteTable("event", { - id: text().primaryKey(), + id: text().$type().primaryKey(), aggregate_id: text() .notNull() .references(() => EventSequenceTable.aggregate_id, { onDelete: "cascade" }), diff --git a/packages/core/src/flag/flag.ts b/packages/core/src/flag/flag.ts index 54f2445e00d1..c9269b9c2617 100644 --- a/packages/core/src/flag/flag.ts +++ b/packages/core/src/flag/flag.ts @@ -8,6 +8,10 @@ function truthy(key: string) { const OPENCODE_EXPERIMENTAL = truthy("OPENCODE_EXPERIMENTAL") const copy = process.env["OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT"] +function enabledByExperimental(key: string) { + return process.env[key] === undefined ? OPENCODE_EXPERIMENTAL : truthy(key) +} + export const Flag = { OTEL_EXPORTER_OTLP_ENDPOINT: process.env["OTEL_EXPORTER_OTLP_ENDPOINT"], OTEL_EXPORTER_OTLP_HEADERS: process.env["OTEL_EXPORTER_OTLP_HEADERS"], @@ -42,7 +46,8 @@ export const Flag = { OPENCODE_DB: process.env["OPENCODE_DB"], OPENCODE_WORKSPACE_ID: process.env["OPENCODE_WORKSPACE_ID"], - OPENCODE_EXPERIMENTAL_WORKSPACES: OPENCODE_EXPERIMENTAL || truthy("OPENCODE_EXPERIMENTAL_WORKSPACES"), + OPENCODE_EXPERIMENTAL_WORKSPACES: enabledByExperimental("OPENCODE_EXPERIMENTAL_WORKSPACES"), + OPENCODE_EXPERIMENTAL_SESSION_SWITCHER: enabledByExperimental("OPENCODE_EXPERIMENTAL_SESSION_SWITCHER"), // Evaluated at access time (not module load) because tests, the CLI, and // external tooling set these env vars at runtime. diff --git a/packages/core/src/id/id.ts b/packages/core/src/id/id.ts new file mode 100644 index 000000000000..847a5c032924 --- /dev/null +++ b/packages/core/src/id/id.ts @@ -0,0 +1,80 @@ +import { randomBytes } from "crypto" + +const prefixes = { + job: "job", + event: "evt", + session: "ses", + message: "msg", + permission: "per", + question: "que", + part: "prt", + pty: "pty", + tool: "tool", + workspace: "wrk", +} as const + +const LENGTH = 26 + +// State for monotonic ID generation +let lastTimestamp = 0 +let counter = 0 + +export function ascending(prefix: keyof typeof prefixes, given?: string) { + return generateID(prefix, "ascending", given) +} + +export function descending(prefix: keyof typeof prefixes, given?: string) { + return generateID(prefix, "descending", given) +} + +function generateID(prefix: keyof typeof prefixes, direction: "descending" | "ascending", given?: string): string { + if (!given) { + return create(prefixes[prefix], direction) + } + + if (!given.startsWith(prefixes[prefix])) { + throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`) + } + return given +} + +function randomBase62(length: number): string { + const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + let result = "" + const bytes = randomBytes(length) + for (let i = 0; i < length; i++) { + result += chars[bytes[i] % 62] + } + return result +} + +export function create(prefix: string, direction: "descending" | "ascending", timestamp?: number): string { + const currentTimestamp = timestamp ?? Date.now() + + if (currentTimestamp !== lastTimestamp) { + lastTimestamp = currentTimestamp + counter = 0 + } + counter++ + + let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter) + + now = direction === "descending" ? ~now : now + + const timeBytes = Buffer.alloc(6) + for (let i = 0; i < 6; i++) { + timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff)) + } + + return prefix + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - 12) +} + +/** Extract timestamp from an ascending ID. Does not work with descending IDs. */ +export function timestamp(id: string): number { + const prefix = id.split("_")[0] + const hex = id.slice(prefix.length + 1, prefix.length + 13) + const encoded = BigInt("0x" + hex) + return Number(encoded / BigInt(0x1000)) +} + +export * as Identifier from "./id" diff --git a/packages/core/src/location-layer.ts b/packages/core/src/location-layer.ts index c40a94043031..a43486fa21be 100644 --- a/packages/core/src/location-layer.ts +++ b/packages/core/src/location-layer.ts @@ -1,13 +1,40 @@ import { Layer, LayerMap } from "effect" import { Location } from "./location" +import { Policy } from "./policy" +import { Config } from "./config" +import { PluginV2 } from "./plugin" import { Catalog } from "./catalog" +import { AgentV2 } from "./agent" import { PluginBoot } from "./plugin/boot" +import { Project } from "./project" +import { EventV2 } from "./event" +import { Auth } from "./auth" +import { Npm } from "./npm" +import { ModelsDev } from "./models-dev" +import { AppFileSystem } from "./filesystem" +import { Global } from "./global" export class LocationServiceMap extends LayerMap.Service()("@opencode/example/LocationServiceMap", { - lookup: (ref: Location.Ref) => - Layer.mergeAll(Catalog.defaultLayer, PluginBoot.defaultLayer).pipe( - Layer.provide([Layer.succeed(Location.Service, Location.Service.of(ref))]), - ), - idleTimeToLive: "5 minutes", - dependencies: [], + lookup: (ref: Location.Ref) => { + const location = Location.layer(ref) + return Layer.mergeAll( + location, + Policy.locationLayer, + Config.locationLayer, + PluginV2.locationLayer, + Catalog.locationLayer, + AgentV2.locationLayer, + PluginBoot.locationLayer, + ).pipe(Layer.provideMerge(location), Layer.fresh) + }, + idleTimeToLive: "60 minutes", + dependencies: [ + Project.defaultLayer, + EventV2.defaultLayer, + Auth.defaultLayer, + Npm.defaultLayer, + ModelsDev.defaultLayer, + AppFileSystem.defaultLayer, + Global.defaultLayer, + ], }) {} diff --git a/packages/core/src/location.ts b/packages/core/src/location.ts index 00ff9cd3ea72..9613885c9702 100644 --- a/packages/core/src/location.ts +++ b/packages/core/src/location.ts @@ -1,11 +1,38 @@ -import { Context, Schema } from "effect" +import { Context, Effect, Layer, Schema } from "effect" +import { Project } from "./project" +import { AbsolutePath } from "./schema" export * as Location from "./location" export const Ref = Schema.Struct({ - directory: Schema.String, + directory: AbsolutePath, workspaceID: Schema.optional(Schema.String), }).annotate({ identifier: "Location.Ref" }) export type Ref = typeof Ref.Type -export class Service extends Context.Service()("@opencode/Location") {} +export interface Interface { + readonly directory: AbsolutePath + readonly workspaceID?: string + readonly project: { + readonly id: Project.ID + readonly directory: AbsolutePath + } + readonly vcs?: Project.Vcs +} + +export class Service extends Context.Service()("@opencode/Location") {} + +export const layer = (ref: Ref) => + Layer.effect( + Service, + Effect.gen(function* () { + const project = yield* Project.Service + const resolved = yield* project.resolve(ref.directory) + return Service.of({ + directory: ref.directory, + workspaceID: ref.workspaceID, + project: { id: resolved.id, directory: resolved.directory }, + vcs: resolved.vcs, + }) + }), + ) diff --git a/packages/core/src/model.ts b/packages/core/src/model.ts index 77b8c60ebe77..b0de0802a386 100644 --- a/packages/core/src/model.ts +++ b/packages/core/src/model.ts @@ -36,7 +36,7 @@ export const Cost = Schema.Struct({ export const Ref = Schema.Struct({ id: ID, providerID: ProviderV2.ID, - variant: VariantID, + variant: VariantID.pipe(Schema.optional), }) export type Ref = typeof Ref.Type @@ -68,8 +68,8 @@ export class Info extends Schema.Class("ModelV2.Info")({ output: Schema.Int, }), }) { - static empty(providerID: ProviderV2.ID, modelID: ID) { - return new Info({ + static empty(providerID: ProviderV2.ID, modelID: ID): Info { + return { id: modelID, apiID: modelID, providerID, @@ -101,7 +101,7 @@ export class Info extends Schema.Class("ModelV2.Info")({ context: 0, output: 0, }, - }) + } } } diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index ec8038f7134d..95c2745b9dd3 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -2,18 +2,29 @@ export * as PermissionV2 from "./permission" import { Schema } from "effect" import { Wildcard } from "./util/wildcard" +import { Identifier } from "./id/id" +import { Newtype } from "./schema" + +export class PermissionID extends Newtype()( + "PermissionID", + Schema.String.check(Schema.isStartsWith("per")), +) { + static ascending(id?: string): PermissionID { + return this.make(Identifier.ascending("permission", id)) + } +} -export const Action = Schema.Literals(["allow", "deny", "ask"]).annotate({ identifier: "PermissionV2.Action" }) +export const Action = Schema.Literals(["allow", "deny", "ask"]).annotate({ identifier: "Permission.Action" }) export type Action = typeof Action.Type export const Rule = Schema.Struct({ permission: Schema.String, pattern: Schema.String, action: Action, -}).annotate({ identifier: "PermissionV2.Rule" }) +}).annotate({ identifier: "Permission.Rule" }) export type Rule = typeof Rule.Type -export const Ruleset = Schema.Array(Rule).annotate({ identifier: "PermissionV2.Ruleset" }) +export const Ruleset = Schema.Array(Rule).annotate({ identifier: "Permission.Ruleset" }) export type Ruleset = typeof Ruleset.Type const EDIT_TOOLS = ["edit", "write", "apply_patch"] diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index ab2d4cbf7d6a..7297ef0f3e87 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -2,24 +2,33 @@ export * as PluginV2 from "./plugin" import { createDraft, finishDraft, type Draft } from "immer" import type { LanguageModelV3 } from "@ai-sdk/provider" -import { Context, Effect, Exit, Layer, PubSub, Schema, Scope, Stream } from "effect" +import { Context, Effect, Exit, Layer, Schema, Scope } from "effect" import type { ModelV2 } from "./model" -import type { AgentV2 } from "./agent" import type { Catalog } from "./catalog" +import { EventV2 } from "./event" export const ID = Schema.String.pipe(Schema.brand("Plugin.ID")) export type ID = typeof ID.Type +export const Event = { + Added: EventV2.define({ + type: "plugin.added", + schema: { + id: ID, + }, + }), +} + type HookSpec = { "catalog.transform": { - input: Catalog.Context + input: Catalog.Editor output: {} } "account.switched": { input: { - serviceID: import("./account").AccountV2.ServiceID - from?: import("./account").AccountV2.ID - to?: import("./account").AccountV2.ID + serviceID: import("./auth").Auth.ServiceID + from?: import("./auth").Auth.ID + to?: import("./auth").Auth.ID } output: {} } @@ -43,27 +52,6 @@ type HookSpec = { sdk?: any } } - "agent.update": { - input: {} - output: { - agent: AgentV2.Info - cancel: boolean - } - } - "agent.remove": { - input: { - agent: AgentV2.Info - } - output: { - cancel: boolean - } - } - "agent.default": { - input: {} - output: { - agent?: AgentV2.ID - } - } } export type Hooks = { @@ -93,7 +81,6 @@ export interface Interface { effect: Effect.Effect }) => Effect.Effect readonly remove: (id: ID) => Effect.Effect - readonly added: () => Stream.Stream readonly triggerFor: ( id: ID, name: Name, @@ -117,16 +104,21 @@ export const layer = Layer.effect( hooks: HookFunctions scope: Scope.Closeable }[] = [] - const added = yield* PubSub.unbounded() - - yield* Effect.addFinalizer(() => PubSub.shutdown(added)) + const events = yield* EventV2.Service const svc = Service.of({ add: Effect.fn("Plugin.add")(function* (input) { const existing = hooks.find((item) => item.id === input.id) if (existing) yield* Scope.close(existing.scope, Exit.void).pipe(Effect.ignore) const scope = yield* Scope.make() - const result = yield* input.effect.pipe(Scope.provide(scope)) + const result = yield* input.effect.pipe( + Scope.provide(scope), + Effect.withSpan("Plugin.load", { + attributes: { + "plugin.id": input.id, + }, + }), + ) hooks = [ ...hooks.filter((item) => item.id !== input.id), { @@ -135,9 +127,8 @@ export const layer = Layer.effect( scope, }, ] - yield* PubSub.publish(added, input.id) + yield* events.publish(Event.Added, { id: input.id }) }), - added: () => Stream.fromPubSub(added), trigger: Effect.fn("Plugin.trigger")(function* (name, input, output) { return yield* svc.triggerFor(ID.make("*"), name, input, output) }), @@ -185,7 +176,7 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer +export const locationLayer = layer // opencode // sdcok diff --git a/packages/core/src/plugin/account.ts b/packages/core/src/plugin/account.ts index d4d00c3ab681..68bb43674d21 100644 --- a/packages/core/src/plugin/account.ts +++ b/packages/core/src/plugin/account.ts @@ -1,16 +1,18 @@ import { Effect, Scope, Stream } from "effect" -import { AccountV2 } from "../account" import { EventV2 } from "../event" import { PluginV2 } from "../plugin" +import { Auth } from "../auth" +// Depending on what account is active, enable matching providers for that +// service export const AccountPlugin = PluginV2.define({ id: PluginV2.ID.make("account"), effect: Effect.gen(function* () { - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const events = yield* EventV2.Service const scope = yield* Scope.Scope - yield* events.subscribe(AccountV2.Event.Switched).pipe( + yield* events.subscribe(Auth.Event.Switched).pipe( Stream.runForEach((event) => PluginV2.Service.use((plugin) => plugin.trigger("account.switched", event.data, {})).pipe(Effect.asVoid), ), @@ -19,8 +21,10 @@ export const AccountPlugin = PluginV2.define({ return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { - const account = yield* accounts.active(AccountV2.ServiceID.make(item.provider.id)).pipe(Effect.orDie) + const active = yield* accounts.activeAll().pipe(Effect.orDie) + if (active.size === 0) return + for (const item of evt.provider.list()) { + const account = active.get(Auth.ServiceID.make(item.provider.id)) if (!account) continue evt.provider.update(item.provider.id, (provider) => { provider.enabled = { diff --git a/packages/core/src/plugin/agent.ts b/packages/core/src/plugin/agent.ts new file mode 100644 index 000000000000..9baba75c3869 --- /dev/null +++ b/packages/core/src/plugin/agent.ts @@ -0,0 +1,211 @@ +export * as AgentPlugin from "./agent" + +import path from "path" +import { Effect } from "effect" +import { AgentV2 } from "../agent" +import { Global } from "../global" +import { Location } from "../location" +import { PermissionV2 } from "../permission" +import { PluginV2 } from "../plugin" + +const TRUNCATION_GLOB = path.join(Global.Path.data, "tool-output", "*") + +const PROMPT_EXPLORE = `You are a file search specialist. You excel at thoroughly navigating and exploring codebases. + +Your strengths: +- Rapidly finding files using glob patterns +- Searching code and text with powerful regex patterns +- Reading and analyzing file contents + +Guidelines: +- Use Glob for broad file pattern matching +- Use Grep for searching file contents with regex +- Use Read when you know the specific file path you need to read +- Use Bash for file operations like copying, moving, or listing directory contents +- Adapt your search approach based on the thoroughness level specified by the caller +- Return file paths as absolute paths in your final response +- For clear communication, avoid using emojis +- Do not create any files, or run bash commands that modify the user's system state in any way + +Complete the user's search request efficiently and report your findings clearly.` + +const PROMPT_COMPACTION = `You are an anchored context summarization assistant for coding sessions. + +Summarize only the conversation history you are given. The newest turns may be kept verbatim outside your summary, so focus on the older context that still matters for continuing the work. + +If the prompt includes a block, treat it as the current anchored summary. Update it with the new history by preserving still-true details, removing stale details, and merging in new facts. + +Always follow the exact output structure requested by the user prompt. Keep every section, preserve exact file paths and identifiers when known, and prefer terse bullets over paragraphs. + +Do not answer the conversation itself. Do not mention that you are summarizing, compacting, or merging context. Respond in the same language as the conversation.` + +const PROMPT_TITLE = `You are a title generator. You output ONLY a thread title. Nothing else. + + +Generate a brief title that would help the user find this conversation later. + +Follow all rules in +Use the so you know what a good title looks like. +Your output must be: +- A single line +- <=50 characters +- No explanations + + + +- you MUST use the same language as the user message you are summarizing +- Title must be grammatically correct and read naturally - no word salad +- Never include tool names in the title (e.g. "read tool", "bash tool", "edit tool") +- Focus on the main topic or question the user needs to retrieve +- Vary your phrasing - avoid repetitive patterns like always starting with "Analyzing" +- When a file is mentioned, focus on WHAT the user wants to do WITH the file, not just that they shared it +- Keep exact: technical terms, numbers, filenames, HTTP codes +- Remove: the, this, my, a, an +- Never assume tech stack +- Never use tools +- NEVER respond to questions, just generate a title for the conversation +- The title should NEVER include "summarizing" or "generating" when generating a title +- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT +- Always output something meaningful, even if the input is minimal. +- If the user message is short or conversational (e.g. "hello", "lol", "what's up", "hey"): + -> create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.) + + + +"debug 500 errors in production" -> Debugging production 500 errors +"refactor user service" -> Refactoring user service +"why is app.js failing" -> app.js failure investigation +"implement rate limiting" -> Rate limiting implementation +"how do I connect postgres to my API" -> Postgres API connection +"best practices for React hooks" -> React hooks best practices +"@src/auth.ts can you add refresh token support" -> Auth refresh token support +"@utils/parser.ts this is broken" -> Parser bug fix +"look at @config.json" -> Config review +"@App.tsx add dark mode toggle" -> Dark mode toggle in App +` + +const PROMPT_SUMMARY = `Summarize what was done in this conversation. Write like a pull request description. + +Rules: +- 2-3 sentences max +- Describe the changes made, not the process +- Do not mention running tests, builds, or other validation steps +- Do not explain what the user asked for +- Write in first person (I added..., I fixed...) +- Never ask questions or add new questions +- 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` + +export const Plugin = PluginV2.define({ + id: PluginV2.ID.make("agent"), + effect: Effect.gen(function* () { + const agent = yield* AgentV2.Service + const location = yield* Location.Service + const worktree = location.directory + const whitelistedDirs = [TRUNCATION_GLOB, path.join(Global.Path.tmp, "*")] + const readonlyExternalDirectory: PermissionV2.Ruleset = [ + { permission: "external_directory", pattern: "*", action: "ask" }, + ...whitelistedDirs.map( + (pattern): PermissionV2.Rule => ({ permission: "external_directory", pattern, action: "allow" }), + ), + ] + const defaults: PermissionV2.Ruleset = [ + { permission: "*", pattern: "*", action: "allow" }, + ...readonlyExternalDirectory, + { permission: "question", pattern: "*", action: "deny" }, + { permission: "plan_enter", pattern: "*", action: "deny" }, + { permission: "plan_exit", pattern: "*", action: "deny" }, + { permission: "repo_clone", pattern: "*", action: "deny" }, + { permission: "repo_overview", pattern: "*", action: "deny" }, + { permission: "read", pattern: "*", action: "allow" }, + { permission: "read", pattern: "*.env", action: "ask" }, + { permission: "read", pattern: "*.env.*", action: "ask" }, + { permission: "read", pattern: "*.env.example", action: "allow" }, + ] + + yield* agent.update((editor) => { + editor.update(AgentV2.ID.make("build"), (item) => { + item.description = "The default agent. Executes tools based on configured permissions." + item.mode = "primary" + item.permissions.push( + ...PermissionV2.merge(defaults, [ + { permission: "question", pattern: "*", action: "allow" }, + { permission: "plan_enter", pattern: "*", action: "allow" }, + ]), + ) + }) + + editor.update(AgentV2.ID.make("plan"), (item) => { + item.description = "Plan mode. Disallows all edit tools." + item.mode = "primary" + item.permissions.push( + ...PermissionV2.merge(defaults, [ + { permission: "question", pattern: "*", action: "allow" }, + { permission: "plan_exit", pattern: "*", action: "allow" }, + { permission: "external_directory", pattern: path.join(Global.Path.data, "plans", "*"), action: "allow" }, + { permission: "edit", pattern: "*", action: "deny" }, + { permission: "edit", pattern: path.join(".opencode", "plans", "*.md"), action: "allow" }, + { + permission: "edit", + pattern: path.relative(worktree, path.join(Global.Path.data, "plans", "*.md")), + action: "allow", + }, + ]), + ) + }) + + editor.update(AgentV2.ID.make("general"), (item) => { + item.description = + "General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel." + item.mode = "subagent" + item.permissions.push( + ...PermissionV2.merge(defaults, [{ permission: "todowrite", pattern: "*", action: "deny" }]), + ) + }) + + editor.update(AgentV2.ID.make("explore"), (item) => { + 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.' + item.system = PROMPT_EXPLORE + item.mode = "subagent" + item.permissions.push( + ...PermissionV2.merge( + defaults, + [ + { permission: "*", pattern: "*", action: "deny" }, + { permission: "grep", pattern: "*", action: "allow" }, + { permission: "glob", pattern: "*", action: "allow" }, + { permission: "list", pattern: "*", action: "allow" }, + { permission: "bash", pattern: "*", action: "allow" }, + { permission: "webfetch", pattern: "*", action: "allow" }, + { permission: "websearch", pattern: "*", action: "allow" }, + { permission: "read", pattern: "*", action: "allow" }, + ], + readonlyExternalDirectory, + ), + ) + }) + + editor.update(AgentV2.ID.make("compaction"), (item) => { + item.mode = "primary" + item.hidden = true + item.system = PROMPT_COMPACTION + item.permissions.push(...PermissionV2.merge(defaults, [{ permission: "*", pattern: "*", action: "deny" }])) + }) + + editor.update(AgentV2.ID.make("title"), (item) => { + item.mode = "primary" + item.hidden = true + item.system = PROMPT_TITLE + item.permissions.push(...PermissionV2.merge(defaults, [{ permission: "*", pattern: "*", action: "deny" }])) + }) + + editor.update(AgentV2.ID.make("summary"), (item) => { + item.mode = "primary" + item.hidden = true + item.system = PROMPT_SUMMARY + item.permissions.push(...PermissionV2.merge(defaults, [{ permission: "*", pattern: "*", action: "deny" }])) + }) + }) + }), +}) diff --git a/packages/core/src/plugin/boot.ts b/packages/core/src/plugin/boot.ts index 5624369e0475..98004600e6e1 100644 --- a/packages/core/src/plugin/boot.ts +++ b/packages/core/src/plugin/boot.ts @@ -1,13 +1,19 @@ export * as PluginBoot from "./boot" import { Context, Deferred, Effect, Layer } from "effect" -import { AccountV2 } from "../account" +import { Auth } from "../auth" import { AgentV2 } from "../agent" import { Catalog } from "../catalog" +import { Config } from "../config" +import { ConfigAgentPlugin } from "../config/plugin/agent" import { EventV2 } from "../event" +import { Location } from "../location" +import { ModelsDev } from "../models-dev" import { Npm } from "../npm" import { PluginV2 } from "../plugin" import { AccountPlugin } from "./account" +import { AgentPlugin } from "./agent" +import { ConfigProviderPlugin } from "../config/plugin/provider" import { EnvPlugin } from "./env" import { ModelsDevPlugin } from "./models-dev" import { ProviderPlugins } from "./provider" @@ -15,7 +21,15 @@ import { ProviderPlugins } from "./provider" type Plugin = { id: PluginV2.ID effect: PluginV2.Effect< - Catalog.Service | AgentV2.Service | AccountV2.Service | Npm.Service | EventV2.Service | PluginV2.Service + | Catalog.Service + | Auth.Service + | AgentV2.Service + | Npm.Service + | EventV2.Service + | Location.Service + | PluginV2.Service + | Config.Service + | ModelsDev.Service > } @@ -28,10 +42,13 @@ export class Service extends Context.Service()("@opencode/v2 export const layer = Layer.effect( Service, Effect.gen(function* () { - const agent = yield* AgentV2.Service const catalog = yield* Catalog.Service const plugin = yield* PluginV2.Service - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.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 done = yield* Deferred.make() @@ -41,8 +58,11 @@ export const layer = Layer.effect( id: input.id, effect: input.effect.pipe( Effect.provideService(Catalog.Service, catalog), - Effect.provideService(AgentV2.Service, agent), - Effect.provideService(AccountV2.Service, accounts), + Effect.provideService(Auth.Service, accounts), + 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(PluginV2.Service, plugin), @@ -53,10 +73,13 @@ export const layer = Layer.effect( const boot = Effect.gen(function* () { yield* add(EnvPlugin) yield* add(AccountPlugin) + yield* add(AgentPlugin.Plugin) for (const item of ProviderPlugins) { yield* add(item) } yield* add(ModelsDevPlugin) + yield* add(ConfigProviderPlugin.Plugin) + yield* add(ConfigAgentPlugin.Plugin) }).pipe(Effect.withSpan("PluginBoot.boot")) yield* boot.pipe( @@ -71,11 +94,8 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe( - Layer.provide(AgentV2.defaultLayer), - Layer.provide(Catalog.defaultLayer), - Layer.provide(EventV2.defaultLayer), - Layer.provide(PluginV2.defaultLayer), - Layer.provide(AccountV2.defaultLayer), - Layer.provide(Npm.defaultLayer), +export const locationLayer = layer.pipe( + Layer.provideMerge(Catalog.locationLayer), + Layer.provideMerge(Config.locationLayer), + Layer.provideMerge(AgentV2.locationLayer), ) diff --git a/packages/core/src/plugin/env.ts b/packages/core/src/plugin/env.ts index 3d716fe6f38e..35e6981a40c1 100644 --- a/packages/core/src/plugin/env.ts +++ b/packages/core/src/plugin/env.ts @@ -6,7 +6,7 @@ export const EnvPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { const key = item.provider.env.find((env) => process.env[env]) if (!key) continue evt.provider.update(item.provider.id, (provider) => { diff --git a/packages/core/src/plugin/models-dev.ts b/packages/core/src/plugin/models-dev.ts index bde162d72908..7ee38ac6de80 100644 --- a/packages/core/src/plugin/models-dev.ts +++ b/packages/core/src/plugin/models-dev.ts @@ -57,10 +57,10 @@ export const ModelsDevPlugin = PluginV2.define({ const modelsDev = yield* ModelsDev.Service const events = yield* EventV2.Service const scope = yield* Scope.Scope - const load = yield* catalog.loader() + const transform = yield* catalog.transform() const refresh = Effect.fn("ModelsDevPlugin.refresh")(function* () { const data = yield* modelsDev.get() - yield* load((catalog) => { + yield* transform((catalog) => { for (const item of Object.values(data)) { const providerID = ProviderV2.ID.make(item.id) catalog.provider.update(providerID, (provider) => { @@ -114,7 +114,7 @@ export const ModelsDevPlugin = PluginV2.define({ yield* refresh() yield* events.subscribe(ModelsDev.Event.Refreshed).pipe( Stream.runForEach(() => refresh()), - Effect.forkIn(scope, { startImmediately: true }), + Effect.forkScoped({ startImmediately: true }), ) - }).pipe(Effect.provide(ModelsDev.defaultLayer)), + }), }) diff --git a/packages/core/src/plugin/provider.ts b/packages/core/src/plugin/provider.ts index 1880787495fd..eb84a73aca69 100644 --- a/packages/core/src/plugin/provider.ts +++ b/packages/core/src/plugin/provider.ts @@ -1 +1,67 @@ -export { ProviderPlugins } from "./provider/index" +import { AlibabaPlugin } from "./provider/alibaba" +import { AmazonBedrockPlugin } from "./provider/amazon-bedrock" +import { AnthropicPlugin } from "./provider/anthropic" +import { AzureCognitiveServicesPlugin, AzurePlugin } from "./provider/azure" +import { CerebrasPlugin } from "./provider/cerebras" +import { CloudflareAIGatewayPlugin } from "./provider/cloudflare-ai-gateway" +import { CloudflareWorkersAIPlugin } from "./provider/cloudflare-workers-ai" +import { CoherePlugin } from "./provider/cohere" +import { DeepInfraPlugin } from "./provider/deepinfra" +import { DynamicProviderPlugin } from "./provider/dynamic" +import { GatewayPlugin } from "./provider/gateway" +import { GithubCopilotPlugin } from "./provider/github-copilot" +import { GitLabPlugin } from "./provider/gitlab" +import { GooglePlugin } from "./provider/google" +import { GoogleVertexAnthropicPlugin, GoogleVertexPlugin } from "./provider/google-vertex" +import { GroqPlugin } from "./provider/groq" +import { KiloPlugin } from "./provider/kilo" +import { LLMGatewayPlugin } from "./provider/llmgateway" +import { MistralPlugin } from "./provider/mistral" +import { NvidiaPlugin } from "./provider/nvidia" +import { OpenAIPlugin } from "./provider/openai" +import { OpenAICompatiblePlugin } from "./provider/openai-compatible" +import { OpencodePlugin } from "./provider/opencode" +import { OpenRouterPlugin } from "./provider/openrouter" +import { PerplexityPlugin } from "./provider/perplexity" +import { SapAICorePlugin } from "./provider/sap-ai-core" +import { TogetherAIPlugin } from "./provider/togetherai" +import { VercelPlugin } from "./provider/vercel" +import { VenicePlugin } from "./provider/venice" +import { XAIPlugin } from "./provider/xai" +import { ZenmuxPlugin } from "./provider/zenmux" + +export const ProviderPlugins = [ + AlibabaPlugin, + AmazonBedrockPlugin, + AnthropicPlugin, + AzureCognitiveServicesPlugin, + AzurePlugin, + CerebrasPlugin, + CloudflareAIGatewayPlugin, + CloudflareWorkersAIPlugin, + CoherePlugin, + DeepInfraPlugin, + GatewayPlugin, + GithubCopilotPlugin, + GitLabPlugin, + GooglePlugin, + GoogleVertexAnthropicPlugin, + GoogleVertexPlugin, + GroqPlugin, + KiloPlugin, + LLMGatewayPlugin, + MistralPlugin, + NvidiaPlugin, + OpencodePlugin, + OpenAICompatiblePlugin, + OpenAIPlugin, + OpenRouterPlugin, + PerplexityPlugin, + SapAICorePlugin, + TogetherAIPlugin, + VercelPlugin, + VenicePlugin, + XAIPlugin, + ZenmuxPlugin, + DynamicProviderPlugin, +] diff --git a/packages/core/src/plugin/provider/amazon-bedrock.ts b/packages/core/src/plugin/provider/amazon-bedrock.ts index 44a5d44e2b24..e7452ac2e976 100644 --- a/packages/core/src/plugin/provider/amazon-bedrock.ts +++ b/packages/core/src/plugin/provider/amazon-bedrock.ts @@ -51,7 +51,7 @@ export const AmazonBedrockPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/amazon-bedrock") continue evt.provider.update(item.provider.id, (provider) => { diff --git a/packages/core/src/plugin/provider/anthropic.ts b/packages/core/src/plugin/provider/anthropic.ts index 99fbf56ab37c..026da3634924 100644 --- a/packages/core/src/plugin/provider/anthropic.ts +++ b/packages/core/src/plugin/provider/anthropic.ts @@ -6,7 +6,7 @@ export const AnthropicPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/anthropic") continue evt.provider.update(item.provider.id, (provider) => { diff --git a/packages/core/src/plugin/provider/azure.ts b/packages/core/src/plugin/provider/azure.ts index ea5c34d7c0ec..bea98cf21190 100644 --- a/packages/core/src/plugin/provider/azure.ts +++ b/packages/core/src/plugin/provider/azure.ts @@ -15,7 +15,7 @@ export const AzurePlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/azure") continue const configured = item.provider.options.aisdk.provider.resourceName @@ -58,7 +58,7 @@ export const AzureCognitiveServicesPlugin = PluginV2.define({ "catalog.transform": Effect.fn(function* (evt) { const resourceName = process.env.AZURE_COGNITIVE_SERVICES_RESOURCE_NAME if (!resourceName) return - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/openai-compatible") continue if (!item.provider.id.includes("azure-cognitive-services")) continue diff --git a/packages/core/src/plugin/provider/cerebras.ts b/packages/core/src/plugin/provider/cerebras.ts index 12da38592083..b18884cb6ed4 100644 --- a/packages/core/src/plugin/provider/cerebras.ts +++ b/packages/core/src/plugin/provider/cerebras.ts @@ -6,7 +6,7 @@ export const CerebrasPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (ctx) { - for (const item of ctx.data) { + for (const item of ctx.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/cerebras") continue ctx.provider.update(item.provider.id, (provider) => { diff --git a/packages/core/src/plugin/provider/cloudflare-workers-ai.ts b/packages/core/src/plugin/provider/cloudflare-workers-ai.ts index d10f8e79e407..32cfb059f437 100644 --- a/packages/core/src/plugin/provider/cloudflare-workers-ai.ts +++ b/packages/core/src/plugin/provider/cloudflare-workers-ai.ts @@ -11,7 +11,7 @@ export const CloudflareWorkersAIPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - const item = evt.data.find((record) => record.provider.id === providerID) + const item = evt.provider.get(providerID) if (!item) return evt.provider.update(item.provider.id, (provider) => { if (provider.endpoint.type !== "aisdk") return diff --git a/packages/core/src/plugin/provider/github-copilot.ts b/packages/core/src/plugin/provider/github-copilot.ts index dc984cdef946..20b1ad6d6c3b 100644 --- a/packages/core/src/plugin/provider/github-copilot.ts +++ b/packages/core/src/plugin/provider/github-copilot.ts @@ -31,7 +31,7 @@ export const GithubCopilotPlugin = PluginV2.define({ : evt.sdk.chat(evt.model.apiID) }), "catalog.transform": Effect.fn(function* (evt) { - const item = evt.data.find((record) => record.provider.id === ProviderV2.ID.githubCopilot) + 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, diff --git a/packages/core/src/plugin/provider/google-vertex.ts b/packages/core/src/plugin/provider/google-vertex.ts index 3da7caf4e744..ae1692b933ce 100644 --- a/packages/core/src/plugin/provider/google-vertex.ts +++ b/packages/core/src/plugin/provider/google-vertex.ts @@ -43,9 +43,9 @@ function authFetch(fetchWithRuntimeOptions?: unknown) { // do not, so inject a Google access token into their fetch path. return async (input: Parameters[0], init?: RequestInit) => { const { GoogleAuth } = await import("google-auth-library") - const auth = new GoogleAuth() - const client = await auth.getApplicationDefault() - const token = await client.credential.getAccessToken() + const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] }) + const client = await auth.getClient() + const token = await client.getAccessToken() const headers = new Headers(init?.headers) headers.set("Authorization", `Bearer ${token.token}`) return typeof fetchWithRuntimeOptions === "function" @@ -59,7 +59,7 @@ export const GoogleVertexPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if ( item.provider.endpoint.package !== "@ai-sdk/google-vertex" && @@ -110,7 +110,7 @@ export const GoogleVertexAnthropicPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/google-vertex/anthropic") continue const project = diff --git a/packages/core/src/plugin/provider/index.ts b/packages/core/src/plugin/provider/index.ts deleted file mode 100644 index fd02d322a1f9..000000000000 --- a/packages/core/src/plugin/provider/index.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { AlibabaPlugin } from "./alibaba" -import { AmazonBedrockPlugin } from "./amazon-bedrock" -import { AnthropicPlugin } from "./anthropic" -import { AzureCognitiveServicesPlugin, AzurePlugin } from "./azure" -import { CerebrasPlugin } from "./cerebras" -import { CloudflareAIGatewayPlugin } from "./cloudflare-ai-gateway" -import { CloudflareWorkersAIPlugin } from "./cloudflare-workers-ai" -import { CoherePlugin } from "./cohere" -import { DeepInfraPlugin } from "./deepinfra" -import { DynamicProviderPlugin } from "./dynamic" -import { GatewayPlugin } from "./gateway" -import { GithubCopilotPlugin } from "./github-copilot" -import { GitLabPlugin } from "./gitlab" -import { GooglePlugin } from "./google" -import { GoogleVertexAnthropicPlugin, GoogleVertexPlugin } from "./google-vertex" -import { GroqPlugin } from "./groq" -import { KiloPlugin } from "./kilo" -import { LLMGatewayPlugin } from "./llmgateway" -import { MistralPlugin } from "./mistral" -import { NvidiaPlugin } from "./nvidia" -import { OpenAIPlugin } from "./openai" -import { OpenAICompatiblePlugin } from "./openai-compatible" -import { OpencodePlugin } from "./opencode" -import { OpenRouterPlugin } from "./openrouter" -import { PerplexityPlugin } from "./perplexity" -import { SapAICorePlugin } from "./sap-ai-core" -import { TogetherAIPlugin } from "./togetherai" -import { VercelPlugin } from "./vercel" -import { VenicePlugin } from "./venice" -import { XAIPlugin } from "./xai" -import { ZenmuxPlugin } from "./zenmux" - -export const ProviderPlugins = [ - AlibabaPlugin, - AmazonBedrockPlugin, - AnthropicPlugin, - AzureCognitiveServicesPlugin, - AzurePlugin, - CerebrasPlugin, - CloudflareAIGatewayPlugin, - CloudflareWorkersAIPlugin, - CoherePlugin, - DeepInfraPlugin, - GatewayPlugin, - GithubCopilotPlugin, - GitLabPlugin, - GooglePlugin, - GoogleVertexAnthropicPlugin, - GoogleVertexPlugin, - GroqPlugin, - KiloPlugin, - LLMGatewayPlugin, - MistralPlugin, - NvidiaPlugin, - OpencodePlugin, - OpenAICompatiblePlugin, - OpenAIPlugin, - OpenRouterPlugin, - PerplexityPlugin, - SapAICorePlugin, - TogetherAIPlugin, - VercelPlugin, - VenicePlugin, - XAIPlugin, - ZenmuxPlugin, - DynamicProviderPlugin, -] diff --git a/packages/core/src/plugin/provider/kilo.ts b/packages/core/src/plugin/provider/kilo.ts index 17436d9f96f7..098e5576c467 100644 --- a/packages/core/src/plugin/provider/kilo.ts +++ b/packages/core/src/plugin/provider/kilo.ts @@ -6,7 +6,7 @@ export const KiloPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/openai-compatible") continue if (item.provider.endpoint.url !== "https://api.kilo.ai/api/gateway") continue diff --git a/packages/core/src/plugin/provider/llmgateway.ts b/packages/core/src/plugin/provider/llmgateway.ts index de1872935caf..8a971f0a0d9b 100644 --- a/packages/core/src/plugin/provider/llmgateway.ts +++ b/packages/core/src/plugin/provider/llmgateway.ts @@ -6,7 +6,7 @@ export const LLMGatewayPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.enabled === false) continue if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/openai-compatible") continue diff --git a/packages/core/src/plugin/provider/nvidia.ts b/packages/core/src/plugin/provider/nvidia.ts index 0c1301c84214..f9c2a0420b36 100644 --- a/packages/core/src/plugin/provider/nvidia.ts +++ b/packages/core/src/plugin/provider/nvidia.ts @@ -6,7 +6,7 @@ export const NvidiaPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/openai-compatible") continue if (item.provider.endpoint.url !== "https://integrate.api.nvidia.com/v1") continue diff --git a/packages/core/src/plugin/provider/openai.ts b/packages/core/src/plugin/provider/openai.ts index d76d7417f157..2d33fbcbbe1f 100644 --- a/packages/core/src/plugin/provider/openai.ts +++ b/packages/core/src/plugin/provider/openai.ts @@ -17,7 +17,7 @@ export const OpenAIPlugin = PluginV2.define({ evt.language = evt.sdk.responses(evt.model.apiID) }), "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/openai") continue if (!item.models.has(ModelV2.ID.make("gpt-5-chat-latest"))) continue diff --git a/packages/core/src/plugin/provider/opencode.ts b/packages/core/src/plugin/provider/opencode.ts index 411cbe091ef8..64d20f8bd4e0 100644 --- a/packages/core/src/plugin/provider/opencode.ts +++ b/packages/core/src/plugin/provider/opencode.ts @@ -8,7 +8,7 @@ export const OpencodePlugin = PluginV2.define({ let hasKey = false return { "catalog.transform": Effect.fn(function* (evt) { - const item = evt.data.find((record) => record.provider.id === ProviderV2.ID.opencode) + const item = evt.provider.get(ProviderV2.ID.opencode) if (!item) return hasKey = Boolean( process.env.OPENCODE_API_KEY || diff --git a/packages/core/src/plugin/provider/openrouter.ts b/packages/core/src/plugin/provider/openrouter.ts index 317f48158a5f..dd3e16070b04 100644 --- a/packages/core/src/plugin/provider/openrouter.ts +++ b/packages/core/src/plugin/provider/openrouter.ts @@ -7,7 +7,7 @@ export const OpenRouterPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@openrouter/ai-sdk-provider") continue evt.provider.update(item.provider.id, (provider) => { diff --git a/packages/core/src/plugin/provider/vercel.ts b/packages/core/src/plugin/provider/vercel.ts index fa368d10d746..1da00989b372 100644 --- a/packages/core/src/plugin/provider/vercel.ts +++ b/packages/core/src/plugin/provider/vercel.ts @@ -6,7 +6,7 @@ export const VercelPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/vercel") continue evt.provider.update(item.provider.id, (provider) => { diff --git a/packages/core/src/plugin/provider/zenmux.ts b/packages/core/src/plugin/provider/zenmux.ts index 3b0fcff1659a..01c3bd8adb47 100644 --- a/packages/core/src/plugin/provider/zenmux.ts +++ b/packages/core/src/plugin/provider/zenmux.ts @@ -6,7 +6,7 @@ export const ZenmuxPlugin = PluginV2.define({ effect: Effect.gen(function* () { return { "catalog.transform": Effect.fn(function* (evt) { - for (const item of evt.data) { + for (const item of evt.provider.list()) { if (item.provider.endpoint.type !== "aisdk") continue if (item.provider.endpoint.package !== "@ai-sdk/openai-compatible") continue if (item.provider.endpoint.url !== "https://zenmux.ai/api/v1") continue diff --git a/packages/core/src/policy.ts b/packages/core/src/policy.ts new file mode 100644 index 000000000000..9b7438f4ffda --- /dev/null +++ b/packages/core/src/policy.ts @@ -0,0 +1,46 @@ +export * as Policy from "./policy" + +import { Context, Effect as EffectRuntime, Layer, Schema } from "effect" +import { Wildcard } from "./util/wildcard" +import { Location } from "./location" + +export const Effect = Schema.Literals(["allow", "deny"]).annotate({ identifier: "Policy.Effect" }) +export type Effect = typeof Effect.Type + +export class Info extends Schema.Class("Policy.Info")({ + action: Schema.String, + effect: Effect, + resource: Schema.String, +}) {} + +export interface Interface { + readonly load: (statements: Info[]) => EffectRuntime.Effect + readonly evaluate: (action: string, resource: string, fallback: Effect) => EffectRuntime.Effect + readonly hasStatements: () => boolean +} + +export class Service extends Context.Service()("@opencode/v2/Policy") {} + +export const layer = Layer.effect( + Service, + EffectRuntime.gen(function* () { + let statements: Info[] = [] + yield* Location.Service + + return Service.of({ + load: EffectRuntime.fn("Policy.load")(function* (input) { + statements = input + }), + hasStatements: () => statements.length > 0, + evaluate: EffectRuntime.fn("Policy.evaluate")(function* (action, resource, fallback) { + return ( + statements.findLast( + (statement) => Wildcard.match(action, statement.action) && Wildcard.match(resource, statement.resource), + )?.effect ?? fallback + ) + }), + }) + }), +) + +export const locationLayer = layer diff --git a/packages/core/src/project.ts b/packages/core/src/project.ts index 9c265d75be8e..f71b828246b0 100644 --- a/packages/core/src/project.ts +++ b/packages/core/src/project.ts @@ -1,3 +1,4 @@ +export * as ProjectV2 from "./project" export * as Project from "./project" import { Context, Effect, Layer, Schema } from "effect" @@ -25,7 +26,6 @@ export type Vcs = typeof Vcs.Type export class Info extends Schema.Class("Project.Info")({ id: ID, - vcs: Schema.optional(Vcs), }) {} export interface Interface { @@ -105,7 +105,7 @@ export const layer = Layer.effect( const resolve = Effect.fn("Project.resolve")(function* (input: AbsolutePath) { const repo = yield* git.find(input) - if (!repo) return { id: ID.global, directory: input, vcs: undefined } + if (!repo) return { id: ID.global, directory: AbsolutePath.make(path.parse(input).root), vcs: undefined } const previous = yield* cached(repo.store) const id = (yield* remote(repo)) ?? previous ?? (yield* root(repo)) diff --git a/packages/opencode/src/project/project.sql.ts b/packages/core/src/project/sql.ts similarity index 75% rename from packages/opencode/src/project/project.sql.ts rename to packages/core/src/project/sql.ts index 2d486114a368..1588446cfb14 100644 --- a/packages/opencode/src/project/project.sql.ts +++ b/packages/core/src/project/sql.ts @@ -1,9 +1,9 @@ import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core" -import { Timestamps } from "../storage/schema.sql" -import type { ProjectID } from "./schema" +import { Timestamps } from "../database/schema.sql" +import { ProjectV2 } from "../project" export const ProjectTable = sqliteTable("project", { - id: text().$type().primaryKey(), + id: text().$type().primaryKey(), worktree: text().notNull(), vcs: text(), name: text(), diff --git a/packages/core/src/provider.ts b/packages/core/src/provider.ts index 7ba2172ada34..31127f2f3c3a 100644 --- a/packages/core/src/provider.ts +++ b/packages/core/src/provider.ts @@ -22,6 +22,9 @@ export const ID = Schema.String.pipe( ) export type ID = typeof ID.Type +export const ModelID = Schema.String.pipe(Schema.brand("ModelID")) +export type ModelID = typeof ModelID.Type + const OpenAIResponses = Schema.Struct({ type: Schema.Literal("openai/responses"), url: Schema.String, @@ -98,8 +101,8 @@ export class Info extends Schema.Class("ProviderV2.Info")({ endpoint: Endpoint, options: Options, }) { - static empty(providerID: ID) { - return new Info({ + static empty(providerID: ID): Info { + return { id: providerID, name: providerID, enabled: false, @@ -115,6 +118,6 @@ export class Info extends Schema.Class("ProviderV2.Info")({ request: {}, }, }, - }) + } } } diff --git a/packages/core/src/schema.ts b/packages/core/src/schema.ts index 523a4eace5d7..b5cee90a57dc 100644 --- a/packages/core/src/schema.ts +++ b/packages/core/src/schema.ts @@ -1,11 +1,5 @@ import { Option, Schema, SchemaGetter } from "effect" -export const AbsolutePath = Schema.String.pipe(Schema.brand("AbsolutePath")) -export type AbsolutePath = typeof AbsolutePath.Type - -export const RelativePath = Schema.String.pipe(Schema.brand("RelativePath")) -export type RelativePath = typeof RelativePath.Type - /** * Integer greater than zero. */ @@ -16,6 +10,18 @@ export const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0)) */ export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) +/** + * Relative file path (e.g., `src/components/Button.tsx`). + */ +export const RelativePath = Schema.String.pipe(Schema.brand("RelativePath")) +export type RelativePath = Schema.Schema.Type + +/** + * Absolute file path (e.g., `/home/user/projects/myapp/src/main.ts`). + */ +export const AbsolutePath = Schema.String.pipe(Schema.brand("AbsolutePath")) +export type AbsolutePath = Schema.Schema.Type + /** * Optional public JSON field that can hold explicit `undefined` on the type * side but encodes it as an omitted key, matching legacy `JSON.stringify`. diff --git a/packages/core/src/session-message-updater.ts b/packages/core/src/session-message-updater.ts deleted file mode 100644 index bbdf59c555d5..000000000000 --- a/packages/core/src/session-message-updater.ts +++ /dev/null @@ -1,417 +0,0 @@ -import { produce, type WritableDraft } from "immer" -import { SessionEvent } from "./session-event" -import { SessionMessage } from "./session-message" - -export type MemoryState = { - messages: SessionMessage.Message[] -} - -export interface Adapter { - readonly getCurrentAssistant: () => SessionMessage.Assistant | undefined - readonly getCurrentCompaction: () => SessionMessage.Compaction | undefined - readonly getCurrentShell: (callID: string) => SessionMessage.Shell | undefined - readonly updateAssistant: (assistant: SessionMessage.Assistant) => void - readonly updateCompaction: (compaction: SessionMessage.Compaction) => void - readonly updateShell: (shell: SessionMessage.Shell) => void - readonly appendMessage: (message: SessionMessage.Message) => void - readonly finish: () => Result -} - -export function memory(state: MemoryState): Adapter { - const activeAssistantIndex = () => - state.messages.findLastIndex((message) => message.type === "assistant" && !message.time.completed) - const activeCompactionIndex = () => state.messages.findLastIndex((message) => message.type === "compaction") - const activeShellIndex = (callID: string) => - state.messages.findLastIndex((message) => message.type === "shell" && message.callID === callID) - - return { - getCurrentAssistant() { - const index = activeAssistantIndex() - if (index < 0) return - const assistant = state.messages[index] - return assistant?.type === "assistant" ? assistant : undefined - }, - getCurrentCompaction() { - const index = activeCompactionIndex() - if (index < 0) return - const compaction = state.messages[index] - return compaction?.type === "compaction" ? compaction : undefined - }, - getCurrentShell(callID) { - const index = activeShellIndex(callID) - if (index < 0) return - const shell = state.messages[index] - return shell?.type === "shell" ? shell : undefined - }, - updateAssistant(assistant) { - const index = activeAssistantIndex() - if (index < 0) return - const current = state.messages[index] - if (current?.type !== "assistant") return - state.messages[index] = assistant - }, - updateCompaction(compaction) { - const index = activeCompactionIndex() - if (index < 0) return - const current = state.messages[index] - if (current?.type !== "compaction") return - state.messages[index] = compaction - }, - updateShell(shell) { - const index = activeShellIndex(shell.callID) - if (index < 0) return - const current = state.messages[index] - if (current?.type !== "shell") return - state.messages[index] = shell - }, - appendMessage(message) { - state.messages.push(message) - }, - finish() { - return state - }, - } -} - -export function update(adapter: Adapter, event: SessionEvent.Event): Result { - const currentAssistant = adapter.getCurrentAssistant() - type DraftAssistant = WritableDraft - type DraftTool = WritableDraft - type DraftText = WritableDraft - type DraftReasoning = WritableDraft - - const latestTool = (assistant: DraftAssistant | undefined, callID?: string) => - assistant?.content.findLast( - (item): item is DraftTool => item.type === "tool" && (callID === undefined || item.id === callID), - ) - - const latestText = (assistant: DraftAssistant | undefined) => - assistant?.content.findLast((item): item is DraftText => item.type === "text") - - const latestReasoning = (assistant: DraftAssistant | undefined, reasoningID: string) => - assistant?.content.findLast((item): item is DraftReasoning => item.type === "reasoning" && item.id === reasoningID) - - SessionEvent.All.match(event, { - "session.next.agent.switched": (event) => { - adapter.appendMessage( - new SessionMessage.AgentSwitched({ - id: event.id, - type: "agent-switched", - metadata: event.metadata, - agent: event.data.agent, - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.model.switched": (event) => { - adapter.appendMessage( - new SessionMessage.ModelSwitched({ - id: event.id, - type: "model-switched", - metadata: event.metadata, - model: event.data.model, - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.prompted": (event) => { - adapter.appendMessage( - new SessionMessage.User({ - id: event.id, - type: "user", - metadata: event.metadata, - text: event.data.prompt.text, - files: event.data.prompt.files, - agents: event.data.prompt.agents, - references: event.data.prompt.references, - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.synthetic": (event) => { - adapter.appendMessage( - new SessionMessage.Synthetic({ - sessionID: event.data.sessionID, - text: event.data.text, - id: event.id, - type: "synthetic", - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.shell.started": (event) => { - adapter.appendMessage( - new SessionMessage.Shell({ - id: event.id, - type: "shell", - metadata: event.metadata, - callID: event.data.callID, - command: event.data.command, - output: "", - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.shell.ended": (event) => { - const currentShell = adapter.getCurrentShell(event.data.callID) - if (currentShell) { - adapter.updateShell( - produce(currentShell, (draft) => { - draft.output = event.data.output - draft.time.completed = event.data.timestamp - }), - ) - } - }, - "session.next.step.started": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - draft.time.completed = event.data.timestamp - }), - ) - } - adapter.appendMessage( - new SessionMessage.Assistant({ - id: event.id, - type: "assistant", - agent: event.data.agent, - model: event.data.model, - time: { created: event.data.timestamp }, - content: [], - snapshot: event.data.snapshot ? { start: event.data.snapshot } : undefined, - }), - ) - }, - "session.next.step.ended": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - draft.time.completed = event.data.timestamp - draft.finish = event.data.finish - draft.cost = event.data.cost - draft.tokens = event.data.tokens - if (event.data.snapshot) draft.snapshot = { ...draft.snapshot, end: event.data.snapshot } - }), - ) - } - }, - "session.next.step.failed": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - draft.time.completed = event.data.timestamp - draft.finish = "error" - draft.error = event.data.error - }), - ) - } - }, - "session.next.text.started": () => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - draft.content.push({ - type: "text", - text: "", - }) - }), - ) - } - }, - "session.next.text.delta": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestText(draft) - if (match) match.text += event.data.delta - }), - ) - } - }, - "session.next.text.ended": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestText(draft) - if (match) match.text = event.data.text - }), - ) - } - }, - "session.next.tool.input.started": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - draft.content.push({ - type: "tool", - id: event.data.callID, - name: event.data.name, - time: { - created: event.data.timestamp, - }, - state: { - status: "pending", - input: "", - }, - }) - }), - ) - } - }, - "session.next.tool.input.delta": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestTool(draft, event.data.callID) - // oxlint-disable-next-line no-base-to-string -- event.delta is a Schema.String (runtime string) - if (match && match.state.status === "pending") match.state.input += event.data.delta - }), - ) - } - }, - "session.next.tool.input.ended": () => {}, - "session.next.tool.called": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestTool(draft, event.data.callID) - if (match) { - match.provider = event.data.provider - match.time.ran = event.data.timestamp - match.state = { - status: "running", - input: event.data.input, - structured: {}, - content: [], - } - } - }), - ) - } - }, - "session.next.tool.progress": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestTool(draft, event.data.callID) - if (match && match.state.status === "running") { - match.state.structured = event.data.structured - match.state.content = [...event.data.content] - } - }), - ) - } - }, - "session.next.tool.success": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestTool(draft, event.data.callID) - if (match && match.state.status === "running") { - match.provider = event.data.provider - match.time.completed = event.data.timestamp - match.state = { - status: "completed", - input: match.state.input, - structured: event.data.structured, - content: [...event.data.content], - } - } - }), - ) - } - }, - "session.next.tool.failed": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestTool(draft, event.data.callID) - if (match && match.state.status === "running") { - match.provider = event.data.provider - match.time.completed = event.data.timestamp - match.state = { - status: "error", - error: event.data.error, - input: match.state.input, - structured: match.state.structured, - content: match.state.content, - } - } - }), - ) - } - }, - "session.next.reasoning.started": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - draft.content.push({ - type: "reasoning", - id: event.data.reasoningID, - text: "", - }) - }), - ) - } - }, - "session.next.reasoning.delta": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestReasoning(draft, event.data.reasoningID) - if (match) match.text += event.data.delta - }), - ) - } - }, - "session.next.reasoning.ended": (event) => { - if (currentAssistant) { - adapter.updateAssistant( - produce(currentAssistant, (draft) => { - const match = latestReasoning(draft, event.data.reasoningID) - if (match) match.text = event.data.text - }), - ) - } - }, - "session.next.retried": () => {}, - "session.next.compaction.started": (event) => { - adapter.appendMessage( - new SessionMessage.Compaction({ - id: event.id, - type: "compaction", - metadata: event.metadata, - reason: event.data.reason, - summary: "", - time: { created: event.data.timestamp }, - }), - ) - }, - "session.next.compaction.delta": (event) => { - const currentCompaction = adapter.getCurrentCompaction() - if (currentCompaction) { - adapter.updateCompaction( - produce(currentCompaction, (draft) => { - draft.summary += event.data.text - }), - ) - } - }, - "session.next.compaction.ended": (event) => { - const currentCompaction = adapter.getCurrentCompaction() - if (currentCompaction) { - adapter.updateCompaction( - produce(currentCompaction, (draft) => { - draft.summary = event.data.text - draft.include = event.data.include - }), - ) - } - }, - }) - - return adapter.finish() -} - -export * as SessionMessageUpdater from "./session-message-updater" diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 756531e32809..3dc26838531f 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -1,13 +1,337 @@ -export * as Session from "./session" +export * as SessionV2 from "./session" +export * from "./session/schema" -import { Schema } from "effect" -import { withStatics } from "./schema" -import { Identifier } from "./util/identifier" +import { DateTime, Effect, Layer, Schema, Context } from "effect" +import { and, asc, desc, eq, gt, gte, like, lt, or, type SQL } from "drizzle-orm" +import { ProjectV2 } from "./project" +import { WorkspaceV2 } from "./workspace" +import { ModelV2 } from "./model" +import { Location } from "./location" +import { SessionMessage } from "./session/message" +import type { Prompt } from "./session/prompt" +import { EventV2 } from "./event" +import { ProviderV2 } from "./provider" +import { Database } from "./database/database" +import { SessionProjector } from "./session/projector" +import { SessionMessageTable, SessionTable } from "./session/sql" +import { SessionSchema } from "./session/schema" +import { AbsolutePath, RelativePath } from "./schema" -export const ID = Schema.String.check(Schema.isStartsWith("ses")).pipe( - Schema.brand("SessionID"), - withStatics((schema) => ({ - descending: (id?: string) => schema.make(id ?? "ses_" + Identifier.descending()), - })), +// get project -> project.locations +// +// get all sessions +// + +// - by project +// - by subpath +// - by workspace (home is special) + +export const ListCursor = Schema.Struct({ + id: SessionSchema.ID, + time: Schema.Finite, + direction: Schema.Literals(["previous", "next"]), +}) +export type ListCursor = typeof ListCursor.Type + +const ListInputBase = { + workspaceID: WorkspaceV2.ID.pipe(Schema.optional), + search: Schema.String.pipe(Schema.optional), + limit: Schema.Int.pipe(Schema.optional), + order: Schema.Literals(["asc", "desc"]).pipe(Schema.optional), + cursor: ListCursor.pipe(Schema.optional), +} + +export const ListInput = Schema.Union([ + Schema.Struct({ + ...ListInputBase, + }), + Schema.Struct({ + ...ListInputBase, + directory: AbsolutePath, + }), + Schema.Struct({ + ...ListInputBase, + project: ProjectV2.ID, + subpath: RelativePath.pipe(Schema.optional), + }), +]) +export type ListInput = typeof ListInput.Type + +type CreateInput = { + id?: SessionSchema.ID + agent?: string + model?: ModelV2.Ref + location: Location.Ref +} + +type MoveInput = { + sessionID: SessionSchema.ID + location: Location.Ref +} + +type CompactInput = { + sessionID: SessionSchema.ID + prompt?: Prompt +} + +export class NotFoundError extends Schema.TaggedErrorClass()("Session.NotFoundError", { + sessionID: SessionSchema.ID, +}) {} + +export class OperationUnavailableError extends Schema.TaggedErrorClass()( + "Session.OperationUnavailableError", + { + operation: Schema.Literals(["prompt", "compact", "wait"]), + }, +) {} + +export class MessageDecodeError extends Schema.TaggedErrorClass()("Session.MessageDecodeError", { + sessionID: SessionSchema.ID, + messageID: SessionMessage.ID, +}) {} + +export type Error = NotFoundError | MessageDecodeError | OperationUnavailableError + +export interface Interface { + readonly list: (input?: ListInput) => Effect.Effect + readonly create: (input?: CreateInput) => Effect.Effect + readonly move: (input: MoveInput) => Effect.Effect + readonly get: (sessionID: SessionSchema.ID) => Effect.Effect + readonly messages: (input: { + sessionID: SessionSchema.ID + limit?: number + order?: "asc" | "desc" + cursor?: { + id: SessionMessage.ID + time: number + direction: "previous" | "next" + } + }) => Effect.Effect + readonly context: ( + sessionID: SessionSchema.ID, + ) => Effect.Effect + readonly switchAgent: (input: { sessionID: SessionSchema.ID; agent: string }) => Effect.Effect + readonly switchModel: (input: { sessionID: SessionSchema.ID; model: ModelV2.Ref }) => Effect.Effect + readonly prompt: (input: { + id?: EventV2.ID + sessionID: SessionSchema.ID + prompt: Prompt + delivery?: SessionSchema.Delivery + resume?: boolean + }) => Effect.Effect + readonly shell: (input: { + id?: EventV2.ID + sessionID: SessionSchema.ID + command: string + delivery?: SessionSchema.Delivery + resume?: boolean + }) => Effect.Effect + readonly skill: (input: { + id?: EventV2.ID + sessionID: SessionSchema.ID + skill: string + delivery?: SessionSchema.Delivery + resume?: boolean + }) => Effect.Effect + readonly compact: (input: CompactInput) => Effect.Effect + readonly wait: (id: SessionSchema.ID) => Effect.Effect + readonly resume: (sessionID: SessionSchema.ID) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/v2/Session") {} + +function fromRow(row: typeof SessionTable.$inferSelect): SessionSchema.Info { + return new SessionSchema.Info({ + id: SessionSchema.ID.make(row.id), + projectID: ProjectV2.ID.make(row.project_id), + workspaceID: row.workspace_id ? WorkspaceV2.ID.make(row.workspace_id) : undefined, + title: row.title, + parentID: row.parent_id ? SessionSchema.ID.make(row.parent_id) : undefined, + path: row.path ?? "", + agent: row.agent ?? undefined, + model: row.model + ? { + id: ModelV2.ID.make(row.model.id), + providerID: ProviderV2.ID.make(row.model.providerID), + variant: ModelV2.VariantID.make(row.model.variant ?? "default"), + } + : undefined, + cost: row.cost, + tokens: { + input: row.tokens_input, + output: row.tokens_output, + reasoning: row.tokens_reasoning, + cache: { + read: row.tokens_cache_read, + write: row.tokens_cache_write, + }, + }, + time: { + created: DateTime.makeUnsafe(row.time_created), + updated: DateTime.makeUnsafe(row.time_updated), + archived: row.time_archived ? DateTime.makeUnsafe(row.time_archived) : undefined, + }, + }) +} + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const db = (yield* Database.Service).db + const decodeMessage = Schema.decodeUnknownEffect(SessionMessage.Message) + + const decode = (row: typeof SessionMessageTable.$inferSelect) => + decodeMessage({ ...row.data, id: row.id, type: row.type }).pipe( + Effect.mapError( + () => + new MessageDecodeError({ + sessionID: SessionSchema.ID.make(row.session_id), + messageID: SessionMessage.ID.make(row.id), + }), + ), + ) + + const result = Service.of({ + create: Effect.fn("V2Session.create")(function* () { + return {} as SessionSchema.Info + }), + get: Effect.fn("V2Session.get")(function* (sessionID) { + const row = yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie) + if (!row) return yield* new NotFoundError({ sessionID }) + return fromRow(row) + }), + list: Effect.fn("V2Session.list")(function* (input = {}) { + const direction = input.cursor?.direction ?? "next" + const requestedOrder = input.order ?? "desc" + const order = direction === "previous" ? (requestedOrder === "asc" ? "desc" : "asc") : requestedOrder + const sortColumn = SessionTable.time_updated + const conditions: SQL[] = [] + if ("directory" in input) conditions.push(eq(SessionTable.directory, input.directory)) + if (input.workspaceID) conditions.push(eq(SessionTable.workspace_id, input.workspaceID)) + if ("project" in input) conditions.push(eq(SessionTable.project_id, input.project)) + if (input.search) conditions.push(like(SessionTable.title, `%${input.search}%`)) + if (input.cursor) { + conditions.push( + order === "asc" + ? or( + gt(sortColumn, input.cursor.time), + and(eq(sortColumn, input.cursor.time), gt(SessionTable.id, input.cursor.id)), + )! + : or( + lt(sortColumn, input.cursor.time), + and(eq(sortColumn, input.cursor.time), lt(SessionTable.id, input.cursor.id)), + )!, + ) + } + const query = db + .select() + .from(SessionTable) + .where(conditions.length > 0 ? and(...conditions) : undefined) + .orderBy( + order === "asc" ? asc(sortColumn) : desc(sortColumn), + order === "asc" ? asc(SessionTable.id) : desc(SessionTable.id), + ) + const rows = yield* (input.limit === undefined ? query.all() : query.limit(input.limit).all()).pipe( + Effect.orDie, + ) + return (direction === "previous" ? rows.toReversed() : rows).map((row) => fromRow(row)) + }), + messages: Effect.fn("V2Session.messages")(function* (input) { + yield* result.get(input.sessionID) + const direction = input.cursor?.direction ?? "next" + const requestedOrder = input.order ?? "desc" + const order = direction === "previous" ? (requestedOrder === "asc" ? "desc" : "asc") : requestedOrder + const boundary = input.cursor + ? order === "asc" + ? or( + gt(SessionMessageTable.time_created, input.cursor.time), + and( + eq(SessionMessageTable.time_created, input.cursor.time), + gt(SessionMessageTable.id, input.cursor.id), + ), + ) + : or( + lt(SessionMessageTable.time_created, input.cursor.time), + and( + eq(SessionMessageTable.time_created, input.cursor.time), + lt(SessionMessageTable.id, input.cursor.id), + ), + ) + : undefined + const where = boundary + ? and(eq(SessionMessageTable.session_id, input.sessionID), boundary) + : eq(SessionMessageTable.session_id, input.sessionID) + const query = db + .select() + .from(SessionMessageTable) + .where(where) + .orderBy( + order === "asc" ? asc(SessionMessageTable.time_created) : desc(SessionMessageTable.time_created), + order === "asc" ? asc(SessionMessageTable.id) : desc(SessionMessageTable.id), + ) + const rows = yield* (input.limit === undefined ? query.all() : query.limit(input.limit).all()).pipe( + Effect.orDie, + ) + return yield* Effect.forEach(direction === "previous" ? rows.toReversed() : rows, decode) + }), + context: Effect.fn("V2Session.context")(function* (sessionID) { + yield* result.get(sessionID) + const compaction = yield* db + .select() + .from(SessionMessageTable) + .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "compaction"))) + .orderBy(desc(SessionMessageTable.time_created), desc(SessionMessageTable.id)) + .limit(1) + .get() + .pipe(Effect.orDie) + const rows = yield* db + .select() + .from(SessionMessageTable) + .where( + and( + eq(SessionMessageTable.session_id, sessionID), + compaction + ? or( + gt(SessionMessageTable.time_created, compaction.time_created), + and( + eq(SessionMessageTable.time_created, compaction.time_created), + gte(SessionMessageTable.id, compaction.id), + ), + ) + : undefined, + ), + ) + .orderBy(asc(SessionMessageTable.time_created), asc(SessionMessageTable.id)) + .all() + .pipe(Effect.orDie) + return yield* Effect.forEach(rows, decode) + }), + prompt: Effect.fn("V2Session.prompt")(function* (input) { + yield* result.get(input.sessionID) + return yield* Effect.fail(new OperationUnavailableError({ operation: "prompt" })) + }), + shell: Effect.fn("V2Session.shell")(function* () {}), + skill: Effect.fn("V2Session.skill")(function* () {}), + switchAgent: Effect.fn("V2Session.switchAgent")(function* () {}), + switchModel: Effect.fn("V2Session.switchModel")(function* () {}), + compact: Effect.fn("V2Session.compact")(function* (input) { + yield* result.get(input.sessionID) + return yield* new OperationUnavailableError({ operation: "compact" }) + }), + wait: Effect.fn("V2Session.wait")(function* (sessionID) { + yield* result.get(sessionID) + return yield* new OperationUnavailableError({ operation: "wait" }) + }), + resume: Effect.fn("V2Session.resume")(function* () {}), + move: Effect.fn("V2Session.move")(function* () {}), + }) + + return result + }), +) + +export const defaultLayer = layer.pipe( + Layer.provide(SessionProjector.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.orDie, ) -export type ID = typeof ID.Type diff --git a/packages/core/src/session-event.ts b/packages/core/src/session/event.ts similarity index 95% rename from packages/core/src/session-event.ts rename to packages/core/src/session/event.ts index a98d9cc05144..c8b4aac503bd 100644 --- a/packages/core/src/session-event.ts +++ b/packages/core/src/session/event.ts @@ -1,11 +1,11 @@ import { Schema } from "effect" -import { EventV2 } from "./event" -import { ModelV2 } from "./model" -import { NonNegativeInt } from "./schema" -import { Session } from "./session" -import { FileAttachment, Prompt } from "./session-prompt" -import { ToolOutput } from "./tool-output" -import { V2Schema } from "./v2-schema" +import { EventV2 } from "../event" +import { ModelV2 } from "../model" +import { NonNegativeInt } from "../schema" +import { ToolOutput } from "../tool-output" +import { V2Schema } from "../v2-schema" +import { FileAttachment, Prompt } from "./prompt" +import { SessionSchema } from "./schema" export { FileAttachment } @@ -20,12 +20,14 @@ export type Source = typeof Source.Type const Base = { timestamp: V2Schema.DateTimeUtcFromMillis, - sessionID: Session.ID, + sessionID: SessionSchema.ID, } const options = { - aggregate: "sessionID", - version: 1, + sync: { + aggregate: "sessionID", + version: 1, + }, } as const export const UnknownError = Schema.Struct({ @@ -395,8 +397,7 @@ export const All = Schema.Union( mode: "oneOf", }, ).pipe(Schema.toTaggedUnion("type")) - export type Event = typeof All.Type export type Type = Event["type"] -export * as SessionEvent from "./session-event" +export * as SessionEvent from "./event" diff --git a/packages/core/src/session/legacy.ts b/packages/core/src/session/legacy.ts new file mode 100644 index 000000000000..a1896a9dedba --- /dev/null +++ b/packages/core/src/session/legacy.ts @@ -0,0 +1,625 @@ +export * as SessionLegacy from "./legacy" + +import { Effect, Schema, Types } from "effect" +import { EventV2 } from "../event" +import { PermissionV2 } from "../permission" +import { ProjectV2 } from "../project" +import { ProviderV2 } from "../provider" +import { optionalOmitUndefined, withStatics } from "../schema" +import { Identifier } from "../util/identifier" +import { NonNegativeInt } from "../schema" +import { NamedError } from "../util/error" +import { SessionSchema } from "./schema" +import { WorkspaceV2 } from "../workspace" + +export const MessageID = Schema.String.check(Schema.isStartsWith("msg")).pipe( + Schema.brand("MessageID"), + withStatics((schema) => ({ ascending: (id?: string) => schema.make(id ?? "msg_" + Identifier.ascending()) })), +) +export type MessageID = typeof MessageID.Type + +export const PartID = Schema.String.check(Schema.isStartsWith("prt")).pipe( + Schema.brand("PartID"), + withStatics((schema) => ({ ascending: (id?: string) => schema.make(id ?? "prt_" + Identifier.ascending()) })), +) +export type PartID = typeof PartID.Type + +export const OutputLengthError = NamedError.create("MessageOutputLengthError", {}) + +export const AuthError = NamedError.create("ProviderAuthError", { + providerID: Schema.String, + message: Schema.String, +}) + +export const AbortedError = NamedError.create("MessageAbortedError", { message: Schema.String }) +export const StructuredOutputError = NamedError.create("StructuredOutputError", { + message: Schema.String, + retries: NonNegativeInt, +}) +export const APIError = NamedError.create("APIError", { + message: Schema.String, + statusCode: Schema.optional(NonNegativeInt), + isRetryable: Schema.Boolean, + responseHeaders: Schema.optional(Schema.Record(Schema.String, Schema.String)), + responseBody: Schema.optional(Schema.String), + metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)), +}) +export type APIError = Schema.Schema.Type +export const ContextOverflowError = NamedError.create("ContextOverflowError", { + message: Schema.String, + responseBody: Schema.optional(Schema.String), +}) + +export class OutputFormatText extends Schema.Class("OutputFormatText")({ + type: Schema.Literal("text"), +}) {} + +export class OutputFormatJsonSchema extends Schema.Class("OutputFormatJsonSchema")({ + type: Schema.Literal("json_schema"), + schema: Schema.Record(Schema.String, Schema.Any).annotate({ identifier: "JSONSchema" }), + retryCount: NonNegativeInt.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed(2))), +}) {} + +export const Format = Schema.Union([OutputFormatText, OutputFormatJsonSchema]).annotate({ + discriminator: "type", + identifier: "OutputFormat", +}) +export type OutputFormat = Schema.Schema.Type + +const partBase = { + id: PartID, + sessionID: SessionSchema.ID, + messageID: MessageID, +} + +export const SnapshotPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("snapshot"), + snapshot: Schema.String, +}).annotate({ identifier: "SnapshotPart" }) +export type SnapshotPart = Types.DeepMutable> + +export const PatchPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("patch"), + hash: Schema.String, + files: Schema.Array(Schema.String), +}).annotate({ identifier: "PatchPart" }) +export type PatchPart = Types.DeepMutable> + +export const TextPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("text"), + text: Schema.String, + synthetic: Schema.optional(Schema.Boolean), + ignored: Schema.optional(Schema.Boolean), + time: Schema.optional( + Schema.Struct({ + start: NonNegativeInt, + end: Schema.optional(NonNegativeInt), + }), + ), + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), +}).annotate({ identifier: "TextPart" }) +export type TextPart = Types.DeepMutable> + +export const ReasoningPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("reasoning"), + text: Schema.String, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), + time: Schema.Struct({ + start: NonNegativeInt, + end: Schema.optional(NonNegativeInt), + }), +}).annotate({ identifier: "ReasoningPart" }) +export type ReasoningPart = Types.DeepMutable> + +const filePartSourceBase = { + text: Schema.Struct({ + value: Schema.String, + start: Schema.Finite, + end: Schema.Finite, + }).annotate({ identifier: "FilePartSourceText" }), +} + +export const Range = Schema.Struct({ + start: Schema.Struct({ line: NonNegativeInt, character: NonNegativeInt }), + end: Schema.Struct({ line: NonNegativeInt, character: NonNegativeInt }), +}).annotate({ identifier: "Range" }) +export type Range = typeof Range.Type + +export const FileSource = Schema.Struct({ + ...filePartSourceBase, + type: Schema.Literal("file"), + path: Schema.String, +}).annotate({ identifier: "FileSource" }) + +export const SymbolSource = Schema.Struct({ + ...filePartSourceBase, + type: Schema.Literal("symbol"), + path: Schema.String, + range: Range, + name: Schema.String, + kind: NonNegativeInt, +}).annotate({ identifier: "SymbolSource" }) + +export const ResourceSource = Schema.Struct({ + ...filePartSourceBase, + type: Schema.Literal("resource"), + clientName: Schema.String, + uri: Schema.String, +}).annotate({ identifier: "ResourceSource" }) + +export const FilePartSource = Schema.Union([FileSource, SymbolSource, ResourceSource]).annotate({ + discriminator: "type", + identifier: "FilePartSource", +}) + +export const FilePart = Schema.Struct({ + ...partBase, + type: Schema.Literal("file"), + mime: Schema.String, + filename: Schema.optional(Schema.String), + url: Schema.String, + source: Schema.optional(FilePartSource), +}).annotate({ identifier: "FilePart" }) +export type FilePart = Types.DeepMutable> + +export const AgentPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("agent"), + name: Schema.String, + source: Schema.optional( + Schema.Struct({ + value: Schema.String, + start: NonNegativeInt, + end: NonNegativeInt, + }), + ), +}).annotate({ identifier: "AgentPart" }) +export type AgentPart = Types.DeepMutable> + +export const CompactionPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("compaction"), + auto: Schema.Boolean, + overflow: Schema.optional(Schema.Boolean), + tail_start_id: Schema.optional(MessageID), +}).annotate({ identifier: "CompactionPart" }) +export type CompactionPart = Types.DeepMutable> + +export const SubtaskPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("subtask"), + prompt: Schema.String, + description: Schema.String, + agent: Schema.String, + model: Schema.optional( + Schema.Struct({ + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, + }), + ), + command: Schema.optional(Schema.String), +}).annotate({ identifier: "SubtaskPart" }) +export type SubtaskPart = Types.DeepMutable> + +export const RetryPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("retry"), + attempt: NonNegativeInt, + error: APIError.EffectSchema, + time: Schema.Struct({ + created: NonNegativeInt, + }), +}).annotate({ identifier: "RetryPart" }) +export type RetryPart = Omit>, "error"> & { + error: APIError +} + +export const StepStartPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("step-start"), + snapshot: Schema.optional(Schema.String), +}).annotate({ identifier: "StepStartPart" }) +export type StepStartPart = Types.DeepMutable> + +export const StepFinishPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("step-finish"), + reason: Schema.String, + snapshot: Schema.optional(Schema.String), + cost: Schema.Finite, + tokens: Schema.Struct({ + total: Schema.optional(Schema.Finite), + input: Schema.Finite, + output: Schema.Finite, + reasoning: Schema.Finite, + cache: Schema.Struct({ + read: Schema.Finite, + write: Schema.Finite, + }), + }), +}).annotate({ identifier: "StepFinishPart" }) +export type StepFinishPart = Types.DeepMutable> + +export const ToolStatePending = Schema.Struct({ + status: Schema.Literal("pending"), + input: Schema.Record(Schema.String, Schema.Any), + raw: Schema.String, +}).annotate({ identifier: "ToolStatePending" }) +export type ToolStatePending = Types.DeepMutable> + +export const ToolStateRunning = Schema.Struct({ + status: Schema.Literal("running"), + input: Schema.Record(Schema.String, Schema.Any), + title: Schema.optional(Schema.String), + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), + time: Schema.Struct({ + start: NonNegativeInt, + }), +}).annotate({ identifier: "ToolStateRunning" }) +export type ToolStateRunning = Types.DeepMutable> + +export const ToolStateCompleted = Schema.Struct({ + status: Schema.Literal("completed"), + input: Schema.Record(Schema.String, Schema.Any), + output: Schema.String, + title: Schema.String, + metadata: Schema.Record(Schema.String, Schema.Any), + time: Schema.Struct({ + start: NonNegativeInt, + end: NonNegativeInt, + compacted: Schema.optional(NonNegativeInt), + }), + attachments: Schema.optional(Schema.Array(FilePart)), +}).annotate({ identifier: "ToolStateCompleted" }) +export type ToolStateCompleted = Types.DeepMutable> + +export const ToolStateError = Schema.Struct({ + status: Schema.Literal("error"), + input: Schema.Record(Schema.String, Schema.Any), + error: Schema.String, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), + time: Schema.Struct({ + start: NonNegativeInt, + end: NonNegativeInt, + }), +}).annotate({ identifier: "ToolStateError" }) +export type ToolStateError = Types.DeepMutable> + +export const ToolState = Schema.Union([ + ToolStatePending, + ToolStateRunning, + ToolStateCompleted, + ToolStateError, +]).annotate({ + discriminator: "status", + identifier: "ToolState", +}) +export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError + +export const ToolPart = Schema.Struct({ + ...partBase, + type: Schema.Literal("tool"), + callID: Schema.String, + tool: Schema.String, + state: ToolState, + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), +}).annotate({ identifier: "ToolPart" }) +export type ToolPart = Omit>, "state"> & { + state: ToolState +} + +const messageBase = { + id: MessageID, + sessionID: partBase.sessionID, +} + +const FileDiff = Schema.Struct({ + file: Schema.optional(Schema.String), + patch: Schema.optional(Schema.String), + additions: Schema.Finite, + deletions: Schema.Finite, + status: Schema.optional(Schema.Literals(["added", "deleted", "modified"])), +}).annotate({ identifier: "SnapshotFileDiff" }) + +export const User = Schema.Struct({ + ...messageBase, + role: Schema.Literal("user"), + time: Schema.Struct({ + created: NonNegativeInt, + }), + format: Schema.optional(Format), + summary: Schema.optional( + Schema.Struct({ + title: Schema.optional(Schema.String), + body: Schema.optional(Schema.String), + diffs: Schema.Array(FileDiff), + }), + ), + agent: Schema.String, + model: Schema.Struct({ + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, + variant: Schema.optional(Schema.String), + }), + system: Schema.optional(Schema.String), + tools: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)), +}).annotate({ identifier: "UserMessage" }) +export type User = Types.DeepMutable> + +export const Part = Schema.Union([ + TextPart, + SubtaskPart, + ReasoningPart, + FilePart, + ToolPart, + StepStartPart, + StepFinishPart, + SnapshotPart, + PatchPart, + AgentPart, + RetryPart, + CompactionPart, +]).annotate({ discriminator: "type", identifier: "Part" }) +export type Part = + | TextPart + | SubtaskPart + | ReasoningPart + | FilePart + | ToolPart + | StepStartPart + | StepFinishPart + | SnapshotPart + | PatchPart + | AgentPart + | RetryPart + | CompactionPart + +const AssistantErrorSchema = Schema.Union([ + AuthError.EffectSchema, + NamedError.Unknown.EffectSchema, + OutputLengthError.EffectSchema, + AbortedError.EffectSchema, + StructuredOutputError.EffectSchema, + ContextOverflowError.EffectSchema, + APIError.EffectSchema, +]).annotate({ discriminator: "name" }) +type AssistantError = Schema.Schema.Type + +export const TextPartInput = Schema.Struct({ + id: Schema.optional(PartID), + type: Schema.Literal("text"), + text: Schema.String, + synthetic: Schema.optional(Schema.Boolean), + ignored: Schema.optional(Schema.Boolean), + time: Schema.optional( + Schema.Struct({ + start: NonNegativeInt, + end: Schema.optional(NonNegativeInt), + }), + ), + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), +}).annotate({ identifier: "TextPartInput" }) +export type TextPartInput = Types.DeepMutable> + +export const FilePartInput = Schema.Struct({ + id: Schema.optional(PartID), + type: Schema.Literal("file"), + mime: Schema.String, + filename: Schema.optional(Schema.String), + url: Schema.String, + source: Schema.optional(FilePartSource), +}).annotate({ identifier: "FilePartInput" }) +export type FilePartInput = Types.DeepMutable> + +export const AgentPartInput = Schema.Struct({ + id: Schema.optional(PartID), + type: Schema.Literal("agent"), + name: Schema.String, + source: Schema.optional( + Schema.Struct({ + value: Schema.String, + start: NonNegativeInt, + end: NonNegativeInt, + }), + ), +}).annotate({ identifier: "AgentPartInput" }) +export type AgentPartInput = Types.DeepMutable> + +export const SubtaskPartInput = Schema.Struct({ + id: Schema.optional(PartID), + type: Schema.Literal("subtask"), + prompt: Schema.String, + description: Schema.String, + agent: Schema.String, + model: Schema.optional( + Schema.Struct({ + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, + }), + ), + command: Schema.optional(Schema.String), +}).annotate({ identifier: "SubtaskPartInput" }) +export type SubtaskPartInput = Types.DeepMutable> + +export const Assistant = Schema.Struct({ + ...messageBase, + role: Schema.Literal("assistant"), + time: Schema.Struct({ + created: NonNegativeInt, + completed: Schema.optional(NonNegativeInt), + }), + error: Schema.optional(AssistantErrorSchema), + parentID: MessageID, + modelID: ProviderV2.ModelID, + providerID: ProviderV2.ID, + mode: Schema.String, + agent: Schema.String, + path: Schema.Struct({ + cwd: Schema.String, + root: Schema.String, + }), + summary: Schema.optional(Schema.Boolean), + cost: Schema.Finite, + tokens: Schema.Struct({ + total: Schema.optional(Schema.Finite), + input: Schema.Finite, + output: Schema.Finite, + reasoning: Schema.Finite, + cache: Schema.Struct({ + read: Schema.Finite, + write: Schema.Finite, + }), + }), + structured: Schema.optional(Schema.Any), + variant: Schema.optional(Schema.String), + finish: Schema.optional(Schema.String), +}).annotate({ identifier: "AssistantMessage" }) +export type Assistant = Omit>, "error"> & { + error?: AssistantError +} + +export const Info = Schema.Union([User, Assistant]).annotate({ discriminator: "role", identifier: "Message" }) +export type Info = User | Assistant + +export const WithParts = Schema.Struct({ + info: Info, + parts: Schema.Array(Part), +}) +export type WithParts = { + info: Info + parts: Part[] +} + +const options = { + sync: { + aggregate: "sessionID", + version: 1, + }, +} as const + +const SessionSummary = Schema.Struct({ + additions: Schema.Finite, + deletions: Schema.Finite, + files: Schema.Finite, + diffs: optionalOmitUndefined(Schema.Array(FileDiff)), +}) + +const SessionTokens = Schema.Struct({ + input: Schema.Finite, + output: Schema.Finite, + reasoning: Schema.Finite, + cache: Schema.Struct({ + read: Schema.Finite, + write: Schema.Finite, + }), +}) + +const SessionShare = Schema.Struct({ + url: Schema.String, +}) + +const SessionRevert = Schema.Struct({ + messageID: MessageID, + partID: optionalOmitUndefined(PartID), + snapshot: optionalOmitUndefined(Schema.String), + diff: optionalOmitUndefined(Schema.String), +}) + +const SessionModel = Schema.Struct({ + id: ProviderV2.ModelID, + providerID: ProviderV2.ID, + variant: optionalOmitUndefined(Schema.String), +}) + +export const SessionInfo = Schema.Struct({ + id: SessionSchema.ID, + slug: Schema.String, + projectID: ProjectV2.ID, + workspaceID: optionalOmitUndefined(WorkspaceV2.ID), + directory: Schema.String, + path: optionalOmitUndefined(Schema.String), + parentID: optionalOmitUndefined(SessionSchema.ID), + summary: optionalOmitUndefined(SessionSummary), + cost: optionalOmitUndefined(Schema.Finite), + tokens: optionalOmitUndefined(SessionTokens), + share: optionalOmitUndefined(SessionShare), + title: Schema.String, + agent: optionalOmitUndefined(Schema.String), + model: optionalOmitUndefined(SessionModel), + version: Schema.String, + metadata: optionalOmitUndefined(Schema.Record(Schema.String, Schema.Any)), + time: Schema.Struct({ + created: NonNegativeInt, + updated: NonNegativeInt, + compacting: optionalOmitUndefined(NonNegativeInt), + archived: optionalOmitUndefined(Schema.Finite), + }), + permission: optionalOmitUndefined(PermissionV2.Ruleset), + revert: optionalOmitUndefined(SessionRevert), +}).annotate({ identifier: "Session" }) +export type SessionInfo = typeof SessionInfo.Type + +export const Event = { + Created: EventV2.define({ + type: "session.created", + ...options, + schema: { + sessionID: SessionSchema.ID, + info: SessionInfo, + }, + }), + Updated: EventV2.define({ + type: "session.updated", + ...options, + schema: { + sessionID: SessionSchema.ID, + info: SessionInfo, + }, + }), + Deleted: EventV2.define({ + type: "session.deleted", + ...options, + schema: { + sessionID: SessionSchema.ID, + info: SessionInfo, + }, + }), + MessageUpdated: EventV2.define({ + type: "message.updated", + ...options, + schema: { + sessionID: SessionSchema.ID, + info: Info, + }, + }), + MessageRemoved: EventV2.define({ + type: "message.removed", + ...options, + schema: { + sessionID: SessionSchema.ID, + messageID: MessageID, + }, + }), + PartUpdated: EventV2.define({ + type: "message.part.updated", + ...options, + schema: { + sessionID: SessionSchema.ID, + part: Part, + time: Schema.Finite, + }, + }), + PartRemoved: EventV2.define({ + type: "message.part.removed", + ...options, + schema: { + sessionID: SessionSchema.ID, + messageID: MessageID, + partID: PartID, + }, + }), +} diff --git a/packages/core/src/session/message-updater.ts b/packages/core/src/session/message-updater.ts new file mode 100644 index 000000000000..1c1e21880587 --- /dev/null +++ b/packages/core/src/session/message-updater.ts @@ -0,0 +1,474 @@ +import { produce, type WritableDraft } from "immer" +import { Effect } from "effect" +import { SessionEvent } from "./event" +import { SessionMessage } from "./message" + +export type MemoryState = { + messages: SessionMessage.Message[] +} + +export interface Adapter { + readonly getCurrentAssistant: () => Effect.Effect + readonly getCurrentCompaction: () => Effect.Effect + readonly getCurrentShell: (callID: string) => Effect.Effect + readonly updateAssistant: (assistant: SessionMessage.Assistant) => Effect.Effect + readonly updateCompaction: (compaction: SessionMessage.Compaction) => Effect.Effect + readonly updateShell: (shell: SessionMessage.Shell) => Effect.Effect + readonly appendMessage: (message: SessionMessage.Message) => Effect.Effect +} + +export function memory(state: MemoryState): Adapter { + const activeAssistantIndex = () => + state.messages.findLastIndex((message) => message.type === "assistant" && !message.time.completed) + const activeCompactionIndex = () => state.messages.findLastIndex((message) => message.type === "compaction") + const activeShellIndex = (callID: string) => + state.messages.findLastIndex((message) => message.type === "shell" && message.callID === callID) + + return { + getCurrentAssistant() { + return Effect.sync(() => { + const index = activeAssistantIndex() + if (index < 0) return + const assistant = state.messages[index] + return assistant?.type === "assistant" ? assistant : undefined + }) + }, + getCurrentCompaction() { + return Effect.sync(() => { + const index = activeCompactionIndex() + if (index < 0) return + const compaction = state.messages[index] + return compaction?.type === "compaction" ? compaction : undefined + }) + }, + getCurrentShell(callID) { + return Effect.sync(() => { + const index = activeShellIndex(callID) + if (index < 0) return + const shell = state.messages[index] + return shell?.type === "shell" ? shell : undefined + }) + }, + updateAssistant(assistant) { + return Effect.sync(() => { + const index = activeAssistantIndex() + if (index < 0) return + const current = state.messages[index] + if (current?.type !== "assistant") return + state.messages[index] = assistant + }) + }, + updateCompaction(compaction) { + return Effect.sync(() => { + const index = activeCompactionIndex() + if (index < 0) return + const current = state.messages[index] + if (current?.type !== "compaction") return + state.messages[index] = compaction + }) + }, + updateShell(shell) { + return Effect.sync(() => { + const index = activeShellIndex(shell.callID) + if (index < 0) return + const current = state.messages[index] + if (current?.type !== "shell") return + state.messages[index] = shell + }) + }, + appendMessage(message) { + return Effect.sync(() => { + state.messages.push(message) + }) + }, + } +} + +export function update(adapter: Adapter, event: SessionEvent.Event) { + type DraftAssistant = WritableDraft + type DraftTool = WritableDraft + type DraftText = WritableDraft + type DraftReasoning = WritableDraft + + const latestTool = (assistant: DraftAssistant | undefined, callID?: string) => + assistant?.content.findLast( + (item): item is DraftTool => item.type === "tool" && (callID === undefined || item.id === callID), + ) + + const latestText = (assistant: DraftAssistant | undefined) => + assistant?.content.findLast((item): item is DraftText => item.type === "text") + + const latestReasoning = (assistant: DraftAssistant | undefined, reasoningID: string) => + assistant?.content.findLast((item): item is DraftReasoning => item.type === "reasoning" && item.id === reasoningID) + + return Effect.gen(function* () { + yield* SessionEvent.All.match(event, { + "session.next.agent.switched": (event) => { + return adapter.appendMessage( + new SessionMessage.AgentSwitched({ + id: event.id, + type: "agent-switched", + metadata: event.metadata, + agent: event.data.agent, + time: { created: event.data.timestamp }, + }), + ) + }, + "session.next.model.switched": (event) => { + return adapter.appendMessage( + new SessionMessage.ModelSwitched({ + id: event.id, + type: "model-switched", + metadata: event.metadata, + model: event.data.model, + time: { created: event.data.timestamp }, + }), + ) + }, + "session.next.prompted": (event) => { + return adapter.appendMessage( + new SessionMessage.User({ + id: event.id, + type: "user", + metadata: event.metadata, + text: event.data.prompt.text, + files: event.data.prompt.files, + agents: event.data.prompt.agents, + references: event.data.prompt.references, + time: { created: event.data.timestamp }, + }), + ) + }, + "session.next.synthetic": (event) => { + return adapter.appendMessage( + new SessionMessage.Synthetic({ + sessionID: event.data.sessionID, + text: event.data.text, + id: event.id, + type: "synthetic", + time: { created: event.data.timestamp }, + }), + ) + }, + "session.next.shell.started": (event) => { + return adapter.appendMessage( + new SessionMessage.Shell({ + id: event.id, + type: "shell", + metadata: event.metadata, + callID: event.data.callID, + command: event.data.command, + output: "", + time: { created: event.data.timestamp }, + }), + ) + }, + "session.next.shell.ended": (event) => { + return Effect.gen(function* () { + const currentShell = yield* adapter.getCurrentShell(event.data.callID) + if (currentShell) { + yield* adapter.updateShell( + produce(currentShell, (draft) => { + draft.output = event.data.output + draft.time.completed = event.data.timestamp + }), + ) + } + }) + }, + "session.next.step.started": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + draft.time.completed = event.data.timestamp + }), + ) + } + yield* adapter.appendMessage( + new SessionMessage.Assistant({ + id: event.id, + type: "assistant", + agent: event.data.agent, + model: event.data.model, + time: { created: event.data.timestamp }, + content: [], + snapshot: event.data.snapshot ? { start: event.data.snapshot } : undefined, + }), + ) + }) + }, + "session.next.step.ended": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + draft.time.completed = event.data.timestamp + draft.finish = event.data.finish + draft.cost = event.data.cost + draft.tokens = event.data.tokens + if (event.data.snapshot) draft.snapshot = { ...draft.snapshot, end: event.data.snapshot } + }), + ) + } + }) + }, + "session.next.step.failed": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + draft.time.completed = event.data.timestamp + draft.finish = "error" + draft.error = event.data.error + }), + ) + } + }) + }, + "session.next.text.started": () => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + draft.content.push(new SessionMessage.AssistantText({ type: "text", text: "" }) as DraftText) + }), + ) + } + }) + }, + "session.next.text.delta": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestText(draft) + if (match) match.text += event.data.delta + }), + ) + } + }) + }, + "session.next.text.ended": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestText(draft) + if (match) match.text = event.data.text + }), + ) + } + }) + }, + "session.next.tool.input.started": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + draft.content.push( + new SessionMessage.AssistantTool({ + type: "tool", + id: event.data.callID, + name: event.data.name, + time: { created: event.data.timestamp }, + state: new SessionMessage.ToolStatePending({ status: "pending", input: "" }), + }) as DraftTool, + ) + }), + ) + } + }) + }, + "session.next.tool.input.delta": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestTool(draft, event.data.callID) + // oxlint-disable-next-line no-base-to-string -- event.delta is a Schema.String (runtime string) + if (match && match.state.status === "pending") match.state.input += event.data.delta + }), + ) + } + }) + }, + "session.next.tool.input.ended": () => Effect.void, + "session.next.tool.called": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestTool(draft, event.data.callID) + if (match) { + match.provider = event.data.provider + match.time.ran = event.data.timestamp + match.state = { + status: "running", + input: event.data.input, + structured: {}, + content: [], + } + } + }), + ) + } + }) + }, + "session.next.tool.progress": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestTool(draft, event.data.callID) + if (match && match.state.status === "running") { + match.state.structured = event.data.structured + match.state.content = [...event.data.content] + } + }), + ) + } + }) + }, + "session.next.tool.success": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestTool(draft, event.data.callID) + if (match && match.state.status === "running") { + match.provider = event.data.provider + match.time.completed = event.data.timestamp + match.state = { + status: "completed", + input: match.state.input, + structured: event.data.structured, + content: [...event.data.content], + } + } + }), + ) + } + }) + }, + "session.next.tool.failed": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestTool(draft, event.data.callID) + if (match && match.state.status === "running") { + match.provider = event.data.provider + match.time.completed = event.data.timestamp + match.state = { + status: "error", + error: event.data.error, + input: match.state.input, + structured: match.state.structured, + content: match.state.content, + } + } + }), + ) + } + }) + }, + "session.next.reasoning.started": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + draft.content.push( + new SessionMessage.AssistantReasoning({ + type: "reasoning", + id: event.data.reasoningID, + text: "", + }) as DraftReasoning, + ) + }), + ) + } + }) + }, + "session.next.reasoning.delta": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestReasoning(draft, event.data.reasoningID) + if (match) match.text += event.data.delta + }), + ) + } + }) + }, + "session.next.reasoning.ended": (event) => { + return Effect.gen(function* () { + const currentAssistant = yield* adapter.getCurrentAssistant() + if (currentAssistant) { + yield* adapter.updateAssistant( + produce(currentAssistant, (draft) => { + const match = latestReasoning(draft, event.data.reasoningID) + if (match) match.text = event.data.text + }), + ) + } + }) + }, + "session.next.retried": () => Effect.void, + "session.next.compaction.started": (event) => { + return adapter.appendMessage( + new SessionMessage.Compaction({ + id: event.id, + type: "compaction", + metadata: event.metadata, + reason: event.data.reason, + summary: "", + time: { created: event.data.timestamp }, + }), + ) + }, + "session.next.compaction.delta": (event) => { + return Effect.gen(function* () { + const currentCompaction = yield* adapter.getCurrentCompaction() + if (currentCompaction) { + yield* adapter.updateCompaction( + produce(currentCompaction, (draft) => { + draft.summary += event.data.text + }), + ) + } + }) + }, + "session.next.compaction.ended": (event) => { + return Effect.gen(function* () { + const currentCompaction = yield* adapter.getCurrentCompaction() + if (currentCompaction) { + yield* adapter.updateCompaction( + produce(currentCompaction, (draft) => { + draft.summary = event.data.text + draft.include = event.data.include + }), + ) + } + }) + }, + }) + }) +} + +export * as SessionMessageUpdater from "./message-updater" diff --git a/packages/core/src/session-message.ts b/packages/core/src/session/message.ts similarity index 95% rename from packages/core/src/session-message.ts rename to packages/core/src/session/message.ts index 73b6dd7da2b9..9de73a17bbe5 100644 --- a/packages/core/src/session-message.ts +++ b/packages/core/src/session/message.ts @@ -1,10 +1,12 @@ +export * as SessionMessage from "./message" + import { Schema } from "effect" -import { Prompt } from "./session-prompt" -import { SessionEvent } from "./session-event" -import { EventV2 } from "./event" -import { ToolOutput } from "./tool-output" -import { V2Schema } from "./v2-schema" -import { ModelV2 } from "./model" +import { EventV2 } from "../event" +import { ModelV2 } from "../model" +import { ToolOutput } from "../tool-output" +import { V2Schema } from "../v2-schema" +import { SessionEvent } from "./event" +import { Prompt } from "./prompt" export const ID = EventV2.ID export type ID = Schema.Schema.Type @@ -169,5 +171,3 @@ export const Message = Schema.Union([AgentSwitched, ModelSwitched, User, Synthet export type Message = Schema.Schema.Type export type Type = Message["type"] - -export * as SessionMessage from "./session-message" diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts new file mode 100644 index 000000000000..3044aee52ddc --- /dev/null +++ b/packages/core/src/session/projector.ts @@ -0,0 +1,456 @@ +export * as SessionProjector from "./projector" + +import { and, eq, sql } from "drizzle-orm" +import { DateTime, Effect, Layer, Schema } from "effect" +import { Database } from "../database/database" +import { EventV2 } from "../event" +import { SessionEvent } from "./event" +import { SessionLegacy } from "./legacy" +import { WorkspaceTable } from "../control-plane/workspace.sql" +import { SessionMessage } from "./message" +import { SessionMessageUpdater } from "./message-updater" +import { MessageTable, PartTable, SessionMessageTable, SessionTable } from "./sql" +import type { DeepMutable } from "../schema" + +type DatabaseService = Database.Interface["db"] + +const decodeMessage = Schema.decodeUnknownSync(SessionMessage.Message) +const encodeMessage = Schema.encodeSync(SessionMessage.Message) + +type Usage = { + cost: number + tokens: { + input: number + output: number + reasoning: number + cache: { read: number; write: number } + } +} + +function usage(part: (typeof SessionLegacy.Event.PartUpdated.Type)["data"]["part"] | unknown): Usage | undefined { + if (typeof part !== "object" || part === null) return undefined + const value = part as Record + if (value.type !== "step-finish") return undefined + if (!("cost" in value) || !("tokens" in value)) return undefined + return { cost: value.cost as Usage["cost"], tokens: value.tokens as Usage["tokens"] } +} + +function sessionRow(info: SessionLegacy.SessionInfo): typeof SessionTable.$inferInsert { + return { + id: info.id, + project_id: info.projectID, + workspace_id: info.workspaceID ?? null, + parent_id: info.parentID, + slug: info.slug, + directory: info.directory, + path: info.path, + title: info.title, + agent: info.agent, + model: info.model, + version: info.version, + share_url: info.share?.url, + summary_additions: info.summary?.additions, + summary_deletions: info.summary?.deletions, + summary_files: info.summary?.files, + summary_diffs: info.summary?.diffs ? [...info.summary.diffs] : undefined, + metadata: info.metadata, + cost: info.cost ?? 0, + tokens_input: (info.tokens ?? { input: 0 }).input, + tokens_output: (info.tokens ?? { output: 0 }).output, + tokens_reasoning: (info.tokens ?? { reasoning: 0 }).reasoning, + tokens_cache_read: (info.tokens ?? { cache: { read: 0 } }).cache.read, + tokens_cache_write: (info.tokens ?? { cache: { write: 0 } }).cache.write, + revert: info.revert ?? null, + permission: info.permission ? [...info.permission] : undefined, + time_created: info.time.created, + time_updated: info.time.updated, + time_compacting: info.time.compacting, + time_archived: info.time.archived, + } +} + +function messageData( + info: (typeof SessionLegacy.Event.MessageUpdated.Type)["data"]["info"], +): typeof MessageTable.$inferInsert.data { + const { id: _, sessionID: __, ...rest } = info + return rest as DeepMutable +} + +function partData( + part: (typeof SessionLegacy.Event.PartUpdated.Type)["data"]["part"], +): typeof PartTable.$inferInsert.data { + const { id: _, messageID: __, sessionID: ___, ...rest } = part + return rest as DeepMutable +} + +function applyUsage( + db: DatabaseService, + sessionID: (typeof SessionLegacy.Event.MessageUpdated.Type)["data"]["sessionID"], + value: Usage, + sign = 1, +) { + return db + .update(SessionTable) + .set({ + cost: sql`${SessionTable.cost} + ${value.cost * sign}`, + tokens_input: sql`${SessionTable.tokens_input} + ${value.tokens.input * sign}`, + tokens_output: sql`${SessionTable.tokens_output} + ${value.tokens.output * sign}`, + tokens_reasoning: sql`${SessionTable.tokens_reasoning} + ${value.tokens.reasoning * sign}`, + tokens_cache_read: sql`${SessionTable.tokens_cache_read} + ${value.tokens.cache.read * sign}`, + tokens_cache_write: sql`${SessionTable.tokens_cache_write} + ${value.tokens.cache.write * sign}`, + time_updated: sql`${SessionTable.time_updated}`, + }) + .where(eq(SessionTable.id, sessionID)) + .run() + .pipe(Effect.orDie) +} + +function run(db: DatabaseService, event: SessionEvent.Event) { + return Effect.gen(function* () { + const adapter: SessionMessageUpdater.Adapter = { + getCurrentAssistant() { + return Effect.gen(function* () { + const rows = yield* db + .select() + .from(SessionMessageTable) + .where( + and(eq(SessionMessageTable.session_id, event.data.sessionID), eq(SessionMessageTable.type, "assistant")), + ) + .all() + .pipe(Effect.orDie) + return rows + .map((row) => decodeMessage({ ...row.data, id: row.id, type: row.type })) + .find( + (message): message is SessionMessage.Assistant => message.type === "assistant" && !message.time.completed, + ) + }) + }, + getCurrentCompaction() { + return Effect.gen(function* () { + const rows = yield* db + .select() + .from(SessionMessageTable) + .where( + and(eq(SessionMessageTable.session_id, event.data.sessionID), eq(SessionMessageTable.type, "compaction")), + ) + .all() + .pipe(Effect.orDie) + return rows + .map((row) => decodeMessage({ ...row.data, id: row.id, type: row.type })) + .find((message): message is SessionMessage.Compaction => message.type === "compaction") + }) + }, + getCurrentShell(callID) { + return Effect.gen(function* () { + const rows = yield* db + .select() + .from(SessionMessageTable) + .where(and(eq(SessionMessageTable.session_id, event.data.sessionID), eq(SessionMessageTable.type, "shell"))) + .all() + .pipe(Effect.orDie) + return rows + .map((row) => decodeMessage({ ...row.data, id: row.id, type: row.type })) + .find((message): message is SessionMessage.Shell => message.type === "shell" && message.callID === callID) + }) + }, + updateAssistant(message) { + return Effect.gen(function* () { + const encoded = encodeMessage(message) + const { id, type, ...data } = encoded + yield* db + .insert(SessionMessageTable) + .values([ + { + id: SessionMessage.ID.make(id), + session_id: event.data.sessionID, + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + ]) + .onConflictDoUpdate({ + target: SessionMessageTable.id, + set: { + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + }) + .run() + .pipe(Effect.orDie) + }) + }, + updateCompaction(message) { + return Effect.gen(function* () { + const encoded = encodeMessage(message) + const { id, type, ...data } = encoded + yield* db + .insert(SessionMessageTable) + .values([ + { + id: SessionMessage.ID.make(id), + session_id: event.data.sessionID, + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + ]) + .onConflictDoUpdate({ + target: SessionMessageTable.id, + set: { + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + }) + .run() + .pipe(Effect.orDie) + }) + }, + updateShell(message) { + return Effect.gen(function* () { + const encoded = encodeMessage(message) + const { id, type, ...data } = encoded + yield* db + .insert(SessionMessageTable) + .values([ + { + id: SessionMessage.ID.make(id), + session_id: event.data.sessionID, + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + ]) + .onConflictDoUpdate({ + target: SessionMessageTable.id, + set: { + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + }) + .run() + .pipe(Effect.orDie) + }) + }, + appendMessage(message) { + return Effect.gen(function* () { + const encoded = encodeMessage(message) + const { id, type, ...data } = encoded + yield* db + .insert(SessionMessageTable) + .values([ + { + id: SessionMessage.ID.make(id), + session_id: event.data.sessionID, + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + ]) + .onConflictDoUpdate({ + target: SessionMessageTable.id, + set: { + type, + time_created: DateTime.toEpochMillis(message.time.created), + data, + }, + }) + .run() + .pipe(Effect.orDie) + }) + }, + } + yield* SessionMessageUpdater.update(adapter, event) + }) +} + +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + yield* events.project(SessionLegacy.Event.Created, (event) => + Effect.gen(function* () { + yield* db.insert(SessionTable).values(sessionRow(event.data.info)).run().pipe(Effect.orDie) + if (event.data.info.workspaceID) { + yield* db + .update(WorkspaceTable) + .set({ time_used: Date.now() }) + .where(eq(WorkspaceTable.id, event.data.info.workspaceID)) + .run() + .pipe(Effect.orDie) + } + }), + ) + yield* events.project(SessionLegacy.Event.Updated, (event) => + db + .update(SessionTable) + .set(sessionRow(event.data.info)) + .where(eq(SessionTable.id, event.data.sessionID)) + .run() + .pipe(Effect.orDie), + ) + yield* events.project(SessionLegacy.Event.Deleted, (event) => + db.delete(SessionTable).where(eq(SessionTable.id, event.data.sessionID)).run().pipe(Effect.orDie), + ) + yield* events.project(SessionLegacy.Event.MessageUpdated, (event) => + Effect.gen(function* () { + const time_created = event.data.info.time.created + const id = event.data.info.id + const sessionID = event.data.info.sessionID + const data = messageData(event.data.info) + yield* db + .insert(MessageTable) + .values({ id, session_id: sessionID, time_created, data }) + .onConflictDoUpdate({ target: MessageTable.id, set: { data } }) + .run() + .pipe(Effect.orDie) + }), + ) + yield* events.project(SessionLegacy.Event.MessageRemoved, (event) => + Effect.gen(function* () { + const rows = yield* db + .select() + .from(PartTable) + .where(and(eq(PartTable.message_id, event.data.messageID), eq(PartTable.session_id, event.data.sessionID))) + .all() + .pipe(Effect.orDie) + for (const row of rows) { + const previous = usage(row.data) + if (previous) yield* applyUsage(db, event.data.sessionID, previous, -1) + } + yield* db + .delete(MessageTable) + .where(and(eq(MessageTable.id, event.data.messageID), eq(MessageTable.session_id, event.data.sessionID))) + .run() + .pipe(Effect.orDie) + }), + ) + yield* events.project(SessionLegacy.Event.PartRemoved, (event) => + Effect.gen(function* () { + const row = yield* db + .select() + .from(PartTable) + .where(and(eq(PartTable.id, event.data.partID), eq(PartTable.session_id, event.data.sessionID))) + .get() + .pipe(Effect.orDie) + const previous = row && usage(row.data) + if (previous) yield* applyUsage(db, event.data.sessionID, previous, -1) + yield* db + .delete(PartTable) + .where(and(eq(PartTable.id, event.data.partID), eq(PartTable.session_id, event.data.sessionID))) + .run() + .pipe(Effect.orDie) + }), + ) + yield* events.project(SessionLegacy.Event.PartUpdated, (event) => + Effect.gen(function* () { + const id = event.data.part.id + const messageID = event.data.part.messageID + const sessionID = event.data.part.sessionID + const data = partData(event.data.part) + const row = yield* db.select().from(PartTable).where(eq(PartTable.id, id)).get().pipe(Effect.orDie) + yield* db + .insert(PartTable) + .values({ id, message_id: messageID, session_id: sessionID, time_created: event.data.time, data }) + .onConflictDoUpdate({ target: PartTable.id, set: { data } }) + .run() + .pipe(Effect.orDie) + const previous = row && usage(row.data) + const next = usage(event.data.part) + if (previous) yield* applyUsage(db, row.session_id, previous, -1) + if (next) yield* applyUsage(db, sessionID, next) + }), + ) + // session.next.* projectors are disabled while the v2 message projection is stabilized. + // The events still publish through EventV2 and fan out through the opencode bridge. + // yield* events.project(SessionEvent.AgentSwitched, (event) => + // Effect.gen(function* () { + // const message = Schema.encodeSync(SessionMessage.AgentSwitched)( + // new SessionMessage.AgentSwitched({ + // id: event.id, + // type: "agent-switched", + // metadata: event.metadata, + // agent: event.data.agent, + // time: { created: event.data.timestamp }, + // }), + // ) + // const data = { metadata: message.metadata, agent: message.agent, time: message.time } + // yield* db + // .update(SessionTable) + // .set({ agent: event.data.agent, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + // .where(eq(SessionTable.id, event.data.sessionID)) + // .run() + // .pipe(Effect.orDie) + // yield* db + // .insert(SessionMessageTable) + // .values([ + // { + // id: SessionMessage.ID.make(event.id), + // session_id: event.data.sessionID, + // type: "agent-switched", + // time_created: DateTime.toEpochMillis(event.data.timestamp), + // data, + // }, + // ]) + // .run() + // .pipe(Effect.orDie) + // }), + // ) + // yield* events.project(SessionEvent.ModelSwitched, (event) => + // Effect.gen(function* () { + // const message = Schema.encodeSync(SessionMessage.ModelSwitched)( + // new SessionMessage.ModelSwitched({ + // id: event.id, + // type: "model-switched", + // metadata: event.metadata, + // model: event.data.model, + // time: { created: event.data.timestamp }, + // }), + // ) + // const data = { metadata: message.metadata, model: message.model, time: message.time } + // yield* db + // .update(SessionTable) + // .set({ model: event.data.model, time_updated: DateTime.toEpochMillis(event.data.timestamp) }) + // .where(eq(SessionTable.id, event.data.sessionID)) + // .run() + // .pipe(Effect.orDie) + // yield* db + // .insert(SessionMessageTable) + // .values([ + // { + // id: SessionMessage.ID.make(event.id), + // session_id: event.data.sessionID, + // type: "model-switched", + // time_created: DateTime.toEpochMillis(event.data.timestamp), + // data, + // }, + // ]) + // .run() + // .pipe(Effect.orDie) + // }), + // ) + // yield* events.project(SessionEvent.Prompted, (event) => run(db, event)) + // yield* events.project(SessionEvent.Synthetic, (event) => run(db, event)) + // yield* events.project(SessionEvent.Shell.Started, (event) => run(db, event)) + // yield* events.project(SessionEvent.Shell.Ended, (event) => run(db, event)) + // yield* events.project(SessionEvent.Step.Started, (event) => run(db, event)) + // yield* events.project(SessionEvent.Step.Ended, (event) => run(db, event)) + // yield* events.project(SessionEvent.Step.Failed, (event) => run(db, event)) + // yield* events.project(SessionEvent.Text.Started, (event) => run(db, event)) + // yield* events.project(SessionEvent.Text.Ended, (event) => run(db, event)) + // yield* events.project(SessionEvent.Tool.Input.Started, (event) => run(db, event)) + // yield* events.project(SessionEvent.Tool.Input.Ended, (event) => run(db, event)) + // yield* events.project(SessionEvent.Tool.Called, (event) => run(db, event)) + // yield* events.project(SessionEvent.Tool.Success, (event) => run(db, event)) + // yield* events.project(SessionEvent.Tool.Failed, (event) => run(db, event)) + // yield* events.project(SessionEvent.Reasoning.Started, (event) => run(db, event)) + // yield* events.project(SessionEvent.Reasoning.Ended, (event) => run(db, event)) + // yield* events.project(SessionEvent.Retried, (event) => run(db, event)) + // yield* events.project(SessionEvent.Compaction.Started, (event) => run(db, event)) + // yield* events.project(SessionEvent.Compaction.Ended, (event) => run(db, event)) + }), +) + +export const defaultLayer = layer.pipe(Layer.provide(EventV2.defaultLayer), Layer.provide(Database.defaultLayer)) diff --git a/packages/core/src/session-prompt.ts b/packages/core/src/session/prompt.ts similarity index 100% rename from packages/core/src/session-prompt.ts rename to packages/core/src/session/prompt.ts diff --git a/packages/core/src/session/schema.ts b/packages/core/src/session/schema.ts new file mode 100644 index 000000000000..8562a097e53c --- /dev/null +++ b/packages/core/src/session/schema.ts @@ -0,0 +1,59 @@ +export * as SessionSchema from "./schema" + +import { Schema } from "effect" +import { Location } from "../location" +import { ModelV2 } from "../model" +import { ProjectV2 } from "../project" +import { RelativePath, optionalOmitUndefined, withStatics } from "../schema" +import { WorkspaceV2 } from "../workspace" +import { Identifier } from "../util/identifier" +import { V2Schema } from "../v2-schema" + +export const Delivery = Schema.Literals(["immediate", "deferred"]).annotate({ + identifier: "Session.Delivery", +}) +export type Delivery = Schema.Schema.Type + +export const DefaultDelivery = "immediate" satisfies Delivery + +export const ID = Schema.String.check(Schema.isStartsWith("ses")).pipe( + Schema.brand("SessionID"), + withStatics((schema) => ({ + descending: (id?: string) => schema.make(id ?? "ses_" + Identifier.descending()), + })), +) +export type ID = typeof ID.Type + +export const LegacyInfo = Schema.Struct({ + id: ID, + location: Location.Ref, + subpath: RelativePath, // derived from location + project: ProjectV2.ID, // derived from location +}) +export type LegacyInfo = typeof LegacyInfo.Type + +export class Info extends Schema.Class("Session.Info")({ + id: ID, + parentID: optionalOmitUndefined(ID), + projectID: ProjectV2.ID, + workspaceID: optionalOmitUndefined(WorkspaceV2.ID), + path: optionalOmitUndefined(Schema.String), + agent: optionalOmitUndefined(Schema.String), + model: ModelV2.Ref.pipe(optionalOmitUndefined), + cost: Schema.Finite, + tokens: Schema.Struct({ + input: Schema.Finite, + output: Schema.Finite, + reasoning: Schema.Finite, + cache: Schema.Struct({ + read: Schema.Finite, + write: Schema.Finite, + }), + }), + time: Schema.Struct({ + created: V2Schema.DateTimeUtcFromMillis, + updated: V2Schema.DateTimeUtcFromMillis, + archived: optionalOmitUndefined(V2Schema.DateTimeUtcFromMillis), + }), + title: Schema.String, +}) {} diff --git a/packages/opencode/src/session/session.sql.ts b/packages/core/src/session/sql.ts similarity index 74% rename from packages/opencode/src/session/session.sql.ts rename to packages/core/src/session/sql.ts index 610ca72c4696..cc474cd960ab 100644 --- a/packages/opencode/src/session/session.sql.ts +++ b/packages/core/src/session/sql.ts @@ -1,28 +1,28 @@ import { sqliteTable, text, integer, index, primaryKey, real } from "drizzle-orm/sqlite-core" -import { ProjectTable } from "../project/project.sql" -import type { MessageV2 } from "./message-v2" -import type { SessionMessage } from "@opencode-ai/core/session-message" +import { ProjectTable } from "../project/sql" +import type { SessionMessage } from "./message" import type { Snapshot } from "../snapshot" -import type { Permission } from "../permission" -import type { ProjectID } from "../project/schema" -import type { SessionID, MessageID, PartID } from "./schema" -import type { WorkspaceID } from "../control-plane/schema" -import { Timestamps } from "../storage/schema.sql" +import { PermissionV2 } from "../permission" +import { ProjectV2 } from "../project" +import type { SessionSchema } from "./schema" +import type { MessageID, PartID, Info as LegacyMessageInfo, Part as LegacyMessagePart } from "./legacy" +import { WorkspaceV2 } from "../workspace" +import { Timestamps } from "../database/schema.sql" -type PartData = Omit -type InfoData = T extends unknown ? Omit : never type SessionMessageData = Omit<(typeof SessionMessage.Message)["Encoded"], "type" | "id"> +type LegacyMessageData = Omit +type LegacyPartData = Omit export const SessionTable = sqliteTable( "session", { - id: text().$type().primaryKey(), + id: text().$type().primaryKey(), project_id: text() - .$type() + .$type() .notNull() .references(() => ProjectTable.id, { onDelete: "cascade" }), - workspace_id: text().$type(), - parent_id: text().$type(), + workspace_id: text().$type(), + parent_id: text().$type(), slug: text().notNull(), directory: text().notNull(), path: text(), @@ -33,6 +33,7 @@ export const SessionTable = sqliteTable( summary_deletions: integer(), summary_files: integer(), summary_diffs: text({ mode: "json" }).$type(), + metadata: text({ mode: "json" }).$type>(), cost: real().notNull().default(0), tokens_input: integer().notNull().default(0), tokens_output: integer().notNull().default(0), @@ -40,7 +41,7 @@ export const SessionTable = sqliteTable( tokens_cache_read: integer().notNull().default(0), tokens_cache_write: integer().notNull().default(0), revert: text({ mode: "json" }).$type<{ messageID: MessageID; partID?: PartID; snapshot?: string; diff?: string }>(), - permission: text({ mode: "json" }).$type(), + permission: text({ mode: "json" }).$type(), agent: text(), model: text({ mode: "json" }).$type<{ id: string @@ -63,11 +64,11 @@ export const MessageTable = sqliteTable( { id: text().$type().primaryKey(), session_id: text() - .$type() + .$type() .notNull() .references(() => SessionTable.id, { onDelete: "cascade" }), ...Timestamps, - data: text({ mode: "json" }).notNull().$type(), + data: text({ mode: "json" }).notNull().$type(), }, (table) => [index("message_session_time_created_id_idx").on(table.session_id, table.time_created, table.id)], ) @@ -80,9 +81,9 @@ export const PartTable = sqliteTable( .$type() .notNull() .references(() => MessageTable.id, { onDelete: "cascade" }), - session_id: text().$type().notNull(), + session_id: text().$type().notNull(), ...Timestamps, - data: text({ mode: "json" }).notNull().$type(), + data: text({ mode: "json" }).notNull().$type(), }, (table) => [ index("part_message_id_id_idx").on(table.message_id, table.id), @@ -94,7 +95,7 @@ export const TodoTable = sqliteTable( "todo", { session_id: text() - .$type() + .$type() .notNull() .references(() => SessionTable.id, { onDelete: "cascade" }), content: text().notNull(), @@ -114,7 +115,7 @@ export const SessionMessageTable = sqliteTable( { id: text().$type().primaryKey(), session_id: text() - .$type() + .$type() .notNull() .references(() => SessionTable.id, { onDelete: "cascade" }), type: text().$type().notNull(), @@ -133,5 +134,5 @@ export const PermissionTable = sqliteTable("permission", { .primaryKey() .references(() => ProjectTable.id, { onDelete: "cascade" }), ...Timestamps, - data: text({ mode: "json" }).notNull().$type(), + data: text({ mode: "json" }).notNull().$type(), }) diff --git a/packages/opencode/src/share/share.sql.ts b/packages/core/src/share/sql.ts similarity index 75% rename from packages/opencode/src/share/share.sql.ts rename to packages/core/src/share/sql.ts index f337e106a583..a7a08d0c0254 100644 --- a/packages/opencode/src/share/share.sql.ts +++ b/packages/core/src/share/sql.ts @@ -1,6 +1,6 @@ import { sqliteTable, text } from "drizzle-orm/sqlite-core" -import { SessionTable } from "../session/session.sql" -import { Timestamps } from "../storage/schema.sql" +import { SessionTable } from "../session/sql" +import { Timestamps } from "../database/schema.sql" export const SessionShareTable = sqliteTable("session_share", { session_id: text() diff --git a/packages/core/src/snapshot.ts b/packages/core/src/snapshot.ts new file mode 100644 index 000000000000..b39c0f7f0140 --- /dev/null +++ b/packages/core/src/snapshot.ts @@ -0,0 +1,9 @@ +export namespace Snapshot { + export type FileDiff = { + file?: string + patch?: string + additions: number + deletions: number + status?: "added" | "deleted" | "modified" + } +} diff --git a/packages/core/src/state.ts b/packages/core/src/state.ts new file mode 100644 index 000000000000..aa3ab0e2407b --- /dev/null +++ b/packages/core/src/state.ts @@ -0,0 +1,64 @@ +export * as State from "./state" + +import { Effect, Scope, Semaphore } from "effect" +import type { Draft, Objectish } from "immer" + +export type Transform = (editor: Editor) => void +export type MakeEditor = (draft: Draft) => Editor + +export interface Options { + readonly initial: () => State + readonly editor: MakeEditor + /** Completes every committed edit; reason identifies exceptional update origins. */ + readonly finalize?: (editor: Editor, reason?: string) => Effect.Effect +} + +export interface Interface { + readonly get: () => State + readonly transform: () => Effect.Effect<(transform: Transform) => Effect.Effect, never, Scope.Scope> + readonly update: (update: (editor: Editor) => Effect.Effect, reason?: string) => Effect.Effect +} + +export function create(options: Options): Interface { + let state = options.initial() + let transforms: { update: Transform }[] = [] + const semaphore = Semaphore.makeUnsafe(1) + + const commit = Effect.fn("State.commit")(function* (next: State, reason?: string) { + const api = options.editor(next as Draft) + if (options.finalize) yield* options.finalize(api, reason) + state = next + }) + + const rebuild = Effect.fn("State.rebuild")(function* () { + const next = options.initial() + const api = options.editor(next as Draft) + for (const transform of transforms) + yield* Effect.sync(() => transform.update(api)).pipe(Effect.withSpan("State.rebuild.update", {})) + yield* commit(next) + }, semaphore.withPermit) + + return { + get: () => state, + transform: Effect.fn("State.transform")(function* () { + const transform = { update: (_editor: Editor) => {} } + transforms = [...transforms, transform] + const scope = yield* Scope.Scope + yield* Scope.addFinalizer( + scope, + Effect.sync(() => { + transforms = transforms.filter((item) => item !== transform) + }).pipe(Effect.andThen(rebuild())), + ) + return Effect.fnUntraced(function* (update: Transform) { + transform.update = update + yield* rebuild() + }) + }), + update: Effect.fn("State.update")(function* (update, reason) { + const api = options.editor(state as Draft) + yield* update(api) + if (options.finalize) yield* options.finalize(api, reason) + }, semaphore.withPermit), + } +} diff --git a/packages/core/src/workspace.ts b/packages/core/src/workspace.ts new file mode 100644 index 000000000000..30d33abbee64 --- /dev/null +++ b/packages/core/src/workspace.ts @@ -0,0 +1,18 @@ +export * as WorkspaceV2 from "./workspace" + +import { Schema } from "effect" +import { withStatics } from "./schema" +import { Identifier } from "./util/identifier" + +export const ID = Schema.String.check(Schema.isStartsWith("wrk")).pipe( + Schema.brand("WorkspaceV2.ID"), + withStatics((schema) => ({ + ascending: (id?: string) => { + if (!id) return schema.make("wrk_" + Identifier.ascending()) + if (!id.startsWith("wrk")) throw new Error(`ID ${id} does not start with wrk`) + return schema.make(id) + }, + create: () => schema.make("wrk_" + Identifier.ascending()), + })), +) +export type ID = typeof ID.Type diff --git a/packages/core/test/account.test.ts b/packages/core/test/account.test.ts index cf60740b1e67..4e69df25d31e 100644 --- a/packages/core/test/account.test.ts +++ b/packages/core/test/account.test.ts @@ -2,7 +2,7 @@ import path from "path" import { describe, expect } from "bun:test" import { produce } from "immer" import { Effect, Fiber, Layer, Option, Stream } from "effect" -import { AccountV2 } from "@opencode-ai/core/account" +import { Auth } from "@opencode-ai/core/auth" import { Catalog } from "@opencode-ai/core/catalog" import { EventV2 } from "@opencode-ai/core/event" import { AppFileSystem } from "@opencode-ai/core/filesystem" @@ -14,17 +14,16 @@ import { ProviderV2 } from "@opencode-ai/core/provider" import { tmpdir } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" -const it = testEffect(PluginV2.defaultLayer) +const it = testEffect(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer))) function context( records: { provider: ProviderV2.Info; models: Map }[], updates: Array<{ id: ProviderV2.ID; enabled: ProviderV2.Info["enabled"]; apiKey?: string }>, -): Catalog.Context { +): Catalog.Editor { return { - data: records, - updateProvider: (providerID, fn) => context(records, updates).provider.update(providerID, fn), - updateModel: (providerID, modelID, fn) => context(records, updates).model.update(providerID, modelID, fn), provider: { + list: () => records, + get: (providerID) => records.find((item) => item.provider.id === providerID), update: (providerID, fn) => { const record = records.find((item) => item.provider.id === providerID) const provider = produce(record?.provider ?? ProviderV2.Info.empty(providerID), fn) @@ -45,14 +44,19 @@ function context( }, }, model: { + get: () => undefined, update: () => {}, remove: () => {}, + default: { + get: () => undefined, + set: () => {}, + }, }, } } function testLayer(dir: string) { - return AccountV2.layer.pipe( + return Auth.layer.pipe( Layer.provide(AppFileSystem.defaultLayer), Layer.provideMerge(EventV2.defaultLayer), Layer.provide( @@ -70,7 +74,7 @@ function testLayer(dir: string) { ) } -describe("AccountV2", () => { +describe("Auth", () => { it.live("emits account lifecycle events", () => Effect.acquireRelease( Effect.promise(() => tmpdir()), @@ -78,23 +82,23 @@ describe("AccountV2", () => { ).pipe( Effect.flatMap((tmp) => Effect.gen(function* () { - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const eventSvc = yield* EventV2.Service const addedFiber = yield* eventSvc - .subscribe(AccountV2.Event.Added) + .subscribe(Auth.Event.Added) .pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped) const switchedFiber = yield* eventSvc - .subscribe(AccountV2.Event.Switched) + .subscribe(Auth.Event.Switched) .pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped) const removedFiber = yield* eventSvc - .subscribe(AccountV2.Event.Removed) + .subscribe(Auth.Event.Removed) .pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped) yield* Effect.yieldNow const first = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "raw-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "raw-key" }), }) expect(first).toBeDefined() if (!first) return @@ -109,8 +113,8 @@ describe("AccountV2", () => { if (updated?.credential.type === "api") expect(updated.credential.key).toBe("raw-key") const second = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "second-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "second-key" }), }) expect(second).toBeDefined() if (!second) return @@ -121,9 +125,9 @@ describe("AccountV2", () => { const removed = Array.from(yield* Fiber.join(removedFiber)) expect(added.map((event) => event.data.account.id)).toEqual([first.id, second.id]) expect(switched.map((event) => event.data)).toEqual([ - { serviceID: AccountV2.ServiceID.make("provider"), from: undefined, to: first.id }, - { serviceID: AccountV2.ServiceID.make("provider"), from: first.id, to: second.id }, - { serviceID: AccountV2.ServiceID.make("provider"), from: second.id, to: first.id }, + { serviceID: Auth.ServiceID.make("provider"), from: undefined, to: first.id }, + { serviceID: Auth.ServiceID.make("provider"), from: first.id, to: second.id }, + { serviceID: Auth.ServiceID.make("provider"), from: second.id, to: first.id }, ]) expect(removed[0]?.data.account.id).toBe(second.id) }).pipe(Effect.provide(testLayer(tmp.path))), @@ -138,25 +142,25 @@ describe("AccountV2", () => { ).pipe( Effect.flatMap((tmp) => Effect.gen(function* () { - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const eventSvc = yield* EventV2.Service const switchedFiber = yield* eventSvc - .subscribe(AccountV2.Event.Switched) + .subscribe(Auth.Event.Switched) .pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped) yield* Effect.yieldNow const first = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "first-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "first-key" }), }) const second = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "second-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "second-key" }), }) const third = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "third-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "third-key" }), }) expect(first).toBeDefined() @@ -164,11 +168,11 @@ describe("AccountV2", () => { expect(third).toBeDefined() if (!first || !second || !third) return - expect((yield* accounts.active(AccountV2.ServiceID.make("provider")))?.id).toBe(third.id) + expect((yield* accounts.active(Auth.ServiceID.make("provider")))?.id).toBe(third.id) expect(Array.from(yield* Fiber.join(switchedFiber)).map((event) => event.data)).toEqual([ - { serviceID: AccountV2.ServiceID.make("provider"), from: undefined, to: first.id }, - { serviceID: AccountV2.ServiceID.make("provider"), from: first.id, to: second.id }, - { serviceID: AccountV2.ServiceID.make("provider"), from: second.id, to: third.id }, + { serviceID: Auth.ServiceID.make("provider"), from: undefined, to: first.id }, + { serviceID: Auth.ServiceID.make("provider"), from: first.id, to: second.id }, + { serviceID: Auth.ServiceID.make("provider"), from: second.id, to: third.id }, ]) }).pipe(Effect.provide(testLayer(tmp.path))), ), @@ -182,7 +186,7 @@ describe("AccountV2", () => { ).pipe( Effect.flatMap((tmp) => Effect.gen(function* () { - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const plugin = yield* PluginV2.Service const records = [ { @@ -192,7 +196,7 @@ describe("AccountV2", () => { ] const updates: Array<{ id: ProviderV2.ID; enabled: ProviderV2.Info["enabled"]; apiKey?: string }> = [] const catalog = Catalog.Service.of({ - loader: () => Effect.die("unexpected catalog.loader"), + transform: () => Effect.die("unexpected catalog.transform"), provider: { get: () => Effect.die("unexpected provider.get"), all: () => Effect.succeed([]), @@ -203,7 +207,6 @@ describe("AccountV2", () => { all: () => Effect.succeed([]), available: () => Effect.succeed([]), default: () => Effect.succeed(Option.none()), - setDefault: () => Effect.die("unexpected model.setDefault"), small: () => Effect.succeed(Option.none()), }, }) @@ -212,7 +215,7 @@ describe("AccountV2", () => { yield* plugin.add({ ...AccountPlugin, effect: AccountPlugin.effect.pipe( - Effect.provideService(AccountV2.Service, accounts), + Effect.provideService(Auth.Service, accounts), Effect.provideService(Catalog.Service, catalog), Effect.provideService(EventV2.Service, eventSvc), Effect.provideService(PluginV2.Service, plugin), @@ -221,8 +224,8 @@ describe("AccountV2", () => { yield* Effect.yieldNow const first = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "first-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "first-key" }), }) expect(first).toBeDefined() if (!first) return @@ -230,15 +233,15 @@ describe("AccountV2", () => { expect(updates).toEqual([ { id: ProviderV2.ID.make("provider"), - enabled: { via: "account", service: AccountV2.ServiceID.make("provider") }, + enabled: { via: "account", service: Auth.ServiceID.make("provider") }, apiKey: "first-key", }, ]) updates.length = 0 const second = yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("provider"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "second-key" }), + serviceID: Auth.ServiceID.make("provider"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "second-key" }), }) expect(second).toBeDefined() if (!second) return @@ -246,7 +249,7 @@ describe("AccountV2", () => { expect(updates).toEqual([ { id: ProviderV2.ID.make("provider"), - enabled: { via: "account", service: AccountV2.ServiceID.make("provider") }, + enabled: { via: "account", service: Auth.ServiceID.make("provider") }, apiKey: "second-key", }, ]) @@ -257,7 +260,7 @@ describe("AccountV2", () => { expect(updates).toEqual([ { id: ProviderV2.ID.make("provider"), - enabled: { via: "account", service: AccountV2.ServiceID.make("provider") }, + enabled: { via: "account", service: Auth.ServiceID.make("provider") }, apiKey: "first-key", }, ]) @@ -268,7 +271,7 @@ describe("AccountV2", () => { expect(updates).toEqual([ { id: ProviderV2.ID.make("provider"), - enabled: { via: "account", service: AccountV2.ServiceID.make("provider") }, + enabled: { via: "account", service: Auth.ServiceID.make("provider") }, apiKey: "second-key", }, ]) diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts new file mode 100644 index 000000000000..2aef203351b7 --- /dev/null +++ b/packages/core/test/agent.test.ts @@ -0,0 +1,101 @@ +import { describe, expect } from "bun:test" +import { Effect, Exit, Scope } from "effect" +import { AgentV2 } from "@opencode-ai/core/agent" +import { testEffect } from "./lib/effect" + +const it = testEffect(AgentV2.locationLayer) + +describe("AgentV2", () => { + it.effect("starts without agents", () => + Effect.gen(function* () { + const agent = yield* AgentV2.Service + + expect(yield* agent.all()).toEqual([]) + expect(yield* agent.get(AgentV2.ID.make("build"))).toBeUndefined() + }), + ) + + it.effect("materializes replayable agent transforms", () => + Effect.gen(function* () { + const agent = yield* AgentV2.Service + const id = AgentV2.ID.make("reviewer") + const transform = yield* agent.transform() + + yield* transform((editor) => + editor.update(id, (info) => { + info.description = "Reviews code" + info.mode = "subagent" + }), + ) + + expect(yield* agent.get(id)).toMatchObject({ id, description: "Reviews code", mode: "subagent" }) + expect((yield* agent.all()).map((info) => info.id)).toEqual([id]) + }), + ) + + it.effect("rebuilds state when a transform is replaced", () => + Effect.gen(function* () { + const agent = yield* AgentV2.Service + const id = AgentV2.ID.make("reviewer") + const transform = yield* agent.transform() + + yield* transform((editor) => + editor.update(id, (info) => { + info.description = "Old description" + info.hidden = true + }), + ) + yield* transform((editor) => + editor.update(id, (info) => { + info.description = "New description" + }), + ) + + expect(yield* agent.get(id)).toMatchObject({ description: "New description", hidden: false }) + }), + ) + + it.effect("removes a transform contribution when its scope closes", () => + Effect.gen(function* () { + const agent = yield* AgentV2.Service + const id = AgentV2.ID.make("scoped") + const scope = yield* Scope.make() + const transform = yield* agent.transform().pipe(Scope.provide(scope)) + + yield* transform((editor) => editor.update(id, () => {})) + expect(yield* agent.get(id)).toBeDefined() + + yield* Scope.close(scope, Exit.void) + expect(yield* agent.get(id)).toBeUndefined() + }), + ) + + it.effect("applies direct agent updates", () => + Effect.gen(function* () { + const agent = yield* AgentV2.Service + const id = AgentV2.ID.make("build") + + yield* agent.update((editor) => + editor.update(id, (info) => { + info.mode = "primary" + info.hidden = true + }), + ) + + expect(yield* agent.get(id)).toMatchObject({ id, mode: "primary", hidden: true }) + }), + ) + + it.effect("creates agents with runtime defaults and supports direct removal", () => + Effect.gen(function* () { + const agent = yield* AgentV2.Service + const id = AgentV2.ID.make("custom") + + yield* agent.update((editor) => editor.update(id, () => {})) + expect(yield* agent.get(id)).toEqual(AgentV2.Info.empty(id)) + + yield* agent.update((editor) => editor.remove(id)) + expect(yield* agent.get(id)).toBeUndefined() + }), + ) +}) diff --git a/packages/core/test/catalog.test.ts b/packages/core/test/catalog.test.ts index 97f816d0056d..121b1fe01278 100644 --- a/packages/core/test/catalog.test.ts +++ b/packages/core/test/catalog.test.ts @@ -5,16 +5,18 @@ import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" +import { Policy } from "@opencode-ai/core/policy" import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "./fixture/location" import { testEffect } from "./lib/effect" -const locationLayer = Layer.succeed(Location.Service, Location.Service.of({ directory: "test" })) +const locationLayer = Layer.succeed( + Location.Service, + Location.Service.of(location({ directory: AbsolutePath.make("test") })), +) const it = testEffect( - Catalog.layer.pipe( - Layer.provideMerge(EventV2.defaultLayer), - Layer.provideMerge(PluginV2.defaultLayer), - Layer.provideMerge(locationLayer), - ), + Catalog.locationLayer.pipe(Layer.provideMerge(EventV2.defaultLayer), Layer.provideMerge(locationLayer)), ) describe("CatalogV2", () => { @@ -22,9 +24,9 @@ describe("CatalogV2", () => { Effect.gen(function* () { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.make("test") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => + yield* transform((catalog) => catalog.provider.update(providerID, (provider) => { provider.endpoint = { type: "aisdk", @@ -48,9 +50,9 @@ describe("CatalogV2", () => { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.make("test") const modelID = ModelV2.ID.make("model") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => { + yield* transform((catalog) => { catalog.provider.update(providerID, (provider) => { provider.endpoint = { type: "aisdk", @@ -77,9 +79,9 @@ describe("CatalogV2", () => { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.make("test") const modelID = ModelV2.ID.make("model") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => { + yield* transform((catalog) => { catalog.provider.update(providerID, (provider) => { provider.endpoint = { type: "aisdk", @@ -104,14 +106,14 @@ describe("CatalogV2", () => { const plugin = yield* PluginV2.Service const providerID = ProviderV2.ID.make("test") const seen: unknown[] = [] - const load = yield* catalog.loader() + const transform = yield* catalog.transform() yield* plugin.add({ id: PluginV2.ID.make("test"), effect: Effect.succeed({ "catalog.transform": (evt) => Effect.sync(() => { - const item = evt.data.find((record) => record.provider.id === providerID) + const item = evt.provider.get(providerID) if (!item) return seen.push(item.provider.endpoint.type) if (item?.provider.endpoint.type === "aisdk") seen.push(item.provider.endpoint.url) @@ -119,7 +121,7 @@ describe("CatalogV2", () => { }), }), }) - yield* load((catalog) => + yield* transform((catalog) => catalog.provider.update(providerID, (provider) => { provider.endpoint = { type: "aisdk", package: "@ai-sdk/openai-compatible" } provider.options.aisdk.provider.baseURL = "https://provider.example.com" @@ -135,9 +137,9 @@ describe("CatalogV2", () => { const catalog = yield* Catalog.Service const plugin = yield* PluginV2.Service const providerID = ProviderV2.ID.make("test") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => + yield* transform((catalog) => catalog.provider.update(providerID, (provider) => { provider.name = "Before" }), @@ -159,14 +161,40 @@ describe("CatalogV2", () => { }), ) + it.effect("ignores plugin additions from another location", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const plugin = yield* PluginV2.Service + let invoked = 0 + + yield* plugin.add({ + id: PluginV2.ID.make("test-transform"), + effect: Effect.succeed({ + "catalog.transform": () => Effect.sync(() => invoked++), + }), + }) + yield* Effect.yieldNow + expect(invoked).toBe(1) + + yield* events.publish( + PluginV2.Event.Added, + { id: PluginV2.ID.make("test-transform") }, + { location: { directory: AbsolutePath.make("other") } }, + ) + yield* Effect.yieldNow + + expect(invoked).toBe(1) + }), + ) + it.effect("resolves provider and model option merges", () => Effect.gen(function* () { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.make("test") const modelID = ModelV2.ID.make("model") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => { + yield* transform((catalog) => { catalog.provider.update(providerID, (provider) => { provider.options.headers.provider = "provider" provider.options.headers.shared = "provider" @@ -194,9 +222,9 @@ describe("CatalogV2", () => { Effect.gen(function* () { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.make("test") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => { + yield* transform((catalog) => { catalog.provider.update(providerID, (provider) => { provider.enabled = { via: "custom", data: {} } }) @@ -212,13 +240,44 @@ describe("CatalogV2", () => { }), ) + it.effect("uses a transform-provided default model until that transform is replaced", () => + Effect.gen(function* () { + const catalog = yield* Catalog.Service + const providerID = ProviderV2.ID.make("test") + const old = ModelV2.ID.make("old") + const newest = ModelV2.ID.make("new") + const transform = yield* catalog.transform() + + const models = (catalog: Catalog.Editor) => { + catalog.provider.update(providerID, (provider) => { + provider.enabled = { via: "custom", data: {} } + }) + catalog.model.update(providerID, old, (model) => { + model.time.released = DateTime.makeUnsafe(1000) + }) + catalog.model.update(providerID, newest, (model) => { + model.time.released = DateTime.makeUnsafe(2000) + }) + } + + yield* transform((catalog) => { + models(catalog) + catalog.model.default.set(providerID, old) + }) + expect(Option.getOrUndefined(yield* catalog.model.default())?.id).toBe(old) + + yield* transform(models) + expect(Option.getOrUndefined(yield* catalog.model.default())?.id).toBe(newest) + }), + ) + it.effect("small model prefers small keyword candidates before cost scoring", () => Effect.gen(function* () { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.make("test") - const load = yield* catalog.loader() + const transform = yield* catalog.transform() - yield* load((catalog) => { + yield* transform((catalog) => { catalog.provider.update(providerID, () => {}) catalog.model.update(providerID, ModelV2.ID.make("cheap-large"), (model) => { model.capabilities.input = ["text"] @@ -237,4 +296,23 @@ describe("CatalogV2", () => { expect(Option.getOrUndefined(yield* catalog.model.small(providerID))?.id).toMatch("expensive-mini") }), ) + + it.effect("removes providers denied by policy after loading", () => + Effect.gen(function* () { + const catalog = yield* Catalog.Service + const policy = yield* Policy.Service + const providerID = ProviderV2.ID.make("blocked") + const transform = yield* catalog.transform() + + yield* policy.load([new Policy.Info({ effect: "deny", action: "provider.use", resource: "blocked" })]) + yield* transform((catalog) => { + catalog.provider.update(providerID, () => {}) + catalog.model.update(providerID, ModelV2.ID.make("model"), () => {}) + }) + + expect(yield* catalog.provider.all()).toEqual([]) + expect(yield* catalog.model.all()).toEqual([]) + expect(yield* catalog.provider.get(providerID).pipe(Effect.option)).toEqual(Option.none()) + }), + ) }) diff --git a/packages/core/test/config/agent.test.ts b/packages/core/test/config/agent.test.ts new file mode 100644 index 000000000000..34ca99b0979c --- /dev/null +++ b/packages/core/test/config/agent.test.ts @@ -0,0 +1,186 @@ +import { describe, expect } from "bun:test" +import { Effect, Schema } from "effect" +import { AgentV2 } from "@opencode-ai/core/agent" +import { Config } from "@opencode-ai/core/config" +import { ConfigAgentPlugin } from "@opencode-ai/core/config/plugin/agent" +import { PermissionV2 } from "@opencode-ai/core/permission" +import { testEffect } from "../lib/effect" + +const it = testEffect(AgentV2.locationLayer) +const decode = Schema.decodeUnknownSync(Config.Info) + +describe("ConfigAgentPlugin.Plugin", () => { + it.effect("applies global permissions between built-in and agent-specific permissions", () => + Effect.gen(function* () { + const agents = yield* AgentV2.Service + const build = AgentV2.ID.make("build") + const defaults = yield* agents.transform() + + yield* defaults((editor) => + editor.update(build, (agent) => { + agent.mode = "primary" + agent.permissions.push({ permission: "bash", pattern: "*", action: "allow" }) + }), + ) + + const config = Config.Service.of({ + directories: () => Effect.succeed([]), + get: () => + Effect.succeed([ + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + permissions: [{ permission: "bash", pattern: "*", action: "ask" }], + agents: { + build: { + permissions: [{ permission: "bash", pattern: "git *", action: "allow" }], + }, + reviewer: { + model: "openrouter/openai/gpt-5", + description: "Review changes", + mode: "subagent", + permissions: [{ permission: "edit", pattern: "*", action: "deny" }], + }, + removed: { description: "Removed later" }, + }, + }), + }), + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + agents: { + reviewer: { variant: "high", hidden: true }, + removed: { disabled: true }, + }, + }), + }), + ]), + }) + + yield* ConfigAgentPlugin.Plugin.effect.pipe( + Effect.provideService(Config.Service, config), + Effect.provideService(AgentV2.Service, agents), + ) + + const buildAgent = yield* agents.get(build) + if (!buildAgent) throw new Error("expected configured build agent") + expect(buildAgent.permissions).toEqual([ + { permission: "bash", pattern: "*", action: "allow" }, + { permission: "bash", pattern: "*", action: "ask" }, + { permission: "bash", pattern: "git *", action: "allow" }, + ]) + expect(PermissionV2.evaluate("bash", "git status", buildAgent.permissions).action).toBe("allow") + expect(PermissionV2.evaluate("bash", "bun test", buildAgent.permissions).action).toBe("ask") + + const reviewer = yield* agents.get(AgentV2.ID.make("reviewer")) + if (!reviewer) throw new Error("expected configured reviewer agent") + expect(reviewer).toMatchObject({ + description: "Review changes", + mode: "subagent", + hidden: true, + model: { providerID: "openrouter", id: "openai/gpt-5", variant: "high" }, + }) + expect(reviewer.permissions).toEqual([ + { permission: "bash", pattern: "*", action: "ask" }, + { permission: "edit", pattern: "*", action: "deny" }, + ]) + expect(yield* agents.get(AgentV2.ID.make("removed"))).toBeUndefined() + }), + ) + + it.effect("maps configured agent fields and preserves an unspecified model variant", () => + Effect.gen(function* () { + const agents = yield* AgentV2.Service + const config = Config.Service.of({ + directories: () => Effect.succeed([]), + get: () => + Effect.succeed([ + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + agents: { + reviewer: { + model: "anthropic/claude-sonnet", + system: "Review carefully.", + description: "Reviews changes", + mode: "subagent", + hidden: true, + color: "warning", + steps: 12, + options: { + headers: { first: "one", shared: "first" }, + body: { enabled: true }, + aisdk: { provider: { profile: "review" }, request: { effort: "medium" } }, + }, + }, + }, + }), + }), + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + agents: { + reviewer: { + options: { + headers: { shared: "last", second: "two" }, + body: { retries: 2 }, + aisdk: { request: { effort: "high" } }, + }, + }, + }, + }), + }), + ]), + }) + + yield* ConfigAgentPlugin.Plugin.effect.pipe( + Effect.provideService(Config.Service, config), + Effect.provideService(AgentV2.Service, agents), + ) + + const reviewer = yield* agents.get(AgentV2.ID.make("reviewer")) + if (!reviewer) throw new Error("expected configured reviewer agent") + expect(reviewer).toMatchObject({ + system: "Review carefully.", + description: "Reviews changes", + mode: "subagent", + hidden: true, + color: "warning", + steps: 12, + model: { providerID: "anthropic", id: "claude-sonnet", variant: undefined }, + }) + expect(reviewer.options).toEqual({ + headers: { first: "one", shared: "last", second: "two" }, + body: { enabled: true, retries: 2 }, + aisdk: { provider: { profile: "review" }, request: { effort: "high" } }, + }) + }), + ) + + it.effect("removes a built-in agent disabled by configuration", () => + Effect.gen(function* () { + const agents = yield* AgentV2.Service + const build = AgentV2.ID.make("build") + const defaults = yield* agents.transform() + yield* defaults((editor) => editor.update(build, () => {})) + + const config = Config.Service.of({ + directories: () => Effect.succeed([]), + get: () => + Effect.succeed([ + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ agents: { build: { disabled: true } } }), + }), + ]), + }) + + yield* ConfigAgentPlugin.Plugin.effect.pipe( + Effect.provideService(Config.Service, config), + Effect.provideService(AgentV2.Service, agents), + ) + + expect(yield* agents.get(build)).toBeUndefined() + }), + ) +}) diff --git a/packages/core/test/config/config.test.ts b/packages/core/test/config/config.test.ts new file mode 100644 index 000000000000..47e0206d466b --- /dev/null +++ b/packages/core/test/config/config.test.ts @@ -0,0 +1,459 @@ +import path from "path" +import fs from "fs/promises" +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { Config } from "@opencode-ai/core/config" +import { ConfigProvider } from "@opencode-ai/core/config/provider" +import { AppFileSystem } from "@opencode-ai/core/filesystem" +import { Global } from "@opencode-ai/core/global" +import { Location } from "@opencode-ai/core/location" +import { Policy } from "@opencode-ai/core/policy" +import { Project } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "../fixture/location" +import { tmpdir } from "../fixture/tmpdir" +import { testEffect } from "../lib/effect" + +const it = testEffect(Layer.empty) + +function testLayer( + directory: string, + globalDirectory = path.join(directory, "global"), + projectDirectory = directory, + vcs?: Project.Vcs, +) { + return Config.locationLayer.pipe( + Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(Global.layerWith({ config: globalDirectory })), + Layer.provide( + Layer.succeed( + Location.Service, + Location.Service.of( + location( + { directory: AbsolutePath.make(directory) }, + { projectDirectory: AbsolutePath.make(projectDirectory), vcs }, + ), + ), + ), + ), + ) +} + +const provider = { + endpoint: { type: "unknown" }, + options: { + headers: {}, + body: {}, + aisdk: { + provider: {}, + request: {}, + }, + }, + models: {}, +} + +describe("Config", () => { + it.live("returns an empty configuration when directory files do not exist", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + const config = yield* Config.Service + const documents = yield* config.get() + + expect(documents).toEqual([]) + }).pipe(Effect.provide(testLayer(tmp.path))), + ), + ), + ) + + it.live("loads JSON and JSONC files from lowest to highest priority", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + yield* Effect.promise(() => + Promise.all([ + fs.writeFile( + path.join(tmp.path, "config.json"), + JSON.stringify({ $schema: "base", providers: { base: provider } }), + ), + fs.writeFile( + path.join(tmp.path, "opencode.json"), + JSON.stringify({ $schema: "middle", providers: { middle: provider } }), + ), + fs.writeFile( + path.join(tmp.path, "opencode.jsonc"), + `{ + // Later global files override scalar fields while retaining providers. + "$schema": "last", + "providers": { "last": ${JSON.stringify(provider)} }, + }`, + ), + ]), + ) + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const documents = yield* config.get() + + expect(documents).toHaveLength(3) + expect(documents.map((document) => document.source.type)).toEqual(["file", "file", "file"]) + expect(documents.map((document) => document.info.$schema)).toEqual(["base", "middle", "last"]) + expect(documents[0]).toBeInstanceOf(Config.Loaded) + expect(documents[0]?.source.type === "file" ? documents[0].source.path : undefined).toBe( + path.join(tmp.path, "config.json"), + ) + expect(documents[2]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info) + + yield* Effect.promise(() => + fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ $schema: "changed" })), + ) + expect((yield* config.get()).map((document) => document.info.$schema)).toEqual(["base", "middle", "last"]) + }).pipe(Effect.provide(testLayer(tmp.path))) + }), + ), + ), + ) + + it.live("accepts $schema metadata without writing it into config files", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + const file = path.join(tmp.path, "opencode.json") + const contents = JSON.stringify({ + shell: "/bin/zsh", + experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] }, + providers: { local: provider }, + }) + yield* Effect.promise(() => fs.writeFile(file, contents)) + + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const documents = yield* config.get() + + expect(documents[0]?.info.$schema).toBeUndefined() + expect(documents[0]?.info.shell).toBe("/bin/zsh") + expect(documents[0]?.info.experimental?.policies?.[0]).toEqual({ + effect: "deny", + action: "provider.use", + resource: "openai", + }) + expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents) + }).pipe(Effect.provide(testLayer(tmp.path))) + }), + ), + ), + ) + + it.live("loads supported scalar and resource configuration", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + yield* Effect.promise(() => + fs.writeFile( + path.join(tmp.path, "opencode.json"), + JSON.stringify({ + shell: "/bin/bash", + model: "anthropic/claude", + autoupdate: "notify", + share: "disabled", + enterprise: { url: "https://share.example.com" }, + username: "test-user", + permissions: [ + { permission: "bash", pattern: "*", action: "ask" }, + { permission: "bash", pattern: "git status", action: "allow" }, + ], + agents: { + reviewer: { + model: "openrouter/openai/gpt-5", + variant: "high", + options: { + headers: { "x-agent": "reviewer" }, + aisdk: { request: { reasoningEffort: "high" } }, + }, + description: "Review changes for correctness", + system: "Find regressions.", + mode: "subagent", + hidden: false, + color: "warning", + steps: 12, + disabled: false, + permissions: [{ permission: "edit", pattern: "*", action: "deny" }], + }, + }, + snapshots: false, + watcher: { ignore: ["node_modules/**", "dist/**", ".git"] }, + formatter: { + prettier: { disabled: true }, + custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] }, + }, + lsp: { typescript: { disabled: true }, custom: { command: ["custom-lsp"], extensions: [".foo"] } }, + attachments: { + image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 }, + }, + tool_output: { max_lines: 1000, max_bytes: 32768 }, + mcp: { + timeout: 5000, + servers: { + local: { + type: "local", + command: ["node", "./mcp/server.js"], + environment: { API_KEY: "secret" }, + disabled: false, + timeout: 10000, + }, + remote: { + type: "remote", + url: "https://mcp.example.com/mcp", + headers: { Authorization: "Bearer token" }, + oauth: { client_id: "client", scope: "read write", callback_port: 19876 }, + disabled: true, + }, + }, + }, + compaction: { + auto: true, + prune: false, + keep: { turns: 3, tokens: 2000 }, + buffer: 10000, + }, + skills: ["./skills", "~/shared-skills", "https://example.com/.well-known/skills/"], + instructions: ["CONTRIBUTING.md", ".cursor/rules/*.md", "https://example.com/shared-rules.md"], + references: { + local: { path: "../library" }, + sdk: { repository: "github.com/example/sdk", branch: "main" }, + shorthand: "github.com/example/docs", + }, + plugins: [ + "opencode-helicone-session", + { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } }, + ], + }), + ), + ) + + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const documents = yield* config.get() + + expect(documents).toHaveLength(1) + expect(documents[0]?.info.shell).toBe("/bin/bash") + expect(documents[0]?.info.model).toBe("anthropic/claude") + expect(documents[0]?.info.autoupdate).toBe("notify") + expect(documents[0]?.info.share).toBe("disabled") + expect(documents[0]?.info.enterprise).toEqual({ url: "https://share.example.com" }) + expect(documents[0]?.info.username).toBe("test-user") + expect(documents[0]?.info.permissions).toEqual([ + { permission: "bash", pattern: "*", action: "ask" }, + { permission: "bash", pattern: "git status", action: "allow" }, + ]) + expect(documents[0]?.info.agents?.reviewer).toEqual({ + model: "openrouter/openai/gpt-5", + variant: "high", + options: { + headers: { "x-agent": "reviewer" }, + aisdk: { request: { reasoningEffort: "high" } }, + }, + description: "Review changes for correctness", + system: "Find regressions.", + mode: "subagent", + hidden: false, + color: "warning", + steps: 12, + disabled: false, + permissions: [{ permission: "edit", pattern: "*", action: "deny" }], + }) + expect(documents[0]?.info.snapshots).toBe(false) + expect(documents[0]?.info.watcher).toEqual({ ignore: ["node_modules/**", "dist/**", ".git"] }) + expect(documents[0]?.info.formatter).toEqual({ + prettier: { disabled: true }, + custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] }, + }) + expect(documents[0]?.info.lsp).toEqual({ + typescript: { disabled: true }, + custom: { command: ["custom-lsp"], extensions: [".foo"] }, + }) + expect(documents[0]?.info.attachments).toEqual({ + image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 }, + }) + expect(documents[0]?.info.tool_output).toEqual({ max_lines: 1000, max_bytes: 32768 }) + expect(documents[0]?.info.mcp).toEqual({ + timeout: 5000, + servers: { + local: { + type: "local", + command: ["node", "./mcp/server.js"], + environment: { API_KEY: "secret" }, + disabled: false, + timeout: 10000, + }, + remote: { + type: "remote", + url: "https://mcp.example.com/mcp", + headers: { Authorization: "Bearer token" }, + oauth: { client_id: "client", scope: "read write", callback_port: 19876 }, + disabled: true, + }, + }, + }) + expect(documents[0]?.info.compaction).toEqual({ + auto: true, + prune: false, + keep: { turns: 3, tokens: 2000 }, + buffer: 10000, + }) + expect(documents[0]?.info.skills).toEqual([ + "./skills", + "~/shared-skills", + "https://example.com/.well-known/skills/", + ]) + expect(documents[0]?.info.instructions).toEqual([ + "CONTRIBUTING.md", + ".cursor/rules/*.md", + "https://example.com/shared-rules.md", + ]) + expect(documents[0]?.info.references).toEqual({ + local: { path: "../library" }, + sdk: { repository: "github.com/example/sdk", branch: "main" }, + shorthand: "github.com/example/docs", + }) + expect(documents[0]?.info.plugins).toEqual([ + "opencode-helicone-session", + { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } }, + ]) + }).pipe(Effect.provide(testLayer(tmp.path))) + }), + ), + ), + ) + + it.live("ignores invalid files while loading valid config values", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => + Effect.gen(function* () { + yield* Effect.promise(() => + Promise.all([ + fs.writeFile(path.join(tmp.path, "config.json"), JSON.stringify({ $schema: "base" })), + fs.writeFile(path.join(tmp.path, "opencode.json"), "{ invalid"), + fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ providers: { invalid: true } })), + ]), + ) + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const documents = yield* config.get() + + expect(documents.map((document) => document.info.$schema)).toEqual(["base"]) + }).pipe(Effect.provide(testLayer(tmp.path))) + }), + ), + ), + ) + + it.live("loads policy statements in reverse config order", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => { + const global = path.join(tmp.path, "global") + return Effect.gen(function* () { + yield* Effect.promise(async () => { + await fs.mkdir(global, { recursive: true }) + await fs.writeFile( + path.join(global, "opencode.json"), + JSON.stringify({ + experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] }, + }), + ) + await fs.writeFile( + path.join(tmp.path, "opencode.json"), + JSON.stringify({ + experimental: { policies: [{ effect: "allow", action: "provider.use", resource: "openai" }] }, + }), + ) + }) + + return yield* Effect.gen(function* () { + const policy = yield* Policy.Service + + expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny") + }).pipe(Effect.provide(testLayer(tmp.path, global))) + }) + }), + ), + ) + + it.live("loads global, ancestor, and .opencode configuration up to the project boundary", () => + Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), + ).pipe( + Effect.flatMap((tmp) => { + const global = path.join(tmp.path, "global") + const root = path.join(tmp.path, "repo") + const parent = path.join(root, "packages") + const directory = path.join(parent, "app") + return Effect.gen(function* () { + yield* Effect.promise(async () => { + await fs.mkdir(global, { recursive: true }) + await fs.mkdir(directory, { recursive: true }) + await fs.mkdir(path.join(root, ".opencode"), { recursive: true }) + await fs.mkdir(path.join(directory, ".opencode"), { recursive: true }) + await Promise.all([ + fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "outside" })), + fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ $schema: "global" })), + fs.writeFile(path.join(root, "opencode.json"), JSON.stringify({ $schema: "root" })), + fs.writeFile(path.join(parent, "opencode.jsonc"), JSON.stringify({ $schema: "parent" })), + fs.writeFile(path.join(directory, "config.json"), JSON.stringify({ $schema: "directory" })), + fs.writeFile(path.join(root, ".opencode", "opencode.json"), JSON.stringify({ $schema: "root-dot" })), + fs.writeFile( + path.join(directory, ".opencode", "opencode.jsonc"), + JSON.stringify({ $schema: "directory-dot" }), + ), + ]) + }) + + return yield* Effect.gen(function* () { + const config = yield* Config.Service + const directories = yield* config.directories() + const documents = yield* config.get() + + expect(directories).toEqual([ + AbsolutePath.make(global), + AbsolutePath.make(path.join(root, ".opencode")), + AbsolutePath.make(path.join(directory, ".opencode")), + ]) + expect(documents.map((document) => document.info.$schema)).toEqual([ + "global", + "root", + "parent", + "directory", + "root-dot", + "directory-dot", + ]) + }).pipe( + Effect.provide( + testLayer(directory, global, root, { + type: "git", + store: AbsolutePath.make(path.join(root, ".git")), + }), + ), + ) + }) + }), + ), + ) +}) diff --git a/packages/core/test/config/provider.test.ts b/packages/core/test/config/provider.test.ts new file mode 100644 index 000000000000..01b8c9c9aa3d --- /dev/null +++ b/packages/core/test/config/provider.test.ts @@ -0,0 +1,131 @@ +import { describe, expect } from "bun:test" +import { Effect, Schema } from "effect" +import { Catalog } from "@opencode-ai/core/catalog" +import { Config } from "@opencode-ai/core/config" +import { ConfigProviderPlugin } from "@opencode-ai/core/config/plugin/provider" +import { ModelV2 } from "@opencode-ai/core/model" +import { PluginV2 } from "@opencode-ai/core/plugin" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { it } from "../plugin/provider-helper" + +function options(headers: Record, variant?: string) { + return { + headers, + variant, + } +} + +const decode = Schema.decodeUnknownSync(Config.Info) + +describe("ConfigProviderPlugin.Plugin", () => { + it.effect("loads configured providers and applies later model overrides", () => + Effect.gen(function* () { + const catalog = yield* Catalog.Service + const plugin = yield* PluginV2.Service + const providerID = ProviderV2.ID.make("custom") + const modelID = ModelV2.ID.make("chat") + const config = Config.Service.of({ + directories: () => Effect.succeed([]), + get: () => + Effect.succeed([ + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + providers: { + custom: { + name: "Configured", + env: ["CUSTOM_API_KEY"], + endpoint: { type: "unknown" }, + options: options({ first: "first", shared: "first" }), + models: { + chat: { + name: "First", + capabilities: { tools: true, input: ["text"], output: ["text"] }, + disabled: true, + limit: { context: 100, output: 50 }, + cost: { input: 1, output: 2 }, + options: options({ first: "first", shared: "first" }, "retained"), + variants: [ + { + id: "fast", + headers: { first: "first", shared: "first" }, + }, + ], + }, + }, + }, + }, + }), + }), + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + providers: { + custom: { + endpoint: { type: "aisdk", package: "custom-sdk", url: "https://example.test" }, + options: options({ last: "last", shared: "last" }), + models: { + chat: { + api_id: "api-chat", + name: "Last", + limit: { output: 75 }, + options: options({ last: "last", shared: "last" }), + variants: [ + { + id: "fast", + headers: { last: "last", shared: "last" }, + }, + { + id: "slow", + headers: { slow: "slow" }, + }, + ], + }, + }, + }, + }, + }), + }), + new Config.Loaded({ + source: { type: "memory" }, + info: decode({ + providers: { + custom: { name: "Renamed" }, + }, + }), + }), + ]), + }) + + yield* plugin.add({ + ...ConfigProviderPlugin.Plugin, + effect: ConfigProviderPlugin.Plugin.effect.pipe( + Effect.provideService(Config.Service, config), + Effect.provideService(Catalog.Service, catalog), + ), + }) + + const provider = yield* catalog.provider.get(providerID) + const model = yield* catalog.model.get(providerID, modelID) + expect(provider.name).toBe("Renamed") + expect(provider.env).toEqual(["CUSTOM_API_KEY"]) + expect(provider.enabled).toEqual({ via: "custom", data: {} }) + expect(provider.endpoint).toEqual({ type: "aisdk", package: "custom-sdk", url: "https://example.test" }) + expect(provider.options.headers).toEqual({ first: "first", shared: "last", last: "last" }) + expect(model.apiID).toBe(ModelV2.ID.make("api-chat")) + expect(model.name).toBe("Last") + expect(model.capabilities).toEqual({ tools: true, input: ["text"], output: ["text"] }) + expect(model.enabled).toBe(false) + expect(model.limit).toEqual({ context: 100, output: 75 }) + expect(model.cost).toEqual([{ input: 1, output: 2, cache: { read: 0, write: 0 }, tier: undefined }]) + expect(model.options.headers).toEqual({ first: "first", shared: "last", last: "last" }) + expect(model.options.variant).toBe("retained") + expect(model.variants.map((variant) => variant.id)).toEqual([ + ModelV2.VariantID.make("fast"), + ModelV2.VariantID.make("slow"), + ]) + expect(model.variants[0]?.headers).toEqual({ first: "first", shared: "last", last: "last" }) + expect(model.variants[1]?.headers).toEqual({ slow: "slow" }) + }), + ) +}) diff --git a/packages/core/test/database-migration.test.ts b/packages/core/test/database-migration.test.ts new file mode 100644 index 000000000000..316974de8c66 --- /dev/null +++ b/packages/core/test/database-migration.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, test } from "bun:test" +import { $ } from "bun" +import { fileURLToPath } from "url" +import { SqliteClient } from "@effect/sql-sqlite-bun" +import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite" +import { Effect } from "effect" +import { sql } from "drizzle-orm" +import { DatabaseMigration } from "@opencode-ai/core/database/migration" +import sessionUsageMigration from "@opencode-ai/core/database/migration/20260510033149_session_usage" +import sessionMetadataMigration from "@opencode-ai/core/database/migration/20260511173437_session-metadata" +import type { SqlClient as SqlClientService } from "effect/unstable/sql/SqlClient" + +const run = (effect: Effect.Effect) => + Effect.runPromise( + effect.pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Effect.scoped), + ) + +const makeDb = EffectDrizzleSqlite.makeWithDefaults() + +describe("DatabaseMigration", () => { + if (process.platform === "linux") { + test("declared schema has no ungenerated migrations", async () => { + const result = await $`bun ${fileURLToPath(new URL("../script/migration.ts", import.meta.url))} --check` + .quiet() + .nothrow() + expect(result.exitCode, result.stderr.toString()).toBe(0) + expect(result.stdout.toString()).toContain("No schema changes, nothing to migrate") + }, 30_000) + } + + test("applies tracked migrations to an empty database", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* DatabaseMigration.apply(db) + + expect(yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'`)).toEqual({ + name: "session", + }) + expect(yield* db.get(sql`SELECT count(*) as count FROM migration`)).toEqual({ count: 21 }) + }), + ) + }) + + test("runs session usage backfill in order with schema changes", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, time_updated integer NOT NULL)`) + yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, data text NOT NULL)`) + yield* db.run(sql`INSERT INTO session (id, time_updated) VALUES ('session_1', 1)`) + yield* db.run( + sql`INSERT INTO message (id, session_id, data) VALUES ('message_1', 'session_1', '{"role":"assistant","cost":1.25,"tokens":{"input":2,"output":3,"reasoning":4,"cache":{"read":5,"write":6}}}')`, + ) + + yield* DatabaseMigration.applyOnly(db, [sessionUsageMigration]) + + expect( + yield* db.get( + sql`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = 'session_1'`, + ), + ).toEqual({ + cost: 1.25, + tokens_input: 2, + tokens_output: 3, + tokens_reasoning: 4, + tokens_cache_read: 5, + tokens_cache_write: 6, + }) + }), + ) + }) + + test("imports existing drizzle migration state", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* db.run( + sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`, + ) + yield* db.run(sql` + INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at) + VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()}) + `) + + yield* DatabaseMigration.applyOnly(db, []) + + expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" }) + }), + ) + }) + + test("does not replay a migrated session metadata column", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`) + yield* db.run( + sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`, + ) + yield* db.run(sql` + INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at) + VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()}) + `) + + yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration]) + + expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }]) + }), + ) + }) + + test("accepts the temporary replacement session metadata migration id", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`) + yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`) + yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`) + + yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration]) + + expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([ + { id: "20260511173437_session-metadata" }, + { id: "20260530232709_lovely_romulus" }, + ]) + }), + ) + }) + + test("skips drizzle import when migration table already has state", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`) + yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`) + yield* db.run( + sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`, + ) + yield* db.run(sql` + INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at) + VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()}) + `) + + yield* DatabaseMigration.applyOnly(db, []) + + expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }]) + }), + ) + }) +}) diff --git a/packages/core/test/event.test.ts b/packages/core/test/event.test.ts index b67b2897a1b0..c3e5d2d75a8c 100644 --- a/packages/core/test/event.test.ts +++ b/packages/core/test/event.test.ts @@ -1,15 +1,21 @@ import { describe, expect } from "bun:test" import { Effect, Fiber, Layer, Schema, Stream } from "effect" import { EventV2 } from "@opencode-ai/core/event" +import { Database } from "@opencode-ai/core/database/database" +import { EventSequenceTable, EventTable } from "@opencode-ai/core/event/sql" import { Location } from "@opencode-ai/core/location" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { eq } from "drizzle-orm" +import { location } from "./fixture/location" import { testEffect } from "./lib/effect" const locationLayer = Layer.succeed( Location.Service, - Location.Service.of({ directory: "project", workspaceID: "workspace" }), + Location.Service.of(location({ directory: AbsolutePath.make("project"), workspaceID: "workspace" })), ) -const it = testEffect(EventV2.layer.pipe(Layer.provideMerge(locationLayer))) -const itWithoutLocation = testEffect(EventV2.layer) +const eventLayer = Layer.mergeAll(EventV2.defaultLayer, Database.defaultLayer) +const it = testEffect(eventLayer.pipe(Layer.provideMerge(locationLayer))) +const itWithoutLocation = testEffect(eventLayer) const Message = EventV2.define({ type: "test.message", @@ -18,6 +24,30 @@ const Message = EventV2.define({ }, }) +const SyncMessage = EventV2.define({ + type: "test.sync", + sync: { + version: 1, + aggregate: "id", + }, + schema: { + id: Schema.String, + text: Schema.String, + }, +}) + +const SyncSent = EventV2.define({ + type: "test.sent", + sync: { + version: 1, + aggregate: "messageID", + }, + schema: { + messageID: Schema.String, + text: Schema.String, + }, +}) + const GlobalMessage = EventV2.define({ type: "test.global", schema: { @@ -27,8 +57,12 @@ const GlobalMessage = EventV2.define({ const VersionedMessage = EventV2.define({ type: "test.versioned", - version: 2, + sync: { + version: 2, + aggregate: "id", + }, schema: { + id: Schema.String, text: Schema.String, }, }) @@ -46,7 +80,7 @@ describe("EventV2", () => { expect(event.type).toBe("test.message") expect(event).not.toHaveProperty("version") expect(event.data).toEqual({ text: "hello" }) - expect(event.location).toEqual({ directory: "project", workspaceID: "workspace" }) + expect(event.location).toEqual({ directory: AbsolutePath.make("project"), workspaceID: "workspace" }) }), ) @@ -63,7 +97,7 @@ describe("EventV2", () => { it.effect("publishes definition version", () => Effect.gen(function* () { const events = yield* EventV2.Service - const event = yield* events.publish(VersionedMessage, { text: "hello" }) + const event = yield* events.publish(VersionedMessage, { id: "one", text: "hello" }) expect(event.type).toBe("test.versioned") expect(event.version).toBe(2) @@ -76,6 +110,23 @@ describe("EventV2", () => { }), ) + it.effect("keeps the latest sync definition in the registry", () => + Effect.sync(() => { + const latest = EventV2.define({ + type: "test.out-of-order", + sync: { version: 2, aggregate: "id" }, + schema: { id: Schema.String }, + }) + EventV2.define({ + type: "test.out-of-order", + sync: { version: 1, aggregate: "id" }, + schema: { id: Schema.String }, + }) + + expect(EventV2.registry.get("test.out-of-order")).toBe(latest) + }), + ) + it.effect("publishes to typed and wildcard subscriptions", () => Effect.gen(function* () { const events = yield* EventV2.Service @@ -89,25 +140,25 @@ describe("EventV2", () => { }), ) - it.effect("runs sync handlers inline", () => + it.effect("runs projectors inline", () => Effect.gen(function* () { const events = yield* EventV2.Service const received = new Array() - const unsubscribe = yield* events.sync((event) => + yield* events.project(SyncMessage, (event) => Effect.sync(() => { received.push(event) }), ) - const event = yield* events.publish(Message, { text: "hello" }) - yield* unsubscribe - yield* events.publish(Message, { text: "after unsubscribe" }) + const event = yield* events.publish(SyncMessage, { id: "one", text: "hello" }) + yield* events.publish(SyncMessage, { id: "one", text: "after unsubscribe" }) - expect(received).toEqual([event]) + expect(received[0]).toEqual(event) + expect(received[1]?.data).toEqual({ id: "one", text: "after unsubscribe" }) }), ) - it.effect("runs sync handlers before publishing to streams", () => + it.effect("runs projectors before publishing to streams", () => Effect.gen(function* () { const events = yield* EventV2.Service const received = new Array() @@ -116,17 +167,410 @@ describe("EventV2", () => { Stream.runForEach(() => Effect.sync(() => received.push("stream"))), Effect.forkScoped, ) - yield* events.sync((event) => + yield* events.project(SyncMessage, (event) => Effect.sync(() => { received.push(event.type) }), ) yield* Effect.yieldNow - yield* events.publish(Message, { text: "hello" }) + yield* events.publish(SyncMessage, { id: "one", text: "hello" }) yield* Fiber.join(fiber) - expect(received).toEqual([Message.type, "stream"]) + expect(received).toEqual([SyncMessage.type, "stream"]) + }), + ) + + it.effect("runs listeners inline after projectors", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const received = new Array() + yield* events.project(SyncMessage, () => + Effect.sync(() => { + received.push("projector") + }), + ) + const unsubscribe = yield* events.listen(() => + Effect.sync(() => { + received.push("listener") + }), + ) + + yield* events.publish(SyncMessage, { id: "one", text: "hello" }) + yield* unsubscribe + yield* events.publish(SyncMessage, { id: "one", text: "after unsubscribe" }) + + expect(received).toEqual(["projector", "listener", "projector"]) + }), + ) + + it.effect("inserts sync event rows on publish", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.publish(SyncMessage, { id: aggregateID, text: "first" }) + const rows = yield* db + .select() + .from(EventTable) + .where(eq(EventTable.aggregate_id, aggregateID)) + .all() + .pipe(Effect.orDie) + + expect(rows).toHaveLength(1) + expect(rows[0]?.type).toBe(EventV2.versionedType(SyncMessage.type, 1)) + expect(rows[0]?.aggregate_id).toBe(aggregateID) + }), + ) + + it.effect("increments sync event seq per aggregate", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.publish(SyncMessage, { id: aggregateID, text: "first" }) + yield* events.publish(SyncMessage, { id: aggregateID, text: "second" }) + const rows = yield* db + .select() + .from(EventTable) + .where(eq(EventTable.aggregate_id, aggregateID)) + .all() + .pipe(Effect.orDie) + + expect(rows.map((row) => row.seq)).toEqual([0, 1]) + }), + ) + + it.effect("uses custom sync aggregate field", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.publish(SyncSent, { messageID: aggregateID, text: "sent" }) + const rows = yield* db + .select() + .from(EventTable) + .where(eq(EventTable.aggregate_id, aggregateID)) + .all() + .pipe(Effect.orDie) + + expect(rows).toHaveLength(1) + expect(rows[0]?.aggregate_id).toBe(aggregateID) + }), + ) + + it.effect("replays sync events through projectors", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const received = new Array() + yield* events.project(SyncMessage, (event) => + Effect.sync(() => { + received.push(event) + }), + ) + const aggregateID = EventV2.ID.create() + + yield* events.replay({ + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "hello" }, + }) + + expect(received[0]?.type).toBe(SyncMessage.type) + expect(received[0]?.data).toEqual({ id: aggregateID, text: "hello" }) + }), + ) + + it.effect("replay inserts external event rows", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.replay({ + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "replayed" }, + }) + const rows = yield* db + .select() + .from(EventTable) + .where(eq(EventTable.aggregate_id, aggregateID)) + .all() + .pipe(Effect.orDie) + + expect(rows).toHaveLength(1) + expect(rows[0]?.aggregate_id).toBe(aggregateID) + }), + ) + + it.effect("replay defects on sequence mismatch", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const aggregateID = EventV2.ID.create() + + yield* events.replay({ + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "first" }, + }) + const exit = yield* events + .replay({ + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 5, + aggregateID, + data: { id: aggregateID, text: "bad" }, + }) + .pipe(Effect.exit) + + expect(String(exit)).toContain("Sequence mismatch") + }), + ) + + it.effect("replay defects on unknown event type", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const exit = yield* events + .replay({ + id: EventV2.ID.create(), + type: "unknown.event.1", + seq: 0, + aggregateID: EventV2.ID.create(), + data: {}, + }) + .pipe(Effect.exit) + + expect(String(exit)).toContain("Unknown sync event type") + }), + ) + + it.effect("replayAll validates contiguous aggregate events", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const aggregateID = EventV2.ID.create() + const source = yield* events.replayAll([ + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "one" }, + }, + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 1, + aggregateID, + data: { id: aggregateID, text: "two" }, + }, + ]) + + expect(source).toBe(aggregateID) + }), + ) + + it.effect("replayAll accepts later chunks after the first batch", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + const one = yield* events.replayAll([ + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "one" }, + }, + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 1, + aggregateID, + data: { id: aggregateID, text: "two" }, + }, + ]) + const two = yield* events.replayAll([ + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 2, + aggregateID, + data: { id: aggregateID, text: "three" }, + }, + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 3, + aggregateID, + data: { id: aggregateID, text: "four" }, + }, + ]) + const rows = yield* db + .select() + .from(EventTable) + .where(eq(EventTable.aggregate_id, aggregateID)) + .all() + .pipe(Effect.orDie) + + expect(one).toBe(aggregateID) + expect(two).toBe(aggregateID) + expect(rows.map((row) => row.seq)).toEqual([0, 1, 2, 3]) + }), + ) + + it.effect("claim fences replay owners", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const received = new Array() + const aggregateID = EventV2.ID.create() + yield* events.publish(SyncMessage, { id: aggregateID, text: "seed" }) + yield* events.claim(aggregateID, "owner-a") + yield* events.project(SyncMessage, (event) => + Effect.sync(() => { + received.push(event) + }), + ) + + yield* events.replay( + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 1, + aggregateID, + data: { id: aggregateID, text: "ignored" }, + }, + { ownerID: "owner-b" }, + ) + + expect(received).toHaveLength(0) + }), + ) + + it.effect("replay with owner claims an unowned sequence", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.replay( + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "owned" }, + }, + { ownerID: "owner-1" }, + ) + const row = yield* db + .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) + .from(EventSequenceTable) + .where(eq(EventSequenceTable.aggregate_id, aggregateID)) + .get() + .pipe(Effect.orDie) + + expect(row).toEqual({ seq: 0, ownerID: "owner-1" }) + }), + ) + + it.effect("replay from a different owner leaves claimed sequence unchanged", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.replay( + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "first" }, + }, + { ownerID: "owner-1" }, + ) + yield* events.replay( + { + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 1, + aggregateID, + data: { id: aggregateID, text: "ignored" }, + }, + { ownerID: "owner-2" }, + ) + const rows = yield* db + .select() + .from(EventTable) + .where(eq(EventTable.aggregate_id, aggregateID)) + .all() + .pipe(Effect.orDie) + const sequence = yield* db + .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) + .from(EventSequenceTable) + .where(eq(EventSequenceTable.aggregate_id, aggregateID)) + .get() + .pipe(Effect.orDie) + + expect(rows).toHaveLength(1) + expect(sequence).toEqual({ seq: 0, ownerID: "owner-1" }) + }), + ) + + it.effect("claim updates the event sequence owner", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const { db } = yield* Database.Service + const aggregateID = EventV2.ID.create() + + yield* events.publish(SyncMessage, { id: aggregateID, text: "claimed" }) + yield* events.claim(aggregateID, "owner-1") + yield* events.claim(aggregateID, "owner-2") + const row = yield* db + .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) + .from(EventSequenceTable) + .where(eq(EventSequenceTable.aggregate_id, aggregateID)) + .get() + .pipe(Effect.orDie) + + expect(row).toEqual({ seq: 0, ownerID: "owner-2" }) + }), + ) + + it.effect("remove clears sync event sequence", () => + Effect.gen(function* () { + const events = yield* EventV2.Service + const received = new Array() + const aggregateID = EventV2.ID.create() + yield* events.publish(SyncMessage, { id: aggregateID, text: "seed" }) + yield* events.remove(aggregateID) + yield* events.project(SyncMessage, (event) => + Effect.sync(() => { + received.push(event) + }), + ) + + yield* events.replay({ + id: EventV2.ID.create(), + type: EventV2.versionedType(SyncMessage.type, 1), + seq: 0, + aggregateID, + data: { id: aggregateID, text: "replayed" }, + }) + + expect(received[0]?.data).toEqual({ id: aggregateID, text: "replayed" }) }), ) }) diff --git a/packages/core/test/fixture/location.ts b/packages/core/test/fixture/location.ts new file mode 100644 index 000000000000..00b3ffbd13f0 --- /dev/null +++ b/packages/core/test/fixture/location.ts @@ -0,0 +1,12 @@ +import { Location } from "@opencode-ai/core/location" +import { Project } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" + +export function location(ref: Location.Ref, input: { projectDirectory?: AbsolutePath; vcs?: Project.Vcs } = {}) { + return { + directory: ref.directory, + workspaceID: ref.workspaceID, + project: { id: Project.ID.global, directory: input.projectDirectory ?? ref.directory }, + vcs: input.vcs, + } satisfies Location.Interface +} diff --git a/packages/core/test/location-layer.test.ts b/packages/core/test/location-layer.test.ts new file mode 100644 index 000000000000..19ab93121261 --- /dev/null +++ b/packages/core/test/location-layer.test.ts @@ -0,0 +1,72 @@ +import fs from "fs/promises" +import path from "path" +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { Catalog } from "@opencode-ai/core/catalog" +import { LocationServiceMap } from "@opencode-ai/core/location-layer" +import { PluginBoot } from "@opencode-ai/core/plugin/boot" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { tmpdir } from "./fixture/tmpdir" +import { testEffect } from "./lib/effect" +import { AppFileSystem } from "../src/filesystem" +import { Auth } from "../src/auth" +import { EventV2 } from "../src/event" +import { Global } from "../src/global" +import { ModelsDev } from "../src/models-dev" +import { Npm } from "../src/npm" +import { Project } from "../src/project" + +const it = testEffect( + LocationServiceMap.layer.pipe( + Layer.provide( + Layer.mergeAll( + Project.defaultLayer, + EventV2.defaultLayer, + Auth.defaultLayer, + Npm.defaultLayer, + ModelsDev.defaultLayer, + AppFileSystem.defaultLayer, + Global.defaultLayer, + ), + ), + ), +) + +describe("LocationServiceMap", () => { + it.live("isolates location state while sharing location policy with catalog", () => + Effect.acquireRelease( + Effect.promise(() => Promise.all([tmpdir(), tmpdir()])), + (dirs) => Effect.promise(() => Promise.all(dirs.map((dir) => dir[Symbol.asyncDispose]())).then(() => undefined)), + ).pipe( + Effect.flatMap(([blocked, allowed]) => + Effect.gen(function* () { + yield* Effect.promise(() => + fs.writeFile( + path.join(blocked.path, "opencode.json"), + JSON.stringify({ + experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "test" }] }, + }), + ), + ) + + const update = (directory: string) => + Effect.gen(function* () { + yield* PluginBoot.Service.use((boot) => boot.wait()) + const catalog = yield* Catalog.Service + const transform = yield* catalog.transform() + yield* transform((editor) => editor.provider.update(ProviderV2.ID.make("test"), () => {})) + return yield* catalog.provider.all() + }).pipe(Effect.scoped, Effect.provide(LocationServiceMap.get({ directory: AbsolutePath.make(directory) }))) + + expect((yield* update(blocked.path)).some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe( + false, + ) + expect((yield* update(allowed.path)).some((provider) => provider.id === ProviderV2.ID.make("test"))).toBe( + true, + ) + }), + ), + ), + ) +}) diff --git a/packages/core/test/location.test.ts b/packages/core/test/location.test.ts new file mode 100644 index 000000000000..305083bfedd4 --- /dev/null +++ b/packages/core/test/location.test.ts @@ -0,0 +1,38 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { Location } from "@opencode-ai/core/location" +import { Project } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { testEffect } from "./lib/effect" + +const ref = { directory: AbsolutePath.make("/repo/packages/app"), workspaceID: "workspace" } +const projectLayer = Layer.succeed( + Project.Service, + Project.Service.of({ + resolve: () => + Effect.succeed({ + id: Project.ID.make("project"), + directory: AbsolutePath.make("/repo"), + vcs: { type: "git", store: AbsolutePath.make("/repo/.git") }, + }), + commit: () => Effect.void, + }), +) +const it = testEffect(Location.layer(ref).pipe(Layer.provide(projectLayer))) + +describe("Location", () => { + it.effect("resolves the current project and vcs information", () => + Effect.gen(function* () { + const location = yield* Location.Service + + expect(location.directory).toBe(AbsolutePath.make("/repo/packages/app")) + expect(location.workspaceID).toBe("workspace") + expect(location.project.id).toBe(Project.ID.make("project")) + expect(location.project.directory).toBe(AbsolutePath.make("/repo")) + expect(location.vcs).toEqual({ + type: "git", + store: AbsolutePath.make("/repo/.git"), + }) + }), + ) +}) diff --git a/packages/core/test/model.test.ts b/packages/core/test/model.test.ts new file mode 100644 index 000000000000..fe97acc25aad --- /dev/null +++ b/packages/core/test/model.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" +import { ModelV2 } from "@opencode-ai/core/model" +import { ProviderV2 } from "@opencode-ai/core/provider" + +const decode = Schema.decodeUnknownSync(ModelV2.Ref) + +describe("ModelV2.Ref", () => { + test("accepts a model selection without a variant", () => { + expect(decode({ id: "claude-sonnet", providerID: "anthropic" })).toEqual({ + id: ModelV2.ID.make("claude-sonnet"), + providerID: ProviderV2.ID.make("anthropic"), + }) + }) + + test("preserves an explicit model variant", () => { + expect(decode({ id: "claude-sonnet", providerID: "anthropic", variant: "high" })).toEqual({ + id: ModelV2.ID.make("claude-sonnet"), + providerID: ProviderV2.ID.make("anthropic"), + variant: ModelV2.VariantID.make("high"), + }) + }) +}) diff --git a/packages/core/test/plugin/provider-amazon-bedrock.test.ts b/packages/core/test/plugin/provider-amazon-bedrock.test.ts index f2034eb1e321..602e85624b79 100644 --- a/packages/core/test/plugin/provider-amazon-bedrock.test.ts +++ b/packages/core/test/plugin/provider-amazon-bedrock.test.ts @@ -24,8 +24,8 @@ describe("AmazonBedrockPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AmazonBedrockPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const bedrock = provider("amazon-bedrock", { endpoint: { type: "aisdk", package: "@ai-sdk/amazon-bedrock" }, options: { diff --git a/packages/core/test/plugin/provider-anthropic.test.ts b/packages/core/test/plugin/provider-anthropic.test.ts index 0a1d5662d375..6cae612fd227 100644 --- a/packages/core/test/plugin/provider-anthropic.test.ts +++ b/packages/core/test/plugin/provider-anthropic.test.ts @@ -12,8 +12,8 @@ describe("AnthropicPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AnthropicPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("anthropic", { endpoint: { type: "aisdk", package: "@ai-sdk/anthropic" }, options: { headers: { Existing: "1" }, body: {}, aisdk: { provider: {}, request: {} } }, @@ -35,8 +35,8 @@ describe("AnthropicPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AnthropicPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => catalog.provider.update(provider("openai").id, () => {})) + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(provider("openai").id, () => {})) expect((yield* catalog.provider.get(ProviderV2.ID.openai)).options.headers["anthropic-beta"]).toBeUndefined() }), ) diff --git a/packages/core/test/plugin/provider-azure-cognitive-services.test.ts b/packages/core/test/plugin/provider-azure-cognitive-services.test.ts index 8b8baacb7ecb..a3837a66ad99 100644 --- a/packages/core/test/plugin/provider-azure-cognitive-services.test.ts +++ b/packages/core/test/plugin/provider-azure-cognitive-services.test.ts @@ -13,8 +13,8 @@ describe("AzureCognitiveServicesPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AzureCognitiveServicesPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.make("azure-cognitive-services"), (item) => { item.endpoint = { type: "aisdk", package: "@ai-sdk/openai-compatible" } }) @@ -37,8 +37,8 @@ describe("AzureCognitiveServicesPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AzureCognitiveServicesPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const azure = provider("azure-cognitive-services", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible" }, }) diff --git a/packages/core/test/plugin/provider-azure.test.ts b/packages/core/test/plugin/provider-azure.test.ts index 8c8995a372c9..1b917c5af8f3 100644 --- a/packages/core/test/plugin/provider-azure.test.ts +++ b/packages/core/test/plugin/provider-azure.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" -import { AccountV2 } from "@opencode-ai/core/account" +import { Auth } from "@opencode-ai/core/auth" import { Catalog } from "@opencode-ai/core/catalog" import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" @@ -8,15 +8,18 @@ import { PluginV2 } from "@opencode-ai/core/plugin" import { AccountPlugin } from "@opencode-ai/core/plugin/account" import { AzurePlugin } from "@opencode-ai/core/plugin/provider/azure" import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "../fixture/location" import { testEffect } from "../lib/effect" import { fakeSelectorSdk, it, model, npmLayer, provider, withEnv } from "./provider-helper" const itWithAccount = testEffect( - Catalog.layer.pipe( - Layer.provideMerge(PluginV2.defaultLayer), - Layer.provideMerge(AccountV2.defaultLayer), + Catalog.locationLayer.pipe( + Layer.provideMerge(Auth.defaultLayer), Layer.provideMerge(EventV2.defaultLayer), - Layer.provideMerge(Layer.succeed(Location.Service, Location.Service.of({ directory: "test" }))), + Layer.provideMerge( + Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make("test") }))), + ), Layer.provideMerge(npmLayer), ), ) @@ -28,8 +31,8 @@ describe("AzurePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AzurePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.azure, (item) => { item.endpoint = { type: "aisdk", package: "@ai-sdk/azure" } }) @@ -45,8 +48,8 @@ describe("AzurePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AzurePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const azure = provider("azure", { endpoint: { type: "aisdk", package: "@ai-sdk/azure" }, options: { headers: {}, body: {}, aisdk: { provider: { resourceName: "from-config" }, request: {} } }, @@ -73,12 +76,12 @@ describe("AzurePlugin", () => { () => Effect.gen(function* () { const plugin = yield* PluginV2.Service - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const catalog = yield* Catalog.Service const events = yield* EventV2.Service yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("azure"), - credential: new AccountV2.ApiKeyCredential({ + serviceID: Auth.ServiceID.make("azure"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "key", metadata: { resourceName: "from-account" }, @@ -87,15 +90,15 @@ describe("AzurePlugin", () => { yield* plugin.add({ ...AccountPlugin, effect: AccountPlugin.effect.pipe( - Effect.provideService(AccountV2.Service, accounts), + Effect.provideService(Auth.Service, accounts), Effect.provideService(Catalog.Service, catalog), Effect.provideService(EventV2.Service, events), Effect.provideService(PluginV2.Service, plugin), ), }) yield* plugin.add(AzurePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.azure, (item) => { item.endpoint = { type: "aisdk", package: "@ai-sdk/azure" } }) @@ -113,8 +116,8 @@ describe("AzurePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AzurePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const azure = provider("azure", { endpoint: { type: "aisdk", package: "@ai-sdk/azure" }, options: { headers: {}, body: {}, aisdk: { provider: { resourceName: "" }, request: {} } }, @@ -135,8 +138,8 @@ describe("AzurePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(AzurePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const azure = provider("azure", { endpoint: { type: "aisdk", package: "@ai-sdk/azure" }, options: { headers: {}, body: {}, aisdk: { provider: { resourceName: " " }, request: {} } }, diff --git a/packages/core/test/plugin/provider-cerebras.test.ts b/packages/core/test/plugin/provider-cerebras.test.ts index dd8d34c7df0a..982b587a71b8 100644 --- a/packages/core/test/plugin/provider-cerebras.test.ts +++ b/packages/core/test/plugin/provider-cerebras.test.ts @@ -24,8 +24,8 @@ describe("CerebrasPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(CerebrasPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.make("cerebras"), (item) => { item.endpoint = { type: "aisdk", package: "@ai-sdk/cerebras" } item.options.headers.Existing = "1" @@ -43,8 +43,8 @@ describe("CerebrasPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(CerebrasPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => catalog.provider.update(ProviderV2.ID.make("groq"), () => {})) + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("groq"), () => {})) expect((yield* catalog.provider.get(ProviderV2.ID.make("groq"))).options.headers).toEqual({}) }), ) diff --git a/packages/core/test/plugin/provider-cloudflare-workers-ai.test.ts b/packages/core/test/plugin/provider-cloudflare-workers-ai.test.ts index d1db7b27a1ce..980269b37e2b 100644 --- a/packages/core/test/plugin/provider-cloudflare-workers-ai.test.ts +++ b/packages/core/test/plugin/provider-cloudflare-workers-ai.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" -import { AccountV2 } from "@opencode-ai/core/account" +import { Auth } from "@opencode-ai/core/auth" import { Catalog } from "@opencode-ai/core/catalog" import { Location } from "@opencode-ai/core/location" import { EventV2 } from "@opencode-ai/core/event" @@ -9,15 +9,18 @@ import { PluginV2 } from "@opencode-ai/core/plugin" import { AccountPlugin } from "@opencode-ai/core/plugin/account" import { CloudflareWorkersAIPlugin } from "@opencode-ai/core/plugin/provider/cloudflare-workers-ai" import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "../fixture/location" import { testEffect } from "../lib/effect" import { fakeSelectorSdk, it, model, npmLayer, withEnv } from "./provider-helper" const itWithAccount = testEffect( - Catalog.layer.pipe( - Layer.provideMerge(PluginV2.defaultLayer), - Layer.provideMerge(AccountV2.defaultLayer), + Catalog.locationLayer.pipe( + Layer.provideMerge(Auth.defaultLayer), Layer.provideMerge(EventV2.defaultLayer), - Layer.provideMerge(Layer.succeed(Location.Service, Location.Service.of({ directory: "test" }))), + Layer.provideMerge( + Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make("test") }))), + ), Layer.provideMerge(npmLayer), ), ) @@ -48,8 +51,8 @@ describe("CloudflareWorkersAIPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(CloudflareWorkersAIPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("cloudflare-workers-ai"), (provider) => { provider.endpoint = { type: "aisdk", package: "test-provider" } }), @@ -80,8 +83,8 @@ describe("CloudflareWorkersAIPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(CloudflareWorkersAIPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("cloudflare-workers-ai"), (provider) => { provider.endpoint = { type: "aisdk", package: "test-provider", url: "https://proxy.example/v1" } }), @@ -125,12 +128,12 @@ describe("CloudflareWorkersAIPlugin", () => { () => Effect.gen(function* () { const plugin = yield* PluginV2.Service - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const catalog = yield* Catalog.Service const events = yield* EventV2.Service yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("cloudflare-workers-ai"), - credential: new AccountV2.ApiKeyCredential({ + serviceID: Auth.ServiceID.make("cloudflare-workers-ai"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "account-key", metadata: { accountId: "account-acct" }, @@ -139,15 +142,15 @@ describe("CloudflareWorkersAIPlugin", () => { yield* plugin.add({ ...AccountPlugin, effect: AccountPlugin.effect.pipe( - Effect.provideService(AccountV2.Service, accounts), + Effect.provideService(Auth.Service, accounts), Effect.provideService(Catalog.Service, catalog), Effect.provideService(EventV2.Service, events), Effect.provideService(PluginV2.Service, plugin), ), }) yield* plugin.add(CloudflareWorkersAIPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("cloudflare-workers-ai"), (provider) => { provider.endpoint = { type: "aisdk", package: "test-provider" } }), @@ -167,8 +170,8 @@ describe("CloudflareWorkersAIPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(CloudflareWorkersAIPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("cloudflare-workers-ai"), (provider) => { provider.endpoint = { type: "aisdk", package: "test-provider" } provider.options.aisdk.provider.accountId = "configured-acct" diff --git a/packages/core/test/plugin/provider-deepinfra.test.ts b/packages/core/test/plugin/provider-deepinfra.test.ts index 9a9cb861eaf8..234127236508 100644 --- a/packages/core/test/plugin/provider-deepinfra.test.ts +++ b/packages/core/test/plugin/provider-deepinfra.test.ts @@ -1,12 +1,15 @@ import { describe, expect, mock } from "bun:test" import { Effect, Layer } from "effect" import { AISDK } from "@opencode-ai/core/aisdk" +import { EventV2 } from "@opencode-ai/core/event" import { PluginV2 } from "@opencode-ai/core/plugin" import { DeepInfraPlugin } from "@opencode-ai/core/plugin/provider/deepinfra" import { testEffect } from "../lib/effect" import { it, model } from "./provider-helper" -const itAISDK = testEffect(Layer.provideMerge(AISDK.layer, PluginV2.defaultLayer)) +const itAISDK = testEffect( + Layer.provideMerge(AISDK.layer, PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer))), +) const deepinfraOptions: Record[] = [] const deepinfraLanguageModels: string[] = [] diff --git a/packages/core/test/plugin/provider-dynamic.test.ts b/packages/core/test/plugin/provider-dynamic.test.ts index c15568eebd15..d0e7c80e7d96 100644 --- a/packages/core/test/plugin/provider-dynamic.test.ts +++ b/packages/core/test/plugin/provider-dynamic.test.ts @@ -6,6 +6,7 @@ import os from "os" import path from "path" import { fileURLToPath } from "url" import { AISDK } from "@opencode-ai/core/aisdk" +import { EventV2 } from "@opencode-ai/core/event" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { DynamicProviderPlugin } from "@opencode-ai/core/plugin/provider/dynamic" @@ -13,7 +14,9 @@ import { testEffect } from "../lib/effect" import { fixtureProvider, it, model, npmLayer } from "./provider-helper" const fixtureProviderPath = fileURLToPath(fixtureProvider) -const itWithAISDK = testEffect(AISDK.layer.pipe(Layer.provideMerge(PluginV2.defaultLayer))) +const itWithAISDK = testEffect( + AISDK.layer.pipe(Layer.provideMerge(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer)))), +) function npmEntrypointLayer(entrypoint: Option.Option) { return Layer.succeed( diff --git a/packages/core/test/plugin/provider-github-copilot.test.ts b/packages/core/test/plugin/provider-github-copilot.test.ts index 51822c26ac45..c07f70597ab6 100644 --- a/packages/core/test/plugin/provider-github-copilot.test.ts +++ b/packages/core/test/plugin/provider-github-copilot.test.ts @@ -152,8 +152,8 @@ describe("GithubCopilotPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GithubCopilotPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.make("github-copilot"), () => {}) catalog.model.update(ProviderV2.ID.make("github-copilot"), ModelV2.ID.make("gpt-5-chat-latest"), () => {}) }) @@ -168,8 +168,8 @@ describe("GithubCopilotPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GithubCopilotPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.make("custom-copilot"), () => {}) catalog.model.update(ProviderV2.ID.make("custom-copilot"), ModelV2.ID.make("gpt-5-chat-latest"), () => {}) }) diff --git a/packages/core/test/plugin/provider-gitlab.test.ts b/packages/core/test/plugin/provider-gitlab.test.ts index e785fbbb7fbe..b2cba8e465df 100644 --- a/packages/core/test/plugin/provider-gitlab.test.ts +++ b/packages/core/test/plugin/provider-gitlab.test.ts @@ -1,6 +1,6 @@ import { describe, expect, mock } from "bun:test" import { Effect, Layer } from "effect" -import { AccountV2 } from "@opencode-ai/core/account" +import { Auth } from "@opencode-ai/core/auth" import { Catalog } from "@opencode-ai/core/catalog" import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" @@ -8,6 +8,8 @@ import { PluginV2 } from "@opencode-ai/core/plugin" import { AccountPlugin } from "@opencode-ai/core/plugin/account" import { GitLabPlugin } from "@opencode-ai/core/plugin/provider/gitlab" import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "../fixture/location" import { testEffect } from "../lib/effect" import { it, model, npmLayer, withEnv } from "./provider-helper" @@ -27,11 +29,12 @@ void mock.module("gitlab-ai-provider", () => ({ })) const itWithAccount = testEffect( - Catalog.layer.pipe( - Layer.provideMerge(PluginV2.defaultLayer), - Layer.provideMerge(AccountV2.defaultLayer), + Catalog.locationLayer.pipe( + Layer.provideMerge(Auth.defaultLayer), Layer.provideMerge(EventV2.defaultLayer), - Layer.provideMerge(Layer.succeed(Location.Service, Location.Service.of({ directory: "test" }))), + Layer.provideMerge( + Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make("/") }))), + ), Layer.provideMerge(npmLayer), ), ) @@ -162,25 +165,25 @@ describe("GitLabPlugin", () => { Effect.gen(function* () { gitlabSDKOptions.length = 0 const plugin = yield* PluginV2.Service - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const catalog = yield* Catalog.Service const events = yield* EventV2.Service yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("gitlab"), - credential: new AccountV2.ApiKeyCredential({ type: "api", key: "account-token" }), + serviceID: Auth.ServiceID.make("gitlab"), + credential: new Auth.ApiKeyCredential({ type: "api", key: "account-token" }), }) yield* plugin.add({ ...AccountPlugin, effect: AccountPlugin.effect.pipe( - Effect.provideService(AccountV2.Service, accounts), + Effect.provideService(Auth.Service, accounts), Effect.provideService(Catalog.Service, catalog), Effect.provideService(EventV2.Service, events), Effect.provideService(PluginV2.Service, plugin), ), }) yield* plugin.add(GitLabPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => catalog.provider.update(ProviderV2.ID.make("gitlab"), () => {})) + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("gitlab"), () => {})) const provider = yield* catalog.provider.get(ProviderV2.ID.make("gitlab")) yield* plugin.trigger( "aisdk.sdk", @@ -205,12 +208,12 @@ describe("GitLabPlugin", () => { Effect.gen(function* () { gitlabSDKOptions.length = 0 const plugin = yield* PluginV2.Service - const accounts = yield* AccountV2.Service + const accounts = yield* Auth.Service const catalog = yield* Catalog.Service const events = yield* EventV2.Service yield* accounts.create({ - serviceID: AccountV2.ServiceID.make("gitlab"), - credential: new AccountV2.OAuthCredential({ + serviceID: Auth.ServiceID.make("gitlab"), + credential: new Auth.OAuthCredential({ type: "oauth", refresh: "refresh-token", access: "account-oauth-token", @@ -220,15 +223,15 @@ describe("GitLabPlugin", () => { yield* plugin.add({ ...AccountPlugin, effect: AccountPlugin.effect.pipe( - Effect.provideService(AccountV2.Service, accounts), + Effect.provideService(Auth.Service, accounts), Effect.provideService(Catalog.Service, catalog), Effect.provideService(EventV2.Service, events), Effect.provideService(PluginV2.Service, plugin), ), }) yield* plugin.add(GitLabPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => catalog.provider.update(ProviderV2.ID.make("gitlab"), () => {})) + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("gitlab"), () => {})) const provider = yield* catalog.provider.get(ProviderV2.ID.make("gitlab")) yield* plugin.trigger( "aisdk.sdk", diff --git a/packages/core/test/plugin/provider-google-vertex-anthropic.test.ts b/packages/core/test/plugin/provider-google-vertex-anthropic.test.ts index 7cb2b24ffd68..9d23dfefb35f 100644 --- a/packages/core/test/plugin/provider-google-vertex-anthropic.test.ts +++ b/packages/core/test/plugin/provider-google-vertex-anthropic.test.ts @@ -22,8 +22,8 @@ describe("GoogleVertexAnthropicPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexAnthropicPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex-anthropic"), (provider) => { provider.endpoint = { type: "aisdk", package: "@ai-sdk/google-vertex/anthropic" } }), @@ -41,8 +41,8 @@ describe("GoogleVertexAnthropicPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexAnthropicPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex-anthropic"), (provider) => { provider.endpoint = { type: "aisdk", package: "@ai-sdk/google-vertex/anthropic" } provider.options.aisdk.provider.project = "configured-project" diff --git a/packages/core/test/plugin/provider-google-vertex.test.ts b/packages/core/test/plugin/provider-google-vertex.test.ts index 2a9a18875c28..2abb342cc381 100644 --- a/packages/core/test/plugin/provider-google-vertex.test.ts +++ b/packages/core/test/plugin/provider-google-vertex.test.ts @@ -7,6 +7,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider" import { fakeSelectorSdk, it, model, withEnv } from "./provider-helper" const vertexOptions: Record[] = [] +const googleAuthOptions: Record[] = [] void mock.module("@ai-sdk/google-vertex", () => ({ createVertex: (options: Record) => { @@ -19,12 +20,14 @@ void mock.module("@ai-sdk/google-vertex", () => ({ void mock.module("google-auth-library", () => ({ GoogleAuth: class { - async getApplicationDefault() { + constructor(options: Record) { + googleAuthOptions.push(options) + } + + async getClient() { return { - credential: { - async getAccessToken() { - return { token: "vertex-token" } - }, + async getAccessToken() { + return { token: "vertex-token" } }, } } @@ -47,8 +50,8 @@ describe("GoogleVertexPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex"), (provider) => { provider.endpoint = { type: "aisdk", @@ -86,8 +89,8 @@ describe("GoogleVertexPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex"), (provider) => { provider.endpoint = { type: "aisdk", @@ -136,8 +139,8 @@ describe("GoogleVertexPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex"), (provider) => { provider.endpoint = { type: "aisdk", @@ -165,8 +168,8 @@ describe("GoogleVertexPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex"), (provider) => { provider.endpoint = { type: "aisdk", @@ -201,8 +204,8 @@ describe("GoogleVertexPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(GoogleVertexPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(ProviderV2.ID.make("google-vertex"), (provider) => { provider.endpoint = { type: "aisdk", package: "@ai-sdk/google-vertex" } provider.options.aisdk.provider.project = "config-project" @@ -247,6 +250,7 @@ describe("GoogleVertexPlugin", () => { it.effect("keeps Google auth fetch for OpenAI-compatible Vertex endpoints", () => Effect.gen(function* () { + googleAuthOptions.length = 0 const fetchCalls: { input: Parameters[0]; init?: RequestInit }[] = [] const plugin = yield* PluginV2.Service yield* plugin.add(GoogleVertexPlugin) @@ -292,6 +296,7 @@ describe("GoogleVertexPlugin", () => { }), ) expect(fetchCalls).toHaveLength(1) + expect(googleAuthOptions).toEqual([{ scopes: ["https://www.googleapis.com/auth/cloud-platform"] }]) expect(fetchCalls[0].input).toBe("https://vertex.example") expect(new Headers(fetchCalls[0].init?.headers).get("authorization")).toBe("Bearer vertex-token") expect(new Headers(fetchCalls[0].init?.headers).get("x-test")).toBe("1") diff --git a/packages/core/test/plugin/provider-google.test.ts b/packages/core/test/plugin/provider-google.test.ts index fdb7bf75eeaf..8844208e4bd8 100644 --- a/packages/core/test/plugin/provider-google.test.ts +++ b/packages/core/test/plugin/provider-google.test.ts @@ -1,13 +1,16 @@ import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" import { AISDK } from "@opencode-ai/core/aisdk" +import { EventV2 } from "@opencode-ai/core/event" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { GooglePlugin } from "@opencode-ai/core/plugin/provider/google" import { testEffect } from "../lib/effect" import { it, model } from "./provider-helper" -const itWithAISDK = testEffect(AISDK.layer.pipe(Layer.provideMerge(PluginV2.defaultLayer))) +const itWithAISDK = testEffect( + AISDK.layer.pipe(Layer.provideMerge(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer)))), +) describe("GooglePlugin", () => { it.effect("creates a Google Generative AI SDK for @ai-sdk/google using the provider ID as SDK name", () => diff --git a/packages/core/test/plugin/provider-groq.test.ts b/packages/core/test/plugin/provider-groq.test.ts index 579d70da59a3..0eb3f538b8a0 100644 --- a/packages/core/test/plugin/provider-groq.test.ts +++ b/packages/core/test/plugin/provider-groq.test.ts @@ -2,13 +2,16 @@ import { describe, expect } from "bun:test" import { createGroq } from "@ai-sdk/groq" import { Effect, Layer } from "effect" import { AISDK } from "@opencode-ai/core/aisdk" +import { EventV2 } from "@opencode-ai/core/event" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { GroqPlugin } from "@opencode-ai/core/plugin/provider/groq" import { it, model } from "./provider-helper" import { testEffect } from "../lib/effect" -const aisdkIt = testEffect(AISDK.layer.pipe(Layer.provideMerge(PluginV2.defaultLayer))) +const aisdkIt = testEffect( + AISDK.layer.pipe(Layer.provideMerge(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer)))), +) describe("GroqPlugin", () => { it.effect("creates a Groq SDK for @ai-sdk/groq", () => diff --git a/packages/core/test/plugin/provider-helper.ts b/packages/core/test/plugin/provider-helper.ts index 1b8f1c65a020..f99510ac7085 100644 --- a/packages/core/test/plugin/provider-helper.ts +++ b/packages/core/test/plugin/provider-helper.ts @@ -8,10 +8,15 @@ import { Location } from "@opencode-ai/core/location" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "../fixture/location" import { testEffect } from "../lib/effect" export const fixtureProvider = new URL("./fixtures/provider-factory.ts", import.meta.url).href -const locationLayer = Layer.succeed(Location.Service, Location.Service.of({ directory: "test" })) +const locationLayer = Layer.succeed( + Location.Service, + Location.Service.of(location({ directory: AbsolutePath.make("test") })), +) export const npmLayer = Layer.succeed( Npm.Service, @@ -25,7 +30,7 @@ export const npmLayer = Layer.succeed( export const catalogLayer = Layer.succeed( Catalog.Service, Catalog.Service.of({ - loader: () => Effect.die("unexpected catalog.loader"), + transform: () => Effect.die("unexpected catalog.transform"), provider: { get: () => Effect.die("unexpected provider.get"), all: () => Effect.succeed([]), @@ -36,15 +41,13 @@ export const catalogLayer = Layer.succeed( all: () => Effect.succeed([]), available: () => Effect.succeed([]), default: () => Effect.succeed(Option.none()), - setDefault: () => Effect.die("unexpected model.setDefault"), small: () => Effect.succeed(Option.none()), }, }), ) export const it = testEffect( - Catalog.layer.pipe( - Layer.provideMerge(PluginV2.defaultLayer), + Catalog.locationLayer.pipe( Layer.provideMerge(EventV2.defaultLayer), Layer.provideMerge(locationLayer), Layer.provideMerge(npmLayer), diff --git a/packages/core/test/plugin/provider-kilo.test.ts b/packages/core/test/plugin/provider-kilo.test.ts index cafe4c10f61b..ac3cc172a2ff 100644 --- a/packages/core/test/plugin/provider-kilo.test.ts +++ b/packages/core/test/plugin/provider-kilo.test.ts @@ -22,8 +22,8 @@ describe("KiloPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(KiloPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const kilo = provider("kilo", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://api.kilo.ai/api/gateway" }, options: { headers: { Existing: "value" }, body: {}, aisdk: { provider: {}, request: {} } }, @@ -48,8 +48,8 @@ describe("KiloPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(KiloPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("kilo", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://api.kilo.ai/api/gateway" }, }) @@ -74,8 +74,8 @@ describe("KiloPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(KiloPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const kilo = provider("kilo", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://api.kilo.ai/api/gateway" }, }) diff --git a/packages/core/test/plugin/provider-llmgateway.test.ts b/packages/core/test/plugin/provider-llmgateway.test.ts index f34b7b3fcc0f..980abe225830 100644 --- a/packages/core/test/plugin/provider-llmgateway.test.ts +++ b/packages/core/test/plugin/provider-llmgateway.test.ts @@ -22,8 +22,8 @@ describe("LLMGatewayPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(LLMGatewayPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const llmgateway = provider("llmgateway", { enabled: { via: "env", name: "LLMGATEWAY_API_KEY" }, endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://api.llmgateway.io/v1" }, @@ -56,8 +56,8 @@ describe("LLMGatewayPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(LLMGatewayPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("llmgateway", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://api.llmgateway.io/v1" }, }) diff --git a/packages/core/test/plugin/provider-nvidia.test.ts b/packages/core/test/plugin/provider-nvidia.test.ts index 8bd9051bd8b6..dea0000717c2 100644 --- a/packages/core/test/plugin/provider-nvidia.test.ts +++ b/packages/core/test/plugin/provider-nvidia.test.ts @@ -22,8 +22,8 @@ describe("NvidiaPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(NvidiaPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const nvidia = provider("nvidia", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://integrate.api.nvidia.com/v1" }, options: { headers: { Existing: "value" }, body: {}, aisdk: { provider: {}, request: {} } }, @@ -49,8 +49,8 @@ describe("NvidiaPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(NvidiaPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("nvidia", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://integrate.api.nvidia.com/v1" }, options: { headers: {}, body: {}, aisdk: { provider: {}, request: {} } }, @@ -74,8 +74,8 @@ describe("NvidiaPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(NvidiaPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("nvidia", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://integrate.api.nvidia.com/v1" }, options: { diff --git a/packages/core/test/plugin/provider-openai.test.ts b/packages/core/test/plugin/provider-openai.test.ts index 93e451e0189f..b65beb3c7123 100644 --- a/packages/core/test/plugin/provider-openai.test.ts +++ b/packages/core/test/plugin/provider-openai.test.ts @@ -77,8 +77,8 @@ describe("OpenAIPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpenAIPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("openai", { endpoint: { type: "aisdk", package: "@ai-sdk/openai" } }) catalog.provider.update(item.id, (draft) => { draft.endpoint = item.endpoint @@ -96,8 +96,8 @@ describe("OpenAIPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpenAIPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("custom-openai") catalog.provider.update(item.id, () => {}) catalog.model.update(item.id, ModelV2.ID.make("gpt-5-chat-latest"), () => {}) diff --git a/packages/core/test/plugin/provider-opencode.test.ts b/packages/core/test/plugin/provider-opencode.test.ts index 3f59a349779b..405488071141 100644 --- a/packages/core/test/plugin/provider-opencode.test.ts +++ b/packages/core/test/plugin/provider-opencode.test.ts @@ -1,15 +1,21 @@ import { describe, expect } from "bun:test" import { DateTime, Effect, Layer, Option } from "effect" import { Catalog } from "@opencode-ai/core/catalog" +import { EventV2 } from "@opencode-ai/core/event" import { Location } from "@opencode-ai/core/location" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { OpencodePlugin } from "@opencode-ai/core/plugin/provider/opencode" import { ProviderV2 } from "@opencode-ai/core/provider" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "../fixture/location" import { it, model, provider, withEnv } from "./provider-helper" const cost = (input: number, output = 0) => [{ input, output, cache: { read: 0, write: 0 } }] -const locationLayer = Layer.succeed(Location.Service, Location.Service.of({ directory: "test" })) +const locationLayer = Layer.succeed( + Location.Service, + Location.Service.of(location({ directory: AbsolutePath.make("test") })), +) describe("OpencodePlugin", () => { it.effect("uses a public key and disables paid models without credentials", () => @@ -18,8 +24,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode") catalog.provider.update(item.id, () => {}) const paid = model("opencode", "paid", { cost: cost(1) }) @@ -39,8 +45,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode") catalog.provider.update(item.id, () => {}) const free = model("opencode", "free", { cost: cost(0) }) @@ -60,8 +66,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode") catalog.provider.update(item.id, () => {}) const outputOnly = model("opencode", "output-only", { cost: cost(0, 1) }) @@ -81,8 +87,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode") catalog.provider.update(item.id, () => {}) const paid = model("opencode", "paid", { cost: cost(1) }) @@ -102,8 +108,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode", { env: ["CUSTOM_OPENCODE_API_KEY"] }) catalog.provider.update(item.id, (draft) => { draft.env = [...item.env] @@ -125,8 +131,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode", { options: { headers: {}, @@ -157,8 +163,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("opencode", { enabled: { via: "account", service: "opencode" } }) catalog.provider.update(item.id, (draft) => { draft.enabled = item.enabled @@ -180,8 +186,8 @@ describe("OpencodePlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpencodePlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("openai") catalog.provider.update(item.id, () => {}) const paid = model("openai", "paid", { cost: cost(1) }) @@ -200,8 +206,8 @@ describe("OpencodePlugin", () => { const catalog = yield* Catalog.Service const providerID = ProviderV2.ID.opencode - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(providerID, () => {}) catalog.model.update(providerID, ModelV2.ID.make("cheap-mini"), (model) => { model.capabilities.input = ["text"] @@ -220,6 +226,8 @@ describe("OpencodePlugin", () => { const selected = yield* catalog.model.small(providerID) expect(Option.getOrUndefined(selected)?.id).toBe(ModelV2.ID.make("gpt-5-nano")) - }).pipe(Effect.provide(Catalog.defaultLayer.pipe(Layer.provide(locationLayer)))), + }).pipe( + Effect.provide(Catalog.locationLayer.pipe(Layer.provide(EventV2.defaultLayer), Layer.provide(locationLayer))), + ), ) }) diff --git a/packages/core/test/plugin/provider-openrouter.test.ts b/packages/core/test/plugin/provider-openrouter.test.ts index a60323b8d38c..d19575a9bb3c 100644 --- a/packages/core/test/plugin/provider-openrouter.test.ts +++ b/packages/core/test/plugin/provider-openrouter.test.ts @@ -23,8 +23,8 @@ describe("OpenRouterPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpenRouterPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const openrouter = provider("openrouter", { endpoint: { type: "aisdk", package: "@openrouter/ai-sdk-provider" }, options: { headers: { Existing: "value" }, body: {}, aisdk: { provider: {}, request: {} } }, @@ -75,8 +75,8 @@ describe("OpenRouterPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpenRouterPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const openrouter = provider("openrouter", { endpoint: { type: "aisdk", package: "@openrouter/ai-sdk-provider" }, }) @@ -108,8 +108,8 @@ describe("OpenRouterPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(OpenRouterPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { catalog.provider.update(ProviderV2.ID.make("custom-openrouter"), () => {}) catalog.model.update(ProviderV2.ID.make("custom-openrouter"), ModelV2.ID.make("gpt-5-chat-latest"), () => {}) }) diff --git a/packages/core/test/plugin/provider-vercel.test.ts b/packages/core/test/plugin/provider-vercel.test.ts index f6d9efd1926c..ba34281196ce 100644 --- a/packages/core/test/plugin/provider-vercel.test.ts +++ b/packages/core/test/plugin/provider-vercel.test.ts @@ -12,8 +12,8 @@ describe("VercelPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(VercelPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("vercel", { endpoint: { type: "aisdk", package: "@ai-sdk/vercel" }, options: { headers: { Existing: "1" }, body: {}, aisdk: { provider: {}, request: {} } }, @@ -36,8 +36,8 @@ describe("VercelPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(VercelPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("vercel", { endpoint: { type: "aisdk", package: "@ai-sdk/vercel" } }) catalog.provider.update(item.id, (draft) => { draft.endpoint = item.endpoint @@ -69,8 +69,8 @@ describe("VercelPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(VercelPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => catalog.provider.update(provider("gateway").id, () => {})) + const transform = yield* catalog.transform() + yield* transform((catalog) => catalog.provider.update(provider("gateway").id, () => {})) expect((yield* catalog.provider.get(ProviderV2.ID.make("gateway"))).options.headers).toEqual({}) }), ) diff --git a/packages/core/test/plugin/provider-xai.test.ts b/packages/core/test/plugin/provider-xai.test.ts index 63af32dae7de..de4953b060f4 100644 --- a/packages/core/test/plugin/provider-xai.test.ts +++ b/packages/core/test/plugin/provider-xai.test.ts @@ -1,5 +1,6 @@ import { describe, expect } from "bun:test" -import { Effect } from "effect" +import { Effect, Layer } from "effect" +import { EventV2 } from "@opencode-ai/core/event" import { ModelV2 } from "@opencode-ai/core/model" import { PluginV2 } from "@opencode-ai/core/plugin" import { XAIPlugin } from "@opencode-ai/core/plugin/provider/xai" @@ -7,7 +8,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider" import { testEffect } from "../lib/effect" import { fakeSelectorSdk } from "./provider-helper" -const it = testEffect(PluginV2.defaultLayer) +const it = testEffect(PluginV2.locationLayer.pipe(Layer.provide(EventV2.defaultLayer))) const model = new ModelV2.Info({ ...ModelV2.Info.empty(ProviderV2.ID.make("xai"), ModelV2.ID.make("grok-4")), diff --git a/packages/core/test/plugin/provider-zenmux.test.ts b/packages/core/test/plugin/provider-zenmux.test.ts index 71067a5a1e27..c5899627cfb7 100644 --- a/packages/core/test/plugin/provider-zenmux.test.ts +++ b/packages/core/test/plugin/provider-zenmux.test.ts @@ -22,8 +22,8 @@ describe("ZenmuxPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(ZenmuxPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("zenmux", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://zenmux.ai/api/v1" }, }) @@ -42,8 +42,8 @@ describe("ZenmuxPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(ZenmuxPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("zenmux", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://zenmux.ai/api/v1" }, options: { headers: { Existing: "value" }, body: {}, aisdk: { provider: {}, request: {} } }, @@ -67,8 +67,8 @@ describe("ZenmuxPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(ZenmuxPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("zenmux", { endpoint: { type: "aisdk", package: "@ai-sdk/openai-compatible", url: "https://zenmux.ai/api/v1" }, options: { @@ -95,8 +95,8 @@ describe("ZenmuxPlugin", () => { const plugin = yield* PluginV2.Service const catalog = yield* Catalog.Service yield* plugin.add(ZenmuxPlugin) - const load = yield* catalog.loader() - yield* load((catalog) => { + const transform = yield* catalog.transform() + yield* transform((catalog) => { const item = provider("openrouter", { options: { headers: { "HTTP-Referer": "https://example.com/", "X-Title": "custom-title" }, diff --git a/packages/core/test/policy.test.ts b/packages/core/test/policy.test.ts new file mode 100644 index 000000000000..42736eb7d8a9 --- /dev/null +++ b/packages/core/test/policy.test.ts @@ -0,0 +1,83 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { Location } from "@opencode-ai/core/location" +import { Policy } from "@opencode-ai/core/policy" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { location } from "./fixture/location" +import { testEffect } from "./lib/effect" + +const it = testEffect( + Policy.locationLayer.pipe( + Layer.provide( + Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make("test") }))), + ), + ), +) + +describe("Policy", () => { + it.effect("returns the caller's fallback when no statement matches", () => + Effect.gen(function* () { + const policy = yield* Policy.Service + + expect(yield* policy.evaluate("provider.use", "anthropic", "allow")).toBe("allow") + expect(yield* policy.evaluate("provider.use", "anthropic", "deny")).toBe("deny") + }), + ) + + it.effect("evaluates wildcard provider rules in written order", () => + Effect.gen(function* () { + const policy = yield* Policy.Service + yield* policy.load([ + new Policy.Info({ + effect: "deny", + action: "provider.*", + resource: "*", + }), + new Policy.Info({ + effect: "allow", + action: "provider.use", + resource: "anthropic", + }), + ]) + + expect(yield* policy.evaluate("provider.use", "anthropic", "allow")).toBe("allow") + expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny") + }), + ) + + it.effect("matches action and resource independently", () => + Effect.gen(function* () { + const policy = yield* Policy.Service + yield* policy.load([ + new Policy.Info({ + effect: "deny", + action: "provider.*", + resource: "company-*", + }), + ]) + + expect(yield* policy.evaluate("provider.use", "company-stable", "allow")).toBe("deny") + expect(yield* policy.evaluate("plugin.load", "company-stable", "allow")).toBe("allow") + }), + ) + + it.effect("uses the last matching loaded statement", () => + Effect.gen(function* () { + const policy = yield* Policy.Service + yield* policy.load([ + new Policy.Info({ + effect: "allow", + action: "provider.use", + resource: "openai", + }), + new Policy.Info({ + effect: "deny", + action: "provider.use", + resource: "openai", + }), + ]) + + expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny") + }), + ) +}) diff --git a/packages/core/test/project.test.ts b/packages/core/test/project.test.ts index c5b96b638985..94ea40f6727f 100644 --- a/packages/core/test/project.test.ts +++ b/packages/core/test/project.test.ts @@ -3,16 +3,16 @@ import { $ } from "bun" import fs from "fs/promises" import path from "path" import { Effect } from "effect" -import { Project } from "@opencode-ai/core/project" +import { ProjectV2 } from "@opencode-ai/core/project" import { AbsolutePath } from "@opencode-ai/core/schema" import { Hash } from "@opencode-ai/core/util/hash" import { tmpdir } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" -const it = testEffect(Project.defaultLayer) +const it = testEffect(ProjectV2.defaultLayer) function remoteID(remote: string) { - return Project.ID.make(Hash.fast(`git-remote:${remote}`)) + return ProjectV2.ID.make(Hash.fast(`git-remote:${remote}`)) } function abs(value: string) { @@ -44,12 +44,12 @@ describe("ProjectV2.resolve", () => { Effect.promise(() => tmpdir()), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(tmp.path)) - expect(result.id).toBe(Project.ID.make("global")) - expect(path.resolve(result.directory)).toBe(path.resolve(tmp.path)) + expect(result.id).toBe(ProjectV2.ID.make("global")) + expect(path.resolve(result.directory)).toBe(path.parse(tmp.path).root) expect(result.previous).toBeUndefined() expect(result.vcs).toBeUndefined() }), @@ -62,11 +62,11 @@ describe("ProjectV2.resolve", () => { (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) yield* Effect.promise(() => initRepo(tmp.path)) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(tmp.path)) - expect(result.id).toBe(Project.ID.make("global")) + expect(result.id).toBe(ProjectV2.ID.make("global")) expect(result.directory).toBe(yield* real(tmp.path)) expect(result.previous).toBeUndefined() expect(result.vcs?.type).toBe("git") @@ -80,11 +80,11 @@ describe("ProjectV2.resolve", () => { (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) yield* Effect.promise(() => initRepo(tmp.path, { commit: true })) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(tmp.path)) - expect(result.id).toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path)))) + expect(result.id).toBe(ProjectV2.ID.make(yield* Effect.promise(() => rootCommit(tmp.path)))) expect(result.directory).toBe(yield* real(tmp.path)) expect(result.previous).toBeUndefined() expect(result.vcs?.type).toBe("git") @@ -98,12 +98,12 @@ describe("ProjectV2.resolve", () => { (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:Acme/App.git" })) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(tmp.path)) expect(result.id).toBe(remoteID("github.com/Acme/App")) - expect(result.id).not.toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path)))) + expect(result.id).not.toBe(ProjectV2.ID.make(yield* Effect.promise(() => rootCommit(tmp.path)))) expect(result.directory).toBe(yield* real(tmp.path)) expect(result.vcs?.type).toBe("git") }), @@ -121,7 +121,7 @@ describe("ProjectV2.resolve", () => { ) yield* Effect.promise(() => initRepo(ssh.path, { commit: true, remote: "git@github.com:owner/repo.git" })) yield* Effect.promise(() => initRepo(https.path, { commit: true, remote: "https://github.com/owner/repo.git" })) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const a = yield* project.resolve(abs(ssh.path)) const b = yield* project.resolve(abs(https.path)) @@ -138,11 +138,11 @@ describe("ProjectV2.resolve", () => { (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: `file://${tmp.path}` })) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(tmp.path)) - expect(result.id).toBe(Project.ID.make(yield* Effect.promise(() => rootCommit(tmp.path)))) + expect(result.id).toBe(ProjectV2.ID.make(yield* Effect.promise(() => rootCommit(tmp.path)))) }), ) @@ -154,11 +154,11 @@ describe("ProjectV2.resolve", () => { ) yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" })) yield* Effect.promise(() => Bun.write(path.join(tmp.path, ".git", "opencode"), "old-id")) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(tmp.path)) - expect(result.previous).toBe(Project.ID.make("old-id")) + expect(result.previous).toBe(ProjectV2.ID.make("old-id")) expect(result.id).toBe(remoteID("github.com/owner/repo")) }), ) @@ -170,7 +170,7 @@ describe("ProjectV2.resolve", () => { (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ) yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" })) - const project = yield* Project.Service + const project = yield* ProjectV2.Service yield* project.resolve(abs(tmp.path)) @@ -186,7 +186,7 @@ describe("ProjectV2.resolve", () => { ) yield* Effect.promise(() => initRepo(tmp.path, { commit: true })) yield* Effect.promise(() => fs.mkdir(path.join(tmp.path, "a", "b"), { recursive: true })) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(path.join(tmp.path, "a", "b"))) @@ -207,12 +207,12 @@ describe("ProjectV2.resolve", () => { yield* Effect.promise(() => initRepo(tmp.path, { commit: true, remote: "git@github.com:owner/repo.git" })) yield* Effect.promise(() => Bun.write(path.join(tmp.path, ".git", "opencode"), "old-id")) yield* Effect.promise(() => $`git worktree add ${worktree} -b test-${Date.now()}`.cwd(tmp.path).quiet()) - const project = yield* Project.Service + const project = yield* ProjectV2.Service const result = yield* project.resolve(abs(worktree)) expect(result.directory).toBe(yield* real(worktree)) - expect(result.previous).toBe(Project.ID.make("old-id")) + expect(result.previous).toBe(ProjectV2.ID.make("old-id")) expect(result.id).toBe(remoteID("github.com/owner/repo")) expect(result.vcs?.type).toBe("git") }), diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 146aa162d2b4..8e868f69ecaf 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -59,12 +59,12 @@ "zod-openapi": "5.4.6" }, "optionalDependencies": { - "@lydell/node-pty-darwin-arm64": "1.2.0-beta.10", - "@lydell/node-pty-darwin-x64": "1.2.0-beta.10", - "@lydell/node-pty-linux-arm64": "1.2.0-beta.10", - "@lydell/node-pty-linux-x64": "1.2.0-beta.10", - "@lydell/node-pty-win32-arm64": "1.2.0-beta.10", - "@lydell/node-pty-win32-x64": "1.2.0-beta.10", + "@lydell/node-pty-darwin-arm64": "1.2.0-beta.12", + "@lydell/node-pty-darwin-x64": "1.2.0-beta.12", + "@lydell/node-pty-linux-arm64": "1.2.0-beta.12", + "@lydell/node-pty-linux-x64": "1.2.0-beta.12", + "@lydell/node-pty-win32-arm64": "1.2.0-beta.12", + "@lydell/node-pty-win32-x64": "1.2.0-beta.12", "@parcel/watcher-darwin-arm64": "2.5.1", "@parcel/watcher-darwin-x64": "2.5.1", "@parcel/watcher-linux-arm64-glibc": "2.5.1", diff --git a/packages/effect-drizzle-sqlite/package.json b/packages/effect-drizzle-sqlite/package.json index 0fcba7216ca4..1d0e26dde841 100644 --- a/packages/effect-drizzle-sqlite/package.json +++ b/packages/effect-drizzle-sqlite/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "1.15.10", + "version": "1.15.13", "name": "@opencode-ai/effect-drizzle-sqlite", "type": "module", "license": "MIT", diff --git a/packages/effect-sqlite-node/package.json b/packages/effect-sqlite-node/package.json new file mode 100644 index 000000000000..74671bb5b49a --- /dev/null +++ b/packages/effect-sqlite-node/package.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json.schemastore.org/package.json", + "version": "1.15.10", + "name": "@opencode-ai/effect-sqlite-node", + "type": "module", + "license": "MIT", + "private": true, + "scripts": { + "typecheck": "tsgo --noEmit" + }, + "exports": { + ".": "./src/index.ts" + }, + "devDependencies": { + "@tsconfig/bun": "catalog:", + "@types/node": "catalog:", + "@typescript/native-preview": "catalog:" + }, + "dependencies": { + "effect": "catalog:" + } +} diff --git a/packages/effect-sqlite-node/src/index.ts b/packages/effect-sqlite-node/src/index.ts new file mode 100644 index 000000000000..37e255391da1 --- /dev/null +++ b/packages/effect-sqlite-node/src/index.ts @@ -0,0 +1,168 @@ +export * as NodeSqliteClient from "./index" + +import { DatabaseSync, type SQLInputValue } from "node:sqlite" +import { identity } from "effect/Function" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Fiber from "effect/Fiber" +import * as Layer from "effect/Layer" +import * as Scope from "effect/Scope" +import * as Semaphore from "effect/Semaphore" +import * as Stream from "effect/Stream" +import * as Reactivity from "effect/unstable/reactivity/Reactivity" +import * as Client from "effect/unstable/sql/SqlClient" +import type { Connection } from "effect/unstable/sql/SqlConnection" +import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError" +import * as Statement from "effect/unstable/sql/Statement" + +const ATTR_DB_SYSTEM_NAME = "db.system.name" + +export const TypeId: TypeId = "~@opencode-ai/effect-sqlite-node/NodeSqliteClient" +export type TypeId = "~@opencode-ai/effect-sqlite-node/NodeSqliteClient" + +export interface SqliteClient extends Client.SqlClient { + readonly [TypeId]: TypeId + readonly config: SqliteClientConfig + readonly loadExtension: (path: string) => Effect.Effect + readonly updateValues: never +} + +export const SqliteClient = Context.Service("@opencode-ai/effect-sqlite-node/NodeSqliteClient") + +export interface SqliteClientConfig { + readonly filename: string + readonly readonly?: boolean | undefined + readonly create?: boolean | undefined + readonly readwrite?: boolean | undefined + readonly disableWAL?: boolean | undefined + readonly timeout?: number | undefined + readonly allowExtension?: boolean | undefined + readonly spanAttributes?: Record | undefined + readonly transformResultNames?: ((str: string) => string) | undefined + readonly transformQueryNames?: ((str: string) => string) | undefined +} + +interface SqliteConnection extends Connection { + readonly loadExtension: (path: string) => Effect.Effect +} + +export const make = ( + options: SqliteClientConfig, +): Effect.Effect => + Effect.gen(function* () { + const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) + const transformRows = options.transformResultNames + ? Statement.defaultTransforms(options.transformResultNames).array + : undefined + + const makeConnection = Effect.gen(function* () { + const db = new DatabaseSync(options.filename, { + readOnly: options.readonly, + timeout: options.timeout, + allowExtension: options.allowExtension, + enableForeignKeyConstraints: true, + open: true, + }) + yield* Effect.addFinalizer(() => Effect.sync(() => db.close())) + + if (options.disableWAL !== true && options.readonly !== true) { + db.exec("PRAGMA journal_mode = WAL;") + } + + const run = (sql: string, params: ReadonlyArray = []) => + Effect.withFiber>, SqlError>((fiber) => { + const statement = db.prepare(sql) + statement.setReadBigInts(Context.get(fiber.context, Client.SafeIntegers)) + try { + return Effect.succeed(statement.all(...(params as SQLInputValue[])) as Array>) + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }), + }), + ) + } + }) + + const runValues = (sql: string, params: ReadonlyArray = []) => + Effect.withFiber>, SqlError>((fiber) => { + const statement = db.prepare(sql) + statement.setReadBigInts(Context.get(fiber.context, Client.SafeIntegers)) + statement.setReturnArrays(true) + try { + return Effect.succeed( + statement.all(...(params as SQLInputValue[])) as unknown as ReadonlyArray>, + ) + } catch (cause) { + return Effect.fail( + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to execute statement", operation: "execute" }), + }), + ) + } + }) + + return identity({ + execute(sql, params, transformRows) { + return transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params) + }, + executeRaw(sql, params) { + return run(sql, params) + }, + executeValues(sql, params) { + return runValues(sql, params) + }, + executeUnprepared(sql, params, transformRows) { + return this.execute(sql, params, transformRows) + }, + executeStream() { + return Stream.die("executeStream not implemented") + }, + loadExtension: (path) => + Effect.try({ + try: () => db.loadExtension(path), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { message: "Failed to load extension", operation: "loadExtension" }), + }), + }), + }) + }) + + const semaphore = yield* Semaphore.make(1) + const connection = yield* makeConnection + const acquirer = semaphore.withPermits(1)(Effect.succeed(connection)) + const transactionAcquirer = Effect.uninterruptibleMask((restore) => { + const fiber = Fiber.getCurrent()! + const scope = Context.getUnsafe(fiber.context, Scope.Scope) + return Effect.as( + Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), + connection, + ) + }) + + return Object.assign( + (yield* Client.make({ + acquirer, + compiler, + transactionAcquirer, + spanAttributes: [ + ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), + [ATTR_DB_SYSTEM_NAME, "sqlite"], + ], + transformRows, + })) as SqliteClient, + { + [TypeId]: TypeId as TypeId, + config: options, + loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path)), + }, + ) + }) + +export const layer = (config: SqliteClientConfig): Layer.Layer => + Layer.effectContext( + Effect.map(make(config), (client) => + Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)), + ), + ).pipe(Layer.provide(Reactivity.layer)) diff --git a/packages/effect-sqlite-node/sst-env.d.ts b/packages/effect-sqlite-node/sst-env.d.ts new file mode 100644 index 000000000000..64441936d7a0 --- /dev/null +++ b/packages/effect-sqlite-node/sst-env.d.ts @@ -0,0 +1,10 @@ +/* This file is auto-generated by SST. Do not edit. */ +/* tslint:disable */ +/* eslint-disable */ +/* deno-fmt-ignore-file */ +/* biome-ignore-all lint: auto-generated */ + +/// + +import "sst" +export {} \ No newline at end of file diff --git a/packages/effect-sqlite-node/tsconfig.json b/packages/effect-sqlite-node/tsconfig.json new file mode 100644 index 000000000000..2bc480ffbb60 --- /dev/null +++ b/packages/effect-sqlite-node/tsconfig.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@tsconfig/bun/tsconfig.json", + "compilerOptions": { + "lib": ["ESNext", "DOM", "DOM.Iterable"], + "noUncheckedIndexedAccess": false, + "plugins": [ + { + "name": "@effect/language-service", + "transform": "@effect/language-service/transform", + "namespaceImportPackages": ["effect", "@effect/*"] + } + ] + } +} diff --git a/packages/enterprise/vite.config.ts b/packages/enterprise/vite.config.ts index 11ca1729dfe4..90f4665c59bc 100644 --- a/packages/enterprise/vite.config.ts +++ b/packages/enterprise/vite.config.ts @@ -8,7 +8,7 @@ const nitroConfig: any = (() => { if (target === "cloudflare") { return { compatibilityDate: "2024-09-19", - preset: "cloudflare_module", + preset: "cloudflare-module", cloudflare: { nodeCompat: true, }, @@ -29,6 +29,7 @@ export default defineConfig({ server: { host: "0.0.0.0", allowedHosts: true, + port: 3002, }, worker: { format: "es", diff --git a/packages/http-recorder/package.json b/packages/http-recorder/package.json index c3efb8fc1b39..243b4be76eea 100644 --- a/packages/http-recorder/package.json +++ b/packages/http-recorder/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "1.15.10", + "version": "1.15.13", "name": "@opencode-ai/http-recorder", "type": "module", "license": "MIT", diff --git a/packages/llm/package.json b/packages/llm/package.json index fafa98cb5490..3aca204c2e91 100644 --- a/packages/llm/package.json +++ b/packages/llm/package.json @@ -1,6 +1,6 @@ { "$schema": "https://json.schemastore.org/package.json", - "version": "1.15.10", + "version": "1.15.13", "name": "@opencode-ai/llm", "type": "module", "license": "MIT", diff --git a/packages/llm/src/protocols/openai-responses.ts b/packages/llm/src/protocols/openai-responses.ts index 70211b3cba5e..cc29f5019069 100644 --- a/packages/llm/src/protocols/openai-responses.ts +++ b/packages/llm/src/protocols/openai-responses.ts @@ -429,6 +429,7 @@ const lowerOptions = Effect.fn("OpenAIResponses.lowerOptions")(function* (reques const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request: LLMRequest) { const generation = request.generation + const options = yield* lowerOptions(request) return { model: request.model.id, input: yield* lowerMessages(request), @@ -438,7 +439,7 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request: max_output_tokens: generation?.maxTokens, temperature: generation?.temperature, top_p: generation?.topP, - ...(yield* lowerOptions(request)), + ...options, } }) diff --git a/packages/opencode/AGENTS.md b/packages/opencode/AGENTS.md index 0aa96cc42421..f07170c5851c 100644 --- a/packages/opencode/AGENTS.md +++ b/packages/opencode/AGENTS.md @@ -1,47 +1,9 @@ -# opencode (lash fork) - -Lash is a fork of opencode with shell-mode: natural language → AI agent in a shell. - -## Lash Additions - -### Plugin System (`plugin/`) -- `plugin/shell-mode/` — cwd tracking (`getCwd`/`setCwd`), execution mode, command detection, tab completion, NL detection, shell session execution -- `plugin/tui-integration/` — `ExecutionModeProvider`, `WorkingDirProvider`, keyboard hooks (`handleModeToggleKey`, `determineRouting`, tab completion) - -### Key Patterns -- **getCwd()**: All tool files (`bash.ts`, `read.ts`, `write.ts`, `edit.ts`, `glob.ts`, `grep.ts`, `ls.ts`, `lsp.ts`) resolve paths against `getCwd()` instead of `Instance.directory`. This makes `cd` work. -- **CWD sentinel**: `prompt.ts` `shell()` wraps commands with sentinels to capture cwd after execution, then calls `setCwd()`. -- **Spawn cwd**: `prompt.ts` `shell()` passes `cwd: getCwd()` to `spawn()` so each shell command starts in the tracked directory. -- **Execution modes**: Auto/Shell/Agent — toggled via `ctrl+space` (`mode_toggle` keybind in `config.ts`). -- **Kitty keyboard normalization**: `keybind.tsx` normalizes `" "` → `"space"` for Kitty terminal protocol compatibility. -- **agent_cycle**: Default is `shift+tab` (not `tab`) to avoid conflict with shell tab completion. - -### Path Aliases (`tsconfig.json`) -``` -@shell-mode → plugin/shell-mode/index.ts -@tui-integration → plugin/tui-integration/index.ts -@plugin/* → plugin/* -``` - -### Lash-Specific Files -- `script/build-lash.ts`, `script/publish-lash.ts`, `script/postinstall-lash.mjs` — build/release for lash npm package -- `script/release-lash.ts` (root) — release orchestration -- `src/cli/cmd/tui/component/dialog-execution-mode.tsx` — mode picker dialog -- `src/session/prompt.ts` — heavily modified for shell execution, CWD sentinels, NL detection rerouting -- `src/cli/cmd/tui/component/prompt/index.tsx` — shell mode UI, tab completion, mode indicators -- `FORK.md` — fork documentation - -### SDK `Path` type -Server (`server.ts`) and SDK include `cwd: string` in the Path object. App package (`global-sync.tsx`, `child-store.ts`) and TUI (`sync.tsx`) must include `cwd` in their Path initial state. +# opencode database guide ## Database -- **Schema**: Drizzle schema lives in `src/**/*.sql.ts`. -- **Naming**: tables and columns use snake\_case; join columns are `_id`; indexes are `__idx`. -- **Migrations**: generated by Drizzle Kit using `drizzle.config.ts` (schema: `./src/**/*.sql.ts`, output: `./migration`). -- **Command**: `bun run db generate --name `. -- **Output**: creates `migration/_/migration.sql` and `snapshot.json`. -- **Tests**: migration tests should read the per-folder layout (no `_journal.json`). +- **Schema**: Drizzle schema lives in `packages/core/src/**/*.sql.ts`. +- **Migrations**: database migrations live in `packages/core` and are applied by core. ## Development server diff --git a/packages/opencode/migration/20260511173437_session-metadata/migration.sql b/packages/opencode/migration/20260511173437_session-metadata/migration.sql new file mode 100644 index 000000000000..0ce73631f0d7 --- /dev/null +++ b/packages/opencode/migration/20260511173437_session-metadata/migration.sql @@ -0,0 +1 @@ +ALTER TABLE `session` ADD `metadata` text; \ No newline at end of file diff --git a/packages/opencode/migration/20260511173437_session-metadata/snapshot.json b/packages/opencode/migration/20260511173437_session-metadata/snapshot.json new file mode 100644 index 000000000000..07d9ec016a8c --- /dev/null +++ b/packages/opencode/migration/20260511173437_session-metadata/snapshot.json @@ -0,0 +1,1500 @@ +{ + "version": "7", + "dialect": "sqlite", + "id": "85d2086c-3c95-4706-90b0-f7480b73db5c", + "prevIds": ["fdfcccee-fb3a-481f-b801-b9835fa30d5d"], + "ddl": [ + { + "name": "account_state", + "entityType": "tables" + }, + { + "name": "account", + "entityType": "tables" + }, + { + "name": "control_account", + "entityType": "tables" + }, + { + "name": "workspace", + "entityType": "tables" + }, + { + "name": "data_migration", + "entityType": "tables" + }, + { + "name": "project", + "entityType": "tables" + }, + { + "name": "message", + "entityType": "tables" + }, + { + "name": "part", + "entityType": "tables" + }, + { + "name": "permission", + "entityType": "tables" + }, + { + "name": "session_message", + "entityType": "tables" + }, + { + "name": "session", + "entityType": "tables" + }, + { + "name": "todo", + "entityType": "tables" + }, + { + "name": "session_share", + "entityType": "tables" + }, + { + "name": "event_sequence", + "entityType": "tables" + }, + { + "name": "event", + "entityType": "tables" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "account_state" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "active_account_id", + "entityType": "columns", + "table": "account_state" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "active_org_id", + "entityType": "columns", + "table": "account_state" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "email", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "url", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "access_token", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "refresh_token", + "entityType": "columns", + "table": "account" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "token_expiry", + "entityType": "columns", + "table": "account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "email", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "url", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "access_token", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "refresh_token", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "token_expiry", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "active", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "control_account" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "''", + "generated": null, + "name": "name", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "branch", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "directory", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "extra", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_used", + "entityType": "columns", + "table": "workspace" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "name", + "entityType": "columns", + "table": "data_migration" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_completed", + "entityType": "columns", + "table": "data_migration" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "worktree", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "vcs", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "name", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "icon_url", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "icon_url_override", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "icon_color", + "entityType": "columns", + "table": "project" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "project" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "project" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_initialized", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "sandboxes", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "commands", + "entityType": "columns", + "table": "project" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "message" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "message_id", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "part" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "part" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "part" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "permission" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "permission" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "permission" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "permission" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "session_message" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "workspace_id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "parent_id", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "slug", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "directory", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "path", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "title", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "version", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "share_url", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_additions", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_deletions", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_files", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "summary_diffs", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "metadata", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "revert", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "permission", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "agent", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "model", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_compacting", + "entityType": "columns", + "table": "session" + }, + { + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_archived", + "entityType": "columns", + "table": "session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "content", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "status", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "priority", + "entityType": "columns", + "table": "todo" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "position", + "entityType": "columns", + "table": "todo" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "todo" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "todo" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "secret", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "url", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "session_share" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "aggregate_id", + "entityType": "columns", + "table": "event_sequence" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "seq", + "entityType": "columns", + "table": "event_sequence" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "owner_id", + "entityType": "columns", + "table": "event_sequence" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "id", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "aggregate_id", + "entityType": "columns", + "table": "event" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "seq", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "type", + "entityType": "columns", + "table": "event" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "event" + }, + { + "columns": ["active_account_id"], + "tableTo": "account", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "nameExplicit": false, + "name": "fk_account_state_active_account_id_account_id_fk", + "entityType": "fks", + "table": "account_state" + }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_workspace_project_id_project_id_fk", + "entityType": "fks", + "table": "workspace" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_message_session_id_session_id_fk", + "entityType": "fks", + "table": "message" + }, + { + "columns": ["message_id"], + "tableTo": "message", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_part_message_id_message_id_fk", + "entityType": "fks", + "table": "part" + }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_permission_project_id_project_id_fk", + "entityType": "fks", + "table": "permission" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_message_session_id_session_id_fk", + "entityType": "fks", + "table": "session_message" + }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_project_id_project_id_fk", + "entityType": "fks", + "table": "session" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_todo_session_id_session_id_fk", + "entityType": "fks", + "table": "todo" + }, + { + "columns": ["session_id"], + "tableTo": "session", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_session_share_session_id_session_id_fk", + "entityType": "fks", + "table": "session_share" + }, + { + "columns": ["aggregate_id"], + "tableTo": "event_sequence", + "columnsTo": ["aggregate_id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_event_aggregate_id_event_sequence_aggregate_id_fk", + "entityType": "fks", + "table": "event" + }, + { + "columns": ["email", "url"], + "nameExplicit": false, + "name": "control_account_pk", + "entityType": "pks", + "table": "control_account" + }, + { + "columns": ["session_id", "position"], + "nameExplicit": false, + "name": "todo_pk", + "entityType": "pks", + "table": "todo" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "account_state_pk", + "table": "account_state", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "account_pk", + "table": "account", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "workspace_pk", + "table": "workspace", + "entityType": "pks" + }, + { + "columns": ["name"], + "nameExplicit": false, + "name": "data_migration_pk", + "table": "data_migration", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "project_pk", + "table": "project", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "message_pk", + "table": "message", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "part_pk", + "table": "part", + "entityType": "pks" + }, + { + "columns": ["project_id"], + "nameExplicit": false, + "name": "permission_pk", + "table": "permission", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "session_message_pk", + "table": "session_message", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "session_pk", + "table": "session", + "entityType": "pks" + }, + { + "columns": ["session_id"], + "nameExplicit": false, + "name": "session_share_pk", + "table": "session_share", + "entityType": "pks" + }, + { + "columns": ["aggregate_id"], + "nameExplicit": false, + "name": "event_sequence_pk", + "table": "event_sequence", + "entityType": "pks" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "event_pk", + "table": "event", + "entityType": "pks" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + }, + { + "value": "time_created", + "isExpression": false + }, + { + "value": "id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "message_session_time_created_id_idx", + "entityType": "indexes", + "table": "message" + }, + { + "columns": [ + { + "value": "message_id", + "isExpression": false + }, + { + "value": "id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "part_message_id_id_idx", + "entityType": "indexes", + "table": "part" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "part_session_idx", + "entityType": "indexes", + "table": "part" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_message_session_idx", + "entityType": "indexes", + "table": "session_message" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + }, + { + "value": "type", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_message_session_type_idx", + "entityType": "indexes", + "table": "session_message" + }, + { + "columns": [ + { + "value": "time_created", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_message_time_created_idx", + "entityType": "indexes", + "table": "session_message" + }, + { + "columns": [ + { + "value": "project_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_project_idx", + "entityType": "indexes", + "table": "session" + }, + { + "columns": [ + { + "value": "workspace_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_workspace_idx", + "entityType": "indexes", + "table": "session" + }, + { + "columns": [ + { + "value": "parent_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "session_parent_idx", + "entityType": "indexes", + "table": "session" + }, + { + "columns": [ + { + "value": "session_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "todo_session_idx", + "entityType": "indexes", + "table": "todo" + } + ], + "renames": [] +} diff --git a/packages/opencode/package.json b/packages/opencode/package.json index 4b7c86eb85b3..557c755f8d9a 100644 --- a/packages/opencode/package.json +++ b/packages/opencode/package.json @@ -15,8 +15,7 @@ "build": "bun run script/build.ts", "fix-node-pty": "bun run script/fix-node-pty.ts", "dev": "bun run --conditions=browser ./src/index.ts", - "dev:temporary": "bun run --conditions=browser ./src/temporary.ts", - "db": "bun drizzle-kit" + "dev:temporary": "bun run --conditions=browser ./src/temporary.ts" }, "bin": { "opencode": "./bin/opencode" @@ -62,7 +61,6 @@ "@types/which": "3.0.4", "@types/yargs": "17.0.33", "@typescript/native-preview": "catalog:", - "drizzle-kit": "catalog:", "drizzle-orm": "catalog:", "prettier": "3.6.2", "typescript": "catalog:", @@ -81,8 +79,8 @@ "@ai-sdk/cohere": "3.0.27", "@ai-sdk/deepinfra": "2.0.41", "@ai-sdk/gateway": "3.0.104", - "@ai-sdk/google": "3.0.75", - "@ai-sdk/google-vertex": "4.0.131", + "@ai-sdk/google": "3.0.73", + "@ai-sdk/google-vertex": "4.0.128", "@ai-sdk/groq": "3.0.31", "@ai-sdk/mistral": "3.0.27", "@ai-sdk/openai": "3.0.53", @@ -122,6 +120,7 @@ "@solid-primitives/event-bus": "1.1.2", "@solid-primitives/scheduled": "1.5.2", "@standard-schema/spec": "1.0.0", + "@types/ws": "8.18.1", "@zip.js/zip.js": "2.7.62", "ai": "catalog:", "ai-gateway-provider": "3.1.2", @@ -135,7 +134,7 @@ "drizzle-orm": "catalog:", "effect": "catalog:", "fuzzysort": "3.1.0", - "gitlab-ai-provider": "6.7.0", + "gitlab-ai-provider": "6.8.0", "glob": "13.0.5", "google-auth-library": "10.5.0", "gray-matter": "4.0.3", @@ -162,6 +161,7 @@ "vscode-jsonrpc": "8.2.1", "web-tree-sitter": "0.25.10", "which": "6.0.1", + "ws": "8.21.0", "xdg-basedir": "5.1.0", "yargs": "18.0.0", "zod": "catalog:" diff --git a/packages/opencode/plugin/shell-mode/cwd.ts b/packages/opencode/plugin/shell-mode/cwd.ts index 4a2960142ced..68a63ee0b098 100644 --- a/packages/opencode/plugin/shell-mode/cwd.ts +++ b/packages/opencode/plugin/shell-mode/cwd.ts @@ -4,8 +4,8 @@ */ import { context as instanceContext } from "@/project/instance-context" -import { Bus } from "@/bus" -import { BusEvent } from "@/bus/bus-event" +import { GlobalBus } from "@/bus/global" +import { EventV2 } from "@opencode-ai/core/event" import path from "path" import os from "os" import { Schema } from "effect" @@ -16,12 +16,12 @@ let currentCwd: string | null = null * Event published when the working directory changes. */ export const CwdEvent = { - Updated: BusEvent.define( - "cwd.updated", - Schema.Struct({ + Updated: EventV2.define({ + type: "cwd.updated", + schema: { cwd: Schema.String, - }), - ), + }, + }), } /** @@ -59,10 +59,18 @@ export function setCwd(dir: string): void { const changed = currentCwd !== resolved currentCwd = resolved - // Publish event if cwd changed + // Publish event if cwd changed. EventV2 / Bus refactor (upstream PR #29068) + // collapsed BusEvent.publish into GlobalBus.emit for ambient (non-Effect) callers. if (changed) { try { - void Bus.publish(instanceContext.use(), CwdEvent.Updated, { cwd: resolved }) + const ctx = instanceContext.use() + GlobalBus.emit("event", { + directory: ctx.directory, + payload: { + type: CwdEvent.Updated.type, + properties: { cwd: resolved }, + }, + }) } catch { // No instance context available; skip publishing } diff --git a/packages/opencode/plugin/shell-mode/session-shell.ts b/packages/opencode/plugin/shell-mode/session-shell.ts index 803b9fb6040c..1607f97a88d5 100644 --- a/packages/opencode/plugin/shell-mode/session-shell.ts +++ b/packages/opencode/plugin/shell-mode/session-shell.ts @@ -7,7 +7,7 @@ import { spawn, type ChildProcess } from "child_process" import { ulid } from "ulid" import path from "path" import os from "os" -import { Bus } from "@/bus" +import { GlobalBus, type GlobalEvent } from "@/bus/global" import { SessionStatus } from "@/session/status" import * as Log from "@opencode-ai/core/util/log" import { Shell } from "@/shell/shell" @@ -331,12 +331,19 @@ function ensureSubscribed() { if (subscribed) return subscribed = true - // Listen for session idle events to schedule cleanup - Bus.subscribe(SessionStatus.Event.Idle, (evt) => { - const shell = shells.get(evt.properties.sessionID) + // Listen for session idle events to schedule cleanup. + // Upstream PR #29068 replaced the per-instance Bus.subscribe with GlobalBus.on + // for ambient (non-Effect) callers; filter by event type on the GlobalEvent payload. + GlobalBus.on("event", (event: GlobalEvent) => { + const payload = event.payload + if (!payload || typeof payload !== "object") return + if (payload.type !== SessionStatus.Event.Idle.type) return + const sessionID = payload.properties?.sessionID + if (typeof sessionID !== "string") return + const shell = shells.get(sessionID) if (shell) { shell.resetIdleTimer(() => { - dispose(evt.properties.sessionID) + dispose(sessionID) }) } }) diff --git a/packages/opencode/script/build-node.ts b/packages/opencode/script/build-node.ts index 0f0d55b46aaa..e6a4171f70f1 100755 --- a/packages/opencode/script/build-node.ts +++ b/packages/opencode/script/build-node.ts @@ -1,7 +1,6 @@ #!/usr/bin/env bun import { Script } from "@opencode-ai/script" -import fs from "fs" import path from "path" import { fileURLToPath } from "url" @@ -13,36 +12,6 @@ process.chdir(dir) const generated = await import("./generate.ts") -// Load migrations from migration directories -const migrationDirs = ( - await fs.promises.readdir(path.join(dir, "migration"), { - withFileTypes: true, - }) -) - .filter((entry) => entry.isDirectory() && /^\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}/.test(entry.name)) - .map((entry) => entry.name) - .sort() - -const migrations = await Promise.all( - migrationDirs.map(async (name) => { - const file = path.join(dir, "migration", name, "migration.sql") - const sql = await Bun.file(file).text() - const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(name) - const timestamp = match - ? Date.UTC( - Number(match[1]), - Number(match[2]) - 1, - Number(match[3]), - Number(match[4]), - Number(match[5]), - Number(match[6]), - ) - : 0 - return { sql, timestamp, name } - }), -) -console.log(`Loaded ${migrations.length} migrations`) - await Bun.build({ target: "node", entrypoints: ["./src/node.ts"], @@ -51,7 +20,6 @@ await Bun.build({ sourcemap: "linked", external: ["jsonc-parser", "@lydell/node-pty"], define: { - OPENCODE_MIGRATIONS: JSON.stringify(migrations), OPENCODE_MODELS_DEV: generated.modelsData, OPENCODE_CHANNEL: `'${Script.channel}'`, }, diff --git a/packages/opencode/script/build.ts b/packages/opencode/script/build.ts index 33db38d84cc1..c93ae46d11ec 100755 --- a/packages/opencode/script/build.ts +++ b/packages/opencode/script/build.ts @@ -17,36 +17,6 @@ const generated = await import("./generate.ts") import { Script } from "@opencode-ai/script" import pkg from "../package.json" -// Load migrations from migration directories -const migrationDirs = ( - await fs.promises.readdir(path.join(dir, "migration"), { - withFileTypes: true, - }) -) - .filter((entry) => entry.isDirectory() && /^\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}/.test(entry.name)) - .map((entry) => entry.name) - .sort() - -const migrations = await Promise.all( - migrationDirs.map(async (name) => { - const file = path.join(dir, "migration", name, "migration.sql") - const sql = await Bun.file(file).text() - const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(name) - const timestamp = match - ? Date.UTC( - Number(match[1]), - Number(match[2]) - 1, - Number(match[3]), - Number(match[4]), - Number(match[5]), - Number(match[6]), - ) - : 0 - return { sql, timestamp, name } - }), -) -console.log(`Loaded ${migrations.length} migrations`) - const singleFlag = process.argv.includes("--single") const baselineFlag = process.argv.includes("--baseline") const skipInstall = process.argv.includes("--skip-install") @@ -217,7 +187,6 @@ for (const item of targets) { entrypoints: ["./src/index.ts", parserWorker, workerPath, ...(embeddedFileMap ? ["opencode-web-ui.gen.ts"] : [])], define: { OPENCODE_VERSION: `'${Script.version}'`, - OPENCODE_MIGRATIONS: JSON.stringify(migrations), OPENCODE_MODELS_DEV: generated.modelsData, OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath, OPENCODE_WORKER_PATH: workerPath, diff --git a/packages/opencode/script/check-migrations.ts b/packages/opencode/script/check-migrations.ts deleted file mode 100644 index f5eaf79323b2..000000000000 --- a/packages/opencode/script/check-migrations.ts +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bun - -import { $ } from "bun" - -// drizzle-kit check compares schema to migrations, exits non-zero if drift -const result = await $`bun drizzle-kit check`.quiet().nothrow() - -if (result.exitCode !== 0) { - console.error("Schema has changes not captured in migrations!") - console.error("Run: bun drizzle-kit generate") - console.error("") - console.error(result.stderr.toString()) - process.exit(1) -} - -console.log("Migrations are up to date") diff --git a/packages/opencode/src/account/account.ts b/packages/opencode/src/account/account.ts index 2d855e0e952b..9d9f7e4a2882 100644 --- a/packages/opencode/src/account/account.ts +++ b/packages/opencode/src/account/account.ts @@ -454,6 +454,6 @@ export const layer: Layer.Layer[0] extends (db: infer T) => unknown ? T : never -type DbTransactionCallback = Parameters>[0] - const ACCOUNT_STATE_ID = 1 export interface Interface { @@ -41,32 +38,24 @@ export class Service extends Context.Service()("@opencode/Ac export const use = serviceUse(Service) -export const layer: Layer.Layer = Layer.effect( +export const layer = Layer.effect( Service, Effect.gen(function* () { + const { db } = yield* Database.Service const decode = Schema.decodeUnknownSync(Info) - const query = (f: DbTransactionCallback) => - Effect.try({ - try: () => Database.use(f), - catch: (cause) => new AccountRepoError({ message: "Database operation failed", cause }), - }) - - const tx = (f: DbTransactionCallback) => - Effect.try({ - try: () => Database.transaction(f), - catch: (cause) => new AccountRepoError({ message: "Database operation failed", cause }), - }) + const query = (effect: Effect.Effect) => + effect.pipe(Effect.mapError((cause) => new AccountRepoError({ message: "Database operation failed", cause }))) - const current = (db: DbClient) => { - const state = db.select().from(AccountStateTable).where(eq(AccountStateTable.id, ACCOUNT_STATE_ID)).get() + const current = Effect.fnUntraced(function* () { + const state = yield* db.select().from(AccountStateTable).where(eq(AccountStateTable.id, ACCOUNT_STATE_ID)).get() if (!state?.active_account_id) return - const account = db.select().from(AccountTable).where(eq(AccountTable.id, state.active_account_id)).get() + const account = yield* db.select().from(AccountTable).where(eq(AccountTable.id, state.active_account_id)).get() if (!account) return return { ...account, active_org_id: state.active_org_id ?? null } - } + }) - const state = (db: DbClient, accountID: AccountID, orgID: Option.Option) => { + const state = (accountID: AccountID, orgID: Option.Option) => { const id = Option.getOrNull(orgID) return db .insert(AccountStateTable) @@ -79,41 +68,46 @@ export const layer: Layer.Layer = Layer.effect( } const active = Effect.fn("AccountRepo.active")(() => - query((db) => current(db)).pipe(Effect.map((row) => (row ? Option.some(decode(row)) : Option.none()))), + query(current()).pipe(Effect.map((row) => (row ? Option.some(decode(row)) : Option.none()))), ) const list = Effect.fn("AccountRepo.list")(() => - query((db) => + query( db .select() .from(AccountTable) .all() - .map((row: AccountRow) => decode({ ...row, active_org_id: null })), + .pipe(Effect.map((rows) => rows.map((row: AccountRow) => decode({ ...row, active_org_id: null })))), ), ) const remove = Effect.fn("AccountRepo.remove")((accountID: AccountID) => - tx((db) => { - db.update(AccountStateTable) - .set({ active_account_id: null, active_org_id: null }) - .where(eq(AccountStateTable.active_account_id, accountID)) - .run() - db.delete(AccountTable).where(eq(AccountTable.id, accountID)).run() - }).pipe(Effect.asVoid), + query( + db.transaction((tx) => + Effect.gen(function* () { + yield* tx + .update(AccountStateTable) + .set({ active_account_id: null, active_org_id: null }) + .where(eq(AccountStateTable.active_account_id, accountID)) + .run() + yield* tx.delete(AccountTable).where(eq(AccountTable.id, accountID)).run() + }), + ), + ).pipe(Effect.asVoid), ) const use = Effect.fn("AccountRepo.use")((accountID: AccountID, orgID: Option.Option) => - query((db) => state(db, accountID, orgID)).pipe(Effect.asVoid), + query(state(accountID, orgID)).pipe(Effect.asVoid), ) const getRow = Effect.fn("AccountRepo.getRow")((accountID: AccountID) => - query((db) => db.select().from(AccountTable).where(eq(AccountTable.id, accountID)).get()).pipe( + query(db.select().from(AccountTable).where(eq(AccountTable.id, accountID)).get()).pipe( Effect.map(Option.fromNullishOr), ), ) const persistToken = Effect.fn("AccountRepo.persistToken")((input) => - query((db) => + query( db .update(AccountTable) .set({ @@ -127,31 +121,36 @@ export const layer: Layer.Layer = Layer.effect( ) const persistAccount = Effect.fn("AccountRepo.persistAccount")((input) => - tx((db) => { - const url = normalizeServerUrl(input.url) - - db.insert(AccountTable) - .values({ - id: input.id, - email: input.email, - url, - access_token: input.accessToken, - refresh_token: input.refreshToken, - token_expiry: input.expiry, - }) - .onConflictDoUpdate({ - target: AccountTable.id, - set: { - email: input.email, - url, - access_token: input.accessToken, - refresh_token: input.refreshToken, - token_expiry: input.expiry, - }, - }) - .run() - void state(db, input.id, input.orgID) - }).pipe(Effect.asVoid), + query( + db.transaction((tx) => + Effect.gen(function* () { + const url = normalizeServerUrl(input.url) + + yield* tx + .insert(AccountTable) + .values({ + id: input.id, + email: input.email, + url, + access_token: input.accessToken, + refresh_token: input.refreshToken, + token_expiry: input.expiry, + }) + .onConflictDoUpdate({ + target: AccountTable.id, + set: { + email: input.email, + url, + access_token: input.accessToken, + refresh_token: input.refreshToken, + token_expiry: input.expiry, + }, + }) + .run() + yield* state(input.id, input.orgID) + }), + ), + ).pipe(Effect.asVoid), ) return Service.of({ @@ -166,4 +165,6 @@ export const layer: Layer.Layer = Layer.effect( }), ) +export const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer)) + export * as AccountRepo from "./repo" diff --git a/packages/opencode/src/acp-next/agent.ts b/packages/opencode/src/acp-next/agent.ts deleted file mode 100644 index f0d3a77bcd4f..000000000000 --- a/packages/opencode/src/acp-next/agent.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { - RequestError, - type Agent as ACPAgent, - type AgentSideConnection, - type AuthenticateRequest, - type CancelNotification, - type InitializeRequest, - type LoadSessionRequest, - type NewSessionRequest, - type PromptRequest, -} from "@agentclientprotocol/sdk" -import { Effect } from "effect" -import type { OpencodeClient } from "@opencode-ai/sdk/v2" -import * as ACPNextError from "./error" -import * as ACPNextService from "./service" - -export function init({ sdk: _sdk }: { sdk: OpencodeClient }) { - return { - create: (connection: AgentSideConnection) => { - return new Agent(ACPNextService.make({ sdk: _sdk, connection })) - }, - } -} - -export class Agent implements ACPAgent { - constructor(private readonly service: ACPNextService.Interface) {} - - initialize(params: InitializeRequest) { - return run(this.service.initialize(params)) - } - - authenticate(params: AuthenticateRequest) { - return run(this.service.authenticate(params)) - } - - newSession(params: NewSessionRequest) { - return run(this.service.newSession(params)) - } - - loadSession(params: LoadSessionRequest) { - return run(this.service.loadSession(params)) - } - - prompt(params: PromptRequest) { - return run(this.service.prompt(params)) - } - - cancel(params: CancelNotification) { - return run(this.service.cancel(params)) - } -} - -function run(effect: Effect.Effect) { - return Effect.runPromise(effect.pipe(Effect.mapError(ACPNextError.toRequestError))).catch((defect: unknown) => { - if (defect instanceof RequestError) throw defect - throw ACPNextError.toRequestError(ACPNextError.fromUnknownDefect(defect)) - }) -} - -export * as ACPNext from "./agent" diff --git a/packages/opencode/src/acp-next/service.ts b/packages/opencode/src/acp-next/service.ts deleted file mode 100644 index 66ed5aaed0ca..000000000000 --- a/packages/opencode/src/acp-next/service.ts +++ /dev/null @@ -1,533 +0,0 @@ -import { - type AgentSideConnection, - type AuthenticateRequest, - type AuthenticateResponse, - type AuthMethod, - type CancelNotification, - type InitializeRequest, - type InitializeResponse, - type LoadSessionRequest, - type LoadSessionResponse, - type McpServer, - type NewSessionRequest, - type NewSessionResponse, - type PromptRequest, - type PromptResponse, -} from "@agentclientprotocol/sdk" -import { InstallationVersion } from "@opencode-ai/core/installation/version" -import type { OpencodeClient } from "@opencode-ai/sdk/v2" -import { Context, Effect, Layer, ManagedRuntime } from "effect" -import * as ACPNextError from "./error" -import { buildConfigOptions } from "./config-option" -import { Directory } from "./directory" -import { ACPNextSession } from "./session" -import { ModelID, ProviderID } from "@/provider/schema" -import { Provider } from "@/provider/provider" -import type { Command } from "@/command" - -export const AuthMethodID = "opencode-login" - -export type Error = ACPNextError.Error - -export type Interface = { - readonly initialize: (input: InitializeRequest) => Effect.Effect - readonly authenticate: (input: AuthenticateRequest) => Effect.Effect - readonly newSession: (input: NewSessionRequest) => Effect.Effect - readonly loadSession: (input: LoadSessionRequest) => Effect.Effect - readonly prompt: (input: PromptRequest) => Effect.Effect - readonly cancel: (input: CancelNotification) => Effect.Effect -} - -export class Service extends Context.Service()("@opencode/ACPNext/Service") {} - -export function make(input: { - sdk: OpencodeClient - connection?: Pick - directory?: Directory.Interface - session?: ACPNextSession.Interface -}): Interface { - const session = input.session ?? makeSessionService() - const directoryService = input.directory ?? makeDirectoryService(input.sdk) - const registeredMcp = new Map>() - - const initialize = Effect.fn("ACPNext.initialize")(function* (params: InitializeRequest) { - const authMethod: AuthMethod = { - description: "Run `opencode auth login` in the terminal", - name: "Login with opencode", - id: AuthMethodID, - } - - if (params.clientCapabilities?._meta?.["terminal-auth"] === true) { - authMethod._meta = { - "terminal-auth": { - command: "opencode", - args: ["auth", "login"], - label: "OpenCode Login", - }, - } - } - - return { - protocolVersion: 1, - agentCapabilities: { - loadSession: true, - mcpCapabilities: { - http: true, - sse: true, - }, - promptCapabilities: { - embeddedContext: true, - image: true, - }, - }, - authMethods: [authMethod], - agentInfo: { - name: "OpenCode", - version: InstallationVersion, - }, - } - }) - - const authenticate = Effect.fn("ACPNext.authenticate")(function* (params: AuthenticateRequest) { - if (params.methodId !== AuthMethodID) { - return yield* new ACPNextError.UnknownAuthMethodError({ methodId: params.methodId }) - } - return {} - }) - - const directorySnapshot = Effect.fn("ACPNext.directorySnapshot")(function* (cwd: string) { - return yield* directoryService.get(cwd) - }) - - const newSession = Effect.fn("ACPNext.newSession")(function* (params: NewSessionRequest) { - const snapshot = yield* directorySnapshot(params.cwd) - const selected = selectDefaultModel(snapshot) - const variant = selectVariant(snapshot, selected) - const modeId = snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined - const created = yield* request( - () => - input.sdk.session.create( - { - directory: params.cwd, - ...(modeId ? { agent: modeId } : {}), - model: { - providerID: selected.providerID, - id: selected.modelID, - ...(variant ? { variant } : {}), - }, - }, - { throwOnError: true }, - ), - "session", - ) - const state = yield* session.create({ - id: created.id, - cwd: params.cwd, - mcpServers: params.mcpServers, - model: selected, - variant, - modeId, - }) - - yield* registerMcpServers(input.sdk, registeredMcp, params.cwd, state.id, params.mcpServers) - yield* sendAvailableCommands(input.connection, state.id, snapshot) - - return { - sessionId: state.id, - configOptions: configOptions(snapshot, { - model: state.model ?? selected, - variant: state.variant, - modeId: state.modeId, - }), - } - }) - - const loadSession = Effect.fn("ACPNext.loadSession")(function* (params: LoadSessionRequest) { - const snapshot = yield* directorySnapshot(params.cwd) - yield* request( - () => input.sdk.session.get({ directory: params.cwd, sessionID: params.sessionId }, { throwOnError: true }), - "session", - ) - const messages = yield* request( - () => - input.sdk.session.messages( - { directory: params.cwd, sessionID: params.sessionId, limit: 100 }, - { throwOnError: true }, - ), - "session", - ) - const restored = restoreFromMessages(messages.map((item) => item.info)) - const model = restored.model ?? selectDefaultModel(snapshot) - const state = yield* session.load({ - id: params.sessionId, - cwd: params.cwd, - mcpServers: params.mcpServers, - model, - variant: restored.variant ?? selectVariant(snapshot, model), - modeId: restored.modeId ?? (snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined), - }) - - yield* registerMcpServers(input.sdk, registeredMcp, params.cwd, state.id, params.mcpServers) - yield* sendAvailableCommands(input.connection, state.id, snapshot) - - return { - sessionId: state.id, - configOptions: configOptions(snapshot, { - model: state.model ?? model, - variant: state.variant, - modeId: state.modeId, - }), - } - }) - - return { - initialize, - authenticate, - newSession, - loadSession, - prompt: Effect.fn("ACPNext.prompt")(function* (_input: PromptRequest) { - return yield* new ACPNextError.UnsupportedOperationError({ method: "session/prompt" }) - }), - cancel: Effect.fn("ACPNext.cancel")(function* (_input: CancelNotification) { - return yield* new ACPNextError.UnsupportedOperationError({ method: "session/cancel" }) - }), - } -} - -function makeSessionService() { - return ManagedRuntime.make(ACPNextSession.defaultLayer).runSync( - ACPNextSession.Service.use((service) => Effect.succeed(service)), - ) -} - -function makeDirectoryService(sdk: OpencodeClient) { - return ManagedRuntime.make( - Directory.layer.pipe( - Layer.provide( - Layer.succeed( - Directory.Loader, - Directory.Loader.of({ - load: (directory) => request(() => loadDirectorySnapshot(sdk, directory), "directory"), - }), - ), - ), - ), - ).runSync(Directory.Service.use((service) => Effect.succeed(service))) -} - -type ConfigState = { - readonly model: Directory.DefaultModel - readonly variant?: string - readonly modeId?: string -} - -type SdkResponse = { - readonly data?: T - readonly error?: unknown -} - -type MessageInfo = { - readonly role?: string - readonly model?: { - readonly providerID?: string - readonly modelID?: string - readonly variant?: string - } - readonly providerID?: string - readonly modelID?: string - readonly variant?: string - readonly mode?: string - readonly agent?: string -} - -function request(fn: () => Promise>, service?: string) { - return Effect.tryPromise({ - try: async () => { - const result = await fn() - if (isSdkResponse(result)) { - if (result.error) throw result.error - if (result.data !== undefined) return result.data - } - return result as T - }, - catch: (error) => fromUnknownError(error, service), - }) -} - -async function loadDirectorySnapshot(sdk: OpencodeClient, directory: string) { - const [providersResponse, agentsResponse, commandsResponse, skillsResponse] = await Promise.all([ - sdk.config.providers({ directory }, { throwOnError: true }), - sdk.app.agents({ directory }, { throwOnError: true }), - sdk.command.list({ directory }, { throwOnError: true }), - sdk.app.skills({ directory }, { throwOnError: true }), - ]) - const providersData = providersResponse.data! - const agents = agentsResponse.data! - const commandsData = commandsResponse.data! - const skills = skillsResponse.data! - const providers = Object.fromEntries(providersData.providers.map((provider) => [provider.id, provider])) as Record< - ProviderID, - Provider.Info - > - const defaultModel = await defaultModelFromSdk(sdk, directory, providers) - const modes = agents - .filter((agent) => agent.mode !== "subagent" && agent.hidden !== true) - .map((agent) => ({ - id: agent.name, - name: agent.name, - ...(agent.description ? { description: agent.description } : {}), - })) - const commands = [ - ...commandsData, - ...skills - .filter((skill) => !commandsData.some((command) => command.name === skill.name)) - .map((skill) => ({ - name: skill.name, - description: skill.description, - source: "skill" as const, - template: skill.content, - hints: [], - })), - ] as Command.Info[] - - return Directory.build({ - directory, - providers, - modes, - defaultModeID: agents.find((agent) => agent.mode === "primary" && agent.hidden !== true)?.name ?? "build", - commands: commands.toSorted((a, b) => a.name.localeCompare(b.name)), - ...(defaultModel ? { defaultModel } : {}), - }) -} - -async function defaultModelFromSdk( - sdk: OpencodeClient, - directory: string, - providers: Record, -): Promise { - const configured = await sdk.config - .get({ directory }, { throwOnError: true }) - .then((response) => (response.data?.model ? Provider.parseModel(response.data.model) : undefined)) - .catch(() => undefined) - if (configured && providers[configured.providerID]?.models[configured.modelID]) return configured - - const lastUsed = await lastUsedModel(sdk, directory, providers) - if (lastUsed) return lastUsed - - const opencodeProvider = providers[ProviderID.make("opencode")] - const opencodeModel = opencodeProvider ? Provider.sort(Object.values(opencodeProvider.models))[0] : undefined - if (opencodeProvider && opencodeModel) return { providerID: opencodeProvider.id, modelID: opencodeModel.id } - - const best = Provider.sort(Object.values(providers).flatMap((provider) => Object.values(provider.models)))[0] - if (best) return { providerID: best.providerID, modelID: best.id } - if (configured) return configured -} - -async function lastUsedModel( - sdk: OpencodeClient, - directory: string, - providers: Record, -): Promise { - const session = await sdk.session - .list({ directory, roots: true, limit: 1 }, { throwOnError: true }) - .then((response) => response.data?.[0]) - .catch(() => undefined) - if (!session) return - - const lastUser = await sdk.session - .messages({ directory, sessionID: session.id, limit: 20 }, { throwOnError: true }) - .then((response) => response.data?.findLast((message) => message.info.role === "user")?.info) - .catch(() => undefined) - if (lastUser?.role !== "user") return - if (!providers[ProviderID.make(lastUser.model.providerID)]?.models[ModelID.make(lastUser.model.modelID)]) return - - return { - providerID: ProviderID.make(lastUser.model.providerID), - modelID: ModelID.make(lastUser.model.modelID), - } -} - -function selectDefaultModel(snapshot: Directory.Snapshot) { - if (snapshot.defaultModel) return snapshot.defaultModel - const model = snapshot.modelOptions[0] - if (model) return { providerID: model.providerID, modelID: model.modelID } - return { providerID: "unknown" as ProviderID, modelID: "unknown" as ModelID } -} - -function selectVariant(snapshot: Directory.Snapshot, model: Directory.DefaultModel) { - const variants = Directory.variants(snapshot, model) - if (!variants) return - if (variants.default) return "default" - return Object.keys(variants)[0] -} - -function configOptions(snapshot: Directory.Snapshot, session: ConfigState) { - return buildConfigOptions({ - providers: Object.values(snapshot.providers), - currentModel: session.model, - currentVariant: session.variant, - modes: snapshot.availableModes, - currentModeId: session.modeId, - }) -} - -function sendAvailableCommands( - connection: Pick | undefined, - sessionId: string, - snapshot: Directory.Snapshot, -) { - if (!connection) return Effect.void - return Effect.sync(() => { - setTimeout(() => { - void connection.sessionUpdate({ - sessionId, - update: { - sessionUpdate: "available_commands_update", - availableCommands: snapshot.availableCommands.map((command) => ({ - name: command.name, - description: command.description ?? "", - })), - }, - }) - }, 0) - }) -} - -function registerMcpServers( - sdk: OpencodeClient, - registered: Map>, - directory: string, - sessionId: string, - servers: readonly McpServer[], -) { - const current = registered.get(sessionId) ?? new Set() - registered.set(sessionId, current) - const pending = new Set() - - return Effect.all( - servers - .map((server) => ({ server, config: mcpConfig(server) })) - .filter((entry) => { - const key = mcpRegistrationKey(entry.server.name, entry.config) - if (current.has(key) || pending.has(key)) return false - pending.add(key) - return true - }) - .map((entry) => - request( - () => - sdk.mcp.add( - { - directory, - name: entry.server.name, - config: entry.config, - }, - { throwOnError: true }, - ), - "mcp", - ).pipe( - Effect.tap(() => Effect.sync(() => current.add(mcpRegistrationKey(entry.server.name, entry.config)))), - Effect.ignore, - ), - ), - { concurrency: "unbounded" }, - ).pipe(Effect.asVoid) -} - -function mcpRegistrationKey(name: string, config: ReturnType) { - return `${name}:${stableStringify(config)}` -} - -function mcpConfig(server: McpServer) { - if ("type" in server) { - return { - type: "remote" as const, - url: server.url, - headers: Object.fromEntries(server.headers.map((header) => [header.name, header.value])), - } - } - return { - type: "local" as const, - command: [server.command, ...server.args], - environment: Object.fromEntries(server.env.map((entry) => [entry.name, entry.value])), - } -} - -function stableStringify(value: unknown): string { - if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]` - if (!value || typeof value !== "object") return JSON.stringify(value) - return `{${Object.entries(value) - .toSorted(([a], [b]) => a.localeCompare(b)) - .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`) - .join(",")}}` -} - -function restoreFromMessages(messages: readonly MessageInfo[]) { - const user = messages.findLast( - (message) => message.role === "user" && message.model?.providerID && message.model.modelID, - ) - if (user?.model?.providerID && user.model.modelID) { - return { - model: { providerID: user.model.providerID as ProviderID, modelID: user.model.modelID as ModelID }, - variant: user.model.variant, - modeId: user.agent, - } - } - - const assistant = messages.findLast((message) => message.providerID && message.modelID) - if (assistant?.providerID && assistant.modelID) { - return { - model: { providerID: assistant.providerID as ProviderID, modelID: assistant.modelID as ModelID }, - variant: assistant.variant, - modeId: assistant.mode ?? assistant.agent, - } - } - - return {} -} - -function isSdkResponse(value: T | SdkResponse): value is SdkResponse { - return typeof value === "object" && value !== null && ("data" in value || "error" in value) -} - -function fromUnknownError(error: unknown, service?: string): Error { - if (isACPNextError(error)) return error - if (isAuthRequired(error)) { - return new ACPNextError.AuthRequiredError({ providerId: findProviderID(error) }) - } - return new ACPNextError.ServiceFailureError({ safeMessage: "OpenCode service failure", service }) -} - -function isACPNextError(error: unknown): error is Error { - return ( - typeof error === "object" && - error !== null && - "_tag" in error && - typeof error._tag === "string" && - error._tag.startsWith("ACPNext") - ) -} - -function isAuthRequired(value: unknown): boolean { - if (typeof value !== "object" || value === null) return false - if (value instanceof Error && (value.name === "ProviderAuthError" || value.name === "LoadAPIKeyError")) return true - if ( - value instanceof Error && - (value.message.includes("ProviderAuthError") || value.message.includes("LoadAPIKeyError")) - ) { - return true - } - if ("name" in value && (value.name === "ProviderAuthError" || value.name === "LoadAPIKeyError")) return true - if ("_tag" in value && (value._tag === "ProviderAuthError" || value._tag === "LoadAPIKeyError")) return true - if ("error" in value && isAuthRequired(value.error)) return true - if ("data" in value && isAuthRequired(value.data)) return true - return false -} - -function findProviderID(value: unknown): string | undefined { - if (typeof value !== "object" || value === null) return - if ("providerID" in value && typeof value.providerID === "string") return value.providerID - if ("providerId" in value && typeof value.providerId === "string") return value.providerId - if ("data" in value) return findProviderID(value.data) - if ("error" in value) return findProviderID(value.error) -} diff --git a/packages/opencode/src/acp-next/session.ts b/packages/opencode/src/acp-next/session.ts deleted file mode 100644 index 7a969c867f5f..000000000000 --- a/packages/opencode/src/acp-next/session.ts +++ /dev/null @@ -1,215 +0,0 @@ -import type { McpServer } from "@agentclientprotocol/sdk" -import { Context, Effect, Layer, Ref } from "effect" -import type { ModelID, ProviderID } from "../provider/schema" -import * as ACPNextError from "./error" - -export type SelectedModel = { - providerID: ProviderID - modelID: ModelID -} - -export type KnownMessagePartMetadata = { - messageId: string - partId: string - toolCallId?: string - metadata?: unknown -} - -export type Info = { - id: string - cwd: string - mcpServers: readonly McpServer[] - createdAt: Date - model?: SelectedModel - variant?: string - modeId?: string - knownParts: ReadonlyMap -} - -export type StoreInput = { - id: string - cwd: string - mcpServers?: readonly McpServer[] - createdAt?: Date - model?: SelectedModel - variant?: string - modeId?: string -} - -export type RecordPartMetadataInput = { - sessionId: string - messageId: string - partId: string - toolCallId?: string - metadata?: unknown -} - -export type PartMetadataLookupInput = { - sessionId: string - messageId: string - partId: string -} - -export type Interface = { - readonly create: (input: StoreInput) => Effect.Effect - readonly load: (input: StoreInput) => Effect.Effect - readonly get: (sessionId: string) => Effect.Effect - readonly tryGet: (sessionId: string) => Effect.Effect - readonly remove: (sessionId: string) => Effect.Effect - readonly setModel: ( - sessionId: string, - model: SelectedModel | undefined, - ) => Effect.Effect - readonly getModel: (sessionId: string) => Effect.Effect - readonly setVariant: ( - sessionId: string, - variant: string | undefined, - ) => Effect.Effect - readonly getVariant: (sessionId: string) => Effect.Effect - readonly setMode: ( - sessionId: string, - modeId: string | undefined, - ) => Effect.Effect - readonly getMode: (sessionId: string) => Effect.Effect - readonly recordPartMetadata: ( - input: RecordPartMetadataInput, - ) => Effect.Effect - readonly getPartMetadata: ( - input: PartMetadataLookupInput, - ) => Effect.Effect - readonly tryGetPartMetadata: (input: PartMetadataLookupInput) => Effect.Effect -} - -export class Service extends Context.Service()("@opencode/ACPNext/Session") {} - -type State = Map - -export const layer = Layer.effect( - Service, - Effect.gen(function* () { - const sessions = yield* Ref.make(new Map()) - - const store = Effect.fn("ACPNext.Session.store")(function* (input: StoreInput) { - const session = makeSession(input) - yield* Ref.update(sessions, (state) => new Map(state).set(session.id, session)) - return snapshot(session) - }) - - const tryGet = Effect.fn("ACPNext.Session.tryGet")(function* (sessionId: string) { - const session = (yield* Ref.get(sessions)).get(sessionId) - if (!session) return - return snapshot(session) - }) - - const get = Effect.fn("ACPNext.Session.get")(function* (sessionId: string) { - const session = yield* tryGet(sessionId) - if (session) return session - return yield* new ACPNextError.SessionNotFoundError({ sessionId }) - }) - - const update = Effect.fn("ACPNext.Session.update")(function* (sessionId: string, fn: (session: Info) => Info) { - const result = yield* Ref.modify(sessions, (state) => { - const session = state.get(sessionId) - if (!session) return [undefined, state] as const - const next = fn(session) - return [snapshot(next), new Map(state).set(sessionId, next)] as const - }) - if (result) return result - return yield* new ACPNextError.SessionNotFoundError({ sessionId }) - }) - - const remove = Effect.fn("ACPNext.Session.remove")(function* (sessionId: string) { - return yield* Ref.modify(sessions, (state) => { - const session = state.get(sessionId) - if (!session) return [undefined, state] as const - const next = new Map(state) - next.delete(sessionId) - return [snapshot(session), next] as const - }) - }) - - const setModel: Interface["setModel"] = Effect.fn("ACPNext.Session.setModel")((sessionId, model) => - update(sessionId, (session) => ({ ...session, model })), - ) - - const setVariant: Interface["setVariant"] = Effect.fn("ACPNext.Session.setVariant")((sessionId, variant) => - update(sessionId, (session) => ({ ...session, variant })), - ) - - const setMode: Interface["setMode"] = Effect.fn("ACPNext.Session.setMode")((sessionId, modeId) => - update(sessionId, (session) => ({ ...session, modeId })), - ) - - const recordPartMetadata: Interface["recordPartMetadata"] = Effect.fn("ACPNext.Session.recordPartMetadata")(( - input, - ) => { - const metadata = { - messageId: input.messageId, - partId: input.partId, - toolCallId: input.toolCallId, - metadata: input.metadata, - } - return update(input.sessionId, (session) => ({ - ...session, - knownParts: new Map(session.knownParts).set(partMetadataKey(input), metadata), - })).pipe(Effect.as(metadata)) - }) - - return Service.of({ - create: store, - load: store, - get, - tryGet, - remove, - setModel, - getModel: Effect.fn("ACPNext.Session.getModel")(function* (sessionId) { - return (yield* get(sessionId)).model - }), - setVariant, - getVariant: Effect.fn("ACPNext.Session.getVariant")(function* (sessionId) { - return (yield* get(sessionId)).variant - }), - setMode, - getMode: Effect.fn("ACPNext.Session.getMode")(function* (sessionId) { - return (yield* get(sessionId)).modeId - }), - recordPartMetadata, - getPartMetadata: Effect.fn("ACPNext.Session.getPartMetadata")(function* (input) { - return (yield* get(input.sessionId)).knownParts.get(partMetadataKey(input)) - }), - tryGetPartMetadata: Effect.fn("ACPNext.Session.tryGetPartMetadata")(function* (input) { - return (yield* tryGet(input.sessionId))?.knownParts.get(partMetadataKey(input)) - }), - }) - }), -) - -export const defaultLayer = layer - -function makeSession(input: StoreInput): Info { - return { - id: input.id, - cwd: input.cwd, - mcpServers: [...(input.mcpServers ?? [])], - createdAt: input.createdAt ? new Date(input.createdAt) : new Date(), - model: input.model, - variant: input.variant, - modeId: input.modeId, - knownParts: new Map(), - } -} - -function snapshot(session: Info): Info { - return { - ...session, - mcpServers: [...session.mcpServers], - createdAt: new Date(session.createdAt), - knownParts: new Map(session.knownParts), - } -} - -function partMetadataKey(input: { messageId: string; partId: string }) { - return `${input.messageId}:${input.partId}` -} - -export * as ACPNextSession from "./session" diff --git a/packages/opencode/src/acp/README.md b/packages/opencode/src/acp/README.md deleted file mode 100644 index aab33259bb18..000000000000 --- a/packages/opencode/src/acp/README.md +++ /dev/null @@ -1,174 +0,0 @@ -# ACP (Agent Client Protocol) Implementation - -This directory contains a clean, protocol-compliant implementation of the [Agent Client Protocol](https://agentclientprotocol.com/) for opencode. - -## Architecture - -The implementation follows a clean separation of concerns: - -### Core Components - -- **`agent.ts`** - Implements the `Agent` interface from `@agentclientprotocol/sdk` - - Handles initialization and capability negotiation - - Manages session lifecycle (`session/new`, `session/load`) - - Processes prompts and returns responses - - Properly implements ACP protocol v1 - -- **`client.ts`** - Implements the `Client` interface for client-side capabilities - - File operations (`readTextFile`, `writeTextFile`) - - Permission requests (auto-approves for now) - - Terminal support (stub implementation) - -- **`session.ts`** - Session state management - - Creates and tracks ACP sessions - - Maps ACP sessions to internal opencode sessions - - Maintains working directory context - - Handles MCP server configurations - -- **`server.ts`** - ACP server startup and lifecycle - - Sets up JSON-RPC over stdio using the official library - - Manages graceful shutdown on SIGTERM/SIGINT - - Provides Instance context for the agent - -- **`types.ts`** - Type definitions for internal use - -## Usage - -### Command Line - -```bash -# Start the ACP server in the current directory -opencode acp - -# Start in a specific directory -opencode acp --cwd /path/to/project -``` - -### Question Tool Opt-In - -ACP excludes `QuestionTool` by default. - -```bash -OPENCODE_ENABLE_QUESTION_TOOL=1 opencode acp -``` - -Enable this only for ACP clients that support interactive question prompts. - -### Programmatic - -```typescript -import { ACPServer } from "./acp/server" - -await ACPServer.start() -``` - -### Integration with Zed - -Add to your Zed configuration (`~/.config/zed/settings.json`): - -```json -{ - "agent_servers": { - "OpenCode": { - "command": "opencode", - "args": ["acp"] - } - } -} -``` - -## Protocol Compliance - -This implementation follows the ACP specification v1: - -✅ **Initialization** - -- Proper `initialize` request/response with protocol version negotiation -- Capability advertisement (`agentCapabilities`) -- Authentication support (stub) - -✅ **Session Management** - -- `session/new` - Create new conversation sessions -- `session/load` - Resume existing sessions (basic support) -- Working directory context (`cwd`) -- MCP server configuration support - -✅ **Prompting** - -- `session/prompt` - Process user messages -- Content block handling (text, resources) -- Response with stop reasons - -✅ **Client Capabilities** - -- File read/write operations -- Permission requests -- Terminal support (stub for future) - -## Current Limitations - -### Not Yet Implemented - -1. **Streaming Responses** - Currently returns complete responses instead of streaming via `session/update` notifications -2. **Tool Call Reporting** - Doesn't report tool execution progress -3. **Session Modes** - No mode switching support yet -4. **Authentication** - No actual auth implementation -5. **Terminal Support** - Placeholder only -6. **Session Persistence** - `session/load` doesn't restore actual conversation history - -### Future Enhancements - -- **Real-time Streaming**: Implement `session/update` notifications for progressive responses -- **Tool Call Visibility**: Report tool executions as they happen -- **Session Persistence**: Save and restore full conversation history -- **Mode Support**: Implement different operational modes (ask, code, etc.) -- **Enhanced Permissions**: More sophisticated permission handling -- **Terminal Integration**: Full terminal support via opencode's bash tool - -## Testing - -```bash -# Run ACP tests -bun test test/acp.test.ts - -# Test manually with stdio -echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}' | opencode acp -``` - -## Design Decisions - -### Why the Official Library? - -We use `@agentclientprotocol/sdk` instead of implementing JSON-RPC ourselves because: - -- Ensures protocol compliance -- Handles edge cases and future protocol versions -- Reduces maintenance burden -- Works with other ACP clients automatically - -### Clean Architecture - -Each component has a single responsibility: - -- **Agent** = Protocol interface -- **Client** = Client-side operations -- **Session** = State management -- **Server** = Lifecycle and I/O - -This makes the codebase maintainable and testable. - -### Mapping to OpenCode - -ACP sessions map cleanly to opencode's internal session model: - -- ACP `session/new` → creates internal Session -- ACP `session/prompt` → uses SessionPrompt.prompt() -- Working directory context preserved per-session -- Tool execution uses existing ToolRegistry - -## References - -- [ACP Specification](https://agentclientprotocol.com/) -- [TypeScript Library](https://github.com/agentclientprotocol/typescript-sdk) -- [Protocol Examples](https://github.com/agentclientprotocol/typescript-sdk/tree/main/src/examples) diff --git a/packages/opencode/src/acp/agent.ts b/packages/opencode/src/acp/agent.ts index 8b74b9c9bad3..a7c59a261551 100644 --- a/packages/opencode/src/acp/agent.ts +++ b/packages/opencode/src/acp/agent.ts @@ -3,1964 +3,93 @@ import { type Agent as ACPAgent, type AgentSideConnection, type AuthenticateRequest, - type AuthMethod, type CancelNotification, type CloseSessionRequest, - type CloseSessionResponse, type ForkSessionRequest, - type ForkSessionResponse, type InitializeRequest, - type InitializeResponse, type ListSessionsRequest, - type ListSessionsResponse, type LoadSessionRequest, type NewSessionRequest, - type PermissionOption, - type PlanEntry, type PromptRequest, type ResumeSessionRequest, - type ResumeSessionResponse, - type Role, - type SessionInfo, - type SetSessionModelRequest, - type SessionConfigOption, type SetSessionConfigOptionRequest, - type SetSessionConfigOptionResponse, + type SetSessionModelRequest, type SetSessionModeRequest, - type SetSessionModeResponse, - type ToolCallContent, - type ToolKind, - type Usage, } from "@agentclientprotocol/sdk" - -import * as Log from "@opencode-ai/core/util/log" -import { pathToFileURL } from "url" -import { Filesystem } from "@/util/filesystem" -import { Hash } from "@opencode-ai/core/util/hash" -import { ACPSessionManager } from "./session" -import type { ACPConfig } from "./types" -import { ACPRuntime } from "./runtime" -import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "../provider/schema" -import { MessageV2 } from "@/session/message-v2" -import { ConfigMCP } from "@/config/mcp" -import { Todo } from "@/session/todo" -import { Result, Schema } from "effect" -import { LoadAPIKeyError } from "ai" -import type { AssistantMessage, Event, OpencodeClient, SessionMessageResponse, ToolPart } from "@opencode-ai/sdk/v2" -import { applyPatch } from "diff" -import { InstallationVersion } from "@opencode-ai/core/installation/version" -import { ShellID } from "@/tool/shell/id" - -type ModeOption = { id: string; name: string; description?: string } -type ModelOption = { modelId: string; name: string } -const decodeTodos = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Array(Todo.Info))) - -const DEFAULT_VARIANT_VALUE = "default" - -const log = Log.create({ service: "acp-agent" }) - -async function getContextLimit( - sdk: OpencodeClient, - providerID: ProviderID, - modelID: ModelID, - directory: string, -): Promise { - const providers = await sdk.config - .providers({ directory }) - .then((x) => x.data?.providers ?? []) - .catch((error) => { - log.error("failed to get providers for context limit", { error }) - return [] - }) - - const provider = providers.find((p) => p.id === providerID) - const model = provider?.models[modelID] - return model?.limit.context ?? null -} - -async function sendUsageUpdate( - connection: AgentSideConnection, - sdk: OpencodeClient, - sessionID: string, - directory: string, -): Promise { - const messages = await sdk.session - .messages({ sessionID, directory }, { throwOnError: true }) - .then((x) => x.data) - .catch((error) => { - log.error("failed to fetch messages for usage update", { error }) - return undefined - }) - - if (!messages) return - - const assistantMessages = messages.filter( - (m): m is { info: AssistantMessage; parts: SessionMessageResponse["parts"] } => m.info.role === "assistant", - ) - - const lastAssistant = assistantMessages[assistantMessages.length - 1] - if (!lastAssistant) return - - const msg = lastAssistant.info - if (!msg.providerID || !msg.modelID) return - const size = await getContextLimit(sdk, ProviderID.make(msg.providerID), ModelID.make(msg.modelID), directory) - - if (!size) { - // Cannot calculate usage without known context size - return - } - - const used = msg.tokens.input + (msg.tokens.cache?.read ?? 0) - const totalCost = assistantMessages.reduce((sum, m) => sum + m.info.cost, 0) - - await connection - .sessionUpdate({ - sessionId: sessionID, - update: { - sessionUpdate: "usage_update", - used, - size, - cost: { amount: totalCost, currency: "USD" }, - }, - }) - .catch((error) => { - log.error("failed to send usage update", { error }) - }) -} +import { Effect } from "effect" +import type { OpencodeClient } from "@opencode-ai/sdk/v2" +import * as ACPError from "./error" +import * as ACPService from "./service" export function init({ sdk: _sdk }: { sdk: OpencodeClient }) { return { - create: (connection: AgentSideConnection, fullConfig: ACPConfig) => { - return new Agent(connection, fullConfig) + create: (connection: AgentSideConnection) => { + return new Agent(ACPService.make({ sdk: _sdk, connection })) }, } } export class Agent implements ACPAgent { - private connection: AgentSideConnection - private config: ACPConfig - private sdk: OpencodeClient - private sessionManager: ACPSessionManager - private eventAbort = new AbortController() - private eventStarted = false - private shellSnapshots = new Map() - private toolStarts = new Set() - private permissionQueues = new Map>() - private permissionOptions: PermissionOption[] = [ - { optionId: "once", kind: "allow_once", name: "Allow once" }, - { optionId: "always", kind: "allow_always", name: "Always allow" }, - { optionId: "reject", kind: "reject_once", name: "Reject" }, - ] - - constructor(connection: AgentSideConnection, config: ACPConfig) { - this.connection = connection - this.config = config - this.sdk = config.sdk - this.sessionManager = new ACPSessionManager(this.sdk) - this.startEventSubscription() - } - - private startEventSubscription() { - if (this.eventStarted) return - this.eventStarted = true - this.runEventSubscription().catch((error) => { - if (this.eventAbort.signal.aborted) return - log.error("event subscription failed", { error }) - }) - } - - private async runEventSubscription() { - while (true) { - if (this.eventAbort.signal.aborted) return - const events = await this.sdk.global.event({ - signal: this.eventAbort.signal, - }) - for await (const event of events.stream) { - if (this.eventAbort.signal.aborted) return - const payload = event?.payload - if (!payload) continue - await this.handleEvent(payload as Event).catch((error) => { - log.error("failed to handle event", { error, type: payload.type }) - }) - } - } - } - - private async handleEvent(event: Event) { - switch (event.type) { - case "permission.asked": { - const permission = event.properties - const session = this.sessionManager.tryGet(permission.sessionID) - if (!session) return - - const prev = this.permissionQueues.get(permission.sessionID) ?? Promise.resolve() - const next = prev - .then(async () => { - const directory = session.cwd - - const res = await this.connection - .requestPermission({ - sessionId: permission.sessionID, - toolCall: { - toolCallId: permission.tool?.callID ?? permission.id, - status: "pending", - title: permission.permission, - rawInput: permission.metadata, - kind: toToolKind(permission.permission), - locations: toLocations(permission.permission, permission.metadata), - }, - options: this.permissionOptions, - }) - .catch(async (error) => { - log.error("failed to request permission from ACP", { - error, - permissionID: permission.id, - sessionID: permission.sessionID, - }) - await this.sdk.permission.reply({ - requestID: permission.id, - reply: "reject", - directory, - }) - return undefined - }) - - if (!res) return - if (res.outcome.outcome !== "selected") { - await this.sdk.permission.reply({ - requestID: permission.id, - reply: "reject", - directory, - }) - return - } - - if (res.outcome.optionId !== "reject" && permission.permission == "edit") { - const metadata = permission.metadata || {} - const filepath = typeof metadata["filepath"] === "string" ? metadata["filepath"] : "" - const diff = typeof metadata["diff"] === "string" ? metadata["diff"] : "" - const content = (await Filesystem.exists(filepath)) ? await Filesystem.readText(filepath) : "" - const newContent = getNewContent(content, diff) - - if (newContent) { - void this.connection.writeTextFile({ - sessionId: session.id, - path: filepath, - content: newContent, - }) - } - } - - await this.sdk.permission.reply({ - requestID: permission.id, - reply: res.outcome.optionId as "once" | "always" | "reject", - directory, - }) - }) - .catch((error) => { - log.error("failed to handle permission", { error, permissionID: permission.id }) - }) - .finally(() => { - if (this.permissionQueues.get(permission.sessionID) === next) { - this.permissionQueues.delete(permission.sessionID) - } - }) - this.permissionQueues.set(permission.sessionID, next) - return - } - - case "message.part.updated": { - log.info("message part updated", { event: event.properties }) - const props = event.properties - const part = props.part - const session = this.sessionManager.tryGet(part.sessionID) - if (!session) return - const sessionId = session.id - - if (part.type === "tool") { - await this.toolStart(sessionId, part) - - switch (part.state.status) { - case "pending": - this.shellSnapshots.delete(part.callID) - return - - case "running": - const output = this.shellOutput(part) - const content: ToolCallContent[] = [] - if (output) { - const hash = Hash.fast(output) - if (part.tool === ShellID.ToolID) { - if (this.shellSnapshots.get(part.callID) === hash) { - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "in_progress", - kind: toToolKind(part.tool), - title: part.tool, - locations: toLocations(part.tool, part.state.input), - rawInput: part.state.input, - }, - }) - .catch((error) => { - log.error("failed to send tool in_progress to ACP", { error }) - }) - return - } - this.shellSnapshots.set(part.callID, hash) - } - content.push({ - type: "content", - content: { - type: "text", - text: output, - }, - }) - } - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "in_progress", - kind: toToolKind(part.tool), - title: part.tool, - locations: toLocations(part.tool, part.state.input), - rawInput: part.state.input, - ...(content.length > 0 && { content }), - }, - }) - .catch((error) => { - log.error("failed to send tool in_progress to ACP", { error }) - }) - return - - case "completed": { - this.toolStarts.delete(part.callID) - this.shellSnapshots.delete(part.callID) - const kind = toToolKind(part.tool) - const content = completedToolContent(part, kind) - - if (part.tool === "todowrite") { - const parsedTodos = decodeTodos(part.state.output) - if (Result.isSuccess(parsedTodos)) { - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "plan", - entries: parsedTodos.success.map((todo) => { - const status: PlanEntry["status"] = - todo.status === "cancelled" ? "completed" : (todo.status as PlanEntry["status"]) - return { - priority: "medium", - status, - content: todo.content, - } - }), - }, - }) - .catch((error) => { - log.error("failed to send session update for todo", { error }) - }) - } else { - log.error("failed to parse todo output", { error: parsedTodos.failure }) - } - } - - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "completed", - kind, - content, - title: part.state.title, - rawInput: part.state.input, - rawOutput: completedToolRawOutput(part), - }, - }) - .catch((error) => { - log.error("failed to send tool completed to ACP", { error }) - }) - return - } - case "error": - this.toolStarts.delete(part.callID) - this.shellSnapshots.delete(part.callID) - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "failed", - kind: toToolKind(part.tool), - title: part.tool, - rawInput: part.state.input, - content: [ - { - type: "content", - content: { - type: "text", - text: part.state.error, - }, - }, - ], - rawOutput: { - error: part.state.error, - metadata: part.state.metadata, - }, - }, - }) - .catch((error) => { - log.error("failed to send tool error to ACP", { error }) - }) - return - } - } - - // ACP clients already know the prompt they just submitted, so replaying - // live user parts duplicates the message. We still replay user history in - // loadSession() and forkSession() via processMessage(). - if (part.type !== "text" && part.type !== "file") return - - return - } - - case "message.part.delta": { - const props = event.properties - const session = this.sessionManager.tryGet(props.sessionID) - if (!session) return - const sessionId = session.id - - const message = await this.sdk.session - .message( - { - sessionID: props.sessionID, - messageID: props.messageID, - directory: session.cwd, - }, - { throwOnError: true }, - ) - .then((x) => x.data) - .catch((error) => { - log.error("unexpected error when fetching message", { error }) - return undefined - }) - - if (!message || message.info.role !== "assistant") return - - const part = message.parts.find((p) => p.id === props.partID) - if (!part) return - - if (part.type === "text" && props.field === "text" && part.ignored !== true) { - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - messageId: props.messageID, - content: { - type: "text", - text: props.delta, - }, - }, - }) - .catch((error) => { - log.error("failed to send text delta to ACP", { error }) - }) - return - } - - if (part.type === "reasoning" && props.field === "text") { - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "agent_thought_chunk", - messageId: props.messageID, - content: { - type: "text", - text: props.delta, - }, - }, - }) - .catch((error) => { - log.error("failed to send reasoning delta to ACP", { error }) - }) - } - return - } - } - } - - async initialize(params: InitializeRequest): Promise { - log.info("initialize", { protocolVersion: params.protocolVersion }) - - const authMethod: AuthMethod = { - description: "Run `opencode auth login` in the terminal", - name: "Login with opencode", - id: "opencode-login", - } - - // If client supports terminal-auth capability, use that instead. - if (params.clientCapabilities?._meta?.["terminal-auth"] === true) { - authMethod._meta = { - "terminal-auth": { - command: "opencode", - args: ["auth", "login"], - label: "OpenCode Login", - }, - } - } - - return { - protocolVersion: 1, - agentCapabilities: { - loadSession: true, - mcpCapabilities: { - http: true, - sse: true, - }, - promptCapabilities: { - embeddedContext: true, - image: true, - }, - sessionCapabilities: { - close: {}, - fork: {}, - list: {}, - resume: {}, - }, - }, - authMethods: [authMethod], - agentInfo: { - name: "OpenCode", - version: InstallationVersion, - }, - } - } - - async authenticate(_params: AuthenticateRequest) { - throw new Error("Authentication not implemented") - } - - async newSession(params: NewSessionRequest) { - const directory = params.cwd - try { - const model = await defaultModel(this.config, directory) - - // Store ACP session state - const state = await this.sessionManager.create(params.cwd, params.mcpServers, model) - const sessionId = state.id + constructor(private readonly service: ACPService.Interface) {} - log.info("creating_session", { sessionId, mcpServers: params.mcpServers.length }) - - const load = await this.loadSessionMode({ - cwd: directory, - mcpServers: params.mcpServers, - sessionId, - }) - - return { - sessionId, - configOptions: load.configOptions, - models: load.models, - modes: load.modes, - _meta: load._meta, - } - } catch (e) { - const error = MessageV2.fromError(e, { - providerID: ProviderID.make(this.config.defaultModel?.providerID ?? "unknown"), - }) - if (LoadAPIKeyError.isInstance(error)) { - throw RequestError.authRequired() - } - throw e - } + initialize(params: InitializeRequest) { + return run(this.service.initialize(params)) } - async loadSession(params: LoadSessionRequest) { - const directory = params.cwd - const sessionId = params.sessionId - - try { - const model = await defaultModel(this.config, directory) - - // Store ACP session state - await this.sessionManager.load(sessionId, params.cwd, params.mcpServers, model) - - const messages = await this.loadSessionMessages(directory, sessionId) - this.restoreSessionStateFromMessages(sessionId, messages) - - log.info("load_session", { sessionId, mcpServers: params.mcpServers.length }) - - const result = await this.loadSessionMode({ - cwd: directory, - mcpServers: params.mcpServers, - sessionId, - }) - - for (const msg of messages ?? []) { - log.debug("replay message", msg) - await this.processMessage(msg) - } - - await sendUsageUpdate(this.connection, this.sdk, sessionId, directory) - - return result - } catch (e) { - const error = MessageV2.fromError(e, { - providerID: ProviderID.make(this.config.defaultModel?.providerID ?? "unknown"), - }) - if (LoadAPIKeyError.isInstance(error)) { - throw RequestError.authRequired() - } - throw e - } + authenticate(params: AuthenticateRequest) { + return run(this.service.authenticate(params)) } - async listSessions(params: ListSessionsRequest): Promise { - try { - const cursor = params.cursor ? Number(params.cursor) : undefined - const limit = 100 - - const sessions = await this.sdk.session - .list( - { - directory: params.cwd ?? undefined, - roots: true, - }, - { throwOnError: true }, - ) - .then((x) => x.data ?? []) - - const sorted = sessions.toSorted((a, b) => b.time.updated - a.time.updated) - const filtered = cursor ? sorted.filter((s) => s.time.updated < cursor) : sorted - const page = filtered.slice(0, limit) - - const entries: SessionInfo[] = page.map((session) => ({ - sessionId: session.id, - cwd: session.directory, - title: session.title, - updatedAt: new Date(session.time.updated).toISOString(), - })) - - const last = page[page.length - 1] - const next = filtered.length > limit && last ? String(last.time.updated) : undefined - - const response: ListSessionsResponse = { - sessions: entries, - } - if (next) response.nextCursor = next - return response - } catch (e) { - const error = MessageV2.fromError(e, { - providerID: ProviderID.make(this.config.defaultModel?.providerID ?? "unknown"), - }) - if (LoadAPIKeyError.isInstance(error)) { - throw RequestError.authRequired() - } - throw e - } + newSession(params: NewSessionRequest) { + return run(this.service.newSession(params)) } - async unstable_forkSession(params: ForkSessionRequest): Promise { - const directory = params.cwd - const mcpServers = params.mcpServers ?? [] - - try { - const model = await defaultModel(this.config, directory) - - const forked = await this.sdk.session - .fork( - { - sessionID: params.sessionId, - directory, - }, - { throwOnError: true }, - ) - .then((x) => x.data) - - if (!forked) { - throw new Error("Fork session returned no data") - } - - const sessionId = forked.id - await this.sessionManager.load(sessionId, directory, mcpServers, model) - - const messages = await this.loadSessionMessages(directory, sessionId) - this.restoreSessionStateFromMessages(sessionId, messages) - - log.info("fork_session", { sessionId, mcpServers: mcpServers.length }) - - const mode = await this.loadSessionMode({ - cwd: directory, - mcpServers, - sessionId, - }) - - for (const msg of messages ?? []) { - log.debug("replay message", msg) - await this.processMessage(msg) - } - - await sendUsageUpdate(this.connection, this.sdk, sessionId, directory) - - return mode - } catch (e) { - const error = MessageV2.fromError(e, { - providerID: ProviderID.make(this.config.defaultModel?.providerID ?? "unknown"), - }) - if (LoadAPIKeyError.isInstance(error)) { - throw RequestError.authRequired() - } - throw e - } + loadSession(params: LoadSessionRequest) { + return run(this.service.loadSession(params)) } - async resumeSession(params: ResumeSessionRequest): Promise { - const directory = params.cwd - const sessionId = params.sessionId - const mcpServers = params.mcpServers ?? [] - - try { - const model = await defaultModel(this.config, directory) - await this.sessionManager.load(sessionId, directory, mcpServers, model) - - const messages = await this.loadSessionMessages(directory, sessionId, 20) - this.restoreSessionStateFromMessages(sessionId, messages) - - log.info("resume_session", { sessionId, mcpServers: mcpServers.length }) - - const result = await this.loadSessionMode({ - cwd: directory, - mcpServers, - sessionId, - }) - - await sendUsageUpdate(this.connection, this.sdk, sessionId, directory) - - return result - } catch (e) { - const error = MessageV2.fromError(e, { - providerID: ProviderID.make(this.config.defaultModel?.providerID ?? "unknown"), - }) - if (LoadAPIKeyError.isInstance(error)) { - throw RequestError.authRequired() - } - throw e - } + listSessions(params: ListSessionsRequest) { + return run(this.service.listSessions(params)) } - async closeSession(params: CloseSessionRequest): Promise { - const session = this.sessionManager.remove(params.sessionId) - if (!session) return {} - - await this.sdk.session - .abort( - { - sessionID: params.sessionId, - directory: session.cwd, - }, - { throwOnError: true }, - ) - .catch((error) => { - log.error("failed to abort session while closing ACP session", { error, sessionID: params.sessionId }) - }) - - this.permissionQueues.delete(params.sessionId) - log.info("close_session", { sessionId: params.sessionId }) - return {} - } - - private async processMessage(message: SessionMessageResponse) { - log.debug("process message", message) - if (message.info.role !== "assistant" && message.info.role !== "user") return - const sessionId = message.info.sessionID - - for (const part of message.parts) { - if (part.type === "tool") { - await this.toolStart(sessionId, part) - switch (part.state.status) { - case "pending": - this.shellSnapshots.delete(part.callID) - break - case "running": - const output = this.shellOutput(part) - const runningContent: ToolCallContent[] = [] - if (output) { - runningContent.push({ - type: "content", - content: { - type: "text", - text: output, - }, - }) - } - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "in_progress", - kind: toToolKind(part.tool), - title: part.tool, - locations: toLocations(part.tool, part.state.input), - rawInput: part.state.input, - ...(runningContent.length > 0 && { content: runningContent }), - }, - }) - .catch((err) => { - log.error("failed to send tool in_progress to ACP", { error: err }) - }) - break - case "completed": - this.toolStarts.delete(part.callID) - this.shellSnapshots.delete(part.callID) - const kind = toToolKind(part.tool) - const content = completedToolContent(part, kind) - - if (part.tool === "todowrite") { - const parsedTodos = decodeTodos(part.state.output) - if (Result.isSuccess(parsedTodos)) { - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "plan", - entries: parsedTodos.success.map((todo) => { - const status: PlanEntry["status"] = - todo.status === "cancelled" ? "completed" : (todo.status as PlanEntry["status"]) - return { - priority: "medium", - status, - content: todo.content, - } - }), - }, - }) - .catch((err) => { - log.error("failed to send session update for todo", { error: err }) - }) - } else { - log.error("failed to parse todo output", { error: parsedTodos.failure }) - } - } - - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "completed", - kind, - content, - title: part.state.title, - rawInput: part.state.input, - rawOutput: completedToolRawOutput(part), - }, - }) - .catch((err) => { - log.error("failed to send tool completed to ACP", { error: err }) - }) - break - case "error": - this.toolStarts.delete(part.callID) - this.shellSnapshots.delete(part.callID) - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: part.callID, - status: "failed", - kind: toToolKind(part.tool), - title: part.tool, - rawInput: part.state.input, - content: [ - { - type: "content", - content: { - type: "text", - text: part.state.error, - }, - }, - ], - rawOutput: { - error: part.state.error, - metadata: part.state.metadata, - }, - }, - }) - .catch((err) => { - log.error("failed to send tool error to ACP", { error: err }) - }) - break - } - } else if (part.type === "text") { - if (part.text) { - const audience: Role[] | undefined = part.synthetic ? ["assistant"] : part.ignored ? ["user"] : undefined - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: message.info.role === "user" ? "user_message_chunk" : "agent_message_chunk", - messageId: message.info.id, - content: { - type: "text", - text: part.text, - ...(audience && { annotations: { audience } }), - }, - }, - }) - .catch((err) => { - log.error("failed to send text to ACP", { error: err }) - }) - } - } else if (part.type === "file") { - // Replay file attachments as appropriate ACP content blocks. - // OpenCode stores files internally as { type: "file", url, filename, mime }. - // We convert these back to ACP blocks based on the URL scheme and MIME type: - // - file:// URLs → resource_link - // - data: URLs with image/* → image block - // - data: URLs with text/* or application/json → resource with text - // - data: URLs with other types → resource with blob - const url = part.url - const filename = part.filename ?? "file" - const mime = part.mime || "application/octet-stream" - const messageChunk = message.info.role === "user" ? "user_message_chunk" : "agent_message_chunk" - - if (url.startsWith("file://")) { - // Local file reference - send as resource_link - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: messageChunk, - messageId: message.info.id, - content: { type: "resource_link", uri: url, name: filename, mimeType: mime }, - }, - }) - .catch((err) => { - log.error("failed to send resource_link to ACP", { error: err }) - }) - } else if (url.startsWith("data:")) { - // Embedded content - parse data URL and send as appropriate block type - const base64Match = url.match(/^data:([^;]+);base64,(.*)$/) - const dataMime = base64Match?.[1] - const base64Data = base64Match?.[2] ?? "" - - const effectiveMime = dataMime || mime - - if (effectiveMime.startsWith("image/")) { - // Image - send as image block - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: messageChunk, - messageId: message.info.id, - content: { - type: "image", - mimeType: effectiveMime, - data: base64Data, - uri: pathToFileURL(filename).href, - }, - }, - }) - .catch((err) => { - log.error("failed to send image to ACP", { error: err }) - }) - } else { - // Non-image: text types get decoded, binary types stay as blob - const isText = effectiveMime.startsWith("text/") || effectiveMime === "application/json" - const fileUri = pathToFileURL(filename).href - const resource = isText - ? { - uri: fileUri, - mimeType: effectiveMime, - text: Buffer.from(base64Data, "base64").toString("utf-8"), - } - : { uri: fileUri, mimeType: effectiveMime, blob: base64Data } - - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: messageChunk, - messageId: message.info.id, - content: { type: "resource", resource }, - }, - }) - .catch((err) => { - log.error("failed to send resource to ACP", { error: err }) - }) - } - } - // URLs that don't match file:// or data: are skipped (unsupported) - } else if (part.type === "reasoning") { - if (part.text) { - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "agent_thought_chunk", - messageId: message.info.id, - content: { - type: "text", - text: part.text, - }, - }, - }) - .catch((err) => { - log.error("failed to send reasoning to ACP", { error: err }) - }) - } - } - } + resumeSession(params: ResumeSessionRequest) { + return run(this.service.resumeSession(params)) } - private shellOutput(part: ToolPart) { - if (part.tool !== ShellID.ToolID) return - if (!("metadata" in part.state) || !part.state.metadata || typeof part.state.metadata !== "object") return - const output = part.state.metadata["output"] - if (typeof output !== "string") return - return output + closeSession(params: CloseSessionRequest) { + return run(this.service.closeSession(params)) } - private async toolStart(sessionId: string, part: ToolPart) { - if (this.toolStarts.has(part.callID)) return - this.toolStarts.add(part.callID) - await this.connection - .sessionUpdate({ - sessionId, - update: { - sessionUpdate: "tool_call", - toolCallId: part.callID, - title: part.tool, - kind: toToolKind(part.tool), - status: "pending", - locations: [], - rawInput: {}, - }, - }) - .catch((error) => { - log.error("failed to send tool pending to ACP", { error }) - }) + unstable_forkSession(params: ForkSessionRequest) { + return run(this.service.forkSession(params)) } - private async loadAvailableModes(directory: string): Promise { - const agents = await this.config.sdk.app - .agents( - { - directory, - }, - { throwOnError: true }, - ) - .then((resp) => resp.data!) - - return agents - .filter((agent) => agent.mode !== "subagent" && !agent.hidden) - .map((agent) => ({ - id: agent.name, - name: agent.name, - description: agent.description, - })) + setSessionConfigOption(params: SetSessionConfigOptionRequest) { + return run(this.service.setSessionConfigOption(params)) } - private async resolveModeState( - directory: string, - sessionId: string, - ): Promise<{ availableModes: ModeOption[]; currentModeId?: string }> { - const availableModes = await this.loadAvailableModes(directory) - const storedModeId = this.sessionManager.get(sessionId).modeId - if (storedModeId && availableModes.some((mode) => mode.id === storedModeId)) { - return { availableModes, currentModeId: storedModeId } - } - - const currentModeId = await (async () => { - if (!availableModes.length) return undefined - const defaultAgent = await ACPRuntime.defaultAgentInfo(directory) - const resolvedModeId = availableModes.find((mode) => mode.name === defaultAgent.name)?.id ?? availableModes[0].id - this.sessionManager.setMode(sessionId, resolvedModeId) - return resolvedModeId - })() - - return { availableModes, currentModeId } + setSessionMode(params: SetSessionModeRequest) { + return run(this.service.setSessionMode(params)) } - private async loadSessionMode(params: LoadSessionRequest) { - const directory = params.cwd - const sessionId = params.sessionId - const model = this.sessionManager.get(sessionId).model ?? (await defaultModel(this.config, directory)) - - const providers = await this.sdk.config.providers({ directory }).then((x) => x.data!.providers) - const entries = sortProvidersByName(providers) - const availableVariants = modelVariantsFromProviders(entries, model) - const currentVariant = this.sessionManager.getVariant(sessionId) - if (currentVariant && !availableVariants.includes(currentVariant)) { - this.sessionManager.setVariant(sessionId, undefined) - } - const availableModels = buildAvailableModels(entries) - const modeState = await this.resolveModeState(directory, sessionId) - const currentModeId = modeState.currentModeId - const modes = currentModeId - ? { - availableModes: modeState.availableModes, - currentModeId, - } - : undefined - - const commands = await this.config.sdk.command - .list( - { - directory, - }, - { throwOnError: true }, - ) - .then((resp) => resp.data!) - - const availableCommands = commands.map((command) => ({ - name: command.name, - description: command.description ?? "", - })) - const names = new Set(availableCommands.map((c) => c.name)) - if (!names.has("compact")) - availableCommands.push({ - name: "compact", - description: "compact the session", - }) - - const mcpServers: Record = {} - for (const server of params.mcpServers) { - if ("type" in server) { - mcpServers[server.name] = { - url: server.url, - headers: server.headers.reduce>((acc, { name, value }) => { - acc[name] = value - return acc - }, {}), - type: "remote", - } - } else { - mcpServers[server.name] = { - type: "local", - command: [server.command, ...server.args], - environment: server.env.reduce>((acc, { name, value }) => { - acc[name] = value - return acc - }, {}), - } - } - } - - await Promise.all( - Object.entries(mcpServers).map(async ([key, mcp]) => { - await this.sdk.mcp - .add( - { - directory, - name: key, - config: mcp, - }, - { throwOnError: true }, - ) - .catch((error) => { - log.error("failed to add mcp server", { name: key, error }) - }) - }), - ) - - setTimeout(() => { - void this.connection.sessionUpdate({ - sessionId, - update: { - sessionUpdate: "available_commands_update", - availableCommands, - }, - }) - }, 0) - - return { - sessionId, - models: { - currentModelId: formatModelIdWithVariant(model, currentVariant, availableVariants, false), - availableModels, - }, - modes, - configOptions: buildConfigOptions({ - currentModelId: formatModelIdWithVariant(model, currentVariant, availableVariants, false), - availableModels, - currentVariant, - availableVariants, - modes, - }), - _meta: buildVariantMeta({ - model, - variant: this.sessionManager.getVariant(sessionId), - availableVariants, - }), - } + unstable_setSessionModel(params: SetSessionModelRequest) { + return run(this.service.setSessionModel(params)) } - async unstable_setSessionModel(params: SetSessionModelRequest) { - const session = this.sessionManager.get(params.sessionId) - const providers = await this.sdk.config - .providers({ directory: session.cwd }, { throwOnError: true }) - .then((x) => x.data!.providers) - - const selection = parseModelSelection(params.modelId, providers) - this.sessionManager.setModel(session.id, selection.model) - this.sessionManager.setVariant(session.id, selection.variant) - - const entries = sortProvidersByName(providers) - const availableVariants = modelVariantsFromProviders(entries, selection.model) - const modeState = await this.resolveModeState(session.cwd, session.id) - const modes = modeState.currentModeId - ? { availableModes: modeState.availableModes, currentModeId: modeState.currentModeId } - : undefined - - await this.connection.sessionUpdate({ - sessionId: session.id, - update: { - sessionUpdate: "config_option_update", - configOptions: buildConfigOptions({ - currentModelId: formatModelIdWithVariant(selection.model, selection.variant, availableVariants, false), - availableModels: buildAvailableModels(entries), - currentVariant: selection.variant, - availableVariants, - modes, - }), - }, - }) - - return { - _meta: buildVariantMeta({ - model: selection.model, - variant: selection.variant, - availableVariants, - }), - } + prompt(params: PromptRequest) { + return run(this.service.prompt(params)) } - async setSessionMode(params: SetSessionModeRequest): Promise { - const session = this.sessionManager.get(params.sessionId) - const availableModes = await this.loadAvailableModes(session.cwd) - if (!availableModes.some((mode) => mode.id === params.modeId)) { - throw new Error(`Agent not found: ${params.modeId}`) - } - this.sessionManager.setMode(params.sessionId, params.modeId) - } - - async setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise { - const session = this.sessionManager.get(params.sessionId) - const providers = await this.sdk.config - .providers({ directory: session.cwd }, { throwOnError: true }) - .then((x) => x.data!.providers) - const entries = sortProvidersByName(providers) - - if (params.configId === "model") { - if (typeof params.value !== "string") throw RequestError.invalidParams("model value must be a string") - const selection = parseModelSelection(params.value, providers) - this.sessionManager.setModel(session.id, selection.model) - this.sessionManager.setVariant(session.id, selection.variant) - } else if (params.configId === "effort") { - if (typeof params.value !== "string") throw RequestError.invalidParams("effort value must be a string") - const current = session.model ?? (await defaultModel(this.config, session.cwd)) - const availableVariants = modelVariantsFromProviders(entries, current) - if (!availableVariants.includes(params.value)) { - throw RequestError.invalidParams(JSON.stringify({ error: `Effort not found: ${params.value}` })) - } - this.sessionManager.setVariant(session.id, params.value) - } else if (params.configId === "mode") { - if (typeof params.value !== "string") throw RequestError.invalidParams("mode value must be a string") - const availableModes = await this.loadAvailableModes(session.cwd) - if (!availableModes.some((mode) => mode.id === params.value)) { - throw RequestError.invalidParams(JSON.stringify({ error: `Mode not found: ${params.value}` })) - } - this.sessionManager.setMode(session.id, params.value) - } else { - throw RequestError.invalidParams(JSON.stringify({ error: `Unknown config option: ${params.configId}` })) - } - - const updatedSession = this.sessionManager.get(session.id) - const model = updatedSession.model ?? (await defaultModel(this.config, session.cwd)) - const availableVariants = modelVariantsFromProviders(entries, model) - const currentModelId = formatModelIdWithVariant(model, updatedSession.variant, availableVariants, false) - const availableModels = buildAvailableModels(entries) - const modeState = await this.resolveModeState(session.cwd, session.id) - const modes = modeState.currentModeId - ? { availableModes: modeState.availableModes, currentModeId: modeState.currentModeId } - : undefined - - return { - configOptions: buildConfigOptions({ - currentModelId, - availableModels, - currentVariant: updatedSession.variant, - availableVariants, - modes, - }), - } - } - - async prompt(params: PromptRequest) { - const sessionID = params.sessionId - const session = this.sessionManager.get(sessionID) - const directory = session.cwd - - const current = session.model - const model = current ?? (await defaultModel(this.config, directory)) - if (!current) { - this.sessionManager.setModel(session.id, model) - } - const agent = session.modeId ?? (await ACPRuntime.defaultAgentInfo(directory)).name - - const parts: Array< - | { type: "text"; text: string; synthetic?: boolean; ignored?: boolean } - | { type: "file"; url: string; filename: string; mime: string } - > = [] - for (const part of params.prompt) { - switch (part.type) { - case "text": - const audience = part.annotations?.audience - const forAssistant = audience?.length === 1 && audience[0] === "assistant" - const forUser = audience?.length === 1 && audience[0] === "user" - parts.push({ - type: "text" as const, - text: part.text, - ...(forAssistant && { synthetic: true }), - ...(forUser && { ignored: true }), - }) - break - case "image": { - const parsed = parseUri(part.uri ?? "") - const filename = parsed.type === "file" ? parsed.filename : "image" - if (part.data) { - parts.push({ - type: "file", - url: `data:${part.mimeType};base64,${part.data}`, - filename, - mime: part.mimeType, - }) - } else if (part.uri && part.uri.startsWith("http:")) { - parts.push({ - type: "file", - url: part.uri, - filename, - mime: part.mimeType, - }) - } - break - } - - case "resource_link": - const parsed = parseUri(part.uri) - // Use the name from resource_link if available - if (part.name && parsed.type === "file") { - parsed.filename = part.name - } - parts.push(parsed) - - break - - case "resource": { - const resource = part.resource - if ("text" in resource && resource.text) { - parts.push({ - type: "text", - text: resource.text, - }) - } else if ("blob" in resource && resource.blob && resource.mimeType) { - // Binary resource (PDFs, etc.): store as file part with data URL - const parsed = parseUri(resource.uri ?? "") - const filename = parsed.type === "file" ? parsed.filename : "file" - parts.push({ - type: "file", - url: `data:${resource.mimeType};base64,${resource.blob}`, - filename, - mime: resource.mimeType, - }) - } - break - } - - default: - break - } - } - - log.info("parts", { parts }) - - const cmd = (() => { - const text = parts - .filter((p): p is { type: "text"; text: string } => p.type === "text") - .map((p) => p.text) - .join("") - .trim() - - if (!text.startsWith("/")) return - - const [name, ...rest] = text.slice(1).split(/\s+/) - return { name, args: rest.join(" ").trim() } - })() - - const buildUsage = (msg: AssistantMessage): Usage => ({ - totalTokens: - msg.tokens.input + - msg.tokens.output + - msg.tokens.reasoning + - (msg.tokens.cache?.read ?? 0) + - (msg.tokens.cache?.write ?? 0), - inputTokens: msg.tokens.input, - outputTokens: msg.tokens.output, - thoughtTokens: msg.tokens.reasoning || undefined, - cachedReadTokens: msg.tokens.cache?.read || undefined, - cachedWriteTokens: msg.tokens.cache?.write || undefined, - }) - - if (!cmd) { - const response = await this.sdk.session.prompt({ - sessionID, - model: { - providerID: model.providerID, - modelID: model.modelID, - }, - variant: this.sessionManager.getVariant(sessionID), - parts, - agent, - directory, - }) - const msg = response.data?.info - - await sendUsageUpdate(this.connection, this.sdk, sessionID, directory) - - return { - stopReason: "end_turn" as const, - usage: msg ? buildUsage(msg) : undefined, - _meta: {}, - } - } - - const command = await this.config.sdk.command - .list({ directory }, { throwOnError: true }) - .then((x) => x.data!.find((c) => c.name === cmd.name)) - if (command) { - const response = await this.sdk.session.command({ - sessionID, - command: command.name, - arguments: cmd.args, - model: model.providerID + "/" + model.modelID, - agent, - directory, - }) - const msg = response.data?.info - - await sendUsageUpdate(this.connection, this.sdk, sessionID, directory) - - return { - stopReason: "end_turn" as const, - usage: msg ? buildUsage(msg) : undefined, - _meta: {}, - } - } - - switch (cmd.name) { - case "compact": - await this.config.sdk.session.summarize( - { - sessionID, - directory, - providerID: model.providerID, - modelID: model.modelID, - }, - { throwOnError: true }, - ) - break - } - - await sendUsageUpdate(this.connection, this.sdk, sessionID, directory) - - return { - stopReason: "end_turn" as const, - _meta: {}, - } - } - - async cancel(params: CancelNotification) { - const session = this.sessionManager.get(params.sessionId) - await this.config.sdk.session.abort( - { - sessionID: params.sessionId, - directory: session.cwd, - }, - { throwOnError: true }, - ) - } - - private async loadSessionMessages(directory: string, sessionId: string, limit?: number) { - return this.sdk.session - .messages( - { - sessionID: sessionId, - directory, - limit, - }, - { throwOnError: true }, - ) - .then((x) => x.data) - .catch((error) => { - log.error("unexpected error when fetching message", { error }) - return undefined - }) - } - - private restoreSessionStateFromMessages(sessionId: string, messages: SessionMessageResponse[] | undefined) { - const lastUser = messages?.findLast((message) => message.info.role === "user")?.info - if (lastUser?.role !== "user") return - - this.sessionManager.setModel(sessionId, { - providerID: ProviderID.make(lastUser.model.providerID), - modelID: ModelID.make(lastUser.model.modelID), - }) - this.sessionManager.setVariant(sessionId, lastUser.model.variant) - if (lastUser.agent) { - this.sessionManager.setMode(sessionId, lastUser.agent) - } - } -} - -function toToolKind(toolName: string): ToolKind { - const tool = toolName.toLocaleLowerCase() - - switch (tool) { - case ShellID.ToolID: - return "execute" - - case "webfetch": - return "fetch" - - case "edit": - case "patch": - case "write": - return "edit" - - case "grep": - case "glob": - case "repo_clone": - case "repo_overview": - case "context7_resolve_library_id": - case "context7_get_library_docs": - return "search" - - case "read": - return "read" - - default: - return "other" - } -} - -function toLocations(toolName: string, input: Record): { path: string }[] { - const tool = toolName.toLocaleLowerCase() - - switch (tool) { - case "read": - case "edit": - case "write": - return input["filePath"] ? [{ path: input["filePath"] }] : [] - case "glob": - case "grep": - return input["path"] ? [{ path: input["path"] }] : [] - case "repo_clone": - return input["path"] ? [{ path: input["path"] }] : [] - case "repo_overview": - return input["path"] ? [{ path: input["path"] }] : [] - case ShellID.ToolID: - return [] - default: - return [] - } -} - -function completedToolContent(part: ToolPart, kind: ToolKind): ToolCallContent[] { - if (part.state.status !== "completed") return [] - - const content: ToolCallContent[] = [ - { - type: "content", - content: { - type: "text", - text: part.state.output, - }, - }, - ] - - if (kind === "edit") { - const input = part.state.input - const filePath = typeof input["filePath"] === "string" ? input["filePath"] : "" - const oldText = typeof input["oldString"] === "string" ? input["oldString"] : "" - const newText = - typeof input["newString"] === "string" - ? input["newString"] - : typeof input["content"] === "string" - ? input["content"] - : "" - content.push({ - type: "diff", - path: filePath, - oldText, - newText, - }) - } - - content.push(...imageContents(part.state.attachments ?? [])) - return content -} - -function completedToolRawOutput(part: ToolPart) { - if (part.state.status !== "completed") return {} - return { - output: part.state.output, - metadata: part.state.metadata, - ...(part.state.attachments?.length ? { attachments: part.state.attachments } : {}), + cancel(params: CancelNotification) { + return run(this.service.cancel(params)) } } -function imageContents(attachments: Array<{ mime: string; url: string }>): ToolCallContent[] { - return attachments.flatMap((attachment): ToolCallContent[] => { - const match = attachment.url.match(/^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/) - const mime = match?.[1] ?? attachment.mime - if (!mime.startsWith("image/")) return [] - const data = match?.[2] - if (data === undefined) return [] - return [ - { - type: "content" as const, - content: { - type: "image" as const, - mimeType: mime, - data, - }, - }, - ] +function run(effect: Effect.Effect) { + return Effect.runPromise(effect.pipe(Effect.mapError(ACPError.toRequestError))).catch((defect: unknown) => { + if (defect instanceof RequestError) throw defect + throw ACPError.toRequestError(ACPError.fromUnknownDefect(defect)) }) } -async function defaultModel(config: ACPConfig, cwd?: string): Promise<{ providerID: ProviderID; modelID: ModelID }> { - const sdk = config.sdk - const configured = config.defaultModel - if (configured) return configured - - const directory = cwd ?? process.cwd() - - const specified = await sdk.config - .get({ directory }, { throwOnError: true }) - .then((resp) => { - const cfg = resp.data - if (!cfg || !cfg.model) return undefined - return Provider.parseModel(cfg.model) - }) - .catch((error) => { - log.error("failed to load user config for default model", { error }) - return undefined - }) - - const providers = await sdk.config - .providers({ directory }, { throwOnError: true }) - .then((x) => x.data?.providers ?? []) - .catch((error) => { - log.error("failed to list providers for default model", { error }) - return [] - }) - - if (specified && providers.length) { - const provider = providers.find((p) => p.id === specified.providerID) - if (provider && provider.models[specified.modelID]) return specified - } - - if (specified && !providers.length) return specified - - const lastUsed = await lastUsedModel(sdk, directory, providers) - if (lastUsed) return lastUsed - - const opencodeProvider = providers.find((p) => p.id === "opencode") - if (opencodeProvider) { - const [best] = Provider.sort(Object.values(opencodeProvider.models)) - if (best) { - return { - providerID: ProviderID.make(best.providerID), - modelID: ModelID.make(best.id), - } - } - } - - const models = providers.flatMap((p) => Object.values(p.models)) - const [best] = Provider.sort(models) - if (best) { - return { - providerID: ProviderID.make(best.providerID), - modelID: ModelID.make(best.id), - } - } - - if (specified) return specified - throw new Error("No models available") -} - -async function lastUsedModel( - sdk: OpencodeClient, - directory: string, - providers: Array<{ id: string; models: Record }>, -): Promise<{ providerID: ProviderID; modelID: ModelID } | undefined> { - const session = await sdk.session - .list({ directory, roots: true, limit: 1 }, { throwOnError: true }) - .then((x) => x.data?.[0]) - .catch((error) => { - log.error("failed to list sessions for default model", { error }) - return undefined - }) - if (!session) return - - const lastUser = await sdk.session - .messages({ sessionID: session.id, directory, limit: 20 }, { throwOnError: true }) - .then((x) => x.data?.findLast((message) => message.info.role === "user")?.info) - .catch((error) => { - log.error("failed to load session messages for default model", { error, sessionID: session.id }) - return undefined - }) - if (lastUser?.role !== "user") return - - const provider = providers.find((entry) => entry.id === lastUser.model.providerID) - if (!provider?.models[lastUser.model.modelID]) return - return { - providerID: ProviderID.make(lastUser.model.providerID), - modelID: ModelID.make(lastUser.model.modelID), - } -} - -function parseUri( - uri: string, -): { type: "file"; url: string; filename: string; mime: string } | { type: "text"; text: string } { - try { - if (uri.startsWith("file://")) { - const path = uri.slice(7) - const name = path.split("/").pop() || path - return { - type: "file", - url: uri, - filename: name, - mime: "text/plain", - } - } - if (uri.startsWith("zed://")) { - const url = new URL(uri) - const path = url.searchParams.get("path") - if (path) { - const name = path.split("/").pop() || path - return { - type: "file", - url: pathToFileURL(path).href, - filename: name, - mime: "text/plain", - } - } - } - return { - type: "text", - text: uri, - } - } catch { - return { - type: "text", - text: uri, - } - } -} - -function getNewContent(fileOriginal: string, unifiedDiff: string): string | undefined { - const result = applyPatch(fileOriginal, unifiedDiff) - if (result === false) { - log.error("Failed to apply unified diff (context mismatch)") - return undefined - } - return result -} - -function sortProvidersByName(providers: T[]): T[] { - return [...providers].sort((a, b) => { - const nameA = a.name.toLowerCase() - const nameB = b.name.toLowerCase() - if (nameA < nameB) return -1 - if (nameA > nameB) return 1 - return 0 - }) -} - -function modelVariantsFromProviders( - providers: Array<{ id: string; models: Record }> }>, - model: { providerID: ProviderID; modelID: ModelID }, -): string[] { - const provider = providers.find((entry) => entry.id === model.providerID) - if (!provider) return [] - const modelInfo = provider.models[model.modelID] - if (!modelInfo?.variants) return [] - return Object.keys(modelInfo.variants) -} - -function buildAvailableModels( - providers: Array<{ id: string; name: string; models: Record }>, - options: { includeVariants?: boolean } = {}, -): ModelOption[] { - const includeVariants = options.includeVariants ?? false - return providers.flatMap((provider) => { - const unsorted: Array<{ id: string; name: string; variants?: Record }> = Object.values(provider.models) - const models = Provider.sort(unsorted) - return models.flatMap((model) => { - const base: ModelOption = { - modelId: `${provider.id}/${model.id}`, - name: `${provider.name}/${model.name}`, - } - if (!includeVariants || !model.variants) return [base] - const variants = Object.keys(model.variants).filter((variant) => variant !== DEFAULT_VARIANT_VALUE) - const variantOptions = variants.map((variant) => ({ - modelId: `${provider.id}/${model.id}/${variant}`, - name: `${provider.name}/${model.name} (${variant})`, - })) - return [base, ...variantOptions] - }) - }) -} - -function formatModelIdWithVariant( - model: { providerID: ProviderID; modelID: ModelID }, - variant: string | undefined, - availableVariants: string[], - includeVariant: boolean, -) { - const base = `${model.providerID}/${model.modelID}` - if (!includeVariant || availableVariants.length === 0) return base - const selectedVariant = - variant && availableVariants.includes(variant) - ? variant - : availableVariants.includes(DEFAULT_VARIANT_VALUE) - ? DEFAULT_VARIANT_VALUE - : availableVariants[0] - return `${base}/${selectedVariant}` -} - -function buildVariantMeta(input: { - model: { providerID: ProviderID; modelID: ModelID } - variant?: string - availableVariants: string[] -}) { - return { - opencode: { - modelId: `${input.model.providerID}/${input.model.modelID}`, - variant: input.variant ?? null, - availableVariants: input.availableVariants, - }, - } -} - -function parseModelSelection( - modelId: string, - providers: Array<{ id: string; models: Record }> }>, -): { model: { providerID: ProviderID; modelID: ModelID }; variant?: string } { - const parsed = Provider.parseModel(modelId) - const provider = providers.find((p) => p.id === parsed.providerID) - if (!provider) { - return { model: parsed, variant: undefined } - } - - // Check if modelID exists directly - if (provider.models[parsed.modelID]) { - return { model: parsed, variant: undefined } - } - - // Try to extract variant from end of modelID (e.g., "claude-sonnet-4/high" -> model: "claude-sonnet-4", variant: "high") - const segments = parsed.modelID.split("/") - if (segments.length > 1) { - const candidateVariant = segments[segments.length - 1] - const baseModelId = segments.slice(0, -1).join("/") - const baseModelInfo = provider.models[baseModelId] - if (baseModelInfo?.variants && candidateVariant in baseModelInfo.variants) { - return { - model: { providerID: parsed.providerID, modelID: ModelID.make(baseModelId) }, - variant: candidateVariant, - } - } - } - - return { model: parsed, variant: undefined } -} - -function buildConfigOptions(input: { - currentModelId: string - availableModels: ModelOption[] - currentVariant?: string - availableVariants?: string[] - modes?: { availableModes: ModeOption[]; currentModeId: string } | undefined -}): SessionConfigOption[] { - const options: SessionConfigOption[] = [ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: input.currentModelId, - options: input.availableModels.map((m) => ({ value: m.modelId, name: m.name })), - }, - ] - if (input.availableVariants?.length) { - options.push({ - id: "effort", - name: "Effort", - description: "Available effort levels for this model", - category: "thought_level", - type: "select", - currentValue: - input.currentVariant && input.availableVariants.includes(input.currentVariant) - ? input.currentVariant - : input.availableVariants.includes(DEFAULT_VARIANT_VALUE) - ? DEFAULT_VARIANT_VALUE - : input.availableVariants[0], - options: input.availableVariants.map((variant) => ({ value: variant, name: formatVariantName(variant) })), - }) - } - if (input.modes) { - options.push({ - id: "mode", - name: "Session Mode", - category: "mode", - type: "select", - currentValue: input.modes.currentModeId, - options: input.modes.availableModes.map((m) => ({ - value: m.id, - name: m.name, - ...(m.description ? { description: m.description } : {}), - })), - }) - } - return options -} - -function formatVariantName(variant: string) { - return variant - .split(/[_-]/) - .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part)) - .join(" ") -} - export * as ACP from "./agent" diff --git a/packages/opencode/src/acp-next/config-option.ts b/packages/opencode/src/acp/config-option.ts similarity index 100% rename from packages/opencode/src/acp-next/config-option.ts rename to packages/opencode/src/acp/config-option.ts diff --git a/packages/opencode/src/acp-next/content.ts b/packages/opencode/src/acp/content.ts similarity index 96% rename from packages/opencode/src/acp-next/content.ts rename to packages/opencode/src/acp/content.ts index f83a75ef197e..32630a620c58 100644 --- a/packages/opencode/src/acp-next/content.ts +++ b/packages/opencode/src/acp/content.ts @@ -1,9 +1,9 @@ import type { ContentBlock, ContentChunk, ResourceLink, Role } from "@agentclientprotocol/sdk" import path from "node:path" import { pathToFileURL } from "node:url" -import type { MessageV2 } from "@/session/message-v2" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" -export type PromptPart = MessageV2.TextPartInput | MessageV2.FilePartInput +export type PromptPart = SessionLegacy.TextPartInput | SessionLegacy.FilePartInput export type ReplayPart = | { @@ -141,7 +141,7 @@ function uriToFilePart( uri: string, mime: string, filename?: string, -): MessageV2.FilePartInput | MessageV2.TextPartInput { +): SessionLegacy.FilePartInput | SessionLegacy.TextPartInput { try { if (uri.startsWith("file://")) { return { diff --git a/packages/opencode/src/acp-next/directory.ts b/packages/opencode/src/acp/directory.ts similarity index 89% rename from packages/opencode/src/acp-next/directory.ts rename to packages/opencode/src/acp/directory.ts index 90ffa36358ff..eb0b7885929f 100644 --- a/packages/opencode/src/acp-next/directory.ts +++ b/packages/opencode/src/acp/directory.ts @@ -2,15 +2,15 @@ import { Agent } from "@/agent/agent" import { Command } from "@/command" import { InstanceRef } from "@/effect/instance-ref" import { InstanceStore } from "@/project/instance-store" -import { ModelID, ProviderID } from "@/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" import { Provider } from "@/provider/provider" import { Context, Effect, Layer, SynchronizedRef } from "effect" -import type * as ACPNextError from "./error" +import type * as ACPError from "./error" export type ModelOption = { - readonly providerID: ProviderID + readonly providerID: ProviderV2.ID readonly providerName: string - readonly modelID: ModelID + readonly modelID: ProviderV2.ModelID readonly modelName: string } @@ -23,13 +23,13 @@ export type ModeOption = { export type ModelVariants = NonNullable export type DefaultModel = { - readonly providerID: ProviderID - readonly modelID: ModelID + readonly providerID: ProviderV2.ID + readonly modelID: ProviderV2.ModelID } export type Snapshot = { readonly directory: string - readonly providers: Record + readonly providers: Record readonly modelOptions: readonly ModelOption[] readonly variantsByModel: Readonly> readonly availableModes: readonly ModeOption[] @@ -39,18 +39,18 @@ export type Snapshot = { } export interface LoaderInterface { - readonly load: (directory: string) => Effect.Effect + readonly load: (directory: string) => Effect.Effect } export interface Interface { - readonly get: (directory: string) => Effect.Effect - readonly refresh: (directory: string) => Effect.Effect + readonly get: (directory: string) => Effect.Effect + readonly refresh: (directory: string) => Effect.Effect readonly variants: (snapshot: Snapshot, model: DefaultModel) => ModelVariants | undefined } -export class Loader extends Context.Service()("@opencode/ACPNextDirectoryLoader") {} +export class Loader extends Context.Service()("@opencode/ACPDirectoryLoader") {} -export class Service extends Context.Service()("@opencode/ACPNextDirectory") {} +export class Service extends Context.Service()("@opencode/ACPDirectory") {} export const modelKey = (model: DefaultModel) => `${model.providerID}/${model.modelID}` @@ -58,7 +58,7 @@ export const variants = (snapshot: Snapshot, model: DefaultModel) => snapshot.va export const build = (input: { readonly directory: string - readonly providers: Record + readonly providers: Record readonly modes: readonly ModeOption[] readonly defaultModeID: string readonly commands: readonly Command.Info[] @@ -110,7 +110,7 @@ export const loaderLayer = Layer.effect( const command = yield* Command.Service return Loader.of({ - load: Effect.fn("ACPNextDirectoryLoader.load")(function* (directory) { + load: Effect.fn("ACPDirectoryLoader.load")(function* (directory) { const ctx = yield* store.load({ directory }) return yield* Effect.gen(function* () { const providers = yield* provider.list() @@ -142,7 +142,7 @@ export const layer = Layer.effect( Service, Effect.gen(function* () { const loader = yield* Loader - const snapshots = yield* SynchronizedRef.make(new Map>()) + const snapshots = yield* SynchronizedRef.make(new Map>()) const cached = Effect.fnUntraced(function* (directory: string) { return yield* SynchronizedRef.modifyEffect( @@ -166,11 +166,11 @@ export const layer = Layer.effect( ) }) - const get = Effect.fn("ACPNextDirectory.get")(function* (directory: string) { + const get = Effect.fn("ACPDirectory.get")(function* (directory: string) { return yield* yield* cached(directory) }) - const refresh = Effect.fn("ACPNextDirectory.refresh")(function* (directory: string) { + const refresh = Effect.fn("ACPDirectory.refresh")(function* (directory: string) { return yield* SynchronizedRef.modifyEffect( snapshots, Effect.fnUntraced(function* (items) { diff --git a/packages/opencode/src/acp-next/error.ts b/packages/opencode/src/acp/error.ts similarity index 75% rename from packages/opencode/src/acp-next/error.ts rename to packages/opencode/src/acp/error.ts index 1d4af53b5030..0c66a0e0498f 100644 --- a/packages/opencode/src/acp-next/error.ts +++ b/packages/opencode/src/acp/error.ts @@ -1,52 +1,49 @@ import { RequestError } from "@agentclientprotocol/sdk" import { Schema } from "effect" -export class SessionNotFoundError extends Schema.TaggedErrorClass()( - "ACPNextSessionNotFoundError", - { - sessionId: Schema.String, - }, -) {} +export class SessionNotFoundError extends Schema.TaggedErrorClass()("ACPSessionNotFoundError", { + sessionId: Schema.String, +}) {} export class InvalidConfigOptionError extends Schema.TaggedErrorClass()( - "ACPNextInvalidConfigOptionError", + "ACPInvalidConfigOptionError", { configId: Schema.String, }, ) {} -export class InvalidModelError extends Schema.TaggedErrorClass()("ACPNextInvalidModelError", { +export class InvalidModelError extends Schema.TaggedErrorClass()("ACPInvalidModelError", { modelId: Schema.String, providerId: Schema.optional(Schema.String), }) {} -export class InvalidEffortError extends Schema.TaggedErrorClass()("ACPNextInvalidEffortError", { +export class InvalidEffortError extends Schema.TaggedErrorClass()("ACPInvalidEffortError", { effort: Schema.String, }) {} -export class InvalidModeError extends Schema.TaggedErrorClass()("ACPNextInvalidModeError", { +export class InvalidModeError extends Schema.TaggedErrorClass()("ACPInvalidModeError", { mode: Schema.String, }) {} -export class AuthRequiredError extends Schema.TaggedErrorClass()("ACPNextAuthRequiredError", { +export class AuthRequiredError extends Schema.TaggedErrorClass()("ACPAuthRequiredError", { providerId: Schema.optional(Schema.String), }) {} export class UnknownAuthMethodError extends Schema.TaggedErrorClass()( - "ACPNextUnknownAuthMethodError", + "ACPUnknownAuthMethodError", { methodId: Schema.String, }, ) {} export class UnsupportedOperationError extends Schema.TaggedErrorClass()( - "ACPNextUnsupportedOperationError", + "ACPUnsupportedOperationError", { method: Schema.String, }, ) {} -export class ServiceFailureError extends Schema.TaggedErrorClass()("ACPNextServiceFailureError", { +export class ServiceFailureError extends Schema.TaggedErrorClass()("ACPServiceFailureError", { safeMessage: Schema.String, service: Schema.optional(Schema.String), }) {} @@ -64,26 +61,26 @@ export type Error = export function toRequestError(error: Error) { switch (error._tag) { - case "ACPNextSessionNotFoundError": + case "ACPSessionNotFoundError": return RequestError.invalidParams({ sessionId: error.sessionId }, `session not found: ${error.sessionId}`) - case "ACPNextInvalidConfigOptionError": + case "ACPInvalidConfigOptionError": return RequestError.invalidParams({ configId: error.configId }, `unknown config option: ${error.configId}`) - case "ACPNextInvalidModelError": + case "ACPInvalidModelError": return RequestError.invalidParams( { providerId: error.providerId, modelId: error.modelId }, `model not found: ${error.modelId}`, ) - case "ACPNextInvalidEffortError": + case "ACPInvalidEffortError": return RequestError.invalidParams({ effort: error.effort }, `effort not found: ${error.effort}`) - case "ACPNextInvalidModeError": + case "ACPInvalidModeError": return RequestError.invalidParams({ mode: error.mode }, `mode not found: ${error.mode}`) - case "ACPNextAuthRequiredError": + case "ACPAuthRequiredError": return RequestError.authRequired({ providerId: error.providerId }, "provider authentication required") - case "ACPNextUnknownAuthMethodError": + case "ACPUnknownAuthMethodError": return RequestError.invalidParams({ methodId: error.methodId }, `unknown auth method: ${error.methodId}`) - case "ACPNextUnsupportedOperationError": + case "ACPUnsupportedOperationError": return RequestError.methodNotFound(error.method) - case "ACPNextServiceFailureError": + case "ACPServiceFailureError": return RequestError.internalError({ service: error.service }, error.safeMessage) } } diff --git a/packages/opencode/src/acp/event.ts b/packages/opencode/src/acp/event.ts new file mode 100644 index 000000000000..df105d6acf77 --- /dev/null +++ b/packages/opencode/src/acp/event.ts @@ -0,0 +1,319 @@ +import type { AgentSideConnection } from "@agentclientprotocol/sdk" +import * as Log from "@opencode-ai/core/util/log" +import type { + Event, + EventMessagePartDelta, + EventMessagePartUpdated, + OpencodeClient, + Part, + SessionMessageResponse, + ToolPart, +} from "@opencode-ai/sdk/v2" +import { Effect } from "effect" +import { ACPSession } from "./session" +import { ACPPermission } from "./permission" +import { + duplicateRunningToolUpdate, + errorToolUpdate, + pendingToolCall, + runningToolUpdate, + shellOutputSnapshot, + completedToolUpdate, +} from "./tool" + +const log = Log.create({ service: "acp-event" }) + +type Connection = Pick & + Partial> +type GlobalEventEnvelope = { + payload?: Event +} +type GlobalEventStream = { + stream: AsyncIterable +} + +export function start(input: { sdk: OpencodeClient; connection: Connection; session: ACPSession.Interface }) { + const subscription = new Subscription(input) + subscription.start() + return subscription +} + +export class Subscription { + private readonly abort = new AbortController() + private readonly shellSnapshots = new Map() + private readonly toolStarts = new Set() + private readonly permission: ACPPermission.Handler + private started = false + + constructor( + private readonly input: { + sdk: OpencodeClient + connection: Connection + session: ACPSession.Interface + }, + ) { + this.permission = new ACPPermission.Handler(input) + } + + start() { + if (this.started) return + this.started = true + this.run().catch((error: unknown) => { + if (this.abort.signal.aborted) return + log.error("event subscription failed", { error }) + }) + } + + stop() { + this.abort.abort() + } + + async handle(event: Event) { + switch (event.type) { + case "permission.asked": + this.permission.handle(event) + return + case "message.part.updated": + return this.handlePartUpdated(event) + case "message.part.delta": + return this.handlePartDelta(event) + } + } + + async replayMessage(message: SessionMessageResponse) { + if (message.info.role !== "assistant" && message.info.role !== "user") return + + for (const part of message.parts) { + await this.recordFetchedPart(message.info.sessionID, message, part) + if (part.type === "tool") { + await this.handleToolPart(message.info.sessionID, part) + } + } + } + + private async run() { + while (!this.abort.signal.aborted) { + const events = (await this.input.sdk.global.event({ + signal: this.abort.signal, + })) as GlobalEventStream + + for await (const event of events.stream) { + if (this.abort.signal.aborted) return + if (!event.payload) continue + await this.handle(event.payload).catch((error: unknown) => { + log.error("failed to handle event", { error, type: event.payload?.type }) + }) + } + if (!this.abort.signal.aborted) await new Promise((resolve) => setTimeout(resolve, 1000)) + } + } + + private async handlePartUpdated(event: EventMessagePartUpdated) { + const part = event.properties.part + const sessionId = part.sessionID || event.properties.sessionID + const session = await Effect.runPromise(this.input.session.tryGet(sessionId)) + if (!session) return + + await Effect.runPromise( + this.input.session.recordPartMetadata({ + sessionId: session.id, + messageId: part.messageID, + partId: part.id, + partType: part.type, + role: part.type === "reasoning" ? "assistant" : undefined, + ignored: part.type === "text" ? part.ignored : undefined, + toolCallId: part.type === "tool" ? part.callID : undefined, + metadata: "metadata" in part ? part.metadata : undefined, + }), + ) + if (part.type === "tool") { + await this.handleToolPart(session.id, part) + } + } + + private async handlePartDelta(event: EventMessagePartDelta) { + const props = event.properties + const session = await Effect.runPromise(this.input.session.tryGet(props.sessionID)) + if (!session) return + + const known = await Effect.runPromise( + this.input.session.tryGetPartMetadata({ + sessionId: session.id, + messageId: props.messageID, + partId: props.partID, + }), + ) + const metadata = + known?.role && known.partType + ? known + : await this.fetchPartMetadata(session.id, session.cwd, props.messageID, props.partID) + if (metadata?.role !== "assistant") return + if (metadata.partType === "text" && props.field === "text" && metadata.ignored !== true) { + await this.input.connection.sessionUpdate({ + sessionId: session.id, + update: { + sessionUpdate: "agent_message_chunk", + messageId: props.messageID, + content: { + type: "text", + text: props.delta, + }, + }, + }) + return + } + + if (metadata.partType === "reasoning" && props.field === "text") { + await this.input.connection.sessionUpdate({ + sessionId: session.id, + update: { + sessionUpdate: "agent_thought_chunk", + messageId: props.messageID, + content: { + type: "text", + text: props.delta, + }, + }, + }) + } + } + + private async fetchPartMetadata(sessionId: string, cwd: string, messageId: string, partId: string) { + const message = await this.input.sdk.session + .message( + { + sessionID: sessionId, + messageID: messageId, + directory: cwd, + }, + { throwOnError: true }, + ) + .then((response) => response.data) + .catch((error: unknown) => { + log.error("unexpected error when fetching message for delta metadata", { error, messageId, partId }) + return undefined + }) + if (!message) return + + const part = message.parts.find((item) => item.id === partId) + if (!part) return + return await this.recordFetchedPart(sessionId, message, part) + } + + private async recordFetchedPart(sessionId: string, message: SessionMessageResponse, part: Part) { + return await Effect.runPromise( + this.input.session.recordPartMetadata({ + sessionId, + messageId: part.messageID, + partId: part.id, + partType: part.type, + role: message.info.role, + ignored: part.type === "text" ? part.ignored : undefined, + toolCallId: part.type === "tool" ? part.callID : undefined, + metadata: "metadata" in part ? part.metadata : undefined, + }), + ) + } + + private async handleToolPart(sessionId: string, part: ToolPart) { + await this.toolStart(sessionId, part) + + switch (part.state.status) { + case "pending": + this.shellSnapshots.delete(part.callID) + return + + case "running": + await this.runningTool(sessionId, part) + return + + case "completed": + this.clearTool(part.callID) + await this.input.connection.sessionUpdate({ + sessionId, + update: { + sessionUpdate: "tool_call_update", + ...completedToolUpdate({ + toolCallId: part.callID, + toolName: part.tool, + state: part.state, + }), + }, + }) + return + + case "error": + this.clearTool(part.callID) + await this.input.connection.sessionUpdate({ + sessionId, + update: { + sessionUpdate: "tool_call_update", + ...errorToolUpdate({ + toolCallId: part.callID, + toolName: part.tool, + state: part.state, + }), + }, + }) + return + } + } + + private async runningTool(sessionId: string, part: ToolPart) { + if (part.state.status !== "running") return + + const output = part.tool === "bash" ? shellOutputSnapshot(part.state) : undefined + if (output !== undefined) { + if (this.shellSnapshots.get(part.callID) === output) { + await this.input.connection.sessionUpdate({ + sessionId, + update: { + sessionUpdate: "tool_call_update", + ...duplicateRunningToolUpdate({ + toolCallId: part.callID, + toolName: part.tool, + state: part.state, + }), + }, + }) + return + } + this.shellSnapshots.set(part.callID, output) + } + + await this.input.connection.sessionUpdate({ + sessionId, + update: { + sessionUpdate: "tool_call_update", + ...runningToolUpdate({ + toolCallId: part.callID, + toolName: part.tool, + state: part.state, + output, + }), + }, + }) + } + + private async toolStart(sessionId: string, part: ToolPart) { + if (this.toolStarts.has(part.callID)) return + this.toolStarts.add(part.callID) + await this.input.connection.sessionUpdate({ + sessionId, + update: { + sessionUpdate: "tool_call", + ...pendingToolCall({ + toolCallId: part.callID, + toolName: part.tool, + }), + }, + }) + } + + private clearTool(toolCallId: string) { + this.toolStarts.delete(toolCallId) + this.shellSnapshots.delete(toolCallId) + } +} + +export * as ACPEvent from "./event" diff --git a/packages/opencode/src/acp/permission.ts b/packages/opencode/src/acp/permission.ts new file mode 100644 index 000000000000..cefd2a34f361 --- /dev/null +++ b/packages/opencode/src/acp/permission.ts @@ -0,0 +1,145 @@ +import type { AgentSideConnection, PermissionOption, RequestPermissionResponse } from "@agentclientprotocol/sdk" +import * as Log from "@opencode-ai/core/util/log" +import type { Event, OpencodeClient } from "@opencode-ai/sdk/v2" +import { applyPatch } from "diff" +import { exists, readText } from "@/util/filesystem" +import type { ACPSession } from "./session" +import { toLocations, toToolKind, type ToolInput } from "./tool" +import { Effect } from "effect" + +const log = Log.create({ service: "acp-permission" }) + +type PermissionEvent = Extract +type Reply = "once" | "always" | "reject" +type Connection = Partial> + +const permissionOptions: PermissionOption[] = [ + { optionId: "once", kind: "allow_once", name: "Allow once" }, + { optionId: "always", kind: "allow_always", name: "Always allow" }, + { optionId: "reject", kind: "reject_once", name: "Reject" }, +] + +export class Handler { + private readonly queues = new Map>() + + constructor( + private readonly input: { + sdk: OpencodeClient + connection: Connection + session: ACPSession.Interface + }, + ) {} + + handle(event: PermissionEvent) { + const permission = event.properties + const previous = this.queues.get(permission.sessionID) ?? Promise.resolve() + const next = previous + .then(() => this.process(event)) + .catch((error: unknown) => { + log.error("failed to handle permission", { error, permissionID: permission.id }) + }) + .finally(() => { + if (this.queues.get(permission.sessionID) === next) { + this.queues.delete(permission.sessionID) + } + }) + this.queues.set(permission.sessionID, next) + } + + private async process(event: PermissionEvent) { + const permission = event.properties + const session = await Effect.runPromise(this.input.session.tryGet(permission.sessionID)) + if (!session) return + + if (!this.input.connection.requestPermission) { + log.error("ACP connection cannot request permission", { + permissionID: permission.id, + sessionID: permission.sessionID, + }) + await this.reply(permission.id, "reject", session.cwd) + return + } + + const result = await this.input.connection + .requestPermission({ + sessionId: permission.sessionID, + toolCall: { + toolCallId: permission.tool?.callID ?? permission.id, + status: "pending", + title: permission.permission, + rawInput: permission.metadata, + kind: toToolKind(permission.permission), + locations: toLocations(permission.permission, permission.metadata), + }, + options: permissionOptions, + }) + .catch(async (error: unknown) => { + log.error("failed to request permission from ACP", { + error, + permissionID: permission.id, + sessionID: permission.sessionID, + }) + await this.reply(permission.id, "reject", session.cwd) + return undefined + }) + + if (!result) return + + const reply = selectedReply(result) + if (reply !== "once" && reply !== "always") { + await this.reply(permission.id, "reject", session.cwd) + return + } + + if (permission.permission === "edit") { + await this.writeProposedEdit(session.id, permission.metadata).catch((error: unknown) => { + log.error("failed to write proposed edit through ACP", { + error, + permissionID: permission.id, + sessionID: permission.sessionID, + }) + }) + } + + await this.reply(permission.id, reply, session.cwd) + } + + private async reply(requestID: string, reply: Reply, directory: string) { + await this.input.sdk.permission.reply({ + requestID, + reply, + directory, + }) + } + + private async writeProposedEdit(sessionId: string, metadata: ToolInput) { + const filepath = stringValue(metadata.filepath) + const diff = stringValue(metadata.diff) + if (!filepath || !diff || !this.input.connection.writeTextFile) return + + const content = (await exists(filepath)) ? await readText(filepath) : "" + const next = applyPatch(content, diff) + if (next === false) { + log.error("Failed to apply unified diff (context mismatch)") + return + } + + void this.input.connection.writeTextFile({ + sessionId, + path: filepath, + content: next, + }) + } +} + +function selectedReply(result: RequestPermissionResponse): Reply { + if (result.outcome.outcome !== "selected") return "reject" + if (result.outcome.optionId === "once" || result.outcome.optionId === "always") return result.outcome.optionId + return "reject" +} + +function stringValue(value: unknown) { + return typeof value === "string" ? value : undefined +} + +export * as ACPPermission from "./permission" diff --git a/packages/opencode/src/acp/profile.ts b/packages/opencode/src/acp/profile.ts new file mode 100644 index 000000000000..9e728b6a1aad --- /dev/null +++ b/packages/opencode/src/acp/profile.ts @@ -0,0 +1,42 @@ +const enabled = process.env.OPENCODE_ACP_PROFILE === "1" +const started = performance.now() + +export function mark(name: string, fields?: Record) { + if (!enabled) return + write(`${name}.mark`, performance.now() - started, fields) +} + +export function duration( + name: string, + startedAt: number, + fields?: Record, +) { + if (!enabled) return + write(name, performance.now() - startedAt, fields) +} + +export async function measure( + name: string, + fn: () => Promise, + fields?: Record, +) { + if (!enabled) return fn() + const start = performance.now() + try { + return await fn() + } finally { + write(name, performance.now() - start, fields) + } +} + +function write(name: string, durationMs: number, fields?: Record) { + const extra = fields + ? Object.entries(fields) + .filter((entry): entry is [string, string | number | boolean] => entry[1] !== undefined) + .map(([key, value]) => `${key}=${value}`) + .join(" ") + : "" + console.error(`[acp-profile] ${name} ${Math.round(durationMs)}ms${extra ? ` ${extra}` : ""}`) +} + +export * as ACPProfile from "./profile" diff --git a/packages/opencode/src/acp/runtime.ts b/packages/opencode/src/acp/runtime.ts deleted file mode 100644 index b08c73cf2e2b..000000000000 --- a/packages/opencode/src/acp/runtime.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Agent } from "@/agent/agent" -import { AppRuntime, type AppServices } from "@/effect/app-runtime" -import { InstanceRef } from "@/effect/instance-ref" -import { InstanceRuntime } from "@/project/instance-runtime" -import { Effect } from "effect" - -// Global ACP Effect re-entry: no project InstanceRef is provided. -export const runGlobal = AppRuntime.runPromise - -// Directory-scoped ACP Effect re-entry: load the project instance and provide InstanceRef. -export async function runDirectory(input: { directory: string; effect: Effect.Effect }) { - const ctx = await InstanceRuntime.load({ directory: input.directory }) - return AppRuntime.runPromise(input.effect.pipe(Effect.provideService(InstanceRef, ctx))) -} - -export const defaultAgentInfo = (directory: string) => - runDirectory({ - directory, - effect: Agent.Service.use((svc) => svc.defaultInfo()), - }) - -export * as ACPRuntime from "./runtime" diff --git a/packages/opencode/src/acp/service.ts b/packages/opencode/src/acp/service.ts new file mode 100644 index 000000000000..b8c700ea064f --- /dev/null +++ b/packages/opencode/src/acp/service.ts @@ -0,0 +1,1065 @@ +import { + type AgentSideConnection, + type AuthenticateRequest, + type AuthenticateResponse, + type AuthMethod, + type CancelNotification, + type CloseSessionRequest, + type CloseSessionResponse, + type ForkSessionRequest, + type ForkSessionResponse, + type InitializeRequest, + type InitializeResponse, + type ListSessionsRequest, + type ListSessionsResponse, + type LoadSessionRequest, + type LoadSessionResponse, + type McpServer, + type NewSessionRequest, + type NewSessionResponse, + type PromptRequest, + type PromptResponse, + type ResumeSessionRequest, + type ResumeSessionResponse, + type SessionInfo, + type SetSessionConfigOptionRequest, + type SetSessionConfigOptionResponse, + type SetSessionModelRequest, + type SetSessionModelResponse, + type SetSessionModeRequest, + type SetSessionModeResponse, +} from "@agentclientprotocol/sdk" +import { InstallationVersion } from "@opencode-ai/core/installation/version" +import * as Log from "@opencode-ai/core/util/log" +import type { Message, OpencodeClient, SessionMessageResponse } from "@opencode-ai/sdk/v2" +import { Context, Effect, Layer, ManagedRuntime } from "effect" +import * as ACPError from "./error" +import { buildConfigOptions, parseModelSelection } from "./config-option" +import { promptContentToParts } from "./content" +import { Directory } from "./directory" +import { ACPEvent } from "./event" +import { ACPSession } from "./session" +import { UsageService } from "./usage" +import { ACPProfile } from "./profile" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { Provider } from "@/provider/provider" +import type { Command } from "@/command" + +export const AuthMethodID = "opencode-login" +const log = Log.create({ service: "acp-service" }) + +export type Error = ACPError.Error +type ServiceConnection = Pick & + Partial> + +export type Interface = { + readonly initialize: (input: InitializeRequest) => Effect.Effect + readonly authenticate: (input: AuthenticateRequest) => Effect.Effect + readonly newSession: (input: NewSessionRequest) => Effect.Effect + readonly loadSession: (input: LoadSessionRequest) => Effect.Effect + readonly listSessions: (input: ListSessionsRequest) => Effect.Effect + readonly resumeSession: (input: ResumeSessionRequest) => Effect.Effect + readonly closeSession: (input: CloseSessionRequest) => Effect.Effect + readonly forkSession: (input: ForkSessionRequest) => Effect.Effect + readonly setSessionConfigOption: ( + input: SetSessionConfigOptionRequest, + ) => Effect.Effect + readonly setSessionMode: (input: SetSessionModeRequest) => Effect.Effect + readonly setSessionModel: (input: SetSessionModelRequest) => Effect.Effect + readonly prompt: (input: PromptRequest) => Effect.Effect + readonly cancel: (input: CancelNotification) => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/ACP/Service") {} + +export function make(input: { + sdk: OpencodeClient + connection?: ServiceConnection + directory?: Directory.Interface + session?: ACPSession.Interface + usage?: UsageService.Interface + eventSubscription?: (subscription: ACPEvent.Subscription) => void +}): Interface { + const session = input.session ?? makeSessionService() + const directoryService = input.directory ?? makeDirectoryService(input.sdk) + const registeredMcp = new Map>() + const sessionSnapshots = new Map() + const events = input.connection + ? ACPEvent.start({ sdk: input.sdk, connection: input.connection, session }) + : undefined + if (events) input.eventSubscription?.(events) + + const initialize = Effect.fn("ACP.initialize")(function* (params: InitializeRequest) { + const started = performance.now() + const authMethod: AuthMethod = { + description: "Run `opencode auth login` in the terminal", + name: "Login with opencode", + id: AuthMethodID, + } + + if (params.clientCapabilities?._meta?.["terminal-auth"] === true) { + authMethod._meta = { + "terminal-auth": { + command: "opencode", + args: ["auth", "login"], + label: "OpenCode Login", + }, + } + } + + const response = { + protocolVersion: 1, + agentCapabilities: { + loadSession: true, + mcpCapabilities: { + http: true, + sse: true, + }, + promptCapabilities: { + embeddedContext: true, + image: true, + }, + sessionCapabilities: { + close: {}, + fork: {}, + list: {}, + resume: {}, + }, + }, + authMethods: [authMethod], + agentInfo: { + name: "OpenCode", + version: InstallationVersion, + }, + } + ACPProfile.duration("acp.initialize", started) + return response + }) + + const authenticate = Effect.fn("ACP.authenticate")(function* (params: AuthenticateRequest) { + if (params.methodId !== AuthMethodID) { + return yield* new ACPError.UnknownAuthMethodError({ methodId: params.methodId }) + } + return {} + }) + + const directorySnapshot = Effect.fn("ACP.directorySnapshot")(function* (cwd: string) { + const started = performance.now() + const snapshot = yield* directoryService.get(cwd) + ACPProfile.duration("acp.directory.snapshot", started) + return snapshot + }) + + const configSnapshot = Effect.fn("ACP.configSnapshot")(function* (state: ACPSession.Info) { + const snapshot = sessionSnapshots.get(state.id) + if (snapshot) return snapshot + const loaded = yield* directorySnapshot(state.cwd) + sessionSnapshots.set(state.id, loaded) + return loaded + }) + + const newSession = Effect.fn("ACP.newSession")(function* (params: NewSessionRequest) { + const started = performance.now() + const snapshot = yield* directorySnapshot(params.cwd) + const selected = selectDefaultModel(snapshot) + const variant = selectVariant(snapshot, selected) + const modeId = snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined + const created = yield* profiledRequest( + "acp.newSession.session.create", + () => + input.sdk.session.create( + { + directory: params.cwd, + ...(modeId ? { agent: modeId } : {}), + model: { + providerID: selected.providerID, + id: selected.modelID, + ...(variant ? { variant } : {}), + }, + }, + { throwOnError: true }, + ), + "session", + ) + const state = yield* session.create({ + id: created.id, + cwd: params.cwd, + mcpServers: params.mcpServers, + model: selected, + variant, + modeId, + }) + sessionSnapshots.set(state.id, snapshot) + + yield* registerMcpServers(input.sdk, registeredMcp, params.cwd, state.id, params.mcpServers) + yield* sendAvailableCommands(input.connection, state.id, snapshot) + + const response = { + sessionId: state.id, + configOptions: configOptions(snapshot, { + model: state.model ?? selected, + variant: state.variant, + modeId: state.modeId, + }), + } + ACPProfile.duration("acp.newSession", started) + return response + }) + + const loadSession = Effect.fn("ACP.loadSession")(function* (params: LoadSessionRequest) { + const snapshot = yield* directorySnapshot(params.cwd) + yield* request( + () => input.sdk.session.get({ directory: params.cwd, sessionID: params.sessionId }, { throwOnError: true }), + "session", + ) + const messages = yield* request( + () => + input.sdk.session.messages( + { directory: params.cwd, sessionID: params.sessionId, limit: 100 }, + { throwOnError: true }, + ), + "session", + ) + const restored = restoreFromMessages(messages.map((item) => item.info)) + const model = restored.model ?? selectDefaultModel(snapshot) + const state = yield* session.load({ + id: params.sessionId, + cwd: params.cwd, + mcpServers: params.mcpServers, + model, + variant: restored.variant ?? selectVariant(snapshot, model), + modeId: restored.modeId ?? (snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined), + }) + sessionSnapshots.set(state.id, snapshot) + + yield* registerMcpServers(input.sdk, registeredMcp, params.cwd, state.id, params.mcpServers) + yield* sendAvailableCommands(input.connection, state.id, snapshot) + yield* replayMessages(events, messages) + + return { + configOptions: configOptions(snapshot, { + model: state.model ?? model, + variant: state.variant, + modeId: state.modeId, + }), + } + }) + + const listSessions = Effect.fn("ACP.listSessions")(function* (params: ListSessionsRequest) { + const cursor = params.cursor ? Number(params.cursor) : undefined + const limit = 100 + const sessions = yield* request( + () => + input.sdk.session.list( + { + ...(params.cwd ? { directory: params.cwd } : {}), + roots: true, + }, + { throwOnError: true }, + ), + "session", + ) + const serverEntries = sessions.map( + (item): SessionInfo => ({ + sessionId: item.id, + cwd: item.directory, + title: item.title, + updatedAt: new Date(item.time.updated).toISOString(), + }), + ) + const liveEntries = (yield* session.list(params.cwd ?? undefined)) + .filter((item) => !serverEntries.some((entry) => entry.sessionId === item.id)) + .map( + (item): SessionInfo => ({ + sessionId: item.id, + cwd: item.cwd, + updatedAt: item.createdAt.toISOString(), + }), + ) + const sorted = [...liveEntries, ...serverEntries].toSorted( + (a, b) => new Date(b.updatedAt ?? 0).getTime() - new Date(a.updatedAt ?? 0).getTime(), + ) + const filtered = + cursor === undefined || !Number.isFinite(cursor) + ? sorted + : sorted.filter((item) => new Date(item.updatedAt ?? 0).getTime() < cursor) + const page = filtered.slice(0, limit) + const last = page.at(-1) + return { + sessions: page, + ...(filtered.length > limit && last ? { nextCursor: String(new Date(last.updatedAt ?? 0).getTime()) } : {}), + } + }) + + const resumeSession = Effect.fn("ACP.resumeSession")(function* (params: ResumeSessionRequest) { + const snapshot = yield* directorySnapshot(params.cwd) + yield* request( + () => input.sdk.session.get({ directory: params.cwd, sessionID: params.sessionId }, { throwOnError: true }), + "session", + ) + const messages = yield* request( + () => + input.sdk.session.messages( + { directory: params.cwd, sessionID: params.sessionId, limit: 20 }, + { throwOnError: true }, + ), + "session", + ) + const restored = restoreFromMessages(messages.map((item) => item.info)) + const model = restored.model ?? selectDefaultModel(snapshot) + const state = yield* session.load({ + id: params.sessionId, + cwd: params.cwd, + mcpServers: params.mcpServers ?? [], + model, + variant: restored.variant ?? selectVariant(snapshot, model), + modeId: restored.modeId ?? (snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined), + }) + sessionSnapshots.set(state.id, snapshot) + + yield* registerMcpServers(input.sdk, registeredMcp, params.cwd, state.id, params.mcpServers ?? []) + yield* sendAvailableCommands(input.connection, state.id, snapshot) + yield* replayMessages(events, messages) + + return { + configOptions: configOptions(snapshot, { + model: state.model ?? model, + variant: state.variant, + modeId: state.modeId, + }), + } + }) + + const abortBackingSession = Effect.fn("ACP.abortBackingSession")(function* (current: ACPSession.Info) { + yield* request( + () => input.sdk.session.abort({ directory: current.cwd, sessionID: current.id }, { throwOnError: true }), + "session", + ).pipe( + Effect.catch((error) => + Effect.sync(() => { + log.error("failed to abort ACP backing session", { error, sessionID: current.id }) + }), + ), + ) + }) + + const closeSession = Effect.fn("ACP.closeSession")(function* (params: CloseSessionRequest) { + const removed = yield* session.remove(params.sessionId) + registeredMcp.delete(params.sessionId) + sessionSnapshots.delete(params.sessionId) + if (!removed) return {} + + yield* abortBackingSession(removed) + return {} + }) + + const cancel = Effect.fn("ACP.cancel")(function* (params: CancelNotification) { + const current = yield* session.get(params.sessionId) + yield* abortBackingSession(current) + }) + + const forkSession = Effect.fn("ACP.forkSession")(function* (params: ForkSessionRequest) { + const snapshot = yield* directorySnapshot(params.cwd) + const forked = yield* request( + () => + input.sdk.session.fork( + { + directory: params.cwd, + sessionID: params.sessionId, + }, + { throwOnError: true }, + ), + "session", + ) + const messages = yield* request( + () => + input.sdk.session.messages({ directory: params.cwd, sessionID: forked.id, limit: 20 }, { throwOnError: true }), + "session", + ) + const restored = restoreFromMessages(messages.map((item) => item.info)) + const model = restored.model ?? selectDefaultModel(snapshot) + const state = yield* session.load({ + id: forked.id, + cwd: params.cwd, + mcpServers: params.mcpServers ?? [], + model, + variant: restored.variant ?? selectVariant(snapshot, model), + modeId: restored.modeId ?? (snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined), + }) + sessionSnapshots.set(state.id, snapshot) + + yield* registerMcpServers(input.sdk, registeredMcp, params.cwd, state.id, params.mcpServers ?? []) + yield* sendAvailableCommands(input.connection, state.id, snapshot) + yield* replayMessages(events, messages) + + return { + sessionId: state.id, + configOptions: configOptions(snapshot, { + model: state.model ?? model, + variant: state.variant, + modeId: state.modeId, + }), + } + }) + + const setSessionConfigOption = Effect.fn("ACP.setSessionConfigOption")(function* ( + params: SetSessionConfigOptionRequest, + ) { + const current = yield* session.get(params.sessionId) + const snapshot = yield* configSnapshot(current) + if (typeof params.value !== "string") { + return yield* new ACPError.InvalidConfigOptionError({ configId: params.configId }) + } + + if (params.configId === "model") { + const selected = yield* parseSelectedModel(snapshot, params.value) + const variant = selected.variant ?? selectVariant(snapshot, selected.model) + const state = yield* session + .setVariant(params.sessionId, Directory.variants(snapshot, selected.model) ? variant : undefined) + .pipe(Effect.andThen(session.setModel(params.sessionId, selected.model))) + return { + configOptions: configOptions(snapshot, { + model: state.model ?? selected.model, + variant: state.variant, + modeId: state.modeId, + }), + } + } + + if (params.configId === "effort") { + const model = current.model ?? selectDefaultModel(snapshot) + const variants = Directory.variants(snapshot, model) + if (!variants || !Object.keys(variants).includes(params.value)) { + return yield* new ACPError.InvalidEffortError({ effort: params.value }) + } + const state = yield* session.setVariant(params.sessionId, params.value) + return { + configOptions: configOptions(snapshot, { + model: state.model ?? model, + variant: state.variant, + modeId: state.modeId, + }), + } + } + + if (params.configId === "mode") { + if (!snapshot.availableModes.some((mode) => mode.id === params.value)) { + return yield* new ACPError.InvalidModeError({ mode: params.value }) + } + const state = yield* session.setMode(params.sessionId, params.value) + return { + configOptions: configOptions(snapshot, { + model: state.model ?? selectDefaultModel(snapshot), + variant: state.variant, + modeId: state.modeId, + }), + } + } + + return yield* new ACPError.InvalidConfigOptionError({ configId: params.configId }) + }) + + const setSessionMode = Effect.fn("ACP.setSessionMode")(function* (params: SetSessionModeRequest) { + const current = yield* session.get(params.sessionId) + const snapshot = yield* configSnapshot(current) + if (!snapshot.availableModes.some((mode) => mode.id === params.modeId)) { + return yield* new ACPError.InvalidModeError({ mode: params.modeId }) + } + yield* session.setMode(params.sessionId, params.modeId) + return {} + }) + + const setSessionModel = Effect.fn("ACP.setSessionModel")(function* (params: SetSessionModelRequest) { + const current = yield* session.get(params.sessionId) + const snapshot = yield* configSnapshot(current) + const selected = yield* parseSelectedModel(snapshot, params.modelId) + yield* session + .setVariant( + params.sessionId, + Directory.variants(snapshot, selected.model) + ? (selected.variant ?? selectVariant(snapshot, selected.model)) + : undefined, + ) + .pipe(Effect.andThen(session.setModel(params.sessionId, selected.model))) + return {} + }) + + return { + initialize, + authenticate, + newSession, + loadSession, + listSessions, + resumeSession, + closeSession, + forkSession, + setSessionConfigOption, + setSessionMode, + setSessionModel, + prompt: Effect.fn("ACP.prompt")(function* (params: PromptRequest) { + const current = yield* session.get(params.sessionId) + const snapshot = yield* directorySnapshot(current.cwd) + const selected = current.model ?? selectDefaultModel(snapshot) + if (!current.model) { + yield* session.setModel(params.sessionId, selected) + } + const variant = current.variant ?? selectVariant(snapshot, selected) + const modeId = current.modeId ?? (snapshot.availableModes.length > 0 ? snapshot.defaultModeID : undefined) + const parts = promptContentToParts(params.prompt) + const command = detectSlashCommand(parts) + + if (!command) { + const response = yield* request( + () => + input.sdk.session.prompt( + { + sessionID: current.id, + model: { + providerID: selected.providerID, + modelID: selected.modelID, + }, + ...(variant ? { variant } : {}), + parts, + ...(modeId ? { agent: modeId } : {}), + directory: current.cwd, + }, + { throwOnError: true }, + ), + "session", + ) + yield* sendUsageUpdate(input.usage, input.sdk, input.connection, current.id, current.cwd) + return promptResponse(response.info, params.messageId) + } + + const known = snapshot.availableCommands.find((item) => item.name === command.name) + if (known) { + const response = yield* request( + () => + input.sdk.session.command( + { + sessionID: current.id, + command: known.name, + arguments: command.args, + model: `${selected.providerID}/${selected.modelID}`, + ...(variant ? { variant } : {}), + ...(modeId ? { agent: modeId } : {}), + directory: current.cwd, + }, + { throwOnError: true }, + ), + "session", + ) + yield* sendUsageUpdate(input.usage, input.sdk, input.connection, current.id, current.cwd) + return promptResponse(response.info, params.messageId) + } + + if (command.name === "compact") { + yield* request( + () => + input.sdk.session.summarize( + { + sessionID: current.id, + directory: current.cwd, + providerID: selected.providerID, + modelID: selected.modelID, + }, + { throwOnError: true }, + ), + "session", + ) + } + + yield* sendUsageUpdate(input.usage, input.sdk, input.connection, current.id, current.cwd) + return promptResponse(undefined, params.messageId) + }), + cancel, + } +} + +function makeSessionService() { + return ManagedRuntime.make(ACPSession.defaultLayer).runSync( + ACPSession.Service.use((service) => Effect.succeed(service)), + ) +} + +function makeDirectoryService(sdk: OpencodeClient) { + return ManagedRuntime.make( + Directory.layer.pipe( + Layer.provide( + Layer.succeed( + Directory.Loader, + Directory.Loader.of({ + load: (directory) => request(() => loadDirectorySnapshot(sdk, directory), "directory"), + }), + ), + ), + ), + ).runSync(Directory.Service.use((service) => Effect.succeed(service))) +} + +function makeUsageService(sdk: OpencodeClient) { + const limits = new Map>() + const contextLimit: UsageService.Interface["contextLimit"] = Effect.fn("ACP.promptUsage.contextLimit")( + function* (params) { + const key = `${params.directory}\u0000${params.providerID}\u0000${params.modelID}` + const current = limits.get(key) + if (current) return yield* Effect.promise(() => current) + + const next = sdk.config + .providers({ directory: params.directory }, { throwOnError: true }) + .then((response) => { + const providers = Object.fromEntries( + (response.data?.providers ?? []).map((provider) => [provider.id, provider]), + ) as Record + return UsageService.findContextLimit(providers, params.providerID, params.modelID) + }) + .catch((error: unknown) => { + log.error("failed to get providers for usage context limit", { error }) + return undefined + }) + limits.set(key, next) + return yield* Effect.promise(() => next) + }, + ) + + const sendUpdate: UsageService.Interface["sendUpdate"] = Effect.fn("ACP.promptUsage.sendUpdate")(function* (params) { + const messages = yield* request( + () => + sdk.session.messages( + { + sessionID: params.sessionID, + directory: params.directory, + }, + { throwOnError: true }, + ), + "session", + ).pipe( + Effect.map((messages) => messages as readonly UsageService.SessionMessage[]), + Effect.catch((error) => + Effect.sync(() => { + log.error("failed to fetch messages for usage update", { error }) + return undefined + }), + ), + ) + if (!messages) return + + const message = UsageService.latestAssistantMessage(messages) + if (!message?.providerID || !message.modelID) return + + const size = yield* contextLimit({ + directory: params.directory, + providerID: ProviderV2.ID.make(message.providerID), + modelID: ProviderV2.ModelID.make(message.modelID), + }) + if (!size) return + + yield* Effect.promise(() => + params.connection + .sessionUpdate({ + sessionId: params.sessionID, + update: { + sessionUpdate: "usage_update", + used: message.tokens.input + message.tokens.cache.read, + size, + cost: { amount: UsageService.totalSessionCost(messages), currency: "USD" }, + }, + }) + .catch((error) => { + log.error("failed to send usage update", { error }) + }), + ) + }) + + return UsageService.Service.of({ + buildUsage: UsageService.buildUsage, + latestAssistantMessage: UsageService.latestAssistantMessage, + totalSessionCost: UsageService.totalSessionCost, + contextLimit, + sendUpdate, + }) +} + +function replayMessages(subscription: ACPEvent.Subscription | undefined, messages: SessionMessageResponse[]) { + if (!subscription) return Effect.void + return Effect.promise(async () => { + for (const message of messages) { + await subscription.replayMessage(message).catch((error: unknown) => { + log.error("failed to replay ACP message", { error, messageID: message.info.id }) + }) + } + }) +} + +type ConfigState = { + readonly model: Directory.DefaultModel + readonly variant?: string + readonly modeId?: string +} + +type SdkResponse = { + readonly data?: T + readonly error?: unknown +} + +type MessageInfo = { + readonly role?: Message["role"] + readonly model?: Extract["model"] + readonly providerID?: Extract["providerID"] + readonly modelID?: Extract["modelID"] + readonly variant?: Extract["variant"] + readonly mode?: Extract["mode"] + readonly agent?: Message["agent"] +} + +type AssistantInfo = UsageService.AssistantTokenCost | undefined + +function request(fn: () => Promise>, service?: string) { + return Effect.tryPromise({ + try: async () => { + const result = await fn() + if (isSdkResponse(result)) { + if (result.error) throw result.error + if (result.data !== undefined) return result.data + } + return result as T + }, + catch: (error) => fromUnknownError(error, service), + }) +} + +function profiledRequest(name: string, fn: () => Promise>, service?: string) { + return request(() => ACPProfile.measure(name, fn), service) +} + +async function loadDirectorySnapshot(sdk: OpencodeClient, directory: string) { + return ACPProfile.measure("acp.directory.load", async () => { + const [providersResponse, agentsResponse, commandsResponse, skillsResponse, configResponse] = await Promise.all([ + ACPProfile.measure("acp.directory.provider.list", () => + sdk.config.providers({ directory }, { throwOnError: true }), + ), + ACPProfile.measure("acp.directory.mode.defaultAgent.load", () => + sdk.app.agents({ directory }, { throwOnError: true }), + ), + ACPProfile.measure("acp.directory.command.list", () => sdk.command.list({ directory }, { throwOnError: true })), + ACPProfile.measure("acp.directory.skill.list", () => sdk.app.skills({ directory }, { throwOnError: true })), + ACPProfile.measure("acp.directory.defaultModel.config", () => + sdk.config.get({ directory }, { throwOnError: true }).catch(() => undefined), + ), + ]) + const providersData = providersResponse.data! + const agents = agentsResponse.data! + const commandsData = commandsResponse.data! + const skills = skillsResponse.data! + const providers = Object.fromEntries(providersData.providers.map((provider) => [provider.id, provider])) as Record< + ProviderV2.ID, + Provider.Info + > + const defaultModelStarted = performance.now() + const defaultModel = defaultModelFromConfig(configResponse?.data?.model, providers) + ACPProfile.duration("acp.directory.defaultModel.resolve", defaultModelStarted, { configured: !!defaultModel }) + const modes = agents + .filter((agent) => agent.mode !== "subagent" && agent.hidden !== true) + .map((agent) => ({ + id: agent.name, + name: agent.name, + ...(agent.description ? { description: agent.description } : {}), + })) + const commands = [ + ...commandsData, + ...skills + .filter((skill) => !commandsData.some((command) => command.name === skill.name)) + .map((skill) => ({ + name: skill.name, + description: skill.description, + source: "skill" as const, + template: skill.content, + hints: [], + })), + ] as Command.Info[] + + return Directory.build({ + directory, + providers, + modes, + defaultModeID: agents.find((agent) => agent.mode === "primary" && agent.hidden !== true)?.name ?? "build", + commands: commands.toSorted((a, b) => a.name.localeCompare(b.name)), + ...(defaultModel ? { defaultModel } : {}), + }) + }) +} + +function defaultModelFromConfig( + configuredModel: string | undefined, + providers: Record, +): Directory.DefaultModel | undefined { + const configured = configuredModel ? Provider.parseModel(configuredModel) : undefined + if (configured && providers[configured.providerID]?.models[configured.modelID]) return configured + + // First-session ACP startup must not scan historical sessions just to infer + // a default. Configured model, opencode provider, then sorted best model keep + // the protocol response deterministic without extra session/message reads. + const opencodeProvider = providers[ProviderV2.ID.make("opencode")] + const opencodeModel = opencodeProvider ? Provider.sort(Object.values(opencodeProvider.models))[0] : undefined + if (opencodeProvider && opencodeModel) return { providerID: opencodeProvider.id, modelID: opencodeModel.id } + + const best = Provider.sort(Object.values(providers).flatMap((provider) => Object.values(provider.models)))[0] + if (best) return { providerID: best.providerID, modelID: best.id } + if (configured) return configured +} + +function selectDefaultModel(snapshot: Directory.Snapshot) { + if (snapshot.defaultModel) return snapshot.defaultModel + const model = snapshot.modelOptions[0] + if (model) return { providerID: model.providerID, modelID: model.modelID } + return { providerID: "unknown" as ProviderV2.ID, modelID: "unknown" as ProviderV2.ModelID } +} + +function detectSlashCommand(parts: ReturnType) { + const text = parts + .filter((part): part is Extract<(typeof parts)[number], { type: "text" }> => part.type === "text") + .map((part) => part.text) + .join("") + .trim() + if (!text.startsWith("/")) return + + const [name, ...rest] = text.slice(1).split(/\s+/) + if (!name) return + return { name, args: rest.join(" ").trim() } +} + +function promptResponse(info: AssistantInfo, messageId: string | null | undefined): PromptResponse { + return { + stopReason: "end_turn", + ...(info ? { usage: UsageService.buildUsage(info) } : {}), + ...(messageId ? { userMessageId: messageId } : {}), + _meta: {}, + } +} + +function sendUsageUpdate( + usage: UsageService.Interface | undefined, + sdk: OpencodeClient, + connection: ServiceConnection | undefined, + sessionID: string, + directory: string, +) { + if (!connection) return Effect.void + return (usage ?? makeUsageService(sdk)).sendUpdate({ + connection, + sessionID, + directory, + }) +} + +function selectVariant(snapshot: Directory.Snapshot, model: Directory.DefaultModel) { + const variants = Directory.variants(snapshot, model) + if (!variants) return + if (variants.default) return "default" + return Object.keys(variants)[0] +} + +function configOptions(snapshot: Directory.Snapshot, session: ConfigState) { + return buildConfigOptions({ + providers: Object.values(snapshot.providers), + currentModel: session.model, + currentVariant: session.variant, + modes: snapshot.availableModes, + currentModeId: session.modeId, + }) +} + +function parseSelectedModel(snapshot: Directory.Snapshot, modelId: string) { + const selected = parseModelSelection(modelId, Object.values(snapshot.providers)) + const provider = snapshot.providers[ProviderV2.ID.make(selected.model.providerID)] + const model = provider?.models[ProviderV2.ModelID.make(selected.model.modelID)] + if (!model) { + return Effect.fail( + new ACPError.InvalidModelError({ + providerId: selected.model.providerID, + modelId, + }), + ) + } + if (selected.variant && !model.variants?.[selected.variant]) { + return Effect.fail(new ACPError.InvalidEffortError({ effort: selected.variant })) + } + return Effect.succeed({ + model: { + providerID: provider.id, + modelID: model.id, + }, + variant: selected.variant, + }) +} + +function sendAvailableCommands( + connection: Pick | undefined, + sessionId: string, + snapshot: Directory.Snapshot, +) { + if (!connection) return Effect.void + return Effect.sync(() => { + setTimeout(() => { + void connection.sessionUpdate({ + sessionId, + update: { + sessionUpdate: "available_commands_update", + availableCommands: snapshot.availableCommands.map((command) => ({ + name: command.name, + description: command.description ?? "", + })), + }, + }) + }, 0) + }) +} + +function registerMcpServers( + sdk: OpencodeClient, + registered: Map>, + directory: string, + sessionId: string, + servers: readonly McpServer[], +) { + const started = performance.now() + const current = registered.get(sessionId) ?? new Set() + registered.set(sessionId, current) + const pending = new Set() + + return Effect.all( + servers + .map((server) => ({ server, config: mcpConfig(server) })) + .filter((entry) => { + const key = mcpRegistrationKey(entry.server.name, entry.config) + if (current.has(key) || pending.has(key)) return false + pending.add(key) + return true + }) + .map((entry) => + request( + () => + sdk.mcp.add( + { + directory, + name: entry.server.name, + config: entry.config, + }, + { throwOnError: true }, + ), + "mcp", + ).pipe( + Effect.tap(() => Effect.sync(() => current.add(mcpRegistrationKey(entry.server.name, entry.config)))), + Effect.ignore, + ), + ), + { concurrency: "unbounded" }, + ).pipe( + Effect.tap(() => + Effect.sync(() => + ACPProfile.duration("acp.mcp.register", started, { + count: pending.size, + }), + ), + ), + Effect.asVoid, + ) +} + +function mcpRegistrationKey(name: string, config: ReturnType) { + return `${name}:${stableStringify(config)}` +} + +function mcpConfig(server: McpServer) { + if ("type" in server) { + return { + type: "remote" as const, + url: server.url, + headers: Object.fromEntries(server.headers.map((header) => [header.name, header.value])), + } + } + return { + type: "local" as const, + command: [server.command, ...server.args], + environment: Object.fromEntries(server.env.map((entry) => [entry.name, entry.value])), + } +} + +function stableStringify(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]` + if (!value || typeof value !== "object") return JSON.stringify(value) + return `{${Object.entries(value) + .toSorted(([a], [b]) => a.localeCompare(b)) + .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`) + .join(",")}}` +} + +function restoreFromMessages(messages: readonly MessageInfo[]) { + const user = messages.findLast( + (message) => message.role === "user" && message.model?.providerID && message.model.modelID, + ) + if (user?.model?.providerID && user.model.modelID) { + return { + model: { providerID: user.model.providerID as ProviderV2.ID, modelID: user.model.modelID as ProviderV2.ModelID }, + variant: user.model.variant, + modeId: user.agent, + } + } + + const assistant = messages.findLast((message) => message.providerID && message.modelID) + if (assistant?.providerID && assistant.modelID) { + return { + model: { providerID: assistant.providerID as ProviderV2.ID, modelID: assistant.modelID as ProviderV2.ModelID }, + variant: assistant.variant, + modeId: assistant.mode ?? assistant.agent, + } + } + + return {} +} + +function isSdkResponse(value: T | SdkResponse): value is SdkResponse { + return typeof value === "object" && value !== null && ("data" in value || "error" in value) +} + +function fromUnknownError(error: unknown, service?: string): Error { + if (isACPError(error)) return error + if (isAuthRequired(error)) { + return new ACPError.AuthRequiredError({ providerId: findProviderID(error) }) + } + return new ACPError.ServiceFailureError({ safeMessage: "OpenCode service failure", service }) +} + +function isACPError(error: unknown): error is Error { + return ( + typeof error === "object" && + error !== null && + "_tag" in error && + typeof error._tag === "string" && + error._tag.startsWith("ACP") + ) +} + +function isAuthRequired(value: unknown): boolean { + if (typeof value !== "object" || value === null) return false + if (value instanceof Error && (value.name === "ProviderAuthError" || value.name === "LoadAPIKeyError")) return true + if ( + value instanceof Error && + (value.message.includes("ProviderAuthError") || value.message.includes("LoadAPIKeyError")) + ) { + return true + } + if ("name" in value && (value.name === "ProviderAuthError" || value.name === "LoadAPIKeyError")) return true + if ("_tag" in value && (value._tag === "ProviderAuthError" || value._tag === "LoadAPIKeyError")) return true + if ("error" in value && isAuthRequired(value.error)) return true + if ("data" in value && isAuthRequired(value.data)) return true + return false +} + +function findProviderID(value: unknown): string | undefined { + if (typeof value !== "object" || value === null) return + if ("providerID" in value && typeof value.providerID === "string") return value.providerID + if ("providerId" in value && typeof value.providerId === "string") return value.providerId + if ("data" in value) return findProviderID(value.data) + if ("error" in value) return findProviderID(value.error) +} diff --git a/packages/opencode/src/acp/session.ts b/packages/opencode/src/acp/session.ts index cc1ed0be3098..7b7dc9d4a12c 100644 --- a/packages/opencode/src/acp/session.ts +++ b/packages/opencode/src/acp/session.ts @@ -1,122 +1,230 @@ -import { RequestError, type McpServer } from "@agentclientprotocol/sdk" -import type { ACPSessionState } from "./types" -import * as Log from "@opencode-ai/core/util/log" -import type { OpencodeClient } from "@opencode-ai/sdk/v2" +import type { McpServer } from "@agentclientprotocol/sdk" +import type { Message, Part } from "@opencode-ai/sdk/v2" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { Context, Effect, Layer, Ref } from "effect" +import * as ACPError from "./error" + +export type SelectedModel = { + providerID: ProviderV2.ID + modelID: ProviderV2.ModelID +} -const log = Log.create({ service: "acp-session-manager" }) +export type KnownMessagePartMetadata = { + messageId: string + partId: string + partType?: Part["type"] + role?: Message["role"] + ignored?: boolean + toolCallId?: string + metadata?: unknown +} -export class ACPSessionManager { - private sessions = new Map() - private sdk: OpencodeClient +export type Info = { + id: string + cwd: string + mcpServers: readonly McpServer[] + createdAt: Date + model?: SelectedModel + variant?: string + modeId?: string + knownParts: ReadonlyMap +} - constructor(sdk: OpencodeClient) { - this.sdk = sdk - } +export type StoreInput = { + id: string + cwd: string + mcpServers?: readonly McpServer[] + createdAt?: Date + model?: SelectedModel + variant?: string + modeId?: string +} - tryGet(sessionId: string): ACPSessionState | undefined { - return this.sessions.get(sessionId) - } +export type RecordPartMetadataInput = { + sessionId: string + messageId: string + partId: string + partType?: Part["type"] + role?: Message["role"] + ignored?: boolean + toolCallId?: string + metadata?: unknown +} - async create(cwd: string, mcpServers: McpServer[], model?: ACPSessionState["model"]): Promise { - const session = await this.sdk.session - .create( - { - directory: cwd, - }, - { throwOnError: true }, - ) - .then((x) => x.data!) - - const sessionId = session.id - const resolvedModel = model - - const state: ACPSessionState = { - id: sessionId, - cwd, - mcpServers, - createdAt: new Date(), - model: resolvedModel, - } - log.info("creating_session", { state }) - - this.sessions.set(sessionId, state) - return state - } +export type PartMetadataLookupInput = { + sessionId: string + messageId: string + partId: string +} - async load( +export type Interface = { + readonly create: (input: StoreInput) => Effect.Effect + readonly load: (input: StoreInput) => Effect.Effect + readonly list: (cwd?: string) => Effect.Effect + readonly get: (sessionId: string) => Effect.Effect + readonly tryGet: (sessionId: string) => Effect.Effect + readonly remove: (sessionId: string) => Effect.Effect + readonly setModel: ( sessionId: string, - cwd: string, - mcpServers: McpServer[], - model?: ACPSessionState["model"], - ): Promise { - const session = await this.sdk.session - .get( - { - sessionID: sessionId, - directory: cwd, - }, - { throwOnError: true }, - ) - .then((x) => x.data!) - - const resolvedModel = model - - const state: ACPSessionState = { - id: sessionId, - cwd, - mcpServers, - createdAt: new Date(session.time.created), - model: resolvedModel, - } - log.info("loading_session", { state }) - - this.sessions.set(sessionId, state) - return state - } - - get(sessionId: string): ACPSessionState { - const session = this.sessions.get(sessionId) - if (!session) { - log.error("session not found", { sessionId }) - throw RequestError.invalidParams(JSON.stringify({ error: `Session not found: ${sessionId}` })) - } - return session - } - - getModel(sessionId: string) { - const session = this.get(sessionId) - return session.model - } - - setModel(sessionId: string, model: ACPSessionState["model"]) { - const session = this.get(sessionId) - session.model = model - this.sessions.set(sessionId, session) - return session - } - - getVariant(sessionId: string) { - const session = this.get(sessionId) - return session.variant - } + model: SelectedModel | undefined, + ) => Effect.Effect + readonly getModel: (sessionId: string) => Effect.Effect + readonly setVariant: ( + sessionId: string, + variant: string | undefined, + ) => Effect.Effect + readonly getVariant: (sessionId: string) => Effect.Effect + readonly setMode: ( + sessionId: string, + modeId: string | undefined, + ) => Effect.Effect + readonly getMode: (sessionId: string) => Effect.Effect + readonly recordPartMetadata: ( + input: RecordPartMetadataInput, + ) => Effect.Effect + readonly getPartMetadata: ( + input: PartMetadataLookupInput, + ) => Effect.Effect + readonly tryGetPartMetadata: (input: PartMetadataLookupInput) => Effect.Effect +} - setVariant(sessionId: string, variant?: string) { - const session = this.get(sessionId) - session.variant = variant - this.sessions.set(sessionId, session) - return session +export class Service extends Context.Service()("@opencode/ACP/Session") {} + +type State = Map + +export const layer = Layer.effect( + Service, + Effect.gen(function* () { + const sessions = yield* Ref.make(new Map()) + + const store = Effect.fn("ACP.Session.store")(function* (input: StoreInput) { + const session = makeSession(input) + yield* Ref.update(sessions, (state) => new Map(state).set(session.id, session)) + return snapshot(session) + }) + + const tryGet = Effect.fn("ACP.Session.tryGet")(function* (sessionId: string) { + const session = (yield* Ref.get(sessions)).get(sessionId) + if (!session) return + return snapshot(session) + }) + + const get = Effect.fn("ACP.Session.get")(function* (sessionId: string) { + const session = yield* tryGet(sessionId) + if (session) return session + return yield* new ACPError.SessionNotFoundError({ sessionId }) + }) + + const update = Effect.fn("ACP.Session.update")(function* (sessionId: string, fn: (session: Info) => Info) { + const result = yield* Ref.modify(sessions, (state) => { + const session = state.get(sessionId) + if (!session) return [undefined, state] as const + const next = fn(session) + return [snapshot(next), new Map(state).set(sessionId, next)] as const + }) + if (result) return result + return yield* new ACPError.SessionNotFoundError({ sessionId }) + }) + + const remove = Effect.fn("ACP.Session.remove")(function* (sessionId: string) { + return yield* Ref.modify(sessions, (state) => { + const session = state.get(sessionId) + if (!session) return [undefined, state] as const + const next = new Map(state) + next.delete(sessionId) + return [snapshot(session), next] as const + }) + }) + + const setModel: Interface["setModel"] = Effect.fn("ACP.Session.setModel")((sessionId, model) => + update(sessionId, (session) => ({ ...session, model })), + ) + + const setVariant: Interface["setVariant"] = Effect.fn("ACP.Session.setVariant")((sessionId, variant) => + update(sessionId, (session) => ({ ...session, variant })), + ) + + const setMode: Interface["setMode"] = Effect.fn("ACP.Session.setMode")((sessionId, modeId) => + update(sessionId, (session) => ({ ...session, modeId })), + ) + + const recordPartMetadata: Interface["recordPartMetadata"] = Effect.fn("ACP.Session.recordPartMetadata")((input) => { + const metadata = { + messageId: input.messageId, + partId: input.partId, + partType: input.partType, + role: input.role, + ignored: input.ignored, + toolCallId: input.toolCallId, + metadata: input.metadata, + } + return update(input.sessionId, (session) => ({ + ...session, + knownParts: new Map(session.knownParts).set(partMetadataKey(input), metadata), + })).pipe(Effect.as(metadata)) + }) + + return Service.of({ + create: store, + load: store, + list: Effect.fn("ACP.Session.list")(function* (cwd?: string) { + return [...(yield* Ref.get(sessions)).values()] + .filter((session) => !cwd || session.cwd === cwd) + .map(snapshot) + .toSorted((a, b) => b.createdAt.getTime() - a.createdAt.getTime()) + }), + get, + tryGet, + remove, + setModel, + getModel: Effect.fn("ACP.Session.getModel")(function* (sessionId) { + return (yield* get(sessionId)).model + }), + setVariant, + getVariant: Effect.fn("ACP.Session.getVariant")(function* (sessionId) { + return (yield* get(sessionId)).variant + }), + setMode, + getMode: Effect.fn("ACP.Session.getMode")(function* (sessionId) { + return (yield* get(sessionId)).modeId + }), + recordPartMetadata, + getPartMetadata: Effect.fn("ACP.Session.getPartMetadata")(function* (input) { + return (yield* get(input.sessionId)).knownParts.get(partMetadataKey(input)) + }), + tryGetPartMetadata: Effect.fn("ACP.Session.tryGetPartMetadata")(function* (input) { + return (yield* tryGet(input.sessionId))?.knownParts.get(partMetadataKey(input)) + }), + }) + }), +) + +export const defaultLayer = layer + +function makeSession(input: StoreInput): Info { + return { + id: input.id, + cwd: input.cwd, + mcpServers: [...(input.mcpServers ?? [])], + createdAt: input.createdAt ? new Date(input.createdAt) : new Date(), + model: input.model, + variant: input.variant, + modeId: input.modeId, + knownParts: new Map(), } +} - setMode(sessionId: string, modeId: string) { - const session = this.get(sessionId) - session.modeId = modeId - this.sessions.set(sessionId, session) - return session +function snapshot(session: Info): Info { + return { + ...session, + mcpServers: [...session.mcpServers], + createdAt: new Date(session.createdAt), + knownParts: new Map(session.knownParts), } +} - remove(sessionId: string): ACPSessionState | undefined { - const session = this.sessions.get(sessionId) - this.sessions.delete(sessionId) - return session - } +function partMetadataKey(input: { messageId: string; partId: string }) { + return `${input.messageId}:${input.partId}` } + +export * as ACPSession from "./session" diff --git a/packages/opencode/src/acp-next/tool.ts b/packages/opencode/src/acp/tool.ts similarity index 57% rename from packages/opencode/src/acp-next/tool.ts rename to packages/opencode/src/acp/tool.ts index 128c4c9c856e..08cf7ff845e6 100644 --- a/packages/opencode/src/acp-next/tool.ts +++ b/packages/opencode/src/acp/tool.ts @@ -1,4 +1,4 @@ -import type { ToolCallContent, ToolCallLocation, ToolKind } from "@agentclientprotocol/sdk" +import type { ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdate, ToolKind } from "@agentclientprotocol/sdk" export type ToolInput = Record @@ -16,6 +16,19 @@ export type CompletedToolState = { readonly attachments?: ReadonlyArray } +export type RunningToolState = { + readonly status: "running" + readonly input: ToolInput + readonly title?: string +} + +export type ErrorToolState = { + readonly status: "error" + readonly input: ToolInput + readonly error: string + readonly metadata?: unknown +} + export type ImageAttachment = { readonly mimeType: string readonly data: string @@ -61,7 +74,7 @@ export function toLocations(toolName: string, input: ToolInput): ToolCallLocatio case "read": case "edit": case "write": - return locationFrom(input.filePath) + return locationFrom(input.filePath ?? input.filepath) case "grep": case "glob": @@ -100,6 +113,104 @@ export function completedToolContent(toolName: string, state: CompletedToolState return content } +export function pendingToolCall(input: { readonly toolCallId: string; readonly toolName: string }): ToolCall { + return { + toolCallId: input.toolCallId, + title: input.toolName, + kind: toToolKind(input.toolName), + status: "pending", + locations: [], + rawInput: {}, + } +} + +export function runningToolUpdate(input: { + readonly toolCallId: string + readonly toolName: string + readonly state: RunningToolState + readonly output?: string +}): ToolCallUpdate { + const content = input.output + ? [ + { + type: "content" as const, + content: { + type: "text" as const, + text: input.output, + }, + }, + ] + : undefined + + return { + toolCallId: input.toolCallId, + status: "in_progress", + kind: toToolKind(input.toolName), + title: input.state.title ?? input.toolName, + locations: toLocations(input.toolName, input.state.input), + rawInput: input.state.input, + ...(content ? { content } : {}), + } +} + +export function duplicateRunningToolUpdate(input: { + readonly toolCallId: string + readonly toolName: string + readonly state: RunningToolState +}): ToolCallUpdate { + return { + toolCallId: input.toolCallId, + status: "in_progress", + kind: toToolKind(input.toolName), + title: input.state.title ?? input.toolName, + locations: toLocations(input.toolName, input.state.input), + rawInput: input.state.input, + } +} + +export function completedToolUpdate(input: { + readonly toolCallId: string + readonly toolName: string + readonly state: CompletedToolState & { readonly title: string } +}): ToolCallUpdate { + return { + toolCallId: input.toolCallId, + status: "completed", + kind: toToolKind(input.toolName), + title: input.state.title, + content: completedToolContent(input.toolName, input.state), + rawInput: input.state.input, + rawOutput: completedToolRawOutput(input.state), + } +} + +export function errorToolUpdate(input: { + readonly toolCallId: string + readonly toolName: string + readonly state: ErrorToolState +}): ToolCallUpdate { + return { + toolCallId: input.toolCallId, + status: "failed", + kind: toToolKind(input.toolName), + title: input.toolName, + rawInput: input.state.input, + content: [ + { + type: "content", + content: { + type: "text", + text: input.state.error, + }, + }, + ], + rawOutput: { + error: input.state.error, + metadata: input.state.metadata, + }, + } +} + export function completedToolRawOutput(state: CompletedToolState) { return { output: state.output, @@ -138,6 +249,11 @@ export const extractLocations = toLocations export const buildCompletedToolContent = completedToolContent export const buildCompletedRawOutput = completedToolRawOutput export const extractShellOutputSnapshot = shellOutputSnapshot +export const buildPendingToolCall = pendingToolCall +export const buildRunningToolUpdate = runningToolUpdate +export const buildDuplicateRunningToolUpdate = duplicateRunningToolUpdate +export const buildCompletedToolUpdate = completedToolUpdate +export const buildErrorToolUpdate = errorToolUpdate function locationFrom(value: unknown): ToolCallLocation[] { const path = stringValue(value) diff --git a/packages/opencode/src/acp/types.ts b/packages/opencode/src/acp/types.ts deleted file mode 100644 index 2c3e886bc185..000000000000 --- a/packages/opencode/src/acp/types.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { McpServer } from "@agentclientprotocol/sdk" -import type { OpencodeClient } from "@opencode-ai/sdk/v2" -import type { ProviderID, ModelID } from "../provider/schema" - -export interface ACPSessionState { - id: string - cwd: string - mcpServers: McpServer[] - createdAt: Date - model?: { - providerID: ProviderID - modelID: ModelID - } - variant?: string - modeId?: string -} - -export interface ACPConfig { - sdk: OpencodeClient - defaultModel?: { - providerID: ProviderID - modelID: ModelID - } -} diff --git a/packages/opencode/src/acp-next/usage.ts b/packages/opencode/src/acp/usage.ts similarity index 83% rename from packages/opencode/src/acp-next/usage.ts rename to packages/opencode/src/acp/usage.ts index a37f370c6880..a6db606b5928 100644 --- a/packages/opencode/src/acp-next/usage.ts +++ b/packages/opencode/src/acp/usage.ts @@ -1,34 +1,22 @@ import type { AgentSideConnection, Usage } from "@agentclientprotocol/sdk" import * as Log from "@opencode-ai/core/util/log" +import type { AssistantMessage as OpenCodeAssistantMessage, Message } from "@opencode-ai/sdk/v2" import { InstanceRef } from "@/effect/instance-ref" import { InstanceStore } from "@/project/instance-store" -import { ModelID, ProviderID } from "@/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" import { Provider } from "@/provider/provider" import { Context, Effect, Layer, SynchronizedRef } from "effect" -const log = Log.create({ service: "acp-next-usage" }) - -export type AssistantTokenCost = { - readonly cost: number - readonly tokens: { - readonly input: number - readonly output: number - readonly reasoning: number - readonly cache: { - readonly read: number - readonly write: number - } - } -} +const log = Log.create({ service: "acp-usage" }) -export type AssistantMessage = AssistantTokenCost & { - readonly role: "assistant" - readonly providerID?: string - readonly modelID?: string -} +export type AssistantTokenCost = Pick + +export type AssistantMessage = AssistantTokenCost & + Pick & + Partial> export type SessionMessage = { - readonly info: { readonly role: string } | AssistantMessage + readonly info: { readonly role: Message["role"] } | AssistantMessage } export type MessagesInput = { @@ -50,7 +38,7 @@ export interface MessageLoaderInterface { } export interface ContextLimitLoaderInterface { - readonly providers: (directory: string) => Effect.Effect, unknown> + readonly providers: (directory: string) => Effect.Effect, unknown> } export type UsageConnection = Pick @@ -61,8 +49,8 @@ export interface Interface { readonly totalSessionCost: (messages: readonly SessionMessage[]) => number readonly contextLimit: (input: { readonly directory: string - readonly providerID: ProviderID - readonly modelID: ModelID + readonly providerID: ProviderV2.ID + readonly modelID: ProviderV2.ModelID }) => Effect.Effect readonly sendUpdate: (input: { readonly connection: UsageConnection @@ -72,14 +60,14 @@ export interface Interface { } export class MessageLoader extends Context.Service()( - "@opencode/ACPNextUsageMessageLoader", + "@opencode/ACPUsageMessageLoader", ) {} export class ContextLimitLoader extends Context.Service()( - "@opencode/ACPNextUsageContextLimitLoader", + "@opencode/ACPUsageContextLimitLoader", ) {} -export class Service extends Context.Service()("@opencode/ACPNextUsage") {} +export class Service extends Context.Service()("@opencode/ACPUsage") {} export function messageLoaderFromSDK(sdk: SDK): MessageLoaderInterface { return MessageLoader.of({ @@ -122,9 +110,9 @@ export function totalSessionCost(messages: readonly SessionMessage[]): number { } export function findContextLimit( - providers: Record, - providerID: ProviderID, - modelID: ModelID, + providers: Record, + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, ): number | undefined { return providers[providerID]?.models[modelID]?.limit.context } @@ -136,7 +124,7 @@ export const contextLimitLoaderLayer = Layer.effect( const provider = yield* Provider.Service return ContextLimitLoader.of({ - providers: Effect.fn("ACPNextUsageContextLimitLoader.providers")(function* (directory) { + providers: Effect.fn("ACPUsageContextLimitLoader.providers")(function* (directory) { const ctx = yield* store.load({ directory }) return yield* Effect.gen(function* () { return yield* provider.list() @@ -155,8 +143,8 @@ export const layer = Layer.effect( const cachedLimit = Effect.fnUntraced(function* (input: { readonly directory: string - readonly providerID: ProviderID - readonly modelID: ModelID + readonly providerID: ProviderV2.ID + readonly modelID: ProviderV2.ModelID }) { return yield* SynchronizedRef.modifyEffect( limits, @@ -180,15 +168,15 @@ export const layer = Layer.effect( ) }) - const contextLimit = Effect.fn("ACPNextUsage.contextLimit")(function* (input: { + const contextLimit = Effect.fn("ACPUsage.contextLimit")(function* (input: { readonly directory: string - readonly providerID: ProviderID - readonly modelID: ModelID + readonly providerID: ProviderV2.ID + readonly modelID: ProviderV2.ModelID }) { return yield* yield* cachedLimit(input) }) - const sendUpdate = Effect.fn("ACPNextUsage.sendUpdate")(function* (input: { + const sendUpdate = Effect.fn("ACPUsage.sendUpdate")(function* (input: { readonly connection: UsageConnection readonly sessionID: string readonly directory: string @@ -209,8 +197,8 @@ export const layer = Layer.effect( const size = yield* contextLimit({ directory: input.directory, - providerID: ProviderID.make(message.providerID), - modelID: ModelID.make(message.modelID), + providerID: ProviderV2.ID.make(message.providerID), + modelID: ProviderV2.ModelID.make(message.modelID), }) if (!size) return diff --git a/packages/opencode/src/agent/agent.ts b/packages/opencode/src/agent/agent.ts index 064a59f59ed1..9dba3445be05 100644 --- a/packages/opencode/src/agent/agent.ts +++ b/packages/opencode/src/agent/agent.ts @@ -1,7 +1,7 @@ import { Config } from "@/config/config" import { serviceUse } from "@opencode-ai/core/effect/service-use" import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "../provider/schema" + import { generateObject, streamObject, type ModelMessage } from "ai" import { Truncate } from "@/tool/truncate" import { Auth } from "../auth" @@ -25,6 +25,7 @@ import { RuntimeFlags } from "@/effect/runtime-flags" import * as Option from "effect/Option" import * as OtelTracer from "@effect/opentelemetry/Tracer" import { type DeepMutable } from "@opencode-ai/core/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" export const Info = Schema.Struct({ name: Schema.String, @@ -38,8 +39,8 @@ export const Info = Schema.Struct({ permission: Permission.Ruleset, model: Schema.optional( Schema.Struct({ - modelID: ModelID, - providerID: ProviderID, + modelID: ProviderV2.ModelID, + providerID: ProviderV2.ID, }), ), variant: Schema.optional(Schema.String), @@ -62,7 +63,7 @@ export interface Interface { readonly defaultAgent: () => Effect.Effect readonly generate: (input: { description: string - model?: { providerID: ProviderID; modelID: ModelID } + model?: { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID } }) => Effect.Effect< { identifier: string @@ -383,7 +384,7 @@ export const layer = Layer.effect( }), generate: Effect.fn("Agent.generate")(function* (input: { description: string - model?: { providerID: ProviderID; modelID: ModelID } + model?: { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID } }) { const cfg = yield* config.get() const model = input.model ?? (yield* provider.defaultModel()) diff --git a/packages/opencode/src/bus/bus-event.ts b/packages/opencode/src/bus/bus-event.ts deleted file mode 100644 index 5a9e52ef0735..000000000000 --- a/packages/opencode/src/bus/bus-event.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Schema } from "effect" -import { EventV2 } from "@opencode-ai/core/event" - -export type Definition = { - type: Type - properties: Properties -} - -const registry = new Map() - -export function define( - type: Type, - properties: Properties, -): Definition { - const result = { type, properties } - registry.set(type, result) - return result -} - -export function effectPayloads() { - return [ - ...registry - .entries() - .map(([type, def]) => - Schema.Struct({ - id: Schema.String, - type: Schema.Literal(type), - properties: def.properties, - }).annotate({ identifier: `Event.${type}` }), - ) - .toArray(), - ...EventV2.registry - .values() - .map((definition) => - Schema.Struct({ - id: Schema.String, - type: Schema.Literal(definition.type), - properties: definition.data, - }).annotate({ identifier: `Event.${definition.type}` }), - ) - .toArray(), - ] -} - -export * as BusEvent from "./bus-event" diff --git a/packages/opencode/src/bus/index.ts b/packages/opencode/src/bus/index.ts deleted file mode 100644 index 73ec18d73b13..000000000000 --- a/packages/opencode/src/bus/index.ts +++ /dev/null @@ -1,217 +0,0 @@ -import { Effect, Exit, Layer, PubSub, Scope, Context, Stream, Schema } from "effect" -import { EffectBridge } from "@/effect/bridge" -import * as Log from "@opencode-ai/core/util/log" -import { BusEvent } from "./bus-event" -import { GlobalBus } from "./global" -import { InstanceState } from "@/effect/instance-state" -import { makeRuntime } from "@/effect/run-service" -import { serviceUse } from "@opencode-ai/core/effect/service-use" -import { Identifier } from "@/id/id" -import type { InstanceContext } from "@/project/instance-context" -import { InstanceRef } from "@/effect/instance-ref" - -const log = Log.create({ service: "bus" }) - -type BusProperties> = Schema.Schema.Type - -export const InstanceDisposed = BusEvent.define( - "server.instance.disposed", - Schema.Struct({ - directory: Schema.String, - }), -) - -type Payload = { - id: string - type: D["type"] - properties: BusProperties -} - -type State = { - wildcard: PubSub.PubSub - typed: Map> -} - -export interface Interface { - readonly publish: ( - def: D, - properties: BusProperties, - options?: { id?: string }, - ) => Effect.Effect - // subscribe / subscribeAll are eager: the underlying PubSub subscription is - // acquired in the caller's Scope at `yield*` time. Any publish after the - // yield is delivered, even if stream consumption starts later. The previous - // Stream-returning shape acquired the subscription lazily on first pull, - // opening a race window during which publishes were lost — see - // test/bus/bus-effect.test.ts RACE tests. - readonly subscribe: ( - def: D, - ) => Effect.Effect>, never, Scope.Scope> - readonly subscribeAll: () => Effect.Effect, never, Scope.Scope> - readonly subscribeCallback: ( - def: D, - callback: (event: Payload) => unknown, - ) => Effect.Effect<() => void> - readonly subscribeAllCallback: (callback: (event: any) => unknown) => Effect.Effect<() => void> -} - -export class Service extends Context.Service()("@opencode/Bus") {} - -export const use = serviceUse(Service) - -export const layer = Layer.effect( - Service, - Effect.gen(function* () { - const state = yield* InstanceState.make( - Effect.fn("Bus.state")(function* (ctx) { - const wildcard = yield* PubSub.unbounded() - const typed = new Map>() - - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - // Publish InstanceDisposed before shutting down so subscribers see it - yield* PubSub.publish(wildcard, { - type: InstanceDisposed.type, - id: createID(), - properties: { directory: ctx.directory }, - }) - yield* PubSub.shutdown(wildcard) - for (const ps of typed.values()) { - yield* PubSub.shutdown(ps) - } - }), - ) - - return { wildcard, typed } - }), - ) - - function getOrCreate(state: State, def: D) { - return Effect.gen(function* () { - let ps = state.typed.get(def.type) - if (!ps) { - ps = yield* PubSub.unbounded() - state.typed.set(def.type, ps) - } - return ps as unknown as PubSub.PubSub> - }) - } - - function publish(def: D, properties: BusProperties, options?: { id?: string }) { - return Effect.gen(function* () { - const s = yield* InstanceState.get(state) - const payload: Payload = { id: options?.id ?? createID(), type: def.type, properties } - log.info("publishing", { type: def.type }) - - const ps = s.typed.get(def.type) - if (ps) yield* PubSub.publish(ps, payload) - yield* PubSub.publish(s.wildcard, payload) - - const dir = yield* InstanceState.directory - const context = yield* InstanceState.context - const workspace = yield* InstanceState.workspaceID - - GlobalBus.emit("event", { - directory: dir, - project: context.project.id, - workspace, - payload, - }) - }) - } - - const subscribe = ( - def: D, - ): Effect.Effect>, never, Scope.Scope> => - Effect.gen(function* () { - log.info("subscribing", { type: def.type }) - const s = yield* InstanceState.get(state) - const ps = yield* getOrCreate(s, def) - const subscription = yield* PubSub.subscribe(ps) - yield* Effect.addFinalizer(() => Effect.sync(() => log.info("unsubscribing", { type: def.type }))) - return Stream.fromSubscription(subscription) - }) - - const subscribeAll = (): Effect.Effect, never, Scope.Scope> => - Effect.gen(function* () { - log.info("subscribing", { type: "*" }) - const s = yield* InstanceState.get(state) - const subscription = yield* PubSub.subscribe(s.wildcard) - yield* Effect.addFinalizer(() => Effect.sync(() => log.info("unsubscribing", { type: "*" }))) - return Stream.fromSubscription(subscription) - }) - - function on(pubsub: PubSub.PubSub, type: string, callback: (event: T) => unknown) { - return Effect.gen(function* () { - log.info("subscribing", { type }) - const bridge = yield* EffectBridge.make() - const scope = yield* Scope.make() - const subscription = yield* Scope.provide(scope)(PubSub.subscribe(pubsub)) - - yield* Scope.provide(scope)( - Stream.fromSubscription(subscription).pipe( - Stream.runForEach((msg) => - Effect.tryPromise({ - try: () => Promise.resolve().then(() => callback(msg)), - catch: (cause) => { - log.error("subscriber failed", { type, cause }) - }, - }).pipe(Effect.ignore), - ), - Effect.forkScoped, - ), - ) - - return () => { - log.info("unsubscribing", { type }) - bridge.fork(Scope.close(scope, Exit.void)) - } - }) - } - - const subscribeCallback = Effect.fn("Bus.subscribeCallback")(function* ( - def: D, - callback: (event: Payload) => unknown, - ) { - const s = yield* InstanceState.get(state) - const ps = yield* getOrCreate(s, def) - return yield* on(ps, def.type, callback) - }) - - const subscribeAllCallback = Effect.fn("Bus.subscribeAllCallback")(function* (callback: (event: any) => unknown) { - const s = yield* InstanceState.get(state) - return yield* on(s.wildcard, "*", callback) - }) - - return Service.of({ publish, subscribe, subscribeAll, subscribeCallback, subscribeAllCallback }) - }), -) - -export const defaultLayer = layer - -const { runPromise, runSync } = makeRuntime(Service, layer) - -// runSync is safe here because the subscribe chain (InstanceState.get, PubSub.subscribe, -// Scope.make, Effect.forkScoped) is entirely synchronous. If any step becomes async, this will throw. -export function createID() { - return Identifier.create("evt", "ascending") -} - -export async function publish( - ctx: InstanceContext, - def: D, - properties: BusProperties, - options?: { id?: string }, -) { - return runPromise((svc) => svc.publish(def, properties, options).pipe(Effect.provideService(InstanceRef, ctx))) -} - -export function subscribe(def: D, callback: (event: Payload) => unknown) { - return runSync((svc) => svc.subscribeCallback(def, callback)) -} - -export function subscribeAll(callback: (event: any) => unknown) { - return runSync((svc) => svc.subscribeAllCallback(callback)) -} - -export * as Bus from "." diff --git a/packages/opencode/src/cli/cmd/acp.ts b/packages/opencode/src/cli/cmd/acp.ts index b113a278f965..99647e5e2a2a 100644 --- a/packages/opencode/src/cli/cmd/acp.ts +++ b/packages/opencode/src/cli/cmd/acp.ts @@ -3,12 +3,11 @@ import { Effect } from "effect" import { effectCmd } from "../effect-cmd" import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk" import { ACP } from "@/acp/agent" -import { ACPNext } from "@/acp-next/agent" import { Server } from "@/server/server" import { ServerAuth } from "@/server/auth" import { createOpencodeClient } from "@opencode-ai/sdk/v2" import { withNetworkOptions, resolveNetworkOptions } from "../network" -import { RuntimeFlags } from "@/effect/runtime-flags" +import { ACPProfile } from "@/acp/profile" const log = Log.create({ service: "acp-command" }) @@ -23,10 +22,10 @@ export const AcpCommand = effectCmd({ }) }, handler: Effect.fn("Cli.acp")(function* (args) { + ACPProfile.mark("cli.acp.handler") process.env.OPENCODE_CLIENT = "acp" - const flags = yield* RuntimeFlags.Service const opts = yield* resolveNetworkOptions(args) - const server = yield* Effect.promise(() => Server.listen(opts)) + const server = yield* Effect.promise(() => ACPProfile.measure("cli.acp.server.listen", () => Server.listen(opts))) const sdk = createOpencodeClient({ baseUrl: `http://${server.hostname}:${server.port}`, @@ -57,10 +56,11 @@ export const AcpCommand = effectCmd({ }) const stream = ndJsonStream(input, output) - const agent = flags.acpNext ? ACPNext.init({ sdk }) : ACP.init({ sdk }) + const agent = ACP.init({ sdk }) new AgentSideConnection((conn) => { - return agent.create(conn, { sdk }) + ACPProfile.mark("cli.acp.connection.create") + return agent.create(conn) }, stream) log.info("setup connection") diff --git a/packages/opencode/src/cli/cmd/db.ts b/packages/opencode/src/cli/cmd/db.ts index b113455f3b97..9e7e37e18e91 100644 --- a/packages/opencode/src/cli/cmd/db.ts +++ b/packages/opencode/src/cli/cmd/db.ts @@ -1,17 +1,14 @@ import type { Argv } from "yargs" import { spawn } from "child_process" -import { Database } from "@/storage/db" -import { drizzle } from "drizzle-orm/bun-sqlite" -import { Database as BunDatabase } from "bun:sqlite" -import { UI } from "../ui" -import { cmd } from "./cmd" -import { JsonMigration } from "@/storage/json-migration" -import { EOL } from "os" -import { errorMessage } from "../../util/error" +import { Database } from "@opencode-ai/core/database/database" +import { Effect } from "effect" +import { sql } from "drizzle-orm" +import { effectCmd } from "../effect-cmd" -const QueryCommand = cmd({ +const QueryCommand = effectCmd({ command: "$0 [query]", describe: "open an interactive sqlite3 shell or run a query", + instance: false, builder: (yargs: Argv) => { return yargs .positional("query", { @@ -25,96 +22,41 @@ const QueryCommand = cmd({ describe: "Output format", }) }, - handler: async (args: { query?: string; format: string }) => { + handler: Effect.fn("Cli.db.query")(function* (args: { query?: string; format: string }) { const query = args.query as string | undefined if (query) { - const db = new BunDatabase(Database.getPath(), { readonly: true }) - try { - const result = db.query(query).all() as Record[] - if (args.format === "json") { - console.log(JSON.stringify(result, null, 2)) - } else if (result.length > 0) { - const keys = Object.keys(result[0]) - console.log(keys.join("\t")) - for (const row of result) { - console.log(keys.map((k) => row[k]).join("\t")) - } - } - } catch (err) { - UI.error(errorMessage(err)) - process.exit(1) + const { db } = yield* Database.Service + const result = yield* db.all>(sql.raw(query)).pipe(Effect.orDie) + if (args.format === "json") console.log(JSON.stringify(result, null, 2)) + else if (result.length > 0) { + const keys = Object.keys(result[0]) + console.log(keys.join("\t")) + for (const row of result) console.log(keys.map((key) => row[key]).join("\t")) } - db.close() return } - const child = spawn("sqlite3", [Database.getPath()], { + const child = spawn("sqlite3", [Database.path()], { stdio: "inherit", }) - await new Promise((resolve) => child.on("close", resolve)) - }, + yield* Effect.promise(() => new Promise((resolve) => child.on("close", resolve))) + }), }) -const PathCommand = cmd({ +const PathCommand = effectCmd({ command: "path", describe: "print the database path", - handler: () => { - console.log(Database.getPath()) - }, -}) - -const MigrateCommand = cmd({ - command: "migrate", - describe: "migrate JSON data to SQLite (merges with existing data)", - handler: async () => { - const sqlite = new BunDatabase(Database.getPath()) - const tty = process.stderr.isTTY - const width = 36 - const orange = "\x1b[38;5;214m" - const muted = "\x1b[0;2m" - const reset = "\x1b[0m" - let last = -1 - if (tty) process.stderr.write("\x1b[?25l") - try { - const stats = await JsonMigration.run(drizzle({ client: sqlite }), { - progress: (event) => { - const percent = Math.floor((event.current / event.total) * 100) - if (percent === last) return - last = percent - if (tty) { - const fill = Math.round((percent / 100) * width) - const bar = `${"■".repeat(fill)}${"・".repeat(width - fill)}` - process.stderr.write( - `\r${orange}${bar} ${percent.toString().padStart(3)}%${reset} ${muted}${event.current}/${event.total}${reset} `, - ) - } else { - process.stderr.write(`sqlite-migration:${percent}${EOL}`) - } - }, - }) - if (tty) process.stderr.write("\n") - if (tty) process.stderr.write("\x1b[?25h") - else process.stderr.write(`sqlite-migration:done${EOL}`) - UI.println( - `Migration complete: ${stats.projects} projects, ${stats.sessions} sessions, ${stats.messages} messages`, - ) - if (stats.errors.length > 0) { - UI.println(`${stats.errors.length} errors occurred during migration`) - } - } catch (err) { - if (tty) process.stderr.write("\x1b[?25h") - UI.error(`Migration failed: ${errorMessage(err)}`) - process.exit(1) - } finally { - sqlite.close() - } - }, + instance: false, + handler: Effect.fn("Cli.db.path")(function* () { + console.log(Database.path()) + }), }) -export const DbCommand = cmd({ +export const DbCommand = effectCmd({ command: "db", describe: "database tools", + instance: false, builder: (yargs: Argv) => { - return yargs.command(QueryCommand).command(PathCommand).command(MigrateCommand).demandCommand() + return yargs.command(QueryCommand).command(PathCommand).demandCommand() }, - handler: () => {}, + handler: Effect.fn("Cli.db")(function* () {}), }) diff --git a/packages/opencode/src/cli/cmd/debug/agent.ts b/packages/opencode/src/cli/cmd/debug/agent.ts index c74c1c907943..0c310474e53e 100644 --- a/packages/opencode/src/cli/cmd/debug/agent.ts +++ b/packages/opencode/src/cli/cmd/debug/agent.ts @@ -1,4 +1,5 @@ import { EOL } from "os" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { basename } from "path" import { Cause, Effect } from "effect" import { Agent } from "../../../agent/agent" @@ -163,7 +164,7 @@ const createToolContext = Effect.fn("Cli.debug.agent.createToolContext")(functio ) }) const now = Date.now() - const message: MessageV2.Assistant = { + const message: SessionLegacy.Assistant = { id: messageID, sessionID: session.id, role: "assistant", diff --git a/packages/opencode/src/cli/cmd/debug/scrap.ts b/packages/opencode/src/cli/cmd/debug/scrap.ts index 2a127e5dbdd1..124dfd135633 100644 --- a/packages/opencode/src/cli/cmd/debug/scrap.ts +++ b/packages/opencode/src/cli/cmd/debug/scrap.ts @@ -1,15 +1,18 @@ import { EOL } from "os" import { Project } from "@/project/project" import * as Log from "@opencode-ai/core/util/log" +import { makeRuntime } from "@opencode-ai/core/effect/runtime" import { cmd } from "../cmd" +const runtime = makeRuntime(Project.Service, Project.defaultLayer) + export const ScrapCommand = cmd({ command: "scrap", describe: "list all known projects", builder: (yargs) => yargs, async handler() { const timer = Log.Default.time("scrap") - const list = await Project.list() + const list = await runtime.runPromise((project) => project.list()) process.stdout.write(JSON.stringify(list, null, 2) + EOL) timer.stop() }, diff --git a/packages/opencode/src/cli/cmd/debug/v2.ts b/packages/opencode/src/cli/cmd/debug/v2.ts index 56866a0e0244..aab7018982e5 100644 --- a/packages/opencode/src/cli/cmd/debug/v2.ts +++ b/packages/opencode/src/cli/cmd/debug/v2.ts @@ -3,6 +3,7 @@ import { Effect, Option } from "effect" import { Catalog } from "@opencode-ai/core/catalog" import { LocationServiceMap } from "@opencode-ai/core/location-layer" import { PluginBoot } from "@opencode-ai/core/plugin/boot" +import { AbsolutePath } from "@opencode-ai/core/schema" import { effectCmd } from "../../effect-cmd" export const V2Command = effectCmd({ @@ -37,7 +38,7 @@ export const V2Command = effectCmd({ Effect.withSpan("Cli.debug.v2"), Effect.provide( LocationServiceMap.get({ - directory: process.cwd(), + directory: AbsolutePath.make(process.cwd()), }), ), Effect.provide(LocationServiceMap.layer), diff --git a/packages/opencode/src/cli/cmd/export.ts b/packages/opencode/src/cli/cmd/export.ts index 9eb1faffea7f..e6bff506ca65 100644 --- a/packages/opencode/src/cli/cmd/export.ts +++ b/packages/opencode/src/cli/cmd/export.ts @@ -1,4 +1,5 @@ import { Session } from "@/session/session" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { MessageV2 } from "../../session/message-v2" import { SessionID } from "../../session/schema" import { effectCmd, fail } from "../effect-cmd" @@ -31,7 +32,7 @@ function diff(kind: string, diffs: { file?: string; patch?: string }[] | undefin })) } -function source(part: MessageV2.FilePart) { +function source(part: SessionLegacy.FilePart) { if (!part.source) return part.source if (part.source.type === "symbol") { return { @@ -56,7 +57,7 @@ function source(part: MessageV2.FilePart) { } } -function filepart(part: MessageV2.FilePart): MessageV2.FilePart { +function filepart(part: SessionLegacy.FilePart): SessionLegacy.FilePart { return { ...part, url: redact("file-url", part.id, part.url), @@ -65,7 +66,7 @@ function filepart(part: MessageV2.FilePart): MessageV2.FilePart { } } -function part(part: MessageV2.Part): MessageV2.Part { +function part(part: SessionLegacy.Part): SessionLegacy.Part { switch (part.type) { case "text": return { @@ -159,7 +160,7 @@ function part(part: MessageV2.Part): MessageV2.Part { const partFn = part -function sanitize(data: { info: Session.Info; messages: MessageV2.WithParts[] }) { +function sanitize(data: { info: Session.Info; messages: SessionLegacy.WithParts[] }) { return { info: { ...data.info, diff --git a/packages/opencode/src/cli/cmd/github.ts b/packages/opencode/src/cli/cmd/github.ts index 9ac605f46fe9..e12604c3a2e2 100644 --- a/packages/opencode/src/cli/cmd/github.ts +++ b/packages/opencode/src/cli/cmd/github.ts @@ -1,4 +1,5 @@ import path from "path" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { exec } from "child_process" import { Filesystem } from "@/util/filesystem" import * as prompts from "@clack/prompts" @@ -26,8 +27,9 @@ import { Session } from "@/session/session" import type { SessionID } from "../../session/schema" import { MessageID, PartID } from "../../session/schema" import { Provider } from "@/provider/provider" -import { Bus } from "../../bus" import { MessageV2 } from "../../session/message-v2" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" import { SessionPrompt } from "@/session/prompt" import { Git } from "@/git" import { setTimeout as sleep } from "node:timers/promises" @@ -159,7 +161,7 @@ export { parseGitHubRemote } * Returns null for non-text responses (signals summary needed). * Throws only for truly empty responses. */ -export function extractResponseText(parts: MessageV2.Part[]): string | null { +export function extractResponseText(parts: SessionLegacy.Part[]): string | null { const textPart = parts.findLast((p) => p.type === "text") if (textPart) return textPart.text @@ -435,7 +437,7 @@ export const GithubRunCommand = effectCmd({ const sessionSvc = yield* Session.Service const sessionShare = yield* SessionShare.Service const sessionPrompt = yield* SessionPrompt.Service - const busSvc = yield* Bus.Service + const events = yield* EventV2Bridge.Service const runLocalEffect = (effect: Effect.Effect) => Effect.runPromise(effect.pipe(Effect.provideService(InstanceRef, ctx))) yield* Effect.promise(async () => { @@ -897,10 +899,12 @@ export const GithubRunCommand = effectCmd({ let text = "" await runLocalEffect( - busSvc.subscribeCallback(MessageV2.Event.PartUpdated, (evt) => { - if (evt.properties.part.sessionID !== session.id) return + events.listen((evt) => { + if (evt.type !== MessageV2.Event.PartUpdated.type) return Effect.void + const data = evt.data as EventV2.Data + if (data.part.sessionID !== session.id) return Effect.void //if (evt.properties.part.messageID === messageID) return - const part = evt.properties.part + const part = data.part if (part.type === "tool" && part.state.status === "completed") { const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD] @@ -920,9 +924,10 @@ export const GithubRunCommand = effectCmd({ UI.println(UI.markdown(text)) UI.empty() text = "" - return + return Effect.void } } + return Effect.void }), ) } diff --git a/packages/opencode/src/cli/cmd/import.ts b/packages/opencode/src/cli/cmd/import.ts index 569aa309a461..7cad05baec01 100644 --- a/packages/opencode/src/cli/cmd/import.ts +++ b/packages/opencode/src/cli/cmd/import.ts @@ -1,9 +1,10 @@ import type { Session as SDKSession, Message, Part } from "@opencode-ai/sdk/v2" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Session } from "@/session/session" import { MessageV2 } from "../../session/message-v2" import { CliError, effectCmd } from "../effect-cmd" -import { Database } from "@/storage/db" -import { SessionTable, MessageTable, PartTable } from "../../session/session.sql" +import { Database } from "@opencode-ai/core/database/database" +import { SessionTable, MessageTable, PartTable } from "@opencode-ai/core/session/sql" import { InstanceRef } from "@/effect/instance-ref" import { ShareNext } from "@/share/share-next" import { EOL } from "os" @@ -12,8 +13,8 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Effect, Schema } from "effect" import type { InstanceContext } from "@/project/instance-context" -const decodeMessageInfo = Schema.decodeUnknownSync(MessageV2.Info) -const decodePart = Schema.decodeUnknownSync(MessageV2.Part) +const decodeMessageInfo = Schema.decodeUnknownSync(SessionLegacy.Info) +const decodePart = Schema.decodeUnknownSync(SessionLegacy.Part) /** Discriminated union returned by the ShareNext API (GET /api/shares/:id/data) */ export type ShareData = @@ -98,6 +99,7 @@ export const ImportCommand = effectCmd({ const runImport = Effect.fn("Cli.import.body")(function* (file: string, ctx: InstanceContext) { const share = yield* ShareNext.Service const fs = yield* AppFileSystem.Service + const { db } = yield* Database.Service let exportData: ExportData | undefined @@ -175,48 +177,45 @@ const runImport = Effect.fn("Cli.import.body")(function* (file: string, ctx: Ins path: path.relative(path.resolve(ctx.worktree), ctx.directory).replaceAll("\\", "/"), }) as Session.Info const row = Session.toRow(info) - Database.use((db) => - db - .insert(SessionTable) - .values(row) - .onConflictDoUpdate({ - target: SessionTable.id, - set: { project_id: row.project_id, directory: row.directory, path: row.path }, - }) - .run(), - ) + yield* db + .insert(SessionTable) + .values(row) + .onConflictDoUpdate({ + target: SessionTable.id, + set: { project_id: row.project_id, directory: row.directory, path: row.path }, + }) + .run() + .pipe(Effect.orDie) for (const msg of exportData.messages) { - const msgInfo = decodeMessageInfo(msg.info) as MessageV2.Info + const msgInfo = decodeMessageInfo(msg.info) as SessionLegacy.Info const { id, sessionID: _, ...msgData } = msgInfo - Database.use((db) => - db - .insert(MessageTable) + yield* db + .insert(MessageTable) + .values({ + id, + session_id: row.id, + time_created: msgInfo.time?.created ?? Date.now(), + data: msgData as never, + }) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie) + + for (const part of msg.parts) { + const partInfo = decodePart(part) as SessionLegacy.Part + const { id: partId, sessionID: _s, messageID, ...partData } = partInfo + yield* db + .insert(PartTable) .values({ - id, + id: partId, + message_id: messageID, session_id: row.id, - time_created: msgInfo.time?.created ?? Date.now(), - data: msgData, + data: partData, }) .onConflictDoNothing() - .run(), - ) - - for (const part of msg.parts) { - const partInfo = decodePart(part) as MessageV2.Part - const { id: partId, sessionID: _s, messageID, ...partData } = partInfo - Database.use((db) => - db - .insert(PartTable) - .values({ - id: partId, - message_id: messageID, - session_id: row.id, - data: partData, - }) - .onConflictDoNothing() - .run(), - ) + .run() + .pipe(Effect.orDie) } } diff --git a/packages/opencode/src/cli/cmd/mcp.ts b/packages/opencode/src/cli/cmd/mcp.ts index f7ea030aa96a..75e41b3c8a07 100644 --- a/packages/opencode/src/cli/cmd/mcp.ts +++ b/packages/opencode/src/cli/cmd/mcp.ts @@ -17,7 +17,8 @@ import path from "path" import { Global } from "@opencode-ai/core/global" import { modify, applyEdits } from "jsonc-parser" import { Filesystem } from "@/util/filesystem" -import { Bus } from "../../bus" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" import { Effect } from "effect" function getAuthStatusIcon(status: MCP.AuthStatus): string { @@ -256,13 +257,17 @@ export const McpAuthCommand = effectCmd({ spinner.start("Starting OAuth flow...") // Subscribe to browser open failure events to show URL for manual opening - const unsubscribe = Bus.subscribe(MCP.BrowserOpenFailed, (evt) => { - if (evt.properties.mcpName === serverName) { + const events = yield* EventV2Bridge.Service + const unsubscribe = yield* events.listen((event) => { + if (event.type !== MCP.BrowserOpenFailed.type) return Effect.void + const data = event.data as EventV2.Data + if (data.mcpName === serverName) { spinner.stop("Could not open browser automatically") prompts.log.warn("Please open this URL in your browser to authenticate:") - prompts.log.info(evt.properties.url) + prompts.log.info(data.url) spinner.start("Waiting for authorization...") } + return Effect.void }) yield* MCP.Service.use((mcp) => mcp.authenticate(serverName)).pipe( @@ -300,7 +305,7 @@ export const McpAuthCommand = effectCmd({ prompts.log.error(error instanceof Error ? error.message : String(error)) }), ), - Effect.ensuring(Effect.sync(() => unsubscribe())), + Effect.ensuring(unsubscribe), ) prompts.outro("Done") diff --git a/packages/opencode/src/cli/cmd/models.ts b/packages/opencode/src/cli/cmd/models.ts index 909b0b40babc..3349d3c5eb1d 100644 --- a/packages/opencode/src/cli/cmd/models.ts +++ b/packages/opencode/src/cli/cmd/models.ts @@ -1,10 +1,11 @@ import { EOL } from "os" import { Effect } from "effect" import { Provider } from "@/provider/provider" -import { ProviderID } from "../../provider/schema" + import { ModelsDev } from "@opencode-ai/core/models-dev" import { effectCmd, fail } from "../effect-cmd" import { UI } from "../ui" +import { ProviderV2 } from "@opencode-ai/core/provider" export const ModelsCommand = effectCmd({ command: "models [provider]", @@ -33,7 +34,7 @@ export const ModelsCommand = effectCmd({ const provider = yield* Provider.Service const providers = yield* provider.list() - const print = (providerID: ProviderID, verbose?: boolean) => { + const print = (providerID: ProviderV2.ID, verbose?: boolean) => { const p = providers[providerID] const sorted = Object.entries(p.models).sort(([a], [b]) => a.localeCompare(b)) for (const [modelID, model] of sorted) { @@ -47,7 +48,7 @@ export const ModelsCommand = effectCmd({ } if (args.provider) { - const providerID = ProviderID.make(args.provider) + const providerID = ProviderV2.ID.make(args.provider) if (!providers[providerID]) return yield* fail(`Provider not found: ${args.provider}`) print(providerID, args.verbose) return @@ -61,6 +62,6 @@ export const ModelsCommand = effectCmd({ return a.localeCompare(b) }) - for (const providerID of ids) print(ProviderID.make(providerID), args.verbose) + for (const providerID of ids) print(ProviderV2.ID.make(providerID), args.verbose) }), }) diff --git a/packages/opencode/src/cli/cmd/prompt-display.ts b/packages/opencode/src/cli/cmd/prompt-display.ts index 4e8cb9046ac6..4c22942ea897 100644 --- a/packages/opencode/src/cli/cmd/prompt-display.ts +++ b/packages/opencode/src/cli/cmd/prompt-display.ts @@ -1,6 +1,6 @@ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" }) -function promptOffsetWidth(value: string) { +export function promptOffsetWidth(value: string) { let width = 0 for (const part of graphemes.segment(value)) { // Textarea offsets count newlines as one position; Bun.stringWidth counts them as zero. diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index b80a2389ef24..cdbf4562d535 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -221,7 +221,7 @@ export const RunCommand = effectCmd({ .option("replay", { type: "boolean", default: false, - describe: "replay visible session history on interactive resume", + describe: "replay interactive session history on resume and after resize", }) .option("replay-limit", { type: "number", diff --git a/packages/opencode/src/cli/cmd/run/footer.command.tsx b/packages/opencode/src/cli/cmd/run/footer.command.tsx index cf6822c06613..90ba6fc6734c 100644 --- a/packages/opencode/src/cli/cmd/run/footer.command.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.command.tsx @@ -4,9 +4,8 @@ import { useKeyboard, type JSX } from "@opentui/solid" import fuzzysort from "fuzzysort" import { createEffect, createMemo, createSignal, type Accessor } from "solid-js" import { RunFooterMenu, createFooterMenuState, type RunFooterMenuItem } from "./footer.menu" -import { formatBindings } from "./keymap.shared" import type { RunFooterTheme } from "./theme" -import type { FooterKeybinds, FooterSubagentTab, RunCommand, RunInput, RunProvider } from "./types" +import type { FooterQueuedPrompt, FooterSubagentTab, RunCommand, RunInput, RunProvider } from "./types" type PanelEntry = RunFooterMenuItem & { category: string @@ -15,6 +14,7 @@ type PanelEntry = RunFooterMenuItem & { type CommandEntry = | (PanelEntry & { action: "model" }) + | (PanelEntry & { action: "queued" }) | (PanelEntry & { action: "subagent" }) | (PanelEntry & { action: "variant.cycle" }) | (PanelEntry & { action: "variant.list" }) @@ -38,6 +38,10 @@ type SubagentEntry = PanelEntry & { current: boolean } +type QueuedEntry = PanelEntry & { + prompt: FooterQueuedPrompt +} + type MenuState = ReturnType const PANEL_PAD = 2 @@ -295,11 +299,13 @@ export function RunCommandMenuBody(props: { theme: Accessor commands: Accessor subagents: Accessor + queued: Accessor variants: Accessor - keybinds: FooterKeybinds + variantCycle: string onClose: () => void onModel: () => void onSubagent: () => void + onQueued: () => void onVariant: () => void onVariantCycle: () => void onCommand: (name: string) => void @@ -316,6 +322,20 @@ export function RunCommandMenuBody(props: { category: "Suggested", display: "Switch model", }, + ...(props.queued().length > 0 + ? [ + { + action: "queued" as const, + category: "Suggested", + display: "Manage queued prompts", + footer: `${props.queued().length} queued`, + keywords: props + .queued() + .map((item) => item.prompt.text) + .join(" "), + }, + ] + : []), ...(props.subagents().length > 0 ? [ { @@ -334,7 +354,7 @@ export function RunCommandMenuBody(props: { action: "variant.cycle", category: "Suggested", display: "Variant cycle", - footer: formatBindings(props.keybinds.variantCycle, props.keybinds.leader), + footer: props.variantCycle, keywords: "variant cycle", }, ...(props.variants().length > 0 @@ -388,6 +408,11 @@ export function RunCommandMenuBody(props: { return } + if (item.action === "queued") { + props.onQueued() + return + } + if (item.action === "variant.cycle") { props.onVariantCycle() return @@ -560,6 +585,102 @@ export function RunSubagentSelectBody(props: { ) } +export function RunQueuedPromptSelectBody(props: { + theme: Accessor + prompts: Accessor + onClose: () => void + onEdit: (prompt: FooterQueuedPrompt) => void | Promise + onDelete: (prompt: FooterQueuedPrompt) => void | Promise + onRows?: (rows: number) => void +}) { + let field: InputRenderable | undefined + const [query, setQuery] = createSignal("") + const entries = createMemo(() => + props.prompts().map((prompt) => ({ + category: "", + display: prompt.prompt.text.replaceAll("\n", " "), + footer: "queued · ctrl+e edit · ctrl+d remove", + keywords: prompt.prompt.text, + prompt, + })), + ) + const items = createMemo(() => match(query(), entries())) + const menu = createFooterMenuState({ count: () => items().length, limit: SUBAGENT_LIST_ROWS }) + const selected = () => items()[menu.selected()] + + createEffect(() => { + query() + menu.reset() + }) + + createEffect(() => { + props.onRows?.(menu.rows() + PANEL_FRAME_ROWS) + }) + + useKeyboard((event) => { + if (event.defaultPrevented) { + return + } + + const item = selected() + const ctrl = event.ctrl && !event.meta && !event.shift && !event.super + if (item && (event.name === "delete" || (ctrl && event.name === "d"))) { + event.preventDefault() + props.onDelete(item.prompt) + return + } + + if (item && ctrl && event.name === "e") { + event.preventDefault() + props.onEdit(item.prompt) + return + } + + handleKey({ + event, + menu, + field: () => field, + setQuery, + select: () => { + const item = selected() + if (item) props.onEdit(item.prompt) + }, + close: props.onClose, + }) + }) + + return ( + { + field = input + }} + onQuery={setQuery} + > + + + ) +} + export function RunVariantSelectBody(props: { theme: Accessor variants: Accessor diff --git a/packages/opencode/src/cli/cmd/run/footer.permission.tsx b/packages/opencode/src/cli/cmd/run/footer.permission.tsx index b38c2da9d1c9..2790a9e0b66c 100644 --- a/packages/opencode/src/cli/cmd/run/footer.permission.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.permission.tsx @@ -64,7 +64,8 @@ function buttons( ) } -function RejectField(props: { +/** @internal Exported to test managed textarea submission without permission navigation. */ +export function RejectField(props: { theme: RunFooterTheme text: string disabled: boolean @@ -107,6 +108,7 @@ function RejectField(props: { focusedBackgroundColor={props.theme.surface} cursorColor={props.theme.text} focused={!props.disabled} + onSubmit={props.onConfirm} onContentChange={() => { if (!area || area.isDestroyed) { return @@ -119,11 +121,6 @@ function RejectField(props: { props.onCancel() return } - - if (event.name === "return" && !event.meta && !event.ctrl && !event.shift) { - event.preventDefault() - props.onConfirm() - } }} ref={(item) => { area = item diff --git a/packages/opencode/src/cli/cmd/run/footer.prompt.tsx b/packages/opencode/src/cli/cmd/run/footer.prompt.tsx index c3f9918acc35..7f4a9ca5b294 100644 --- a/packages/opencode/src/cli/cmd/run/footer.prompt.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.prompt.tsx @@ -1,13 +1,13 @@ // Prompt textarea component and its state machine for direct interactive mode. // -// createPromptState() wires keybinds, history navigation, leader-key sequences, -// and `@` autocomplete for files, subagents, and MCP resources. +// createPromptState() wires keymap command layers, history navigation, and +// `@` autocomplete for files, subagents, and MCP resources. // It produces a PromptState that RunPromptBody renders as an OpenTUI textarea, // while the footer view renders the current menu state below it. /** @jsxImportSource @opentui/solid */ import { pathToFileURL } from "bun" -import { StyledText, bg, fg, type KeyBinding, type KeyEvent, type TextareaRenderable } from "@opentui/core" -import { useKeyboard, useRenderer } from "@opentui/solid" +import { StyledText, bg, fg, type KeyEvent, type TextareaRenderable } from "@opentui/core" +import { useRenderer } from "@opentui/solid" import fuzzysort from "fuzzysort" import path from "path" import { createEffect, createMemo, createResource, createSignal, onCleanup, onMount, type Accessor } from "solid-js" @@ -20,15 +20,12 @@ import { mentionTriggerIndex, isNewCommand, movePromptHistory, - promptCycle, - promptHit, - promptInfo, - promptKeys, pushPromptHistory, } from "./prompt.shared" +import { OPENCODE_BASE_MODE, useBindings } from "@/cli/cmd/tui/keymap" import { FOOTER_MENU_ROWS, createFooterMenuState, type RunFooterMenuItem } from "./footer.menu" import type { RunFooterTheme } from "./theme" -import type { FooterKeybinds, FooterState, RunAgent, RunCommand, RunPrompt, RunPromptPart, RunResource } from "./types" +import type { FooterState, RunAgent, RunCommand, RunPrompt, RunPromptPart, RunResource, RunTuiConfig } from "./types" const AUTOCOMPLETE_ROWS = FOOTER_MENU_ROWS const AUTOCOMPLETE_BOTTOM_ROWS = 1 @@ -66,10 +63,9 @@ type PromptInput = { directory: string findFiles: (query: string) => Promise agents: Accessor - subagents: Accessor resources: Accessor commands: Accessor - keybinds: FooterKeybinds + tuiConfig: RunTuiConfig state: Accessor view: Accessor prompt: Accessor @@ -82,14 +78,12 @@ type PromptInput = { onInputClear: () => void onExitRequest?: () => boolean onExit: () => void - onSubagentMenu?: () => void onRows: (rows: number) => void onStatus: (text: string) => void } export type PromptState = { placeholder: Accessor - bindings: Accessor shell: Accessor visible: Accessor options: Accessor @@ -102,6 +96,7 @@ export type PromptState = { onKeyDown: (event: KeyEvent) => void onContentChange: () => void replaceDraft: (text: string) => void + replacePrompt: (prompt: RunPrompt) => void bind: (area?: TextareaRenderable) => void } @@ -199,7 +194,6 @@ export function hintFlags(width: number) { export function RunPromptBody(props: { theme: () => RunFooterTheme placeholder: () => StyledText | string - bindings: () => KeyBinding[] onSubmit: () => void onKeyDown: (event: KeyEvent) => void onContentChange: () => void @@ -263,7 +257,6 @@ export function RunPromptBody(props: { backgroundColor={props.theme().surface} focusedBackgroundColor={props.theme().surface} cursorColor={props.theme().text} - keyBindings={props.bindings()} onSubmit={props.onSubmit} onKeyDown={props.onKeyDown} onPaste={() => { @@ -280,8 +273,6 @@ export function RunPromptBody(props: { } export function createPromptState(input: PromptInput): PromptState { - const keys = createMemo(() => promptKeys(input.keybinds)) - const bindings = createMemo(() => keys().bindings) const [shell, setShell] = createSignal(false) const placeholder = createMemo(() => { if (shell()) { @@ -301,8 +292,6 @@ export function createPromptState(input: PromptInput): PromptState { let draft: RunPrompt = { text: "", parts: [] } let stash: RunPrompt = { text: "", parts: [] } let area: TextareaRenderable | undefined - let leader = false - let timeout: NodeJS.Timeout | undefined let tick = false let prev = input.view() let type = 0 @@ -461,24 +450,6 @@ export function createPromptState(input: PromptInput): PromptState { return visible() ? menu.rows() - 1 + AUTOCOMPLETE_BOTTOM_ROWS : 0 }) - const clear = () => { - leader = false - if (!timeout) { - return - } - - clearTimeout(timeout) - timeout = undefined - } - - const arm = () => { - clear() - leader = true - timeout = setTimeout(() => { - clear() - }, input.keybinds.leaderTimeout) - } - const hide = () => { setMode(false) setQuery("") @@ -742,7 +713,7 @@ export function createPromptState(input: PromptInput): PromptState { const move = (dir: -1 | 1, event: KeyEvent) => { if (!area || area.isDestroyed) { - return + return false } if (history.index === null && dir === -1) { @@ -751,7 +722,7 @@ export function createPromptState(input: PromptInput): PromptState { const next = movePromptHistory(history, dir, area.plainText, area.cursorOffset) if (!next.apply || next.text === undefined || next.cursor === undefined) { - return + return false } history = next.state @@ -759,28 +730,27 @@ export function createPromptState(input: PromptInput): PromptState { next.state.index === null ? stash : (next.state.items[next.state.index] ?? { text: next.text, parts: [] }) restore(value, next.cursor) event.preventDefault() + return true } - const cycle = (event: KeyEvent): boolean => { - const next = promptCycle(leader, promptInfo(event), keys().leaders, keys().cycles) - if (!next.consume) { - return false - } + const historyCommand = (dir: -1 | 1, event: KeyEvent) => { + if (move(dir, event)) return + if (!area || area.isDestroyed) return false - if (next.clear) { - clear() - } - - if (next.arm) { - arm() + const endOffset = Bun.stringWidth(area.plainText) + if (dir === -1 && area.visualCursor.visualRow === 0) { + area.cursorOffset = 0 } - if (next.cycle) { - input.onCycle() + const end = + typeof area.height === "number" && Number.isFinite(area.height) && area.height > 0 + ? area.height - 1 + : Math.max(0, (area.virtualLineCount ?? 1) - 1) + if (dir === 1 && area.visualCursor.visualRow === end) { + area.cursorOffset = endOffset } - event.preventDefault() - return true + return false } const requestExit = () => { @@ -820,12 +790,20 @@ export function createPromptState(input: PromptInput): PromptState { } if (next.kind === "slash") { - const text = `/${next.name} ` const cursor = area.cursorOffset + const head = slashHead(area.plainText) + const local = !shell() && (next.name === "new" || next.name === "exit") + const separator = !shell() && !local && head && /\s/.test(area.plainText[head.end] ?? "") ? "" : " " + const text = `/${next.name}${separator}` area.cursorOffset = 0 const start = area.logicalCursor - area.cursorOffset = cursor + area.cursorOffset = + shell() || !head + ? cursor + : local + ? Bun.stringWidth(area.plainText) + : Bun.stringWidth(area.plainText.slice(0, head.end)) const end = area.logicalCursor area.deleteRange(start.row, start.col, end.row, end.col) @@ -833,6 +811,11 @@ export function createPromptState(input: PromptInput): PromptState { area.cursorOffset = Bun.stringWidth(text) hide() syncDraft() + if (!shell()) { + submitPrompt(clonePrompt(draft)) + return + } + scheduleRows() area.focus() return @@ -912,178 +895,180 @@ export function createPromptState(input: PromptInput): PromptState { refresh() } - const onKeyDown = (event: KeyEvent) => { - const key = promptInfo(event) - if (visible()) { - const name = event.name.toLowerCase() - const ctrl = event.ctrl && !event.meta && !event.shift - if (name === "up" || (ctrl && name === "p")) { - event.preventDefault() - if (options().length > 0) { - menu.move(-1) - } - return - } - - if (name === "down" || (ctrl && name === "n")) { - event.preventDefault() - if (options().length > 0) { - menu.move(1) - } - return - } - - if (name === "escape") { - event.preventDefault() - cancelAutocomplete() - return - } - - if (name === "return") { - if (mode() === "slash" && options().length === 0) { - hide() - return - } - - event.preventDefault() - select() - return - } - - if (name === "tab") { - if (mode() === "slash" && options().length === 0) { - hide() - return - } - - event.preventDefault() - const item = options()[menu.selected()] - if (item?.kind === "mention" && item.directory) { - expand() - return - } - - select() - return - } - } - - if ( - key.name === "!" && - !shell() && - !event.ctrl && - !event.meta && - !event.super && - area && - !area.isDestroyed && - area.cursorOffset === 0 - ) { - event.preventDefault() - setShellMode(true) - return - } - - if (shell() && !visible()) { - if (key.name === "escape") { - event.preventDefault() - setShellMode(false) - return - } - - if (key.name === "backspace" && area && !area.isDestroyed && area.cursorOffset === 0) { - event.preventDefault() - setShellMode(false) - return - } - } - - if ( - key.name === "down" && - !visible() && - !event.ctrl && - !event.meta && - !event.shift && - !event.super && - area && - !area.isDestroyed && - area.plainText.length === 0 && - input.subagents() > 0 - ) { - event.preventDefault() - input.onSubagentMenu?.() - return - } - - if (promptHit(keys().clear, key)) { - const handled = requestExit() - if (handled) { - event.preventDefault() - } - return - } - - if (promptHit(keys().interrupts, key)) { - if (input.onInterrupt()) { - event.preventDefault() - return - } - } - - if (cycle(event)) { - return - } - - const up = promptHit(keys().previous, key) - const down = promptHit(keys().next, key) - if (!up && !down) { - return - } - - if (!area || area.isDestroyed) { - return - } - - const dir = up ? -1 : 1 - const endOffset = Bun.stringWidth(area.plainText) - if ((dir === -1 && area.cursorOffset === 0) || (dir === 1 && area.cursorOffset === endOffset)) { - move(dir, event) - return - } - - if (dir === -1 && area.visualCursor.visualRow === 0) { - area.cursorOffset = 0 - } - - const end = - typeof area.height === "number" && Number.isFinite(area.height) && area.height > 0 - ? area.height - 1 - : Math.max(0, (area.virtualLineCount ?? 1) - 1) - if (dir === 1 && area.visualCursor.visualRow === end) { - area.cursorOffset = endOffset - } + const baseBindingsEnabled = () => { + const current = input.view() + if (current === "command") return false + if (current === "model") return false + if (current === "variant") return false + if (current === "queued-menu") return false + if (current === "subagent-menu") return false + return true } - useKeyboard((event) => { - if (input.prompt()) { - return - } - - if ( - input.view() === "command" || - input.view() === "model" || - input.view() === "variant" || - input.view() === "subagent-menu" - ) { - return - } - - if (promptHit(keys().clear, promptInfo(event))) { - const handled = requestExit() - if (handled) { - event.preventDefault() - } - } - }) + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: baseBindingsEnabled(), + commands: [ + { + name: "prompt.clear", + title: "Clear prompt or exit", + category: "Prompt", + run() { + if (requestExit()) return + return false + }, + }, + ], + bindings: input.tuiConfig.keybinds.get("prompt.clear"), + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: input.prompt(), + commands: [ + { + name: "session.interrupt", + title: "Interrupt session", + category: "Session", + run() { + if (input.onInterrupt()) return + return false + }, + }, + ], + bindings: input.tuiConfig.keybinds.get("session.interrupt"), + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: input.prompt() && !visible(), + commands: [ + { + name: "prompt.history.previous", + title: "Previous prompt history", + category: "Prompt", + run(ctx: { event: KeyEvent }) { + return historyCommand(-1, ctx.event) + }, + }, + { + name: "prompt.history.next", + title: "Next prompt history", + category: "Prompt", + run(ctx: { event: KeyEvent }) { + return historyCommand(1, ctx.event) + }, + }, + ], + bindings: [ + ...input.tuiConfig.keybinds.get("prompt.history.previous"), + ...input.tuiConfig.keybinds.get("prompt.history.next"), + ], + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: input.prompt() && !visible(), + bindings: [ + { + key: "!", + desc: "Shell mode", + group: "Prompt", + cmd() { + if (shell()) return false + if (!area || area.isDestroyed) return false + if (area.cursorOffset !== 0) return false + setShellMode(true) + }, + }, + ], + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: input.prompt() && shell() && !visible(), + bindings: [ + { + key: "escape", + desc: "Exit shell mode", + group: "Prompt", + cmd: () => setShellMode(false), + }, + { + key: "backspace", + desc: "Exit shell mode", + group: "Prompt", + cmd() { + if (!area || area.isDestroyed) return false + if (area.cursorOffset !== 0) return false + setShellMode(false) + }, + }, + ], + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: input.prompt() && visible(), + commands: [ + { + name: "prompt.autocomplete.prev", + title: "Previous autocomplete item", + category: "Autocomplete", + run: () => menu.move(-1), + }, + { + name: "prompt.autocomplete.next", + title: "Next autocomplete item", + category: "Autocomplete", + run: () => menu.move(1), + }, + { + name: "prompt.autocomplete.hide", + title: "Hide autocomplete", + category: "Autocomplete", + run: cancelAutocomplete, + }, + { + name: "prompt.autocomplete.select", + title: "Select autocomplete item", + category: "Autocomplete", + run() { + if (mode() === "slash" && options().length === 0) { + hide() + return + } + select() + }, + }, + { + name: "prompt.autocomplete.complete", + title: "Complete autocomplete item", + category: "Autocomplete", + run() { + if (mode() === "slash" && options().length === 0) { + hide() + return + } + const item = options()[menu.selected()] + if (item?.kind === "mention" && item.directory) { + expand() + return + } + select() + }, + }, + ], + bindings: input.tuiConfig.keybinds.gather("run.prompt.autocomplete", [ + "prompt.autocomplete.prev", + "prompt.autocomplete.next", + "prompt.autocomplete.hide", + "prompt.autocomplete.select", + "prompt.autocomplete.complete", + ]), + })) + + const onKeyDown = (_event: KeyEvent) => {} const submitPrompt = (next: RunPrompt) => { if (!area || area.isDestroyed) { @@ -1144,7 +1129,6 @@ export function createPromptState(input: PromptInput): PromptState { } onCleanup(() => { - clear() if (area && !area.isDestroyed) { area.off("line-info-change", scheduleRows) } @@ -1188,7 +1172,6 @@ export function createPromptState(input: PromptInput): PromptState { syncDraft() } - clear() hide() prev = kind if (kind !== "prompt") { @@ -1202,7 +1185,6 @@ export function createPromptState(input: PromptInput): PromptState { return { placeholder, - bindings, shell, visible, options, @@ -1219,6 +1201,7 @@ export function createPromptState(input: PromptInput): PromptState { scheduleRows() }, replaceDraft, + replacePrompt: restore, bind, } } diff --git a/packages/opencode/src/cli/cmd/run/footer.question.tsx b/packages/opencode/src/cli/cmd/run/footer.question.tsx index 5bea73a919c5..d0f36246a564 100644 --- a/packages/opencode/src/cli/cmd/run/footer.question.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.question.tsx @@ -177,10 +177,6 @@ export function RunQuestionBody(props: { return } - if (event.name === "return" && !event.shift && !event.ctrl && !event.meta) { - saveCustom() - event.preventDefault() - } return } @@ -496,6 +492,7 @@ export function RunQuestionBody(props: { focusedBackgroundColor={props.theme.surface} cursorColor={props.theme.text} focused={!disabled()} + onSubmit={saveCustom} onContentChange={() => { if (!area || area.isDestroyed || disabled()) { return diff --git a/packages/opencode/src/cli/cmd/run/footer.ts b/packages/opencode/src/cli/cmd/run/footer.ts index c94c664cc0fd..90ca009e3ecf 100644 --- a/packages/opencode/src/cli/cmd/run/footer.ts +++ b/packages/opencode/src/cli/cmd/run/footer.ts @@ -24,24 +24,25 @@ // Ctrl-c clears a live prompt draft first; otherwise interrupt and exit use a // two-press pattern where the first press shows a hint and the second press // within 5 seconds actually fires the action. -import { CliRenderEvents, type CliRenderer, type TreeSitterClient } from "@opentui/core" +import { CliRenderEvents, type CliRenderer, type KeyEvent, type Renderable, type TreeSitterClient } from "@opentui/core" +import type { Keymap } from "@opentui/keymap" import { render } from "@opentui/solid" import { createComponent, createSignal, type Accessor, type Setter } from "solid-js" import { createStore, reconcile } from "solid-js/store" +import { OpencodeKeymapProvider, formatKeyBindings } from "@/cli/cmd/tui/keymap" import { withRunSpan } from "./otel" import { RUN_COMMAND_PANEL_ROWS, RUN_SUBAGENT_PANEL_ROWS } from "./footer.command" import { SUBAGENT_INSPECTOR_ROWS } from "./footer.subagent" import { PROMPT_MAX_ROWS, TEXTAREA_MIN_ROWS } from "./footer.prompt" -import { printableBinding } from "./prompt.shared" import { RunFooterView } from "./footer.view" import { RunScrollbackStream } from "./scrollback.surface" import type { RunTheme } from "./theme" import type { FooterApi, FooterEvent, - FooterKeybinds, FooterPatch, FooterPromptRoute, + FooterQueuedPrompt, FooterState, FooterSubagentState, FooterView, @@ -55,6 +56,7 @@ import type { RunPrompt, RunProvider, RunResource, + RunTuiConfig, StreamCommit, } from "./types" @@ -80,7 +82,8 @@ type RunFooterOptions = { first: boolean history?: RunPrompt[] theme: RunTheme - keybinds: FooterKeybinds + keymap: Keymap + tuiConfig: RunTuiConfig diffStyle: RunDiffStyle onPermissionReply: (input: PermissionReply) => void | Promise onQuestionReply: (input: QuestionReply) => void | Promise @@ -162,11 +165,13 @@ export class RunFooter implements FooterApi { private closed = false private destroyed = false private prompts = new Set<(input: RunPrompt) => void>() + private queuedRemoves = new Set<(messageID: string) => boolean | Promise>() private closes = new Set<() => void>() // Microtask-coalesced commit queue. Flushed on next microtask or on close/destroy. private queue: StreamCommit[] = [] private pending = false private flushing: Promise = Promise.resolve() + private flushError: unknown // Fixed portion of footer height above the textarea. private base: number private rows = TEXTAREA_MIN_ROWS @@ -190,15 +195,25 @@ export class RunFooter implements FooterApi { private setView: Setter private subagent: Accessor private setSubagent: (next: FooterSubagentState) => void + private queuedPrompts: Accessor + private setQueuedPrompts: Setter private promptRoute: FooterPromptRoute = { type: "composer" } private subagentMenuRows = SUBAGENT_ROWS private autocomplete = false private interruptTimeout: NodeJS.Timeout | undefined private exitTimeout: NodeJS.Timeout | undefined - private interruptHint: string private requestExitHandler: (() => boolean) | undefined private scrollback: RunScrollbackStream + private createScrollback(wrote: boolean): RunScrollbackStream { + return new RunScrollbackStream(this.renderer, this.options.theme, { + diffStyle: this.options.diffStyle, + wrote, + sessionID: this.options.sessionID, + treeSitterClient: this.options.treeSitterClient, + }) + } + constructor( private renderer: CliRenderer, private options: RunFooterOptions, @@ -248,53 +263,58 @@ export class RunFooter implements FooterApi { setSubagent("permissions", reconcile(next.permissions, { key: "id" })) setSubagent("questions", reconcile(next.questions, { key: "id" })) } + const [queuedPrompts, setQueuedPrompts] = createSignal([]) + this.queuedPrompts = queuedPrompts + this.setQueuedPrompts = setQueuedPrompts this.base = Math.max(1, renderer.footerHeight - TEXTAREA_MIN_ROWS) - this.interruptHint = printableBinding(options.keybinds.interrupt, options.keybinds.leader) || "esc" - this.scrollback = new RunScrollbackStream(renderer, options.theme, { - diffStyle: options.diffStyle, - wrote: options.wrote, - sessionID: options.sessionID, - treeSitterClient: options.treeSitterClient, - }) + this.scrollback = this.createScrollback(options.wrote ?? false) this.renderer.on(CliRenderEvents.DESTROY, this.handleDestroy) + const footer = this void render( () => - createComponent(RunFooterView, { - directory: options.directory, - state: this.state, - view: this.view, - subagent: this.subagent, - findFiles: options.findFiles, - agents: this.agents, - resources: this.resources, - commands: this.commands, - providers: this.providers, - currentModel: this.currentModel, - variants: this.variants, - currentVariant: this.currentVariant, - theme: options.theme, - diffStyle: options.diffStyle, - keybinds: options.keybinds, - history: options.history, - agent: options.agentLabel, - onSubmit: this.handlePrompt, - onPermissionReply: this.handlePermissionReply, - onQuestionReply: this.handleQuestionReply, - onQuestionReject: this.handleQuestionReject, - onCycle: this.handleCycle, - onInterrupt: this.handleInterrupt, - onInputClear: this.handleInputClear, - onExitRequest: this.handleExit, - onRequestExit: this.setRequestExitHandler, - onExit: () => this.close(), - onModelSelect: this.handleModelSelect, - onVariantSelect: this.handleVariantSelect, - onRows: this.syncRows, - onLayout: this.syncLayout, - onStatus: this.setStatus, - onSubagentSelect: options.onSubagentSelect, + createComponent(OpencodeKeymapProvider, { + keymap: options.keymap, + get children() { + return createComponent(RunFooterView, { + directory: options.directory, + state: footer.state, + view: footer.view, + subagent: footer.subagent, + queuedPrompts: footer.queuedPrompts, + findFiles: options.findFiles, + agents: footer.agents, + resources: footer.resources, + commands: footer.commands, + providers: footer.providers, + currentModel: footer.currentModel, + variants: footer.variants, + currentVariant: footer.currentVariant, + theme: options.theme, + diffStyle: options.diffStyle, + tuiConfig: options.tuiConfig, + history: options.history, + agent: options.agentLabel, + onSubmit: footer.handlePrompt, + onPermissionReply: footer.handlePermissionReply, + onQuestionReply: footer.handleQuestionReply, + onQuestionReject: footer.handleQuestionReject, + onCycle: footer.handleCycle, + onInterrupt: footer.handleInterrupt, + onInputClear: footer.handleInputClear, + onExitRequest: footer.handleExit, + onRequestExit: footer.setRequestExitHandler, + onExit: () => footer.close(), + onModelSelect: footer.handleModelSelect, + onVariantSelect: footer.handleVariantSelect, + onRows: footer.syncRows, + onLayout: footer.syncLayout, + onStatus: footer.setStatus, + onSubagentSelect: options.onSubagentSelect, + onQueuedRemove: footer.handleQueuedRemove, + }) + }, }), this.renderer, ).catch(() => { @@ -319,6 +339,13 @@ export class RunFooter implements FooterApi { } } + public onQueuedRemove(fn: (messageID: string) => boolean | Promise): () => void { + this.queuedRemoves.add(fn) + return () => { + this.queuedRemoves.delete(fn) + } + } + public onClose(fn: () => void): () => void { if (this.isClosed) { fn() @@ -364,6 +391,15 @@ export class RunFooter implements FooterApi { return } + if (next.type === "queued.prompts") { + if (this.isGone) { + return + } + + this.setQueuedPrompts(next.prompts) + return + } + const patch = eventPatch(next) if (patch) { this.patch(patch) @@ -434,7 +470,9 @@ export class RunFooter implements FooterApi { }, ), ) - .catch(() => {}) + .catch((error) => { + this.flushError = error + }) } private present(view: FooterView): void { @@ -492,6 +530,12 @@ export class RunFooter implements FooterApi { } return this.flushing.then(async () => { + if (this.flushError !== undefined) { + const error = this.flushError + this.flushError = undefined + throw error + } + if (this.isGone) { return } @@ -504,6 +548,15 @@ export class RunFooter implements FooterApi { }) } + public resetForReplay(wrote: boolean): void { + if (this.isGone) { + return + } + + this.scrollback.destroy() + this.scrollback = this.createScrollback(wrote) + } + public close(): void { if (this.closed) { return @@ -540,6 +593,11 @@ export class RunFooter implements FooterApi { this.requestExitHandler = fn } + private handleQueuedRemove = async (messageID: string): Promise => { + const fn = [...this.queuedRemoves][0] + return fn ? await fn(messageID) : false + } + private handleInputClear = (): void => { this.clearInterruptTimer() this.clearExitTimer() @@ -567,11 +625,13 @@ export class RunFooter implements FooterApi { ? 1 + MODEL_ROWS : this.promptRoute.type === "variant" ? 1 + VARIANT_ROWS - : this.promptRoute.type === "subagent-menu" + : this.promptRoute.type === "queued-menu" ? 1 + this.subagentMenuRows - : this.promptRoute.type === "subagent" - ? this.base + SUBAGENT_INSPECTOR_ROWS - : Math.max(base + TEXTAREA_MIN_ROWS, Math.min(base + PROMPT_MAX_ROWS, base + this.rows)) + : this.promptRoute.type === "subagent-menu" + ? 1 + this.subagentMenuRows + : this.promptRoute.type === "subagent" + ? this.base + SUBAGENT_INSPECTOR_ROWS + : Math.max(base + TEXTAREA_MIN_ROWS, Math.min(base + PROMPT_MAX_ROWS, base + this.rows)) if (height !== this.renderer.footerHeight) { this.renderer.footerHeight = height @@ -781,6 +841,13 @@ export class RunFooter implements FooterApi { }, 5000) } + private interruptHint(): string { + const bindings = this.options.keymap + .getCommandBindings({ visibility: "registered", commands: ["session.interrupt"] }) + .get("session.interrupt") + return formatKeyBindings(bindings, this.options.tuiConfig) || "esc" + } + private clearExitTimer(): void { if (!this.exitTimeout) { return @@ -815,7 +882,7 @@ export class RunFooter implements FooterApi { if (next < 2) { this.armInterruptTimer() - this.patch({ status: `${this.interruptHint} again to interrupt` }) + this.patch({ status: `${this.interruptHint()} again to interrupt` }) return true } @@ -859,6 +926,7 @@ export class RunFooter implements FooterApi { this.clearExitTimer() this.renderer.off(CliRenderEvents.DESTROY, this.handleDestroy) this.prompts.clear() + this.queuedRemoves.clear() this.closes.clear() this.scrollback.destroy() } @@ -890,6 +958,8 @@ export class RunFooter implements FooterApi { }, ), ) - .catch(() => {}) + .catch((error) => { + this.flushError = error + }) } } diff --git a/packages/opencode/src/cli/cmd/run/footer.view.tsx b/packages/opencode/src/cli/cmd/run/footer.view.tsx index affc664b155f..816f6c992644 100644 --- a/packages/opencode/src/cli/cmd/run/footer.view.tsx +++ b/packages/opencode/src/cli/cmd/run/footer.view.tsx @@ -10,7 +10,7 @@ // All state comes from the parent RunFooter through SolidJS signals. // The view itself is stateless except for derived memos. /** @jsxImportSource @opentui/solid */ -import { useKeyboard, useTerminalDimensions } from "@opentui/solid" +import { useTerminalDimensions } from "@opentui/solid" import { Match, Show, Switch, createEffect, createMemo, createSignal, onCleanup } from "solid-js" import "opentui-spinner/solid" import { createColors, createFrames } from "../tui/ui/spinner" @@ -18,6 +18,7 @@ import { RUN_SUBAGENT_PANEL_ROWS, RunCommandMenuBody, RunModelSelectBody, + RunQueuedPromptSelectBody, RunSubagentSelectBody, RunVariantSelectBody, } from "./footer.command" @@ -26,10 +27,16 @@ import { RunFooterSubagentBody } from "./footer.subagent" import { RunPromptBody, createPromptState, hintFlags } from "./footer.prompt" import { RunPermissionBody } from "./footer.permission" import { RunQuestionBody } from "./footer.question" -import { printableBinding, promptBindings, promptHit, promptInfo } from "./prompt.shared" +import { + OPENCODE_BASE_MODE, + formatKeyBindings, + useBindings, + useKeymapSelector, + type OpenTuiKeymap, +} from "@/cli/cmd/tui/keymap" import type { - FooterKeybinds, FooterPromptRoute, + FooterQueuedPrompt, FooterState, FooterSubagentState, FooterView, @@ -43,6 +50,7 @@ import type { RunPrompt, RunProvider, RunResource, + RunTuiConfig, } from "./types" import { RUN_THEME_FALLBACK, type RunTheme } from "./theme" @@ -73,9 +81,10 @@ type RunFooterViewProps = { state: () => FooterState view?: () => FooterView subagent?: () => FooterSubagentState + queuedPrompts?: () => FooterQueuedPrompt[] theme?: RunTheme diffStyle?: RunDiffStyle - keybinds: FooterKeybinds + tuiConfig: RunTuiConfig history?: RunPrompt[] agent: string onSubmit: (input: RunPrompt) => boolean @@ -94,6 +103,7 @@ type RunFooterViewProps = { onLayout: (input: { route: FooterPromptRoute; autocomplete: boolean; subagentRows: number }) => void onStatus: (text: string) => void onSubagentSelect?: (sessionID: string | undefined) => void + onQueuedRemove: (messageID: string) => Promise } export { TEXTAREA_MIN_ROWS, TEXTAREA_MAX_ROWS } from "./footer.prompt" @@ -113,13 +123,15 @@ export function RunFooterView(props: RunFooterViewProps) { }) const [route, setRoute] = createSignal({ type: "composer" }) const [subagentMenuRows, setSubagentMenuRows] = createSignal(RUN_SUBAGENT_PANEL_ROWS) + const queuedPrompts = createMemo(() => props.queuedPrompts?.() ?? []) const prompt = createMemo(() => active().type === "prompt" && route().type === "composer") const selectingSubagent = createMemo(() => active().type === "prompt" && route().type === "subagent-menu") + const selectingQueued = createMemo(() => active().type === "prompt" && route().type === "queued-menu") const inspecting = createMemo(() => active().type === "prompt" && route().type === "subagent") const commanding = createMemo(() => active().type === "prompt" && route().type === "command") const modeling = createMemo(() => active().type === "prompt" && route().type === "model") const varianting = createMemo(() => active().type === "prompt" && route().type === "variant") - const panel = createMemo(() => selectingSubagent() || commanding() || modeling() || varianting()) + const panel = createMemo(() => selectingQueued() || selectingSubagent() || commanding() || modeling() || varianting()) const selected = createMemo(() => { const current = route() return current.type === "subagent" ? current.sessionID : undefined @@ -145,18 +157,64 @@ export function RunFooterView(props: RunFooterViewProps) { label: count === 1 ? "agent" : "agents", } }) + const queuedIndicator = createMemo(() => { + const count = queuedPrompts().length + if (count === 0) return + return { count, label: count === 1 ? "prompt" : "prompts" } + }) const detail = createMemo(() => { const current = route() return current.type === "subagent" ? subagent().details[current.sessionID] : undefined }) - const command = createMemo(() => printableBinding(props.keybinds.commandList, props.keybinds.leader)) - const interrupt = createMemo(() => printableBinding(props.keybinds.interrupt, props.keybinds.leader)) - const commandKeys = createMemo(() => promptBindings(props.keybinds.commandList, props.keybinds.leader)) + const command = useKeymapSelector( + (keymap: OpenTuiKeymap) => + formatKeyBindings( + keymap + .getCommandBindings({ visibility: "registered", commands: ["command.palette.show"] }) + .get("command.palette.show"), + props.tuiConfig, + ) ?? "", + ) + const interrupt = useKeymapSelector( + (keymap: OpenTuiKeymap) => + formatKeyBindings( + keymap + .getCommandBindings({ visibility: "registered", commands: ["session.interrupt"] }) + .get("session.interrupt"), + props.tuiConfig, + ) ?? "", + ) + const variantCycle = useKeymapSelector( + (keymap: OpenTuiKeymap) => + formatKeyBindings( + keymap.getCommandBindings({ visibility: "registered", commands: ["variant.cycle"] }).get("variant.cycle"), + props.tuiConfig, + ) ?? "", + ) + const queuedShortcut = useKeymapSelector( + (keymap: OpenTuiKeymap) => + formatKeyBindings( + keymap + .getCommandBindings({ visibility: "registered", commands: ["session.queued_prompts"] }) + .get("session.queued_prompts"), + props.tuiConfig, + ) ?? "", + ) + const subagentShortcut = useKeymapSelector( + (keymap: OpenTuiKeymap) => + formatKeyBindings( + keymap + .getCommandBindings({ visibility: "registered", commands: ["session.child.first"] }) + .get("session.child.first"), + props.tuiConfig, + ) ?? "", + ) const hints = createMemo(() => hintFlags(term().width)) const busy = createMemo(() => props.state().phase === "running") const armed = createMemo(() => props.state().interrupt > 0) const exiting = createMemo(() => props.state().exit > 0) const queue = createMemo(() => props.state().queue) + const additionalQueue = createMemo(() => Math.max(0, queue() - queuedPrompts().length)) const duration = createMemo(() => props.state().duration) const usage = createMemo(() => props.state().usage) const interruptKey = createMemo(() => interrupt() || "/exit") @@ -220,6 +278,12 @@ export function RunFooterView(props: RunFooterViewProps) { props.onSubagentSelect?.(undefined) } + const openQueuedMenu = () => { + if (queuedPrompts().length === 0) return + setRoute({ type: "queued-menu" }) + props.onSubagentSelect?.(undefined) + } + const closePanel = () => { setRoute({ type: "composer" }) } @@ -254,10 +318,9 @@ export function RunFooterView(props: RunFooterViewProps) { directory: props.directory, findFiles: props.findFiles, agents: props.agents, - subagents: () => tabs().length, resources: props.resources, commands: props.commands, - keybinds: props.keybinds, + tuiConfig: props.tuiConfig, state: props.state, view: promptView, prompt, @@ -270,7 +333,6 @@ export function RunFooterView(props: RunFooterViewProps) { onInputClear: props.onInputClear, onExitRequest: props.onExitRequest, onExit: props.onExit, - onSubagentMenu: openSubagentMenu, onRows: props.onRows, onStatus: props.onStatus, }) @@ -285,30 +347,56 @@ export function RunFooterView(props: RunFooterViewProps) { props.onRequestExit?.(undefined) }) - useKeyboard((event) => { - if (event.defaultPrevented) { - return - } - - if (active().type !== "prompt") { - return - } - - if (route().type !== "composer") { - return - } - - if (composer.visible()) { - return - } - - if (!promptHit(commandKeys(), promptInfo(event))) { - return - } - - event.preventDefault() - openCommand() - }) + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: active().type === "prompt" && route().type === "composer" && !composer.visible(), + commands: [ + { + name: "command.palette.show", + title: "Open command palette", + category: "Prompt", + run: openCommand, + }, + { + name: "variant.cycle", + title: "Cycle model variant", + category: "Model", + run: props.onCycle, + }, + ], + bindings: [ + ...props.tuiConfig.keybinds.get("command.palette.show"), + ...props.tuiConfig.keybinds.get("variant.cycle"), + ], + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: active().type === "prompt" && route().type === "composer" && tabs().length > 0, + commands: [ + { + name: "session.child.first", + title: "View subagents", + category: "Session", + run: openSubagentMenu, + }, + ], + bindings: props.tuiConfig.keybinds.get("session.child.first"), + })) + + useBindings(() => ({ + mode: OPENCODE_BASE_MODE, + enabled: active().type === "prompt" && route().type === "composer" && queuedPrompts().length > 0, + commands: [ + { + name: "session.queued_prompts", + title: "Manage queued prompts", + category: "Session", + run: openQueuedMenu, + }, + ], + bindings: props.tuiConfig.keybinds.get("session.queued_prompts"), + })) createEffect(() => { const current = route() @@ -335,6 +423,11 @@ export function RunFooterView(props: RunFooterViewProps) { closePanel() }) + createEffect(() => { + if (route().type !== "queued-menu" || queuedPrompts().length > 0) return + closePanel() + }) + createEffect(() => { if (active().type === "prompt") { return @@ -345,6 +438,7 @@ export function RunFooterView(props: RunFooterViewProps) { current.type !== "command" && current.type !== "model" && current.type !== "variant" && + current.type !== "queued-menu" && current.type !== "subagent-menu" ) { return @@ -407,7 +501,6 @@ export function RunFooterView(props: RunFooterViewProps) { + + void props.onQueuedRemove(item.messageID)} + onEdit={async (item) => { + if (!(await props.onQueuedRemove(item.messageID))) return + closePanel() + queueMicrotask(() => composer.replacePrompt(item.prompt)) + }} + onRows={setSubagentMenuRows} + /> + { props.onCycle() @@ -590,7 +699,9 @@ export function RunFooterView(props: RunFooterViewProps) { gap={1} flexShrink={0} > - 0 || subagentIndicator()}> + 0 || queuedIndicator() || subagentIndicator()} + > @@ -640,11 +751,24 @@ export function RunFooterView(props: RunFooterViewProps) { {info().count} {info().label} · - + {subagentShortcut() || "leader+down"} to view )} + + {(info) => ( + + 0 || subagentIndicator()}> + · + + {info().count} queued {info().label} + · + {queuedShortcut() || "leader+q"} + to edit/remove + + )} + @@ -661,9 +785,9 @@ export function RunFooterView(props: RunFooterViewProps) { when={shell()} fallback={ <> - 0}> + 0}> - {queue()} queued + {additionalQueue()} queued 0}> diff --git a/packages/opencode/src/cli/cmd/run/keymap.shared.ts b/packages/opencode/src/cli/cmd/run/keymap.shared.ts deleted file mode 100644 index 8adc77e730e6..000000000000 --- a/packages/opencode/src/cli/cmd/run/keymap.shared.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { KeyEvent } from "@opentui/core" -import { Keymap, type Binding, type KeySequencePart } from "@opentui/keymap" -import { registerDefaultKeys, registerLeader } from "@opentui/keymap/addons" -import { formatCommandBindings, formatKeySequence } from "@opentui/keymap/extras" - -type ParsedBindingInput = Pick - -export type ParsedBinding = { - sequence: KeySequencePart[] - event: "press" | "release" -} - -const keyNameAliases = { - delete: "del", - enter: "return", - escape: "esc", - pagedown: "pgdn", - pageup: "pgup", -} as const - -const modifierAliases = { - meta: "alt", -} as const - -function hostPlatform() { - if (process.platform === "darwin") { - return "macos" as const - } - - if (process.platform === "win32") { - return "windows" as const - } - - if (process.platform === "linux") { - return "linux" as const - } - - return "unknown" as const -} - -function createCommandEvent() { - return new KeyEvent({ - name: "command", - ctrl: false, - meta: false, - shift: false, - option: false, - sequence: "", - number: false, - raw: "", - eventType: "press", - source: "raw", - }) -} - -function createParser(leader: string) { - const platform = hostPlatform() - const keymap = new Keymap({ - metadata: { - platform, - primaryModifier: platform === "macos" ? "super" : platform === "unknown" ? "unknown" : "ctrl", - modifiers: { - ctrl: "supported", - shift: "supported", - meta: "supported", - super: "unknown", - hyper: "unknown", - }, - }, - rootTarget: {}, - isDestroyed: false, - getFocusedTarget() { - return null - }, - getParentTarget(_target) { - return null - }, - isTargetDestroyed(_target) { - return false - }, - onKeyPress(_listener) { - return () => {} - }, - onKeyRelease(_listener) { - return () => {} - }, - onFocusChange(_listener) { - return () => {} - }, - onTargetDestroy(_target, _listener) { - return () => {} - }, - createCommandEvent, - }) - - const offDefault = registerDefaultKeys(keymap) - const offLeader = registerLeader(keymap, { trigger: leader }) - - return { - keymap, - dispose() { - offLeader() - offDefault() - }, - } -} - -function formatOptions(leader: string) { - return { - tokenDisplay: { - leader, - }, - keyNameAliases, - modifierAliases, - } as const -} - -function splitBinding(binding: ParsedBindingInput) { - if (typeof binding.key !== "string" || !binding.key.includes(",")) { - return [binding] - } - - return binding.key - .split(",") - .map((key) => key.trim()) - .filter(Boolean) - .map((key) => ({ - ...binding, - key, - })) -} - -export function parseBindings(bindings: readonly ParsedBindingInput[], leader: string): ParsedBinding[] { - const parser = createParser(leader) - - try { - return bindings.flatMap((binding) => - splitBinding(binding).map((item) => ({ - sequence: Array.from(parser.keymap.parseKeySequence(item.key)), - event: item.event ?? "press", - })), - ) - } finally { - parser.dispose() - } -} - -export function formatBinding(bindings: readonly ParsedBindingInput[], leader: string) { - return formatKeySequence(parseBindings(bindings, leader)[0]?.sequence, formatOptions(leader)) -} - -export function formatBindings(bindings: readonly ParsedBindingInput[], leader: string) { - return formatCommandBindings(parseBindings(bindings, leader), formatOptions(leader)) -} diff --git a/packages/opencode/src/cli/cmd/run/prompt.shared.ts b/packages/opencode/src/cli/cmd/run/prompt.shared.ts index 2dda26bae10f..5f9570fd98b8 100644 --- a/packages/opencode/src/cli/cmd/run/prompt.shared.ts +++ b/packages/opencode/src/cli/cmd/run/prompt.shared.ts @@ -1,20 +1,14 @@ // Pure state machine for the prompt input. // -// Handles keybind parsing, history ring navigation, and the leader-key -// sequence for variant cycling. All functions are pure -- they take state -// in and return new state out, with no side effects. +// Handles history ring navigation and prompt text helpers. All functions are +// pure -- they take state in and return new state out, with no side effects. // // The history ring (PromptHistoryState) stores past prompts and tracks // the current browse position. When the user arrows up at cursor offset 0, // the current draft is saved and history begins. Arrowing past the end // restores the draft. -// -// The leader-key cycle (promptCycle) uses a two-step pattern: first press -// arms the leader, second press within the timeout fires the action. -import type { KeyBinding } from "@opentui/core" export { displayCharAt, displaySlice, mentionTriggerIndex } from "../prompt-display" -import { formatBinding, parseBindings } from "./keymap.shared" -import type { FooterKeybinds, RunPrompt } from "./types" +import type { RunPrompt } from "./types" const HISTORY_LIMIT = 200 @@ -24,36 +18,6 @@ export type PromptHistoryState = { draft: string } -export function promptInfo(event: { name: string; ctrl?: boolean; meta?: boolean; shift?: boolean; super?: boolean }) { - return { - name: event.name === " " ? "space" : event.name, - ctrl: !!event.ctrl, - meta: !!event.meta, - shift: !!event.shift, - super: !!event.super, - leader: false, - } -} - -type PromptInfo = ReturnType - -export type PromptKeys = { - leaders: PromptInfo[] - cycles: PromptInfo[] - interrupts: PromptInfo[] - previous: PromptInfo[] - next: PromptInfo[] - clear: PromptInfo[] - bindings: KeyBinding[] -} - -export type PromptCycle = { - arm: boolean - clear: boolean - cycle: boolean - consume: boolean -} - export type PromptMove = { state: PromptHistoryState text?: string @@ -73,98 +37,6 @@ export function promptSame(a: RunPrompt, b: RunPrompt): boolean { return a.mode === b.mode && a.text === b.text && JSON.stringify(a.parts) === JSON.stringify(b.parts) } -function promptKey(binding: ReturnType[number]): PromptInfo | undefined { - if (binding.event !== "press") { - return undefined - } - - const first = binding.sequence[0] - const second = binding.sequence[1] - - if (!first) { - return undefined - } - - if (!second) { - return first.patternName || first.tokenName - ? undefined - : { - name: first.stroke.name, - ctrl: first.stroke.ctrl, - meta: first.stroke.meta, - shift: first.stroke.shift, - super: first.stroke.super, - leader: false, - } - } - - if (binding.sequence.length !== 2 || first.tokenName !== "leader" || second.patternName || second.tokenName) { - return undefined - } - - return { - name: second.stroke.name, - ctrl: second.stroke.ctrl, - meta: second.stroke.meta, - shift: second.stroke.shift, - super: second.stroke.super, - leader: true, - } -} - -export function promptBindings(bindings: FooterKeybinds["commandList"], leader: string): PromptInfo[] { - return parseBindings(bindings, leader).flatMap((binding) => { - const key = promptKey(binding) - return key ? [key] : [] - }) -} - -function mapInputBindings( - bindings: FooterKeybinds["inputSubmit"], - leader: string, - action: "submit" | "newline", -): KeyBinding[] { - return promptBindings(bindings, leader).flatMap((key) => { - if (key.leader) { - return [] - } - - return [ - { - name: key.name, - ctrl: key.ctrl || undefined, - meta: key.meta || undefined, - shift: key.shift || undefined, - super: key.super || undefined, - action, - }, - ] - }) -} - -function textareaBindings(keybinds: FooterKeybinds): KeyBinding[] { - return [ - ...mapInputBindings(keybinds.inputSubmit, keybinds.leader, "submit"), - ...mapInputBindings(keybinds.inputNewline, keybinds.leader, "newline"), - ] -} - -export function promptKeys(keybinds: FooterKeybinds): PromptKeys { - return { - leaders: promptBindings([{ key: keybinds.leader }], keybinds.leader), - cycles: promptBindings(keybinds.variantCycle, keybinds.leader), - interrupts: promptBindings(keybinds.interrupt, keybinds.leader), - previous: promptBindings(keybinds.historyPrevious, keybinds.leader), - next: promptBindings(keybinds.historyNext, keybinds.leader), - clear: promptBindings(keybinds.inputClear, keybinds.leader), - bindings: textareaBindings(keybinds), - } -} - -export function printableBinding(bindings: FooterKeybinds["commandList"], leader: string): string { - return formatBinding(bindings, leader) -} - export function isExitCommand(input: string): boolean { const text = input.trim().toLowerCase() return text === "/exit" || text === "/quit" || text === ":q" @@ -174,59 +46,6 @@ export function isNewCommand(input: string): boolean { return input.trim().toLowerCase() === "/new" } -export function promptHit(bindings: PromptInfo[], event: PromptInfo): boolean { - return bindings.some( - (item) => - item.name === event.name && - item.ctrl === event.ctrl && - item.meta === event.meta && - item.shift === event.shift && - item.super === event.super && - item.leader === event.leader, - ) -} - -export function promptCycle( - armed: boolean, - event: PromptInfo, - leaders: PromptInfo[], - cycles: PromptInfo[], -): PromptCycle { - if (!armed && promptHit(leaders, event)) { - return { - arm: true, - clear: false, - cycle: false, - consume: true, - } - } - - if (armed) { - return { - arm: false, - clear: true, - cycle: promptHit(cycles, { ...event, leader: true }), - consume: true, - } - } - - if (!promptHit(cycles, event)) { - return { - arm: false, - clear: false, - cycle: false, - consume: false, - } - } - - return { - arm: false, - clear: false, - cycle: true, - consume: true, - } -} - export function createPromptHistory(items?: RunPrompt[]): PromptHistoryState { const list = (items ?? []).filter((item) => item.text.trim().length > 0).map(promptCopy) const next: RunPrompt[] = [] diff --git a/packages/opencode/src/cli/cmd/run/runtime.boot.ts b/packages/opencode/src/cli/cmd/run/runtime.boot.ts index 3ff9801c6a2b..d0113466c443 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.boot.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.boot.ts @@ -1,32 +1,21 @@ // Boot-time resolution for direct interactive mode. // // These functions run concurrently at startup to gather everything the runtime -// needs before the first frame: keybinds from TUI config, diff display style, +// needs before the first frame: TUI keymap config, diff display style, // model variant list with context limits, and session history for the prompt // history ring. All are async because they read config or hit the SDK, but // none block each other. import { Context, Effect, Layer } from "effect" -import { stringifyKeyStroke } from "@opentui/keymap" +import { createBindingLookup } from "@opentui/keymap/extras" import { TuiConfig } from "@/cli/cmd/tui/config/tui" import { TuiKeybind } from "@/cli/cmd/tui/config/keybind" import { makeRuntime } from "@/effect/run-service" import { reusePendingTask } from "./runtime.shared" import { resolveSession, sessionHistory } from "./session.shared" -import type { FooterKeybinds, RunDiffStyle, RunInput, RunPrompt, RunProvider } from "./types" +import type { RunDiffStyle, RunInput, RunPrompt, RunProvider, RunTuiConfig } from "./types" import { pickVariant } from "./variant.shared" -const DEFAULT_KEYBINDS: FooterKeybinds = { - leader: TuiKeybind.LeaderDefault, - leaderTimeout: 2000, - commandList: [{ key: "ctrl+p" }], - variantCycle: [{ key: "ctrl+t" }], - interrupt: [{ key: "escape" }], - historyPrevious: [{ key: "up" }], - historyNext: [{ key: "down" }], - inputClear: [{ key: "ctrl+c" }], - inputSubmit: [{ key: "return" }], - inputNewline: [{ key: "shift+return,ctrl+return,alt+return,ctrl+j" }], -} +const DEFAULT_LEADER_TIMEOUT = 2000 export type ModelInfo = { providers: RunProvider[] @@ -52,7 +41,7 @@ type BootService = { sessionID: string, model: RunInput["model"], ) => Effect.Effect - readonly resolveFooterKeybinds: () => Effect.Effect + readonly resolveRunTuiConfig: () => Effect.Effect readonly resolveDiffStyle: () => Effect.Effect } @@ -80,28 +69,27 @@ function emptySessionInfo(): SessionInfo { } } -function leaderKey(config: Config) { - const key = config.keybinds.get("leader")?.[0]?.key - if (!key) return TuiKeybind.LeaderDefault - return typeof key === "string" ? key : stringifyKeyStroke(key) +function defaultRunTuiConfig(): RunTuiConfig { + const keybinds = TuiKeybind.parse({}) + return { + keybinds: createBindingLookup(TuiKeybind.toBindingConfig(keybinds), { + commandMap: TuiKeybind.CommandMap, + bindingDefaults: TuiKeybind.bindingDefaults(), + }), + leader_timeout: DEFAULT_LEADER_TIMEOUT, + diff_style: "auto", + } } -function footerKeybinds(config: Config | undefined): FooterKeybinds { +function runTuiConfig(config: Config | undefined): RunTuiConfig { if (!config) { - return DEFAULT_KEYBINDS + return defaultRunTuiConfig() } return { - leader: leaderKey(config), - leaderTimeout: config.leader_timeout, - commandList: config.keybinds.get("command.palette.show"), - variantCycle: config.keybinds.get("variant.cycle"), - interrupt: config.keybinds.get("session.interrupt"), - historyPrevious: config.keybinds.get("prompt.history.previous"), - historyNext: config.keybinds.get("prompt.history.next"), - inputClear: config.keybinds.get("prompt.clear"), - inputSubmit: config.keybinds.get("input.submit"), - inputNewline: config.keybinds.get("input.newline"), + keybinds: config.keybinds, + leader_timeout: config.leader_timeout, + diff_style: config.diff_style ?? "auto", } } @@ -175,18 +163,18 @@ const layer = Layer.effect( } }) - const resolveFooterKeybinds = Effect.fn("RunBoot.resolveFooterKeybinds")(function* () { - return footerKeybinds(yield* config()) + const resolveRunTuiConfig = Effect.fn("RunBoot.resolveRunTuiConfig")(function* () { + return runTuiConfig(yield* config()) }) const resolveDiffStyle = Effect.fn("RunBoot.resolveDiffStyle")(function* () { - return (yield* config())?.diff_style ?? "auto" + return runTuiConfig(yield* config()).diff_style ?? "auto" }) return Service.of({ resolveModelInfo, resolveSessionInfo, - resolveFooterKeybinds, + resolveRunTuiConfig, resolveDiffStyle, }) }), @@ -212,9 +200,9 @@ export async function resolveSessionInfo( return runtime.runPromise((svc) => svc.resolveSessionInfo(sdk, sessionID, model)).catch(() => emptySessionInfo()) } -// Reads keybind overrides from TUI config and merges them with defaults. -export async function resolveFooterKeybinds(): Promise { - return runtime.runPromise((svc) => svc.resolveFooterKeybinds()).catch(() => DEFAULT_KEYBINDS) +// Reads TUI config once for direct mode keymap setup and display preferences. +export async function resolveRunTuiConfig(): Promise { + return runtime.runPromise((svc) => svc.resolveRunTuiConfig()).catch(() => defaultRunTuiConfig()) } export async function resolveDiffStyle(): Promise { diff --git a/packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts b/packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts index eb342a7fda28..389f868ee8f6 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.lifecycle.ts @@ -8,8 +8,10 @@ // // Also wires SIGINT so Ctrl-c clears a live prompt draft first, then falls // back to the usual two-press exit sequence through RunFooter.requestExit(). -import { createCliRenderer, type CliRenderer, type ScrollbackWriter } from "@opentui/core" +import { CliRenderEvents, createCliRenderer, type CliRenderer, type ScrollbackWriter } from "@opentui/core" +import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import { Session as SessionApi } from "@/session/session" +import { registerOpencodeKeymap } from "@/cli/cmd/tui/keymap" import * as Locale from "@/util/locale" import { withRunSpan } from "./otel" import { resolveInteractiveStdin } from "./runtime.stdin" @@ -17,15 +19,14 @@ import { entrySplash, exitSplash, splashMeta } from "./splash" import { resolveRunTheme } from "./theme" import type { FooterApi, - FooterKeybinds, PermissionReply, QuestionReject, QuestionReply, RunAgent, - RunDiffStyle, RunInput, RunPrompt, RunResource, + RunTuiConfig, } from "./types" import { formatModelLabel } from "./variant.shared" @@ -61,8 +62,7 @@ export type LifecycleInput = { agent: string | undefined model: RunInput["model"] variant: string | undefined - keybinds: FooterKeybinds - diffStyle: RunDiffStyle + tuiConfig: RunTuiConfig onPermissionReply: (input: PermissionReply) => void | Promise onQuestionReply: (input: QuestionReply) => void | Promise onQuestionReject: (input: QuestionReject) => void | Promise @@ -75,6 +75,8 @@ export type LifecycleInput = { export type Lifecycle = { footer: FooterApi + onResize(fn: () => void): () => void + resetForReplay(input: { sessionTitle?: string; sessionID?: string; history: RunPrompt[] }): Promise close(input: { showExit: boolean; sessionTitle?: string; sessionID?: string; history?: RunPrompt[] }): Promise } @@ -169,6 +171,7 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise { const source = resolveInteractiveStdin() + let unregisterKeymap: (() => void) | undefined try { const renderer = await createCliRenderer({ @@ -188,6 +191,8 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise {}) footer.destroy() + unregisterKeymap?.() shutdown(renderer) source.cleanup?.() } @@ -302,9 +309,50 @@ export async function createRuntimeLifecycle(input: LifecycleInput): Promise { + if (width === renderer.terminalWidth && height === renderer.terminalHeight) { + return + } + + width = renderer.terminalWidth + height = renderer.terminalHeight + fn() + } + renderer.on(CliRenderEvents.RESIZE, resize) + return () => renderer.off(CliRenderEvents.RESIZE, resize) + }, + async resetForReplay(next) { + if (closed || renderer.isDestroyed || footer.isClosed) { + throw new Error("runtime closed") + } + + await footer.idle() + if (closed || renderer.isDestroyed || footer.isClosed) { + throw new Error("runtime closed") + } + + footer.resetForReplay(true) + renderer.resetSplitFooterForReplay({ clearSavedLines: true }) + const splash = splashInfo(next.sessionTitle ?? input.sessionTitle, next.history) + renderer.writeToScrollback( + entrySplash({ + ...splashMeta({ + title: splash.title, + session_id: next.sessionID ?? input.getSessionID?.() ?? input.sessionID, + }), + theme: theme.splash, + showSession: splash.showSession, + }), + ) + renderer.requestRender() + }, close, } } catch (error) { + unregisterKeymap?.() source.cleanup?.() throw error } diff --git a/packages/opencode/src/cli/cmd/run/runtime.queue.ts b/packages/opencode/src/cli/cmd/run/runtime.queue.ts index 79be71cadf13..e575647afd15 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.queue.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.queue.ts @@ -1,17 +1,17 @@ // Serial prompt queue for direct interactive mode. // // Prompts arrive from the footer (user types and hits enter) and queue up -// here. The queue drains one turn at a time: it appends the user row to -// scrollback, calls input.run() to execute the turn through the stream -// transport, and waits for completion before starting the next prompt. +// here. The queue drains one turn at a time; ordinary prompts waiting behind +// an active ordinary turn are exposed for edit/removal until they begin. // // The queue also handles /exit, /quit, and /new commands, empty-prompt rejection, // and tracks per-turn wall-clock duration for the footer status line. // // Resolves when the footer closes and all in-flight work finishes. import * as Locale from "@/util/locale" +import { MessageID, PartID } from "@/session/schema" import { isExitCommand, isNewCommand } from "./prompt.shared" -import type { FooterApi, FooterEvent, RunPrompt } from "./types" +import type { FooterApi, FooterEvent, FooterQueuedPrompt, RunPrompt } from "./types" type Trace = { write(type: string, data?: unknown): void @@ -34,6 +34,8 @@ export type QueueInput = { type State = { queue: RunPrompt[] + queued: FooterQueuedPrompt[] + active?: RunPrompt ctrl?: AbortController closed: boolean } @@ -51,15 +53,15 @@ function defer(): Deferred { // Runs the prompt queue until the footer closes. // -// Subscribes to footer prompt events, queues them, and drains one at a -// time through input.run(). If the user submits multiple prompts while -// a turn is running, they queue up and execute in order. The footer shows -// the queue depth so the user knows how many are pending. +// Subscribes to footer prompt events and drains operations through input.run(). +// Ordinary prompts submitted during an ordinary active turn remain local and +// are exposed by the footer for edit/removal until their turn begins. export async function runPromptQueue(input: QueueInput): Promise { const stop = defer<{ type: "closed" }>() const done = defer() const state: State = { queue: [], + queued: [], closed: input.footer.isClosed, } let draining: Promise | undefined @@ -69,6 +71,24 @@ export async function runPromptQueue(input: QueueInput): Promise { input.footer.event(next) } + const syncQueue = () => { + const queue = state.queue.length + emit({ type: "queue", queue }, { queue }) + emit( + { + type: "queued.prompts", + prompts: [...state.queued], + }, + { queued: state.queued.length }, + ) + } + + const removeLocalQueued = (queued: FooterQueuedPrompt) => { + if (!state.queued.includes(queued)) return + state.queued = state.queued.filter((item) => item !== queued) + syncQueue() + } + const finish = () => { if (!state.closed || draining) { return @@ -84,6 +104,7 @@ export async function runPromptQueue(input: QueueInput): Promise { state.closed = true state.queue.length = 0 + state.queued.length = 0 state.ctrl?.abort() stop.resolve({ type: "closed" }) finish() @@ -102,16 +123,11 @@ export async function runPromptQueue(input: QueueInput): Promise { continue } + const queued = state.queued.find((item) => item.prompt === prompt) + if (queued) removeLocalQueued(queued) + if (prompt.mode !== "shell" && isNewCommand(prompt.text)) { - emit( - { - type: "queue", - queue: state.queue.length, - }, - { - queue: state.queue.length, - }, - ) + syncQueue() if (!input.onNewSession) { emit( { @@ -146,6 +162,15 @@ export async function runPromptQueue(input: QueueInput): Promise { continue } + const sent = + prompt.mode === "shell" + ? prompt + : { + ...prompt, + messageID: prompt.messageID ?? queued?.messageID ?? MessageID.ascending(), + } + state.active = sent + emit( { type: "turn.send", @@ -167,18 +192,24 @@ export async function runPromptQueue(input: QueueInput): Promise { break } - if (prompt.mode !== "shell") { - const commit = { kind: "user", text: prompt.text, phase: "start", source: "system" } as const + if (sent.mode !== "shell") { + const commit = { + kind: "user", + text: sent.text, + phase: "start", + source: "system", + messageID: sent.messageID, + } as const input.trace?.write("ui.commit", commit) input.footer.append(commit) } - input.onSend?.(prompt) + input.onSend?.(sent) if (state.closed) { break } - const task = input.run(prompt, ctrl.signal).then( + const task = input.run(sent, ctrl.signal).then( () => ({ type: "done" as const }), (error) => ({ type: "error" as const, error }), ) @@ -207,6 +238,7 @@ export async function runPromptQueue(input: QueueInput): Promise { duration, }, ) + state.active = undefined } } } catch (error) { @@ -241,16 +273,28 @@ export async function runPromptQueue(input: QueueInput): Promise { return } + const active = state.active + if ( + active && + active.mode !== "shell" && + !active.command && + prompt.mode !== "shell" && + !prompt.command && + !isNewCommand(prompt.text) + ) { + const queued: FooterQueuedPrompt = { + messageID: MessageID.ascending(), + partID: PartID.ascending(), + prompt, + } + state.queued = [...state.queued, queued] + state.queue.push(prompt) + syncQueue() + return + } + state.queue.push(prompt) - emit( - { - type: "queue", - queue: state.queue.length, - }, - { - queue: state.queue.length, - }, - ) + syncQueue() if (prompt.mode !== "shell" && isNewCommand(prompt.text)) { drain() return @@ -274,6 +318,13 @@ export async function runPromptQueue(input: QueueInput): Promise { const offClose = input.footer.onClose(() => { close() }) + const offRemoveQueued = input.footer.onQueuedRemove((messageID) => { + const queued = state.queued.find((item) => item.messageID === messageID) + if (!queued) return false + state.queue = state.queue.filter((prompt) => prompt !== queued.prompt) + removeLocalQueued(queued) + return true + }) try { if (state.closed) { @@ -289,6 +340,7 @@ export async function runPromptQueue(input: QueueInput): Promise { } finally { offPrompt() offClose() + offRemoveQueued() close() await draining?.catch(() => {}) } diff --git a/packages/opencode/src/cli/cmd/run/runtime.ts b/packages/opencode/src/cli/cmd/run/runtime.ts index c9450d4602db..01665db1c9f1 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.ts @@ -7,20 +7,21 @@ // runInteractiveLocalMode -- used for local in-process mode (no server) // // Both delegate to runInteractiveRuntime, which: -// 1. resolves keybinds, diff style, model info, and session history, +// 1. resolves TUI config, model info, and session history, // 2. creates the split-footer lifecycle (renderer + RunFooter), // 3. starts the stream transport (SDK event subscription), lazily for fresh // local sessions, // 4. runs the prompt queue until the footer closes. import { createOpencodeClient } from "@opencode-ai/sdk/v2" import { Flag } from "@opencode-ai/core/flag/flag" +import { MessageID } from "@/session/schema" import { createRunDemo } from "./demo" -import { resolveDiffStyle, resolveFooterKeybinds, resolveModelInfo, resolveSessionInfo } from "./runtime.boot" +import { resolveModelInfo, resolveRunTuiConfig, resolveSessionInfo } from "./runtime.boot" import { createRuntimeLifecycle } from "./runtime.lifecycle" import { recordRunSpanError, setRunSpanAttributes, withRunSpan } from "./otel" import { trace } from "./trace" import { cycleVariant, formatModelLabel, resolveSavedVariant, resolveVariant, saveVariant } from "./variant.shared" -import type { RunInput, RunPrompt, RunProvider } from "./types" +import type { LocalReplayAnchor, LocalReplayRow, RunInput, RunPrompt, RunProvider, StreamCommit } from "./types" /** @internal Exported for testing */ export { pickVariant, resolveVariant } from "./variant.shared" @@ -114,6 +115,7 @@ type RuntimeState = { activeVariant: string | undefined sessionID: string history: RunPrompt[] + localRows: LocalReplayRow[] sessionTitle?: string agent: string | undefined switching?: Promise @@ -139,6 +141,9 @@ function variantsFor(providers: RunProvider[], model: RunInput["model"]) { return Object.keys(providers.find((item) => item.id === model.providerID)?.models?.[model.modelID]?.variants ?? {}) } +const REPLAY_RESIZE_DELAY = 250 +const LOCAL_REPLAY_ROW_LIMIT = 100 + async function resolveExitTitle( ctx: BootContext, input: RunRuntimeInput, @@ -173,8 +178,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { async (span) => { const start = performance.now() const log = trace() - const keybindTask = resolveFooterKeybinds() - const diffTask = resolveDiffStyle() + const tuiConfigTask = resolveRunTuiConfig() const ctx = await input.boot() const modelTask = resolveModelInfo(ctx.sdk, ctx.directory, ctx.model) const sessionTask = @@ -186,12 +190,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { variant: undefined, }) const savedTask = resolveSavedVariant(ctx.model) - const [keybinds, diffStyle, session, savedVariant] = await Promise.all([ - keybindTask, - diffTask, - sessionTask, - savedTask, - ]) + const [tuiConfig, session, savedVariant] = await Promise.all([tuiConfigTask, sessionTask, savedTask]) const state: RuntimeState = { shown: !session.first, aborting: false, @@ -202,6 +201,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { activeVariant: resolveVariant(ctx.variant, session.variant, savedVariant, []), sessionID: ctx.sessionID, history: [...session.history], + localRows: [], sessionTitle: ctx.sessionTitle, agent: ctx.agent, } @@ -252,8 +252,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { agent: state.agent, model: state.model, variant: state.activeVariant, - keybinds, - diffStyle, + tuiConfig, onPermissionReply: async (next) => { if (state.demo?.permission(next)) { return @@ -381,6 +380,9 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { }, }) const footer = shell.footer + const rememberLocal = (commit: StreamCommit, after?: LocalReplayAnchor) => { + state.localRows = [...state.localRows, { commit, after }].slice(-LOCAL_REPLAY_ROW_LIMIT) + } const loadCatalog = async (): Promise => { if (footer.isClosed) { @@ -517,6 +519,36 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { return next } + let replayResizeTimer: ReturnType | undefined + const offResize = input.replay + ? shell.onResize(() => { + if (replayResizeTimer) { + clearTimeout(replayResizeTimer) + } + + replayResizeTimer = setTimeout(() => { + replayResizeTimer = undefined + if (footer.isClosed || !state.stream) { + return + } + + void state.stream + .then((item) => + item.handle.replayOnResize({ + localRows: () => state.localRows, + reset: () => + shell.resetForReplay({ + sessionTitle: state.sessionTitle, + sessionID: state.sessionID, + history: state.history, + }), + }), + ) + .catch(() => {}) + }, REPLAY_RESIZE_DELAY) + }) + : () => {} + const runQueue = async () => { let includeFiles = true if (state.demo) { @@ -532,6 +564,15 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { onSend: (prompt) => { state.shown = true state.history.push(prompt) + if (prompt.mode !== "shell") { + rememberLocal({ + kind: "user", + text: prompt.text, + phase: "start", + source: "system", + messageID: prompt.messageID, + }) + } }, onNewSession: createSession ? async () => { @@ -552,6 +593,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { state.sessionTitle = created.sessionTitle state.agent = created.agent ?? state.agent state.history = [] + state.localRows = [] includeFiles = true state.demo = input.demo ? createRunDemo({ @@ -605,12 +647,15 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { status: "failed to start new session", }, }) - footer.append({ + const commit = { kind: "error", text: error instanceof Error ? error.message : String(error), phase: "start", source: "system", - }) + messageID: MessageID.ascending(), + } as const + rememberLocal(commit) + footer.append(commit) } } : undefined, @@ -621,6 +666,7 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { await state.switching?.catch(() => {}) + let outputAnchor: LocalReplayAnchor | undefined return withRunSpan( "RunInteractive.turn", { @@ -651,8 +697,16 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { prompt, files: input.files, includeFiles, + onVisibleOutput: (anchor) => { + outputAnchor = anchor + }, signal, }) + if (prompt.messageID) { + state.localRows = state.localRows.filter( + (row) => row.commit.kind !== "user" || row.commit.messageID !== prompt.messageID, + ) + } includeFiles = false } catch (error) { if (signal.aborted || footer.isClosed) { @@ -663,7 +717,15 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { const text = (await state.stream?.then((item) => item.mod).catch(() => undefined))?.formatUnknownError(error) ?? (error instanceof Error ? error.message : String(error)) - footer.append({ kind: "error", text, phase: "start", source: "system" }) + const commit = { + kind: "error", + text, + phase: "start", + source: "system", + messageID: prompt.messageID, + } as const + rememberLocal(commit, outputAnchor) + footer.append(commit) } }, ) @@ -690,6 +752,10 @@ async function runInteractiveRuntime(input: RunRuntimeInput): Promise { try { await runQueue() } finally { + if (replayResizeTimer) { + clearTimeout(replayResizeTimer) + } + offResize() await state.stream?.then((item) => item.handle.close()).catch(() => {}) } } finally { diff --git a/packages/opencode/src/cli/cmd/run/session-data.ts b/packages/opencode/src/cli/cmd/run/session-data.ts index 4a3a49fb83a4..03951ec4c9e1 100644 --- a/packages/opencode/src/cli/cmd/run/session-data.ts +++ b/packages/opencode/src/cli/cmd/run/session-data.ts @@ -60,6 +60,7 @@ type SessionCommit = StreamCommit // - part: part ID → "assistant" | "reasoning" (text parts only) // - text: part ID → full accumulated text so far // - sent: part ID → byte offset of last flushed text (for incremental output) +// - visible: part ID → rendered text for an active part after display transforms // - end: part IDs whose time.end has arrived (part is finished) // - shell: shell call ID → chosen transcript source for direct shell calls // - echo: message ID → bash outputs to strip from the next assistant chunk @@ -82,6 +83,7 @@ export type SessionData = { part: Map text: Map sent: Map + visible: Map end: Set echo: Map> } @@ -119,6 +121,7 @@ export function createSessionData( part: new Map(), text: new Map(), sent: new Map(), + visible: new Map(), end: new Set(), echo: new Map(), } @@ -538,6 +541,7 @@ function flushPart(data: SessionData, commits: SessionCommit[], partID: string, if (chunk) { data.sent.set(partID, text.length) + data.visible.set(partID, (data.visible.get(partID) ?? "") + chunk) commits.push({ kind, text: chunk, @@ -567,6 +571,7 @@ function drop(data: SessionData, partID: string) { data.part.delete(partID) data.text.delete(partID) data.sent.delete(partID) + data.visible.delete(partID) data.msg.delete(partID) data.end.delete(partID) } diff --git a/packages/opencode/src/cli/cmd/run/session-replay.ts b/packages/opencode/src/cli/cmd/run/session-replay.ts index f43bff5bed9c..8074aa4f631b 100644 --- a/packages/opencode/src/cli/cmd/run/session-replay.ts +++ b/packages/opencode/src/cli/cmd/run/session-replay.ts @@ -1,7 +1,7 @@ import type { Event, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2" import { bootstrapSessionData, createSessionData, reduceSessionData, type SessionData } from "./session-data" import { messagePrompt, type SessionMessages } from "./session.shared" -import type { FooterPatch, StreamCommit } from "./types" +import type { FooterPatch, LocalReplayRow, StreamCommit } from "./types" type ReplayInput = { messages: SessionMessages @@ -186,3 +186,116 @@ export function replaySession(input: ReplayInput): SessionReplay { patch: replayPatch(data, patch), } } + +export function replayLocalRows( + messages: SessionMessages, + commits: StreamCommit[], + rows: LocalReplayRow[], +): StreamCommit[] { + const persisted = new Set(messages.map((message) => message.info.id)) + return rows.reduce((out, local) => { + const row = local.commit + if (row.kind === "user" && row.messageID && persisted.has(row.messageID)) { + return out + } + + if (!row.messageID) { + return [...out, row] + } + + const exact = local.after + ? out.findIndex( + (commit) => + commit.kind === local.after?.kind && + commit.text === local.after.text && + commit.phase === local.after.phase && + commit.toolState === local.after.toolState && + (local.after.partID ? commit.partID === local.after.partID : commit.messageID === local.after.messageID), + ) + : -1 + const anchored = + exact !== -1 + ? exact + : local.after + ? out.findLastIndex((commit) => + local.after?.partID + ? commit.partID === local.after.partID + : commit.kind === local.after?.kind && commit.messageID === local.after.messageID, + ) + : -1 + if (anchored !== -1) { + const commit = out[anchored] + const visible = local.after?.visible + if (commit && visible && commit.text.startsWith(visible) && commit.text.length > visible.length) { + return [ + ...out.slice(0, anchored), + { ...commit, text: visible }, + row, + { ...commit, text: commit.text.slice(visible.length) }, + ...out.slice(anchored + 1), + ] + } + + return [...out.slice(0, anchored + 1), row, ...out.slice(anchored + 1)] + } + + const after = out.findIndex((commit) => commit.kind === "user" && commit.messageID === row.messageID) + if (after !== -1) { + return [...out.slice(0, after + 1), row, ...out.slice(after + 1)] + } + + const before = out.findIndex((commit) => commit.messageID && row.messageID! < commit.messageID) + if (before === -1) { + return [...out, row] + } + + return [...out.slice(0, before), row, ...out.slice(before)] + }, commits) +} + +export function replayActiveText(data: SessionData, current: SessionData): StreamCommit[] { + return [...current.part.entries()].flatMap(([partID, kind]) => { + if (kind === "user" || current.end.has(partID) || data.ids.has(partID)) { + return [] + } + + const text = current.text.get(partID) ?? "" + const existing = data.text.get(partID) ?? "" + const sent = current.sent.get(partID) ?? 0 + const existingSent = data.sent.get(partID) ?? 0 + const visible = current.visible.get(partID) ?? "" + const existingVisible = data.visible.get(partID) ?? "" + if (!text.startsWith(existing) || existingSent > sent || !visible.startsWith(existingVisible)) { + return [] + } + + data.part.set(partID, kind) + data.text.set(partID, text) + data.sent.set(partID, sent) + data.visible.set(partID, visible) + const messageID = current.msg.get(partID) + if (messageID) { + data.msg.set(partID, messageID) + const role = current.role.get(messageID) + if (role) { + data.role.set(messageID, role) + } + } + + const chunk = visible.slice(existingVisible.length) + if (!chunk) { + return [] + } + + return [ + { + kind, + text: chunk, + phase: "progress", + source: kind, + ...(messageID ? { messageID } : {}), + partID, + }, + ] satisfies StreamCommit[] + }) +} diff --git a/packages/opencode/src/cli/cmd/run/stream.transport.ts b/packages/opencode/src/cli/cmd/run/stream.transport.ts index 41a083c702fc..5641b8f07265 100644 --- a/packages/opencode/src/cli/cmd/run/stream.transport.ts +++ b/packages/opencode/src/cli/cmd/run/stream.transport.ts @@ -5,8 +5,8 @@ // produce scrollback commits and footer patches, which get forwarded to the // footer through stream.ts. // -// Prompt turns are one-at-a-time: runPromptTurn() sends the prompt to the -// SDK, arms a deferred Wait, and resolves when the session becomes idle. +// Prompt turns are one-at-a-time: runPromptTurn() sends the prompt, arms a +// deferred Wait, and resolves when the session becomes idle. // Prefer session.status idle events, but also poll session.status because some // transports can miss status events while still delivering message events. If // the turn is aborted (user interrupt), it flushes any in-progress parts as @@ -27,7 +27,7 @@ import { reduceSessionData, type SessionData, } from "./session-data" -import { replaySession } from "./session-replay" +import { replayActiveText, replayLocalRows, replaySession } from "./session-replay" import { bootstrapSubagentCalls, bootstrapSubagentData, @@ -51,6 +51,8 @@ import type { FooterSubagentState, FooterSubagentTab, FooterView, + LocalReplayAnchor, + LocalReplayRow, RunFilePart, RunInput, RunPrompt, @@ -81,6 +83,7 @@ type Wait = { tick: number armed: boolean live: boolean + onVisibleOutput?: (anchor: LocalReplayAnchor) => void done: Deferred.Deferred } @@ -91,15 +94,22 @@ export type SessionTurnInput = { prompt: RunPrompt files: RunFilePart[] includeFiles: boolean + onVisibleOutput?: (anchor: LocalReplayAnchor) => void signal?: AbortSignal } export type SessionTransport = { runPromptTurn(input: SessionTurnInput): Promise selectSubagent(sessionID: string | undefined): void + replayOnResize(input: SessionResizeReplayInput): Promise close(): Promise } +export type SessionResizeReplayInput = { + localRows: () => LocalReplayRow[] + reset: () => Promise +} + type State = { data: SessionData subagent: SubagentData @@ -115,6 +125,7 @@ type State = { type TransportService = { readonly runPromptTurn: (input: SessionTurnInput) => Effect.Effect readonly selectSubagent: (sessionID: string | undefined) => Effect.Effect + readonly replayOnResize: (input: SessionResizeReplayInput) => Effect.Effect readonly close: () => Effect.Effect } @@ -440,6 +451,9 @@ function createLayer(input: StreamInput) { blockers: new Map(), } let booting = true + let replaying = false + let replayDisabled = false + let replayPending: SessionResizeReplayInput | undefined const buffered: Event[] = [] const replayedParts = new Set() const recovering = new Set() @@ -594,6 +608,38 @@ function createLayer(input: StreamInput) { Effect.orElseSucceed(() => []), ) + const replayMessages = () => + Effect.promise(() => + input.sdk.session.messages({ + sessionID: input.sessionID, + ...(input.replayLimit === undefined + ? {} + : { limit: Math.max(input.replayLimit, SUBAGENT_BOOTSTRAP_LIMIT) }), + }), + ).pipe(Effect.flatMap((item) => (item.error ? Effect.fail(item.error) : Effect.succeed(item.data ?? [])))) + + const replayRequests = () => + Effect.all( + [ + Effect.promise(() => input.sdk.permission.list()).pipe( + Effect.flatMap((item) => (item.error ? Effect.fail(item.error) : Effect.succeed(item.data ?? []))), + ), + Effect.promise(() => input.sdk.question.list()).pipe( + Effect.flatMap((item) => (item.error ? Effect.fail(item.error) : Effect.succeed(item.data ?? []))), + ), + ], + { concurrency: "unbounded" }, + ) + + const markReplayedParts = (data: SessionData) => { + replayedParts.clear() + for (const [partID] of data.text) { + if (data.part.has(partID)) { + replayedParts.add(partID) + } + } + } + const bootstrapSubagentHistory = Effect.fn("RunStreamTransport.bootstrapSubagentHistory")(function* ( sessions: string[], ) { @@ -681,7 +727,6 @@ function createLayer(input: StreamInput) { }) : history - replayedParts.clear() if (history) { state.data = history.data } @@ -695,14 +740,8 @@ function createLayer(input: StreamInput) { }) } - if (replay) { - for (const [partID] of replay.data.text) { - if (!replay.data.part.has(partID)) { - continue - } - - replayedParts.add(partID) - } + if (history) { + markReplayedParts(history.data) } bootstrapSubagentData({ @@ -862,6 +901,20 @@ function createLayer(input: StreamInput) { limits: input.limits(), }) state.data = next.data + const visible = next.commits.at(-1) + if (visible) { + state.wait?.onVisibleOutput?.({ + kind: visible.kind, + text: visible.text, + phase: visible.phase, + messageID: visible.messageID, + partID: visible.partID, + toolState: visible.toolState, + ...(visible.partID && state.data.visible.has(visible.partID) + ? { visible: state.data.visible.get(visible.partID) } + : {}), + }) + } if ( event.type === "message.part.updated" && @@ -910,13 +963,161 @@ function createLayer(input: StreamInput) { yield* applyEvent(event) } - if (!changed) { + const arrived = buffered.splice(0) + if (!changed && arrived.length === 0) { buffered.push(...next) return } - pending = next + pending = [...next, ...arrived] + } + }) + + const replayOnResize: (next: SessionResizeReplayInput) => Effect.Effect = Effect.fn( + "RunStreamTransport.replayOnResize", + )(function* (next: SessionResizeReplayInput) { + if (!input.replay || replayDisabled || booting || closed || input.footer.isClosed) { + return false } + + if (replaying) { + replayPending = next + return false + } + + const finish: () => Effect.Effect = Effect.fnUntraced(function* () { + yield* drainBuffered() + const pending = replayPending + replayPending = undefined + if (!pending || replayDisabled || closed || input.footer.isClosed) { + replaying = false + return + } + + replaying = false + yield* replayOnResize(pending).pipe(Effect.asVoid) + }) + + replayedParts.clear() + replaying = true + input.trace?.write("replay.resize.start", { + sessionID: input.sessionID, + }) + const source = yield* Effect.all([replayMessages(), replayRequests()], { concurrency: "unbounded" }).pipe( + Effect.exit, + ) + if (Exit.isFailure(source)) { + input.trace?.write("replay.resize.abort", { + sessionID: input.sessionID, + phase: "snapshot", + }) + yield* finish() + return false + } + + const [messagesList, [permissions, questions]] = source.value + const sessionPermissions = permissions.filter((item) => item.sessionID === input.sessionID) + const sessionQuestions = questions.filter((item) => item.sessionID === input.sessionID) + const snapshot = yield* Effect.try({ + try: () => { + const history = replaySession({ + messages: messagesList, + permissions: sessionPermissions, + questions: sessionQuestions, + thinking: input.thinking, + limits: input.limits(), + }) + const activeCommits = replayActiveText(history.data, state.data) + return { + history, + activeCommits, + patch: + history.data.part.size > 0 || history.data.tools.size > 0 + ? { ...history.patch, phase: "running" as const } + : history.patch, + visible: + input.replayLimit !== undefined && messagesList.length > input.replayLimit + ? replaySession({ + messages: messagesList.slice(-input.replayLimit), + permissions: sessionPermissions, + questions: sessionQuestions, + thinking: input.thinking, + limits: input.limits(), + }) + : history, + } + }, + catch: (error) => error, + }).pipe(Effect.exit) + if (Exit.isFailure(snapshot)) { + input.trace?.write("replay.resize.abort", { + sessionID: input.sessionID, + phase: "snapshot", + }) + yield* finish() + return false + } + + const idle = yield* Effect.promise(() => input.footer.idle()).pipe(Effect.exit) + if (Exit.isFailure(idle) || closed || input.footer.isClosed) { + yield* finish() + return false + } + + const reset = yield* Effect.promise(() => next.reset()).pipe(Effect.exit) + if (Exit.isFailure(reset)) { + replayDisabled = true + input.trace?.write("replay.resize.disable", { + sessionID: input.sessionID, + phase: "reset", + }) + input.footer.append({ + kind: "error", + text: "resize replay failed; disabled for this session", + phase: "start", + source: "system", + }) + yield* finish() + return false + } + + state.data = snapshot.value.history.data + for (const request of [...state.data.permissions, ...state.data.questions]) { + seedBlocker(request.id) + } + + for (const commit of replayLocalRows( + messagesList, + [...snapshot.value.visible.commits, ...snapshot.value.activeCommits], + next.localRows(), + )) { + input.trace?.write("ui.commit", commit) + input.footer.append(commit) + } + + syncFooter([], snapshot.value.patch, currentSubagentState()) + const rebuilt = yield* Effect.promise(() => input.footer.idle()).pipe(Effect.exit) + if (Exit.isFailure(rebuilt)) { + replayDisabled = true + input.trace?.write("replay.resize.disable", { + sessionID: input.sessionID, + phase: "rebuild", + }) + input.footer.append({ + kind: "error", + text: "resize replay failed; disabled for this session", + phase: "start", + source: "system", + }) + yield* finish() + return false + } + + input.trace?.write("replay.resize.complete", { + sessionID: input.sessionID, + }) + yield* finish() + return true }) const watch = Effect.fn("RunStreamTransport.watch")(() => @@ -943,7 +1144,7 @@ function createLayer(input: StreamInput) { } const sessionID = sid(event) - if (booting) { + if (booting || replaying) { if (sessionID) { input.trace?.write("recv.event", event) buffered.push(event) @@ -1005,6 +1206,7 @@ function createLayer(input: StreamInput) { tick: state.tick, armed: false, live: false, + onVisibleOutput: next.onVisibleOutput, done: yield* Deferred.make(), } state.wait = item @@ -1020,6 +1222,7 @@ function createLayer(input: StreamInput) { const req = { sessionID: input.sessionID, + messageID: next.prompt.messageID, agent: next.agent, model: next.model, variant: next.variant, @@ -1081,6 +1284,7 @@ function createLayer(input: StreamInput) { input.sdk.session.command( { sessionID: input.sessionID, + messageID: next.prompt.messageID, agent: next.agent, model: next.model ? `${next.model.providerID}/${next.model.modelID}` : undefined, variant: next.variant, @@ -1231,6 +1435,7 @@ function createLayer(input: StreamInput) { return Service.of({ runPromptTurn, selectSubagent, + replayOnResize, close, }) }), @@ -1254,6 +1459,7 @@ export async function createSessionTransport(input: StreamInput): Promise runtime.runPromise((svc) => svc.runPromptTurn(next)), selectSubagent: (sessionID) => runtime.runSync((svc) => svc.selectSubagent(sessionID)), + replayOnResize: (next) => runtime.runPromise((svc) => svc.replayOnResize(next)), close: () => runtime.runPromise((svc) => svc.close()), } } diff --git a/packages/opencode/src/cli/cmd/run/types.ts b/packages/opencode/src/cli/cmd/run/types.ts index d2de3fca8abd..65099394c292 100644 --- a/packages/opencode/src/cli/cmd/run/types.ts +++ b/packages/opencode/src/cli/cmd/run/types.ts @@ -11,9 +11,8 @@ // → stream.ts bridges to footer API // → footer.ts queues commits and patches the footer view // → OpenTUI split-footer renderer writes to terminal -import type { KeyEvent, Renderable } from "@opentui/core" -import type { Binding } from "@opentui/keymap" import type { OpencodeClient, PermissionRequest, QuestionRequest, ToolPart } from "@opencode-ai/sdk/v2" +import type { TuiConfig } from "@/cli/cmd/tui/config/tui" export type RunFilePart = { type: "file" @@ -32,6 +31,8 @@ export type RunCommand = NonNullable>["data"]>["all"][number] export type RunPrompt = { + messageID?: string + partID?: string text: string parts: RunPromptPart[] mode?: "shell" @@ -41,6 +42,12 @@ export type RunPrompt = { } } +export type FooterQueuedPrompt = { + messageID: string + partID: string + prompt: RunPrompt +} + export type RunAgent = NonNullable>["data"]>[number] type RunResourceMap = NonNullable>["data"]> @@ -163,6 +170,7 @@ export type FooterView = export type FooterPromptRoute = | { type: "composer" } + | { type: "queued-menu" } | { type: "subagent-menu" } | { type: "subagent"; sessionID: string } | { type: "command" } @@ -223,6 +231,10 @@ export type FooterEvent = type: "queue" queue: number } + | { + type: "queued.prompts" + prompts: FooterQueuedPrompt[] + } | { type: "first" first: boolean @@ -265,20 +277,7 @@ export type QuestionReply = Parameters[0] export type QuestionReject = Parameters[0] -type FooterBinding = Binding - -export type FooterKeybinds = { - leader: string - leaderTimeout: number - commandList: readonly FooterBinding[] - variantCycle: readonly FooterBinding[] - interrupt: readonly FooterBinding[] - historyPrevious: readonly FooterBinding[] - historyNext: readonly FooterBinding[] - inputClear: readonly FooterBinding[] - inputSubmit: readonly FooterBinding[] - inputNewline: readonly FooterBinding[] -} +export type RunTuiConfig = Pick // Lifecycle phase of a scrollback entry. "start" opens the entry, "progress" // appends content (coalesced in the footer queue), "final" closes it. @@ -310,12 +309,28 @@ export type StreamCommit = { } } +export type LocalReplayAnchor = { + kind: EntryKind + text: string + phase: StreamPhase + messageID?: string + partID?: string + toolState?: StreamToolState + visible?: string +} + +export type LocalReplayRow = { + commit: StreamCommit + after?: LocalReplayAnchor +} + // The public contract between the stream transport / prompt queue and // the footer. RunFooter implements this. The transport and queue never // touch the renderer directly -- they go through this interface. export type FooterApi = { readonly isClosed: boolean onPrompt(fn: (input: RunPrompt) => void): () => void + onQueuedRemove(fn: (messageID: string) => boolean | Promise): () => void onClose(fn: () => void): () => void event(next: FooterEvent): void append(commit: StreamCommit): void diff --git a/packages/opencode/src/cli/cmd/stats.ts b/packages/opencode/src/cli/cmd/stats.ts index 7ee16c2e219a..22dee14772cd 100644 --- a/packages/opencode/src/cli/cmd/stats.ts +++ b/packages/opencode/src/cli/cmd/stats.ts @@ -2,8 +2,8 @@ import { Effect } from "effect" import { effectCmd } from "../effect-cmd" import { Session } from "@/session/session" import { NotFoundError } from "@/storage/storage" -import { Database } from "@/storage/db" -import { SessionTable } from "../../session/session.sql" +import { Database } from "@opencode-ai/core/database/database" +import { SessionTable } from "@opencode-ai/core/session/sql" import { Project } from "@/project/project" import { InstanceRef } from "@/effect/instance-ref" @@ -80,9 +80,10 @@ export const StatsCommand = effectCmd({ }), }) -const getAllSessions = Effect.sync(() => - Database.use((db) => db.select().from(SessionTable).all()).map((row) => Session.fromRow(row)), -) +const getAllSessions = Effect.fnUntraced(function* () { + const { db } = yield* Database.Service + return (yield* db.select().from(SessionTable).all().pipe(Effect.orDie)).map((row) => Session.fromRow(row)) +}) const aggregateSessionStats = Effect.fn("Cli.stats.aggregate")(function* ( days?: number, @@ -90,7 +91,7 @@ const aggregateSessionStats = Effect.fn("Cli.stats.aggregate")(function* ( currentProject?: Project.Info, ) { const svc = yield* Session.Service - const sessions = yield* getAllSessions + const sessions = yield* getAllSessions() const MS_IN_DAY = 24 * 60 * 60 * 1000 const cutoffTime = (() => { diff --git a/packages/opencode/src/cli/cmd/tui/app.tsx b/packages/opencode/src/cli/cmd/tui/app.tsx index 18ee0a92b543..6a92f5f7c5f4 100644 --- a/packages/opencode/src/cli/cmd/tui/app.tsx +++ b/packages/opencode/src/cli/cmd/tui/app.tsx @@ -3,7 +3,7 @@ import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import * as Clipboard from "@tui/util/clipboard" import * as Selection from "@tui/util/selection" import * as TuiAudio from "@tui/util/audio" -import { createCliRenderer, MouseButton, type CliRendererConfig } from "@opentui/core" +import { createCliRenderer, MouseButton, type CliRenderer, type CliRendererConfig } from "@opentui/core" import { RouteProvider, useRoute } from "@tui/context/route" import { Switch, @@ -18,7 +18,7 @@ import { Show, on, } from "solid-js" -import { win32DisableProcessedInput, win32InstallCtrlCGuard } from "./win32" +import { win32DisableProcessedInput, win32FlushInputBuffer, win32InstallCtrlCGuard } from "./win32" import { Flag } from "@opencode-ai/core/flag/flag" import semver from "semver" import { DialogProvider, useDialog } from "@tui/ui/dialog" @@ -41,6 +41,7 @@ import { DialogThemeList } from "@tui/component/dialog-theme-list" import { DialogHelp } from "./ui/dialog-help" import { DialogAgent } from "@tui/component/dialog-agent" import { DialogSessionList } from "@tui/component/dialog-session-list" +import { DialogWorkspaceList } from "@tui/component/dialog-workspace-list" import { DialogConsoleOrg } from "@tui/component/dialog-console-org" import { ThemeProvider, useTheme } from "@tui/context/theme" import { Home } from "@tui/routes/home" @@ -51,7 +52,7 @@ import { PromptStashProvider } from "./component/prompt/stash" import { DialogAlert } from "./ui/dialog-alert" import { DialogConfirm } from "./ui/dialog-confirm" import { ToastProvider, useToast } from "./ui/toast" -import { ExitProvider, useExit } from "./context/exit" +import { createExit, ExitProvider, useExit, type Exit } from "./context/exit" import { Session as SessionApi } from "@/session/session" import { TuiEvent } from "./event" import { KVProvider, useKV } from "./context/kv" @@ -80,8 +81,7 @@ import { import type { EventSource } from "./context/sdk" import { DialogVariant } from "./component/dialog-variant" -const appBindingCommands = [ - "command.palette.show", +const appGlobalBindingCommands = [ "session.list", "session.new", "session.quick_switch.1", @@ -93,6 +93,10 @@ const appBindingCommands = [ "session.quick_switch.7", "session.quick_switch.8", "session.quick_switch.9", +] as const + +const appBindingCommands = [ + "command.palette.show", "model.list", "model.cycle_recent", "model.cycle_recent_reverse", @@ -112,6 +116,7 @@ const appBindingCommands = [ "theme.mode.lock", "help.show", "docs.open", + "workspace.list", "app.debug", "app.console", "app.heap_snapshot", @@ -124,7 +129,7 @@ const appBindingCommands = [ "app.toggle.session_directory_filter", ] as const -function rendererConfig(_config: TuiConfig.Resolved): CliRendererConfig { +export function tuiRendererConfig(_config: TuiConfig.Resolved): CliRendererConfig { const mouseEnabled = !Flag.OPENCODE_DISABLE_MOUSE && (_config.mouse ?? true) return { @@ -147,6 +152,34 @@ function rendererConfig(_config: TuiConfig.Resolved): CliRendererConfig { } } +export function createTuiRenderer(config: TuiConfig.Resolved) { + return createCliRenderer(tuiRendererConfig(config)) +} + +export type TuiHandle = { + ready: Promise + done: Promise + exit: Exit +} + +type TuiInput = { + url: string + args: Args + config: TuiConfig.Resolved + renderer: CliRenderer + onSnapshot?: () => Promise + directory?: string + fetch?: typeof fetch + headers?: RequestInit["headers"] + events?: EventSource +} + +type TuiLifecycle = { + exit: Exit + exited: Promise + fail(error: unknown): Promise +} + function errorMessage(error: unknown) { const formatted = FormatError(error) if (formatted !== undefined) return formatted @@ -164,109 +197,179 @@ function errorMessage(error: unknown) { return FormatUnknownError(error) } -export function tui(input: { - url: string - args: Args - config: TuiConfig.Resolved - onSnapshot?: () => Promise - directory?: string - fetch?: typeof fetch - headers?: RequestInit["headers"] - events?: EventSource -}) { - // promise to prevent immediate exit - // oxlint-disable-next-line no-async-promise-executor -- intentional: async executor used for sequential setup before resolve - return new Promise(async (resolve) => { - const unguard = win32InstallCtrlCGuard() - win32DisableProcessedInput() - - const onExit = async () => { - unguard?.() - resolve() - } - const onBeforeExit = async () => { - offKeymap() +export function tui(input: TuiInput): TuiHandle { + const unguard = win32InstallCtrlCGuard() + win32DisableProcessedInput() + + const renderer = input.renderer + const keymap = createDefaultOpenTuiKeymap(renderer) + const unregisterKeymap = registerOpencodeKeymap(keymap, renderer, input.config) + const lifecycle = createTuiLifecycle({ + renderer, + unguard, + cleanup: async () => { + unregisterKeymap() await TuiPluginRuntime.dispose() TuiAudio.dispose() + }, + }) + const ready = mountTui({ ...input, keymap, exit: lifecycle.exit }).catch((error) => lifecycle.fail(error)) + const done = waitUntilDone(ready, lifecycle.exited) + + return { ready, done, exit: lifecycle.exit } +} + +async function mountTui(input: TuiInput & { keymap: ReturnType; exit: Exit }) { + const renderer = input.renderer + // Prewarm palette before ThemeProvider mounts so `system` theme avoids a first-paint fallback flash. + void renderer.getPalette({ size: 16 }).catch(() => undefined) + const mode = (await renderer.waitForThemeMode(1000)) ?? "dark" + if (renderer.isDestroyed) return + + await render(() => { + return ( + } + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ) + }, renderer) +} + +function createTuiLifecycle(input: { + renderer: CliRenderer + unguard?: () => void + cleanup: () => Promise +}): TuiLifecycle { + let resolveExited!: () => void + const exited = new Promise((resolve) => { + resolveExited = resolve + }) + let exitCompleted = false + let exiting = false + let cleanupTask: Promise | undefined + + const completeExit = () => { + if (exitCompleted) return + exitCompleted = true + resolveExited() + } + + const cleanup = () => { + cleanupTask ??= (async () => { + process.off("SIGHUP", onSighup) + try { + await input.cleanup() + } finally { + input.unguard?.() + } + })() + return cleanupTask + } + + const exit = createExit(async (reason, message) => { + exiting = true + await cleanup() + if (!input.renderer.isDestroyed) { + input.renderer.setTerminalTitle("") + input.renderer.destroy() } + win32FlushInputBuffer() + if (reason) { + const formatted = FormatError(reason) ?? FormatUnknownError(reason) + if (formatted) process.stderr.write(formatted + "\n") + } + const text = message() + if (text) process.stdout.write(text + "\n") + completeExit() + }) + const onSighup = () => { + void exit() + } - const renderer = await createCliRenderer(rendererConfig(input.config)) - // Prewarm palette before ThemeProvider mounts so `system` theme avoids a first-paint fallback flash. - void renderer.getPalette({ size: 16 }).catch(() => undefined) - const mode = (await renderer.waitForThemeMode(1000)) ?? "dark" - - const keymap = createDefaultOpenTuiKeymap(renderer) - const offKeymap = registerOpencodeKeymap(keymap, renderer, input.config) - - await render(() => { - return ( - ( - - )} - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ) - }, renderer) + input.renderer.once("destroy", () => { + if (exiting) return + void cleanup().finally(() => { + win32FlushInputBuffer() + completeExit() + }) }) + process.on("SIGHUP", onSighup) + + return { + exit, + exited, + async fail(error) { + exiting = true + await cleanup().catch(() => {}) + if (!input.renderer.isDestroyed) input.renderer.destroy() + completeExit() + throw error + }, + } +} + +async function waitUntilDone(ready: Promise, exited: Promise) { + await ready + await exited } function App(props: { onSnapshot?: () => Promise }) { @@ -510,6 +613,16 @@ function App(props: { onSnapshot?: () => Promise }) { dialog.clear() }, }, + { + name: "workspace.list", + title: "Manage workspaces", + category: "Workspace", + hidden: !Flag.OPENCODE_EXPERIMENTAL_WORKSPACES, + slashName: "workspaces", + run: () => { + dialog.replace(() => ) + }, + }, ...Array.from({ length: 9 }, (_, i) => ({ name: `session.quick_switch.${i + 1}`, title: `Switch to session in quick slot ${i + 1}`, @@ -836,6 +949,10 @@ function App(props: { onSnapshot?: () => Promise }) { bindings: tuiConfig.keybinds.gather("app", appBindingCommands), })) + useBindings(() => ({ + bindings: tuiConfig.keybinds.gather("app.global", appGlobalBindingCommands), + })) + useBindings(() => ({ mode: OPENCODE_BASE_MODE, enabled: () => { @@ -970,7 +1087,9 @@ function App(props: { onSnapshot?: () => Promise }) { - + + {(_) => } + {plugin()} diff --git a/packages/opencode/src/cli/cmd/tui/attach.ts b/packages/opencode/src/cli/cmd/tui/attach.ts index 2897a41caf45..b908887c39f8 100644 --- a/packages/opencode/src/cli/cmd/tui/attach.ts +++ b/packages/opencode/src/cli/cmd/tui/attach.ts @@ -67,7 +67,6 @@ export const AttachCommand = cmd({ })() const headers = ServerAuth.headers({ password: args.password, username: args.username }) const config = await TuiConfig.get() - const { tui } = await import("./app") try { await validateSession({ @@ -82,9 +81,12 @@ export const AttachCommand = cmd({ return } - await tui({ + const { createTuiRenderer, tui } = await import("./app") + const renderer = await createTuiRenderer(config) + const handle = tui({ url: args.url, config, + renderer, args: { continue: args.continue, sessionID: args.session, @@ -93,6 +95,7 @@ export const AttachCommand = cmd({ directory, headers, }) + await handle.done } finally { unguard?.() } diff --git a/packages/opencode/src/cli/cmd/tui/component/dialog-model.tsx b/packages/opencode/src/cli/cmd/tui/component/dialog-model.tsx index 09c2d64b00dc..4b4484b79818 100644 --- a/packages/opencode/src/cli/cmd/tui/component/dialog-model.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/dialog-model.tsx @@ -73,6 +73,7 @@ export function DialogModel(props: { providerID?: string }) { map(([model, info]) => ({ value: { providerID: provider.id, modelID: model }, title: info.name ?? model, + releaseDate: info.release_date, description: favorites.some((item) => item.providerID === provider.id && item.modelID === model) ? "(Favorite)" : undefined, @@ -91,10 +92,7 @@ export function DialogModel(props: { providerID?: string }) { return false return true }), - sortBy( - (x) => x.footer !== "Free", - (x) => x.title, - ), + (options) => sortModelOptions(options, props.providerID !== undefined), ), ), ) @@ -173,3 +171,15 @@ export function DialogModel(props: { providerID?: string }) { /> ) } + +export function sortModelOptions( + options: T[], + newestFirst: boolean, +) { + if (newestFirst) return sortBy(options, [(option) => option.releaseDate, "desc"], (option) => option.title) + return sortBy( + options, + (option) => option.footer !== "Free", + (option) => option.title, + ) +} diff --git a/packages/opencode/src/cli/cmd/tui/component/dialog-provider.tsx b/packages/opencode/src/cli/cmd/tui/component/dialog-provider.tsx index 2caa67b559ac..7c1386ae76c3 100644 --- a/packages/opencode/src/cli/cmd/tui/component/dialog-provider.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/dialog-provider.tsx @@ -262,6 +262,13 @@ function AutoMethod(props: AutoMethodProps) { method: props.index, }) if (result.error) { + toast.show({ + variant: "error", + message: + "name" in result.error && result.error.name === "ProviderAuthOauthCallbackFailed" + ? "OAuth authorization failed. Try /connect again." + : JSON.stringify(result.error), + }) dialog.clear() return } @@ -373,7 +380,7 @@ function ApiMethod(props: ApiMethodProps) { with generous usage limits. - Go to https://opencode.ai/zen and enable OpenCode Go + Go to https://opencode.ai/go and enable OpenCode Go ), diff --git a/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx b/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx index 17653af6b9a9..e16893353a80 100644 --- a/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/dialog-session-list.tsx @@ -53,13 +53,22 @@ export function DialogSessionList() { const workspaceID = await (async () => { if (selection.type === "none") return null if (selection.type === "existing") return selection.workspaceID - const result = await sdk.client.experimental.workspace - .create({ type: selection.workspaceType, branch: null }) - .catch(() => undefined) + let result + try { + result = await sdk.client.experimental.workspace.create({ type: selection.workspaceType, branch: null }) + } catch (err) { + toast.show({ + title: "Failed to create workspace", + message: errorMessage(err), + variant: "error", + }) + return + } const workspace = result?.data if (!workspace) { toast.show({ - message: `Failed to create workspace: ${errorMessage(result?.error ?? "no response")}`, + title: "Failed to create workspace", + message: errorMessage(result?.error ?? "no response"), variant: "error", }) return diff --git a/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-create.tsx b/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-create.tsx index b22930bc6c1a..29566c46102a 100644 --- a/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-create.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-create.tsx @@ -61,15 +61,17 @@ async function loadWorkspaceAdapters(input: { const dir = input.sync.path.directory || input.sdk.directory const url = new URL("/experimental/workspace/adapter", input.sdk.url) if (dir) url.searchParams.set("directory", dir) - const res = await input.sdk - .fetch(url) - .then((x) => x.json() as Promise) - .catch(() => undefined) - if (res) return res - input.toast.show({ - message: "Failed to load workspace adapters", - variant: "error", - }) + try { + const response = await input.sdk.fetch(url) + return (await response.json()) as Adapter[] + } catch (err) { + input.toast.show({ + title: "Failed to load workspace adapters", + message: errorMessage(err), + variant: "error", + }) + return undefined + } } export async function openWorkspaceSelect(input: { @@ -100,13 +102,21 @@ export async function warpWorkspaceSession(input: { copyChanges: boolean done?: () => void }): Promise { - const result = await input.sdk.client.experimental.workspace - .warp({ + let result + try { + result = await input.sdk.client.experimental.workspace.warp({ id: input.workspaceID, sessionID: input.sessionID, copyChanges: input.copyChanges, }) - .catch(() => undefined) + } catch (err) { + input.toast.show({ + title: "Failed to warp session", + message: errorMessage(err), + variant: "error", + }) + return false + } if (!result?.data) { if (result?.error && "name" in result.error && result.error.name === "VcsApplyError") { await DialogAlert.show( @@ -118,7 +128,8 @@ export async function warpWorkspaceSession(input: { } input.toast.show({ - message: `Failed to warp session: ${errorMessage(result?.error ?? "no response")}`, + title: "Failed to warp session", + message: errorMessage(result?.error ?? "no response"), variant: "error", }) return false diff --git a/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-list.tsx b/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-list.tsx new file mode 100644 index 000000000000..0790d6479650 --- /dev/null +++ b/packages/opencode/src/cli/cmd/tui/component/dialog-workspace-list.tsx @@ -0,0 +1,112 @@ +import type { Workspace } from "@opencode-ai/sdk/v2" +import { useDialog } from "@tui/ui/dialog" +import { DialogSelect, type DialogSelectOption } from "@tui/ui/dialog-select" +import { useProject } from "@tui/context/project" +import { useRoute } from "@tui/context/route" +import { useSync } from "@tui/context/sync" +import { useTheme } from "@tui/context/theme" +import { createMemo, createSignal, onMount } from "solid-js" +import { createStore } from "solid-js/store" +import { errorMessage } from "@/util/error" +import { useSDK } from "../context/sdk" +import { useToast } from "../ui/toast" + +type WorkspaceOption = { workspace: Workspace } + +export function DialogWorkspaceList() { + const dialog = useDialog() + const route = useRoute() + const sync = useSync() + const sdk = useSDK() + const toast = useToast() + const project = useProject() + const { theme } = useTheme() + const [deleting, setDeleting] = createSignal() + const [removing, setRemoving] = createSignal() + const [expanded, setExpanded] = createStore>({}) + + const current = createMemo(() => { + if (route.data.type === "session") return sync.session.get(route.data.sessionID)?.workspaceID + return project.workspace.current() + }) + + const options = createMemo[]>(() => + project.workspace + .list() + .toSorted((a, b) => a.name.localeCompare(b.name)) + .map((workspace) => { + const status = project.workspace.status(workspace.id) + return { + title: + removing() === workspace.id + ? "Deleting..." + : deleting() === workspace.id + ? `Delete ${workspace.name}? Press delete again` + : workspace.name, + value: { workspace }, + footer: workspace.type, + details: expanded[workspace.id] && workspace.directory ? [workspace.directory] : undefined, + gutter: () => , + } + }), + ) + + function showDetails(workspace: Workspace) { + setExpanded(workspace.id, (open) => !open) + } + + async function remove(workspace: Workspace) { + if (removing()) return + if (deleting() !== workspace.id) { + setDeleting(workspace.id) + return + } + + setDeleting(undefined) + setRemoving(workspace.id) + const result = await sdk.client.experimental.workspace.remove({ id: workspace.id }).catch((err) => ({ + error: err, + })) + if (result?.error) { + setRemoving(undefined) + toast.show({ + variant: "error", + title: "Failed to delete workspace", + message: errorMessage(result.error), + }) + return + } + + if (current() === workspace.id) { + project.workspace.set(undefined) + route.navigate({ type: "home" }) + } + await project.workspace.sync() + await sync.bootstrap({ fatal: false }).catch(() => undefined) + setRemoving(undefined) + } + + onMount(() => { + dialog.setSize("large") + void sdk.client.experimental.workspace.syncList().catch(() => undefined) + void project.workspace.sync() + }) + + return ( + { + setDeleting(undefined) + }} + onSelect={(option) => showDetails(option.value.workspace)} + actions={[ + { + command: "session.delete", + title: "delete", + onTrigger: (option) => void remove(option.value.workspace), + }, + ]} + /> + ) +} diff --git a/packages/opencode/src/cli/cmd/tui/component/error-component.tsx b/packages/opencode/src/cli/cmd/tui/component/error-component.tsx index fcbd27ca9bd0..e67dc249c8ff 100644 --- a/packages/opencode/src/cli/cmd/tui/component/error-component.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/error-component.tsx @@ -1,32 +1,21 @@ import { TextAttributes } from "@opentui/core" -import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/solid" +import { useKeyboard, useTerminalDimensions } from "@opentui/solid" import * as Clipboard from "@tui/util/clipboard" import { createSignal } from "solid-js" import { InstallationVersion } from "@opencode-ai/core/installation/version" -import { win32FlushInputBuffer } from "../win32" import { getScrollAcceleration } from "../util/scroll" export function ErrorComponent(props: { error: Error reset: () => void - onBeforeExit?: () => Promise - onExit: () => Promise + exit: () => Promise mode?: "dark" | "light" }) { const term = useTerminalDimensions() - const renderer = useRenderer() - - const handleExit = async () => { - await props.onBeforeExit?.() - renderer.setTerminalTitle("") - renderer.destroy() - win32FlushInputBuffer() - await props.onExit() - } useKeyboard((evt) => { if (evt.ctrl && evt.name === "c") { - void handleExit() + void props.exit() } }) const [copied, setCopied] = createSignal(false) @@ -79,7 +68,7 @@ export function ErrorComponent(props: { Reset TUI - + void props.exit()} backgroundColor={colors.primary} padding={1}> Exit diff --git a/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx b/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx index b5f5395bbce1..0780b2d97f26 100644 --- a/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx +++ b/packages/opencode/src/cli/cmd/tui/component/prompt/index.tsx @@ -25,10 +25,11 @@ import { useSync } from "@tui/context/sync" import { useEvent } from "@tui/context/event" import { editorSelectionKey, useEditorContext, type EditorSelection } from "@tui/context/editor" import { MessageID, PartID } from "@/session/schema" +import { promptOffsetWidth } from "@/cli/cmd/prompt-display" import { createStore, produce, unwrap } from "solid-js/store" import { usePromptHistory, type PromptInfo } from "./history" import { computePromptTraits } from "./traits" -import { assign, expandPastedTextPlaceholders } from "./part" +import { assign, expandPastedTextPlaceholders, expandTrackedPastedText } from "./part" import { usePromptStash } from "./stash" import { DialogStash } from "../dialog-stash" import { DialogExecutionMode } from "../dialog-execution-mode" @@ -41,6 +42,7 @@ import type { AssistantMessage, FilePart, UserMessage } from "@opencode-ai/sdk/v import { TuiEvent } from "../../event" import { iife } from "@/util/iife" import { Locale } from "@/util/locale" +import { errorMessage } from "@/util/error" import { formatDuration } from "@/util/format" import { createColors, createFrames } from "../../ui/spinner.ts" import { useDialog } from "@tui/ui/dialog" @@ -228,14 +230,25 @@ export function Prompt(props: PromptProps) { async function createWorkspace(selection: Extract) { setCreatingWorkspace(true) - const result = await sdk.client.experimental.workspace - .create({ type: selection.workspaceType, branch: null }) - .catch(() => undefined) - if (result == undefined || result.error || !result.data) { + let result + try { + result = await sdk.client.experimental.workspace.create({ type: selection.workspaceType, branch: null }) + } catch (err) { + selectWorkspace(undefined) + setCreatingWorkspace(false) + toast.show({ + title: "Creating workspace failed", + message: errorMessage(err), + variant: "error", + }) + return + } + if (result.error || !result.data) { selectWorkspace(undefined) setCreatingWorkspace(false) toast.show({ - message: "Creating workspace failed", + title: "Creating workspace failed", + message: errorMessage(result.error ?? "no response"), variant: "error", }) return @@ -526,7 +539,10 @@ export function Prompt(props: PromptProps) { const content = await Editor.open({ value, renderer, - cwd: project.instance.path().worktree || project.instance.directory() || process.cwd(), + cwd: + (project.instance.path().worktree === "/" ? undefined : project.instance.path().worktree) || + project.instance.directory() || + process.cwd(), }) if (!content) return @@ -1165,23 +1181,15 @@ export function Prompt(props: PromptProps) { } const messageID = MessageID.ascending() - let inputText = store.prompt.input - - // Expand pasted text inline before submitting - const allExtmarks = input.extmarks.getAllForTypeId(promptPartTypeId) - const sortedExtmarks = allExtmarks.sort((a: { start: number }, b: { start: number }) => b.start - a.start) - - for (const extmark of sortedExtmarks) { - const partIndex = store.extmarkToPartIndex.get(extmark.id) - if (partIndex !== undefined) { - const part = store.prompt.parts[partIndex] - if (part?.type === "text" && part.text) { - const before = inputText.slice(0, extmark.start) - const after = inputText.slice(extmark.end) - inputText = before + part.text + after - } - } - } + const inputText = expandTrackedPastedText( + store.prompt.input, + input.extmarks.getAllForTypeId(promptPartTypeId).flatMap((extmark) => { + const partIndex = store.extmarkToPartIndex.get(extmark.id) + const part = partIndex === undefined ? undefined : store.prompt.parts[partIndex] + if (part?.type !== "text") return [] + return [{ start: extmark.start, end: extmark.end, text: part.text }] + }), + ) // Filter out text parts (pasted content) since they're now expanded inline const nonTextParts = store.prompt.parts.filter((part) => part.type !== "text") @@ -1301,9 +1309,9 @@ export function Prompt(props: PromptProps) { const exit = useExit() function pasteText(text: string, virtualText: string) { - const currentOffset = input.visualCursor.offset + const currentOffset = input.cursorOffset const extmarkStart = currentOffset - const extmarkEnd = extmarkStart + virtualText.length + const extmarkEnd = extmarkStart + promptOffsetWidth(virtualText) input.insertText(virtualText + " ") @@ -1395,7 +1403,7 @@ export function Prompt(props: PromptProps) { } async function pasteAttachment(file: { filename?: string; filepath?: string; content: string; mime: string }) { - const currentOffset = input.visualCursor.offset + const currentOffset = input.cursorOffset const extmarkStart = currentOffset const pdf = file.mime === "application/pdf" const count = store.prompt.parts.filter((x) => { diff --git a/packages/opencode/src/cli/cmd/tui/component/prompt/part.ts b/packages/opencode/src/cli/cmd/tui/component/prompt/part.ts index c5ab85bc1ec1..55b2e9a3f154 100644 --- a/packages/opencode/src/cli/cmd/tui/component/prompt/part.ts +++ b/packages/opencode/src/cli/cmd/tui/component/prompt/part.ts @@ -1,4 +1,5 @@ import { PartID } from "@/session/schema" +import { displaySlice } from "@/cli/cmd/prompt-display" import type { PromptInfo } from "./history" type Item = PromptInfo["parts"][number] @@ -21,3 +22,10 @@ export function expandPastedTextPlaceholders(text: string, parts: PromptInfo["pa return result.replace(part.source.text.value, part.text) }, text) } + +export function expandTrackedPastedText(text: string, ranges: { start: number; end: number; text: string }[]) { + return ranges + .slice() + .sort((a, b) => b.start - a.start) + .reduce((result, part) => displaySlice(result, 0, part.start) + part.text + displaySlice(result, part.end), text) +} diff --git a/packages/opencode/src/cli/cmd/tui/config/keybind.ts b/packages/opencode/src/cli/cmd/tui/config/keybind.ts index eaa4e280d7cd..e16c0043b2b8 100644 --- a/packages/opencode/src/cli/cmd/tui/config/keybind.ts +++ b/packages/opencode/src/cli/cmd/tui/config/keybind.ts @@ -95,6 +95,7 @@ export const Definitions = { session_compact: keybind("c", "Compact the session"), session_toggle_timestamps: keybind("none", "Toggle message timestamps"), session_toggle_generic_tool_output: keybind("none", "Toggle generic tool output"), + session_queued_prompts: keybind("q", "Manage queued prompts"), session_child_first: keybind("down", "Go to first child session"), session_child_cycle: keybind("right", "Go to next child session"), session_child_cycle_reverse: keybind("left", "Go to previous child session"), @@ -292,6 +293,7 @@ export const CommandMap = { session_compact: "session.compact", session_toggle_timestamps: "session.toggle.timestamps", session_toggle_generic_tool_output: "session.toggle.generic_tool_output", + session_queued_prompts: "session.queued_prompts", session_child_first: "session.child.first", session_child_cycle: "session.child.next", session_child_cycle_reverse: "session.child.previous", diff --git a/packages/opencode/src/cli/cmd/tui/context/exit.tsx b/packages/opencode/src/cli/cmd/tui/context/exit.tsx index 205025f867de..5b25a600396f 100644 --- a/packages/opencode/src/cli/cmd/tui/context/exit.tsx +++ b/packages/opencode/src/cli/cmd/tui/context/exit.tsx @@ -1,8 +1,6 @@ -import { useRenderer } from "@opentui/solid" import { createSimpleContext } from "./helper" -import { FormatError, FormatUnknownError } from "@/cli/error" -import { win32FlushInputBuffer } from "../win32" -type Exit = ((reason?: unknown) => Promise) & { + +export type Exit = ((reason?: unknown) => Promise) & { message: { set: (value?: string) => () => void clear: () => void @@ -10,51 +8,35 @@ type Exit = ((reason?: unknown) => Promise) & { } } +export function createExit(run: (reason: unknown | undefined, message: () => string | undefined) => Promise) { + let message: string | undefined + let task: Promise | undefined + const store = { + set: (value?: string) => { + const prev = message + message = value + return () => { + message = prev + } + }, + clear: () => { + message = undefined + }, + get: () => message, + } + + return Object.assign( + (reason?: unknown) => { + task ??= run(reason, store.get) + return task + }, + { + message: store, + }, + ) satisfies Exit +} + export const { use: useExit, provider: ExitProvider } = createSimpleContext({ name: "Exit", - init: (input: { onBeforeExit?: () => Promise; onExit?: () => Promise }) => { - const renderer = useRenderer() - let message: string | undefined - let task: Promise | undefined - const store = { - set: (value?: string) => { - const prev = message - message = value - return () => { - message = prev - } - }, - clear: () => { - message = undefined - }, - get: () => message, - } - const exit: Exit = Object.assign( - (reason?: unknown) => { - if (task) return task - task = (async () => { - await input.onBeforeExit?.() - // Reset window title before destroying renderer - renderer.setTerminalTitle("") - renderer.destroy() - win32FlushInputBuffer() - if (reason) { - const formatted = FormatError(reason) ?? FormatUnknownError(reason) - if (formatted) { - process.stderr.write(formatted + "\n") - } - } - const text = store.get() - if (text) process.stdout.write(text + "\n") - await input.onExit?.() - })() - return task - }, - { - message: store, - }, - ) - process.on("SIGHUP", () => exit()) - return exit - }, + init: (input: { exit: Exit }) => input.exit, }) diff --git a/packages/opencode/src/cli/cmd/tui/event.ts b/packages/opencode/src/cli/cmd/tui/event.ts index bebb1fc6aa61..73412b8778b9 100644 --- a/packages/opencode/src/cli/cmd/tui/event.ts +++ b/packages/opencode/src/cli/cmd/tui/event.ts @@ -1,15 +1,15 @@ -import { BusEvent } from "@/bus/bus-event" import { SessionID } from "@/session/schema" import { PositiveInt } from "@opencode-ai/core/schema" +import { EventV2 } from "@opencode-ai/core/event" import { Effect, Schema } from "effect" const DEFAULT_TOAST_DURATION = 5000 export const TuiEvent = { - PromptAppend: BusEvent.define("tui.prompt.append", Schema.Struct({ text: Schema.String })), - CommandExecute: BusEvent.define( - "tui.command.execute", - Schema.Struct({ + PromptAppend: EventV2.define({ type: "tui.prompt.append", schema: { text: Schema.String } }), + CommandExecute: EventV2.define({ + type: "tui.command.execute", + schema: { command: Schema.Union([ Schema.Literals([ "session.list", @@ -31,23 +31,23 @@ export const TuiEvent = { ]), Schema.String, ]), - }), - ), - ToastShow: BusEvent.define( - "tui.toast.show", - Schema.Struct({ + }, + }), + ToastShow: EventV2.define({ + type: "tui.toast.show", + schema: { title: Schema.optional(Schema.String), message: Schema.String, variant: Schema.Literals(["info", "success", "warning", "error"]), duration: PositiveInt.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_TOAST_DURATION))).annotate({ description: "Duration in milliseconds", }), - }), - ), - SessionSelect: BusEvent.define( - "tui.session.select", - Schema.Struct({ + }, + }), + SessionSelect: EventV2.define({ + type: "tui.session.select", + schema: { sessionID: SessionID.annotate({ description: "Session ID to navigate to" }), - }), - ), + }, + }), } diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/session/dialog.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/dialog.tsx new file mode 100644 index 000000000000..816546b868c3 --- /dev/null +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/dialog.tsx @@ -0,0 +1,335 @@ +import { useDialog } from "@tui/ui/dialog" +import { DialogSelect, type DialogSelectOption, type DialogSelectRef } from "@tui/ui/dialog-select" +import { useRoute } from "@tui/context/route" +import { useSync } from "@tui/context/sync" +import { useProject } from "@tui/context/project" +import { useTheme } from "@tui/context/theme" +import { useSDK } from "@tui/context/sdk" +import { useLocal } from "@tui/context/local" +import { useToast } from "@tui/ui/toast" +import { useCommandShortcut } from "@tui/keymap" +import { createEffect, createMemo, createResource, createSignal, on, onMount, untrack } from "solid-js" +import { Spinner } from "@tui/component/spinner" +import { DialogSessionRename } from "@tui/component/dialog-session-rename" +import { DialogSessionDeleteFailed } from "@tui/component/dialog-session-delete-failed" +import { + openWorkspaceSelect, + type WorkspaceSelection, + warpWorkspaceSession, +} from "@tui/component/dialog-workspace-create" +import { createDebouncedSignal } from "@tui/util/signal" +import { errorMessage } from "@/util/error" +import { SessionPreviewPane, createLeadingTrailingSignal } from "./preview-pane" +import { relativeTime } from "./util" + +export function SessionSwitcherDialog() { + const dialog = useDialog() + const route = useRoute() + const sync = useSync() + const project = useProject() + const { theme } = useTheme() + const sdk = useSDK() + const local = useLocal() + const toast = useToast() + const [toDelete, setToDelete] = createSignal() + const [search, setSearch] = createDebouncedSignal("", 150) + const deleteHint = useCommandShortcut("session.delete") + const quickSwitch1 = useCommandShortcut("session.quick_switch.1") + const quickSwitch9 = useCommandShortcut("session.quick_switch.9") + let select: DialogSelectRef | undefined + + const [searchResults, { refetch }] = createResource( + () => ({ query: search(), filter: sync.session.query() }), + async (input) => { + if (!input.query) return undefined + const result = await sdk.client.session.list({ search: input.query, limit: 30, ...input.filter }) + return result.data ?? [] + }, + ) + + const currentSessionID = createMemo(() => (route.data.type === "session" ? route.data.sessionID : undefined)) + const sessions = createMemo(() => searchResults() ?? sync.data.session) + const [focusedSession, setFocusedSession, scheduleFocused] = createLeadingTrailingSignal( + undefined, + 150, + ) + const focusedSessionInfo = createMemo(() => { + const id = focusedSession() + if (!id) return undefined + return sessions().find((session) => session.id === id) ?? sync.data.session.find((session) => session.id === id) + }) + + function recoverFailed(session: NonNullable[number]>) { + const workspace = project.workspace.get(session.workspaceID!) + const list = () => dialog.replace(() => ) + const warp = async (selection: WorkspaceSelection) => { + const workspaceID = await (async () => { + if (selection.type === "none") return null + if (selection.type === "existing") return selection.workspaceID + const result = await sdk.client.experimental.workspace + .create({ type: selection.workspaceType, branch: null }) + .catch(() => undefined) + const created = result?.data + if (!created) { + toast.show({ + message: `Failed to create workspace: ${errorMessage(result?.error ?? "no response")}`, + variant: "error", + }) + return + } + await project.workspace.sync() + return created.id + })() + if (workspaceID === undefined) return + await warpWorkspaceSession({ + dialog, + sdk, + sync, + project, + toast, + sourceWorkspaceID: session.workspaceID, + workspaceID, + sessionID: session.id, + copyChanges: false, + done: list, + }) + } + dialog.replace(() => ( + { + const current = currentSessionID() + const info = current ? sync.data.session.find((item) => item.id === current) : undefined + const result = await sdk.client.experimental.workspace.remove({ id: session.workspaceID! }) + if (result.error) { + toast.show({ + variant: "error", + title: "Failed to delete workspace", + message: errorMessage(result.error), + }) + return false + } + await project.workspace.sync() + await sync.session.refresh() + if (search()) await refetch() + if (info?.workspaceID === session.workspaceID) { + route.navigate({ type: "home" }) + } + return true + }} + onRestore={() => { + void openWorkspaceSelect({ + dialog, + sdk, + sync, + project, + toast, + onSelect: (selection) => { + void warp(selection) + }, + }) + return false + }} + /> + )) + } + + function orderByRecency(sessionsList: NonNullable>) { + return sessionsList + .filter((x) => x.parentID === undefined) + .toSorted((a, b) => b.time.updated - a.time.updated) + .map((x) => x.id) + } + + const [browseOrder] = createSignal(orderByRecency(sync.data.session)) + + const quickSwitchHint = createMemo(() => { + const first = quickSwitch1() + const last = quickSwitch9() + if (!first || !last) return undefined + return quickSwitchRange(first, last) + }) + const quickSwitchFooterHints = createMemo(() => { + const hint = quickSwitchHint() + return hint && local.session.slots().length > 0 ? [{ title: "switch", label: hint }] : [] + }) + + const options = createMemo[]>(() => { + const today = new Date().toDateString() + const sessionMap = new Map( + sessions() + .filter((x) => x.parentID === undefined) + .map((x) => [x.id, x]), + ) + + const searchResult = searchResults() + const displayOrder = searchResult ? orderByRecency(searchResult) : browseOrder() + + const pinned = local.session.pinned().filter((id) => sessionMap.has(id)) + const pinnedSet = new Set(pinned) + const slotByID = new Map(local.session.slots().map((id, i) => [id, i + 1])) + + function buildOption(id: string, category: string): DialogSelectOption | undefined { + const x = sessionMap.get(id) + if (!x) return undefined + const workspace = x.workspaceID ? project.workspace.get(x.workspaceID) : undefined + + const footer = relativeTime(x.time.updated) + const isWorktree = workspace?.type === "worktree" + + const isDeleting = toDelete() === x.id + const status = sync.data.session_status?.[x.id] + const isWorking = status?.type === "busy" || status?.type === "retry" + const slot = slotByID.get(x.id) + const gutter = isWorking + ? () => + : slot !== undefined + ? () => {slot} + : undefined + const titleText = isDeleting ? `Press ${deleteHint()} again to confirm` : isWorktree ? `⎇ ${x.title}` : x.title + return { + title: titleText, + bg: isDeleting ? theme.error : undefined, + value: x.id, + category, + footer, + gutter, + } + } + + const remaining = displayOrder + .filter((id) => !pinnedSet.has(id)) + .map((id) => { + const x = sessionMap.get(id) + if (!x) return undefined + const label = new Date(x.time.updated).toDateString() + return buildOption(id, label === today ? "Today" : label) + }) + .filter((x): x is DialogSelectOption => x !== undefined) + + return [ + ...pinned.map((id) => buildOption(id, "Pinned")).filter((x): x is DialogSelectOption => x !== undefined), + ...remaining, + ] + }) + + createEffect( + on([options, currentSessionID], ([items, current]) => { + const selected = untrack(() => select?.selected) + const selectedID = selected && items.some((item) => item.value === selected.value) ? selected.value : undefined + const currentID = current && items.some((item) => item.value === current) ? current : undefined + setFocusedSession(selectedID ?? currentID ?? items[0]?.value) + }), + ) + + onMount(() => { + dialog.setSize("xlarge") + }) + + const list = ( + (select = value)} + title="Sessions" + options={options()} + skipFilter={true} + current={currentSessionID()} + onFilter={setSearch} + onMove={(option) => { + setToDelete(undefined) + scheduleFocused(option.value) + }} + onSelect={(option) => { + route.navigate({ + type: "session", + sessionID: option.value, + }) + dialog.clear() + }} + actions={[ + { + command: "session.pin.toggle", + title: "pin/unpin", + onTrigger: (option: { value: string }) => { + local.session.togglePin(option.value) + }, + }, + { + command: "session.delete", + title: "delete", + onTrigger: async (option) => { + if (toDelete() === option.value) { + const session = sessions().find((item) => item.id === option.value) + const status = session?.workspaceID ? project.workspace.status(session.workspaceID) : undefined + + try { + const result = await sdk.client.session.delete({ + sessionID: option.value, + }) + if (result.error) { + if (session?.workspaceID) { + recoverFailed(session) + } else { + toast.show({ + variant: "error", + title: "Failed to delete session", + message: errorMessage(result.error), + }) + } + setToDelete(undefined) + return + } + } catch (err) { + if (session?.workspaceID) { + recoverFailed(session) + } else { + toast.show({ + variant: "error", + title: "Failed to delete session", + message: errorMessage(err), + }) + } + setToDelete(undefined) + return + } + if (status && status !== "connected") { + await sync.session.refresh() + } + if (search()) await refetch() + setToDelete(undefined) + return + } + setToDelete(option.value) + }, + }, + { + command: "session.rename", + title: "rename", + onTrigger: async (option) => { + dialog.replace(() => ) + }, + }, + ]} + footerHints={quickSwitchFooterHints()} + /> + ) + + return ( + + + {list} + + + + + + + ) +} + +function quickSwitchRange(first: string, last: string) { + const prefix = first.slice(0, -1) + if (first.endsWith("1") && last === `${prefix}9`) return `${prefix}1-9` + return `${first} through ${last}` +} diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/session/index.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/index.tsx new file mode 100644 index 000000000000..50055d3bdb3b --- /dev/null +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/index.tsx @@ -0,0 +1,32 @@ +import type { TuiPlugin } from "@opencode-ai/plugin/tui" +import type { InternalTuiPlugin } from "../../plugin/internal" +import { SessionSwitcherDialog } from "./dialog" + +const id = "internal:session-switcher" + +const tui: TuiPlugin = async (api) => { + api.keymap.registerLayer({ + priority: 1000, + commands: [ + { + name: "session.list", + title: "Switch session", + category: "Session", + namespace: "palette", + suggested: () => api.state.session.count() > 0, + slashName: "sessions", + slashAliases: ["resume", "continue"], + run() { + api.ui.dialog.replace(() => ) + }, + }, + ], + }) +} + +const plugin: InternalTuiPlugin = { + id, + tui, +} + +export default plugin diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/session/preview-pane.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/preview-pane.tsx new file mode 100644 index 000000000000..8e75745a6c30 --- /dev/null +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/preview-pane.tsx @@ -0,0 +1,382 @@ +import { createResource, Show, createMemo, createSignal, onMount, type Accessor, type JSX } from "solid-js" +import { TextAttributes, type RGBA } from "@opentui/core" +import { useTerminalDimensions } from "@opentui/solid" +import { debounce, leadingAndTrailing } from "@solid-primitives/scheduled" +import type { Message, Part, Session as SdkSession, SnapshotFileDiff } from "@opencode-ai/sdk/v2" +import { useTheme } from "@tui/context/theme" +import { useSDK } from "@tui/context/sdk" +import { useSync } from "@tui/context/sync" +import { Locale } from "@/util/locale" +import { Spinner } from "@tui/component/spinner" +import { extractMessageMarkdown, extractMessageText, formatDiffSummary, relativeTime, shortModelLabel } from "./util" + +type WithParts = { info: Message; parts: Part[] } + +type Sdk = ReturnType +type Sync = ReturnType + +const messageCache = new Map>() +const diffCache = new Map>() + +function cacheKey(sessionID: string, version: number) { + return `${sessionID}:${version}` +} + +function hydrateFromSync(sync: Sync, sessionID: string): WithParts[] | undefined { + const infos = sync.data.message[sessionID] + if (!infos || infos.length === 0) return undefined + return infos.map((info) => ({ info, parts: sync.data.part[info.id] ?? [] })) +} + +function loadMessages(sdk: Sdk, sessionID: string, version: number): Promise { + const key = cacheKey(sessionID, version) + const cached = messageCache.get(key) + if (cached) return cached + + const promise = sdk.client.session + .messages({ sessionID, limit: 50 }) + .then((res) => { + if (res.error) messageCache.delete(key) + return (res.data as WithParts[] | undefined) ?? [] + }) + .catch(() => { + messageCache.delete(key) + return [] as WithParts[] + }) + messageCache.set(key, promise) + return promise +} + +function loadDiff(sdk: Sdk, sessionID: string, version: number): Promise { + const key = cacheKey(sessionID, version) + const cached = diffCache.get(key) + if (cached) return cached + + const promise = sdk.client.session + .diff({ sessionID }) + .then((res) => { + if (res.error) diffCache.delete(key) + return (res.data as SnapshotFileDiff[] | undefined) ?? [] + }) + .catch(() => { + diffCache.delete(key) + return [] as SnapshotFileDiff[] + }) + diffCache.set(key, promise) + return promise +} + +export function prefetchPreviews(sdk: Sdk, sync: Sync, sessionIDs: readonly string[]) { + for (const id of sessionIDs) { + const version = sync.data.session.find((session) => session.id === id)?.time.updated ?? 0 + if (!hydrateFromSync(sync, id)) loadMessages(sdk, id, version).catch(() => {}) + if (!sync.data.session_diff[id]?.length) loadDiff(sdk, id, version).catch(() => {}) + } +} + +export function createLeadingTrailingSignal(initial: T, ms: number): [Accessor, (v: T) => void, (v: T) => void] { + const [get, set] = createSignal(initial) + const setNow = (v: T) => set(() => v) + const schedule = leadingAndTrailing(debounce, setNow, ms) + return [get, setNow, schedule] +} + +export function SessionPreviewPane(props: { + sessionID: Accessor + session?: Accessor +}) { + const { theme } = useTheme() + const sdk = useSDK() + const sync = useSync() + const dimensions = useTerminalDimensions() + + const maxHeight = createMemo(() => Math.max(8, Math.floor(dimensions().height / 2) - 4)) + const session = createMemo(() => { + const provided = props.session?.() + if (provided) return provided + const id = props.sessionID() + if (!id) return undefined + return sync.data.session.find((s) => s.id === id) + }) + + const status = createMemo(() => { + const id = props.sessionID() + if (!id) return undefined + return sync.data.session_status?.[id]?.type + }) + + onMount(() => { + const top = sync.data.session + .filter((s) => s.parentID === undefined) + .slice() + .sort((a, b) => b.time.updated - a.time.updated) + .slice(0, 5) + .map((s) => s.id) + prefetchPreviews(sdk, sync, top) + }) + + const syncedMessages = createMemo(() => { + const id = props.sessionID() + if (!id) return undefined + return hydrateFromSync(sync, id) + }) + + const syncedDiff = createMemo(() => { + const id = props.sessionID() + if (!id) return undefined + const diff = sync.data.session_diff[id] + return diff && diff.length > 0 ? (diff as SnapshotFileDiff[]) : undefined + }) + + const [fetchedMessages] = createResource( + () => { + const id = props.sessionID() + if (!id || syncedMessages()) return undefined + return { sessionID: id, version: session()?.time.updated ?? 0 } + }, + async (input) => loadMessages(sdk, input.sessionID, input.version), + ) + + const [fetchedDiff] = createResource( + () => { + const id = props.sessionID() + if (!id || syncedDiff()) return undefined + return { sessionID: id, version: session()?.time.updated ?? 0 } + }, + async (input) => loadDiff(sdk, input.sessionID, input.version), + ) + + const messages = createMemo(() => syncedMessages() ?? fetchedMessages() ?? []) + const diff = createMemo(() => syncedDiff() ?? fetchedDiff() ?? []) + + const diffSummary = createMemo(() => { + const live = diff() + if (live && live.length > 0) { + let additions = 0 + let deletions = 0 + for (const file of live) { + additions += file.additions ?? 0 + deletions += file.deletions ?? 0 + } + return formatDiffSummary({ additions, deletions, files: live.length }) + } + return formatDiffSummary(session()?.summary) + }) + + const exchange = createMemo(() => { + const items = messages() + if (!items || items.length === 0) return undefined + const sorted = items.toSorted((a, b) => messageCreated(a) - messageCreated(b)) + const user = sorted.findLast((item) => messageRole(item) === "user") + const assistant = user + ? sorted.findLast((item) => messageRole(item) === "assistant" && messageParentID(item) === user.info.id) + : sorted.findLast((item) => messageRole(item) === "assistant") + return { user, assistant } + }) + + const loading = createMemo(() => (fetchedMessages.loading || fetchedDiff.loading) && !exchange()) + + const statusLabel = createMemo(() => { + const s = status() + if (s === "busy") return { text: "working", color: theme.warning } + if (s === "retry") return { text: "retrying", color: theme.warning } + return { text: "idle", color: theme.textMuted } + }) + + return ( + + + No session selected + + } + > + {(s) => ( + <> +
+ + loading preview... + + + + No messages yet + + + } + > + {(ex) => } + + + )} + + + ) +} + +function messageRole(item: WithParts) { + return (item.info as { role?: string }).role +} + +function messageCreated(item: WithParts) { + return (item.info.time as { created?: number }).created ?? 0 +} + +function messageParentID(item: WithParts) { + return (item.info as { parentID?: string }).parentID +} + +const ROW_WIDTH = 40 + +function Header(props: { + session: SdkSession + statusLabel: { text: string; color: RGBA } + diff: { additions: number; deletions: number; files: number } | undefined +}) { + const { theme } = useTheme() + const title = createMemo(() => Locale.truncate(props.session.title, ROW_WIDTH)) + const modelAgent = createMemo(() => { + const m = shortModelLabel(props.session.model) + const a = props.session.agent ?? "" + if (m && a) return Locale.truncate(`${m} · ${a}`, ROW_WIDTH) + if (m) return Locale.truncate(m, ROW_WIDTH) + if (a) return Locale.truncate(a, ROW_WIDTH) + return "" + }) + const statusRest = createMemo(() => { + const joined = ` · ${relativeTime(props.session.time.updated)}` + return Locale.truncate(joined, Math.max(0, ROW_WIDTH - props.statusLabel.text.length)) + }) + + return ( + + + + {title()} + + + + + + {modelAgent()} + + + + + + {props.statusLabel.text} + {statusRest()} + + + {(d) => } + + ) +} + +function Row(props: { height: number; children: JSX.Element }) { + return ( + + {props.children} + + ) +} + +function DiffRow(props: { diff: { additions: number; deletions: number; files: number } }) { + const { theme } = useTheme() + const showAdds = () => props.diff.additions > 0 + const showDels = () => props.diff.deletions > 0 + if (!showAdds() && !showDels()) return null + return ( + + + + +{props.diff.additions} + + + + + + −{props.diff.deletions} + + + + ) +} + +const PROMPT_MAX_CHARS = 240 +const REPLY_MAX_LINES = 12 +const REPLY_MAX_CHARS = 800 + +function Exchange(props: { exchange: { user?: WithParts; assistant?: WithParts } }) { + const { theme, syntax } = useTheme() + const userText = createMemo(() => + props.exchange.user ? extractMessageText(props.exchange.user.parts, PROMPT_MAX_CHARS) : undefined, + ) + const assistantMarkdown = createMemo(() => + props.exchange.assistant + ? extractMessageMarkdown(props.exchange.assistant.parts, REPLY_MAX_LINES, REPLY_MAX_CHARS) + : undefined, + ) + + return ( + + + + + {userText()!} + + + + + + + + + + ) +} + +function NonTextHint(props: { exchange: { user?: WithParts; assistant?: WithParts } }) { + const { theme } = useTheme() + const summary = createMemo(() => { + const counts: Record = {} + for (const item of [props.exchange.user, props.exchange.assistant]) { + if (!item) continue + for (const part of item.parts) { + counts[part.type] = (counts[part.type] ?? 0) + 1 + } + } + return Object.entries(counts) + .map(([k, n]) => `${n} ${k}`) + .join(", ") + }) + return ( + + + Latest exchange has no text content ({summary()}) + + + ) +} diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/session/util.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/util.tsx new file mode 100644 index 000000000000..4323602ab73f --- /dev/null +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/session/util.tsx @@ -0,0 +1,70 @@ +import type { Part } from "@opencode-ai/sdk/v2" +import { Locale } from "@/util/locale" + +export function relativeTime(timestamp: number): string { + const diff = Date.now() - timestamp + if (diff < 0) return "just now" + const seconds = Math.floor(diff / 1000) + if (seconds < 60) return "just now" + const minutes = Math.floor(seconds / 60) + if (minutes < 60) return `${minutes}m ago` + const hours = Math.floor(minutes / 60) + if (hours < 24) return `${hours}h ago` + const days = Math.floor(hours / 24) + if (days < 7) return `${days}d ago` + const d = new Date(timestamp) + return d.toLocaleDateString(undefined, { month: "short", day: "numeric" }) +} + +export function extractMessageText(parts: readonly Part[], maxLength: number): string { + const joined = collectTextParts(parts).join(" ").replace(/\s+/g, " ").trim() + return Locale.truncate(joined, maxLength) +} + +export function extractMessageMarkdown(parts: readonly Part[], maxLines: number, maxChars: number): string { + const joined = collectTextParts(parts).join("\n\n").trim() + if (!joined) return joined + + let truncated = joined + const lines = truncated.split("\n") + if (lines.length > maxLines) { + truncated = lines.slice(0, maxLines).join("\n") + } + if (truncated.length > maxChars) { + truncated = truncated.slice(0, maxChars).trimEnd() + } + if (truncated.length === joined.length) return joined + // Close any unterminated fenced code block so the renderer doesn't keep + // the rest of the panel in "code mode". + const fences = (truncated.match(/^```/gm) ?? []).length + if (fences % 2 === 1) truncated += "\n```" + return truncated + "\n\n…" +} + +function collectTextParts(parts: readonly Part[]): string[] { + const chunks: string[] = [] + for (const part of parts) { + if (part.type !== "text") continue + const p = part as Part & { type: "text"; text: string; synthetic?: boolean; ignored?: boolean } + if (p.synthetic || p.ignored) continue + if (!p.text) continue + chunks.push(p.text) + } + return chunks +} + +export function formatDiffSummary( + summary: { additions: number; deletions: number; files: number } | undefined, +): { additions: number; deletions: number; files: number } | undefined { + if (!summary) return undefined + if (!summary.additions && !summary.deletions && !summary.files) return undefined + return summary +} + +export function shortModelLabel(model: { id: string; providerID?: string; variant?: string } | undefined): string { + if (!model) return "" + const id = model.id ?? "" + const stripped = + model.providerID && id.startsWith(`${model.providerID}/`) ? id.slice(model.providerID.length + 1) : id + return model.variant ? `${stripped} (${model.variant})` : stripped +} diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/system/diff-viewer.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/system/diff-viewer.tsx index 924bbd7eb312..614408bcecee 100644 --- a/packages/opencode/src/cli/cmd/tui/feature-plugins/system/diff-viewer.tsx +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/system/diff-viewer.tsx @@ -11,6 +11,7 @@ import { createEffect, createMemo, createResource, createSignal, For, Match, onC import { DiffViewerFileTree } from "./diff-viewer-file-tree" import { Panel, PanelGroup, Separator } from "./diff-viewer-ui" import { DialogSelect } from "@tui/ui/dialog-select" +import { getScrollAcceleration } from "@tui/util/scroll" import { allExpandedFileTreeDirectories, buildFileTree, @@ -133,6 +134,7 @@ function DiffViewer(props: { api: TuiPluginApi }) { const [activePatchFileIndex, setActivePatchFileIndex] = createSignal() const [selectedFileIndex, setSelectedFileIndex] = createSignal() const [reviewedFileNames, setReviewedFileNames] = createSignal>(new Set()) + const patchScrollAcceleration = createMemo(() => getScrollAcceleration(props.api.tuiConfig)) const fileRows = createMemo(() => flattenFileTree(fileTree(), expandedFileNodes())) const patchFileIndexes = createMemo(() => orderedPatchFileIndexes(flattenFileTree(fileTree()))) const focusRunner = (input: Record void>) => () => input[focus()]() @@ -713,6 +715,7 @@ function DiffViewer(props: { api: TuiPluginApi }) { ref={(element: ScrollBoxRenderable) => (scroll = element)} flexGrow={1} minHeight={0} + scrollAcceleration={patchScrollAcceleration()} verticalScrollbarOptions={{ visible: false }} horizontalScrollbarOptions={{ visible: false }} > diff --git a/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx b/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx index 8b9b088805cc..8b2b2ed37b28 100644 --- a/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx +++ b/packages/opencode/src/cli/cmd/tui/feature-plugins/system/session-v2.tsx @@ -442,16 +442,25 @@ function ReasoningHeader(props: { toggleable: boolean; open: boolean; done: bool : theme.warning return ( - - - {props.open ? "- " : "+ "} - - {props.done ? "Thought" : "Thinking"} - - : - {props.title} - - + + + + {props.title ? "Thinking: " + props.title : "Thinking"} + + + + + + {props.open ? "- " : "+ "} + + Thought + + : + {props.title} + + + + ) } diff --git a/packages/opencode/src/cli/cmd/tui/keymap.tsx b/packages/opencode/src/cli/cmd/tui/keymap.tsx index d8489fd2f73e..461b204a2058 100644 --- a/packages/opencode/src/cli/cmd/tui/keymap.tsx +++ b/packages/opencode/src/cli/cmd/tui/keymap.tsx @@ -1,4 +1,4 @@ -import { type CliRenderer } from "@opentui/core" +import { InputRenderable, TextareaRenderable, type CliRenderer } from "@opentui/core" import * as addons from "@opentui/keymap/addons/opentui" import { stringifyKeyStroke } from "@opentui/keymap" import { @@ -31,6 +31,7 @@ type CommandSlashEntry = { onSelect: () => void } type Command = ReturnType[number] +type FormatConfig = Pick const modeStacks = new WeakMap() @@ -160,13 +161,22 @@ const inputCommands = [ "input.submit", ] as const -function leaderDisplay(config: TuiConfig.Resolved) { +function hasManagedTextareaFocus(renderer: CliRenderer) { + const editor = renderer.currentFocusedEditor + return editor instanceof TextareaRenderable && !(editor instanceof InputRenderable) +} + +function leaderDisplay(config: FormatConfig) { const key = config.keybinds.get(LEADER_TOKEN)?.[0]?.key if (!key) return TuiKeybind.LeaderDefault return typeof key === "string" ? key : stringifyKeyStroke(key) } -function formatOptions(config: TuiConfig.Resolved) { +function leaderKey(config: FormatConfig) { + return config.keybinds.get(LEADER_TOKEN)?.[0]?.key +} + +function formatOptions(config: FormatConfig) { return { tokenDisplay: { [LEADER_TOKEN]: leaderDisplay(config), @@ -182,14 +192,11 @@ function formatOptions(config: TuiConfig.Resolved) { } as const } -export function formatKeySequence(parts: Parameters[0], config: TuiConfig.Resolved) { +export function formatKeySequence(parts: Parameters[0], config: FormatConfig) { return formatKeySequenceExtra(parts, formatOptions(config)) } -export function formatKeyBindings( - bindings: Parameters[0], - config: TuiConfig.Resolved, -) { +export function formatKeyBindings(bindings: Parameters[0], config: FormatConfig) { return formatCommandBindingsExtra(bindings, formatOptions(config)) } @@ -202,15 +209,18 @@ export function registerOpencodeKeymap( const offCommaBindings = addons.registerCommaBindings(keymap) const offAliasExpander = registerKeyAliases(keymap) const offBaseLayout = addons.registerBaseLayoutFallback(keymap) - const offLeader = addons.registerTimedLeader(keymap, { - trigger: config.keybinds.get(LEADER_TOKEN), - name: LEADER_TOKEN, - timeoutMs: config.leader_timeout, - }) + const leader = leaderKey(config) + const offLeader = leader + ? addons.registerTimedLeader(keymap, { + trigger: leader, + name: LEADER_TOKEN, + timeoutMs: config.leader_timeout, + }) + : () => {} const offEscape = addons.registerEscapeClearsPendingSequence(keymap) const offBackspace = addons.registerBackspacePopsPendingSequence(keymap) const offInputBindings = addons.registerManagedTextareaLayer(keymap, renderer, { - enabled: () => renderer.currentFocusedEditor !== null, + enabled: () => hasManagedTextareaFocus(renderer), bindings: config.keybinds.gather("input", inputCommands), }) diff --git a/packages/opencode/src/cli/cmd/tui/plugin/internal.ts b/packages/opencode/src/cli/cmd/tui/plugin/internal.ts index d85b38c569fa..0180ea69d2fd 100644 --- a/packages/opencode/src/cli/cmd/tui/plugin/internal.ts +++ b/packages/opencode/src/cli/cmd/tui/plugin/internal.ts @@ -11,6 +11,8 @@ import Notifications from "../feature-plugins/system/notifications" import SessionV2Debug from "../feature-plugins/system/session-v2" import WhichKey from "../feature-plugins/system/which-key" import DiffViewer from "../feature-plugins/system/diff-viewer" +import SessionSwitcher from "../feature-plugins/session" +import { Flag } from "@opencode-ai/core/flag/flag" import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui" import type { RuntimeFlags } from "@/effect/runtime-flags" @@ -35,5 +37,6 @@ export function internalTuiPlugins(flags: Pick permissions().length > 0 || questions().length > 0) const pending = createMemo(() => { - return messages().findLast((x) => x.role === "assistant" && !x.time.completed)?.id + const completed = messages().findLast((x) => x.role === "assistant" && x.time.completed)?.id + return messages().findLast((x) => x.role === "assistant" && !x.time.completed && (!completed || x.id > completed)) + ?.id }) const lastAssistant = createMemo(() => { @@ -409,15 +417,19 @@ export function Session() { const local = useLocal() + function enterChild(sessionID: string) { + navigate({ + type: "session", + sessionID, + }) + const status = sync.data.session_status[sessionID] + if (status?.type === "retry") void DialogAlert.show(dialog, "Retry Error", status.message) + } + function moveFirstChild() { if (children().length === 1) return const next = children().find((x) => !!x.parentID) - if (next) { - navigate({ - type: "session", - sessionID: next.id, - }) - } + if (next) enterChild(next.id) } function moveChild(direction: number) { @@ -428,12 +440,7 @@ export function Session() { if (next >= sessions.length) next = 0 if (next < 0) next = sessions.length - 1 - if (sessions[next]) { - navigate({ - type: "session", - sessionID: sessions[next].id, - }) - } + if (sessions[next]) enterChild(sessions[next].id) } function childSessionHandler(func: () => void) { @@ -968,7 +975,10 @@ export function Session() { await Editor.open({ value: transcript, renderer, - cwd: project.instance.path().worktree || project.instance.directory() || process.cwd(), + cwd: + (project.instance.path().worktree === "/" ? undefined : project.instance.path().worktree) || + project.instance.directory() || + process.cwd(), }) } else { const exportDir = process.cwd() @@ -981,7 +991,10 @@ export function Session() { const result = await Editor.open({ value: transcript, renderer, - cwd: project.instance.path().worktree || project.instance.directory() || process.cwd(), + cwd: + (project.instance.path().worktree === "/" ? undefined : project.instance.path().worktree) || + project.instance.directory() || + process.cwd(), }) if (result !== undefined) { await Filesystem.write(filepath, result) @@ -1001,8 +1014,8 @@ export function Session() { category: "Session", hidden: true, run: () => { - moveFirstChild() dialog.clear() + moveFirstChild() }, }, { @@ -1029,8 +1042,8 @@ export function Session() { hidden: true, enabled: !!session()?.parentID, run: childSessionHandler(() => { - moveChild(1) dialog.clear() + moveChild(1) }), }, { @@ -1040,8 +1053,8 @@ export function Session() { hidden: true, enabled: !!session()?.parentID, run: childSessionHandler(() => { - moveChild(-1) dialog.clear() + moveChild(-1) }), }, ]) @@ -1061,6 +1074,15 @@ export function Session() { commands: sessionCommands(), })) + useBindings(() => ({ + bindings: tuiConfig.keybinds.gather("session.global", sessionGlobalBindingCommands), + })) + + useBindings(() => ({ + enabled: () => renderer.currentFocusedEditor === null, + bindings: tuiConfig.keybinds.gather("session.global.unfocused", sessionGlobalUnfocusedBindingCommands), + })) + useBindings(() => ({ mode: OPENCODE_BASE_MODE, bindings: tuiConfig.keybinds.gather("session", sessionBindingCommands), @@ -1504,6 +1526,8 @@ const PART_MAPPING = { reasoning: ReasoningPart, } +const INLINE_TOOL_ICON_WIDTH = 2 + function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: AssistantMessage }) { const { theme } = useTheme() const ctx = use() @@ -1575,24 +1599,33 @@ function ReasoningHeader(props: { : theme.warning return ( - - - {props.open ? "- " : "+ "} - - {props.done ? "Thought" : "Thinking"} - - : - - - {props.title} - - - - {props.title ? " · " : ""} - {props.duration} - - - + + + + {props.title ? "Thinking: " + props.title : "Thinking"} + + + + + + {props.open ? "- " : "+ "} + + Thought + + : + + + {props.title} + + + + {props.title ? " · " : ""} + {props.duration} + + + + + ) } @@ -1752,6 +1785,7 @@ function GenericTool(props: ToolProps) { function InlineTool(props: { icon: string iconColor?: RGBA + color?: RGBA complete: any pending: string spinner?: boolean @@ -1759,12 +1793,12 @@ function InlineTool(props: { part: ToolPart onClick?: () => void }) { - const [margin, setMargin] = createSignal(0) const { theme } = useTheme() const ctx = use() const sync = useSync() const renderer = useRenderer() const [hover, setHover] = createSignal(false) + const [errorExpanded, setErrorExpanded] = createSignal(false) const permission = createMemo(() => { const callID = sync.data.permission[ctx.sessionID]?.at(0)?.tool?.callID @@ -1772,13 +1806,6 @@ function InlineTool(props: { return callID === props.part.callID }) - const fg = createMemo(() => { - if (permission()) return theme.warning - if (hover() && props.onClick) return theme.text - if (props.complete) return theme.textMuted - return theme.text - }) - const error = createMemo(() => (props.part.state.status === "error" ? props.part.state.error : undefined)) const denied = createMemo( @@ -1789,53 +1816,134 @@ function InlineTool(props: { error()?.includes("user dismissed"), ) + const failed = createMemo(() => Boolean(error() && !denied())) + const clickable = createMemo(() => Boolean(props.onClick || failed())) + const fg = createMemo(() => { + if (props.color) return props.color + if (permission()) return theme.warning + if (failed()) return theme.error + if (hover() && props.onClick) return theme.text + if (props.complete) return theme.textMuted + return theme.text + }) + return ( - props.onClick && setHover(true)} + + sync.data.message[ctx.sessionID]?.some((message) => message.role === "user" && message.id === id) ?? false + } + onMouseOver={() => clickable() && setHover(true)} onMouseOut={() => setHover(false)} onMouseUp={() => { if (renderer.getSelection()?.getSelectedText()) return + if (failed()) { + setErrorExpanded((value) => !value) + return + } props.onClick?.() }} + > + {props.children} + + ) +} + +export function InlineToolRow(props: { + icon: string + iconColor?: RGBA + color?: RGBA + errorColor?: RGBA + failed?: boolean + denied?: boolean + error?: string + errorExpanded?: boolean + complete: any + pending: string + spinner?: boolean + children: JSX.Element + separateAfter?: (id: string | undefined) => boolean + onMouseOver?: () => void + onMouseOut?: () => void + onMouseUp?: () => void +}) { + const [margin, setMargin] = createSignal(0) + + return ( + 1) { - setMargin(1) - return - } const children = parent.getChildren() const index = children.indexOf(el) const previous = children[index - 1] - if (!previous) { - setMargin(0) - return - } - if (previous.height > 1 || previous.id.startsWith("text-")) { - setMargin(1) - return - } + setMargin( + previous?.id.startsWith("text-") || + previous?.id.startsWith("tool-block-") || + props.separateAfter?.(previous?.id) + ? 1 + : 0, + ) }} > - + - - ~ {props.pending}} when={props.complete}> - {props.icon} {props.children} - - + + ~ {props.pending} + + } + when={props.complete} + > + + + {props.icon} + + + {props.children} + + + - - {error()} + + + {props.error} + ) @@ -1854,6 +1962,7 @@ function BlockTool(props: { const error = createMemo(() => (props.part?.state.status === "error" ? props.part.state.error : undefined)) return ( ) { } function Task(props: ToolProps) { + const { theme } = useTheme() const { navigate } = useRoute() const sync = useSync() + const dialog = useDialog() onMount(() => { if (props.metadata.sessionId && !sync.data.message[props.metadata.sessionId]?.length) @@ -2080,6 +2191,11 @@ function Task(props: ToolProps) { ) const isRunning = createMemo(() => props.part.state.status === "running") + const retry = createMemo(() => { + const status = sync.data.session_status[props.metadata.sessionId ?? ""] + if (status?.type !== "retry") return + return status + }) const duration = createMemo(() => { const first = messages().find((x) => x.role === "user")?.time.created @@ -2094,7 +2210,10 @@ function Task(props: ToolProps) { props.metadata.background === true ? `${props.input.description} (background)` : props.input.description let content = [`${Locale.titlecase(props.input.subagent_type ?? "General")} Task — ${description}`] - if (isRunning() && tools().length > 0) { + const retrying = retry() + if (isRunning() && retrying) { + content.push(`↳ ${Locale.truncate(retrying.message, 80)} [retrying attempt #${retrying.attempt}]`) + } else if (isRunning() && tools().length > 0) { // content[0] += ` · ${tools().length} toolcalls` if (current()) { const state = current()!.state @@ -2117,6 +2236,7 @@ function Task(props: ToolProps) { return ( ) { if (props.metadata.sessionId) { navigate({ type: "session", sessionID: props.metadata.sessionId }) } + const status = retry() + if (status) void DialogAlert.show(dialog, "Retry Error", status.message) }} > {content()} diff --git a/packages/opencode/src/cli/cmd/tui/thread.ts b/packages/opencode/src/cli/cmd/tui/thread.ts index 7230dae16ae4..382147d918f5 100644 --- a/packages/opencode/src/cli/cmd/tui/thread.ts +++ b/packages/opencode/src/cli/cmd/tui/thread.ts @@ -228,9 +228,11 @@ export const TuiThreadCommand = cmd({ }, 1000).unref?.() try { - const { tui } = await import("./app") - await tui({ + const { createTuiRenderer, tui } = await import("./app") + const renderer = await createTuiRenderer(config) + const handle = tui({ url: transport.url, + renderer, async onSnapshot() { const tui = writeHeapSnapshot("tui.heapsnapshot") const server = await client.call("snapshot", undefined) @@ -249,6 +251,7 @@ export const TuiThreadCommand = cmd({ fork: args.fork, }, }) + await handle.done } finally { await stop() } diff --git a/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx b/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx index 700735d38cbf..464615e48635 100644 --- a/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx +++ b/packages/opencode/src/cli/cmd/tui/ui/dialog-select.tsx @@ -51,6 +51,7 @@ export interface DialogSelectOption { title: string value: T description?: string + details?: string[] footer?: JSX.Element | string category?: string categoryView?: JSX.Element @@ -64,6 +65,7 @@ export interface DialogSelectOption { export type DialogSelectRef = { filter: string filtered: DialogSelectOption[] + selected: DialogSelectOption | undefined } export function DialogSelect(props: DialogSelectProps) { @@ -167,7 +169,7 @@ export function DialogSelect(props: DialogSelectProps) { if (!category) return acc return acc + (i > 0 ? 2 : 1) }, 0) - return flat().length + headers + return flat().reduce((acc, option) => acc + 1 + (option.details?.length ?? 0), headers) }) const dimensions = useTerminalDimensions() @@ -336,6 +338,9 @@ export function DialogSelect(props: DialogSelectProps) { get filtered() { return filtered() }, + get selected() { + return selected() + }, } props.ref?.(ref) @@ -349,7 +354,7 @@ export function DialogSelect(props: DialogSelectProps) { const right = createMemo(() => visibleActions().filter((item) => item.side === "right")) return ( - + @@ -386,93 +391,108 @@ export function DialogSelect(props: DialogSelectProps) { - 0} - fallback={ - - No results found - - } - > - (scroll = r)} - maxHeight={height()} + + 0} + fallback={ + + No results found + + } > - - {([category, options], index) => ( - <> - - 0 ? 1 : 0} paddingLeft={3}> - - {category} - - } - > - {options[0]?.categoryView} - - - - - {(option) => { - const active = createMemo(() => isDeepEqual(option.value, selected()?.value)) - const current = createMemo(() => isDeepEqual(option.value, props.current)) - return ( - { - setStore("input", "mouse") - }} - onMouseUp={() => { - option.onSelect?.(dialog) - props.onSelect?.(option) - }} - onMouseOver={() => { - if (store.input !== "mouse") return - const index = flat().findIndex((x) => isDeepEqual(x.value, option.value)) - if (index === -1) return - moveTo(index) - }} - onMouseDown={() => { - const index = flat().findIndex((x) => isDeepEqual(x.value, option.value)) - if (index === -1) return - moveTo(index) - }} - backgroundColor={active() ? (option.bg ?? theme.primary) : RGBA.fromInts(0, 0, 0, 0)} - paddingLeft={current() || option.gutter ? 1 : 3} - paddingRight={3} - gap={1} + (scroll = r)} + maxHeight={height()} + > + + {([category, options], index) => ( + <> + + 0 ? 1 : 0} paddingLeft={3}> + + {category} + + } > - - - {option.margin} + {options[0]?.categoryView} + + + + + {(option) => { + const active = createMemo(() => isDeepEqual(option.value, selected()?.value)) + const current = createMemo(() => isDeepEqual(option.value, props.current)) + return ( + { + setStore("input", "mouse") + }} + onMouseUp={() => { + option.onSelect?.(dialog) + props.onSelect?.(option) + }} + onMouseOver={() => { + if (store.input !== "mouse") return + const index = flat().findIndex((x) => isDeepEqual(x.value, option.value)) + if (index === -1) return + moveTo(index) + }} + onMouseDown={() => { + const index = flat().findIndex((x) => isDeepEqual(x.value, option.value)) + if (index === -1) return + moveTo(index) + }} + > + + + + {option.margin} + + + - - - ) - }} - - - )} - - - + + {(detail) => ( + + + {Locale.truncateMiddle(detail, Math.max(1, Math.min(76, dimensions().width - 12)))} + + + )} + + + ) + }} + + + )} + + + + }> -export type ToastOptions = Schema.Schema.Type +type ToastInput = Schema.Codec.Encoded +export type ToastOptions = Schema.Schema.Type -const decodeToastOptions = Schema.decodeUnknownSync(TuiEvent.ToastShow.properties) +const decodeToastOptions = Schema.decodeUnknownSync(TuiEvent.ToastShow.data) export function Toast() { const toast = useToast() diff --git a/packages/opencode/src/command/index.ts b/packages/opencode/src/command/index.ts index 96e171733df0..6ef2ab780dc2 100644 --- a/packages/opencode/src/command/index.ts +++ b/packages/opencode/src/command/index.ts @@ -1,4 +1,3 @@ -import { BusEvent } from "@/bus/bus-event" import { InstanceState } from "@/effect/instance-state" import { EffectBridge } from "@/effect/bridge" import type { InstanceContext } from "@/project/instance-context" @@ -7,6 +6,7 @@ import { Effect, Layer, Context, Schema } from "effect" import { Config } from "@/config/config" import { MCP } from "../mcp" import { Skill } from "../skill" +import { EventV2 } from "@opencode-ai/core/event" import PROMPT_INITIALIZE from "./template/initialize.txt" import PROMPT_REVIEW from "./template/review.txt" @@ -15,15 +15,15 @@ type State = { } export const Event = { - Executed: BusEvent.define( - "command.executed", - Schema.Struct({ + Executed: EventV2.define({ + type: "command.executed", + schema: { name: Schema.String, sessionID: SessionID, arguments: Schema.String, messageID: MessageID, - }), - ), + }, + }), } export const Info = Schema.Struct({ diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index 307b02ca4d9f..8dc8c6ee54a8 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -43,6 +43,7 @@ import { ConfigSkills } from "./skills" import { ConfigVariable } from "./variable" import { Npm } from "@opencode-ai/core/npm" import { withTransientReadRetry } from "@/util/effect-http-client" +import { ConfigExperimental } from "@opencode-ai/core/config/experimental" const log = Log.create({ service: "config" }) @@ -301,6 +302,9 @@ export const Info = Schema.Struct({ mcp_timeout: Schema.optional(PositiveInt).annotate({ description: "Timeout in milliseconds for model context protocol (MCP) requests", }), + policies: Schema.optional(Schema.mutable(Schema.Array(ConfigExperimental.Policy))).annotate({ + description: "Policy statements applied to supported resources, such as provider access", + }), }), ), }).annotate({ identifier: "Config" }) @@ -762,7 +766,14 @@ export const layer = Layer.effect( result.permission = mergeDeep(perms, result.permission ?? {}) } - if (!result.username) result.username = os.userInfo().username + if (!result.username) { + try { + result.username = os.userInfo().username || "user" + } catch (err) { + log.warn("failed to read system username, using fallback", { err }) + result.username = "user" + } + } if (result.autoshare === true && !result.share) { result.share = "auto" diff --git a/packages/opencode/src/config/managed.ts b/packages/opencode/src/config/managed.ts index 5b0488420867..c5348afaf716 100644 --- a/packages/opencode/src/config/managed.ts +++ b/packages/opencode/src/config/managed.ts @@ -46,7 +46,14 @@ export function parseManagedPlist(json: string): string { export async function readManagedPreferences() { if (process.platform !== "darwin") return - const user = os.userInfo().username + const user = (() => { + try { + return os.userInfo().username || "user" + } catch (err) { + log.warn("failed to read system username, using fallback", { err }) + return "user" + } + })() const paths = [ path.join("/Library/Managed Preferences", user, `${MANAGED_PLIST_DOMAIN}.plist`), path.join("/Library/Managed Preferences", `${MANAGED_PLIST_DOMAIN}.plist`), diff --git a/packages/opencode/src/config/provider.ts b/packages/opencode/src/config/provider.ts index 5635512cedf9..a7b6fefc5b21 100644 --- a/packages/opencode/src/config/provider.ts +++ b/packages/opencode/src/config/provider.ts @@ -44,8 +44,10 @@ export const Model = Schema.Struct({ ), modalities: Schema.optional( Schema.Struct({ - input: Schema.mutable(Schema.Array(Schema.Literals(["text", "audio", "image", "video", "pdf"]))), - output: Schema.mutable(Schema.Array(Schema.Literals(["text", "audio", "image", "video", "pdf"]))), + input: Schema.optional(Schema.mutable(Schema.Array(Schema.Literals(["text", "audio", "image", "video", "pdf"])))), + output: Schema.optional( + Schema.mutable(Schema.Array(Schema.Literals(["text", "audio", "image", "video", "pdf"]))), + ), }), ), experimental: Schema.optional(Schema.Boolean), @@ -88,13 +90,20 @@ export const Info = Schema.Struct({ description: "Enable promptCacheKey for this provider (default false)", }), timeout: Schema.optional( + Schema.Union([PositiveInt, Schema.Literal(false)]).annotate({ + description: "Timeout in milliseconds for full requests to this provider. Set to false to disable timeout.", + }), + ).annotate({ + description: "Timeout in milliseconds for full requests to this provider. Set to false to disable timeout.", + }), + headerTimeout: Schema.optional( Schema.Union([PositiveInt, Schema.Literal(false)]).annotate({ description: - "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.", + "Timeout in milliseconds to wait for response headers. Provider integrations may set defaults. Set to false to disable timeout.", }), ).annotate({ description: - "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.", + "Timeout in milliseconds to wait for response headers. Provider integrations may set defaults. Set to false to disable timeout.", }), chunkTimeout: Schema.optional(PositiveInt).annotate({ description: diff --git a/packages/opencode/src/control-plane/adapters/index.ts b/packages/opencode/src/control-plane/adapters/index.ts index e5fa13714bc7..0b052f5c9152 100644 --- a/packages/opencode/src/control-plane/adapters/index.ts +++ b/packages/opencode/src/control-plane/adapters/index.ts @@ -1,4 +1,4 @@ -import type { ProjectID } from "@/project/schema" +import type { ProjectV2 } from "@opencode-ai/core/project" import type { WorkspaceAdapter, WorkspaceAdapterEntry } from "../types" import { WorktreeAdapter } from "./worktree" @@ -6,9 +6,9 @@ const BUILTIN: Record = { worktree: WorktreeAdapter, } -const state = new Map>() +const state = new Map>() -export function getAdapter(projectID: ProjectID, type: string): WorkspaceAdapter { +export function getAdapter(projectID: ProjectV2.ID, type: string): WorkspaceAdapter { const custom = state.get(projectID)?.get(type) if (custom) return custom @@ -18,7 +18,7 @@ export function getAdapter(projectID: ProjectID, type: string): WorkspaceAdapter throw new Error(`Unknown workspace adapter: ${type}`) } -export function listAdapters(projectID: ProjectID): WorkspaceAdapterEntry[] { +export function listAdapters(projectID: ProjectV2.ID): WorkspaceAdapterEntry[] { return registeredAdapters(projectID).map(([type, adapter]) => ({ type, name: adapter.name, @@ -26,15 +26,15 @@ export function listAdapters(projectID: ProjectID): WorkspaceAdapterEntry[] { })) } -export function registeredAdapters(projectID: ProjectID): [string, WorkspaceAdapter][] { +export function registeredAdapters(projectID: ProjectV2.ID): [string, WorkspaceAdapter][] { const adapters = new Map(Object.entries(BUILTIN)) for (const [type, adapter] of state.get(projectID)?.entries() ?? []) adapters.set(type, adapter) return [...adapters.entries()] } // Plugins can be loaded per-project so we need to scope them. If you -// want to install a global one pass `ProjectID.global` -export function registerAdapter(projectID: ProjectID, type: string, adapter: WorkspaceAdapter) { +// want to install a global one pass `ProjectV2.ID.global` +export function registerAdapter(projectID: ProjectV2.ID, type: string, adapter: WorkspaceAdapter) { const adapters = state.get(projectID) ?? new Map() adapters.set(type, adapter) state.set(projectID, adapters) diff --git a/packages/opencode/src/control-plane/schema.ts b/packages/opencode/src/control-plane/schema.ts deleted file mode 100644 index 1954543f4afe..000000000000 --- a/packages/opencode/src/control-plane/schema.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Schema } from "effect" - -import { Identifier } from "@/id/id" -import { withStatics } from "@opencode-ai/core/schema" - -const workspaceIdSchema = Schema.String.check(Schema.isStartsWith("wrk")).pipe(Schema.brand("WorkspaceID")) - -export type WorkspaceID = typeof workspaceIdSchema.Type - -export const WorkspaceID = workspaceIdSchema.pipe( - withStatics((schema: typeof workspaceIdSchema) => ({ - ascending: (id?: string) => schema.make(Identifier.ascending("workspace", id)), - })), -) diff --git a/packages/opencode/src/control-plane/types.ts b/packages/opencode/src/control-plane/types.ts index daa837453029..f54a878dbdae 100644 --- a/packages/opencode/src/control-plane/types.ts +++ b/packages/opencode/src/control-plane/types.ts @@ -1,17 +1,17 @@ import { Schema, Struct } from "effect" -import { ProjectID } from "@/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import type { InstanceContext } from "@/project/instance-context" -import { WorkspaceID } from "./schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import type { DeepMutable } from "@opencode-ai/core/schema" export const WorkspaceInfo = Schema.Struct({ - id: WorkspaceID, + id: WorkspaceV2.ID, type: Schema.String, name: Schema.String, branch: Schema.optional(Schema.NullOr(Schema.String)), directory: Schema.optional(Schema.NullOr(Schema.String)), extra: Schema.optional(Schema.NullOr(Schema.Unknown)), - projectID: ProjectID, + projectID: ProjectV2.ID, }).annotate({ identifier: "Workspace" }) export type WorkspaceInfo = DeepMutable> @@ -40,7 +40,7 @@ export type Target = export type WorkspaceAdapterContext = { readonly instance?: InstanceContext - readonly workspaceID?: WorkspaceID + readonly workspaceID?: WorkspaceV2.ID } export type WorkspaceAdapter = { diff --git a/packages/opencode/src/control-plane/workspace-context.ts b/packages/opencode/src/control-plane/workspace-context.ts index 2e6aff1be6d7..52229e563926 100644 --- a/packages/opencode/src/control-plane/workspace-context.ts +++ b/packages/opencode/src/control-plane/workspace-context.ts @@ -1,18 +1,18 @@ import { LocalContext } from "@/util/local-context" -import type { WorkspaceID } from "../control-plane/schema" +import type { WorkspaceV2 } from "@opencode-ai/core/workspace" export interface WorkspaceContext { - workspaceID: WorkspaceID | undefined + workspaceID: WorkspaceV2.ID | undefined } const context = LocalContext.create("instance") export const WorkspaceContext = { - async provide(input: { workspaceID?: WorkspaceID; fn: () => R }): Promise { + async provide(input: { workspaceID?: WorkspaceV2.ID; fn: () => R }): Promise { return context.provide({ workspaceID: input.workspaceID }, () => input.fn()) }, - restore(workspaceID: WorkspaceID, fn: () => R): R { + restore(workspaceID: WorkspaceV2.ID, fn: () => R): R { return context.provide({ workspaceID }, fn) }, diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index 9f44d22334c0..d3147ec993d4 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -1,28 +1,28 @@ import { Context, Effect, FiberMap, Iterable, Layer, Schema, Stream } from "effect" import { serviceUse } from "@opencode-ai/core/effect/service-use" import { FetchHttpClient, HttpBody, HttpClient, HttpClientError, HttpClientRequest } from "effect/unstable/http" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { asc } from "drizzle-orm" import { eq } from "drizzle-orm" import { inArray } from "drizzle-orm" import { Project } from "@/project/project" -import { BusEvent } from "@/bus/bus-event" import { GlobalBus } from "@/bus/global" import { Auth } from "@/auth" -import { SyncEvent } from "@/sync" -import { EventSequenceTable, EventTable } from "@/sync/event.sql" +import { EventV2 } from "@opencode-ai/core/event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventSequenceTable, EventTable } from "@opencode-ai/core/event/sql" import { AppFileSystem } from "@opencode-ai/core/filesystem" import * as Log from "@opencode-ai/core/util/log" import { RuntimeFlags } from "@/effect/runtime-flags" -import { ProjectID } from "@/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { Slug } from "@opencode-ai/core/util/slug" -import { WorkspaceTable } from "./workspace.sql" +import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" import { getAdapter, registeredAdapters } from "./adapters" import { type Target, type WorkspaceInfo, WorkspaceInfo as WorkspaceInfoSchema } from "./types" -import { WorkspaceID } from "./schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { Session } from "@/session/session" import { SessionPrompt } from "@/session/prompt" -import { SessionTable } from "@/session/session.sql" +import { SessionTable } from "@opencode-ai/core/session/sql" import { SessionID } from "@/session/schema" import { NotFoundError } from "@/storage/storage" import { errorData } from "@/util/error" @@ -40,25 +40,25 @@ export const Info = Schema.Struct({ export type Info = WorkspaceInfo & { timeUsed: number } export const ConnectionStatus = Schema.Struct({ - workspaceID: WorkspaceID, + workspaceID: WorkspaceV2.ID, status: Schema.Literals(["connected", "connecting", "disconnected", "error"]), }) export type ConnectionStatus = Schema.Schema.Type export const Event = { - Ready: BusEvent.define( - "workspace.ready", - Schema.Struct({ + Ready: EventV2.define({ + type: "workspace.ready", + schema: { name: Schema.String, - }), - ), - Failed: BusEvent.define( - "workspace.failed", - Schema.Struct({ + }, + }), + Failed: EventV2.define({ + type: "workspace.failed", + schema: { message: Schema.String, - }), - ), - Status: BusEvent.define("workspace.status", ConnectionStatus), + }, + }), + Status: EventV2.define({ type: "workspace.status", schema: ConnectionStatus.fields }), } function fromRow(row: typeof WorkspaceTable.$inferSelect): Info { @@ -74,22 +74,19 @@ function fromRow(row: typeof WorkspaceTable.$inferSelect): Info { } } -const db = (fn: (d: Parameters[0] extends (trx: infer D) => any ? D : never) => T) => - Effect.sync(() => Database.use(fn)) - const log = Log.create({ service: "workspace-sync" }) export const CreateInput = Schema.Struct({ - id: Schema.optional(WorkspaceID), + id: Schema.optional(WorkspaceV2.ID), type: Info.fields.type, branch: Info.fields.branch, - projectID: ProjectID, + projectID: ProjectV2.ID, extra: Schema.optional(Info.fields.extra), }) export type CreateInput = Schema.Schema.Type export const SessionWarpInput = Schema.Struct({ - workspaceID: Schema.NullOr(WorkspaceID), + workspaceID: Schema.NullOr(WorkspaceV2.ID), sessionID: SessionID, copyChanges: Schema.optional(Schema.Boolean), }) @@ -105,7 +102,7 @@ export class WorkspaceNotFoundError extends Schema.TaggedErrorClass Effect.Effect readonly list: (project: Project.Info) => Effect.Effect readonly syncList: (project: Project.Info) => Effect.Effect - readonly get: (id: WorkspaceID) => Effect.Effect - readonly remove: (id: WorkspaceID) => Effect.Effect + readonly get: (id: WorkspaceV2.ID) => Effect.Effect + readonly remove: (id: WorkspaceV2.ID) => Effect.Effect readonly status: () => Effect.Effect - readonly isSyncing: (workspaceID: WorkspaceID) => Effect.Effect + readonly isSyncing: (workspaceID: WorkspaceV2.ID) => Effect.Effect readonly waitForSync: ( - workspaceID: WorkspaceID, + workspaceID: WorkspaceV2.ID, state: Record, signal?: AbortSignal, timeout?: number, ) => Effect.Effect - readonly startWorkspaceSyncing: (projectID: ProjectID) => Effect.Effect + readonly startWorkspaceSyncing: (projectID: ProjectV2.ID) => Effect.Effect } export class Service extends Context.Service()("@opencode/Workspace") {} @@ -177,14 +174,15 @@ export const layer = Layer.effect( const session = yield* Session.Service const prompt = yield* SessionPrompt.Service const http = yield* HttpClient.HttpClient - const sync = yield* SyncEvent.Service + const events = yield* EventV2Bridge.Service const vcs = yield* Vcs.Service const flags = yield* RuntimeFlags.Service const fs = yield* AppFileSystem.Service - const connections = new Map() - const syncFibers = yield* FiberMap.make() + const { db } = yield* Database.Service + const connections = new Map() + const syncFibers = yield* FiberMap.make() - const setStatus = (id: WorkspaceID, status: ConnectionStatus["status"]) => { + const setStatus = (id: WorkspaceV2.ID, status: ConnectionStatus["status"]) => { const prev = connections.get(id) if (prev?.status === status) return const next = { workspaceID: id, status } @@ -270,7 +268,7 @@ export const layer = Layer.effect( }) const runInWorkspace = (input: { - workspaceID?: WorkspaceID + workspaceID?: WorkspaceV2.ID local: () => Effect.Effect remote: (input: { workspace: Info @@ -333,19 +331,20 @@ export const layer = Layer.effect( url: URL | string, headers: HeadersInit | undefined, ) { - const sessionIDs = yield* db((db) => - db - .select({ id: SessionTable.id }) - .from(SessionTable) - .where(eq(SessionTable.workspace_id, space.id)) - .all() - .map((row) => row.id), - ) + const sessionIDs = (yield* db + .select({ id: SessionTable.id }) + .from(SessionTable) + .where(eq(SessionTable.workspace_id, space.id)) + .all() + .pipe(Effect.orDie)).map((row) => row.id) const state = sessionIDs.length ? Object.fromEntries( - (yield* db((db) => - db.select().from(EventSequenceTable).where(inArray(EventSequenceTable.aggregate_id, sessionIDs)).all(), - )).map((row) => [row.aggregate_id, row.seq]), + (yield* db + .select() + .from(EventSequenceTable) + .where(inArray(EventSequenceTable.aggregate_id, sessionIDs)) + .all() + .pipe(Effect.orDie)).map((row) => [row.aggregate_id, row.seq]), ) : {} @@ -371,20 +370,20 @@ export const layer = Layer.effect( }) } - const events = (yield* response.json) as HistoryEvent[] + const history = (yield* response.json) as HistoryEvent[] log.info("workspace history synced", { workspaceID: space.id, - events: events.length, + events: history.length, }) yield* Effect.forEach( - events, + history, (event) => - sync + events .replay( { - id: event.id, + id: EventV2.ID.make(event.id), aggregateID: event.aggregate_id, seq: event.seq, type: event.type, @@ -431,11 +430,11 @@ export const layer = Layer.effect( yield* parseSSE(stream, (evt) => Effect.gen(function* () { if (!evt || typeof evt !== "object" || !("payload" in evt)) return - const payload = evt.payload as { type?: string; syncEvent?: SyncEvent.SerializedEvent } + const payload = evt.payload as { type?: string; syncEvent?: EventV2.SerializedEvent } if (payload.type === "server.heartbeat") return if (payload.type === "sync" && payload.syncEvent) { - const failed = yield* sync.replay(payload.syncEvent).pipe( + const failed = yield* events.replay(payload.syncEvent, { publish: true }).pipe( Effect.as(false), Effect.catchCause((error) => Effect.sync(() => { @@ -524,13 +523,13 @@ export const layer = Layer.effect( ) }) - const stopSync = Effect.fn("Workspace.stopSync")(function* (id: WorkspaceID) { + const stopSync = Effect.fn("Workspace.stopSync")(function* (id: WorkspaceV2.ID) { yield* FiberMap.remove(syncFibers, id) connections.delete(id) }) const create = Effect.fn("Workspace.create")(function* (input: CreateInput) { - const id = WorkspaceID.ascending(input.id) + const id = WorkspaceV2.ID.ascending(input.id) const adapter = getAdapter(input.projectID, input.type) const config = yield* WorkspaceAdapterRuntime.configure(adapter, { ...input, @@ -551,20 +550,20 @@ export const layer = Layer.effect( timeUsed: Date.now(), } - yield* db((db) => { - db.insert(WorkspaceTable) - .values({ - id: info.id, - type: info.type, - branch: info.branch, - name: info.name, - directory: info.directory, - extra: info.extra, - project_id: info.projectID, - time_used: info.timeUsed, - }) - .run() - }) + yield* db + .insert(WorkspaceTable) + .values({ + id: info.id, + type: info.type, + branch: info.branch, + name: info.name, + directory: info.directory, + extra: info.extra, + project_id: info.projectID, + time_used: info.timeUsed, + }) + .run() + .pipe(Effect.orDie) const env = { OPENCODE_AUTH_CONTENT: JSON.stringify(yield* auth.all()), @@ -603,13 +602,12 @@ export const layer = Layer.effect( sessionID: input.sessionID, }) - const current = yield* db((db) => - db - .select({ workspaceID: SessionTable.workspace_id }) - .from(SessionTable) - .where(eq(SessionTable.id, input.sessionID)) - .get(), - ) + const current = yield* db + .select({ workspaceID: SessionTable.workspace_id }) + .from(SessionTable) + .where(eq(SessionTable.id, input.sessionID)) + .get() + .pipe(Effect.orDie) if (current?.workspaceID) { const previous = yield* get(current.workspaceID) @@ -634,7 +632,7 @@ export const layer = Layer.effect( // "claim" this session so any future events coming from // the old workspace are ignored - yield* sync.claim(input.sessionID, input.workspaceID ?? previous.projectID) + yield* events.claim(input.sessionID, input.workspaceID ?? previous.projectID) } } @@ -669,12 +667,7 @@ export const layer = Layer.effect( } if (input.workspaceID === null) { - yield* sync.run(Session.Event.Updated, { - sessionID: input.sessionID, - info: { - workspaceID: null, - }, - }) + yield* session.setWorkspace({ sessionID: input.sessionID, workspaceID: undefined }) log.info("session warp complete", { workspaceID: input.workspaceID, @@ -695,12 +688,7 @@ export const layer = Layer.effect( const target = yield* WorkspaceAdapterRuntime.target(space) if (target.type === "local") { - yield* sync.run(Session.Event.Updated, { - sessionID: input.sessionID, - info: { - workspaceID: input.workspaceID, - }, - }) + yield* session.setWorkspace({ sessionID: input.sessionID, workspaceID: input.workspaceID }) log.info("session warp complete", { workspaceID: input.workspaceID, @@ -710,20 +698,19 @@ export const layer = Layer.effect( return } - const rows = yield* db((db) => - db - .select({ - id: EventTable.id, - aggregateID: EventTable.aggregate_id, - seq: EventTable.seq, - type: EventTable.type, - data: EventTable.data, - }) - .from(EventTable) - .where(eq(EventTable.aggregate_id, input.sessionID)) - .orderBy(asc(EventTable.seq)) - .all(), - ) + const rows = yield* db + .select({ + id: EventTable.id, + aggregateID: EventTable.aggregate_id, + seq: EventTable.seq, + type: EventTable.type, + data: EventTable.data, + }) + .from(EventTable) + .where(eq(EventTable.aggregate_id, input.sessionID)) + .orderBy(asc(EventTable.seq)) + .all() + .pipe(Effect.orDie) if (rows.length === 0) return yield* new SessionEventsNotFoundError({ message: `No events found for session: ${input.sessionID}`, @@ -810,6 +797,8 @@ export const layer = Layer.effect( }) } + yield* session.setWorkspace({ sessionID: input.sessionID, workspaceID: input.workspaceID }) + log.info("session warp complete", { workspaceID: input.workspaceID, sessionID: input.sessionID, @@ -829,15 +818,14 @@ export const layer = Layer.effect( }) const list = Effect.fn("Workspace.list")(function* (project: Project.Info) { - return yield* db((db) => - db - .select() - .from(WorkspaceTable) - .where(eq(WorkspaceTable.project_id, project.id)) - .all() - .map(fromRow) - .sort((a, b) => a.id.localeCompare(b.id)), - ) + return (yield* db + .select() + .from(WorkspaceTable) + .where(eq(WorkspaceTable.project_id, project.id)) + .all() + .pipe(Effect.orDie)) + .map(fromRow) + .sort((a, b) => a.id.localeCompare(b.id)) }) const syncList = Effect.fn("Workspace.syncList")(function* (project: Project.Info) { @@ -864,7 +852,7 @@ export const layer = Layer.effect( names.add(item.name) const info: Info = { - id: WorkspaceID.ascending(), + id: WorkspaceV2.ID.ascending(), type: item.type, branch: item.branch, name: item.name, @@ -874,20 +862,20 @@ export const layer = Layer.effect( timeUsed: Date.now(), } - yield* db((db) => { - db.insert(WorkspaceTable) - .values({ - id: info.id, - type: info.type, - branch: info.branch, - name: info.name, - directory: info.directory, - extra: info.extra, - project_id: info.projectID, - time_used: info.timeUsed, - }) - .run() - }) + yield* db + .insert(WorkspaceTable) + .values({ + id: info.id, + type: info.type, + branch: info.branch, + name: info.name, + directory: info.directory, + extra: info.extra, + project_id: info.projectID, + time_used: info.timeUsed, + }) + .run() + .pipe(Effect.orDie) yield* startSync(info) }), @@ -895,20 +883,19 @@ export const layer = Layer.effect( ) }) - const get = Effect.fn("Workspace.get")(function* (id: WorkspaceID) { - const row = yield* db((db) => db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, id)).get()) + const get = Effect.fn("Workspace.get")(function* (id: WorkspaceV2.ID) { + const row = yield* db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, id)).get().pipe(Effect.orDie) if (!row) return return fromRow(row) }) - const remove = Effect.fn("Workspace.remove")(function* (id: WorkspaceID) { - const sessions = yield* db((db) => - db - .select({ id: SessionTable.id, parentID: SessionTable.parent_id }) - .from(SessionTable) - .where(eq(SessionTable.workspace_id, id)) - .all(), - ) + const remove = Effect.fn("Workspace.remove")(function* (id: WorkspaceV2.ID) { + const sessions = yield* db + .select({ id: SessionTable.id, parentID: SessionTable.parent_id }) + .from(SessionTable) + .where(eq(SessionTable.workspace_id, id)) + .all() + .pipe(Effect.orDie) const sessionIDs = new Set(sessions.map((sessionInfo) => sessionInfo.id)) yield* Effect.forEach( sessions.filter((sessionInfo) => !sessionInfo.parentID || !sessionIDs.has(sessionInfo.parentID)), @@ -917,7 +904,7 @@ export const layer = Layer.effect( { discard: true }, ) - const row = yield* db((db) => db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, id)).get()) + const row = yield* db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, id)).get().pipe(Effect.orDie) if (!row) return yield* stopSync(id) @@ -933,7 +920,7 @@ export const layer = Layer.effect( }), ) - yield* db((db) => db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, id)).run()) + yield* db.delete(WorkspaceTable).where(eq(WorkspaceTable.id, id)).run().pipe(Effect.orDie) return info }) @@ -941,30 +928,21 @@ export const layer = Layer.effect( return [...connections.values()] }) - const isSyncing = Effect.fn("Workspace.isSyncing")(function* (workspaceID: WorkspaceID) { + const isSyncing = Effect.fn("Workspace.isSyncing")(function* (workspaceID: WorkspaceV2.ID) { const exists = yield* FiberMap.has(syncFibers, workspaceID) return exists && connections.get(workspaceID)?.status !== "error" }) const waitForSync = Effect.fn("Workspace.waitForSync")(function* ( - workspaceID: WorkspaceID, + workspaceID: WorkspaceV2.ID, state: Record, signal?: AbortSignal, timeout = TIMEOUT, ) { - if (synced(state)) return + if (yield* synced(db, state)) return yield* Effect.catch( - waitEvent({ - timeout, - signal, - fn(event) { - if (event.workspace !== workspaceID && event.payload.type !== "sync") { - return false - } - return synced(state) - }, - }), + waitUntilSynced({ db, workspaceID, state, signal, timeout }), (): Effect.Effect => signal?.aborted ? Effect.fail( @@ -982,14 +960,13 @@ export const layer = Layer.effect( ) }) - const startWorkspaceSyncing = Effect.fn("Workspace.startWorkspaceSyncing")(function* (projectID: ProjectID) { - const rows = yield* db((db) => - db - .selectDistinct({ workspace: WorkspaceTable }) - .from(WorkspaceTable) - .where(eq(WorkspaceTable.project_id, projectID)) - .all(), - ) + const startWorkspaceSyncing = Effect.fn("Workspace.startWorkspaceSyncing")(function* (projectID: ProjectV2.ID) { + const rows = yield* db + .selectDistinct({ workspace: WorkspaceTable }) + .from(WorkspaceTable) + .where(eq(WorkspaceTable.project_id, projectID)) + .all() + .pipe(Effect.orDie) for (const { workspace } of rows) { yield* startSync(fromRow(workspace)).pipe( @@ -1025,11 +1002,12 @@ export const layer = Layer.effect( export const defaultLayer = layer.pipe( Layer.provide(Auth.defaultLayer), Layer.provide(Session.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(SessionPrompt.defaultLayer), Layer.provide(Project.defaultLayer), Layer.provide(Vcs.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(RuntimeFlags.defaultLayer), ) @@ -1044,26 +1022,46 @@ type HistoryEvent = { data: Record } -function synced(state: Record) { +function waitUntilSynced(input: { + db: Database.Interface["db"] + workspaceID: WorkspaceV2.ID + state: Record + signal?: AbortSignal + timeout: number +}): Effect.Effect { + return Effect.suspend(() => + waitEvent({ + timeout: input.timeout, + signal: input.signal, + fn(event) { + return event.workspace === input.workspaceID || event.payload.type === "sync" + }, + }).pipe( + Effect.andThen(synced(input.db, input.state)), + Effect.flatMap((done): Effect.Effect => (done ? Effect.void : waitUntilSynced(input))), + ), + ) +} + +function synced(db: Database.Interface["db"], state: Record): Effect.Effect { const ids = Object.keys(state) - if (ids.length === 0) return true - - const done = Object.fromEntries( - Database.use((db) => - db - .select({ - id: EventSequenceTable.aggregate_id, - seq: EventSequenceTable.seq, - }) - .from(EventSequenceTable) - .where(inArray(EventSequenceTable.aggregate_id, ids)) - .all(), - ).map((row) => [row.id, row.seq]), - ) as Record - - return ids.every((id) => { - return (done[id] ?? -1) >= state[id] - }) + if (ids.length === 0) return Effect.succeed(true) + + return db + .select({ + id: EventSequenceTable.aggregate_id, + seq: EventSequenceTable.seq, + }) + .from(EventSequenceTable) + .where(inArray(EventSequenceTable.aggregate_id, ids)) + .all() + .pipe( + Effect.orDie, + Effect.map((rows) => { + const done = Object.fromEntries(rows.map((row) => [row.id, row.seq])) as Record + return ids.every((id) => (done[id] ?? -1) >= state[id]) + }), + ) } function route(url: string | URL, path: string) { diff --git a/packages/opencode/src/data-migration.ts b/packages/opencode/src/data-migration.ts deleted file mode 100644 index b6956032a411..000000000000 --- a/packages/opencode/src/data-migration.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { Context, Effect, Layer } from "effect" -import { Database } from "./storage/db" -import { DataMigrationTable } from "./data-migration.sql" -import * as Log from "@opencode-ai/core/util/log" -import { and, asc, eq, gt, inArray, sql } from "drizzle-orm" -import { MessageTable, SessionTable } from "./session/session.sql" -import type { SessionID } from "./session/schema" - -export type Migration = { - name: string - run: Effect.Effect -} - -const log = Log.create({ service: "data-migration" }) - -export interface Interface {} - -export class Service extends Context.Service()("@opencode/DataMigration") {} - -export const layer = Layer.effect( - Service, - Effect.gen(function* () { - const migrations: Migration[] = [ - { - name: "session_usage_from_messages", - run: Effect.gen(function* () { - type Usage = { - cost: number - tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } - } - - for (let cursor: SessionID | undefined, page = 1; ; page++) { - const next = yield* Effect.gen(function* () { - const sessions = yield* Effect.sync(() => - Database.use((db) => - db - .select({ id: SessionTable.id }) - .from(SessionTable) - .where(cursor ? gt(SessionTable.id, cursor) : undefined) - .orderBy(asc(SessionTable.id)) - .limit(100) - .all(), - ), - ) - if (sessions.length === 0) return - - yield* Effect.sync(() => - Database.transaction((db) => { - const usageBySession = new Map( - sessions.map((session) => [ - session.id, - { cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } }, - ]), - ) - - for (const row of db - .select({ - session_id: MessageTable.session_id, - cost: sql`coalesce(sum(coalesce(json_extract(${MessageTable.data}, '$.cost'), 0)), 0)`, - tokens_input: sql`coalesce(sum(coalesce(json_extract(${MessageTable.data}, '$.tokens.input'), 0)), 0)`, - tokens_output: sql`coalesce(sum(coalesce(json_extract(${MessageTable.data}, '$.tokens.output'), 0)), 0)`, - tokens_reasoning: sql`coalesce(sum(coalesce(json_extract(${MessageTable.data}, '$.tokens.reasoning'), 0)), 0)`, - tokens_cache_read: sql`coalesce(sum(coalesce(json_extract(${MessageTable.data}, '$.tokens.cache.read'), 0)), 0)`, - tokens_cache_write: sql`coalesce(sum(coalesce(json_extract(${MessageTable.data}, '$.tokens.cache.write'), 0)), 0)`, - }) - .from(MessageTable) - .where( - and( - inArray( - MessageTable.session_id, - sessions.map((session) => session.id), - ), - sql`json_extract(${MessageTable.data}, '$.role') = 'assistant'`, - ), - ) - .groupBy(MessageTable.session_id) - .all()) { - const current = usageBySession.get(row.session_id) - if (!current) continue - current.cost = row.cost - current.tokens.input = row.tokens_input - current.tokens.output = row.tokens_output - current.tokens.reasoning = row.tokens_reasoning - current.tokens.cache.read = row.tokens_cache_read - current.tokens.cache.write = row.tokens_cache_write - } - - for (const [sessionID, value] of usageBySession) { - db.update(SessionTable) - .set({ - cost: value.cost, - tokens_input: value.tokens.input, - tokens_output: value.tokens.output, - tokens_reasoning: value.tokens.reasoning, - tokens_cache_read: value.tokens.cache.read, - tokens_cache_write: value.tokens.cache.write, - time_updated: sql`${SessionTable.time_updated}`, - }) - .where(eq(SessionTable.id, sessionID)) - .run() - } - }), - ) - - return sessions.at(-1)?.id - }).pipe( - Effect.withSpan("DataMigration.sessionUsage.page", { - attributes: { - "data_migration.name": "session_usage_from_messages", - "data_migration.page": page, - "data_migration.cursor": cursor ?? "", - }, - }), - ) - if (!next) return - cursor = next - yield* Effect.sleep("10 millis") - } - }), - }, - ] - - yield* Effect.gen(function* () { - if (migrations.length === 0) return - - // Migrations run in a background fiber, so they must be resumable until - // their completion row is written. - for (const migration of migrations) { - const completed = Database.use((db) => - db - .select({ name: DataMigrationTable.name }) - .from(DataMigrationTable) - .where(eq(DataMigrationTable.name, migration.name)) - .get(), - ) - if (completed) continue - - log.info("running data migration", { name: migration.name }) - yield* migration.run.pipe(Effect.withSpan("DataMigration", { attributes: { name: migration.name } })) - Database.use((db) => - db - .insert(DataMigrationTable) - .values({ name: migration.name, time_completed: Date.now() }) - .onConflictDoNothing() - .run(), - ) - } - }).pipe( - Effect.tapCause((cause) => - Effect.logError("failed to run data migrations").pipe(Effect.annotateLogs("cause", cause)), - ), - Effect.ignore, - Effect.forkScoped, - ) - return Service.of({}) - }), -) - -export const defaultLayer = layer - -export * as DataMigration from "./data-migration" diff --git a/packages/opencode/src/effect/app-runtime.ts b/packages/opencode/src/effect/app-runtime.ts index 2bef35ed075d..5434bb713f55 100644 --- a/packages/opencode/src/effect/app-runtime.ts +++ b/packages/opencode/src/effect/app-runtime.ts @@ -3,7 +3,7 @@ import { attach } from "./run-service" import * as Observability from "@opencode-ai/core/effect/observability" import { AppFileSystem } from "@opencode-ai/core/filesystem" -import { Bus } from "@/bus" +import { Database } from "@opencode-ai/core/database/database" import { Auth } from "@/auth" import { Account } from "@/account/account" import { Config } from "@/config/config" @@ -51,18 +51,16 @@ import { PtyTicket } from "@/pty/ticket" import { Installation } from "@/installation" import { ShareNext } from "@/share/share-next" import { SessionShare } from "@/share/session" -import { SyncEvent } from "@/sync" import { Npm } from "@opencode-ai/core/npm" import { memoMap } from "@opencode-ai/core/effect/memo-map" -import { DataMigration } from "@/data-migration" import { BackgroundJob } from "@/background/job" -import { EventV2Bridge } from "@/event-v2-bridge" import { RuntimeFlags } from "@/effect/runtime-flags" +import { EventV2Bridge } from "@/event-v2-bridge" export const AppLayer = Layer.mergeAll( Npm.defaultLayer, AppFileSystem.defaultLayer, - Bus.defaultLayer, + Database.defaultLayer, Auth.defaultLayer, Account.defaultLayer, Config.defaultLayer, @@ -86,6 +84,7 @@ export const AppLayer = Layer.mergeAll( SessionStatus.defaultLayer, BackgroundJob.defaultLayer, RuntimeFlags.defaultLayer, + EventV2Bridge.defaultLayer, SessionRunState.defaultLayer, SessionProcessor.defaultLayer, SessionCompaction.defaultLayer, @@ -111,9 +110,6 @@ export const AppLayer = Layer.mergeAll( Installation.defaultLayer, ShareNext.defaultLayer, SessionShare.defaultLayer, - SyncEvent.defaultLayer, - EventV2Bridge.defaultLayer, - DataMigration.defaultLayer, ).pipe(Layer.provideMerge(InstanceLayer.layer), Layer.provideMerge(Observability.layer)) const rt = ManagedRuntime.make(AppLayer, { memoMap }) diff --git a/packages/opencode/src/effect/bootstrap-runtime.ts b/packages/opencode/src/effect/bootstrap-runtime.ts index 7f18538523e7..da3c10ff91dd 100644 --- a/packages/opencode/src/effect/bootstrap-runtime.ts +++ b/packages/opencode/src/effect/bootstrap-runtime.ts @@ -8,7 +8,6 @@ import { ShareNext } from "@/share/share-next" import { File } from "@/file" import { Vcs } from "@/project/vcs" import { Snapshot } from "@/snapshot" -import { Bus } from "@/bus" import { Config } from "@/config/config" import * as Observability from "@opencode-ai/core/effect/observability" import { memoMap } from "@opencode-ai/core/effect/memo-map" @@ -23,7 +22,6 @@ export const BootstrapLayer = Layer.mergeAll( FileWatcher.defaultLayer, Vcs.defaultLayer, Snapshot.defaultLayer, - Bus.defaultLayer, ).pipe(Layer.provide(Observability.layer)) export const BootstrapRuntime = ManagedRuntime.make(BootstrapLayer, { memoMap }) diff --git a/packages/opencode/src/effect/bridge.ts b/packages/opencode/src/effect/bridge.ts index 99f16f43712f..a51c2938d869 100644 --- a/packages/opencode/src/effect/bridge.ts +++ b/packages/opencode/src/effect/bridge.ts @@ -1,6 +1,6 @@ import { Context, Effect, Exit, Fiber } from "effect" import { WorkspaceContext } from "@/control-plane/workspace-context" -import type { WorkspaceID } from "@/control-plane/schema" +import type { WorkspaceV2 } from "@opencode-ai/core/workspace" import { InstanceRef, WorkspaceRef } from "./instance-ref" import { attachWith } from "./run-service" @@ -11,7 +11,7 @@ export interface Shape { readonly bind: (fn: (...args: Args) => Result) => (...args: Args) => Result } -function restoreWorkspace(workspace: WorkspaceID | undefined, fn: () => R): R { +function restoreWorkspace(workspace: WorkspaceV2.ID | undefined, fn: () => R): R { if (workspace !== undefined) return WorkspaceContext.restore(workspace, fn) return fn() } diff --git a/packages/opencode/src/effect/instance-ref.ts b/packages/opencode/src/effect/instance-ref.ts index d95932c2de67..49636c1f4995 100644 --- a/packages/opencode/src/effect/instance-ref.ts +++ b/packages/opencode/src/effect/instance-ref.ts @@ -1,11 +1,11 @@ import { Context } from "effect" import type { InstanceContext } from "@/project/instance-context" -import type { WorkspaceID } from "@/control-plane/schema" +import type { WorkspaceV2 } from "@opencode-ai/core/workspace" export const InstanceRef = Context.Reference("~opencode/InstanceRef", { defaultValue: () => undefined, }) -export const WorkspaceRef = Context.Reference("~opencode/WorkspaceRef", { +export const WorkspaceRef = Context.Reference("~opencode/WorkspaceRef", { defaultValue: () => undefined, }) diff --git a/packages/opencode/src/effect/runtime-flags.ts b/packages/opencode/src/effect/runtime-flags.ts index 520bcb30f893..c26e10aba286 100644 --- a/packages/opencode/src/effect/runtime-flags.ts +++ b/packages/opencode/src/effect/runtime-flags.ts @@ -1,4 +1,4 @@ -import { Config, ConfigProvider, Context, Effect, Layer } from "effect" +import { Config, ConfigProvider, Context, Effect, Layer, Option } from "effect" import { ConfigService } from "@/effect/config-service" const bool = (name: string) => Config.boolean(name).pipe(Config.withDefault(false)) @@ -9,17 +9,17 @@ const positiveInteger = (name: string) => ) const experimental = bool("OPENCODE_EXPERIMENTAL") const enabledByExperimental = (name: string) => - Config.all({ experimental, enabled: bool(name) }).pipe(Config.map((flags) => flags.experimental || flags.enabled)) + Config.all({ experimental, enabled: Config.boolean(name).pipe(Config.option) }).pipe( + Config.map((flags) => Option.getOrElse(flags.enabled, () => flags.experimental)), + ) export class Service extends ConfigService.Service()("@opencode/RuntimeFlags", { autoShare: bool("OPENCODE_AUTO_SHARE"), pure: bool("OPENCODE_PURE"), disableDefaultPlugins: bool("OPENCODE_DISABLE_DEFAULT_PLUGINS"), - disableChannelDb: bool("OPENCODE_DISABLE_CHANNEL_DB"), disableEmbeddedWebUi: bool("OPENCODE_DISABLE_EMBEDDED_WEB_UI"), disableExternalSkills: bool("OPENCODE_DISABLE_EXTERNAL_SKILLS"), disableLspDownload: bool("OPENCODE_DISABLE_LSP_DOWNLOAD"), - skipMigrations: bool("OPENCODE_SKIP_MIGRATIONS"), disableClaudeCodePrompt: Config.all({ broad: bool("OPENCODE_DISABLE_CLAUDE_CODE"), direct: bool("OPENCODE_DISABLE_CLAUDE_CODE_PROMPT"), @@ -48,10 +48,10 @@ export class Service extends ConfigService.Service()("@opencode/Runtime experimentalEventSystem: enabledByExperimental("OPENCODE_EXPERIMENTAL_EVENT_SYSTEM"), experimentalWorkspaces: enabledByExperimental("OPENCODE_EXPERIMENTAL_WORKSPACES"), experimentalIconDiscovery: enabledByExperimental("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY"), - acpNext: bool("OPENCODE_ACP_NEXT"), outputTokenMax: positiveInteger("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"), bashDefaultTimeoutMs: positiveInteger("OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS"), experimentalNativeLlm: bool("OPENCODE_EXPERIMENTAL_NATIVE_LLM"), + experimentalWebSockets: bool("OPENCODE_EXPERIMENTAL_WEBSOCKETS"), client: Config.string("OPENCODE_CLIENT").pipe(Config.withDefault("cli")), }) {} diff --git a/packages/opencode/src/event-v2-bridge.ts b/packages/opencode/src/event-v2-bridge.ts index 4c6c79a7078b..673bf1f15b42 100644 --- a/packages/opencode/src/event-v2-bridge.ts +++ b/packages/opencode/src/event-v2-bridge.ts @@ -1,27 +1,13 @@ -// Temporary V2 bridge: core events are the publish path, but the rest of -// opencode and the HTTP event stream still expect legacy bus/sync payloads. -// This layer goes away once consumers subscribe to core EventV2 directly. -import { Bus as ProjectBus } from "@/bus" -import { GlobalBus } from "@/bus/global" +// Opencode publish boundary for core events. Attach routed instance location +// so direct EventV2 consumers can isolate directory/workspace streams. import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" -import { InstanceStore } from "@/project/instance-store" -import { SyncEvent } from "@/sync" +import { GlobalBus } from "@/bus/global" import { EventV2 } from "@opencode-ai/core/event" +import { AbsolutePath } from "@opencode-ai/core/schema" import "@opencode-ai/core/account" import "@opencode-ai/core/catalog" -import "@opencode-ai/core/session-event" -import { Context, Effect, Layer, Option } from "effect" - -export function toSyncDefinition(definition: D) { - const result = { - type: definition.type, - version: definition.version, - aggregate: definition.aggregate, - schema: definition.data, - properties: definition.data, - } - return result as SyncEvent.Definition -} +import "@opencode-ai/core/session/event" +import { Context, Effect, Layer } from "effect" export class Service extends Context.Service()("@opencode/EventV2Bridge") {} @@ -29,62 +15,40 @@ export const layer = Layer.effect( Service, Effect.gen(function* () { const events = yield* EventV2.Service - const bus = yield* ProjectBus.Service - const sync = yield* SyncEvent.Service - const publishGlobal = (event: EventV2.Payload) => - Effect.sync(() => { - GlobalBus.emit("event", { - workspace: event.location?.workspaceID, - payload: { - id: event.id, - type: event.type, - properties: event.data, + const publish: EventV2.Interface["publish"] = (definition, data, options) => + Effect.gen(function* () { + if (options?.location) return yield* events.publish(definition, data, options) + const ctx = yield* InstanceRef + if (!ctx) return yield* events.publish(definition, data, options) + const workspaceID = yield* WorkspaceRef + return yield* events.publish(definition, data, { + ...options, + location: { + directory: AbsolutePath.make(ctx.directory), + ...(workspaceID ? { workspaceID } : {}), }, }) }) - const provideEventLocation = (event: EventV2.Payload, effect: Effect.Effect) => { - return Effect.gen(function* () { + const unsubscribe = yield* events.listen((event) => + Effect.gen(function* () { const ctx = yield* InstanceRef - if (ctx) return yield* effect - const store = Option.getOrUndefined(yield* Effect.serviceOption(InstanceStore.Service)) - if (!event.location?.directory || !store) return yield* publishGlobal(event) - return yield* store.load({ directory: event.location.directory }).pipe( - Effect.flatMap((ctx) => { - const withInstance = effect.pipe(Effect.provideService(InstanceRef, ctx)) - if (!event.location?.workspaceID) return withInstance - return withInstance.pipe(Effect.provideService(WorkspaceRef, event.location.workspaceID)) - }), - ) - }) - } - - const unsubscribe = yield* events.sync((event) => { - const definition = EventV2.registry.get(event.type) - if (!definition) return Effect.void - const aggregateID = definition.aggregate - ? (event.data as Record)[definition.aggregate] - : undefined - - if (definition.version !== undefined && typeof aggregateID === "string") { - return provideEventLocation(event, sync.run(toSyncDefinition(definition), event.data)) - } - - return provideEventLocation( - event, - bus.publish({ type: definition.type, properties: definition.data }, event.data, { id: event.id }), - ) - }) + const workspaceID = (yield* WorkspaceRef) ?? event.location?.workspaceID + GlobalBus.emit("event", { + directory: event.location?.directory ?? ctx?.directory, + project: ctx?.project.id, + workspace: workspaceID, + payload: { id: event.id, type: event.type, properties: event.data }, + }) + }), + ) yield* Effect.addFinalizer(() => unsubscribe) - return Service.of(events) + + return Service.of({ ...events, publish }) }), ) -export const defaultLayer = layer.pipe( - Layer.provide(EventV2.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), - Layer.provide(ProjectBus.defaultLayer), -) +export const defaultLayer = layer.pipe(Layer.provide(EventV2.defaultLayer)) export * as EventV2Bridge from "./event-v2-bridge" diff --git a/packages/opencode/src/file/index.ts b/packages/opencode/src/file/index.ts index 0992289fe29b..c4aa2e1cfba5 100644 --- a/packages/opencode/src/file/index.ts +++ b/packages/opencode/src/file/index.ts @@ -1,4 +1,4 @@ -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" import { serviceUse } from "@opencode-ai/core/effect/service-use" import { InstanceState } from "@/effect/instance-state" @@ -62,12 +62,12 @@ export const Content = Schema.Struct({ export type Content = DeepMutable> export const Event = { - Edited: BusEvent.define( - "file.edited", - Schema.Struct({ + Edited: EventV2.define({ + type: "file.edited", + schema: { file: Schema.String, - }), - ), + }, + }), } const log = Log.create({ service: "file" }) diff --git a/packages/opencode/src/file/watcher.ts b/packages/opencode/src/file/watcher.ts index 91ad9ff4de5d..eeb3e5f5f550 100644 --- a/packages/opencode/src/file/watcher.ts +++ b/packages/opencode/src/file/watcher.ts @@ -4,8 +4,8 @@ import { createWrapper } from "@parcel/watcher/wrapper" import type ParcelWatcher from "@parcel/watcher" import { readdir, realpath } from "fs/promises" import path from "path" -import { Bus } from "@/bus" -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" +import { EventV2Bridge } from "@/event-v2-bridge" import { EffectBridge } from "@/effect/bridge" import { InstanceState } from "@/effect/instance-state" import { Flag } from "@opencode-ai/core/flag/flag" @@ -22,13 +22,13 @@ const log = Log.create({ service: "file.watcher" }) const SUBSCRIBE_TIMEOUT_MS = 10_000 export const Event = { - Updated: BusEvent.define( - "file.watcher.updated", - Schema.Struct({ + Updated: EventV2.define({ + type: "file.watcher.updated", + schema: { file: Schema.String, event: Schema.Literals(["add", "change", "unlink"]), - }), - ), + }, + }), } const watcher = lazy((): typeof import("@parcel/watcher") | undefined => { @@ -69,6 +69,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const config = yield* Config.Service const git = yield* Git.Service + const events = yield* EventV2Bridge.Service const state = yield* InstanceState.make( Effect.fn("FileWatcher.state")( @@ -98,9 +99,9 @@ export const layer = Layer.effect( const cb: ParcelWatcher.SubscribeCallback = bridge.bind((err, evts) => { // if (err) return for (const evt of evts) { - if (evt.type === "create") void Bus.publish(ctx, Event.Updated, { file: evt.path, event: "add" }) - if (evt.type === "update") void Bus.publish(ctx, Event.Updated, { file: evt.path, event: "change" }) - if (evt.type === "delete") void Bus.publish(ctx, Event.Updated, { file: evt.path, event: "unlink" }) + if (evt.type === "create") bridge.fork(events.publish(Event.Updated, { file: evt.path, event: "add" })) + if (evt.type === "update") bridge.fork(events.publish(Event.Updated, { file: evt.path, event: "change" })) + if (evt.type === "delete") bridge.fork(events.publish(Event.Updated, { file: evt.path, event: "unlink" })) } }) @@ -162,6 +163,10 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(Config.defaultLayer), Layer.provide(Git.defaultLayer)) +export const defaultLayer = layer.pipe( + Layer.provide(Config.defaultLayer), + Layer.provide(Git.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), +) export * as FileWatcher from "./watcher" diff --git a/packages/opencode/src/ide/index.ts b/packages/opencode/src/ide/index.ts index a31c5bd05729..4df2ce8c2e69 100644 --- a/packages/opencode/src/ide/index.ts +++ b/packages/opencode/src/ide/index.ts @@ -1,4 +1,4 @@ -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" import { Schema } from "effect" import { NamedError } from "@opencode-ai/core/util/error" import * as Log from "@opencode-ai/core/util/log" @@ -15,12 +15,12 @@ const SUPPORTED_IDES = [ const log = Log.create({ service: "ide" }) export const Event = { - Installed: BusEvent.define( - "ide.installed", - Schema.Struct({ + Installed: EventV2.define({ + type: "ide.installed", + schema: { ide: Schema.String, - }), - ), + }, + }), } export const AlreadyInstalledError = NamedError.create("AlreadyInstalledError", {}) diff --git a/packages/opencode/src/image/image.ts b/packages/opencode/src/image/image.ts index 2a3c4fa5c009..8ecf0dcfcb66 100644 --- a/packages/opencode/src/image/image.ts +++ b/packages/opencode/src/image/image.ts @@ -1,4 +1,5 @@ import { Config } from "@/config/config" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import type { MessageV2 } from "@/session/message-v2" import * as Log from "@opencode-ai/core/util/log" import photonWasm from "@silvia-odwyer/photon-node/photon_rs_bg.wasm" with { type: "file" } @@ -52,7 +53,7 @@ export class SizeError extends Schema.TaggedErrorClass()("ImageSizeEr export type Error = ResizerUnavailableError | InvalidDataUrlError | DecodeError | SizeError export interface Interface { - readonly normalize: (input: MessageV2.FilePart) => Effect.Effect + readonly normalize: (input: SessionLegacy.FilePart) => Effect.Effect } export class Service extends Context.Service()("@opencode/Image") {} @@ -73,7 +74,7 @@ export const layer = Layer.effect( ), ) - const normalize = Effect.fn("Image.normalize")(function* (input: MessageV2.FilePart) { + const normalize = Effect.fn("Image.normalize")(function* (input: SessionLegacy.FilePart) { const image = (yield* config.get()).attachment?.image const info = { autoResize: image?.auto_resize ?? AUTO_RESIZE, diff --git a/packages/opencode/src/index.ts b/packages/opencode/src/index.ts index d20f29dd4d2f..d8bcdff7b24c 100644 --- a/packages/opencode/src/index.ts +++ b/packages/opencode/src/index.ts @@ -30,10 +30,9 @@ import { WebCommand } from "./cli/cmd/web" import { PrCommand } from "./cli/cmd/pr" import { SessionCommand } from "./cli/cmd/session" import { DbCommand } from "./cli/cmd/db" -import path from "path" import { Global } from "@opencode-ai/core/global" import { JsonMigration } from "@/storage/json-migration" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { errorMessage } from "./util/error" import { PluginCommand } from "./cli/cmd/plug" import { Heap } from "./cli/heap" @@ -116,7 +115,7 @@ const cli = yargs(args) run_id: processMetadata.runID, }) - const marker = path.join(Global.Path.data, "opencode.db") + const marker = Database.path() if (!(await Filesystem.exists(marker))) { const tty = process.stderr.isTTY process.stderr.write("Performing one time database migration, may take a few minutes..." + EOL) @@ -126,8 +125,9 @@ const cli = yargs(args) const reset = "\x1b[0m" let last = -1 if (tty) process.stderr.write("\x1b[?25l") + const sqlite = new (await import("bun:sqlite")).Database(marker) try { - await JsonMigration.run(drizzle({ client: Database.Client().$client }), { + await JsonMigration.run(drizzle({ client: sqlite }), { progress: (event) => { const percent = Math.floor((event.current / event.total) * 100) if (percent === last && event.current !== event.total) return @@ -145,6 +145,7 @@ const cli = yargs(args) }, }) } finally { + sqlite.close() if (tty) process.stderr.write("\x1b[?25h") else { process.stderr.write(`sqlite-migration:done${EOL}`) diff --git a/packages/opencode/src/installation/index.ts b/packages/opencode/src/installation/index.ts index 1f8dc116b18f..4367a26796a9 100644 --- a/packages/opencode/src/installation/index.ts +++ b/packages/opencode/src/installation/index.ts @@ -6,7 +6,7 @@ import { errorMessage } from "@/util/error" import { ChildProcess } from "effect/unstable/process" import { AppProcess } from "@opencode-ai/core/process" import path from "path" -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" import * as Log from "@opencode-ai/core/util/log" import { makeRuntime } from "@opencode-ai/core/effect/runtime" import semver from "semver" @@ -20,18 +20,18 @@ export type Method = "curl" | "npm" | "yarn" | "pnpm" | "bun" | "brew" | "scoop" export type ReleaseType = "patch" | "minor" | "major" export const Event = { - Updated: BusEvent.define( - "installation.updated", - Schema.Struct({ + Updated: EventV2.define({ + type: "installation.updated", + schema: { version: Schema.String, - }), - ), - UpdateAvailable: BusEvent.define( - "installation.update-available", - Schema.Struct({ + }, + }), + UpdateAvailable: EventV2.define({ + type: "installation.update-available", + schema: { version: Schema.String, - }), - ), + }, + }), } export function getReleaseType(current: string, latest: string): ReleaseType { diff --git a/packages/opencode/src/lsp/client.ts b/packages/opencode/src/lsp/client.ts index 205cba6f29e0..25da0b10cb5b 100644 --- a/packages/opencode/src/lsp/client.ts +++ b/packages/opencode/src/lsp/client.ts @@ -1,5 +1,3 @@ -import { BusEvent } from "@/bus/bus-event" -import { Bus } from "@/bus" import path from "path" import { pathToFileURL, fileURLToPath } from "url" import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node" @@ -11,8 +9,6 @@ import { Effect, Schema } from "effect" import type * as LSPServer from "./server" import { withTimeout } from "../util/timeout" import { Filesystem } from "@/util/filesystem" -import { InstanceRef } from "@/effect/instance-ref" -import { makeRuntime } from "@/effect/run-service" import type { InstanceContext } from "@/project/instance-context" const DIAGNOSTICS_DEBOUNCE_MS = 150 @@ -28,8 +24,6 @@ const FILE_CHANGE_CHANGED = 2 const TEXT_DOCUMENT_SYNC_INCREMENTAL = 2 const log = Log.create({ service: "lsp.client" }) -const busRuntime = makeRuntime(Bus.Service, Bus.layer) - export type Info = NonNullable>> export type Diagnostic = VSCodeDiagnostic @@ -39,16 +33,6 @@ export class InitializeError extends Schema.TaggedErrorClass()( cause: Schema.optional(Schema.Defect), }) {} -export const Event = { - Diagnostics: BusEvent.define( - "lsp.client.diagnostics", - Schema.Struct({ - serverID: Schema.String, - path: Schema.String, - }), - ), -} - type DocumentDiagnosticReport = { items?: Diagnostic[] relatedDocuments?: Record @@ -169,15 +153,12 @@ export async function create(input: { const published = new Map() const diagnosticRegistrations = new Map() const registrationListeners = new Set<() => void>() + const diagnosticListeners = new Set<(input: { path: string; serverID: string }) => void>() const mergedDiagnostics = (filePath: string) => dedupeDiagnostics([...(pushDiagnostics.get(filePath) ?? []), ...(pullDiagnostics.get(filePath) ?? [])]) const updatePushDiagnostics = (filePath: string, next: Diagnostic[]) => { pushDiagnostics.set(filePath, next) - void busRuntime.runPromise((svc) => - svc - .publish(Event.Diagnostics, { path: filePath, serverID: input.serverID }) - .pipe(Effect.provideService(InstanceRef, instance)), - ) + for (const listener of diagnosticListeners) listener({ path: filePath, serverID: input.serverID }) } const updatePullDiagnostics = (filePath: string, next: Diagnostic[]) => { pullDiagnostics.set(filePath, next) @@ -525,14 +506,12 @@ export async function create(input: { } timeoutTimer = setTimeout(() => finish(false), request.timeout) - unsub = busRuntime.runSync((svc) => - svc - .subscribeCallback(Event.Diagnostics, (event) => { - if (event.properties.path !== request.path || event.properties.serverID !== input.serverID) return - schedule() - }) - .pipe(Effect.provideService(InstanceRef, instance)), - ) + const listener = (event: { path: string; serverID: string }) => { + if (event.path !== request.path || event.serverID !== input.serverID) return + schedule() + } + diagnosticListeners.add(listener) + unsub = () => diagnosticListeners.delete(listener) schedule() }) } diff --git a/packages/opencode/src/lsp/lsp.ts b/packages/opencode/src/lsp/lsp.ts index 3117b834c50c..a0fcfb3fcd2e 100644 --- a/packages/opencode/src/lsp/lsp.ts +++ b/packages/opencode/src/lsp/lsp.ts @@ -1,5 +1,5 @@ -import { BusEvent } from "@/bus/bus-event" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" import * as Log from "@opencode-ai/core/util/log" import * as LSPClient from "./client" import path from "path" @@ -17,7 +17,7 @@ import { RuntimeFlags } from "@/effect/runtime-flags" const log = Log.create({ service: "lsp" }) export const Event = { - Updated: BusEvent.define("lsp.updated", Schema.Struct({})), + Updated: EventV2.define({ type: "lsp.updated", schema: {} }), } const Position = Schema.Struct({ @@ -144,6 +144,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const config = yield* Config.Service const flags = yield* RuntimeFlags.Service + const events = yield* EventV2Bridge.Service const state = yield* InstanceState.make( Effect.fn("LSP.state")(function* (ctx) { @@ -212,9 +213,10 @@ export const layer = Layer.effect( const ctx = yield* InstanceState.context if (!containsPath(file, ctx)) return [] as LSPClient.Info[] const s = yield* InstanceState.get(state) - return yield* Effect.promise(async () => { + const clients = yield* Effect.promise(async () => { const extension = path.parse(file).ext || file const result: LSPClient.Info[] = [] + let updated = 0 async function schedule(server: LSPServer.Info, root: string, key: string) { const handle = await server @@ -291,11 +293,15 @@ export const layer = Layer.effect( if (!client) continue result.push(client) - await Bus.publish(ctx, Event.Updated, {}) + updated++ } - return result + return { result, updated } + }) + yield* Effect.forEach(Array.from({ length: clients.updated }), () => events.publish(Event.Updated, {}), { + discard: true, }) + return clients.result }) const run = Effect.fnUntraced(function* (file: string, fn: (client: LSPClient.Info) => Promise) { @@ -500,7 +506,11 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer)) +export const defaultLayer = layer.pipe( + Layer.provide(Config.defaultLayer), + Layer.provide(RuntimeFlags.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), +) export * as Diagnostic from "./diagnostic" diff --git a/packages/opencode/src/mcp/auth.ts b/packages/opencode/src/mcp/auth.ts index adddea0b35a1..bf421473f74c 100644 --- a/packages/opencode/src/mcp/auth.ts +++ b/packages/opencode/src/mcp/auth.ts @@ -3,6 +3,7 @@ import { serviceUse } from "@opencode-ai/core/effect/service-use" import { Global } from "@opencode-ai/core/global" import { Effect, Layer, Context, Option, Schema } from "effect" import { AppFileSystem } from "@opencode-ai/core/filesystem" +import { EffectFlock } from "@opencode-ai/core/util/effect-flock" export const Tokens = Schema.Struct({ accessToken: Schema.mutableKey(Schema.String), @@ -33,6 +34,7 @@ const decodeAuthData = Schema.decodeUnknownOption(Schema.Record(Schema.String, E type AuthData = Record const filepath = path.join(Global.Path.data, "mcp-auth.json") +const lockKey = `mcp-auth:${filepath}` export interface Interface { readonly all: () => Effect.Effect> @@ -58,14 +60,27 @@ export const layer = Layer.effect( Service, Effect.gen(function* () { const fs = yield* AppFileSystem.Service + const flock = yield* EffectFlock.Service - const all = Effect.fn("McpAuth.all")(function* () { + const read = Effect.fn("McpAuth.read")(function* () { return yield* fs.readJson(filepath).pipe( Effect.map((data): AuthData => Option.getOrElse(decodeAuthData(data), () => ({}) as AuthData) as AuthData), Effect.catch(() => Effect.succeed({} as AuthData)), ) }) + const all = Effect.fn("McpAuth.all")(function* () { + return yield* read().pipe(flock.withLock(lockKey), Effect.orDie) + }) + + const mutate = Effect.fn("McpAuth.mutate")(function* (update: (data: AuthData) => AuthData | undefined) { + yield* Effect.gen(function* () { + const next = update(yield* read()) + if (!next) return + yield* fs.writeJson(filepath, next, 0o600).pipe(Effect.orDie) + }).pipe(flock.withLock(lockKey), Effect.orDie) + }) + const get = Effect.fn("McpAuth.get")(function* (mcpName: string) { const data = yield* all() return data[mcpName] @@ -80,31 +95,38 @@ export const layer = Layer.effect( }) const set = Effect.fn("McpAuth.set")(function* (mcpName: string, entry: Entry, serverUrl?: string) { - const data = yield* all() - if (serverUrl) entry.serverUrl = serverUrl - yield* fs.writeJson(filepath, { ...data, [mcpName]: entry }, 0o600).pipe(Effect.orDie) + yield* mutate((data) => ({ + ...data, + [mcpName]: serverUrl ? { ...entry, serverUrl } : entry, + })) }) const remove = Effect.fn("McpAuth.remove")(function* (mcpName: string) { - const data = yield* all() - delete data[mcpName] - yield* fs.writeJson(filepath, data, 0o600).pipe(Effect.orDie) + yield* mutate((data) => { + const next = { ...data } + delete next[mcpName] + return next + }) }) const updateField = (field: K, spanName: string) => Effect.fn(`McpAuth.${spanName}`)(function* (mcpName: string, value: NonNullable, serverUrl?: string) { - const entry = (yield* get(mcpName)) ?? {} - entry[field] = value - yield* set(mcpName, entry, serverUrl) + yield* mutate((data) => { + const entry = data[mcpName] ?? {} + entry[field] = value + if (serverUrl) entry.serverUrl = serverUrl + return { ...data, [mcpName]: entry } + }) }) const clearField = (field: keyof Entry, spanName: string) => Effect.fn(`McpAuth.${spanName}`)(function* (mcpName: string) { - const entry = yield* get(mcpName) - if (entry) { + yield* mutate((data) => { + const entry = data[mcpName] + if (!entry) return undefined delete entry[field] - yield* set(mcpName, entry) - } + return { ...data, [mcpName]: entry } + }) }) const updateTokens = updateField("tokens", "updateTokens") @@ -144,6 +166,9 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(AppFileSystem.defaultLayer)) +export const defaultLayer = layer.pipe( + Layer.provide(EffectFlock.defaultLayer), + Layer.provide(AppFileSystem.defaultLayer), +) export * as McpAuth from "./auth" diff --git a/packages/opencode/src/mcp/index.ts b/packages/opencode/src/mcp/index.ts index efd72c0c1f71..1717799e331f 100644 --- a/packages/opencode/src/mcp/index.ts +++ b/packages/opencode/src/mcp/index.ts @@ -22,8 +22,8 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { McpOAuthProvider, OAUTH_CALLBACK_PATH } from "./oauth-provider" import { McpOAuthCallback } from "./oauth-callback" import { McpAuth } from "./auth" -import { BusEvent } from "../bus/bus-event" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" import { TuiEvent } from "@/cli/cmd/tui/event" import open from "open" import { Effect, Exit, Layer, Option, Context, Schema, Stream } from "effect" @@ -48,20 +48,20 @@ export const Resource = Schema.Struct({ }).annotate({ identifier: "McpResource" }) export type Resource = Schema.Schema.Type -export const ToolsChanged = BusEvent.define( - "mcp.tools.changed", - Schema.Struct({ +export const ToolsChanged = EventV2.define({ + type: "mcp.tools.changed", + schema: { server: Schema.String, - }), -) + }, +}) -export const BrowserOpenFailed = BusEvent.define( - "mcp.browser.open.failed", - Schema.Struct({ +export const BrowserOpenFailed = EventV2.define({ + type: "mcp.browser.open.failed", + schema: { mcpName: Schema.String, url: Schema.String, - }), -) + }, +}) export const Failed = NamedError.create("MCPFailed", { name: Schema.String, @@ -234,6 +234,7 @@ interface AuthResult { // --- Effect Service --- interface State { + config: Record status: Record clients: Record defs: Record @@ -277,7 +278,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner const auth = yield* McpAuth.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service type Transport = StdioClientTransport | StreamableHTTPClientTransport | SSEClientTransport @@ -372,7 +373,7 @@ export const layer = Layer.effect( status: "needs_client_registration" as const, error: "Server does not support dynamic client registration. Please provide clientId in config.", } - return bus + return events .publish(TuiEvent.ToastShow, { title: "MCP Authentication Required", message: `Server "${key}" requires a pre-registered client ID. Add clientId to your config.`, @@ -383,7 +384,7 @@ export const layer = Layer.effect( } else { pendingOAuthTransports.set(key, transport) lastStatus = { status: "needs_auth" as const } - return bus + return events .publish(TuiEvent.ToastShow, { title: "MCP Authentication Required", message: `Server "${key}" requires authentication. Run: opencode mcp auth ${key}`, @@ -515,7 +516,7 @@ export const layer = Layer.effect( if (s.clients[name] !== client || s.status[name]?.status !== "connected") return s.defs[name] = listed - await bridge.promise(bus.publish(ToolsChanged, { server: name }).pipe(Effect.ignore)) + await bridge.promise(events.publish(ToolsChanged, { server: name }).pipe(Effect.ignore)) }) } @@ -525,6 +526,7 @@ export const layer = Layer.effect( const bridge = yield* EffectBridge.make() const config = cfg.mcp ?? {} const s: State = { + config: {}, status: {}, clients: {}, defs: {}, @@ -619,6 +621,10 @@ export const layer = Layer.effect( result[key] = s.status[key] ?? { status: "disabled" } } + for (const key of Object.keys(s.config)) { + result[key] = s.status[key] ?? { status: "disabled" } + } + return result }) @@ -642,8 +648,9 @@ export const layer = Layer.effect( }) const add = Effect.fn("MCP.add")(function* (name: string, mcp: ConfigMCP.Info) { - yield* createAndStore(name, mcp) const s = yield* InstanceState.get(state) + s.config[name] = mcp + yield* createAndStore(name, mcp) return { status: s.status } }) @@ -677,7 +684,7 @@ export const layer = Layer.effect( ([clientName, client]) => Effect.gen(function* () { const mcpConfig = config[clientName] - const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : undefined + const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : s.config[clientName] const listed = s.defs[clientName] if (!listed) { @@ -756,6 +763,9 @@ export const layer = Layer.effect( }) const getMcpConfig = Effect.fnUntraced(function* (mcpName: string) { + const s = yield* InstanceState.get(state) + if (s.config[mcpName]) return s.config[mcpName] + const cfg = yield* cfgSvc.get() const mcpConfig = cfg.mcp?.[mcpName] if (!mcpConfig || !isMcpConfigured(mcpConfig)) return undefined @@ -870,7 +880,7 @@ export const layer = Layer.effect( ), Effect.catch(() => { log.warn("failed to open browser, user must open URL manually", { mcpName }) - return bus.publish(BrowserOpenFailed, { mcpName, url: result.authorizationUrl }).pipe(Effect.ignore) + return events.publish(BrowserOpenFailed, { mcpName, url: result.authorizationUrl }).pipe(Effect.ignore) }), ) @@ -961,8 +971,8 @@ export type AuthStatus = "authenticated" | "expired" | "not_authenticated" // --- Per-service runtime --- export const defaultLayer = layer.pipe( - Layer.provide(McpAuth.layer), - Layer.provide(Bus.layer), + Layer.provide(McpAuth.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(Config.defaultLayer), Layer.provide(CrossSpawnSpawner.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), diff --git a/packages/opencode/src/node.ts b/packages/opencode/src/node.ts index 9c29dcd984ab..48b4293d19e6 100644 --- a/packages/opencode/src/node.ts +++ b/packages/opencode/src/node.ts @@ -2,5 +2,5 @@ export { Config } from "@/config/config" export { Server } from "./server/server" export { bootstrap } from "./cli/bootstrap" export * as Log from "@opencode-ai/core/util/log" -export { Database } from "@/storage/db" +export { Database } from "@opencode-ai/core/database/database" export { JsonMigration } from "@/storage/json-migration" diff --git a/packages/opencode/src/permission/index.ts b/packages/opencode/src/permission/index.ts index 1814c5ab2ba8..220abc8348a8 100644 --- a/packages/opencode/src/permission/index.ts +++ b/packages/opencode/src/permission/index.ts @@ -1,11 +1,9 @@ -import { Bus } from "@/bus" -import { BusEvent } from "@/bus/bus-event" import { ConfigPermission } from "@/config/permission" import { InstanceState } from "@/effect/instance-state" -import { ProjectID } from "@/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { MessageID, SessionID } from "@/session/schema" -import { PermissionTable } from "@/session/session.sql" -import { Database } from "@/storage/db" +import { PermissionTable } from "@opencode-ai/core/session/sql" +import { Database } from "@opencode-ai/core/database/database" import { eq } from "drizzle-orm" import * as Log from "@opencode-ai/core/util/log" import { Wildcard } from "@opencode-ai/core/util/wildcard" @@ -13,6 +11,8 @@ import { Deferred, Effect, Layer, Schema, Context } from "effect" import os from "os" import { PermissionV2 } from "@opencode-ai/core/permission" import { PermissionID } from "./schema" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" const log = Log.create({ service: "permission" }) @@ -61,21 +61,21 @@ export const ReplyBody = Schema.Struct(reply).annotate({ identifier: "Permission export type ReplyBody = Schema.Schema.Type export const Approval = Schema.Struct({ - projectID: ProjectID, + projectID: ProjectV2.ID, patterns: Schema.Array(Schema.String), }).annotate({ identifier: "PermissionApproval" }) export type Approval = Schema.Schema.Type export const Event = { - Asked: BusEvent.define("permission.asked", Request), - Replied: BusEvent.define( - "permission.replied", - Schema.Struct({ + Asked: EventV2.define({ type: "permission.asked", schema: Request.fields }), + Replied: EventV2.define({ + type: "permission.replied", + schema: { sessionID: SessionID, requestID: PermissionID, reply: Reply, - }), - ), + }, + }), } export class RejectedError extends Schema.TaggedErrorClass()("PermissionRejectedError", {}) { @@ -144,12 +144,16 @@ export class Service extends Context.Service()("@opencode/Pe export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service + const { db } = yield* Database.Service const state = yield* InstanceState.make( Effect.fn("Permission.state")(function* (ctx) { - const row = Database.use((db) => - db.select().from(PermissionTable).where(eq(PermissionTable.project_id, ctx.project.id)).get(), - ) + const row = yield* db + .select() + .from(PermissionTable) + .where(eq(PermissionTable.project_id, ctx.project.id)) + .get() + .pipe(Effect.orDie) const state = { pending: new Map(), approved: [...(row?.data ?? [])], @@ -201,7 +205,7 @@ export const layer = Layer.effect( const deferred = yield* Deferred.make() pending.set(id, { info, deferred }) - yield* bus.publish(Event.Asked, info) + yield* events.publish(Event.Asked, info) return yield* Effect.ensuring( Deferred.await(deferred), Effect.sync(() => { @@ -216,7 +220,7 @@ export const layer = Layer.effect( if (!existing) return yield* new NotFoundError({ requestID: input.requestID }) pending.delete(input.requestID) - yield* bus.publish(Event.Replied, { + yield* events.publish(Event.Replied, { sessionID: existing.info.sessionID, requestID: existing.info.id, reply: input.reply, @@ -231,7 +235,7 @@ export const layer = Layer.effect( for (const [id, item] of pending.entries()) { if (item.info.sessionID !== existing.info.sessionID) continue pending.delete(id) - yield* bus.publish(Event.Replied, { + yield* events.publish(Event.Replied, { sessionID: item.info.sessionID, requestID: item.info.id, reply: "reject", @@ -259,7 +263,7 @@ export const layer = Layer.effect( ) if (!ok) continue pending.delete(id) - yield* bus.publish(Event.Replied, { + yield* events.publish(Event.Replied, { sessionID: item.info.sessionID, requestID: item.info.id, reply: "always", @@ -307,6 +311,6 @@ export function disabled(tools: string[], ruleset: Ruleset): Set { return PermissionV2.disabled(tools, ruleset) } -export const defaultLayer = layer.pipe(Layer.provide(Bus.layer)) +export const defaultLayer = layer.pipe(Layer.provide(Database.defaultLayer), Layer.provide(EventV2Bridge.defaultLayer)) export * as Permission from "." diff --git a/packages/opencode/src/plugin/digitalocean.ts b/packages/opencode/src/plugin/digitalocean.ts index 19d1364875d9..d04437a4ea81 100644 --- a/packages/opencode/src/plugin/digitalocean.ts +++ b/packages/opencode/src/plugin/digitalocean.ts @@ -3,18 +3,20 @@ import type { Model } from "@opencode-ai/sdk/v2" import * as Log from "@opencode-ai/core/util/log" import { InstallationVersion } from "@opencode-ai/core/installation/version" import { createServer } from "http" +import open from "open" const log = Log.create({ service: "plugin.digitalocean" }) const DO_OAUTH_CLIENT_ID = "b1a6c5158156caac821fd1b30253ca8acb52454a48fa744420e41889cb589f82" const DO_AUTHORIZE_URL = "https://cloud.digitalocean.com/v1/oauth/authorize" const DO_API_BASE = "https://api.digitalocean.com" +const DO_GENAI_API = `${DO_API_BASE}/v2/gen-ai` const DO_INFERENCE_BASE = "https://inference.do-ai.run/v1" const OAUTH_PORT = 1456 const OAUTH_REDIRECT_PATH = "/auth/callback" const OAUTH_TOKEN_PATH = "/auth/token" const ROUTER_REFRESH_INTERVAL_MS = 5 * 60 * 1000 -const MAK_NAME_PREFIX = "opencode-oauth" +const OAUTH_SCOPES = "genai:read inference:query" interface ImplicitTokenPayload { access_token: string @@ -28,12 +30,6 @@ interface PendingOAuth { reject: (error: Error) => void } -interface ApiKeyInfo { - uuid: string - name: string - secret_key: string -} - interface RouterEntry { name: string uuid?: string @@ -59,7 +55,7 @@ function buildAuthorizeUrl(state: string): string { response_type: "token", client_id: DO_OAUTH_CLIENT_ID, redirect_uri: redirectUri(), - scope: "genai:create genai:read", + scope: OAUTH_SCOPES, state, }) return `${DO_AUTHORIZE_URL}?${params.toString()}` @@ -91,15 +87,20 @@ const HTML_CALLBACK = ` const errorDescription = params.get("error_description") || search.get("error_description") const titleEl = document.getElementById("title") const msgEl = document.getElementById("msg") + const tokenUrl = new URL(${JSON.stringify(OAUTH_TOKEN_PATH)}, window.location.origin).href try { const body = error ? { error, error_description: errorDescription || "" } : { access_token: params.get("access_token") || "", expires_in: params.get("expires_in") || "0", state: params.get("state") || "" } - await fetch(${JSON.stringify(OAUTH_TOKEN_PATH)}, { + const res = await fetch(tokenUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }) + if (!res.ok) { + const detail = await res.text().catch(function () { return "" }) + throw new Error(detail || ("callback failed (" + res.status + ")")) + } if (error) { titleEl.textContent = "Authorization Failed" msgEl.textContent = errorDescription || error @@ -225,31 +226,10 @@ function waitForOAuthCallback(state: string): Promise { }) } -async function createModelAccessKey(bearer: string): Promise { - // Suffix-on-collision strategy keeps re-`/connect` non-destructive. - const name = `${MAK_NAME_PREFIX}-${Math.floor(Date.now() / 1000)}` - const res = await fetch(`${DO_API_BASE}/v2/gen-ai/models/api_keys`, { - method: "POST", - headers: { - Authorization: `Bearer ${bearer}`, - "Content-Type": "application/json", - "User-Agent": `opencode/${InstallationVersion}`, - }, - body: JSON.stringify({ name }), - }) - if (!res.ok) { - const body = await res.text().catch(() => "") - throw new Error(`Failed to create Model Access Key (${res.status}): ${body}`) - } - const data = (await res.json()) as { api_key_info?: ApiKeyInfo } - if (!data.api_key_info?.secret_key) throw new Error("Model Access Key response missing secret_key") - return data.api_key_info -} - async function listRouters( bearer: string, ): Promise<{ ok: true; routers: RouterEntry[] } | { ok: false; status: number }> { - const res = await fetch(`${DO_API_BASE}/v2/gen-ai/models/routers`, { + const res = await fetch(`${DO_GENAI_API}/models/routers`, { headers: { Authorization: `Bearer ${bearer}`, Accept: "application/json", @@ -362,15 +342,16 @@ export async function DigitalOceanAuthPlugin(input: PluginInput): Promise await startOAuthServer() const state = generateState() const callbackPromise = waitForOAuthCallback(state) + const url = buildAuthorizeUrl(state) + await open(url).catch(() => undefined) return { - url: buildAuthorizeUrl(state), + url, instructions: - "Sign in to DigitalOcean in your browser. OpenCode will create a Model Access Key named opencode-oauth-* and load your Inference Routers. Re-run /connect to refresh routers later.", + "Sign in to DigitalOcean in your browser. OpenCode will use your DigitalOcean API token directly for inference and load your Inference Routers. Re-run /connect to refresh routers later.", method: "auto" as const, async callback() { try { const tokens = await callbackPromise - const apiKeyInfo = await createModelAccessKey(tokens.access_token) const routerResult = await listRouters(tokens.access_token) const routers = routerResult.ok ? routerResult.routers : [] if (!routerResult.ok) { @@ -379,12 +360,11 @@ export async function DigitalOceanAuthPlugin(input: PluginInput): Promise return { type: "success" as const, provider: "digitalocean", - key: apiKeyInfo.secret_key, + key: tokens.access_token, metadata: { - mak_uuid: apiKeyInfo.uuid, - mak_name: apiKeyInfo.name, oauth_access: tokens.access_token, oauth_expires: String(Date.now() + tokens.expires_in * 1000), + oauth_scopes: OAUTH_SCOPES, routers: JSON.stringify( routers.map((r) => ({ name: r.name, uuid: r.uuid, description: r.description })), ), diff --git a/packages/opencode/src/plugin/index.ts b/packages/opencode/src/plugin/index.ts index e59fefe08060..478114209207 100644 --- a/packages/opencode/src/plugin/index.ts +++ b/packages/opencode/src/plugin/index.ts @@ -6,11 +6,10 @@ import type { WorkspaceAdapter as PluginWorkspaceAdapter, } from "@opencode-ai/plugin" import { Config } from "@/config/config" -import { Bus } from "../bus" import * as Log from "@opencode-ai/core/util/log" import { createOpencodeClient } from "@opencode-ai/sdk" import { ServerAuth } from "@/server/auth" -import { CodexAuthPlugin } from "./codex" +import { CodexAuthPlugin } from "./openai/codex" import { Session } from "@/session/session" import { NamedError } from "@opencode-ai/core/util/error" import { CopilotAuthPlugin } from "./github-copilot/copilot" @@ -20,7 +19,7 @@ import { CloudflareAIGatewayAuthPlugin, CloudflareWorkersAuthPlugin } from "./cl import { AzureAuthPlugin } from "./azure" import { DigitalOceanAuthPlugin } from "./digitalocean" import { XaiAuthPlugin } from "./xai" -import { Effect, Layer, Context, Stream } from "effect" +import { Effect, Layer, Context } from "effect" import { EffectBridge } from "@/effect/bridge" import { InstanceState } from "@/effect/instance-state" import { errorMessage } from "@/util/error" @@ -29,6 +28,8 @@ import { parsePluginSpecifier, readPluginId, readV1Plugin, resolvePluginId } fro import { registerAdapter } from "@/control-plane/adapters" import type { WorkspaceAdapter } from "@/control-plane/types" import { RuntimeFlags } from "@/effect/runtime-flags" +import { EventV2Bridge } from "@/event-v2-bridge" +import { InstallationChannel } from "@opencode-ai/core/installation/version" const log = Log.create({ service: "plugin" }) @@ -57,18 +58,28 @@ export interface Interface { export class Service extends Context.Service()("@opencode/Plugin") {} +export function experimentalWebSocketsEnabled(input: { enabled: boolean; channel?: string }) { + return input.enabled || ["local", "dev", "beta"].includes(input.channel ?? InstallationChannel) +} + // Built-in plugins that are directly imported (not installed from npm) -const INTERNAL_PLUGINS: PluginInstance[] = [ - CodexAuthPlugin, - CopilotAuthPlugin, - GitlabAuthPlugin, - PoeAuthPlugin, - CloudflareWorkersAuthPlugin, - CloudflareAIGatewayAuthPlugin, - AzureAuthPlugin, - DigitalOceanAuthPlugin, - XaiAuthPlugin, -] +function internalPlugins(flags: RuntimeFlags.Info): PluginInstance[] { + return [ + // Temporary rollout: pre-release builds use WebSockets by default; releases require explicit opt-in. + (input) => + CodexAuthPlugin(input, { + experimentalWebSockets: experimentalWebSocketsEnabled({ enabled: flags.experimentalWebSockets }), + }), + CopilotAuthPlugin, + GitlabAuthPlugin, + PoeAuthPlugin, + CloudflareWorkersAuthPlugin, + CloudflareAIGatewayAuthPlugin, + AzureAuthPlugin, + DigitalOceanAuthPlugin, + XaiAuthPlugin, + ] +} function isServerPlugin(value: unknown): value is PluginInstance { return typeof value === "function" @@ -112,7 +123,7 @@ async function applyPlugin(load: PluginLoader.Loaded, input: PluginInput, hooks: export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const config = yield* Config.Service const flags = yield* RuntimeFlags.Service @@ -122,7 +133,7 @@ export const layer = Layer.effect( const bridge = yield* EffectBridge.make() function publishPluginError(message: string) { - bridge.fork(bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })) + bridge.fork(events.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })) } const { Server } = yield* Effect.promise(() => import("../server/server")) @@ -151,7 +162,7 @@ export const layer = Layer.effect( $: typeof Bun === "undefined" ? undefined : Bun.$, } - for (const plugin of flags.disableDefaultPlugins ? [] : INTERNAL_PLUGINS) { + for (const plugin of flags.disableDefaultPlugins ? [] : internalPlugins(flags)) { log.info("loading internal plugin", { name: plugin.name }) const init = yield* Effect.tryPromise({ try: () => plugin(input), @@ -224,7 +235,7 @@ export const layer = Layer.effect( }).pipe( Effect.catch(() => { // TODO: make proper events for this - // bus.publish(Session.Event.Error, { + // events.publish(Session.Event.Error, { // error: new NamedError.Unknown({ // message: `Failed to load plugin ${load.spec}: ${message}`, // }).toObject(), @@ -244,16 +255,28 @@ export const layer = Layer.effect( }).pipe(Effect.ignore) } - // Subscribe to bus events, fiber interrupted when scope closes - yield* (yield* bus.subscribeAll()).pipe( - Stream.runForEach((input) => - Effect.sync(() => { - for (const hook of hooks) { - void hook["event"]?.({ event: input as any }) - } - }), + const unsubscribe = yield* events.listen((event) => { + if (event.location?.directory !== ctx.directory) return Effect.void + return Effect.sync(() => { + for (const hook of hooks) { + void hook["event"]?.({ event: { id: event.id, type: event.type, properties: event.data } as any }) + } + }) + }) + yield* Effect.addFinalizer(() => unsubscribe) + + yield* Effect.addFinalizer(() => + Effect.forEach( + hooks, + (hook) => + Effect.tryPromise({ + try: () => Promise.resolve(hook.dispose?.()), + catch: (error) => { + log.error("plugin dispose hook failed", { error }) + }, + }).pipe(Effect.ignore), + { discard: true }, ), - Effect.forkScoped, ) return { hooks } @@ -289,7 +312,7 @@ export const layer = Layer.effect( ) export const defaultLayer = layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), ) diff --git a/packages/opencode/src/plugin/openai/README.md b/packages/opencode/src/plugin/openai/README.md new file mode 100644 index 000000000000..2286b3509d69 --- /dev/null +++ b/packages/opencode/src/plugin/openai/README.md @@ -0,0 +1,31 @@ +# OpenAI Responses WebSocket + +Enabled by default on `local`, `dev`, and `beta`. On `latest` and `prod`, set `OPENCODE_EXPERIMENTAL_WEBSOCKETS=true`. + +## Flow + +1. A streamed `POST /responses` request arrives. +2. If it has no `session-id` or `x-session-affinity` header, use HTTP. +3. Title requests use HTTP. +4. If that session's socket is busy or already in fallback mode, use HTTP. +5. Otherwise, reuse its open socket or open a new one. +6. Send `response.create` and return WebSocket events as SSE. + +## Lifetime + +- Connect timeout: 15 seconds. +- Idle timeout: 5 minutes. +- After a completed response, keep the socket for reuse. +- Reuse a socket for up to 55 minutes, then replace it on the next request. + +## Retries + +- Retry WebSocket stream/setup failures up to 5 times, then use HTTP for that session until the pool entry is idle-pruned. +- `websocket_connection_limit_reached` consumes the same retry budget and HTTP fallback. +- If a WebSocket fails after its first event, fail it as retryable rather than replaying partial output in transport. +- Abort or cancel closes the socket. + +## Next Steps + +- `previous_response_id` continuation. +- Optional second WebSocket for concurrent requests in one session. Currently these use HTTP. diff --git a/packages/opencode/src/plugin/codex.ts b/packages/opencode/src/plugin/openai/codex.ts similarity index 91% rename from packages/opencode/src/plugin/codex.ts rename to packages/opencode/src/plugin/openai/codex.ts index df4b4d0d5c05..7ed48d087959 100644 --- a/packages/opencode/src/plugin/codex.ts +++ b/packages/opencode/src/plugin/openai/codex.ts @@ -1,10 +1,11 @@ import type { Hooks, PluginInput } from "@opencode-ai/plugin" import * as Log from "@opencode-ai/core/util/log" import { InstallationVersion } from "@opencode-ai/core/installation/version" -import { OAUTH_DUMMY_KEY } from "../auth" +import { OAUTH_DUMMY_KEY } from "../../auth" import os from "os" import { setTimeout as sleep } from "node:timers/promises" import { createServer } from "http" +import { OpenAIWebSocketPool } from "./ws-pool" const log = Log.create({ service: "plugin.codex" }) @@ -28,20 +29,12 @@ interface PkceCodes { } async function generatePKCE(): Promise { - const verifier = generateRandomString(43) - const encoder = new TextEncoder() - const data = encoder.encode(verifier) - const hash = await crypto.subtle.digest("SHA-256", data) - const challenge = base64UrlEncode(hash) - return { verifier, challenge } -} - -function generateRandomString(length: number): string { const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" - const bytes = crypto.getRandomValues(new Uint8Array(length)) - return Array.from(bytes) + const verifier = Array.from(crypto.getRandomValues(new Uint8Array(43))) .map((b) => chars[b % chars.length]) .join("") + const challenge = base64UrlEncode(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))) + return { verifier, challenge } } function base64UrlEncode(buffer: ArrayBuffer): string { @@ -50,10 +43,6 @@ function base64UrlEncode(buffer: ArrayBuffer): string { return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") } -function generateState(): string { - return base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer) -} - export interface IdTokenClaims { chatgpt_account_id?: string organizations?: Array<{ id: string }> @@ -120,6 +109,7 @@ interface TokenResponse { interface CodexAuthPluginOptions { issuer?: string codexApiEndpoint?: string + experimentalWebSockets?: boolean } async function exchangeCodeForTokens(code: string, redirectUri: string, pkce: PkceCodes): Promise { @@ -371,8 +361,14 @@ function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise { const issuer = options.issuer ?? ISSUER const codexApiEndpoint = options.codexApiEndpoint ?? CODEX_API_ENDPOINT + let websocketFetchInstalled = false + const websocketFetches: Array> = [] return { + async dispose() { + for (const websocketFetch of websocketFetches) websocketFetch.close() + websocketFetches.length = 0 + }, provider: { id: "openai", async models(provider, ctx) { @@ -410,7 +406,14 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug provider: "openai", async loader(getAuth) { const auth = await getAuth() - if (auth.type !== "oauth") return {} + const websocketFetch = options.experimentalWebSockets + ? OpenAIWebSocketPool.createWebSocketFetch({ httpFetch: fetch }) + : undefined + if (websocketFetch) { + websocketFetches.push(websocketFetch) + websocketFetchInstalled = true + } + if (auth.type !== "oauth") return websocketFetch ? { fetch: websocketFetch } : {} let refreshPromise: | Promise<{ @@ -422,7 +425,6 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug return { apiKey: OAUTH_DUMMY_KEY, async fetch(requestInput: RequestInfo | URL, init?: RequestInit) { - // Remove dummy API key authorization header if (init?.headers) { if (init.headers instanceof Headers) { init.headers.delete("authorization") @@ -436,12 +438,11 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug } const currentAuth = await getAuth() - if (currentAuth.type !== "oauth") return fetch(requestInput, init) + if (currentAuth.type !== "oauth") + return websocketFetch ? websocketFetch(requestInput, init) : fetch(requestInput, init) - // Cast to include accountId field const authWithAccount = currentAuth as typeof currentAuth & { accountId?: string } - // Check if token needs refresh if (!currentAuth.access || currentAuth.expires < Date.now()) { if (!refreshPromise) { log.info("refreshing codex access token") @@ -473,7 +474,6 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug authWithAccount.accountId = refreshed.accountId } - // Build headers const headers = new Headers() if (init?.headers) { if (init.headers instanceof Headers) { @@ -488,16 +488,11 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug } } } - - // Set authorization header with access token headers.set("authorization", `Bearer ${currentAuth.access}`) - - // Set ChatGPT-Account-Id header for organization subscriptions if (authWithAccount.accountId) { headers.set("ChatGPT-Account-Id", authWithAccount.accountId) } - // Rewrite URL to Codex endpoint const parsed = requestInput instanceof URL ? requestInput @@ -507,10 +502,12 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug ? new URL(codexApiEndpoint) : parsed - return fetch(url, { + const requestInit = { ...init, headers, - }) + } + if (websocketFetch && parsed.pathname.endsWith("/responses")) return websocketFetch(url, requestInit) + return fetch(url, OpenAIWebSocketPool.withoutInternalHeaders(requestInit)) }, } }, @@ -521,7 +518,7 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug authorize: async () => { const { redirectUri } = await startOAuthServer() const pkce = await generatePKCE() - const state = generateState() + const state = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer) const authUrl = buildAuthorizeUrl(redirectUri, pkce, state) const callbackPromise = waitForOAuthCallback(pkce, state) @@ -638,7 +635,11 @@ export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPlug if (input.model.providerID !== "openai") return output.headers.originator = "opencode" output.headers["User-Agent"] = `opencode/${InstallationVersion} (${os.platform()} ${os.release()}; ${os.arch()})` - output.headers.session_id = input.sessionID + output.headers["session-id"] = input.sessionID + // Temporary fetch-layer hack: title generation currently shares the conversation + // session ID, so the OpenAI plugin marks it for HTTP fallback until transport + // context can be passed directly instead of smuggled through headers. + if (websocketFetchInstalled && input.agent === "title") output.headers[OpenAIWebSocketPool.TITLE_HEADER] = "true" }, "chat.params": async (input, output) => { if (input.model.providerID !== "openai") return diff --git a/packages/opencode/src/plugin/openai/ws-pool.ts b/packages/opencode/src/plugin/openai/ws-pool.ts new file mode 100644 index 000000000000..3316570976ec --- /dev/null +++ b/packages/opencode/src/plugin/openai/ws-pool.ts @@ -0,0 +1,272 @@ +import WebSocket from "ws" +import * as Log from "@opencode-ai/core/util/log" +import { ProviderError } from "@/provider/error" +import { isRecord } from "@/util/record" +import { OpenAIWebSocket } from "./ws" + +export const TITLE_HEADER = "x-opencode-title" + +const log = Log.create({ service: "plugin.openai.ws" }) + +export interface CreateWebSocketFetchOptions { + httpFetch?: typeof globalThis.fetch + url?: string + connectTimeout?: number + idleTimeout?: number + maxConnectionAge?: number + streamRetries?: number +} + +interface PoolEntry { + socket?: WebSocket + connectedAt?: number + lastUsedAt: number + busy: boolean + fallback: boolean + streamFailures: number +} + +const DEFAULT_CONNECT_TIMEOUT = 15_000 +const DEFAULT_IDLE_TIMEOUT = 5 * 60 * 1000 +const DEFAULT_MAX_CONNECTION_AGE = 55 * 60 * 1000 +const CONNECTION_LIMIT_REACHED_CODE = "websocket_connection_limit_reached" + +export function createWebSocketFetch(options?: CreateWebSocketFetchOptions) { + const httpFetch = options?.httpFetch ?? globalThis.fetch + const pool = new Map() + const connectTimeout = options?.connectTimeout ?? DEFAULT_CONNECT_TIMEOUT + const idleTimeout = options?.idleTimeout ?? DEFAULT_IDLE_TIMEOUT + const maxConnectionAge = options?.maxConnectionAge ?? DEFAULT_MAX_CONNECTION_AGE + const streamRetries = options?.streamRetries ?? 5 + const pruneTimer = setInterval(() => prune(), Math.min(idleTimeout, 60_000)) + if (typeof pruneTimer === "object" && "unref" in pruneTimer && typeof pruneTimer.unref === "function") { + pruneTimer.unref() + } + + async function websocketFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + const url = input instanceof URL ? input.toString() : typeof input === "string" ? input : input.url + const internalHeaders = OpenAIWebSocket.normalizeHeaders(init?.headers) + const httpInit = withoutInternalHeaders(init) + + if (init?.method !== "POST" || !new URL(url).pathname.endsWith("/responses")) { + return httpFetch(input, httpInit) + } + + const body = (() => { + try { + if (typeof init?.body !== "string") return undefined + const parsed = JSON.parse(init.body) + return typeof parsed === "object" && parsed !== null ? parsed : undefined + } catch { + return undefined + } + })() + if (!body?.stream) return httpFetch(input, httpInit) + if (internalHeaders[TITLE_HEADER] === "true") { + log.debug("http fallback", { reason: "title" }) + return httpFetch(input, httpInit) + } + + const sessionID = internalHeaders["x-session-affinity"] ?? internalHeaders["session-id"] + if (!sessionID) { + log.debug("http fallback", { reason: "missing_session" }) + return httpFetch(input, httpInit) + } + const key = `${sessionID}:conversation` + + const entry = pool.get(key) ?? { lastUsedAt: Date.now(), busy: false, fallback: false, streamFailures: 0 } + pool.set(key, entry) + + if (entry.fallback) { + log.debug("http fallback", { key, reason: "fallback_active" }) + return httpFetch(input, httpInit) + } + if (entry.busy) { + log.debug("http fallback", { key, reason: "busy" }) + return httpFetch(input, httpInit) + } + + entry.busy = true + entry.lastUsedAt = Date.now() + try { + entry.socket = await socket( + entry, + options?.url ?? url, + OpenAIWebSocket.normalizeHeaders(httpInit?.headers), + connectTimeout, + maxConnectionAge, + init?.signal, + ) + let resolveFirstEvent: (started: boolean) => void = () => {} + let rejectFirstEvent: (error: Error) => void = () => {} + const firstEvent = new Promise((resolve, reject) => { + resolveFirstEvent = resolve + rejectFirstEvent = reject + }) + const response = OpenAIWebSocket.streamResponsesWebSocket({ + socket: entry.socket, + body, + idleTimeout, + signal: init?.signal ?? undefined, + onFirstEvent: () => resolveFirstEvent(true), + onTerminal: (event) => { + entry.busy = false + entry.lastUsedAt = Date.now() + entry.streamFailures = 0 + if (event.type !== "response.completed" && event.type !== "response.done") { + log.warn("websocket terminal failure", { key, type: event.type }) + invalidate(entry) + } + }, + onConnectionInvalid: (error) => { + log.warn("websocket invalidated", { key, error: error.message }) + entry.busy = false + if (!entry.fallback) recordStreamFailure(entry) + invalidate(entry) + resolveFirstEvent(false) + }, + onAbort: (error) => { + log.debug("websocket aborted", { key }) + entry.busy = false + entry.lastUsedAt = Date.now() + entry.streamFailures = 0 + invalidate(entry) + rejectFirstEvent(error) + }, + onRetryableTerminal: async (event) => { + const error = connectionLimitError(event) + if (!error) return undefined + log.warn("websocket connection limit reached", { key }) + throw error + }, + }) + if (await firstEvent) return response + if (!entry.fallback) return response + log.debug("http fallback", { key, reason: "websocket_retries_exhausted" }) + return httpFetch(input, httpInit) + } catch (error) { + entry.busy = false + entry.lastUsedAt = Date.now() + if (OpenAIWebSocket.isAbortError(error)) { + entry.streamFailures = 0 + invalidate(entry) + throw error + } + + recordStreamFailure(entry) + log.warn("websocket setup failed", { + key, + error: error instanceof Error ? error.message : String(error), + fallback: entry.fallback ? "http" : undefined, + }) + invalidate(entry) + if (entry.fallback) return httpFetch(input, httpInit) + return failedResponse( + new ProviderError.ResponseStreamError(error instanceof Error ? error.message : String(error), { + cause: error, + }), + ) + } + } + + function recordStreamFailure(entry: PoolEntry) { + entry.streamFailures++ + // Codex counts retries after the initial failed WebSocket attempt. + if (entry.streamFailures > streamRetries) entry.fallback = true + } + + function prune() { + const now = Date.now() + for (const [key, entry] of pool) { + if (entry.busy) continue + if (now - entry.lastUsedAt < idleTimeout) continue + log.debug("websocket idle prune", { key }) + invalidate(entry) + pool.delete(key) + } + } + + function close() { + log.debug("websocket pool close", { count: pool.size }) + clearInterval(pruneTimer) + for (const entry of pool.values()) invalidate(entry) + pool.clear() + } + + return Object.assign(websocketFetch, { close }) +} + +function connectionLimitError(event: Record) { + if (event.type !== "error" || !isRecord(event.error) || event.error.code !== CONNECTION_LIMIT_REACHED_CODE) return + return new Error(typeof event.error.message === "string" ? event.error.message : CONNECTION_LIMIT_REACHED_CODE) +} + +function failedResponse(error: ProviderError.ResponseStreamError) { + return new Response( + new ReadableStream({ + start(controller) { + controller.error(error) + }, + }), + { + status: 200, + headers: { "content-type": "text/event-stream" }, + }, + ) +} + +async function socket( + entry: PoolEntry, + url: string, + headers: Record, + connectTimeout: number, + maxConnectionAge: number, + signal?: AbortSignal | null, +) { + if ( + entry.socket?.readyState === WebSocket.OPEN && + entry.connectedAt && + Date.now() - entry.connectedAt < maxConnectionAge + ) { + return entry.socket + } + + invalidate(entry) + const next = await OpenAIWebSocket.connectResponsesWebSocket({ + url: OpenAIWebSocket.toWebSocketUrl(url), + headers, + timeout: connectTimeout, + signal: signal ?? undefined, + }) + entry.connectedAt = Date.now() + return next +} + +function invalidate(entry: PoolEntry) { + if (entry.socket) { + entry.socket.on("error", () => {}) + entry.socket.terminate() + entry.socket = undefined + } + entry.connectedAt = undefined +} + +export function withoutInternalHeaders(init: T | undefined): T | undefined { + if (!init?.headers) return init + if (init.headers instanceof Headers) { + const headers = new Headers(init.headers) + headers.delete(TITLE_HEADER) + return { ...init, headers } + } + + if (Array.isArray(init.headers)) { + return { ...init, headers: init.headers.filter((item) => item[0].toLowerCase() !== TITLE_HEADER) } + } + + return { + ...init, + headers: Object.fromEntries(Object.entries(init.headers).filter(([key]) => key.toLowerCase() !== TITLE_HEADER)), + } +} + +export * as OpenAIWebSocketPool from "./ws-pool" diff --git a/packages/opencode/src/plugin/openai/ws.ts b/packages/opencode/src/plugin/openai/ws.ts new file mode 100644 index 000000000000..7ff8d7bb8312 --- /dev/null +++ b/packages/opencode/src/plugin/openai/ws.ts @@ -0,0 +1,334 @@ +// Low-level OpenAI Responses WebSocket protocol helpers. Session pooling, +// fallback, and continuation state intentionally live above this file. + +import WebSocket from "ws" +import { ProviderError } from "@/provider/error" +import { errorMessage } from "@/util/error" +import { ProxyEnv } from "@/util/proxy-env" + +export const PROTOCOL_HEADER = "responses_websockets=2026-02-06" + +export interface ConnectResponsesWebSocketOptions { + url: string + headers: Record + timeout?: number + signal?: AbortSignal +} + +export interface StreamResponsesWebSocketOptions { + socket: WebSocket + body: Record + idleTimeout?: number + signal?: AbortSignal + onFirstEvent?: () => void + onComplete?: (event: Record) => void + onTerminal?: (event: Record) => void + onRetryableTerminal?: (event: Record) => Promise + onConnectionInvalid?: (error: ProviderError.ResponseStreamError) => void + onAbort?: (error: Error) => void +} + +export function toWebSocketUrl(url: string) { + return url.replace(/^http/, "ws") +} + +export function normalizeHeaders(headers: HeadersInit | undefined): Record { + const result: Record = {} + if (!headers) return result + + if (headers instanceof Headers) { + headers.forEach((value, key) => { + result[key.toLowerCase()] = value + }) + return result + } + + if (Array.isArray(headers)) { + for (const [key, value] of headers) { + result[key.toLowerCase()] = value + } + return result + } + + for (const [key, value] of Object.entries(headers)) { + if (value != null) result[key.toLowerCase()] = value + } + return result +} + +export function isAbortError(error: unknown): error is DOMException { + return error instanceof DOMException && error.name === "AbortError" +} + +export function connectResponsesWebSocket(options: ConnectResponsesWebSocketOptions) { + return new Promise((resolve, reject) => { + if (options.signal?.aborted) { + reject(abortError(options.signal)) + return + } + + const headers: Record = { + ...options.headers, + "openai-beta": options.headers["openai-beta"] ?? PROTOCOL_HEADER, + } + delete headers["content-length"] + + // Bun does not apply HTTP(S)_PROXY to WebSockets unless the proxy is supplied explicitly. + const proxy = + typeof Bun === "undefined" + ? undefined + : ProxyEnv.getProxyForUrl(options.url.replace(/^wss:/, "https:").replace(/^ws:/, "http:")) + const connect = { headers, ...(proxy ? { proxy } : {}) } + const socket = new WebSocket(options.url, connect) + const timeout = options.timeout + ? setTimeout(() => { + cleanup() + socket.on("error", () => {}) + socket.terminate() + reject(new Error("WebSocket connect timed out")) + }, options.timeout) + : undefined + + function cleanup() { + if (timeout) clearTimeout(timeout) + socket.off("open", onOpen) + socket.off("error", onError) + socket.off("close", onClose) + options.signal?.removeEventListener("abort", onAbort) + } + + function onOpen() { + cleanup() + resolve(socket) + } + + function onError(error: unknown) { + socket.on("error", () => {}) + cleanup() + reject(error instanceof Error ? error : new Error(errorMessage(error), { cause: error })) + } + + function onClose(code: number, reason: Buffer) { + cleanup() + reject(new Error(closeMessage("WebSocket closed before open", code, reason))) + } + + function onAbort() { + cleanup() + socket.on("error", () => {}) + socket.terminate() + reject(abortError(options.signal)) + } + + socket.once("open", onOpen) + socket.once("error", onError) + socket.once("close", onClose) + options.signal?.addEventListener("abort", onAbort, { once: true }) + }) +} + +export function streamResponsesWebSocket(options: StreamResponsesWebSocketOptions) { + const encoder = new TextEncoder() + + let socket = options.socket + let controller: ReadableStreamDefaultController | undefined + let cleanupSocket = () => {} + let completed = false + let emitted = false + let idleTimer: ReturnType | undefined + + function cleanup() { + if (idleTimer) clearTimeout(idleTimer) + cleanupSocket() + options.signal?.removeEventListener("abort", onAbort) + } + + function terminateSocket(target = socket) { + target.on("error", () => {}) + target.terminate() + } + + function closeCompleted() { + cleanup() + controller?.enqueue(encoder.encode("data: [DONE]\n\n")) + controller?.close() + } + + function invalidate(error: ProviderError.ResponseStreamError) { + if (completed) return + completed = true + cleanup() + options.onConnectionInvalid?.(error) + controller?.error(error) + } + + function resetIdleTimeout(message: string) { + if (completed) return + if (!options.idleTimeout) return + if (idleTimer) clearTimeout(idleTimer) + idleTimer = setTimeout(() => invalidate(new ProviderError.ResponseStreamError(message)), options.idleTimeout) + } + + async function onMessage(data: WebSocket.RawData, isBinary: boolean) { + if (completed) return + if (isBinary) { + invalidate(new ProviderError.ResponseStreamError("Unexpected binary WebSocket frame")) + return + } + + const text = data.toString() + const event = (() => { + try { + const parsed = JSON.parse(text) + return typeof parsed === "object" && parsed !== null ? parsed : undefined + } catch { + return undefined + } + })() + + if (event?.type === "error" && !emitted && options.onRetryableTerminal) { + cleanupSocket() + if (idleTimer) clearTimeout(idleTimer) + idleTimer = undefined + try { + const next = await options.onRetryableTerminal(event) + if (completed) { + if (next) terminateSocket(next) + return + } + if (next) { + attach(next) + return + } + } catch (error) { + invalidate( + new ProviderError.ResponseStreamError(error instanceof Error ? error.message : String(error), { + cause: error, + }), + ) + return + } + } + + if (!emitted) options.onFirstEvent?.() + controller?.enqueue( + encoder.encode( + `${text + .split(/\r?\n/) + .map((line) => `data: ${line}`) + .join("\n")}\n\n`, + ), + ) + emitted = true + resetIdleTimeout("idle timeout waiting for websocket") + + if (!event) return + + if (event.type === "response.completed" || event.type === "response.done") { + completed = true + options.onComplete?.(event) + options.onTerminal?.(event) + closeCompleted() + return + } + + if (event.type === "response.failed" || event.type === "response.incomplete" || event.type === "error") { + completed = true + options.onTerminal?.(event) + closeCompleted() + } + } + + function onError(error: Error) { + invalidate(new ProviderError.ResponseStreamError(error.message, { cause: error })) + } + + function onClose(code: number, reason: Buffer) { + if (completed) return + invalidate( + new ProviderError.ResponseStreamError(closeMessage("WebSocket closed before response.completed", code, reason)), + ) + } + + function onAbort() { + const error = abortError(options.signal) + if (completed) return + completed = true + cleanup() + terminateSocket() + options.onAbort?.(error) + controller?.error(error) + } + + function onCancel(reason: unknown) { + if (completed) return + completed = true + cleanup() + terminateSocket() + options.onAbort?.(cancelError(reason)) + } + + function attach(next: WebSocket) { + cleanupSocket() + socket = next + socket.on("message", onMessage) + socket.once("error", onError) + socket.once("close", onClose) + cleanupSocket = () => { + socket.off("message", onMessage) + socket.off("error", onError) + socket.off("close", onClose) + } + const { stream: _stream, background: _background, ...payload } = options.body + resetIdleTimeout("idle timeout sending websocket request") + socket.send(JSON.stringify({ type: "response.create", ...payload }), (error) => { + if (completed) return + resetIdleTimeout("idle timeout waiting for websocket") + if (error) invalidate(new ProviderError.ResponseStreamError(error.message, { cause: error })) + }) + } + + return new Response( + new ReadableStream({ + start(next) { + controller = next + options.signal?.addEventListener("abort", onAbort, { once: true }) + + if (options.signal?.aborted) { + onAbort() + return + } + + attach(socket) + }, + cancel(reason) { + onCancel(reason) + }, + }), + { + status: 200, + headers: { "content-type": "text/event-stream" }, + }, + ) +} + +function cancelError(reason: unknown) { + if (isAbortError(reason)) return reason + if (reason instanceof Error) return reason + return new DOMException(typeof reason === "string" ? reason : "Aborted", "AbortError") +} + +function abortError(signal: AbortSignal | undefined) { + const reason = signal?.reason + if (isAbortError(reason)) return reason + return new DOMException(reason instanceof Error ? reason.message : "Aborted", "AbortError") +} + +function closeMessage(message: string, code: number, reason: Buffer) { + const details = [`code ${code}`] + if (code === 1009) details.push("message too big") + if (reason.length > 0) details.push(reason.toString()) + return `${message} (${details.join(": ")})` +} + +export * as OpenAIWebSocket from "./ws" diff --git a/packages/opencode/src/project/bootstrap.ts b/packages/opencode/src/project/bootstrap.ts index a7e67d45e9b7..e6c5d698ac5a 100644 --- a/packages/opencode/src/project/bootstrap.ts +++ b/packages/opencode/src/project/bootstrap.ts @@ -5,7 +5,6 @@ import { File } from "../file" import { Snapshot } from "../snapshot" import * as Project from "./project" import * as Vcs from "./vcs" -import { Bus } from "../bus" import { InstanceState } from "@/effect/instance-state" import { FileWatcher } from "@/file/watcher" import { ShareNext } from "@/share/share-next" @@ -57,7 +56,6 @@ export const layer = Layer.effect( export const defaultLayer: Layer.Layer = layer.pipe( Layer.provide([ - Bus.layer, Config.defaultLayer, File.defaultLayer, FileWatcher.defaultLayer, diff --git a/packages/opencode/src/project/instance-store.ts b/packages/opencode/src/project/instance-store.ts index 1f513fb1b49f..ccac93ae15db 100644 --- a/packages/opencode/src/project/instance-store.ts +++ b/packages/opencode/src/project/instance-store.ts @@ -19,6 +19,7 @@ export interface Interface { readonly load: (input: LoadInput) => Effect.Effect readonly reload: (input: LoadInput) => Effect.Effect readonly dispose: (ctx: InstanceContext) => Effect.Effect + readonly disposeDirectory: (directory: string) => Effect.Effect readonly disposeAll: () => Effect.Effect readonly provide: (input: LoadInput, effect: Effect.Effect) => Effect.Effect } @@ -151,6 +152,15 @@ export const layer: Layer.Layer> export const Event = { - Updated: BusEvent.define("project.updated", Info), + Updated: EventV2.define({ type: "project.updated", schema: Info.fields }), } type Row = typeof ProjectTable.$inferSelect @@ -92,7 +91,7 @@ function mergePermissionRules(oldRules: T, newRule } export const UpdateInput = Schema.Struct({ - projectID: ProjectID, + projectID: ProjectV2.ID, name: Schema.optional(Schema.String), icon: Schema.optional(ProjectIcon), commands: Schema.optional(ProjectCommands), @@ -107,7 +106,7 @@ export const UpdatePayload = Schema.Struct({ export type UpdatePayload = Types.DeepMutable> export class NotFoundError extends Schema.TaggedErrorClass()("Project.NotFoundError", { - projectID: ProjectID, + projectID: ProjectV2.ID, }) {} // --------------------------------------------------------------------------- @@ -124,13 +123,13 @@ export interface Interface { readonly fromDirectory: (directory: string) => Effect.Effect<{ project: Info; sandbox: string }> readonly discover: (input: Info) => Effect.Effect readonly list: () => Effect.Effect - readonly get: (id: ProjectID) => Effect.Effect + readonly get: (id: ProjectV2.ID) => Effect.Effect readonly update: (input: UpdateInput) => Effect.Effect readonly initGit: (input: { directory: string; project: Info }) => Effect.Effect - readonly setInitialized: (id: ProjectID) => Effect.Effect - readonly sandboxes: (id: ProjectID) => Effect.Effect - readonly addSandbox: (id: ProjectID, directory: string) => Effect.Effect - readonly removeSandbox: (id: ProjectID, directory: string) => Effect.Effect + readonly setInitialized: (id: ProjectV2.ID) => Effect.Effect + readonly sandboxes: (id: ProjectV2.ID) => Effect.Effect + readonly addSandbox: (id: ProjectV2.ID, directory: string) => Effect.Effect + readonly removeSandbox: (id: ProjectV2.ID, directory: string) => Effect.Effect } export class Service extends Context.Service()("@opencode/Project") {} @@ -144,8 +143,9 @@ export const layer = Layer.effect( const proc = yield* AppProcess.Service const spawner = yield* ChildProcessSpawner.ChildProcessSpawner const projectV2 = yield* ProjectV2.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service + const { db } = yield* Database.Service const git = Effect.fnUntraced( function* (args: string[], opts?: { cwd?: string }) { @@ -163,9 +163,6 @@ export const layer = Layer.effect( Effect.catch(() => Effect.succeed({ code: 1, text: "", stderr: "" } satisfies GitResult)), ) - const db = (fn: (d: Parameters[0] extends (trx: infer D) => any ? D : never) => T) => - Effect.sync(() => Database.use(fn)) - const emitUpdated = (data: Info) => Effect.sync(() => GlobalBus.emit("event", { @@ -180,56 +177,76 @@ export const layer = Layer.effect( const scope = yield* Scope.Scope const migrateProjectId = Effect.fn("Project.migrateProjectId")(function* ( - oldID: ProjectID | undefined, - newID: ProjectID, + oldID: ProjectV2.ID | undefined, + newID: ProjectV2.ID, ) { if (!oldID) return - if (oldID === ProjectID.global) return + if (oldID === ProjectV2.ID.global) return if (oldID === newID) return - yield* Effect.sync(() => - Database.transaction( - (d) => { - const oldProject = d.select().from(ProjectTable).where(eq(ProjectTable.id, oldID)).get() - const newProject = d.select().from(ProjectTable).where(eq(ProjectTable.id, newID)).get() - if (oldProject && !newProject) { - d.insert(ProjectTable) - .values({ - ...oldProject, - id: newID, - time_updated: Date.now(), - }) - .run() - } - - const oldPermission = d.select().from(PermissionTable).where(eq(PermissionTable.project_id, oldID)).get() - const newPermission = d.select().from(PermissionTable).where(eq(PermissionTable.project_id, newID)).get() - if (oldPermission && newPermission) { - d.update(PermissionTable) - .set({ - data: mergePermissionRules(oldPermission.data, newPermission.data), - time_created: Math.min(oldPermission.time_created, newPermission.time_created), - time_updated: Date.now(), - }) + yield* db + .transaction( + (d) => + Effect.gen(function* () { + const oldProject = yield* d.select().from(ProjectTable).where(eq(ProjectTable.id, oldID)).get() + const newProject = yield* d.select().from(ProjectTable).where(eq(ProjectTable.id, newID)).get() + if (oldProject && !newProject) { + yield* d + .insert(ProjectTable) + .values({ + ...oldProject, + id: newID, + time_updated: Date.now(), + }) + .run() + } + + const oldPermission = yield* d + .select() + .from(PermissionTable) + .where(eq(PermissionTable.project_id, oldID)) + .get() + const newPermission = yield* d + .select() + .from(PermissionTable) .where(eq(PermissionTable.project_id, newID)) + .get() + if (oldPermission && newPermission) { + yield* d + .update(PermissionTable) + .set({ + data: mergePermissionRules(oldPermission.data, newPermission.data), + time_created: Math.min(oldPermission.time_created, newPermission.time_created), + time_updated: Date.now(), + }) + .where(eq(PermissionTable.project_id, newID)) + .run() + yield* d.delete(PermissionTable).where(eq(PermissionTable.project_id, oldID)).run() + } + if (oldPermission && !newPermission) { + yield* d + .update(PermissionTable) + .set({ project_id: newID }) + .where(eq(PermissionTable.project_id, oldID)) + .run() + } + + yield* d + .update(SessionTable) + .set({ project_id: newID, time_updated: sql`${SessionTable.time_updated}` }) + .where(eq(SessionTable.project_id, oldID)) .run() - d.delete(PermissionTable).where(eq(PermissionTable.project_id, oldID)).run() - } - if (oldPermission && !newPermission) { - d.update(PermissionTable).set({ project_id: newID }).where(eq(PermissionTable.project_id, oldID)).run() - } - - d.update(SessionTable) - .set({ project_id: newID, time_updated: sql`${SessionTable.time_updated}` }) - .where(eq(SessionTable.project_id, oldID)) - .run() - d.update(WorkspaceTable).set({ project_id: newID }).where(eq(WorkspaceTable.project_id, oldID)).run() - - if (oldProject) d.delete(ProjectTable).where(eq(ProjectTable.id, oldID)).run() - }, + yield* d + .update(WorkspaceTable) + .set({ project_id: newID }) + .where(eq(WorkspaceTable.project_id, oldID)) + .run() + + if (oldProject) yield* d.delete(ProjectTable).where(eq(ProjectTable.id, oldID)).run() + }), { behavior: "immediate" }, - ), - ) + ) + .pipe(Effect.orDie) }) const fromDirectory = Effect.fn("Project.fromDirectory")(function* (directory: string) { @@ -239,9 +256,9 @@ export const layer = Layer.effect( const worktree = data.id === ProjectV2.ID.make("global") && !data.vcs ? "/" : data.directory // Phase 2: upsert - const projectID = ProjectID.make(data.id) - yield* migrateProjectId(data.previous ? ProjectID.make(data.previous) : undefined, projectID) - const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get()) + const projectID = ProjectV2.ID.make(data.id) + yield* migrateProjectId(data.previous ? ProjectV2.ID.make(data.previous) : undefined, projectID) + const row = yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get().pipe(Effect.orDie) const existing = row ? fromRow(row) : { @@ -256,12 +273,12 @@ export const layer = Layer.effect( const result: Info = { ...existing, - worktree: projectID === ProjectID.global ? worktree : existing.worktree, + worktree: projectID === ProjectV2.ID.global ? worktree : existing.worktree, vcs: data.vcs?.type ?? fakeVcs, time: { ...existing.time, updated: Date.now() }, } if ( - projectID !== ProjectID.global && + projectID !== ProjectV2.ID.global && data.directory !== result.worktree && !result.sandboxes.includes(data.directory) ) @@ -276,53 +293,51 @@ export const layer = Layer.effect( { concurrency: "unbounded" }, ).pipe(Effect.map((arr) => arr.filter((x): x is string => x !== undefined))) - yield* db((d) => - d - .insert(ProjectTable) - .values({ - id: result.id, + yield* db + .insert(ProjectTable) + .values({ + id: result.id, + worktree: result.worktree, + vcs: result.vcs ?? null, + name: result.name, + icon_url: result.icon?.url, + icon_url_override: result.icon?.override, + icon_color: result.icon?.color, + time_created: result.time.created, + time_updated: result.time.updated, + time_initialized: result.time.initialized, + sandboxes: result.sandboxes, + commands: result.commands, + }) + .onConflictDoUpdate({ + target: ProjectTable.id, + set: { worktree: result.worktree, vcs: result.vcs ?? null, name: result.name, icon_url: result.icon?.url, icon_url_override: result.icon?.override, icon_color: result.icon?.color, - time_created: result.time.created, time_updated: result.time.updated, time_initialized: result.time.initialized, sandboxes: result.sandboxes, commands: result.commands, - }) - .onConflictDoUpdate({ - target: ProjectTable.id, - set: { - worktree: result.worktree, - vcs: result.vcs ?? null, - name: result.name, - icon_url: result.icon?.url, - icon_url_override: result.icon?.override, - icon_color: result.icon?.color, - time_updated: result.time.updated, - time_initialized: result.time.initialized, - sandboxes: result.sandboxes, - commands: result.commands, - }, - }) - .run(), - ) + }, + }) + .run() + .pipe(Effect.orDie) - if (projectID !== ProjectID.global) { - yield* db((d) => - d - .update(SessionTable) - .set({ project_id: projectID }) - .where(and(eq(SessionTable.project_id, ProjectID.global), eq(SessionTable.directory, data.directory))) - .run(), - ) + if (projectID !== ProjectV2.ID.global) { + yield* db + .update(SessionTable) + .set({ project_id: projectID }) + .where(and(eq(SessionTable.project_id, ProjectV2.ID.global), eq(SessionTable.directory, data.directory))) + .run() + .pipe(Effect.orDie) } yield* emitUpdated(result) - if (projectID !== ProjectID.global && data.vcs?.type === "git") { + if (projectID !== ProjectV2.ID.global && data.vcs?.type === "git") { yield* projectV2.commit({ store: data.vcs.store, id: data.id }) } return { project: result, sandbox: data.vcs ? data.directory : worktree } @@ -353,30 +368,29 @@ export const layer = Layer.effect( }) const list = Effect.fn("Project.list")(function* () { - return yield* db((d) => d.select().from(ProjectTable).all().map(fromRow)) + return (yield* db.select().from(ProjectTable).all().pipe(Effect.orDie)).map(fromRow) }) - const get = Effect.fn("Project.get")(function* (id: ProjectID) { - const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + const get = Effect.fn("Project.get")(function* (id: ProjectV2.ID) { + const row = yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get().pipe(Effect.orDie) return row ? fromRow(row) : undefined }) const update = Effect.fn("Project.update")(function* (input: UpdateInput) { - const result = yield* db((d) => - d - .update(ProjectTable) - .set({ - name: input.name, - icon_url: input.icon?.url, - icon_url_override: input.icon?.override, - icon_color: input.icon?.color, - commands: input.commands, - time_updated: Date.now(), - }) - .where(eq(ProjectTable.id, input.projectID)) - .returning() - .get(), - ) + const result = yield* db + .update(ProjectTable) + .set({ + name: input.name, + icon_url: input.icon?.url, + icon_url_override: input.icon?.override, + icon_color: input.icon?.color, + commands: input.commands, + time_updated: Date.now(), + }) + .where(eq(ProjectTable.id, input.projectID)) + .returning() + .get() + .pipe(Effect.orDie) if (!result) return yield* new NotFoundError({ projectID: input.projectID }) const data = fromRow(result) yield* emitUpdated(data) @@ -394,20 +408,24 @@ export const layer = Layer.effect( return project }) - const setInitialized = Effect.fn("Project.setInitialized")(function* (id: ProjectID) { - yield* db((d) => - d.update(ProjectTable).set({ time_initialized: Date.now() }).where(eq(ProjectTable.id, id)).run(), - ) + const setInitialized = Effect.fn("Project.setInitialized")(function* (id: ProjectV2.ID) { + yield* db + .update(ProjectTable) + .set({ time_initialized: Date.now() }) + .where(eq(ProjectTable.id, id)) + .run() + .pipe(Effect.orDie) }) const initState = yield* InstanceState.make( Effect.fn("Project.initState")(function* (ctx) { - yield* (yield* bus.subscribe(Command.Event.Executed)).pipe( - Stream.runForEach((payload) => - payload.properties.name === Command.Default.INIT ? setInitialized(ctx.project.id) : Effect.void, - ), - Effect.forkScoped, - ) + const unsubscribe = yield* events.listen((event) => { + if (event.type !== Command.Event.Executed.type || event.location?.directory !== ctx.directory) + return Effect.void + const data = event.data as EventV2.Data + return data.name === Command.Default.INIT ? setInitialized(ctx.project.id) : Effect.void + }) + yield* Effect.addFinalizer(() => unsubscribe) }), ) @@ -415,8 +433,8 @@ export const layer = Layer.effect( yield* InstanceState.get(initState) }) - const sandboxes = Effect.fn("Project.sandboxes")(function* (id: ProjectID) { - const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + const sandboxes = Effect.fn("Project.sandboxes")(function* (id: ProjectV2.ID) { + const row = yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get().pipe(Effect.orDie) if (!row) return [] const data = fromRow(row) return yield* Effect.forEach( @@ -430,35 +448,33 @@ export const layer = Layer.effect( ).pipe(Effect.map((arr) => arr.filter((x): x is string => x !== undefined))) }) - const addSandbox = Effect.fn("Project.addSandbox")(function* (id: ProjectID, directory: string) { - const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + const addSandbox = Effect.fn("Project.addSandbox")(function* (id: ProjectV2.ID, directory: string) { + const row = yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get().pipe(Effect.orDie) if (!row) throw new Error(`Project not found: ${id}`) const sboxes = [...row.sandboxes] if (!sboxes.includes(directory)) sboxes.push(directory) - const result = yield* db((d) => - d - .update(ProjectTable) - .set({ sandboxes: sboxes, time_updated: Date.now() }) - .where(eq(ProjectTable.id, id)) - .returning() - .get(), - ) + const result = yield* db + .update(ProjectTable) + .set({ sandboxes: sboxes, time_updated: Date.now() }) + .where(eq(ProjectTable.id, id)) + .returning() + .get() + .pipe(Effect.orDie) if (!result) throw new Error(`Project not found: ${id}`) yield* emitUpdated(fromRow(result)) }) - const removeSandbox = Effect.fn("Project.removeSandbox")(function* (id: ProjectID, directory: string) { - const row = yield* db((d) => d.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) + const removeSandbox = Effect.fn("Project.removeSandbox")(function* (id: ProjectV2.ID, directory: string) { + const row = yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get().pipe(Effect.orDie) if (!row) throw new Error(`Project not found: ${id}`) const sboxes = row.sandboxes.filter((s) => s !== directory) - const result = yield* db((d) => - d - .update(ProjectTable) - .set({ sandboxes: sboxes, time_updated: Date.now() }) - .where(eq(ProjectTable.id, id)) - .returning() - .get(), - ) + const result = yield* db + .update(ProjectTable) + .set({ sandboxes: sboxes, time_updated: Date.now() }) + .where(eq(ProjectTable.id, id)) + .returning() + .get() + .pipe(Effect.orDie) if (!result) throw new Error(`Project not found: ${id}`) yield* emitUpdated(fromRow(result)) }) @@ -480,36 +496,15 @@ export const layer = Layer.effect( ) export const defaultLayer = layer.pipe( - Layer.provide(Bus.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(ProjectV2.defaultLayer), Layer.provide(AppProcess.defaultLayer), Layer.provide(CrossSpawnSpawner.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(Database.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), ) export const use = serviceUse(Service) -export function list() { - return Database.use((db) => - db - .select() - .from(ProjectTable) - .all() - .map((row) => fromRow(row)), - ) -} - -export function get(id: ProjectID): Info | undefined { - const row = Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, id)).get()) - if (!row) return undefined - return fromRow(row) -} - -export function setInitialized(id: ProjectID) { - Database.use((db) => - db.update(ProjectTable).set({ time_initialized: Date.now() }).where(eq(ProjectTable.id, id)).run(), - ) -} - export * as Project from "./project" diff --git a/packages/opencode/src/project/schema.ts b/packages/opencode/src/project/schema.ts deleted file mode 100644 index e511a75ffa2e..000000000000 --- a/packages/opencode/src/project/schema.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Schema } from "effect" - -import { withStatics } from "@opencode-ai/core/schema" - -const projectIdSchema = Schema.String.pipe(Schema.brand("ProjectID")) - -export type ProjectID = typeof projectIdSchema.Type - -export const ProjectID = projectIdSchema.pipe( - withStatics((schema: typeof projectIdSchema) => ({ - global: schema.make("global"), - })), -) diff --git a/packages/opencode/src/project/vcs.ts b/packages/opencode/src/project/vcs.ts index d2b5729dd4da..d809bc31f861 100644 --- a/packages/opencode/src/project/vcs.ts +++ b/packages/opencode/src/project/vcs.ts @@ -1,11 +1,11 @@ import { Effect, Layer, Context, Schema, Stream, Scope } from "effect" import { formatPatch, structuredPatch } from "diff" -import { Bus } from "@/bus" -import { BusEvent } from "@/bus/bus-event" import { InstanceState } from "@/effect/instance-state" import { FileWatcher } from "@/file/watcher" import { Git } from "@/git" import * as Log from "@opencode-ai/core/util/log" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" const log = Log.create({ service: "vcs" }) const PATCH_CONTEXT_LINES = 2_147_483_647 @@ -239,12 +239,12 @@ export const Mode = Schema.Literals(["git", "branch"]) export type Mode = Schema.Schema.Type export const Event = { - BranchUpdated: BusEvent.define( - "vcs.branch.updated", - Schema.Struct({ + BranchUpdated: EventV2.define({ + type: "vcs.branch.updated", + schema: { branch: Schema.optional(Schema.String), - }), - ), + }, + }), } export const Info = Schema.Struct({ @@ -305,11 +305,11 @@ interface State { export class Service extends Context.Service()("@opencode/Vcs") {} -export const layer: Layer.Layer = Layer.effect( +export const layer: Layer.Layer = Layer.effect( Service, Effect.gen(function* () { const git = yield* Git.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const scope = yield* Scope.Scope const state = yield* InstanceState.make( @@ -327,20 +327,21 @@ export const layer: Layer.Layer = Lay const value = { current, root } log.info("initialized", { branch: value.current, default_branch: value.root?.name }) - yield* (yield* bus.subscribe(FileWatcher.Event.Updated)).pipe( - Stream.filter((evt) => evt.properties.file.endsWith("HEAD")), - Stream.runForEach((_evt) => - Effect.gen(function* () { - const next = yield* get() - if (next !== value.current) { - log.info("branch changed", { from: value.current, to: next }) - value.current = next - yield* bus.publish(Event.BranchUpdated, { branch: next }) - } - }), - ), - Effect.forkScoped, - ) + const unsubscribe = yield* events.listen((event) => { + if (event.type !== FileWatcher.Event.Updated.type || event.location?.directory !== ctx.directory) + return Effect.void + const data = event.data as EventV2.Data + if (!data.file.endsWith("HEAD")) return Effect.void + return Effect.gen(function* () { + const next = yield* get() + if (next !== value.current) { + log.info("branch changed", { from: value.current, to: next }) + value.current = next + yield* events.publish(Event.BranchUpdated, { branch: next }) + } + }) + }) + yield* Effect.addFinalizer(() => unsubscribe) return value }), @@ -429,6 +430,6 @@ export const layer: Layer.Layer = Lay }), ) -export const defaultLayer = layer.pipe(Layer.provide(Git.defaultLayer), Layer.provide(Bus.layer)) +export const defaultLayer = layer.pipe(Layer.provide(Git.defaultLayer), Layer.provide(EventV2Bridge.defaultLayer)) export * as Vcs from "./vcs" diff --git a/packages/opencode/src/provider/auth.ts b/packages/opencode/src/provider/auth.ts index a304fec540ba..3f0607ec4161 100644 --- a/packages/opencode/src/provider/auth.ts +++ b/packages/opencode/src/provider/auth.ts @@ -4,7 +4,7 @@ import { Auth } from "@/auth" import { InstanceState } from "@/effect/instance-state" import { optionalOmitUndefined } from "@opencode-ai/core/schema" import { Plugin } from "../plugin" -import { ProviderID } from "./schema" +import { ProviderV2 } from "@opencode-ai/core/provider" import { Array as Arr, Effect, Layer, Record, Result, Context, Schema } from "effect" const When = Schema.Struct({ @@ -65,11 +65,11 @@ export const CallbackInput = Schema.Struct({ export type CallbackInput = Schema.Schema.Type export class OauthMissing extends Schema.TaggedErrorClass()("ProviderAuthOauthMissing", { - providerID: ProviderID, + providerID: ProviderV2.ID, }) {} export class OauthCodeMissing extends Schema.TaggedErrorClass()("ProviderAuthOauthCodeMissing", { - providerID: ProviderID, + providerID: ProviderV2.ID, }) {} export class OauthCallbackFailed extends Schema.TaggedErrorClass()( @@ -90,15 +90,15 @@ export interface Interface { readonly methods: () => Effect.Effect readonly authorize: ( input: { - providerID: ProviderID + providerID: ProviderV2.ID } & AuthorizeInput, ) => Effect.Effect - readonly callback: (input: { providerID: ProviderID } & CallbackInput) => Effect.Effect + readonly callback: (input: { providerID: ProviderV2.ID } & CallbackInput) => Effect.Effect } interface State { - hooks: Record - pending: Map + hooks: Record + pending: Map } export class Service extends Context.Service()("@opencode/ProviderAuth") {} @@ -117,11 +117,11 @@ export const layer: Layer.Layer = hooks: Record.fromEntries( Arr.filterMap(plugins, (x) => x.auth?.provider !== undefined - ? Result.succeed([ProviderID.make(x.auth.provider), x.auth] as const) + ? Result.succeed([ProviderV2.ID.make(x.auth.provider), x.auth] as const) : Result.failVoid, ), ), - pending: new Map(), + pending: new Map(), } }), ) @@ -160,7 +160,7 @@ export const layer: Layer.Layer = }) const authorize = Effect.fn("ProviderAuth.authorize")(function* ( - input: { providerID: ProviderID } & AuthorizeInput, + input: { providerID: ProviderV2.ID } & AuthorizeInput, ) { const { hooks, pending } = yield* InstanceState.get(state) const method = hooks[input.providerID].methods[input.method] @@ -184,7 +184,9 @@ export const layer: Layer.Layer = } }) - const callback = Effect.fn("ProviderAuth.callback")(function* (input: { providerID: ProviderID } & CallbackInput) { + const callback = Effect.fn("ProviderAuth.callback")(function* ( + input: { providerID: ProviderV2.ID } & CallbackInput, + ) { const pending = (yield* InstanceState.get(state)).pending const match = pending.get(input.providerID) if (!match) return yield* new OauthMissing({ providerID: input.providerID }) diff --git a/packages/opencode/src/provider/error.ts b/packages/opencode/src/provider/error.ts index 7363b5ce5969..0d5a5130c460 100644 --- a/packages/opencode/src/provider/error.ts +++ b/packages/opencode/src/provider/error.ts @@ -1,7 +1,23 @@ import { APICallError } from "ai" import { STATUS_CODES } from "http" import { iife } from "@/util/iife" -import type { ProviderID } from "./schema" +import type { ProviderV2 } from "@opencode-ai/core/provider" + +export class HeaderTimeoutError extends Error { + public override readonly name = "ProviderHeaderTimeoutError" + + constructor(public readonly ms: number) { + super(`Provider response headers timed out after ${ms}ms`) + } +} + +export class ResponseStreamError extends Error { + public override readonly name = "ProviderResponseStreamError" + + constructor(message: string, options?: ErrorOptions) { + super(message, options) + } +} // Adapted from overflow detection patterns in: // https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/overflow.ts @@ -45,7 +61,7 @@ function isOverflow(message: string) { return /^4(00|13)\s*(status code)?\s*\(no body\)/i.test(message) } -function message(providerID: ProviderID, e: APICallError) { +function message(providerID: ProviderV2.ID, e: APICallError) { return iife(() => { const msg = e.message if (msg === "") { @@ -178,7 +194,7 @@ export type ParsedAPICallError = metadata?: Record } -export function parseAPICallError(input: { providerID: ProviderID; error: APICallError }): ParsedAPICallError { +export function parseAPICallError(input: { providerID: ProviderV2.ID; error: APICallError }): ParsedAPICallError { const m = message(input.providerID, input.error) const body = json(input.error.responseBody) if (isOverflow(m) || input.error.statusCode === 413 || body?.error?.code === "context_length_exceeded") { diff --git a/packages/opencode/src/provider/provider.ts b/packages/opencode/src/provider/provider.ts index 496a2f6d2d3b..ad860be92abc 100644 --- a/packages/opencode/src/provider/provider.ts +++ b/packages/opencode/src/provider/provider.ts @@ -3,13 +3,13 @@ import fuzzysort from "fuzzysort" import { Config } from "@/config/config" import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda" import { NoSuchModelError, type Provider as SDK } from "ai" -import * as Log from "@opencode-ai/core/util/log" +import { Log } from "@opencode-ai/core/util/log" import { Npm } from "@opencode-ai/core/npm" import { Hash } from "@opencode-ai/core/util/hash" import { Plugin } from "../plugin" import { serviceUse } from "@opencode-ai/core/effect/service-use" import { type LanguageModelV3 } from "@ai-sdk/provider" -import * as ModelsDev from "@opencode-ai/core/models-dev" +import { ModelsDev } from "@opencode-ai/core/models-dev" import { Auth } from "../auth" import { Env } from "../env" import { InstallationVersion } from "@opencode-ai/core/installation/version" @@ -24,18 +24,14 @@ import { EffectPromise } from "@/effect/promise" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { isRecord } from "@/util/record" import { optionalOmitUndefined } from "@opencode-ai/core/schema" -import * as ProviderTransform from "./transform" -import { ModelID, ProviderID } from "./schema" +import { ProviderTransform } from "./transform" +import { ProviderV2 } from "@opencode-ai/core/provider" import { ModelStatus } from "./model-status" import { RuntimeFlags } from "@/effect/runtime-flags" +import { ProviderError } from "./error" const log = Log.create({ service: "provider" }) - -function shouldUseCopilotResponsesApi(modelID: string): boolean { - const match = /^gpt-(\d+)/.exec(modelID) - if (!match) return false - return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini") -} +const OPENAI_HEADER_TIMEOUT_DEFAULT = 10_000 function wrapSSE(res: Response, ms: number, ctl: AbortController) { if (typeof ms !== "number" || ms <= 0) return res @@ -47,7 +43,7 @@ function wrapSSE(res: Response, ms: number, ctl: AbortController) { async pull(ctrl) { const part = await new Promise>>((resolve, reject) => { const id = setTimeout(() => { - const err = new Error("SSE read timed out") + const err = new ProviderError.ResponseStreamError("SSE read timed out") ctl.abort(err) void reader.cancel(err) reject(err) @@ -85,6 +81,15 @@ function wrapSSE(res: Response, ms: number, ctl: AbortController) { }) } +function timeoutController(ms: number) { + const ctl = new AbortController() + const id = setTimeout(() => ctl.abort(new ProviderError.HeaderTimeoutError(ms)), ms) + return { + signal: ctl.signal, + clear: () => clearTimeout(id), + } +} + function googleVertexAnthropicBaseURL(project: string | undefined, location: string | undefined) { if (!project) return if (location !== "eu" && location !== "us") return @@ -142,10 +147,6 @@ type CustomDep = { get: (key: string) => Effect.Effect } -function useLanguageModel(sdk: any) { - return sdk.responses === undefined && sdk.chat === undefined -} - function selectAzureLanguageModel(sdk: any, modelID: string, useChat: boolean) { if (useChat && sdk.chat) return sdk.chat(modelID) if (sdk.responses) return sdk.responses(modelID) @@ -194,7 +195,7 @@ function custom(dep: CustomDep): Record { async getModel(sdk: any, modelID: string, _options?: Record) { return sdk.responses(modelID) }, - options: {}, + options: { headerTimeout: OPENAI_HEADER_TIMEOUT_DEFAULT }, }), xai: () => Effect.succeed({ @@ -208,8 +209,10 @@ function custom(dep: CustomDep): Record { Effect.succeed({ autoload: false, async getModel(sdk: any, modelID: string, _options?: Record) { - if (useLanguageModel(sdk)) return sdk.languageModel(modelID) - return shouldUseCopilotResponsesApi(modelID) ? sdk.responses(modelID) : sdk.chat(modelID) + if (sdk.responses === undefined && sdk.chat === undefined) return sdk.languageModel(modelID) + const match = /^gpt-(\d+)/.exec(modelID) + if (match && Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")) return sdk.responses(modelID) + return sdk.chat(modelID) }, options: {}, }), @@ -492,9 +495,9 @@ function custom(dep: CustomDep): Record { location, fetch: async (input: RequestInfo | URL, init?: RequestInit) => { const { GoogleAuth } = await import("google-auth-library") - const auth = new GoogleAuth() - const client = await auth.getApplicationDefault() - const token = await client.credential.getAccessToken() + const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] }) + const client = await auth.getClient() + const token = await client.getAccessToken() const headers = new Headers(init?.headers) headers.set("Authorization", `Bearer ${token.token}`) @@ -572,11 +575,7 @@ function custom(dep: CustomDep): Record { const instanceUrl = (yield* dep.get("GITLAB_INSTANCE_URL")) || "https://gitlab.com" const auth = yield* dep.auth(input.id) - const apiKey = yield* Effect.sync(() => { - if (auth?.type === "oauth") return auth.access - if (auth?.type === "api") return auth.key - return undefined - }) + const apiKey = auth?.type === "oauth" ? auth.access : auth?.type === "api" ? auth.key : undefined const token = apiKey ?? (yield* dep.get("GITLAB_TOKEN")) const providerConfig = (yield* dep.config()).provider?.["gitlab"] @@ -653,8 +652,8 @@ function custom(dep: CustomDep): Record { for (const m of result.models) { if (!input.models[m.id]) { models[m.id] = { - id: ModelID.make(m.id), - providerID: ProviderID.make("gitlab"), + id: ProviderV2.ModelID.make(m.id), + providerID: ProviderV2.ID.make("gitlab"), name: `Agent Platform (${m.name})`, family: "", api: { @@ -724,12 +723,7 @@ function custom(dep: CustomDep): Record { }, } - const apiKey = yield* Effect.gen(function* () { - const envToken = env["CLOUDFLARE_API_KEY"] - if (envToken) return envToken - if (auth?.type === "api") return auth.key - return undefined - }) + const apiKey = env["CLOUDFLARE_API_KEY"] || (auth?.type === "api" ? auth.key : undefined) return { autoload: !!apiKey, @@ -775,12 +769,8 @@ function custom(dep: CustomDep): Record { } // Get API token from env or auth - required for authenticated gateways - const apiToken = yield* Effect.gen(function* () { - const envToken = env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"] - if (envToken) return envToken - if (auth?.type === "api") return auth.key - return undefined - }) + const apiToken = + env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"] || (auth?.type === "api" ? auth.key : undefined) if (!apiToken) { throw new Error( @@ -918,8 +908,8 @@ const ProviderLimit = Schema.Struct({ }) export const Model = Schema.Struct({ - id: ModelID, - providerID: ProviderID, + id: ProviderV2.ModelID, + providerID: ProviderV2.ID, api: ProviderApiInfo, name: Schema.String, family: optionalOmitUndefined(Schema.String), @@ -935,7 +925,7 @@ export const Model = Schema.Struct({ export type Model = Types.DeepMutable> export const Info = Schema.Struct({ - id: ProviderID, + id: ProviderV2.ID, name: Schema.String, source: Schema.Literals(["env", "config", "custom", "api"]), env: Schema.Array(Schema.String), @@ -975,8 +965,8 @@ export function defaultModelIDs()("ProviderModelNotFoundError", { - providerID: ProviderID, - modelID: ModelID, + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, suggestions: Schema.optional(Schema.Array(Schema.String)), cause: Schema.optional(Schema.Defect), }) { @@ -986,7 +976,7 @@ export class ModelNotFoundError extends Schema.TaggedErrorClass()("ProviderInitError", { - providerID: ProviderID, + providerID: ProviderV2.ID, cause: Schema.optional(Schema.Defect), }) { static isInstance(input: unknown): input is InitError { @@ -1001,7 +991,7 @@ export class NoProvidersError extends Schema.TaggedErrorClass( } export class NoModelsError extends Schema.TaggedErrorClass()("ProviderNoModelsError", { - providerID: ProviderID, + providerID: ProviderV2.ID, }) { static isInstance(input: unknown): input is NoModelsError { return input instanceof NoModelsError @@ -1012,22 +1002,28 @@ export type DefaultModelError = ModelNotFoundError | NoProvidersError | NoModels export type Error = ModelNotFoundError | InitError | NoProvidersError | NoModelsError export interface Interface { - readonly list: () => Effect.Effect> - readonly getProvider: (providerID: ProviderID) => Effect.Effect - readonly getModel: (providerID: ProviderID, modelID: ModelID) => Effect.Effect + readonly list: () => Effect.Effect> + readonly getProvider: (providerID: ProviderV2.ID) => Effect.Effect + readonly getModel: ( + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, + ) => Effect.Effect readonly getLanguage: (model: Model) => Effect.Effect readonly closest: ( - providerID: ProviderID, + providerID: ProviderV2.ID, query: string[], - ) => Effect.Effect<{ providerID: ProviderID; modelID: string } | undefined> - readonly getSmallModel: (providerID: ProviderID) => Effect.Effect - readonly defaultModel: () => Effect.Effect<{ providerID: ProviderID; modelID: ModelID }, DefaultModelError> + ) => Effect.Effect<{ providerID: ProviderV2.ID; modelID: string } | undefined> + readonly getSmallModel: (providerID: ProviderV2.ID) => Effect.Effect + readonly defaultModel: () => Effect.Effect< + { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID }, + DefaultModelError + > } interface State { models: Map - providers: Record - catalog: Record + providers: Record + catalog: Record sdk: Map modelLoaders: Record varsLoaders: Record @@ -1072,8 +1068,8 @@ function cost(c: ModelsDev.Model["cost"]): Model["cost"] { function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model { const base: Model = { - id: ModelID.make(model.id), - providerID: ProviderID.make(provider.id), + id: ProviderV2.ModelID.make(model.id), + providerID: ProviderV2.ID.make(provider.id), name: model.name, family: model.family, api: { @@ -1130,7 +1126,7 @@ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info { const base = fromModelsDevModel(provider, model) models[id] = { ...base, - id: ModelID.make(id), + id: ProviderV2.ModelID.make(id), name: `${model.name} ${mode[0].toUpperCase()}${mode.slice(1)}`, cost: opts.cost ? mergeDeep(base.cost, cost(opts.cost)) : base.cost, options: opts.provider?.body @@ -1146,7 +1142,7 @@ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info { } } return { - id: ProviderID.make(provider.id), + id: ProviderV2.ID.make(provider.id), source: "custom", name: provider.name, env: [...(provider.env ?? [])], @@ -1155,18 +1151,15 @@ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info { } } -function suggestionModelIDs(provider: Info | undefined, enableExperimentalModels: boolean) { - if (!provider) return [] - return Object.keys(provider.models).filter((id) => { - const model = provider.models[id] - if (model.status === "deprecated") return false - if (model.status === "alpha" && !enableExperimentalModels) return false - return true - }) -} - -function modelSuggestions(provider: Info | undefined, modelID: ModelID, enableExperimentalModels: boolean) { - const available = suggestionModelIDs(provider, enableExperimentalModels) +function modelSuggestions(provider: Info | undefined, modelID: ProviderV2.ModelID, enableExperimentalModels: boolean) { + const available = provider + ? Object.keys(provider.models).filter((id) => { + const model = provider.models[id] + if (model.status === "deprecated") return false + if (model.status === "alpha" && !enableExperimentalModels) return false + return true + }) + : [] const fuzzy = fuzzysort.go(modelID, available, { limit: 3, threshold: -10000 }).map((m) => m.target) if (fuzzy.length) return fuzzy const query = modelID @@ -1207,7 +1200,7 @@ export const layer = Layer.effect( const catalog = mapValues(modelsDev, fromModelsDevProvider) const database = mapValues(catalog, toPublicInfo) - const providers: Record = {} as Record + const providers: Record = {} as Record const languages = new Map() const modelLoaders: { [providerID: string]: CustomModelLoader @@ -1228,7 +1221,7 @@ export const layer = Layer.effect( log.info("init") - function mergeProvider(providerID: ProviderID, provider: Partial) { + function mergeProvider(providerID: ProviderV2.ID, provider: Partial) { const existing = providers[providerID] if (existing) { // @ts-expect-error @@ -1249,7 +1242,7 @@ export const layer = Layer.effect( const disabled = new Set(cfg.disabled_providers ?? []) const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : null - function isProviderAllowed(providerID: ProviderID): boolean { + function isProviderAllowed(providerID: ProviderV2.ID): boolean { if (enabled && !enabled.has(providerID)) return false if (disabled.has(providerID)) return false return true @@ -1260,7 +1253,7 @@ export const layer = Layer.effect( const models = p?.models if (!p || !models) continue - const providerID = ProviderID.make(p.id) + const providerID = ProviderV2.ID.make(p.id) if (disabled.has(providerID)) continue const provider = database[providerID] @@ -1274,7 +1267,7 @@ export const layer = Layer.effect( id, { ...model, - id: ModelID.make(id), + id: ProviderV2.ModelID.make(id), providerID, }, ]), @@ -1286,7 +1279,7 @@ export const layer = Layer.effect( for (const [providerID, provider] of configProviders) { const existing = database[providerID] const parsed: Info = { - id: ProviderID.make(providerID), + id: ProviderV2.ID.make(providerID), name: provider.name ?? existing?.name ?? providerID, env: provider.env ?? existing?.env ?? [], options: mergeDeep(existing?.options ?? {}, provider.options ?? {}), @@ -1309,7 +1302,7 @@ export const layer = Layer.effect( return existingModel?.name ?? modelID }) const parsedModel: Model = { - id: ModelID.make(modelID), + id: ProviderV2.ModelID.make(modelID), api: { id: apiID, npm: apiNpm, @@ -1317,7 +1310,7 @@ export const layer = Layer.effect( }, status: model.status ?? existingModel?.status ?? "active", name, - providerID: ProviderID.make(providerID), + providerID: ProviderV2.ID.make(providerID), capabilities: { temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false, reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false, @@ -1379,7 +1372,7 @@ export const layer = Layer.effect( // load env const envs = yield* env.all() for (const [id, provider] of Object.entries(database)) { - const providerID = ProviderID.make(id) + const providerID = ProviderV2.ID.make(id) if (disabled.has(providerID)) continue const apiKey = provider.env.map((item) => envs[item]).find(Boolean) if (!apiKey) continue @@ -1392,7 +1385,7 @@ export const layer = Layer.effect( // load apikeys const auths = yield* auth.all().pipe(Effect.orDie) for (const [id, provider] of Object.entries(auths)) { - const providerID = ProviderID.make(id) + const providerID = ProviderV2.ID.make(id) if (disabled.has(providerID)) continue if (provider.type === "api") { mergeProvider(providerID, { @@ -1405,7 +1398,7 @@ export const layer = Layer.effect( // plugin auth loader - database now has entries for config providers for (const plugin of plugins) { if (!plugin.auth) continue - const providerID = ProviderID.make(plugin.auth.provider) + const providerID = ProviderV2.ID.make(plugin.auth.provider) if (disabled.has(providerID)) continue const stored = yield* auth.get(providerID).pipe(Effect.orDie) @@ -1424,7 +1417,7 @@ export const layer = Layer.effect( } for (const [id, fn] of Object.entries(custom(dep))) { - const providerID = ProviderID.make(id) + const providerID = ProviderV2.ID.make(id) if (disabled.has(providerID)) continue const data = database[providerID] if (!data) { @@ -1444,7 +1437,7 @@ export const layer = Layer.effect( // load config - re-apply with updated data for (const [id, provider] of configProviders) { - const providerID = ProviderID.make(id) + const providerID = ProviderV2.ID.make(id) const partial: Partial = { source: "config" } if (provider.env) partial.env = provider.env if (provider.name) partial.name = provider.name @@ -1452,7 +1445,7 @@ export const layer = Layer.effect( mergeProvider(providerID, partial) } - const gitlab = ProviderID.make("gitlab") + const gitlab = ProviderV2.ID.make("gitlab") if (discoveryLoaders[gitlab] && providers[gitlab] && isProviderAllowed(gitlab)) { yield* Effect.promise(async () => { try { @@ -1469,7 +1462,7 @@ export const layer = Layer.effect( } for (const [id, provider] of Object.entries(providers)) { - const providerID = ProviderID.make(id) + const providerID = ProviderV2.ID.make(id) if (!isProviderAllowed(providerID)) { delete providers[providerID] continue @@ -1483,10 +1476,10 @@ export const layer = Layer.effect( // These chat aliases are invalid for the special handling in the // built-in providers below, but custom providers may support them. (modelID === "gpt-5-chat-latest" && - (providerID === ProviderID.openai || - providerID === ProviderID.githubCopilot || - providerID === ProviderID.openrouter)) || - (providerID === ProviderID.openrouter && modelID === "openai/gpt-5-chat") + (providerID === ProviderV2.ID.openai || + providerID === ProviderV2.ID.githubCopilot || + providerID === ProviderV2.ID.openrouter)) || + (providerID === ProviderV2.ID.openrouter && modelID === "openai/gpt-5-chat") ) delete provider.models[modelID] if (model.status === "alpha" && !runtimeFlags.enableExperimentalModels) delete provider.models[modelID] @@ -1601,16 +1594,21 @@ export const layer = Layer.effect( const customFetch = options["fetch"] const chunkTimeout = options["chunkTimeout"] + const headerTimeout = options["headerTimeout"] delete options["chunkTimeout"] + delete options["headerTimeout"] options["fetch"] = async (input: any, init?: BunFetchRequestInit) => { const fetchFn = customFetch ?? fetch const opts = init ?? {} const chunkAbortCtl = typeof chunkTimeout === "number" && chunkTimeout > 0 ? new AbortController() : undefined + const headerTimeoutMs = headerTimeout === false ? undefined : headerTimeout + const headerTimeoutCtl = typeof headerTimeoutMs === "number" ? timeoutController(headerTimeoutMs) : undefined const signals: AbortSignal[] = [] if (opts.signal) signals.push(opts.signal) if (chunkAbortCtl) signals.push(chunkAbortCtl.signal) + if (headerTimeoutCtl) signals.push(headerTimeoutCtl.signal) if (options["timeout"] !== undefined && options["timeout"] !== null && options["timeout"] !== false) signals.push(AbortSignal.timeout(options["timeout"])) @@ -1639,7 +1637,7 @@ export const layer = Layer.effect( ...opts, // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682 timeout: false, - }) + }).finally(() => headerTimeoutCtl?.clear()) if (!chunkAbortCtl) return res return wrapSSE(res, chunkTimeout, chunkAbortCtl) @@ -1660,15 +1658,15 @@ export const layer = Layer.effect( return loaded as SDK } - let installedPath: string - if (!model.api.npm.startsWith("file://")) { + const installedPath = await (async () => { + if (model.api.npm.startsWith("file://")) { + log.info("loading local provider", { pkg: model.api.npm }) + return model.api.npm + } const item = await Npm.add(model.api.npm) if (!item.entrypoint) throw new Error(`Package ${model.api.npm} has no import entrypoint`) - installedPath = item.entrypoint - } else { - log.info("loading local provider", { pkg: model.api.npm }) - installedPath = model.api.npm - } + return item.entrypoint + })() // `installedPath` is a local entry path or an existing `file://` URL. Normalize // only path inputs so Node on Windows accepts the dynamic import. @@ -1687,11 +1685,11 @@ export const layer = Layer.effect( } } - const getProvider = Effect.fn("Provider.getProvider")((providerID: ProviderID) => + const getProvider = Effect.fn("Provider.getProvider")((providerID: ProviderV2.ID) => InstanceState.use(state, (s) => s.providers[providerID]), ) - const getModel = Effect.fn("Provider.getModel")(function* (providerID: ProviderID, modelID: ModelID) { + const getModel = Effect.fn("Provider.getModel")(function* (providerID: ProviderV2.ID, modelID: ProviderV2.ModelID) { const s = yield* InstanceState.get(state) const provider = s.providers[providerID] if (!provider) { @@ -1741,7 +1739,7 @@ export const layer = Layer.effect( ) }) - const closest = Effect.fn("Provider.closest")(function* (providerID: ProviderID, query: string[]) { + const closest = Effect.fn("Provider.closest")(function* (providerID: ProviderV2.ID, query: string[]) { const s = yield* InstanceState.get(state) const provider = s.providers[providerID] if (!provider) return undefined @@ -1753,7 +1751,7 @@ export const layer = Layer.effect( return undefined }) - const getSmallModel = Effect.fn("Provider.getSmallModel")(function* (providerID: ProviderID) { + const getSmallModel = Effect.fn("Provider.getSmallModel")(function* (providerID: ProviderV2.ID) { const cfg = yield* config.get() if (cfg.small_model) { @@ -1767,7 +1765,7 @@ export const layer = Layer.effect( const provider = s.providers[providerID] if (!provider) return undefined - let priority = [ + const defaultPriority = [ "claude-haiku-4-5", "claude-haiku-4.5", "3-5-haiku", @@ -1776,14 +1774,13 @@ export const layer = Layer.effect( "gemini-2.5-flash", "gpt-5-nano", ] - if (providerID.startsWith("opencode")) { - priority = ["gpt-5-nano"] - } - if (providerID.startsWith("github-copilot")) { - priority = ["gpt-5-mini", "claude-haiku-4.5", ...priority] - } + const priority = providerID.startsWith("opencode") + ? ["gpt-5-nano"] + : providerID.startsWith("github-copilot") + ? ["gpt-5-mini", "claude-haiku-4.5", ...defaultPriority] + : defaultPriority for (const item of priority) { - if (providerID === ProviderID.amazonBedrock) { + if (providerID === ProviderV2.ID.amazonBedrock) { const crossRegionPrefixes = ["global.", "us.", "eu."] const candidates = Object.keys(provider.models).filter((m) => m.includes(item)) @@ -1817,16 +1814,16 @@ export const layer = Layer.effect( const s = yield* InstanceState.get(state) const recent = yield* fs.readJson(path.join(Global.Path.state, "model.json")).pipe( - Effect.map((x): { providerID: ProviderID; modelID: ModelID }[] => { + Effect.map((x): { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID }[] => { if (!isRecord(x) || !Array.isArray(x.recent)) return [] return x.recent.flatMap((item) => { if (!isRecord(item)) return [] if (typeof item.providerID !== "string") return [] if (typeof item.modelID !== "string") return [] - return [{ providerID: ProviderID.make(item.providerID), modelID: ModelID.make(item.modelID) }] + return [{ providerID: ProviderV2.ID.make(item.providerID), modelID: ProviderV2.ModelID.make(item.modelID) }] }) }), - Effect.catch(() => Effect.succeed([] as { providerID: ProviderID; modelID: ModelID }[])), + Effect.catch(() => Effect.succeed([] as { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID }[])), ) for (const entry of recent) { const provider = s.providers[entry.providerID] @@ -1874,8 +1871,8 @@ export function sort(models: T[]) { export function parseModel(model: string) { const [providerID, ...rest] = model.split("/") return { - providerID: ProviderID.make(providerID), - modelID: ModelID.make(rest.join("/")), + providerID: ProviderV2.ID.make(providerID), + modelID: ProviderV2.ModelID.make(rest.join("/")), } } diff --git a/packages/opencode/src/provider/schema.ts b/packages/opencode/src/provider/schema.ts deleted file mode 100644 index db05b47843e9..000000000000 --- a/packages/opencode/src/provider/schema.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { Schema } from "effect" - -import { withStatics } from "@opencode-ai/core/schema" - -const providerIdSchema = Schema.String.pipe(Schema.brand("ProviderID")) - -export type ProviderID = typeof providerIdSchema.Type - -export const ProviderID = providerIdSchema.pipe( - withStatics((schema: typeof providerIdSchema) => ({ - // Well-known providers - opencode: schema.make("opencode"), - anthropic: schema.make("anthropic"), - openai: schema.make("openai"), - google: schema.make("google"), - googleVertex: schema.make("google-vertex"), - githubCopilot: schema.make("github-copilot"), - amazonBedrock: schema.make("amazon-bedrock"), - azure: schema.make("azure"), - openrouter: schema.make("openrouter"), - mistral: schema.make("mistral"), - gitlab: schema.make("gitlab"), - })), -) - -const modelIdSchema = Schema.String.pipe(Schema.brand("ModelID")) - -export type ModelID = typeof modelIdSchema.Type - -export const ModelID = modelIdSchema diff --git a/packages/opencode/src/provider/transform.ts b/packages/opencode/src/provider/transform.ts index 08b2f4922104..c791aebf9713 100644 --- a/packages/opencode/src/provider/transform.ts +++ b/packages/opencode/src/provider/transform.ts @@ -596,11 +596,25 @@ function openaiCompatibleReasoningEfforts(id: string) { return gpt5CodexReasoningEfforts(apiId) ?? versionedGpt5ReasoningEfforts(apiId) ?? OPENAI_EFFORTS } +function anthropicOpus47OrLater(apiId: string) { + // Matches "opus-4.7" (Anthropic/Bedrock/Vertex) and "claude-4.7-opus" (SAP AI Core inverted). + // Greedy \d+ correctly extends to multi-digit majors (e.g. "claude-10.0-opus") for forward compatibility. + const version = /opus-(\d+)[.-](\d+)(?:[.@-]|$)|claude-(\d+)[.-](\d+)-opus(?:[.@-]|$)/i.exec(apiId) + if (!version) return false + const major = Number(version[1] ?? version[3]) + const minor = Number(version[2] ?? version[4]) + return major > 4 || (major === 4 && minor >= 7) +} + function anthropicAdaptiveEfforts(apiId: string): string[] | null { - if (["opus-4-7", "opus-4.7"].some((v) => apiId.includes(v))) { + if (anthropicOpus47OrLater(apiId)) { return ["low", "medium", "high", "xhigh", "max"] } - if (["opus-4-6", "opus-4.6", "sonnet-4-6", "sonnet-4.6"].some((v) => apiId.includes(v))) { + if ( + ["opus-4-6", "opus-4.6", "4-6-opus", "4.6-opus", "sonnet-4-6", "sonnet-4.6", "4-6-sonnet", "4.6-sonnet"].some((v) => + apiId.includes(v), + ) + ) { return ["low", "medium", "high", "max"] } return null @@ -625,6 +639,7 @@ export function variants(model: Provider.Model): Record= 1.2.0-beta.12) assigns the child pid + // asynchronously, so `proc.pid` is 0 at the synchronous spawn point and only + // resolves a tick later. `create` snapshots it immediately, so 0 is a valid + // "pid not yet assigned" value here. + pid: NonNegativeInt, }).annotate({ identifier: "Pty" }) export type Info = Types.DeepMutable> @@ -92,10 +96,10 @@ export class NotFoundError extends Schema.TaggedErrorClass()("Pty }) {} export const Event = { - Created: BusEvent.define("pty.created", Schema.Struct({ info: Info })), - Updated: BusEvent.define("pty.updated", Schema.Struct({ info: Info })), - Exited: BusEvent.define("pty.exited", Schema.Struct({ id: PtyID, exitCode: NonNegativeInt })), - Deleted: BusEvent.define("pty.deleted", Schema.Struct({ id: PtyID })), + Created: EventV2.define({ type: "pty.created", schema: { info: Info } }), + Updated: EventV2.define({ type: "pty.updated", schema: { info: Info } }), + Exited: EventV2.define({ type: "pty.exited", schema: { id: PtyID, exitCode: NonNegativeInt } }), + Deleted: EventV2.define({ type: "pty.deleted", schema: { id: PtyID } }), } export interface Interface { @@ -122,7 +126,7 @@ export const layer = Layer.effect( Service, Effect.gen(function* () { const config = yield* Config.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const plugin = yield* Plugin.Service function teardown(session: Active) { @@ -169,7 +173,7 @@ export const layer = Layer.effect( s.sessions.delete(id) log.info("removing session", { id }) teardown(session) - yield* bus.publish(Event.Deleted, { id: session.info.id }) + yield* events.publish(Event.Deleted, { id: session.info.id }) }) const list = Effect.fn("Pty.list")(function* () { @@ -265,10 +269,10 @@ export const layer = Layer.effect( if (session.info.status === "exited") return log.info("session exited", { id, exitCode }) session.info.status = "exited" - bridge.fork(bus.publish(Event.Exited, { id, exitCode })) + bridge.fork(events.publish(Event.Exited, { id, exitCode })) bridge.fork(remove(id)) }) - yield* bus.publish(Event.Created, { info }) + yield* events.publish(Event.Created, { info }) return info }) @@ -280,7 +284,7 @@ export const layer = Layer.effect( if (input.size) { session.process.resize(input.size.cols, input.size.rows) } - yield* bus.publish(Event.Updated, { info: session.info }) + yield* events.publish(Event.Updated, { info: session.info }) return session.info }) @@ -365,7 +369,7 @@ export const layer = Layer.effect( ) export const defaultLayer = layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(Plugin.defaultLayer), Layer.provide(Config.defaultLayer), ) diff --git a/packages/opencode/src/pty/pty.node.ts b/packages/opencode/src/pty/pty.node.ts index b45c5bf50985..76f415f4cdd7 100644 --- a/packages/opencode/src/pty/pty.node.ts +++ b/packages/opencode/src/pty/pty.node.ts @@ -1,4 +1,3 @@ -/** @ts-expect-error */ import * as pty from "@lydell/node-pty" import type { Opts, Proc } from "./pty" diff --git a/packages/opencode/src/pty/ticket.ts b/packages/opencode/src/pty/ticket.ts index 0978e520837f..cf6751fb1865 100644 --- a/packages/opencode/src/pty/ticket.ts +++ b/packages/opencode/src/pty/ticket.ts @@ -1,6 +1,6 @@ export * as PtyTicket from "./ticket" -import { WorkspaceID } from "@/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" import { PtyID } from "@/pty/schema" import { PositiveInt } from "@opencode-ai/core/schema" @@ -17,7 +17,7 @@ export const ConnectToken = Schema.Struct({ export type Scope = { readonly ptyID: PtyID readonly directory?: string - readonly workspaceID?: WorkspaceID + readonly workspaceID?: WorkspaceV2.ID } export interface Interface { diff --git a/packages/opencode/src/question/index.ts b/packages/opencode/src/question/index.ts index e03af848b070..f93fc8eb209e 100644 --- a/packages/opencode/src/question/index.ts +++ b/packages/opencode/src/question/index.ts @@ -1,10 +1,10 @@ import { Deferred, Effect, Layer, Schema, Context } from "effect" -import { Bus } from "@/bus" -import { BusEvent } from "@/bus/bus-event" import { InstanceState } from "@/effect/instance-state" import { SessionID, MessageID } from "@/session/schema" import * as Log from "@opencode-ai/core/util/log" import { QuestionID } from "./schema" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" const log = Log.create({ service: "question" }) @@ -75,21 +75,21 @@ export const Reply = Schema.Struct({ }).annotate({ identifier: "QuestionReply" }) export type Reply = Schema.Schema.Type -const Replied = Schema.Struct({ +export const Replied = Schema.Struct({ sessionID: SessionID, requestID: QuestionID, answers: Schema.Array(Answer), }).annotate({ identifier: "QuestionReplied" }) -const Rejected = Schema.Struct({ +export const Rejected = Schema.Struct({ sessionID: SessionID, requestID: QuestionID, }).annotate({ identifier: "QuestionRejected" }) export const Event = { - Asked: BusEvent.define("question.asked", Request), - Replied: BusEvent.define("question.replied", Replied), - Rejected: BusEvent.define("question.rejected", Rejected), + Asked: EventV2.define({ type: "question.asked", schema: Request.fields }), + Replied: EventV2.define({ type: "question.replied", schema: Replied.fields }), + Rejected: EventV2.define({ type: "question.rejected", schema: Rejected.fields }), } export class RejectedError extends Schema.TaggedErrorClass()("QuestionRejectedError", {}) { @@ -132,7 +132,7 @@ export class Service extends Context.Service()("@opencode/Qu export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const state = yield* InstanceState.make( Effect.fn("Question.state")(function* () { const state = { @@ -169,7 +169,7 @@ export const layer = Layer.effect( tool: input.tool, } pending.set(id, { info, deferred }) - yield* bus.publish(Event.Asked, info) + yield* events.publish(Event.Asked, info) return yield* Effect.ensuring( Deferred.await(deferred), @@ -191,7 +191,7 @@ export const layer = Layer.effect( } pending.delete(input.requestID) log.info("replied", { requestID: input.requestID, answers: input.answers }) - yield* bus.publish(Event.Replied, { + yield* events.publish(Event.Replied, { sessionID: existing.info.sessionID, requestID: existing.info.id, answers: input.answers.map((a) => [...a]), @@ -208,7 +208,7 @@ export const layer = Layer.effect( } pending.delete(requestID) log.info("rejected", { requestID }) - yield* bus.publish(Event.Rejected, { + yield* events.publish(Event.Rejected, { sessionID: existing.info.sessionID, requestID: existing.info.id, }) @@ -224,6 +224,6 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(Bus.layer)) +export const defaultLayer = layer.pipe(Layer.provide(EventV2Bridge.defaultLayer)) export * as Question from "." diff --git a/packages/opencode/src/server/event.ts b/packages/opencode/src/server/event.ts index d5f10f47dbe4..a58131255587 100644 --- a/packages/opencode/src/server/event.ts +++ b/packages/opencode/src/server/event.ts @@ -1,7 +1,13 @@ -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" import { Schema } from "effect" export const Event = { - Connected: BusEvent.define("server.connected", Schema.Struct({})), - Disposed: BusEvent.define("global.disposed", Schema.Struct({})), + Connected: EventV2.define({ type: "server.connected", schema: {} }), + Disposed: EventV2.define({ type: "global.disposed", schema: {} }), } + +export const InstanceDisposed = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("server.instance.disposed"), + properties: Schema.Struct({ directory: Schema.String }), +}).annotate({ identifier: "Event.server.instance.disposed" }) diff --git a/packages/opencode/src/server/projectors.ts b/packages/opencode/src/server/projectors.ts index c5fb2420a0ce..b9142beab2a9 100644 --- a/packages/opencode/src/server/projectors.ts +++ b/packages/opencode/src/server/projectors.ts @@ -1,26 +1 @@ -import sessionProjectors from "../session/projectors" -import { SyncEvent } from "@/sync" -import { Session } from "@/session/session" -import { SessionTable } from "@/session/session.sql" -import { Database } from "@/storage/db" -import { eq } from "drizzle-orm" - -export function initProjectors() { - SyncEvent.init({ - projectors: sessionProjectors, - convertEvent: (type, data) => { - if (type === "session.updated") { - const id = (data as SyncEvent.Event["data"]).sessionID - const row = Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()) - - if (!row) return data - - return { - sessionID: id, - info: Session.fromRow(row), - } - } - return data - }, - }) -} +export function initProjectors() {} diff --git a/packages/opencode/src/server/routes/instance/httpapi/AGENTS.md b/packages/opencode/src/server/routes/instance/httpapi/AGENTS.md index a6ccf794ddca..c44db1edbbfb 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/AGENTS.md +++ b/packages/opencode/src/server/routes/instance/httpapi/AGENTS.md @@ -14,18 +14,20 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", For SSE endpoints, stay in `HttpApiBuilder.group(...)` and return `HttpServerResponse.stream(...)` from the handler. Annotate the endpoint success schema with `HttpApiSchema.asText({ contentType: "text/event-stream" })` so OpenAPI documents the stream content type. -Use raw `HttpRouter.use(...)` only for routes that do not fit the request/response HttpApi model, such as WebSocket upgrade routes or catch-all fallback routes. Yield stable services at route-layer construction and close over them in `router.add(...)` callbacks. +Use `HttpApiBuilder.group(...)` with `handleRaw(...)` for declared endpoints that need the raw request or response, including WebSocket upgrade routes. This keeps endpoint middleware, routing context, and OpenAPI metadata on one typed route tree. ```ts -export const rawRoute = HttpRouter.use((router) => +export const ptyConnectHandlers = HttpApiBuilder.group(PtyConnectApi, "pty-connect", (handlers) => Effect.gen(function* () { const pty = yield* Pty.Service - yield* router.add("GET", PtyPaths.connect, (request) => connectPty(request, pty)) + return handlers.handleRaw("connect", (ctx) => connectPty(ctx.request, pty)) }), ) ``` +Use raw `HttpRouter.use(...)` only for routes outside the declared API surface, such as a catch-all UI fallback. + Avoid `Effect.provide(SomeLayer)` inside request handlers or raw route callbacks. Stable layers should be provided once at the application/layer boundary, not rebuilt or scoped per request. Avoid `HttpRouter.provideRequest(...)` unless the dependency is intentionally request-level. Prefer `HttpRouter.use(...)` for stable app services. @@ -34,4 +36,4 @@ Use `Effect.provideService(...)` in middleware only for request-derived context, Public JSON errors should be explicit `Schema.ErrorClass` contracts declared on each endpoint. Use built-in `HttpApiError.*` classes only when their empty/tagged body is the intended wire shape; for SDK-visible errors with messages, define an API error schema such as `ApiNotFoundError` and fail with that exact declared error. Keep domain and storage services free of HttpApi types, and translate expected domain errors at the handler boundary. -When adding middleware, compose it at the layer boundary and keep the route tree explicit in `server.ts`. Shared router middleware such as auth, workspace routing, and instance context should stay visible where routes are assembled. +When adding middleware, declare endpoint-contract middleware on the owning `HttpApiGroup` and provide its implementation layer at the assembly boundary in `server.ts`. Keep router middleware for truly raw fallback routes or global transport policy. diff --git a/packages/opencode/src/server/routes/instance/httpapi/api.ts b/packages/opencode/src/server/routes/instance/httpapi/api.ts index eff336b3c638..11649d11f8f2 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/api.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/api.ts @@ -1,13 +1,13 @@ import { Schema } from "effect" import { HttpApi } from "effect/unstable/httpapi" -import { BusEvent } from "@/bus/bus-event" -import { SyncEvent } from "@/sync" +import { EventV2 } from "@opencode-ai/core/event" +import { InstanceDisposed } from "@/server/event" +import { Question } from "@/question" import { ConfigApi } from "./groups/config" import { ControlApi } from "./groups/control" import { EventApi } from "./groups/event" import { ExperimentalApi } from "./groups/experimental" import { FileApi } from "./groups/file" -import { GlobalApi } from "./groups/global" import { InstanceApi } from "./groups/instance" import { McpApi } from "./groups/mcp" import { PermissionApi } from "./groups/permission" @@ -20,12 +20,24 @@ import { SyncApi } from "./groups/sync" import { TuiApi } from "./groups/tui" import { WorkspaceApi } from "./groups/workspace" import { V2Api } from "./groups/v2" +// GlobalEventSchema snapshots the registry after event-producing groups register their variants. +import { GlobalApi } from "./groups/global" import { Authorization } from "./middleware/authorization" import { SchemaErrorMiddleware } from "./middleware/schema-error" -// SSE event schemas built from the BusEvent/SyncEvent registries. -const EventSchema = Schema.Union(BusEvent.effectPayloads()).annotate({ identifier: "Event" }) -const SyncEventSchemas = SyncEvent.effectPayloads() +const EventSchema = Schema.Union([ + ...EventV2.registry + .values() + .map((definition) => + Schema.Struct({ + id: Schema.String, + type: Schema.Literal(definition.type), + properties: definition.data, + }).annotate({ identifier: `Event.${definition.type}` }), + ) + .toArray(), + InstanceDisposed, +]).annotate({ identifier: "Event" }) export const RootHttpApi = HttpApi.make("opencode-root") .addHttpApi(ControlApi) @@ -56,7 +68,7 @@ export const OpenCodeHttpApi = HttpApi.make("opencode") .addHttpApi(EventApi) .addHttpApi(InstanceHttpApi) .addHttpApi(PtyConnectApi) - .annotate(HttpApi.AdditionalSchemas, [EventSchema, ...SyncEventSchemas]) + .annotate(HttpApi.AdditionalSchemas, [EventSchema, Question.Replied, Question.Rejected]) export type RootHttpApiType = typeof RootHttpApi export type InstanceHttpApiType = typeof InstanceHttpApi diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/control.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/control.ts index 33e6a8e4a05b..49f43f0154f6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/control.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/control.ts @@ -1,11 +1,12 @@ import { Auth } from "@/auth" -import { ProviderID } from "@/provider/schema" + import { Schema } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { described } from "./metadata" +import { ProviderV2 } from "@opencode-ai/core/provider" const AuthParams = Schema.Struct({ - providerID: ProviderID, + providerID: ProviderV2.ID, }) const LogQuery = Schema.Struct({ diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/event.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/event.ts index 7ebc229ee5aa..6de2214443b2 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/event.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/event.ts @@ -1,6 +1,8 @@ import { Schema } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" -import { WorkspaceRoutingQuery } from "../middleware/workspace-routing" +import { Authorization } from "../middleware/authorization" +import { InstanceContextMiddleware } from "../middleware/instance-context" +import { WorkspaceRoutingMiddleware, WorkspaceRoutingQuery } from "../middleware/workspace-routing" export const EventPaths = { event: "/event", @@ -20,5 +22,8 @@ export const EventApi = HttpApi.make("event").add( }), ), ) + .middleware(InstanceContextMiddleware) + .middleware(WorkspaceRoutingMiddleware) + .middleware(Authorization) .annotateMerge(OpenApi.annotations({ title: "event", description: "Instance event stream route." })), ) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts index 4cda970e87d5..c40a3bf00615 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts @@ -1,11 +1,11 @@ import { AccountID, OrgID } from "@/account/schema" import { MCP } from "@/mcp" -import { ProviderID, ModelID } from "@/provider/schema" + import { Session } from "@/session/session" import { Worktree } from "@/worktree" import { NonNegativeInt } from "@opencode-ai/core/schema" import { Schema } from "effect" -import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" +import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" import { Authorization } from "../middleware/authorization" import { InstanceContextMiddleware } from "../middleware/instance-context" import { @@ -15,6 +15,7 @@ import { } from "../middleware/workspace-routing" import { described } from "./metadata" import { QueryBoolean } from "./query" +import { ProviderV2 } from "@opencode-ai/core/provider" const ConsoleStateResponse = Schema.Struct({ consoleManagedProviders: Schema.mutable(Schema.Array(Schema.String)), @@ -49,8 +50,8 @@ const ToolListItem = Schema.Struct({ const ToolList = Schema.Array(ToolListItem).annotate({ identifier: "ToolList" }) export const ToolListQuery = Schema.Struct({ ...WorkspaceRoutingQueryFields, - provider: ProviderID, - model: ModelID, + provider: ProviderV2.ID, + model: ProviderV2.ModelID, }) const WorktreeList = Schema.Array(Schema.String) @@ -168,7 +169,7 @@ export const ExperimentalApi = HttpApi.make("experimental") HttpApiEndpoint.post("worktreeCreate", ExperimentalPaths.worktree, { disableCodecs: true, query: WorkspaceRoutingQuery, - payload: Schema.UndefinedOr(Worktree.CreateInput), + payload: [HttpApiSchema.NoContent, Worktree.CreateInput], success: described(Worktree.Info, "Worktree created"), error: WorktreeApiError, }).annotateMerge( diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/global.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/global.ts index 75441b4ca4a3..fa9995ee4c73 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/global.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/global.ts @@ -1,9 +1,10 @@ import { Config } from "@/config/config" -import { BusEvent } from "@/bus/bus-event" -import { SyncEvent } from "@/sync" +import { EventV2 } from "@opencode-ai/core/event" +import { InstanceDisposed } from "@/server/event" +import "@opencode-ai/core/account" import "@/server/event" import { Schema } from "effect" -import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" +import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" import { described } from "./metadata" const GlobalHealth = Schema.Struct({ @@ -11,11 +12,37 @@ const GlobalHealth = Schema.Struct({ version: Schema.String, }) +const SyncEventSchemas = EventV2.registry + .values() + .flatMap((definition) => { + if (!definition.sync) return [] + return [ + Schema.Struct({ + type: Schema.Literal("sync"), + name: Schema.Literal(EventV2.versionedType(definition.type, definition.sync.version)), + id: Schema.String, + seq: Schema.Finite, + aggregateID: Schema.Literal(definition.sync.aggregate), + data: definition.data, + }).annotate({ identifier: `SyncEvent.${definition.type}` }), + ] + }) + .toArray() + const GlobalEventSchema = Schema.Struct({ directory: Schema.String, project: Schema.optional(Schema.String), workspace: Schema.optional(Schema.String), - payload: Schema.Union([...BusEvent.effectPayloads(), ...SyncEvent.effectPayloads()]), + payload: Schema.Union([ + ...EventV2.registry + .values() + .map((definition) => + Schema.Struct({ id: Schema.String, type: Schema.Literal(definition.type), properties: definition.data }), + ) + .toArray(), + InstanceDisposed, + ...SyncEventSchemas, + ]), }).annotate({ identifier: "GlobalEvent" }) export const GlobalUpgradeInput = Schema.Struct({ @@ -92,7 +119,7 @@ export const GlobalApi = HttpApi.make("global").add( }), ), HttpApiEndpoint.post("upgrade", GlobalPaths.upgrade, { - payload: GlobalUpgradeInput, + payload: [HttpApiSchema.NoContent, GlobalUpgradeInput], success: described(GlobalUpgradeResult, "Upgrade result"), error: HttpApiError.BadRequest, }).annotateMerge( diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts index b7be4044fc0e..c6b2fab40a96 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts @@ -1,5 +1,5 @@ import { Project } from "@/project/project" -import { ProjectID } from "@/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { Schema } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { ProjectNotFoundError } from "../errors" @@ -50,7 +50,7 @@ export const ProjectApi = HttpApi.make("project") }), ), HttpApiEndpoint.patch("update", `${root}/:projectID`, { - params: { projectID: ProjectID }, + params: { projectID: ProjectV2.ID }, query: WorkspaceRoutingQuery, payload: UpdatePayload, success: described(Project.Info, "Updated project information"), diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/provider.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/provider.ts index 0d8e49022b62..3a9ae0c6d36c 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/provider.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/provider.ts @@ -1,12 +1,13 @@ import { ProviderAuth } from "@/provider/auth" import { Provider } from "@/provider/provider" -import { ProviderID } from "@/provider/schema" + import { Schema } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { Authorization } from "../middleware/authorization" import { InstanceContextMiddleware } from "../middleware/instance-context" import { WorkspaceRoutingMiddleware, WorkspaceRoutingQuery } from "../middleware/workspace-routing" import { described } from "./metadata" +import { ProviderV2 } from "@opencode-ai/core/provider" const root = "/provider" @@ -21,7 +22,7 @@ export class ProviderAuthApiError extends Schema.ErrorClass ({ + ...operation, + parameters: [ + ...(operation.parameters ?? []), + ...["directory", "workspace", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({ + in: "query", + name, + schema: { type: "string" }, + })), + ], + }), }), ), ) - .annotateMerge(OpenApi.annotations({ title: "pty", description: "PTY websocket route." })), + .annotateMerge(OpenApi.annotations({ title: "pty", description: "PTY websocket route." })) + .middleware(InstanceContextMiddleware) + .middleware(WorkspaceRoutingMiddleware) + .middleware(PtyConnectAuthorization), ) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts index cd2f3be19c81..c648572b6309 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/session.ts @@ -1,6 +1,7 @@ import { Permission } from "@/permission" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { PermissionID } from "@/permission/schema" -import { ModelID, ProviderID } from "@/provider/schema" + import { Session } from "@/session/session" import { MessageV2 } from "@/session/message-v2" import { SessionPrompt } from "@/session/prompt" @@ -22,6 +23,7 @@ import { import { ApiNotFoundError, PermissionNotFoundError, SessionBusyError } from "../errors" import { described } from "./metadata" import { QueryBoolean } from "./query" +import { ProviderV2 } from "@opencode-ai/core/provider" const root = "/session" export const ListQuery = Schema.Struct({ @@ -45,6 +47,7 @@ export const MessagesQuery = Schema.Struct({ export const StatusMap = Schema.Record(Schema.String, SessionStatus.Info) export const UpdatePayload = Schema.Struct({ title: Schema.optional(Schema.String), + metadata: Schema.optional(Session.Metadata), permission: Schema.optional(Permission.Ruleset), time: Schema.optional( Schema.Struct({ @@ -54,13 +57,13 @@ export const UpdatePayload = Schema.Struct({ }) export const ForkPayload = Schema.Struct(Struct.omit(Session.ForkInput.fields, ["sessionID"])) export const InitPayload = Schema.Struct({ - modelID: ModelID, - providerID: ProviderID, + modelID: ProviderV2.ModelID, + providerID: ProviderV2.ID, messageID: MessageID, }) export const SummarizePayload = Schema.Struct({ - providerID: ProviderID, - modelID: ModelID, + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, auto: Schema.optional(Schema.Boolean), }) export const PromptPayload = Schema.Struct(Struct.omit(SessionPrompt.PromptInput.fields, ["sessionID"])) @@ -175,7 +178,7 @@ export const SessionApi = HttpApi.make("session") HttpApiEndpoint.get("messages", SessionPaths.messages, { params: { sessionID: SessionID }, query: MessagesQuery, - success: described(Schema.Array(MessageV2.WithParts), "List of messages"), + success: described(Schema.Array(SessionLegacy.WithParts), "List of messages"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ @@ -187,7 +190,7 @@ export const SessionApi = HttpApi.make("session") HttpApiEndpoint.get("message", SessionPaths.message, { params: { sessionID: SessionID, messageID: MessageID }, query: WorkspaceRoutingQuery, - success: described(MessageV2.WithParts, "Message"), + success: described(SessionLegacy.WithParts, "Message"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ @@ -236,7 +239,7 @@ export const SessionApi = HttpApi.make("session") HttpApiEndpoint.post("fork", SessionPaths.fork, { params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, - payload: Schema.optional(ForkPayload), + payload: [HttpApiSchema.NoContent, ForkPayload], success: described(Session.Info, "200"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( @@ -313,7 +316,7 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, payload: PromptPayload, - success: described(MessageV2.WithParts, "Created message"), + success: described(SessionLegacy.WithParts, "Created message"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ @@ -340,7 +343,7 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, payload: CommandPayload, - success: described(MessageV2.WithParts, "Created message"), + success: described(SessionLegacy.WithParts, "Created message"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ @@ -353,7 +356,7 @@ export const SessionApi = HttpApi.make("session") params: { sessionID: SessionID }, query: WorkspaceRoutingQuery, payload: ShellPayload, - success: described(MessageV2.WithParts, "Created message"), + success: described(SessionLegacy.WithParts, "Created message"), error: [HttpApiError.BadRequest, ApiNotFoundError, SessionBusyError], }).annotateMerge( OpenApi.annotations({ @@ -429,8 +432,8 @@ export const SessionApi = HttpApi.make("session") HttpApiEndpoint.patch("updatePart", SessionPaths.updatePart, { params: { sessionID: SessionID, messageID: MessageID, partID: PartID }, query: WorkspaceRoutingQuery, - payload: MessageV2.Part, - success: described(MessageV2.Part, "Successfully updated part"), + payload: SessionLegacy.Part, + success: described(SessionLegacy.Part, "Successfully updated part"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( OpenApi.annotations({ diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/tui.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/tui.ts index 3cf3de5b8eb6..692461d68830 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/tui.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/tui.ts @@ -12,19 +12,19 @@ const root = "/tui" export const CommandPayload = Schema.Struct({ command: Schema.String }) const EventTuiPromptAppend = Schema.Struct({ type: Schema.Literal(TuiEvent.PromptAppend.type), - properties: TuiEvent.PromptAppend.properties, + properties: TuiEvent.PromptAppend.data, }).annotate({ identifier: "EventTuiPromptAppend" }) const EventTuiCommandExecute = Schema.Struct({ type: Schema.Literal(TuiEvent.CommandExecute.type), - properties: TuiEvent.CommandExecute.properties, + properties: TuiEvent.CommandExecute.data, }).annotate({ identifier: "EventTuiCommandExecute" }) const EventTuiToastShow = Schema.Struct({ type: Schema.Literal(TuiEvent.ToastShow.type), - properties: TuiEvent.ToastShow.properties, + properties: TuiEvent.ToastShow.data, }).annotate({ identifier: "EventTuiToastShow" }) const EventTuiSessionSelect = Schema.Struct({ type: Schema.Literal(TuiEvent.SessionSelect.type), - properties: TuiEvent.SessionSelect.properties, + properties: TuiEvent.SessionSelect.data, }).annotate({ identifier: "EventTuiSessionSelect" }) export const TuiPublishPayload = Schema.Union([ EventTuiPromptAppend, @@ -55,7 +55,7 @@ export const TuiApi = HttpApi.make("tui") .add( HttpApiEndpoint.post("appendPrompt", TuiPaths.appendPrompt, { query: WorkspaceRoutingQuery, - payload: TuiEvent.PromptAppend.properties, + payload: TuiEvent.PromptAppend.data, success: described(Schema.Boolean, "Prompt processed successfully"), error: HttpApiError.BadRequest, }).annotateMerge( @@ -139,7 +139,7 @@ export const TuiApi = HttpApi.make("tui") ), HttpApiEndpoint.post("showToast", TuiPaths.showToast, { query: WorkspaceRoutingQuery, - payload: TuiEvent.ToastShow.properties, + payload: TuiEvent.ToastShow.data, success: described(Schema.Boolean, "Toast notification shown successfully"), }).annotateMerge( OpenApi.annotations({ @@ -162,7 +162,7 @@ export const TuiApi = HttpApi.make("tui") ), HttpApiEndpoint.post("selectSession", TuiPaths.selectSession, { query: WorkspaceRoutingQuery, - payload: TuiEvent.SessionSelect.properties, + payload: TuiEvent.SessionSelect.data, success: described(Schema.Boolean, "Session selected successfully"), error: [HttpApiError.BadRequest, ApiNotFoundError], }).annotateMerge( diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/location.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/location.ts index f2a9a33557a5..c9b21b5adf8e 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/location.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/location.ts @@ -1,6 +1,7 @@ import { Catalog } from "@opencode-ai/core/catalog" import { Location } from "@opencode-ai/core/location" import { LocationServiceMap } from "@opencode-ai/core/location-layer" +import { AbsolutePath } from "@opencode-ai/core/schema" import { PluginBoot } from "@opencode-ai/core/plugin/boot" import { Effect, Layer, Schema } from "effect" import { HttpServerRequest } from "effect/unstable/http" @@ -40,7 +41,9 @@ export class V2LocationMiddleware extends HttpApiMiddleware.Service< function ref(request: HttpServerRequest.HttpServerRequest): Location.Ref { const query = new URL(request.url, "http://localhost").searchParams return { - directory: query.get("location[directory]") || request.headers["x-opencode-directory"] || process.cwd(), + directory: AbsolutePath.make( + query.get("location[directory]") || request.headers["x-opencode-directory"] || process.cwd(), + ), workspaceID: query.get("location[workspace]") || request.headers["x-opencode-workspace"], } } diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts index 794a7496323c..be2fdb5ba4d6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/message.ts @@ -1,5 +1,5 @@ import { SessionID } from "@/session/schema" -import { SessionMessage } from "@opencode-ai/core/session-message" +import { SessionMessage } from "@opencode-ai/core/session/message" import { Schema } from "effect" import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { InvalidCursorError, SessionNotFoundError, UnknownError } from "../../errors" diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts index c1a07957dba9..da228445c043 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/v2/session.ts @@ -1,7 +1,7 @@ import { SessionID } from "@/session/schema" -import { SessionMessage } from "@opencode-ai/core/session-message" -import { Prompt } from "@opencode-ai/core/session-prompt" -import { SessionV2 } from "@/v2/session" +import { SessionMessage } from "@opencode-ai/core/session/message" +import { Prompt } from "@opencode-ai/core/session/prompt" +import { SessionV2 } from "@opencode-ai/core/session" import { Schema } from "effect" import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi" import { diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/workspace.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/workspace.ts index 6a5101dc4219..09a6e67b6e9b 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/workspace.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/workspace.ts @@ -27,6 +27,16 @@ export class ApiWorkspaceWarpError extends Schema.ErrorClass("WorkspaceCreateError")( + { + name: Schema.Literal("WorkspaceCreateError"), + data: Schema.Struct({ + message: Schema.String, + }), + }, + { httpApiStatus: 400 }, +) {} + export const WorkspacePaths = { adapters: `${root}/adapter`, list: root, @@ -64,7 +74,7 @@ export const WorkspaceApi = HttpApi.make("workspace") query: WorkspaceRoutingQuery, payload: CreatePayload, success: described(Workspace.Info, "Workspace created"), - error: HttpApiError.BadRequest, + error: [ApiWorkspaceCreateError, HttpApiError.BadRequest], }).annotateMerge( OpenApi.annotations({ identifier: "experimental.workspace.create", diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/control.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/control.ts index e1ede2274b69..7bbbfcca61e6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/control.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/control.ts @@ -1,24 +1,27 @@ import { Auth } from "@/auth" -import { ProviderID } from "@/provider/schema" + import * as Log from "@opencode-ai/core/util/log" import { Effect } from "effect" import { HttpApiBuilder } from "effect/unstable/httpapi" import { RootHttpApi } from "../api" import { LogInput } from "../groups/control" +import { ProviderV2 } from "@opencode-ai/core/provider" export const controlHandlers = HttpApiBuilder.group(RootHttpApi, "control", (handlers) => Effect.gen(function* () { const auth = yield* Auth.Service const authSet = Effect.fn("ControlHttpApi.authSet")(function* (ctx: { - params: { providerID: ProviderID } + params: { providerID: ProviderV2.ID } payload: Auth.Info }) { yield* auth.set(ctx.params.providerID, ctx.payload).pipe(Effect.orDie) return true }) - const authRemove = Effect.fn("ControlHttpApi.authRemove")(function* (ctx: { params: { providerID: ProviderID } }) { + const authRemove = Effect.fn("ControlHttpApi.authRemove")(function* (ctx: { + params: { providerID: ProviderV2.ID } + }) { yield* auth.remove(ctx.params.providerID).pipe(Effect.orDie) return true }) diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/event.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/event.ts index e770a7cfba1a..e1294c177473 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/event.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/event.ts @@ -1,6 +1,9 @@ -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" +import { InstanceState } from "@/effect/instance-state" +import { GlobalBus } from "@/bus/global" +import { EventV2 } from "@opencode-ai/core/event" import * as Log from "@opencode-ai/core/util/log" -import { Effect } from "effect" +import { Effect, Queue } from "effect" import * as Stream from "effect/Stream" import { HttpServerResponse } from "effect/unstable/http" import { HttpApiBuilder } from "effect/unstable/httpapi" @@ -18,24 +21,57 @@ function eventData(data: unknown): Sse.Event { } } -function eventResponse(bus: Bus.Interface) { +function eventID() { + return EventV2.ID.create() +} + +function eventResponse(events: EventV2.Interface) { return Effect.gen(function* () { - // Subscribe eagerly: the bus subscription is acquired in the request scope - // at this yield, so any publish from now on is queued for the body-pump - // fiber to drain — closing the race where Stream.concat(server.connected, - // lazy-subscribe) used to drop publishes in the prefix-consume window. - const events = (yield* bus.subscribeAll()).pipe( - Stream.takeUntil((event) => event.type === Bus.InstanceDisposed.type), + const instance = yield* InstanceState.context + const workspaceID = yield* InstanceState.workspaceID + // Listener registration is eager, so events published after this point cannot + // be lost while the HTTP body fiber is starting or emitting server.connected. + const queue = yield* Queue.unbounded() + const unsubscribe = yield* events.listen((event) => Effect.sync(() => Queue.offerUnsafe(queue, event))) + yield* Effect.addFinalizer(() => unsubscribe) + const stream = Stream.fromQueue(queue).pipe( + Stream.filter( + (event) => + event.location?.directory === instance.directory && + (event.location.workspaceID === undefined || event.location.workspaceID === workspaceID), + ), + Stream.map((event) => ({ id: event.id, type: event.type, properties: event.data })), + ) + const disposed = Stream.callback<{ id: string; type: string; properties: unknown }>((queue) => { + const listener = (event: { + directory?: string + payload: { id?: string; type?: string; properties?: unknown } + }) => { + if (event.directory !== instance.directory || event.payload.type !== "server.instance.disposed") return + Queue.offerUnsafe(queue, { + id: event.payload.id ?? eventID(), + type: "server.instance.disposed", + properties: event.payload.properties ?? {}, + }) + } + return Effect.acquireRelease( + Effect.sync(() => GlobalBus.on("event", listener)), + () => Effect.sync(() => GlobalBus.off("event", listener)), + ) + }) + const output = stream.pipe( + Stream.merge(disposed, { haltStrategy: "left" }), + Stream.takeUntil((event) => event.type === "server.instance.disposed"), ) const heartbeat = Stream.tick("10 seconds").pipe( Stream.drop(1), - Stream.map(() => ({ id: Bus.createID(), type: "server.heartbeat", properties: {} })), + Stream.map(() => ({ id: eventID(), type: "server.heartbeat", properties: {} })), ) log.info("event connected") return HttpServerResponse.stream( - Stream.make({ id: Bus.createID(), type: "server.connected", properties: {} }).pipe( - Stream.concat(events.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }))), + Stream.make({ id: eventID(), type: "server.connected", properties: {} }).pipe( + Stream.concat(output.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }))), Stream.map(eventData), Stream.pipeThroughChannel(Sse.encode()), Stream.encodeText, @@ -55,11 +91,11 @@ function eventResponse(bus: Bus.Interface) { export const eventHandlers = HttpApiBuilder.group(EventApi, "event", (handlers) => Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service return handlers.handleRaw( "subscribe", Effect.fn("EventHttpApi.subscribe")(function* () { - return yield* eventResponse(bus) + return yield* eventResponse(events) }), ) }), diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts index 56a8de3ffac5..e995c21602a3 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts @@ -29,6 +29,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper const project = yield* Project.Service const registry = yield* ToolRegistry.Service const worktreeSvc = yield* Worktree.Service + const sessions = yield* Session.Service const getConsole = Effect.fn("ExperimentalHttpApi.console")(function* () { const [state, groups] = yield* Effect.all( @@ -104,9 +105,9 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper }) const worktreeCreate = Effect.fn("ExperimentalHttpApi.worktreeCreate")(function* (ctx: { - payload: Worktree.CreateInput | undefined + payload: typeof Worktree.CreateInput.Type | void }) { - return yield* mapWorktreeError(worktreeSvc.create(ctx.payload)) + return yield* mapWorktreeError(worktreeSvc.create(ctx.payload ?? undefined)) }) const worktreeRemove = Effect.fn("ExperimentalHttpApi.worktreeRemove")(function* (input: { @@ -127,21 +128,19 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper const session = Effect.fn("ExperimentalHttpApi.session")(function* (ctx: { query: typeof SessionListQuery.Type }) { const limit = ctx.query.limit ?? 100 - const sessions = Array.from( - Session.listGlobal({ - directory: ctx.query.directory, - roots: ctx.query.roots, - start: ctx.query.start, - cursor: ctx.query.cursor, - search: ctx.query.search, - limit: limit + 1, - archived: ctx.query.archived, - }), - ) - const list = sessions.length > limit ? sessions.slice(0, limit) : sessions + const all = yield* sessions.listGlobal({ + directory: ctx.query.directory, + roots: ctx.query.roots, + start: ctx.query.start, + cursor: ctx.query.cursor, + search: ctx.query.search, + limit: limit + 1, + archived: ctx.query.archived, + }) + const list = all.length > limit ? all.slice(0, limit) : all return HttpServerResponse.jsonUnsafe(list, { headers: - sessions.length > limit && list.length > 0 + all.length > limit && list.length > 0 ? { "x-next-cursor": String(list[list.length - 1].time.updated) } : undefined, }) diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/global.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/global.ts index f80869b64d3f..a63a9a958ff4 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/global.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/global.ts @@ -1,7 +1,7 @@ import { Config } from "@/config/config" import { GlobalBus, type GlobalEvent as GlobalBusEvent } from "@/bus/global" import { EffectBridge } from "@/effect/bridge" -import { Bus } from "@/bus" +import { EventV2 } from "@opencode-ai/core/event" import { Installation } from "@/installation" import { disposeAllInstancesAndEmitGlobalDisposed } from "@/server/global-lifecycle" import { InstallationVersion } from "@opencode-ai/core/installation/version" @@ -44,11 +44,11 @@ function eventResponse() { }) const heartbeat = Stream.tick("10 seconds").pipe( Stream.drop(1), - Stream.map(() => ({ payload: { id: Bus.createID(), type: "server.heartbeat", properties: {} } })), + Stream.map(() => ({ payload: { id: EventV2.ID.create(), type: "server.heartbeat", properties: {} } })), ) return HttpServerResponse.stream( - Stream.make({ payload: { id: Bus.createID(), type: "server.connected", properties: {} } }).pipe( + Stream.make({ payload: { id: EventV2.ID.create(), type: "server.connected", properties: {} } }).pipe( Stream.concat(events.pipe(Stream.merge(heartbeat, { haltStrategy: "left" }))), Stream.map(eventData), Stream.pipeThroughChannel(Sse.encode()), diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts index 1b61204c4ca0..8b4fc608fb8a 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts @@ -1,6 +1,6 @@ import * as InstanceState from "@/effect/instance-state" import { Project } from "@/project/project" -import { ProjectID } from "@/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { Effect } from "effect" import { HttpApiBuilder } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" @@ -33,7 +33,7 @@ export const projectHandlers = HttpApiBuilder.group(InstanceHttpApi, "project", }) const update = Effect.fn("ProjectHttpApi.update")(function* (ctx: { - params: { projectID: ProjectID } + params: { projectID: ProjectV2.ID } payload: Project.UpdatePayload }) { return yield* svc.update({ ...ctx.payload, projectID: ctx.params.projectID }).pipe( diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/provider.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/provider.ts index b9766ca97b53..e1377b6f75c5 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/provider.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/provider.ts @@ -2,13 +2,14 @@ import { ProviderAuth } from "@/provider/auth" import { Config } from "@/config/config" import { ModelsDev } from "@opencode-ai/core/models-dev" import { Provider } from "@/provider/provider" -import { ProviderID } from "@/provider/schema" + import { mapValues } from "remeda" import { Effect, Schema } from "effect" import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http" import { HttpApiBuilder } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" import { ProviderAuthApiError } from "../groups/provider" +import { ProviderV2 } from "@opencode-ai/core/provider" function mapProviderAuthError(self: Effect.Effect) { return self.pipe( @@ -62,7 +63,7 @@ export const providerHandlers = HttpApiBuilder.group(InstanceHttpApi, "provider" }) const authorize = Effect.fn("ProviderHttpApi.authorize")(function* (ctx: { - params: { providerID: ProviderID } + params: { providerID: ProviderV2.ID } payload: ProviderAuth.AuthorizeInput }) { return yield* mapProviderAuthError( @@ -75,7 +76,7 @@ export const providerHandlers = HttpApiBuilder.group(InstanceHttpApi, "provider" }) const authorizeRaw = Effect.fn("ProviderHttpApi.authorizeRaw")(function* (ctx: { - params: { providerID: ProviderID } + params: { providerID: ProviderV2.ID } request: HttpServerRequest.HttpServerRequest }) { const body = yield* Effect.orDie(ctx.request.text) @@ -90,7 +91,7 @@ export const providerHandlers = HttpApiBuilder.group(InstanceHttpApi, "provider" }) const callback = Effect.fn("ProviderHttpApi.callback")(function* (ctx: { - params: { providerID: ProviderID } + params: { providerID: ProviderV2.ID } payload: ProviderAuth.CallbackInput }) { yield* mapProviderAuthError( diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/pty.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/pty.ts index 4644b02934dc..f9349464be7a 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/pty.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/pty.ts @@ -10,13 +10,13 @@ import { PTY_CONNECT_TOKEN_HEADER, PTY_CONNECT_TOKEN_HEADER_VALUE, } from "@/server/shared/pty-ticket" -import { Effect } from "effect" -import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" +import { Effect, Option, Schema } from "effect" +import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http" import { HttpApiBuilder } from "effect/unstable/httpapi" import * as Socket from "effect/unstable/socket/Socket" import { InstanceHttpApi } from "../api" import * as ApiError from "../errors" -import { CursorQuery, Params, PtyPaths } from "../groups/pty" +import { CursorQuery, PtyConnectApi } from "../groups/pty" import { WebSocketTracker } from "../websocket-tracker" function validOrigin(request: HttpServerRequest.HttpServerRequest, opts: CorsOptions | undefined) { @@ -121,37 +121,39 @@ export const ptyHandlers = HttpApiBuilder.group(InstanceHttpApi, "pty", (handler }), ) -export const ptyConnectRoute = HttpRouter.use((router) => +export const ptyConnectHandlers = HttpApiBuilder.group(PtyConnectApi, "pty-connect", (handlers) => Effect.gen(function* () { const pty = yield* Pty.Service const tickets = yield* PtyTicket.Service const cors = yield* CorsConfig - yield* router.add( - "GET", - PtyPaths.connect, - Effect.gen(function* () { - const params = yield* HttpRouter.schemaPathParams(Params) - const exists = yield* pty.get(params.ptyID).pipe( + + return handlers.handleRaw( + "connect", + Effect.fn("PtyHttpApi.connect")(function* (ctx: { + params: { ptyID: PtyID } + request: HttpServerRequest.HttpServerRequest + }) { + const exists = yield* pty.get(ctx.params.ptyID).pipe( Effect.as(true), Effect.catchTag("Pty.NotFoundError", () => Effect.succeed(false)), ) if (!exists) return HttpServerResponse.empty({ status: 404 }) - const query = yield* HttpServerRequest.schemaSearchParams(CursorQuery) - const request = yield* HttpServerRequest.HttpServerRequest - const ticket = new URL(request.url, "http://localhost").searchParams.get(PTY_CONNECT_TICKET_QUERY) + const query = Schema.decodeUnknownOption(CursorQuery)(yield* HttpServerRequest.ParsedSearchParams) + if (Option.isNone(query)) return HttpServerResponse.empty({ status: 400 }) + const ticket = new URL(ctx.request.url, "http://localhost").searchParams.get(PTY_CONNECT_TICKET_QUERY) if (ticket) { - const valid = validOrigin(request, cors) - ? yield* tickets.consume({ ticket, ptyID: params.ptyID, ...(yield* PtyTicket.scope) }) + const valid = validOrigin(ctx.request, cors) + ? yield* tickets.consume({ ticket, ptyID: ctx.params.ptyID, ...(yield* PtyTicket.scope) }) : false if (!valid) return HttpServerResponse.empty({ status: 403 }) } - const parsedCursor = query.cursor === undefined ? undefined : Number(query.cursor) + const parsedCursor = query.value.cursor === undefined ? undefined : Number(query.value.cursor) const cursor = parsedCursor !== undefined && Number.isSafeInteger(parsedCursor) && parsedCursor >= -1 ? parsedCursor : undefined - const socket = yield* Effect.orDie(request.upgrade) + const socket = yield* Effect.orDie(ctx.request.upgrade) const write = yield* socket.writer const closeAccepted = (event: Socket.CloseEvent) => socket @@ -186,7 +188,7 @@ export const ptyConnectRoute = HttpRouter.use((router) => }, } const handler = yield* pty - .connect(params.ptyID, adapter, cursor) + .connect(ctx.params.ptyID, adapter, cursor) .pipe( Effect.catchTag("Pty.NotFoundError", () => closeAccepted(new Socket.CloseEvent(4404, "session not found")).pipe(Effect.as(undefined)), @@ -194,12 +196,8 @@ export const ptyConnectRoute = HttpRouter.use((router) => ) if (!handler) return HttpServerResponse.empty() - // No `pending[]`-style early-frame buffer (the legacy handler had one). - // `request.upgrade` returns a Socket without running the WS handshake; the - // handshake fires inside `socket.runRaw` below, AFTER `pty.connect` resolves - // and the message callback is registered. The client therefore can't fire - // `open` and start sending until the listener is already wired. Don't move - // `runRaw` ahead of `pty.connect` without re-introducing a buffer. + // The handshake runs inside `socket.runRaw`, after the input callback is + // registered, so the client cannot send frames before PTY input is wired. yield* socket .runRaw((message) => handlePtyInput(handler, message)) .pipe( diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts index 4d4cce367b41..773fb412365b 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts @@ -1,5 +1,6 @@ import { Agent } from "@/agent/agent" -import { Bus } from "@/bus" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { EventV2Bridge } from "@/event-v2-bridge" import { Command } from "@/command" import { Permission } from "@/permission" import { PermissionID } from "@/permission/schema" @@ -56,7 +57,7 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", const statusSvc = yield* SessionStatus.Service const todoSvc = yield* Todo.Service const summary = yield* SessionSummary.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const scope = yield* Scope.Scope const list = Effect.fn("SessionHttpApi.list")(function* (ctx: { query: typeof ListQuery.Type }) { @@ -185,6 +186,9 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", if (ctx.payload.title !== undefined) { yield* session.setTitle({ sessionID: ctx.params.sessionID, title: ctx.payload.title }) } + if (ctx.payload.metadata !== undefined) { + yield* session.setMetadata({ sessionID: ctx.params.sessionID, metadata: ctx.payload.metadata }) + } if (ctx.payload.permission !== undefined) { yield* session.setPermission({ sessionID: ctx.params.sessionID, @@ -202,7 +206,10 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", payload?: typeof ForkPayload.Type }) { return yield* SessionError.mapStorageNotFound( - session.fork({ sessionID: ctx.params.sessionID, messageID: ctx.payload?.messageID }), + session.fork({ + sessionID: ctx.params.sessionID, + messageID: ctx.payload?.messageID, + }), ) }) @@ -310,7 +317,7 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", yield* Effect.logError("prompt_async failed").pipe( Effect.annotateLogs({ sessionID: ctx.params.sessionID, cause }), ) - yield* bus.publish(Session.Event.Error, { + yield* events.publish(Session.Event.Error, { sessionID: ctx.params.sessionID, error: new NamedError.Unknown({ message: Cause.pretty(cause) }).toObject(), }) @@ -389,10 +396,10 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", const updatePart = Effect.fn("SessionHttpApi.updatePart")(function* (ctx: { params: { sessionID: SessionID; messageID: MessageID; partID: PartID } - payload: typeof MessageV2.Part.Type + payload: typeof SessionLegacy.Part.Type }) { yield* requireSession(ctx.params.sessionID) - const payload = ctx.payload as MessageV2.Part + const payload = ctx.payload as SessionLegacy.Part if ( payload.id !== ctx.params.partID || payload.messageID !== ctx.params.messageID || diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts index ffe8d0baa4b8..5269f3546931 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/sync.ts @@ -1,9 +1,10 @@ import { Workspace } from "@/control-plane/workspace" import * as InstanceState from "@/effect/instance-state" import { Session } from "@/session/session" -import { Database } from "@/storage/db" -import { SyncEvent } from "@/sync" -import { EventTable } from "@/sync/event.sql" +import { Database } from "@opencode-ai/core/database/database" +import { EventV2 } from "@opencode-ai/core/event" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventTable } from "@opencode-ai/core/event/sql" import { asc } from "drizzle-orm" import { and } from "drizzle-orm" import { eq } from "drizzle-orm" @@ -21,8 +22,10 @@ const log = Log.create({ service: "server.sync" }) export const syncHandlers = HttpApiBuilder.group(InstanceHttpApi, "sync", (handlers) => Effect.gen(function* () { const workspace = yield* Workspace.Service + const session = yield* Session.Service const scope = yield* Scope.Scope - const sync = yield* SyncEvent.Service + const events = yield* EventV2Bridge.Service + const { db } = yield* Database.Service const start = Effect.fn("SyncHttpApi.start")(function* () { yield* workspace @@ -32,27 +35,27 @@ export const syncHandlers = HttpApiBuilder.group(InstanceHttpApi, "sync", (handl }) const replay = Effect.fn("SyncHttpApi.replay")(function* (ctx: { payload: typeof ReplayPayload.Type }) { - const events: SyncEvent.SerializedEvent[] = ctx.payload.events.map((event) => ({ - id: event.id, + const payload: EventV2.SerializedEvent[] = ctx.payload.events.map((event) => ({ + id: EventV2.ID.make(event.id), aggregateID: event.aggregateID, seq: event.seq, type: event.type, data: { ...event.data }, })) - const source = events[0].aggregateID + const source = payload[0].aggregateID log.info("sync replay requested", { sessionID: source, - events: events.length, - first: events[0]?.seq, - last: events.at(-1)?.seq, + events: payload.length, + first: payload[0]?.seq, + last: payload.at(-1)?.seq, directory: ctx.payload.directory, }) - yield* sync.replayAll(events) + yield* events.replayAll(payload) log.info("sync replay complete", { sessionID: source, - events: events.length, - first: events[0]?.seq, - last: events.at(-1)?.seq, + events: payload.length, + first: payload[0]?.seq, + last: payload.at(-1)?.seq, }) return { sessionID: source } }) @@ -61,12 +64,7 @@ export const syncHandlers = HttpApiBuilder.group(InstanceHttpApi, "sync", (handl const workspaceID = yield* InstanceState.workspaceID if (!workspaceID) return yield* new HttpApiError.BadRequest({}) - yield* sync.run(Session.Event.Updated, { - sessionID: ctx.payload.sessionID, - info: { - workspaceID, - }, - }) + yield* session.setWorkspace({ sessionID: ctx.payload.sessionID, workspaceID }) log.info("sync session stolen", { sessionID: ctx.payload.sessionID, @@ -78,18 +76,17 @@ export const syncHandlers = HttpApiBuilder.group(InstanceHttpApi, "sync", (handl const history = Effect.fn("SyncHttpApi.history")(function* (ctx: { payload: typeof HistoryPayload.Type }) { const exclude = Object.entries(ctx.payload) - return Database.use((db) => - db - .select() - .from(EventTable) - .where( - exclude.length > 0 - ? not(or(...exclude.map(([id, seq]) => and(eq(EventTable.aggregate_id, id), lte(EventTable.seq, seq))))!) - : undefined, - ) - .orderBy(asc(EventTable.seq)) - .all(), - ) + return yield* db + .select() + .from(EventTable) + .where( + exclude.length > 0 + ? not(or(...exclude.map(([id, seq]) => and(eq(EventTable.aggregate_id, id), lte(EventTable.seq, seq))))!) + : undefined, + ) + .orderBy(asc(EventTable.seq)) + .all() + .pipe(Effect.orDie) }) return handlers.handle("start", start).handle("replay", replay).handle("steal", steal).handle("history", history) diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/tui.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/tui.ts index 0ecebf451fe2..22039ca454d6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/tui.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/tui.ts @@ -1,4 +1,4 @@ -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { TuiEvent } from "@/cli/cmd/tui/event" import { Session } from "@/session/session" import { Effect } from "effect" @@ -26,15 +26,15 @@ const commandAliases = { export const tuiHandlers = HttpApiBuilder.group(InstanceHttpApi, "tui", (handlers) => Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const session = yield* Session.Service - const publishCommand = (command: typeof TuiEvent.CommandExecute.properties.Type.command | undefined) => - bus.publish(TuiEvent.CommandExecute, { command } as typeof TuiEvent.CommandExecute.properties.Type) + const publishCommand = (command: typeof TuiEvent.CommandExecute.data.Type.command | undefined) => + events.publish(TuiEvent.CommandExecute, { command } as typeof TuiEvent.CommandExecute.data.Type) const appendPrompt = Effect.fn("TuiHttpApi.appendPrompt")(function* (ctx: { - payload: typeof TuiEvent.PromptAppend.properties.Type + payload: typeof TuiEvent.PromptAppend.data.Type }) { - yield* bus.publish(TuiEvent.PromptAppend, ctx.payload) + yield* events.publish(TuiEvent.PromptAppend, ctx.payload) return true }) @@ -77,29 +77,30 @@ export const tuiHandlers = HttpApiBuilder.group(InstanceHttpApi, "tui", (handler }) const showToast = Effect.fn("TuiHttpApi.showToast")(function* (ctx: { - payload: typeof TuiEvent.ToastShow.properties.Type + payload: typeof TuiEvent.ToastShow.data.Type }) { - yield* bus.publish(TuiEvent.ToastShow, ctx.payload) + yield* events.publish(TuiEvent.ToastShow, ctx.payload) return true }) const publish = Effect.fn("TuiHttpApi.publish")(function* (ctx: { payload: typeof TuiPublishPayload.Type }) { if (ctx.payload.type === TuiEvent.PromptAppend.type) - yield* bus.publish(TuiEvent.PromptAppend, ctx.payload.properties) + yield* events.publish(TuiEvent.PromptAppend, ctx.payload.properties) if (ctx.payload.type === TuiEvent.CommandExecute.type) - yield* bus.publish(TuiEvent.CommandExecute, ctx.payload.properties) - if (ctx.payload.type === TuiEvent.ToastShow.type) yield* bus.publish(TuiEvent.ToastShow, ctx.payload.properties) + yield* events.publish(TuiEvent.CommandExecute, ctx.payload.properties) + if (ctx.payload.type === TuiEvent.ToastShow.type) + yield* events.publish(TuiEvent.ToastShow, ctx.payload.properties) if (ctx.payload.type === TuiEvent.SessionSelect.type) - yield* bus.publish(TuiEvent.SessionSelect, ctx.payload.properties) + yield* events.publish(TuiEvent.SessionSelect, ctx.payload.properties) return true }) const selectSession = Effect.fn("TuiHttpApi.selectSession")(function* (ctx: { - payload: typeof TuiEvent.SessionSelect.properties.Type + payload: typeof TuiEvent.SessionSelect.data.Type }) { if (!ctx.payload.sessionID.startsWith("ses")) return yield* new HttpApiError.BadRequest({}) yield* SessionError.mapStorageNotFound(session.get(ctx.payload.sessionID)) - yield* bus.publish(TuiEvent.SessionSelect, ctx.payload) + yield* events.publish(TuiEvent.SessionSelect, ctx.payload) return true }) diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts index daa799b7a8b4..0514ea56a3d2 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2.ts @@ -1,4 +1,4 @@ -import { SessionV2 } from "@/v2/session" +import { SessionV2 } from "@opencode-ai/core/session" import { Layer } from "effect" import { layer as v2LocationLayer } from "../groups/v2/location" import { messageHandlers } from "./v2/message" diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts index 0d9273d8cd02..c9cfe33bc826 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/message.ts @@ -1,5 +1,5 @@ -import { SessionMessage } from "@opencode-ai/core/session-message" -import { SessionV2 } from "@/v2/session" +import { SessionMessage } from "@opencode-ai/core/session/message" +import { SessionV2 } from "@opencode-ai/core/session" import { Effect, Schema } from "effect" import * as DateTime from "effect/DateTime" import { HttpApiBuilder } from "effect/unstable/httpapi" diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/session.ts index ff4e098fb427..f6f126335232 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/v2/session.ts @@ -1,5 +1,6 @@ -import { WorkspaceID } from "@/control-plane/schema" -import { SessionV2 } from "@/v2/session" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" +import { SessionV2 } from "@opencode-ai/core/session" +import { AbsolutePath } from "@opencode-ai/core/schema" import { DateTime, Effect, Option, Schema } from "effect" import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../../api" @@ -20,7 +21,7 @@ const SessionCursor = Schema.Struct({ direction: Schema.Union([Schema.Literal("previous"), Schema.Literal("next")]), directory: Schema.String.pipe(Schema.optional), path: Schema.String.pipe(Schema.optional), - workspaceID: WorkspaceID.pipe(Schema.optional), + workspaceID: WorkspaceV2.ID.pipe(Schema.optional), roots: Schema.Boolean.pipe(Schema.optional), start: Schema.Finite.pipe(Schema.optional), search: Schema.String.pipe(Schema.optional), @@ -78,7 +79,7 @@ const sessionCursor = { function decodeWorkspaceID(input: string | undefined) { if (input === undefined) return Effect.succeed(undefined) - const workspaceID = Schema.decodeUnknownOption(WorkspaceID)(input) + const workspaceID = Schema.decodeUnknownOption(WorkspaceV2.ID)(input) if (Option.isSome(workspaceID)) return Effect.succeed(workspaceID.value) return Effect.fail( new InvalidRequestError({ @@ -114,17 +115,21 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "v2.session start: ctx.query.start, search: ctx.query.search, } - const sessions = yield* session.list({ + const input = { limit: ctx.query.limit ?? DefaultSessionsLimit, order, - directory: filters.directory, - path: filters.path, workspaceID: filters.workspaceID, - roots: filters.roots, - start: filters.start, search: filters.search, cursor: decoded ? { id: decoded.id, time: decoded.time, direction: decoded.direction } : undefined, - }) + } + const sessions = yield* session.list( + filters.directory + ? { + ...input, + directory: AbsolutePath.make(filters.directory), + } + : input, + ) const first = sessions[0] const last = sessions.at(-1) return { @@ -168,7 +173,7 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "v2.session .handle( "compact", Effect.fn(function* (ctx) { - yield* session.compact(ctx.params.sessionID).pipe( + yield* session.compact({ sessionID: ctx.params.sessionID }).pipe( Effect.catchTag("Session.NotFoundError", (error) => Effect.fail( new SessionNotFoundError({ diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/workspace.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/workspace.ts index 2699c8659040..7f5c437d9d58 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/workspace.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/workspace.ts @@ -2,12 +2,12 @@ import { listAdapters } from "@/control-plane/adapters" import { Workspace } from "@/control-plane/workspace" import * as InstanceState from "@/effect/instance-state" import { Vcs } from "@/project/vcs" -import { Effect } from "effect" -import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi" +import { Cause, Effect } from "effect" +import { HttpApiBuilder } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" import { notFound } from "../errors" import { ApiVcsApplyError } from "../groups/instance" -import { ApiWorkspaceWarpError, CreatePayload, WarpPayload } from "../groups/workspace" +import { ApiWorkspaceCreateError, ApiWorkspaceWarpError, CreatePayload, WarpPayload } from "../groups/workspace" export const workspaceHandlers = HttpApiBuilder.group(InstanceHttpApi, "workspace", (handlers) => Effect.gen(function* () { @@ -30,7 +30,22 @@ export const workspaceHandlers = HttpApiBuilder.group(InstanceHttpApi, "workspac extra: ctx.payload.extra ?? null, projectID: instance.project.id, }) - .pipe(Effect.mapError(() => new HttpApiError.BadRequest({}))) + .pipe( + Effect.catchCause((cause) => { + // Plugin throws surface as defects (because EffectBridge.fromPromise uses Effect.promise), + // bypassing Effect.mapError. Walk the cause to surface the real error to the client. + const die = cause.reasons.find(Cause.isDieReason) + const fail = cause.reasons.find(Cause.isFailReason) + const reason: unknown = die?.defect ?? fail?.error + const message = reason instanceof Error ? reason.message : "Workspace creation failed" + return Effect.fail( + new ApiWorkspaceCreateError({ + name: "WorkspaceCreateError", + data: { message }, + }), + ) + }), + ) }) const syncList = Effect.fn("WorkspaceHttpApi.syncList")(function* () { diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts index a36d97a1fad9..db6554590f86 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts @@ -27,6 +27,13 @@ export class V2Authorization extends HttpApiMiddleware.Service( }, ) {} +export class PtyConnectAuthorization extends HttpApiMiddleware.Service()( + "@opencode/ExperimentalHttpApiPtyConnectAuthorization", + { + error: HttpApiError.UnauthorizedNoContent, + }, +) {} + function emptyCredential() { return { username: "", @@ -56,11 +63,11 @@ function decodeCredential(input: string) { Effect.match({ onFailure: emptyCredential, onSuccess: (header) => { - const parts = header.split(":") - if (parts.length !== 2) return emptyCredential() + const separator = header.indexOf(":") + if (separator === -1) return emptyCredential() return { - username: parts[0], - password: Redacted.make(parts[1]), + username: header.slice(0, separator), + password: Redacted.make(header.slice(separator + 1)), } }, }), @@ -105,7 +112,6 @@ export const authorizationRouterMiddleware = HttpRouter.middleware()( const request = yield* HttpServerRequest.HttpServerRequest const url = new URL(request.url, "http://localhost") if (isPublicUIPath(request.method, url.pathname)) return yield* effect - if (hasPtyConnectTicketURL(url)) return yield* effect return yield* credentialFromURL(url, request).pipe( Effect.flatMap((credential) => validateRawCredential(effect, credential, config)), ) @@ -129,6 +135,24 @@ export const authorizationLayer = Layer.effect( }), ) +export const ptyConnectAuthorizationLayer = Layer.effect( + PtyConnectAuthorization, + Effect.gen(function* () { + const config = yield* ServerAuth.Config + if (!ServerAuth.required(config)) return PtyConnectAuthorization.of((effect) => effect) + return PtyConnectAuthorization.of((effect) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest + const url = new URL(request.url, "http://localhost") + if (hasPtyConnectTicketURL(url)) return yield* effect + return yield* credentialFromURL(url, request).pipe( + Effect.flatMap((credential) => validateCredential(effect, credential, config)), + ) + }), + ) + }), +) + export const v2AuthorizationLayer = Layer.effect( V2Authorization, Effect.gen(function* () { diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/fence.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/fence.ts index f3bfe06689a5..c5cbc7b82083 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/fence.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/fence.ts @@ -1,20 +1,25 @@ import { Flag } from "@opencode-ai/core/flag/flag" +import { Database } from "@opencode-ai/core/database/database" import { Effect } from "effect" import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" import * as Fence from "@/server/shared/fence" const ignoredMethods = new Set(["GET", "HEAD", "OPTIONS"]) -export const fenceLayer = HttpRouter.middleware<{ handles: unknown }>()((effect) => +export const fenceLayer = HttpRouter.middleware<{ requires: Database.Service; handles: unknown }>()( Effect.gen(function* () { - const request = yield* HttpServerRequest.HttpServerRequest - if (!Flag.OPENCODE_WORKSPACE_ID || ignoredMethods.has(request.method)) return yield* effect + const { db } = yield* Database.Service + return (effect) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest + if (!Flag.OPENCODE_WORKSPACE_ID || ignoredMethods.has(request.method)) return yield* effect - const previous = Fence.load() - const response = yield* effect - const current = Fence.diff(previous, Fence.load()) - if (Object.keys(current).length === 0) return response + const previous = yield* Fence.load(db) + const response = yield* effect + const current = Fence.diff(previous, yield* Fence.load(db)) + if (Object.keys(current).length === 0) return response - return HttpServerResponse.setHeader(response, Fence.HEADER, JSON.stringify(current)) + return HttpServerResponse.setHeader(response, Fence.HEADER, JSON.stringify(current)) + }) }), ).layer diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts index 90f3ce47738e..e39eb7394a50 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts @@ -1,7 +1,7 @@ import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" import { InstanceStore } from "@/project/instance-store" import { Effect, Layer } from "effect" -import { HttpRouter, HttpServerResponse } from "effect/unstable/http" +import { HttpServerResponse } from "effect/unstable/http" import { HttpApiMiddleware } from "effect/unstable/httpapi" import { WorkspaceRouteContext } from "./workspace-routing" @@ -41,10 +41,3 @@ export const instanceContextLayer = Layer.effect( return InstanceContextMiddleware.of((effect) => provideInstanceContext(effect, store)) }), ) - -export const instanceRouterMiddleware = HttpRouter.middleware()( - Effect.gen(function* () { - const store = yield* InstanceStore.Service - return (effect) => provideInstanceContext(effect, store) - }), -) diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/proxy.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/proxy.ts index 230f5b105bfa..e5362f8cbe13 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/proxy.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/proxy.ts @@ -4,17 +4,11 @@ import { HttpBody, HttpClient, HttpClientRequest, HttpServerRequest, HttpServerR import * as Socket from "effect/unstable/socket/Socket" import { WebSocketTracker } from "../websocket-tracker" -function webSource(request: HttpServerRequest.HttpServerRequest): Request | undefined { - return request.source instanceof Request ? request.source : undefined -} - function requestBody(request: HttpServerRequest.HttpServerRequest) { if (request.method === "GET" || request.method === "HEAD") return HttpBody.empty + if (request.source instanceof Request && request.source.body === null) return HttpBody.empty const len = request.headers["content-length"] - return HttpBody.raw(webSource(request)?.body ?? null, { - contentType: request.headers["content-type"], - contentLength: len ? Number(len) : undefined, - }) + return HttpBody.stream(request.stream, request.headers["content-type"], len ? Number(len) : undefined) } export function websocket( diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts index 8bffe59640fb..873abd834938 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts @@ -1,4 +1,4 @@ -import { WorkspaceID } from "@/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import type { Target } from "@/control-plane/types" import { Workspace } from "@/control-plane/workspace" import { WorkspaceAdapterRuntime } from "@/control-plane/workspace-adapter-runtime" @@ -9,7 +9,7 @@ import { getWorkspaceRouteSessionID, isLocalWorkspaceRoute, workspaceProxyURL } import { NotFoundError } from "@/storage/storage" import { Flag } from "@opencode-ai/core/flag/flag" import { Context, Data, Effect, Layer, Option, Schema } from "effect" -import { HttpClient, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" +import { HttpClient, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" import { HttpApiMiddleware } from "effect/unstable/httpapi" import * as Socket from "effect/unstable/socket/Socket" import { InvalidRequestError } from "../errors" @@ -30,8 +30,8 @@ type RemoteTarget = Extract type RequestPlan = Data.TaggedEnum<{ InvalidWorkspace: {} - MissingWorkspace: { readonly workspaceID: WorkspaceID } - Local: { readonly directory: string; readonly workspaceID?: WorkspaceID } + MissingWorkspace: { readonly workspaceID: WorkspaceV2.ID } + Local: { readonly directory: string; readonly workspaceID?: WorkspaceV2.ID } Remote: { readonly request: HttpServerRequest.HttpServerRequest readonly workspace: Workspace.Info @@ -46,7 +46,7 @@ export class WorkspaceRouteContext extends Context.Service< WorkspaceRouteContext, { readonly directory: string - readonly workspaceID?: WorkspaceID + readonly workspaceID?: WorkspaceV2.ID } >()("@opencode/ExperimentalHttpApiWorkspaceRouteContext") {} @@ -62,23 +62,23 @@ function requestURL(request: HttpServerRequest.HttpServerRequest): URL { return new URL(request.url, "http://localhost") } -function configuredWorkspaceID(): WorkspaceID | undefined { - return Flag.OPENCODE_WORKSPACE_ID ? WorkspaceID.make(Flag.OPENCODE_WORKSPACE_ID) : undefined +function configuredWorkspaceID(): WorkspaceV2.ID | undefined { + return Flag.OPENCODE_WORKSPACE_ID ? WorkspaceV2.ID.make(Flag.OPENCODE_WORKSPACE_ID) : undefined } -function selectedWorkspaceID(url: URL, sessionWorkspaceID?: WorkspaceID): WorkspaceID | undefined { +function selectedWorkspaceID(url: URL, sessionWorkspaceID?: WorkspaceV2.ID): WorkspaceV2.ID | undefined { const workspaceParam = url.searchParams.get("workspace") - return sessionWorkspaceID ?? (workspaceParam ? WorkspaceID.make(workspaceParam) : undefined) + return sessionWorkspaceID ?? (workspaceParam ? WorkspaceV2.ID.make(workspaceParam) : undefined) } function selectedV2WorkspaceID( url: URL, - sessionWorkspaceID?: WorkspaceID, -): WorkspaceID | typeof InvalidWorkspaceID | undefined { + sessionWorkspaceID?: WorkspaceV2.ID, +): WorkspaceV2.ID | typeof InvalidWorkspaceID | undefined { if (sessionWorkspaceID) return sessionWorkspaceID const workspaceParam = url.searchParams.get("workspace") if (!workspaceParam) return undefined - const workspaceID = Schema.decodeUnknownOption(WorkspaceID)(workspaceParam) + const workspaceID = Schema.decodeUnknownOption(WorkspaceV2.ID)(workspaceParam) if (Option.isNone(workspaceID)) return InvalidWorkspaceID return workspaceID.value } @@ -92,14 +92,14 @@ function shouldStayOnControlPlane(request: HttpServerRequest.HttpServerRequest, } function resolveWorkspace( - id: WorkspaceID | undefined, - envWorkspaceID: WorkspaceID | undefined, + id: WorkspaceV2.ID | undefined, + envWorkspaceID: WorkspaceV2.ID | undefined, ): Effect.Effect { if (!id || envWorkspaceID) return Effect.void return Workspace.Service.use((workspace) => workspace.get(id)) } -function missingWorkspaceResponse(id: WorkspaceID): HttpServerResponse.HttpServerResponse { +function missingWorkspaceResponse(id: WorkspaceV2.ID): HttpServerResponse.HttpServerResponse { return HttpServerResponse.text(`Workspace not found: ${id}`, { status: 500, contentType: "text/plain; charset=utf-8", @@ -159,14 +159,14 @@ function planWorkspaceRequest( function planRequest( request: HttpServerRequest.HttpServerRequest, - sessionWorkspaceID?: WorkspaceID, + session?: Session.Info, ): Effect.Effect { return Effect.gen(function* () { const url = requestURL(request) const envWorkspaceID = configuredWorkspaceID() const workspaceID = url.pathname.startsWith("/api/") - ? selectedV2WorkspaceID(url, sessionWorkspaceID) - : selectedWorkspaceID(url, sessionWorkspaceID) + ? selectedV2WorkspaceID(url, session?.workspaceID) + : selectedWorkspaceID(url, session?.workspaceID) if (workspaceID === InvalidWorkspaceID) return RequestPlan.InvalidWorkspace() const workspace = yield* resolveWorkspace(workspaceID, envWorkspaceID) @@ -178,7 +178,10 @@ function planRequest( return yield* planWorkspaceRequest(request, url, workspace) } - return RequestPlan.Local({ directory: defaultDirectory(request, url), workspaceID: envWorkspaceID ?? workspaceID }) + return RequestPlan.Local({ + directory: session?.directory || defaultDirectory(request, url), + workspaceID: envWorkspaceID ?? workspaceID, + }) }) } @@ -219,11 +222,14 @@ function routeHttpApiWorkspace( const sessionID = getWorkspaceRouteSessionID(requestURL(request)) const session = sessionID ? yield* Session.Service.use((svc) => svc.get(sessionID)).pipe( - Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(undefined)), + Effect.catchIf( + (error): error is NotFoundError => NotFoundError.isInstance(error), + () => Effect.succeed(undefined), + ), Effect.catchDefect(() => Effect.succeed(undefined)), ) : undefined - const plan = yield* planRequest(request, session?.workspaceID) + const plan = yield* planRequest(request, session) return yield* routeWorkspace(client, effect, plan) }) } @@ -242,20 +248,3 @@ export const workspaceRoutingLayer = Layer.effect( ) }), ) - -export const workspaceRouterMiddleware = HttpRouter.middleware<{ provides: WorkspaceRouteContext }>()( - Effect.gen(function* () { - const makeWebSocket = yield* Socket.WebSocketConstructor - const workspace = yield* Workspace.Service - const client = yield* HttpClient.HttpClient - return (effect) => - Effect.gen(function* () { - const request = yield* HttpServerRequest.HttpServerRequest - const plan = yield* planRequest(request) - return yield* routeWorkspace(client, effect, plan) - }).pipe( - Effect.provideService(Socket.WebSocketConstructor, makeWebSocket), - Effect.provideService(Workspace.Service, workspace), - ) - }), -) diff --git a/packages/opencode/src/server/routes/instance/httpapi/server.ts b/packages/opencode/src/server/routes/instance/httpapi/server.ts index 6ccc995c6601..12761ab7ff39 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/server.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/server.ts @@ -13,7 +13,6 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Account } from "@/account/account" import { Agent } from "@/agent/agent" import { Auth } from "@/auth" -import { Bus } from "@/bus" import { Config } from "@/config/config" import { Command } from "@/command" import * as Observability from "@opencode-ai/core/effect/observability" @@ -46,9 +45,9 @@ import { Todo } from "@/session/todo" import { SessionShare } from "@/share/session" import { ShareNext } from "@/share/share-next" import { EventV2Bridge } from "@/event-v2-bridge" +import { Database } from "@opencode-ai/core/database/database" import { Skill } from "@/skill" import { Snapshot } from "@/snapshot" -import { SyncEvent } from "@/sync" import { ToolRegistry } from "@/tool/registry" import { lazy } from "@/util/lazy" import { Vcs } from "@/project/vcs" @@ -59,8 +58,14 @@ import { serveUIEffect } from "@/server/shared/ui" import { ServerAuth } from "@/server/auth" import { InstanceHttpApi, RootHttpApi } from "./api" import { PublicApi } from "./public" -import { authorizationLayer, authorizationRouterMiddleware, v2AuthorizationLayer } from "./middleware/authorization" +import { + authorizationLayer, + authorizationRouterMiddleware, + ptyConnectAuthorizationLayer, + v2AuthorizationLayer, +} from "./middleware/authorization" import { EventApi } from "./groups/event" +import { PtyConnectApi } from "./groups/pty" import { eventHandlers } from "./handlers/event" import { configHandlers } from "./handlers/config" import { controlHandlers } from "./handlers/control" @@ -72,15 +77,15 @@ import { mcpHandlers } from "./handlers/mcp" import { permissionHandlers } from "./handlers/permission" import { projectHandlers } from "./handlers/project" import { providerHandlers } from "./handlers/provider" -import { ptyConnectRoute, ptyHandlers } from "./handlers/pty" +import { ptyConnectHandlers, ptyHandlers } from "./handlers/pty" import { questionHandlers } from "./handlers/question" import { sessionHandlers } from "./handlers/session" import { syncHandlers } from "./handlers/sync" import { tuiHandlers } from "./handlers/tui" import { v2Handlers } from "./handlers/v2" import { workspaceHandlers } from "./handlers/workspace" -import { instanceContextLayer, instanceRouterMiddleware } from "./middleware/instance-context" -import { workspaceRouterMiddleware, workspaceRoutingLayer } from "./middleware/workspace-routing" +import { instanceContextLayer } from "./middleware/instance-context" +import { workspaceRoutingLayer } from "./middleware/workspace-routing" import { disposeMiddleware } from "./lifecycle" import { memoMap } from "@opencode-ai/core/effect/memo-map" import { compressionLayer } from "./middleware/compression" @@ -102,24 +107,27 @@ const cors = (corsOptions?: CorsOptions) => // Route tree: // - rootApiRoutes: typed /global/* and control routes; auth is declared by RootHttpApi. -// - eventApiRoutes/rawInstanceRoutes: raw instance routes; auth and workspace routing happen as router middleware. -// - instanceApiRoutes: schema routes; auth is declared on each group and workspace context is provided below. +// - eventApiRoutes: typed SSE route with instance routing context and its existing API contract. +// - ptyConnectApiRoutes: typed WebSocket upgrade route with ticket-aware auth. +// - instanceApiRoutes: remaining typed instance routes. // - uiRoute: raw catch-all fallback; auth is router middleware so public static assets can bypass it. const authOnlyRouterLayer = authorizationRouterMiddleware.layer.pipe(Layer.provide(ServerAuth.Config.defaultLayer)) const httpApiAuthLayer = authorizationLayer.pipe(Layer.provide(ServerAuth.Config.defaultLayer)) +const ptyConnectHttpApiAuthLayer = ptyConnectAuthorizationLayer.pipe(Layer.provide(ServerAuth.Config.defaultLayer)) const v2HttpApiAuthLayer = v2AuthorizationLayer.pipe(Layer.provide(ServerAuth.Config.defaultLayer)) +const workspaceRoutingLive = workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)) const rootApiRoutes = HttpApiBuilder.layer(RootHttpApi).pipe( Layer.provide([controlHandlers, globalHandlers]), Layer.provide(schemaErrorLayer), Layer.provide(httpApiAuthLayer), ) -const instanceRouterLayer = authorizationRouterMiddleware - .combine(instanceRouterMiddleware) - .combine(workspaceRouterMiddleware) - .layer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal), Layer.provide(ServerAuth.Config.defaultLayer)) const eventApiRoutes = HttpApiBuilder.layer(EventApi).pipe( Layer.provide(eventHandlers), - Layer.provide(instanceRouterLayer), + Layer.provide([httpApiAuthLayer, workspaceRoutingLive, instanceContextLayer]), +) +const ptyConnectApiRoutes = HttpApiBuilder.layer(PtyConnectApi).pipe( + Layer.provide(ptyConnectHandlers), + Layer.provide([ptyConnectHttpApiAuthLayer, workspaceRoutingLive, instanceContextLayer]), ) const instanceApiRoutes = HttpApiBuilder.layer(InstanceHttpApi).pipe( Layer.provide([ @@ -141,15 +149,8 @@ const instanceApiRoutes = HttpApiBuilder.layer(InstanceHttpApi).pipe( ]), ) -const rawInstanceRoutes = Layer.mergeAll(ptyConnectRoute).pipe(Layer.provide(instanceRouterLayer)) -const instanceRoutes = Layer.mergeAll(rawInstanceRoutes, instanceApiRoutes).pipe( - Layer.provide([ - httpApiAuthLayer, - v2HttpApiAuthLayer, - workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)), - instanceContextLayer, - schemaErrorLayer, - ]), +const instanceRoutes = instanceApiRoutes.pipe( + Layer.provide([httpApiAuthLayer, v2HttpApiAuthLayer, workspaceRoutingLive, instanceContextLayer, schemaErrorLayer]), ) // `OpenApi.fromApi` is non-trivial; defer until /doc is actually hit so @@ -184,13 +185,14 @@ type RouteRequirements = export function createRoutes( corsOptions?: CorsOptions, ): Layer.Layer { - return Layer.mergeAll(rootApiRoutes, eventApiRoutes, instanceRoutes, docRoute, uiRoute).pipe( + return Layer.mergeAll(rootApiRoutes, eventApiRoutes, ptyConnectApiRoutes, instanceRoutes, docRoute, uiRoute).pipe( Layer.provide([ errorLayer, compressionLayer, corsVaryFix, - fenceLayer, + fenceLayer.pipe(Layer.provide(Database.defaultLayer)), cors(corsOptions), + Database.defaultLayer, Account.defaultLayer, Agent.defaultLayer, Auth.defaultLayer, @@ -223,7 +225,6 @@ export function createRoutes( SessionSummary.defaultLayer, ShareNext.defaultLayer, Snapshot.defaultLayer, - SyncEvent.defaultLayer, EventV2Bridge.defaultLayer, Skill.defaultLayer, Todo.defaultLayer, @@ -231,7 +232,6 @@ export function createRoutes( Vcs.defaultLayer, Workspace.defaultLayer, Worktree.appLayer, - Bus.layer, AppFileSystem.defaultLayer, FetchHttpClient.layer, HttpServer.layerServices, diff --git a/packages/opencode/src/server/shared/fence.ts b/packages/opencode/src/server/shared/fence.ts index 770e4588bf6a..d01f15d218b1 100644 --- a/packages/opencode/src/server/shared/fence.ts +++ b/packages/opencode/src/server/shared/fence.ts @@ -1,8 +1,8 @@ -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { inArray } from "drizzle-orm" -import { EventSequenceTable } from "@/sync/event.sql" +import { EventSequenceTable } from "@opencode-ai/core/event/sql" import { Workspace } from "@/control-plane/workspace" -import type { WorkspaceID } from "@/control-plane/schema" +import type { WorkspaceV2 } from "@opencode-ai/core/workspace" import * as Log from "@opencode-ai/core/util/log" import { Effect } from "effect" @@ -10,16 +10,16 @@ export const HEADER = "x-opencode-sync" export type State = Record const log = Log.create({ service: "fence" }) -export function load(ids?: string[]) { - const rows = Database.use((db) => { - if (!ids?.length) { - return db.select().from(EventSequenceTable).all() - } +export function load(db: Database.Interface["db"], ids?: string[]) { + return Effect.gen(function* () { + const rows = yield* ( + ids?.length + ? db.select().from(EventSequenceTable).where(inArray(EventSequenceTable.aggregate_id, ids)).all() + : db.select().from(EventSequenceTable).all() + ).pipe(Effect.orDie) - return db.select().from(EventSequenceTable).where(inArray(EventSequenceTable.aggregate_id, ids)).all() + return Object.fromEntries(rows.map((row) => [row.aggregate_id, row.seq])) }) - - return Object.fromEntries(rows.map((row) => [row.aggregate_id, row.seq])) } export function diff(prev: State, next: State) { @@ -53,7 +53,7 @@ export function parse(headers: Headers): State | undefined { ) } -export function wait(workspaceID: WorkspaceID, state: State, signal?: AbortSignal) { +export function wait(workspaceID: WorkspaceV2.ID, state: State, signal?: AbortSignal) { return Effect.gen(function* () { log.info("waiting for state", { workspaceID, diff --git a/packages/opencode/src/session/compaction.ts b/packages/opencode/src/session/compaction.ts index 4f87edf64a58..c687df59bbe5 100644 --- a/packages/opencode/src/session/compaction.ts +++ b/packages/opencode/src/session/compaction.ts @@ -1,17 +1,16 @@ -import { BusEvent } from "@/bus/bus-event" -import { Bus } from "@/bus" -import * as Session from "./session" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Session } from "./session" import { SessionID, MessageID, PartID } from "./schema" import { Provider } from "@/provider/provider" import { MessageV2 } from "./message-v2" import { Token } from "@/util/token" -import * as Log from "@opencode-ai/core/util/log" +import { Log } from "@opencode-ai/core/util/log" import { SessionProcessor } from "./processor" import { Agent } from "@/agent/agent" import { Plugin } from "@/plugin" import { Config } from "@/config/config" import { NotFoundError } from "@/storage/storage" -import { ModelID, ProviderID } from "@/provider/schema" + import { Effect, Layer, Context, Schema } from "effect" import * as DateTime from "effect/DateTime" import { InstanceState } from "@/effect/instance-state" @@ -19,17 +18,19 @@ import { isOverflow as overflow, usable } from "./overflow" import { serviceUse } from "@opencode-ai/core/effect/service-use" import { RuntimeFlags } from "@/effect/runtime-flags" import { EventV2Bridge } from "@/event-v2-bridge" -import { SessionEvent } from "@opencode-ai/core/session-event" +import { SessionEvent } from "@opencode-ai/core/session/event" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { EventV2 } from "@opencode-ai/core/event" const log = Log.create({ service: "session.compaction" }) export const Event = { - Compacted: BusEvent.define( - "session.compacted", - Schema.Struct({ + Compacted: EventV2.define({ + type: "session.compacted", + schema: { sessionID: SessionID, - }), - ), + }, + }), } export const PRUNE_MINIMUM = 20_000 @@ -92,9 +93,9 @@ type CompletedCompaction = { summary: string | undefined } -function summaryText(message: MessageV2.WithParts) { +function summaryText(message: SessionLegacy.WithParts) { const text = message.parts - .filter((part): part is MessageV2.TextPart => part.type === "text") + .filter((part): part is SessionLegacy.TextPart => part.type === "text") .map((part) => part.text.trim()) .filter(Boolean) .join("\n\n") @@ -102,7 +103,7 @@ function summaryText(message: MessageV2.WithParts) { return text || undefined } -function completedCompactions(messages: MessageV2.WithParts[]) { +function completedCompactions(messages: SessionLegacy.WithParts[]) { const users = new Map() for (let i = 0; i < messages.length; i++) { const msg = messages[i] @@ -140,7 +141,7 @@ function preserveRecentBudget(input: { cfg: Config.Info; model: Provider.Model } ) } -function turns(messages: MessageV2.WithParts[]) { +function turns(messages: SessionLegacy.WithParts[]) { const result: Turn[] = [] for (let i = 0; i < messages.length; i++) { const msg = messages[i] @@ -159,11 +160,11 @@ function turns(messages: MessageV2.WithParts[]) { } function splitTurn(input: { - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] turn: Turn model: Provider.Model budget: number - estimate: (input: { messages: MessageV2.WithParts[]; model: Provider.Model }) => Effect.Effect + estimate: (input: { messages: SessionLegacy.WithParts[]; model: Provider.Model }) => Effect.Effect }) { return Effect.gen(function* () { if (input.budget <= 0) return undefined @@ -185,13 +186,13 @@ function splitTurn(input: { export interface Interface { readonly isOverflow: (input: { - tokens: MessageV2.Assistant["tokens"] + tokens: SessionLegacy.Assistant["tokens"] model: Provider.Model }) => Effect.Effect readonly prune: (input: { sessionID: SessionID }) => Effect.Effect readonly process: (input: { parentID: MessageID - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] sessionID: SessionID auto: boolean overflow?: boolean @@ -199,7 +200,7 @@ export interface Interface { readonly create: (input: { sessionID: SessionID agent: string - model: { providerID: ProviderID; modelID: ModelID } + model: { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID } auto: boolean overflow?: boolean }) => Effect.Effect @@ -212,7 +213,6 @@ export const use = serviceUse(Service) export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service const config = yield* Config.Service const session = yield* Session.Service const agents = yield* Agent.Service @@ -223,7 +223,7 @@ export const layer = Layer.effect( const flags = yield* RuntimeFlags.Service const isOverflow = Effect.fn("SessionCompaction.isOverflow")(function* (input: { - tokens: MessageV2.Assistant["tokens"] + tokens: SessionLegacy.Assistant["tokens"] model: Provider.Model }) { return overflow({ @@ -235,7 +235,7 @@ export const layer = Layer.effect( }) const estimate = Effect.fn("SessionCompaction.estimate")(function* (input: { - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] model: Provider.Model }) { const msgs = yield* MessageV2.toModelMessagesEffect(input.messages, input.model) @@ -243,7 +243,7 @@ export const layer = Layer.effect( }) const select = Effect.fn("SessionCompaction.select")(function* (input: { - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] cfg: Config.Info model: Provider.Model }) { @@ -307,7 +307,7 @@ export const layer = Layer.effect( let total = 0 let pruned = 0 - const toPrune: MessageV2.ToolPart[] = [] + const toPrune: SessionLegacy.ToolPart[] = [] let turns = 0 loop: for (let msgIndex = msgs.length - 1; msgIndex >= 0; msgIndex--) { @@ -343,7 +343,7 @@ export const layer = Layer.effect( const processCompaction = Effect.fn("SessionCompaction.process")(function* (input: { parentID: MessageID - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] sessionID: SessionID auto: boolean overflow?: boolean @@ -353,13 +353,15 @@ export const layer = Layer.effect( throw new Error(`Compaction parent must be a user message: ${input.parentID}`) } const userMessage = parent.info - const compactionPart = parent.parts.find((part): part is MessageV2.CompactionPart => part.type === "compaction") + const compactionPart = parent.parts.find( + (part): part is SessionLegacy.CompactionPart => part.type === "compaction", + ) let messages = input.messages let replay: | { - info: MessageV2.User - parts: MessageV2.Part[] + info: SessionLegacy.User + parts: SessionLegacy.Part[] } | undefined if (input.overflow) { @@ -408,7 +410,7 @@ export const layer = Layer.effect( toolOutputMaxChars: TOOL_OUTPUT_MAX_CHARS, }) const ctx = yield* InstanceState.context - const msg: MessageV2.Assistant = { + const msg: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", parentID: input.parentID, @@ -457,7 +459,7 @@ export const layer = Layer.effect( }) if (result === "compact") { - processor.message.error = new MessageV2.ContextOverflowError({ + processor.message.error = new SessionLegacy.ContextOverflowError({ message: replay ? "Conversation history too large to compact - exceeds model context limit" : "Session too large to compact - context exceeds model limit even after stripping media", @@ -576,7 +578,7 @@ export const layer = Layer.effect( include: selected.tail_start_id, }) } - yield* bus.publish(Event.Compacted, { sessionID: input.sessionID }) + yield* events.publish(Event.Compacted, { sessionID: input.sessionID }) } return result }) @@ -584,7 +586,7 @@ export const layer = Layer.effect( const create = Effect.fn("SessionCompaction.create")(function* (input: { sessionID: SessionID agent: string - model: { providerID: ProviderID; modelID: ModelID } + model: { providerID: ProviderV2.ID; modelID: ProviderV2.ModelID } auto: boolean overflow?: boolean }) { @@ -629,7 +631,6 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(SessionProcessor.defaultLayer), Layer.provide(Agent.defaultLayer), Layer.provide(Plugin.defaultLayer), - Layer.provide(Bus.layer), Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), Layer.provide(EventV2Bridge.defaultLayer), diff --git a/packages/opencode/src/session/instruction.ts b/packages/opencode/src/session/instruction.ts index ad9a74445b9a..cae261e72b23 100644 --- a/packages/opencode/src/session/instruction.ts +++ b/packages/opencode/src/session/instruction.ts @@ -1,4 +1,5 @@ import path from "path" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Effect, Layer, Context } from "effect" import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http" import { Config } from "@/config/config" @@ -11,13 +12,7 @@ import { Global } from "@opencode-ai/core/global" import type { MessageV2 } from "./message-v2" import type { MessageID } from "./schema" -const files = (disableClaudeCodePrompt: boolean) => [ - "AGENTS.md", - ...(disableClaudeCodePrompt ? [] : ["CLAUDE.md"]), - "CONTEXT.md", // deprecated -] - -function extract(messages: MessageV2.WithParts[]) { +function extract(messages: SessionLegacy.WithParts[]) { const paths = new Set() for (const msg of messages) { for (const part of msg.parts) { @@ -40,7 +35,7 @@ export interface Interface { readonly system: () => Effect.Effect readonly find: (dir: string) => Effect.Effect readonly resolve: ( - messages: MessageV2.WithParts[], + messages: SessionLegacy.WithParts[], filepath: string, messageID: MessageID, ) => Effect.Effect<{ filepath: string; content: string }[], AppFileSystem.Error> @@ -64,7 +59,11 @@ export const layer: Layer.Layer< path.join(global.config, "AGENTS.md"), ...(!flags.disableClaudeCodePrompt ? [path.join(global.home, ".claude", "CLAUDE.md")] : []), ] - const instructionFiles = files(flags.disableClaudeCodePrompt) + const instructionFiles = [ + "AGENTS.md", + ...(!flags.disableClaudeCodePrompt ? ["CLAUDE.md"] : []), + "CONTEXT.md", // deprecated + ] const state = yield* InstanceState.make( Effect.fn("Instruction.state")(() => @@ -176,7 +175,7 @@ export const layer: Layer.Layer< }) const resolve = Effect.fn("Instruction.resolve")(function* ( - messages: MessageV2.WithParts[], + messages: SessionLegacy.WithParts[], filepath: string, messageID: MessageID, ) { @@ -231,7 +230,7 @@ export const defaultLayer = layer.pipe( Layer.provide(RuntimeFlags.defaultLayer), ) -export function loaded(messages: MessageV2.WithParts[]) { +export function loaded(messages: SessionLegacy.WithParts[]) { return extract(messages) } diff --git a/packages/opencode/src/session/llm.ts b/packages/opencode/src/session/llm.ts index ea2efc99d007..ebaad3e9306d 100644 --- a/packages/opencode/src/session/llm.ts +++ b/packages/opencode/src/session/llm.ts @@ -1,6 +1,7 @@ import { Provider } from "@/provider/provider" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { serviceUse } from "@opencode-ai/core/effect/service-use" -import * as Log from "@opencode-ai/core/util/log" +import { Log } from "@opencode-ai/core/util/log" import { Context, Effect, Layer } from "effect" import * as Stream from "effect/Stream" import { streamText, wrapLanguageModel, type ModelMessage, type Tool } from "ai" @@ -15,7 +16,8 @@ import type { MessageV2 } from "./message-v2" import { Plugin } from "@/plugin" import { Permission } from "@/permission" import { PermissionID } from "@/permission/schema" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" import { Wildcard } from "@/util/wildcard" import { SessionID } from "@/session/schema" import { Auth } from "@/auth" @@ -31,7 +33,7 @@ const log = Log.create({ service: "llm" }) export const OUTPUT_TOKEN_MAX = ProviderTransform.OUTPUT_TOKEN_MAX export type StreamInput = { - user: MessageV2.User + user: SessionLegacy.User sessionID: string parentSessionID?: string model: Provider.Model @@ -65,6 +67,7 @@ const live: Layer.Layer< | Provider.Service | Plugin.Service | Permission.Service + | EventV2Bridge.Service | LLMClientService | RuntimeFlags.Service > = Layer.effect( @@ -75,6 +78,7 @@ const live: Layer.Layer< const provider = yield* Provider.Service const plugin = yield* Plugin.Service const perm = yield* Permission.Service + const events = yield* EventV2Bridge.Service const llmClient = yield* LLMClient.Service const flags = yield* RuntimeFlags.Service @@ -162,11 +166,17 @@ const live: Layer.Layer< } const id = PermissionID.ascending() - let unsub: (() => void) | undefined + let unsub: EventV2.Unsubscribe | undefined try { - unsub = Bus.subscribe(Permission.Event.Replied, (evt) => { - if (evt.properties.requestID === id) void evt.properties.reply - }) + unsub = await bridge.promise( + events.listen((event) => { + if (event.type !== Permission.Event.Replied.type) return Effect.void + const data = event.data as EventV2.Data + if (data.requestID !== id) return Effect.void + void data.reply + return Effect.void + }), + ) const toolPatterns = approvalTools.map((t: { name: string; args: string }) => { try { const parsed = JSON.parse(t.args) as Record @@ -194,7 +204,7 @@ const live: Layer.Layer< } catch { return { approved: false } } finally { - unsub?.() + if (unsub) await bridge.promise(unsub) } }) } @@ -370,7 +380,7 @@ const live: Layer.Layer< }), ) -export const layer = live.pipe(Layer.provide(Permission.defaultLayer)) +export const layer = live.pipe(Layer.provide(Permission.defaultLayer), Layer.provide(EventV2Bridge.defaultLayer)) export const defaultLayer = Layer.suspend(() => layer.pipe( diff --git a/packages/opencode/src/session/llm/request.ts b/packages/opencode/src/session/llm/request.ts index 34713424053a..60847dab3f1b 100644 --- a/packages/opencode/src/session/llm/request.ts +++ b/packages/opencode/src/session/llm/request.ts @@ -1,4 +1,5 @@ import type { Auth } from "@/auth" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import type { RuntimeFlags } from "@/effect/runtime-flags" import { InstanceState } from "@/effect/instance-state" import { Permission } from "@/permission" @@ -16,7 +17,7 @@ import { mergeDeep } from "remeda" const USER_AGENT = `opencode/${InstallationVersion}` type PrepareInput = { - readonly user: MessageV2.User + readonly user: SessionLegacy.User readonly sessionID: string readonly parentSessionID?: string readonly model: Provider.Model diff --git a/packages/opencode/src/session/message-v2.ts b/packages/opencode/src/session/message-v2.ts index 2745ff4f45d7..2884c4cf860b 100644 --- a/packages/opencode/src/session/message-v2.ts +++ b/packages/opencode/src/session/message-v2.ts @@ -1,11 +1,27 @@ -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" import { SessionID, MessageID, PartID } from "./schema" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { + APIError, + AbortedError, + Assistant, + AuthError, + CompactionPart, + ContextOverflowError, + Info, + OutputLengthError, + Part, + StructuredOutputError, + SubtaskPart, + User, + WithParts, + type ToolPart, +} from "@opencode-ai/core/session/legacy" + import { NamedError } from "@opencode-ai/core/util/error" import { APICallError, convertToModelMessages, LoadAPIKeyError, type ModelMessage, type UIMessage } from "ai" -import { LSP } from "@/lsp/lsp" -import { Snapshot } from "@/snapshot" -import { SyncEvent } from "../sync" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { NotFoundError } from "@/storage/storage" import { and } from "drizzle-orm" import { desc } from "drizzle-orm" @@ -13,20 +29,15 @@ import { eq } from "drizzle-orm" import { inArray } from "drizzle-orm" import { lt } from "drizzle-orm" import { or } from "drizzle-orm" -import { MessageTable, PartTable, SessionTable } from "./session.sql" -import * as ProviderError from "@/provider/error" +import { MessageTable, PartTable, SessionTable } from "@opencode-ai/core/session/sql" +import { ProviderError } from "@/provider/error" import { iife } from "@/util/iife" import { errorMessage } from "@/util/error" import { isMedia } from "@/util/media" import type { SystemError } from "bun" import type { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "@/provider/schema" -import { Effect, Schema, Types } from "effect" -import { NonNegativeInt } from "@opencode-ai/core/schema" +import { Effect, Schema } from "effect" import * as EffectLogger from "@opencode-ai/core/effect/logger" -import { MessageError } from "./message-error" -import { AuthError, OutputLengthError } from "./message-error" -export { AuthError, OutputLengthError } from "./message-error" /** Error shape thrown by Bun's fetch() when gzip/br decompression fails mid-stream */ interface FetchDecompressionError extends Error { @@ -38,526 +49,27 @@ interface FetchDecompressionError extends Error { export const SYNTHETIC_ATTACHMENT_PROMPT = "Attached media from tool result:" export { isMedia } -export const AbortedError = NamedError.create("MessageAbortedError", { message: Schema.String }) -export const StructuredOutputError = NamedError.create("StructuredOutputError", { - message: Schema.String, - retries: NonNegativeInt, -}) -export const APIError = NamedError.create("APIError", { - message: Schema.String, - statusCode: Schema.optional(NonNegativeInt), - isRetryable: Schema.Boolean, - responseHeaders: Schema.optional(Schema.Record(Schema.String, Schema.String)), - responseBody: Schema.optional(Schema.String), - metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)), -}) -export type APIError = Schema.Schema.Type -export const ContextOverflowError = NamedError.create("ContextOverflowError", { - message: Schema.String, - responseBody: Schema.optional(Schema.String), -}) - -export class OutputFormatText extends Schema.Class("OutputFormatText")({ - type: Schema.Literal("text"), -}) {} - -export class OutputFormatJsonSchema extends Schema.Class("OutputFormatJsonSchema")({ - type: Schema.Literal("json_schema"), - schema: Schema.Record(Schema.String, Schema.Any).annotate({ identifier: "JSONSchema" }), - retryCount: NonNegativeInt.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed(2))), -}) {} - -export const Format = Schema.Union([OutputFormatText, OutputFormatJsonSchema]).annotate({ - discriminator: "type", - identifier: "OutputFormat", -}) -export type OutputFormat = Schema.Schema.Type - -const partBase = { - id: PartID, - sessionID: SessionID, - messageID: MessageID, -} - -export const SnapshotPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("snapshot"), - snapshot: Schema.String, -}).annotate({ identifier: "SnapshotPart" }) -export type SnapshotPart = Types.DeepMutable> - -export const PatchPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("patch"), - hash: Schema.String, - files: Schema.Array(Schema.String), -}).annotate({ identifier: "PatchPart" }) -export type PatchPart = Types.DeepMutable> - -export const TextPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("text"), - text: Schema.String, - synthetic: Schema.optional(Schema.Boolean), - ignored: Schema.optional(Schema.Boolean), - time: Schema.optional( - Schema.Struct({ - start: NonNegativeInt, - end: Schema.optional(NonNegativeInt), - }), - ), - metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), -}).annotate({ identifier: "TextPart" }) -export type TextPart = Types.DeepMutable> - -export const ReasoningPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("reasoning"), - text: Schema.String, - metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), - time: Schema.Struct({ - start: NonNegativeInt, - end: Schema.optional(NonNegativeInt), - }), -}).annotate({ identifier: "ReasoningPart" }) -export type ReasoningPart = Types.DeepMutable> - -const filePartSourceBase = { - text: Schema.Struct({ - value: Schema.String, - start: Schema.Finite, - end: Schema.Finite, - }).annotate({ identifier: "FilePartSourceText" }), -} - -export const FileSource = Schema.Struct({ - ...filePartSourceBase, - type: Schema.Literal("file"), - path: Schema.String, -}).annotate({ identifier: "FileSource" }) - -export const SymbolSource = Schema.Struct({ - ...filePartSourceBase, - type: Schema.Literal("symbol"), - path: Schema.String, - range: LSP.Range, - name: Schema.String, - kind: NonNegativeInt, -}).annotate({ identifier: "SymbolSource" }) - -export const ResourceSource = Schema.Struct({ - ...filePartSourceBase, - type: Schema.Literal("resource"), - clientName: Schema.String, - uri: Schema.String, -}).annotate({ identifier: "ResourceSource" }) - -export const FilePartSource = Schema.Union([FileSource, SymbolSource, ResourceSource]).annotate({ - discriminator: "type", - identifier: "FilePartSource", -}) - -export const FilePart = Schema.Struct({ - ...partBase, - type: Schema.Literal("file"), - mime: Schema.String, - filename: Schema.optional(Schema.String), - url: Schema.String, - source: Schema.optional(FilePartSource), -}).annotate({ identifier: "FilePart" }) -export type FilePart = Types.DeepMutable> - -export const AgentPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("agent"), - name: Schema.String, - source: Schema.optional( - Schema.Struct({ - value: Schema.String, - start: NonNegativeInt, - end: NonNegativeInt, - }), - ), -}).annotate({ identifier: "AgentPart" }) -export type AgentPart = Types.DeepMutable> - -export const CompactionPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("compaction"), - auto: Schema.Boolean, - overflow: Schema.optional(Schema.Boolean), - tail_start_id: Schema.optional(MessageID), -}).annotate({ identifier: "CompactionPart" }) -export type CompactionPart = Types.DeepMutable> - -export const SubtaskPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("subtask"), - prompt: Schema.String, - description: Schema.String, - agent: Schema.String, - model: Schema.optional( - Schema.Struct({ - providerID: ProviderID, - modelID: ModelID, - }), - ), - command: Schema.optional(Schema.String), -}).annotate({ identifier: "SubtaskPart" }) -export type SubtaskPart = Types.DeepMutable> - -export const RetryPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("retry"), - attempt: NonNegativeInt, - error: APIError.EffectSchema, - time: Schema.Struct({ - created: NonNegativeInt, - }), -}).annotate({ identifier: "RetryPart" }) -export type RetryPart = Omit>, "error"> & { - error: APIError -} - -export const StepStartPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("step-start"), - snapshot: Schema.optional(Schema.String), -}).annotate({ identifier: "StepStartPart" }) -export type StepStartPart = Types.DeepMutable> - -export const StepFinishPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("step-finish"), - reason: Schema.String, - snapshot: Schema.optional(Schema.String), - cost: Schema.Finite, - tokens: Schema.Struct({ - total: Schema.optional(Schema.Finite), - input: Schema.Finite, - output: Schema.Finite, - reasoning: Schema.Finite, - cache: Schema.Struct({ - read: Schema.Finite, - write: Schema.Finite, - }), - }), -}).annotate({ identifier: "StepFinishPart" }) -export type StepFinishPart = Types.DeepMutable> - -export const ToolStatePending = Schema.Struct({ - status: Schema.Literal("pending"), - input: Schema.Record(Schema.String, Schema.Any), - raw: Schema.String, -}).annotate({ identifier: "ToolStatePending" }) -export type ToolStatePending = Types.DeepMutable> - -export const ToolStateRunning = Schema.Struct({ - status: Schema.Literal("running"), - input: Schema.Record(Schema.String, Schema.Any), - title: Schema.optional(Schema.String), - metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), - time: Schema.Struct({ - start: NonNegativeInt, - }), -}).annotate({ identifier: "ToolStateRunning" }) -export type ToolStateRunning = Types.DeepMutable> - -export const ToolStateCompleted = Schema.Struct({ - status: Schema.Literal("completed"), - input: Schema.Record(Schema.String, Schema.Any), - output: Schema.String, - title: Schema.String, - metadata: Schema.Record(Schema.String, Schema.Any), - time: Schema.Struct({ - start: NonNegativeInt, - end: NonNegativeInt, - compacted: Schema.optional(NonNegativeInt), - }), - attachments: Schema.optional(Schema.Array(FilePart)), -}).annotate({ identifier: "ToolStateCompleted" }) -export type ToolStateCompleted = Types.DeepMutable> - function truncateToolOutput(text: string, maxChars?: number) { if (!maxChars || text.length <= maxChars) return text const omitted = text.length - maxChars return `${text.slice(0, maxChars)}\n[Tool output truncated for compaction: omitted ${omitted} chars]` } -export const ToolStateError = Schema.Struct({ - status: Schema.Literal("error"), - input: Schema.Record(Schema.String, Schema.Any), - error: Schema.String, - metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), - time: Schema.Struct({ - start: NonNegativeInt, - end: NonNegativeInt, - }), -}).annotate({ identifier: "ToolStateError" }) -export type ToolStateError = Types.DeepMutable> - -export const ToolState = Schema.Union([ - ToolStatePending, - ToolStateRunning, - ToolStateCompleted, - ToolStateError, -]).annotate({ - discriminator: "status", - identifier: "ToolState", -}) -export type ToolState = ToolStatePending | ToolStateRunning | ToolStateCompleted | ToolStateError - -export const ToolPart = Schema.Struct({ - ...partBase, - type: Schema.Literal("tool"), - callID: Schema.String, - tool: Schema.String, - state: ToolState, - metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), -}).annotate({ identifier: "ToolPart" }) -export type ToolPart = Omit>, "state"> & { - state: ToolState -} - -const messageBase = { - id: MessageID, - sessionID: SessionID, -} - -export const User = Schema.Struct({ - ...messageBase, - role: Schema.Literal("user"), - time: Schema.Struct({ - created: NonNegativeInt, - }), - format: Schema.optional(Format), - summary: Schema.optional( - Schema.Struct({ - title: Schema.optional(Schema.String), - body: Schema.optional(Schema.String), - diffs: Schema.Array(Snapshot.FileDiff), - }), - ), - agent: Schema.String, - model: Schema.Struct({ - providerID: ProviderID, - modelID: ModelID, - variant: Schema.optional(Schema.String), - }), - system: Schema.optional(Schema.String), - tools: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)), -}).annotate({ identifier: "UserMessage" }) -export type User = Types.DeepMutable> - -export const Part = Schema.Union([ - TextPart, - SubtaskPart, - ReasoningPart, - FilePart, - ToolPart, - StepStartPart, - StepFinishPart, - SnapshotPart, - PatchPart, - AgentPart, - RetryPart, - CompactionPart, -]).annotate({ discriminator: "type", identifier: "Part" }) -export type Part = - | TextPart - | SubtaskPart - | ReasoningPart - | FilePart - | ToolPart - | StepStartPart - | StepFinishPart - | SnapshotPart - | PatchPart - | AgentPart - | RetryPart - | CompactionPart - -const AssistantErrorSchema = Schema.Union([ - ...MessageError.Shared, - AbortedError.EffectSchema, - StructuredOutputError.EffectSchema, - ContextOverflowError.EffectSchema, - APIError.EffectSchema, -]).annotate({ discriminator: "name" }) -type AssistantError = Schema.Schema.Type - -// ── Prompt input schemas ───────────────────────────────────────────────────── -// -// Consumers of `SessionPrompt.PromptInput.parts` send part drafts without the -// ambient IDs (`messageID`, `sessionID`) that live on stored parts, and may -// omit `id` to let the server allocate one. These Schema-Struct variants -// carry that shape so prompt decoding can accept drafts without stored IDs. - -export const TextPartInput = Schema.Struct({ - id: Schema.optional(PartID), - type: Schema.Literal("text"), - text: Schema.String, - synthetic: Schema.optional(Schema.Boolean), - ignored: Schema.optional(Schema.Boolean), - time: Schema.optional( - Schema.Struct({ - start: NonNegativeInt, - end: Schema.optional(NonNegativeInt), - }), - ), - metadata: Schema.optional(Schema.Record(Schema.String, Schema.Any)), -}).annotate({ identifier: "TextPartInput" }) -export type TextPartInput = Types.DeepMutable> - -export const FilePartInput = Schema.Struct({ - id: Schema.optional(PartID), - type: Schema.Literal("file"), - mime: Schema.String, - filename: Schema.optional(Schema.String), - url: Schema.String, - source: Schema.optional(FilePartSource), -}).annotate({ identifier: "FilePartInput" }) -export type FilePartInput = Types.DeepMutable> - -export const AgentPartInput = Schema.Struct({ - id: Schema.optional(PartID), - type: Schema.Literal("agent"), - name: Schema.String, - source: Schema.optional( - Schema.Struct({ - value: Schema.String, - start: NonNegativeInt, - end: NonNegativeInt, - }), - ), -}).annotate({ identifier: "AgentPartInput" }) -export type AgentPartInput = Types.DeepMutable> - -export const SubtaskPartInput = Schema.Struct({ - id: Schema.optional(PartID), - type: Schema.Literal("subtask"), - prompt: Schema.String, - description: Schema.String, - agent: Schema.String, - model: Schema.optional( - Schema.Struct({ - providerID: ProviderID, - modelID: ModelID, - }), - ), - command: Schema.optional(Schema.String), -}).annotate({ identifier: "SubtaskPartInput" }) -export type SubtaskPartInput = Types.DeepMutable> - -export const Assistant = Schema.Struct({ - ...messageBase, - role: Schema.Literal("assistant"), - time: Schema.Struct({ - created: NonNegativeInt, - completed: Schema.optional(NonNegativeInt), - }), - error: Schema.optional(AssistantErrorSchema), - parentID: MessageID, - modelID: ModelID, - providerID: ProviderID, - /** - * @deprecated - */ - mode: Schema.String, - agent: Schema.String, - path: Schema.Struct({ - cwd: Schema.String, - root: Schema.String, - }), - summary: Schema.optional(Schema.Boolean), - cost: Schema.Finite, - tokens: Schema.Struct({ - total: Schema.optional(Schema.Finite), - input: Schema.Finite, - output: Schema.Finite, - reasoning: Schema.Finite, - cache: Schema.Struct({ - read: Schema.Finite, - write: Schema.Finite, - }), - }), - structured: Schema.optional(Schema.Any), - variant: Schema.optional(Schema.String), - finish: Schema.optional(Schema.String), -}).annotate({ identifier: "AssistantMessage" }) -export type Assistant = Omit>, "error"> & { - error?: AssistantError -} - -export const Info = Schema.Union([User, Assistant]).annotate({ discriminator: "role", identifier: "Message" }) -export type Info = User | Assistant - -const UpdatedEventSchema = Schema.Struct({ - sessionID: SessionID, - info: Info, -}) - -const RemovedEventSchema = Schema.Struct({ - sessionID: SessionID, - messageID: MessageID, -}) - -const PartUpdatedEventSchema = Schema.Struct({ - sessionID: SessionID, - part: Part, - time: NonNegativeInt, -}) - -const PartRemovedEventSchema = Schema.Struct({ - sessionID: SessionID, - messageID: MessageID, - partID: PartID, -}) - export const Event = { - Updated: SyncEvent.define({ - type: "message.updated", - version: 1, - aggregate: "sessionID", - schema: UpdatedEventSchema, - }), - Removed: SyncEvent.define({ - type: "message.removed", - version: 1, - aggregate: "sessionID", - schema: RemovedEventSchema, - }), - PartUpdated: SyncEvent.define({ - type: "message.part.updated", - version: 1, - aggregate: "sessionID", - schema: PartUpdatedEventSchema, - }), - PartDelta: BusEvent.define( - "message.part.delta", - Schema.Struct({ + Updated: SessionLegacy.Event.MessageUpdated, + Removed: SessionLegacy.Event.MessageRemoved, + PartUpdated: SessionLegacy.Event.PartUpdated, + PartDelta: EventV2.define({ + type: "message.part.delta", + schema: { sessionID: SessionID, messageID: MessageID, partID: PartID, field: Schema.String, delta: Schema.String, - }), - ), - PartRemoved: SyncEvent.define({ - type: "message.part.removed", - version: 1, - aggregate: "sessionID", - schema: PartRemovedEventSchema, + }, }), -} - -export const WithParts = Schema.Struct({ - info: Info, - parts: Schema.Array(Part), -}) -export type WithParts = { - info: Info - parts: Part[] + PartRemoved: SessionLegacy.Event.PartRemoved, } const Cursor = Schema.Struct({ @@ -595,30 +107,31 @@ const part = (row: typeof PartTable.$inferSelect) => const older = (row: Cursor) => or(lt(MessageTable.time_created, row.time), and(eq(MessageTable.time_created, row.time), lt(MessageTable.id, row.id))) -function hydrate(rows: (typeof MessageTable.$inferSelect)[]) { +function hydrate(db: Database.Interface["db"], rows: (typeof MessageTable.$inferSelect)[]) { const ids = rows.map((row) => row.id) const partByMessage = new Map() - if (ids.length > 0) { - const partRows = Database.use((db) => - db + return Effect.gen(function* () { + if (ids.length > 0) { + const partRows = yield* db .select() .from(PartTable) .where(inArray(PartTable.message_id, ids)) .orderBy(PartTable.message_id, PartTable.id) - .all(), - ) - for (const row of partRows) { - const next = part(row) - const list = partByMessage.get(row.message_id) - if (list) list.push(next) - else partByMessage.set(row.message_id, [next]) + .all() + .pipe(Effect.orDie) + for (const row of partRows) { + const next = part(row) + const list = partByMessage.get(row.message_id) + if (list) list.push(next) + else partByMessage.set(row.message_id, [next]) + } } - } - return rows.map((row) => ({ - info: info(row), - parts: partByMessage.get(row.id) ?? [], - })) + return rows.map((row) => ({ + info: info(row), + parts: partByMessage.get(row.id) ?? [], + })) + }) } function providerMeta(metadata: Record | undefined) { @@ -925,23 +438,26 @@ export const page = Effect.fn("MessageV2.page")(function* (input: { limit: number before?: string }) { + const { db } = yield* Database.Service const before = input.before ? cursor.decode(input.before) : undefined const where = before ? and(eq(MessageTable.session_id, input.sessionID), older(before)) : eq(MessageTable.session_id, input.sessionID) - const rows = Database.use((db) => - db - .select() - .from(MessageTable) - .where(where) - .orderBy(desc(MessageTable.time_created), desc(MessageTable.id)) - .limit(input.limit + 1) - .all(), - ) + const rows = yield* db + .select() + .from(MessageTable) + .where(where) + .orderBy(desc(MessageTable.time_created), desc(MessageTable.id)) + .limit(input.limit + 1) + .all() + .pipe(Effect.orDie) if (rows.length === 0) { - const row = Database.use((db) => - db.select({ id: SessionTable.id }).from(SessionTable).where(eq(SessionTable.id, input.sessionID)).get(), - ) + const row = yield* db + .select({ id: SessionTable.id }) + .from(SessionTable) + .where(eq(SessionTable.id, input.sessionID)) + .get() + .pipe(Effect.orDie) if (!row) return yield* new NotFoundError({ message: `Session not found: ${input.sessionID}` }) return { items: [] as WithParts[], @@ -951,7 +467,7 @@ export const page = Effect.fn("MessageV2.page")(function* (input: { const more = rows.length > input.limit const slice = more ? rows.slice(0, input.limit) : rows - const items = hydrate(slice) + const items = yield* hydrate(db, slice) items.reverse() const tail = slice.at(-1) return { @@ -961,53 +477,55 @@ export const page = Effect.fn("MessageV2.page")(function* (input: { } }) -export function* stream(sessionID: SessionID) { +export function stream(sessionID: SessionID) { const size = 50 - let before: string | undefined - while (true) { - const next = Effect.runSync( - page({ sessionID, limit: size, before }).pipe( + return Effect.gen(function* () { + const result = [] as WithParts[] + let before: string | undefined + while (true) { + const next = yield* page({ sessionID, limit: size, before }).pipe( Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed({ items: [] as WithParts[], more: false, cursor: undefined }), ), - ), - ) - if (next.items.length === 0) break - for (let i = next.items.length - 1; i >= 0; i--) { - yield next.items[i] + ) + if (next.items.length === 0) break + for (let i = next.items.length - 1; i >= 0; i--) { + const item = next.items[i] + if (item) result.push(item) + } + if (!next.more || !next.cursor) break + before = next.cursor } - if (!next.more || !next.cursor) break - before = next.cursor - } + return result + }) } -export function parts(message_id: MessageID) { - const rows = Database.use((db) => - db.select().from(PartTable).where(eq(PartTable.message_id, message_id)).orderBy(PartTable.id).all(), - ) - return rows.map( - (row) => - ({ - ...row.data, - id: row.id, - sessionID: row.session_id, - messageID: row.message_id, - }) as Part, - ) +export function parts(messageID: MessageID) { + return Effect.gen(function* () { + const { db } = yield* Database.Service + const rows = yield* db + .select() + .from(PartTable) + .where(eq(PartTable.message_id, messageID)) + .orderBy(PartTable.id) + .all() + .pipe(Effect.orDie) + return rows.map(part) + }) } export const get = Effect.fn("MessageV2.get")(function* (input: { sessionID: SessionID; messageID: MessageID }) { - const row = Database.use((db) => - db - .select() - .from(MessageTable) - .where(and(eq(MessageTable.id, input.messageID), eq(MessageTable.session_id, input.sessionID))) - .get(), - ) + const { db } = yield* Database.Service + const row = yield* db + .select() + .from(MessageTable) + .where(and(eq(MessageTable.id, input.messageID), eq(MessageTable.session_id, input.sessionID))) + .get() + .pipe(Effect.orDie) if (!row) return yield* new NotFoundError({ message: `Message not found: ${input.messageID}` }) return { info: info(row), - parts: parts(input.messageID), + parts: yield* parts(input.messageID), } }) @@ -1065,7 +583,7 @@ export function filterCompacted(msgs: Iterable) { } export const filterCompactedEffect = Effect.fnUntraced(function* (sessionID: SessionID) { - return filterCompacted(stream(sessionID)) + return filterCompacted(yield* stream(sessionID)) }) // filterCompacted reorders messages for model consumption @@ -1095,7 +613,7 @@ export function latest(msgs: WithParts[]) { export function fromError( e: unknown, - ctx: { providerID: ProviderID; aborted?: boolean }, + ctx: { providerID: ProviderV2.ID; aborted?: boolean }, ): NonNullable { switch (true) { case e instanceof DOMException && e.name === "AbortError": @@ -1143,6 +661,29 @@ export function fromError( }, { cause: e }, ).toObject() + case e instanceof ProviderError.HeaderTimeoutError: + return new APIError( + { + message: e.message, + isRetryable: true, + metadata: { + code: e.name, + timeoutMs: String(e.ms), + }, + }, + { cause: e }, + ).toObject() + case e instanceof ProviderError.ResponseStreamError: + return new APIError( + { + message: e.message, + isRetryable: true, + metadata: { + code: e.name, + }, + }, + { cause: e }, + ).toObject() case APICallError.isInstance(e): const parsed = ProviderError.parseAPICallError({ providerID: ctx.providerID, diff --git a/packages/opencode/src/session/message.ts b/packages/opencode/src/session/message.ts index 39c842f94bc5..e5332992f51e 100644 --- a/packages/opencode/src/session/message.ts +++ b/packages/opencode/src/session/message.ts @@ -1,9 +1,10 @@ import { Schema } from "effect" import { SessionID } from "./schema" -import { ModelID, ProviderID } from "../provider/schema" + import { NonNegativeInt } from "@opencode-ai/core/schema" import { MessageError } from "./message-error" import { AuthError, OutputLengthError } from "./message-error" +import { ProviderV2 } from "@opencode-ai/core/provider" export { AuthError, OutputLengthError } from "./message-error" export const ToolCall = Schema.Struct({ @@ -119,8 +120,8 @@ export const Info = Schema.Struct({ assistant: Schema.optional( Schema.Struct({ system: Schema.Array(Schema.String), - modelID: ModelID, - providerID: ProviderID, + modelID: ProviderV2.ModelID, + providerID: ProviderV2.ID, path: Schema.Struct({ cwd: Schema.String, root: Schema.String, diff --git a/packages/opencode/src/session/overflow.ts b/packages/opencode/src/session/overflow.ts index d01fe5c624dd..343c8408e95f 100644 --- a/packages/opencode/src/session/overflow.ts +++ b/packages/opencode/src/session/overflow.ts @@ -1,4 +1,5 @@ import type { Config } from "@/config/config" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import type { Provider } from "@/provider/provider" import { ProviderTransform } from "@/provider/transform" import type { MessageV2 } from "./message-v2" @@ -19,7 +20,7 @@ export function usable(input: { cfg: Config.Info; model: Provider.Model; outputT export function isOverflow(input: { cfg: Config.Info - tokens: MessageV2.Assistant["tokens"] + tokens: SessionLegacy.Assistant["tokens"] model: Provider.Model outputTokenMax?: number }) { diff --git a/packages/opencode/src/session/processor.ts b/packages/opencode/src/session/processor.ts index a287c3b00680..8f9b83a79cf3 100644 --- a/packages/opencode/src/session/processor.ts +++ b/packages/opencode/src/session/processor.ts @@ -1,13 +1,13 @@ import { Image } from "@/image/image" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Cause, Deferred, Effect, Exit, Layer, Context, Scope, Schema } from "effect" import * as Stream from "effect/Stream" import { Agent } from "@/agent/agent" -import { Bus } from "@/bus" import { Config } from "@/config/config" import { Permission } from "@/permission" import { Plugin } from "@/plugin" import { Snapshot } from "@/snapshot" -import * as Session from "./session" +import { Session } from "./session" import { LLM } from "./llm" import { MessageV2 } from "./message-v2" import { isOverflow } from "./overflow" @@ -19,10 +19,11 @@ import { SessionSummary } from "./summary" import type { Provider } from "@/provider/provider" import { Question } from "@/question" import { errorMessage } from "@/util/error" -import * as Log from "@opencode-ai/core/util/log" +import { Log } from "@opencode-ai/core/util/log" import { isRecord } from "@/util/record" import { EventV2Bridge } from "@/event-v2-bridge" -import { SessionEvent } from "@opencode-ai/core/session-event" +import { Database } from "@opencode-ai/core/database/database" +import { SessionEvent } from "@opencode-ai/core/session/event" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" import * as DateTime from "effect/DateTime" @@ -35,25 +36,25 @@ const log = Log.create({ service: "session.processor" }) export type Result = "compact" | "stop" | "continue" export interface Handle { - readonly message: MessageV2.Assistant + readonly message: SessionLegacy.Assistant readonly updateToolCall: ( toolCallID: string, - update: (part: MessageV2.ToolPart) => MessageV2.ToolPart, - ) => Effect.Effect + update: (part: SessionLegacy.ToolPart) => SessionLegacy.ToolPart, + ) => Effect.Effect readonly completeToolCall: ( toolCallID: string, output: { title: string metadata: Record output: string - attachments?: MessageV2.FilePart[] + attachments?: SessionLegacy.FilePart[] }, ) => Effect.Effect readonly process: (streamInput: LLM.StreamInput) => Effect.Effect } type Input = { - assistantMessage: MessageV2.Assistant + assistantMessage: SessionLegacy.Assistant sessionID: SessionID model: Provider.Model } @@ -63,9 +64,9 @@ export interface Interface { } type ToolCall = { - partID: MessageV2.ToolPart["id"] - messageID: MessageV2.ToolPart["messageID"] - sessionID: MessageV2.ToolPart["sessionID"] + partID: SessionLegacy.ToolPart["id"] + messageID: SessionLegacy.ToolPart["messageID"] + sessionID: SessionLegacy.ToolPart["sessionID"] done: Deferred.Deferred inputEnded: boolean } @@ -76,8 +77,8 @@ interface ProcessorContext extends Input { snapshot: string | undefined blocked: boolean needsCompaction: boolean - currentText: MessageV2.TextPart | undefined - reasoningMap: Record + currentText: SessionLegacy.TextPart | undefined + reasoningMap: Record } type StreamEvent = LLMEvent @@ -89,7 +90,6 @@ export const layer = Layer.effect( Effect.gen(function* () { const session = yield* Session.Service const config = yield* Config.Service - const bus = yield* Bus.Service const snapshot = yield* Snapshot.Service const agents = yield* Agent.Service const llm = yield* LLM.Service @@ -101,6 +101,7 @@ export const layer = Layer.effect( const image = yield* Image.Service const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service + const database = yield* Database.Service const create = Effect.fn("SessionProcessor.create")(function* (input: Input) { // Pre-capture snapshot before the LLM stream starts. The AI SDK @@ -151,7 +152,7 @@ export const layer = Layer.effect( const updateToolCall = Effect.fn("SessionProcessor.updateToolCall")(function* ( toolCallID: string, - update: (part: MessageV2.ToolPart) => MessageV2.ToolPart, + update: (part: SessionLegacy.ToolPart) => SessionLegacy.ToolPart, ) { const match = yield* readToolCall(toolCallID) if (!match) return undefined @@ -171,7 +172,7 @@ export const layer = Layer.effect( title: string metadata: Record output: string - attachments?: MessageV2.FilePart[] + attachments?: SessionLegacy.FilePart[] }, ) { const match = yield* readToolCall(toolCallID) @@ -266,7 +267,7 @@ export const layer = Layer.effect( callID: input.id, state: { status: "pending", input: {}, raw: "" }, metadata: input.providerExecuted ? { providerExecuted: true } : undefined, - } satisfies MessageV2.ToolPart) + } satisfies SessionLegacy.ToolPart) ctx.toolcalls[input.id] = { done: yield* Deferred.make(), partID: part.id, @@ -277,11 +278,11 @@ export const layer = Layer.effect( return { call: ctx.toolcalls[input.id], part } }) - const isFilePart = (value: unknown): value is MessageV2.FilePart => Schema.is(MessageV2.FilePart)(value) + const isFilePart = (value: unknown): value is SessionLegacy.FilePart => Schema.is(SessionLegacy.FilePart)(value) const toolResultOutput = ( value: Extract, - ): { title: string; metadata: Record; output: string; attachments?: MessageV2.FilePart[] } => { + ): { title: string; metadata: Record; output: string; attachments?: SessionLegacy.FilePart[] } => { if (isRecord(value.result.value) && typeof value.result.value.output === "string") { return { title: typeof value.result.value.title === "string" ? value.result.value.title : value.name, @@ -300,8 +301,6 @@ export const layer = Layer.effect( } } - const toolInput = (value: unknown): Record => (isRecord(value) ? value : { value }) - const handleEvent = Effect.fnUntraced(function* (value: StreamEvent) { switch (value.type) { case "reasoning-start": @@ -379,7 +378,7 @@ export const layer = Layer.effect( throw new Error(`Tool call not allowed while generating summary: ${value.name}`) } const toolCall = yield* ensureToolCall(value) - const input = toolInput(value.input) + const input = isRecord(value.input) ? value.input : { value: value.input } if (!toolCall.call.inputEnded) { // TODO(v2): Temporary dual-write while migrating session messages to v2 events. if (flags.experimentalEventSystem) { @@ -421,7 +420,9 @@ export const layer = Layer.effect( : value.providerMetadata, })) - const parts = MessageV2.parts(ctx.assistantMessage.id) + const parts = yield* MessageV2.parts(ctx.assistantMessage.id).pipe( + Effect.provideService(Database.Service, database), + ) const recentParts = parts.slice(-DOOM_LOOP_THRESHOLD) if ( @@ -461,7 +462,7 @@ export const layer = Layer.effect( ), Effect.exit, ) - : Effect.succeed(Exit.succeed(attachment)), + : Effect.succeed(Exit.succeed(attachment)), ) const omitted = normalized.filter(Exit.isFailure).length const attachments = normalized.filter(Exit.isSuccess).map((item) => item.value) @@ -484,7 +485,7 @@ export const layer = Layer.effect( type: "text", text: output.output, }, - ...(output.attachments?.map((item: MessageV2.FilePart) => ({ + ...(output.attachments?.map((item: SessionLegacy.FilePart) => ({ type: "file" as const, uri: item.url, mime: item.mime, @@ -751,9 +752,9 @@ export const layer = Layer.effect( const halt = Effect.fn("SessionProcessor.halt")(function* (e: unknown) { slog.error("process", { error: errorMessage(e), stack: e instanceof Error ? e.stack : undefined }) const error = parse(e) - if (MessageV2.ContextOverflowError.isInstance(error)) { + if (SessionLegacy.ContextOverflowError.isInstance(error)) { ctx.needsCompaction = true - yield* bus.publish(Session.Event.Error, { sessionID: ctx.sessionID, error }) + yield* events.publish(Session.Event.Error, { sessionID: ctx.sessionID, error }) return } if (!ctx.assistantMessage.summary) { @@ -770,7 +771,7 @@ export const layer = Layer.effect( } } ctx.assistantMessage.error = error - yield* bus.publish(Session.Event.Error, { + yield* events.publish(Session.Event.Error, { sessionID: ctx.assistantMessage.sessionID, error: ctx.assistantMessage.error, }) @@ -873,9 +874,9 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(SessionSummary.defaultLayer), Layer.provide(SessionStatus.defaultLayer), Layer.provide(Image.defaultLayer), - Layer.provide(Bus.layer), Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), + Layer.provide(Database.defaultLayer), Layer.provide(EventV2Bridge.defaultLayer), ), ) diff --git a/packages/opencode/src/session/projectors-next.ts b/packages/opencode/src/session/projectors-next.ts deleted file mode 100644 index ae5b9c5d2fb9..000000000000 --- a/packages/opencode/src/session/projectors-next.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { and, desc, eq } from "@/storage/db" -import type { Database } from "@/storage/db" -import { SessionMessage } from "@opencode-ai/core/session-message" -import { SessionMessageUpdater } from "@opencode-ai/core/session-message-updater" -import { SessionEvent } from "@opencode-ai/core/session-event" -import * as DateTime from "effect/DateTime" -import { SyncEvent } from "@/sync" -import { EventV2Bridge } from "@/event-v2-bridge" -import { SessionMessageTable, SessionTable } from "./session.sql" -import type { SessionID } from "./schema" -import { Schema } from "effect" - -const decodeMessage = Schema.decodeUnknownSync(SessionMessage.Message) -type SessionMessageData = NonNullable<(typeof SessionMessageTable.$inferInsert)["data"]> - -function encodeDateTimes(value: unknown): unknown { - if (DateTime.isDateTime(value)) return DateTime.toEpochMillis(value) - if (Array.isArray(value)) return value.map(encodeDateTimes) - if (typeof value === "object" && value !== null) { - return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encodeDateTimes(item)])) - } - return value -} - -function encodeMessageData(value: unknown): SessionMessageData { - return encodeDateTimes(value) as SessionMessageData -} - -function sqlite(db: Database.TxOrDb, sessionID: SessionID): SessionMessageUpdater.Adapter { - return { - getCurrentAssistant() { - return db - .select() - .from(SessionMessageTable) - .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "assistant"))) - .orderBy(desc(SessionMessageTable.id)) - .all() - .map((row) => decodeMessage({ ...row.data, id: row.id, type: row.type })) - .find((message): message is SessionMessage.Assistant => message.type === "assistant" && !message.time.completed) - }, - getCurrentCompaction() { - return db - .select() - .from(SessionMessageTable) - .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "compaction"))) - .orderBy(desc(SessionMessageTable.id)) - .all() - .map((row) => decodeMessage({ ...row.data, id: row.id, type: row.type })) - .find((message): message is SessionMessage.Compaction => message.type === "compaction") - }, - getCurrentShell(callID) { - return db - .select() - .from(SessionMessageTable) - .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "shell"))) - .orderBy(desc(SessionMessageTable.id)) - .all() - .map((row) => decodeMessage({ ...row.data, id: row.id, type: row.type })) - .find((message): message is SessionMessage.Shell => message.type === "shell" && message.callID === callID) - }, - updateAssistant(assistant) { - const { id, type, ...data } = assistant - db.update(SessionMessageTable) - .set({ data: encodeMessageData(data) }) - .where( - and( - eq(SessionMessageTable.id, id), - eq(SessionMessageTable.session_id, sessionID), - eq(SessionMessageTable.type, type), - ), - ) - .run() - }, - updateCompaction(compaction) { - const { id, type, ...data } = compaction - db.update(SessionMessageTable) - .set({ data: encodeMessageData(data) }) - .where( - and( - eq(SessionMessageTable.id, id), - eq(SessionMessageTable.session_id, sessionID), - eq(SessionMessageTable.type, type), - ), - ) - .run() - }, - updateShell(shell) { - const { id, type, ...data } = shell - db.update(SessionMessageTable) - .set({ data: encodeMessageData(data) }) - .where( - and( - eq(SessionMessageTable.id, id), - eq(SessionMessageTable.session_id, sessionID), - eq(SessionMessageTable.type, type), - ), - ) - .run() - }, - appendMessage(message) { - const { id, type, ...data } = message - db.insert(SessionMessageTable) - .values([ - { - id, - session_id: sessionID, - type, - time_created: DateTime.toEpochMillis(message.time.created), - data: encodeMessageData(data), - }, - ]) - .run() - }, - finish() {}, - } -} - -function update(db: Database.TxOrDb, event: SessionEvent.Event) { - SessionMessageUpdater.update(sqlite(db, event.data.sessionID), event) -} - -export default [ - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.AgentSwitched), (db, data, event) => { - db.update(SessionTable) - .set({ - agent: data.agent, - time_updated: DateTime.toEpochMillis(data.timestamp), - }) - .where(eq(SessionTable.id, data.sessionID)) - .run() - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.agent.switched", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.ModelSwitched), (db, data, event) => { - db.update(SessionTable) - .set({ - model: data.model, - time_updated: DateTime.toEpochMillis(data.timestamp), - }) - .where(eq(SessionTable.id, data.sessionID)) - .run() - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.model.switched", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Prompted), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.prompted", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Synthetic), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.synthetic", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Shell.Started), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.shell.started", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Shell.Ended), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.shell.ended", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Step.Started), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.step.started", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Step.Ended), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.step.ended", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Step.Failed), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.step.failed", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Text.Started), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.text.started", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Text.Delta), () => {}), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Text.Ended), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.text.ended", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Input.Started), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.input.started", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Input.Delta), () => {}), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Input.Ended), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.input.ended", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Called), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.called", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Success), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.success", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Tool.Failed), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.tool.failed", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Reasoning.Started), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.reasoning.started", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Reasoning.Delta), () => {}), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Reasoning.Ended), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.reasoning.ended", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Retried), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.retried", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Compaction.Started), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.compaction.started", data }) - }), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Compaction.Delta), () => {}), - SyncEvent.project(EventV2Bridge.toSyncDefinition(SessionEvent.Compaction.Ended), (db, data, event) => { - update(db, { id: SessionMessage.ID.make(event.id), type: "session.next.compaction.ended", data }) - }), -] diff --git a/packages/opencode/src/session/projectors.ts b/packages/opencode/src/session/projectors.ts deleted file mode 100644 index 3dd848c5bc05..000000000000 --- a/packages/opencode/src/session/projectors.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { NotFoundError } from "@/storage/storage" -import { eq } from "drizzle-orm" -import { and } from "drizzle-orm" -import { sql } from "drizzle-orm" -import type { TxOrDb } from "@/storage/db" -import { SyncEvent } from "@/sync" -import * as Session from "./session" -import { MessageV2 } from "./message-v2" -import { SessionTable, MessageTable, PartTable } from "./session.sql" -import { WorkspaceTable } from "@/control-plane/workspace.sql" -import { Log } from "@opencode-ai/core/util/log" -import nextProjectors from "./projectors-next" - -const log = Log.create({ service: "session.projector" }) - -function foreign(err: unknown) { - if (typeof err !== "object" || err === null) return false - if ("code" in err && err.code === "SQLITE_CONSTRAINT_FOREIGNKEY") return true - return "message" in err && typeof err.message === "string" && err.message.includes("FOREIGN KEY constraint failed") -} - -export type DeepPartial = T extends object ? { [K in keyof T]?: DeepPartial | null } : T - -type Usage = Pick - -function usage(part: MessageV2.Part | (typeof PartTable.$inferSelect)["data"]): Usage | undefined { - if (part.type !== "step-finish") return undefined - if (!("cost" in part) || !("tokens" in part)) return undefined - return { cost: part.cost, tokens: part.tokens } -} - -function applyUsage(db: TxOrDb, sessionID: Session.Info["id"], value: Usage, sign = 1) { - db.update(SessionTable) - .set({ - cost: sql`${SessionTable.cost} + ${value.cost * sign}`, - tokens_input: sql`${SessionTable.tokens_input} + ${value.tokens.input * sign}`, - tokens_output: sql`${SessionTable.tokens_output} + ${value.tokens.output * sign}`, - tokens_reasoning: sql`${SessionTable.tokens_reasoning} + ${value.tokens.reasoning * sign}`, - tokens_cache_read: sql`${SessionTable.tokens_cache_read} + ${value.tokens.cache.read * sign}`, - tokens_cache_write: sql`${SessionTable.tokens_cache_write} + ${value.tokens.cache.write * sign}`, - time_updated: sql`${SessionTable.time_updated}`, - }) - .where(eq(SessionTable.id, sessionID)) - .run() -} - -function grab( - obj: T, - field1: K1, - cb?: (val: NonNullable) => X, -): X | undefined { - if (obj == undefined || !(field1 in obj)) return undefined - - const val = obj[field1] - if (val && typeof val === "object" && cb) { - return cb(val) - } - if (val === undefined) { - throw new Error( - "Session update failure: pass `null` to clear a field instead of `undefined`: " + JSON.stringify(obj), - ) - } - return val as X | undefined -} - -export function toPartialRow(info: DeepPartial) { - const obj = { - id: grab(info, "id"), - project_id: grab(info, "projectID"), - workspace_id: grab(info, "workspaceID"), - parent_id: grab(info, "parentID"), - slug: grab(info, "slug"), - directory: grab(info, "directory"), - path: grab(info, "path"), - title: grab(info, "title"), - version: grab(info, "version"), - share_url: grab(info, "share", (v) => grab(v, "url")), - summary_additions: grab(info, "summary", (v) => grab(v, "additions")), - summary_deletions: grab(info, "summary", (v) => grab(v, "deletions")), - summary_files: grab(info, "summary", (v) => grab(v, "files")), - summary_diffs: grab(info, "summary", (v) => grab(v, "diffs")), - cost: grab(info, "cost"), - tokens_input: grab(info, "tokens", (v) => grab(v, "input")), - tokens_output: grab(info, "tokens", (v) => grab(v, "output")), - tokens_reasoning: grab(info, "tokens", (v) => grab(v, "reasoning")), - tokens_cache_read: grab(info, "tokens", (v) => grab(v, "cache", (cache) => grab(cache, "read"))), - tokens_cache_write: grab(info, "tokens", (v) => grab(v, "cache", (cache) => grab(cache, "write"))), - revert: grab(info, "revert"), - permission: grab(info, "permission"), - time_created: grab(info, "time", (v) => grab(v, "created")), - time_updated: grab(info, "time", (v) => grab(v, "updated")), - time_compacting: grab(info, "time", (v) => grab(v, "compacting")), - time_archived: grab(info, "time", (v) => grab(v, "archived")), - } - - return Object.fromEntries(Object.entries(obj).filter(([_, val]) => val !== undefined)) -} - -export default [ - SyncEvent.project(Session.Event.Created, (db, data) => { - db.insert(SessionTable) - .values(Session.toRow(data.info as Session.Info)) - .run() - - if (data.info.workspaceID) { - db.update(WorkspaceTable).set({ time_used: Date.now() }).where(eq(WorkspaceTable.id, data.info.workspaceID)).run() - } - }), - - SyncEvent.project(Session.Event.Updated, (db, data) => { - const info = data.info - const row = db - .update(SessionTable) - .set({ time_updated: sql`${SessionTable.time_updated}`, ...toPartialRow(info as Session.Patch) }) - .where(eq(SessionTable.id, data.sessionID)) - .returning() - .get() - if (!row) throw new NotFoundError({ message: `Session not found: ${data.sessionID}` }) - }), - - SyncEvent.project(Session.Event.Deleted, (db, data) => { - db.delete(SessionTable).where(eq(SessionTable.id, data.sessionID)).run() - }), - - SyncEvent.project(MessageV2.Event.Updated, (db, data) => { - const time_created = data.info.time.created - const { id, sessionID, ...rest } = data.info - - try { - db.insert(MessageTable) - .values({ - id, - session_id: sessionID, - time_created, - data: rest, - }) - .onConflictDoUpdate({ target: MessageTable.id, set: { data: rest } }) - .run() - } catch (err) { - if (!foreign(err)) throw err - log.warn("ignored late message update", { messageID: id, sessionID }) - } - }), - - SyncEvent.project(MessageV2.Event.Removed, (db, data) => { - for (const row of db - .select() - .from(PartTable) - .where(and(eq(PartTable.message_id, data.messageID), eq(PartTable.session_id, data.sessionID))) - .all()) { - const previous = usage(row.data) - if (previous) applyUsage(db, data.sessionID, previous, -1) - } - db.delete(MessageTable) - .where(and(eq(MessageTable.id, data.messageID), eq(MessageTable.session_id, data.sessionID))) - .run() - }), - - SyncEvent.project(MessageV2.Event.PartRemoved, (db, data) => { - const row = db - .select() - .from(PartTable) - .where(and(eq(PartTable.id, data.partID), eq(PartTable.session_id, data.sessionID))) - .get() - const previous = row && usage(row.data) - if (previous) applyUsage(db, data.sessionID, previous, -1) - - db.delete(PartTable) - .where(and(eq(PartTable.id, data.partID), eq(PartTable.session_id, data.sessionID))) - .run() - }), - - SyncEvent.project(MessageV2.Event.PartUpdated, (db, data) => { - const { id, messageID, sessionID, ...rest } = data.part - const row = db.select().from(PartTable).where(eq(PartTable.id, id)).get() - - try { - db.insert(PartTable) - .values({ - id, - message_id: messageID, - session_id: sessionID, - time_created: data.time, - data: rest, - }) - .onConflictDoUpdate({ target: PartTable.id, set: { data: rest } }) - .run() - const previous = row && usage(row.data) - const next = usage(data.part) - if (previous) applyUsage(db, row.session_id, previous, -1) - if (next) applyUsage(db, sessionID, next) - } catch (err) { - if (!foreign(err)) throw err - log.warn("ignored late part update", { partID: id, messageID, sessionID }) - } - }), - - ...nextProjectors, -] diff --git a/packages/opencode/src/session/prompt.ts b/packages/opencode/src/session/prompt.ts index 4a2090e6ea57..3655819dd651 100644 --- a/packages/opencode/src/session/prompt.ts +++ b/packages/opencode/src/session/prompt.ts @@ -1,17 +1,17 @@ import path from "path" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import os from "os" import { SessionID, MessageID, PartID } from "./schema" import { MessageV2 } from "./message-v2" -import * as Log from "@opencode-ai/core/util/log" +import { Log } from "@opencode-ai/core/util/log" import { SessionRevert } from "./revert" -import * as Session from "./session" +import { Session } from "./session" import { Agent } from "../agent/agent" import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "../provider/schema" + import { type Tool as AITool, tool, jsonSchema } from "ai" import type { JSONSchema7 } from "@ai-sdk/provider" import { SessionCompaction } from "./compaction" -import { Bus } from "../bus" import { SystemPrompt } from "./system" import { Instruction } from "./instruction" import { Plugin } from "../plugin" @@ -49,15 +49,15 @@ import { TaskTool, type TaskPromptOps } from "@/tool/task" import { SessionRunState } from "./run-state" import { RuntimeFlags } from "@/effect/runtime-flags" import { EventV2Bridge } from "@/event-v2-bridge" -import { SessionEvent } from "@opencode-ai/core/session-event" +import { Database } from "@opencode-ai/core/database/database" +import { SessionEvent } from "@opencode-ai/core/session/event" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" -import { AgentAttachment, FileAttachment, ReferenceAttachment, Source } from "@opencode-ai/core/session-prompt" +import { AgentAttachment, FileAttachment, ReferenceAttachment, Source } from "@opencode-ai/core/session/prompt" import { Reference } from "@/reference/reference" import * as DateTime from "effect/DateTime" -import { eq } from "@/storage/db" -import * as Database from "@/storage/db" -import { SessionTable } from "./session.sql" +import { eq } from "drizzle-orm" +import { SessionTable } from "@opencode-ai/core/session/sql" import { referencePromptMetadata, referenceTextPart } from "./prompt/reference" import { SessionReminders } from "./reminders" import { SessionTools } from "./tools" @@ -66,8 +66,8 @@ import { LLMEvent } from "@opencode-ai/llm" // @ts-ignore globalThis.AI_SDK_LOG_WARNINGS = false -const decodeMessageInfo = Schema.decodeUnknownExit(MessageV2.Info) -const decodeMessagePart = Schema.decodeUnknownExit(MessageV2.Part) +const decodeMessageInfo = Schema.decodeUnknownExit(SessionLegacy.Info) +const decodeMessagePart = Schema.decodeUnknownExit(SessionLegacy.Part) const STRUCTURED_OUTPUT_DESCRIPTION = `Use this tool to return your final response in the requested structured format. @@ -82,7 +82,7 @@ const STRUCTURED_OUTPUT_SYSTEM_PROMPT = `IMPORTANT: The user has requested struc const log = Log.create({ service: "session.prompt" }) const elog = EffectLogger.create({ service: "session.prompt" }) -function isOrphanedInterruptedTool(part: MessageV2.ToolPart) { +function isOrphanedInterruptedTool(part: SessionLegacy.ToolPart) { // cleanup() marks abandoned tool_use blocks this way after retries/aborts. // They are not pending work and must not trigger an assistant-prefill request. return part.state.status === "error" && part.state.metadata?.interrupted === true @@ -90,10 +90,10 @@ function isOrphanedInterruptedTool(part: MessageV2.ToolPart) { export interface Interface { readonly cancel: (sessionID: SessionID) => Effect.Effect - readonly prompt: (input: PromptInput) => Effect.Effect - readonly loop: (input: LoopInput) => Effect.Effect - readonly shell: (input: ShellInput) => Effect.Effect - readonly command: (input: CommandInput) => Effect.Effect + readonly prompt: (input: PromptInput) => Effect.Effect + readonly loop: (input: LoopInput) => Effect.Effect + readonly shell: (input: ShellInput) => Effect.Effect + readonly command: (input: CommandInput) => Effect.Effect readonly resolvePromptParts: (template: string) => Effect.Effect } @@ -102,7 +102,6 @@ export class Service extends Context.Service()("@opencode/Se export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service const status = yield* SessionStatus.Service const sessions = yield* Session.Service const agents = yield* Agent.Service @@ -130,12 +129,13 @@ export const layer = Layer.effect( const references = yield* Reference.Service const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service + const database = yield* Database.Service + const { db } = database const ops = Effect.fn("SessionPrompt.ops")(function* () { return { cancel: (sessionID: SessionID) => cancel(sessionID), resolvePromptParts: (template: string) => resolvePromptParts(template), prompt: (input: PromptInput) => prompt(input).pipe(Effect.catch(Effect.die)), - loop: (input: LoopInput) => loop(input), } satisfies TaskPromptOps }) @@ -149,10 +149,6 @@ export const layer = Layer.effect( const parts: Types.DeepMutable = [{ type: "text", text: template }] const files = ConfigMarkdown.files(template) const seen = new Set() - const mentionSource = (match: RegExpMatchArray) => { - const start = match.index ?? 0 - return { value: match[0], start, end: start + match[0].length } - } yield* Effect.forEach( files, Effect.fnUntraced(function* (match) { @@ -165,7 +161,8 @@ export const layer = Layer.effect( const alias = slash === -1 ? name : name.slice(0, slash) const reference = yield* references.get(alias) if (reference) { - const source = mentionSource(match) + const start = match.index ?? 0 + const source = { value: match[0], start, end: start + match[0].length } if (reference.kind === "invalid") { parts.push( referenceTextPart({ reference, source, target: slash === -1 ? undefined : name.slice(slash + 1) }), @@ -242,14 +239,14 @@ export const layer = Layer.effect( const title = Effect.fn("SessionPrompt.ensureTitle")(function* (input: { session: Session.Info - history: MessageV2.WithParts[] - providerID: ProviderID - modelID: ModelID + history: SessionLegacy.WithParts[] + providerID: ProviderV2.ID + modelID: ProviderV2.ModelID }) { if (input.session.parentID) return if (!Session.isDefaultTitle(input.session.title)) return - const real = (m: MessageV2.WithParts) => + const real = (m: SessionLegacy.WithParts) => m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic) const idx = input.history.findIndex(real) if (idx === -1) return @@ -260,7 +257,7 @@ export const layer = Layer.effect( if (!firstUser || firstUser.info.role !== "user") return const firstInfo = firstUser.info - const subtasks = firstUser.parts.filter((p): p is MessageV2.SubtaskPart => p.type === "subtask") + const subtasks = firstUser.parts.filter((p): p is SessionLegacy.SubtaskPart => p.type === "subtask") const onlySubtasks = subtasks.length > 0 && firstUser.parts.every((p) => p.type === "subtask") const ag = yield* agents.get("title") @@ -303,19 +300,19 @@ export const layer = Layer.effect( }) const handleSubtask = Effect.fn("SessionPrompt.handleSubtask")(function* (input: { - task: MessageV2.SubtaskPart + task: SessionLegacy.SubtaskPart model: Provider.Model - lastUser: MessageV2.User + lastUser: SessionLegacy.User sessionID: SessionID session: Session.Info - msgs: MessageV2.WithParts[] + msgs: SessionLegacy.WithParts[] }) { const { task, model, lastUser, sessionID, session, msgs } = input const ctx = yield* InstanceState.context const promptOps = yield* ops() const { task: taskTool } = yield* registry.named() const taskModel = task.model ? yield* getModel(task.model.providerID, task.model.modelID, sessionID) : model - const assistantMessage: MessageV2.Assistant = yield* sessions.updateMessage({ + const assistantMessage: SessionLegacy.Assistant = yield* sessions.updateMessage({ id: MessageID.ascending(), role: "assistant", parentID: lastUser.id, @@ -330,7 +327,7 @@ export const layer = Layer.effect( providerID: taskModel.providerID, time: { created: Date.now() }, }) - let part: MessageV2.ToolPart = yield* sessions.updatePart({ + let part: SessionLegacy.ToolPart = yield* sessions.updatePart({ id: PartID.ascending(), messageID: assistantMessage.id, sessionID: assistantMessage.sessionID, @@ -365,7 +362,7 @@ export const layer = Layer.effect( const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name) const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" const error = new NamedError.Unknown({ message: `Agent not found: "${task.agent}".${hint}` }) - yield* bus.publish(Session.Event.Error, { sessionID, error: error.toObject() }) + yield* events.publish(Session.Event.Error, { sessionID, error: error.toObject() }) throw error } @@ -386,7 +383,7 @@ export const layer = Layer.effect( ...part, type: "tool", state: { ...part.state, ...val }, - } satisfies MessageV2.ToolPart) + } satisfies SessionLegacy.ToolPart) }), ask: (req: any) => permission @@ -420,7 +417,7 @@ export const layer = Layer.effect( metadata: part.state.metadata, input: part.state.input, }, - } satisfies MessageV2.ToolPart) + } satisfies SessionLegacy.ToolPart) } }), ), @@ -455,7 +452,7 @@ export const layer = Layer.effect( attachments, time: { ...part.state.time, end: Date.now() }, }, - } satisfies MessageV2.ToolPart) + } satisfies SessionLegacy.ToolPart) } if (!result) { @@ -471,12 +468,12 @@ export const layer = Layer.effect( metadata: part.state.status === "pending" ? undefined : part.state.metadata, input: part.state.input, }, - } satisfies MessageV2.ToolPart) + } satisfies SessionLegacy.ToolPart) } if (!task.command) return - const summaryUserMsg: MessageV2.User = { + const summaryUserMsg: SessionLegacy.User = { id: MessageID.ascending(), sessionID, role: "user", @@ -492,7 +489,7 @@ export const layer = Layer.effect( type: "text", text: "Summarize the task tool output above and continue with your task.", synthetic: true, - } satisfies MessageV2.TextPart) + } satisfies SessionLegacy.TextPart) }) const shellImpl = Effect.fn("SessionPrompt.shellImpl")(function* (input: ShellInput, ready?: Latch.Latch) { @@ -510,11 +507,11 @@ export const layer = Layer.effect( const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name) const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" const error = new NamedError.Unknown({ message: `Agent not found: "${input.agent}".${hint}` }) - yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) + yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) throw error } const model = input.model ?? agent.model ?? (yield* currentModel(input.sessionID)) - const userMsg: MessageV2.User = { + const userMsg: SessionLegacy.User = { id: input.messageID ?? MessageID.ascending(), sessionID: input.sessionID, time: { created: Date.now() }, @@ -523,7 +520,7 @@ export const layer = Layer.effect( model: { providerID: model.providerID, modelID: model.modelID }, } yield* sessions.updateMessage(userMsg) - const userPart: MessageV2.Part = { + const userPart: SessionLegacy.Part = { type: "text", id: PartID.ascending(), messageID: userMsg.id, @@ -533,7 +530,7 @@ export const layer = Layer.effect( } yield* sessions.updatePart(userPart) - const msg: MessageV2.Assistant = { + const msg: SessionLegacy.Assistant = { id: MessageID.ascending(), sessionID: input.sessionID, parentID: userMsg.id, @@ -549,7 +546,7 @@ export const layer = Layer.effect( } yield* sessions.updateMessage(msg) const started = Date.now() - const part: MessageV2.ToolPart = { + const part: SessionLegacy.ToolPart = { type: "tool", id: PartID.ascending(), messageID: msg.id, @@ -762,8 +759,8 @@ export const layer = Layer.effect( }) const getModel = Effect.fn("SessionPrompt.getModel")(function* ( - providerID: ProviderID, - modelID: ModelID, + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, sessionID: SessionID, ) { const exit = yield* provider.getModel(providerID, modelID).pipe(Effect.exit) @@ -771,7 +768,7 @@ export const layer = Layer.effect( const err = Cause.squash(exit.cause) if (Provider.ModelNotFoundError.isInstance(err)) { const hint = err.suggestions?.length ? ` Did you mean: ${err.suggestions.join(", ")}?` : "" - yield* bus.publish(Session.Event.Error, { + yield* events.publish(Session.Event.Error, { sessionID, error: new NamedError.Unknown({ message: `Model not found: ${err.providerID}/${err.modelID}.${hint}`, @@ -782,13 +779,16 @@ export const layer = Layer.effect( }) const currentModel = Effect.fnUntraced(function* (sessionID: SessionID) { - const current = Database.use((db) => - db.select({ model: SessionTable.model }).from(SessionTable).where(eq(SessionTable.id, sessionID)).get(), - ) + const current = yield* db + .select({ model: SessionTable.model }) + .from(SessionTable) + .where(eq(SessionTable.id, sessionID)) + .get() + .pipe(Effect.orDie) if (current?.model) { return { - providerID: ProviderID.make(current.model.providerID), - modelID: ModelID.make(current.model.id), + providerID: ProviderV2.ID.make(current.model.providerID), + modelID: ProviderV2.ModelID.make(current.model.id), ...(current.model.variant && current.model.variant !== "default" ? { variant: current.model.variant } : {}), } } @@ -806,17 +806,16 @@ export const layer = Layer.effect( const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name) const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` }) - yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) + yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) throw error } - const current = Database.use((db) => - db - .select({ agent: SessionTable.agent, model: SessionTable.model }) - .from(SessionTable) - .where(eq(SessionTable.id, input.sessionID)) - .get(), - ) + const current = yield* db + .select({ agent: SessionTable.agent, model: SessionTable.model }) + .from(SessionTable) + .where(eq(SessionTable.id, input.sessionID)) + .get() + .pipe(Effect.orDie) const model = input.model ?? ag.model ?? (yield* currentModel(input.sessionID)) const same = ag.model && model.providerID === ag.model.providerID && model.modelID === ag.model.modelID const full = @@ -827,7 +826,7 @@ export const layer = Layer.effect( : undefined const variant = input.variant ?? (ag.variant && full?.variants?.[ag.variant] ? ag.variant : undefined) - const info: MessageV2.User = { + const info: SessionLegacy.User = { id: input.messageID ?? MessageID.ascending(), role: "user", sessionID: input.sessionID, @@ -868,8 +867,8 @@ export const layer = Layer.effect( yield* Effect.addFinalizer(() => instruction.clear(info.id)) - type Draft = T extends MessageV2.Part ? Omit & { id?: string } : never - const assign = (part: Draft): MessageV2.Part => ({ + type Draft = T extends SessionLegacy.Part ? Omit & { id?: string } : never + const assign = (part: Draft): SessionLegacy.Part => ({ ...part, id: part.id ? PartID.make(part.id) : PartID.ascending(), }) @@ -898,14 +897,14 @@ export const layer = Layer.effect( }) }) - const resolvePart: (part: PromptInput["parts"][number]) => Effect.Effect[]> = Effect.fn( + const resolvePart: (part: PromptInput["parts"][number]) => Effect.Effect[]> = Effect.fn( "SessionPrompt.resolveUserPart", )(function* (part) { if (part.type === "file") { if (part.source?.type === "resource") { const { clientName, uri } = part.source log.info("mcp resource", { clientName, uri, mime: part.mime }) - const pieces: Draft[] = [ + const pieces: Draft[] = [ { messageID: info.id, sessionID: input.sessionID, @@ -1025,7 +1024,7 @@ export const layer = Layer.effect( if (end) limit = end - (offset - 1) } const args = { filePath: filepath, offset, limit } - const pieces: Draft[] = [ + const pieces: Draft[] = [ ...(referenceContext ? [{ ...referenceContext, messageID: info.id, sessionID: input.sessionID }] : []), @@ -1067,7 +1066,7 @@ export const layer = Layer.effect( const error = Cause.squash(exit.cause) log.error("failed to read file", { error }) const message = error instanceof Error ? error.message : String(error) - yield* bus.publish(Session.Event.Error, { + yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: new NamedError.Unknown({ message }).toObject(), }) @@ -1089,7 +1088,7 @@ export const layer = Layer.effect( const error = Cause.squash(exit.cause) log.error("failed to read directory", { error }) const message = error instanceof Error ? error.message : String(error) - yield* bus.publish(Session.Event.Error, { + yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: new NamedError.Unknown({ message }).toObject(), }) @@ -1321,7 +1320,7 @@ export const layer = Layer.effect( return { info, parts } }, Effect.scoped) - const prompt: (input: PromptInput) => Effect.Effect = Effect.fn( + const prompt: (input: PromptInput) => Effect.Effect = Effect.fn( "SessionPrompt.prompt", )(function* (input: PromptInput) { const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie) @@ -1350,7 +1349,7 @@ export const layer = Layer.effect( throw new Error("Impossible") }) - const runLoop: (sessionID: SessionID) => Effect.Effect = Effect.fn("SessionPrompt.run")( + const runLoop: (sessionID: SessionID) => Effect.Effect = Effect.fn("SessionPrompt.run")( function* (sessionID: SessionID) { const ctx = yield* InstanceState.context const slog = elog.with({ sessionID }) @@ -1362,7 +1361,9 @@ export const layer = Layer.effect( yield* status.set(sessionID, { type: "busy" }) yield* slog.info("loop", { step }) - let msgs = yield* MessageV2.filterCompactedEffect(sessionID) + let msgs = yield* MessageV2.filterCompactedEffect(sessionID).pipe( + Effect.provideService(Database.Service, database), + ) const { user: lastUser, assistant: lastAssistant, finished: lastFinished, tasks } = MessageV2.latest(msgs) @@ -1386,7 +1387,7 @@ export const layer = Layer.effect( lastUser.id < lastAssistant.id ) { const orphan = lastAssistantMsg?.parts.find( - (part): part is MessageV2.ToolPart => part.type === "tool" && isOrphanedInterruptedTool(part), + (part): part is SessionLegacy.ToolPart => part.type === "tool" && isOrphanedInterruptedTool(part), ) if (orphan) { yield* slog.warn("loop exit with orphaned interrupted tool", { @@ -1442,7 +1443,7 @@ export const layer = Layer.effect( const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name) const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" const error = new NamedError.Unknown({ message: `Agent not found: "${lastUser.agent}".${hint}` }) - yield* bus.publish(Session.Event.Error, { sessionID, error: error.toObject() }) + yield* events.publish(Session.Event.Error, { sessionID, error: error.toObject() }) throw error } const maxSteps = agent.steps ?? Infinity @@ -1453,7 +1454,7 @@ export const layer = Layer.effect( Effect.provideService(Session.Service, sessions), ) - const msg: MessageV2.Assistant = { + const msg: SessionLegacy.Assistant = { id: MessageID.ascending(), parentID: lastUser.id, role: "assistant", @@ -1573,7 +1574,7 @@ export const layer = Layer.effect( const finished = handle.message.finish && !["tool-calls", "unknown"].includes(handle.message.finish) if (finished && !handle.message.error) { if (format.type === "json_schema") { - handle.message.error = new MessageV2.StructuredOutputError({ + handle.message.error = new SessionLegacy.StructuredOutputError({ message: "Model did not produce structured output", retries: 0, }).toObject() @@ -1606,13 +1607,13 @@ export const layer = Layer.effect( }, ) - const loop: (input: LoopInput) => Effect.Effect = Effect.fn("SessionPrompt.loop")(function* ( - input: LoopInput, - ) { - return yield* state.ensureRunning(input.sessionID, lastAssistant(input.sessionID), runLoop(input.sessionID)) - }) + const loop: (input: LoopInput) => Effect.Effect = Effect.fn("SessionPrompt.loop")( + function* (input: LoopInput) { + return yield* state.ensureRunning(input.sessionID, lastAssistant(input.sessionID), runLoop(input.sessionID)) + }, + ) - const shell: (input: ShellInput) => Effect.Effect = Effect.fn( + const shell: (input: ShellInput) => Effect.Effect = Effect.fn( "SessionPrompt.shell", )(function* (input: ShellInput) { const ready = yield* Latch.make() @@ -1626,7 +1627,7 @@ export const layer = Layer.effect( const available = (yield* commands.list()).map((c) => c.name) const hint = available.length ? ` Available commands: ${available.join(", ")}` : "" const error = new NamedError.Unknown({ message: `Command not found: "${input.command}".${hint}` }) - yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) + yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) throw error } const agentName = cmd.agent ?? input.agent @@ -1687,7 +1688,7 @@ export const layer = Layer.effect( const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name) const hint = available.length ? ` Available agents: ${available.join(", ")}` : "" const error = new NamedError.Unknown({ message: `Agent not found: "${agentName}".${hint}` }) - yield* bus.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) + yield* events.publish(Session.Event.Error, { sessionID: input.sessionID, error: error.toObject() }) throw error } @@ -1727,7 +1728,7 @@ export const layer = Layer.effect( parts, variant: input.variant, }) - yield* bus.publish(Command.Event.Executed, { + yield* events.publish(Command.Event.Executed, { name: input.command, sessionID: input.sessionID, arguments: input.arguments, @@ -1770,21 +1771,21 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Image.defaultLayer), Layer.provide( Layer.mergeAll( - EventV2Bridge.defaultLayer, Agent.defaultLayer, + Database.defaultLayer, SystemPrompt.defaultLayer, LLM.defaultLayer, Reference.defaultLayer, - Bus.layer, CrossSpawnSpawner.defaultLayer, RuntimeFlags.defaultLayer, + EventV2Bridge.defaultLayer, ), ), ), ) const ModelRef = Schema.Struct({ - providerID: ProviderID, - modelID: ModelID, + providerID: ProviderV2.ID, + modelID: ProviderV2.ModelID, }) export const PromptInput = Schema.Struct({ @@ -1797,15 +1798,15 @@ export const PromptInput = Schema.Struct({ description: "@deprecated tools and permissions have been merged, you can set permissions on the session itself now", }), - format: Schema.optional(MessageV2.Format), + format: Schema.optional(SessionLegacy.Format), system: Schema.optional(Schema.String), variant: Schema.optional(Schema.String), parts: Schema.Array( Schema.Union([ - MessageV2.TextPartInput, - MessageV2.FilePartInput, - MessageV2.AgentPartInput, - MessageV2.SubtaskPartInput, + SessionLegacy.TextPartInput, + SessionLegacy.FilePartInput, + SessionLegacy.AgentPartInput, + SessionLegacy.SubtaskPartInput, ]).annotate({ discriminator: "type" }), ), }) @@ -1844,7 +1845,7 @@ export const CommandInput = Schema.Struct({ mime: Schema.String, filename: Schema.optional(Schema.String), url: Schema.String, - source: Schema.optional(MessageV2.FilePartSource), + source: Schema.optional(SessionLegacy.FilePartSource), }), ]).annotate({ discriminator: "type" }), ), diff --git a/packages/opencode/src/session/prompt/reference.ts b/packages/opencode/src/session/prompt/reference.ts index ae1a46579828..de20b7f45f96 100644 --- a/packages/opencode/src/session/prompt/reference.ts +++ b/packages/opencode/src/session/prompt/reference.ts @@ -1,4 +1,5 @@ import { Option, Schema } from "effect" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { MessageV2 } from "../message-v2" import { Reference } from "@/reference/reference" @@ -33,7 +34,7 @@ export function referenceTextPart(input: { target?: string targetPath?: string problem?: string -}): MessageV2.TextPartInput { +}): SessionLegacy.TextPartInput { const metadata: ReferencePromptMetadata = { name: input.reference.name, kind: input.reference.kind, diff --git a/packages/opencode/src/session/reminders.ts b/packages/opencode/src/session/reminders.ts index a11bd5e67b71..a868a59dd3df 100644 --- a/packages/opencode/src/session/reminders.ts +++ b/packages/opencode/src/session/reminders.ts @@ -1,4 +1,5 @@ import path from "path" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Effect } from "effect" import { Agent } from "@/agent/agent" import { AppFileSystem } from "@opencode-ai/core/filesystem" @@ -6,13 +7,13 @@ import { InstanceState } from "@/effect/instance-state" import { RuntimeFlags } from "@/effect/runtime-flags" import { PartID } from "./schema" import { MessageV2 } from "./message-v2" -import * as Session from "./session" +import { Session } from "./session" import PROMPT_PLAN from "./prompt/plan.txt" import BUILD_SWITCH from "./prompt/build-switch.txt" import PLAN_MODE from "./prompt/plan-mode.txt" export const apply = Effect.fn("SessionReminders.apply")(function* (input: { - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] agent: Agent.Info session: Session.Info }) { diff --git a/packages/opencode/src/session/retry.ts b/packages/opencode/src/session/retry.ts index 463bc27a95db..bcfb54c47551 100644 --- a/packages/opencode/src/session/retry.ts +++ b/packages/opencode/src/session/retry.ts @@ -1,4 +1,5 @@ import type { NamedError } from "@opencode-ai/core/util/error" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Cause, Clock, Duration, Effect, Schedule } from "effect" import { MessageV2 } from "./message-v2" import { iife } from "@/util/iife" @@ -31,7 +32,7 @@ function cap(ms: number) { return Math.min(ms, RETRY_MAX_DELAY) } -export function delay(attempt: number, error?: MessageV2.APIError) { +export function delay(attempt: number, error?: SessionLegacy.APIError) { if (error) { const headers = error.data.responseHeaders if (headers) { @@ -66,8 +67,8 @@ export function delay(attempt: number, error?: MessageV2.APIError) { export function retryable(error: Err, provider: string) { // context overflow errors should not be retried - if (MessageV2.ContextOverflowError.isInstance(error)) return undefined - if (MessageV2.APIError.isInstance(error)) { + if (SessionLegacy.ContextOverflowError.isInstance(error)) return undefined + if (SessionLegacy.APIError.isInstance(error)) { const status = error.data.statusCode // 5xx errors are transient server failures and should always be retried, // even when the provider SDK doesn't explicitly mark them as retryable. @@ -183,7 +184,7 @@ export function policy(opts: { const retry = retryable(error, opts.provider) if (!retry) return Cause.done(meta.attempt) return Effect.gen(function* () { - const wait = delay(meta.attempt, MessageV2.APIError.isInstance(error) ? error : undefined) + const wait = delay(meta.attempt, SessionLegacy.APIError.isInstance(error) ? error : undefined) const now = yield* Clock.currentTimeMillis yield* opts.set({ attempt: meta.attempt, diff --git a/packages/opencode/src/session/revert.ts b/packages/opencode/src/session/revert.ts index 950d533a3d42..19a372558333 100644 --- a/packages/opencode/src/session/revert.ts +++ b/packages/opencode/src/session/revert.ts @@ -1,10 +1,10 @@ import { Effect, Layer, Context, Schema } from "effect" -import { Bus } from "../bus" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { EventV2Bridge } from "@/event-v2-bridge" import { Snapshot } from "../snapshot" import { Storage } from "@/storage/storage" -import { SyncEvent } from "../sync" -import * as Log from "@opencode-ai/core/util/log" -import * as Session from "./session" +import { Log } from "@opencode-ai/core/util/log" +import { Session } from "./session" import { MessageV2 } from "./message-v2" import { SessionID, MessageID, PartID } from "./schema" import { SessionRunState } from "./run-state" @@ -33,15 +33,14 @@ export const layer = Layer.effect( const sessions = yield* Session.Service const snap = yield* Snapshot.Service const storage = yield* Storage.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const summary = yield* SessionSummary.Service const state = yield* SessionRunState.Service - const sync = yield* SyncEvent.Service const revert = Effect.fn("SessionRevert.revert")(function* (input: RevertInput) { yield* state.assertNotBusy(input.sessionID) const all = yield* sessions.messages({ sessionID: input.sessionID }).pipe(Effect.orDie) - let lastUser: MessageV2.User | undefined + let lastUser: SessionLegacy.User | undefined const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie) let rev: Session.Info["revert"] @@ -77,7 +76,7 @@ export const layer = Layer.effect( const range = all.filter((msg) => msg.info.id >= rev.messageID) const diffs = yield* summary.computeDiff({ messages: range }) yield* storage.write(["session_diff", input.sessionID], diffs).pipe(Effect.ignore) - yield* bus.publish(Session.Event.Diff, { sessionID: input.sessionID, diff: diffs }) + yield* events.publish(Session.Event.Diff, { sessionID: input.sessionID, diff: diffs }) yield* sessions.setRevert({ sessionID: input.sessionID, revert: rev, @@ -105,8 +104,8 @@ export const layer = Layer.effect( const sessionID = session.id const msgs = yield* sessions.messages({ sessionID }).pipe(Effect.orDie) const messageID = session.revert.messageID - const remove = [] as MessageV2.WithParts[] - let target: MessageV2.WithParts | undefined + const remove = [] as SessionLegacy.WithParts[] + let target: SessionLegacy.WithParts | undefined for (const msg of msgs) { if (msg.info.id < messageID) continue if (msg.info.id > messageID) { @@ -120,10 +119,7 @@ export const layer = Layer.effect( remove.push(msg) } for (const msg of remove) { - yield* sync.run(MessageV2.Event.Removed, { - sessionID, - messageID: msg.info.id, - }) + yield* sessions.removeMessage({ sessionID, messageID: msg.info.id }) } if (session.revert.partID && target) { const partID = session.revert.partID @@ -132,11 +128,7 @@ export const layer = Layer.effect( const removeParts = target.parts.slice(idx) target.parts = target.parts.slice(0, idx) for (const part of removeParts) { - yield* sync.run(MessageV2.Event.PartRemoved, { - sessionID, - messageID: target.info.id, - partID: part.id, - }) + yield* sessions.removePart({ sessionID, messageID: target.info.id, partID: part.id }) } } } @@ -153,9 +145,8 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Session.defaultLayer), Layer.provide(Snapshot.defaultLayer), Layer.provide(Storage.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(SessionSummary.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), ), ) diff --git a/packages/opencode/src/session/run-state.ts b/packages/opencode/src/session/run-state.ts index 8f0051dfbae7..399a5b604ed9 100644 --- a/packages/opencode/src/session/run-state.ts +++ b/packages/opencode/src/session/run-state.ts @@ -1,8 +1,9 @@ import { InstanceState } from "@/effect/instance-state" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Runner } from "@/effect/runner" import { BackgroundJob } from "@/background/job" import { Effect, Latch, Layer, Scope, Context } from "effect" -import * as Session from "./session" +import { Session } from "./session" import { MessageV2 } from "./message-v2" import { SessionID } from "./schema" import { SessionStatus } from "./status" @@ -12,15 +13,15 @@ export interface Interface { readonly cancel: (sessionID: SessionID) => Effect.Effect readonly ensureRunning: ( sessionID: SessionID, - onInterrupt: Effect.Effect, - work: Effect.Effect, - ) => Effect.Effect + onInterrupt: Effect.Effect, + work: Effect.Effect, + ) => Effect.Effect readonly startShell: ( sessionID: SessionID, - onInterrupt: Effect.Effect, - work: Effect.Effect, + onInterrupt: Effect.Effect, + work: Effect.Effect, ready?: Latch.Latch, - ) => Effect.Effect + ) => Effect.Effect } export class Service extends Context.Service()("@opencode/SessionRunState") {} @@ -34,7 +35,7 @@ export const layer = Layer.effect( const state = yield* InstanceState.make( Effect.fn("SessionRunState.state")(function* () { const scope = yield* Scope.Scope - const runners = new Map>() + const runners = new Map>() yield* Effect.addFinalizer( Effect.fnUntraced(function* () { yield* Effect.forEach(runners.values(), (runner) => runner.cancel, { @@ -50,12 +51,12 @@ export const layer = Layer.effect( const runner = Effect.fn("SessionRunState.runner")(function* ( sessionID: SessionID, - onInterrupt: Effect.Effect, + onInterrupt: Effect.Effect, ) { const data = yield* InstanceState.get(state) const existing = data.runners.get(sessionID) if (existing) return existing - const next = Runner.make(data.scope, { + const next = Runner.make(data.scope, { onIdle: Effect.gen(function* () { data.runners.delete(sessionID) yield* status.set(sessionID, { type: "idle" }) @@ -86,16 +87,16 @@ export const layer = Layer.effect( const ensureRunning = Effect.fn("SessionRunState.ensureRunning")(function* ( sessionID: SessionID, - onInterrupt: Effect.Effect, - work: Effect.Effect, + onInterrupt: Effect.Effect, + work: Effect.Effect, ) { return yield* (yield* runner(sessionID, onInterrupt)).ensureRunning(work) }) const startShell = Effect.fn("SessionRunState.startShell")(function* ( sessionID: SessionID, - onInterrupt: Effect.Effect, - work: Effect.Effect, + onInterrupt: Effect.Effect, + work: Effect.Effect, ready?: Latch.Latch, ) { return yield* (yield* runner(sessionID, onInterrupt)) diff --git a/packages/opencode/src/session/schema.ts b/packages/opencode/src/session/schema.ts index f1622b6958c5..4a49d110c8c2 100644 --- a/packages/opencode/src/session/schema.ts +++ b/packages/opencode/src/session/schema.ts @@ -1,10 +1,10 @@ import { Schema } from "effect" import { Identifier } from "@/id/id" -import { Session as CoreSession } from "@opencode-ai/core/session" +import { SessionV2 } from "@opencode-ai/core/session" import { withStatics } from "@opencode-ai/core/schema" -export const SessionID = CoreSession.ID +export const SessionID = SessionV2.ID export type SessionID = Schema.Schema.Type export const MessageID = Schema.String.check(Schema.isStartsWith("msg")).pipe( diff --git a/packages/opencode/src/session/session.ts b/packages/opencode/src/session/session.ts index f75ac910d40a..a8a867a425c9 100644 --- a/packages/opencode/src/session/session.ts +++ b/packages/opencode/src/session/session.ts @@ -1,14 +1,17 @@ import { Slug } from "@opencode-ai/core/util/slug" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { serviceUse } from "@opencode-ai/core/effect/service-use" import path from "path" import { BackgroundJob } from "@/background/job" -import { BusEvent } from "@/bus/bus-event" -import { Bus } from "@/bus" import { Decimal } from "decimal.js" import type { ProviderMetadata, Usage } from "@opencode-ai/llm" import { InstallationVersion } from "@opencode-ai/core/installation/version" +import { Database } from "@opencode-ai/core/database/database" +import { makeRuntime } from "@opencode-ai/core/effect/runtime" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" +import { SessionV2 } from "@opencode-ai/core/session" -import { Database } from "@/storage/db" import { NotFoundError } from "@/storage/storage" import { eq } from "drizzle-orm" import { and } from "drizzle-orm" @@ -19,37 +22,32 @@ import { like } from "drizzle-orm" import { inArray } from "drizzle-orm" import { lt } from "drizzle-orm" import { or } from "drizzle-orm" -import { SyncEvent } from "../sync" import type { SQL } from "drizzle-orm" -import { PartTable, SessionTable } from "./session.sql" -import { ProjectTable } from "../project/project.sql" -import { Storage } from "@/storage/storage" -import * as Log from "@opencode-ai/core/util/log" +import { PartTable, SessionTable } from "@opencode-ai/core/session/sql" +import { ProjectTable } from "@opencode-ai/core/project/sql" +import { Log } from "@opencode-ai/core/util/log" import { MessageV2 } from "./message-v2" import type { InstanceContext } from "../project/instance-context" import { InstanceState } from "@/effect/instance-state" import { Snapshot } from "@/snapshot" -import { ProjectID } from "../project/schema" -import { WorkspaceID } from "../control-plane/schema" +import { ProjectV2 } from "@opencode-ai/core/project" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { SessionID, MessageID, PartID } from "./schema" -import { ModelID, ProviderID } from "@/provider/schema" import type { Provider } from "@/provider/provider" import { Permission } from "@/permission" import { Global } from "@opencode-ai/core/global" import { Effect, Layer, Option, Context, Schema, Types } from "effect" -import { NonNegativeInt, optionalOmitUndefined } from "@opencode-ai/core/schema" +import { AbsolutePath, NonNegativeInt, optionalOmitUndefined } from "@opencode-ai/core/schema" import { RuntimeFlags } from "@/effect/runtime-flags" +import { ProviderV2 } from "@opencode-ai/core/provider" const log = Log.create({ service: "session" }) +const runtime = makeRuntime(Database.Service, Database.defaultLayer) const parentTitlePrefix = "New session - " const childTitlePrefix = "Child session - " -function createDefaultTitle(isChild = false) { - return (isChild ? childTitlePrefix : parentTitlePrefix) + new Date().toISOString() -} - export function isDefaultTitle(title: string) { return new RegExp( `^(${parentTitlePrefix}|${childTitlePrefix})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$`, @@ -82,8 +80,8 @@ export function fromRow(row: SessionRow): Info { agent: row.agent ?? undefined, model: row.model ? { - id: ModelID.make(row.model.id), - providerID: ProviderID.make(row.model.providerID), + id: ProviderV2.ModelID.make(row.model.id), + providerID: ProviderV2.ID.make(row.model.providerID), variant: row.model.variant, } : undefined, @@ -100,6 +98,7 @@ export function fromRow(row: SessionRow): Info { }, }, share, + metadata: row.metadata ?? undefined, revert, permission: row.permission ? [...row.permission] : undefined, time: { @@ -111,6 +110,13 @@ export function fromRow(row: SessionRow): Info { } } +function eventLocation(info: Pick) { + return { + directory: AbsolutePath.make(info.directory), + workspaceID: info.workspaceID, + } +} + export function toRow(info: Info) { return { id: info.id, @@ -129,6 +135,7 @@ export function toRow(info: Info) { summary_deletions: info.summary?.deletions, summary_files: info.summary?.files, summary_diffs: info.summary?.diffs, + metadata: info.metadata, cost: info.cost ?? 0, tokens_input: (info.tokens ?? EmptyTokens).input, tokens_output: (info.tokens ?? EmptyTokens).output, @@ -200,16 +207,18 @@ const Revert = Schema.Struct({ }) const Model = Schema.Struct({ - id: ModelID, - providerID: ProviderID, + id: ProviderV2.ModelID, + providerID: ProviderV2.ID, variant: optionalOmitUndefined(Schema.String), }) +export const Metadata = Schema.Record(Schema.String, Schema.Any) + export const Info = Schema.Struct({ id: SessionID, slug: Schema.String, - projectID: ProjectID, - workspaceID: optionalOmitUndefined(WorkspaceID), + projectID: ProjectV2.ID, + workspaceID: optionalOmitUndefined(WorkspaceV2.ID), directory: Schema.String, path: optionalOmitUndefined(Schema.String), parentID: optionalOmitUndefined(SessionID), @@ -221,6 +230,7 @@ export const Info = Schema.Struct({ agent: optionalOmitUndefined(Schema.String), model: optionalOmitUndefined(Model), version: Schema.String, + metadata: optionalOmitUndefined(Metadata), time: Time, permission: optionalOmitUndefined(Permission.Ruleset), revert: optionalOmitUndefined(Revert), @@ -228,7 +238,7 @@ export const Info = Schema.Struct({ export type Info = Types.DeepMutable> export const ProjectInfo = Schema.Struct({ - id: ProjectID, + id: ProjectV2.ID, name: optionalOmitUndefined(Schema.String), worktree: Schema.String, }).annotate({ identifier: "ProjectSummary" }) @@ -246,8 +256,9 @@ export const CreateInput = Schema.optional( title: Schema.optional(Schema.String), agent: Schema.optional(Schema.String), model: Schema.optional(Model), + metadata: Schema.optional(Metadata), permission: Schema.optional(Permission.Ruleset), - workspaceID: Schema.optional(WorkspaceID), + workspaceID: Schema.optional(WorkspaceV2.ID), }), ) export type CreateInput = Types.DeepMutable> @@ -264,6 +275,10 @@ export const SetArchivedInput = Schema.Struct({ sessionID: SessionID, time: Schema.optional(ArchivedTimestamp), }) +export const SetMetadataInput = Schema.Struct({ + sessionID: SessionID, + metadata: Metadata, +}) export const SetPermissionInput = Schema.Struct({ sessionID: SessionID, permission: Permission.Ruleset, @@ -281,13 +296,23 @@ export type ListInput = { directory?: string scope?: "project" path?: string - workspaceID?: WorkspaceID + workspaceID?: WorkspaceV2.ID roots?: boolean start?: number search?: string limit?: number } +export type GlobalListInput = { + directory?: string + roots?: boolean + start?: number + cursor?: number + search?: string + limit?: number + archived?: boolean +} + const CreatedEventSchema = Schema.Struct({ sessionID: SessionID, info: Info, @@ -307,8 +332,8 @@ const UpdatedTime = Schema.Struct({ const UpdatedInfo = Schema.Struct({ id: Schema.optional(Schema.NullOr(SessionID)), slug: Schema.optional(Schema.NullOr(Schema.String)), - projectID: Schema.optional(Schema.NullOr(ProjectID)), - workspaceID: Schema.optional(Schema.NullOr(WorkspaceID)), + projectID: Schema.optional(Schema.NullOr(ProjectV2.ID)), + workspaceID: Schema.optional(Schema.NullOr(WorkspaceV2.ID)), directory: Schema.optional(Schema.NullOr(Schema.String)), path: Schema.optional(Schema.NullOr(Schema.String)), parentID: Schema.optional(Schema.NullOr(SessionID)), @@ -320,6 +345,7 @@ const UpdatedInfo = Schema.Struct({ agent: Schema.optional(Schema.NullOr(Schema.String)), model: Schema.optional(Schema.NullOr(Model)), version: Schema.optional(Schema.NullOr(Schema.String)), + metadata: Schema.optional(Schema.NullOr(Metadata)), time: Schema.optional(UpdatedTime), permission: Schema.optional(Schema.NullOr(Permission.Ruleset)), revert: Schema.optional(Schema.NullOr(Revert)), @@ -331,41 +357,25 @@ const UpdatedEventSchema = Schema.Struct({ }) export const Event = { - Created: SyncEvent.define({ - type: "session.created", - version: 1, - aggregate: "sessionID", - schema: CreatedEventSchema, - }), - Updated: SyncEvent.define({ - type: "session.updated", - version: 1, - aggregate: "sessionID", - schema: UpdatedEventSchema, - busSchema: CreatedEventSchema, - }), - Deleted: SyncEvent.define({ - type: "session.deleted", - version: 1, - aggregate: "sessionID", - schema: CreatedEventSchema, - }), - Diff: BusEvent.define( - "session.diff", - Schema.Struct({ + Created: SessionLegacy.Event.Created, + Updated: SessionLegacy.Event.Updated, + Deleted: SessionLegacy.Event.Deleted, + Diff: EventV2.define({ + type: "session.diff", + schema: { sessionID: SessionID, diff: Schema.Array(Snapshot.FileDiff), - }), - ), - Error: BusEvent.define( - "session.error", - Schema.Struct({ + }, + }), + Error: EventV2.define({ + type: "session.error", + schema: { sessionID: Schema.optional(SessionID), - // Reuses MessageV2.Assistant.fields.error (already Schema.optional) so - // the derived zod keeps the same discriminated-union shape on the bus. - error: MessageV2.Assistant.fields.error, - }), - ), + // Reuses SessionLegacy.Assistant.fields.error (already Schema.optional) so + // the derived schema keeps the same discriminated-union shape on the event stream. + error: SessionLegacy.Assistant.fields.error, + }, + }), } export function plan(input: { slug: string; time: { created: number } }, instance: InstanceContext) { @@ -450,19 +460,22 @@ export type NotFound = NotFoundError export interface Interface { readonly list: (input?: ListInput) => Effect.Effect + readonly listGlobal: (input?: GlobalListInput) => Effect.Effect readonly create: (input?: { parentID?: SessionID title?: string agent?: string model?: Schema.Schema.Type + metadata?: typeof Metadata.Type permission?: Permission.Ruleset - workspaceID?: WorkspaceID + workspaceID?: WorkspaceV2.ID }) => Effect.Effect readonly fork: (input: { sessionID: SessionID; messageID?: MessageID }) => Effect.Effect readonly touch: (sessionID: SessionID) => Effect.Effect readonly get: (id: SessionID) => Effect.Effect readonly setTitle: (input: { sessionID: SessionID; title: string }) => Effect.Effect readonly setArchived: (input: { sessionID: SessionID; time?: number }) => Effect.Effect + readonly setMetadata: (input: typeof SetMetadataInput.Type) => Effect.Effect readonly setPermission: (input: { sessionID: SessionID; permission: Permission.Ruleset }) => Effect.Effect readonly setRevert: (input: { sessionID: SessionID @@ -471,19 +484,24 @@ export interface Interface { }) => Effect.Effect readonly clearRevert: (sessionID: SessionID) => Effect.Effect readonly setSummary: (input: { sessionID: SessionID; summary: Info["summary"] }) => Effect.Effect + readonly setShare: (input: { sessionID: SessionID; share: Info["share"] }) => Effect.Effect + readonly setWorkspace: (input: { sessionID: SessionID; workspaceID: Info["workspaceID"] }) => Effect.Effect readonly diff: (sessionID: SessionID) => Effect.Effect - readonly messages: (input: { sessionID: SessionID; limit?: number }) => Effect.Effect + readonly messages: (input: { + sessionID: SessionID + limit?: number + }) => Effect.Effect readonly children: (parentID: SessionID) => Effect.Effect readonly remove: (sessionID: SessionID) => Effect.Effect - readonly updateMessage: (msg: T) => Effect.Effect + readonly updateMessage: (msg: T) => Effect.Effect readonly removeMessage: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect readonly removePart: (input: { sessionID: SessionID; messageID: MessageID; partID: PartID }) => Effect.Effect readonly getPart: (input: { sessionID: SessionID messageID: MessageID partID: PartID - }) => Effect.Effect - readonly updatePart: (part: T) => Effect.Effect + }) => Effect.Effect + readonly updatePart: (part: T) => Effect.Effect readonly updatePartDelta: (input: { sessionID: SessionID messageID: MessageID @@ -494,41 +512,59 @@ export interface Interface { /** Finds the first message matching the predicate, searching newest-first. */ readonly findMessage: ( sessionID: SessionID, - predicate: (msg: MessageV2.WithParts) => boolean, - ) => Effect.Effect, NotFound> + predicate: (msg: SessionLegacy.WithParts) => boolean, + ) => Effect.Effect, NotFound> } export class Service extends Context.Service()("@opencode/Session") {} export const use = serviceUse(Service) -export type Patch = Types.DeepMutable["data"]["info"]> - -const db = (fn: (d: Parameters[0] extends (trx: infer D) => any ? D : never) => T) => - Effect.sync(() => Database.use(fn)) +export type Patch = Omit, "time" | "share" | "summary" | "revert" | "permission"> & { + time?: Partial + share?: Partial> | null + summary?: Info["summary"] | null + revert?: Info["revert"] | null + permission?: Info["permission"] | null +} export const layer: Layer.Layer< Service, never, - BackgroundJob.Service | Bus.Service | Storage.Service | SyncEvent.Service | RuntimeFlags.Service + BackgroundJob.Service | RuntimeFlags.Service | Database.Service | EventV2Bridge.Service > = Layer.effect( Service, Effect.gen(function* () { + const { db } = yield* Database.Service + const database = yield* Database.Service const background = yield* BackgroundJob.Service - const bus = yield* Bus.Service - const storage = yield* Storage.Service - const sync = yield* SyncEvent.Service + const events = yield* EventV2Bridge.Service const flags = yield* RuntimeFlags.Service + const locationForSession = Effect.fnUntraced(function* (sessionID: SessionID) { + const row = yield* db + .select({ directory: SessionTable.directory, workspaceID: SessionTable.workspace_id }) + .from(SessionTable) + .where(eq(SessionTable.id, sessionID)) + .get() + .pipe(Effect.orDie) + if (!row) return + return { + directory: AbsolutePath.make(row.directory), + workspaceID: row.workspaceID ?? undefined, + } + }) + const createNext = Effect.fn("Session.createNext")(function* (input: { id?: SessionID title?: string agent?: string model?: Schema.Schema.Type parentID?: SessionID - workspaceID?: WorkspaceID + workspaceID?: WorkspaceV2.ID directory: string path?: string + metadata?: typeof Metadata.Type permission?: Permission.Ruleset }) { const ctx = yield* InstanceState.context @@ -541,9 +577,10 @@ export const layer: Layer.Layer< path: input.path, workspaceID: input.workspaceID, parentID: input.parentID, - title: input.title ?? createDefaultTitle(!!input.parentID), + title: input.title ?? (input.parentID ? childTitlePrefix : parentTitlePrefix) + new Date().toISOString(), agent: input.agent, model: input.model, + metadata: input.metadata, permission: input.permission ? [...input.permission] : undefined, cost: 0, tokens: EmptyTokens, @@ -554,41 +591,78 @@ export const layer: Layer.Layer< } log.info("created", result) - yield* sync.run(Event.Created, { sessionID: result.id, info: result }) - - if (!flags.experimentalWorkspaces) { - // This only exist for backwards compatibility. We should not be - // manually publishing this event; it is a sync event now - yield* bus.publish(Event.Updated, { - sessionID: result.id, - info: result, - }) - } + yield* events.publish( + SessionLegacy.Event.Created, + { sessionID: result.id, info: result }, + { location: eventLocation(result) }, + ) return result }) const get = Effect.fn("Session.get")(function* (id: SessionID) { - const row = yield* db((d) => d.select().from(SessionTable).where(eq(SessionTable.id, id)).get()) + const row = yield* db.select().from(SessionTable).where(eq(SessionTable.id, id)).get().pipe(Effect.orDie) if (!row) return yield* Effect.fail(new NotFoundError({ message: `Session not found: ${id}` })) return fromRow(row) }) const list = Effect.fn("Session.list")(function* (input?: ListInput) { const ctx = yield* InstanceState.context - return Array.from( - listByProject({ projectID: ctx.project.id, experimentalWorkspaces: flags.experimentalWorkspaces, ...input }), - ) + return yield* listByProject(db, { + projectID: ctx.project.id, + experimentalWorkspaces: flags.experimentalWorkspaces, + ...input, + }) + }) + + const listGlobal = Effect.fn("Session.listGlobal")(function* (input?: GlobalListInput) { + const conditions: SQL[] = [] + if (input?.directory) conditions.push(eq(SessionTable.directory, input.directory)) + if (input?.roots) conditions.push(isNull(SessionTable.parent_id)) + if (input?.start) conditions.push(gte(SessionTable.time_updated, input.start)) + if (input?.cursor) conditions.push(lt(SessionTable.time_updated, input.cursor)) + if (input?.search) conditions.push(like(SessionTable.title, `%${input.search}%`)) + if (!input?.archived) conditions.push(isNull(SessionTable.time_archived)) + + const query = + conditions.length > 0 + ? db + .select() + .from(SessionTable) + .where(and(...conditions)) + : db.select().from(SessionTable) + const rows = yield* query + .orderBy(desc(SessionTable.time_updated), desc(SessionTable.id)) + .limit(input?.limit ?? 100) + .all() + .pipe(Effect.orDie) + const ids = [...new Set(rows.map((row) => row.project_id))] + const projects = new Map() + if (ids.length > 0) { + const items = yield* db + .select({ id: ProjectTable.id, name: ProjectTable.name, worktree: ProjectTable.worktree }) + .from(ProjectTable) + .where(inArray(ProjectTable.id, ids)) + .all() + .pipe(Effect.orDie) + for (const item of items) { + projects.set(item.id, { + id: item.id, + name: item.name ?? undefined, + worktree: item.worktree, + }) + } + } + return rows.map((row) => ({ ...fromRow(row), project: projects.get(row.project_id) ?? null })) }) const children = Effect.fn("Session.children")(function* (parentID: SessionID) { - const rows = yield* db((d) => - d - .select() - .from(SessionTable) - .where(and(eq(SessionTable.parent_id, parentID))) - .all(), - ) + const rows = yield* db + .select() + .from(SessionTable) + .where(and(eq(SessionTable.parent_id, parentID))) + .all() + .pipe(Effect.orDie) return rows.map(fromRow) }) @@ -608,50 +682,59 @@ export const layer: Layer.Layer< yield* remove(child.id) } - yield* sync.run(Event.Deleted, { sessionID, info: session }, { publish: hasInstance }) - yield* sync.remove(sessionID) + yield* events.publish( + SessionLegacy.Event.Deleted, + { sessionID, info: session }, + { location: eventLocation(session) }, + ) + yield* events.remove(sessionID) } catch (e) { log.error(e) } }) - const updateMessage = (msg: T): Effect.Effect => + const updateMessage = (msg: T): Effect.Effect => Effect.gen(function* () { - yield* sync.run(MessageV2.Event.Updated, { sessionID: msg.sessionID, info: msg }) + const location = yield* locationForSession(msg.sessionID) + yield* events.publish(SessionLegacy.Event.MessageUpdated, { sessionID: msg.sessionID, info: msg }, { location }) return msg }).pipe(Effect.withSpan("Session.updateMessage")) - const updatePart = (part: T): Effect.Effect => + const updatePart = (part: T): Effect.Effect => Effect.gen(function* () { - yield* sync.run(MessageV2.Event.PartUpdated, { - sessionID: part.sessionID, - part: structuredClone(part), - time: Date.now(), - }) + const location = yield* locationForSession(part.sessionID) + yield* events.publish( + SessionLegacy.Event.PartUpdated, + { + sessionID: part.sessionID, + part: structuredClone(part), + time: Date.now(), + }, + { location }, + ) return part }).pipe(Effect.withSpan("Session.updatePart")) const getPart: Interface["getPart"] = Effect.fn("Session.getPart")(function* (input) { - const row = Database.use((db) => - db - .select() - .from(PartTable) - .where( - and( - eq(PartTable.session_id, input.sessionID), - eq(PartTable.message_id, input.messageID), - eq(PartTable.id, input.partID), - ), - ) - .get(), - ) + const row = yield* db + .select() + .from(PartTable) + .where( + and( + eq(PartTable.session_id, input.sessionID), + eq(PartTable.message_id, input.messageID), + eq(PartTable.id, input.partID), + ), + ) + .get() + .pipe(Effect.orDie) if (!row) return return { ...row.data, id: row.id, sessionID: row.session_id, messageID: row.message_id, - } as MessageV2.Part + } as SessionLegacy.Part }) const create = Effect.fn("Session.create")(function* (input?: { @@ -659,8 +742,9 @@ export const layer: Layer.Layer< title?: string agent?: string model?: Schema.Schema.Type + metadata?: typeof Metadata.Type permission?: Permission.Ruleset - workspaceID?: WorkspaceID + workspaceID?: WorkspaceV2.ID }) { const ctx = yield* InstanceState.context const workspace = yield* InstanceState.workspaceID @@ -671,6 +755,7 @@ export const layer: Layer.Layer< title: input?.title, agent: input?.agent, model: input?.model, + metadata: input?.metadata, permission: input?.permission, workspaceID: input?.workspaceID ?? workspace, }) @@ -685,6 +770,7 @@ export const layer: Layer.Layer< path: sessionPath(ctx.worktree, ctx.directory), workspaceID: original.workspaceID, title, + metadata: structuredClone(original.metadata), }) const msgs = yield* messages({ sessionID: input.sessionID }) const idMap = new Map() @@ -703,7 +789,7 @@ export const layer: Layer.Layer< }) for (const part of msg.parts) { - const p: MessageV2.Part = { + const p: SessionLegacy.Part = { ...part, id: PartID.ascending(), messageID: cloned.id, @@ -718,25 +804,44 @@ export const layer: Layer.Layer< return session }) - const patch = (sessionID: SessionID, info: Patch) => sync.run(Event.Updated, { sessionID, info }) + const patch = (sessionID: SessionID, info: Patch) => + Effect.gen(function* () { + const current = yield* get(sessionID) + const next = { + ...current, + ...info, + time: info.time ? { ...current.time, ...info.time } : current.time, + share: info.share === null ? undefined : info.share ? { ...current.share, ...info.share } : current.share, + summary: info.summary === null ? undefined : (info.summary ?? current.summary), + revert: info.revert === null ? undefined : (info.revert ?? current.revert), + permission: info.permission === null ? undefined : (info.permission ?? current.permission), + } as Info + yield* events.publish(SessionLegacy.Event.Updated, { sessionID, info: next }, { location: eventLocation(next) }) + }) const touch = Effect.fn("Session.touch")(function* (sessionID: SessionID) { - yield* patch(sessionID, { time: { updated: Date.now() } }) + yield* patch(sessionID, { time: { updated: Date.now() } }).pipe(Effect.orDie) }) const setTitle = Effect.fn("Session.setTitle")(function* (input: { sessionID: SessionID; title: string }) { - yield* patch(input.sessionID, { title: input.title }) + yield* patch(input.sessionID, { title: input.title }).pipe(Effect.orDie) }) const setArchived = Effect.fn("Session.setArchived")(function* (input: { sessionID: SessionID; time?: number }) { - yield* patch(input.sessionID, { time: { archived: input.time } }) + yield* patch(input.sessionID, { time: { archived: input.time } }).pipe(Effect.orDie) + }) + + const setMetadata = Effect.fn("Session.setMetadata")(function* (input: typeof SetMetadataInput.Type) { + yield* patch(input.sessionID, { metadata: input.metadata, time: { updated: Date.now() } }).pipe(Effect.orDie) }) const setPermission = Effect.fn("Session.setPermission")(function* (input: { sessionID: SessionID permission: Permission.Ruleset }) { - yield* patch(input.sessionID, { permission: [...input.permission], time: { updated: Date.now() } }) + yield* patch(input.sessionID, { permission: [...input.permission], time: { updated: Date.now() } }).pipe( + Effect.orDie, + ) }) const setRevert = Effect.fn("Session.setRevert")(function* (input: { @@ -744,36 +849,56 @@ export const layer: Layer.Layer< revert: Info["revert"] summary: Info["summary"] }) { - yield* patch(input.sessionID, { summary: input.summary, time: { updated: Date.now() }, revert: input.revert }) + yield* patch(input.sessionID, { + summary: input.summary, + time: { updated: Date.now() }, + revert: input.revert, + }).pipe(Effect.orDie) }) const clearRevert = Effect.fn("Session.clearRevert")(function* (sessionID: SessionID) { - yield* patch(sessionID, { time: { updated: Date.now() }, revert: null }) + yield* patch(sessionID, { time: { updated: Date.now() }, revert: null }).pipe(Effect.orDie) }) const setSummary = Effect.fn("Session.setSummary")(function* (input: { sessionID: SessionID summary: Info["summary"] }) { - yield* patch(input.sessionID, { time: { updated: Date.now() }, summary: input.summary }) + yield* patch(input.sessionID, { time: { updated: Date.now() }, summary: input.summary }).pipe(Effect.orDie) + }) + + const setShare = Effect.fn("Session.setShare")(function* (input: { sessionID: SessionID; share: Info["share"] }) { + yield* patch(input.sessionID, { share: input.share ?? null, time: { updated: Date.now() } }).pipe(Effect.orDie) + }) + + const setWorkspace = Effect.fn("Session.setWorkspace")(function* (input: { + sessionID: SessionID + workspaceID: Info["workspaceID"] + }) { + yield* patch(input.sessionID, { workspaceID: input.workspaceID, time: { updated: Date.now() } }).pipe( + Effect.orDie, + ) }) const diff = Effect.fn("Session.diff")(function* (sessionID: SessionID) { - return yield* storage - .read(["session_diff", sessionID]) - .pipe(Effect.orElseSucceed((): Snapshot.FileDiff[] => [])) + void sessionID + return [] as Snapshot.FileDiff[] }) const messages: Interface["messages"] = Effect.fn("Session.messages")(function* (input) { if (input.limit) { - return (yield* MessageV2.page({ sessionID: input.sessionID, limit: input.limit })).items + return (yield* MessageV2.page({ sessionID: input.sessionID, limit: input.limit }).pipe( + Effect.provideService(Database.Service, database), + )).items } const size = 50 - const result = [] as MessageV2.WithParts[] + const result = [] as SessionLegacy.WithParts[] let before: string | undefined while (true) { - const page = yield* MessageV2.page({ sessionID: input.sessionID, limit: size, before }) + const page = yield* MessageV2.page({ sessionID: input.sessionID, limit: size, before }).pipe( + Effect.provideService(Database.Service, database), + ) if (page.items.length === 0) break for (let i = page.items.length - 1; i >= 0; i--) { const item = page.items[i] @@ -789,10 +914,15 @@ export const layer: Layer.Layer< sessionID: SessionID messageID: MessageID }) { - yield* sync.run(MessageV2.Event.Removed, { - sessionID: input.sessionID, - messageID: input.messageID, - }) + const location = yield* locationForSession(input.sessionID) + yield* events.publish( + SessionLegacy.Event.MessageRemoved, + { + sessionID: input.sessionID, + messageID: input.messageID, + }, + { location }, + ) return input.messageID }) @@ -801,11 +931,16 @@ export const layer: Layer.Layer< messageID: MessageID partID: PartID }) { - yield* sync.run(MessageV2.Event.PartRemoved, { - sessionID: input.sessionID, - messageID: input.messageID, - partID: input.partID, - }) + const location = yield* locationForSession(input.sessionID) + yield* events.publish( + SessionLegacy.Event.PartRemoved, + { + sessionID: input.sessionID, + messageID: input.messageID, + partID: input.partID, + }, + { location }, + ) return input.partID }) @@ -816,7 +951,7 @@ export const layer: Layer.Layer< field: string delta: string }) { - yield* bus.publish(MessageV2.Event.PartDelta, input) + yield* events.publish(MessageV2.Event.PartDelta, input) }) /** Finds the first message matching the predicate, searching newest-first. */ @@ -824,7 +959,9 @@ export const layer: Layer.Layer< const size = 50 let before: string | undefined while (true) { - const page = yield* MessageV2.page({ sessionID, limit: size, before }) + const page = yield* MessageV2.page({ sessionID, limit: size, before }).pipe( + Effect.provideService(Database.Service, database), + ) if (page.items.length === 0) break for (let i = page.items.length - 1; i >= 0; i--) { const item = page.items[i] @@ -833,21 +970,25 @@ export const layer: Layer.Layer< if (!page.more || !page.cursor) break before = page.cursor } - return Option.none() + return Option.none() }) return Service.of({ list, + listGlobal, create, fork, touch, get, setTitle, setArchived, + setMetadata, setPermission, setRevert, clearRevert, setSummary, + setShare, + setWorkspace, diff, messages, children, @@ -865,9 +1006,9 @@ export const layer: Layer.Layer< export const defaultLayer = layer.pipe( Layer.provide(BackgroundJob.defaultLayer), - Layer.provide(Bus.layer), - Layer.provide(Storage.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(SessionV2.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), ) @@ -888,9 +1029,10 @@ const cancelBackgroundJobs = Effect.fn("Session.cancelBackgroundJobs")(function* ) }) -function* listByProject( +function listByProject( + db: Database.Interface["db"], input: ListInput & { - projectID: ProjectID + projectID: ProjectV2.ID experimentalWorkspaces: boolean }, ) { @@ -926,18 +1068,17 @@ function* listByProject( const limit = input.limit ?? 100 - const rows = Database.use((db) => - db - .select() - .from(SessionTable) - .where(and(...conditions)) - .orderBy(desc(SessionTable.time_updated)) - .limit(limit) - .all(), - ) - for (const row of rows) { - yield fromRow(row) - } + return db + .select() + .from(SessionTable) + .where(and(...conditions)) + .orderBy(desc(SessionTable.time_updated)) + .limit(limit) + .all() + .pipe( + Effect.orDie, + Effect.map((rows) => rows.map(fromRow)), + ) } export function* listGlobal(input?: { @@ -972,7 +1113,7 @@ export function* listGlobal(input?: { const limit = input?.limit ?? 100 - const rows = Database.use((db) => { + const rows = runtime.runSync(({ db }) => { const query = conditions.length > 0 ? db @@ -980,19 +1121,20 @@ export function* listGlobal(input?: { .from(SessionTable) .where(and(...conditions)) : db.select().from(SessionTable) - return query.orderBy(desc(SessionTable.time_updated), desc(SessionTable.id)).limit(limit).all() + return query.orderBy(desc(SessionTable.time_updated), desc(SessionTable.id)).limit(limit).all().pipe(Effect.orDie) }) const ids = [...new Set(rows.map((row) => row.project_id))] const projects = new Map() if (ids.length > 0) { - const items = Database.use((db) => + const items = runtime.runSync(({ db }) => db .select({ id: ProjectTable.id, name: ProjectTable.name, worktree: ProjectTable.worktree }) .from(ProjectTable) .where(inArray(ProjectTable.id, ids)) - .all(), + .all() + .pipe(Effect.orDie), ) for (const item of items) { projects.set(item.id, { diff --git a/packages/opencode/src/session/status.ts b/packages/opencode/src/session/status.ts index 089559e2cd7b..a7a6c5f87ef8 100644 --- a/packages/opencode/src/session/status.ts +++ b/packages/opencode/src/session/status.ts @@ -1,9 +1,9 @@ -import { BusEvent } from "@/bus/bus-event" -import { Bus } from "@/bus" import { InstanceState } from "@/effect/instance-state" import { SessionID } from "./schema" import { NonNegativeInt } from "@opencode-ai/core/schema" import { Effect, Layer, Context, Schema } from "effect" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" export const Info = Schema.Union([ Schema.Struct({ @@ -32,20 +32,20 @@ export const Info = Schema.Union([ export type Info = Schema.Schema.Type export const Event = { - Status: BusEvent.define( - "session.status", - Schema.Struct({ + Status: EventV2.define({ + type: "session.status", + schema: { sessionID: SessionID, status: Info, - }), - ), + }, + }), // deprecated - Idle: BusEvent.define( - "session.idle", - Schema.Struct({ + Idle: EventV2.define({ + type: "session.idle", + schema: { sessionID: SessionID, - }), - ), + }, + }), } export interface Interface { @@ -59,7 +59,7 @@ export class Service extends Context.Service()("@opencode/Se export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const state = yield* InstanceState.make( Effect.fn("SessionStatus.state")(() => Effect.succeed(new Map())), @@ -76,9 +76,9 @@ export const layer = Layer.effect( const set = Effect.fn("SessionStatus.set")(function* (sessionID: SessionID, status: Info) { const data = yield* InstanceState.get(state) - yield* bus.publish(Event.Status, { sessionID, status }) + yield* events.publish(Event.Status, { sessionID, status }) if (status.type === "idle") { - yield* bus.publish(Event.Idle, { sessionID }) + yield* events.publish(Event.Idle, { sessionID }) data.delete(sessionID) return } @@ -89,6 +89,6 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(Bus.layer)) +export const defaultLayer = layer.pipe(Layer.provide(EventV2Bridge.defaultLayer)) export * as SessionStatus from "./status" diff --git a/packages/opencode/src/session/summary.ts b/packages/opencode/src/session/summary.ts index aa4b8719bc9e..89652d9a3912 100644 --- a/packages/opencode/src/session/summary.ts +++ b/packages/opencode/src/session/summary.ts @@ -1,10 +1,10 @@ import { Effect, Layer, Context, Schema } from "effect" -import { Bus } from "@/bus" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { EventV2Bridge } from "@/event-v2-bridge" import { Snapshot } from "@/snapshot" -import { Storage } from "@/storage/storage" -import * as Session from "./session" -import { MessageV2 } from "./message-v2" +import { Session } from "./session" import { SessionID, MessageID } from "./schema" +import { Config } from "@/config/config" function unquoteGitPath(input: string) { if (!input.startsWith('"')) return input @@ -65,7 +65,7 @@ function unquoteGitPath(input: string) { export interface Interface { readonly summarize: (input: { sessionID: SessionID; messageID: MessageID }) => Effect.Effect readonly diff: (input: { sessionID: SessionID; messageID?: MessageID }) => Effect.Effect - readonly computeDiff: (input: { messages: MessageV2.WithParts[] }) => Effect.Effect + readonly computeDiff: (input: { messages: SessionLegacy.WithParts[] }) => Effect.Effect } export class Service extends Context.Service()("@opencode/SessionSummary") {} @@ -75,10 +75,12 @@ export const layer = Layer.effect( Effect.gen(function* () { const sessions = yield* Session.Service const snapshot = yield* Snapshot.Service - const storage = yield* Storage.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service + const config = yield* Config.Service - const computeDiff = Effect.fn("SessionSummary.computeDiff")(function* (input: { messages: MessageV2.WithParts[] }) { + const computeDiff = Effect.fn("SessionSummary.computeDiff")(function* (input: { + messages: SessionLegacy.WithParts[] + }) { let from: string | undefined let to: string | undefined for (const item of input.messages) { @@ -102,20 +104,18 @@ export const layer = Layer.effect( sessionID: SessionID messageID: MessageID }) { - const all = yield* sessions.messages({ sessionID: input.sessionID }).pipe(Effect.orDie) - if (!all.length) return - - const diffs = yield* computeDiff({ messages: all }) yield* sessions.setSummary({ sessionID: input.sessionID, summary: { - additions: diffs.reduce((sum, x) => sum + x.additions, 0), - deletions: diffs.reduce((sum, x) => sum + x.deletions, 0), - files: diffs.length, + additions: 0, + deletions: 0, + files: 0, }, }) - yield* storage.write(["session_diff", input.sessionID], diffs).pipe(Effect.ignore) - yield* bus.publish(Session.Event.Diff, { sessionID: input.sessionID, diff: diffs }) + yield* events.publish(Session.Event.Diff, { sessionID: input.sessionID, diff: [] }) + if ((yield* config.get()).snapshot === false) return + const all = yield* sessions.messages({ sessionID: input.sessionID }).pipe(Effect.orDie) + if (!all.length) return const messages = all.filter( (m) => m.info.id === input.messageID || (m.info.role === "assistant" && m.info.parentID === input.messageID), @@ -128,18 +128,18 @@ export const layer = Layer.effect( }) const diff = Effect.fn("SessionSummary.diff")(function* (input: { sessionID: SessionID; messageID?: MessageID }) { - const diffs = yield* storage - .read(["session_diff", input.sessionID]) - .pipe(Effect.catch(() => Effect.succeed([] as Snapshot.FileDiff[]))) - const next = diffs.map((item) => { + if (!input.messageID) return [] + const message = (yield* sessions.messages({ sessionID: input.sessionID }).pipe(Effect.orDie)).find( + (item) => item.info.id === input.messageID, + ) + if (!message || message.info.role !== "user") return [] + const diffs = message.info.summary?.diffs ?? [] + return diffs.map((item) => { if (item.file === undefined) return item const file = unquoteGitPath(item.file) if (file === item.file) return item return { ...item, file } }) - const changed = next.some((item, i) => item.file !== diffs[i]?.file) - if (changed) yield* storage.write(["session_diff", input.sessionID], next).pipe(Effect.ignore) - return next }) return Service.of({ summarize, diff, computeDiff }) @@ -150,8 +150,8 @@ export const defaultLayer = Layer.suspend(() => layer.pipe( Layer.provide(Session.defaultLayer), Layer.provide(Snapshot.defaultLayer), - Layer.provide(Storage.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(Config.defaultLayer), ), ) diff --git a/packages/opencode/src/session/todo.ts b/packages/opencode/src/session/todo.ts index 005b3b7c4e64..37598f9d560b 100644 --- a/packages/opencode/src/session/todo.ts +++ b/packages/opencode/src/session/todo.ts @@ -1,11 +1,11 @@ -import { BusEvent } from "@/bus/bus-event" -import { Bus } from "@/bus" import { SessionID } from "./schema" import { Effect, Layer, Context, Schema } from "effect" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { eq } from "drizzle-orm" import { asc } from "drizzle-orm" -import { TodoTable } from "./session.sql" +import { TodoTable } from "@opencode-ai/core/session/sql" +import { EventV2Bridge } from "@/event-v2-bridge" +import { EventV2 } from "@opencode-ai/core/event" export const Info = Schema.Struct({ content: Schema.String.annotate({ description: "Brief description of the task" }), @@ -17,13 +17,13 @@ export const Info = Schema.Struct({ export type Info = Schema.Schema.Type export const Event = { - Updated: BusEvent.define( - "todo.updated", - Schema.Struct({ + Updated: EventV2.define({ + type: "todo.updated", + schema: { sessionID: SessionID, todos: Schema.Array(Info), - }), - ), + }, + }), } export interface Interface { @@ -36,35 +36,41 @@ export class Service extends Context.Service()("@opencode/Se export const layer = Layer.effect( Service, Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service + const { db } = yield* Database.Service const update = Effect.fn("Todo.update")(function* (input: { sessionID: SessionID; todos: Info[] }) { - yield* Effect.sync(() => - Database.transaction((db) => { - db.delete(TodoTable).where(eq(TodoTable.session_id, input.sessionID)).run() - if (input.todos.length === 0) return - db.insert(TodoTable) - .values( - input.todos.map((todo, position) => ({ - session_id: input.sessionID, - content: todo.content, - status: todo.status, - priority: todo.priority, - position, - })), - ) - .run() - }), - ) - yield* bus.publish(Event.Updated, input) + yield* db + .transaction((tx) => + Effect.gen(function* () { + yield* tx.delete(TodoTable).where(eq(TodoTable.session_id, input.sessionID)).run() + if (input.todos.length === 0) return + yield* tx + .insert(TodoTable) + .values( + input.todos.map((todo, position) => ({ + session_id: input.sessionID, + content: todo.content, + status: todo.status, + priority: todo.priority, + position, + })), + ) + .run() + }), + ) + .pipe(Effect.orDie) + yield* events.publish(Event.Updated, input) }) const get = Effect.fn("Todo.get")(function* (sessionID: SessionID) { - const rows = yield* Effect.sync(() => - Database.use((db) => - db.select().from(TodoTable).where(eq(TodoTable.session_id, sessionID)).orderBy(asc(TodoTable.position)).all(), - ), - ) + const rows = yield* db + .select() + .from(TodoTable) + .where(eq(TodoTable.session_id, sessionID)) + .orderBy(asc(TodoTable.position)) + .all() + .pipe(Effect.orDie) return rows.map((row) => ({ content: row.content, status: row.status, @@ -76,6 +82,6 @@ export const layer = Layer.effect( }), ) -export const defaultLayer = layer.pipe(Layer.provide(Bus.layer)) +export const defaultLayer = layer.pipe(Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(Database.defaultLayer)) export * as Todo from "./todo" diff --git a/packages/opencode/src/session/tools.ts b/packages/opencode/src/session/tools.ts index f45df9d0fa23..b91e138eda6c 100644 --- a/packages/opencode/src/session/tools.ts +++ b/packages/opencode/src/session/tools.ts @@ -1,4 +1,5 @@ import { Agent } from "@/agent/agent" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Provider } from "@/provider/provider" import { ProviderTransform } from "@/provider/transform" import { MCP } from "@/mcp" @@ -7,17 +8,18 @@ import { Tool } from "@/tool/tool" import { ToolJsonSchema } from "@/tool/json-schema" import { ToolRegistry } from "@/tool/registry" import { Truncate } from "@/tool/truncate" -import { ModelID } from "@/provider/schema" + import { Plugin } from "@/plugin" import type { TaskPromptOps } from "@/tool/task" import { type Tool as AITool, tool, jsonSchema, type ToolExecutionOptions, asSchema } from "ai" import { Effect } from "effect" import { MessageV2 } from "./message-v2" -import * as Session from "./session" +import { Session } from "./session" import { SessionProcessor } from "./processor" import { PartID } from "./schema" -import * as Log from "@opencode-ai/core/util/log" +import { Log } from "@opencode-ai/core/util/log" import { EffectBridge } from "@/effect/bridge" +import { ProviderV2 } from "@opencode-ai/core/provider" const log = Log.create({ service: "session.tools" }) @@ -27,7 +29,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: { session: Session.Info processor: Pick bypassAgentCheck: boolean - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] promptOps: TaskPromptOps }) { using _ = log.time("resolveTools") @@ -73,7 +75,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: { }) for (const item of yield* registry.tools({ - modelID: ModelID.make(input.model.api.id), + modelID: ProviderV2.ModelID.make(input.model.api.id), providerID: input.model.providerID, agent: input.agent, })) { @@ -151,7 +153,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: { ) const textParts: string[] = [] - const attachments: Omit[] = [] + const attachments: Omit[] = [] for (const contentItem of result.content) { if (contentItem.type === "text") textParts.push(contentItem.text) else if (contentItem.type === "image") { diff --git a/packages/opencode/src/share/session.ts b/packages/opencode/src/share/session.ts index a13b6c9deba9..b27bc728a5e2 100644 --- a/packages/opencode/src/share/session.ts +++ b/packages/opencode/src/share/session.ts @@ -1,6 +1,5 @@ import { Session } from "@/session/session" import { SessionID } from "@/session/schema" -import { SyncEvent } from "@/sync" import { Effect, Layer, Scope, Context } from "effect" import { Config } from "@/config/config" import { RuntimeFlags } from "@/effect/runtime-flags" @@ -21,20 +20,19 @@ export const layer = Layer.effect( const session = yield* Session.Service const shareNext = yield* ShareNext.Service const scope = yield* Scope.Scope - const sync = yield* SyncEvent.Service const flags = yield* RuntimeFlags.Service const share = Effect.fn("SessionShare.share")(function* (sessionID: SessionID) { const conf = yield* cfg.get() if (conf.share === "disabled") throw new Error("Sharing is disabled in configuration") const result = yield* shareNext.create(sessionID) - yield* sync.run(Session.Event.Updated, { sessionID, info: { share: { url: result.url } } }) + yield* session.setShare({ sessionID, share: { url: result.url } }) return result }) const unshare = Effect.fn("SessionShare.unshare")(function* (sessionID: SessionID) { yield* shareNext.remove(sessionID) - yield* sync.run(Session.Event.Updated, { sessionID, info: { share: { url: null } } }) + yield* session.setShare({ sessionID, share: undefined }) }) const create = Effect.fn("SessionShare.create")(function* (input?: Session.CreateInput) { @@ -54,7 +52,6 @@ export const defaultLayer = layer.pipe( Layer.provide(ShareNext.defaultLayer), Layer.provide(Session.defaultLayer), Layer.provide(Config.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), ) diff --git a/packages/opencode/src/share/share-next.ts b/packages/opencode/src/share/share-next.ts index ab2d9d151d60..665b62898b8d 100644 --- a/packages/opencode/src/share/share-next.ts +++ b/packages/opencode/src/share/share-next.ts @@ -3,18 +3,20 @@ import { serviceUse } from "@opencode-ai/core/effect/service-use" import { Effect, Exit, Layer, Option, Schema, Scope, Context, Stream } from "effect" import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" import { Account } from "@/account/account" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { InstanceState } from "@/effect/instance-state" import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "@/provider/schema" + import { Session } from "@/session/session" import { MessageV2 } from "@/session/message-v2" import type { SessionID } from "@/session/schema" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { eq } from "drizzle-orm" import { Config } from "@/config/config" import * as Log from "@opencode-ai/core/util/log" -import { SessionShareTable } from "./share.sql" +import { SessionShareTable } from "@opencode-ai/core/share/sql" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { EventV2 } from "@opencode-ai/core/event" const log = Log.create({ service: "share-next" }) const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1" @@ -79,9 +81,6 @@ export class Service extends Context.Service()("@opencode/Sh export const use = serviceUse(Service) -const db = (fn: (d: Parameters[0] extends (trx: infer D) => any ? D : never) => T) => - Effect.sync(() => Database.use(fn)) - function api(resource: string): Api { return { create: `/api/${resource}`, @@ -113,14 +112,15 @@ export const layer = Layer.effect( Service, Effect.gen(function* () { const account = yield* Account.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const cfg = yield* Config.Service + const { db } = yield* Database.Service const http = yield* HttpClient.HttpClient const httpOk = HttpClient.filterStatusOk(http) const provider = yield* Provider.Service const session = yield* Session.Service - function sync(sessionID: SessionID, data: Data[]): Effect.Effect { + function sync(sessionID: SessionID, data: Data[]) { return Effect.gen(function* () { if (disabled) return const share = yield* getCached(sessionID) @@ -166,49 +166,41 @@ export const layer = Layer.effect( if (disabled) return cache - const watch = ( + const watch = ( def: D, - fn: (evt: { properties: any }) => Effect.Effect, + fn: (data: EventV2.Data) => Effect.Effect, ) => - bus.subscribe(def as never).pipe( - Effect.flatMap((stream) => - stream.pipe( - Stream.runForEach((evt) => - fn(evt).pipe( - Effect.catchCause((cause) => - Effect.sync(() => { - log.error("share subscriber failed", { type: def.type, cause }) - }), - ), - ), - ), - Effect.forkScoped, + events.listen((event) => { + if (event.type !== def.type || event.location?.directory !== _ctx.directory) return Effect.void + return fn(event.data as EventV2.Data).pipe( + Effect.catchCause((cause) => + Effect.sync(() => log.error("share subscriber failed", { type: def.type, cause })), ), - ), - ) + ) + }) - yield* watch(Session.Event.Updated, (evt) => + yield* watch(Session.Event.Updated, (data) => Effect.gen(function* () { - const info = evt.properties.info - yield* sync(info.id, [{ type: "session", data: info }]) + const info = data.info + yield* sync(info.id, [{ type: "session", data: structuredClone(info) as SDK.Session }]) }), ) - yield* watch(MessageV2.Event.Updated, (evt) => + yield* watch(MessageV2.Event.Updated, (data) => Effect.gen(function* () { - const info = evt.properties.info - yield* sync(info.sessionID, [{ type: "message", data: info }]) + const info = data.info + yield* sync(info.sessionID, [{ type: "message", data: structuredClone(info) as SDK.Message }]) if (info.role !== "user") return const model = yield* provider.getModel(info.model.providerID, info.model.modelID) yield* sync(info.sessionID, [{ type: "model", data: [model] }]) }), ) - yield* watch(MessageV2.Event.PartUpdated, (evt) => - sync(evt.properties.part.sessionID, [{ type: "part", data: evt.properties.part }]), + yield* watch(MessageV2.Event.PartUpdated, (data) => + sync(data.part.sessionID, [{ type: "part", data: structuredClone(data.part) as SDK.Part }]), ) - yield* watch(Session.Event.Diff, (evt) => - sync(evt.properties.sessionID, [{ type: "session_diff", data: evt.properties.diff }]), + yield* watch(Session.Event.Diff, (data) => + sync(data.sessionID, [{ type: "session_diff", data: structuredClone(data.diff) as SDK.SnapshotFileDiff[] }]), ) - yield* watch(Session.Event.Deleted, (evt) => remove(evt.properties.sessionID)) + yield* watch(Session.Event.Deleted, (data) => remove(data.sessionID)) return cache }), @@ -233,9 +225,12 @@ export const layer = Layer.effect( }) const get = Effect.fnUntraced(function* (sessionID: SessionID) { - const row = yield* db((db) => - db.select().from(SessionShareTable).where(eq(SessionShareTable.session_id, sessionID)).get(), - ) + const row = yield* db + .select() + .from(SessionShareTable) + .where(eq(SessionShareTable.session_id, sessionID)) + .get() + .pipe(Effect.orDie) if (!row) return return { id: row.id, secret: row.secret, url: row.url } satisfies Share }) @@ -289,7 +284,7 @@ export const layer = Layer.effect( .map((item) => [`${item.providerID}/${item.modelID}`, item] as const), ).values(), ), - (item) => provider.getModel(ProviderID.make(item.providerID), ModelID.make(item.modelID)), + (item) => provider.getModel(ProviderV2.ID.make(item.providerID), ProviderV2.ModelID.make(item.modelID)), { concurrency: 8 }, ) @@ -321,16 +316,15 @@ export const layer = Layer.effect( Effect.flatMap((r) => httpOk.execute(r)), Effect.flatMap(HttpClientResponse.schemaBodyJson(ShareSchema)), ) - yield* db((db) => - db - .insert(SessionShareTable) - .values({ session_id: sessionID, id: result.id, secret: result.secret, url: result.url }) - .onConflictDoUpdate({ - target: SessionShareTable.session_id, - set: { id: result.id, secret: result.secret, url: result.url }, - }) - .run(), - ) + yield* db + .insert(SessionShareTable) + .values({ session_id: sessionID, id: result.id, secret: result.secret, url: result.url }) + .onConflictDoUpdate({ + target: SessionShareTable.session_id, + set: { id: result.id, secret: result.secret, url: result.url }, + }) + .run() + .pipe(Effect.orDie) const s = yield* InstanceState.get(state) s.shared.set(sessionID, result) yield* full(sessionID).pipe( @@ -362,7 +356,7 @@ export const layer = Layer.effect( Effect.flatMap((r) => httpOk.execute(r)), ) - yield* db((db) => db.delete(SessionShareTable).where(eq(SessionShareTable.session_id, sessionID)).run()) + yield* db.delete(SessionShareTable).where(eq(SessionShareTable.session_id, sessionID)).run().pipe(Effect.orDie) s.shared.delete(sessionID) s.queue.delete(sessionID) }) @@ -372,9 +366,10 @@ export const layer = Layer.effect( ) export const defaultLayer = layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(Account.defaultLayer), Layer.provide(Config.defaultLayer), + Layer.provide(Database.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(Provider.defaultLayer), Layer.provide(Session.defaultLayer), diff --git a/packages/opencode/src/skill/index.ts b/packages/opencode/src/skill/index.ts index c1c6d0d6f28a..fc2fd0799f91 100644 --- a/packages/opencode/src/skill/index.ts +++ b/packages/opencode/src/skill/index.ts @@ -3,7 +3,7 @@ import { pathToFileURL } from "url" import { Effect, Layer, Context, Schema } from "effect" import { NamedError } from "@opencode-ai/core/util/error" import type { Agent } from "@/agent/agent" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { InstanceState } from "@/effect/instance-state" import { Global } from "@opencode-ai/core/global" import { Permission } from "@/permission" @@ -101,7 +101,7 @@ export interface Interface { readonly available: (agent?: Agent.Info) => Effect.Effect } -const add = Effect.fnUntraced(function* (state: State, match: string, bus: Bus.Interface) { +const add = Effect.fnUntraced(function* (state: State, match: string, events: EventV2Bridge.Service["Service"]) { const md = yield* Effect.tryPromise({ try: () => ConfigMarkdown.parse(match), catch: (err) => err, @@ -112,7 +112,7 @@ const add = Effect.fnUntraced(function* (state: State, match: string, bus: Bus.I ? err.data.message : `Failed to parse skill ${match}` const { Session } = yield* Effect.promise(() => import("@/session/session")) - yield* bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) + yield* events.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() }) log.error("failed to load skill", { skill: match, err }) return undefined }), @@ -232,8 +232,12 @@ const discoverSkills = Effect.fnUntraced(function* ( } }) -const loadSkills = Effect.fnUntraced(function* (state: State, discovered: DiscoveryState, bus: Bus.Interface) { - yield* Effect.forEach(discovered.matches, (match) => add(state, match, bus), { +const loadSkills = Effect.fnUntraced(function* ( + state: State, + discovered: DiscoveryState, + events: EventV2Bridge.Service["Service"], +) { + yield* Effect.forEach(discovered.matches, (match) => add(state, match, events), { concurrency: "unbounded", discard: true, }) @@ -248,7 +252,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const discovery = yield* Discovery.Service const config = yield* Config.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const fsys = yield* AppFileSystem.Service const global = yield* Global.Service const flags = yield* RuntimeFlags.Service @@ -277,7 +281,7 @@ export const layer = Layer.effect( location: "", content: CUSTOMIZE_OPENCODE_SKILL_BODY, } - yield* loadSkills(s, yield* InstanceState.get(discovered), bus) + yield* loadSkills(s, yield* InstanceState.get(discovered), events) return s }), ) @@ -317,7 +321,7 @@ export const layer = Layer.effect( export const defaultLayer = layer.pipe( Layer.provide(Discovery.defaultLayer), Layer.provide(Config.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(Global.layer), Layer.provide(RuntimeFlags.defaultLayer), diff --git a/packages/opencode/src/storage/db.bun.ts b/packages/opencode/src/storage/db.bun.ts deleted file mode 100644 index fa6190925aab..000000000000 --- a/packages/opencode/src/storage/db.bun.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Database } from "bun:sqlite" -import { drizzle } from "drizzle-orm/bun-sqlite" - -export function init(path: string) { - const sqlite = new Database(path, { create: true }) - const db = drizzle({ client: sqlite }) - return db -} diff --git a/packages/opencode/src/storage/db.node.ts b/packages/opencode/src/storage/db.node.ts deleted file mode 100644 index 0dba8dcef336..000000000000 --- a/packages/opencode/src/storage/db.node.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { DatabaseSync } from "node:sqlite" -import { drizzle } from "drizzle-orm/node-sqlite" - -export function init(path: string) { - const sqlite = new DatabaseSync(path) - const db = drizzle({ client: sqlite }) - return db -} diff --git a/packages/opencode/src/storage/db.ts b/packages/opencode/src/storage/db.ts deleted file mode 100644 index 06f1f84a9ae7..000000000000 --- a/packages/opencode/src/storage/db.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { type SQLiteBunDatabase } from "drizzle-orm/bun-sqlite" -import { migrate } from "drizzle-orm/bun-sqlite/migrator" -import { type SQLiteTransaction } from "drizzle-orm/sqlite-core" -export * from "drizzle-orm" -import { RuntimeFlags } from "@/effect/runtime-flags" -import { LocalContext } from "@/util/local-context" -import { Global } from "@opencode-ai/core/global" -import * as Log from "@opencode-ai/core/util/log" -import { NamedError } from "@opencode-ai/core/util/error" -import path from "path" -import { readFileSync, readdirSync, existsSync } from "fs" -import { Flag } from "@opencode-ai/core/flag/flag" -import { InstallationChannel } from "@opencode-ai/core/installation/version" -import { EffectBridge } from "@/effect/bridge" -import { init } from "#db" -import { Effect, Schema } from "effect" - -declare const OPENCODE_MIGRATIONS: { sql: string; timestamp: number; name: string }[] | undefined - -export const NotFoundError = NamedError.create("NotFoundError", { - message: Schema.String, -}) - -const log = Log.create({ service: "db" }) - -type DatabaseFlags = Pick - -const readRuntimeFlags = () => - Effect.runSync(RuntimeFlags.Service.useSync((flags) => flags).pipe(Effect.provide(RuntimeFlags.defaultLayer))) - -export function getChannelPath(flags: Pick = readRuntimeFlags()) { - if (["latest", "beta", "prod"].includes(InstallationChannel) || flags.disableChannelDb) - return path.join(Global.Path.data, "opencode.db") - const safe = InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-") - return path.join(Global.Path.data, `opencode-${safe}.db`) -} - -export const getPath = (flags?: Pick) => { - if (Flag.OPENCODE_DB) { - if (Flag.OPENCODE_DB === ":memory:" || path.isAbsolute(Flag.OPENCODE_DB)) return Flag.OPENCODE_DB - return path.join(Global.Path.data, Flag.OPENCODE_DB) - } - return getChannelPath(flags) -} - -export type Transaction = SQLiteTransaction<"sync", void> - -type Client = ReturnType - -type Journal = { sql: string; timestamp: number; name: string }[] - -// Drizzle's migrate overloads trigger expensive variance checks here; narrow to the journal overload we actually use. -const migrateFromJournal = migrate as unknown as (db: SQLiteBunDatabase, entries: Journal) => void - -function applyMigrations(db: SQLiteBunDatabase, entries: Journal) { - migrateFromJournal(db, entries) -} - -function time(tag: string) { - const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(tag) - if (!match) return 0 - return Date.UTC( - Number(match[1]), - Number(match[2]) - 1, - Number(match[3]), - Number(match[4]), - Number(match[5]), - Number(match[6]), - ) -} - -function migrations(dir: string): Journal { - const dirs = readdirSync(dir, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name) - - const sql = dirs - .map((name) => { - const file = path.join(dir, name, "migration.sql") - if (!existsSync(file)) return - return { - sql: readFileSync(file, "utf-8"), - timestamp: time(name), - name, - } - }) - .filter(Boolean) as Journal - - return sql.sort((a, b) => a.timestamp - b.timestamp) -} - -let client: Client | undefined -let loaded = false - -export const Client = Object.assign( - (flags: DatabaseFlags = readRuntimeFlags()): Client => { - if (loaded) return client as Client - - const dbPath = getPath(flags) - log.info("opening database", { path: dbPath }) - - const db = init(dbPath) - - db.run("PRAGMA journal_mode = WAL") - db.run("PRAGMA synchronous = NORMAL") - db.run("PRAGMA busy_timeout = 5000") - db.run("PRAGMA cache_size = -64000") - db.run("PRAGMA foreign_keys = ON") - db.run("PRAGMA wal_checkpoint(PASSIVE)") - - // Apply schema migrations - const entries = - typeof OPENCODE_MIGRATIONS !== "undefined" - ? OPENCODE_MIGRATIONS - : migrations(path.join(import.meta.dirname, "../../migration")) - if (entries.length > 0) { - log.info("applying migrations", { - count: entries.length, - mode: typeof OPENCODE_MIGRATIONS !== "undefined" ? "bundled" : "dev", - }) - if (flags.skipMigrations) { - for (const item of entries) { - item.sql = "select 1;" - } - } - applyMigrations(db, entries) - } - - client = db - loaded = true - return db - }, - { - reset: () => { - loaded = false - client = undefined - }, - loaded: () => loaded, - }, -) - -export function close() { - if (!Client.loaded()) return - Client().$client.close() - Client.reset() -} - -export type TxOrDb = Transaction | Client - -const ctx = LocalContext.create<{ - tx: TxOrDb - effects: (() => void | Promise)[] -}>("database") - -export function use(callback: (trx: TxOrDb) => T): T { - try { - return callback(ctx.use().tx) - } catch (err) { - if (err instanceof LocalContext.NotFound) { - const effects: (() => void | Promise)[] = [] - const result = ctx.provide({ effects, tx: Client() }, () => callback(Client())) - for (const effect of effects) effect() - return result - } - throw err - } -} - -export function effect(fn: () => any | Promise) { - const bound = EffectBridge.bind(fn) - try { - ctx.use().effects.push(bound) - } catch { - bound() - } -} - -type NotPromise = T extends Promise ? never : T - -export function transaction( - callback: (tx: TxOrDb) => NotPromise, - options?: { - behavior?: "deferred" | "immediate" | "exclusive" - }, -): NotPromise { - try { - return callback(ctx.use().tx) - } catch (err) { - if (err instanceof LocalContext.NotFound) { - const effects: (() => void | Promise)[] = [] - const txCallback = EffectBridge.bind((tx: TxOrDb) => ctx.provide({ tx, effects }, () => callback(tx))) - const result = Client().transaction(txCallback, { behavior: options?.behavior }) - for (const effect of effects) effect() - return result as NotPromise - } - throw err - } -} - -export * as Database from "./db" diff --git a/packages/opencode/src/storage/json-migration.ts b/packages/opencode/src/storage/json-migration.ts index 3930e591a42a..00a10e6d9249 100644 --- a/packages/opencode/src/storage/json-migration.ts +++ b/packages/opencode/src/storage/json-migration.ts @@ -2,9 +2,9 @@ import type { SQLiteBunDatabase } from "drizzle-orm/bun-sqlite" import type { NodeSQLiteDatabase } from "drizzle-orm/node-sqlite" import { Global } from "@opencode-ai/core/global" import * as Log from "@opencode-ai/core/util/log" -import { ProjectTable } from "../project/project.sql" -import { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "../session/session.sql" -import { SessionShareTable } from "../share/share.sql" +import { ProjectTable } from "@opencode-ai/core/project/sql" +import { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "@opencode-ai/core/session/sql" +import { SessionShareTable } from "@opencode-ai/core/share/sql" import path from "path" import { existsSync } from "fs" import { Filesystem } from "@/util/filesystem" diff --git a/packages/opencode/src/storage/schema.ts b/packages/opencode/src/storage/schema.ts index 0c12cee62201..01d47fcb5a30 100644 --- a/packages/opencode/src/storage/schema.ts +++ b/packages/opencode/src/storage/schema.ts @@ -1,5 +1,5 @@ -export { AccountTable, AccountStateTable, ControlAccountTable } from "../account/account.sql" -export { ProjectTable } from "../project/project.sql" -export { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "../session/session.sql" -export { SessionShareTable } from "../share/share.sql" -export { WorkspaceTable } from "../control-plane/workspace.sql" +export { AccountTable, AccountStateTable, ControlAccountTable } from "@opencode-ai/core/account/sql" +export { ProjectTable } from "@opencode-ai/core/project/sql" +export { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "@opencode-ai/core/session/sql" +export { SessionShareTable } from "@opencode-ai/core/share/sql" +export { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" diff --git a/packages/opencode/src/sync/index.ts b/packages/opencode/src/sync/index.ts deleted file mode 100644 index 8573636615d5..000000000000 --- a/packages/opencode/src/sync/index.ts +++ /dev/null @@ -1,411 +0,0 @@ -// Legacy sync event system. It should stay unaware of core EventV2 execution; -// the only temporary V2 coupling here is exposing versioned core event schemas -// in effectPayloads() so existing HTTP/SDK schema generation remains stable. -// Remove that registry read when event schemas are generated from core directly. -import { Database } from "@/storage/db" -import { eq } from "drizzle-orm" -import { GlobalBus } from "@/bus/global" -import { Bus as ProjectBus } from "@/bus" -import { BusEvent } from "@/bus/bus-event" -import { EventSequenceTable, EventTable } from "./event.sql" -import { EventID } from "./schema" -import { Context, Effect, Layer, Schema as EffectSchema } from "effect" -import type { DeepMutable } from "@opencode-ai/core/schema" -import { EventV2 } from "@opencode-ai/core/event" -import { serviceUse } from "@opencode-ai/core/effect/service-use" -import { InstanceState } from "@/effect/instance-state" -import { RuntimeFlags } from "@/effect/runtime-flags" -import { EffectBridge } from "@/effect/bridge" - -// Keep `Event["data"]` mutable because projectors mutate the persisted shape -// when writing to the database. Bus payloads (`Properties`) stay readonly — -// subscribers only read. - -export type Definition< - Type extends string = string, - Schema extends EffectSchema.Top = EffectSchema.Top, - BusSchema extends EffectSchema.Top = Schema, -> = { - type: Type - version: number - aggregate: string - schema: Schema - // Bus event payload schema. Defaults to `schema` unless `busSchema` was - // passed at definition time (see `session.updated`, whose projector - // expands the persisted data to a `{ sessionID, info }` bus payload). - properties: BusSchema -} - -export type Event = { - id: string - seq: number - aggregateID: string - data: DeepMutable> -} - -export type Properties = EffectSchema.Schema.Type - -export type SerializedEvent = Event & { type: string } - -type ProjectorFunc = (db: Database.TxOrDb, data: unknown, event: Event) => void -type ConvertEvent = (type: string, data: Event["data"]) => unknown | Promise - -export interface Interface { - readonly run: ( - def: Def, - data: Event["data"], - options?: { publish?: boolean }, - ) => Effect.Effect - readonly replay: (event: SerializedEvent, options?: { publish: boolean; ownerID?: string }) => Effect.Effect - readonly replayAll: ( - events: SerializedEvent[], - options?: { publish: boolean; ownerID?: string }, - ) => Effect.Effect - readonly remove: (aggregateID: string) => Effect.Effect - readonly claim: (aggregateID: string, ownerID: string) => Effect.Effect -} - -export class Service extends Context.Service()("@opencode/SyncEvent") {} - -export const layer = Layer.effect(Service)( - Effect.gen(function* () { - const flags = yield* RuntimeFlags.Service - const bus = yield* ProjectBus.Service - - const replay: Interface["replay"] = Effect.fn("SyncEvent.replay")(function* (event, options) { - const def = registry.get(event.type) - if (!def) { - throw new Error(`Unknown event type: ${event.type}`) - } - - const row = Database.use((db) => - db - .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) - .from(EventSequenceTable) - .where(eq(EventSequenceTable.aggregate_id, event.aggregateID)) - .get(), - ) - - const latest = row?.seq ?? -1 - if (event.seq <= latest) return - - if (row?.ownerID && row.ownerID !== options?.ownerID) { - return - } - - const expected = latest + 1 - if (event.seq !== expected) { - throw new Error( - `Sequence mismatch for aggregate "${event.aggregateID}": expected ${expected}, got ${event.seq}`, - ) - } - - const publish = !!options?.publish - // Bridge captures handler-fiber refs (InstanceRef/WorkspaceRef) and the - // full Effect context, so the forked publish + GlobalBus emit run with - // the right state without a per-call attachWith. - const bridge = yield* EffectBridge.make() - process(def, event, { - bus, - bridge, - publish, - ownerID: options?.ownerID, - experimentalWorkspaces: flags.experimentalWorkspaces, - }) - }) - - const replayAll: Interface["replayAll"] = Effect.fn("SyncEvent.replayAll")(function* (events, options) { - const source = events[0]?.aggregateID - if (!source) return undefined - if (events.some((item) => item.aggregateID !== source)) { - throw new Error("Replay events must belong to the same session") - } - const start = events[0].seq - for (const [i, item] of events.entries()) { - const seq = start + i - if (item.seq !== seq) { - throw new Error(`Replay sequence mismatch at index ${i}: expected ${seq}, got ${item.seq}`) - } - } - for (const item of events) { - yield* replay(item, options) - } - return source - }) - - const run: Interface["run"] = Effect.fn("SyncEvent.run")(function* (def, data, options) { - const agg = (data as Record)[def.aggregate] - // This should never happen: we've enforced it via typescript in - // the definition - if (agg == null) { - throw new Error(`SyncEvent.run: "${def.aggregate}" required but not found: ${JSON.stringify(data)}`) - } - - if (def.version !== versions.get(def.type)) { - throw new Error(`SyncEvent.run: running old versions of events is not allowed: ${def.type}`) - } - - const { publish = true } = options || {} - const bridge = yield* EffectBridge.make() - - // Note that this is an "immediate" transaction which is critical. - // We need to make sure we can safely read and write with nothing - // else changing the data from under us - Database.transaction( - (tx) => { - const id = EventID.ascending() - const row = tx - .select({ seq: EventSequenceTable.seq }) - .from(EventSequenceTable) - .where(eq(EventSequenceTable.aggregate_id, agg)) - .get() - const seq = row?.seq != null ? row.seq + 1 : 0 - - const event = { id, seq, aggregateID: agg, data } - process(def, event, { bus, bridge, publish, experimentalWorkspaces: flags.experimentalWorkspaces }) - }, - { - behavior: "immediate", - }, - ) - }) - - const remove: Interface["remove"] = Effect.fn("SyncEvent.remove")(function* (aggregateID) { - Database.transaction((tx) => { - tx.delete(EventSequenceTable).where(eq(EventSequenceTable.aggregate_id, aggregateID)).run() - tx.delete(EventTable).where(eq(EventTable.aggregate_id, aggregateID)).run() - }) - }) - - const claim: Interface["claim"] = Effect.fn("SyncEvent.claim")((aggregateID, ownerID) => - Effect.sync(() => - Database.use((db) => - db - .update(EventSequenceTable) - .set({ owner_id: ownerID }) - .where(eq(EventSequenceTable.aggregate_id, aggregateID)) - .run(), - ), - ), - ) - - return Service.of({ - run, - replay, - replayAll, - remove, - claim, - }) - }), -) - -export const defaultLayer = layer.pipe(Layer.provide([ProjectBus.defaultLayer, RuntimeFlags.defaultLayer])) - -export const use = serviceUse(Service) - -export const registry = new Map() -let projectors: Map | undefined -const versions = new Map() -let frozen = false -let convertEvent: ConvertEvent - -export function reset() { - frozen = false - projectors = undefined - convertEvent = (_, data) => data -} - -export function init(input: { projectors: Array<[Definition, ProjectorFunc]>; convertEvent?: ConvertEvent }) { - projectors = new Map(input.projectors.map(([def, func]) => [versionedType(def.type, def.version), func])) - for (let entry of EventV2.registry.values()) { - if (!entry.version || !entry.aggregate) continue - register({ - type: entry.type, - version: entry.version, - aggregate: entry.aggregate, - properties: entry.data, - schema: entry.data, - }) - } - - // Install all the latest event defs to the bus. We only ever emit - // latest versions from code, and keep around old versions for - // replaying. Replaying does not go through the bus, and it - // simplifies the bus to only use unversioned latest events - for (let [type, version] of versions.entries()) { - let def = registry.get(versionedType(type, version))! - BusEvent.define(def.type, def.properties) - } - - // Freeze the system so it clearly errors if events are defined - // after `init` which would cause bugs - frozen = true - convertEvent = input.convertEvent ?? ((_, data) => data) -} - -export function versionedType(type: A): A -export function versionedType(type: A, version: B): `${A}/${B}` -export function versionedType(type: string, version?: number) { - return version ? `${type}.${version}` : type -} - -export function define< - Type extends string, - Agg extends string, - Schema extends EffectSchema.Top, - BusSchema extends EffectSchema.Top = Schema, ->(input: { - type: Type - version: number - aggregate: Agg - schema: Schema - busSchema?: BusSchema -}): Definition { - if (frozen) { - throw new Error("Error defining sync event: sync system has been frozen") - } - - const def = { - type: input.type, - version: input.version, - aggregate: input.aggregate, - schema: input.schema, - properties: (input.busSchema ?? input.schema) as BusSchema, - } - - register(def) - - return def -} - -export function project( - def: Def, - func: (db: Database.TxOrDb, data: Event["data"], event: Event) => void, -): [Definition, ProjectorFunc] { - return [def, func as ProjectorFunc] -} - -function register(def: Definition) { - versions.set(def.type, Math.max(def.version, versions.get(def.type) || 0)) - registry.set(versionedType(def.type, def.version), def) -} - -function process( - def: Def, - event: Event, - options: { - bus: ProjectBus.Interface - bridge: EffectBridge.Shape - publish: boolean - ownerID?: string - experimentalWorkspaces: boolean - }, -) { - if (projectors == null) { - throw new Error("No projectors available. Call `SyncEvent.init` to install projectors") - } - - const projector = projectors.get(versionedType(def.type, def.version)) - if (!projector) { - if (!def.type.includes("next")) throw new Error(`Projector not found for event: ${def.type}`) - return - } - - Database.transaction((tx) => { - projector(tx, event.data, event) - - if (options.experimentalWorkspaces) { - tx.insert(EventSequenceTable) - .values({ - aggregate_id: event.aggregateID, - seq: event.seq, - owner_id: options?.ownerID, - }) - .onConflictDoUpdate({ - target: EventSequenceTable.aggregate_id, - set: { seq: event.seq }, - }) - .run() - tx.insert(EventTable) - .values({ - id: event.id, - seq: event.seq, - aggregate_id: event.aggregateID, - type: versionedType(def.type, def.version), - data: event.data as Record, - }) - .run() - } - - Database.effect(() => { - if (!options.publish) return - const result = convertEvent(def.type, event.data) - // The bridge was built inside the caller's fiber so it already carries - // InstanceRef/WorkspaceRef and the full Effect context. Both the bus - // publish and the GlobalBus emit run inside the forked Effect so they - // share the same instance/workspace lookup. - const publish = (data: unknown) => - options.bridge.fork( - Effect.gen(function* () { - yield* options.bus.publish(def, data as Properties, { id: event.id }) - const instance = yield* InstanceState.context - const workspace = yield* InstanceState.workspaceID - GlobalBus.emit("event", { - directory: instance.directory, - project: instance.project.id, - workspace, - payload: { - type: "sync", - syncEvent: { - type: versionedType(def.type, def.version), - ...event, - }, - }, - }) - }), - ) - if (result instanceof Promise) { - void result.then(publish) - } else { - publish(result) - } - }) - }) -} - -export function effectPayloads() { - return [ - ...registry - .entries() - .map(([type, def]) => - EffectSchema.Struct({ - type: EffectSchema.Literal("sync"), - name: EffectSchema.Literal(type), - id: EffectSchema.String, - seq: EffectSchema.Finite, - aggregateID: EffectSchema.Literal(def.aggregate), - data: def.schema, - }).annotate({ identifier: `SyncEvent.${type}` }), - ) - .toArray(), - ...EventV2.registry - .values() - .filter( - (definition) => - definition.version !== undefined && !registry.has(versionedType(definition.type, definition.version)), - ) - .map((definition) => - EffectSchema.Struct({ - type: EffectSchema.Literal("sync"), - name: EffectSchema.Literal(versionedType(definition.type, definition.version!)), - id: EffectSchema.String, - seq: EffectSchema.Finite, - aggregateID: EffectSchema.Literal(definition.aggregate!), - data: definition.data, - }).annotate({ identifier: `SyncEvent.${definition.type}` }), - ) - .toArray(), - ] -} - -export * as SyncEvent from "." diff --git a/packages/opencode/src/tool/apply_patch.ts b/packages/opencode/src/tool/apply_patch.ts index 84e84cc3962e..356d09f65c7f 100644 --- a/packages/opencode/src/tool/apply_patch.ts +++ b/packages/opencode/src/tool/apply_patch.ts @@ -1,7 +1,7 @@ import * as path from "path" import { Effect, Schema } from "effect" import * as Tool from "./tool" -import { Bus } from "../bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { FileWatcher } from "../file/watcher" import { InstanceState } from "@/effect/instance-state" import { Patch } from "../patch" @@ -25,7 +25,7 @@ export const ApplyPatchTool = Tool.define( const lsp = yield* LSP.Service const afs = yield* AppFileSystem.Service const format = yield* Format.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const run = Effect.fn("ApplyPatchTool.execute")(function* ( params: Schema.Schema.Type, @@ -253,13 +253,13 @@ export const ApplyPatchTool = Tool.define( if (yield* format.file(edited)) { yield* Bom.syncFile(afs, edited, change.bom) } - yield* bus.publish(File.Event.Edited, { file: edited }) + yield* events.publish(File.Event.Edited, { file: edited }) } } // Publish file change events for (const update of updates) { - yield* bus.publish(FileWatcher.Event.Updated, update) + yield* events.publish(FileWatcher.Event.Updated, update) } // Notify LSP of file changes and collect diagnostics diff --git a/packages/opencode/src/tool/edit.ts b/packages/opencode/src/tool/edit.ts index ea3aac34807d..79df2fa1b034 100644 --- a/packages/opencode/src/tool/edit.ts +++ b/packages/opencode/src/tool/edit.ts @@ -11,7 +11,7 @@ import { createTwoFilesPatch, diffLines } from "diff" import DESCRIPTION from "./edit.txt" import { File } from "../file" import { FileWatcher } from "../file/watcher" -import { Bus } from "../bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { Format } from "../format" import { InstanceState } from "@/effect/instance-state" import { Snapshot } from "@/snapshot" @@ -61,7 +61,7 @@ export const EditTool = Tool.define( const lsp = yield* LSP.Service const afs = yield* AppFileSystem.Service const format = yield* Format.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service return { description: DESCRIPTION, @@ -108,8 +108,8 @@ export const EditTool = Tool.define( if (yield* format.file(filePath)) { contentNew = yield* Bom.syncFile(afs, filePath, desiredBom) } - yield* bus.publish(File.Event.Edited, { file: filePath }) - yield* bus.publish(FileWatcher.Event.Updated, { + yield* events.publish(File.Event.Edited, { file: filePath }) + yield* events.publish(FileWatcher.Event.Updated, { file: filePath, event: existed ? "change" : "add", }) @@ -152,8 +152,8 @@ export const EditTool = Tool.define( if (yield* format.file(filePath)) { contentNew = yield* Bom.syncFile(afs, filePath, desiredBom) } - yield* bus.publish(File.Event.Edited, { file: filePath }) - yield* bus.publish(FileWatcher.Event.Updated, { + yield* events.publish(File.Event.Edited, { file: filePath }) + yield* events.publish(FileWatcher.Event.Updated, { file: filePath, event: "change", }) diff --git a/packages/opencode/src/tool/plan.ts b/packages/opencode/src/tool/plan.ts index af206f66a59d..01ca4a69c962 100644 --- a/packages/opencode/src/tool/plan.ts +++ b/packages/opencode/src/tool/plan.ts @@ -1,4 +1,5 @@ import path from "path" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Effect, Schema } from "effect" import * as Tool from "./tool" import { Question } from "../question" @@ -49,7 +50,7 @@ export const PlanExitTool = Tool.define( const model = lastUser?.info.role === "user" && lastUser.info.model ? lastUser.info.model : yield* provider.defaultModel() - const msg: MessageV2.User = { + const msg: SessionLegacy.User = { id: MessageID.ascending(), sessionID: ctx.sessionID, role: "user", @@ -65,7 +66,7 @@ export const PlanExitTool = Tool.define( type: "text", text: `The plan at ${plan} has been approved, you can now edit files. Execute the plan`, synthetic: true, - } satisfies MessageV2.TextPart) + } satisfies SessionLegacy.TextPart) return { title: "Switching to build agent", diff --git a/packages/opencode/src/tool/read.ts b/packages/opencode/src/tool/read.ts index 33bff77b9f37..32306872879d 100644 --- a/packages/opencode/src/tool/read.ts +++ b/packages/opencode/src/tool/read.ts @@ -87,7 +87,8 @@ export const ReadTool = Tool.define( }) const warm = Effect.fn("ReadTool.warm")(function* (filepath: string) { - yield* lsp.touchFile(filepath).pipe(Effect.ignore, Effect.forkIn(scope)) + // LSP warm-up is optional; do not let a background defect fail an otherwise successful read. + yield* lsp.touchFile(filepath).pipe(Effect.ignoreCause, Effect.forkIn(scope)) }) const readSample = Effect.fn("ReadTool.readSample")(function* ( diff --git a/packages/opencode/src/tool/registry.ts b/packages/opencode/src/tool/registry.ts index 6ef6d39a65a5..fed3824a7f40 100644 --- a/packages/opencode/src/tool/registry.ts +++ b/packages/opencode/src/tool/registry.ts @@ -7,7 +7,7 @@ import { GlobTool } from "./glob" import { GrepTool } from "./grep" import { ReadTool } from "./read" import { TaskTool } from "./task" -import { TaskStatusTool } from "./task_status" +import { Database } from "@opencode-ai/core/database/database" import { TodoWriteTool } from "./todo" import { WebFetchTool } from "./webfetch" import { WriteTool } from "./write" @@ -21,7 +21,7 @@ import { Schema } from "effect" import z from "zod" import { Plugin } from "../plugin" import { Provider } from "@/provider/provider" -import { ProviderID, type ModelID } from "../provider/schema" + import { WebSearchTool } from "./websearch" import { RepoCloneTool } from "./repo_clone" import { RepoOverviewTool } from "./repo_overview" @@ -46,20 +46,20 @@ import { Todo } from "../session/todo" import { LSP } from "@/lsp/lsp" import { Instruction } from "../session/instruction" import { AppFileSystem } from "@opencode-ai/core/filesystem" -import { Bus } from "../bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { Agent } from "../agent/agent" import { Git } from "@/git" import { Skill } from "../skill" import { Permission } from "@/permission" import { Reference } from "@/reference/reference" import { BackgroundJob } from "@/background/job" -import { SessionStatus } from "@/session/status" import { RuntimeFlags } from "@/effect/runtime-flags" +import { ProviderV2 } from "@opencode-ai/core/provider" const log = Log.create({ service: "tool.registry" }) -export function webSearchEnabled(providerID: ProviderID, flags = { exa: false, parallel: false }) { - return providerID === ProviderID.opencode || flags.exa || flags.parallel +export function webSearchEnabled(providerID: ProviderV2.ID, flags = { exa: false, parallel: false }) { + return providerID === ProviderV2.ID.opencode || flags.exa || flags.parallel } type TaskDef = Tool.InferDef @@ -76,7 +76,11 @@ export interface Interface { readonly ids: () => Effect.Effect readonly all: () => Effect.Effect readonly named: () => Effect.Effect<{ task: TaskDef; read: ReadDef }> - readonly tools: (model: { providerID: ProviderID; modelID: ModelID; agent: Agent.Info }) => Effect.Effect + readonly tools: (model: { + providerID: ProviderV2.ID + modelID: ProviderV2.ModelID + agent: Agent.Info + }) => Effect.Effect } export class Service extends Context.Service()("@opencode/ToolRegistry") {} @@ -91,7 +95,6 @@ export const layer: Layer.Layer< | Agent.Service | Skill.Service | Session.Service - | SessionStatus.Service | BackgroundJob.Service | Provider.Service | Git.Service @@ -100,13 +103,14 @@ export const layer: Layer.Layer< | LSP.Service | Instruction.Service | AppFileSystem.Service - | Bus.Service + | EventV2Bridge.Service | HttpClient.HttpClient | ChildProcessSpawner | Ripgrep.Service | Format.Service | Truncate.Service | RuntimeFlags.Service + | Database.Service > = Layer.effect( Service, Effect.gen(function* () { @@ -119,7 +123,6 @@ export const layer: Layer.Layer< const invalid = yield* InvalidTool const task = yield* TaskTool - const taskStatus = yield* TaskStatusTool const read = yield* ReadTool const question = yield* QuestionTool const todo = yield* TodoWriteTool @@ -235,7 +238,6 @@ export const layer: Layer.Layer< edit: Tool.init(edit), write: Tool.init(writetool), task: Tool.init(task), - task_status: Tool.init(taskStatus), fetch: Tool.init(webfetch), todo: Tool.init(todo), search: Tool.init(websearch), @@ -260,7 +262,6 @@ export const layer: Layer.Layer< tool.edit, tool.write, tool.task, - ...(flags.experimentalBackgroundSubagents ? [tool.task_status] : []), tool.fetch, tool.todo, tool.search, @@ -385,21 +386,21 @@ export const defaultLayer = Layer.suspend(() => Layer.provide(Skill.defaultLayer), Layer.provide(Agent.defaultLayer), Layer.provide(Session.defaultLayer), - Layer.provide(Layer.mergeAll(SessionStatus.defaultLayer, BackgroundJob.defaultLayer)), + Layer.provide(BackgroundJob.defaultLayer), Layer.provide(Provider.defaultLayer), Layer.provide(Layer.mergeAll(Git.defaultLayer, RepositoryCache.defaultLayer)), Layer.provide(Reference.defaultLayer), Layer.provide(LSP.defaultLayer), Layer.provide(Instruction.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(Format.defaultLayer), Layer.provide(CrossSpawnSpawner.defaultLayer), Layer.provide(Ripgrep.defaultLayer), Layer.provide(Truncate.defaultLayer), ) - .pipe(Layer.provide(RuntimeFlags.defaultLayer)), + .pipe(Layer.provide(Database.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer)), ) function isZodType(value: unknown): value is z.ZodType { diff --git a/packages/opencode/src/tool/task.ts b/packages/opencode/src/tool/task.ts index fece68800b06..bf52030d9c08 100644 --- a/packages/opencode/src/tool/task.ts +++ b/packages/opencode/src/tool/task.ts @@ -1,26 +1,24 @@ import * as Tool from "./tool" import DESCRIPTION from "./task.txt" import { ToolJsonSchema } from "./json-schema" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { BackgroundJob } from "@/background/job" -import { Bus } from "@/bus" import { Session } from "@/session/session" import { SessionID, MessageID } from "../session/schema" import { MessageV2 } from "../session/message-v2" import { Agent } from "../agent/agent" import { deriveSubagentSessionPermission } from "../agent/subagent-permissions" import type { SessionPrompt } from "../session/prompt" -import { SessionStatus } from "@/session/status" import { Config } from "@/config/config" -import { TuiEvent } from "@/cli/cmd/tui/event" -import { Cause, Effect, Exit, Option, Schema, Scope } from "effect" +import { Cause, Effect, Exit, Schema, Scope } from "effect" import { EffectBridge } from "@/effect/bridge" import { RuntimeFlags } from "@/effect/runtime-flags" +import { Database } from "@opencode-ai/core/database/database" export interface TaskPromptOps { cancel(sessionID: SessionID): Effect.Effect resolvePromptParts(template: string): Effect.Effect - prompt(input: SessionPrompt.PromptInput): Effect.Effect - loop(input: SessionPrompt.LoopInput): Effect.Effect + prompt(input: SessionPrompt.PromptInput): Effect.Effect } const id = "task" @@ -28,12 +26,14 @@ const BACKGROUND_DESCRIPTION = [ "", "", [ - "Background mode: background=true launches the subagent asynchronously.", - "Use task_status(task_id=..., wait=false) to poll, or wait=true to block until done.", + "Background mode: background=true launches the subagent asynchronously and returns immediately.", + "Foreground is the default; use it when you need the result before continuing.", + "Use background only for independent work that can run while you continue elsewhere.", + "You will be notified automatically when it finishes.", ].join(" "), ].join("\n") -const BaseParameters = Schema.Struct({ +const BaseParameterFields = { description: Schema.String.annotate({ description: "A short (3-5 words) description of the task" }), prompt: Schema.String.annotate({ description: "The task for the agent to perform" }), subagent_type: Schema.String.annotate({ description: "The type of specialized agent to use for this task" }), @@ -42,40 +42,30 @@ const BaseParameters = Schema.Struct({ "This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)", }), command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }), -}) +} + +const BaseParameters = Schema.Struct(BaseParameterFields) export const Parameters = Schema.Struct({ - description: Schema.String.annotate({ description: "A short (3-5 words) description of the task" }), - prompt: Schema.String.annotate({ description: "The task for the agent to perform" }), - subagent_type: Schema.String.annotate({ description: "The type of specialized agent to use for this task" }), - task_id: Schema.optional(Schema.String).annotate({ - description: - "This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)", - }), - command: Schema.optional(Schema.String).annotate({ description: "The command that triggered this task" }), + ...BaseParameterFields, background: Schema.optional(Schema.Boolean).annotate({ - description: "When true, launch the subagent in the background and return immediately", + description: "Run the agent in the background. You will be notified when it completes.", }), }) function output(sessionID: SessionID, text: string) { - return [ - `task_id: ${sessionID} (for resuming to continue this task if needed)`, - "", - "", - text, - "", - ].join("\n") + return [``, "", text, "", ""].join("\n") } function backgroundOutput(sessionID: SessionID) { return [ - `task_id: ${sessionID} (for polling this task with task_status)`, - "state: running", - "", + ``, + "Background task started", "", - "Background task started. Continue your current work and call task_status when you need the result.", + "Background task started. You will be notified automatically when it finishes; do not poll for progress.", + "Do not duplicate its work. Continue only with non-overlapping work, or stop if there is nothing else useful to do.", "", + "", ].join("\n") } @@ -90,9 +80,14 @@ function backgroundMessage(input: { input.state === "completed" ? `Background task completed: ${input.description}` : `Background task failed: ${input.description}` - return [title, `task_id: ${input.sessionID}`, `state: ${input.state}`, "", `<${tag}>`, input.text, ``].join( - "\n", - ) + return [ + ``, + `${title}`, + `<${tag}>`, + input.text, + ``, + "", + ].join("\n") } function errorText(error: unknown) { @@ -105,12 +100,11 @@ export const TaskTool = Tool.define( Effect.gen(function* () { const agent = yield* Agent.Service const background = yield* BackgroundJob.Service - const bus = yield* Bus.Service const config = yield* Config.Service const sessions = yield* Session.Service const scope = yield* Scope.Scope - const status = yield* SessionStatus.Service const flags = yield* RuntimeFlags.Service + const database = yield* Database.Service const run = Effect.fn("TaskTool.execute")(function* ( params: Schema.Schema.Type, @@ -141,9 +135,8 @@ export const TaskTool = Tool.define( return yield* Effect.fail(new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`)) } - const taskID = params.task_id - const session = taskID - ? yield* sessions.get(SessionID.make(taskID)).pipe(Effect.catchCause(() => Effect.succeed(undefined))) + const session = params.task_id + ? yield* sessions.get(SessionID.make(params.task_id)).pipe(Effect.catchCause(() => Effect.succeed(undefined))) : undefined const parent = yield* sessions.get(ctx.sessionID) const parentAgent = parent.agent @@ -168,7 +161,10 @@ export const TaskTool = Tool.define( ], })) - const msg = yield* MessageV2.get({ sessionID: ctx.sessionID, messageID: ctx.messageID }).pipe(Effect.orDie) + const msg = yield* MessageV2.get({ sessionID: ctx.sessionID, messageID: ctx.messageID }).pipe( + Effect.provideService(Database.Service, database), + Effect.orDie, + ) if (msg.info.role !== "assistant") return yield* Effect.fail(new Error("Not an assistant message")) const model = next.model ?? { @@ -189,7 +185,6 @@ export const TaskTool = Tool.define( const ops = ctx.extra?.promptOps as TaskPromptOps if (!ops) return yield* Effect.fail(new Error("TaskTool requires promptOps in ctx.extra")) - const runCancel = yield* EffectBridge.make() const runTask = Effect.fn("TaskTool.runTask")(function* () { const parts = yield* ops.resolvePromptParts(params.prompt) @@ -211,68 +206,34 @@ export const TaskTool = Tool.define( return result.parts.findLast((item) => item.type === "text")?.text ?? "" }) - const resumeWhenIdle: (input: { userID: MessageID; state: "completed" | "error" }) => Effect.Effect = - Effect.fn("TaskTool.resumeWhenIdle")(function* (input: { userID: MessageID; state: "completed" | "error" }) { - const latest = yield* sessions - .findMessage(ctx.sessionID, (item) => item.info.role === "user") - .pipe(Effect.orDie) - if (Option.isNone(latest)) return - if (latest.value.info.id !== input.userID) return - if ((yield* status.get(ctx.sessionID)).type !== "idle") { - yield* Effect.sleep("300 millis") - return yield* resumeWhenIdle(input) - } - yield* bus.publish(TuiEvent.ToastShow, { - title: input.state === "completed" ? "Background task complete" : "Background task failed", - message: - input.state === "completed" - ? `Background task "${params.description}" finished. Resuming the main thread.` - : `Background task "${params.description}" failed. Resuming the main thread.`, - variant: input.state === "completed" ? "success" : "error", - duration: 5000, - }) - yield* ops - .loop({ sessionID: ctx.sessionID }) - .pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) - }) - - const continueIfIdle = Effect.fn("TaskTool.continueIfIdle")(function* (input: { - userID: MessageID - state: "completed" | "error" - }) { - yield* resumeWhenIdle(input).pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) - }) - const inject = Effect.fn("TaskTool.injectBackgroundResult")(function* ( state: "completed" | "error", text: string, ) { const currentParent = yield* sessions.get(ctx.sessionID) - const message = yield* ops.prompt({ - sessionID: ctx.sessionID, - noReply: true, - agent: currentParent.agent ?? ctx.agent, - parts: [ - { - type: "text", - synthetic: true, - text: backgroundMessage({ - sessionID: nextSession.id, - description: params.description, - state, - text, - }), - }, - ], - }) - yield* continueIfIdle({ userID: message.info.id, state }) + yield* ops + .prompt({ + sessionID: ctx.sessionID, + agent: currentParent.agent ?? ctx.agent, + parts: [ + { + type: "text", + synthetic: true, + text: backgroundMessage({ + sessionID: nextSession.id, + description: params.description, + state, + text, + }), + }, + ], + }) + .pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })) }) const existing = yield* background.get(nextSession.id) if (existing?.status === "running") { - return yield* Effect.fail( - new Error(`Task ${nextSession.id} is already running. Use task_status to check progress.`), - ) + return yield* Effect.fail(new Error(`Task ${nextSession.id} is already running.`)) } if (runInBackground) { @@ -302,6 +263,7 @@ export const TaskTool = Tool.define( } } + const runCancel = yield* EffectBridge.make() const cancel = ops.cancel(nextSession.id) function onAbort() { diff --git a/packages/opencode/src/tool/task_status.ts b/packages/opencode/src/tool/task_status.ts deleted file mode 100644 index b458b4fc45fa..000000000000 --- a/packages/opencode/src/tool/task_status.ts +++ /dev/null @@ -1,179 +0,0 @@ -import * as Tool from "./tool" -import DESCRIPTION from "./task_status.txt" -import { BackgroundJob } from "@/background/job" -import { Session } from "@/session/session" -import { MessageV2 } from "@/session/message-v2" -import { SessionID } from "@/session/schema" -import { SessionStatus } from "@/session/status" -import { PositiveInt } from "@opencode-ai/core/schema" -import { RuntimeFlags } from "@/effect/runtime-flags" -import { Effect, Option, Schema } from "effect" - -const DEFAULT_TIMEOUT = 60_000 -const POLL_MS = 300 - -const Parameters = Schema.Struct({ - task_id: SessionID.annotate({ description: "The task_id returned by the task tool" }), - wait: Schema.optional(Schema.Boolean).annotate({ - description: "When true, wait until the task reaches a terminal state or timeout", - }), - timeout_ms: Schema.optional(PositiveInt).annotate({ - description: "Maximum milliseconds to wait when wait=true (default: 60000)", - }), -}) - -type State = BackgroundJob.Status -type InspectResult = { state: State; text: string } - -function format(input: { taskID: SessionID; state: State; text: string }) { - const tag = input.state === "completed" || input.state === "running" ? "task_result" : "task_error" - return [`task_id: ${input.taskID}`, `state: ${input.state}`, "", `<${tag}>`, input.text, ``].join("\n") -} - -function errorText(error: NonNullable) { - const data = Reflect.get(error, "data") - const message = data && typeof data === "object" ? Reflect.get(data, "message") : undefined - if (typeof message === "string" && message) return message - return error.name -} - -function inspectMessage(message: MessageV2.WithParts): InspectResult | undefined { - if (message.info.role !== "assistant") return - const text = message.parts.findLast((part) => part.type === "text")?.text ?? "" - if (message.info.error) return { state: "error", text: text || errorText(message.info.error) } - if (message.info.finish && !["tool-calls", "unknown"].includes(message.info.finish)) - return { state: "completed", text } - return { state: "running", text: text || "Task is still running." } -} - -export const TaskStatusTool = Tool.define( - "task_status", - Effect.gen(function* () { - const jobs = yield* BackgroundJob.Service - const sessions = yield* Session.Service - const status = yield* SessionStatus.Service - const flags = yield* RuntimeFlags.Service - - const inspect: (taskID: SessionID) => Effect.Effect = Effect.fn("TaskStatusTool.inspect")(function* ( - taskID: SessionID, - ) { - const job = yield* jobs.get(taskID) - if (job) { - return { - state: job.status, - text: - job.output ?? - job.error ?? - (job.status === "running" - ? "Task is still running." - : job.status === "cancelled" - ? "Task was cancelled." - : ""), - } - } - - const current = yield* status.get(taskID) - if (current.type === "busy" || current.type === "retry") { - return { - state: "running", - text: current.type === "retry" ? `Task is retrying: ${current.message}` : "Task is still running.", - } - } - - const latestAssistant = yield* sessions - .findMessage(taskID, (item) => item.info.role === "assistant") - .pipe(Effect.orDie) - if (Option.isSome(latestAssistant)) { - const latest = inspectMessage(latestAssistant.value) - if (!latest) return { state: "error", text: "Task is not running in this process." } - if (latest.state === "running") - return { state: "error", text: "Task is not running in this process and has no final output." } - return latest - } - return { state: "error", text: "Task is not running in this process and has not produced output." } - }) - - const waitForTerminal: ( - taskID: SessionID, - timeout: number, - ) => Effect.Effect<{ result: InspectResult; timedOut: boolean }> = Effect.fn("TaskStatusTool.waitForTerminal")( - function* (taskID: SessionID, timeout: number) { - const result = yield* inspect(taskID) - if (result.state !== "running") return { result, timedOut: false } - if (timeout <= 0) return { result, timedOut: true } - const sleep = Math.min(POLL_MS, timeout) - yield* Effect.sleep(`${sleep} millis`) - return yield* waitForTerminal(taskID, timeout - sleep) - }, - ) - - const run = Effect.fn("TaskStatusTool.execute")(function* ( - params: Schema.Schema.Type, - _ctx: Tool.Context, - ) { - if (!flags.experimentalBackgroundSubagents) { - return yield* Effect.fail(new Error("task_status requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true")) - } - - const session = yield* sessions.get(params.task_id).pipe(Effect.catchCause(() => Effect.succeed(undefined))) - if (!session) { - return { - title: "Task status", - metadata: { - task_id: params.task_id, - state: "error" as const, - timed_out: false, - }, - output: format({ - taskID: params.task_id, - state: "error", - text: `Task not found: ${params.task_id}`, - }), - } - } - - const waited = - params.wait === true - ? yield* jobs.wait({ id: params.task_id, timeout: params.timeout_ms ?? DEFAULT_TIMEOUT }) - : { info: yield* jobs.get(params.task_id), timedOut: false } - const inspected = waited.info - ? { - result: { - state: waited.info.status, - text: - waited.info.output ?? - waited.info.error ?? - (waited.info.status === "running" ? "Task is still running." : ""), - }, - timedOut: waited.timedOut, - } - : params.wait === true - ? yield* waitForTerminal(params.task_id, params.timeout_ms ?? DEFAULT_TIMEOUT) - : { result: yield* inspect(params.task_id), timedOut: false } - const text = inspected.timedOut - ? `Timed out after ${params.timeout_ms ?? DEFAULT_TIMEOUT}ms while waiting for task completion.` - : inspected.result.text - - return { - title: "Task status", - metadata: { - task_id: params.task_id, - state: inspected.result.state, - timed_out: inspected.timedOut, - }, - output: format({ - taskID: params.task_id, - state: inspected.result.state, - text, - }), - } - }) - - return { - description: DESCRIPTION, - parameters: Parameters, - execute: (params: Schema.Schema.Type, ctx: Tool.Context) => - run(params, ctx).pipe(Effect.orDie), - } - }), -) diff --git a/packages/opencode/src/tool/task_status.txt b/packages/opencode/src/tool/task_status.txt deleted file mode 100644 index ed6fa727b2a9..000000000000 --- a/packages/opencode/src/tool/task_status.txt +++ /dev/null @@ -1,13 +0,0 @@ -Poll the status of a background subagent task launched with the task tool. - -Use this for tasks started with `task(background=true)`. - -Parameters: -- `task_id` (required): the task session id returned by the task tool -- `wait` (optional): when true, wait for completion -- `timeout_ms` (optional): max wait duration in milliseconds when `wait=true` - -Returns compact, parseable output: -- `task_id` -- `state` (`running`, `completed`, `error`, or `cancelled`) -- `...` or `...` containing final output, error summary, or current progress text diff --git a/packages/opencode/src/tool/tool.ts b/packages/opencode/src/tool/tool.ts index f072773fad2d..4edbec94cc68 100644 --- a/packages/opencode/src/tool/tool.ts +++ b/packages/opencode/src/tool/tool.ts @@ -1,4 +1,5 @@ import { Effect, Schema } from "effect" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import type { JSONSchema7 } from "@ai-sdk/provider" import type { MessageV2 } from "../session/message-v2" import type { Permission } from "../permission" @@ -38,7 +39,7 @@ export type Context = { abort: AbortSignal callID?: string extra?: { [key: string]: unknown } - messages: MessageV2.WithParts[] + messages: SessionLegacy.WithParts[] metadata(input: { title?: string; metadata?: M }): Effect.Effect ask(input: Omit): Effect.Effect } @@ -47,7 +48,7 @@ export interface ExecuteResult { title: string metadata: M output: string - attachments?: Omit[] + attachments?: Omit[] } export interface Def< diff --git a/packages/opencode/src/tool/webfetch.ts b/packages/opencode/src/tool/webfetch.ts index f8a4b6233ae9..e6150345459e 100644 --- a/packages/opencode/src/tool/webfetch.ts +++ b/packages/opencode/src/tool/webfetch.ts @@ -17,7 +17,7 @@ export const Parameters = Schema.Struct({ description: "The format to return the content in (text, markdown, or html). Defaults to markdown.", default: "markdown", }) - .pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("markdown" as const))), + .pipe(Schema.withDecodingDefault(Effect.succeed("markdown" as const))), timeout: Schema.optional(Schema.Number).annotate({ description: "Optional timeout in seconds (max 120)" }), }) diff --git a/packages/opencode/src/tool/write.ts b/packages/opencode/src/tool/write.ts index c2be73ab1cdb..40de52279a56 100644 --- a/packages/opencode/src/tool/write.ts +++ b/packages/opencode/src/tool/write.ts @@ -5,7 +5,7 @@ import * as Tool from "./tool" import { LSP } from "@/lsp/lsp" import { createTwoFilesPatch } from "diff" import DESCRIPTION from "./write.txt" -import { Bus } from "../bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { File } from "../file" import { FileWatcher } from "../file/watcher" import { Format } from "../format" @@ -29,7 +29,7 @@ export const WriteTool = Tool.define( Effect.gen(function* () { const lsp = yield* LSP.Service const fs = yield* AppFileSystem.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const format = yield* Format.Service return { @@ -65,8 +65,8 @@ export const WriteTool = Tool.define( if (yield* format.file(filepath)) { yield* Bom.syncFile(fs, filepath, desiredBom) } - yield* bus.publish(File.Event.Edited, { file: filepath }) - yield* bus.publish(FileWatcher.Event.Updated, { + yield* events.publish(File.Event.Edited, { file: filepath }) + yield* events.publish(FileWatcher.Event.Updated, { file: filepath, event: exists ? "change" : "add", }) diff --git a/packages/opencode/src/util/proxy-env.ts b/packages/opencode/src/util/proxy-env.ts new file mode 100644 index 000000000000..6682b3ca1390 --- /dev/null +++ b/packages/opencode/src/util/proxy-env.ts @@ -0,0 +1,72 @@ +/* + * Adapted from proxy-from-env: https://github.com/Rob--W/proxy-from-env + * + * The MIT License + * + * Copyright (C) 2016-2018 Rob Wu + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +const DEFAULT_PORTS: Record = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +} + +export function getProxyForUrl(input: string | URL) { + const url = typeof input === "string" ? (URL.canParse(input) ? new URL(input) : undefined) : input + if (!url) return + + const protocol = url.protocol.split(":", 1)[0] + const hostname = url.host.replace(/:\d*$/, "") + const port = Number.parseInt(url.port) || DEFAULT_PORTS[protocol] || 0 + if (!shouldProxy(hostname, port)) return + + const proxy = env(`${protocol}_proxy`) || env("all_proxy") + if (!proxy) return + return proxy.includes("://") ? proxy : `${protocol}://${proxy}` +} + +function shouldProxy(hostname: string, port: number) { + const noProxy = env("no_proxy").toLowerCase() + if (!noProxy) return true + if (noProxy === "*") return false + + return noProxy.split(/[,\s]/).every((proxy) => { + if (!proxy) return true + + const parsed = proxy.match(/^(.+):(\d+)$/) + const proxyHostname = parsed ? parsed[1] : proxy + const proxyPort = parsed ? Number.parseInt(parsed[2]) : 0 + if (proxyPort && proxyPort !== port) return true + + if (!/^[.*]/.test(proxyHostname)) return hostname !== proxyHostname + return !hostname.endsWith(proxyHostname.startsWith("*") ? proxyHostname.slice(1) : proxyHostname) + }) +} + +function env(key: string) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || "" +} + +export * as ProxyEnv from "./proxy-env" diff --git a/packages/opencode/src/v2/provider-parity-checklist.md b/packages/opencode/src/v2/provider-parity-checklist.md deleted file mode 100644 index e3a599d8ec3b..000000000000 --- a/packages/opencode/src/v2/provider-parity-checklist.md +++ /dev/null @@ -1,95 +0,0 @@ -# Unported Provider Logic Checklist - -This tracks legacy provider behavior from `packages/opencode/src/provider/provider.ts` that still needs to be ported into the v2 provider plugins under `packages/opencode/src/v2/plugin/provider/`. Keep entries checked only when v2 has equivalent behavior or when the item is intentionally skipped. - -## Provider Setup - -- [x] Cloudflare AI Gateway custom SDK construction with `createAiGateway` / `createUnified`. -- [x] Google Vertex authenticated `fetch` injection. -- [x] Amazon Bedrock AWS credential chain setup. -- [x] Amazon Bedrock bearer token setup. -- [x] SAP AI Core service key setup. - -## Provider Options - -- [x] Azure resource name resolution. -- [x] Azure missing-resource error. -- [x] Azure Cognitive Services baseURL resolution. -- [x] Cloudflare Workers AI account ID validation. -- [x] Cloudflare Workers AI account ID vars. -- [x] Cloudflare AI Gateway account ID validation. -- [x] Cloudflare AI Gateway gateway ID validation. -- [x] Cloudflare AI Gateway token validation. -- [x] Amazon Bedrock region precedence. -- [x] Amazon Bedrock profile precedence. -- [x] Amazon Bedrock endpoint precedence. -- [x] Google Vertex project resolution. -- [x] Google Vertex location resolution. -- [x] GitLab instance URL resolution. -- [x] GitLab token resolution. -- [x] GitLab AI gateway headers. -- [x] GitLab feature flags. -- [x] Opencode unauthenticated paid-model filtering. -- [x] Opencode public API key fallback. - -## Request Behavior - -- [x] Request timeout handling. -- [x] Chunk timeout handling. -- [x] SSE timeout wrapping. -- [x] OpenAI response item ID stripping. -- [x] Azure response item ID stripping. -- [x] OpenAI-compatible `includeUsage` defaulting. - -## Dynamic Models - -- [ ] GitLab workflow model discovery. - -## Model Filtering - -- [ ] Experimental alpha model filtering. -- [ ] Deprecated model filtering. -- [ ] Config whitelist filtering. -- [ ] Config blacklist filtering. -- [ ] `gpt-5-chat-latest` filtering. -- [ ] OpenRouter `openai/gpt-5-chat` filtering. - -## Default Models - -- [x] Configured default model selection. Replaced by explicit `Catalog.model.setDefault`. -- [SKIP] Recent-history default model selection — not porting to server-side v2 catalog. -- [x] Default model fallback sorting. Uses newest available model, not legacy hard-coded priority. - -## Small Models - -- [SKIP] Configured `small_model` selection — not porting config-driven selection to server-side v2 catalog. -- [x] Provider-specific small model priority. Replaced by cheapest output cost selection. -- [x] Opencode small model priority. Replaced by cheapest output cost selection. -- [x] GitHub Copilot small model priority. Replaced by cheapest output cost selection. -- [x] Amazon Bedrock region-aware small model selection. Replaced by cheapest output cost selection. - -## URL And Env Vars - -- [SKIP] BaseURL `${VAR}` interpolation — not porting generic URL templating; provider plugins should construct concrete URLs. -- [x] Azure `AZURE_RESOURCE_NAME` vars. Handled by Azure provider plugins. -- [x] Google Vertex vars. Handled by Google Vertex provider plugins. -- [x] Cloudflare Workers AI vars. Handled by Cloudflare Workers AI provider plugin. - -## Auth - -- [ ] Auth-derived provider API keys. -- [ ] OpenAI OAuth/API auth distinction. -- [ ] GitLab OAuth token selection. -- [ ] GitLab API token selection. -- [ ] Azure auth metadata resource name. -- [ ] Cloudflare auth metadata account ID. -- [ ] Cloudflare auth metadata gateway ID. - -## Config And Plugin Parity - -- [ ] Legacy plugin auth loader behavior. -- [ ] Config provider merge behavior. -- [ ] Config model merge behavior. -- [ ] Variant generation from model metadata. -- [ ] Config variant merge behavior. -- [ ] Config variant disable behavior. diff --git a/packages/opencode/src/v2/session.ts b/packages/opencode/src/v2/session.ts deleted file mode 100644 index 5e477cc8a3d2..000000000000 --- a/packages/opencode/src/v2/session.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { SessionMessageTable, SessionTable } from "@/session/session.sql" -import { SessionID } from "@/session/schema" -import { WorkspaceID } from "@/control-plane/schema" -import { and, asc, desc, eq, gt, gte, isNull, like, lt, or, type SQL } from "@/storage/db" -import * as Database from "@/storage/db" -import { Context, DateTime, Effect, Layer, Schema } from "effect" -import { SessionMessage } from "@opencode-ai/core/session-message" -import type { Prompt } from "@opencode-ai/core/session-prompt" -import { ProjectID } from "@/project/schema" -import { SessionEvent } from "@opencode-ai/core/session-event" -import { V2Schema } from "@opencode-ai/core/v2-schema" -import { optionalOmitUndefined } from "@opencode-ai/core/schema" -import { EventV2 } from "@opencode-ai/core/event" -import { EventV2Bridge } from "@/event-v2-bridge" -import { ModelV2 } from "@opencode-ai/core/model" -import { ProviderV2 } from "@opencode-ai/core/provider" - -export const Delivery = Schema.Literals(["immediate", "deferred"]).annotate({ - identifier: "Session.Delivery", -}) -export type Delivery = Schema.Schema.Type - -export const DefaultDelivery = "immediate" satisfies Delivery - -export class Info extends Schema.Class("Session.Info")({ - id: SessionID, - parentID: optionalOmitUndefined(SessionID), - projectID: ProjectID, - workspaceID: optionalOmitUndefined(WorkspaceID), - path: optionalOmitUndefined(Schema.String), - agent: optionalOmitUndefined(Schema.String), - model: ModelV2.Ref.pipe(optionalOmitUndefined), - cost: Schema.Finite, - tokens: Schema.Struct({ - input: Schema.Finite, - output: Schema.Finite, - reasoning: Schema.Finite, - cache: Schema.Struct({ - read: Schema.Finite, - write: Schema.Finite, - }), - }), - time: Schema.Struct({ - created: V2Schema.DateTimeUtcFromMillis, - updated: V2Schema.DateTimeUtcFromMillis, - archived: optionalOmitUndefined(V2Schema.DateTimeUtcFromMillis), - }), - title: Schema.String, - /* - slug: Schema.String, - directory: Schema.String, - path: optionalOmitUndefined(Schema.String), - parentID: optionalOmitUndefined(SessionID), - summary: optionalOmitUndefined(Summary), - share: optionalOmitUndefined(Share), - title: Schema.String, - version: Schema.String, - time: Time, - permission: optionalOmitUndefined(Permission.Ruleset), - revert: optionalOmitUndefined(Revert), - */ -}) {} - -export class NotFoundError extends Schema.TaggedErrorClass()("Session.NotFoundError", { - sessionID: SessionID, -}) {} - -export class OperationUnavailableError extends Schema.TaggedErrorClass()( - "Session.OperationUnavailableError", - { - operation: Schema.Literals(["prompt", "compact", "wait"]), - }, -) {} - -export class MessageDecodeError extends Schema.TaggedErrorClass()("Session.MessageDecodeError", { - sessionID: SessionID, - messageID: SessionMessage.ID, -}) {} - -export interface Interface { - readonly create: (input?: { - agent?: string - model?: ModelV2.Ref - parentID?: SessionID - workspaceID?: WorkspaceID - }) => Effect.Effect - readonly get: (sessionID: SessionID) => Effect.Effect - readonly list: (input: { - limit?: number - order?: "asc" | "desc" - directory?: string - path?: string - workspaceID?: WorkspaceID - roots?: boolean - start?: number - search?: string - cursor?: { - id: SessionID - time: number - direction: "previous" | "next" - } - }) => Effect.Effect - readonly messages: (input: { - sessionID: SessionID - limit?: number - order?: "asc" | "desc" - cursor?: { - id: SessionMessage.ID - time: number - direction: "previous" | "next" - } - }) => Effect.Effect - readonly context: ( - sessionID: SessionID, - ) => Effect.Effect - readonly prompt: (input: { - id?: EventV2.ID - sessionID: SessionID - prompt: Prompt - delivery?: Delivery - }) => Effect.Effect - readonly shell: (input: { id?: EventV2.ID; sessionID: SessionID; command: string }) => Effect.Effect - readonly skill: (input: { id?: EventV2.ID; sessionID: SessionID; skill: string }) => Effect.Effect - readonly subagent: (input: { - id?: EventV2.ID - parentID: SessionID - prompt: Prompt - agent: string - model?: ModelV2.Ref - }) => Effect.Effect - readonly switchAgent: (input: { sessionID: SessionID; agent: string }) => Effect.Effect - readonly switchModel: (input: { sessionID: SessionID; model: ModelV2.Ref }) => Effect.Effect - readonly compact: (sessionID: SessionID) => Effect.Effect - readonly wait: (sessionID: SessionID) => Effect.Effect -} - -export class Service extends Context.Service()("@opencode/v2/Session") {} - -export const layer = Layer.effect( - Service, - Effect.gen(function* () { - const events = yield* EventV2Bridge.Service - const decodeMessage = Schema.decodeUnknownEffect(SessionMessage.Message) - - const decode = (row: typeof SessionMessageTable.$inferSelect) => - decodeMessage({ ...row.data, id: row.id, type: row.type }).pipe( - Effect.mapError( - () => - new MessageDecodeError({ - sessionID: SessionID.make(row.session_id), - messageID: SessionMessage.ID.make(row.id), - }), - ), - ) - - function fromRow(row: typeof SessionTable.$inferSelect): Info { - return new Info({ - id: SessionID.make(row.id), - projectID: ProjectID.make(row.project_id), - workspaceID: row.workspace_id ? WorkspaceID.make(row.workspace_id) : undefined, - title: row.title, - parentID: row.parent_id ? SessionID.make(row.parent_id) : undefined, - path: row.path ?? "", - agent: row.agent ?? undefined, - model: row.model - ? { - id: ModelV2.ID.make(row.model.id), - providerID: ProviderV2.ID.make(row.model.providerID), - variant: ModelV2.VariantID.make(row.model.variant ?? "default"), - } - : undefined, - cost: row.cost, - tokens: { - input: row.tokens_input, - output: row.tokens_output, - reasoning: row.tokens_reasoning, - cache: { - read: row.tokens_cache_read, - write: row.tokens_cache_write, - }, - }, - time: { - created: DateTime.makeUnsafe(row.time_created), - updated: DateTime.makeUnsafe(row.time_updated), - archived: row.time_archived ? DateTime.makeUnsafe(row.time_archived) : undefined, - }, - }) - } - - const result = Service.of({ - create: Effect.fn("V2Session.create")(function* (_input) { - return {} as any - }), - get: Effect.fn("V2Session.get")(function* (sessionID) { - const row = Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get()) - if (!row) return yield* new NotFoundError({ sessionID }) - return fromRow(row) - }), - list: Effect.fn("V2Session.list")(function* (input) { - const direction = input.cursor?.direction ?? "next" - let order = input.order ?? "desc" - // This is a load bearing sort, desktop relies on this - const sortColumn = SessionTable.time_updated - // Query the adjacent rows in reverse, then flip them back into the requested order below. - if (direction === "previous" && order === "asc") order = "desc" - if (direction === "previous" && order === "desc") order = "asc" - const conditions: SQL[] = [] - if (input.directory) conditions.push(eq(SessionTable.directory, input.directory)) - if (input.path) - conditions.push(or(eq(SessionTable.path, input.path), like(SessionTable.path, `${input.path}/%`))!) - if (input.workspaceID) conditions.push(eq(SessionTable.workspace_id, input.workspaceID)) - if (input.roots) conditions.push(isNull(SessionTable.parent_id)) - if (input.start) conditions.push(gte(sortColumn, input.start)) - if (input.search) conditions.push(like(SessionTable.title, `%${input.search}%`)) - if (input.cursor) { - conditions.push( - order === "asc" - ? or( - gt(sortColumn, input.cursor.time), - and(eq(sortColumn, input.cursor.time), gt(SessionTable.id, input.cursor.id)), - )! - : or( - lt(sortColumn, input.cursor.time), - and(eq(sortColumn, input.cursor.time), lt(SessionTable.id, input.cursor.id)), - )!, - ) - } - const query = Database.Client() - .select() - .from(SessionTable) - .where(conditions.length > 0 ? and(...conditions) : undefined) - .orderBy( - order === "asc" ? asc(sortColumn) : desc(sortColumn), - order === "asc" ? asc(SessionTable.id) : desc(SessionTable.id), - ) - - const rows = input.limit === undefined ? query.all() : query.limit(input.limit).all() - return (direction === "previous" ? rows.toReversed() : rows).map((row) => fromRow(row)) - }), - messages: Effect.fn("V2Session.messages")(function* (input) { - yield* result.get(input.sessionID) - const direction = input.cursor?.direction ?? "next" - let order = input.order ?? "desc" - // Query the adjacent rows in reverse, then flip them back into the requested order below. - if (direction === "previous" && order === "asc") order = "desc" - if (direction === "previous" && order === "desc") order = "asc" - const boundary = input.cursor - ? order === "asc" - ? or( - gt(SessionMessageTable.time_created, input.cursor.time), - and( - eq(SessionMessageTable.time_created, input.cursor.time), - gt(SessionMessageTable.id, input.cursor.id), - ), - ) - : or( - lt(SessionMessageTable.time_created, input.cursor.time), - and( - eq(SessionMessageTable.time_created, input.cursor.time), - lt(SessionMessageTable.id, input.cursor.id), - ), - ) - : undefined - const where = boundary - ? and(eq(SessionMessageTable.session_id, input.sessionID), boundary) - : eq(SessionMessageTable.session_id, input.sessionID) - - const rows = Database.use((db) => { - const query = db - .select() - .from(SessionMessageTable) - .where(where) - .orderBy( - order === "asc" ? asc(SessionMessageTable.time_created) : desc(SessionMessageTable.time_created), - order === "asc" ? asc(SessionMessageTable.id) : desc(SessionMessageTable.id), - ) - const rows = input.limit === undefined ? query.all() : query.limit(input.limit).all() - return direction === "previous" ? rows.toReversed() : rows - }) - return yield* Effect.forEach(rows, (row) => decode(row)) - }), - context: Effect.fn("V2Session.context")(function* (sessionID) { - yield* result.get(sessionID) - const rows = Database.use((db) => { - const compaction = db - .select() - .from(SessionMessageTable) - .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "compaction"))) - .orderBy(desc(SessionMessageTable.time_created), desc(SessionMessageTable.id)) - .limit(1) - .get() - - return db - .select() - .from(SessionMessageTable) - .where( - and( - eq(SessionMessageTable.session_id, sessionID), - compaction - ? or( - gt(SessionMessageTable.time_created, compaction.time_created), - and( - eq(SessionMessageTable.time_created, compaction.time_created), - gte(SessionMessageTable.id, compaction.id), - ), - ) - : undefined, - ), - ) - .orderBy(asc(SessionMessageTable.time_created), asc(SessionMessageTable.id)) - .all() - }) - return yield* Effect.forEach(rows, (row) => decode(row)) - }), - prompt: Effect.fn("V2Session.prompt")(function* (input) { - yield* result.get(input.sessionID) - return yield* new OperationUnavailableError({ operation: "prompt" }) - }), - shell: Effect.fn("V2Session.shell")(function* (_input) {}), - skill: Effect.fn("V2Session.skill")(function* (_input) {}), - switchAgent: Effect.fn("V2Session.switchAgent")(function* (input) { - yield* events.publish(SessionEvent.AgentSwitched, { - sessionID: input.sessionID, - timestamp: DateTime.makeUnsafe(Date.now()), - agent: input.agent, - }) - }), - switchModel: Effect.fn("V2Session.switchModel")(function* (input) { - yield* events.publish(SessionEvent.ModelSwitched, { - sessionID: input.sessionID, - timestamp: DateTime.makeUnsafe(Date.now()), - model: input.model, - }) - }), - subagent: Effect.fn("V2Session.subagent")(function* (input) { - const parent = yield* result.get(input.parentID) - const child = yield* result.create({ - agent: input.agent, - model: input.model, - parentID: input.parentID, - workspaceID: parent.workspaceID, - }) - yield* result.prompt({ - prompt: input.prompt, - sessionID: child.id, - }) - yield* Effect.gen(function* () { - yield* result.wait(child.id) - const messages = yield* result.messages({ sessionID: child.id, order: "desc" }) - const assistant = messages.find((msg) => msg.type === "assistant") - if (!assistant) return - const text = assistant.content.findLast((part) => part.type === "text") - if (!text) return - }).pipe(Effect.forkChild()) - }), - compact: Effect.fn("V2Session.compact")(function* (sessionID) { - yield* result.get(sessionID) - return yield* new OperationUnavailableError({ operation: "compact" }) - }), - wait: Effect.fn("V2Session.wait")(function* (sessionID) { - yield* result.get(sessionID) - return yield* new OperationUnavailableError({ operation: "wait" }) - }), - }) - - return result - }), -) - -export const defaultLayer = layer.pipe(Layer.provide(EventV2Bridge.defaultLayer)) - -export * as SessionV2 from "./session" diff --git a/packages/opencode/src/worktree/index.ts b/packages/opencode/src/worktree/index.ts index a1d4f89c2ac5..7a866c24c943 100644 --- a/packages/opencode/src/worktree/index.ts +++ b/packages/opencode/src/worktree/index.ts @@ -2,14 +2,14 @@ import { Global } from "@opencode-ai/core/global" import { InstanceLayer } from "@/project/instance-layer" import { InstanceStore } from "@/project/instance-store" import { Project } from "@/project/project" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { eq } from "drizzle-orm" -import { ProjectTable } from "../project/project.sql" -import type { ProjectID } from "../project/schema" +import { ProjectTable } from "@opencode-ai/core/project/sql" +import type { ProjectV2 } from "@opencode-ai/core/project" import * as Log from "@opencode-ai/core/util/log" import { Slug } from "@opencode-ai/core/util/slug" import { errorMessage } from "../util/error" -import { BusEvent } from "@/bus/bus-event" +import { EventV2 } from "@opencode-ai/core/event" import { GlobalBus } from "@/bus/global" import { Git } from "@/git" import { Effect, Layer, Path, Schema, Scope, Context } from "effect" @@ -22,19 +22,19 @@ import { InstanceState } from "@/effect/instance-state" const log = Log.create({ service: "worktree" }) export const Event = { - Ready: BusEvent.define( - "worktree.ready", - Schema.Struct({ + Ready: EventV2.define({ + type: "worktree.ready", + schema: { name: Schema.String, branch: Schema.optional(Schema.String), - }), - ), - Failed: BusEvent.define( - "worktree.failed", - Schema.Struct({ + }, + }), + Failed: EventV2.define({ + type: "worktree.failed", + schema: { message: Schema.String, - }), - ), + }, + }), } export const Info = Schema.Struct({ @@ -149,7 +149,13 @@ type GitResult = { code: number; text: string; stderr: string } export const layer: Layer.Layer< Service, never, - AppFileSystem.Service | Path.Path | AppProcess.Service | Git.Service | Project.Service | InstanceStore.Service + | AppFileSystem.Service + | Path.Path + | AppProcess.Service + | Git.Service + | Project.Service + | InstanceStore.Service + | Database.Service > = Layer.effect( Service, Effect.gen(function* () { @@ -157,6 +163,7 @@ export const layer: Layer.Layer< const fs = yield* AppFileSystem.Service const pathSvc = yield* Path.Path const appProcess = yield* AppProcess.Service + const { db } = yield* Database.Service const gitSvc = yield* Git.Service const project = yield* Project.Service const store = yield* InstanceStore.Service @@ -351,7 +358,7 @@ export const layer: Layer.Layer< return yield* new ListFailedError({ message: result.stderr || result.text || "Failed to read git worktrees" }) } - const primary = yield* canonical(ctx.worktree) + const primary = yield* canonical(ctx.project.worktree) const primaryName = pathSvc.basename(primary).toLowerCase() return yield* Effect.forEach(parseWorktreeList(result.text), (entry) => Effect.gen(function* () { @@ -377,10 +384,19 @@ export const layer: Layer.Layer< function cleanDirectory(target: string) { return Effect.tryPromise({ - try: () => - import("fs/promises").then((fsp) => - fsp.rm(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }), - ), + try: async () => { + const fsp = await import("fs/promises") + const attempts = process.platform === "win32" ? 50 : 5 + for (const attempt of Array.from({ length: attempts }, (_, i) => i)) { + try { + await fsp.rm(target, { recursive: true, force: true }) + return + } catch (error) { + if (attempt === attempts - 1) throw error + await new Promise((resolve) => setTimeout(resolve, 100)) + } + } + }, catch: (error) => new RemoveFailedError({ message: errorMessage(error) || "Failed to remove git worktree directory" }), }) @@ -394,6 +410,9 @@ export const layer: Layer.Layer< const directory = yield* canonical(input.directory) + // Preserve the loaded path casing for the store cache; `directory` is lowercased on Windows. + if (directory !== (yield* canonical(ctx.worktree))) yield* store.disposeDirectory(input.directory) + const list = yield* git(["worktree", "list", "--porcelain"], { cwd: ctx.worktree }) if (list.code !== 0) { return yield* new RemoveFailedError({ message: list.stderr || list.text || "Failed to read git worktrees" }) @@ -411,6 +430,8 @@ export const layer: Layer.Layer< return true } + // Git may return the original casing when a caller supplied a normalized Windows path. + yield* store.disposeDirectory(entry.path) yield* stopFsmonitor(entry.path) const removed = yield* git(["worktree", "remove", "--force", entry.path], { cwd: ctx.worktree }) if (removed.code !== 0) { @@ -476,11 +497,14 @@ export const layer: Layer.Layer< const runStartScripts = Effect.fnUntraced(function* ( directory: string, - input: { projectID: ProjectID; extra?: string }, + input: { projectID: ProjectV2.ID; extra?: string }, ) { - const row = yield* Effect.sync(() => - Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, input.projectID)).get()), - ) + const row = yield* db + .select() + .from(ProjectTable) + .where(eq(ProjectTable.id, input.projectID)) + .get() + .pipe(Effect.orDie) const project = row ? Project.fromRow(row) : undefined const startup = project?.commands?.start?.trim() ?? "" const ok = yield* runStartScript(directory, startup, "project") @@ -611,6 +635,7 @@ export const appLayer = layer.pipe( Layer.provide(Git.defaultLayer), Layer.provide(AppProcess.defaultLayer), Layer.provide(Project.defaultLayer), + Layer.provide(Database.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(NodePath.layer), ) diff --git a/packages/opencode/test/account/repo.test.ts b/packages/opencode/test/account/repo.test.ts index 137665154311..42851fc19d46 100644 --- a/packages/opencode/test/account/repo.test.ts +++ b/packages/opencode/test/account/repo.test.ts @@ -1,20 +1,21 @@ import { expect } from "bun:test" import { Effect, Layer, Option } from "effect" +import { sql } from "drizzle-orm" import { AccountRepo } from "../../src/account/repo" import { AccessToken, AccountID, OrgID, RefreshToken } from "../../src/account/schema" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { testEffect } from "../lib/effect" const truncate = Layer.effectDiscard( - Effect.sync(() => { - const db = Database.Client() - db.run(/*sql*/ `DELETE FROM account_state`) - db.run(/*sql*/ `DELETE FROM account`) + Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db.run(sql`DELETE FROM account_state`) + yield* db.run(sql`DELETE FROM account`) }), -) +).pipe(Layer.provide(Database.defaultLayer)) -const it = testEffect(Layer.merge(AccountRepo.layer, truncate)) +const it = testEffect(Layer.merge(AccountRepo.defaultLayer, truncate)) it.live("list returns empty when no accounts exist", () => Effect.gen(function* () { diff --git a/packages/opencode/test/account/service.test.ts b/packages/opencode/test/account/service.test.ts index ffe5d78a1fff..04d425e2c465 100644 --- a/packages/opencode/test/account/service.test.ts +++ b/packages/opencode/test/account/service.test.ts @@ -1,5 +1,6 @@ import { expect } from "bun:test" import { Duration, Effect, Layer, Option, Schema } from "effect" +import { sql } from "drizzle-orm" import { HttpClient, HttpClientError, HttpClientResponse } from "effect/unstable/http" import { AccountRepo } from "../../src/account/repo" @@ -15,18 +16,18 @@ import { RefreshToken, UserCode, } from "../../src/account/schema" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { testEffect } from "../lib/effect" const truncate = Layer.effectDiscard( - Effect.sync(() => { - const db = Database.Client() - db.run(/*sql*/ `DELETE FROM account_state`) - db.run(/*sql*/ `DELETE FROM account`) + Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db.run(sql`DELETE FROM account_state`) + yield* db.run(sql`DELETE FROM account`) }), -) +).pipe(Layer.provide(Database.defaultLayer)) -const it = testEffect(Layer.merge(AccountRepo.layer, truncate)) +const it = testEffect(Layer.merge(AccountRepo.defaultLayer, truncate)) const insideEagerRefreshWindow = Duration.toMillis(Duration.minutes(1)) const outsideEagerRefreshWindow = Duration.toMillis(Duration.minutes(10)) diff --git a/packages/opencode/test/acp-next/service-session.test.ts b/packages/opencode/test/acp-next/service-session.test.ts deleted file mode 100644 index a9ecb3cf48cc..000000000000 --- a/packages/opencode/test/acp-next/service-session.test.ts +++ /dev/null @@ -1,366 +0,0 @@ -import { describe, expect, it } from "bun:test" -import type { AgentSideConnection, LoadSessionResponse, NewSessionResponse } from "@agentclientprotocol/sdk" -import type { OpencodeClient } from "@opencode-ai/sdk/v2" -import { Effect } from "effect" -import * as ACPNextService from "@/acp-next/service" -import * as ACPNextError from "@/acp-next/error" -import { ModelID, ProviderID } from "@/provider/schema" -import type { Provider } from "@/provider/provider" - -const providerID = ProviderID.make("test") -const modelID = ModelID.make("test-model") -const configuredModelID = ModelID.make("configured-model") - -const provider: Provider.Info = { - id: providerID, - name: "Test", - source: "config", - env: [], - options: {}, - models: { - [modelID]: { - id: modelID, - providerID, - api: { - id: modelID, - url: "https://example.com", - npm: "@ai-sdk/openai-compatible", - }, - name: "Test Model", - family: "test", - capabilities: { - temperature: true, - reasoning: true, - attachment: false, - toolcall: true, - input: { text: true, audio: false, image: false, video: false, pdf: false }, - output: { text: true, audio: false, image: false, video: false, pdf: false }, - interleaved: false, - }, - cost: { - input: 0, - output: 0, - cache: { read: 0, write: 0 }, - }, - limit: { - context: 128000, - output: 4096, - }, - status: "active", - options: {}, - headers: {}, - release_date: "2026-01-01", - variants: { - default: {}, - high: { reasoningEffort: "high" }, - }, - }, - [configuredModelID]: { - id: configuredModelID, - providerID, - api: { - id: configuredModelID, - url: "https://example.com", - npm: "@ai-sdk/openai-compatible", - }, - name: "Configured Model", - family: "test", - capabilities: { - temperature: true, - reasoning: false, - attachment: false, - toolcall: true, - input: { text: true, audio: false, image: false, video: false, pdf: false }, - output: { text: true, audio: false, image: false, video: false, pdf: false }, - interleaved: false, - }, - cost: { - input: 0, - output: 0, - cache: { read: 0, write: 0 }, - }, - limit: { - context: 128000, - output: 4096, - }, - status: "active", - options: {}, - headers: {}, - release_date: "2026-01-01", - }, - }, -} - -describe("ACP next service sessions", () => { - const makeService = (messages: readonly { info: unknown; parts: readonly unknown[] }[] = []) => { - const updates: unknown[] = [] - const mcpAdds: string[] = [] - const sdk = { - config: { - providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), - get: () => Promise.resolve({ data: {} }), - }, - app: { - agents: () => - Promise.resolve({ - data: [ - { name: "build", mode: "primary", permission: [], options: {} }, - { name: "plan", mode: "primary", description: "Plan first", permission: [], options: {} }, - { name: "hidden", mode: "primary", hidden: true, permission: [], options: {} }, - ], - }), - skills: () => - Promise.resolve({ - data: [{ name: "review-skill", description: "Review", location: "/skills/review", content: "review" }], - }), - }, - command: { - list: () => - Promise.resolve({ - data: [{ name: "init", description: "Initialize", source: "command", template: "init", hints: [] }], - }), - }, - session: { - create: () => Promise.resolve({ data: { id: "ses_new" } }), - get: () => Promise.resolve({ data: { id: "ses_loaded" } }), - list: () => Promise.resolve({ data: [] }), - messages: () => Promise.resolve({ data: messages }), - }, - mcp: { - add: (input: { name?: string }) => { - if (input.name) mcpAdds.push(input.name) - return Promise.resolve({ data: {} }) - }, - }, - } as unknown as OpencodeClient - const connection = { - sessionUpdate: (update: unknown) => { - updates.push(update) - return Promise.resolve() - }, - } as Pick - - return { service: ACPNextService.make({ sdk, connection }), updates, mcpAdds } - } - - it("creates a backed session with config options and command update", async () => { - const { service, updates, mcpAdds } = makeService() - const result = await Effect.runPromise( - service.newSession({ - cwd: "/workspace", - mcpServers: [ - { name: "tools", command: "node", args: ["server.js"], env: [] }, - { name: "tools", command: "node", args: ["server.js"], env: [] }, - ], - }), - ) - - await new Promise((resolve) => setTimeout(resolve, 5)) - - expect(result.sessionId).toBe("ses_new") - expect(categories(result)).toContain("model") - expect(categories(result)).toContain("thought_level") - expect(categories(result)).toContain("mode") - expect(updates).toHaveLength(1) - expect(JSON.stringify(updates[0])).toContain("available_commands_update") - expect(JSON.stringify(updates[0])).toContain("review-skill") - expect(mcpAdds).toEqual(["tools"]) - }) - - it("loads a session and restores model variant and mode from messages", async () => { - const { service } = makeService([ - { - info: { - role: "assistant", - providerID: "test", - modelID: "test-model", - variant: "high", - mode: "plan", - }, - parts: [], - }, - ]) - const result = await Effect.runPromise( - service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] }), - ) - - expect(result.configOptions?.find((option) => option.id === "effort")?.currentValue).toBe("high") - expect(result.configOptions?.find((option) => option.id === "mode")?.currentValue).toBe("plan") - }) - - it("restores model variant and mode from the latest user message", async () => { - const { service } = makeService([ - { - info: { - role: "user", - model: { providerID: "test", modelID: "test-model", variant: "default" }, - agent: "build", - }, - parts: [], - }, - { - info: { - role: "user", - model: { providerID: "test", modelID: "test-model", variant: "high" }, - agent: "plan", - }, - parts: [], - }, - ]) - const result = await Effect.runPromise( - service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] }), - ) - - expect(result.configOptions?.find((option) => option.id === "effort")?.currentValue).toBe("high") - expect(result.configOptions?.find((option) => option.id === "mode")?.currentValue).toBe("plan") - }) - - it("maps provider auth failures to auth-required request errors", async () => { - const service = ACPNextService.make({ - sdk: { - config: { - providers: () => Promise.reject({ name: "ProviderAuthError", data: { providerID: "test" } }), - get: () => Promise.resolve({ data: {} }), - }, - app: { - agents: () => Promise.resolve({ data: [] }), - skills: () => Promise.resolve({ data: [] }), - }, - command: { - list: () => Promise.resolve({ data: [] }), - }, - } as unknown as OpencodeClient, - }) - const error = await Effect.runPromise( - service - .newSession({ cwd: "/workspace", mcpServers: [] }) - .pipe(Effect.mapError(ACPNextError.toRequestError), Effect.flip), - ) - - expect(error.code).toBe(-32000) - }) - - it("does not cache failed directory snapshots", async () => { - let providersCalls = 0 - const sdk = { - config: { - providers: () => { - providersCalls++ - if (providersCalls === 1) { - return Promise.reject({ name: "ProviderAuthError", data: { providerID: "test" } }) - } - return Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }) - }, - get: () => Promise.resolve({ data: {} }), - }, - app: { - agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), - skills: () => Promise.resolve({ data: [] }), - }, - command: { - list: () => Promise.resolve({ data: [] }), - }, - session: { - create: () => Promise.resolve({ data: { id: "ses_retry" } }), - list: () => Promise.resolve({ data: [] }), - }, - mcp: { - add: () => Promise.resolve({ data: {} }), - }, - } as unknown as OpencodeClient - const service = ACPNextService.make({ sdk }) - - const first = await Effect.runPromise( - service - .newSession({ cwd: "/workspace", mcpServers: [] }) - .pipe(Effect.mapError(ACPNextError.toRequestError), Effect.flip), - ) - const second = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) - - expect(first.code).toBe(-32000) - expect(second.sessionId).toBe("ses_retry") - expect(providersCalls).toBe(2) - }) - - it("registers same-name MCP servers again for different sessions or configs", async () => { - const adds: unknown[] = [] - let nextSession = 0 - const sdk = { - config: { - providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), - get: () => Promise.resolve({ data: {} }), - }, - app: { - agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), - skills: () => Promise.resolve({ data: [] }), - }, - command: { - list: () => Promise.resolve({ data: [] }), - }, - session: { - create: () => { - nextSession++ - return Promise.resolve({ data: { id: `ses_${nextSession}` } }) - }, - list: () => Promise.resolve({ data: [] }), - }, - mcp: { - add: (input: unknown) => { - adds.push(input) - return Promise.resolve({ data: {} }) - }, - }, - } as unknown as OpencodeClient - const service = ACPNextService.make({ sdk }) - - await Effect.runPromise( - service.newSession({ - cwd: "/workspace", - mcpServers: [{ name: "tools", command: "node", args: ["one.js"], env: [] }], - }), - ) - await Effect.runPromise( - service.newSession({ - cwd: "/workspace", - mcpServers: [{ name: "tools", command: "node", args: ["two.js"], env: [] }], - }), - ) - - expect(adds).toHaveLength(2) - expect(JSON.stringify(adds[0])).toContain("one.js") - expect(JSON.stringify(adds[1])).toContain("two.js") - }) - - it("uses the configured model as the new session default", async () => { - const sdk = { - config: { - providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), - get: () => Promise.resolve({ data: { model: "test/configured-model" } }), - }, - app: { - agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), - skills: () => Promise.resolve({ data: [] }), - }, - command: { - list: () => Promise.resolve({ data: [] }), - }, - session: { - create: (input: { model?: { id?: string } }) => Promise.resolve({ data: { id: input.model?.id } }), - list: () => Promise.resolve({ data: [] }), - }, - mcp: { - add: () => Promise.resolve({ data: {} }), - }, - } as unknown as OpencodeClient - const service = ACPNextService.make({ sdk }) - - const result = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) - - expect(result.sessionId).toBe("configured-model") - expect(result.configOptions?.find((option) => option.id === "model")?.currentValue).toBe("test/configured-model") - }) -}) - -function categories(result: NewSessionResponse | LoadSessionResponse) { - return result.configOptions?.map((option) => option.category) ?? [] -} diff --git a/packages/opencode/test/acp/agent-interface.test.ts b/packages/opencode/test/acp/agent-interface.test.ts deleted file mode 100644 index 7c4633d7d828..000000000000 --- a/packages/opencode/test/acp/agent-interface.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { ACP } from "../../src/acp/agent" -import type { Agent as ACPAgent } from "@agentclientprotocol/sdk" - -/** - * Type-level test: This line will fail to compile if ACP.Agent - * doesn't properly implement the ACPAgent interface. - * - * The SDK checks for methods like `agent.unstable_setSessionModel` at runtime - * and throws "Method not found" if they're missing. TypeScript allows optional - * interface methods to be omitted, but the SDK still expects them. - * - * @see https://github.com/agentclientprotocol/typescript-sdk/commit/7072d3f - */ -type _AssertAgentImplementsACPAgent = ACP.Agent extends ACPAgent ? true : never -const _typeCheck: _AssertAgentImplementsACPAgent = true - -/** - * Runtime verification that optional methods the SDK expects are actually implemented. - * The SDK's router checks `if (!agent.methodName)` and throws MethodNotFound if missing. - */ -describe("acp.agent interface compliance", () => { - // Extract method names from the ACPAgent interface type - type ACPAgentMethods = keyof ACPAgent - - // Methods that the SDK's router explicitly checks for at runtime - const sdkCheckedMethods: ACPAgentMethods[] = [ - // Required - "initialize", - "newSession", - "prompt", - "cancel", - // Optional but checked by SDK router - "loadSession", - "setSessionMode", - "authenticate", - // Capability-gated methods checked by the SDK router - "listSessions", - "resumeSession", - "closeSession", - "unstable_forkSession", - "unstable_setSessionModel", - ] - - test("Agent implements all SDK-checked methods", () => { - for (const method of sdkCheckedMethods) { - expect(typeof ACP.Agent.prototype[method as keyof typeof ACP.Agent.prototype], `Missing method: ${method}`).toBe( - "function", - ) - } - }) -}) diff --git a/packages/opencode/test/acp-next/config-option.test.ts b/packages/opencode/test/acp/config-option.test.ts similarity index 98% rename from packages/opencode/test/acp-next/config-option.test.ts rename to packages/opencode/test/acp/config-option.test.ts index d538ee81c01a..846cfadad67e 100644 --- a/packages/opencode/test/acp-next/config-option.test.ts +++ b/packages/opencode/test/acp/config-option.test.ts @@ -8,7 +8,7 @@ import { formatVariantName, parseModelSelection, type ConfigOptionProvider, -} from "@/acp-next/config-option" +} from "@/acp/config-option" const providers: ConfigOptionProvider[] = [ { @@ -46,7 +46,7 @@ const providers: ConfigOptionProvider[] = [ }, ] -describe("acp-next config options", () => { +describe("acp config options", () => { test("builds the model select option with ACP verifier category", () => { expect( buildModelSelectOption({ diff --git a/packages/opencode/test/acp-next/content.test.ts b/packages/opencode/test/acp/content.test.ts similarity index 97% rename from packages/opencode/test/acp-next/content.test.ts rename to packages/opencode/test/acp/content.test.ts index 88f8608345b1..90f62f9d1892 100644 --- a/packages/opencode/test/acp-next/content.test.ts +++ b/packages/opencode/test/acp/content.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from "bun:test" import type { ContentBlock } from "@agentclientprotocol/sdk" import { pathToFileURL } from "node:url" -import { contentBlockToParts, partsToContentChunks, promptContentToParts } from "../../src/acp-next/content" +import { contentBlockToParts, partsToContentChunks, promptContentToParts } from "../../src/acp/content" -describe("acp-next content conversion", () => { +describe("acp content conversion", () => { test("plain text block becomes a text part", () => { expect(contentBlockToParts({ type: "text", text: "hello" })).toEqual([{ type: "text", text: "hello" }]) }) @@ -158,7 +158,7 @@ describe("acp-next content conversion", () => { }) }) -describe("acp-next replay conversion", () => { +describe("acp replay conversion", () => { test("replays text audience annotations", () => { expect(partsToContentChunks([{ type: "text", text: "cached", synthetic: true }])).toEqual([ { diff --git a/packages/opencode/test/acp-next/directory.test.ts b/packages/opencode/test/acp/directory.test.ts similarity index 87% rename from packages/opencode/test/acp-next/directory.test.ts rename to packages/opencode/test/acp/directory.test.ts index 050ff06d45bb..5cc48d78ff23 100644 --- a/packages/opencode/test/acp-next/directory.test.ts +++ b/packages/opencode/test/acp/directory.test.ts @@ -1,7 +1,7 @@ import { describe, expect } from "bun:test" -import { Directory } from "@/acp-next/directory" +import { Directory } from "@/acp/directory" import { Command } from "@/command" -import { ModelID, ProviderID } from "@/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" import { Provider } from "@/provider/provider" import { Effect, Layer } from "effect" import { it } from "../lib/effect" @@ -13,8 +13,8 @@ const command = (name: string): Command.Info => ({ hints: [], }) -const model = (providerID: ProviderID, id: string, variants?: Directory.ModelVariants): Provider.Model => ({ - id: ModelID.make(id), +const model = (providerID: ProviderV2.ID, id: string, variants?: Directory.ModelVariants): Provider.Model => ({ + id: ProviderV2.ModelID.make(id), providerID, api: { id, @@ -49,8 +49,8 @@ const model = (providerID: ProviderID, id: string, variants?: Directory.ModelVar }) const snapshot = (directory: string) => { - const providerID = ProviderID.make(`provider-${directory}`) - const modelID = ModelID.make(`model-${directory}`) + const providerID = ProviderV2.ID.make(`provider-${directory}`) + const modelID = ProviderV2.ModelID.make(`model-${directory}`) const providers = { [providerID]: { id: providerID, @@ -63,10 +63,10 @@ const snapshot = (directory: string) => { low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, }), - [ModelID.make(`plain-${directory}`)]: model(providerID, `plain-${directory}`), + [ProviderV2.ModelID.make(`plain-${directory}`)]: model(providerID, `plain-${directory}`), }, }, - } satisfies Record + } satisfies Record return Directory.build({ directory, @@ -97,7 +97,7 @@ const fakeLayer = (calls: string[]) => ), ) -describe("ACP next directory snapshot", () => { +describe("ACP directory snapshot", () => { it.effect("two concurrent callers share one load", () => { const calls: string[] = [] return Effect.gen(function* () { @@ -148,7 +148,7 @@ describe("ACP next directory snapshot", () => { low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, }) - expect(directory.variants(alpha, { ...model, modelID: ModelID.make("missing") })).toBeUndefined() + expect(directory.variants(alpha, { ...model, modelID: ProviderV2.ModelID.make("missing") })).toBeUndefined() }).pipe(Effect.provide(fakeLayer([]))), ) diff --git a/packages/opencode/test/acp-next/error.test.ts b/packages/opencode/test/acp/error.test.ts similarity index 51% rename from packages/opencode/test/acp-next/error.test.ts rename to packages/opencode/test/acp/error.test.ts index a82c6c576e11..649f7d806ff0 100644 --- a/packages/opencode/test/acp-next/error.test.ts +++ b/packages/opencode/test/acp/error.test.ts @@ -1,35 +1,33 @@ import { describe, expect, test } from "bun:test" import { RequestError } from "@agentclientprotocol/sdk" -import * as ACPNextError from "../../src/acp-next/error" +import * as ACPError from "../../src/acp/error" -describe("acp-next.error", () => { +describe("acp.error", () => { test("maps validation failures to invalid params", () => { - const cases: ACPNextError.Error[] = [ - new ACPNextError.SessionNotFoundError({ sessionId: "ses_missing" }), - new ACPNextError.InvalidConfigOptionError({ configId: "temperature" }), - new ACPNextError.InvalidModelError({ providerId: "anthropic", modelId: "claude-missing" }), - new ACPNextError.InvalidEffortError({ effort: "extreme" }), - new ACPNextError.InvalidModeError({ mode: "turbo" }), + const cases: ACPError.Error[] = [ + new ACPError.SessionNotFoundError({ sessionId: "ses_missing" }), + new ACPError.InvalidConfigOptionError({ configId: "temperature" }), + new ACPError.InvalidModelError({ providerId: "anthropic", modelId: "claude-missing" }), + new ACPError.InvalidEffortError({ effort: "extreme" }), + new ACPError.InvalidModeError({ mode: "turbo" }), ] - expect(cases.map((error) => ACPNextError.toRequestError(error).code)).toEqual([ - -32602, -32602, -32602, -32602, -32602, - ]) + expect(cases.map((error) => ACPError.toRequestError(error).code)).toEqual([-32602, -32602, -32602, -32602, -32602]) }) test("includes safe validation details", () => { - expect(ACPNextError.toRequestError(new ACPNextError.SessionNotFoundError({ sessionId: "ses_123" }))).toMatchObject({ + expect(ACPError.toRequestError(new ACPError.SessionNotFoundError({ sessionId: "ses_123" }))).toMatchObject({ code: -32602, data: { sessionId: "ses_123" }, }) - expect(ACPNextError.toRequestError(new ACPNextError.InvalidModelError({ modelId: "gpt-missing" }))).toMatchObject({ + expect(ACPError.toRequestError(new ACPError.InvalidModelError({ modelId: "gpt-missing" }))).toMatchObject({ code: -32602, data: { modelId: "gpt-missing" }, }) }) test("maps auth required to the SDK auth error", () => { - const requestError = ACPNextError.toRequestError(new ACPNextError.AuthRequiredError({ providerId: "anthropic" })) + const requestError = ACPError.toRequestError(new ACPError.AuthRequiredError({ providerId: "anthropic" })) expect(requestError).toBeInstanceOf(RequestError) expect(requestError.code).toBe(-32000) @@ -38,17 +36,15 @@ describe("acp-next.error", () => { }) test("maps unsupported operations to method not found", () => { - const requestError = ACPNextError.toRequestError( - new ACPNextError.UnsupportedOperationError({ method: "session/new" }), - ) + const requestError = ACPError.toRequestError(new ACPError.UnsupportedOperationError({ method: "session/new" })) expect(requestError.code).toBe(-32601) expect(requestError.data).toEqual({ method: "session/new" }) }) test("maps service failures to safe internal errors", () => { - const requestError = ACPNextError.toRequestError( - new ACPNextError.ServiceFailureError({ service: "provider", safeMessage: "Provider request failed" }), + const requestError = ACPError.toRequestError( + new ACPError.ServiceFailureError({ service: "provider", safeMessage: "Provider request failed" }), ) expect(requestError.code).toBe(-32603) @@ -57,8 +53,8 @@ describe("acp-next.error", () => { }) test("wraps unknown defects without leaking raw details", () => { - const requestError = ACPNextError.toRequestError( - ACPNextError.fromUnknownDefect(new Error("stack has sk-ant-secret and oauth refresh token")), + const requestError = ACPError.toRequestError( + ACPError.fromUnknownDefect(new Error("stack has sk-ant-secret and oauth refresh token")), ) const serialized = JSON.stringify(requestError.toErrorResponse()) diff --git a/packages/opencode/test/acp/event-subscription.test.ts b/packages/opencode/test/acp/event-subscription.test.ts deleted file mode 100644 index a01680e30596..000000000000 --- a/packages/opencode/test/acp/event-subscription.test.ts +++ /dev/null @@ -1,977 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { ACP } from "../../src/acp/agent" -import type { AgentSideConnection } from "@agentclientprotocol/sdk" -import type { - Event, - EventMessagePartUpdated, - ToolStateCompleted, - ToolStatePending, - ToolStateRunning, -} from "@opencode-ai/sdk/v2" -import { provideTestInstance, tmpdir } from "../fixture/fixture" - -const pollUntil = async ( - check: () => T | undefined | false | Promise, - message: string, - opts?: { timeoutMs?: number; intervalMs?: number }, -): Promise => { - const timeoutMs = opts?.timeoutMs ?? 2000 - const intervalMs = opts?.intervalMs ?? 5 - const started = Date.now() - while (true) { - const v = await check() - if (v !== undefined && v !== null && v !== false) return v as T - if (Date.now() - started > timeoutMs) throw new Error(message) - await new Promise((r) => setTimeout(r, intervalMs)) - } -} - -type SessionUpdateParams = Parameters[0] -type RequestPermissionParams = Parameters[0] -type RequestPermissionResult = Awaited> - -type GlobalEventEnvelope = { - directory?: string - payload?: Event -} - -type EventController = { - push: (event: GlobalEventEnvelope) => void - close: () => void -} - -function inProgressText(update: SessionUpdateParams["update"]) { - if (update.sessionUpdate !== "tool_call_update") return undefined - if (update.status !== "in_progress") return undefined - if (!update.content || !Array.isArray(update.content)) return undefined - const first = update.content[0] - if (!first || first.type !== "content") return undefined - if (first.content.type !== "text") return undefined - return first.content.text -} - -function isToolCallUpdate( - update: SessionUpdateParams["update"], -): update is Extract { - return update.sessionUpdate === "tool_call_update" -} - -function completedToolUpdate(sessionUpdates: SessionUpdateParams[], sessionId: string, callID: string) { - return sessionUpdates - .filter((u) => u.sessionId === sessionId) - .map((u) => u.update) - .filter(isToolCallUpdate) - .find((u) => u.toolCallId === callID && u.status === "completed") -} - -function toolEvent( - sessionId: string, - cwd: string, - opts: { - callID: string - tool: string - input: Record - } & ({ status: "running"; metadata?: Record } | { status: "pending"; raw: string }), -): GlobalEventEnvelope { - const state: ToolStatePending | ToolStateRunning = - opts.status === "running" - ? { - status: "running", - input: opts.input, - ...(opts.metadata && { metadata: opts.metadata }), - time: { start: Date.now() }, - } - : { - status: "pending", - input: opts.input, - raw: opts.raw, - } - const payload: EventMessagePartUpdated = { - id: `evt_${opts.callID}`, - type: "message.part.updated", - properties: { - sessionID: sessionId, - time: Date.now(), - part: { - id: `part_${opts.callID}`, - sessionID: sessionId, - messageID: `msg_${opts.callID}`, - type: "tool", - callID: opts.callID, - tool: opts.tool, - state, - }, - }, - } - return { directory: cwd, payload } -} - -function completedToolEvent( - sessionId: string, - cwd: string, - opts: { - callID: string - tool: string - input: Record - output: string - attachments?: ToolStateCompleted["attachments"] - }, -): GlobalEventEnvelope { - const state: ToolStateCompleted = { - status: "completed", - input: opts.input, - output: opts.output, - title: opts.tool, - metadata: {}, - time: { start: Date.now() - 1, end: Date.now() }, - ...(opts.attachments && { attachments: opts.attachments }), - } - const payload: EventMessagePartUpdated = { - id: `evt_${opts.callID}`, - type: "message.part.updated", - properties: { - sessionID: sessionId, - time: Date.now(), - part: { - id: `part_${opts.callID}`, - sessionID: sessionId, - messageID: `msg_${opts.callID}`, - type: "tool", - callID: opts.callID, - tool: opts.tool, - state, - }, - }, - } - return { directory: cwd, payload } -} - -function createEventStream() { - const queue: GlobalEventEnvelope[] = [] - const waiters: Array<(value: GlobalEventEnvelope | undefined) => void> = [] - const state = { closed: false } - - const push = (event: GlobalEventEnvelope) => { - const waiter = waiters.shift() - if (waiter) { - waiter(event) - return - } - queue.push(event) - } - - const close = () => { - state.closed = true - for (const waiter of waiters.splice(0)) { - waiter(undefined) - } - } - - const stream = async function* (signal?: AbortSignal) { - while (true) { - if (signal?.aborted) return - const next = queue.shift() - if (next) { - yield next - continue - } - if (state.closed) return - const value = await new Promise((resolve) => { - waiters.push(resolve) - if (!signal) return - signal.addEventListener("abort", () => resolve(undefined), { once: true }) - }) - if (!value) return - yield value - } - } - - return { controller: { push, close } satisfies EventController, stream } -} - -function createFakeAgent() { - const updates = new Map() - const chunks = new Map() - const sessionUpdates: SessionUpdateParams[] = [] - const record = (sessionId: string, type: string) => { - const list = updates.get(sessionId) ?? [] - list.push(type) - updates.set(sessionId, list) - } - - const connection = { - async sessionUpdate(params: SessionUpdateParams) { - sessionUpdates.push(params) - const update = params.update - const type = update?.sessionUpdate ?? "unknown" - record(params.sessionId, type) - if (update?.sessionUpdate === "agent_message_chunk") { - const content = update.content - if (content?.type !== "text") return - if (typeof content.text !== "string") return - chunks.set(params.sessionId, (chunks.get(params.sessionId) ?? "") + content.text) - } - }, - async requestPermission(_params: RequestPermissionParams): Promise { - return { outcome: { outcome: "selected", optionId: "once" } } as RequestPermissionResult - }, - } as unknown as AgentSideConnection - - const { controller, stream } = createEventStream() - const calls = { - eventSubscribe: 0, - sessionCreate: 0, - } - - const sdk = { - global: { - event: async (opts?: { signal?: AbortSignal }) => { - calls.eventSubscribe++ - return { stream: stream(opts?.signal) } - }, - }, - session: { - create: async (_params?: any) => { - calls.sessionCreate++ - return { - data: { - id: `ses_${calls.sessionCreate}`, - time: { created: new Date().toISOString() }, - }, - } - }, - get: async (_params?: any) => { - return { - data: { - id: "ses_1", - time: { created: new Date().toISOString() }, - }, - } - }, - messages: async () => { - return { data: [] } - }, - message: async (params?: any) => { - // Return a message with parts that can be looked up by partID - return { - data: { - info: { - role: "assistant", - }, - parts: [ - { - id: params?.messageID ? `${params.messageID}_part` : "part_1", - type: "text", - text: "", - }, - ], - }, - } - }, - }, - permission: { - respond: async () => { - return { data: true } - }, - }, - config: { - providers: async () => { - return { - data: { - providers: [ - { - id: "opencode", - name: "opencode", - models: { - "big-pickle": { id: "big-pickle", name: "big-pickle" }, - }, - }, - ], - }, - } - }, - }, - app: { - agents: async () => { - return { - data: [ - { - name: "build", - description: "build", - mode: "agent", - }, - ], - } - }, - }, - command: { - list: async () => { - return { data: [] } - }, - }, - mcp: { - add: async () => { - return { data: true } - }, - }, - } as any - - const agent = new ACP.Agent(connection, { - sdk, - defaultModel: { providerID: "opencode", modelID: "big-pickle" }, - } as any) - - const stop = () => { - controller.close() - ;(agent as any).eventAbort.abort() - } - - return { agent, controller, calls, updates, chunks, sessionUpdates, stop, sdk, connection } -} - -describe("acp.agent event subscription", () => { - test("routes message.part.delta by the event sessionID (no cross-session pollution)", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, updates, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - - const sessionA = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const sessionB = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - controller.push({ - directory: cwd, - payload: { - type: "message.part.delta", - properties: { - sessionID: sessionB, - messageID: "msg_1", - partID: "msg_1_part", - field: "text", - delta: "hello", - }, - }, - } as any) - - await pollUntil( - () => (updates.get(sessionB) ?? []).includes("agent_message_chunk"), - "sessionB never received agent_message_chunk", - ) - - expect((updates.get(sessionA) ?? []).includes("agent_message_chunk")).toBe(false) - expect((updates.get(sessionB) ?? []).includes("agent_message_chunk")).toBe(true) - - stop() - }, - }) - }) - - test("does not emit user_message_chunk for live prompt parts", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, sessionUpdates, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - controller.push({ - directory: cwd, - payload: { - type: "message.part.updated", - properties: { - sessionID: sessionId, - time: Date.now(), - part: { - id: "part_1", - sessionID: sessionId, - messageID: "msg_user", - type: "text", - text: "hello", - }, - }, - }, - } as any) - - controller.push({ - directory: cwd, - payload: { - type: "message.part.delta", - properties: { - sessionID: sessionId, - messageID: "msg_marker", - partID: "msg_marker_part", - field: "text", - delta: "marker", - }, - }, - } as any) - - await pollUntil( - () => - sessionUpdates.some((u) => u.sessionId === sessionId && u.update.sessionUpdate === "agent_message_chunk"), - "marker event was never processed", - ) - - expect( - sessionUpdates - .filter((u) => u.sessionId === sessionId) - .some((u) => u.update.sessionUpdate === "user_message_chunk"), - ).toBe(false) - - stop() - }, - }) - }) - - test("keeps concurrent sessions isolated when message.part.delta events are interleaved", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, chunks, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - - const sessionA = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const sessionB = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - const tokenA = ["ALPHA_", "111", "_X"] - const tokenB = ["BETA_", "222", "_Y"] - - const push = (sessionId: string, messageID: string, delta: string) => { - controller.push({ - directory: cwd, - payload: { - type: "message.part.delta", - properties: { - sessionID: sessionId, - messageID, - partID: `${messageID}_part`, - field: "text", - delta, - }, - }, - } as any) - } - - push(sessionA, "msg_a", tokenA[0]) - push(sessionB, "msg_b", tokenB[0]) - push(sessionA, "msg_a", tokenA[1]) - push(sessionB, "msg_b", tokenB[1]) - push(sessionA, "msg_a", tokenA[2]) - push(sessionB, "msg_b", tokenB[2]) - - await pollUntil( - () => - (chunks.get(sessionA) ?? "").includes(tokenA.join("")) && - (chunks.get(sessionB) ?? "").includes(tokenB.join("")), - "interleaved chunks never fully arrived", - ) - - const a = chunks.get(sessionA) ?? "" - const b = chunks.get(sessionB) ?? "" - - expect(a).toContain(tokenA.join("")) - expect(b).toContain(tokenB.join("")) - for (const part of tokenB) expect(a).not.toContain(part) - for (const part of tokenA) expect(b).not.toContain(part) - - stop() - }, - }) - }) - - test("does not create additional event subscriptions on repeated loadSession()", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, calls, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - await agent.loadSession({ sessionId, cwd, mcpServers: [] } as any) - await agent.loadSession({ sessionId, cwd, mcpServers: [] } as any) - await agent.loadSession({ sessionId, cwd, mcpServers: [] } as any) - await agent.loadSession({ sessionId, cwd, mcpServers: [] } as any) - - expect(calls.eventSubscribe).toBe(1) - - stop() - }, - }) - }) - - test("permission.asked events are handled and replied", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const permissionReplies: string[] = [] - const { agent, controller, stop, sdk } = createFakeAgent() - sdk.permission.reply = async (params: any) => { - permissionReplies.push(params.requestID) - return { data: true } - } - const cwd = "/tmp/opencode-acp-test" - - const sessionA = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - controller.push({ - directory: cwd, - payload: { - type: "permission.asked", - properties: { - id: "perm_1", - sessionID: sessionA, - permission: "bash", - patterns: ["*"], - metadata: {}, - always: [], - }, - }, - } as any) - - await pollUntil(() => permissionReplies.includes("perm_1"), "perm_1 was never replied") - - expect(permissionReplies).toContain("perm_1") - - stop() - }, - }) - }) - - test("permission prompt on session A does not block message updates for session B", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const permissionReplies: string[] = [] - let resolvePermissionA: (() => void) | undefined - const permissionABlocking = new Promise((r) => { - resolvePermissionA = r - }) - - const { agent, controller, chunks, stop, sdk, connection } = createFakeAgent() - - // Make permission request for session A block until we release it - const originalRequestPermission = connection.requestPermission.bind(connection) - let _permissionCalls = 0 - connection.requestPermission = async (params: RequestPermissionParams) => { - _permissionCalls++ - if (params.sessionId.endsWith("1")) { - await permissionABlocking - } - return originalRequestPermission(params) - } - - sdk.permission.reply = async (params: any) => { - permissionReplies.push(params.requestID) - return { data: true } - } - - const cwd = "/tmp/opencode-acp-test" - - const sessionA = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const sessionB = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - // Push permission.asked for session A (will block) - controller.push({ - directory: cwd, - payload: { - type: "permission.asked", - properties: { - id: "perm_a", - sessionID: sessionA, - permission: "bash", - patterns: ["*"], - metadata: {}, - always: [], - }, - }, - } as any) - - await pollUntil(() => _permissionCalls > 0, "permission handling for A never started") - - controller.push({ - directory: cwd, - payload: { - type: "message.part.delta", - properties: { - sessionID: sessionB, - messageID: "msg_b", - partID: "msg_b_part", - field: "text", - delta: "session_b_message", - }, - }, - } as any) - - await pollUntil( - () => (chunks.get(sessionB) ?? "").includes("session_b_message"), - "session B never received its message", - ) - - expect(chunks.get(sessionB) ?? "").toContain("session_b_message") - expect(permissionReplies).not.toContain("perm_a") - - resolvePermissionA!() - await pollUntil(() => permissionReplies.includes("perm_a"), "perm_a was never replied after release") - - expect(permissionReplies).toContain("perm_a") - - stop() - }, - }) - }) - - test("streams running bash output snapshots and de-dupes identical snapshots", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, sessionUpdates, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const input = { command: "echo hello", description: "run command" } - - for (const output of ["a", "a", "ab"]) { - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_1", - tool: "bash", - status: "running", - input, - metadata: { output }, - }), - ) - } - await pollUntil( - () => - sessionUpdates - .filter((u) => u.sessionId === sessionId) - .filter((u) => isToolCallUpdate(u.update)) - .map((u) => inProgressText(u.update)) - .filter((t) => t === "ab").length > 0, - "final bash snapshot 'ab' never arrived", - ) - - const snapshots = sessionUpdates - .filter((u) => u.sessionId === sessionId) - .filter((u) => isToolCallUpdate(u.update)) - .map((u) => inProgressText(u.update)) - - expect(snapshots).toEqual(["a", undefined, "ab"]) - stop() - }, - }) - }) - - test("emits synthetic pending before first running update for any tool", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, sessionUpdates, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_bash", - tool: "bash", - status: "running", - input: { command: "echo hi", description: "run command" }, - metadata: { output: "hi\n" }, - }), - ) - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_read", - tool: "read", - status: "running", - input: { filePath: "/tmp/example.txt" }, - }), - ) - await pollUntil( - () => - sessionUpdates - .filter((u) => u.sessionId === sessionId) - .map((u) => u.update.sessionUpdate) - .filter((u) => u === "tool_call" || u === "tool_call_update").length >= 4, - "expected 4 tool_call/tool_call_update events", - ) - - const types = sessionUpdates - .filter((u) => u.sessionId === sessionId) - .map((u) => u.update.sessionUpdate) - .filter((u) => u === "tool_call" || u === "tool_call_update") - expect(types).toEqual(["tool_call", "tool_call_update", "tool_call", "tool_call_update"]) - - const pendings = sessionUpdates.filter( - (u) => u.sessionId === sessionId && u.update.sessionUpdate === "tool_call", - ) - expect(pendings.every((p) => p.update.sessionUpdate === "tool_call" && p.update.status === "pending")).toBe( - true, - ) - stop() - }, - }) - }) - - test("emits image attachments as ACP tool content blocks on live completed tool updates", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, sessionUpdates, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const data = Buffer.from("image-data").toString("base64") - - controller.push( - completedToolEvent(sessionId, cwd, { - callID: "call_image", - tool: "read", - input: { filePath: "/tmp/image.png" }, - output: "Image read successfully", - attachments: [ - { - id: "part_image", - sessionID: sessionId, - messageID: "msg_image", - type: "file", - mime: "image/png", - filename: "image.png", - url: `data:image/png;base64,${data}`, - }, - { - id: "part_text", - sessionID: sessionId, - messageID: "msg_image", - type: "file", - mime: "text/plain", - filename: "note.txt", - url: "data:text/plain;base64,Zm9v", - }, - ], - }), - ) - await pollUntil( - () => completedToolUpdate(sessionUpdates, sessionId, "call_image"), - "completed tool update for call_image never arrived", - ) - - const update = completedToolUpdate(sessionUpdates, sessionId, "call_image") - expect(update?.content).toContainEqual({ - type: "content", - content: { type: "text", text: "Image read successfully" }, - }) - expect(update?.content).toContainEqual({ - type: "content", - content: { type: "image", mimeType: "image/png", data }, - }) - expect(update?.content?.some((item) => item.type === "content" && item.content.type === "resource")).toBe(false) - expect((update?.rawOutput as { attachments?: unknown[] } | undefined)?.attachments?.length).toBe(2) - - stop() - }, - }) - }) - - test("replays completed tool image attachments as ACP tool content blocks", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, sessionUpdates, stop, sdk } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const data = Buffer.from("replay-image").toString("base64") - - sdk.session.messages = async () => ({ - data: [ - { - info: { - role: "assistant", - sessionID: sessionId, - }, - parts: [ - { - id: "part_replay", - sessionID: sessionId, - messageID: "msg_replay", - type: "tool", - callID: "call_replay_image", - tool: "webfetch", - state: { - status: "completed", - input: { url: "https://example.com/image.png" }, - output: "Image fetched successfully", - title: "webfetch", - metadata: {}, - time: { start: Date.now() - 1, end: Date.now() }, - attachments: [ - { - id: "part_replay_image", - sessionID: sessionId, - messageID: "msg_replay", - type: "file", - mime: "image/jpeg", - filename: "image.jpg", - url: `data:image/jpeg;base64,${data}`, - }, - ], - }, - }, - ], - }, - ], - }) - - await agent.loadSession({ sessionId, cwd, mcpServers: [] } as any) - - const update = completedToolUpdate(sessionUpdates, sessionId, "call_replay_image") - expect(update?.content).toContainEqual({ - type: "content", - content: { type: "text", text: "Image fetched successfully" }, - }) - expect(update?.content).toContainEqual({ - type: "content", - content: { type: "image", mimeType: "image/jpeg", data }, - }) - - stop() - }, - }) - }) - - test("does not emit duplicate synthetic pending after replayed running tool", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, sessionUpdates, stop, sdk } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const input = { command: "echo hi", description: "run command" } - - sdk.session.messages = async () => ({ - data: [ - { - info: { - role: "assistant", - sessionID: sessionId, - }, - parts: [ - { - type: "tool", - callID: "call_1", - tool: "bash", - state: { - status: "running", - input, - metadata: { output: "hi\n" }, - time: { start: Date.now() }, - }, - }, - ], - }, - ], - }) - - await agent.loadSession({ sessionId, cwd, mcpServers: [] } as any) - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_1", - tool: "bash", - status: "running", - input, - metadata: { output: "hi\nthere\n" }, - }), - ) - await pollUntil( - () => - sessionUpdates - .filter((u) => u.sessionId === sessionId) - .map((u) => u.update) - .filter((u) => "toolCallId" in u && u.toolCallId === "call_1") - .map((u) => u.sessionUpdate) - .filter((u) => u === "tool_call" || u === "tool_call_update").length >= 3, - "expected 3 tool events for call_1", - ) - - const types = sessionUpdates - .filter((u) => u.sessionId === sessionId) - .map((u) => u.update) - .filter((u) => "toolCallId" in u && u.toolCallId === "call_1") - .map((u) => u.sessionUpdate) - .filter((u) => u === "tool_call" || u === "tool_call_update") - - expect(types).toEqual(["tool_call", "tool_call_update", "tool_call_update"]) - stop() - }, - }) - }) - - test("clears bash snapshot marker on pending state", async () => { - await using tmp = await tmpdir() - await provideTestInstance({ - directory: tmp.path, - fn: async () => { - const { agent, controller, sessionUpdates, stop } = createFakeAgent() - const cwd = "/tmp/opencode-acp-test" - const sessionId = await agent.newSession({ cwd, mcpServers: [] } as any).then((x) => x.sessionId) - const input = { command: "echo hello", description: "run command" } - - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_1", - tool: "bash", - status: "running", - input, - metadata: { output: "a" }, - }), - ) - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_1", - tool: "bash", - status: "pending", - input, - raw: '{"command":"echo hello"}', - }), - ) - controller.push( - toolEvent(sessionId, cwd, { - callID: "call_1", - tool: "bash", - status: "running", - input, - metadata: { output: "a" }, - }), - ) - await pollUntil( - () => - sessionUpdates - .filter((u) => u.sessionId === sessionId) - .filter((u) => isToolCallUpdate(u.update)) - .map((u) => inProgressText(u.update)) - .filter((t) => t === "a").length >= 2, - "expected two 'a' bash snapshots after pending reset", - ) - - const snapshots = sessionUpdates - .filter((u) => u.sessionId === sessionId) - .filter((u) => isToolCallUpdate(u.update)) - .map((u) => inProgressText(u.update)) - - expect(snapshots).toEqual(["a", "a"]) - stop() - }, - }) - }) -}) diff --git a/packages/opencode/test/acp/event.test.ts b/packages/opencode/test/acp/event.test.ts new file mode 100644 index 000000000000..c79baf035e0a --- /dev/null +++ b/packages/opencode/test/acp/event.test.ts @@ -0,0 +1,657 @@ +import { describe, expect, it } from "bun:test" +import type { AgentSideConnection } from "@agentclientprotocol/sdk" +import type { Event, Message, OpencodeClient, Part, SessionMessageResponse, ToolPart } from "@opencode-ai/sdk/v2" +import { Effect, ManagedRuntime } from "effect" +import { ACPEvent } from "@/acp/event" +import * as ACPService from "@/acp/service" +import { Directory } from "@/acp/directory" +import { ACPSession } from "@/acp/session" + +type SessionUpdateParams = Parameters[0] +type ToolSessionUpdateParams = SessionUpdateParams & { + update: Extract +} +type GlobalEventEnvelope = { + payload?: Event +} +type DeltaPartType = Extract["type"] + +const pollUntil = async ( + check: () => boolean | Promise, + message: string, + opts?: { timeoutMs?: number; intervalMs?: number }, +) => { + const started = Date.now() + while (true) { + if (await check()) return + if (Date.now() - started > (opts?.timeoutMs ?? 2000)) throw new Error(message) + await new Promise((resolve) => setTimeout(resolve, opts?.intervalMs ?? 5)) + } +} + +function makeSessionService() { + return ManagedRuntime.make(ACPSession.defaultLayer).runSync( + ACPSession.Service.use((service) => Effect.succeed(service)), + ) +} + +function createEventStream() { + const queue: GlobalEventEnvelope[] = [] + const waiters: Array<(value: GlobalEventEnvelope | undefined) => void> = [] + const state = { closed: false } + + const push = (event: GlobalEventEnvelope) => { + const waiter = waiters.shift() + if (waiter) { + waiter(event) + return + } + queue.push(event) + } + + const close = () => { + state.closed = true + for (const waiter of waiters.splice(0)) { + waiter(undefined) + } + } + + const stream = async function* (signal?: AbortSignal) { + while (true) { + if (signal?.aborted) return + const next = queue.shift() + if (next) { + yield next + continue + } + if (state.closed) return + const value = await new Promise((resolve) => { + waiters.push(resolve) + signal?.addEventListener("abort", () => resolve(undefined), { once: true }) + }) + if (!value) return + yield value + } + } + + return { push, close, stream } +} + +function createHarness(messages: Record = {}) { + const updates: SessionUpdateParams[] = [] + const calls = { + eventSubscribe: 0, + message: 0, + } + const events = createEventStream() + const sdk = { + global: { + event: (options?: { signal?: AbortSignal }) => { + calls.eventSubscribe++ + return Promise.resolve({ stream: events.stream(options?.signal) }) + }, + }, + session: { + message: (input: { messageID: string }) => { + calls.message++ + return Promise.resolve({ data: messages[input.messageID] }) + }, + get: () => Promise.resolve({ data: { id: "ses_loaded" } }), + messages: () => Promise.resolve({ data: [] }), + }, + } as unknown as OpencodeClient + const connection = { + sessionUpdate: (params: SessionUpdateParams) => { + updates.push(params) + return Promise.resolve() + }, + } satisfies Pick + const session = makeSessionService() + const subscription = new ACPEvent.Subscription({ sdk, connection, session }) + + return { calls, connection, events, sdk, session, subscription, updates } +} + +function textDelta(sessionID: string, messageID: string, partID: string, delta: string): Event { + return { + id: `evt_${sessionID}_${messageID}_${partID}_${delta}`, + type: "message.part.delta", + properties: { + sessionID, + messageID, + partID, + field: "text", + delta, + }, + } +} + +function partUpdated(sessionID: string, messageID: string, partID: string, type: DeltaPartType): Event { + return { + id: `evt_${sessionID}_${messageID}_${partID}`, + type: "message.part.updated", + properties: { + sessionID, + time: Date.now(), + part: + type === "text" + ? { + id: partID, + sessionID, + messageID, + type: "text", + text: "", + } + : { + id: partID, + sessionID, + messageID, + type: "reasoning", + text: "", + time: { start: Date.now() }, + }, + }, + } +} + +function toolUpdated(part: ToolPart): Event { + return { + id: `evt_${part.sessionID}_${part.messageID}_${part.id}_${part.state.status}`, + type: "message.part.updated", + properties: { + sessionID: part.sessionID, + time: Date.now(), + part, + }, + } +} + +function assistantMessage(sessionID: string, messageID: string, partID: string, type: DeltaPartType) { + return { + info: { + id: messageID, + sessionID, + role: "assistant", + time: { created: Date.now() }, + parentID: "msg_parent", + modelID: "model", + providerID: "provider", + mode: "build", + agent: "build", + path: { cwd: "/workspace", root: "/workspace" }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + }, + parts: [ + type === "text" + ? { + id: partID, + sessionID, + messageID, + type: "text", + text: "", + } + : { + id: partID, + sessionID, + messageID, + type: "reasoning", + text: "", + time: { start: Date.now() }, + }, + ], + } satisfies SessionMessageResponse +} + +function assistantToolMessage(part: ToolPart) { + return { + info: { + id: part.messageID, + sessionID: part.sessionID, + role: "assistant", + time: { created: Date.now() }, + parentID: "msg_parent", + modelID: "model", + providerID: "provider", + mode: "build", + agent: "build", + path: { cwd: "/workspace", root: "/workspace" }, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + }, + parts: [part], + } satisfies SessionMessageResponse +} + +function runningTool( + sessionID: string, + callID: string, + output?: string, + input: Record = { cmd: "printf hello" }, +) { + return { + id: `part_${callID}`, + sessionID, + messageID: `msg_${callID}`, + type: "tool", + callID, + tool: "bash", + state: { + status: "running", + input, + title: "bash", + ...(output !== undefined ? { metadata: { output } } : {}), + time: { start: Date.now() }, + }, + } satisfies ToolPart +} + +function completedTool( + sessionID: string, + callID: string, + output = "done", + attachments: Extract["attachments"] = [], +) { + return { + id: `part_${callID}`, + sessionID, + messageID: `msg_${callID}`, + type: "tool", + callID, + tool: "bash", + state: { + status: "completed", + input: { cmd: "printf done" }, + output, + title: "bash", + metadata: { exit: 0 }, + time: { start: Date.now() - 1, end: Date.now() }, + ...(attachments.length ? { attachments } : {}), + }, + } satisfies ToolPart +} + +function errorTool(sessionID: string, callID: string) { + return { + id: `part_${callID}`, + sessionID, + messageID: `msg_${callID}`, + type: "tool", + callID, + tool: "bash", + state: { + status: "error", + input: { cmd: "exit 1" }, + error: "failed hard", + metadata: { exit: 1 }, + time: { start: Date.now() - 1, end: Date.now() }, + }, + } satisfies ToolPart +} + +function toolUpdates(updates: SessionUpdateParams[]) { + return updates.filter((item): item is ToolSessionUpdateParams => { + return item.update.sessionUpdate === "tool_call" || item.update.sessionUpdate === "tool_call_update" + }) +} + +async function createKnownSession( + session: ACPSession.Interface, + sessionId: string, + part: { messageId: string; partId: string; partType: Part["type"]; role?: Message["role"] }, +) { + await Effect.runPromise(session.create({ id: sessionId, cwd: "/workspace" })) + await Effect.runPromise( + session.recordPartMetadata({ + sessionId, + messageId: part.messageId, + partId: part.partId, + partType: part.partType, + role: part.role ?? "assistant", + }), + ) +} + +describe("acp event routing", () => { + it("routes message.part.delta by sessionID without cross-session pollution", async () => { + const harness = createHarness() + await createKnownSession(harness.session, "ses_a", { messageId: "msg_a", partId: "part_a", partType: "text" }) + await createKnownSession(harness.session, "ses_b", { messageId: "msg_b", partId: "part_b", partType: "text" }) + + await harness.subscription.handle(textDelta("ses_b", "msg_b", "part_b", "hello")) + + expect(harness.updates.map((update) => update.sessionId)).toEqual(["ses_b"]) + expect(harness.updates[0]?.update.sessionUpdate).toBe("agent_message_chunk") + }) + + it("keeps interleaved sessions isolated for text and reasoning deltas", async () => { + const harness = createHarness() + await createKnownSession(harness.session, "ses_a", { messageId: "msg_a", partId: "part_a", partType: "text" }) + await createKnownSession(harness.session, "ses_b", { + messageId: "msg_b", + partId: "part_b", + partType: "reasoning", + }) + + await harness.subscription.handle(textDelta("ses_a", "msg_a", "part_a", "A1")) + await harness.subscription.handle(textDelta("ses_b", "msg_b", "part_b", "B1")) + await harness.subscription.handle(textDelta("ses_a", "msg_a", "part_a", "A2")) + await harness.subscription.handle(textDelta("ses_b", "msg_b", "part_b", "B2")) + + expect( + harness.updates.filter((update) => update.sessionId === "ses_a").map((update) => update.update.sessionUpdate), + ).toEqual(["agent_message_chunk", "agent_message_chunk"]) + expect( + harness.updates.filter((update) => update.sessionId === "ses_b").map((update) => update.update.sessionUpdate), + ).toEqual(["agent_thought_chunk", "agent_thought_chunk"]) + }) + + it("does not create extra subscriptions on repeated loadSession", async () => { + const harness = createHarness() + let subscription: ACPEvent.Subscription | undefined + const service = ACPService.make({ + sdk: harness.sdk, + connection: harness.connection, + directory: { + get: () => + Effect.succeed( + Directory.build({ + directory: "/workspace", + providers: {}, + modes: [], + defaultModeID: "build", + commands: [], + }), + ), + refresh: () => + Effect.succeed( + Directory.build({ + directory: "/workspace", + providers: {}, + modes: [], + defaultModeID: "build", + commands: [], + }), + ), + variants: Directory.variants, + }, + session: harness.session, + eventSubscription: (started) => { + subscription = started + }, + }) + + await pollUntil(() => harness.calls.eventSubscribe === 1, "event subscription did not start") + await Effect.runPromise(service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] })) + await Effect.runPromise(service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] })) + await Effect.runPromise(service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] })) + + expect(harness.calls.eventSubscribe).toBe(1) + subscription?.stop() + harness.events.close() + }) + + it("does not call sdk.session.message repeatedly when metadata is known", async () => { + const harness = createHarness() + await createKnownSession(harness.session, "ses_a", { messageId: "msg_a", partId: "part_a", partType: "text" }) + + for (const delta of ["a", "b", "c", "d", "e"]) { + await harness.subscription.handle(textDelta("ses_a", "msg_a", "part_a", delta)) + } + + expect(harness.calls.message).toBe(0) + expect(harness.updates).toHaveLength(5) + }) + + it("fetches unknown part metadata once and reuses it for later deltas", async () => { + const harness = createHarness({ + msg_a: assistantMessage("ses_a", "msg_a", "part_a", "text"), + }) + await Effect.runPromise(harness.session.create({ id: "ses_a", cwd: "/workspace" })) + + await harness.subscription.handle(partUpdated("ses_a", "msg_a", "part_a", "text")) + await harness.subscription.handle(textDelta("ses_a", "msg_a", "part_a", "a")) + await harness.subscription.handle(textDelta("ses_a", "msg_a", "part_a", "b")) + + expect(harness.calls.message).toBe(1) + expect(harness.updates).toHaveLength(2) + }) + + it("replays loaded session messages sequentially and continues after update failures", async () => { + const events = createEventStream() + const updates: SessionUpdateParams[] = [] + const connection = { + sessionUpdate: (params: SessionUpdateParams) => { + if (params.update.sessionUpdate === "tool_call" && params.update.toolCallId === "call_slow") { + return new Promise((resolve) => { + setTimeout(() => { + updates.push(params) + resolve() + }, 20) + }) + } + + if (params.update.sessionUpdate === "tool_call_update" && params.update.toolCallId === "call_slow") { + return Promise.reject(new Error("replay send failed")) + } + + updates.push(params) + return Promise.resolve() + }, + } satisfies Pick + let subscription: ACPEvent.Subscription | undefined + const service = ACPService.make({ + sdk: { + global: { + event: (options?: { signal?: AbortSignal }) => Promise.resolve({ stream: events.stream(options?.signal) }), + }, + session: { + get: () => Promise.resolve({ data: { id: "ses_loaded" } }), + messages: () => + Promise.resolve({ + data: [ + assistantToolMessage(completedTool("ses_loaded", "call_slow", "slow")), + assistantToolMessage(completedTool("ses_loaded", "call_after", "after")), + ], + }), + }, + } as unknown as OpencodeClient, + connection, + directory: { + get: () => + Effect.succeed( + Directory.build({ + directory: "/workspace", + providers: {}, + modes: [], + defaultModeID: "build", + commands: [], + }), + ), + refresh: () => + Effect.succeed( + Directory.build({ + directory: "/workspace", + providers: {}, + modes: [], + defaultModeID: "build", + commands: [], + }), + ), + variants: Directory.variants, + }, + eventSubscription: (started) => { + subscription = started + }, + }) + + await Effect.runPromise(service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] })) + + expect(toolUpdates(updates).map((item) => item.update.toolCallId)).toEqual([ + "call_slow", + "call_after", + "call_after", + ]) + subscription?.stop() + events.close() + }) + + it("ignores unknown sessions and live user parts without user_message_chunk duplication", async () => { + const harness = createHarness() + await createKnownSession(harness.session, "ses_user", { + messageId: "msg_user", + partId: "part_user", + partType: "text", + role: "user", + }) + + await harness.subscription.handle(textDelta("ses_missing", "msg_missing", "part_missing", "ignored")) + await harness.subscription.handle(partUpdated("ses_user", "msg_user", "part_live", "text")) + await harness.subscription.handle(textDelta("ses_user", "msg_user", "part_user", "hello")) + + expect(harness.updates).toHaveLength(0) + }) + + it("emits synthetic pending before the first running tool update", async () => { + const harness = createHarness() + await Effect.runPromise(harness.session.create({ id: "ses_tool", cwd: "/workspace" })) + + await harness.subscription.handle(toolUpdated(runningTool("ses_tool", "call_1", "hello"))) + + expect(toolUpdates(harness.updates).map((item) => item.update.sessionUpdate)).toEqual([ + "tool_call", + "tool_call_update", + ]) + expect(harness.updates[0]?.update).toMatchObject({ status: "pending", toolCallId: "call_1" }) + expect(harness.updates[1]?.update).toMatchObject({ status: "in_progress", toolCallId: "call_1" }) + }) + + it("does not emit duplicate synthetic pending after a replayed running tool", async () => { + const harness = createHarness() + await Effect.runPromise(harness.session.create({ id: "ses_replay", cwd: "/workspace" })) + + await harness.subscription.replayMessage(assistantToolMessage(runningTool("ses_replay", "call_replay", "first"))) + await harness.subscription.handle(toolUpdated(runningTool("ses_replay", "call_replay", "second"))) + + expect(toolUpdates(harness.updates).filter((item) => item.update.sessionUpdate === "tool_call")).toHaveLength(1) + expect(toolUpdates(harness.updates).map((item) => item.update.sessionUpdate)).toEqual([ + "tool_call", + "tool_call_update", + "tool_call_update", + ]) + }) + + it("dedupes shell output snapshots while still sending status-only running updates", async () => { + const harness = createHarness() + await Effect.runPromise(harness.session.create({ id: "ses_shell", cwd: "/workspace" })) + + await harness.subscription.handle(toolUpdated(runningTool("ses_shell", "call_shell", "same"))) + await harness.subscription.handle(toolUpdated(runningTool("ses_shell", "call_shell", "same"))) + + const updates = toolUpdates(harness.updates) + expect(updates).toHaveLength(3) + expect(updates[1]?.update).toMatchObject({ + sessionUpdate: "tool_call_update", + content: [{ type: "content", content: { type: "text", text: "same" } }], + }) + expect(updates[2]?.update).toMatchObject({ sessionUpdate: "tool_call_update", status: "in_progress" }) + expect("content" in updates[2]!.update).toBe(false) + }) + + it("clears shell snapshot marker when a tool returns to pending", async () => { + const harness = createHarness() + await Effect.runPromise(harness.session.create({ id: "ses_pending", cwd: "/workspace" })) + + await harness.subscription.handle(toolUpdated(runningTool("ses_pending", "call_pending", "repeat"))) + await harness.subscription.handle( + toolUpdated({ + id: "part_call_pending", + sessionID: "ses_pending", + messageID: "msg_call_pending", + type: "tool", + callID: "call_pending", + tool: "bash", + state: { + status: "pending", + input: { cmd: "printf repeat" }, + raw: '{"cmd":"printf repeat"}', + }, + }), + ) + await harness.subscription.handle(toolUpdated(runningTool("ses_pending", "call_pending", "repeat"))) + + expect( + toolUpdates(harness.updates) + .filter((item) => item.update.sessionUpdate === "tool_call_update") + .map((item) => ("content" in item.update ? item.update.content : undefined)), + ).toEqual([ + [{ type: "content", content: { type: "text", text: "repeat" } }], + [{ type: "content", content: { type: "text", text: "repeat" } }], + ]) + }) + + it("emits completed tool output and rawOutput", async () => { + const harness = createHarness() + await Effect.runPromise(harness.session.create({ id: "ses_done", cwd: "/workspace" })) + + await harness.subscription.handle(toolUpdated(completedTool("ses_done", "call_done", "finished"))) + + expect(harness.updates.at(-1)?.update).toMatchObject({ + sessionUpdate: "tool_call_update", + toolCallId: "call_done", + status: "completed", + content: [{ type: "content", content: { type: "text", text: "finished" } }], + rawOutput: { output: "finished", metadata: { exit: 0 } }, + }) + }) + + it("emits error tool output", async () => { + const harness = createHarness() + await Effect.runPromise(harness.session.create({ id: "ses_error", cwd: "/workspace" })) + + await harness.subscription.handle(toolUpdated(errorTool("ses_error", "call_error"))) + + expect(harness.updates.at(-1)?.update).toMatchObject({ + sessionUpdate: "tool_call_update", + toolCallId: "call_error", + status: "failed", + content: [{ type: "content", content: { type: "text", text: "failed hard" } }], + rawOutput: { error: "failed hard", metadata: { exit: 1 } }, + }) + }) + + it("emits image attachments as ACP image content for live and replayed completed tool updates", async () => { + const harness = createHarness() + const image = Buffer.from("image-data").toString("base64") + const attachment = { + id: "file_image", + sessionID: "ses_image", + messageID: "msg_image", + type: "file", + mime: "image/png", + filename: "image.png", + url: `data:image/png;base64,${image}`, + } as const + await Effect.runPromise(harness.session.create({ id: "ses_image", cwd: "/workspace" })) + + await harness.subscription.handle(toolUpdated(completedTool("ses_image", "call_live", "live", [attachment]))) + await harness.subscription.replayMessage( + assistantToolMessage(completedTool("ses_image", "call_replayed", "replayed", [attachment])), + ) + + expect( + toolUpdates(harness.updates) + .filter((item) => item.update.sessionUpdate === "tool_call_update" && item.update.status === "completed") + .map((item) => ("content" in item.update ? item.update.content : [])), + ).toEqual([ + [ + { type: "content", content: { type: "text", text: "live" } }, + { type: "content", content: { type: "image", mimeType: "image/png", data: image } }, + ], + [ + { type: "content", content: { type: "text", text: "replayed" } }, + { type: "content", content: { type: "image", mimeType: "image/png", data: image } }, + ], + ]) + }) +}) diff --git a/packages/opencode/test/acp/permission.test.ts b/packages/opencode/test/acp/permission.test.ts new file mode 100644 index 000000000000..fb86026af6c4 --- /dev/null +++ b/packages/opencode/test/acp/permission.test.ts @@ -0,0 +1,237 @@ +import { describe, expect, it } from "bun:test" +import type { + AgentSideConnection, + RequestPermissionRequest, + RequestPermissionResponse, + SessionUpdate, +} from "@agentclientprotocol/sdk" +import type { Event, OpencodeClient } from "@opencode-ai/sdk/v2" +import { Effect, ManagedRuntime } from "effect" +import { ACPEvent } from "@/acp/event" +import { ACPSession } from "@/acp/session" + +type PermissionEvent = Extract +type PermissionReplyParams = Parameters[0] +type SessionUpdateParams = Parameters[0] + +const pollUntil = async ( + check: () => boolean | Promise, + message: string, + opts?: { timeoutMs?: number; intervalMs?: number }, +) => { + const started = Date.now() + while (true) { + if (await check()) return + if (Date.now() - started > (opts?.timeoutMs ?? 2000)) throw new Error(message) + await new Promise((resolve) => setTimeout(resolve, opts?.intervalMs ?? 5)) + } +} + +function makeSessionService() { + return ManagedRuntime.make(ACPSession.defaultLayer).runSync( + ACPSession.Service.use((service) => Effect.succeed(service)), + ) +} + +function createHarness( + requestPermission: (params: RequestPermissionRequest) => Promise = () => + Promise.resolve({ outcome: { outcome: "selected", optionId: "once" } }), +) { + const replies: PermissionReplyParams[] = [] + const requests: RequestPermissionRequest[] = [] + const updates: SessionUpdateParams[] = [] + const session = makeSessionService() + const sdk = { + permission: { + reply: (params: PermissionReplyParams) => { + replies.push(params) + return Promise.resolve({ data: true }) + }, + }, + session: { + message: () => Promise.resolve({ data: undefined }), + }, + } as unknown as OpencodeClient + const connection = { + requestPermission: (params: RequestPermissionRequest) => { + requests.push(params) + return requestPermission(params) + }, + sessionUpdate: (params: SessionUpdateParams) => { + updates.push(params) + return Promise.resolve() + }, + } satisfies Pick + const subscription = new ACPEvent.Subscription({ sdk, connection, session }) + + return { connection, replies, requests, sdk, session, subscription, updates } +} + +async function createSession(session: ACPSession.Interface, sessionId: string, cwd = "/workspace") { + await Effect.runPromise(session.create({ id: sessionId, cwd })) +} + +async function createKnownTextPart( + session: ACPSession.Interface, + sessionId: string, + messageId: string, + partId: string, +) { + await Effect.runPromise( + session.recordPartMetadata({ + sessionId, + messageId, + partId, + partType: "text", + role: "assistant", + }), + ) +} + +function permissionAsked( + sessionID: string, + id: string, + input: { + permission?: string + metadata?: Record + tool?: { messageID: string; callID: string } + } = {}, +) { + return { + id: `evt_${id}`, + type: "permission.asked", + properties: { + id, + sessionID, + permission: input.permission ?? "bash", + patterns: ["*"], + metadata: input.metadata ?? { command: "printf hello" }, + always: [], + ...(input.tool ? { tool: input.tool } : {}), + }, + } as PermissionEvent +} + +function textDelta(sessionID: string, messageID: string, partID: string, delta: string) { + return { + id: `evt_${sessionID}_${messageID}_${partID}`, + type: "message.part.delta", + properties: { + sessionID, + messageID, + partID, + field: "text", + delta, + }, + } as Event +} + +function textFromUpdates(updates: SessionUpdateParams[], sessionId: string) { + return updates + .filter((item) => item.sessionId === sessionId) + .map((item) => item.update) + .filter((update): update is Extract => { + return update.sessionUpdate === "agent_message_chunk" + }) + .map((update) => (update.content.type === "text" ? update.content.text : "")) + .join("") +} + +describe("acp permissions", () => { + it("sends requestPermission and replies with the selected outcome", async () => { + const harness = createHarness() + await createSession(harness.session, "ses_a") + + harness.subscription.handle(permissionAsked("ses_a", "perm_1", { tool: { messageID: "msg_1", callID: "call_1" } })) + + await pollUntil(() => harness.replies.length === 1, "permission was never replied") + + expect(harness.requests[0]).toMatchObject({ + sessionId: "ses_a", + toolCall: { + toolCallId: "call_1", + status: "pending", + title: "bash", + rawInput: { command: "printf hello" }, + kind: "execute", + locations: [], + }, + options: [ + { optionId: "once", kind: "allow_once", name: "Allow once" }, + { optionId: "always", kind: "allow_always", name: "Always allow" }, + { optionId: "reject", kind: "reject_once", name: "Reject" }, + ], + }) + expect(harness.replies).toEqual([{ requestID: "perm_1", reply: "once", directory: "/workspace" }]) + }) + + it("rejects non-selected outcomes", async () => { + const harness = createHarness(() => Promise.resolve({ outcome: { outcome: "cancelled" } })) + await createSession(harness.session, "ses_a") + + harness.subscription.handle(permissionAsked("ses_a", "perm_cancelled")) + + await pollUntil(() => harness.replies.length === 1, "cancelled permission was never replied") + + expect(harness.replies[0]).toMatchObject({ requestID: "perm_cancelled", reply: "reject" }) + }) + + it("rejects when requestPermission fails", async () => { + const harness = createHarness(() => Promise.reject(new Error("client permission UI failed"))) + await createSession(harness.session, "ses_a") + + harness.subscription.handle(permissionAsked("ses_a", "perm_failed")) + + await pollUntil(() => harness.replies.length === 1, "failed permission was never rejected") + + expect(harness.replies[0]).toMatchObject({ requestID: "perm_failed", reply: "reject" }) + }) + + it("does not let a blocked session A permission block session B message updates", async () => { + let releasePermission: (() => void) | undefined + const blocked = new Promise((resolve) => { + releasePermission = () => resolve({ outcome: { outcome: "selected", optionId: "once" } }) + }) + const harness = createHarness(() => blocked) + await createSession(harness.session, "ses_a") + await createSession(harness.session, "ses_b") + await createKnownTextPart(harness.session, "ses_b", "msg_b", "part_b") + + harness.subscription.handle(permissionAsked("ses_a", "perm_blocked")) + await pollUntil(() => harness.requests.length === 1, "blocked permission was never requested") + + await harness.subscription.handle(textDelta("ses_b", "msg_b", "part_b", "session_b_message")) + + expect(textFromUpdates(harness.updates, "ses_b")).toBe("session_b_message") + expect(harness.replies).toHaveLength(0) + + releasePermission?.() + await pollUntil(() => harness.replies.length === 1, "blocked permission was never replied after release") + }) + + it("serializes permission requests per session", async () => { + let releaseFirst: (() => void) | undefined + const first = new Promise((resolve) => { + releaseFirst = () => resolve({ outcome: { outcome: "selected", optionId: "once" } }) + }) + const harness = createHarness(() => + harness.requests.length === 1 ? first : Promise.resolve({ outcome: { outcome: "selected", optionId: "always" } }), + ) + await createSession(harness.session, "ses_a") + + harness.subscription.handle(permissionAsked("ses_a", "perm_1")) + harness.subscription.handle(permissionAsked("ses_a", "perm_2")) + + await pollUntil(() => harness.requests.length === 1, "first permission was never requested") + expect(harness.requests.map((request) => request.toolCall.toolCallId)).toEqual(["perm_1"]) + + releaseFirst?.() + await pollUntil(() => harness.requests.length === 2, "second permission was not requested after first resolved") + await pollUntil(() => harness.replies.length === 2, "serialized permissions were not both replied") + + expect(harness.replies.map((reply) => [reply.requestID, reply.reply])).toEqual([ + ["perm_1", "once"], + ["perm_2", "always"], + ]) + }) +}) diff --git a/packages/opencode/test/acp/service-session.test.ts b/packages/opencode/test/acp/service-session.test.ts new file mode 100644 index 000000000000..e5f1bc64c624 --- /dev/null +++ b/packages/opencode/test/acp/service-session.test.ts @@ -0,0 +1,1133 @@ +import { describe, expect, it } from "bun:test" +import type { + AgentSideConnection, + ForkSessionResponse, + LoadSessionResponse, + NewSessionResponse, + SessionNotification, + ResumeSessionResponse, + SessionConfigOption, + SessionConfigSelectOption, + SetSessionConfigOptionResponse, +} from "@agentclientprotocol/sdk" +import type { OpencodeClient } from "@opencode-ai/sdk/v2" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { Effect } from "effect" +import * as ACPService from "@/acp/service" +import * as ACPError from "@/acp/error" +import { UsageService } from "@/acp/usage" +import type { Provider } from "@/provider/provider" + +const providerID = ProviderV2.ID.make("test") +const modelID = ProviderV2.ModelID.make("test-model") +const configuredModelID = ProviderV2.ModelID.make("configured-model") +const secondModelID = ProviderV2.ModelID.make("second-model") + +const provider: Provider.Info = { + id: providerID, + name: "Test", + source: "config", + env: [], + options: {}, + models: { + [modelID]: { + id: modelID, + providerID, + api: { + id: modelID, + url: "https://example.com", + npm: "@ai-sdk/openai-compatible", + }, + name: "Test Model", + family: "test", + capabilities: { + temperature: true, + reasoning: true, + attachment: false, + toolcall: true, + input: { text: true, audio: false, image: false, video: false, pdf: false }, + output: { text: true, audio: false, image: false, video: false, pdf: false }, + interleaved: false, + }, + cost: { + input: 0, + output: 0, + cache: { read: 0, write: 0 }, + }, + limit: { + context: 128000, + output: 4096, + }, + status: "active", + options: {}, + headers: {}, + release_date: "2026-01-01", + variants: { + default: {}, + high: { reasoningEffort: "high" }, + }, + }, + [configuredModelID]: { + id: configuredModelID, + providerID, + api: { + id: configuredModelID, + url: "https://example.com", + npm: "@ai-sdk/openai-compatible", + }, + name: "Configured Model", + family: "test", + capabilities: { + temperature: true, + reasoning: false, + attachment: false, + toolcall: true, + input: { text: true, audio: false, image: false, video: false, pdf: false }, + output: { text: true, audio: false, image: false, video: false, pdf: false }, + interleaved: false, + }, + cost: { + input: 0, + output: 0, + cache: { read: 0, write: 0 }, + }, + limit: { + context: 128000, + output: 4096, + }, + status: "active", + options: {}, + headers: {}, + release_date: "2026-01-01", + }, + [secondModelID]: { + id: secondModelID, + providerID, + api: { + id: secondModelID, + url: "https://example.com", + npm: "@ai-sdk/openai-compatible", + }, + name: "Second Model", + family: "test", + capabilities: { + temperature: true, + reasoning: true, + attachment: false, + toolcall: true, + input: { text: true, audio: false, image: false, video: false, pdf: false }, + output: { text: true, audio: false, image: false, video: false, pdf: false }, + interleaved: false, + }, + cost: { + input: 0, + output: 0, + cache: { read: 0, write: 0 }, + }, + limit: { + context: 128000, + output: 4096, + }, + status: "active", + options: {}, + headers: {}, + release_date: "2026-01-01", + variants: { + low: { reasoningEffort: "low" }, + medium: { reasoningEffort: "medium" }, + }, + }, + }, +} + +describe("ACP service sessions", () => { + const makeService = ( + messages: readonly { info: unknown; parts: readonly unknown[] }[] = [], + options?: { abort?: (input: { sessionID: string }) => Promise<{ data: boolean }> }, + ) => { + const updates: SessionNotification[] = [] + const mcpAdds: string[] = [] + const aborts: string[] = [] + const forks: string[] = [] + const prompts: unknown[] = [] + const commands: unknown[] = [] + const summarizes: unknown[] = [] + const usageUpdates: string[] = [] + const sessions = Array.from({ length: 102 }, (_, index) => ({ + id: `ses_${index + 1}`, + directory: index % 2 === 0 ? "/workspace" : "/other", + title: `Session ${index + 1}`, + time: { created: index + 1, updated: index + 1 }, + })) + const sdk = { + config: { + providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => + Promise.resolve({ + data: [ + { name: "build", mode: "primary", permission: [], options: {} }, + { name: "plan", mode: "primary", description: "Plan first", permission: [], options: {} }, + { name: "hidden", mode: "primary", hidden: true, permission: [], options: {} }, + ], + }), + skills: () => + Promise.resolve({ + data: [{ name: "review-skill", description: "Review", location: "/skills/review", content: "review" }], + }), + }, + command: { + list: () => + Promise.resolve({ + data: [{ name: "init", description: "Initialize", source: "command", template: "init", hints: [] }], + }), + }, + session: { + create: () => Promise.resolve({ data: { id: "ses_new" } }), + get: () => Promise.resolve({ data: { id: "ses_loaded" } }), + list: (input: { directory?: string }) => + Promise.resolve({ + data: input.directory ? sessions.filter((session) => session.directory === input.directory) : sessions, + }), + messages: () => Promise.resolve({ data: messages }), + prompt: (input: unknown) => { + prompts.push(input) + return Promise.resolve({ + data: { + info: assistantInfo({ + input: 100, + output: 40, + reasoning: 7, + cache: { read: 11, write: 13 }, + }), + }, + }) + }, + command: (input: unknown) => { + commands.push(input) + return Promise.resolve({ + data: { + info: assistantInfo({ + input: 3, + output: 4, + reasoning: 0, + cache: { read: 0, write: 0 }, + }), + }, + }) + }, + summarize: (input: unknown) => { + summarizes.push(input) + return Promise.resolve({ data: true }) + }, + abort: + options?.abort ?? + ((input: { sessionID: string }) => { + aborts.push(input.sessionID) + return Promise.resolve({ data: true }) + }), + fork: (input: { sessionID: string }) => { + forks.push(input.sessionID) + return Promise.resolve({ data: { id: `fork_${input.sessionID}` } }) + }, + }, + mcp: { + add: (input: { name?: string }) => { + if (input.name) mcpAdds.push(input.name) + return Promise.resolve({ data: {} }) + }, + }, + } as unknown as OpencodeClient + const connection = { + sessionUpdate: (update: SessionNotification) => { + updates.push(update) + return Promise.resolve() + }, + } as Pick + const usage = UsageService.Service.of({ + buildUsage: UsageService.buildUsage, + latestAssistantMessage: UsageService.latestAssistantMessage, + totalSessionCost: UsageService.totalSessionCost, + contextLimit: () => Effect.succeed(128000), + sendUpdate: (input) => + Effect.sync(() => { + usageUpdates.push(input.sessionID) + }), + }) + + return { + service: ACPService.make({ sdk, connection, usage }), + updates, + mcpAdds, + aborts, + forks, + prompts, + commands, + summarizes, + usageUpdates, + } + } + + it("creates a backed session with config options and command update", async () => { + const { service, updates, mcpAdds } = makeService() + const result = await Effect.runPromise( + service.newSession({ + cwd: "/workspace", + mcpServers: [ + { name: "tools", command: "node", args: ["server.js"], env: [] }, + { name: "tools", command: "node", args: ["server.js"], env: [] }, + ], + }), + ) + + await new Promise((resolve) => setTimeout(resolve, 5)) + + expect(result.sessionId).toBe("ses_new") + expect(categories(result)).toContain("model") + expect(categories(result)).toContain("thought_level") + expect(categories(result)).toContain("mode") + expect(updates).toHaveLength(1) + expect(JSON.stringify(updates[0])).toContain("available_commands_update") + expect(JSON.stringify(updates[0])).toContain("review-skill") + expect(mcpAdds).toEqual(["tools"]) + }) + + it("loads a session and restores model variant and mode from messages", async () => { + const { service } = makeService([ + { + info: { + role: "assistant", + providerID: "test", + modelID: "test-model", + variant: "high", + mode: "plan", + }, + parts: [], + }, + ]) + const result = await Effect.runPromise( + service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] }), + ) + + expect(result.configOptions?.find((option) => option.id === "effort")?.currentValue).toBe("high") + expect(result.configOptions?.find((option) => option.id === "mode")?.currentValue).toBe("plan") + }) + + it("lists sessions sorted by updated time with cursor support", async () => { + const { service } = makeService() + const first = await Effect.runPromise(service.listSessions({ cwd: "/workspace" })) + const second = await Effect.runPromise(service.listSessions({ cwd: "/workspace", cursor: first.nextCursor })) + + expect(first.sessions).toHaveLength(51) + expect(first.sessions[0]?.sessionId).toBe("ses_101") + expect(first.sessions.at(-1)?.sessionId).toBe("ses_1") + expect(first.nextCursor).toBeUndefined() + expect(second.sessions).toEqual(first.sessions) + }) + + it("includes live ACP sessions before they appear in server-backed session list", async () => { + const { service } = makeService() + const created = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const listed = await Effect.runPromise(service.listSessions({ cwd: "/workspace" })) + + expect(listed.sessions[0]?.sessionId).toBe(created.sessionId) + expect(listed.sessions[0]?.cwd).toBe("/workspace") + }) + + it("lists all sessions with next cursor when the first page is full", async () => { + const { service } = makeService() + const first = await Effect.runPromise(service.listSessions({})) + const second = await Effect.runPromise(service.listSessions({ cursor: first.nextCursor })) + + expect(first.sessions).toHaveLength(100) + expect(first.sessions[0]?.sessionId).toBe("ses_102") + expect(first.sessions.at(-1)?.sessionId).toBe("ses_3") + expect(first.nextCursor).toBe("3") + expect(second.sessions.map((session) => session.sessionId)).toEqual(["ses_2", "ses_1"]) + }) + + it("resumes a session and stores restored state", async () => { + const { service } = makeService([ + { + info: { + role: "user", + model: { providerID: "test", modelID: "test-model", variant: "high" }, + agent: "plan", + }, + parts: [], + }, + ]) + const resumed = await Effect.runPromise( + service.resumeSession({ cwd: "/workspace", sessionId: "ses_resume", mcpServers: [] }), + ) + const updated = await Effect.runPromise( + service.setSessionConfigOption({ sessionId: "ses_resume", configId: "effort", value: "default" }), + ) + + expect(select(resumed, "effort")?.currentValue).toBe("high") + expect(select(updated, "effort")?.currentValue).toBe("default") + }) + + it("closes local ACP state and aborts the backing session best-effort", async () => { + const { service, aborts } = makeService() + const created = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + expect(await Effect.runPromise(service.closeSession({ sessionId: created.sessionId }))).toEqual({}) + const missing = await Effect.runPromise( + service + .setSessionConfigOption({ sessionId: created.sessionId, configId: "effort", value: "high" }) + .pipe(Effect.mapError(ACPError.toRequestError), Effect.flip), + ) + expect(missing.code).toBe(-32602) + expect(aborts).toEqual([created.sessionId]) + expect(await Effect.runPromise(service.closeSession({ sessionId: "missing" }))).toEqual({}) + }) + + it("cancel aborts the backing session and keeps the ACP session", async () => { + const { service, aborts } = makeService() + const created = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + await Effect.runPromise(service.cancel({ sessionId: created.sessionId })) + + // The running turn was aborted via the core session API. + expect(aborts).toEqual([created.sessionId]) + // Unlike closeSession, the ACP session is still present afterwards so + // the client can keep prompting. + const stillUsable = await Effect.runPromise( + service.setSessionConfigOption({ sessionId: created.sessionId, configId: "effort", value: "high" }), + ) + expect(stillUsable).toBeDefined() + }) + + it("does not fail cancel or close when the backing abort fails", async () => { + const { service } = makeService([], { abort: () => Promise.reject(new Error("nope")) }) + const created = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + await Effect.runPromise(service.cancel({ sessionId: created.sessionId })) + expect(await Effect.runPromise(service.closeSession({ sessionId: created.sessionId }))).toEqual({}) + expect(await Effect.runPromise(service.closeSession({ sessionId: "missing" }))).toEqual({}) + }) + + it("forks a session, loads fork state, and returns config options", async () => { + const { service, forks } = makeService([ + { + info: { + role: "assistant", + providerID: "test", + modelID: "second-model", + variant: "medium", + mode: "plan", + }, + parts: [], + }, + ]) + const forked = await Effect.runPromise( + service.forkSession({ cwd: "/workspace", sessionId: "ses_parent", mcpServers: [] }), + ) + const updated = await Effect.runPromise( + service.setSessionConfigOption({ sessionId: forked.sessionId, configId: "effort", value: "low" }), + ) + + expect(forked.sessionId).toBe("fork_ses_parent") + expect(select(forked, "model")?.currentValue).toBe("test/second-model") + expect(select(forked, "effort")?.currentValue).toBe("medium") + expect(select(updated, "effort")?.currentValue).toBe("low") + expect(forks).toEqual(["ses_parent"]) + }) + + it("restores model variant and mode from the latest user message", async () => { + const { service } = makeService([ + { + info: { + role: "user", + model: { providerID: "test", modelID: "test-model", variant: "default" }, + agent: "build", + }, + parts: [], + }, + { + info: { + role: "user", + model: { providerID: "test", modelID: "test-model", variant: "high" }, + agent: "plan", + }, + parts: [], + }, + ]) + const result = await Effect.runPromise( + service.loadSession({ cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] }), + ) + + expect(result.configOptions?.find((option) => option.id === "effort")?.currentValue).toBe("high") + expect(result.configOptions?.find((option) => option.id === "mode")?.currentValue).toBe("plan") + }) + + it("maps provider auth failures to auth-required request errors", async () => { + const service = ACPService.make({ + sdk: { + config: { + providers: () => Promise.reject({ name: "ProviderAuthError", data: { providerID: "test" } }), + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => Promise.resolve({ data: [] }), + skills: () => Promise.resolve({ data: [] }), + }, + command: { + list: () => Promise.resolve({ data: [] }), + }, + } as unknown as OpencodeClient, + }) + const error = await Effect.runPromise( + service + .newSession({ cwd: "/workspace", mcpServers: [] }) + .pipe(Effect.mapError(ACPError.toRequestError), Effect.flip), + ) + + expect(error.code).toBe(-32000) + }) + + it("does not cache failed directory snapshots", async () => { + let providersCalls = 0 + const sdk = { + config: { + providers: () => { + providersCalls++ + if (providersCalls === 1) { + return Promise.reject({ name: "ProviderAuthError", data: { providerID: "test" } }) + } + return Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }) + }, + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), + skills: () => Promise.resolve({ data: [] }), + }, + command: { + list: () => Promise.resolve({ data: [] }), + }, + session: { + create: () => Promise.resolve({ data: { id: "ses_retry" } }), + list: () => Promise.resolve({ data: [] }), + }, + mcp: { + add: () => Promise.resolve({ data: {} }), + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + + const first = await Effect.runPromise( + service + .newSession({ cwd: "/workspace", mcpServers: [] }) + .pipe(Effect.mapError(ACPError.toRequestError), Effect.flip), + ) + const second = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + expect(first.code).toBe(-32000) + expect(second.sessionId).toBe("ses_retry") + expect(providersCalls).toBe(2) + }) + + it("registers same-name MCP servers again for different sessions or configs", async () => { + const adds: unknown[] = [] + let nextSession = 0 + const sdk = { + config: { + providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), + skills: () => Promise.resolve({ data: [] }), + }, + command: { + list: () => Promise.resolve({ data: [] }), + }, + session: { + create: () => { + nextSession++ + return Promise.resolve({ data: { id: `ses_${nextSession}` } }) + }, + list: () => Promise.resolve({ data: [] }), + }, + mcp: { + add: (input: unknown) => { + adds.push(input) + return Promise.resolve({ data: {} }) + }, + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + + await Effect.runPromise( + service.newSession({ + cwd: "/workspace", + mcpServers: [{ name: "tools", command: "node", args: ["one.js"], env: [] }], + }), + ) + await Effect.runPromise( + service.newSession({ + cwd: "/workspace", + mcpServers: [{ name: "tools", command: "node", args: ["two.js"], env: [] }], + }), + ) + + expect(adds).toHaveLength(2) + expect(JSON.stringify(adds[0])).toContain("one.js") + expect(JSON.stringify(adds[1])).toContain("two.js") + }) + + it("uses the configured model as the new session default", async () => { + const sdk = { + config: { + providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), + get: () => Promise.resolve({ data: { model: "test/configured-model" } }), + }, + app: { + agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), + skills: () => Promise.resolve({ data: [] }), + }, + command: { + list: () => Promise.resolve({ data: [] }), + }, + session: { + create: (input: { model?: { id?: string } }) => Promise.resolve({ data: { id: input.model?.id } }), + list: () => Promise.resolve({ data: [] }), + }, + mcp: { + add: () => Promise.resolve({ data: {} }), + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + + const result = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + expect(result.sessionId).toBe("configured-model") + expect(result.configOptions?.find((option) => option.id === "model")?.currentValue).toBe("test/configured-model") + }) + + it("does not scan last-used sessions when resolving the new session default", async () => { + const historyCalls: string[] = [] + const sdk = { + config: { + providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), + skills: () => Promise.resolve({ data: [] }), + }, + command: { + list: () => Promise.resolve({ data: [] }), + }, + session: { + create: (input: { model?: { id?: string } }) => Promise.resolve({ data: { id: input.model?.id } }), + list: () => { + historyCalls.push("list") + return Promise.resolve({ data: [{ id: "ses_recent" }] }) + }, + messages: () => { + historyCalls.push("messages") + return Promise.resolve({ + data: [{ info: { role: "user", model: { providerID: "test", modelID: "second-model" } } }], + }) + }, + }, + mcp: { + add: () => Promise.resolve({ data: {} }), + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + + const result = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + expect(result.sessionId).toBe("test-model") + expect(result.configOptions?.find((option) => option.id === "model")?.currentValue).toBe("test/test-model") + expect(historyCalls).toEqual([]) + }) + + it("switches model and returns updated model and effort options", async () => { + const { service } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const updated = await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "model", + value: "test/second-model", + }), + ) + + expect(select(updated, "model")?.currentValue).toBe("test/second-model") + expect(select(updated, "effort")?.currentValue).toBe("low") + expect(flattenSelectOptions(select(updated, "effort")).map((option) => option.value)).toEqual(["low", "medium"]) + }) + + it("switches effort and returns the updated effort current value", async () => { + const { service } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const updated = await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "effort", + value: "high", + }), + ) + + expect(select(updated, "effort")?.currentValue).toBe("high") + }) + + it("switches mode and returns the updated mode current value", async () => { + const { service } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const updated = await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "mode", + value: "plan", + }), + ) + + expect(select(updated, "mode")?.currentValue).toBe("plan") + }) + + it("maps invalid model effort mode and config id to invalid params", async () => { + const { service } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + const results = await Promise.all( + [ + { configId: "model", value: "test/missing-model" }, + { configId: "effort", value: "max" }, + { configId: "mode", value: "missing-mode" }, + { configId: "missing", value: "value" }, + ].map((input) => + Effect.runPromise( + service + .setSessionConfigOption({ sessionId: session.sessionId, ...input }) + .pipe(Effect.mapError(ACPError.toRequestError), Effect.flip), + ), + ), + ) + expect(results.map((error) => error.code)).toEqual([-32602, -32602, -32602, -32602]) + }) + + it("does not refetch providers modes or commands when switching effort from session snapshot", async () => { + const calls = { + providers: 0, + agents: 0, + commands: 0, + skills: 0, + mcpAdds: 0, + } + const sdk = { + config: { + providers: () => { + calls.providers++ + return Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }) + }, + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => { + calls.agents++ + return Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }) + }, + skills: () => { + calls.skills++ + return Promise.resolve({ data: [] }) + }, + }, + command: { + list: () => { + calls.commands++ + return Promise.resolve({ data: [] }) + }, + }, + session: { + create: () => Promise.resolve({ data: { id: "ses_fast" } }), + list: () => Promise.resolve({ data: [] }), + }, + mcp: { + add: () => { + calls.mcpAdds++ + return Promise.resolve({ data: {} }) + }, + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + expect(calls).toEqual({ providers: 1, agents: 1, commands: 1, skills: 1, mcpAdds: 0 }) + + await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "effort", + value: "high", + }), + ) + + expect(calls).toEqual({ providers: 1, agents: 1, commands: 1, skills: 1, mcpAdds: 0 }) + }) + + it("switches model against the warm provider snapshot without refetching", async () => { + const calls = { + providers: 0, + agents: 0, + commands: 0, + skills: 0, + } + const sdk = { + config: { + providers: () => { + calls.providers++ + return Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }) + }, + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => { + calls.agents++ + return Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }) + }, + skills: () => { + calls.skills++ + return Promise.resolve({ data: [] }) + }, + }, + command: { + list: () => { + calls.commands++ + return Promise.resolve({ data: [] }) + }, + }, + session: { + create: () => Promise.resolve({ data: { id: "ses_model_fast" } }), + list: () => Promise.resolve({ data: [] }), + }, + mcp: { + add: () => Promise.resolve({ data: {} }), + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const updated = await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "model", + value: "test/second-model", + }), + ) + + expect(select(updated, "model")?.currentValue).toBe("test/second-model") + expect(calls).toEqual({ providers: 1, agents: 1, commands: 1, skills: 1 }) + }) + + it("reuses the warm directory snapshot for a second new session in the same cwd", async () => { + const calls = { + providers: 0, + config: 0, + agents: 0, + commands: 0, + skills: 0, + sessionList: 0, + messages: 0, + creates: 0, + } + const sdk = { + config: { + providers: () => { + calls.providers++ + return Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }) + }, + get: () => { + calls.config++ + return Promise.resolve({ data: {} }) + }, + }, + app: { + agents: () => { + calls.agents++ + return Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }) + }, + skills: () => { + calls.skills++ + return Promise.resolve({ data: [] }) + }, + }, + command: { + list: () => { + calls.commands++ + return Promise.resolve({ data: [] }) + }, + }, + session: { + create: () => { + calls.creates++ + return Promise.resolve({ data: { id: `ses_warm_${calls.creates}` } }) + }, + list: () => { + calls.sessionList++ + return Promise.resolve({ data: [] }) + }, + messages: () => { + calls.messages++ + return Promise.resolve({ data: [] }) + }, + }, + mcp: { + add: () => Promise.resolve({ data: {} }), + }, + } as unknown as OpencodeClient + const service = ACPService.make({ sdk }) + + const first = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const second = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + expect(first.sessionId).toBe("ses_warm_1") + expect(second.sessionId).toBe("ses_warm_2") + expect(calls).toEqual({ + providers: 1, + config: 1, + agents: 1, + commands: 1, + skills: 1, + sessionList: 0, + messages: 0, + creates: 2, + }) + }) + + it("normal text prompt sends model variant mode and converted parts", async () => { + const { service, prompts, usageUpdates } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "effort", + value: "high", + }), + ) + await Effect.runPromise( + service.setSessionConfigOption({ + sessionId: session.sessionId, + configId: "mode", + value: "plan", + }), + ) + + const result = await Effect.runPromise( + service.prompt({ + sessionId: session.sessionId, + messageId: "00000000-0000-4000-8000-000000000001", + prompt: [{ type: "text", text: "hello" }], + }), + ) + + expect(prompts).toEqual([ + { + sessionID: session.sessionId, + model: { providerID, modelID }, + variant: "high", + parts: [{ type: "text", text: "hello" }], + agent: "plan", + directory: "/workspace", + }, + ]) + expect(result).toEqual({ + stopReason: "end_turn", + usage: { + inputTokens: 100, + outputTokens: 40, + thoughtTokens: 7, + cachedReadTokens: 11, + cachedWriteTokens: 13, + totalTokens: 171, + }, + userMessageId: "00000000-0000-4000-8000-000000000001", + _meta: {}, + }) + expect(usageUpdates).toEqual([session.sessionId]) + }) + + it("prompt maps assistant and user audience annotations", async () => { + const { service, prompts } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + await Effect.runPromise( + service.prompt({ + sessionId: session.sessionId, + prompt: [ + { type: "text", text: "assistant context", annotations: { audience: ["assistant"] } }, + { type: "text", text: "user context", annotations: { audience: ["user"] } }, + ], + }), + ) + + expect(prompts).toContainEqual({ + sessionID: session.sessionId, + model: { providerID, modelID }, + variant: "default", + parts: [ + { type: "text", text: "assistant context", synthetic: true }, + { type: "text", text: "user context", ignored: true }, + ], + agent: "build", + directory: "/workspace", + }) + }) + + it("prompt sends image and resource parts", async () => { + const { service, prompts } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + await Effect.runPromise( + service.prompt({ + sessionId: session.sessionId, + prompt: [ + { type: "image", data: "AAAA", mimeType: "image/png", uri: "file:///tmp/screenshot.png" }, + { + type: "resource", + resource: { + uri: "file:///tmp/report.pdf", + mimeType: "application/pdf", + blob: "JVBERg==", + }, + }, + ], + }), + ) + + expect((prompts[0] as { parts?: unknown }).parts).toEqual([ + { + type: "file", + url: "data:image/png;base64,AAAA", + filename: "screenshot.png", + mime: "image/png", + }, + { + type: "file", + url: "data:application/pdf;base64,JVBERg==", + filename: "report.pdf", + mime: "application/pdf", + }, + ]) + }) + + it("slash command prompt calls session command", async () => { + const { service, prompts, commands } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + const result = await Effect.runPromise( + service.prompt({ sessionId: session.sessionId, prompt: [{ type: "text", text: "/init now" }] }), + ) + + expect(prompts).toEqual([]) + expect(commands).toEqual([ + { + sessionID: session.sessionId, + command: "init", + arguments: "now", + model: "test/test-model", + variant: "default", + agent: "build", + directory: "/workspace", + }, + ]) + expect(result.usage).toEqual({ inputTokens: 3, outputTokens: 4, totalTokens: 7 }) + }) + + it("compact slash command calls summarize path", async () => { + const { service, prompts, commands, summarizes } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + + await Effect.runPromise( + service.prompt({ sessionId: session.sessionId, prompt: [{ type: "text", text: "/compact" }] }), + ) + + expect(prompts).toEqual([]) + expect(commands).toEqual([]) + expect(summarizes).toEqual([ + { + sessionID: session.sessionId, + directory: "/workspace", + providerID, + modelID, + }, + ]) + }) + + it("maps prompt auth failures to auth-required request errors", async () => { + const { service } = makeService() + const session = await Effect.runPromise(service.newSession({ cwd: "/workspace", mcpServers: [] })) + const failing = ACPService.make({ + sdk: { + config: { + providers: () => Promise.resolve({ data: { providers: [provider], default: { test: modelID } } }), + get: () => Promise.resolve({ data: {} }), + }, + app: { + agents: () => Promise.resolve({ data: [{ name: "build", mode: "primary", permission: [], options: {} }] }), + skills: () => Promise.resolve({ data: [] }), + }, + command: { + list: () => Promise.resolve({ data: [] }), + }, + session: { + create: () => Promise.resolve({ data: { id: session.sessionId } }), + list: () => Promise.resolve({ data: [] }), + prompt: () => Promise.reject({ name: "ProviderAuthError", data: { providerID: "test" } }), + }, + mcp: { + add: () => Promise.resolve({ data: {} }), + }, + } as unknown as OpencodeClient, + usage: UsageService.Service.of({ + buildUsage: UsageService.buildUsage, + latestAssistantMessage: UsageService.latestAssistantMessage, + totalSessionCost: UsageService.totalSessionCost, + contextLimit: () => Effect.succeed(128000), + sendUpdate: () => Effect.void, + }), + }) + await Effect.runPromise(failing.newSession({ cwd: "/workspace", mcpServers: [] })) + const error = await Effect.runPromise( + failing + .prompt({ sessionId: session.sessionId, prompt: [{ type: "text", text: "hello" }] }) + .pipe(Effect.mapError(ACPError.toRequestError), Effect.flip), + ) + + expect(error.code).toBe(-32000) + }) +}) + +function assistantInfo(tokens: UsageService.AssistantTokenCost["tokens"]): UsageService.AssistantMessage { + return { + role: "assistant", + providerID: "test", + modelID: "test-model", + cost: 0, + tokens, + } +} + +function categories(result: NewSessionResponse | LoadSessionResponse) { + return result.configOptions?.map((option) => option.category) ?? [] +} + +function select( + result: SetSessionConfigOptionResponse | ResumeSessionResponse | NewSessionResponse | ForkSessionResponse, + id: string, +) { + return result.configOptions?.find( + (option): option is Extract => + option.id === id && option.type === "select", + ) +} + +function flattenSelectOptions(option: Extract | undefined) { + return option?.options.flatMap((item): SessionConfigSelectOption[] => ("value" in item ? [item] : item.options)) ?? [] +} diff --git a/packages/opencode/test/acp-next/session.test.ts b/packages/opencode/test/acp/session.test.ts similarity index 63% rename from packages/opencode/test/acp-next/session.test.ts rename to packages/opencode/test/acp/session.test.ts index 0c1cb16cc784..a7801218e27a 100644 --- a/packages/opencode/test/acp-next/session.test.ts +++ b/packages/opencode/test/acp/session.test.ts @@ -1,16 +1,16 @@ import { describe, expect } from "bun:test" import type { McpServer } from "@agentclientprotocol/sdk" import { Effect } from "effect" -import * as ACPNextError from "@/acp-next/error" -import * as ACPNextSession from "@/acp-next/session" -import { ModelID, ProviderID } from "@/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" +import * as ACPError from "@/acp/error" +import * as ACPSession from "@/acp/session" import { testEffect } from "../lib/effect" -const sessionTest = testEffect(ACPNextSession.defaultLayer) +const sessionTest = testEffect(ACPSession.defaultLayer) -const model = (providerID: string, modelID: string): ACPNextSession.SelectedModel => ({ - providerID: ProviderID.make(providerID), - modelID: ModelID.make(modelID), +const model = (providerID: string, modelID: string): ACPSession.SelectedModel => ({ + providerID: ProviderV2.ID.make(providerID), + modelID: ProviderV2.ModelID.make(modelID), }) const mcpServer: McpServer = { @@ -20,11 +20,11 @@ const mcpServer: McpServer = { env: [], } -describe("acp-next session state", () => { +describe("acp session state", () => { sessionTest.effect("creates and retrieves session state", () => Effect.gen(function* () { const createdAt = new Date("2026-05-25T00:00:00.000Z") - const created = yield* ACPNextSession.Service.use((session) => + const created = yield* ACPSession.Service.use((session) => session.create({ id: "ses_1", cwd: "/workspace", @@ -35,7 +35,7 @@ describe("acp-next session state", () => { modeId: "build", }), ) - const loaded = yield* ACPNextSession.Service.use((session) => session.get("ses_1")) + const loaded = yield* ACPSession.Service.use((session) => session.get("ses_1")) expect(created).toMatchObject({ id: "ses_1", @@ -52,17 +52,17 @@ describe("acp-next session state", () => { sessionTest.effect("fails required lookups with typed SessionNotFound", () => Effect.gen(function* () { - const error = yield* ACPNextSession.Service.use((session) => session.get("ses_missing")).pipe(Effect.flip) + const error = yield* ACPSession.Service.use((session) => session.get("ses_missing")).pipe(Effect.flip) - expect(error).toBeInstanceOf(ACPNextError.SessionNotFoundError) + expect(error).toBeInstanceOf(ACPError.SessionNotFoundError) expect(error.sessionId).toBe("ses_missing") }), ) sessionTest.effect("tryGet lets event routing ignore unknown sessions", () => Effect.gen(function* () { - const missing = yield* ACPNextSession.Service.use((session) => session.tryGet("ses_missing")) - const missingPart = yield* ACPNextSession.Service.use((session) => + const missing = yield* ACPSession.Service.use((session) => session.tryGet("ses_missing")) + const missingPart = yield* ACPSession.Service.use((session) => session.tryGetPartMetadata({ sessionId: "ses_missing", messageId: "msg_1", partId: "part_1" }), ) @@ -73,7 +73,7 @@ describe("acp-next session state", () => { sessionTest.effect("updates selected model while preserving session identity and inputs", () => Effect.gen(function* () { - yield* ACPNextSession.Service.use((session) => + yield* ACPSession.Service.use((session) => session.create({ id: "ses_model", cwd: "/workspace", @@ -84,7 +84,7 @@ describe("acp-next session state", () => { }), ) - const updated = yield* ACPNextSession.Service.use((session) => + const updated = yield* ACPSession.Service.use((session) => session.setModel("ses_model", model("openai", "gpt-5")), ) @@ -99,7 +99,7 @@ describe("acp-next session state", () => { sessionTest.effect("updates selected variant and mode independently", () => Effect.gen(function* () { - yield* ACPNextSession.Service.use((session) => + yield* ACPSession.Service.use((session) => session.load({ id: "ses_config", cwd: "/workspace", @@ -109,21 +109,21 @@ describe("acp-next session state", () => { }), ) - yield* ACPNextSession.Service.use((session) => session.setVariant("ses_config", "high")) - expect(yield* ACPNextSession.Service.use((session) => session.getVariant("ses_config"))).toBe("high") - expect(yield* ACPNextSession.Service.use((session) => session.getMode("ses_config"))).toBe("plan") + yield* ACPSession.Service.use((session) => session.setVariant("ses_config", "high")) + expect(yield* ACPSession.Service.use((session) => session.getVariant("ses_config"))).toBe("high") + expect(yield* ACPSession.Service.use((session) => session.getMode("ses_config"))).toBe("plan") - yield* ACPNextSession.Service.use((session) => session.setMode("ses_config", "build")) - expect(yield* ACPNextSession.Service.use((session) => session.getVariant("ses_config"))).toBe("high") - expect(yield* ACPNextSession.Service.use((session) => session.getMode("ses_config"))).toBe("build") + yield* ACPSession.Service.use((session) => session.setMode("ses_config", "build")) + expect(yield* ACPSession.Service.use((session) => session.getVariant("ses_config"))).toBe("high") + expect(yield* ACPSession.Service.use((session) => session.getMode("ses_config"))).toBe("build") }), ) sessionTest.effect("records known message part metadata for delta routing", () => Effect.gen(function* () { - yield* ACPNextSession.Service.use((session) => session.create({ id: "ses_parts", cwd: "/workspace" })) + yield* ACPSession.Service.use((session) => session.create({ id: "ses_parts", cwd: "/workspace" })) - const metadata = yield* ACPNextSession.Service.use((session) => + const metadata = yield* ACPSession.Service.use((session) => session.recordPartMetadata({ sessionId: "ses_parts", messageId: "msg_1", @@ -132,7 +132,7 @@ describe("acp-next session state", () => { metadata: { output: "first chunk" }, }), ) - const routed = yield* ACPNextSession.Service.use((session) => + const routed = yield* ACPSession.Service.use((session) => session.getPartMetadata({ sessionId: "ses_parts", messageId: "msg_1", partId: "part_1" }), ) @@ -148,8 +148,8 @@ describe("acp-next session state", () => { sessionTest.effect("keeps repeated part ids distinct across messages", () => Effect.gen(function* () { - yield* ACPNextSession.Service.use((session) => session.create({ id: "ses_duplicate_parts", cwd: "/workspace" })) - yield* ACPNextSession.Service.use((session) => + yield* ACPSession.Service.use((session) => session.create({ id: "ses_duplicate_parts", cwd: "/workspace" })) + yield* ACPSession.Service.use((session) => session.recordPartMetadata({ sessionId: "ses_duplicate_parts", messageId: "msg_1", @@ -157,7 +157,7 @@ describe("acp-next session state", () => { metadata: { output: "from first message" }, }), ) - yield* ACPNextSession.Service.use((session) => + yield* ACPSession.Service.use((session) => session.recordPartMetadata({ sessionId: "ses_duplicate_parts", messageId: "msg_2", @@ -166,10 +166,10 @@ describe("acp-next session state", () => { }), ) - const first = yield* ACPNextSession.Service.use((session) => + const first = yield* ACPSession.Service.use((session) => session.getPartMetadata({ sessionId: "ses_duplicate_parts", messageId: "msg_1", partId: "part_1" }), ) - const second = yield* ACPNextSession.Service.use((session) => + const second = yield* ACPSession.Service.use((session) => session.getPartMetadata({ sessionId: "ses_duplicate_parts", messageId: "msg_2", partId: "part_1" }), ) @@ -180,14 +180,14 @@ describe("acp-next session state", () => { sessionTest.effect("removing a session clears its known part metadata", () => Effect.gen(function* () { - yield* ACPNextSession.Service.use((session) => session.create({ id: "ses_remove", cwd: "/workspace" })) - yield* ACPNextSession.Service.use((session) => + yield* ACPSession.Service.use((session) => session.create({ id: "ses_remove", cwd: "/workspace" })) + yield* ACPSession.Service.use((session) => session.recordPartMetadata({ sessionId: "ses_remove", messageId: "msg_1", partId: "part_1" }), ) - const removed = yield* ACPNextSession.Service.use((session) => session.remove("ses_remove")) - const missing = yield* ACPNextSession.Service.use((session) => session.tryGet("ses_remove")) - const missingPart = yield* ACPNextSession.Service.use((session) => + const removed = yield* ACPSession.Service.use((session) => session.remove("ses_remove")) + const missing = yield* ACPSession.Service.use((session) => session.tryGet("ses_remove")) + const missingPart = yield* ACPSession.Service.use((session) => session.tryGetPartMetadata({ sessionId: "ses_remove", messageId: "msg_1", partId: "part_1" }), ) diff --git a/packages/opencode/test/acp-next/tool.test.ts b/packages/opencode/test/acp/tool.test.ts similarity index 98% rename from packages/opencode/test/acp-next/tool.test.ts rename to packages/opencode/test/acp/tool.test.ts index 0e0cc1e3ffc6..7587f7bbd91b 100644 --- a/packages/opencode/test/acp-next/tool.test.ts +++ b/packages/opencode/test/acp/tool.test.ts @@ -7,9 +7,9 @@ import { shellOutputSnapshot, toLocations, toToolKind, -} from "../../src/acp-next/tool" +} from "../../src/acp/tool" -describe("acp-next tool conversion", () => { +describe("acp tool conversion", () => { test("maps OpenCode tool ids to ACP tool kinds", () => { expect(toToolKind("bash")).toBe("execute") expect(toToolKind("shell")).toBe("execute") diff --git a/packages/opencode/test/acp-next/usage.test.ts b/packages/opencode/test/acp/usage.test.ts similarity index 91% rename from packages/opencode/test/acp-next/usage.test.ts rename to packages/opencode/test/acp/usage.test.ts index 77c17d4f72ea..0366f2321eeb 100644 --- a/packages/opencode/test/acp-next/usage.test.ts +++ b/packages/opencode/test/acp/usage.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test" import type { SessionNotification } from "@agentclientprotocol/sdk" -import { UsageService } from "@/acp-next/usage" -import { ModelID, ProviderID } from "@/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { UsageService } from "@/acp/usage" import { Provider } from "@/provider/provider" import { Effect, Layer } from "effect" import { it } from "../lib/effect" @@ -41,7 +41,7 @@ const assistantWithoutProvider = (): UsageService.SessionMessage => ({ }, }) -const model = (providerID: ProviderID, modelID: ModelID, context: number): Provider.Model => ({ +const model = (providerID: ProviderV2.ID, modelID: ProviderV2.ModelID, context: number): Provider.Model => ({ id: modelID, providerID, api: { @@ -75,9 +75,9 @@ const model = (providerID: ProviderID, modelID: ModelID, context: number): Provi release_date: "2026-01-01", }) -const providers = (context = 128_000): Record => { - const providerID = ProviderID.make("anthropic") - const modelID = ModelID.make("claude-sonnet") +const providers = (context = 128_000): Record => { + const providerID = ProviderV2.ID.make("anthropic") + const modelID = ProviderV2.ModelID.make("claude-sonnet") return { [providerID]: { id: providerID, @@ -94,7 +94,7 @@ const providers = (context = 128_000): Record => { const fakeLayer = (input: { readonly messages?: Effect.Effect - readonly providers?: (directory: string) => Effect.Effect, unknown> + readonly providers?: (directory: string) => Effect.Effect, unknown> }) => UsageService.layer.pipe( Layer.provide( @@ -122,7 +122,7 @@ const connection = (updates: SessionNotification[]) => ({ }, }) -describe("acp-next usage", () => { +describe("acp usage", () => { test("builds ACP Usage from assistant token shape", () => { expect( UsageService.buildUsage({ @@ -178,13 +178,13 @@ describe("acp-next usage", () => { const usage = yield* UsageService.Service const first = yield* usage.contextLimit({ directory: "/workspace", - providerID: ProviderID.make("anthropic"), - modelID: ModelID.make("claude-sonnet"), + providerID: ProviderV2.ID.make("anthropic"), + modelID: ProviderV2.ModelID.make("claude-sonnet"), }) const second = yield* usage.contextLimit({ directory: "/workspace", - providerID: ProviderID.make("anthropic"), - modelID: ModelID.make("claude-sonnet"), + providerID: ProviderV2.ID.make("anthropic"), + modelID: ProviderV2.ModelID.make("claude-sonnet"), }) expect(first).toBe(200_000) diff --git a/packages/opencode/test/agent/plugin-agent-regression.test.ts b/packages/opencode/test/agent/plugin-agent-regression.test.ts index d79e01c78867..60604e811190 100644 --- a/packages/opencode/test/agent/plugin-agent-regression.test.ts +++ b/packages/opencode/test/agent/plugin-agent-regression.test.ts @@ -5,7 +5,7 @@ import { FetchHttpClient } from "effect/unstable/http" import path from "path" import { pathToFileURL } from "url" import { Agent } from "../../src/agent/agent" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "../../src/config/config" import { Env } from "../../src/env" import { RuntimeFlags } from "../../src/effect/runtime-flags" @@ -33,7 +33,7 @@ const configLayer = Config.layer.pipe( Layer.provide(FetchHttpClient.layer), ) const pluginLayer = Plugin.layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(configLayer), Layer.provide(RuntimeFlags.layer({ disableDefaultPlugins: true })), ) diff --git a/packages/opencode/test/auth/auth.test.ts b/packages/opencode/test/auth/auth.test.ts index 55e950aab666..58ce6ea718d0 100644 --- a/packages/opencode/test/auth/auth.test.ts +++ b/packages/opencode/test/auth/auth.test.ts @@ -2,7 +2,6 @@ import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" import { Auth } from "../../src/auth" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { provideTmpdirInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" const node = CrossSpawnSpawner.defaultLayer @@ -10,77 +9,69 @@ const node = CrossSpawnSpawner.defaultLayer const it = testEffect(Layer.mergeAll(Auth.defaultLayer, node)) describe("Auth", () => { - it.live("set normalizes trailing slashes in keys", () => - provideTmpdirInstance(() => - Effect.gen(function* () { - const auth = yield* Auth.Service - yield* auth.set("https://example.com/", { - type: "wellknown", - key: "TOKEN", - token: "abc", - }) - const data = yield* auth.all() - expect(data["https://example.com"]).toBeDefined() - expect(data["https://example.com/"]).toBeUndefined() - }), - ), + it.instance("set normalizes trailing slashes in keys", () => + Effect.gen(function* () { + const auth = yield* Auth.Service + yield* auth.set("https://example.com/", { + type: "wellknown", + key: "TOKEN", + token: "abc", + }) + const data = yield* auth.all() + expect(data["https://example.com"]).toBeDefined() + expect(data["https://example.com/"]).toBeUndefined() + }), ) - it.live("set cleans up pre-existing trailing-slash entry", () => - provideTmpdirInstance(() => - Effect.gen(function* () { - const auth = yield* Auth.Service - yield* auth.set("https://example.com/", { - type: "wellknown", - key: "TOKEN", - token: "old", - }) - yield* auth.set("https://example.com", { - type: "wellknown", - key: "TOKEN", - token: "new", - }) - const data = yield* auth.all() - const keys = Object.keys(data).filter((key) => key.includes("example.com")) - expect(keys).toEqual(["https://example.com"]) - const entry = data["https://example.com"]! - expect(entry.type).toBe("wellknown") - if (entry.type === "wellknown") expect(entry.token).toBe("new") - }), - ), + it.instance("set cleans up pre-existing trailing-slash entry", () => + Effect.gen(function* () { + const auth = yield* Auth.Service + yield* auth.set("https://example.com/", { + type: "wellknown", + key: "TOKEN", + token: "old", + }) + yield* auth.set("https://example.com", { + type: "wellknown", + key: "TOKEN", + token: "new", + }) + const data = yield* auth.all() + const keys = Object.keys(data).filter((key) => key.includes("example.com")) + expect(keys).toEqual(["https://example.com"]) + const entry = data["https://example.com"]! + expect(entry.type).toBe("wellknown") + if (entry.type === "wellknown") expect(entry.token).toBe("new") + }), ) - it.live("remove deletes both trailing-slash and normalized keys", () => - provideTmpdirInstance(() => - Effect.gen(function* () { - const auth = yield* Auth.Service - yield* auth.set("https://example.com", { - type: "wellknown", - key: "TOKEN", - token: "abc", - }) - yield* auth.remove("https://example.com/") - const data = yield* auth.all() - expect(data["https://example.com"]).toBeUndefined() - expect(data["https://example.com/"]).toBeUndefined() - }), - ), + it.instance("remove deletes both trailing-slash and normalized keys", () => + Effect.gen(function* () { + const auth = yield* Auth.Service + yield* auth.set("https://example.com", { + type: "wellknown", + key: "TOKEN", + token: "abc", + }) + yield* auth.remove("https://example.com/") + const data = yield* auth.all() + expect(data["https://example.com"]).toBeUndefined() + expect(data["https://example.com/"]).toBeUndefined() + }), ) - it.live("set and remove are no-ops on keys without trailing slashes", () => - provideTmpdirInstance(() => - Effect.gen(function* () { - const auth = yield* Auth.Service - yield* auth.set("anthropic", { - type: "api", - key: "sk-test", - }) - const data = yield* auth.all() - expect(data["anthropic"]).toBeDefined() - yield* auth.remove("anthropic") - const after = yield* auth.all() - expect(after["anthropic"]).toBeUndefined() - }), - ), + it.instance("set and remove are no-ops on keys without trailing slashes", () => + Effect.gen(function* () { + const auth = yield* Auth.Service + yield* auth.set("anthropic", { + type: "api", + key: "sk-test", + }) + const data = yield* auth.all() + expect(data["anthropic"]).toBeDefined() + yield* auth.remove("anthropic") + const after = yield* auth.all() + expect(after["anthropic"]).toBeUndefined() + }), ) }) diff --git a/packages/opencode/test/bus/bus-effect.test.ts b/packages/opencode/test/bus/bus-effect.test.ts deleted file mode 100644 index dfe653dd1058..000000000000 --- a/packages/opencode/test/bus/bus-effect.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { describe, expect } from "bun:test" -import { Deferred, Effect, Fiber, Latch, Layer, Schema, Stream } from "effect" -import { Bus } from "../../src/bus" -import { BusEvent } from "../../src/bus/bus-event" -import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { disposeAllInstances, provideInstance, tmpdirScoped } from "../fixture/fixture" -import { testEffect } from "../lib/effect" - -const TestEvent = { - Ping: BusEvent.define("test.effect.ping", Schema.Struct({ value: Schema.Number })), - Pong: BusEvent.define("test.effect.pong", Schema.Struct({ message: Schema.String })), - Warmup: BusEvent.define("test.effect.warmup", Schema.Struct({})), -} - -const node = CrossSpawnSpawner.defaultLayer - -const live = Layer.mergeAll(Bus.layer, node) - -const it = testEffect(live) - -// Publishes warmup events until the latch opens, proving the forked subscriber -// fiber has actually wired up its PubSub subscription. -const awaitSubscriberReady = Effect.fn("test.awaitSubscriberReady")(function* ( - ready: Latch.Latch, - warmup: Effect.Effect, -) { - const pump = yield* Effect.forkScoped( - Effect.gen(function* () { - while (true) { - yield* warmup - yield* Effect.sleep("5 millis") - } - }), - ) - yield* ready.await.pipe(Effect.timeout("2 seconds")) - yield* Fiber.interrupt(pump) -}) - -describe("Bus (Effect-native)", () => { - it.instance("publish + subscribe stream delivers events", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: number[] = [] - const done = yield* Deferred.make() - const ready = yield* Latch.make() - - yield* Stream.runForEach(yield* bus.subscribe(TestEvent.Ping), (evt) => - Effect.gen(function* () { - if (evt.properties.value < 0) { - yield* ready.open - return - } - received.push(evt.properties.value) - if (received.length === 2) Deferred.doneUnsafe(done, Effect.void) - }), - ).pipe(Effect.forkScoped) - - yield* awaitSubscriberReady(ready, bus.publish(TestEvent.Ping, { value: -1 })) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* bus.publish(TestEvent.Ping, { value: 2 }) - yield* Deferred.await(done) - - expect(received).toEqual([1, 2]) - }), - ) - - it.instance("subscribe filters by event type", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const pings: number[] = [] - const done = yield* Deferred.make() - const ready = yield* Latch.make() - - yield* Stream.runForEach(yield* bus.subscribe(TestEvent.Ping), (evt) => - Effect.gen(function* () { - if (evt.properties.value < 0) { - yield* ready.open - return - } - pings.push(evt.properties.value) - Deferred.doneUnsafe(done, Effect.void) - }), - ).pipe(Effect.forkScoped) - - yield* awaitSubscriberReady(ready, bus.publish(TestEvent.Ping, { value: -1 })) - yield* bus.publish(TestEvent.Pong, { message: "ignored" }) - yield* bus.publish(TestEvent.Ping, { value: 42 }) - yield* Deferred.await(done) - - expect(pings).toEqual([42]) - }), - ) - - it.instance("subscribeAll receives all types", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const types: string[] = [] - const done = yield* Deferred.make() - const ready = yield* Latch.make() - - yield* Stream.runForEach(yield* bus.subscribeAll(), (evt) => - Effect.gen(function* () { - if (evt.type === TestEvent.Warmup.type) { - yield* ready.open - return - } - types.push(evt.type) - if (types.length === 2) Deferred.doneUnsafe(done, Effect.void) - }), - ).pipe(Effect.forkScoped) - - yield* awaitSubscriberReady(ready, bus.publish(TestEvent.Warmup, {})) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* bus.publish(TestEvent.Pong, { message: "hi" }) - yield* Deferred.await(done) - - expect(types).toContain("test.effect.ping") - expect(types).toContain("test.effect.pong") - }), - ) - - it.instance("multiple subscribers each receive the event", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const a: number[] = [] - const b: number[] = [] - const doneA = yield* Deferred.make() - const doneB = yield* Deferred.make() - const readyA = yield* Latch.make() - const readyB = yield* Latch.make() - - yield* Stream.runForEach(yield* bus.subscribe(TestEvent.Ping), (evt) => - Effect.gen(function* () { - if (evt.properties.value < 0) { - yield* readyA.open - return - } - a.push(evt.properties.value) - Deferred.doneUnsafe(doneA, Effect.void) - }), - ).pipe(Effect.forkScoped) - - yield* Stream.runForEach(yield* bus.subscribe(TestEvent.Ping), (evt) => - Effect.gen(function* () { - if (evt.properties.value < 0) { - yield* readyB.open - return - } - b.push(evt.properties.value) - Deferred.doneUnsafe(doneB, Effect.void) - }), - ).pipe(Effect.forkScoped) - - yield* awaitSubscriberReady(readyA, bus.publish(TestEvent.Ping, { value: -1 })) - yield* awaitSubscriberReady(readyB, bus.publish(TestEvent.Ping, { value: -1 })) - yield* bus.publish(TestEvent.Ping, { value: 99 }) - yield* Deferred.await(doneA) - yield* Deferred.await(doneB) - - expect(a).toEqual([99]) - expect(b).toEqual([99]) - }), - ) - - // RACE 1: eager subscription means publishing immediately after yield* - // bus.subscribe is delivered. Regression for the old lazy `Stream.unwrap` - // shape where PubSub.subscribe ran on first pull and missed any publish - // in the hand-off window. - it.instance("eager subscribe: publish after yield* is delivered without consumer-activation race", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const stream = yield* bus.subscribe(TestEvent.Ping) - - // Hand-off window: subscription is alive (we yielded). Publish goes - // straight into the subscription queue, even with no consumer running. - yield* bus.publish(TestEvent.Ping, { value: 99 }) - - const collected = yield* stream.pipe( - Stream.take(1), - Stream.runCollect, - Effect.timeout("400 millis"), - Effect.option, - ) - - expect(collected._tag).toBe("Some") - if (collected._tag === "Some") { - const arr = Array.from(collected.value) - expect(arr[0].properties.value).toBe(99) - } - }), - ) - - // RACE 2: same property for subscribeAll. - it.instance("eager subscribeAll: publish after yield* is delivered", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const stream = yield* bus.subscribeAll() - - yield* bus.publish(TestEvent.Ping, { value: 42 }) - - const collected = yield* stream.pipe( - Stream.take(1), - Stream.runCollect, - Effect.timeout("400 millis"), - Effect.option, - ) - - expect(collected._tag).toBe("Some") - if (collected._tag === "Some") { - const arr = Array.from(collected.value) - expect(arr[0].type).toBe(TestEvent.Ping.type) - } - }), - ) - - // RACE 3: the /event-handler shape exactly. With eager subscription, the - // bus subscription is alive before Stream.concat ever starts. Publishes - // during the prefix consumption window are queued and delivered. - it.instance("eager subscribe: Stream.concat(initial, subscribe) delivers publish during prefix", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const sawInitial = yield* Deferred.make() - const sawPublish = yield* Deferred.make() - - type Frame = { marker?: "initial"; value?: number } - const subscriptionStream = yield* bus.subscribe(TestEvent.Ping) - const handlerStream: Stream.Stream = Stream.make({ marker: "initial" } as Frame).pipe( - Stream.concat(subscriptionStream.pipe(Stream.map((evt): Frame => ({ value: evt.properties.value })))), - ) - - yield* Stream.runForEach(handlerStream, (frame) => - Effect.gen(function* () { - if (frame.marker === "initial") { - Deferred.doneUnsafe(sawInitial, Effect.void) - return - } - if (frame.value !== undefined) Deferred.doneUnsafe(sawPublish, Effect.succeed(frame.value)) - }), - ).pipe(Effect.forkScoped) - - yield* Deferred.await(sawInitial).pipe(Effect.timeout("1 second")) - - yield* bus.publish(TestEvent.Ping, { value: 7 }) - - const got = yield* Deferred.await(sawPublish).pipe(Effect.timeout("1 second"), Effect.option) - expect(got._tag).toBe("Some") - if (got._tag === "Some") expect(got.value).toBe(7) - }), - ) - - it.live("subscribeAll stream sees InstanceDisposed on disposal", () => - Effect.gen(function* () { - const dir = yield* tmpdirScoped() - const types: string[] = [] - const seen = yield* Deferred.make() - const disposed = yield* Deferred.make() - const ready = yield* Latch.make() - - // Set up subscriber inside the instance - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - - yield* Stream.runForEach(yield* bus.subscribeAll(), (evt) => - Effect.gen(function* () { - if (evt.type === TestEvent.Warmup.type) { - yield* ready.open - return - } - types.push(evt.type) - if (evt.type === TestEvent.Ping.type) Deferred.doneUnsafe(seen, Effect.void) - if (evt.type === Bus.InstanceDisposed.type) Deferred.doneUnsafe(disposed, Effect.void) - }), - ).pipe(Effect.forkScoped) - - yield* awaitSubscriberReady(ready, bus.publish(TestEvent.Warmup, {})) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* Deferred.await(seen) - }).pipe(provideInstance(dir)) - - // Dispose from OUTSIDE the instance scope - yield* Effect.promise(disposeAllInstances) - yield* Deferred.await(disposed).pipe(Effect.timeout("2 seconds")) - - expect(types).toContain("test.effect.ping") - expect(types).toContain(Bus.InstanceDisposed.type) - }), - ) -}) diff --git a/packages/opencode/test/bus/bus-integration.test.ts b/packages/opencode/test/bus/bus-integration.test.ts deleted file mode 100644 index 645a94fb3b6f..000000000000 --- a/packages/opencode/test/bus/bus-integration.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { afterEach, describe, expect } from "bun:test" -import { Deferred, Effect, Layer, Schema } from "effect" -import { Bus } from "../../src/bus" -import { BusEvent } from "../../src/bus/bus-event" -import { disposeAllInstances, provideInstance, tmpdirScoped } from "../fixture/fixture" -import { testEffect } from "../lib/effect" - -const TestEvent = BusEvent.define("test.integration", Schema.Struct({ value: Schema.Number })) -const it = testEffect(Layer.mergeAll(Bus.layer, CrossSpawnSpawner.defaultLayer)) - -describe("Bus integration: acquireRelease subscriber pattern", () => { - afterEach(() => disposeAllInstances()) - - it.instance("subscriber via callback facade receives events and cleans up on unsub", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: number[] = [] - const receivedTwo = yield* Deferred.make() - - const unsub = yield* bus.subscribeCallback(TestEvent, (evt) => { - received.push(evt.properties.value) - if (received.length === 2) Deferred.doneUnsafe(receivedTwo, Effect.void) - }) - yield* bus.publish(TestEvent, { value: 1 }) - yield* bus.publish(TestEvent, { value: 2 }) - yield* Deferred.await(receivedTwo).pipe(Effect.timeout("2 seconds")) - - expect(received).toEqual([1, 2]) - - yield* Effect.sync(unsub) - yield* bus.publish(TestEvent, { value: 3 }) - yield* Effect.sleep("10 millis") - - expect(received).toEqual([1, 2]) - }), - ) - - it.instance("subscribeAll receives events from multiple types", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: Array<{ type: string; value?: number }> = [] - const OtherEvent = BusEvent.define("test.other", Schema.Struct({ value: Schema.Number })) - const receivedTwo = yield* Deferred.make() - - yield* bus.subscribeAllCallback((evt) => { - received.push({ type: evt.type, value: evt.properties.value }) - if (received.length === 2) Deferred.doneUnsafe(receivedTwo, Effect.void) - }) - yield* bus.publish(TestEvent, { value: 10 }) - yield* bus.publish(OtherEvent, { value: 20 }) - yield* Deferred.await(receivedTwo).pipe(Effect.timeout("2 seconds")) - - expect(received).toEqual([ - { type: "test.integration", value: 10 }, - { type: "test.other", value: 20 }, - ]) - }), - ) - - it.live("subscriber cleanup on instance disposal interrupts the stream", () => - Effect.gen(function* () { - const dir = yield* tmpdirScoped() - const received: number[] = [] - const seen = yield* Deferred.make() - const disposed = yield* Deferred.make() - - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.subscribeAllCallback((evt) => { - if (evt.type === Bus.InstanceDisposed.type) { - Deferred.doneUnsafe(disposed, Effect.void) - return - } - received.push(evt.properties.value) - Deferred.doneUnsafe(seen, Effect.void) - }) - yield* bus.publish(TestEvent, { value: 1 }) - yield* Deferred.await(seen).pipe(Effect.timeout("2 seconds")) - }).pipe(provideInstance(dir)) - - yield* Effect.promise(() => disposeAllInstances()) - yield* Deferred.await(disposed).pipe(Effect.timeout("2 seconds")) - - expect(received).toEqual([1]) - }), - ) -}) diff --git a/packages/opencode/test/bus/bus.test.ts b/packages/opencode/test/bus/bus.test.ts deleted file mode 100644 index 08449861621c..000000000000 --- a/packages/opencode/test/bus/bus.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { afterEach, describe, expect } from "bun:test" -import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { Deferred, Effect, Layer, Schema } from "effect" -import { Bus } from "../../src/bus" -import { BusEvent } from "../../src/bus/bus-event" -import { disposeAllInstances, provideInstance, tmpdirScoped } from "../fixture/fixture" -import { testEffect } from "../lib/effect" - -const TestEvent = { - Ping: BusEvent.define("test.ping", Schema.Struct({ value: Schema.Number })), - Pong: BusEvent.define("test.pong", Schema.Struct({ message: Schema.String })), -} - -const it = testEffect(Layer.mergeAll(Bus.layer, CrossSpawnSpawner.defaultLayer)) - -describe("Bus", () => { - afterEach(() => disposeAllInstances()) - - describe("publish + subscribe", () => { - it.instance("subscriber is live immediately after subscribe returns", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: number[] = [] - const done = yield* Deferred.make() - - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - received.push(evt.properties.value) - Deferred.doneUnsafe(done, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 42 }) - yield* Deferred.await(done).pipe(Effect.timeout("2 seconds")) - - expect(received).toEqual([42]) - }), - ) - - it.instance("subscriber receives matching events", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: number[] = [] - const done = yield* Deferred.make() - - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - received.push(evt.properties.value) - if (received.length === 2) Deferred.doneUnsafe(done, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 42 }) - yield* bus.publish(TestEvent.Ping, { value: 99 }) - yield* Deferred.await(done).pipe(Effect.timeout("2 seconds")) - - expect(received).toEqual([42, 99]) - }), - ) - - it.instance("subscriber does not receive events of other types", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const pings: number[] = [] - const done = yield* Deferred.make() - - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - pings.push(evt.properties.value) - Deferred.doneUnsafe(done, Effect.void) - }) - yield* bus.publish(TestEvent.Pong, { message: "hello" }) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* Deferred.await(done).pipe(Effect.timeout("2 seconds")) - - expect(pings).toEqual([1]) - }), - ) - - it.instance("publish with no subscribers does not throw", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.publish(TestEvent.Ping, { value: 1 }) - }), - ) - }) - - describe("unsubscribe", () => { - it.instance("unsubscribe stops delivery", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: number[] = [] - const first = yield* Deferred.make() - - const unsub = yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - received.push(evt.properties.value) - if (evt.properties.value === 1) Deferred.doneUnsafe(first, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* Deferred.await(first).pipe(Effect.timeout("2 seconds")) - yield* Effect.sync(unsub) - yield* bus.publish(TestEvent.Ping, { value: 2 }) - yield* Effect.sleep("10 millis") - - expect(received).toEqual([1]) - }), - ) - }) - - describe("subscribeAll", () => { - it.instance("subscribeAll is live immediately after subscribe returns", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: string[] = [] - const done = yield* Deferred.make() - - yield* bus.subscribeAllCallback((evt) => { - received.push(evt.type) - Deferred.doneUnsafe(done, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* Deferred.await(done).pipe(Effect.timeout("2 seconds")) - - expect(received).toEqual(["test.ping"]) - }), - ) - - it.instance("receives all event types", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const received: string[] = [] - const done = yield* Deferred.make() - - yield* bus.subscribeAllCallback((evt) => { - received.push(evt.type) - if (received.length === 2) Deferred.doneUnsafe(done, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* bus.publish(TestEvent.Pong, { message: "hi" }) - yield* Deferred.await(done).pipe(Effect.timeout("2 seconds")) - - expect(received).toContain("test.ping") - expect(received).toContain("test.pong") - }), - ) - }) - - describe("multiple subscribers", () => { - it.instance("all subscribers for same event type are called", () => - Effect.gen(function* () { - const bus = yield* Bus.Service - const a: number[] = [] - const b: number[] = [] - const doneA = yield* Deferred.make() - const doneB = yield* Deferred.make() - - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - a.push(evt.properties.value) - Deferred.doneUnsafe(doneA, Effect.void) - }) - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - b.push(evt.properties.value) - Deferred.doneUnsafe(doneB, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 7 }) - yield* Deferred.await(doneA).pipe(Effect.timeout("2 seconds")) - yield* Deferred.await(doneB).pipe(Effect.timeout("2 seconds")) - - expect(a).toEqual([7]) - expect(b).toEqual([7]) - }), - ) - }) - - describe("instance isolation", () => { - it.live("events in one directory do not reach subscribers in another", () => - Effect.gen(function* () { - const tmpA = yield* tmpdirScoped() - const tmpB = yield* tmpdirScoped() - const receivedA: number[] = [] - const receivedB: number[] = [] - const doneA = yield* Deferred.make() - const doneB = yield* Deferred.make() - - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - receivedA.push(evt.properties.value) - Deferred.doneUnsafe(doneA, Effect.void) - }) - }).pipe(provideInstance(tmpA)) - - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.subscribeCallback(TestEvent.Ping, (evt) => { - receivedB.push(evt.properties.value) - Deferred.doneUnsafe(doneB, Effect.void) - }) - }).pipe(provideInstance(tmpB)) - - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.publish(TestEvent.Ping, { value: 1 }) - }).pipe(provideInstance(tmpA)) - - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.publish(TestEvent.Ping, { value: 2 }) - }).pipe(provideInstance(tmpB)) - - yield* Deferred.await(doneA).pipe(Effect.timeout("2 seconds")) - yield* Deferred.await(doneB).pipe(Effect.timeout("2 seconds")) - - expect(receivedA).toEqual([1]) - expect(receivedB).toEqual([2]) - }), - ) - }) - - describe("instance disposal", () => { - it.live("InstanceDisposed is delivered to wildcard subscribers before stream ends", () => - Effect.gen(function* () { - const tmp = yield* tmpdirScoped() - const received: string[] = [] - const seen = yield* Deferred.make() - const disposed = yield* Deferred.make() - - yield* Effect.gen(function* () { - const bus = yield* Bus.Service - yield* bus.subscribeAllCallback((evt) => { - received.push(evt.type) - if (evt.type === TestEvent.Ping.type) Deferred.doneUnsafe(seen, Effect.void) - if (evt.type === Bus.InstanceDisposed.type) Deferred.doneUnsafe(disposed, Effect.void) - }) - yield* bus.publish(TestEvent.Ping, { value: 1 }) - yield* Deferred.await(seen).pipe(Effect.timeout("2 seconds")) - }).pipe(provideInstance(tmp)) - - yield* Effect.promise(disposeAllInstances) - yield* Deferred.await(disposed).pipe(Effect.timeout("2 seconds")) - - expect(received).toContain("test.ping") - expect(received).toContain(Bus.InstanceDisposed.type) - }), - ) - }) -}) diff --git a/packages/opencode/test/cli/acp-next/acp-next-process.test.ts b/packages/opencode/test/cli/acp-next/acp-next-process.test.ts deleted file mode 100644 index 426f8225bf1c..000000000000 --- a/packages/opencode/test/cli/acp-next/acp-next-process.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect } from "bun:test" -import type { - AuthenticateResponse, - InitializeResponse, - LoadSessionResponse, - NewSessionResponse, - SessionNotification, -} from "@agentclientprotocol/sdk" -import { Effect } from "effect" -import { cliIt } from "../../lib/cli-process" -import { testProviderConfig } from "../../lib/test-provider" -import { createAcpClient, expectOk, selectConfigOption } from "../acp/acp-test-client" - -describe("opencode acp-next (subprocess)", () => { - cliIt.live( - "responds to initialize behind OPENCODE_ACP_NEXT", - ({ opencode }) => - Effect.gen(function* () { - const acp = createAcpClient(yield* opencode.acp({ env: { OPENCODE_ACP_NEXT: "1" } })) - const initialized = expectOk( - yield* acp.request("initialize", { - protocolVersion: 1, - clientCapabilities: { _meta: { "terminal-auth": true } }, - }), - ) - - expect(initialized.protocolVersion).toBe(1) - expect(initialized.agentCapabilities?.promptCapabilities?.embeddedContext).toBe(true) - expect(initialized.agentCapabilities?.promptCapabilities?.image).toBe(true) - expect(initialized.agentCapabilities?.mcpCapabilities?.http).toBe(true) - expect(initialized.agentCapabilities?.mcpCapabilities?.sse).toBe(true) - expect(initialized.agentCapabilities?.loadSession).toBe(true) - expect(initialized.agentCapabilities?.sessionCapabilities).toBeUndefined() - expect(initialized.agentInfo?.name).toBe("OpenCode") - expect(initialized.authMethods?.[0]?.id).toBe("opencode-login") - expect(initialized.authMethods?.[0]?._meta?.["terminal-auth"]).toBeDefined() - }), - 60_000, - ) - - cliIt.live( - "authenticate succeeds for the advertised auth method and rejects unknown methods safely", - ({ opencode }) => - Effect.gen(function* () { - const acp = createAcpClient(yield* opencode.acp({ env: { OPENCODE_ACP_NEXT: "1" } })) - const initialized = expectOk(yield* acp.request("initialize", { protocolVersion: 1 })) - const methodId = initialized.authMethods?.[0]?.id - expect(methodId).toBe("opencode-login") - - expectOk(yield* acp.request("authenticate", { methodId })) - - const rejected = yield* acp.request("authenticate", { methodId: "missing-auth-method" }) - expect(errorCode(rejected.error)).toBe(-32602) - }), - 60_000, - ) - - cliIt.live( - "creates and loads sessions behind OPENCODE_ACP_NEXT", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_ACP_NEXT: "1", - OPENCODE_CONFIG_CONTENT: JSON.stringify(testProviderConfig(llm.url)), - }, - }), - ) - yield* acp.request("initialize", { protocolVersion: 1 }) - - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - expect(typeof session.sessionId).toBe("string") - expect(selectConfigOption(session.configOptions, "model")?.category).toBe("model") - - const update = yield* acp.waitForNotification( - "session/update", - (params) => - params.sessionId === session.sessionId && params.update.sessionUpdate === "available_commands_update", - ) - expect(update.params?.sessionId).toBe(session.sessionId) - - const loaded = expectOk( - yield* acp.request("session/load", { - cwd: home, - sessionId: session.sessionId, - mcpServers: [], - }), - ) - expect(selectConfigOption(loaded.configOptions, "model")?.category).toBe("model") - - const prompt = yield* acp.request("session/prompt", { - sessionId: "ses_missing", - prompt: [{ type: "text", text: "hello" }], - }) - expect(errorCode(prompt.error)).toBe(-32601) - }), - 60_000, - ) - - cliIt.live( - "exits cleanly when flagged stdin is closed", - ({ opencode }) => - Effect.gen(function* () { - const exitedPromise = yield* Effect.scoped( - Effect.gen(function* () { - const acp = yield* opencode.acp({ env: { OPENCODE_ACP_NEXT: "1" } }) - return acp.exited - }), - ) - - const code = yield* Effect.promise(() => exitedPromise) - expect(typeof code === "number" || code === null).toBe(true) - }), - 60_000, - ) - - cliIt.live( - "default unflagged path still uses production ACP", - ({ opencode }) => - Effect.gen(function* () { - const acp = createAcpClient(yield* opencode.acp()) - const initialized = expectOk(yield* acp.request("initialize", { protocolVersion: 1 })) - - expect(initialized.agentCapabilities?.sessionCapabilities?.close).toEqual({}) - expect(initialized.agentCapabilities?.sessionCapabilities?.resume).toEqual({}) - }), - 60_000, - ) -}) - -function errorCode(error: unknown) { - if (!error || typeof error !== "object") return undefined - if (!("code" in error)) return undefined - return typeof error.code === "number" ? error.code : undefined -} diff --git a/packages/opencode/test/cli/acp/acp-compatibility-baseline.test.ts b/packages/opencode/test/cli/acp/acp-compatibility-baseline.test.ts deleted file mode 100644 index 535203938319..000000000000 --- a/packages/opencode/test/cli/acp/acp-compatibility-baseline.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { describe, expect } from "bun:test" -import type { - CloseSessionResponse, - InitializeResponse, - NewSessionResponse, - ResumeSessionResponse, - SessionNotification, - SetSessionConfigOptionResponse, -} from "@agentclientprotocol/sdk" -import { Effect } from "effect" -import { mkdir } from "node:fs/promises" -import path from "node:path" -import { cliIt } from "../../lib/cli-process" -import { testProviderConfig } from "../../lib/test-provider" -import { - createAcpClient, - expectOk, - firstAlternateValue, - flattenSelectOptions, - selectConfigOption, -} from "./acp-test-client" - -describe("opencode acp verifier compatibility baseline", () => { - cliIt.live( - "initialize advertises close and resume capabilities", - ({ opencode }) => - Effect.gen(function* () { - const acp = createAcpClient(yield* opencode.acp()) - const initialized = expectOk( - yield* acp.request("initialize", { - protocolVersion: 1, - }), - ) - - expect(initialized.protocolVersion).toBe(1) - expect(initialized.agentCapabilities?.sessionCapabilities?.close).toEqual({}) - expect(initialized.agentCapabilities?.sessionCapabilities?.resume).toEqual({}) - }), - 60_000, - ) - - cliIt.live( - "first session timing diagnostic stays bounded and returns model options", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)), - }, - }), - ) - const started = Date.now() - yield* acp.request("initialize", { - protocolVersion: 1, - clientCapabilities: {}, - clientInfo: { name: "opencode-local-acp-baseline", version: "0.1.0" }, - }) - const session = expectOk( - yield* acp.request("session/new", { - cwd: home, - mcpServers: [], - }), - ) - const durationMs = Date.now() - started - expect(durationMs).toBeLessThan(15_000) - - const model = selectConfigOption(session.configOptions, "model") - expect(model?.category).toBe("model") - expect(model?.currentValue).toBe("test/test-model") - expect(model ? flattenSelectOptions(model).length : 0).toBeGreaterThanOrEqual(2) - }), - 60_000, - ) - - cliIt.live( - "warm newSession timing diagnostic stays bounded", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)), - }, - }), - ) - yield* acp.request("initialize", { protocolVersion: 1 }) - yield* acp.request("session/new", { cwd: home, mcpServers: [] }) - - const started = Date.now() - const session = expectOk( - yield* acp.request("session/new", { - cwd: home, - mcpServers: [], - }), - ) - const durationMs = Date.now() - started - expect(durationMs).toBeLessThan(15_000) - expect(session.sessionId).toBeTruthy() - }), - 60_000, - ) - - cliIt.live( - "model switch timing diagnostic updates currentValue", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)), - }, - }), - ) - yield* acp.request("initialize", { protocolVersion: 1 }) - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - const model = selectConfigOption(session.configOptions, "model") - expect(model).toBeDefined() - const nextModel = model - ? flattenSelectOptions(model).find((option) => option.value === "test/second-model")?.value - : undefined - expect(nextModel).toBe("test/second-model") - - const started = Date.now() - const updated = expectOk( - yield* acp.request("session/set_config_option", { - sessionId: session.sessionId, - configId: "model", - value: nextModel, - }), - ) - const durationMs = Date.now() - started - - expect(durationMs).toBeLessThan(15_000) - expect(selectConfigOption(updated.configOptions, "model")?.currentValue).toBe(nextModel) - }), - 60_000, - ) - - cliIt.live( - "effort option is listed for variant-capable models and can switch", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)), - }, - }), - ) - yield* acp.request("initialize", { protocolVersion: 1 }) - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - const effort = selectConfigOption(session.configOptions, "effort") - expect(effort?.category).toBe("thought_level") - const nextEffort = effort ? firstAlternateValue(effort) : undefined - expect(nextEffort).toBe("high") - - const updated = expectOk( - yield* acp.request("session/set_config_option", { - sessionId: session.sessionId, - configId: "effort", - value: nextEffort, - }), - ) - - expect(selectConfigOption(updated.configOptions, "effort")?.currentValue).toBe(nextEffort) - }), - 60_000, - ) - - cliIt.live( - "default test provider documents missing effort option when the model has no variants", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_CONFIG_CONTENT: JSON.stringify(noVariantConfig(llm.url)), - }, - }), - ) - yield* acp.request("initialize", { protocolVersion: 1 }) - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - - expect(selectConfigOption(session.configOptions, "model")?.currentValue).toBe("test/test-model") - expect(selectConfigOption(session.configOptions, "effort")).toBeUndefined() - }), - 60_000, - ) - - cliIt.live( - "skill slash command timing diagnostic appears through available_commands_update", - ({ home, llm, opencode }) => - Effect.gen(function* () { - const skills = path.join(home, "skills") - yield* Effect.promise(() => mkdir(path.join(skills, "verifier-skill"), { recursive: true })) - yield* Effect.promise(() => Bun.write(path.join(skills, "verifier-skill", "SKILL.md"), verifierSkill)) - const acp = createAcpClient( - yield* opencode.acp({ - env: { - OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url, skills)), - }, - }), - ) - yield* acp.request("initialize", { protocolVersion: 1 }) - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - - const update = yield* acp.waitForNotification( - "session/update", - (params) => - params.sessionId === session.sessionId && - params.update.sessionUpdate === "available_commands_update" && - params.update.availableCommands.some((command) => command.name === "verifier-skill"), - ) - - expect(update.params?.sessionId).toBe(session.sessionId) - - const secondSession = expectOk( - yield* acp.request("session/new", { cwd: home, mcpServers: [] }), - ) - const started = Date.now() - yield* acp.waitForNotification( - "session/update", - (params) => - params.sessionId === secondSession.sessionId && - params.update.sessionUpdate === "available_commands_update" && - params.update.availableCommands.some((command) => command.name === "verifier-skill"), - ) - const durationMs = Date.now() - started - expect(durationMs).toBeLessThan(15_000) - }), - 60_000, - ) - - cliIt.live( - "close request succeeds for a live session", - ({ home, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient(yield* opencode.acp()) - yield* acp.request("initialize", { protocolVersion: 1 }) - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - - expectOk(yield* acp.request("session/close", { sessionId: session.sessionId })) - }), - 60_000, - ) - - cliIt.live( - "resume request succeeds for a created session", - ({ home, opencode }) => - Effect.gen(function* () { - const acp = createAcpClient(yield* opencode.acp()) - yield* acp.request("initialize", { protocolVersion: 1 }) - const session = expectOk(yield* acp.request("session/new", { cwd: home, mcpServers: [] })) - - const resumed = expectOk( - yield* acp.request("session/resume", { - sessionId: session.sessionId, - cwd: home, - mcpServers: [], - }), - ) - expect(resumed.configOptions?.length).toBeGreaterThan(0) - }), - 60_000, - ) -}) - -function verifierConfig(llmUrl: string, skills?: string) { - const config = testProviderConfig(llmUrl) - return { - ...config, - model: "test/test-model", - ...(skills ? { skills: { paths: [skills] } } : {}), - provider: { - test: { - ...config.provider.test, - models: { - "test-model": { - ...config.provider.test.models["test-model"], - variants: { - low: {}, - high: {}, - }, - }, - "second-model": { - ...config.provider.test.models["test-model"], - id: "second-model", - name: "Second Test Model", - }, - }, - }, - }, - } -} - -function noVariantConfig(llmUrl: string) { - const config = verifierConfig(llmUrl) - return { - ...config, - provider: { - test: { - ...config.provider.test, - models: { - "test-model": { - ...config.provider.test.models["test-model"], - variants: undefined, - }, - "second-model": config.provider.test.models["second-model"], - }, - }, - }, - } -} - -const verifierSkill = `--- -name: verifier-skill -description: Verifier compatibility skill. ---- - -# Verifier Skill -` diff --git a/packages/opencode/test/cli/acp/acp-process.test.ts b/packages/opencode/test/cli/acp/acp-process.test.ts deleted file mode 100644 index a3c244c6c8ce..000000000000 --- a/packages/opencode/test/cli/acp/acp-process.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Subprocess integration tests for `opencode acp`. ACP is a JSON-RPC -// protocol spoken over stdin/stdout (not HTTP) — see src/acp/README.md. -// This is the only test tier that exercises the full pipe of bun startup → -// server boot → ACP agent init → stdio framing → graceful shutdown. -import { describe, expect } from "bun:test" -import { Duration, Effect } from "effect" -import { cliIt } from "../../lib/cli-process" - -describe("opencode acp (subprocess)", () => { - // Smoke test: send the `initialize` request from src/acp/README.md and - // assert the response advertises the same protocol version and a non-empty - // capabilities block. If this fails, every other ACP test will too — start - // debugging here. - cliIt.live( - "responds to initialize with protocolVersion 1 and capabilities", - ({ opencode }) => - Effect.gen(function* () { - const acp = yield* opencode.acp() - - yield* acp.send({ - jsonrpc: "2.0", - id: 1, - method: "initialize", - params: { protocolVersion: 1 }, - }) - - // Tight deadline — the response should arrive within a few seconds - // once startup completes. A hang means the agent never finished init, - // which is a real regression and not a tuning issue. - const response = (yield* acp.receive.pipe(Effect.timeout(Duration.seconds(10)))) as { - jsonrpc: string - id: number - result?: { protocolVersion: number; agentCapabilities: Record } - error?: unknown - } - - expect(response.jsonrpc).toBe("2.0") - expect(response.id).toBe(1) - expect(response.error).toBeUndefined() - expect(response.result?.protocolVersion).toBe(1) - expect(response.result?.agentCapabilities).toBeDefined() - }), - 60_000, - ) - - // Lock in the scope-close kill path. ACP's clean shutdown is "EOF on stdin" - // — if a future refactor breaks the stdin-end branch in the handler, the - // process would only exit on SIGTERM fallback (2s in the harness). This - // test passing within the inner-scope assertion proves the EOF path works. - cliIt.live( - "exits cleanly when stdin is closed (scope close)", - ({ opencode }) => - Effect.gen(function* () { - const exitedPromise = yield* Effect.scoped( - Effect.gen(function* () { - const acp = yield* opencode.acp() - // Capture the Promise — scope-close fires the finalizer which - // ends stdin, and ACP should exit gracefully. - return acp.exited - }), - ) - - const code = yield* Effect.promise(() => exitedPromise) - // Bun returns a number for normal exit. Anything goes for SIGTERM, - // but we still require resolution within the test timeout. - expect(typeof code === "number" || code === null).toBe(true) - }), - 60_000, - ) -}) diff --git a/packages/opencode/test/cli/acp/config-options.test.ts b/packages/opencode/test/cli/acp/config-options.test.ts new file mode 100644 index 000000000000..0c712f0f2331 --- /dev/null +++ b/packages/opencode/test/cli/acp/config-options.test.ts @@ -0,0 +1,103 @@ +import { describe, expect } from "bun:test" +import type { SetSessionConfigOptionResponse } from "@agentclientprotocol/sdk" +import { Effect } from "effect" +import { cliIt } from "../../lib/cli-process" +import { expectOk, flattenSelectOptions, selectConfigOption } from "./acp-test-client" +import { + createAcpClient, + expectAlternateValue, + expectSelectOption, + initialize, + newSession, + verifierConfig, +} from "./helpers" + +describe("opencode acp config option subprocess", () => { + cliIt.live( + 'model option is listed with category "model"', + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + yield* initialize(acp) + const model = expectSelectOption((yield* newSession(acp, home)).configOptions, "model") + + expect(model.category).toBe("model") + expect(model.currentValue).toBe("test/test-model") + expect(flattenSelectOptions(model).length).toBeGreaterThanOrEqual(2) + }), + 60_000, + ) + + cliIt.live( + "model switch updates currentValue", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + yield* initialize(acp) + const session = yield* newSession(acp, home) + const model = expectSelectOption(session.configOptions, "model") + const nextModel = flattenSelectOptions(model).find((option) => option.value === "test/second-model")?.value + expect(nextModel).toBe("test/second-model") + + const updated = expectOk( + yield* acp.request("session/set_config_option", { + sessionId: session.sessionId, + configId: "model", + value: nextModel, + }), + ) + + expect(selectConfigOption(updated.configOptions, "model")?.currentValue).toBe(nextModel) + }), + 60_000, + ) + + cliIt.live( + 'effort option is listed with category "thought_level" when selected model supports variants', + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + yield* initialize(acp) + const effort = expectSelectOption((yield* newSession(acp, home)).configOptions, "effort") + + expect(effort.category).toBe("thought_level") + expect(effort.currentValue).toBe("low") + expect(flattenSelectOptions(effort).map((option) => option.value)).toEqual(["low", "high"]) + }), + 60_000, + ) + + cliIt.live( + "effort switch updates currentValue", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + yield* initialize(acp) + const session = yield* newSession(acp, home) + const nextEffort = expectAlternateValue(expectSelectOption(session.configOptions, "effort")) + + const updated = expectOk( + yield* acp.request("session/set_config_option", { + sessionId: session.sessionId, + configId: "effort", + value: nextEffort, + }), + ) + + expect(selectConfigOption(updated.configOptions, "effort")?.currentValue).toBe(nextEffort) + }), + 60_000, + ) +}) diff --git a/packages/opencode/test/cli/acp/helpers.ts b/packages/opencode/test/cli/acp/helpers.ts new file mode 100644 index 000000000000..92c560d941ca --- /dev/null +++ b/packages/opencode/test/cli/acp/helpers.ts @@ -0,0 +1,96 @@ +import { expect } from "bun:test" +import type { InitializeResponse, NewSessionResponse, SessionConfigOption } from "@agentclientprotocol/sdk" +import { Effect } from "effect" +import type { CliFixture } from "../../lib/cli-process" +import { testProviderConfig } from "../../lib/test-provider" +import { + createAcpClient as createJsonRpcAcpClient, + expectOk, + flattenSelectOptions, + selectConfigOption, + type AcpClient, +} from "./acp-test-client" + +export function createAcpClient(input: Pick, env?: Record) { + return Effect.gen(function* () { + return createJsonRpcAcpClient(yield* input.opencode.acp(env ? { env } : undefined)) + }) +} + +export function initialize(acp: AcpClient) { + return Effect.gen(function* () { + return expectOk( + yield* acp.request("initialize", { + protocolVersion: 1, + clientCapabilities: { _meta: { "terminal-auth": true } }, + clientInfo: { name: "opencode-local-acp", version: "0.1.0" }, + }), + ) + }) +} + +export function newSession(acp: AcpClient, cwd: string) { + return Effect.gen(function* () { + return expectOk(yield* acp.request("session/new", { cwd, mcpServers: [] })) + }) +} + +export function verifierConfig(llmUrl: string, skills?: string) { + const config = testProviderConfig(llmUrl) + return { + ...config, + model: "test/test-model", + ...(skills ? { skills: { paths: [skills] } } : {}), + provider: { + test: { + ...config.provider.test, + models: { + "test-model": { + ...config.provider.test.models["test-model"], + variants: { + low: {}, + high: {}, + }, + }, + "second-model": { + ...config.provider.test.models["test-model"], + id: "second-model", + name: "Second Test Model", + variants: { + medium: {}, + max: {}, + }, + }, + }, + }, + }, + } +} + +export function expectErrorCode(error: unknown, code: number) { + if (!error || typeof error !== "object" || !("code" in error)) { + expect(error).toEqual({ code }) + return + } + expect(error.code).toBe(code) +} + +export function expectSelectOption(options: SessionConfigOption[] | null | undefined, id: string) { + const option = selectConfigOption(options, id) + expect(option).toBeDefined() + return option! +} + +export function expectAlternateValue(option: ReturnType) { + const value = flattenSelectOptions(option).find((item) => item.value !== option.currentValue)?.value + expect(value).toBeDefined() + return value! +} + +export const verifierSkill = `--- +name: verifier-skill +description: Verifier compatibility skill. +--- + +# Verifier Skill +` diff --git a/packages/opencode/test/cli/acp/initialize-auth.test.ts b/packages/opencode/test/cli/acp/initialize-auth.test.ts new file mode 100644 index 000000000000..709c27f3a319 --- /dev/null +++ b/packages/opencode/test/cli/acp/initialize-auth.test.ts @@ -0,0 +1,61 @@ +import { describe, expect } from "bun:test" +import type { AuthenticateResponse, InitializeResponse } from "@agentclientprotocol/sdk" +import { Effect } from "effect" +import { cliIt } from "../../lib/cli-process" +import { createAcpClient, expectErrorCode, initialize } from "./helpers" + +describe("opencode acp initialize/auth subprocess", () => { + cliIt.live( + "initialize responds with capabilities", + ({ opencode }) => + Effect.gen(function* () { + const initialized = yield* initialize(yield* createAcpClient({ opencode })) + + expect(initialized.protocolVersion).toBe(1) + expect(initialized.agentCapabilities?.promptCapabilities?.embeddedContext).toBe(true) + expect(initialized.agentCapabilities?.promptCapabilities?.image).toBe(true) + expect(initialized.agentCapabilities?.mcpCapabilities?.http).toBe(true) + expect(initialized.agentCapabilities?.mcpCapabilities?.sse).toBe(true) + expect(initialized.agentCapabilities?.loadSession).toBe(true) + expect(initialized.agentCapabilities?.sessionCapabilities?.close).toEqual({}) + expect(initialized.agentCapabilities?.sessionCapabilities?.fork).toEqual({}) + expect(initialized.agentCapabilities?.sessionCapabilities?.list).toEqual({}) + expect(initialized.agentCapabilities?.sessionCapabilities?.resume).toEqual({}) + expect(initialized.agentInfo?.name).toBe("OpenCode") + }), + 60_000, + ) + + cliIt.live( + "auth negotiation is explicit and safe", + ({ opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient({ opencode }) + const initialized = yield* initialize(acp) + + expect(initialized.authMethods?.[0]?.id).toBe("opencode-login") + expect(initialized.authMethods?.[0]?._meta?.["terminal-auth"]).toBeDefined() + expect(yield* acp.request("authenticate", { methodId: "opencode-login" })).toMatchObject({ + result: {}, + }) + + const rejected = yield* acp.request("authenticate", { methodId: "missing-auth-method" }) + expectErrorCode(rejected.error, -32602) + expect(JSON.stringify(rejected.error)).not.toContain(process.env.OPENCODE_AUTH_CONTENT ?? "not-present") + }), + 60_000, + ) + + cliIt.live( + "initialize without terminal-auth metadata keeps auth command implicit", + ({ opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient({ opencode }) + const initialized = yield* acp.request("initialize", { protocolVersion: 1 }) + + expect(initialized.result?.authMethods?.[0]?.id).toBe("opencode-login") + expect(initialized.result?.authMethods?.[0]?._meta?.["terminal-auth"]).toBeUndefined() + }), + 60_000, + ) +}) diff --git a/packages/opencode/test/cli/acp/lifecycle.test.ts b/packages/opencode/test/cli/acp/lifecycle.test.ts new file mode 100644 index 000000000000..9f2558ea2f58 --- /dev/null +++ b/packages/opencode/test/cli/acp/lifecycle.test.ts @@ -0,0 +1,118 @@ +import { describe, expect } from "bun:test" +import type { + CloseSessionResponse, + ListSessionsResponse, + LoadSessionResponse, + ResumeSessionResponse, +} from "@agentclientprotocol/sdk" +import { Duration, Effect } from "effect" +import { cliIt } from "../../lib/cli-process" +import { expectOk, selectConfigOption } from "./acp-test-client" +import { createAcpClient, initialize, newSession, verifierConfig } from "./helpers" + +describe("opencode acp lifecycle subprocess", () => { + cliIt.live( + "stdin EOF exits cleanly", + ({ opencode }) => + Effect.gen(function* () { + const acp = yield* opencode.acp() + acp.close() + + const code = yield* Effect.promise(() => acp.exited).pipe(Effect.timeout(Duration.seconds(5))) + expect(code).toBe(0) + }), + 60_000, + ) + + cliIt.live( + "close capability and close request", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + const initialized = yield* initialize(acp) + expect(initialized.agentCapabilities?.sessionCapabilities?.close).toEqual({}) + + const session = yield* newSession(acp, home) + expectOk(yield* acp.request("session/close", { sessionId: session.sessionId })) + }), + 60_000, + ) + + cliIt.live( + "loadSession capability and load request return session config options", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + const initialized = yield* initialize(acp) + expect(initialized.agentCapabilities?.loadSession).toBe(true) + const session = yield* newSession(acp, home) + const loaded = expectOk( + yield* acp.request("session/load", { + cwd: home, + sessionId: session.sessionId, + mcpServers: [], + }), + ) + + expect(selectConfigOption(loaded.configOptions, "model")?.category).toBe("model") + }), + 60_000, + ) + + cliIt.live( + "list request includes a live ACP-created session", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + yield* initialize(acp) + const session = yield* newSession(acp, home) + const listed = expectOk(yield* acp.request("session/list", { cwd: home })) + + expect(listed.sessions.some((item) => item.sessionId === session.sessionId)).toBe(true) + }), + 60_000, + ) + + cliIt.live( + "resume capability advertisement", + ({ opencode }) => + Effect.gen(function* () { + const initialized = yield* initialize(yield* createAcpClient({ opencode })) + + expect(initialized.agentCapabilities?.sessionCapabilities?.resume).toEqual({}) + }), + 60_000, + ) + + cliIt.live( + "resume request returns session config options", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url)) }, + ) + yield* initialize(acp) + const session = yield* newSession(acp, home) + const resumed = expectOk( + yield* acp.request("session/resume", { + cwd: home, + sessionId: session.sessionId, + mcpServers: [], + }), + ) + + expect(selectConfigOption(resumed.configOptions, "model")?.category).toBe("model") + }), + 60_000, + ) +}) diff --git a/packages/opencode/test/cli/acp/prompt-content.test.ts b/packages/opencode/test/cli/acp/prompt-content.test.ts new file mode 100644 index 000000000000..6b6f6ddeb67e --- /dev/null +++ b/packages/opencode/test/cli/acp/prompt-content.test.ts @@ -0,0 +1,97 @@ +import { describe, expect } from "bun:test" +import type { PromptResponse } from "@agentclientprotocol/sdk" +import { Effect } from "effect" +import { writeFile } from "node:fs/promises" +import path from "node:path" +import { pathToFileURL } from "node:url" +import { cliIt } from "../../lib/cli-process" +import { expectOk } from "./acp-test-client" +import { createAcpClient, initialize, newSession, verifierConfig } from "./helpers" + +const tinyPng = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=" + +describe("opencode acp prompt content subprocess", () => { + cliIt.live( + "accepts embedded text resource image and file resource link prompt content", + ({ home, llm, opencode }) => + Effect.gen(function* () { + yield* Effect.promise(() => writeFile(path.join(home, "README.md"), "# ACP content smoke\n")) + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(promptContentConfig(llm.url)) }, + ) + yield* initialize(acp) + const session = yield* newSession(acp, home) + + yield* llm.text("embedded resource accepted") + expectOk( + yield* acp.request("session/prompt", { + sessionId: session.sessionId, + prompt: [ + { type: "text", text: "Use this embedded resource." }, + { + type: "resource", + resource: { uri: "file:///context.txt", mimeType: "text/plain", text: "embedded context" }, + }, + ], + }), + ) + + yield* llm.text("image accepted") + expectOk( + yield* acp.request("session/prompt", { + sessionId: session.sessionId, + prompt: [ + { type: "text", text: "Use this image." }, + { + type: "image", + mimeType: "image/png", + data: tinyPng, + }, + ], + }), + ) + + yield* llm.text("file link accepted") + const linked = expectOk( + yield* acp.request("session/prompt", { + sessionId: session.sessionId, + prompt: [ + { type: "text", text: "Use this linked file." }, + { + type: "resource_link", + uri: pathToFileURL(path.join(home, "README.md")).href, + name: "README.md", + mimeType: "text/markdown", + }, + ], + }), + ) + + expect(linked.stopReason).toBe("end_turn") + }), + 60_000, + ) +}) + +function promptContentConfig(llmUrl: string) { + const config = verifierConfig(llmUrl) + return { + ...config, + provider: { + test: { + ...config.provider.test, + models: Object.fromEntries( + Object.entries(config.provider.test.models).map(([id, model]) => [ + id, + { + ...model, + attachment: true, + reasoning: true, + }, + ]), + ), + }, + }, + } +} diff --git a/packages/opencode/test/cli/acp/skills.test.ts b/packages/opencode/test/cli/acp/skills.test.ts new file mode 100644 index 000000000000..b423493cfa39 --- /dev/null +++ b/packages/opencode/test/cli/acp/skills.test.ts @@ -0,0 +1,38 @@ +import { describe, expect } from "bun:test" +import type { SessionNotification } from "@agentclientprotocol/sdk" +import { Effect } from "effect" +import { mkdir } from "node:fs/promises" +import path from "node:path" +import { cliIt } from "../../lib/cli-process" +import { createAcpClient, initialize, newSession, verifierConfig, verifierSkill } from "./helpers" + +describe("opencode acp skills subprocess", () => { + cliIt.live( + "skill slash command appears through available_commands_update", + ({ home, llm, opencode }) => + Effect.gen(function* () { + const skills = path.join(home, "skills") + yield* Effect.promise(() => mkdir(path.join(skills, "verifier-skill"), { recursive: true })) + yield* Effect.promise(() => Bun.write(path.join(skills, "verifier-skill", "SKILL.md"), verifierSkill)) + const acp = yield* createAcpClient( + { opencode }, + { OPENCODE_CONFIG_CONTENT: JSON.stringify(verifierConfig(llm.url, skills)) }, + ) + yield* initialize(acp) + const session = yield* newSession(acp, home) + + const update = yield* acp.waitForNotification( + "session/update", + (params) => + params.sessionId === session.sessionId && + params.update.sessionUpdate === "available_commands_update" && + params.update.availableCommands.some( + (command) => command.name === "verifier-skill" && command.description.length > 0, + ), + ) + + expect(update.params?.sessionId).toBe(session.sessionId) + }), + 60_000, + ) +}) diff --git a/packages/opencode/test/cli/cmd/tui/model-options.test.ts b/packages/opencode/test/cli/cmd/tui/model-options.test.ts new file mode 100644 index 000000000000..195078ebd6a4 --- /dev/null +++ b/packages/opencode/test/cli/cmd/tui/model-options.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from "bun:test" +import { sortModelOptions } from "../../../../src/cli/cmd/tui/component/dialog-model" + +describe("sortModelOptions", () => { + test("orders provider-scoped model choices by newest release first", () => { + const sorted = sortModelOptions( + [ + { title: "GPT 5.2", releaseDate: "2025-12-11" }, + { title: "GPT 5.4", releaseDate: "2026-03-05" }, + { title: "GPT 5.1", releaseDate: "2025-11-13" }, + ], + true, + ) + + expect(sorted.map((model) => model.title)).toEqual(["GPT 5.4", "GPT 5.2", "GPT 5.1"]) + }) + + test("preserves free-first alphabetical ordering for the regular picker", () => { + const sorted = sortModelOptions( + [ + { title: "Beta", releaseDate: "2026-01-01" }, + { title: "Alpha", releaseDate: "2025-01-01", footer: "Free" }, + { title: "Gamma", releaseDate: "2024-01-01", footer: "Free" }, + ], + false, + ) + + expect(sorted.map((model) => model.title)).toEqual(["Alpha", "Gamma", "Beta"]) + }) +}) diff --git a/packages/opencode/test/cli/cmd/tui/prompt-part.test.ts b/packages/opencode/test/cli/cmd/tui/prompt-part.test.ts index 326d3e624d27..d4158e363645 100644 --- a/packages/opencode/test/cli/cmd/tui/prompt-part.test.ts +++ b/packages/opencode/test/cli/cmd/tui/prompt-part.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test" import type { PromptInfo } from "../../../../src/cli/cmd/tui/component/prompt/history" -import { assign, strip } from "../../../../src/cli/cmd/tui/component/prompt/part" +import { assign, expandTrackedPastedText, strip } from "../../../../src/cli/cmd/tui/component/prompt/part" describe("prompt part", () => { test("strip removes persisted ids from reused file parts", () => { @@ -44,4 +44,34 @@ describe("prompt part", () => { url: "data:image/png;base64,abc", }) }) + + test("expandTrackedPastedText preserves wide characters around pasted text", () => { + const marker = "[Pasted ~3 lines]" + const prefix = "你好你好\n" + + expect( + expandTrackedPastedText(prefix + marker + "\n阿斯顿法国红酒看来", [ + { + start: Bun.stringWidth("你好你好") + 1, + end: Bun.stringWidth("你好你好") + 1 + Bun.stringWidth(marker), + text: "public:\n\tvoid ExecuteTask();\nprivate:", + }, + ]), + ).toBe("你好你好\npublic:\n\tvoid ExecuteTask();\nprivate:\n阿斯顿法国红酒看来") + }) + + test("expandTrackedPastedText only expands the tracked placeholder occurrence", () => { + const marker = "[Pasted ~3 lines]" + const prefix = `keep ${marker} then ` + + expect( + expandTrackedPastedText(prefix + marker + " tail", [ + { + start: Bun.stringWidth(prefix), + end: Bun.stringWidth(prefix + marker), + text: "alpha\nbeta\ngamma", + }, + ]), + ).toBe(`keep ${marker} then alpha\nbeta\ngamma tail`) + }) }) diff --git a/packages/opencode/test/cli/cmd/tui/sync-fixture.tsx b/packages/opencode/test/cli/cmd/tui/sync-fixture.tsx index 5f51374c16c5..4b3c6037eace 100644 --- a/packages/opencode/test/cli/cmd/tui/sync-fixture.tsx +++ b/packages/opencode/test/cli/cmd/tui/sync-fixture.tsx @@ -2,15 +2,13 @@ import { testRender } from "@opentui/solid" import { onMount } from "solid-js" import { ArgsProvider } from "../../../../src/cli/cmd/tui/context/args" -import { ExitProvider } from "../../../../src/cli/cmd/tui/context/exit" +import { createExit, ExitProvider } from "../../../../src/cli/cmd/tui/context/exit" import { KVProvider, useKV } from "../../../../src/cli/cmd/tui/context/kv" import { ProjectProvider, useProject } from "../../../../src/cli/cmd/tui/context/project" -import { SDKProvider, type EventSource } from "../../../../src/cli/cmd/tui/context/sdk" +import { SDKProvider } from "../../../../src/cli/cmd/tui/context/sdk" import { SyncProvider, useSync } from "../../../../src/cli/cmd/tui/context/sync" -import type { GlobalEvent } from "@opencode-ai/sdk/v2" - -export const worktree = "/tmp/opencode" -export const directory = `${worktree}/packages/opencode` +import { createEventSource, createFetch, type FetchHandler, directory } from "../../../fixture/tui-sdk" +export { createEventSource, createFetch, directory, eventSource, json, worktree } from "../../../fixture/tui-sdk" export async function wait(fn: () => boolean, timeout = 2000) { const start = Date.now() @@ -20,83 +18,6 @@ export async function wait(fn: () => boolean, timeout = 2000) { } } -export function json(data: unknown, init?: ResponseInit) { - return new Response(JSON.stringify(data), { - ...init, - headers: { "content-type": "application/json", ...(init?.headers ?? {}) }, - }) -} - -export function eventSource(): EventSource { - return { subscribe: async () => () => {} } -} - -export function createEventSource() { - let fn: ((event: GlobalEvent) => void) | undefined - - return { - source: { - subscribe: async (handler: (event: GlobalEvent) => void) => { - fn = handler - return () => { - if (fn === handler) fn = undefined - } - }, - } satisfies EventSource, - emit(event: GlobalEvent) { - if (!fn) throw new Error("event source not ready") - fn(event) - }, - } -} - -type FetchHandler = (url: URL) => Response | Promise | undefined - -export function createFetch(override?: FetchHandler) { - const session = [] as URL[] - const fetch = (async (input: RequestInfo | URL) => { - const url = new URL(input instanceof Request ? input.url : String(input)) - if (url.pathname === "/session") session.push(url) - - const overridden = await override?.(url) - if (overridden) return overridden - - switch (url.pathname) { - case "/agent": - case "/command": - case "/experimental/workspace": - case "/experimental/workspace/status": - case "/formatter": - case "/lsp": - return json([]) - case "/config": - case "/experimental/resource": - case "/mcp": - case "/provider/auth": - case "/session/status": - return json({}) - case "/config/providers": - return json({ providers: {}, default: {} }) - case "/experimental/console": - return json({ consoleManagedProviders: [], switchableOrgCount: 0 }) - case "/path": - return json({ home: "", state: "", config: "", worktree, directory }) - case "/project/current": - return json({ id: "proj_test" }) - case "/provider": - return json({ all: [], default: {}, connected: [] }) - case "/session": - return json([]) - case "/vcs": - return json({ branch: "main" }) - } - - throw new Error(`unexpected request: ${url.pathname}`) - }) as typeof globalThis.fetch - - return { fetch, session } -} - type Ctx = { kv: ReturnType; project: ReturnType; sync: ReturnType } export async function mount(override?: FetchHandler) { @@ -123,7 +44,7 @@ export async function mount(override?: FetchHandler) { const app = await testRender(() => ( - + {})}> diff --git a/packages/opencode/test/cli/github-action.test.ts b/packages/opencode/test/cli/github-action.test.ts index 263f3a45f318..1530df66b99d 100644 --- a/packages/opencode/test/cli/github-action.test.ts +++ b/packages/opencode/test/cli/github-action.test.ts @@ -1,10 +1,11 @@ import { test, expect, describe } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { extractResponseText, formatPromptTooLargeError } from "../../src/cli/cmd/github" import type { MessageV2 } from "../../src/session/message-v2" import { SessionID, MessageID, PartID } from "../../src/session/schema" // Helper to create minimal valid parts -function createTextPart(text: string): MessageV2.Part { +function createTextPart(text: string): SessionLegacy.Part { return { id: PartID.ascending(), sessionID: SessionID.make("ses_test"), @@ -14,7 +15,7 @@ function createTextPart(text: string): MessageV2.Part { } } -function createReasoningPart(text: string): MessageV2.Part { +function createReasoningPart(text: string): SessionLegacy.Part { return { id: PartID.ascending(), sessionID: SessionID.make("ses_test"), @@ -25,7 +26,11 @@ function createReasoningPart(text: string): MessageV2.Part { } } -function createToolPart(tool: string, title: string, status: "completed" | "running" = "completed"): MessageV2.Part { +function createToolPart( + tool: string, + title: string, + status: "completed" | "running" = "completed", +): SessionLegacy.Part { if (status === "completed") { return { id: PartID.ascending(), @@ -59,7 +64,7 @@ function createToolPart(tool: string, title: string, status: "completed" | "runn } } -function createStepStartPart(): MessageV2.Part { +function createStepStartPart(): SessionLegacy.Part { return { id: PartID.ascending(), sessionID: SessionID.make("ses_test"), @@ -68,7 +73,7 @@ function createStepStartPart(): MessageV2.Part { } } -function createStepFinishPart(): MessageV2.Part { +function createStepFinishPart(): SessionLegacy.Part { return { id: PartID.ascending(), sessionID: SessionID.make("ses_test"), diff --git a/packages/opencode/test/cli/help/__snapshots__/help-snapshots.test.ts.snap b/packages/opencode/test/cli/help/__snapshots__/help-snapshots.test.ts.snap index 22ad59aaa29d..b7148ebcee9b 100644 --- a/packages/opencode/test/cli/help/__snapshots__/help-snapshots.test.ts.snap +++ b/packages/opencode/test/cli/help/__snapshots__/help-snapshots.test.ts.snap @@ -103,7 +103,7 @@ Options: --variant model variant (provider-specific reasoning effort, e.g., high, max, minimal) [string] --thinking show thinking blocks [boolean] - --replay replay visible session history on interactive resume + --replay replay interactive session history on resume and after resize [boolean] [default: false] --replay-limit cap visible interactive replay to the newest N messages [number] @@ -398,7 +398,6 @@ database tools Commands: opencode db [query] open an interactive sqlite3 shell or run a query [default] opencode db path print the database path - opencode db migrate migrate JSON data to SQLite (merges with existing data) Positionals: query SQL query to execute [string] diff --git a/packages/opencode/test/cli/run/entry.body.test.ts b/packages/opencode/test/cli/run/entry.body.test.ts index e65fd016590c..17659113c573 100644 --- a/packages/opencode/test/cli/run/entry.body.test.ts +++ b/packages/opencode/test/cli/run/entry.body.test.ts @@ -235,11 +235,11 @@ describe("run entry body", () => { }, title: "", output: [ - "task_id: child-1 (for resuming to continue this task if needed)", - "", + '', "", "# Findings\n\n- Footer stays live", "", + "", ].join("\n"), metadata: { sessionId: "child-1", @@ -264,13 +264,9 @@ describe("run entry body", () => { subagent_type: "explore", }, title: "", - output: [ - "task_id: child-1 (for resuming to continue this task if needed)", - "", - "", - "", - "", - ].join("\n"), + output: ['', "", "", "", ""].join( + "\n", + ), metadata: { sessionId: "child-1", }, diff --git a/packages/opencode/test/cli/run/footer.view.test.tsx b/packages/opencode/test/cli/run/footer.view.test.tsx index 697e64efc8f8..ed2df583c06a 100644 --- a/packages/opencode/test/cli/run/footer.view.test.tsx +++ b/packages/opencode/test/cli/run/footer.view.test.tsx @@ -1,13 +1,16 @@ /** @jsxImportSource @opentui/solid */ import { expect, test } from "bun:test" -import { testRender } from "@opentui/solid" +import { testRender, useRenderer } from "@opentui/solid" import { createSignal } from "solid-js" +import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import type { QuestionRequest } from "@opencode-ai/sdk/v2" +import { OpencodeKeymapProvider, registerOpencodeKeymap } from "@/cli/cmd/tui/keymap" import { RUN_COMMAND_PANEL_ROWS, RUN_SUBAGENT_PANEL_ROWS, RunCommandMenuBody, RunModelSelectBody, + RunQueuedPromptSelectBody, RunSubagentSelectBody, RunVariantSelectBody, } from "@/cli/cmd/run/footer.command" @@ -15,34 +18,22 @@ import { RunFooterView } from "@/cli/cmd/run/footer.view" import { RunEntryContent } from "@/cli/cmd/run/scrollback.writer" import { RUN_THEME_FALLBACK } from "@/cli/cmd/run/theme" import type { - FooterKeybinds, FooterState, FooterSubagentState, FooterSubagentTab, FooterView, RunCommand, RunInput, + RunPrompt, RunProvider, + RunTuiConfig, StreamCommit, } from "@/cli/cmd/run/types" import { RunQuestionBody } from "@/cli/cmd/run/footer.question" +import { RejectField } from "@/cli/cmd/run/footer.permission" +import { createTuiResolvedConfig } from "../../fixture/tui-runtime" -function bindings(...keys: string[]) { - return keys.map((key) => ({ key })) -} - -const keybinds: FooterKeybinds = { - leader: "ctrl+x", - leaderTimeout: 2000, - commandList: bindings("ctrl+p"), - variantCycle: bindings("ctrl+t"), - interrupt: bindings("escape"), - historyPrevious: bindings("up"), - historyNext: bindings("down"), - inputClear: bindings("ctrl+c"), - inputSubmit: bindings("return"), - inputNewline: bindings("shift+return,ctrl+return,alt+return,ctrl+j"), -} +const tuiConfig = createTuiResolvedConfig() function command(input: { name: string; description: string; source?: "command" | "mcp" | "skill" }) { return { @@ -143,6 +134,98 @@ function subagent(input: { } satisfies FooterSubagentTab } +function footerState(input: Partial = {}) { + return createSignal({ + phase: "idle", + status: "", + queue: 0, + model: "gpt-5", + duration: "", + usage: "", + first: false, + interrupt: 0, + exit: 0, + ...input, + })[0] +} + +async function renderFooter( + input: { + tuiConfig?: RunTuiConfig + commands?: RunCommand[] + onCycle?: () => void + onSubmit?: (prompt: RunPrompt) => boolean + } = {}, +) { + const [view] = createSignal({ type: "prompt" }) + const [subagents] = createSignal({ tabs: [], details: {}, permissions: [], questions: [] }) + const state = footerState() + const config = input.tuiConfig ?? tuiConfig + let offKeymap: (() => void) | undefined + + function Harness() { + const renderer = useRenderer() + const keymap = createDefaultOpenTuiKeymap(renderer) + offKeymap = registerOpencodeKeymap(keymap, renderer, config) + + return ( + + []} + agents={() => []} + resources={() => []} + commands={() => input.commands ?? []} + providers={() => undefined} + currentModel={() => undefined} + variants={() => []} + currentVariant={() => undefined} + state={state} + view={view} + subagent={subagents} + theme={RUN_THEME_FALLBACK} + tuiConfig={config} + agent="opencode" + onSubmit={input.onSubmit ?? (() => true)} + onPermissionReply={() => {}} + onQuestionReply={() => {}} + onQuestionReject={() => {}} + onCycle={input.onCycle ?? (() => {})} + onInterrupt={() => false} + onInputClear={() => {}} + onExit={() => {}} + onModelSelect={() => {}} + onVariantSelect={() => {}} + onRows={() => {}} + onLayout={() => {}} + onStatus={() => {}} + onQueuedRemove={async () => true} + /> + + ) + } + + const app = await testRender( + () => ( + + + + ), + { width: 100, height: 8, kittyKeyboard: true }, + ) + + return { + ...app, + cleanup() { + app.renderer.currentFocusedRenderable?.blur() + app.renderer.currentFocusedEditor?.blur() + offKeymap?.() + offKeymap = undefined + app.renderer.destroy() + }, + } +} + test("run entry content updates when live commit text changes", async () => { const [commit, setCommit] = createSignal({ kind: "tool", @@ -203,11 +286,13 @@ test("direct command panel renders grouped command palette", async () => { theme={() => RUN_THEME_FALLBACK.footer} commands={commands} subagents={subagents} + queued={() => []} variants={variants} - keybinds={keybinds} + variantCycle="ctrl+t" onClose={() => {}} onModel={() => {}} onSubagent={() => {}} + onQueued={() => {}} onVariant={() => {}} onVariantCycle={() => {}} onCommand={() => {}} @@ -261,11 +346,13 @@ test("direct command panel shows subagent entry when available", async () => { theme={() => RUN_THEME_FALLBACK.footer} commands={commands} subagents={subagents} + queued={() => []} variants={variants} - keybinds={keybinds} + variantCycle="ctrl+t" onClose={() => {}} onModel={() => {}} onSubagent={() => {}} + onQueued={() => {}} onVariant={() => {}} onVariantCycle={() => {}} onCommand={() => {}} @@ -334,11 +421,158 @@ test("direct subagent panel renders active subagents", async () => { } }) -test("direct footer shows subagent indicator while prompt is running", async () => { +test("direct queued prompt panel renders pending prompt actions", async () => { + const [prompts] = createSignal([ + { messageID: "m-1", partID: "p-1", prompt: { text: "fix the auth test", parts: [] } }, + ]) + + const app = await testRender( + () => ( + + RUN_THEME_FALLBACK.footer} + prompts={prompts} + onClose={() => {}} + onEdit={() => {}} + onDelete={() => {}} + /> + + ), + { width: 100, height: RUN_SUBAGENT_PANEL_ROWS }, + ) + + try { + await app.renderOnce() + expect(app.captureCharFrame()).toContain("Queued prompts") + expect(app.captureCharFrame()).toContain("fix the auth test") + expect(app.captureCharFrame()).toContain("queued") + } finally { + app.renderer.destroy() + } +}) + +// OpenTUI currently segfaults when the full footer view suite creates several +// keymap-backed test renderers in one process. Re-enable after the runtime fix. +test.skip("direct footer opens command panel through keymap binding", async () => { + const app = await renderFooter() + + try { + await app.renderOnce() + app.mockInput.pressKey("p", { ctrl: true }) + await app.renderOnce() + + expect(app.captureCharFrame()).toContain("Commands") + } finally { + app.cleanup() + } +}) + +test.skip("direct footer dispatches leader variant binding only when leader is registered", async () => { + const calls: string[] = [] + const app = await renderFooter({ + tuiConfig: createTuiResolvedConfig({ keybinds: { leader: "ctrl+x", variant_cycle: "t" } }), + onCycle: () => calls.push("cycle"), + }) + + try { + await app.renderOnce() + app.mockInput.pressKey("t") + expect(calls).toEqual([]) + + app.mockInput.pressKey("x", { ctrl: true }) + app.mockInput.pressKey("t") + expect(calls).toEqual(["cycle"]) + } finally { + app.cleanup() + } +}) + +test("direct footer keeps leader variant binding inactive when leader is disabled", async () => { + const calls: string[] = [] + const app = await renderFooter({ + tuiConfig: createTuiResolvedConfig({ keybinds: { leader: "none", variant_cycle: "t" } }), + onCycle: () => calls.push("cycle"), + }) + + try { + await app.renderOnce() + app.mockInput.pressKey("t") + app.mockInput.pressKey("x", { ctrl: true }) + app.mockInput.pressKey("t") + + expect(calls).toEqual([]) + } finally { + app.cleanup() + } +}) + +test("direct footer submits slash autocomplete selections without dispatching shell completions", async () => { + const submits: RunPrompt[] = [] + const app = await renderFooter({ + commands: [command({ name: "review", description: "Review code" })], + onSubmit(prompt) { + submits.push(prompt) + return true + }, + }) + + try { + await app.renderOnce() + "/rev".split("").forEach((key) => app.mockInput.pressKey(key)) + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + + "/rev".split("").forEach((key) => app.mockInput.pressKey(key)) + await app.renderOnce() + app.mockInput.pressKey("TAB") + await app.renderOnce() + + "/re branch".split("").forEach((key) => app.mockInput.pressKey(key)) + Array.from({ length: 7 }).forEach(() => app.mockInput.pressKey("ARROW_LEFT")) + app.mockInput.pressKey("v") + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + + "/nx".split("").forEach((key) => app.mockInput.pressKey(key)) + app.mockInput.pressKey("ARROW_LEFT") + app.mockInput.pressKey("e") + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + + "/n scratch".split("").forEach((key) => app.mockInput.pressKey(key)) + Array.from({ length: 8 }).forEach(() => app.mockInput.pressKey("ARROW_LEFT")) + app.mockInput.pressKey("e") + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + + app.mockInput.pressKey("!") + "/rev".split("").forEach((key) => app.mockInput.pressKey(key)) + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + + expect(submits).toEqual([ + { text: "/review ", parts: [], command: { name: "review", arguments: "" } }, + { text: "/review ", parts: [], command: { name: "review", arguments: "" } }, + { text: "/review branch", parts: [], command: { name: "review", arguments: "branch" } }, + { text: "/new ", parts: [] }, + { text: "/new ", parts: [] }, + ]) + expect(app.captureCharFrame()).toContain("/review") + } finally { + app.cleanup() + } +}) + +test("direct footer shows editable prompts and additional queued work while running", async () => { const [state] = createSignal({ phase: "running", status: "", - queue: 0, + queue: 3, model: "gpt-5", duration: "", usage: "", @@ -353,10 +587,14 @@ test("direct footer shows subagent indicator while prompt is running", async () permissions: [], questions: [], }) - - const app = await testRender( - () => ( - + let offKeymap: (() => void) | undefined + function Harness() { + const renderer = useRenderer() + const keymap = createDefaultOpenTuiKeymap(renderer) + offKeymap = registerOpencodeKeymap(keymap, renderer, tuiConfig) + + return ( + []} @@ -370,8 +608,11 @@ test("direct footer shows subagent indicator while prompt is running", async () state={state} view={view} subagent={subagents} + queuedPrompts={() => [ + { messageID: "m-queued", partID: "p-queued", prompt: { text: "follow up", parts: [] } }, + ]} theme={RUN_THEME_FALLBACK} - keybinds={keybinds} + tuiConfig={tuiConfig} agent="opencode" onSubmit={() => true} onPermissionReply={() => {}} @@ -386,19 +627,33 @@ test("direct footer shows subagent indicator while prompt is running", async () onRows={() => {}} onLayout={() => {}} onStatus={() => {}} + onQueuedRemove={async () => true} /> + + ) + } + + const app = await testRender( + () => ( + + ), { - width: 100, + width: 160, height: 8, }, ) try { await app.renderOnce() - expect(app.captureCharFrame()).toContain("interrupt · 1 agent · ↓ to view") + expect(app.captureCharFrame()).toContain("interrupt · 1 agent · ctrl+x down to view · 1 queued prompt · ctrl+x q") + expect(app.captureCharFrame()).toContain("2 queued") + expect(app.captureCharFrame()).not.toContain("agent · ·") } finally { + app.renderer.currentFocusedRenderable?.blur() + app.renderer.currentFocusedEditor?.blur() + offKeymap?.() app.renderer.destroy() } }) @@ -450,6 +705,122 @@ test("direct question body separates single-select checkmark from label", async } }) +// OpenTUI currently segfaults while tearing down this textarea-backed keymap renderer. +// Re-enable after the runtime fix. +test.skip("direct custom answer submits through keymap return binding", async () => { + const question = { + id: "question-1", + sessionID: "session-1", + questions: [ + { + question: "Which answer should I use?", + header: "Answer", + options: [{ label: "Provided", description: "Use the listed answer." }], + custom: true, + }, + ], + } satisfies QuestionRequest + const questions: unknown[] = [] + let off: (() => void) | undefined + + function Harness() { + const renderer = useRenderer() + const keymap = createDefaultOpenTuiKeymap(renderer) + off = registerOpencodeKeymap(keymap, renderer, tuiConfig) + + return ( + + { + questions.push(input) + }} + onReject={() => {}} + /> + + ) + } + + const app = await testRender( + () => ( + + + + ), + { width: 100, height: 18, kittyKeyboard: true }, + ) + + try { + await app.renderOnce() + app.mockInput.pressKey("2") + await app.renderOnce() + "typed".split("").forEach((key) => app.mockInput.pressKey(key)) + await app.renderOnce() + app.mockInput.pressEnter() + await app.renderOnce() + expect(questions).toEqual([{ requestID: "question-1", answers: [["typed"]] }]) + } finally { + app.renderer.currentFocusedRenderable?.blur() + app.renderer.currentFocusedEditor?.blur() + off?.() + app.renderer.destroy() + } +}) + +test("direct permission rejection submits through keymap return binding", async () => { + let text = "" + const submits: string[] = [] + let off: (() => void) | undefined + + function Harness() { + const renderer = useRenderer() + const keymap = createDefaultOpenTuiKeymap(renderer) + off = registerOpencodeKeymap(keymap, renderer, tuiConfig) + + return ( + + { + text = input + }} + onConfirm={() => { + submits.push(text) + }} + onCancel={() => {}} + /> + + ) + } + + const app = await testRender( + () => ( + + + + ), + { width: 100, height: 18, kittyKeyboard: true }, + ) + + try { + await app.renderOnce() + "retry".split("").forEach((key) => app.mockInput.pressKey(key)) + await app.renderOnce() + expect(app.captureCharFrame()).toContain("retry") + app.mockInput.pressEnter() + await app.renderOnce() + expect(submits).toEqual(["retry"]) + } finally { + app.renderer.currentFocusedRenderable?.blur() + app.renderer.currentFocusedEditor?.blur() + off?.() + app.renderer.destroy() + } +}) + test("direct model panel renders current model selector", async () => { const [providers] = createSignal([provider()]) const [current] = createSignal({ providerID: "opencode", modelID: "gpt-5" }) diff --git a/packages/opencode/test/cli/run/prompt.shared.test.ts b/packages/opencode/test/cli/run/prompt.shared.test.ts index 35b35ec3e7a8..cbf2cd9c9e0f 100644 --- a/packages/opencode/test/cli/run/prompt.shared.test.ts +++ b/packages/opencode/test/cli/run/prompt.shared.test.ts @@ -7,32 +7,10 @@ import { isNewCommand, mentionTriggerIndex, movePromptHistory, - printableBinding, - promptCycle, - promptHit, - promptInfo, - promptKeys, pushPromptHistory, } from "@/cli/cmd/run/prompt.shared" import type { RunPrompt } from "@/cli/cmd/run/types" -function bindings(...keys: string[]) { - return keys.map((key) => ({ key })) -} - -const keybinds = { - leader: "ctrl+x", - leaderTimeout: 2000, - commandList: bindings("ctrl+p"), - variantCycle: bindings("ctrl+t", "t"), - interrupt: bindings("escape"), - historyPrevious: bindings("up"), - historyNext: bindings("down"), - inputClear: bindings("ctrl+c"), - inputSubmit: bindings("return"), - inputNewline: bindings("shift+return,ctrl+return,alt+return,ctrl+j"), -} - function prompt(text: string, parts: RunPrompt["parts"] = []): RunPrompt { return { text, parts } } @@ -141,39 +119,6 @@ describe("run prompt shared", () => { expect(mentionTriggerIndex("中文 @src file")).toBeUndefined() }) - test("handles direct and leader-based variant cycling", () => { - const keys = promptKeys(keybinds) - - expect(promptHit(keys.clear, promptInfo({ name: "c", ctrl: true }))).toBe(true) - - expect(promptCycle(false, promptInfo({ name: "x", ctrl: true }), keys.leaders, keys.cycles)).toEqual({ - arm: true, - clear: false, - cycle: false, - consume: true, - }) - - expect(promptCycle(true, promptInfo({ name: "t" }), keys.leaders, keys.cycles)).toEqual({ - arm: false, - clear: true, - cycle: true, - consume: true, - }) - - expect(promptCycle(false, promptInfo({ name: "t", ctrl: true }), keys.leaders, keys.cycles)).toEqual({ - arm: false, - clear: false, - cycle: true, - consume: true, - }) - }) - - test("prints bindings with leader substitution and esc normalization", () => { - expect(printableBinding(keybinds.variantCycle.slice(1), "ctrl+x")).toBe("ctrl+x t") - expect(printableBinding(keybinds.interrupt, "ctrl+x")).toBe("esc") - expect(printableBinding([], "ctrl+x")).toBe("") - }) - test("recognizes exit commands", () => { expect(isExitCommand("/exit")).toBe(true) expect(isExitCommand(" /Quit ")).toBe(true) diff --git a/packages/opencode/test/cli/run/runtime.boot.test.ts b/packages/opencode/test/cli/run/runtime.boot.test.ts index 8dd978553248..e610463c77de 100644 --- a/packages/opencode/test/cli/run/runtime.boot.test.ts +++ b/packages/opencode/test/cli/run/runtime.boot.test.ts @@ -1,8 +1,7 @@ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test" import { OpencodeClient, type Provider } from "@opencode-ai/sdk/v2" import { TuiConfig, type Resolved } from "@/cli/cmd/tui/config/tui" -import { formatBindings } from "@/cli/cmd/run/keymap.shared" -import { resolveDiffStyle, resolveFooterKeybinds, resolveModelInfo } from "@/cli/cmd/run/runtime.boot" +import { resolveDiffStyle, resolveModelInfo, resolveRunTuiConfig } from "@/cli/cmd/run/runtime.boot" import { createTuiResolvedConfig } from "../../fixture/tui-runtime" function model(id: string, providerID: string, context: number, variants?: Record>) { @@ -111,35 +110,44 @@ describe("run runtime boot", () => { }), ) - const result = await resolveFooterKeybinds() + const result = await resolveRunTuiConfig() - expect(result.leader).toBe("ctrl+g") - expect(result.leaderTimeout).toBe(2000) - expect(formatBindings(result.commandList, result.leader)).toBe("ctrl+p") - expect(formatBindings(result.variantCycle, result.leader)).toBe("ctrl+t, alt+t") - expect(formatBindings(result.interrupt, result.leader)).toBe("ctrl+c") - expect(formatBindings(result.historyPrevious, result.leader)).toBe("k") - expect(formatBindings(result.historyNext, result.leader)).toBe("j") - expect(formatBindings(result.inputClear, result.leader)).toBe("ctrl+l") - expect(formatBindings(result.inputSubmit, result.leader)).toBe("ctrl+s") - expect(formatBindings(result.inputNewline, result.leader)).toBe("alt+return") + expect(result.keybinds.get("leader")?.[0]?.key).toBe("ctrl+g") + expect(result.leader_timeout).toBe(2000) + expect(result.keybinds.get("command.palette.show")?.[0]?.key).toBe("ctrl+p") + expect(result.keybinds.get("variant.cycle").map((item) => item.key)).toEqual(["ctrl+t", "alt+t"]) + expect(result.keybinds.get("session.interrupt")?.[0]?.key).toBe("ctrl+c") + expect(result.keybinds.get("prompt.history.previous")?.[0]?.key).toBe("k") + expect(result.keybinds.get("prompt.history.next")?.[0]?.key).toBe("j") + expect(result.keybinds.get("prompt.clear")?.[0]?.key).toBe("ctrl+l") + expect(result.keybinds.get("input.submit")?.[0]?.key).toBe("ctrl+s") + expect(result.keybinds.get("input.newline")?.[0]?.key).toBe("alt+return") }) - test("falls back to default keybinds when config load fails", async () => { + test("falls back to default tui keymap config when config load fails", async () => { spyOn(TuiConfig, "get").mockRejectedValue(new Error("boom")) - const result = await resolveFooterKeybinds() + const result = await resolveRunTuiConfig() - expect(result.leader).toBe("ctrl+x") - expect(result.leaderTimeout).toBe(2000) - expect(formatBindings(result.commandList, result.leader)).toBe("ctrl+p") - expect(formatBindings(result.variantCycle, result.leader)).toBe("ctrl+t") - expect(formatBindings(result.interrupt, result.leader)).toBe("esc") - expect(formatBindings(result.historyPrevious, result.leader)).toBe("up") - expect(formatBindings(result.historyNext, result.leader)).toBe("down") - expect(formatBindings(result.inputClear, result.leader)).toBe("ctrl+c") - expect(formatBindings(result.inputSubmit, result.leader)).toBe("return") - expect(formatBindings(result.inputNewline, result.leader)).toBe("shift+return, ctrl+return, alt+return, ctrl+j") + expect(result.keybinds.get("leader")?.[0]?.key).toBe("ctrl+x") + expect(result.leader_timeout).toBe(2000) + expect(result.diff_style).toBe("auto") + expect(result.keybinds.get("command.palette.show")?.[0]?.key).toBe("ctrl+p") + expect(result.keybinds.get("variant.cycle")?.[0]?.key).toBe("ctrl+t") + expect(result.keybinds.get("session.interrupt")?.[0]?.key).toBe("escape") + expect(result.keybinds.get("prompt.history.previous")?.[0]?.key).toBe("up") + expect(result.keybinds.get("prompt.history.next")?.[0]?.key).toBe("down") + expect(result.keybinds.get("prompt.clear")?.[0]?.key).toBe("ctrl+c") + expect(result.keybinds.get("input.submit")?.[0]?.key).toBe("return") + expect(result.keybinds.get("input.newline")?.[0]?.key).toBe("shift+return,ctrl+return,alt+return,ctrl+j") + }) + + test("preserves disabled leader from resolved tui config", async () => { + spyOn(TuiConfig, "get").mockResolvedValue(config({ leader: "none" })) + + const result = await resolveRunTuiConfig() + + expect(result.keybinds.get("leader")).toEqual([]) }) test("reads diff style and falls back to auto", async () => { diff --git a/packages/opencode/test/cli/run/runtime.queue.test.ts b/packages/opencode/test/cli/run/runtime.queue.test.ts index 5515787caf0f..7eba8bb251ab 100644 --- a/packages/opencode/test/cli/run/runtime.queue.test.ts +++ b/packages/opencode/test/cli/run/runtime.queue.test.ts @@ -4,6 +4,7 @@ import type { FooterApi, FooterEvent, RunPrompt, StreamCommit } from "@/cli/cmd/ function footer() { const prompts = new Set<(input: RunPrompt) => void>() + const queuedRemoves = new Set<(messageID: string) => void>() const closes = new Set<() => void>() const events: FooterEvent[] = [] const commits: StreamCommit[] = [] @@ -19,6 +20,12 @@ function footer() { prompts.delete(fn) } }, + onQueuedRemove(fn) { + queuedRemoves.add(fn) + return () => { + queuedRemoves.delete(fn) + } + }, onClose(fn) { if (closed) { fn() @@ -66,6 +73,9 @@ function footer() { fn(next) } }, + removeQueued(messageID: string) { + for (const fn of [...queuedRemoves]) fn(messageID) + }, } } @@ -133,6 +143,7 @@ describe("run runtime queue", () => { text: "hello", phase: "start", source: "system", + messageID: expect.any(String), }, ]) }) @@ -215,6 +226,7 @@ describe("run runtime queue", () => { text: " hello ", phase: "start", source: "system", + messageID: expect.any(String), }, ]) }) @@ -250,6 +262,7 @@ describe("run runtime queue", () => { text: "/fmt bash", phase: "start", source: "system", + messageID: expect.any(String), }, ]) ui.api.close() @@ -289,6 +302,82 @@ describe("run runtime queue", () => { expect(seen).toEqual(["one", "two"]) }) + test("exposes ordinary in-flight prompts for removal before sending", async () => { + const ui = footer() + const turns: RunPrompt[] = [] + let wake: (() => void) | undefined + const gate = new Promise((resolve) => { + wake = resolve + }) + + const task = runPromptQueue({ + footer: ui.api, + run: async (input) => { + turns.push(input) + await gate + }, + }) + + ui.submit("one") + ui.submit("two") + await Promise.resolve() + await Promise.resolve() + + expect(turns.map((item) => item.text)).toEqual(["one"]) + expect(turns[0]?.messageID).toEqual(expect.any(String)) + expect(ui.commits.map((item) => item.text)).toEqual(["one"]) + const first = ui.events.find((item) => item.type === "queued.prompts") + const event = ui.events.findLast((item) => item.type === "queued.prompts") + expect(first?.type === "queued.prompts" ? first.prompts : []).toEqual([]) + expect( + first?.type === "queued.prompts" && event?.type === "queued.prompts" ? first.prompts === event.prompts : true, + ).toBe(false) + expect(ui.events.findLast((item) => item.type === "queue")).toEqual({ type: "queue", queue: 1 }) + expect(event?.type === "queued.prompts" ? event.prompts.map((item) => item.prompt.text) : []).toEqual(["two"]) + if (event?.type === "queued.prompts") ui.removeQueued(event.prompts[0]!.messageID) + await Promise.resolve() + + wake?.() + ui.api.close() + await task + expect(turns.map((item) => item.text)).toEqual(["one"]) + }) + + test("removing one managed queued prompt preserves the others", async () => { + const ui = footer() + const turns: string[] = [] + let wake: (() => void) | undefined + const gate = new Promise((resolve) => { + wake = resolve + }) + + const task = runPromptQueue({ + footer: ui.api, + run: async (input) => { + turns.push(input.text) + if (input.text === "active") await gate + if (input.text === "queued three") ui.api.close() + }, + }) + + ui.submit("active") + ui.submit("queued one") + ui.submit("queued two") + ui.submit("queued three") + await Promise.resolve() + await Promise.resolve() + + const event = ui.events.findLast((item) => item.type === "queued.prompts") + if (event?.type === "queued.prompts") { + const second = event.prompts.find((item) => item.prompt.text === "queued two") + if (second) ui.removeQueued(second.messageID) + } + + wake?.() + await task + expect(turns).toEqual(["active", "queued one", "queued three"]) + }) + test("drains a prompt queued during an in-flight turn", async () => { const ui = footer() const seen: string[] = [] diff --git a/packages/opencode/test/cli/run/scrollback.surface.test.ts b/packages/opencode/test/cli/run/scrollback.surface.test.ts index da196b7e1020..0d8b297a3524 100644 --- a/packages/opencode/test/cli/run/scrollback.surface.test.ts +++ b/packages/opencode/test/cli/run/scrollback.surface.test.ts @@ -938,8 +938,7 @@ test("renders promoted task markdown without a leading blank row", async () => { subagent_type: "explore", }, output: [ - "task_id: child-1 (for resuming to continue this task if needed)", - "", + '', "", "Location: `/tmp/run.ts`", "", @@ -947,6 +946,7 @@ test("renders promoted task markdown without a leading blank row", async () => { "- Local interactive mode", "- Attach mode", "", + "", ].join("\n"), metadata: { sessionId: "child-1", diff --git a/packages/opencode/test/cli/run/session-replay.test.ts b/packages/opencode/test/cli/run/session-replay.test.ts index 36d25c6b43e6..da4bfd382e54 100644 --- a/packages/opencode/test/cli/run/session-replay.test.ts +++ b/packages/opencode/test/cli/run/session-replay.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { replaySession } from "@/cli/cmd/run/session-replay" +import { replayLocalRows, replaySession } from "@/cli/cmd/run/session-replay" import type { SessionMessages } from "@/cli/cmd/run/session.shared" function userMessage(id: string, text: string): SessionMessages[number] { @@ -156,4 +156,301 @@ describe("run session replay", () => { }), ) }) + + test("merges failed local rows ahead of later persisted prompts", () => { + const persisted = { + kind: "user", + text: "successful", + phase: "start", + source: "system", + messageID: "msg-user-2", + } as const + const failed = { + kind: "user", + text: "failed", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const error = { + kind: "error", + text: "network unavailable", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + + expect( + replayLocalRows([userMessage("msg-user-2", "successful")], [persisted], [{ commit: failed }, { commit: error }]), + ).toEqual([failed, error, persisted]) + }) + + test("retains local errors but not duplicate local prompts once a prompt persists", () => { + const persisted = { + kind: "user", + text: "failed after persistence", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const error = { + kind: "error", + text: "connection closed", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + + expect( + replayLocalRows( + [userMessage("msg-user-1", "failed after persistence")], + [persisted], + [{ commit: persisted }, { commit: error }], + ), + ).toEqual([persisted, error]) + }) + + test("keeps a local turn failure below assistant output already visible for that turn", () => { + const first = { + kind: "user", + text: "start", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const answer = { + kind: "assistant", + text: "partial answer", + phase: "progress", + source: "assistant", + messageID: "msg-assistant-1", + } as const + const error = { + kind: "error", + text: "stream failed", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const second = { + kind: "user", + text: "retry", + phase: "start", + source: "system", + messageID: "msg-user-2", + } as const + + expect( + replayLocalRows( + [userMessage("msg-user-1", "start"), userMessage("msg-user-2", "retry")], + [first, answer, second], + [ + { + commit: error, + after: { kind: "assistant", text: "partial answer", phase: "progress", messageID: "msg-assistant-1" }, + }, + ], + ), + ).toEqual([first, answer, error, second]) + }) + + test("keeps a local failure above assistant output received after the failure", () => { + const first = { + kind: "user", + text: "start", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const error = { + kind: "error", + text: "request failed", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const late = { + kind: "assistant", + text: "late answer", + phase: "progress", + source: "assistant", + messageID: "msg-assistant-1", + } as const + + expect(replayLocalRows([userMessage("msg-user-1", "start")], [first, late], [{ commit: error }])).toEqual([ + first, + error, + late, + ]) + }) + + test("inserts a local failure between persisted output chunks spanning that failure", () => { + const first = { + kind: "user", + text: "start", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const complete = { + kind: "assistant", + text: "before after", + phase: "progress", + source: "assistant", + messageID: "msg-assistant-1", + partID: "part-1", + } as const + const error = { + kind: "error", + text: "stream failed", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + + expect( + replayLocalRows( + [userMessage("msg-user-1", "start")], + [first, complete], + [ + { + commit: error, + after: { + kind: "assistant", + text: "before ", + phase: "progress", + messageID: "msg-assistant-1", + partID: "part-1", + visible: "before ", + }, + }, + ], + ), + ).toEqual([first, { ...complete, text: "before " }, error, { ...complete, text: "after" }]) + }) + + test("places an unpersisted failed prompt before live output from that turn", () => { + const prompt = { + kind: "user", + text: "start", + phase: "start", + source: "system", + messageID: "msg-1", + } as const + const answer = { + kind: "assistant", + text: "partial answer", + phase: "progress", + source: "assistant", + messageID: "msg-2", + } as const + const error = { + kind: "error", + text: "stream failed", + phase: "start", + source: "system", + messageID: "msg-1", + } as const + + expect( + replayLocalRows( + [], + [answer], + [ + { commit: prompt }, + { + commit: error, + after: { kind: "assistant", text: "partial answer", phase: "progress", messageID: "msg-2" }, + }, + ], + ), + ).toEqual([prompt, answer, error]) + }) + + test("anchors a failure after the visible start of a tool that later completes", () => { + const prompt = { + kind: "user", + text: "run ls", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const running = { + kind: "tool", + text: "running bash", + phase: "start", + source: "tool", + messageID: "msg-assistant-1", + partID: "part-tool-1", + toolState: "running", + } as const + const completed = { + kind: "tool", + text: "file.txt", + phase: "final", + source: "tool", + messageID: "msg-assistant-1", + partID: "part-tool-1", + toolState: "completed", + } as const + const error = { + kind: "error", + text: "connection lost", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + + expect( + replayLocalRows( + [userMessage("msg-user-1", "run ls")], + [prompt, running, completed], + [ + { + commit: error, + after: { + kind: "tool", + text: "running bash", + phase: "start", + messageID: "msg-assistant-1", + partID: "part-tool-1", + toolState: "running", + }, + }, + ], + ), + ).toEqual([prompt, running, error, completed]) + }) + + test("retains an unpersisted local diagnostic before later persisted prompts", () => { + const first = { + kind: "user", + text: "before", + phase: "start", + source: "system", + messageID: "msg-user-1", + } as const + const error = { + kind: "error", + text: "failed to start new session", + phase: "start", + source: "system", + messageID: "msg-user-2", + } as const + const second = { + kind: "user", + text: "after", + phase: "start", + source: "system", + messageID: "msg-user-3", + } as const + + expect( + replayLocalRows( + [userMessage("msg-user-1", "before"), userMessage("msg-user-3", "after")], + [first, second], + [{ commit: error }], + ), + ).toEqual([first, error, second]) + }) }) diff --git a/packages/opencode/test/cli/run/stream.test.ts b/packages/opencode/test/cli/run/stream.test.ts index 9fb6e7b614d2..e6b40dd92517 100644 --- a/packages/opencode/test/cli/run/stream.test.ts +++ b/packages/opencode/test/cli/run/stream.test.ts @@ -9,6 +9,7 @@ function footer() { const api: FooterApi = { isClosed: false, onPrompt: () => () => {}, + onQueuedRemove: () => () => {}, onClose: () => () => {}, event: (next) => { events.push(next) diff --git a/packages/opencode/test/cli/run/stream.transport.test.ts b/packages/opencode/test/cli/run/stream.transport.test.ts index d1b145db24b2..2dcfc3c4c8e8 100644 --- a/packages/opencode/test/cli/run/stream.transport.test.ts +++ b/packages/opencode/test/cli/run/stream.transport.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test" import { OpencodeClient, type GlobalEvent } from "@opencode-ai/sdk/v2" import { createSessionTransport } from "@/cli/cmd/run/stream.transport" -import type { FooterApi, FooterEvent, RunFilePart, StreamCommit } from "@/cli/cmd/run/types" +import type { FooterApi, FooterEvent, LocalReplayRow, RunFilePart, StreamCommit } from "@/cli/cmd/run/types" type EventStream = Awaited>["stream"] type GlobalEventStream = Awaited>["stream"] @@ -11,6 +11,7 @@ type SessionChild = NonNullable type SessionStatusMap = NonNullable>["data"]> type TextPart = Extract +type ReasoningPart = Extract afterEach(() => { mock.restore() @@ -298,6 +299,29 @@ function textUpdated(part: TextPart): SdkEvent { } } +function reasoningPart(id: string, messageID: string, text: string): ReasoningPart { + return { + id, + sessionID: "session-1", + messageID, + type: "reasoning", + text, + time: { start: 1 }, + } +} + +function reasoningUpdated(part: ReasoningPart): SdkEvent { + return { + id: `evt-${part.id}-updated`, + type: "message.part.updated", + properties: { + sessionID: part.sessionID, + part, + time: 1, + }, + } +} + function toolUpdated(part: SessionToolPart): SdkEvent { return { id: `evt-${part.id}-updated`, @@ -358,6 +382,7 @@ function footer(fn?: (commit: StreamCommit) => void) { return closed }, onPrompt: () => () => {}, + onQueuedRemove: () => () => {}, onClose: () => () => {}, event(next) { events.push(next) @@ -720,6 +745,444 @@ describe("run stream transport", () => { } }) + test("rebuilds session output on resize and continues live deltas from replayed state", async () => { + const src = eventFeed() + const ui = footer() + let calls = 0 + const transport = await createSessionTransport({ + sdk: sdk({ + stream: src.stream, + messages: async () => { + calls += 1 + if (calls === 1) { + return ok([]) + } + + return ok([ + assistantMessage({ + sessionID: "session-1", + id: "msg-1", + parts: [textPart("text-1", "msg-1", "Hello")], + }), + ]) + }, + }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + const localRows: LocalReplayRow[] = [ + { commit: { kind: "user", text: "pending prompt", phase: "start", source: "system", messageID: "msg-pending" } }, + ] + const reset = mock(() => { + localRows.push({ + commit: { + kind: "user", + text: "sent during reset", + phase: "start", + source: "system", + messageID: "msg-during-reset", + }, + }) + return Promise.resolve() + }) + + try { + expect( + await transport.replayOnResize({ + localRows: () => localRows, + reset, + }), + ).toBe(true) + expect(reset).toHaveBeenCalledTimes(1) + expect(ui.commits).toEqual( + expect.arrayContaining([ + expect.objectContaining({ kind: "assistant", text: "Hello" }), + expect.objectContaining({ kind: "user", text: "sent during reset", messageID: "msg-during-reset" }), + ]), + ) + + src.push(textUpdated(textPart("text-1", "msg-1", "Hello world"))) + await waitFor(() => ui.commits.find((commit) => commit.kind === "assistant" && commit.text === " world")) + expect(ui.commits.filter((commit) => commit.kind === "assistant").map((commit) => commit.text)).toEqual([ + "Hello", + " world", + ]) + } finally { + src.close() + await transport.close() + } + }) + + test("coalesces active resize requests into one trailing replay", async () => { + const src = eventFeed() + const ui = footer() + const firstReset = defer() + const resetA = mock(() => firstReset.promise) + const resetB = mock(() => Promise.resolve()) + const resetC = mock(() => Promise.resolve()) + const transport = await createSessionTransport({ + sdk: sdk({ stream: src.stream }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + + try { + const active = transport.replayOnResize({ localRows: () => [], reset: resetA }) + await waitFor(() => (resetA.mock.calls.length === 1 ? true : undefined)) + + expect(await transport.replayOnResize({ localRows: () => [], reset: resetB })).toBe(false) + expect(await transport.replayOnResize({ localRows: () => [], reset: resetC })).toBe(false) + expect(resetB).not.toHaveBeenCalled() + + firstReset.resolve() + expect(await active).toBe(true) + expect(resetA).toHaveBeenCalledTimes(1) + expect(resetB).not.toHaveBeenCalled() + expect(resetC).toHaveBeenCalledTimes(1) + } finally { + src.close() + await transport.close() + } + }) + + test("keeps coalescing resize requests while buffered events drain", async () => { + const src = eventFeed() + const ui = footer() + const firstReset = defer() + const statusGate = defer() + const statusStarted = defer() + let blockStatus = false + const trace = mock((_type: string, _data?: unknown) => {}) + const resetA = mock(() => firstReset.promise) + const resetB = mock(() => Promise.resolve()) + const resetC = mock(() => Promise.resolve()) + const transport = await createSessionTransport({ + sdk: sdk({ + stream: src.stream, + status: async () => { + if (blockStatus) { + statusStarted.resolve() + await statusGate.promise + } + return ok(statusMap(true)) + }, + }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + trace: { write: trace }, + }) + const turn = transport.runPromptTurn({ + agent: undefined, + model: undefined, + variant: undefined, + prompt: { text: "active", parts: [] }, + files: [], + includeFiles: false, + }) + + try { + await waitFor(() => ui.events.find((event) => event.type === "turn.wait")) + const active = transport.replayOnResize({ localRows: () => [], reset: resetA }) + await waitFor(() => (resetA.mock.calls.length === 1 ? true : undefined)) + blockStatus = true + src.push(busy()) + src.push(idle()) + await waitFor(() => (trace.mock.calls.filter((call) => call[0] === "recv.event").length >= 2 ? true : undefined)) + + expect(await transport.replayOnResize({ localRows: () => [], reset: resetB })).toBe(false) + firstReset.resolve() + await Promise.race([ + statusStarted.promise, + Bun.sleep(1_000).then(() => { + throw new Error("timed out waiting for buffered status drain") + }), + ]) + + expect(await transport.replayOnResize({ localRows: () => [], reset: resetC })).toBe(false) + expect(resetC).not.toHaveBeenCalled() + blockStatus = false + statusGate.resolve() + + expect( + await Promise.race([ + active, + Bun.sleep(1_000).then(() => { + throw new Error("timed out waiting for trailing resize replay") + }), + ]), + ).toBe(true) + expect(resetB).not.toHaveBeenCalled() + expect(resetC).toHaveBeenCalledTimes(1) + } finally { + src.close() + await transport.close() + await turn + } + }) + + test("preserves assistant deltas not yet persisted when replaying during a live stream", async () => { + const src = eventFeed() + const ui = footer() + let calls = 0 + const transport = await createSessionTransport({ + sdk: sdk({ + stream: src.stream, + messages: async () => { + calls += 1 + if (calls === 1) { + return ok([]) + } + + return ok([ + assistantMessage({ + sessionID: "session-1", + id: "msg-live", + parts: [textPart("text-live", "msg-live", "")], + }), + ]) + }, + }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + + try { + src.push(assistant("msg-live")) + src.push(textUpdated(textPart("text-live", "msg-live", ""))) + src.push(textDelta("msg-live", "text-live", "Hello")) + await waitFor(() => ui.commits.find((commit) => commit.kind === "assistant" && commit.text === "Hello")) + ui.commits.length = 0 + + expect(await transport.replayOnResize({ localRows: () => [], reset: () => Promise.resolve() })).toBe(true) + src.push(textDelta("msg-live", "text-live", "Hello")) + src.push( + textUpdated({ + ...textPart("text-live", "msg-live", "HelloHello"), + time: { start: 1, end: 2 }, + }), + ) + + await waitFor(() => + ui.commits.filter((commit) => commit.kind === "assistant" && commit.text === "Hello").length === 2 + ? true + : undefined, + ) + expect( + ui.commits.filter((commit) => commit.kind === "assistant" && commit.text).map((commit) => commit.text), + ).toEqual(["Hello", "Hello"]) + } finally { + src.close() + await transport.close() + } + }) + + test("preserves the display prefix for active reasoning restored during replay", async () => { + const src = eventFeed() + const ui = footer() + let calls = 0 + const transport = await createSessionTransport({ + sdk: sdk({ + stream: src.stream, + messages: async () => { + calls += 1 + if (calls === 1) { + return ok([]) + } + + return ok([ + assistantMessage({ + sessionID: "session-1", + id: "msg-thinking", + parts: [reasoningPart("thinking-1", "msg-thinking", "")], + }), + ]) + }, + }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + + try { + src.push(assistant("msg-thinking")) + src.push(reasoningUpdated(reasoningPart("thinking-1", "msg-thinking", ""))) + src.push(textDelta("msg-thinking", "thinking-1", "plan")) + await waitFor(() => ui.commits.find((commit) => commit.kind === "reasoning" && commit.text === "Thinking: plan")) + ui.commits.length = 0 + + expect(await transport.replayOnResize({ localRows: () => [], reset: () => Promise.resolve() })).toBe(true) + expect(ui.commits.filter((commit) => commit.kind === "reasoning").map((commit) => commit.text)).toEqual([ + "Thinking: plan", + ]) + } finally { + src.close() + await transport.close() + } + }) + + test("does not overlay stale active text when persistence completes during replay", async () => { + const src = eventFeed() + const ui = footer() + let calls = 0 + const transport = await createSessionTransport({ + sdk: sdk({ + stream: src.stream, + messages: async () => { + calls += 1 + if (calls === 1) { + return ok([]) + } + + return ok([ + assistantMessage({ + sessionID: "session-1", + id: "msg-finished", + parts: [ + { + ...textPart("text-finished", "msg-finished", "Hello"), + time: { start: 1, end: 2 }, + }, + ], + }), + ]) + }, + }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + + try { + src.push(assistant("msg-finished")) + src.push(textUpdated(textPart("text-finished", "msg-finished", ""))) + src.push(textDelta("msg-finished", "text-finished", "Hello")) + await waitFor(() => ui.commits.find((commit) => commit.kind === "assistant" && commit.text === "Hello")) + ui.commits.length = 0 + + expect(await transport.replayOnResize({ localRows: () => [], reset: () => Promise.resolve() })).toBe(true) + expect( + ui.commits.filter((commit) => commit.kind === "assistant" && commit.text).map((commit) => commit.text), + ).toEqual(["Hello"]) + } finally { + src.close() + await transport.close() + } + }) + + test("does not clear the terminal when resize replay snapshot fetch fails", async () => { + const src = eventFeed() + const ui = footer() + let calls = 0 + const transport = await createSessionTransport({ + sdk: sdk({ + stream: src.stream, + messages: async () => { + calls += 1 + if (calls === 1) { + return ok([]) + } + + throw new Error("snapshot failed") + }, + }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + const reset = mock(() => Promise.resolve()) + + try { + expect(await transport.replayOnResize({ localRows: () => [], reset })).toBe(false) + expect(reset).not.toHaveBeenCalled() + expect(ui.commits).toEqual([]) + } finally { + src.close() + await transport.close() + } + }) + + test("disables resize replay for the session after terminal reset fails", async () => { + const src = eventFeed() + const ui = footer() + const transport = await createSessionTransport({ + sdk: sdk({ stream: src.stream }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + const reset = mock(() => Promise.reject(new Error("clear failed"))) + + try { + expect(await transport.replayOnResize({ localRows: () => [], reset })).toBe(false) + expect(await transport.replayOnResize({ localRows: () => [], reset })).toBe(false) + expect(reset).toHaveBeenCalledTimes(1) + expect(ui.commits).toContainEqual({ + kind: "error", + text: "resize replay failed; disabled for this session", + phase: "start", + source: "system", + }) + } finally { + src.close() + await transport.close() + } + }) + + test("disables resize replay when rebuilding scrollback fails after terminal reset", async () => { + const src = eventFeed() + const ui = footer() + let cleared = false + const idle = ui.api.idle + ui.api.idle = () => (cleared ? Promise.reject(new Error("render failed")) : idle()) + const transport = await createSessionTransport({ + sdk: sdk({ stream: src.stream }), + sessionID: "session-1", + thinking: true, + replay: true, + limits: () => ({}), + footer: ui.api, + }) + const reset = mock(() => { + cleared = true + return Promise.resolve() + }) + + try { + expect(await transport.replayOnResize({ localRows: () => [], reset })).toBe(false) + expect(await transport.replayOnResize({ localRows: () => [], reset })).toBe(false) + expect(reset).toHaveBeenCalledTimes(1) + expect(ui.commits).toContainEqual({ + kind: "error", + text: "resize replay failed; disabled for this session", + phase: "start", + source: "system", + }) + } finally { + src.close() + await transport.close() + } + }) + test("drops completed historical subagent tabs during bootstrap", async () => { const src = eventFeed() const ui = footer() diff --git a/packages/opencode/test/cli/tui/__snapshots__/inline-tool-wrap-snapshot.test.tsx.snap b/packages/opencode/test/cli/tui/__snapshots__/inline-tool-wrap-snapshot.test.tsx.snap new file mode 100644 index 000000000000..9e317dae888d --- /dev/null +++ b/packages/opencode/test/cli/tui/__snapshots__/inline-tool-wrap-snapshot.test.tsx.snap @@ -0,0 +1,54 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`TUI inline tool wrapping snapshots consecutive grep, glob, and read rows at a narrow width 1`] = ` +" ✱ Grep "OPENCODE.*DB|database|sqlite|drizzle|dev.*db|data. + *dir|xdg|APPDATA" in packages/opencode/src (151 matches) + ✱ Glob "**/*db*" in packages/opencode (6 matches) + → Read packages/opencode/src/storage/db.ts [offset=1, limit=130] + → Read packages/opencode/src/index.ts [offset=1, limit=100] + ✱ Grep "export const OPENCODE_DB|OPENCODE_DB|OPENCODE_DEV|Global\\. + Path\\.data|data =" in packages/opencode/src (115 matches)" +`; + +exports[`TUI inline tool wrapping snapshots expanded tool errors under the tool text 1`] = ` +" ✱ Grep "OPENCODE.*DB|database|sqlite|drizzle|dev.*db|data. + *dir|xdg|APPDATA" in packages/opencode/src (151 matches) + ✱ Glob "**/*db*" in packages/opencode (6 matches) + → Read packages/opencode/src/storage/db.ts [offset=1, limit=130] + → Read packages/opencode/src/index.ts [offset=1, limit=100] + No LSP server available for this file type. + ✱ Grep "export const OPENCODE_DB|OPENCODE_DB|OPENCODE_DEV|Global\\. + Path\\.data|data =" in packages/opencode/src (115 matches)" +`; + +exports[`TUI inline tool wrapping keeps separation after a shell output block 1`] = ` +" + + # List files + + $ ls + + file.ts + + ✱ Grep "OPENCODE.*DB|database|sqlite|drizzle|dev.*db|data. + *dir|xdg|APPDATA" in packages/opencode/src (151 matches) + ✱ Glob "**/*db*" in packages/opencode (6 matches) + → Read packages/opencode/src/storage/db.ts [offset=1, limit=130] + → Read packages/opencode/src/index.ts [offset=1, limit=100] + ✱ Grep "export const OPENCODE_DB|OPENCODE_DB|OPENCODE_DEV|Global\\. + Path\\.data|data =" in packages/opencode/src (115 matches)" +`; + +exports[`TUI inline tool wrapping keeps separation after a padded user message 1`] = ` +" + Check whether the next tool remains separated. + + + ✱ Grep "OPENCODE.*DB|database|sqlite|drizzle|dev.*db|data. + *dir|xdg|APPDATA" in packages/opencode/src (151 matches) + ✱ Glob "**/*db*" in packages/opencode (6 matches) + → Read packages/opencode/src/storage/db.ts [offset=1, limit=130] + → Read packages/opencode/src/index.ts [offset=1, limit=100] + ✱ Grep "export const OPENCODE_DB|OPENCODE_DB|OPENCODE_DEV|Global\\. + Path\\.data|data =" in packages/opencode/src (115 matches)" +`; diff --git a/packages/opencode/test/cli/tui/app-lifecycle.test.ts b/packages/opencode/test/cli/tui/app-lifecycle.test.ts new file mode 100644 index 000000000000..8f5cb5234616 --- /dev/null +++ b/packages/opencode/test/cli/tui/app-lifecycle.test.ts @@ -0,0 +1,261 @@ +import { afterEach, expect, spyOn, test } from "bun:test" +import { createTestRenderer } from "@opentui/core/testing" +import { mkdir } from "node:fs/promises" +import path from "node:path" +import { tmpdir } from "../../fixture/fixture" +import { createTuiResolvedConfig } from "../../fixture/tui-runtime" +import { TuiPluginRuntime } from "../../../src/cli/cmd/tui/plugin/runtime" +import { tui, type TuiHandle } from "../../../src/cli/cmd/tui/app" +import { Global } from "@opencode-ai/core/global" +import { createEventSource, createFetch, directory } from "../../fixture/tui-sdk" +import * as TuiAudio from "../../../src/cli/cmd/tui/util/audio" +import * as TuiKeymap from "../../../src/cli/cmd/tui/keymap" + +type TestRendererSetup = Awaited> +type TmpDir = Awaited> + +const disabledInternalPlugins = { + "internal:home-footer": false, + "internal:home-tips": false, + "internal:sidebar-context": false, + "internal:sidebar-mcp": false, + "internal:sidebar-lsp": false, + "internal:sidebar-todo": false, + "internal:sidebar-files": false, + "internal:sidebar-footer": false, + "internal:plugin-manager": false, + "internal:session-v2-debug": false, + "which-key": false, +} +let active: { handle?: TuiHandle; setup?: TestRendererSetup; restore?: () => void; tmp?: TmpDir } | undefined + +afterEach(async () => { + const current = active + active = undefined + await current?.handle?.exit().catch(() => {}) + await current?.handle?.done.catch(() => {}) + await current?.handle?.ready.catch(() => {}) + if (current?.setup && !current.setup.renderer.isDestroyed) current.setup.renderer.destroy() + current?.restore?.() + await Bun.sleep(20) + await current?.tmp?.[Symbol.asyncDispose]() + await TuiPluginRuntime.dispose().catch(() => {}) +}) + +test("returns a handle immediately and resolves ready after async mount setup", async () => { + const app = await startTui() + + expect(await promiseState(app.handle.ready)).toBe("pending") + + app.theme.resolve("dark") + await app.handle.ready + + expect(app.setup.renderer.isDestroyed).toBe(false) + expect(await promiseState(app.handle.done)).toBe("pending") +}) + +test("production can await done only and still receives mount failures", async () => { + const app = await startTui({ rejectTheme: new Error("theme failed") }) + + await expect(app.handle.done).rejects.toThrow("theme failed") + expect(app.setup.renderer.isDestroyed).toBe(true) +}) + +test("exit destroys the renderer, resolves done, and runs cleanup once", async () => { + const beforeSighup = process.listenerCount("SIGHUP") + const app = await startTui() + + app.theme.resolve("dark") + await app.handle.ready + expect(process.listenerCount("SIGHUP")).toBeGreaterThan(beforeSighup) + + await Promise.all([app.handle.exit(), app.handle.exit()]) + await app.handle.done + + expect(app.setup.renderer.isDestroyed).toBe(true) + expect(process.listenerCount("SIGHUP")).toBe(beforeSighup) +}) + +test("exit preserves reason formatting and exit messages", async () => { + const stdout: string[] = [] + const stderr: string[] = [] + const stdoutWrite = spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array) => { + stdout.push(String(chunk)) + return true + }) + const stderrWrite = spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array) => { + stderr.push(String(chunk)) + return true + }) + + try { + const app = await startTui() + app.theme.resolve("dark") + await app.handle.ready + + app.handle.exit.message.set("goodbye") + await app.handle.exit(new Error("boom")) + await app.handle.done + + expect(stderr.join("")).toContain("boom") + expect(stdout.join("")).toBe("goodbye\n") + } finally { + stdoutWrite.mockRestore() + stderrWrite.mockRestore() + } +}) + +test("exit before ready cancels mount and resolves done", async () => { + const app = await startTui() + + await app.handle.exit() + await app.handle.done + + expect(app.setup.renderer.isDestroyed).toBe(true) + await expect(app.handle.ready).resolves.toBeUndefined() +}) + +test("direct renderer destruction still cleans up and resolves done", async () => { + const beforeSighup = process.listenerCount("SIGHUP") + const app = await startTui() + + app.theme.resolve("dark") + await app.handle.ready + app.setup.renderer.destroy() + await app.handle.done + + expect(process.listenerCount("SIGHUP")).toBe(beforeSighup) +}) + +test("SIGHUP exits before ready and removes its listener", async () => { + const beforeSighup = process.listenerCount("SIGHUP") + const app = await startTui() + + process.emit("SIGHUP") + await app.handle.done + + expect(app.setup.renderer.isDestroyed).toBe(true) + expect(process.listenerCount("SIGHUP")).toBe(beforeSighup) +}) + +test("SIGHUP exits after ready and removes its listener", async () => { + const beforeSighup = process.listenerCount("SIGHUP") + const app = await startTui() + + app.theme.resolve("dark") + await app.handle.ready + process.emit("SIGHUP") + await app.handle.done + + expect(app.setup.renderer.isDestroyed).toBe(true) + expect(process.listenerCount("SIGHUP")).toBe(beforeSighup) +}) + +test("plugin, audio, and keymap cleanup run exactly once", async () => { + const originalRegister = TuiKeymap.registerOpencodeKeymap + let unregisterKeymapCalls = 0 + const registerKeymap = spyOn(TuiKeymap, "registerOpencodeKeymap").mockImplementation((...args) => { + const unregister = originalRegister(...args) + return () => { + unregisterKeymapCalls++ + unregister() + } + }) + const disposePlugins = spyOn(TuiPluginRuntime, "dispose") + const disposeAudio = spyOn(TuiAudio, "dispose") + + try { + const app = await startTui() + app.theme.resolve("dark") + await app.handle.ready + + app.setup.renderer.destroy() + await Promise.all([app.handle.exit(), app.handle.exit()]) + await app.handle.done + + expect(registerKeymap).toHaveBeenCalledTimes(1) + expect(unregisterKeymapCalls).toBe(1) + expect(disposePlugins).toHaveBeenCalledTimes(1) + expect(disposeAudio).toHaveBeenCalledTimes(1) + } finally { + registerKeymap.mockRestore() + disposePlugins.mockRestore() + disposeAudio.mockRestore() + } +}) + +async function startTui(options: { rejectTheme?: Error } = {}) { + const tmp = await tmpdir() + const restore = await isolateGlobalPaths(tmp.path) + const setup = await createTestRenderer({ width: 80, height: 24, useThread: false, maxFps: Number.POSITIVE_INFINITY }) + const theme = deferred<"dark" | "light" | null>() + const waitForThemeMode = spyOn(setup.renderer, "waitForThemeMode").mockImplementation(() => { + if (options.rejectTheme) return Promise.reject(options.rejectTheme) + return theme.promise + }) + setup.renderer.once("destroy", () => theme.resolve(null)) + + const calls = createFetch() + const events = createEventSource() + const handle = tui({ + url: "http://test", + renderer: setup.renderer, + config: createTuiResolvedConfig({ plugin_enabled: disabledInternalPlugins }), + directory, + fetch: calls.fetch, + events: events.source, + args: {}, + }) + active = { + handle, + setup, + tmp, + restore: () => { + waitForThemeMode.mockRestore() + restore() + }, + } + + return { handle, setup, theme } +} + +async function isolateGlobalPaths(root: string) { + const previous = { + config: Global.Path.config, + state: Global.Path.state, + } + Global.Path.config = path.join(root, "config") + Global.Path.state = path.join(root, "state") + await mkdir(Global.Path.config, { recursive: true }) + await mkdir(Global.Path.state, { recursive: true }) + await Bun.write(path.join(Global.Path.state, "kv.json"), JSON.stringify({ animations_enabled: false })) + + return () => { + Global.Path.config = previous.config + Global.Path.state = previous.state + } +} + +async function promiseState(promise: Promise) { + let state: "pending" | "resolved" | "rejected" = "pending" + promise.then( + () => { + state = "resolved" + }, + () => { + state = "rejected" + }, + ) + await Promise.resolve() + return state +} + +function deferred() { + let resolve!: (value: T | PromiseLike) => void + let reject!: (error: unknown) => void + const promise = new Promise((done, fail) => { + resolve = done + reject = fail + }) + return { promise, resolve, reject } +} diff --git a/packages/opencode/test/cli/tui/inline-tool-wrap-snapshot.test.tsx b/packages/opencode/test/cli/tui/inline-tool-wrap-snapshot.test.tsx new file mode 100644 index 000000000000..cab39bdc238f --- /dev/null +++ b/packages/opencode/test/cli/tui/inline-tool-wrap-snapshot.test.tsx @@ -0,0 +1,119 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { For } from "solid-js" +import { testRender, type JSX } from "@opentui/solid" +import { InlineToolRow } from "../../../src/cli/cmd/tui/routes/session/index" + +let testSetup: Awaited> | undefined + +afterEach(() => { + testSetup?.renderer.destroy() + testSetup = undefined +}) + +type ToolFixture = { icon: string; label: string; error?: string } + +const tools: readonly ToolFixture[] = [ + { + icon: "✱", + label: + 'Grep "OPENCODE.*DB|database|sqlite|drizzle|dev.*db|data.*dir|xdg|APPDATA" in packages/opencode/src (151 matches)', + }, + { + icon: "✱", + label: 'Glob "**/*db*" in packages/opencode (6 matches)', + }, + { + icon: "→", + label: "Read packages/opencode/src/storage/db.ts [offset=1, limit=130]", + }, + { + icon: "→", + label: "Read packages/opencode/src/index.ts [offset=1, limit=100]", + error: "No LSP server available for this file type.", + }, + { + icon: "✱", + label: + 'Grep "export const OPENCODE_DB|OPENCODE_DB|OPENCODE_DEV|Global\\.Path\\.data|data =" in packages/opencode/src (115 matches)', + }, +] as const + +function ShellOutput() { + return ( + + # List files + + $ ls + file.ts + + + ) +} + +function UserMessage() { + return ( + + + Check whether the next tool remains separated. + + + ) +} + +function Fixture(props: { errorExpanded?: boolean; before?: "shell" | "user" }) { + return ( + + + {props.before === "shell" && } + {props.before === "user" && } + + {(item) => ( + id === "message-user"} + > + {item.label} + + )} + + + + ) +} + +async function renderFrame(component: () => JSX.Element, options: { width: number; height: number }) { + testSetup = await testRender(component, options) + await testSetup.renderOnce() + await Bun.sleep(25) + await testSetup.renderOnce() + + return testSetup + .captureCharFrame() + .split("\n") + .map((line) => line.trimEnd()) + .join("\n") + .trimEnd() +} + +describe("TUI inline tool wrapping", () => { + test("snapshots consecutive grep, glob, and read rows at a narrow width", async () => { + expect(await renderFrame(() => , { width: 72, height: 12 })).toMatchSnapshot() + }) + + test("snapshots expanded tool errors under the tool text", async () => { + expect(await renderFrame(() => , { width: 72, height: 12 })).toMatchSnapshot() + }) + + test("keeps separation after a shell output block", async () => { + expect(await renderFrame(() => , { width: 72, height: 16 })).toMatchSnapshot() + }) + + test("keeps separation after a padded user message", async () => { + expect(await renderFrame(() => , { width: 72, height: 14 })).toMatchSnapshot() + }) +}) diff --git a/packages/opencode/test/cli/tui/keymap.test.tsx b/packages/opencode/test/cli/tui/keymap.test.tsx index 82cd72d6c874..d1ebefb4c165 100644 --- a/packages/opencode/test/cli/tui/keymap.test.tsx +++ b/packages/opencode/test/cli/tui/keymap.test.tsx @@ -4,7 +4,12 @@ import { testRender, useRenderer } from "@opentui/solid" import { expect, test } from "bun:test" import { onCleanup } from "solid-js" import { createTuiResolvedConfig } from "../../fixture/tui-runtime" -import { OpencodeKeymapProvider, registerOpencodeKeymap } from "@/cli/cmd/tui/keymap" +import { + getOpencodeModeStack, + OPENCODE_BASE_MODE, + OpencodeKeymapProvider, + registerOpencodeKeymap, +} from "@/cli/cmd/tui/keymap" test("legacy page key aliases compile as page keys", async () => { const sequences: Record = {} @@ -52,3 +57,80 @@ test("legacy page key aliases compile as page keys", async () => { app.renderer.destroy() } }) + +test("mode-less bindings stay active when opencode mode changes", async () => { + const counts: Record> = {} + + function Harness() { + const renderer = useRenderer() + const keymap = createDefaultOpenTuiKeymap(renderer) + const config = createTuiResolvedConfig() + const offKeymap = registerOpencodeKeymap(keymap, renderer, config) + const offGlobal = keymap.registerLayer({ + commands: [ + { name: "session.list", run() {} }, + { name: "session.new", run() {} }, + { name: "session.page.up", run() {} }, + { name: "session.first", run() {} }, + ], + bindings: config.keybinds.gather("test.global", [ + "session.list", + "session.new", + "session.page.up", + "session.first", + ]), + }) + const offBase = keymap.registerLayer({ + mode: OPENCODE_BASE_MODE, + commands: [{ name: "model.list", run() {} }], + bindings: config.keybinds.gather("test.base", ["model.list"]), + }) + const activeCounts = () => + Object.fromEntries( + Array.from( + keymap.getCommandBindings({ + visibility: "active", + commands: ["session.list", "session.new", "session.page.up", "session.first", "model.list"], + }), + ([command, bindings]) => [command, bindings.length], + ), + ) + + counts.base = activeCounts() + const popQuestion = getOpencodeModeStack(keymap).push("question") + counts.question = activeCounts() + popQuestion() + const popAutocomplete = getOpencodeModeStack(keymap).push("autocomplete") + counts.autocomplete = activeCounts() + popAutocomplete() + + onCleanup(() => { + offBase() + offGlobal() + offKeymap() + }) + + return ( + + + + ) + } + + const app = await testRender(() => ) + try { + expect(counts).toEqual({ + base: { "session.list": 1, "session.new": 1, "session.page.up": 2, "session.first": 2, "model.list": 1 }, + question: { "session.list": 1, "session.new": 1, "session.page.up": 2, "session.first": 2, "model.list": 0 }, + autocomplete: { + "session.list": 1, + "session.new": 1, + "session.page.up": 2, + "session.first": 2, + "model.list": 0, + }, + }) + } finally { + app.renderer.destroy() + } +}) diff --git a/packages/opencode/test/cli/tui/use-event.test.tsx b/packages/opencode/test/cli/tui/use-event.test.tsx index d690cfd6cec8..2aa3e978128c 100644 --- a/packages/opencode/test/cli/tui/use-event.test.tsx +++ b/packages/opencode/test/cli/tui/use-event.test.tsx @@ -6,6 +6,7 @@ import { onMount } from "solid-js" import { ProjectProvider, useProject } from "../../../src/cli/cmd/tui/context/project" import { SDKProvider } from "../../../src/cli/cmd/tui/context/sdk" import { useEvent } from "../../../src/cli/cmd/tui/context/event" +import { createEventSource, createFetch, directory } from "../../fixture/tui-sdk" const projectID = "proj_test" @@ -46,35 +47,11 @@ function update(version: string): Event { } } -function createSource() { - let fn: ((event: GlobalEvent) => void) | undefined - - return { - source: { - subscribe: async (handler: (event: GlobalEvent) => void) => { - fn = handler - return () => { - if (fn === handler) fn = undefined - } - }, - }, - emit(evt: GlobalEvent) { - if (!fn) throw new Error("event source not ready") - fn(evt) - }, - } -} - async function mount() { - const source = createSource() + const events = createEventSource() + const calls = createFetch() const seen: Event[] = [] const workspaces: Array = [] - const fetch = (async (input: RequestInfo | URL) => { - const url = new URL(input instanceof Request ? input.url : String(input)) - if (url.pathname === "/path") return Response.json({ home: "", state: "", config: "", directory: "/tmp/root" }) - if (url.pathname === "/project/current") return Response.json({ id: projectID }) - throw new Error(`unexpected request: ${url.pathname}`) - }) as typeof globalThis.fetch let project!: ReturnType let done!: () => void const ready = new Promise((resolve) => { @@ -82,7 +59,7 @@ async function mount() { }) const app = await testRender(() => ( - + { @@ -98,7 +75,7 @@ async function mount() { )) await ready - return { app, emit: source.emit, project, seen, workspaces } + return { app, emit: events.emit, project, seen, workspaces } } function Probe(props: { @@ -140,7 +117,7 @@ describe("useEvent", () => { const { app, emit, seen } = await mount() try { - emit(event(vcs("other"), { directory: "/tmp/root", project: "proj_other" })) + emit(event(vcs("other"), { directory, project: "proj_other" })) await Bun.sleep(30) expect(seen).toHaveLength(0) diff --git a/packages/opencode/test/config/config.test.ts b/packages/opencode/test/config/config.test.ts index 6ce0acdb2a7b..85cb78a329c6 100644 --- a/packages/opencode/test/config/config.test.ts +++ b/packages/opencode/test/config/config.test.ts @@ -1,4 +1,4 @@ -import { test, expect, describe, afterEach, beforeEach } from "bun:test" +import { test, expect, describe, afterEach, beforeEach, spyOn } from "bun:test" import { Effect, Exit, Layer, Option } from "effect" import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http" import { NodeFileSystem, NodePath } from "@effect/platform-node" @@ -28,9 +28,10 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { testEffect } from "../lib/effect" import path from "path" import fs from "fs/promises" +import os from "os" import { pathToFileURL } from "url" import { Global } from "@opencode-ai/core/global" -import { ProjectID } from "../../src/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { Filesystem } from "@/util/filesystem" import { ConfigPlugin } from "@/config/plugin" import { AccountTest } from "../fake/account" @@ -274,7 +275,7 @@ async function check(map: (dir: string) => string) { const cfg = await load(ctx) expect(cfg.snapshot).toBe(true) expect(ctx.directory).toBe(Filesystem.resolve(tmp.path)) - expect(ctx.project.id).not.toBe(ProjectID.global) + expect(ctx.project.id).not.toBe(ProjectV2.ID.global) }, }) } finally { @@ -291,6 +292,20 @@ it.instance("loads config with defaults when no files exist", () => }), ) +it.instance("falls back to generic username when system user info is unavailable", () => + Effect.gen(function* () { + const userInfo = spyOn(os, "userInfo").mockImplementation(() => { + throw Object.assign(new Error("missing passwd entry"), { code: "ENOENT" }) + }) + try { + const config = yield* Config.use.get() + expect(config.username).toBe("user") + } finally { + userInfo.mockRestore() + } + }), +) + it.effect("creates global jsonc config with schema when no global configs exist", () => withGlobalConfig({}, ({ dir }) => Effect.gen(function* () { @@ -1485,15 +1500,18 @@ test("remote well-known config can use FetchHttpClient layer", async () => { ).pipe( Effect.scoped, Effect.provide( - Config.layer.pipe( - Layer.provide(testFlock), - Layer.provide(AppFileSystem.defaultLayer), - Layer.provide(Env.defaultLayer), - Layer.provide(wellKnownAuth(server.url.origin)), - Layer.provide(AccountTest.empty), - Layer.provideMerge(infra), - Layer.provide(NpmTest.noop), - Layer.provide(FetchHttpClient.layer), + Layer.mergeAll( + Config.layer.pipe( + Layer.provide(testFlock), + Layer.provide(AppFileSystem.defaultLayer), + Layer.provide(Env.defaultLayer), + Layer.provide(wellKnownAuth(server.url.origin)), + Layer.provide(AccountTest.empty), + Layer.provideMerge(infra), + Layer.provide(NpmTest.noop), + Layer.provide(FetchHttpClient.layer), + ), + testInstanceStoreLayer, ), ), Effect.runPromise, diff --git a/packages/opencode/test/control-plane/adapters.test.ts b/packages/opencode/test/control-plane/adapters.test.ts index 762bb5d57ecc..fbeb7eeb2e5b 100644 --- a/packages/opencode/test/control-plane/adapters.test.ts +++ b/packages/opencode/test/control-plane/adapters.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test" import { getAdapter, registerAdapter } from "../../src/control-plane/adapters" -import { ProjectID } from "../../src/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import type { WorkspaceInfo } from "../../src/control-plane/types" function info(projectID: WorkspaceInfo["projectID"], type: string): WorkspaceInfo { @@ -36,8 +36,8 @@ function adapter(dir: string) { describe("control-plane/adapters", () => { test("isolates custom adapters by project", async () => { const type = `demo-${Math.random().toString(36).slice(2)}` - const one = ProjectID.make(`project-${Math.random().toString(36).slice(2)}`) - const two = ProjectID.make(`project-${Math.random().toString(36).slice(2)}`) + const one = ProjectV2.ID.make(`project-${Math.random().toString(36).slice(2)}`) + const two = ProjectV2.ID.make(`project-${Math.random().toString(36).slice(2)}`) registerAdapter(one, type, adapter("/one")) registerAdapter(two, type, adapter("/two")) @@ -53,7 +53,7 @@ describe("control-plane/adapters", () => { test("latest install wins within a project", async () => { const type = `demo-${Math.random().toString(36).slice(2)}` - const id = ProjectID.make(`project-${Math.random().toString(36).slice(2)}`) + const id = ProjectV2.ID.make(`project-${Math.random().toString(36).slice(2)}`) registerAdapter(id, type, adapter("/one")) expect(await (await getAdapter(id, type)).target(info(id, type))).toEqual({ diff --git a/packages/opencode/test/control-plane/workspace.test.ts b/packages/opencode/test/control-plane/workspace.test.ts index 09810d57d77b..b8928f87a10f 100644 --- a/packages/opencode/test/control-plane/workspace.test.ts +++ b/packages/opencode/test/control-plane/workspace.test.ts @@ -10,20 +10,19 @@ import { eq } from "drizzle-orm" import { AppFileSystem } from "@opencode-ai/core/filesystem" import * as Log from "@opencode-ai/core/util/log" import { GlobalBus, type GlobalEvent } from "@/bus/global" -import { Database } from "@/storage/db" -import { ProjectID } from "@/project/schema" -import { ProjectTable } from "@/project/project.sql" +import { Database } from "@opencode-ai/core/database/database" +import { ProjectV2 } from "@opencode-ai/core/project" +import { ProjectTable } from "@opencode-ai/core/project/sql" import { Session as SessionNs } from "@/session/session" import { SessionID } from "@/session/schema" -import { SessionTable } from "@/session/session.sql" -import { SyncEvent } from "@/sync" -import { EventSequenceTable } from "@/sync/event.sql" +import { SessionTable } from "@opencode-ai/core/session/sql" +import { EventSequenceTable } from "@opencode-ai/core/event/sql" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, provideTmpdirInstance, requireInstance, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { registerAdapter } from "../../src/control-plane/adapters" -import { WorkspaceID } from "../../src/control-plane/schema" -import { WorkspaceTable } from "../../src/control-plane/workspace.sql" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" +import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" import type { Target, WorkspaceAdapter, WorkspaceInfo } from "../../src/control-plane/types" import * as Workspace from "../../src/control-plane/workspace" import { InstanceStore } from "@/project/instance-store" @@ -33,6 +32,7 @@ import { SessionPrompt } from "@/session/prompt" import { Project } from "@/project/project" import { Vcs } from "@/project/vcs" import { RuntimeFlags } from "@/effect/runtime-flags" +import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) @@ -48,10 +48,11 @@ const workspaceLayer = (experimentalWorkspaces: boolean) => Workspace.layer.pipe( Layer.provide(Auth.defaultLayer), Layer.provide(SessionNs.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(SessionPrompt.defaultLayer), Layer.provide(Project.defaultLayer), Layer.provide(Vcs.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces })), @@ -62,6 +63,7 @@ const testServerLayer = Layer.mergeAll( NodeHttpServer.layer(Http.createServer, { host: "127.0.0.1", port: 0 }), workspaceLayer(true), SessionNs.defaultLayer, + Database.defaultLayer, ) const it = testEffect(testServerLayer) @@ -105,7 +107,6 @@ function restoreEnv() { } beforeEach(() => { - Database.close() restoreEnv() process.env.OPENCODE_EXPERIMENTAL_WORKSPACES = "true" }) @@ -129,7 +130,7 @@ async function initGitRepo(dir: string) { await $`git commit -m "base"`.cwd(dir).quiet() } -const startWorkspaceSyncingWithFlag = (projectID: ProjectID, experimentalWorkspaces: boolean) => +const startWorkspaceSyncingWithFlag = (projectID: ProjectV2.ID, experimentalWorkspaces: boolean) => Effect.runPromise( Workspace.use.startWorkspaceSyncing(projectID).pipe(Effect.provide(workspaceLayer(experimentalWorkspaces))), ) @@ -265,9 +266,9 @@ function serverUrl() { }) } -function workspaceInfo(projectID: ProjectID, type: string, input?: Partial): Workspace.Info { +function workspaceInfo(projectID: ProjectV2.ID, type: string, input?: Partial): Workspace.Info { return { - id: input?.id ?? WorkspaceID.ascending(), + id: input?.id ?? WorkspaceV2.ID.ascending(), type, name: input?.name ?? unique("workspace"), branch: input?.branch ?? null, @@ -279,7 +280,7 @@ function workspaceInfo(projectID: ProjectID, type: string, input?: Partial + return Database.Service.use(({ db }) => db .insert(WorkspaceTable) .values({ @@ -292,12 +293,13 @@ function insertWorkspace(info: Workspace.Info) { project_id: info.projectID, time_used: info.timeUsed, }) - .run(), + .run() + .pipe(Effect.orDie), ) } -function insertProject(id: ProjectID, worktree: string) { - Database.use((db) => +function insertProject(id: ProjectV2.ID, worktree: string) { + return Database.Service.use(({ db }) => db .insert(ProjectTable) .values({ @@ -309,38 +311,48 @@ function insertProject(id: ProjectID, worktree: string) { time_updated: Date.now(), sandboxes: [], }) - .run(), + .run() + .pipe(Effect.orDie), ) } -function attachSessionToWorkspace(sessionID: SessionID, workspaceID: WorkspaceID) { - Database.use((db) => - db.update(SessionTable).set({ workspace_id: workspaceID }).where(eq(SessionTable.id, sessionID)).run(), +function attachSessionToWorkspace(sessionID: SessionID, workspaceID: WorkspaceV2.ID) { + return Database.Service.use(({ db }) => + db + .update(SessionTable) + .set({ workspace_id: workspaceID }) + .where(eq(SessionTable.id, sessionID)) + .run() + .pipe(Effect.orDie), ) } function sessionSequence(sessionID: SessionID) { - return Database.use((db) => + return Database.Service.use(({ db }) => db .select({ seq: EventSequenceTable.seq }) .from(EventSequenceTable) .where(eq(EventSequenceTable.aggregate_id, sessionID)) - .get(), - )?.seq + .get() + .pipe( + Effect.orDie, + Effect.map((row) => row?.seq), + ), + ) } function sessionSequenceOwner(sessionID: SessionID) { - return Database.use((db) => + return Database.Service.use(({ db }) => db .select({ ownerID: EventSequenceTable.owner_id }) .from(EventSequenceTable) .where(eq(EventSequenceTable.aggregate_id, sessionID)) - .get(), - )?.ownerID -} - -function sessionUpdatedType() { - return SyncEvent.versionedType(SessionNs.Event.Updated.type, SessionNs.Event.Updated.version) + .get() + .pipe( + Effect.orDie, + Effect.map((row) => row?.ownerID), + ), + ) } describe("workspace schemas and exports", () => { @@ -352,10 +364,10 @@ describe("workspace schemas and exports", () => { test("validates create input with workspace id, project id, branch, type, and extra", () => { const input = { - id: WorkspaceID.ascending("wrk_schema_create"), + id: WorkspaceV2.ID.ascending("wrk_schema_create"), type: "worktree", branch: "feature/schema", - projectID: ProjectID.make("project-schema"), + projectID: ProjectV2.ID.make("project-schema"), extra: { nested: true }, } @@ -372,7 +384,7 @@ describe("workspace CRUD", () => { () => Effect.gen(function* () { const workspace = yield* Workspace.Service - expect(yield* workspace.get(WorkspaceID.ascending("wrk_missing_get"))).toBeUndefined() + expect(yield* workspace.get(WorkspaceV2.ID.ascending("wrk_missing_get"))).toBeUndefined() }), { git: true }, ) @@ -383,24 +395,24 @@ describe("workspace CRUD", () => { Effect.gen(function* () { const instance = yield* requireInstance const workspace = yield* Workspace.Service - const otherProjectID = ProjectID.make("project-other") - insertProject(otherProjectID, "/tmp/other") + const otherProjectID = ProjectV2.ID.make("project-other") + yield* insertProject(otherProjectID, "/tmp/other") const a = workspaceInfo(instance.project.id, "manual", { - id: WorkspaceID.ascending("wrk_a_list"), + id: WorkspaceV2.ID.ascending("wrk_a_list"), branch: "a", directory: "/a", extra: { a: true }, }) const b = workspaceInfo(instance.project.id, "manual", { - id: WorkspaceID.ascending("wrk_b_list"), + id: WorkspaceV2.ID.ascending("wrk_b_list"), branch: "b", directory: "/b", extra: ["b"], }) - const other = workspaceInfo(otherProjectID, "manual", { id: WorkspaceID.ascending("wrk_c_list") }) - insertWorkspace(b) - insertWorkspace(other) - insertWorkspace(a) + const other = workspaceInfo(otherProjectID, "manual", { id: WorkspaceV2.ID.ascending("wrk_c_list") }) + yield* insertWorkspace(b) + yield* insertWorkspace(other) + yield* insertWorkspace(a) expect(yield* workspace.list(instance.project)).toEqual([a, b]) }), @@ -418,7 +430,7 @@ describe("workspace CRUD", () => { process.env.OTEL_EXPORTER_OTLP_ENDPOINT = "https://otel.test" process.env.OTEL_RESOURCE_ATTRIBUTES = "service.name=opencode-test" - const workspaceID = WorkspaceID.ascending("wrk_create_local") + const workspaceID = WorkspaceV2.ID.ascending("wrk_create_local") const type = unique("create-local") const targetDir = path.join(instance.directory, "created-local") const recorded = recordedAdapter({ @@ -578,11 +590,11 @@ describe("workspace CRUD", () => { const workspace = yield* Workspace.Service const type = unique("list-sync") const existing = workspaceInfo(instance.project.id, type, { - id: WorkspaceID.ascending("wrk_list_sync_existing"), + id: WorkspaceV2.ID.ascending("wrk_list_sync_existing"), name: "existing", directory: path.join(instance.directory, "existing"), }) - insertWorkspace(existing) + yield* insertWorkspace(existing) const discovered = { type, @@ -748,7 +760,7 @@ describe("workspace CRUD", () => { () => Effect.gen(function* () { const workspace = yield* Workspace.Service - expect(yield* workspace.remove(WorkspaceID.ascending("wrk_missing_remove"))).toBeUndefined() + expect(yield* workspace.remove(WorkspaceV2.ID.ascending("wrk_missing_remove"))).toBeUndefined() }), { git: true }, ) @@ -767,8 +779,8 @@ describe("workspace CRUD", () => { const info = yield* workspace.create({ type, branch: null, projectID: instance.project.id, extra: null }) const one = yield* sessionSvc.create({}) const two = yield* sessionSvc.create({}) - attachSessionToWorkspace(one.id, info.id) - attachSessionToWorkspace(two.id, info.id) + yield* attachSessionToWorkspace(one.id, info.id) + yield* attachSessionToWorkspace(two.id, info.id) const removed = yield* workspace.remove(info.id) @@ -776,10 +788,14 @@ describe("workspace CRUD", () => { expect(yield* workspace.get(info.id)).toBeUndefined() expect(recorded.calls.remove).toEqual([info]) expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBeUndefined() + const { db } = yield* Database.Service expect( - Database.use((db) => - db.select({ id: SessionTable.id }).from(SessionTable).where(eq(SessionTable.workspace_id, info.id)).all(), - ), + yield* db + .select({ id: SessionTable.id }) + .from(SessionTable) + .where(eq(SessionTable.workspace_id, info.id)) + .all() + .pipe(Effect.orDie), ).toEqual([]) }) }, @@ -793,7 +809,7 @@ describe("workspace CRUD", () => { const instance = yield* requireInstance const workspace = yield* Workspace.Service const type = unique("remove-throws") - const info = workspaceInfo(instance.project.id, type, { id: WorkspaceID.ascending("wrk_remove_throws") }) + const info = workspaceInfo(instance.project.id, type, { id: WorkspaceV2.ID.ascending("wrk_remove_throws") }) registerAdapter( instance.project.id, type, @@ -806,7 +822,7 @@ describe("workspace CRUD", () => { }, }).adapter, ) - insertWorkspace(info) + yield* insertWorkspace(info) expect(yield* workspace.remove(info.id)).toEqual(info) expect(yield* workspace.get(info.id)).toBeUndefined() @@ -826,25 +842,25 @@ describe("workspace CRUD", () => { const targetType = unique("warp-target-local") const previous = workspaceInfo(instance.project.id, previousType) const target = workspaceInfo(instance.project.id, targetType) - insertWorkspace(previous) - insertWorkspace(target) + yield* insertWorkspace(previous) + yield* insertWorkspace(target) registerAdapter(instance.project.id, previousType, localAdapter(path.join(dir, "warp-prev-local")).adapter) registerAdapter(instance.project.id, targetType, localAdapter(path.join(dir, "warp-target-local")).adapter) const session = yield* sessionSvc.create({}) - attachSessionToWorkspace(session.id, previous.id) + yield* attachSessionToWorkspace(session.id, previous.id) yield* workspace.sessionWarp({ workspaceID: target.id, sessionID: session.id }) + const { db } = yield* Database.Service expect( - Database.use((db) => - db - .select({ workspaceID: SessionTable.workspace_id }) - .from(SessionTable) - .where(eq(SessionTable.id, session.id)) - .get(), - )?.workspaceID, + (yield* db + .select({ workspaceID: SessionTable.workspace_id }) + .from(SessionTable) + .where(eq(SessionTable.id, session.id)) + .get() + .pipe(Effect.orDie))?.workspaceID, ).toBe(target.id) - expect(sessionSequenceOwner(session.id)).toBe(target.id) + expect(yield* sessionSequenceOwner(session.id)).toBe(target.id) }) }, { git: true }, @@ -869,12 +885,12 @@ describe("workspace CRUD", () => { const previous = workspaceInfo(instance.project.id, previousType) const target = workspaceInfo(instance.project.id, targetType) - insertWorkspace(previous) - insertWorkspace(target) + yield* insertWorkspace(previous) + yield* insertWorkspace(target) registerAdapter(instance.project.id, previousType, localAdapter(previousDir, { createDir: false }).adapter) registerAdapter(instance.project.id, targetType, localAdapter(targetDir, { createDir: false }).adapter) const session = yield* sessionSvc.create({}) - attachSessionToWorkspace(session.id, previous.id) + yield* attachSessionToWorkspace(session.id, previous.id) yield* workspace.sessionWarp({ workspaceID: target.id, sessionID: session.id, copyChanges: true }) @@ -895,23 +911,23 @@ describe("workspace CRUD", () => { const sessionSvc = yield* SessionNs.Service const previousType = unique("warp-detach-local") const previous = workspaceInfo(instance.project.id, previousType) - insertWorkspace(previous) + yield* insertWorkspace(previous) registerAdapter(instance.project.id, previousType, localAdapter(path.join(dir, "warp-detach-local")).adapter) const session = yield* sessionSvc.create({}) - attachSessionToWorkspace(session.id, previous.id) + yield* attachSessionToWorkspace(session.id, previous.id) yield* workspace.sessionWarp({ workspaceID: null, sessionID: session.id }) + const { db } = yield* Database.Service expect( - Database.use((db) => - db - .select({ workspaceID: SessionTable.workspace_id }) - .from(SessionTable) - .where(eq(SessionTable.id, session.id)) - .get(), - )?.workspaceID, + (yield* db + .select({ workspaceID: SessionTable.workspace_id }) + .from(SessionTable) + .where(eq(SessionTable.id, session.id)) + .get() + .pipe(Effect.orDie))?.workspaceID, ).toBeNull() - expect(sessionSequenceOwner(session.id)).toBe(instance.project.id) + expect(yield* sessionSequenceOwner(session.id)).toBe(instance.project.id) }) }, { git: true }, @@ -928,9 +944,9 @@ describe("workspace CRUD", () => { const sessionSvc = yield* SessionNs.Service const previousType = unique("warp-detach-workspace-instance") const previous = workspaceInfo(projectID, previousType) - insertWorkspace(previous) + yield* insertWorkspace(previous) const session = yield* sessionSvc.create({}) - attachSessionToWorkspace(session.id, previous.id) + yield* attachSessionToWorkspace(session.id, previous.id) const workspaceProjectID = yield* provideTmpdirInstance( (workspaceDir) => @@ -944,17 +960,17 @@ describe("workspace CRUD", () => { { git: true }, ) + const { db } = yield* Database.Service expect( - Database.use((db) => - db - .select({ workspaceID: SessionTable.workspace_id }) - .from(SessionTable) - .where(eq(SessionTable.id, session.id)) - .get(), - )?.workspaceID, + (yield* db + .select({ workspaceID: SessionTable.workspace_id }) + .from(SessionTable) + .where(eq(SessionTable.id, session.id)) + .get() + .pipe(Effect.orDie))?.workspaceID, ).toBeNull() - expect(sessionSequenceOwner(session.id)).toBe(projectID) - expect(sessionSequenceOwner(session.id)).not.toBe(workspaceProjectID) + expect(yield* sessionSequenceOwner(session.id)).toBe(projectID) + expect(yield* sessionSequenceOwner(session.id)).not.toBe(workspaceProjectID) }), { git: true }, ) @@ -962,6 +978,7 @@ describe("workspace CRUD", () => { it.live("sessionWarp syncs previous remote history, replays it, steals, and claims the sequence", () => { const calls: FetchCall[] = [] let historySessionID: SessionID | undefined + let historySession: SessionNs.Info | undefined let historyNextSeq = 0 return Effect.gen(function* () { yield* HttpServer.serveEffect()( @@ -982,8 +999,8 @@ describe("workspace CRUD", () => { id: `evt_${unique("warp-source-history")}`, aggregate_id: historySessionID!, seq: historyNextSeq, - type: sessionUpdatedType(), - data: { sessionID: historySessionID!, info: { title: "from source history" } }, + type: "session.updated.1", + data: { sessionID: historySessionID!, info: historySession! }, }, ]) } @@ -1007,14 +1024,15 @@ describe("workspace CRUD", () => { const targetType = unique("warp-remote-target") const previous = workspaceInfo(instance.project.id, previousType) const target = workspaceInfo(instance.project.id, targetType, { directory: "remote-target-dir" }) - insertWorkspace(previous) - insertWorkspace(target) + yield* insertWorkspace(previous) + yield* insertWorkspace(target) registerAdapter(instance.project.id, previousType, remoteAdapter(`${url}/warp-source`).adapter) registerAdapter(instance.project.id, targetType, remoteAdapter(`${url}/warp-target`).adapter) const session = yield* sessionSvc.create({}) - attachSessionToWorkspace(session.id, previous.id) + yield* attachSessionToWorkspace(session.id, previous.id) historySessionID = session.id - historyNextSeq = (sessionSequence(session.id) ?? -1) + 1 + historySession = { ...session, workspaceID: previous.id, title: "from source history" } + historyNextSeq = ((yield* sessionSequence(session.id)) ?? -1) + 1 yield* workspace.sessionWarp({ workspaceID: target.id, sessionID: session.id, copyChanges: true }) @@ -1033,18 +1051,18 @@ describe("workspace CRUD", () => { { aggregateID: session.id, seq: 0, - type: SyncEvent.versionedType(SessionNs.Event.Created.type, SessionNs.Event.Created.version), + type: "session.created.1", }, { aggregateID: session.id, seq: historyNextSeq, - type: sessionUpdatedType(), + type: "session.updated.1", }, ], }) expect(calls[4].json).toEqual({ sessionID: session.id }) expect((yield* sessionSvc.get(session.id)).title).toBe("from source history") - expect(sessionSequenceOwner(session.id)).toBe(target.id) + expect(yield* sessionSequenceOwner(session.id)).toBe(target.id) }), { git: true }, ) @@ -1064,8 +1082,8 @@ describe("workspace sync state", () => { const type = unique("flag-disabled") const info = workspaceInfo(instance.project.id, type) const session = yield* sessionSvc.create({}) - attachSessionToWorkspace(session.id, info.id) - insertWorkspace(info) + yield* attachSessionToWorkspace(session.id, info.id) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, localAdapter(path.join(dir, "flag-disabled")).adapter) yield* Effect.promise(() => startWorkspaceSyncingWithFlag(instance.project.id, false)) @@ -1090,12 +1108,10 @@ describe("workspace sync state", () => { const second = workspaceInfo(projectID, secondType) yield* Effect.promise(() => fs.mkdir(path.join(dir, "first"), { recursive: true })) yield* Effect.promise(() => fs.mkdir(path.join(dir, "second"), { recursive: true })) - yield* Effect.sync(() => { - insertWorkspace(first) - insertWorkspace(second) - registerAdapter(projectID, firstType, localAdapter(path.join(dir, "first")).adapter) - registerAdapter(projectID, secondType, localAdapter(path.join(dir, "second")).adapter) - }) + yield* insertWorkspace(first) + yield* insertWorkspace(second) + registerAdapter(projectID, firstType, localAdapter(path.join(dir, "first")).adapter) + registerAdapter(projectID, secondType, localAdapter(path.join(dir, "second")).adapter) yield* Effect.addFinalizer(() => Effect.all([workspace.remove(first.id), workspace.remove(second.id)], { discard: true }).pipe(Effect.ignore), ) @@ -1123,13 +1139,13 @@ describe("workspace sync state", () => { const sessionSvc = yield* SessionNs.Service const type = unique("missing-local") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter( instance.project.id, type, localAdapter(path.join(dir, "missing-target"), { createDir: false }).adapter, ) - attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1159,9 +1175,9 @@ describe("workspace sync state", () => { const info = workspaceInfo(instance.project.id, type) const target = path.join(dir, "dedupe-local") yield* Effect.promise(() => fs.mkdir(target, { recursive: true })) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, localAdapter(target).adapter) - attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) yield* workspace.startWorkspaceSyncing(instance.project.id) yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1213,9 +1229,9 @@ describe("workspace sync state", () => { try { const type = unique("remote-start") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, remoteAdapter(`${url}/sync`).adapter) - attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) yield* workspace.startWorkspaceSyncing(instance.project.id) yield* eventuallyEffect( @@ -1267,9 +1283,9 @@ describe("workspace sync state", () => { const instance = yield* requireInstance const type = unique("remote-connect-fail") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, remoteAdapter(`${url}/failed`).adapter) - attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1308,9 +1324,9 @@ describe("workspace sync state", () => { const instance = yield* requireInstance const type = unique("remote-history-fail") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, remoteAdapter(`${url}/history-failed`).adapter) - attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1330,6 +1346,7 @@ describe("workspace sync state", () => { it.live("sync history sends the local sequence fence and replays returned events in workspace context", () => { const historyBodies: unknown[] = [] let historySessionID: SessionID | undefined + let historySession: SessionNs.Info | undefined let historyNextSeq = 0 return Effect.gen(function* () { yield* HttpServer.serveEffect()( @@ -1346,8 +1363,8 @@ describe("workspace sync state", () => { id: `evt_${unique("history")}`, aggregate_id: historySessionID!, seq: historyNextSeq, - type: sessionUpdatedType(), - data: { sessionID: historySessionID!, info: { title: "from history" } }, + type: "session.updated.1", + data: { sessionID: historySessionID!, info: historySession! }, }, ]), ) @@ -1366,12 +1383,13 @@ describe("workspace sync state", () => { try { const type = unique("history-replay") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, remoteAdapter(`${url}/history`).adapter) const session = yield* sessionSvc.create({ title: "before history" }) - attachSessionToWorkspace(session.id, info.id) + yield* attachSessionToWorkspace(session.id, info.id) historySessionID = session.id - historyNextSeq = (sessionSequence(session.id) ?? -1) + 1 + historySession = { ...session, workspaceID: info.id, title: "from history" } + historyNextSeq = ((yield* sessionSequence(session.id)) ?? -1) + 1 yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1385,8 +1403,9 @@ describe("workspace sync state", () => { captured.events.some( (event) => event.workspace === info.id && - event.payload.type === "sync" && - event.payload.syncEvent.seq === historyNextSeq, + event.payload.type === "session.updated" && + event.payload.properties.sessionID === session.id && + event.payload.properties.info.title === "from history", ), ).toBe(true) yield* workspace.remove(info.id) @@ -1434,9 +1453,9 @@ describe("workspace sync state", () => { try { const type = unique("sse-forward") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, remoteAdapter(`${url}/sse-forward`).adapter) - attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1473,6 +1492,7 @@ describe("workspace sync state", () => { it.live("SSE sync events are replayed and forwarded", () => { let sseSessionID: SessionID | undefined + let sseSession: SessionNs.Info | undefined let sseNextSeq = 0 return Effect.gen(function* () { yield* HttpServer.serveEffect()( @@ -1492,8 +1512,8 @@ describe("workspace sync state", () => { id: `evt_${unique("sse")}`, aggregateID: sseSessionID!, seq: sseNextSeq, - type: sessionUpdatedType(), - data: { sessionID: sseSessionID!, info: { title: "from sse" } }, + type: "session.updated.1", + data: { sessionID: sseSessionID!, info: sseSession! }, }, }, }, @@ -1516,12 +1536,13 @@ describe("workspace sync state", () => { try { const type = unique("sse-sync") const info = workspaceInfo(instance.project.id, type) - insertWorkspace(info) + yield* insertWorkspace(info) registerAdapter(instance.project.id, type, remoteAdapter(`${url}/sse-sync`).adapter) const session = yield* sessionSvc.create({ title: "before sse" }) - attachSessionToWorkspace(session.id, info.id) + yield* attachSessionToWorkspace(session.id, info.id) sseSessionID = session.id - sseNextSeq = (sessionSequence(session.id) ?? -1) + 1 + sseSession = { ...session, workspaceID: info.id, title: "from sse" } + sseNextSeq = ((yield* sessionSequence(session.id)) ?? -1) + 1 yield* workspace.startWorkspaceSyncing(instance.project.id) @@ -1555,7 +1576,7 @@ describe("workspace waitForSync", () => { () => Effect.gen(function* () { const workspace = yield* Workspace.Service - expect(yield* workspace.waitForSync(WorkspaceID.ascending("wrk_wait_empty"), {})).toBeUndefined() + expect(yield* workspace.waitForSync(WorkspaceV2.ID.ascending("wrk_wait_empty"), {})).toBeUndefined() }), { git: true }, ) @@ -1566,11 +1587,14 @@ describe("workspace waitForSync", () => { Effect.gen(function* () { const workspace = yield* Workspace.Service const sessionID = SessionID.descending("ses_wait_done") - Database.use((db) => db.insert(EventSequenceTable).values({ aggregate_id: sessionID, seq: 4 }).run()) + const { db } = yield* Database.Service + yield* db.insert(EventSequenceTable).values({ aggregate_id: sessionID, seq: 4 }).run().pipe(Effect.orDie) - expect(yield* workspace.waitForSync(WorkspaceID.ascending("wrk_wait_done"), { [sessionID]: 4 })).toBeUndefined() expect( - yield* workspace.waitForSync(WorkspaceID.ascending("wrk_wait_done_2"), { [sessionID]: 3 }), + yield* workspace.waitForSync(WorkspaceV2.ID.ascending("wrk_wait_done"), { [sessionID]: 4 }), + ).toBeUndefined() + expect( + yield* workspace.waitForSync(WorkspaceV2.ID.ascending("wrk_wait_done_2"), { [sessionID]: 3 }), ).toBeUndefined() }), { git: true }, @@ -1581,22 +1605,22 @@ describe("workspace waitForSync", () => { () => Effect.gen(function* () { const workspace = yield* Workspace.Service - const workspaceID = WorkspaceID.ascending("wrk_wait_event") + const workspaceID = WorkspaceV2.ID.ascending("wrk_wait_event") const sessionID = SessionID.descending("ses_wait_event") - Database.use((db) => db.insert(EventSequenceTable).values({ aggregate_id: sessionID, seq: 1 }).run()) + const { db } = yield* Database.Service + yield* db.insert(EventSequenceTable).values({ aggregate_id: sessionID, seq: 1 }).run().pipe(Effect.orDie) yield* Effect.all( [ workspace.waitForSync(workspaceID, { [sessionID]: 2 }), Effect.gen(function* () { yield* Effect.sleep("10 millis") - Database.use((db) => - db - .update(EventSequenceTable) - .set({ seq: 2 }) - .where(eq(EventSequenceTable.aggregate_id, sessionID)) - .run(), - ) + yield* db + .update(EventSequenceTable) + .set({ seq: 2 }) + .where(eq(EventSequenceTable.aggregate_id, sessionID)) + .run() + .pipe(Effect.orDie) GlobalBus.emit("event", { workspace: workspaceID, payload: { type: "anything" } }) }), ], @@ -1611,24 +1635,24 @@ describe("workspace waitForSync", () => { () => Effect.gen(function* () { const workspace = yield* Workspace.Service - const workspaceID = WorkspaceID.ascending("wrk_wait_sync_any") + const workspaceID = WorkspaceV2.ID.ascending("wrk_wait_sync_any") const sessionID = SessionID.descending("ses_wait_sync_any") - Database.use((db) => db.insert(EventSequenceTable).values({ aggregate_id: sessionID, seq: 0 }).run()) + const { db } = yield* Database.Service + yield* db.insert(EventSequenceTable).values({ aggregate_id: sessionID, seq: 0 }).run().pipe(Effect.orDie) yield* Effect.all( [ workspace.waitForSync(workspaceID, { [sessionID]: 1 }), Effect.gen(function* () { yield* Effect.sleep("10 millis") - Database.use((db) => - db - .update(EventSequenceTable) - .set({ seq: 1 }) - .where(eq(EventSequenceTable.aggregate_id, sessionID)) - .run(), - ) + yield* db + .update(EventSequenceTable) + .set({ seq: 1 }) + .where(eq(EventSequenceTable.aggregate_id, sessionID)) + .run() + .pipe(Effect.orDie) GlobalBus.emit("event", { - workspace: WorkspaceID.ascending("wrk_other_workspace"), + workspace: WorkspaceV2.ID.ascending("wrk_other_workspace"), payload: { type: "sync" }, }) }), @@ -1648,7 +1672,7 @@ describe("workspace waitForSync", () => { const reason = new Error("caller aborted") const fiber = yield* Effect.forkChild( workspace.waitForSync( - WorkspaceID.ascending("wrk_wait_abort"), + WorkspaceV2.ID.ascending("wrk_wait_abort"), { [SessionID.descending("ses_wait_abort")]: 1 }, abort.signal, ), @@ -1668,7 +1692,7 @@ describe("workspace waitForSync", () => { const sessionID = SessionID.descending("ses_wait_timeout") expectExitContains( yield* Effect.exit( - workspace.waitForSync(WorkspaceID.ascending("wrk_wait_timeout"), { [sessionID]: 1 }, undefined, 25), + workspace.waitForSync(WorkspaceV2.ID.ascending("wrk_wait_timeout"), { [sessionID]: 1 }, undefined, 25), ), `Timed out waiting for sync fence: {"${sessionID}":1}`, ) diff --git a/packages/opencode/test/effect/run-service.test.ts b/packages/opencode/test/effect/run-service.test.ts index 16538bb8aec2..08c8fef43651 100644 --- a/packages/opencode/test/effect/run-service.test.ts +++ b/packages/opencode/test/effect/run-service.test.ts @@ -2,7 +2,7 @@ import { expect } from "bun:test" import { Effect, Layer, Context } from "effect" import { InstanceRef } from "../../src/effect/instance-ref" import { makeRuntime } from "../../src/effect/run-service" -import { ProjectID } from "../../src/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { it } from "../lib/effect" class Shared extends Context.Service()("@test/Shared") {} @@ -79,7 +79,7 @@ it.live("makeRuntime inherits InstanceRef from the current fiber", () => directory: testDirectory, worktree: testDirectory, project: { - id: ProjectID.global, + id: ProjectV2.ID.global, worktree: testDirectory, time: { created: 0, updated: 0 }, sandboxes: [], diff --git a/packages/opencode/test/effect/runtime-flags.test.ts b/packages/opencode/test/effect/runtime-flags.test.ts index 0c913979f875..8227cb50a98b 100644 --- a/packages/opencode/test/effect/runtime-flags.test.ts +++ b/packages/opencode/test/effect/runtime-flags.test.ts @@ -24,12 +24,10 @@ describe("RuntimeFlags", () => { fromConfig({ OPENCODE_PURE: "true", OPENCODE_DISABLE_DEFAULT_PLUGINS: "true", - OPENCODE_DISABLE_CHANNEL_DB: "true", OPENCODE_AUTO_SHARE: "true", OPENCODE_DISABLE_EMBEDDED_WEB_UI: "true", OPENCODE_DISABLE_EXTERNAL_SKILLS: "true", OPENCODE_DISABLE_LSP_DOWNLOAD: "true", - OPENCODE_SKIP_MIGRATIONS: "true", OPENCODE_EXPERIMENTAL: "true", OPENCODE_ENABLE_EXA: "true", OPENCODE_ENABLE_PARALLEL: "true", @@ -43,11 +41,9 @@ describe("RuntimeFlags", () => { expect(flags.pure).toBe(true) expect(flags.autoShare).toBe(true) expect(flags.disableDefaultPlugins).toBe(true) - expect(flags.disableChannelDb).toBe(true) expect(flags.disableEmbeddedWebUi).toBe(true) expect(flags.disableExternalSkills).toBe(true) expect(flags.disableLspDownload).toBe(true) - expect(flags.skipMigrations).toBe(true) expect(flags.disableClaudeCodePrompt).toBe(false) expect(flags.enableExa).toBe(true) expect(flags.enableParallel).toBe(true) @@ -63,6 +59,7 @@ describe("RuntimeFlags", () => { expect(flags.experimentalWorkspaces).toBe(true) expect(flags.experimentalIconDiscovery).toBe(true) expect(flags.experimentalNativeLlm).toBe(false) + expect(flags.experimentalWebSockets).toBe(false) expect(flags.client).toBe("desktop") }), ) @@ -91,6 +88,16 @@ describe("RuntimeFlags", () => { }), ) + it.effect("enables WebSockets via dedicated flag only", () => + Effect.gen(function* () { + const explicit = yield* readFlags.pipe(Effect.provide(fromConfig({ OPENCODE_EXPERIMENTAL_WEBSOCKETS: "true" }))) + const umbrella = yield* readFlags.pipe(Effect.provide(fromConfig({ OPENCODE_EXPERIMENTAL: "true" }))) + + expect(explicit.experimentalWebSockets).toBe(true) + expect(umbrella.experimentalWebSockets).toBe(false) + }), + ) + it.effect("layer accepts partial test overrides and fills defaults from Config definitions", () => Effect.gen(function* () { const flags = yield* readFlags.pipe( @@ -100,11 +107,9 @@ describe("RuntimeFlags", () => { expect(flags.pure).toBe(false) expect(flags.autoShare).toBe(false) expect(flags.disableDefaultPlugins).toBe(true) - expect(flags.disableChannelDb).toBe(false) expect(flags.disableEmbeddedWebUi).toBe(false) expect(flags.disableExternalSkills).toBe(false) expect(flags.disableLspDownload).toBe(false) - expect(flags.skipMigrations).toBe(false) expect(flags.disableClaudeCodePrompt).toBe(false) expect(flags.disableClaudeCodeSkills).toBe(false) expect(flags.enableExa).toBe(false) @@ -157,22 +162,6 @@ describe("RuntimeFlags", () => { }), ) - it.effect("skipMigrations defaults to false", () => - Effect.gen(function* () { - const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) - - expect(flags.skipMigrations).toBe(false) - }), - ) - - it.effect("skipMigrations reads OPENCODE_SKIP_MIGRATIONS", () => - Effect.gen(function* () { - const flags = yield* readFlags.pipe(Effect.provide(fromConfig({ OPENCODE_SKIP_MIGRATIONS: "true" }))) - - expect(flags.skipMigrations).toBe(true) - }), - ) - it.effect("disableClaudeCodePrompt defaults to false", () => Effect.gen(function* () { const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) @@ -213,6 +202,21 @@ describe("RuntimeFlags", () => { }), ) + it.effect("specific experimental flags override OPENCODE_EXPERIMENTAL", () => + Effect.gen(function* () { + const flags = yield* readFlags.pipe( + Effect.provide( + fromConfig({ + OPENCODE_EXPERIMENTAL: "true", + OPENCODE_EXPERIMENTAL_ICON_DISCOVERY: "false", + }), + ), + ) + + expect(flags.experimentalIconDiscovery).toBe(false) + }), + ) + it.effect("experimentalOxfmt defaults to false", () => Effect.gen(function* () { const flags = yield* readFlags.pipe(Effect.provide(fromConfig({}))) @@ -318,7 +322,6 @@ describe("RuntimeFlags", () => { OPENCODE_DISABLE_DEFAULT_PLUGINS: "true", OPENCODE_DISABLE_EXTERNAL_SKILLS: "true", OPENCODE_DISABLE_LSP_DOWNLOAD: "true", - OPENCODE_SKIP_MIGRATIONS: "true", OPENCODE_EXPERIMENTAL: "true", OPENCODE_ENABLE_EXA: "true", OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS: "1234", @@ -330,11 +333,9 @@ describe("RuntimeFlags", () => { expect(flags.pure).toBe(false) expect(flags.disableDefaultPlugins).toBe(false) - expect(flags.disableChannelDb).toBe(false) expect(flags.disableEmbeddedWebUi).toBe(false) expect(flags.disableExternalSkills).toBe(false) expect(flags.disableLspDownload).toBe(false) - expect(flags.skipMigrations).toBe(false) expect(flags.disableClaudeCodePrompt).toBe(false) expect(flags.disableClaudeCodeSkills).toBe(false) expect(flags.enableExa).toBe(false) diff --git a/packages/opencode/test/fake/provider.ts b/packages/opencode/test/fake/provider.ts index 5f8f7a3302a1..e90bde29e2a0 100644 --- a/packages/opencode/test/fake/provider.ts +++ b/packages/opencode/test/fake/provider.ts @@ -1,11 +1,11 @@ import { Effect, Layer } from "effect" import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "../../src/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" export namespace ProviderTest { export function model(override: Partial = {}): Provider.Model { - const id = override.id ?? ModelID.make("gpt-5.2") - const providerID = override.providerID ?? ProviderID.make("openai") + const id = override.id ?? ProviderV2.ModelID.make("gpt-5.2") + const providerID = override.providerID ?? ProviderV2.ID.make("openai") return { id, providerID, diff --git a/packages/opencode/test/file/watcher.test.ts b/packages/opencode/test/file/watcher.test.ts index c205da4862d5..3137f6c7d64a 100644 --- a/packages/opencode/test/file/watcher.test.ts +++ b/packages/opencode/test/file/watcher.test.ts @@ -9,6 +9,7 @@ import { GlobalBus, type GlobalEvent } from "../../src/bus/global" import { Config } from "@/config/config" import { FileWatcher } from "../../src/file/watcher" import { Git } from "../../src/git" +import { EventV2Bridge } from "../../src/event-v2-bridge" // Native @parcel/watcher bindings aren't reliably available in CI (missing on Linux, flaky on Windows) const describeWatcher = FileWatcher.hasNativeBinding() && !process.env.CI ? describe : describe.skip @@ -27,6 +28,7 @@ const watcherConfigLayer = ConfigProvider.layer( const watcherLayer = FileWatcher.layer.pipe( Layer.provide(Config.defaultLayer), Layer.provide(Git.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(watcherConfigLayer), ) diff --git a/packages/opencode/test/fixture/db.ts b/packages/opencode/test/fixture/db.ts index db4a5df20c4d..88f1097f2d89 100644 --- a/packages/opencode/test/fixture/db.ts +++ b/packages/opencode/test/fixture/db.ts @@ -1,11 +1,10 @@ import { rm } from "fs/promises" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { disposeAllInstances } from "./fixture" export async function resetDatabase() { await disposeAllInstances().catch(() => undefined) - Database.close() - const dbPath = Database.getPath() + const dbPath = Database.path() await rm(dbPath, { force: true }).catch(() => undefined) await rm(`${dbPath}-wal`, { force: true }).catch(() => undefined) await rm(`${dbPath}-shm`, { force: true }).catch(() => undefined) diff --git a/packages/opencode/test/fixture/fixture.ts b/packages/opencode/test/fixture/fixture.ts index 0b26359ad71b..41a0953122c6 100644 --- a/packages/opencode/test/fixture/fixture.ts +++ b/packages/opencode/test/fixture/fixture.ts @@ -1,9 +1,8 @@ import { $ } from "bun" -import * as Observability from "@opencode-ai/core/effect/observability" import * as fs from "fs/promises" import os from "os" import path from "path" -import { Effect, Context, Layer, ManagedRuntime } from "effect" +import { Effect, Context, Layer } from "effect" import type * as PlatformError from "effect/PlatformError" import type * as Scope from "effect/Scope" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" @@ -18,35 +17,31 @@ import { TestLLMServer } from "../lib/llm-server" const noopBootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void })) export const testInstanceStoreLayer = InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap)) -const testInstanceRuntime = ManagedRuntime.make(testInstanceStoreLayer.pipe(Layer.provideMerge(Observability.layer))) - -const runTestInstanceStore = (fn: (store: InstanceStore.Interface) => Effect.Effect) => - testInstanceRuntime.runPromise(InstanceStore.Service.use(fn)) export async function provideTestInstance(input: { directory: string init?: Effect.Effect fn: (ctx: InstanceContext) => R }) { - const ctx = await runTestInstanceStore((store) => store.load({ directory: input.directory })) + const ctx = await InstanceRuntime.load({ directory: input.directory }) try { - if (input.init) await testInstanceRuntime.runPromise(input.init.pipe(Effect.provideService(InstanceRef, ctx))) + if (input.init) await Effect.runPromise(input.init.pipe(Effect.provideService(InstanceRef, ctx))) return await input.fn(ctx) } finally { - await runTestInstanceStore((store) => store.dispose(ctx)) + await InstanceRuntime.disposeInstance(ctx) } } export async function withTestInstance(input: { directory: string; fn: (ctx: InstanceContext) => R }) { - return input.fn(await runTestInstanceStore((store) => store.load({ directory: input.directory }))) + return input.fn(await InstanceRuntime.load({ directory: input.directory })) } export async function reloadTestInstance(input: { directory: string }) { - return runTestInstanceStore((store) => store.reload(input)) + return InstanceRuntime.reloadInstance(input) } export async function disposeAllInstances() { - await Promise.all([InstanceRuntime.disposeAllInstances(), runTestInstanceStore((store) => store.disposeAll())]) + await InstanceRuntime.disposeAllInstances() } // Strip null bytes from paths (defensive fix for CI environment issues) @@ -119,9 +114,10 @@ export async function tmpdir(options?: TmpDirOptions) { } /** Effectful scoped tmpdir. Cleaned up when the scope closes. Make sure these stay in sync */ -export function tmpdirScoped(options?: { +export function tmpdirScoped(options?: { git?: boolean config?: Partial | (() => Partial) + init?: (directory: string) => Effect.Effect }) { return Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner @@ -158,19 +154,16 @@ export function tmpdirScoped(options?: { ) } + if (options?.init) yield* options.init(dir) + return dir }) } export const provideInstance = (directory: string) => - (self: Effect.Effect): Effect.Effect => - Effect.contextWith((services: Context.Context) => - Effect.promise(async () => { - const ctx = await runTestInstanceStore((store) => store.load({ directory })) - return Effect.runPromiseWith(services)(self.pipe(Effect.provideService(InstanceRef, ctx))) - }), - ) + (self: Effect.Effect): Effect.Effect => + InstanceStore.Service.use((store) => store.provide({ directory }, self)) export const provideInstanceEffect = (directory: string) => @@ -188,21 +181,8 @@ export function provideTmpdirInstance( ) { return Effect.gen(function* () { const path = yield* tmpdirScoped(options) - let provided = false - - yield* Effect.addFinalizer(() => - provided - ? Effect.promise(() => - runTestInstanceStore((store) => - store.load({ directory: path }).pipe(Effect.flatMap((ctx) => store.dispose(ctx))), - ), - ).pipe(Effect.ignore) - : Effect.void, - ) - - provided = true return yield* self(path).pipe(provideInstance(path)) - }) + }).pipe(Effect.provide(testInstanceStoreLayer)) } export class TestInstance extends Context.Service()("@test/Instance") {} @@ -214,7 +194,11 @@ export const requireInstance = Effect.gen(function* () { }) export const withTmpdirInstance = - (options?: { git?: boolean; config?: Partial | (() => Partial) }) => + (options?: { + git?: boolean + config?: Partial | (() => Partial) + init?: (directory: string) => Effect.Effect + }) => (self: Effect.Effect) => Effect.gen(function* () { const directory = yield* tmpdirScoped(options) diff --git a/packages/opencode/test/fixture/flag.ts b/packages/opencode/test/fixture/flag.ts index 224c5ef1f4aa..cf00d9e7b23b 100644 --- a/packages/opencode/test/fixture/flag.ts +++ b/packages/opencode/test/fixture/flag.ts @@ -1,4 +1,4 @@ -import type { WorkspaceID } from "@/control-plane/schema" +import type { WorkspaceV2 } from "@opencode-ai/core/workspace" import { Flag } from "@opencode-ai/core/flag/flag" import { Effect, Scope } from "effect" @@ -7,7 +7,7 @@ import { Effect, Scope } from "effect" * on entry and restores it via finalizer when the surrounding scope closes — * preserves the original try/finally semantics regardless of test outcome. */ -export function withFixedWorkspaceID(id: WorkspaceID): Effect.Effect { +export function withFixedWorkspaceID(id: WorkspaceV2.ID): Effect.Effect { return Effect.gen(function* () { const previous = Flag.OPENCODE_WORKSPACE_ID Flag.OPENCODE_WORKSPACE_ID = id diff --git a/packages/opencode/test/fixture/tui-sdk.ts b/packages/opencode/test/fixture/tui-sdk.ts new file mode 100644 index 000000000000..cf59222a1512 --- /dev/null +++ b/packages/opencode/test/fixture/tui-sdk.ts @@ -0,0 +1,82 @@ +import type { GlobalEvent } from "@opencode-ai/sdk/v2" +import type { EventSource } from "../../src/cli/cmd/tui/context/sdk" + +export const worktree = "/tmp/opencode" +export const directory = `${worktree}/packages/opencode` + +export function json(data: unknown, init?: ResponseInit) { + return new Response(JSON.stringify(data), { + ...init, + headers: { "content-type": "application/json", ...(init?.headers ?? {}) }, + }) +} + +export function eventSource(): EventSource { + return { subscribe: async () => () => {} } +} + +export function createEventSource() { + let fn: ((event: GlobalEvent) => void) | undefined + + return { + source: { + subscribe: async (handler: (event: GlobalEvent) => void) => { + fn = handler + return () => { + if (fn === handler) fn = undefined + } + }, + } satisfies EventSource, + emit(event: GlobalEvent) { + if (!fn) throw new Error("event source not ready") + fn(event) + }, + } +} + +export type FetchHandler = (url: URL) => Response | Promise | undefined + +export function createFetch(override?: FetchHandler) { + const session = [] as URL[] + const fetch = (async (input: RequestInfo | URL) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (url.pathname === "/session") session.push(url) + + const overridden = await override?.(url) + if (overridden) return overridden + + switch (url.pathname) { + case "/agent": + case "/command": + case "/experimental/workspace": + case "/experimental/workspace/status": + case "/formatter": + case "/lsp": + return json([]) + case "/config": + case "/experimental/resource": + case "/mcp": + case "/provider/auth": + case "/session/status": + return json({}) + case "/config/providers": + return json({ providers: {}, default: {} }) + case "/experimental/console": + return json({ consoleManagedProviders: [], switchableOrgCount: 0 }) + case "/path": + return json({ home: "", state: "", config: "", worktree, directory }) + case "/project/current": + return json({ id: "proj_test" }) + case "/provider": + return json({ all: [], default: {}, connected: [] }) + case "/session": + return json([]) + case "/vcs": + return json({ branch: "main" }) + } + + throw new Error(`unexpected request: ${url.pathname}`) + }) as typeof globalThis.fetch + + return { fetch, session } +} diff --git a/packages/opencode/test/fixture/workspace.ts b/packages/opencode/test/fixture/workspace.ts index 9c201d39824f..b3dceddf8db3 100644 --- a/packages/opencode/test/fixture/workspace.ts +++ b/packages/opencode/test/fixture/workspace.ts @@ -1,5 +1,6 @@ import { FetchHttpClient } from "effect/unstable/http" import { Layer } from "effect" +import { Database } from "@opencode-ai/core/database/database" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Auth } from "../../src/auth" import { Workspace } from "../../src/control-plane/workspace" @@ -10,16 +11,17 @@ import { Project } from "../../src/project/project" import { Vcs } from "../../src/project/vcs" import { Session } from "../../src/session/session" import { SessionPrompt } from "../../src/session/prompt" -import { SyncEvent } from "../../src/sync" +import { EventV2Bridge } from "../../src/event-v2-bridge" export const workspaceLayerWithRuntimeFlags = (overrides: Partial) => Workspace.layer.pipe( Layer.provide(Auth.defaultLayer), Layer.provide(Session.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(SessionPrompt.defaultLayer), Layer.provide(Project.defaultLayer), Layer.provide(Vcs.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(RuntimeFlags.layer(overrides)), diff --git a/packages/opencode/test/format/format.test.ts b/packages/opencode/test/format/format.test.ts index 41468c4d052c..e0388a7fd3ea 100644 --- a/packages/opencode/test/format/format.test.ts +++ b/packages/opencode/test/format/format.test.ts @@ -1,7 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" -import { provideTmpdirInstance } from "../fixture/fixture" +import { provideTmpdirInstance, testInstanceStoreLayer, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Format } from "../../src/format" @@ -10,141 +10,104 @@ import * as Formatter from "../../src/format/formatter" const it = testEffect(Layer.mergeAll(Format.defaultLayer, CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer)) describe("Format", () => { - it.live("status() returns empty list when no formatters are configured", () => - provideTmpdirInstance(() => + it.instance("status() returns empty list when no formatters are configured", () => + Format.Service.use((fmt) => + Effect.gen(function* () { + expect(yield* fmt.status()).toEqual([]) + }), + ), + ) + + it.instance( + "status() returns built-in formatters when formatter is true", + () => Format.Service.use((fmt) => Effect.gen(function* () { - expect(yield* fmt.status()).toEqual([]) + const statuses = yield* fmt.status() + const gofmt = statuses.find((item) => item.name === "gofmt") + expect(gofmt).toBeDefined() + expect(gofmt!.extensions).toContain(".go") }), ), - ), - ) - - it.live("status() returns built-in formatters when formatter is true", () => - provideTmpdirInstance( - () => - Format.Service.use((fmt) => - Effect.gen(function* () { - const statuses = yield* fmt.status() - const gofmt = statuses.find((item) => item.name === "gofmt") - expect(gofmt).toBeDefined() - expect(gofmt!.extensions).toContain(".go") - }), - ), - { - config: { - formatter: true, - }, - }, - ), + { config: { formatter: true } }, ) - it.live("status() keeps built-in formatters when config object is provided", () => - provideTmpdirInstance( - () => - Format.Service.use((fmt) => - Effect.gen(function* () { - const statuses = yield* fmt.status() - const gofmt = statuses.find((item) => item.name === "gofmt") - const mix = statuses.find((item) => item.name === "mix") - expect(gofmt).toBeDefined() - expect(gofmt!.extensions).toContain(".go") - expect(mix).toBeDefined() - }), - ), - { - config: { - formatter: { - gofmt: {}, - }, - }, - }, - ), + it.instance( + "status() keeps built-in formatters when config object is provided", + () => + Format.Service.use((fmt) => + Effect.gen(function* () { + const statuses = yield* fmt.status() + const gofmt = statuses.find((item) => item.name === "gofmt") + const mix = statuses.find((item) => item.name === "mix") + expect(gofmt).toBeDefined() + expect(gofmt!.extensions).toContain(".go") + expect(mix).toBeDefined() + }), + ), + { config: { formatter: { gofmt: {} } } }, ) - it.live("status() excludes formatters marked as disabled in config", () => - provideTmpdirInstance( - () => - Format.Service.use((fmt) => - Effect.gen(function* () { - const statuses = yield* fmt.status() - const gofmt = statuses.find((item) => item.name === "gofmt") - const mix = statuses.find((item) => item.name === "mix") - expect(gofmt).toBeUndefined() - expect(mix).toBeDefined() - }), - ), - { - config: { - formatter: { - gofmt: { disabled: true }, - }, - }, - }, - ), + it.instance( + "status() excludes formatters marked as disabled in config", + () => + Format.Service.use((fmt) => + Effect.gen(function* () { + const statuses = yield* fmt.status() + const gofmt = statuses.find((item) => item.name === "gofmt") + const mix = statuses.find((item) => item.name === "mix") + expect(gofmt).toBeUndefined() + expect(mix).toBeDefined() + }), + ), + { config: { formatter: { gofmt: { disabled: true } } } }, ) - it.live("status() excludes uv when ruff is disabled", () => - provideTmpdirInstance( - () => - Format.Service.use((fmt) => - Effect.gen(function* () { - const statuses = yield* fmt.status() - expect(statuses.find((item) => item.name === "ruff")).toBeUndefined() - expect(statuses.find((item) => item.name === "uv")).toBeUndefined() - }), - ), - { - config: { - formatter: { - ruff: { disabled: true }, - }, - }, - }, - ), + it.instance( + "status() excludes uv when ruff is disabled", + () => + Format.Service.use((fmt) => + Effect.gen(function* () { + const statuses = yield* fmt.status() + expect(statuses.find((item) => item.name === "ruff")).toBeUndefined() + expect(statuses.find((item) => item.name === "uv")).toBeUndefined() + }), + ), + { config: { formatter: { ruff: { disabled: true } } } }, ) - it.live("status() excludes ruff when uv is disabled", () => - provideTmpdirInstance( - () => - Format.Service.use((fmt) => - Effect.gen(function* () { - const statuses = yield* fmt.status() - expect(statuses.find((item) => item.name === "ruff")).toBeUndefined() - expect(statuses.find((item) => item.name === "uv")).toBeUndefined() - }), - ), - { - config: { - formatter: { - uv: { disabled: true }, - }, - }, - }, - ), + it.instance( + "status() excludes ruff when uv is disabled", + () => + Format.Service.use((fmt) => + Effect.gen(function* () { + const statuses = yield* fmt.status() + expect(statuses.find((item) => item.name === "ruff")).toBeUndefined() + expect(statuses.find((item) => item.name === "uv")).toBeUndefined() + }), + ), + { config: { formatter: { uv: { disabled: true } } } }, ) - it.live("service initializes without error", () => provideTmpdirInstance(() => Format.Service.use(() => Effect.void))) + it.instance("service initializes without error", () => Format.Service.use(() => Effect.void)) - it.live("file() returns false when no formatter runs", () => - provideTmpdirInstance( - (dir) => - Effect.gen(function* () { - const file = `${dir}/test.txt` - yield* Effect.promise(() => Bun.write(file, "x")) + it.instance( + "file() returns false when no formatter runs", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const file = `${test.directory}/test.txt` + yield* Effect.promise(() => Bun.write(file, "x")) - const formatted = yield* Format.use.file(file) - expect(formatted).toBe(false) - }), - { - config: { - formatter: false, - }, - }, - ), + const formatted = yield* Format.use.file(file) + expect(formatted).toBe(false) + }), + { config: { formatter: false } }, ) - it.live("status() initializes formatter state per directory", () => + testEffect( + Layer.mergeAll(Format.defaultLayer, CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer, testInstanceStoreLayer), + ).live("status() initializes formatter state per directory", () => Effect.gen(function* () { const a = yield* provideTmpdirInstance(() => Format.use.status(), { config: { formatter: false }, @@ -160,113 +123,106 @@ describe("Format", () => { }), ) - it.live("runs enabled checks for matching formatters in parallel", () => - provideTmpdirInstance( - (path) => - Effect.gen(function* () { - const file = `${path}/test.parallel` - yield* Effect.promise(() => Bun.write(file, "x")) - - const one = { - extensions: Formatter.gofmt.extensions, - enabled: Formatter.gofmt.enabled, - } - const two = { - extensions: Formatter.mix.extensions, - enabled: Formatter.mix.enabled, - } - - let active = 0 - let max = 0 - - yield* Effect.acquireUseRelease( + it.instance( + "runs enabled checks for matching formatters in parallel", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const file = `${test.directory}/test.parallel` + yield* Effect.promise(() => Bun.write(file, "x")) + + const one = { + extensions: Formatter.gofmt.extensions, + enabled: Formatter.gofmt.enabled, + } + const two = { + extensions: Formatter.mix.extensions, + enabled: Formatter.mix.enabled, + } + + let active = 0 + let max = 0 + + yield* Effect.acquireUseRelease( + Effect.sync(() => { + Formatter.gofmt.extensions = [".parallel"] + Formatter.mix.extensions = [".parallel"] + Formatter.gofmt.enabled = async () => { + active++ + max = Math.max(max, active) + await Promise.resolve() + active-- + return ["sh", "-c", "true"] + } + Formatter.mix.enabled = async () => { + active++ + max = Math.max(max, active) + await Promise.resolve() + active-- + return ["sh", "-c", "true"] + } + }), + () => + Format.Service.use((fmt) => + Effect.gen(function* () { + yield* fmt.init() + yield* fmt.file(file) + }), + ), + () => Effect.sync(() => { - Formatter.gofmt.extensions = [".parallel"] - Formatter.mix.extensions = [".parallel"] - Formatter.gofmt.enabled = async () => { - active++ - max = Math.max(max, active) - await Promise.resolve() - active-- - return ["sh", "-c", "true"] - } - Formatter.mix.enabled = async () => { - active++ - max = Math.max(max, active) - await Promise.resolve() - active-- - return ["sh", "-c", "true"] - } + Formatter.gofmt.extensions = one.extensions + Formatter.gofmt.enabled = one.enabled + Formatter.mix.extensions = two.extensions + Formatter.mix.enabled = two.enabled }), - () => - Format.Service.use((fmt) => - Effect.gen(function* () { - yield* fmt.init() - yield* fmt.file(file) - }), - ), - () => - Effect.sync(() => { - Formatter.gofmt.extensions = one.extensions - Formatter.gofmt.enabled = one.enabled - Formatter.mix.extensions = two.extensions - Formatter.mix.enabled = two.enabled - }), - ) + ) - expect(max).toBe(2) - }), - { - config: { - formatter: { - gofmt: {}, - mix: {}, - }, - }, - }, - ), + expect(max).toBe(2) + }), + { config: { formatter: { gofmt: {}, mix: {} } } }, ) - it.live("runs matching formatters sequentially for the same file", () => - provideTmpdirInstance( - (path) => - Effect.gen(function* () { - const file = `${path}/test.seq` - yield* Effect.promise(() => Bun.write(file, "x")) + it.instance( + "runs matching formatters sequentially for the same file", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const file = `${test.directory}/test.seq` + yield* Effect.promise(() => Bun.write(file, "x")) - yield* Format.Service.use((fmt) => - Effect.gen(function* () { - yield* fmt.init() - expect(yield* fmt.file(file)).toBe(true) - }), - ) - - expect(yield* Effect.promise(() => Bun.file(file).text())).toBe("xAB") - }), - { - config: { - formatter: { - first: { - command: [ - "node", - "-e", - "const fs = require('fs'); const file = process.argv[1]; fs.writeFileSync(file, fs.readFileSync(file, 'utf8') + 'A')", - "$FILE", - ], - extensions: [".seq"], - }, - second: { - command: [ - "node", - "-e", - "const fs = require('fs'); const file = process.argv[1]; fs.writeFileSync(file, fs.readFileSync(file, 'utf8') + 'B')", - "$FILE", - ], - extensions: [".seq"], - }, + yield* Format.Service.use((fmt) => + Effect.gen(function* () { + yield* fmt.init() + expect(yield* fmt.file(file)).toBe(true) + }), + ) + + expect(yield* Effect.promise(() => Bun.file(file).text())).toBe("xAB") + }), + { + config: { + formatter: { + first: { + command: [ + "node", + "-e", + "const fs = require('fs'); const file = process.argv[1]; fs.writeFileSync(file, fs.readFileSync(file, 'utf8') + 'A')", + "$FILE", + ], + extensions: [".seq"], + }, + second: { + command: [ + "node", + "-e", + "const fs = require('fs'); const file = process.argv[1]; fs.writeFileSync(file, fs.readFileSync(file, 'utf8') + 'B')", + "$FILE", + ], + extensions: [".seq"], }, }, }, - ), + }, ) }) diff --git a/packages/opencode/test/lib/effect.ts b/packages/opencode/test/lib/effect.ts index f04829601dd9..952cc6b62e6e 100644 --- a/packages/opencode/test/lib/effect.ts +++ b/packages/opencode/test/lib/effect.ts @@ -6,18 +6,25 @@ import * as TestConsole from "effect/testing/TestConsole" import { memoMap } from "@opencode-ai/core/effect/memo-map" import type { Config } from "@/config/config" import { TestInstance, withTmpdirInstance } from "../fixture/fixture" +import { InstanceStore } from "@/project/instance-store" type Body = Effect.Effect | (() => Effect.Effect) -type InstanceOptions = { git?: boolean; config?: Partial | (() => Partial) } +type InstanceOptions = { + git?: boolean + config?: Partial | (() => Partial) + init?: (directory: string) => Effect.Effect +} -function isInstanceOptions(options: InstanceOptions | number | TestOptions | undefined): options is InstanceOptions { - return !!options && typeof options === "object" && ("git" in options || "config" in options) +function isInstanceOptions( + options: InstanceOptions | number | TestOptions | undefined, +): options is InstanceOptions { + return !!options && typeof options === "object" && ("git" in options || "config" in options || "init" in options) } -function instanceArgs( - options?: InstanceOptions | number | TestOptions, +function instanceArgs( + options?: InstanceOptions | number | TestOptions, testOptions?: number | TestOptions, -): { instanceOptions: InstanceOptions | undefined; testOptions: number | TestOptions | undefined } { +): { instanceOptions: InstanceOptions | undefined; testOptions: number | TestOptions | undefined } { if (typeof options === "number") return { instanceOptions: undefined, testOptions: options } if (isInstanceOptions(options)) return { instanceOptions: options, testOptions } return { instanceOptions: undefined, testOptions: options } @@ -75,10 +82,10 @@ const make = (testLayer: Layer.Layer, liveLayer: Layer.Layer, live.skip = (name: string, value: Body, opts?: number | TestOptions) => test.skip(name, () => run(value, liveLayer), opts) - const instance = ( + const instance = ( name: string, - value: Body, - options?: InstanceOptions | number | TestOptions, + value: Body, + options?: InstanceOptions | number | TestOptions, opts?: number | TestOptions, ) => { const args = instanceArgs(options, opts) @@ -89,10 +96,10 @@ const make = (testLayer: Layer.Layer, liveLayer: Layer.Layer, ) } - instance.only = ( + instance.only = ( name: string, - value: Body, - options?: InstanceOptions | number | TestOptions, + value: Body, + options?: InstanceOptions | number | TestOptions, opts?: number | TestOptions, ) => { const args = instanceArgs(options, opts) @@ -103,10 +110,10 @@ const make = (testLayer: Layer.Layer, liveLayer: Layer.Layer, ) } - instance.skip = ( + instance.skip = ( name: string, - value: Body, - options?: InstanceOptions | number | TestOptions, + value: Body, + options?: InstanceOptions | number | TestOptions, opts?: number | TestOptions, ) => { const args = instanceArgs(options, opts) @@ -126,17 +133,17 @@ const testEnv = Layer.mergeAll(TestConsole.layer, TestClock.layer()) // Live environment - uses real clock, but keeps TestConsole for output capture const liveEnv = TestConsole.layer -export const it = make(testEnv, liveEnv) +export const it = make(testEnv, liveEnv) export const testEffect = (layer: Layer.Layer) => - make(Layer.provideMerge(layer, testEnv), Layer.provideMerge(layer, liveEnv)) + make(Layer.provideMerge(layer, testEnv), Layer.provideMerge(layer, liveEnv)) // Variant of `testEffect` that builds the test layer through the shared // process-wide memoMap so services like Bus/Session resolve to the same // instances Server.Default uses. Use when a test needs pub/sub identity with // an in-process HTTP server — most tests should stick with `testEffect`. export const testEffectShared = (layer: Layer.Layer) => - make(Layer.provideMerge(layer, testEnv), Layer.provideMerge(layer, liveEnv), sharedRun) + make(Layer.provideMerge(layer, testEnv), Layer.provideMerge(layer, liveEnv), sharedRun) export const awaitWithTimeout = ( self: Effect.Effect, diff --git a/packages/opencode/test/lsp/index.test.ts b/packages/opencode/test/lsp/index.test.ts index 78543c4583d9..86f3a5dadfc0 100644 --- a/packages/opencode/test/lsp/index.test.ts +++ b/packages/opencode/test/lsp/index.test.ts @@ -1,64 +1,44 @@ import { describe, expect, spyOn } from "bun:test" import path from "path" import { Deferred, Effect, Layer } from "effect" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { Config } from "@/config/config" import { RuntimeFlags } from "@/effect/runtime-flags" import { LSP } from "@/lsp/lsp" import * as LSPServer from "@/lsp/server" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { provideTmpdirInstance } from "../fixture/fixture" +import { TestInstance } from "../fixture/fixture" import { awaitWithTimeout, testEffect } from "../lib/effect" -const it = testEffect(Layer.mergeAll(LSP.defaultLayer, CrossSpawnSpawner.defaultLayer)) +const lspLayer = (flags: Parameters[0] = {}) => + LSP.layer.pipe( + Layer.provide(Config.defaultLayer), + Layer.provide(RuntimeFlags.layer(flags)), + Layer.provideMerge(EventV2Bridge.defaultLayer), + ) + +const it = testEffect(Layer.mergeAll(lspLayer(), CrossSpawnSpawner.defaultLayer)) const experimentalTyIt = testEffect( - Layer.mergeAll( - LSP.layer.pipe(Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.layer({ experimentalLspTy: true }))), - CrossSpawnSpawner.defaultLayer, - ), + Layer.mergeAll(lspLayer({ experimentalLspTy: true }), CrossSpawnSpawner.defaultLayer), ) const fakeServerPath = path.join(__dirname, "../fixture/lsp/fake-lsp-server.js") const disabledDownloadIt = testEffect( - Layer.mergeAll( - LSP.layer.pipe(Layer.provide(Config.defaultLayer), Layer.provide(RuntimeFlags.layer({ disableLspDownload: true }))), - CrossSpawnSpawner.defaultLayer, - ), + Layer.mergeAll(lspLayer({ disableLspDownload: true }), CrossSpawnSpawner.defaultLayer), ) describe("lsp.spawn", () => { - it.live("does not spawn builtin LSP for files outside instance", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) - - try { - yield* lsp.touchFile(path.join(dir, "..", "outside.ts")) - yield* lsp.hover({ - file: path.join(dir, "..", "hover.ts"), - line: 0, - character: 0, - }) - expect(spy).toHaveBeenCalledTimes(0) - } finally { - spy.mockRestore() - } - }), - ), - { config: { lsp: true } }, - ), - ) - - it.live("does not spawn builtin LSP for files inside instance when LSP is unset", () => - provideTmpdirInstance((dir) => + it.instance( + "does not spawn builtin LSP for files outside instance", + () => LSP.Service.use((lsp) => Effect.gen(function* () { + const dir = (yield* TestInstance).directory const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) try { + yield* lsp.touchFile(path.join(dir, "..", "outside.ts")) yield* lsp.hover({ - file: path.join(dir, "src", "inside.ts"), + file: path.join(dir, "..", "hover.ts"), line: 0, character: 0, }) @@ -68,163 +48,185 @@ describe("lsp.spawn", () => { } }), ), - ), + { config: { lsp: true } }, ) - it.live("would spawn builtin LSP for files inside instance when lsp is true", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) - - try { - yield* lsp.hover({ - file: path.join(dir, "src", "inside.ts"), - line: 0, - character: 0, - }) - expect(spy).toHaveBeenCalledTimes(1) - } finally { - spy.mockRestore() - } - }), - ), - { config: { lsp: true } }, + it.instance("does not spawn builtin LSP for files inside instance when LSP is unset", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.ts"), + line: 0, + character: 0, + }) + expect(spy).toHaveBeenCalledTimes(0) + } finally { + spy.mockRestore() + } + }), ), ) - it.live("publishes lsp.updated after custom LSP initialization", () => - provideTmpdirInstance( - (dir) => + it.instance( + "would spawn builtin LSP for files inside instance when lsp is true", + () => + LSP.Service.use((lsp) => Effect.gen(function* () { - const lsp = yield* LSP.Service - const updated = yield* Deferred.make() - const unsubscribe = Bus.subscribe(LSP.Event.Updated, () => - Effect.runSync(Deferred.succeed(updated, undefined)), - ) - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)) - - const file = path.join(dir, "sample.repro") - yield* Effect.promise(() => Bun.write(file, "sample\n")) - yield* lsp.touchFile(file) - yield* awaitWithTimeout(Deferred.await(updated), "lsp.updated event was not published") + const dir = (yield* TestInstance).directory + const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.ts"), + line: 0, + character: 0, + }) + expect(spy).toHaveBeenCalledTimes(1) + } finally { + spy.mockRestore() + } }), - { - config: { - lsp: { - fake: { - command: [process.execPath, fakeServerPath], - extensions: [".repro"], - }, + ), + { config: { lsp: true } }, + ) + + it.instance( + "publishes lsp.updated after custom LSP initialization", + () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const lsp = yield* LSP.Service + const updated = yield* Deferred.make() + const events = yield* EventV2Bridge.Service + const unsubscribe = yield* events.listen((event) => { + if (event.type === LSP.Event.Updated.type) Deferred.doneUnsafe(updated, Effect.void) + return Effect.void + }) + yield* Effect.addFinalizer(() => unsubscribe) + + const file = path.join(dir, "sample.repro") + yield* Effect.promise(() => Bun.write(file, "sample\n")) + yield* lsp.touchFile(file) + yield* awaitWithTimeout(Deferred.await(updated), "lsp.updated event was not published") + }), + { + config: { + lsp: { + fake: { + command: [process.execPath, fakeServerPath], + extensions: [".repro"], }, }, }, - ), + }, ) - it.live("would spawn builtin LSP for files inside instance when config object is provided", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) - - try { - yield* lsp.hover({ - file: path.join(dir, "src", "inside.ts"), - line: 0, - character: 0, - }) - expect(spy).toHaveBeenCalledTimes(1) - } finally { - spy.mockRestore() - } - }), - ), - { - config: { - lsp: { - eslint: { disabled: true }, - }, + it.instance( + "would spawn builtin LSP for files inside instance when config object is provided", + () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const spy = spyOn(LSPServer.Typescript, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.ts"), + line: 0, + character: 0, + }) + expect(spy).toHaveBeenCalledTimes(1) + } finally { + spy.mockRestore() + } + }), + ), + { + config: { + lsp: { + eslint: { disabled: true }, }, }, - ), + }, ) - it.live("uses pyright instead of ty by default", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const ty = spyOn(LSPServer.Ty, "spawn").mockResolvedValue(undefined) - const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) - - try { - yield* lsp.hover({ - file: path.join(dir, "src", "inside.py"), - line: 0, - character: 0, - }) - expect(ty).toHaveBeenCalledTimes(0) - expect(pyright).toHaveBeenCalledTimes(1) - } finally { - ty.mockRestore() - pyright.mockRestore() - } - }), - ), - { config: { lsp: true } }, - ), + it.instance( + "uses pyright instead of ty by default", + () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const ty = spyOn(LSPServer.Ty, "spawn").mockResolvedValue(undefined) + const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.py"), + line: 0, + character: 0, + }) + expect(ty).toHaveBeenCalledTimes(0) + expect(pyright).toHaveBeenCalledTimes(1) + } finally { + ty.mockRestore() + pyright.mockRestore() + } + }), + ), + { config: { lsp: true } }, ) - experimentalTyIt.live("uses ty instead of pyright when experimentalLspTy is enabled", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const ty = spyOn(LSPServer.Ty, "spawn").mockResolvedValue(undefined) - const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) - - try { - yield* lsp.hover({ - file: path.join(dir, "src", "inside.py"), - line: 0, - character: 0, - }) - expect(ty).toHaveBeenCalledTimes(1) - expect(pyright).toHaveBeenCalledTimes(0) - } finally { - ty.mockRestore() - pyright.mockRestore() - } - }), - ), - { config: { lsp: true } }, - ), + experimentalTyIt.instance( + "uses ty instead of pyright when experimentalLspTy is enabled", + () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const ty = spyOn(LSPServer.Ty, "spawn").mockResolvedValue(undefined) + const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.py"), + line: 0, + character: 0, + }) + expect(ty).toHaveBeenCalledTimes(1) + expect(pyright).toHaveBeenCalledTimes(0) + } finally { + ty.mockRestore() + pyright.mockRestore() + } + }), + ), + { config: { lsp: true } }, ) - disabledDownloadIt.live("passes disableLspDownload to builtin LSP spawn", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) - - try { - yield* lsp.hover({ - file: path.join(dir, "src", "inside.py"), - line: 0, - character: 0, - }) - expect(pyright).toHaveBeenCalledTimes(1) - expect(pyright.mock.calls[0]?.[2]).toMatchObject({ disableLspDownload: true }) - } finally { - pyright.mockRestore() - } - }), - ), - { config: { lsp: true } }, - ), + disabledDownloadIt.instance( + "passes disableLspDownload to builtin LSP spawn", + () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const pyright = spyOn(LSPServer.Pyright, "spawn").mockResolvedValue(undefined) + + try { + yield* lsp.hover({ + file: path.join(dir, "src", "inside.py"), + line: 0, + character: 0, + }) + expect(pyright).toHaveBeenCalledTimes(1) + expect(pyright.mock.calls[0]?.[2]).toMatchObject({ disableLspDownload: true }) + } finally { + pyright.mockRestore() + } + }), + ), + { config: { lsp: true } }, ) }) diff --git a/packages/opencode/test/lsp/lifecycle.test.ts b/packages/opencode/test/lsp/lifecycle.test.ts index 11b191f00525..5d0313e6d20d 100644 --- a/packages/opencode/test/lsp/lifecycle.test.ts +++ b/packages/opencode/test/lsp/lifecycle.test.ts @@ -4,7 +4,7 @@ import { Effect, Layer } from "effect" import { LSP } from "@/lsp/lsp" import * as LSPServer from "@/lsp/server" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { provideTmpdirInstance } from "../fixture/fixture" +import { TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" const it = testEffect(Layer.mergeAll(LSP.defaultLayer, CrossSpawnSpawner.defaultLayer)) @@ -20,137 +20,113 @@ describe("LSP service lifecycle", () => { spawnSpy.mockRestore() }) - it.live("init() completes without error", () => provideTmpdirInstance(() => LSP.Service.use((lsp) => lsp.init()))) + it.instance("init() completes without error", () => LSP.Service.use((lsp) => lsp.init())) - it.live("status() returns empty array initially", () => - provideTmpdirInstance(() => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.status() - expect(Array.isArray(result)).toBe(true) - expect(result.length).toBe(0) - }), - ), - ), - ) - - it.live("diagnostics() returns empty object initially", () => - provideTmpdirInstance(() => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.diagnostics() - expect(typeof result).toBe("object") - expect(Object.keys(result).length).toBe(0) - }), - ), - ), - ) - - it.live("hasClients() returns false for .ts files in instance when LSP is unset", () => - provideTmpdirInstance((dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.hasClients(path.join(dir, "test.ts")) - expect(result).toBe(false) - }), - ), + it.instance("status() returns empty array initially", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.status() + expect(Array.isArray(result)).toBe(true) + expect(result.length).toBe(0) + }), ), ) - it.live("hasClients() returns true for .ts files in instance when lsp is true", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.hasClients(path.join(dir, "test.ts")) - expect(result).toBe(true) - }), - ), - { config: { lsp: true } }, + it.instance("diagnostics() returns empty object initially", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.diagnostics() + expect(typeof result).toBe("object") + expect(Object.keys(result).length).toBe(0) + }), ), ) - it.live("hasClients() keeps built-in LSPs when config object is provided", () => - provideTmpdirInstance( - (dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.hasClients(path.join(dir, "test.ts")) - expect(result).toBe(true) - }), - ), - { - config: { - lsp: { - eslint: { disabled: true }, - }, - }, - }, + it.instance("hasClients() returns false for .ts files in instance when LSP is unset", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.hasClients(path.join((yield* TestInstance).directory, "test.ts")) + expect(result).toBe(false) + }), ), ) - it.live("hasClients() returns false for files outside instance", () => - provideTmpdirInstance((dir) => + it.instance( + "hasClients() returns true for .ts files in instance when lsp is true", + () => LSP.Service.use((lsp) => Effect.gen(function* () { - const result = yield* lsp.hasClients(path.join(dir, "..", "outside.ts")) - expect(typeof result).toBe("boolean") + const result = yield* lsp.hasClients(path.join((yield* TestInstance).directory, "test.ts")) + expect(result).toBe(true) }), ), - ), + { config: { lsp: true } }, ) - it.live("workspaceSymbol() returns empty array with no clients", () => - provideTmpdirInstance(() => + it.instance( + "hasClients() keeps built-in LSPs when config object is provided", + () => LSP.Service.use((lsp) => Effect.gen(function* () { - const result = yield* lsp.workspaceSymbol("test") - expect(Array.isArray(result)).toBe(true) - expect(result.length).toBe(0) + const result = yield* lsp.hasClients(path.join((yield* TestInstance).directory, "test.ts")) + expect(result).toBe(true) }), ), + { config: { lsp: { eslint: { disabled: true } } } }, + ) + + it.instance("hasClients() returns false for files outside instance", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.hasClients(path.join((yield* TestInstance).directory, "..", "outside.ts")) + expect(typeof result).toBe("boolean") + }), ), ) - it.live("definition() returns empty array for unknown file", () => - provideTmpdirInstance((dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.definition({ - file: path.join(dir, "nonexistent.ts"), - line: 0, - character: 0, - }) - expect(Array.isArray(result)).toBe(true) - }), - ), + it.instance("workspaceSymbol() returns empty array with no clients", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.workspaceSymbol("test") + expect(Array.isArray(result)).toBe(true) + expect(result.length).toBe(0) + }), ), ) - it.live("references() returns empty array for unknown file", () => - provideTmpdirInstance((dir) => - LSP.Service.use((lsp) => - Effect.gen(function* () { - const result = yield* lsp.references({ - file: path.join(dir, "nonexistent.ts"), - line: 0, - character: 0, - }) - expect(Array.isArray(result)).toBe(true) - }), - ), + it.instance("definition() returns empty array for unknown file", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.definition({ + file: path.join((yield* TestInstance).directory, "nonexistent.ts"), + line: 0, + character: 0, + }) + expect(Array.isArray(result)).toBe(true) + }), ), ) - it.live("multiple init() calls are idempotent", () => - provideTmpdirInstance(() => - LSP.Service.use((lsp) => - Effect.gen(function* () { - yield* lsp.init() - yield* lsp.init() - yield* lsp.init() - }), - ), + it.instance("references() returns empty array for unknown file", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + const result = yield* lsp.references({ + file: path.join((yield* TestInstance).directory, "nonexistent.ts"), + line: 0, + character: 0, + }) + expect(Array.isArray(result)).toBe(true) + }), + ), + ) + + it.instance("multiple init() calls are idempotent", () => + LSP.Service.use((lsp) => + Effect.gen(function* () { + yield* lsp.init() + yield* lsp.init() + yield* lsp.init() + }), ), ) }) diff --git a/packages/opencode/test/mcp/auth.test.ts b/packages/opencode/test/mcp/auth.test.ts new file mode 100644 index 000000000000..efd7579e3765 --- /dev/null +++ b/packages/opencode/test/mcp/auth.test.ts @@ -0,0 +1,78 @@ +import { expect, test } from "bun:test" +import { setTimeout as sleep } from "node:timers/promises" +import { Effect, Layer } from "effect" +import { AppFileSystem } from "@opencode-ai/core/filesystem" +import { EffectFlock } from "@opencode-ai/core/util/effect-flock" +import { McpAuth } from "../../src/mcp/auth" + +function authFile() { + let raw = "" + let activeWrites = 0 + let sawOverlap = false + + const layer = Layer.effect( + AppFileSystem.Service, + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + + return AppFileSystem.Service.of({ + ...fs, + readJson: (file) => + file.endsWith("mcp-auth.json") + ? Effect.try({ + try: () => { + if (!raw) throw new Error("mcp-auth.json missing") + return JSON.parse(raw) + }, + catch: (cause) => new AppFileSystem.FileSystemError({ method: "readJson", cause }), + }) + : fs.readJson(file), + writeJson: (file, value, mode) => + file.endsWith("mcp-auth.json") + ? Effect.promise(async () => { + activeWrites++ + sawOverlap = sawOverlap || activeWrites > 1 + raw = "" + await sleep(10) + const next = JSON.stringify(value, null, 2) + raw = sawOverlap ? `${next}\n}` : next + activeWrites-- + }) + : fs.writeJson(file, value, mode), + }) + }), + ).pipe(Layer.provide(AppFileSystem.defaultLayer)) + + return { layer, raw: () => raw } +} + +function authService(layer: Layer.Layer) { + return McpAuth.Service.use((auth) => Effect.succeed(auth)).pipe( + Effect.provide(McpAuth.layer.pipe(Layer.provide(EffectFlock.defaultLayer), Layer.provide(layer))), + ) +} + +test("serializes concurrent auth file updates across service instances", async () => { + const file = authFile() + + await Effect.runPromise( + Effect.gen(function* () { + const first = yield* authService(file.layer) + const second = yield* authService(file.layer) + + yield* Effect.all( + [ + first.updateTokens("posthog", { accessToken: "access-token" }, "https://mcp.posthog.com/mcp"), + second.updateClientInfo("posthog", { clientId: "client-id" }, "https://mcp.posthog.com/mcp"), + ], + { concurrency: "unbounded" }, + ) + + const entry = yield* first.get("posthog") + expect(entry?.tokens?.accessToken).toBe("access-token") + expect(entry?.clientInfo?.clientId).toBe("client-id") + expect(entry?.serverUrl).toBe("https://mcp.posthog.com/mcp") + expect(() => JSON.parse(file.raw())).not.toThrow() + }), + ) +}) diff --git a/packages/opencode/test/mcp/oauth-auto-connect.test.ts b/packages/opencode/test/mcp/oauth-auto-connect.test.ts index 17bdba690f5e..542069fc6cc5 100644 --- a/packages/opencode/test/mcp/oauth-auto-connect.test.ts +++ b/packages/opencode/test/mcp/oauth-auto-connect.test.ts @@ -112,7 +112,7 @@ beforeEach(() => { // Import modules after mocking const { MCP } = await import("../../src/mcp/index") -const { Bus } = await import("../../src/bus") +const { EventV2Bridge } = await import("../../src/event-v2-bridge") const { Config } = await import("../../src/config/config") const { McpAuth } = await import("../../src/mcp/auth") const { McpOAuthProvider } = await import("../../src/mcp/oauth-provider") @@ -123,7 +123,7 @@ const mcpTest = testEffect( Layer.mergeAll( MCP.layer.pipe( Layer.provide(McpAuth.defaultLayer), - Layer.provideMerge(Bus.layer), + Layer.provideMerge(EventV2Bridge.defaultLayer), Layer.provide(Config.defaultLayer), Layer.provide(CrossSpawnSpawner.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), diff --git a/packages/opencode/test/mcp/oauth-browser.test.ts b/packages/opencode/test/mcp/oauth-browser.test.ts index 16d6a2d46720..92f473b113b5 100644 --- a/packages/opencode/test/mcp/oauth-browser.test.ts +++ b/packages/opencode/test/mcp/oauth-browser.test.ts @@ -106,7 +106,7 @@ beforeEach(() => { // Import modules after mocking const { MCP } = await import("../../src/mcp/index") -const { Bus } = await import("../../src/bus") +const { EventV2Bridge } = await import("../../src/event-v2-bridge") const { Config } = await import("../../src/config/config") const { McpAuth } = await import("../../src/mcp/auth") const { McpOAuthCallback } = await import("../../src/mcp/oauth-callback") @@ -115,7 +115,7 @@ const { CrossSpawnSpawner } = await import("@opencode-ai/core/cross-spawn-spawne const mcpTest = testEffect( MCP.layer.pipe( Layer.provide(McpAuth.defaultLayer), - Layer.provideMerge(Bus.layer), + Layer.provideMerge(EventV2Bridge.defaultLayer), Layer.provide(Config.defaultLayer), Layer.provide(CrossSpawnSpawner.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), @@ -142,12 +142,14 @@ const trackBrowserOpen = Effect.gen(function* () { }) const trackBrowserOpenFailed = Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const event = yield* Deferred.make<{ mcpName: string; url: string }>() - const unsubscribe = yield* bus.subscribeCallback(MCP.BrowserOpenFailed, (evt) => { - Effect.runSync(Deferred.succeed(event, evt.properties).pipe(Effect.ignore)) + const unsubscribe = yield* events.listen((evt) => { + if (evt.type === MCP.BrowserOpenFailed.type) + Deferred.doneUnsafe(event, Effect.succeed(evt.data as { mcpName: string; url: string })) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)) + yield* Effect.addFinalizer(() => unsubscribe) return event }) diff --git a/packages/opencode/test/permission/next.test.ts b/packages/opencode/test/permission/next.test.ts index e969e67ff63a..a6d7e2ead010 100644 --- a/packages/opencode/test/permission/next.test.ts +++ b/packages/opencode/test/permission/next.test.ts @@ -1,8 +1,9 @@ import { test, expect } from "bun:test" import os from "os" import { Cause, Deferred, Effect, Exit, Fiber, Layer } from "effect" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { Database } from "@opencode-ai/core/database/database" import { Permission } from "../../src/permission" import { PermissionID } from "../../src/permission/schema" import { InstanceBootstrap } from "../../src/project/bootstrap-service" @@ -11,11 +12,11 @@ import { TestInstance, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { MessageID, SessionID } from "../../src/session/schema" -const bus = Bus.layer +const events = EventV2Bridge.defaultLayer const noopBootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void })) const env = Layer.mergeAll( - Permission.layer.pipe(Layer.provide(bus)), - bus, + Permission.layer.pipe(Layer.provide(Database.defaultLayer), Layer.provide(events)), + events, CrossSpawnSpawner.defaultLayer, InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap)), ) @@ -653,12 +654,14 @@ it.instance( "ask - publishes asked event", () => Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const seen = yield* Deferred.make() - const unsub = yield* bus.subscribeCallback(Permission.Event.Asked, (event) => { - Deferred.doneUnsafe(seen, Effect.succeed(event.properties)) + const unsub = yield* events.listen((event) => { + if (event.type === Permission.Event.Asked.type) + Deferred.doneUnsafe(seen, Effect.succeed(event.data as Permission.Request)) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsub)) + yield* Effect.addFinalizer(() => unsub) const fiber = yield* ask({ sessionID: SessionID.make("session_test"), @@ -913,7 +916,7 @@ it.instance( "reply - publishes replied event", () => Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const seen = yield* Deferred.make<{ sessionID: SessionID; requestID: PermissionID; reply: Permission.Reply }>() const fiber = yield* ask({ @@ -928,10 +931,15 @@ it.instance( yield* waitForPending(1) - const unsub = yield* bus.subscribeCallback(Permission.Event.Replied, (event) => { - Deferred.doneUnsafe(seen, Effect.succeed(event.properties)) + const unsub = yield* events.listen((event) => { + if (event.type === Permission.Event.Replied.type) + Deferred.doneUnsafe( + seen, + Effect.succeed(event.data as { sessionID: SessionID; requestID: PermissionID; reply: Permission.Reply }), + ) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsub)) + yield* Effect.addFinalizer(() => unsub) yield* reply({ requestID: PermissionID.make("per_test7"), reply: "once" }) yield* Fiber.join(fiber) diff --git a/packages/opencode/test/plugin/auth-override.test.ts b/packages/opencode/test/plugin/auth-override.test.ts index c10957996e27..58ffe197755f 100644 --- a/packages/opencode/test/plugin/auth-override.test.ts +++ b/packages/opencode/test/plugin/auth-override.test.ts @@ -5,14 +5,15 @@ import { Effect, Layer } from "effect" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture" import { ProviderAuth } from "@/provider/auth" -import { ProviderID } from "../../src/provider/schema" + import { Plugin } from "@/plugin" import { RuntimeFlags } from "@/effect/runtime-flags" import { Auth } from "@/auth" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { TestConfig } from "../fixture/config" import { testEffect } from "../lib/effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { ProviderV2 } from "@opencode-ai/core/provider" const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, AppFileSystem.defaultLayer)) @@ -21,7 +22,7 @@ function layer(directory: string, plugins: string[]) { Layer.provide(Auth.defaultLayer), Layer.provide( Plugin.layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(RuntimeFlags.layer()), Layer.provide( TestConfig.layer({ @@ -77,11 +78,11 @@ describe("plugin.auth-override", () => { .methods() .pipe(Effect.provide(layer(plain, [])), provideInstance(plain)) - const copilot = methods[ProviderID.make("github-copilot")] + const copilot = methods[ProviderV2.ID.make("github-copilot")] expect(copilot).toBeDefined() expect(copilot.length).toBe(1) expect(copilot[0].label).toBe("Test Override Auth") - expect(plainMethods[ProviderID.make("github-copilot")][0].label).not.toBe("Test Override Auth") + expect(plainMethods[ProviderV2.ID.make("github-copilot")][0].label).not.toBe("Test Override Auth") }), { git: true }, 30000, diff --git a/packages/opencode/test/plugin/codex.test.ts b/packages/opencode/test/plugin/codex.test.ts index 271bcde99b23..a375fe4ee10d 100644 --- a/packages/opencode/test/plugin/codex.test.ts +++ b/packages/opencode/test/plugin/codex.test.ts @@ -5,7 +5,7 @@ import { extractAccountIdFromClaims, extractAccountId, type IdTokenClaims, -} from "../../src/plugin/codex" +} from "../../src/plugin/openai/codex" function createTestJwt(payload: object): string { const header = Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url") @@ -122,6 +122,24 @@ describe("plugin.codex", () => { }) }) + test("installs websocket transport only when experimental websockets are enabled", async () => { + const disabled = await CodexAuthPlugin({} as never) + const enabled = await CodexAuthPlugin({} as never, { experimentalWebSockets: true }) + + const disabledOptions = await disabled.auth!.loader!( + async () => ({ type: "api", key: "sk-test" }) as never, + {} as never, + ) + const enabledOptions = await enabled.auth!.loader!( + async () => ({ type: "api", key: "sk-test" }) as never, + {} as never, + ) + + expect(disabledOptions.fetch).toBeUndefined() + expect(enabledOptions.fetch).toBeFunction() + await enabled.dispose?.() + }) + test("deduplicates concurrent Codex token refreshes", async () => { let auth = { type: "oauth" as const, diff --git a/packages/opencode/test/plugin/cwd.test.ts b/packages/opencode/test/plugin/cwd.test.ts index b17175350955..6038eb7833ef 100644 --- a/packages/opencode/test/plugin/cwd.test.ts +++ b/packages/opencode/test/plugin/cwd.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test" import os from "os" import path from "path" import { getCwd, setCwd, resetCwd, CwdEvent } from "../../plugin/shell-mode/cwd" -import { Bus } from "../../src/bus" +import { GlobalBus, type GlobalEvent } from "../../src/bus/global" import { provideTestInstance, disposeAllInstances, tmpdir } from "../fixture/fixture" afterEach(async () => { @@ -15,6 +15,16 @@ async function withInstance(fn: () => Promise): Promise { await provideTestInstance({ directory: tmp.path, fn }) } +function subscribeCwd(received: string[]): () => void { + const handler = (event: GlobalEvent) => { + if (event.payload?.type !== CwdEvent.Updated.type) return + const cwd = event.payload.properties?.cwd + if (typeof cwd === "string") received.push(cwd) + } + GlobalBus.on("event", handler) + return () => GlobalBus.off("event", handler) +} + describe("setCwd / getCwd — unit", () => { test("absolute path is stored and returned", async () => { await withInstance(async () => { @@ -122,9 +132,7 @@ describe("CwdEvent.Updated — LAC-742 regression", () => { await provideTestInstance({ directory: tmp.path, fn: async () => { - const unsub = Bus.subscribe(CwdEvent.Updated, (evt) => { - received.push(evt.properties.cwd) - }) + const unsub = subscribeCwd(received) await Bun.sleep(10) setCwd("/tmp") @@ -143,9 +151,7 @@ describe("CwdEvent.Updated — LAC-742 regression", () => { await provideTestInstance({ directory: tmp.path, fn: async () => { - const unsub = Bus.subscribe(CwdEvent.Updated, (evt) => { - received.push(evt.properties.cwd) - }) + const unsub = subscribeCwd(received) await Bun.sleep(10) setCwd("/tmp") @@ -165,9 +171,7 @@ describe("CwdEvent.Updated — LAC-742 regression", () => { await provideTestInstance({ directory: tmp.path, fn: async () => { - const unsub = Bus.subscribe(CwdEvent.Updated, (evt) => { - received.push(evt.properties.cwd) - }) + const unsub = subscribeCwd(received) await Bun.sleep(10) setCwd("/tmp") diff --git a/packages/opencode/test/plugin/loader-shared.test.ts b/packages/opencode/test/plugin/loader-shared.test.ts index ad03d229f2db..909e46c7d6d1 100644 --- a/packages/opencode/test/plugin/loader-shared.test.ts +++ b/packages/opencode/test/plugin/loader-shared.test.ts @@ -5,13 +5,13 @@ import path from "path" import { pathToFileURL } from "url" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { AppFileSystem } from "@opencode-ai/core/filesystem" -import { disposeAllInstances, provideInstance, tmpdirScoped } from "../fixture/fixture" +import { disposeAllInstances, provideInstance, testInstanceStoreLayer, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" const { Plugin } = await import("../../src/plugin/index") const { PluginLoader } = await import("../../src/plugin/loader") const { readPackageThemes } = await import("../../src/plugin/shared") -const { Bus } = await import("../../src/bus") +const { EventV2Bridge } = await import("../../src/event-v2-bridge") const { Npm } = await import("@opencode-ai/core/npm") const { TestConfig } = await import("../fixture/config") const { RuntimeFlags } = await import("../../src/effect/runtime-flags") @@ -20,7 +20,9 @@ afterEach(async () => { await disposeAllInstances() }) -const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, AppFileSystem.defaultLayer)) +const it = testEffect( + Layer.mergeAll(CrossSpawnSpawner.defaultLayer, AppFileSystem.defaultLayer, testInstanceStoreLayer), +) function withTmp( init: (dir: string) => Promise, @@ -46,7 +48,7 @@ function load(dir: string, flags?: Parameters[0]) { }).pipe( Effect.provide( Plugin.layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(RuntimeFlags.layer({ disableDefaultPlugins: true, ...flags })), Layer.provide( TestConfig.layer({ diff --git a/packages/opencode/test/plugin/openai-rollout.test.ts b/packages/opencode/test/plugin/openai-rollout.test.ts new file mode 100644 index 000000000000..1278e1cfbb3a --- /dev/null +++ b/packages/opencode/test/plugin/openai-rollout.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, test } from "bun:test" +import { experimentalWebSocketsEnabled } from "../../src/plugin" + +describe("plugin.openai.websocket rollout", () => { + test("enables websockets by default only on pre-release channels", () => { + expect(experimentalWebSocketsEnabled({ enabled: false, channel: "local" })).toBe(true) + expect(experimentalWebSocketsEnabled({ enabled: false, channel: "dev" })).toBe(true) + expect(experimentalWebSocketsEnabled({ enabled: false, channel: "beta" })).toBe(true) + expect(experimentalWebSocketsEnabled({ enabled: false, channel: "latest" })).toBe(false) + expect(experimentalWebSocketsEnabled({ enabled: false, channel: "prod" })).toBe(false) + }) + + test("allows releases to opt in through the experimental flag", () => { + expect(experimentalWebSocketsEnabled({ enabled: true, channel: "latest" })).toBe(true) + expect(experimentalWebSocketsEnabled({ enabled: true, channel: "prod" })).toBe(true) + }) +}) diff --git a/packages/opencode/test/plugin/openai-ws.test.ts b/packages/opencode/test/plugin/openai-ws.test.ts new file mode 100644 index 000000000000..dcb31199c41e --- /dev/null +++ b/packages/opencode/test/plugin/openai-ws.test.ts @@ -0,0 +1,711 @@ +import { describe, expect, test } from "bun:test" +import { EventEmitter } from "node:events" +import { createServer, type IncomingMessage, type Server as HttpServer } from "node:http" +import net, { type AddressInfo, type Socket } from "node:net" +import WebSocket, { WebSocketServer } from "ws" +import { ProviderError } from "../../src/provider/error" +import { OpenAIWebSocket } from "../../src/plugin/openai/ws" +import { OpenAIWebSocketPool, TITLE_HEADER } from "../../src/plugin/openai/ws-pool" + +describe("plugin.openai.ws", () => { + test("derives websocket URLs and sends auth plus protocol headers", async () => { + let headers: IncomingMessage["headers"] | undefined + await using server = await createWebSocketServer((_socket, request) => { + headers = request.headers + }) + + const socket = await OpenAIWebSocket.connectResponsesWebSocket({ + url: server.wsUrl, + headers: { authorization: "Bearer test", "content-length": "123" }, + }) + + expect(OpenAIWebSocket.toWebSocketUrl("http://example.com/v1/responses")).toBe("ws://example.com/v1/responses") + expect(OpenAIWebSocket.toWebSocketUrl("https://example.com/v1/responses")).toBe("wss://example.com/v1/responses") + expect(headers?.authorization).toBe("Bearer test") + expect(headers?.["openai-beta"]).toBe(OpenAIWebSocket.PROTOCOL_HEADER) + expect(headers?.["content-length"]).toBeUndefined() + socket.terminate() + }) + + test("enforces websocket connect timeout", async () => { + await using server = await createHangingTcpServer() + + await expect( + OpenAIWebSocket.connectResponsesWebSocket({ + url: server.wsUrl, + headers: {}, + timeout: 20, + }), + ).rejects.toThrow("WebSocket connect timed out") + }) + + test("surfaces websocket upgrade rejection messages", async () => { + await using server = await createRejectingWebSocketServer(() => {}) + + await expect( + OpenAIWebSocket.connectResponsesWebSocket({ + url: server.wsUrl, + headers: {}, + }), + ).rejects.toThrow("Expected 101 status code") + }) + + test("enforces websocket send idle timeout", async () => { + const socket = new (class extends EventEmitter { + send(_data: string, _callback: (error?: Error) => void) {} + })() as unknown as WebSocket + const invalid: string[] = [] + const response = OpenAIWebSocket.streamResponsesWebSocket({ + socket, + body: { stream: true, input: "hi" }, + idleTimeout: 20, + onConnectionInvalid: (error) => invalid.push(error.message), + }) + + expect((await readTextError(response.text())).message).toContain("idle timeout sending websocket request") + expect(invalid).toEqual(["idle timeout sending websocket request"]) + }) + + test("streams websocket events as SSE and handles response.done", async () => { + let requestBody: unknown + await using server = await createWebSocketServer((socket) => { + socket.once("message", (data) => { + requestBody = JSON.parse(data.toString()) + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "hello" })) + socket.send(JSON.stringify({ type: "response.done", response: { id: "resp_123" } })) + socket.close(1000, "done") + }) + }) + + const socket = await OpenAIWebSocket.connectResponsesWebSocket({ + url: server.wsUrl, + headers: { authorization: "Bearer test", "content-length": "123" }, + }) + const completed: Record[] = [] + const response = OpenAIWebSocket.streamResponsesWebSocket({ + socket, + body: { stream: true, background: true, input: "hi" }, + onComplete: (event) => completed.push(event), + }) + + expect(await response.text()).toBe( + 'data: {"type":"response.output_text.delta","delta":"hello"}\n\ndata: {"type":"response.done","response":{"id":"resp_123"}}\n\ndata: [DONE]\n\n', + ) + expect(requestBody).toEqual({ type: "response.create", input: "hi" }) + expect(completed).toHaveLength(1) + expect(completed[0]?.type).toBe("response.done") + }) + + test("errors the SSE stream when the server closes before a terminal event", async () => { + const invalid: Error[] = [] + await using server = await createWebSocketServer((socket) => { + socket.once("message", () => { + socket.close(1009, "payload too large") + }) + }) + + const socket = await OpenAIWebSocket.connectResponsesWebSocket({ url: server.wsUrl, headers: {} }) + const response = OpenAIWebSocket.streamResponsesWebSocket({ + socket, + body: { stream: true, input: "hi" }, + onConnectionInvalid: (error) => invalid.push(error), + }) + + expect((await readTextError(response.text())).message).toContain( + "WebSocket closed before response.completed (code 1009: message too big: payload too large)", + ) + expect(invalid[0]).toBeInstanceOf(ProviderError.ResponseStreamError) + expect(invalid.map((error) => error.message)).toEqual([ + "WebSocket closed before response.completed (code 1009: message too big: payload too large)", + ]) + }) + + test("rejects unexpected binary websocket frames", async () => { + const invalid: string[] = [] + await using server = await createWebSocketServer((socket) => { + socket.once("message", () => { + socket.send(Buffer.from("not json text")) + }) + }) + + const socket = await OpenAIWebSocket.connectResponsesWebSocket({ url: server.wsUrl, headers: {} }) + const response = OpenAIWebSocket.streamResponsesWebSocket({ + socket, + body: { stream: true, input: "hi" }, + onConnectionInvalid: (error) => invalid.push(error.message), + }) + + expect((await readTextError(response.text())).message).toContain("Unexpected binary WebSocket frame") + expect(invalid).toEqual(["Unexpected binary WebSocket frame"]) + }) +}) + +describe("plugin.openai.ws-pool", () => { + test("reuses one healthy websocket for sequential requests", async () => { + let connections = 0 + let messages = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.on("message", () => { + messages += 1 + socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${messages}` } })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + }) + + const first = await fetch(server.url, streamRequest()) + expect(await first.text()).toContain("data: [DONE]") + + const second = await fetch(server.url, streamRequest()) + expect(await second.text()).toContain("data: [DONE]") + expect(connections).toBe(1) + expect(messages).toBe(2) + fetch.close() + }) + + test("rotates a socket that exceeds max connection age", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.on("message", () => { + socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${connections}` } })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + maxConnectionAge: 0, + }) + + const first = await fetch(server.url, streamRequest()) + expect(await first.text()).toContain("data: [DONE]") + + const second = await fetch(server.url, streamRequest()) + expect(await second.text()).toContain("data: [DONE]") + expect(connections).toBe(2) + fetch.close() + }) + + test("falls back to HTTP after websocket setup retries are exhausted", async () => { + const attempts: string[] = [] + await using server = await createRejectingWebSocketServer(() => attempts.push("websocket")) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + connectTimeout: 100, + streamRetries: 1, + }) + + const first = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "false" })) + expect(await readTextError(first.text())).toBeInstanceOf(ProviderError.ResponseStreamError) + const second = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "false" })) + const third = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "false" })) + + expect(await second.text()).toBe("http") + expect(await third.text()).toBe("http") + expect(attempts).toEqual(["websocket", "websocket"]) + expect(server.httpRequests).toHaveLength(2) + expect(server.httpRequests[0]?.headers[TITLE_HEADER]).toBeUndefined() + expect(server.httpRequests[1]?.headers[TITLE_HEADER]).toBeUndefined() + fetch.close() + }) + + test("prunes HTTP fallback after its idle timeout", async () => { + let websocketAttempts = 0 + await using server = await createRejectingWebSocketServer(() => websocketAttempts++) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + connectTimeout: 100, + idleTimeout: 20, + streamRetries: 0, + }) + + const first = await fetch(server.url, streamRequest()) + expect(await first.text()).toBe("http") + await new Promise((resolve) => setTimeout(resolve, 50)) + const second = await fetch(server.url, streamRequest()) + + expect(await second.text()).toBe("http") + expect(websocketAttempts).toBe(2) + expect(server.httpRequests).toHaveLength(2) + fetch.close() + }) + + test("invalidates but does not reuse a socket after terminal failure frames", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + socket.send(JSON.stringify({ type: connections === 1 ? "response.failed" : "response.completed" })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + }) + + const first = await fetch(server.url, streamRequest()) + expect(await first.text()).toContain('data: {"type":"response.failed"}') + + const second = await fetch(server.url, streamRequest()) + expect(await second.text()).toContain('data: {"type":"response.completed"}') + expect(connections).toBe(2) + expect(server.httpRequests).toHaveLength(0) + fetch.close() + }) + + test("retries websocket connection limit errors on the next stream attempt", async () => { + let connections = 0 + let messages = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + messages += 1 + if (connections === 1) { + socket.send( + JSON.stringify({ + type: "error", + status: 400, + error: { + type: "invalid_request_error", + code: "websocket_connection_limit_reached", + message: "Responses websocket connection limit reached", + }, + }), + ) + return + } + socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_retry" } })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("Responses websocket connection limit reached") + const second = await fetch(server.url, streamRequest()) + const text = await second.text() + + expect(text).not.toContain("websocket_connection_limit_reached") + expect(text).toContain('data: {"type":"response.completed","response":{"id":"resp_retry"}}') + expect(text).toContain("data: [DONE]") + expect(connections).toBe(2) + expect(messages).toBe(2) + expect(server.httpRequests).toHaveLength(0) + fetch.close() + }) + + test("falls back to HTTP after websocket connection limit retries are exhausted", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + socket.send( + JSON.stringify({ + type: "error", + status: 400, + error: { + type: "invalid_request_error", + code: "websocket_connection_limit_reached", + message: "Responses websocket connection limit reached", + }, + }), + ) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + streamRetries: 2, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("Responses websocket connection limit reached") + const second = await fetch(server.url, streamRequest()) + expect((await readTextError(second.text())).message).toContain("Responses websocket connection limit reached") + const third = await fetch(server.url, streamRequest()) + const fourth = await fetch(server.url, streamRequest()) + + expect(await third.text()).toBe("http") + expect(await fourth.text()).toBe("http") + expect(connections).toBe(3) + expect(server.httpRequests).toHaveLength(2) + fetch.close() + }) + + test("shares the websocket retry budget across stream and connection limit failures", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + if (connections === 1) { + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" })) + socket.terminate() + return + } + socket.send( + JSON.stringify({ + type: "error", + error: { + code: "websocket_connection_limit_reached", + message: "Responses websocket connection limit reached", + }, + }), + ) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + streamRetries: 1, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("WebSocket closed before response.completed") + const second = await fetch(server.url, streamRequest()) + + expect(await second.text()).toBe("http") + expect(connections).toBe(2) + expect(server.httpRequests).toHaveLength(1) + fetch.close() + }) + + test("retries websocket idle failures before first event then falls back to HTTP", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => {}) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + idleTimeout: 20, + streamRetries: 1, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("idle timeout waiting for websocket") + const second = await fetch(server.url, streamRequest()) + const third = await fetch(server.url, streamRequest()) + + expect(await second.text()).toBe("http") + expect(await third.text()).toBe("http") + expect(connections).toBe(2) + expect(server.httpRequests).toHaveLength(2) + fetch.close() + }) + + test("retries failed websocket streams before using HTTP fallback", async () => { + await using server = await createWebSocketServer((socket) => { + socket.once("message", () => { + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + idleTimeout: 20, + streamRetries: 1, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("idle timeout waiting for websocket") + const second = await fetch(server.url, streamRequest()) + expect((await readTextError(second.text())).message).toContain("idle timeout waiting for websocket") + const third = await fetch(server.url, streamRequest()) + + expect(await third.text()).toBe("http") + expect(server.httpRequests).toHaveLength(1) + fetch.close() + }) + + test("resets websocket stream failures after a completed response", async () => { + let connections = 0 + let requests = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.on("message", () => { + requests += 1 + if (requests === 1 || requests === 3) { + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" })) + socket.terminate() + return + } + socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${requests}` } })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + streamRetries: 1, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("WebSocket closed before response.completed") + const second = await fetch(server.url, streamRequest()) + expect(await second.text()).toContain("data: [DONE]") + const third = await fetch(server.url, streamRequest()) + expect((await readTextError(third.text())).message).toContain("WebSocket closed before response.completed") + const fourth = await fetch(server.url, streamRequest()) + + expect(await fourth.text()).toContain("data: [DONE]") + expect(connections).toBe(3) + expect(requests).toBe(4) + expect(server.httpRequests).toHaveLength(0) + fetch.close() + }) + + test("falls back to HTTP for missing session and title requests", async () => { + await using server = await createWebSocketServer(() => {}) + const fetch = OpenAIWebSocketPool.createWebSocketFetch() + + const missingSession = await fetch(server.url, { + method: "POST", + headers: { [TITLE_HEADER]: "false" }, + body: JSON.stringify({ stream: true }), + }) + const title = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "true" })) + + expect(await missingSession.text()).toBe("http") + expect(await title.text()).toBe("http") + expect(server.httpRequests).toHaveLength(2) + expect(server.httpRequests[0]?.headers[TITLE_HEADER]).toBeUndefined() + expect(server.httpRequests[1]?.headers[TITLE_HEADER]).toBeUndefined() + fetch.close() + }) + + test("falls back to HTTP while a websocket lane is busy", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" })) + }) + }) + const abort = new AbortController() + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + }) + + const first = await fetch(server.url, streamRequest({}, abort.signal)) + const firstText = first.text() + await waitFor(() => connections === 1, "websocket did not connect") + const second = await fetch(server.url, streamRequest()) + + expect(await second.text()).toBe("http") + expect(server.httpRequests).toHaveLength(1) + expect(connections).toBe(1) + abort.abort(new Error("stop")) + expect((await readTextError(firstText)).message).toContain("stop") + fetch.close() + }) + + test("reserves a websocket lane while its socket is connecting", async () => { + await using server = await createHangingTcpServer() + await using fallback = await createHttpServer() + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + connectTimeout: 20, + streamRetries: 0, + }) + + const first = fetch(fallback.url, streamRequest()) + await waitFor(() => server.connections() === 1, "first websocket did not begin connecting") + const second = fetch(fallback.url, streamRequest()) + + expect(await (await second).text()).toBe("http") + expect(await (await first).text()).toBe("http") + expect(server.connections()).toBe(1) + expect(fallback.httpRequests).toHaveLength(2) + fetch.close() + }) + + test("retries unexpected closes before first event then falls back to HTTP", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + socket.close(1001, "server shutdown") + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + streamRetries: 1, + }) + + const first = await fetch(server.url, streamRequest()) + expect((await readTextError(first.text())).message).toContain("WebSocket closed before response.completed") + const second = await fetch(server.url, streamRequest()) + const third = await fetch(server.url, streamRequest()) + + expect(await second.text()).toBe("http") + expect(await third.text()).toBe("http") + expect(connections).toBe(2) + expect(server.httpRequests).toHaveLength(2) + fetch.close() + }) + + test("does not keep HTTP fallback active after aborting a websocket response", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + if (connections === 1) { + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" })) + return + } + socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_456" } })) + }) + }) + const abort = new AbortController() + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + }) + + const first = await fetch(server.url, streamRequest({}, abort.signal)) + const firstText = first.text() + await waitFor(() => connections === 1, "first websocket did not connect") + abort.abort(new Error("stop")) + expect((await readTextError(firstText)).message).toContain("stop") + + const second = await fetch(server.url, streamRequest()) + + expect(await second.text()).toContain("data: [DONE]") + expect(connections).toBe(2) + expect(server.httpRequests).toHaveLength(0) + fetch.close() + }) + + test("releases the websocket lane when the response body is cancelled", async () => { + let connections = 0 + await using server = await createWebSocketServer((socket) => { + connections += 1 + socket.once("message", () => { + if (connections === 1) { + socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" })) + return + } + socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_after_cancel" } })) + }) + }) + const fetch = OpenAIWebSocketPool.createWebSocketFetch({ + url: server.url, + }) + + const first = await fetch(server.url, streamRequest()) + await waitFor(() => connections === 1, "first websocket did not connect") + await first.body!.cancel("stop") + + const second = await fetch(server.url, streamRequest()) + + expect(await second.text()).toContain("data: [DONE]") + expect(connections).toBe(2) + expect(server.httpRequests).toHaveLength(0) + fetch.close() + }) +}) + +function streamRequest(headers?: Record, signal?: AbortSignal): RequestInit { + return { + method: "POST", + headers: { + "session-id": "session-1", + authorization: "Bearer test", + ...headers, + }, + body: JSON.stringify({ stream: true, input: "hi" }), + signal, + } +} + +async function readTextError(promise: Promise) { + // Bun 1.3.14 hangs on expect(response.text()).rejects for streams errored from ws callbacks. + return promise.then( + () => { + throw new Error("Expected response text to reject") + }, + (error) => { + expect(error).toBeInstanceOf(Error) + return error as Error + }, + ) +} + +async function createWebSocketServer(onConnection: (socket: WebSocket, request: IncomingMessage) => void) { + const http = await createHttpServer() + const server = new WebSocketServer({ server: http.server }) + server.on("connection", onConnection) + return websocketServerHandle(server, http) +} + +async function createHangingTcpServer() { + const sockets = new Set() + let connections = 0 + const server = net.createServer((socket) => { + connections += 1 + sockets.add(socket) + socket.on("close", () => sockets.delete(socket)) + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + const address = server.address() as AddressInfo + return { + url: `http://127.0.0.1:${address.port}/v1/responses`, + wsUrl: `ws://127.0.0.1:${address.port}/v1/responses`, + connections: () => connections, + async [Symbol.asyncDispose]() { + for (const socket of sockets) socket.destroy() + server.close() + }, + } +} + +async function createRejectingWebSocketServer(onAttempt: () => void) { + const http = await createHttpServer() + const server = new WebSocketServer({ + server: http.server, + verifyClient(_info, callback) { + onAttempt() + callback(false, 401, "denied") + }, + }) + return websocketServerHandle(server, http) +} + +async function createHttpServer() { + const httpRequests: IncomingMessage[] = [] + const server = createServer((request, response) => { + httpRequests.push(request) + response.writeHead(200, { "content-type": "text/plain" }) + response.end("http") + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + const address = server.address() as AddressInfo + return { + server, + httpRequests, + url: `http://127.0.0.1:${address.port}/v1/responses`, + async [Symbol.asyncDispose]() { + await closeHttpServer(server) + }, + } +} + +function websocketServerHandle(server: WebSocketServer, http: Awaited>) { + return { + url: http.url, + wsUrl: http.url.replace(/^http/, "ws"), + httpRequests: http.httpRequests, + async [Symbol.asyncDispose]() { + for (const socket of server.clients) socket.terminate() + server.close() + http.server.close() + }, + } +} + +function closeHttpServer(server: HttpServer) { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) +} + +async function waitFor(predicate: () => boolean, message: string) { + const started = Date.now() + while (!predicate()) { + if (Date.now() - started > 1_000) throw new Error(message) + await new Promise((resolve) => setTimeout(resolve, 1)) + } +} diff --git a/packages/opencode/test/plugin/trigger.test.ts b/packages/opencode/test/plugin/trigger.test.ts index 3716bc3aca5e..a3ed8334a554 100644 --- a/packages/opencode/test/plugin/trigger.test.ts +++ b/packages/opencode/test/plugin/trigger.test.ts @@ -6,17 +6,18 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem" import { EffectFlock } from "@opencode-ai/core/util/effect-flock" import path from "path" import { pathToFileURL } from "url" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "../../src/config/config" import { Env } from "../../src/env" import { RuntimeFlags } from "../../src/effect/runtime-flags" import { Plugin } from "../../src/plugin/index" -import { ModelID, ProviderID } from "../../src/provider/schema" -import { provideTmpdirInstance } from "../fixture/fixture" + +import { TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { AccountTest } from "../fake/account" import { AuthTest } from "../fake/auth" import { NpmTest } from "../fake/npm" +import { ProviderV2 } from "@opencode-ai/core/provider" const configLayer = Config.layer.pipe( Layer.provide(EffectFlock.defaultLayer), @@ -30,7 +31,7 @@ const configLayer = Config.layer.pipe( const it = testEffect( Layer.mergeAll( Plugin.layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(configLayer), Layer.provide(RuntimeFlags.layer({ disableDefaultPlugins: true })), ), @@ -40,31 +41,30 @@ const it = testEffect( const systemHook = "experimental.chat.system.transform" function withProject(source: string, self: Effect.Effect) { - return provideTmpdirInstance((dir) => - Effect.gen(function* () { - const file = path.join(dir, "plugin.ts") - yield* Effect.all( - [ - Effect.promise(() => Bun.write(file, source)), - Effect.promise(() => - Bun.write( - path.join(dir, "opencode.json"), - JSON.stringify( - { - $schema: "https://opencode.ai/config.json", - plugin: [pathToFileURL(file).href], - }, - null, - 2, - ), + return Effect.gen(function* () { + const test = yield* TestInstance + const file = path.join(test.directory, "plugin.ts") + yield* Effect.all( + [ + Effect.promise(() => Bun.write(file, source)), + Effect.promise(() => + Bun.write( + path.join(test.directory, "opencode.json"), + JSON.stringify( + { + $schema: "https://opencode.ai/config.json", + plugin: [pathToFileURL(file).href], + }, + null, + 2, ), ), - ], - { discard: true, concurrency: 2 }, - ) - return yield* self - }), - ) + ), + ], + { discard: true, concurrency: 2 }, + ) + return yield* self + }) } const triggerSystemTransform = Effect.fn("PluginTriggerTest.triggerSystemTransform")(function* () { @@ -74,8 +74,8 @@ const triggerSystemTransform = Effect.fn("PluginTriggerTest.triggerSystemTransfo systemHook, { model: { - providerID: ProviderID.anthropic, - modelID: ModelID.make("claude-sonnet-4-6"), + providerID: ProviderV2.ID.anthropic, + modelID: ProviderV2.ModelID.make("claude-sonnet-4-6"), }, }, out, @@ -84,7 +84,7 @@ const triggerSystemTransform = Effect.fn("PluginTriggerTest.triggerSystemTransfo }) describe("plugin.trigger", () => { - it.live("runs synchronous hooks without crashing", () => + it.instance("runs synchronous hooks without crashing", () => withProject( [ "export default async () => ({", @@ -100,7 +100,7 @@ describe("plugin.trigger", () => { ), ) - it.live("awaits asynchronous hooks", () => + it.instance("awaits asynchronous hooks", () => withProject( [ "export default async () => ({", diff --git a/packages/opencode/test/plugin/workspace-adapter.test.ts b/packages/opencode/test/plugin/workspace-adapter.test.ts index 79964d3deeb7..7fcc26cec697 100644 --- a/packages/opencode/test/plugin/workspace-adapter.test.ts +++ b/packages/opencode/test/plugin/workspace-adapter.test.ts @@ -2,12 +2,13 @@ import { afterEach, describe, expect } from "bun:test" import { Effect, Layer } from "effect" import { FetchHttpClient } from "effect/unstable/http" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { Database } from "@opencode-ai/core/database/database" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { EffectFlock } from "@opencode-ai/core/util/effect-flock" import path from "path" import { pathToFileURL } from "url" import { Auth } from "../../src/auth" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "../../src/config/config" import { Env } from "../../src/env" import { RuntimeFlags } from "../../src/effect/runtime-flags" @@ -20,8 +21,7 @@ import { Vcs } from "../../src/project/vcs" import { InstanceState } from "../../src/effect/instance-state" import { Session } from "../../src/session/session" import { SessionPrompt } from "../../src/session/prompt" -import { SyncEvent } from "../../src/sync" -import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture" +import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { AccountTest } from "../fake/account" import { AuthTest } from "../fake/auth" @@ -37,7 +37,7 @@ const configLayer = Config.layer.pipe( Layer.provide(FetchHttpClient.layer), ) const pluginLayer = Plugin.layer.pipe( - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(configLayer), Layer.provide(RuntimeFlags.layer({ disableDefaultPlugins: true })), ) @@ -45,11 +45,12 @@ const noopBootstrapLayer = Layer.succeed(InstanceBootstrap.Service, InstanceBoot const workspaceLayer = Workspace.layer.pipe( Layer.provide(Auth.defaultLayer), Layer.provide(Session.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(SessionPrompt.defaultLayer), Layer.provide(Project.defaultLayer), Layer.provide(Vcs.defaultLayer), Layer.provide(FetchHttpClient.layer), + Layer.provide(Database.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrapLayer))), Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: true })), @@ -61,77 +62,76 @@ afterEach(async () => { }) describe("plugin.workspace", () => { - it.live("plugin can install a workspace adapter", () => - provideTmpdirInstance((dir) => - Effect.gen(function* () { - const type = `plug-${Math.random().toString(36).slice(2)}` - const file = path.join(dir, "plugin.ts") - const mark = path.join(dir, "created.json") - const space = path.join(dir, "space") - yield* Effect.promise(() => - Bun.write( - file, - [ - "export default async ({ experimental_workspace }) => {", - ` experimental_workspace.register(${JSON.stringify(type)}, {`, - ' name: "plug",', - ' description: "plugin workspace adapter",', - " configure(input) {", - ` return { ...input, name: "plug", branch: "plug/main", directory: ${JSON.stringify(space)} }`, - " },", - " async create(input) {", - ` await Bun.write(${JSON.stringify(mark)}, JSON.stringify(input))`, - " },", - " async remove() {},", - " target(input) {", - ' return { type: "local", directory: input.directory }', - " },", - " })", - " return {}", - "}", - "", - ].join("\n"), - ), - ) + it.instance("plugin can install a workspace adapter", () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const type = `plug-${Math.random().toString(36).slice(2)}` + const file = path.join(dir, "plugin.ts") + const mark = path.join(dir, "created.json") + const space = path.join(dir, "space") + yield* Effect.promise(() => + Bun.write( + file, + [ + "export default async ({ experimental_workspace }) => {", + ` experimental_workspace.register(${JSON.stringify(type)}, {`, + ' name: "plug",', + ' description: "plugin workspace adapter",', + " configure(input) {", + ` return { ...input, name: "plug", branch: "plug/main", directory: ${JSON.stringify(space)} }`, + " },", + " async create(input) {", + ` await Bun.write(${JSON.stringify(mark)}, JSON.stringify(input))`, + " },", + " async remove() {},", + " target(input) {", + ' return { type: "local", directory: input.directory }', + " },", + " })", + " return {}", + "}", + "", + ].join("\n"), + ), + ) - yield* Effect.promise(() => - Bun.write( - path.join(dir, "opencode.json"), - JSON.stringify( - { - $schema: "https://opencode.ai/config.json", - plugin: [pathToFileURL(file).href], - }, - null, - 2, - ), + yield* Effect.promise(() => + Bun.write( + path.join(dir, "opencode.json"), + JSON.stringify( + { + $schema: "https://opencode.ai/config.json", + plugin: [pathToFileURL(file).href], + }, + null, + 2, ), - ) + ), + ) - const plugin = yield* Plugin.Service - yield* plugin.init() - const workspace = yield* Workspace.Service - const ctx = yield* InstanceState.context - const info = yield* workspace.create({ - type, - branch: null, - extra: { key: "value" }, - projectID: ctx.project.id, - }) + const plugin = yield* Plugin.Service + yield* plugin.init() + const workspace = yield* Workspace.Service + const ctx = yield* InstanceState.context + const info = yield* workspace.create({ + type, + branch: null, + extra: { key: "value" }, + projectID: ctx.project.id, + }) - expect(info.type).toBe(type) - expect(info.name).toBe("plug") - expect(info.branch).toBe("plug/main") - expect(info.directory).toBe(space) - expect(info.extra).toEqual({ key: "value" }) - expect(JSON.parse(yield* Effect.promise(() => Bun.file(mark).text()))).toMatchObject({ - type, - name: "plug", - branch: "plug/main", - directory: space, - extra: { key: "value" }, - }) - }), - ), + expect(info.type).toBe(type) + expect(info.name).toBe("plug") + expect(info.branch).toBe("plug/main") + expect(info.directory).toBe(space) + expect(info.extra).toEqual({ key: "value" }) + expect(JSON.parse(yield* Effect.promise(() => Bun.file(mark).text()))).toMatchObject({ + type, + name: "plug", + branch: "plug/main", + directory: space, + extra: { key: "value" }, + }) + }), ) }) diff --git a/packages/opencode/test/preload.ts b/packages/opencode/test/preload.ts index 24b804819ed3..1e9567c59294 100644 --- a/packages/opencode/test/preload.ts +++ b/packages/opencode/test/preload.ts @@ -10,8 +10,6 @@ import { afterAll } from "bun:test" const dir = path.join(os.tmpdir(), "opencode-test-data-" + process.pid) await fs.mkdir(dir, { recursive: true }) afterAll(async () => { - const { Database } = await import("../src/storage/db") - Database.close() const busy = (error: unknown) => typeof error === "object" && error !== null && "code" in error && error.code === "EBUSY" const rm = async (left: number): Promise => { @@ -75,6 +73,11 @@ delete process.env["CEREBRAS_API_KEY"] delete process.env["SAMBANOVA_API_KEY"] delete process.env["OPENCODE_SERVER_PASSWORD"] delete process.env["OPENCODE_SERVER_USERNAME"] +delete process.env["OPENCODE_EXPERIMENTAL"] +delete process.env["OPENCODE_ENABLE_EXPERIMENTAL_MODELS"] +delete process.env["OTEL_EXPORTER_OTLP_ENDPOINT"] +delete process.env["OTEL_EXPORTER_OTLP_HEADERS"] +delete process.env["OTEL_RESOURCE_ATTRIBUTES"] // Use in-memory sqlite process.env["OPENCODE_DB"] = ":memory:" diff --git a/packages/opencode/test/project/migrate-global.test.ts b/packages/opencode/test/project/migrate-global.test.ts index 6efd670c5c98..006ae2473a5b 100644 --- a/packages/opencode/test/project/migrate-global.test.ts +++ b/packages/opencode/test/project/migrate-global.test.ts @@ -1,10 +1,10 @@ import { describe, expect } from "bun:test" import { Project } from "@/project/project" -import { Database } from "@/storage/db" +import { Database } from "@opencode-ai/core/database/database" import { eq } from "drizzle-orm" -import { SessionTable } from "../../src/session/session.sql" -import { ProjectTable } from "../../src/project/project.sql" -import { ProjectID } from "../../src/project/schema" +import { SessionTable } from "@opencode-ai/core/session/sql" +import { ProjectTable } from "@opencode-ai/core/project/sql" +import { ProjectV2 } from "@opencode-ai/core/project" import { SessionID } from "../../src/session/schema" import * as Log from "@opencode-ai/core/util/log" import { $ } from "bun" @@ -15,16 +15,16 @@ import { testEffect } from "../lib/effect" void Log.init({ print: false }) -const it = testEffect(Layer.mergeAll(Project.defaultLayer, CrossSpawnSpawner.defaultLayer)) +const it = testEffect(Layer.mergeAll(Project.defaultLayer, CrossSpawnSpawner.defaultLayer, Database.defaultLayer)) function legacySessionID() { // Global-session migration covers persisted IDs from before prefixed session IDs. return crypto.randomUUID() as SessionID } -function seed(opts: { id: SessionID; dir: string; project: ProjectID }) { +function seed(opts: { id: SessionID; dir: string; project: ProjectV2.ID }) { const now = Date.now() - Database.use((db) => + return Database.Service.use(({ db }) => db .insert(SessionTable) .values({ @@ -37,23 +37,25 @@ function seed(opts: { id: SessionID; dir: string; project: ProjectID }) { time_created: now, time_updated: now, }) - .run(), + .run() + .pipe(Effect.orDie), ) } function ensureGlobal() { - Database.use((db) => + return Database.Service.use(({ db }) => db .insert(ProjectTable) .values({ - id: ProjectID.global, + id: ProjectV2.ID.global, worktree: "/", time_created: Date.now(), time_updated: Date.now(), sandboxes: [], }) .onConflictDoNothing() - .run(), + .run() + .pipe(Effect.orDie), ) } @@ -68,20 +70,22 @@ describe("migrateFromGlobal", () => { yield* Effect.promise(() => $`git config commit.gpgsign false`.cwd(tmp).quiet()) const projects = yield* Project.Service const { project: pre } = yield* projects.fromDirectory(tmp) - expect(pre.id).toBe(ProjectID.global) + expect(pre.id).toBe(ProjectV2.ID.global) // 2. Seed a session under "global" with matching directory const id = legacySessionID() - yield* Effect.sync(() => seed({ id, dir: tmp, project: ProjectID.global })) + yield* seed({ id, dir: tmp, project: ProjectV2.ID.global }) // 3. Make a commit so the project gets a real ID yield* Effect.promise(() => $`git commit --allow-empty -m "root"`.cwd(tmp).quiet()) const { project: real } = yield* projects.fromDirectory(tmp) - expect(real.id).not.toBe(ProjectID.global) + expect(real.id).not.toBe(ProjectV2.ID.global) // 4. The session should have been migrated to the real project ID - const row = Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()) + const row = yield* Database.Service.use(({ db }) => + db.select().from(SessionTable).where(eq(SessionTable.id, id)).get().pipe(Effect.orDie), + ) expect(row).toBeDefined() expect(row!.project_id).toBe(real.id) }), @@ -93,22 +97,24 @@ describe("migrateFromGlobal", () => { const tmp = yield* tmpdirScoped({ git: true }) const projects = yield* Project.Service const { project } = yield* projects.fromDirectory(tmp) - expect(project.id).not.toBe(ProjectID.global) + expect(project.id).not.toBe(ProjectV2.ID.global) // 2. Ensure "global" project row exists (as it would from a prior no-git session) - yield* Effect.sync(() => ensureGlobal()) + yield* ensureGlobal() // 3. Seed a session under "global" with matching directory. // This simulates a session created before git init that wasn't // present when the real project row was first created. const id = legacySessionID() - yield* Effect.sync(() => seed({ id, dir: tmp, project: ProjectID.global })) + yield* seed({ id, dir: tmp, project: ProjectV2.ID.global }) // 4. Call fromDirectory again — project row already exists, // so the current code skips migration entirely. This is the bug. yield* projects.fromDirectory(tmp) - const row = Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()) + const row = yield* Database.Service.use(({ db }) => + db.select().from(SessionTable).where(eq(SessionTable.id, id)).get().pipe(Effect.orDie), + ) expect(row).toBeDefined() expect(row!.project_id).toBe(project.id) }), @@ -119,20 +125,22 @@ describe("migrateFromGlobal", () => { const tmp = yield* tmpdirScoped({ git: true }) const projects = yield* Project.Service const { project } = yield* projects.fromDirectory(tmp) - expect(project.id).not.toBe(ProjectID.global) + expect(project.id).not.toBe(ProjectV2.ID.global) - yield* Effect.sync(() => ensureGlobal()) + yield* ensureGlobal() // Legacy sessions may lack a directory value. // Without a matching origin directory, they should remain global. const id = legacySessionID() - yield* Effect.sync(() => seed({ id, dir: "", project: ProjectID.global })) + yield* seed({ id, dir: "", project: ProjectV2.ID.global }) yield* projects.fromDirectory(tmp) - const row = Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()) + const row = yield* Database.Service.use(({ db }) => + db.select().from(SessionTable).where(eq(SessionTable.id, id)).get().pipe(Effect.orDie), + ) expect(row).toBeDefined() - expect(row!.project_id).toBe(ProjectID.global) + expect(row!.project_id).toBe(ProjectV2.ID.global) }), ) @@ -141,19 +149,21 @@ describe("migrateFromGlobal", () => { const tmp = yield* tmpdirScoped({ git: true }) const projects = yield* Project.Service const { project } = yield* projects.fromDirectory(tmp) - expect(project.id).not.toBe(ProjectID.global) + expect(project.id).not.toBe(ProjectV2.ID.global) - yield* Effect.sync(() => ensureGlobal()) + yield* ensureGlobal() // Seed a session under "global" but for a DIFFERENT directory const id = legacySessionID() - yield* Effect.sync(() => seed({ id, dir: "/some/other/dir", project: ProjectID.global })) + yield* seed({ id, dir: "/some/other/dir", project: ProjectV2.ID.global }) yield* projects.fromDirectory(tmp) - const row = Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()) + const row = yield* Database.Service.use(({ db }) => + db.select().from(SessionTable).where(eq(SessionTable.id, id)).get().pipe(Effect.orDie), + ) expect(row).toBeDefined() // Should remain under "global" — not stolen - expect(row!.project_id).toBe(ProjectID.global) + expect(row!.project_id).toBe(ProjectV2.ID.global) }), ) }) diff --git a/packages/opencode/test/project/project.test.ts b/packages/opencode/test/project/project.test.ts index 869326d87acc..c10c4233745f 100644 --- a/packages/opencode/test/project/project.test.ts +++ b/packages/opencode/test/project/project.test.ts @@ -1,27 +1,25 @@ -import { describe, expect, test } from "bun:test" -import { Bus } from "@/bus" +import { describe, expect } from "bun:test" +import { EventV2Bridge } from "@/event-v2-bridge" import { Project } from "@/project/project" import * as Log from "@opencode-ai/core/util/log" import { $ } from "bun" import path from "path" import { tmpdirScoped } from "../fixture/fixture" import { GlobalBus } from "../../src/bus/global" -import { ProjectID } from "../../src/project/schema" -import { Database } from "@/storage/db" -import { ProjectTable } from "@/project/project.sql" -import { SessionTable } from "@/session/session.sql" -import { PermissionTable } from "@/session/session.sql" -import { WorkspaceTable } from "@/control-plane/workspace.sql" +import { Database } from "@opencode-ai/core/database/database" +import { ProjectTable } from "@opencode-ai/core/project/sql" +import { PermissionTable, SessionTable } from "@opencode-ai/core/session/sql" +import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" import { eq } from "drizzle-orm" import { Hash } from "@opencode-ai/core/util/hash" import { SessionID } from "@/session/schema" -import { WorkspaceID } from "@/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { Cause, Effect, Exit, Layer, Stream } from "effect" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" import { NodePath } from "@effect/platform-node" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { AppProcess } from "@opencode-ai/core/process" -import { Project as ProjectV2 } from "@opencode-ai/core/project" +import { ProjectV2 } from "@opencode-ai/core/project" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { testEffect } from "../lib/effect" import { RuntimeFlags } from "@/effect/runtime-flags" @@ -30,18 +28,11 @@ void Log.init({ print: false }) const encoder = new TextEncoder() -const layer = Layer.mergeAll(Project.defaultLayer, CrossSpawnSpawner.defaultLayer) +const layer = Layer.mergeAll(Project.defaultLayer, Database.defaultLayer, CrossSpawnSpawner.defaultLayer) const it = testEffect(layer) -function run(fn: (svc: Project.Interface) => Effect.Effect) { - return Effect.gen(function* () { - const svc = yield* Project.Service - return yield* fn(svc) - }) -} - function remoteProjectID(remote: string) { - return ProjectID.make(Hash.fast(`git-remote:${remote}`)) + return ProjectV2.ID.make(Hash.fast(`git-remote:${remote}`)) } /** @@ -84,20 +75,22 @@ function projectLayerWithFailure(failArg: string) { Layer.provide(AppProcess.layer.pipe(Layer.provide(mockGitFailure(failArg)))), Layer.provide(mockGitFailure(failArg)), Layer.provide(ProjectV2.defaultLayer), - Layer.provide(Bus.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(NodePath.layer), + Layer.provide(Database.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), ) } function projectLayerWithRuntimeFlags(flags: Parameters[0]) { return Project.layer.pipe( - Layer.provide(Bus.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(ProjectV2.defaultLayer), Layer.provide(AppProcess.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(NodePath.layer), + Layer.provide(Database.defaultLayer), Layer.provide(RuntimeFlags.layer(flags)), ) } @@ -109,10 +102,11 @@ const iconDiscoveryIt = testEffect( Layer.provideMerge(projectLayerWithRuntimeFlags({ experimentalIconDiscovery: true }), CrossSpawnSpawner.defaultLayer), ) -function waitForProjectIcon(id: ProjectID, attempts = 50): Effect.Effect { +function waitForProjectIcon(id: ProjectV2.ID, attempts = 50): Effect.Effect { return Effect.gen(function* () { - const project = Project.get(id) - if (project?.icon?.url) return project + const project = yield* Project.Service + const info = yield* project.get(id) + if (info?.icon?.url) return info if (attempts <= 0) throw new Error(`Project icon was not discovered: ${id}`) yield* Effect.sleep("10 millis") return yield* waitForProjectIcon(id, attempts - 1) @@ -122,15 +116,16 @@ function waitForProjectIcon(id: ProjectID, attempts = 50): Effect.Effect { it.live("should handle git repository with no commits", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped() yield* Effect.promise(() => $`git init`.cwd(tmp).quiet()) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - expect(project).toBeDefined() - expect(project.id).toBe(ProjectID.global) - expect(project.vcs).toBe("git") - expect(project.worktree).toBe(tmp) + expect(result.project).toBeDefined() + expect(result.project.id).toBe(ProjectV2.ID.global) + expect(result.project.vcs).toBe("git") + expect(result.project.worktree).toBe(tmp) const opencodeFile = path.join(tmp, ".git", "opencode") expect(yield* Effect.promise(() => Bun.file(opencodeFile).exists())).toBe(false) @@ -139,117 +134,127 @@ describe("Project.fromDirectory", () => { it.live("should handle git repository with commits", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - expect(project).toBeDefined() - expect(project.id).not.toBe(ProjectID.global) - expect(project.vcs).toBe("git") - expect(project.worktree).toBe(tmp) + expect(result.project).toBeDefined() + expect(result.project.id).not.toBe(ProjectV2.ID.global) + expect(result.project.vcs).toBe("git") + expect(result.project.worktree).toBe(tmp) }), ) it.live("returns global for non-git directory", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped() - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) - expect(project.id).toBe(ProjectID.global) + const result = yield* project.fromDirectory(tmp) + expect(result.project.id).toBe(ProjectV2.ID.global) }), ) it.live("derives stable project ID from root commit", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project: a } = yield* run((svc) => svc.fromDirectory(tmp)) - const { project: b } = yield* run((svc) => svc.fromDirectory(tmp)) - expect(b.id).toBe(a.id) + const result = yield* project.fromDirectory(tmp) + const next = yield* project.fromDirectory(tmp) + expect(next.project.id).toBe(result.project.id) }), ) it.live("prefers normalized origin remote over root commit", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) yield* Effect.promise(() => $`git remote add origin git@github.com:Test-Org/Test-Repo.git`.cwd(tmp).quiet()) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - expect(project.id).toBe(remoteProjectID("github.com/Test-Org/Test-Repo")) + expect(result.project.id).toBe(remoteProjectID("github.com/Test-Org/Test-Repo")) }), ) it.live("normalizes equivalent origin URL forms to the same project ID", () => Effect.gen(function* () { + const project = yield* Project.Service const ssh = yield* tmpdirScoped({ git: true }) const https = yield* tmpdirScoped({ git: true }) yield* Effect.promise(() => $`git remote add origin git@github.com:owner/repo.git`.cwd(ssh).quiet()) yield* Effect.promise(() => $`git remote add origin https://github.com/owner/repo.git`.cwd(https).quiet()) - const { project: a } = yield* run((svc) => svc.fromDirectory(ssh)) - const { project: b } = yield* run((svc) => svc.fromDirectory(https)) + const result = yield* project.fromDirectory(ssh) + const next = yield* project.fromDirectory(https) - expect(a.id).toBe(remoteProjectID("github.com/owner/repo")) - expect(b.id).toBe(a.id) + expect(result.project.id).toBe(remoteProjectID("github.com/owner/repo")) + expect(next.project.id).toBe(result.project.id) }), ) it.live("migrates cached root project data when origin becomes available", () => Effect.gen(function* () { + const { db } = yield* Database.Service const tmp = yield* tmpdirScoped({ git: true }) const projects = yield* Project.Service - const { project: rootProject } = yield* projects.fromDirectory(tmp) + const rootResult = yield* projects.fromDirectory(tmp) + const rootProject = rootResult.project const remoteID = remoteProjectID("github.com/acme/app") const sessionID = crypto.randomUUID() as SessionID - const workspaceID = WorkspaceID.ascending() - - yield* Effect.sync(() => { - Database.use((db) => { - db.insert(SessionTable) - .values({ - id: sessionID, - project_id: rootProject.id, - slug: sessionID, - directory: tmp, - title: "test", - version: "0.0.0-test", - time_created: Date.now(), - time_updated: Date.now(), - }) - .run() - db.insert(PermissionTable) - .values({ - project_id: rootProject.id, - data: [{ permission: "edit", pattern: "*", action: "allow" }], - time_created: Date.now(), - time_updated: Date.now(), - }) - .run() - db.insert(WorkspaceTable) - .values({ - id: workspaceID, - type: "local", - name: "test", - project_id: rootProject.id, - }) - .run() + const workspaceID = WorkspaceV2.ID.ascending() + + yield* db + .insert(SessionTable) + .values({ + id: sessionID, + project_id: rootProject.id, + slug: sessionID, + directory: tmp, + title: "test", + version: "0.0.0-test", + time_created: Date.now(), + time_updated: Date.now(), }) - }) + .run() + .pipe(Effect.orDie) + yield* db + .insert(PermissionTable) + .values({ + project_id: rootProject.id, + data: [{ permission: "edit", pattern: "*", action: "allow" }], + time_created: Date.now(), + time_updated: Date.now(), + }) + .run() + .pipe(Effect.orDie) + yield* db + .insert(WorkspaceTable) + .values({ id: workspaceID, type: "local", name: "test", project_id: rootProject.id }) + .run() + .pipe(Effect.orDie) yield* Effect.promise(() => $`git remote add origin git@github.com:acme/app.git`.cwd(tmp).quiet()) - const { project } = yield* projects.fromDirectory(tmp) + const result = yield* projects.fromDirectory(tmp) - expect(project.id).toBe(remoteID) + expect(result.project.id).toBe(remoteID) expect( - Database.use((db) => db.select().from(ProjectTable).where(eq(ProjectTable.id, rootProject.id)).get()), + yield* db.select().from(ProjectTable).where(eq(ProjectTable.id, rootProject.id)).get().pipe(Effect.orDie), ).toBeUndefined() expect( - Database.use((db) => db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get())?.project_id, + (yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie)) + ?.project_id, ).toBe(remoteID) expect( - Database.use((db) => db.select().from(PermissionTable).where(eq(PermissionTable.project_id, remoteID)).get()), + yield* db + .select() + .from(PermissionTable) + .where(eq(PermissionTable.project_id, remoteID)) + .get() + .pipe(Effect.orDie), ).toBeDefined() expect( - Database.use((db) => db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).get()) + (yield* db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).get().pipe(Effect.orDie)) ?.project_id, ).toBe(remoteID) }), @@ -259,34 +264,37 @@ describe("Project.fromDirectory", () => { describe("Project.fromDirectory git failure paths", () => { it.live("keeps vcs when rev-list exits non-zero (no commits)", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped() yield* Effect.promise(() => $`git init`.cwd(tmp).quiet()) // rev-list fails because HEAD doesn't exist yet: this is the natural scenario. - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) - expect(project.vcs).toBe("git") - expect(project.id).toBe(ProjectID.global) - expect(project.worktree).toBe(tmp) + const result = yield* project.fromDirectory(tmp) + expect(result.project.vcs).toBe("git") + expect(result.project.id).toBe(ProjectV2.ID.global) + expect(result.project.worktree).toBe(tmp) }), ) failureIt("--show-toplevel").live("handles show-toplevel failure gracefully", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project, sandbox } = yield* run((svc) => svc.fromDirectory(tmp)) - expect(project.worktree).toBe(tmp) - expect(sandbox).toBe(tmp) + const result = yield* project.fromDirectory(tmp) + expect(result.project.worktree).toBe(tmp) + expect(result.sandbox).toBe(tmp) }), ) failureIt("--git-common-dir").live("handles git-common-dir failure gracefully", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project, sandbox } = yield* run((svc) => svc.fromDirectory(tmp)) - expect(project.worktree).toBe(tmp) - expect(sandbox).toBe(tmp) + const result = yield* project.fromDirectory(tmp) + expect(result.project.worktree).toBe(tmp) + expect(result.sandbox).toBe(tmp) }), ) }) @@ -294,18 +302,20 @@ describe("Project.fromDirectory git failure paths", () => { describe("Project.fromDirectory with worktrees", () => { it.live("should set worktree to root when called from root", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project, sandbox } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - expect(project.worktree).toBe(tmp) - expect(sandbox).toBe(tmp) - expect(project.sandboxes).not.toContain(tmp) + expect(result.project.worktree).toBe(tmp) + expect(result.sandbox).toBe(tmp) + expect(result.project.sandboxes).not.toContain(tmp) }), ) it.live("tracks a linked worktree as the opened project directory", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) const worktreePath = path.join(tmp, "..", path.basename(tmp) + "-worktree") @@ -319,20 +329,21 @@ describe("Project.fromDirectory with worktrees", () => { ) yield* Effect.promise(() => $`git worktree add ${worktreePath} -b test-branch-${Date.now()}`.cwd(tmp).quiet()) - const { project, sandbox } = yield* run((svc) => svc.fromDirectory(worktreePath)) + const result = yield* project.fromDirectory(worktreePath) - expect(project.worktree).toBe(worktreePath) - expect(sandbox).toBe(worktreePath) - expect(project.sandboxes).not.toContain(worktreePath) - expect(project.sandboxes).not.toContain(tmp) + expect(result.project.worktree).toBe(worktreePath) + expect(result.sandbox).toBe(worktreePath) + expect(result.project.sandboxes).not.toContain(worktreePath) + expect(result.project.sandboxes).not.toContain(tmp) }), ) it.live("worktree should share project ID with main repo", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project: main } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) const worktreePath = path.join(tmp, "..", path.basename(tmp) + "-wt-shared") yield* Effect.addFinalizer(() => @@ -345,9 +356,9 @@ describe("Project.fromDirectory with worktrees", () => { ) yield* Effect.promise(() => $`git worktree add ${worktreePath} -b shared-${Date.now()}`.cwd(tmp).quiet()) - const { project: wt } = yield* run((svc) => svc.fromDirectory(worktreePath)) + const next = yield* project.fromDirectory(worktreePath) - expect(wt.id).toBe(main.id) + expect(next.project.id).toBe(result.project.id) const cache = path.join(tmp, ".git", "opencode") const exists = yield* Effect.promise(() => Bun.file(cache).exists()) @@ -357,6 +368,7 @@ describe("Project.fromDirectory with worktrees", () => { it.live("separate clones of the same repo should share project ID", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) // Create a bare remote, push, then clone into a second directory @@ -368,15 +380,16 @@ describe("Project.fromDirectory with worktrees", () => { yield* Effect.promise(() => $`git clone --bare ${tmp} ${bare}`.quiet()) yield* Effect.promise(() => $`git clone ${bare} ${clone}`.quiet()) - const { project: a } = yield* run((svc) => svc.fromDirectory(tmp)) - const { project: b } = yield* run((svc) => svc.fromDirectory(clone)) + const result = yield* project.fromDirectory(tmp) + const next = yield* project.fromDirectory(clone) - expect(b.id).toBe(a.id) + expect(next.project.id).toBe(result.project.id) }), ) it.live("should accumulate multiple worktrees in sandboxes", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) const worktree1 = path.join(tmp, "..", path.basename(tmp) + "-wt1") @@ -400,12 +413,12 @@ describe("Project.fromDirectory with worktrees", () => { yield* Effect.promise(() => $`git worktree add ${worktree1} -b branch-${Date.now()}`.cwd(tmp).quiet()) yield* Effect.promise(() => $`git worktree add ${worktree2} -b branch-${Date.now() + 1}`.cwd(tmp).quiet()) - yield* run((svc) => svc.fromDirectory(worktree1)) - const { project } = yield* run((svc) => svc.fromDirectory(worktree2)) + yield* project.fromDirectory(worktree1) + const result = yield* project.fromDirectory(worktree2) - expect(project.worktree).toBe(worktree1) - expect(project.sandboxes).toContain(worktree2) - expect(project.sandboxes).not.toContain(tmp) + expect(result.project.worktree).toBe(worktree1) + expect(result.project.sandboxes).toContain(worktree2) + expect(result.project.sandboxes).not.toContain(tmp) }), ) }) @@ -413,12 +426,13 @@ describe("Project.fromDirectory with worktrees", () => { describe("Project.discover", () => { iconDiscoveryIt.live("discovers favicon from fromDirectory when enabled", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.png"), pngData)) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) - const updated = yield* waitForProjectIcon(project.id) + const result = yield* project.fromDirectory(tmp) + const updated = yield* waitForProjectIcon(result.project.id) expect(updated.icon?.url).toStartWith("data:") expect(updated.icon?.url).toContain("base64") @@ -427,15 +441,16 @@ describe("Project.discover", () => { it.live("should discover favicon.png in root", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.png"), pngData)) - yield* run((svc) => svc.discover(project)) + yield* project.discover(result.project) - const updated = Project.get(project.id) + const updated = yield* project.get(result.project.id) expect(updated).toBeDefined() expect(updated!.icon).toBeDefined() expect(updated!.icon?.url).toStartWith("data:") @@ -446,14 +461,15 @@ describe("Project.discover", () => { it.live("should not discover non-image files", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.txt"), "not an image")) - yield* run((svc) => svc.discover(project)) + yield* project.discover(result.project) - const updated = Project.get(project.id) + const updated = yield* project.get(result.project.id) expect(updated).toBeDefined() expect(updated!.icon).toBeUndefined() }), @@ -461,25 +477,24 @@ describe("Project.discover", () => { it.live("should not discover favicon when override is set", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - yield* run((svc) => - svc.update({ - projectID: project.id, - icon: { override: "data:image/png;base64,override" }, - }), - ) + yield* project.update({ + projectID: result.project.id, + icon: { override: "data:image/png;base64,override" }, + }) - const updatedProject = yield* run((svc) => svc.get(project.id)) + const updatedProject = yield* project.get(result.project.id) if (!updatedProject) throw new Error("Project not found") const pngData = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) yield* Effect.promise(() => Bun.write(path.join(tmp, "favicon.png"), pngData)) - yield* run((svc) => svc.discover(updatedProject)) + yield* project.discover(updatedProject) - const updated = Project.get(project.id) + const updated = yield* project.get(result.project.id) expect(updated).toBeDefined() expect(updated!.icon?.override).toBe("data:image/png;base64,override") expect(updated!.icon?.url).toBeUndefined() @@ -490,107 +505,100 @@ describe("Project.discover", () => { describe("Project.update", () => { it.live("should update name", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const updated = yield* run((svc) => - svc.update({ - projectID: project.id, - name: "New Project Name", - }), - ) + const updated = yield* project.update({ + projectID: result.project.id, + name: "New Project Name", + }) expect(updated.name).toBe("New Project Name") - const fromDb = Project.get(project.id) + const fromDb = yield* project.get(result.project.id) expect(fromDb?.name).toBe("New Project Name") }), ) it.live("should update icon url", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const updated = yield* run((svc) => - svc.update({ - projectID: project.id, - icon: { url: "https://example.com/icon.png" }, - }), - ) + const updated = yield* project.update({ + projectID: result.project.id, + icon: { url: "https://example.com/icon.png" }, + }) expect(updated.icon?.url).toBe("https://example.com/icon.png") - const fromDb = Project.get(project.id) + const fromDb = yield* project.get(result.project.id) expect(fromDb?.icon?.url).toBe("https://example.com/icon.png") }), ) it.live("should update icon color", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const updated = yield* run((svc) => - svc.update({ - projectID: project.id, - icon: { color: "#ff0000" }, - }), - ) + const updated = yield* project.update({ + projectID: result.project.id, + icon: { color: "#ff0000" }, + }) expect(updated.icon?.color).toBe("#ff0000") - const fromDb = Project.get(project.id) + const fromDb = yield* project.get(result.project.id) expect(fromDb?.icon?.color).toBe("#ff0000") }), ) it.live("should update icon override", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const updated = yield* run((svc) => - svc.update({ - projectID: project.id, - icon: { override: "data:image/png;base64,abc123" }, - }), - ) + const updated = yield* project.update({ + projectID: result.project.id, + icon: { override: "data:image/png;base64,abc123" }, + }) expect(updated.icon?.override).toBe("data:image/png;base64,abc123") - const fromDb = Project.get(project.id) + const fromDb = yield* project.get(result.project.id) expect(fromDb?.icon?.override).toBe("data:image/png;base64,abc123") }), ) it.live("should update commands", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const updated = yield* run((svc) => - svc.update({ - projectID: project.id, - commands: { start: "npm run dev" }, - }), - ) + const updated = yield* project.update({ + projectID: result.project.id, + commands: { start: "npm run dev" }, + }) expect(updated.commands?.start).toBe("npm run dev") - const fromDb = Project.get(project.id) + const fromDb = yield* project.get(result.project.id) expect(fromDb?.commands?.start).toBe("npm run dev") }), ) it.live("should fail when project not found", () => Effect.gen(function* () { - const exit = yield* run((svc) => - svc.update({ - projectID: ProjectID.make("nonexistent-project-id"), - name: "Should Fail", - }), - ).pipe(Effect.exit) + const project = yield* Project.Service + const exit = yield* project + .update({ projectID: ProjectV2.ID.make("nonexistent-project-id"), name: "Should Fail" }) + .pipe(Effect.exit) expect(Exit.isFailure(exit)).toBe(true) if (Exit.isFailure(exit)) { const error = Cause.squash(exit.cause) @@ -601,8 +609,9 @@ describe("Project.update", () => { it.live("should emit GlobalBus event on update", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) let eventPayload: any = null const on = (data: any) => { @@ -611,7 +620,7 @@ describe("Project.update", () => { GlobalBus.on("event", on) yield* Effect.addFinalizer(() => Effect.sync(() => GlobalBus.off("event", on))) - yield* run((svc) => svc.update({ projectID: project.id, name: "Updated Name" })) + yield* project.update({ projectID: result.project.id, name: "Updated Name" }) expect(eventPayload).not.toBeNull() expect(eventPayload.payload.type).toBe("project.updated") @@ -621,17 +630,16 @@ describe("Project.update", () => { it.live("should update multiple fields at once", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) - - const updated = yield* run((svc) => - svc.update({ - projectID: project.id, - name: "Multi Update", - icon: { url: "https://example.com/favicon.ico", override: "data:image/png;base64,abc123", color: "#00ff00" }, - commands: { start: "make start" }, - }), - ) + const result = yield* project.fromDirectory(tmp) + + const updated = yield* project.update({ + projectID: result.project.id, + name: "Multi Update", + icon: { url: "https://example.com/favicon.ico", override: "data:image/png;base64,abc123", color: "#00ff00" }, + commands: { start: "make start" }, + }) expect(updated.name).toBe("Multi Update") expect(updated.icon?.url).toBe("https://example.com/favicon.ico") @@ -645,43 +653,49 @@ describe("Project.update", () => { describe("Project.list and Project.get", () => { it.live("list returns all projects", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const all = Project.list() + const all = yield* project.list() expect(all.length).toBeGreaterThan(0) - expect(all.find((p) => p.id === project.id)).toBeDefined() + expect(all.find((p) => p.id === result.project.id)).toBeDefined() }), ) it.live("get returns project by id", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - const found = Project.get(project.id) + const found = yield* project.get(result.project.id) expect(found).toBeDefined() - expect(found!.id).toBe(project.id) + expect(found!.id).toBe(result.project.id) }), ) - test("get returns undefined for unknown id", () => { - const found = Project.get(ProjectID.make("nonexistent")) - expect(found).toBeUndefined() - }) + it.live("get returns undefined for unknown id", () => + Effect.gen(function* () { + const project = yield* Project.Service + const found = yield* project.get(ProjectV2.ID.make("nonexistent")) + expect(found).toBeUndefined() + }), + ) }) describe("Project.setInitialized", () => { it.live("sets time_initialized on project", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) - expect(project.time.initialized).toBeUndefined() + expect(result.project.time.initialized).toBeUndefined() - Project.setInitialized(project.id) + yield* project.setInitialized(result.project.id) - const updated = Project.get(project.id) + const updated = yield* project.get(result.project.id) expect(updated?.time.initialized).toBeDefined() }), ) @@ -690,26 +704,28 @@ describe("Project.setInitialized", () => { describe("Project.addSandbox and Project.removeSandbox", () => { it.live("addSandbox adds directory and removeSandbox removes it", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) const sandboxDir = path.join(tmp, "sandbox-test") - yield* run((svc) => svc.addSandbox(project.id, sandboxDir)) + yield* project.addSandbox(result.project.id, sandboxDir) - let found = Project.get(project.id) + let found = yield* project.get(result.project.id) expect(found?.sandboxes).toContain(sandboxDir) - yield* run((svc) => svc.removeSandbox(project.id, sandboxDir)) + yield* project.removeSandbox(result.project.id, sandboxDir) - found = Project.get(project.id) + found = yield* project.get(result.project.id) expect(found?.sandboxes).not.toContain(sandboxDir) }), ) it.live("addSandbox emits GlobalBus event", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) - const { project } = yield* run((svc) => svc.fromDirectory(tmp)) + const result = yield* project.fromDirectory(tmp) const sandboxDir = path.join(tmp, "sandbox-event") const events: any[] = [] @@ -717,7 +733,7 @@ describe("Project.addSandbox and Project.removeSandbox", () => { GlobalBus.on("event", on) yield* Effect.addFinalizer(() => Effect.sync(() => GlobalBus.off("event", on))) - yield* run((svc) => svc.addSandbox(project.id, sandboxDir)) + yield* project.addSandbox(result.project.id, sandboxDir) expect(events.some((e) => e.payload.type === Project.Event.Updated.type)).toBe(true) }), @@ -727,6 +743,7 @@ describe("Project.addSandbox and Project.removeSandbox", () => { describe("Project.fromDirectory with bare repos", () => { it.live("worktree from bare repo should cache in bare repo, not parent", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) const parentDir = path.dirname(tmp) @@ -739,10 +756,10 @@ describe("Project.fromDirectory with bare repos", () => { yield* Effect.promise(() => $`git clone --bare ${tmp} ${barePath}`.quiet()) yield* Effect.promise(() => $`git worktree add ${worktreePath} HEAD`.cwd(barePath).quiet()) - const { project } = yield* run((svc) => svc.fromDirectory(worktreePath)) + const result = yield* project.fromDirectory(worktreePath) - expect(project.id).not.toBe(ProjectID.global) - expect(project.worktree).toBe(worktreePath) + expect(result.project.id).not.toBe(ProjectV2.ID.global) + expect(result.project.worktree).toBe(worktreePath) const correctCache = path.join(barePath, "opencode") const wrongCache = path.join(parentDir, ".git", "opencode") @@ -754,6 +771,7 @@ describe("Project.fromDirectory with bare repos", () => { it.live("different bare repos under same parent should not share project ID", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp1 = yield* tmpdirScoped({ git: true }) const tmp2 = yield* tmpdirScoped({ git: true }) @@ -773,10 +791,10 @@ describe("Project.fromDirectory with bare repos", () => { yield* Effect.promise(() => $`git worktree add ${worktreeA} HEAD`.cwd(bareA).quiet()) yield* Effect.promise(() => $`git worktree add ${worktreeB} HEAD`.cwd(bareB).quiet()) - const { project: projA } = yield* run((svc) => svc.fromDirectory(worktreeA)) - const { project: projB } = yield* run((svc) => svc.fromDirectory(worktreeB)) + const result = yield* project.fromDirectory(worktreeA) + const next = yield* project.fromDirectory(worktreeB) - expect(projA.id).not.toBe(projB.id) + expect(result.project.id).not.toBe(next.project.id) const cacheA = path.join(bareA, "opencode") const cacheB = path.join(bareB, "opencode") @@ -790,6 +808,7 @@ describe("Project.fromDirectory with bare repos", () => { it.live("bare repo without .git suffix is still detected via core.bare", () => Effect.gen(function* () { + const project = yield* Project.Service const tmp = yield* tmpdirScoped({ git: true }) const parentDir = path.dirname(tmp) @@ -802,10 +821,10 @@ describe("Project.fromDirectory with bare repos", () => { yield* Effect.promise(() => $`git clone --bare ${tmp} ${barePath}`.quiet()) yield* Effect.promise(() => $`git worktree add ${worktreePath} HEAD`.cwd(barePath).quiet()) - const { project } = yield* run((svc) => svc.fromDirectory(worktreePath)) + const result = yield* project.fromDirectory(worktreePath) - expect(project.id).not.toBe(ProjectID.global) - expect(project.worktree).toBe(worktreePath) + expect(result.project.id).not.toBe(ProjectV2.ID.global) + expect(result.project.worktree).toBe(worktreePath) const correctCache = path.join(barePath, "opencode") expect(yield* Effect.promise(() => Bun.file(correctCache).exists())).toBe(true) diff --git a/packages/opencode/test/project/vcs.test.ts b/packages/opencode/test/project/vcs.test.ts index b1d637302df5..b3092348201c 100644 --- a/packages/opencode/test/project/vcs.test.ts +++ b/packages/opencode/test/project/vcs.test.ts @@ -5,8 +5,14 @@ import { Deferred, Effect, Layer } from "effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import fs from "fs/promises" import path from "path" -import { disposeAllInstances, provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture" -import { Bus } from "../../src/bus" +import { + disposeAllInstances, + provideInstance, + testInstanceStoreLayer, + TestInstance, + tmpdirScoped, +} from "../fixture/fixture" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { FileWatcher } from "../../src/file/watcher" import { Git } from "../../src/git" import { Vcs } from "@/project/vcs" @@ -19,11 +25,12 @@ import { testEffect } from "../lib/effect" const weird = process.platform === "win32" ? "space file.txt" : "tab\tfile.txt" const layer = Layer.mergeAll( - Vcs.layer.pipe(Layer.provideMerge(Git.defaultLayer), Layer.provideMerge(Bus.layer)), + Vcs.layer.pipe(Layer.provideMerge(Git.defaultLayer), Layer.provideMerge(EventV2Bridge.defaultLayer)), CrossSpawnSpawner.defaultLayer, AppFileSystem.defaultLayer, ) const it = testEffect(layer) +const worktreeIt = testEffect(Layer.mergeAll(layer, testInstanceStoreLayer)) const git = Effect.fn("VcsTest.git")(function* (cwd: string, args: string[]) { const result = yield* Git.Service.use((git) => git.run(args, { cwd })) @@ -47,13 +54,15 @@ const init = Effect.fn("VcsTest.init")(function* () { }) const nextBranchUpdate = Effect.fn("VcsTest.nextBranchUpdate")(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const updated = yield* Deferred.make() - const off = yield* bus.subscribeCallback(Vcs.Event.BranchUpdated, (evt) => { - Effect.runSync(Deferred.succeed(updated, evt.properties.branch)) + const off = yield* events.listen((event) => { + if (event.type === Vcs.Event.BranchUpdated.type) + Deferred.doneUnsafe(updated, Effect.succeed((event.data as typeof Vcs.Event.BranchUpdated.data.Type).branch)) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(off)) + yield* Effect.addFinalizer(() => off) return updated }) @@ -62,9 +71,9 @@ const publishHeadChangeUntil = Effect.fn("VcsTest.publishHeadChangeUntil")(funct pending: Deferred.Deferred, head: string, ) { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service for (let i = 0; i < 50; i++) { - yield* bus.publish(FileWatcher.Event.Updated, { file: head, event: "change" }) + yield* events.publish(FileWatcher.Event.Updated, { file: head, event: "change" }) if (yield* Deferred.isDone(pending)) return yield* Effect.sleep("10 millis") } @@ -183,7 +192,7 @@ describe("Vcs diff", () => { { git: true }, ) - it.live("detects current branch from the active worktree", () => + worktreeIt.live("detects current branch from the active worktree", () => Effect.gen(function* () { const tmp = yield* tmpdirScoped({ git: true }) const wt = yield* tmpdirScoped() diff --git a/packages/opencode/test/project/worktree-remove.test.ts b/packages/opencode/test/project/worktree-remove.test.ts index fa70ecb893b4..c7175780248e 100644 --- a/packages/opencode/test/project/worktree-remove.test.ts +++ b/packages/opencode/test/project/worktree-remove.test.ts @@ -5,122 +5,122 @@ import path from "path" import { Effect, Layer } from "effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Worktree } from "../../src/worktree" -import { provideTmpdirInstance } from "../fixture/fixture" +import { TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" const it = testEffect(Layer.mergeAll(Worktree.defaultLayer, CrossSpawnSpawner.defaultLayer)) -const wintest = process.platform === "win32" ? it.live : it.live.skip +const wintest = process.platform === "win32" ? it.instance : it.instance.skip describe("Worktree.remove", () => { - it.live("continues when git remove exits non-zero after detaching", () => - provideTmpdirInstance( - (root) => - Effect.gen(function* () { - const svc = yield* Worktree.Service - const name = `remove-regression-${Date.now().toString(36)}` - const branch = `opencode/${name}` - const dir = path.join(root, "..", name) - - yield* Effect.promise(() => $`git worktree add --no-checkout -b ${branch} ${dir}`.cwd(root).quiet()) - yield* Effect.promise(() => $`git reset --hard`.cwd(dir).quiet()) - - const real = (yield* Effect.promise(() => $`which git`.quiet().text())).trim() - expect(real).toBeTruthy() - - const bin = path.join(root, "bin") - const shim = path.join(bin, "git") - yield* Effect.promise(() => fs.mkdir(bin, { recursive: true })) - yield* Effect.promise(() => - Bun.write( - shim, - [ - "#!/bin/bash", - `REAL_GIT=${JSON.stringify(real)}`, - 'if [ "$1" = "worktree" ] && [ "$2" = "remove" ]; then', - ' "$REAL_GIT" "$@" >/dev/null 2>&1', - ' echo "fatal: failed to remove worktree: Directory not empty" >&2', - " exit 1", - "fi", - 'exec "$REAL_GIT" "$@"', - ].join("\n"), - ), - ) - yield* Effect.promise(() => fs.chmod(shim, 0o755)) - - const prev = yield* Effect.acquireRelease( + it.instance( + "continues when git remove exits non-zero after detaching", + () => + Effect.gen(function* () { + const root = (yield* TestInstance).directory + const svc = yield* Worktree.Service + const name = `remove-regression-${Date.now().toString(36)}` + const branch = `opencode/${name}` + const dir = path.join(root, "..", name) + + yield* Effect.promise(() => $`git worktree add --no-checkout -b ${branch} ${dir}`.cwd(root).quiet()) + yield* Effect.promise(() => $`git reset --hard`.cwd(dir).quiet()) + + const real = (yield* Effect.promise(() => $`which git`.quiet().text())).trim() + expect(real).toBeTruthy() + + const bin = path.join(root, "bin") + const shim = path.join(bin, "git") + yield* Effect.promise(() => fs.mkdir(bin, { recursive: true })) + yield* Effect.promise(() => + Bun.write( + shim, + [ + "#!/bin/bash", + `REAL_GIT=${JSON.stringify(real)}`, + 'if [ "$1" = "worktree" ] && [ "$2" = "remove" ]; then', + ' "$REAL_GIT" "$@" >/dev/null 2>&1', + ' echo "fatal: failed to remove worktree: Directory not empty" >&2', + " exit 1", + "fi", + 'exec "$REAL_GIT" "$@"', + ].join("\n"), + ), + ) + yield* Effect.promise(() => fs.chmod(shim, 0o755)) + + const prev = yield* Effect.acquireRelease( + Effect.sync(() => { + const prev = process.env.PATH ?? "" + process.env.PATH = `${bin}${path.delimiter}${prev}` + return prev + }), + (prev) => Effect.sync(() => { - const prev = process.env.PATH ?? "" - process.env.PATH = `${bin}${path.delimiter}${prev}` - return prev + process.env.PATH = prev }), - (prev) => - Effect.sync(() => { - process.env.PATH = prev - }), - ) - void prev - - const ok = yield* svc.remove({ directory: dir }) - - expect(ok).toBe(true) - expect( - yield* Effect.promise(() => - fs - .stat(dir) - .then(() => true) - .catch(() => false), - ), - ).toBe(false) - - const list = yield* Effect.promise(() => $`git worktree list --porcelain`.cwd(root).quiet().text()) - expect(list).not.toContain(`worktree ${dir}`) - - const ref = yield* Effect.promise(() => - $`git show-ref --verify --quiet refs/heads/${branch}`.cwd(root).quiet().nothrow(), - ) - expect(ref.exitCode).not.toBe(0) - }), - { git: true }, - ), + ) + void prev + + const ok = yield* svc.remove({ directory: dir }) + + expect(ok).toBe(true) + expect( + yield* Effect.promise(() => + fs + .stat(dir) + .then(() => true) + .catch(() => false), + ), + ).toBe(false) + + const list = yield* Effect.promise(() => $`git worktree list --porcelain`.cwd(root).quiet().text()) + expect(list).not.toContain(`worktree ${dir}`) + + const ref = yield* Effect.promise(() => + $`git show-ref --verify --quiet refs/heads/${branch}`.cwd(root).quiet().nothrow(), + ) + expect(ref.exitCode).not.toBe(0) + }), + { git: true }, ) - wintest("stops fsmonitor before removing a worktree", () => - provideTmpdirInstance( - (root) => - Effect.gen(function* () { - const svc = yield* Worktree.Service - const name = `remove-fsmonitor-${Date.now().toString(36)}` - const branch = `opencode/${name}` - const dir = path.join(root, "..", name) - - yield* Effect.promise(() => $`git worktree add --no-checkout -b ${branch} ${dir}`.cwd(root).quiet()) - yield* Effect.promise(() => $`git reset --hard`.cwd(dir).quiet()) - yield* Effect.promise(() => $`git config core.fsmonitor true`.cwd(dir).quiet()) - yield* Effect.promise(() => $`git fsmonitor--daemon stop`.cwd(dir).quiet().nothrow()) - yield* Effect.promise(() => Bun.write(path.join(dir, "tracked.txt"), "next\n")) - yield* Effect.promise(() => $`git diff`.cwd(dir).quiet()) - - const before = yield* Effect.promise(() => $`git fsmonitor--daemon status`.cwd(dir).quiet().nothrow()) - expect(before.exitCode).toBe(0) - - const ok = yield* svc.remove({ directory: dir }) - - expect(ok).toBe(true) - expect( - yield* Effect.promise(() => - fs - .stat(dir) - .then(() => true) - .catch(() => false), - ), - ).toBe(false) - - const ref = yield* Effect.promise(() => - $`git show-ref --verify --quiet refs/heads/${branch}`.cwd(root).quiet().nothrow(), - ) - expect(ref.exitCode).not.toBe(0) - }), - { git: true }, - ), + wintest( + "stops fsmonitor before removing a worktree", + () => + Effect.gen(function* () { + const root = (yield* TestInstance).directory + const svc = yield* Worktree.Service + const name = `remove-fsmonitor-${Date.now().toString(36)}` + const branch = `opencode/${name}` + const dir = path.join(root, "..", name) + + yield* Effect.promise(() => $`git worktree add --no-checkout -b ${branch} ${dir}`.cwd(root).quiet()) + yield* Effect.promise(() => $`git reset --hard`.cwd(dir).quiet()) + yield* Effect.promise(() => $`git config core.fsmonitor true`.cwd(dir).quiet()) + yield* Effect.promise(() => $`git fsmonitor--daemon stop`.cwd(dir).quiet().nothrow()) + yield* Effect.promise(() => Bun.write(path.join(dir, "tracked.txt"), "next\n")) + yield* Effect.promise(() => $`git diff`.cwd(dir).quiet()) + + const before = yield* Effect.promise(() => $`git fsmonitor--daemon status`.cwd(dir).quiet().nothrow()) + expect(before.exitCode).toBe(0) + + const ok = yield* svc.remove({ directory: dir }) + + expect(ok).toBe(true) + expect( + yield* Effect.promise(() => + fs + .stat(dir) + .then(() => true) + .catch(() => false), + ), + ).toBe(false) + + const ref = yield* Effect.promise(() => + $`git show-ref --verify --quiet refs/heads/${branch}`.cwd(root).quiet().nothrow(), + ) + expect(ref.exitCode).not.toBe(0) + }), + { git: true }, ) }) diff --git a/packages/opencode/test/project/worktree.test.ts b/packages/opencode/test/project/worktree.test.ts index 688b818beed1..3da2d02ea08b 100644 --- a/packages/opencode/test/project/worktree.test.ts +++ b/packages/opencode/test/project/worktree.test.ts @@ -5,8 +5,6 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Cause, Deferred, Effect, Exit, Fiber, Layer } from "effect" import { GlobalBus, type GlobalEvent } from "../../src/bus/global" import { Git } from "../../src/git" -import { InstanceRef } from "../../src/effect/instance-ref" -import { InstanceRuntime } from "../../src/project/instance-runtime" import { Worktree } from "../../src/worktree" import { disposeAllInstances, provideInstance, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" @@ -41,11 +39,6 @@ const waitReady = Effect.fn("WorktreeTest.waitReady")(function* () { const removeCreatedWorktree = (directory: string) => Effect.gen(function* () { const svc = yield* Worktree.Service - const ctx = yield* Effect.gen(function* () { - return yield* InstanceRef - }).pipe(provideInstance(directory)) - if (!ctx) return yield* Effect.die(new Error("missing test instance")) - yield* Effect.promise(() => InstanceRuntime.disposeInstance(ctx)) const ok = yield* svc.remove({ directory }) if (!ok) return yield* Effect.fail(new Error(`failed to remove worktree ${directory}`)) }) @@ -214,6 +207,22 @@ describe("Worktree", () => { { git: true }, ) + it.instance( + "lists the active linked worktree but not the project checkout", + () => + withCreatedWorktree(undefined, ({ info }) => + Effect.gen(function* () { + const test = yield* TestInstance + const svc = yield* Worktree.Service + const list = yield* svc.list().pipe(provideInstance(info.directory)) + + expect(list.map((item) => item.name)).toContain(info.name) + expect(list.map((item) => item.name)).not.toContain(path.basename(test.directory).toLowerCase()) + }), + ), + { git: true }, + ) + it.instance( "create with custom name", () => diff --git a/packages/opencode/test/provider/amazon-bedrock.test.ts b/packages/opencode/test/provider/amazon-bedrock.test.ts index 763b724b636c..470d42fd1bf7 100644 --- a/packages/opencode/test/provider/amazon-bedrock.test.ts +++ b/packages/opencode/test/provider/amazon-bedrock.test.ts @@ -6,9 +6,10 @@ import { Global } from "@opencode-ai/core/global" import { Filesystem } from "@/util/filesystem" import { Env } from "../../src/env" import { Provider } from "@/provider/provider" -import { ProviderID } from "../../src/provider/schema" + import { disposeAllInstances } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" const it = testEffect(Layer.mergeAll(Provider.defaultLayer, Env.defaultLayer)) @@ -62,8 +63,8 @@ it.instance( yield* set("AWS_REGION", "us-east-1") yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].options?.region).toBe("eu-west-1") + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].options?.region).toBe("eu-west-1") }), { config: { provider: { "amazon-bedrock": { options: { region: "eu-west-1" } } } } }, ) @@ -73,8 +74,8 @@ it.instance("Bedrock: falls back to AWS_REGION env var when no config region", ( yield* set("AWS_REGION", "eu-west-1") yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].options?.region).toBe("eu-west-1") + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].options?.region).toBe("eu-west-1") }), ) @@ -87,8 +88,8 @@ it.instance( yield* set("AWS_ACCESS_KEY_ID", "") yield* set("AWS_BEARER_TOKEN_BEDROCK", "") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].options?.region).toBe("eu-west-1") + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].options?.region).toBe("eu-west-1") }), { config: { provider: { "amazon-bedrock": { options: { region: "eu-west-1" } } } } }, ) @@ -100,8 +101,8 @@ it.instance( yield* set("AWS_PROFILE", "default") yield* set("AWS_ACCESS_KEY_ID", "test-key-id") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].options?.region).toBe("us-east-1") + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].options?.region).toBe("us-east-1") }), { config: { @@ -116,8 +117,8 @@ it.instance( Effect.gen(function* () { yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].options?.endpoint).toBe( + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].options?.endpoint).toBe( "https://bedrock-runtime.us-east-1.vpce-xxxxx.amazonaws.com", ) }), @@ -141,8 +142,8 @@ it.instance( yield* set("AWS_PROFILE", "") yield* set("AWS_ACCESS_KEY_ID", "") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].options?.region).toBe("us-east-1") + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].options?.region).toBe("us-east-1") }), { config: { provider: { "amazon-bedrock": { options: { region: "us-east-1" } } } } }, ) @@ -157,8 +158,8 @@ it.instance( Effect.gen(function* () { yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].models["us.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].models["us.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() }), { config: { @@ -178,8 +179,10 @@ it.instance( Effect.gen(function* () { yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].models["global.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect( + providers[ProviderV2.ID.amazonBedrock].models["global.anthropic.claude-opus-4-5-20251101-v1:0"], + ).toBeDefined() }), { config: { @@ -199,8 +202,8 @@ it.instance( Effect.gen(function* () { yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].models["eu.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].models["eu.anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() }), { config: { @@ -220,8 +223,8 @@ it.instance( Effect.gen(function* () { yield* set("AWS_PROFILE", "default") const providers = yield* list - expect(providers[ProviderID.amazonBedrock]).toBeDefined() - expect(providers[ProviderID.amazonBedrock].models["anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock]).toBeDefined() + expect(providers[ProviderV2.ID.amazonBedrock].models["anthropic.claude-opus-4-5-20251101-v1:0"]).toBeDefined() }), { config: { diff --git a/packages/opencode/test/provider/cf-ai-gateway-e2e.test.ts b/packages/opencode/test/provider/cf-ai-gateway-e2e.test.ts index 0c692c50c855..cf18e842f5eb 100644 --- a/packages/opencode/test/provider/cf-ai-gateway-e2e.test.ts +++ b/packages/opencode/test/provider/cf-ai-gateway-e2e.test.ts @@ -13,7 +13,7 @@ import { createAiGateway } from "ai-gateway-provider" import { createUnified } from "ai-gateway-provider/providers/unified" import { ProviderTransform } from "@/provider/transform" import type * as Provider from "@/provider/provider" -import { ModelID, ProviderID } from "@/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" type Captured = { url: string; outerBody: unknown } type ProviderOptions = Record> @@ -56,8 +56,8 @@ afterEach(() => { }) const cfModel = (apiId: string, releaseDate = "2026-03-05"): Provider.Model => ({ - id: ModelID.make(`cloudflare-ai-gateway/${apiId}`), - providerID: ProviderID.make("cloudflare-ai-gateway"), + id: ProviderV2.ModelID.make(`cloudflare-ai-gateway/${apiId}`), + providerID: ProviderV2.ID.make("cloudflare-ai-gateway"), name: apiId, api: { id: apiId, url: "https://gateway.ai.cloudflare.com/v1/compat", npm: "ai-gateway-provider" }, capabilities: { diff --git a/packages/opencode/test/provider/digitalocean.test.ts b/packages/opencode/test/provider/digitalocean.test.ts index 665c792deb2b..59c3f8da7c38 100644 --- a/packages/opencode/test/provider/digitalocean.test.ts +++ b/packages/opencode/test/provider/digitalocean.test.ts @@ -1,10 +1,11 @@ import { expect } from "bun:test" import { Provider } from "../../src/provider/provider" -import { ProviderID } from "../../src/provider/schema" + import { Effect } from "effect" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" -const DIGITALOCEAN = ProviderID.make("digitalocean") +const DIGITALOCEAN = ProviderV2.ID.make("digitalocean") const it = testEffect(Provider.defaultLayer) const withEnv = (values: Record, effect: Effect.Effect) => diff --git a/packages/opencode/test/provider/gitlab-duo.test.ts b/packages/opencode/test/provider/gitlab-duo.test.ts index 4ac62cf69de7..563fa025558b 100644 --- a/packages/opencode/test/provider/gitlab-duo.test.ts +++ b/packages/opencode/test/provider/gitlab-duo.test.ts @@ -6,7 +6,7 @@ export {} // import { test, expect, describe } from "bun:test" // import path from "path" -// import { ProviderID, ModelID } from "../../src/provider/schema" +// import { ProviderV2 } from "@opencode-ai/core/provider" // import { tmpdir, withTestInstance } from "../fixture/fixture" // import { Provider } from "@/provider/provider" // import { Env } from "../../src/env" diff --git a/packages/opencode/test/provider/header-timeout.test.ts b/packages/opencode/test/provider/header-timeout.test.ts new file mode 100644 index 000000000000..e52d6885c2e8 --- /dev/null +++ b/packages/opencode/test/provider/header-timeout.test.ts @@ -0,0 +1,232 @@ +import { afterEach, expect } from "bun:test" +import { createServer, type Server } from "node:http" +import { streamText } from "ai" +import { Effect, Layer } from "effect" +import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture" +import { testEffect } from "../lib/effect" +import { testProviderConfig } from "../lib/test-provider" +import { Env } from "@/env" +import { Plugin } from "@/plugin" +import { Provider } from "@/provider/provider" +import { ProviderError } from "@/provider/error" + +afterEach(async () => { + await disposeAllInstances() +}) + +const it = testEffect( + Layer.mergeAll(Provider.defaultLayer, Env.defaultLayer, Plugin.defaultLayer, CrossSpawnSpawner.defaultLayer), +) + +it.live("headerTimeout does not abort delayed SSE body after headers arrive", () => + Effect.gen(function* () { + const server = yield* Effect.acquireRelease( + Effect.promise(() => delayedBodyServer(250)), + (server) => Effect.sync(() => server.server.close()), + ) + + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const provider = yield* Provider.Service + const model = yield* provider.getModel(ProviderV2.ID.make("test"), ProviderV2.ModelID.make("test-model")) + const result = streamText({ + model: yield* provider.getLanguage(model), + messages: [{ role: "user", content: "hello" }], + }) + + expect(yield* Effect.promise(() => result.text)).toBe("late") + }), + { config: providerConfig(server.url, { headerTimeout: 50 }) }, + ) + }), +) + +it.live("chunkTimeout raises a response stream error when SSE body stalls", () => + Effect.gen(function* () { + const server = yield* Effect.acquireRelease( + Effect.promise(() => delayedBodyServer(250)), + (server) => Effect.sync(() => server.server.close()), + ) + + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const provider = yield* Provider.Service + const model = yield* provider.getModel(ProviderV2.ID.make("test"), ProviderV2.ModelID.make("test-model")) + const result = streamText({ + model: yield* provider.getLanguage(model), + onError() {}, + messages: [{ role: "user", content: "hello" }], + }) + + const error = yield* Effect.promise(async () => { + try { + for await (const part of result.fullStream) { + if (part.type === "error") return part.error + } + } catch (error) { + return error + } + }) + expect(error).toBeInstanceOf(ProviderError.ResponseStreamError) + }), + { config: providerConfig(server.url, { chunkTimeout: 50 }) }, + ) + }), +) + +it.live("headerTimeout aborts when response headers do not arrive", () => + Effect.gen(function* () { + const server = yield* Effect.acquireRelease( + Effect.promise(() => delayedHeaderServer(250)), + (server) => Effect.sync(() => server.server.close()), + ) + + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const provider = yield* Provider.Service + const model = yield* provider.getModel(ProviderV2.ID.make("test"), ProviderV2.ModelID.make("test-model")) + const result = streamText({ + model: yield* provider.getLanguage(model), + onError() {}, + messages: [{ role: "user", content: "hello" }], + }) + + const errors = yield* Effect.promise(async () => { + const errors: string[] = [] + for await (const part of result.fullStream) { + if (part.type === "error") errors.push(String(part.error)) + } + return errors + }) + expect(errors.join("\n")).toContain("response headers timed out") + }), + { config: providerConfig(server.url, { headerTimeout: 50 }) }, + ) + }), +) + +it.live("headerTimeout is opt-in for non-OpenAI providers", () => + Effect.gen(function* () { + const server = yield* Effect.acquireRelease( + Effect.promise(() => delayedHeaderServer(100)), + (server) => Effect.sync(() => server.server.close()), + ) + + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const provider = yield* Provider.Service + const model = yield* provider.getModel(ProviderV2.ID.make("test"), ProviderV2.ModelID.make("test-model")) + const result = streamText({ + model: yield* provider.getLanguage(model), + messages: [{ role: "user", content: "hello" }], + }) + + expect(yield* Effect.promise(() => result.text)).toBe("ok") + }), + { config: providerConfig(server.url) }, + ) + }), +) + +it.live("OpenAI Codex headerTimeout default can be disabled by config", () => + Effect.gen(function* () { + yield* withAuthContent( + Effect.gen(function* () { + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const provider = yield* Provider.Service + const openai = yield* provider.getProvider(ProviderV2.ID.openai) + expect(openai.options.headerTimeout).toBe(false) + }), + { config: { provider: { openai: { options: { headerTimeout: false } } } } }, + ) + }), + ) + }), +) + +it.live("OpenAI API auth gets default headerTimeout", () => + Effect.gen(function* () { + yield* withAuthContent( + Effect.gen(function* () { + yield* provideTmpdirInstance(() => + Effect.gen(function* () { + const provider = yield* Provider.Service + const openai = yield* provider.getProvider(ProviderV2.ID.openai) + expect(openai.options.headerTimeout).toBe(10_000) + }), + ) + }), + { openai: { type: "api", key: "sk-test" } }, + ) + }), +) + +function providerConfig(url: string, options: Record = {}) { + const config = testProviderConfig(url) + return { + ...config, + provider: { + test: { + ...config.provider.test, + options: { ...config.provider.test.options, ...options }, + }, + }, + } +} + +async function delayedHeaderServer(delay: number): Promise<{ server: Server; url: string }> { + const server = createServer((_, res) => { + setTimeout(() => { + res.writeHead(200, { "content-type": "text/event-stream" }) + res.end('data: {"choices":[{"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n') + }, delay) + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + const address = server.address() + if (!address || typeof address === "string") throw new Error("server did not bind to a TCP port") + return { server, url: `http://127.0.0.1:${address.port}` } +} + +async function delayedBodyServer(delay: number): Promise<{ server: Server; url: string }> { + const server = createServer((_, res) => { + res.writeHead(200, { "content-type": "text/event-stream" }) + res.flushHeaders() + setTimeout(() => { + res.end('data: {"choices":[{"delta":{"content":"late"}}]}\n\ndata: [DONE]\n\n') + }, delay) + }) + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)) + const address = server.address() + if (!address || typeof address === "string") throw new Error("server did not bind to a TCP port") + return { server, url: `http://127.0.0.1:${address.port}` } +} + +function withAuthContent(self: Effect.Effect, value: Record = defaultAuthContent()) { + return Effect.acquireUseRelease( + Effect.sync(() => { + const previous = process.env.OPENCODE_AUTH_CONTENT + process.env.OPENCODE_AUTH_CONTENT = JSON.stringify(value) + return previous + }), + () => self, + (previous) => + Effect.sync(() => { + if (previous === undefined) delete process.env.OPENCODE_AUTH_CONTENT + else process.env.OPENCODE_AUTH_CONTENT = previous + }), + ) +} + +function defaultAuthContent() { + return { + openai: { type: "oauth", refresh: "refresh", access: "access", expires: Date.now() + 60_000 }, + } +} diff --git a/packages/opencode/test/provider/provider.test.ts b/packages/opencode/test/provider/provider.test.ts index 8cf93e22d6f1..2492fb271d28 100644 --- a/packages/opencode/test/provider/provider.test.ts +++ b/packages/opencode/test/provider/provider.test.ts @@ -13,11 +13,12 @@ import { Config } from "@/config/config" import { Env } from "../../src/env" import { Plugin } from "../../src/plugin/index" import { Provider } from "@/provider/provider" -import { ProviderID, ModelID } from "../../src/provider/schema" + import { RuntimeFlags } from "@/effect/runtime-flags" import { Filesystem } from "@/util/filesystem" import { InstanceLayer } from "@/project/instance-layer" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" const originalEnv = new Map() @@ -68,7 +69,7 @@ const providerLayer = (flags: Partial = {}) => const list = Provider.use.list() const paid = (providers: Record }>) => { - const item = providers[ProviderID.make("opencode")] + const item = providers[ProviderV2.ID.make("opencode")] expect(item).toBeDefined() return Object.values(item.models).filter((model) => model.cost.input > 0).length } @@ -104,11 +105,11 @@ it.instance("provider loaded from env variable", () => Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() // Provider should retain its connection source even if custom loaders // merge additional options. - expect(providers[ProviderID.anthropic].source).toBe("env") - expect(providers[ProviderID.anthropic].options.headers["anthropic-beta"]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic].source).toBe("env") + expect(providers[ProviderV2.ID.anthropic].options.headers["anthropic-beta"]).toBeDefined() }), ) @@ -116,7 +117,7 @@ it.instance( "provider loaded from config with apiKey option", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() }), { config: { provider: { anthropic: { options: { apiKey: "config-api-key" } } } } }, ) @@ -126,7 +127,7 @@ it.instance( Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeUndefined() + expect(providers[ProviderV2.ID.anthropic]).toBeUndefined() }), { config: { disabled_providers: ["anthropic"] } }, ) @@ -137,8 +138,8 @@ it.instance( yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") yield* setProcessEnv("OPENAI_API_KEY", "test-openai-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - expect(providers[ProviderID.openai]).toBeUndefined() + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.openai]).toBeUndefined() }), { config: { enabled_providers: ["anthropic"] } }, ) @@ -148,8 +149,8 @@ it.instance( Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - const models = Object.keys(providers[ProviderID.anthropic].models) + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + const models = Object.keys(providers[ProviderV2.ID.anthropic].models) expect(models).toContain("claude-sonnet-4-20250514") expect(models.length).toBe(1) }), @@ -161,8 +162,8 @@ it.instance( Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - const models = Object.keys(providers[ProviderID.anthropic].models) + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + const models = Object.keys(providers[ProviderV2.ID.anthropic].models) expect(models).not.toContain("claude-sonnet-4-20250514") }), { config: { provider: { anthropic: { blacklist: ["claude-sonnet-4-20250514"] } } } }, @@ -173,9 +174,9 @@ it.instance( Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - expect(providers[ProviderID.anthropic].models["my-alias"]).toBeDefined() - expect(providers[ProviderID.anthropic].models["my-alias"].name).toBe("My Custom Alias") + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic].models["my-alias"]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic].models["my-alias"].name).toBe("My Custom Alias") }), { config: { @@ -190,9 +191,9 @@ it.instance( "custom provider with npm package", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("custom-provider")]).toBeDefined() - expect(providers[ProviderID.make("custom-provider")].name).toBe("Custom Provider") - expect(providers[ProviderID.make("custom-provider")].models["custom-model"]).toBeDefined() + expect(providers[ProviderV2.ID.make("custom-provider")]).toBeDefined() + expect(providers[ProviderV2.ID.make("custom-provider")].name).toBe("Custom Provider") + expect(providers[ProviderV2.ID.make("custom-provider")].models["custom-model"]).toBeDefined() }), { config: { @@ -220,8 +221,8 @@ it.instance( "filters alpha provider models by default", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("custom-provider")].models["active-model"]).toBeDefined() - expect(providers[ProviderID.make("custom-provider")].models["alpha-model"]).toBeUndefined() + expect(providers[ProviderV2.ID.make("custom-provider")].models["active-model"]).toBeDefined() + expect(providers[ProviderV2.ID.make("custom-provider")].models["alpha-model"]).toBeUndefined() }), { config: alphaProviderConfig }, ) @@ -230,8 +231,8 @@ experimentalModels.instance( "includes alpha provider models when experimental models are enabled", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("custom-provider")].models["active-model"]).toBeDefined() - expect(providers[ProviderID.make("custom-provider")].models["alpha-model"]).toBeDefined() + expect(providers[ProviderV2.ID.make("custom-provider")].models["active-model"]).toBeDefined() + expect(providers[ProviderV2.ID.make("custom-provider")].models["alpha-model"]).toBeDefined() }), { config: alphaProviderConfig }, ) @@ -240,13 +241,13 @@ it.instance( "custom DeepSeek openai-compatible model defaults interleaved reasoning field", Effect.gen(function* () { const providers = yield* list - const provider = providers[ProviderID.make("custom-provider")] + const provider = providers[ProviderV2.ID.make("custom-provider")] expect(provider.models["deepseek-r1"].capabilities.interleaved).toEqual({ field: "reasoning_content" }) expect(provider.models["deepseek-details"].capabilities.interleaved).toEqual({ field: "reasoning_details" }) expect(provider.models["custom-model"].capabilities.interleaved).toBe(false) - expect(providers[ProviderID.make("custom-anthropic-provider")].models["deepseek-r1"].capabilities.interleaved).toBe( - false, - ) + expect( + providers[ProviderV2.ID.make("custom-anthropic-provider")].models["deepseek-r1"].capabilities.interleaved, + ).toBe(false) }), { config: { @@ -279,19 +280,20 @@ it.instance( Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "env-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() // Config options should be merged - expect(providers[ProviderID.anthropic].options.timeout).toBe(60000) - expect(providers[ProviderID.anthropic].options.chunkTimeout).toBe(15000) + expect(providers[ProviderV2.ID.anthropic].options.timeout).toBe(60000) + expect(providers[ProviderV2.ID.anthropic].options.headerTimeout).toBe(10000) + expect(providers[ProviderV2.ID.anthropic].options.chunkTimeout).toBe(15000) }), - { config: { provider: { anthropic: { options: { timeout: 60000, chunkTimeout: 15000 } } } } }, + { config: { provider: { anthropic: { options: { timeout: 60000, headerTimeout: 10000, chunkTimeout: 15000 } } } } }, ) it.instance("getModel returns model for valid provider/model", () => Effect.gen(function* () { yield* setProcessEnv("ANTHROPIC_API_KEY", "test-api-key") const provider = yield* Provider.Service - const model = yield* provider.getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514")) + const model = yield* provider.getModel(ProviderV2.ID.anthropic, ProviderV2.ModelID.make("claude-sonnet-4-20250514")) expect(model).toBeDefined() expect(String(model.providerID)).toBe("anthropic") expect(String(model.id)).toBe("claude-sonnet-4-20250514") @@ -303,7 +305,9 @@ it.instance("getModel returns model for valid provider/model", () => it.instance("getModel throws ModelNotFoundError for invalid model", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const exit = yield* Provider.use.getModel(ProviderID.anthropic, ModelID.make("nonexistent-model")).pipe(Effect.exit) + const exit = yield* Provider.use + .getModel(ProviderV2.ID.anthropic, ProviderV2.ModelID.make("nonexistent-model")) + .pipe(Effect.exit) expect(exit._tag).toBe("Failure") }), ) @@ -311,7 +315,7 @@ it.instance("getModel throws ModelNotFoundError for invalid model", () => it.instance("getModel throws ModelNotFoundError for invalid provider", () => Effect.gen(function* () { const exit = yield* Provider.use - .getModel(ProviderID.make("nonexistent-provider"), ModelID.make("some-model")) + .getModel(ProviderV2.ID.make("nonexistent-provider"), ProviderV2.ModelID.make("some-model")) .pipe(Effect.exit) expect(exit._tag).toBe("Failure") }), @@ -365,8 +369,8 @@ it.instance( "provider with baseURL from config", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("custom-openai")]).toBeDefined() - expect(providers[ProviderID.make("custom-openai")].options.baseURL).toBe("https://custom.openai.com/v1") + expect(providers[ProviderV2.ID.make("custom-openai")]).toBeDefined() + expect(providers[ProviderV2.ID.make("custom-openai")].options.baseURL).toBe("https://custom.openai.com/v1") }), { config: { @@ -387,7 +391,7 @@ it.instance( "model cost defaults to zero when not specified", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.make("test-provider")].models["test-model"] + const model = providers[ProviderV2.ID.make("test-provider")].models["test-model"] expect(model.cost.input).toBe(0) expect(model.cost.output).toBe(0) expect(model.cost.cache.read).toBe(0) @@ -412,7 +416,7 @@ it.instance( "model options are merged from existing model", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.options.customOption).toBe("custom-value") }), { @@ -431,7 +435,7 @@ it.instance( "provider removed when all models filtered out", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeUndefined() + expect(providers[ProviderV2.ID.anthropic]).toBeUndefined() }), { config: { provider: { anthropic: { options: { apiKey: "test-api-key" }, whitelist: ["nonexistent-model"] } } } }, ) @@ -439,7 +443,7 @@ it.instance( it.instance("closest finds model by partial match", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const result = yield* Provider.use.closest(ProviderID.anthropic, ["sonnet-4"]) + const result = yield* Provider.use.closest(ProviderV2.ID.anthropic, ["sonnet-4"]) expect(result).toBeDefined() expect(String(result?.providerID)).toBe("anthropic") expect(String(result?.modelID)).toContain("sonnet-4") @@ -448,7 +452,7 @@ it.instance("closest finds model by partial match", () => it.instance("closest returns undefined for nonexistent provider", () => Effect.gen(function* () { - const result = yield* Provider.use.closest(ProviderID.make("nonexistent"), ["model"]) + const result = yield* Provider.use.closest(ProviderV2.ID.make("nonexistent"), ["model"]) expect(result).toBeUndefined() }), ) @@ -458,9 +462,9 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic].models["my-sonnet"]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic].models["my-sonnet"]).toBeDefined() - const model = yield* Provider.use.getModel(ProviderID.anthropic, ModelID.make("my-sonnet")) + const model = yield* Provider.use.getModel(ProviderV2.ID.anthropic, ProviderV2.ModelID.make("my-sonnet")) expect(model).toBeDefined() expect(String(model.id)).toBe("my-sonnet") expect(model.name).toBe("My Sonnet Alias") @@ -481,7 +485,7 @@ it.instance( Effect.gen(function* () { const providers = yield* list // api field is stored on model.api.url, used by getSDK to set baseURL - expect(providers[ProviderID.make("custom-api")].models["model-1"].api.url).toBe("https://api.example.com/v1") + expect(providers[ProviderV2.ID.make("custom-api")].models["model-1"].api.url).toBe("https://api.example.com/v1") }), { config: { @@ -503,7 +507,7 @@ it.instance( "explicit baseURL overrides api field", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("custom-api")].options.baseURL).toBe("https://custom.override.com/v1") + expect(providers[ProviderV2.ID.make("custom-api")].options.baseURL).toBe("https://custom.override.com/v1") }), { config: { @@ -526,7 +530,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.name).toBe("Custom Name for Sonnet") expect(model.capabilities.toolcall).toBe(true) expect(model.capabilities.attachment).toBe(true) @@ -544,7 +548,7 @@ it.instance( Effect.gen(function* () { yield* set("OPENAI_API_KEY", "test-openai-key") const providers = yield* list - expect(providers[ProviderID.openai]).toBeUndefined() + expect(providers[ProviderV2.ID.openai]).toBeUndefined() }), { config: { disabled_providers: ["openai"] } }, ) @@ -565,8 +569,8 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - const models = Object.keys(providers[ProviderID.anthropic].models) + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + const models = Object.keys(providers[ProviderV2.ID.anthropic].models) expect(models).toContain("claude-sonnet-4-20250514") expect(models).not.toContain("claude-opus-4-20250514") expect(models.length).toBe(1) @@ -587,7 +591,7 @@ it.instance( "model modalities default correctly", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.make("test-provider")].models["test-model"] + const model = providers[ProviderV2.ID.make("test-provider")].models["test-model"] expect(model.capabilities.input.text).toBe(true) expect(model.capabilities.output.text).toBe(true) }), @@ -610,7 +614,7 @@ it.instance( "model with custom cost values", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.make("test-provider")].models["test-model"] + const model = providers[ProviderV2.ID.make("test-provider")].models["test-model"] expect(model.cost.input).toBe(5) expect(model.cost.output).toBe(15) expect(model.cost.cache.read).toBe(2.5) @@ -641,7 +645,7 @@ it.instance( it.instance("getSmallModel returns appropriate small model", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const model = yield* Provider.use.getSmallModel(ProviderID.anthropic) + const model = yield* Provider.use.getSmallModel(ProviderV2.ID.anthropic) expect(model).toBeDefined() expect(model?.id).toContain("haiku") }), @@ -651,7 +655,7 @@ it.instance( "getSmallModel respects config small_model override", Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const model = yield* Provider.use.getSmallModel(ProviderID.anthropic) + const model = yield* Provider.use.getSmallModel(ProviderV2.ID.anthropic) expect(model).toBeDefined() expect(String(model?.providerID)).toBe("anthropic") expect(String(model?.id)).toBe("claude-sonnet-4-20250514") @@ -663,7 +667,7 @@ it.instance( "getSmallModel ignores invalid config small_model", Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const model = yield* Provider.use.getSmallModel(ProviderID.anthropic) + const model = yield* Provider.use.getSmallModel(ProviderV2.ID.anthropic) expect(model).toBeUndefined() }), { config: { small_model: "anthropic/not-a-real-model" } }, @@ -690,10 +694,10 @@ it.instance( yield* set("ANTHROPIC_API_KEY", "test-anthropic-key") yield* set("OPENAI_API_KEY", "test-openai-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - expect(providers[ProviderID.openai]).toBeDefined() - expect(providers[ProviderID.anthropic].options.timeout).toBe(30000) - expect(providers[ProviderID.openai].options.timeout).toBe(60000) + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.openai]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic].options.timeout).toBe(30000) + expect(providers[ProviderV2.ID.openai].options.timeout).toBe(60000) }), { config: { @@ -709,9 +713,9 @@ it.instance( "provider with custom npm package", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("local-llm")]).toBeDefined() - expect(providers[ProviderID.make("local-llm")].models["llama-3"].api.npm).toBe("@ai-sdk/openai-compatible") - expect(providers[ProviderID.make("local-llm")].options.baseURL).toBe("http://localhost:11434/v1") + expect(providers[ProviderV2.ID.make("local-llm")]).toBeDefined() + expect(providers[ProviderV2.ID.make("local-llm")].models["llama-3"].api.npm).toBe("@ai-sdk/openai-compatible") + expect(providers[ProviderV2.ID.make("local-llm")].options.baseURL).toBe("http://localhost:11434/v1") }), { config: { @@ -735,7 +739,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.anthropic].models["sonnet"].name).toBe("sonnet") + expect(providers[ProviderV2.ID.anthropic].models["sonnet"].name).toBe("sonnet") }), { config: { @@ -753,9 +757,9 @@ it.instance( Effect.gen(function* () { yield* set("MULTI_ENV_KEY_1", "test-key") const providers = yield* list - expect(providers[ProviderID.make("multi-env")]).toBeDefined() + expect(providers[ProviderV2.ID.make("multi-env")]).toBeDefined() // When multiple env options exist, key should NOT be auto-set - expect(providers[ProviderID.make("multi-env")].key).toBeUndefined() + expect(providers[ProviderV2.ID.make("multi-env")].key).toBeUndefined() }), { config: { @@ -777,9 +781,9 @@ it.instance( Effect.gen(function* () { yield* set("SINGLE_ENV_KEY", "my-api-key") const providers = yield* list - expect(providers[ProviderID.make("single-env")]).toBeDefined() + expect(providers[ProviderV2.ID.make("single-env")]).toBeDefined() // Single env option should auto-set key - expect(providers[ProviderID.make("single-env")].key).toBe("my-api-key") + expect(providers[ProviderV2.ID.make("single-env")].key).toBe("my-api-key") }), { config: { @@ -801,7 +805,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.cost.input).toBe(999) expect(model.cost.output).toBe(888) }), @@ -820,9 +824,9 @@ it.instance( "completely new provider not in database can be configured", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("brand-new-provider")]).toBeDefined() - expect(providers[ProviderID.make("brand-new-provider")].name).toBe("Brand New") - const model = providers[ProviderID.make("brand-new-provider")].models["new-model"] + expect(providers[ProviderV2.ID.make("brand-new-provider")]).toBeDefined() + expect(providers[ProviderV2.ID.make("brand-new-provider")].name).toBe("Brand New") + const model = providers[ProviderV2.ID.make("brand-new-provider")].models["new-model"] expect(model.capabilities.reasoning).toBe(true) expect(model.capabilities.attachment).toBe(true) expect(model.capabilities.input.image).toBe(true) @@ -861,11 +865,11 @@ it.instance( yield* set("GOOGLE_GENERATIVE_AI_API_KEY", "test-google") const providers = yield* list // anthropic: in enabled, not in disabled = allowed - expect(providers[ProviderID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() // openai: in enabled, but also in disabled = NOT allowed - expect(providers[ProviderID.openai]).toBeUndefined() + expect(providers[ProviderV2.ID.openai]).toBeUndefined() // google: not in enabled = NOT allowed (even though not disabled) - expect(providers[ProviderID.google]).toBeUndefined() + expect(providers[ProviderV2.ID.google]).toBeUndefined() }), { // enabled_providers takes precedence — only these are considered @@ -878,7 +882,7 @@ it.instance( "model with tool_call false", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("no-tools")].models["basic-model"].capabilities.toolcall).toBe(false) + expect(providers[ProviderV2.ID.make("no-tools")].models["basic-model"].capabilities.toolcall).toBe(false) }), { config: { @@ -899,7 +903,7 @@ it.instance( "model defaults tool_call to true when not specified", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("default-tools")].models["model"].capabilities.toolcall).toBe(true) + expect(providers[ProviderV2.ID.make("default-tools")].models["model"].capabilities.toolcall).toBe(true) }), { config: { @@ -920,7 +924,7 @@ it.instance( "model headers are preserved", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.make("headers-provider")].models["model"] + const model = providers[ProviderV2.ID.make("headers-provider")].models["model"] expect(model.headers).toEqual({ "X-Custom-Header": "custom-value", Authorization: "Bearer special-token", @@ -955,7 +959,7 @@ it.instance( yield* set("FALLBACK_KEY", "fallback-api-key") const providers = yield* list // Provider should load because fallback env var is set - expect(providers[ProviderID.make("fallback-env")]).toBeDefined() + expect(providers[ProviderV2.ID.make("fallback-env")]).toBeDefined() }), { config: { @@ -975,8 +979,14 @@ it.instance( it.instance("getModel returns consistent results", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const model1 = yield* Provider.use.getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514")) - const model2 = yield* Provider.use.getModel(ProviderID.anthropic, ModelID.make("claude-sonnet-4-20250514")) + const model1 = yield* Provider.use.getModel( + ProviderV2.ID.anthropic, + ProviderV2.ModelID.make("claude-sonnet-4-20250514"), + ) + const model2 = yield* Provider.use.getModel( + ProviderV2.ID.anthropic, + ProviderV2.ModelID.make("claude-sonnet-4-20250514"), + ) expect(model1.providerID).toEqual(model2.providerID) expect(model1.id).toEqual(model2.id) expect(model1).toEqual(model2) @@ -987,7 +997,7 @@ it.instance( "provider name defaults to id when not in database", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("my-custom-id")].name).toBe("my-custom-id") + expect(providers[ProviderV2.ID.make("my-custom-id")].name).toBe("my-custom-id") }), { config: { @@ -1006,7 +1016,9 @@ it.instance( it.instance("ModelNotFoundError includes suggestions for typos", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const error = yield* Provider.use.getModel(ProviderID.anthropic, ModelID.make("claude-sonet-4")).pipe(Effect.flip) + const error = yield* Provider.use + .getModel(ProviderV2.ID.anthropic, ProviderV2.ModelID.make("claude-sonet-4")) + .pipe(Effect.flip) expect(error.suggestions).toBeDefined() expect((error.suggestions ?? []).length).toBeGreaterThan(0) }), @@ -1016,7 +1028,7 @@ it.instance("ModelNotFoundError for provider includes suggestions", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const error = yield* Provider.use - .getModel(ProviderID.make("antropic"), ModelID.make("claude-sonnet-4")) + .getModel(ProviderV2.ID.make("antropic"), ProviderV2.ModelID.make("claude-sonnet-4")) .pipe(Effect.flip) expect(error.suggestions).toBeDefined() expect(error.suggestions).toContain("anthropic") @@ -1027,7 +1039,7 @@ it.instance("ModelNotFoundError suggests catalog models for unloaded providers", Effect.gen(function* () { yield* remove("OPENCODE_API_KEY") const error = yield* Provider.use - .getModel(ProviderID.opencode, ModelID.make("claude-haiku-fake-model")) + .getModel(ProviderV2.ID.opencode, ProviderV2.ModelID.make("claude-haiku-fake-model")) .pipe(Effect.flip) if (!Provider.ModelNotFoundError.isInstance(error)) throw error expect(error.suggestions ?? []).toContain("claude-haiku-4-5") @@ -1036,7 +1048,7 @@ it.instance("ModelNotFoundError suggests catalog models for unloaded providers", it.instance("getProvider returns undefined for nonexistent provider", () => Effect.gen(function* () { - const provider = yield* Provider.Service.use((svc) => svc.getProvider(ProviderID.make("nonexistent"))) + const provider = yield* Provider.Service.use((svc) => svc.getProvider(ProviderV2.ID.make("nonexistent"))) expect(provider).toBeUndefined() }), ) @@ -1044,7 +1056,7 @@ it.instance("getProvider returns undefined for nonexistent provider", () => it.instance("getProvider returns provider info", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const provider = yield* Provider.use.getProvider(ProviderID.anthropic) + const provider = yield* Provider.use.getProvider(ProviderV2.ID.anthropic) expect(provider).toBeDefined() expect(String(provider?.id)).toBe("anthropic") }), @@ -1053,7 +1065,7 @@ it.instance("getProvider returns provider info", () => it.instance("closest returns undefined when no partial match found", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") - const result = yield* Provider.use.closest(ProviderID.anthropic, ["nonexistent-xyz-model"]) + const result = yield* Provider.use.closest(ProviderV2.ID.anthropic, ["nonexistent-xyz-model"]) expect(result).toBeUndefined() }), ) @@ -1062,7 +1074,7 @@ it.instance("closest checks multiple query terms in order", () => Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") // First term won't match, second will - const result = yield* Provider.use.closest(ProviderID.anthropic, ["nonexistent", "haiku"]) + const result = yield* Provider.use.closest(ProviderV2.ID.anthropic, ["nonexistent", "haiku"]) expect(result).toBeDefined() expect(result?.modelID).toContain("haiku") }), @@ -1072,7 +1084,7 @@ it.instance( "model limit defaults to zero when not specified", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.make("no-limit")].models["model"] + const model = providers[ProviderV2.ID.make("no-limit")].models["model"] expect(model.limit.context).toBe(0) expect(model.limit.output).toBe(0) }), @@ -1097,10 +1109,10 @@ it.instance( yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list // Custom options should be merged - expect(providers[ProviderID.anthropic].options.timeout).toBe(30000) - expect(providers[ProviderID.anthropic].options.headers["X-Custom"]).toBe("custom-value") + expect(providers[ProviderV2.ID.anthropic].options.timeout).toBe(30000) + expect(providers[ProviderV2.ID.anthropic].options.headers["X-Custom"]).toBe("custom-value") // anthropic custom loader adds its own headers, they should coexist - expect(providers[ProviderID.anthropic].options.headers["anthropic-beta"]).toBeDefined() + expect(providers[ProviderV2.ID.anthropic].options.headers["anthropic-beta"]).toBeDefined() }), { config: { @@ -1113,7 +1125,7 @@ it.instance( "hosted nvidia provider adds billing origin header", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("nvidia")].options.headers).toEqual({ + expect(providers[ProviderV2.ID.make("nvidia")].options.headers).toEqual({ "HTTP-Referer": "https://opencode.ai/", "X-Title": "opencode", "X-BILLING-INVOKE-ORIGIN": "OpenCode", @@ -1126,7 +1138,7 @@ it.instance( "custom nvidia baseURL adds billing origin header", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("nvidia")].options.headers).toEqual({ + expect(providers[ProviderV2.ID.make("nvidia")].options.headers).toEqual({ "HTTP-Referer": "https://opencode.ai/", "X-Title": "opencode", "X-BILLING-INVOKE-ORIGIN": "OpenCode", @@ -1139,7 +1151,7 @@ it.instance( "explicit nvidia billing origin header is preserved", Effect.gen(function* () { const providers = yield* list - expect(providers[ProviderID.make("nvidia")].options.headers["X-BILLING-INVOKE-ORIGIN"]).toBe("CustomOrigin") + expect(providers[ProviderV2.ID.make("nvidia")].options.headers["X-BILLING-INVOKE-ORIGIN"]).toBe("CustomOrigin") }), { config: { @@ -1161,7 +1173,7 @@ it.instance( Effect.gen(function* () { yield* set("OPENAI_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.openai].models["my-custom-model"] + const model = providers[ProviderV2.ID.openai].models["my-custom-model"] expect(model).toBeDefined() expect(model.api.npm).toBe("@ai-sdk/openai") }), @@ -1187,15 +1199,15 @@ it.instance( Effect.gen(function* () { yield* set("OPENROUTER_API_KEY", "test-api-key") const providers = yield* list - expect(providers[ProviderID.openrouter]).toBeDefined() + expect(providers[ProviderV2.ID.openrouter]).toBeDefined() // New model not in database should inherit api.url from provider - const intellect = providers[ProviderID.openrouter].models["prime-intellect/intellect-3"] + const intellect = providers[ProviderV2.ID.openrouter].models["prime-intellect/intellect-3"] expect(intellect).toBeDefined() expect(intellect.api.url).toBe("https://openrouter.ai/api/v1") // Another new model should also inherit api.url - const deepseek = providers[ProviderID.openrouter].models["deepseek/deepseek-r1-0528"] + const deepseek = providers[ProviderV2.ID.openrouter].models["deepseek/deepseek-r1-0528"] expect(deepseek).toBeDefined() expect(deepseek.api.url).toBe("https://openrouter.ai/api/v1") expect(deepseek.name).toBe("DeepSeek R1") @@ -1308,7 +1320,7 @@ it.instance("model variants are generated for reasoning models", () => yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list // Claude sonnet 4 has reasoning capability - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.capabilities.reasoning).toBe(true) expect(model.variants).toBeDefined() expect(Object.keys(model.variants!).length).toBeGreaterThan(0) @@ -1320,7 +1332,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants).toBeDefined() expect(model.variants!["high"]).toBeUndefined() // max variant should still exist @@ -1342,7 +1354,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants!["high"]).toBeDefined() expect(model.variants!["high"].thinking.budgetTokens).toBe(20000) }), @@ -1366,7 +1378,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants!["max"]).toBeDefined() expect(model.variants!["max"].disabled).toBeUndefined() expect(model.variants!["max"].customField).toBe("test") @@ -1391,7 +1403,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants).toBeDefined() expect(Object.keys(model.variants!).length).toBe(0) }), @@ -1415,7 +1427,7 @@ it.instance( Effect.gen(function* () { yield* set("ANTHROPIC_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.anthropic].models["claude-sonnet-4-20250514"] + const model = providers[ProviderV2.ID.anthropic].models["claude-sonnet-4-20250514"] expect(model.variants!["high"]).toBeDefined() // Should have both the generated thinking config and the custom option expect(model.variants!["high"].thinking).toBeDefined() @@ -1439,7 +1451,7 @@ it.instance( Effect.gen(function* () { yield* set("OPENAI_API_KEY", "test-api-key") const providers = yield* list - const model = providers[ProviderID.openai].models["gpt-5"] + const model = providers[ProviderV2.ID.openai].models["gpt-5"] expect(model.variants).toBeDefined() expect(model.variants!["high"]).toBeUndefined() // Other variants should still exist @@ -1456,7 +1468,7 @@ it.instance( "custom model with variants enabled and disabled", Effect.gen(function* () { const providers = yield* list - const model = providers[ProviderID.make("custom-reasoning")].models["reasoning-model"] + const model = providers[ProviderV2.ID.make("custom-reasoning")].models["reasoning-model"] expect(model.variants).toBeDefined() // Enabled variants should exist expect(model.variants!["low"]).toBeDefined() @@ -1506,8 +1518,8 @@ it.instance( Effect.gen(function* () { yield* set("GOOGLE_APPLICATION_CREDENTIALS", "test-creds") const providers = yield* list - expect(providers[ProviderID.make("vertex-proxy")]).toBeDefined() - expect(providers[ProviderID.make("vertex-proxy")].options.baseURL).toBe("https://my-proxy.com/v1") + expect(providers[ProviderV2.ID.make("vertex-proxy")]).toBeDefined() + expect(providers[ProviderV2.ID.make("vertex-proxy")].options.baseURL).toBe("https://my-proxy.com/v1") }), { config: { @@ -1534,7 +1546,7 @@ it.instance( Effect.gen(function* () { yield* set("GOOGLE_APPLICATION_CREDENTIALS", "test-creds") const providers = yield* list - const model = providers[ProviderID.make("vertex-openai")].models["gpt-4"] + const model = providers[ProviderV2.ID.make("vertex-openai")].models["gpt-4"] expect(model).toBeDefined() expect(model.api.npm).toBe("@ai-sdk/openai-compatible") }), @@ -1563,7 +1575,10 @@ it.instance("Google Vertex: uses REP endpoint for Claude continental multi-regio yield* set("GOOGLE_CLOUD_PROJECT", "test-project") yield* set("VERTEX_LOCATION", "eu") const provider = yield* Provider.Service - const model = yield* provider.getModel(ProviderID.make("google-vertex"), ModelID.make("claude-sonnet-4-6@default")) + const model = yield* provider.getModel( + ProviderV2.ID.make("google-vertex"), + ProviderV2.ModelID.make("claude-sonnet-4-6@default"), + ) const language = yield* provider.getLanguage(model) expect(languageBaseURL(language)).toBe( "https://aiplatform.eu.rep.googleapis.com/v1/projects/test-project/locations/eu/publishers/anthropic/models", @@ -1577,8 +1592,8 @@ it.instance("Google Vertex Anthropic: uses REP endpoint for continental multi-re yield* set("VERTEX_LOCATION", "us") const provider = yield* Provider.Service const model = yield* provider.getModel( - ProviderID.make("google-vertex-anthropic"), - ModelID.make("claude-sonnet-4-6@default"), + ProviderV2.ID.make("google-vertex-anthropic"), + ProviderV2.ModelID.make("claude-sonnet-4-6@default"), ) const language = yield* provider.getLanguage(model) expect(languageBaseURL(language)).toBe( @@ -1592,7 +1607,10 @@ it.instance("Google Vertex: keeps regional Claude endpoints unchanged", () => yield* set("GOOGLE_CLOUD_PROJECT", "test-project") yield* set("VERTEX_LOCATION", "europe-west1") const provider = yield* Provider.Service - const model = yield* provider.getModel(ProviderID.make("google-vertex"), ModelID.make("claude-sonnet-4-6@default")) + const model = yield* provider.getModel( + ProviderV2.ID.make("google-vertex"), + ProviderV2.ModelID.make("claude-sonnet-4-6@default"), + ) const language = yield* provider.getLanguage(model) expect(languageBaseURL(language)).toBe( "https://europe-west1-aiplatform.googleapis.com/v1/projects/test-project/locations/europe-west1/publishers/anthropic/models", @@ -1606,7 +1624,7 @@ it.instance("cloudflare-ai-gateway loads with env variables", () => yield* set("CLOUDFLARE_GATEWAY_ID", "test-gateway") yield* set("CLOUDFLARE_API_TOKEN", "test-token") const providers = yield* list - expect(providers[ProviderID.make("cloudflare-ai-gateway")]).toBeDefined() + expect(providers[ProviderV2.ID.make("cloudflare-ai-gateway")]).toBeDefined() }), ) @@ -1617,8 +1635,8 @@ it.instance( yield* set("CLOUDFLARE_GATEWAY_ID", "test-gateway") yield* set("CLOUDFLARE_API_TOKEN", "test-token") const providers = yield* list - expect(providers[ProviderID.make("cloudflare-ai-gateway")]).toBeDefined() - expect(providers[ProviderID.make("cloudflare-ai-gateway")].options.metadata).toEqual({ + expect(providers[ProviderV2.ID.make("cloudflare-ai-gateway")]).toBeDefined() + expect(providers[ProviderV2.ID.make("cloudflare-ai-gateway")].options.metadata).toEqual({ invoked_by: "test", project: "opencode", }) @@ -1681,14 +1699,14 @@ it.effect("plugin config providers persist after instance dispose", () => }).pipe(provideInstanceEffect(dir)) const first = yield* loadAndList - expect(first[ProviderID.make("demo")]).toBeDefined() - expect(first[ProviderID.make("demo")].models[ModelID.make("chat")]).toBeDefined() + expect(first[ProviderV2.ID.make("demo")]).toBeDefined() + expect(first[ProviderV2.ID.make("demo")].models[ProviderV2.ModelID.make("chat")]).toBeDefined() yield* Effect.promise(() => disposeAllInstances()) const second = yield* loadAndList - expect(second[ProviderID.make("demo")]).toBeDefined() - expect(second[ProviderID.make("demo")].models[ModelID.make("chat")]).toBeDefined() + expect(second[ProviderV2.ID.make("demo")]).toBeDefined() + expect(second[ProviderV2.ID.make("demo")].models[ProviderV2.ModelID.make("chat")]).toBeDefined() }).pipe(provideMultiInstance), ) @@ -1721,8 +1739,8 @@ it.instance( yield* set("ANTHROPIC_API_KEY", "test-anthropic-key") yield* set("OPENAI_API_KEY", "test-openai-key") const providers = yield* list - expect(providers[ProviderID.anthropic]).toBeDefined() - expect(providers[ProviderID.openai]).toBeUndefined() + expect(providers[ProviderV2.ID.anthropic]).toBeDefined() + expect(providers[ProviderV2.ID.openai]).toBeUndefined() }), ) diff --git a/packages/opencode/test/provider/transform.test.ts b/packages/opencode/test/provider/transform.test.ts index 2bce1585608c..7fb22ddf5770 100644 --- a/packages/opencode/test/provider/transform.test.ts +++ b/packages/opencode/test/provider/transform.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test" import { ProviderTransform } from "@/provider/transform" -import { ModelID, ProviderID } from "../../src/provider/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" describe("ProviderTransform.options - setCacheKey", () => { const sessionID = "test-session-123" @@ -1089,8 +1089,8 @@ describe("ProviderTransform.message - DeepSeek reasoning content", () => { const result = ProviderTransform.message( msgs, { - id: ModelID.make("deepseek/deepseek-chat"), - providerID: ProviderID.make("deepseek"), + id: ProviderV2.ModelID.make("deepseek/deepseek-chat"), + providerID: ProviderV2.ID.make("deepseek"), api: { id: "deepseek-chat", url: "https://api.deepseek.com", @@ -1151,8 +1151,8 @@ describe("ProviderTransform.message - DeepSeek reasoning content", () => { const result = ProviderTransform.message( msgs, { - id: ModelID.make("openai/gpt-4"), - providerID: ProviderID.make("openai"), + id: ProviderV2.ModelID.make("openai/gpt-4"), + providerID: ProviderV2.ID.make("openai"), api: { id: "gpt-4", url: "https://api.openai.com", @@ -2681,12 +2681,14 @@ describe("ProviderTransform.variants", () => { expect(result.xhigh).toEqual({ thinking: { type: "adaptive", + display: "summarized", }, effort: "xhigh", }) expect(result.max).toEqual({ thinking: { type: "adaptive", + display: "summarized", }, effort: "max", }) @@ -2706,6 +2708,47 @@ describe("ProviderTransform.variants", () => { expect(Object.keys(result)).toEqual(["low", "medium", "high", "xhigh", "max"]) }) + test("anthropic opus 4.8 forces display summarized for adaptive reasoning", () => { + const model = createMockModel({ + id: "anthropic/claude-opus-4-8", + providerID: "gateway", + api: { + id: "anthropic/claude-opus-4-8", + url: "https://gateway.ai", + npm: "@ai-sdk/gateway", + }, + }) + const result = ProviderTransform.variants(model) + expect(Object.keys(result)).toEqual(["low", "medium", "high", "xhigh", "max"]) + expect(result.high).toEqual({ + thinking: { + type: "adaptive", + display: "summarized", + }, + effort: "high", + }) + }) + + test("anthropic opus 4.6 omits display so it keeps the summarized default", () => { + const model = createMockModel({ + id: "anthropic/claude-opus-4-6", + providerID: "gateway", + api: { + id: "anthropic/claude-opus-4-6", + url: "https://gateway.ai", + npm: "@ai-sdk/gateway", + }, + }) + const result = ProviderTransform.variants(model) + expect(Object.keys(result)).toEqual(["low", "medium", "high", "max"]) + expect(result.high).toEqual({ + thinking: { + type: "adaptive", + }, + effort: "high", + }) + }) + test("anthropic models return anthropic thinking options", () => { const model = createMockModel({ id: "anthropic/claude-sonnet-4", @@ -3223,6 +3266,12 @@ describe("ProviderTransform.variants", () => { efforts: ["low", "medium", "high", "xhigh", "max"], expectedHigh: { thinking: { type: "adaptive", display: "summarized" }, effort: "high" }, }, + { + name: "opus 4.8", + apiIds: ["claude-opus-4-8", "claude-opus-4.8"], + efforts: ["low", "medium", "high", "xhigh", "max"], + expectedHigh: { thinking: { type: "adaptive", display: "summarized" }, effort: "high" }, + }, ]) { for (const apiId of testCase.apiIds) { test(`${testCase.name} ${apiId} returns supported reasoning efforts`, () => { @@ -3292,6 +3341,30 @@ describe("ProviderTransform.variants", () => { }) }) + describe("@ai-sdk/google-vertex/anthropic", () => { + test("opus 4.8 uses adaptive reasoning for Vertex model IDs", () => { + const result = ProviderTransform.variants( + createMockModel({ + id: "google-vertex-anthropic/claude-opus-4-8@default", + providerID: "google-vertex-anthropic", + api: { + id: "claude-opus-4-8@default", + url: "https://us-central1-aiplatform.googleapis.com", + npm: "@ai-sdk/google-vertex/anthropic", + }, + }), + ) + expect(Object.keys(result)).toEqual(["low", "medium", "high", "xhigh", "max"]) + expect(result.high).toEqual({ + thinking: { + type: "adaptive", + display: "summarized", + }, + effort: "high", + }) + }) + }) + describe("@ai-sdk/amazon-bedrock", () => { test("anthropic sonnet 4.6 returns adaptive reasoning options", () => { const model = createMockModel({ @@ -3341,6 +3414,28 @@ describe("ProviderTransform.variants", () => { }) }) + test("anthropic opus 4.8 returns adaptive reasoning options with xhigh", () => { + const result = ProviderTransform.variants( + createMockModel({ + id: "bedrock/anthropic-claude-opus-4.8", + providerID: "bedrock", + api: { + id: "anthropic.claude-opus-4.8", + url: "https://bedrock.amazonaws.com", + npm: "@ai-sdk/amazon-bedrock", + }, + }), + ) + expect(Object.keys(result)).toEqual(["low", "medium", "high", "xhigh", "max"]) + expect(result.high).toEqual({ + reasoningConfig: { + type: "adaptive", + maxReasoningEffort: "high", + display: "summarized", + }, + }) + }) + test("returns WIDELY_SUPPORTED_EFFORTS with reasoningConfig", () => { const model = createMockModel({ id: "bedrock/llama-4", @@ -3486,142 +3581,86 @@ describe("ProviderTransform.variants", () => { }) describe("@jerome-benoit/sap-ai-provider-v2", () => { - test("anthropic models return thinking variants", () => { - const model = createMockModel({ - id: "sap-ai-core/anthropic--claude-sonnet-4", + const sapModel = (apiId: string) => + createMockModel({ + id: `sap-ai-core/${apiId}`, providerID: "sap-ai-core", api: { - id: "anthropic--claude-sonnet-4", + id: apiId, url: "https://api.ai.sap", npm: "@jerome-benoit/sap-ai-provider-v2", }, }) - const result = ProviderTransform.variants(model) - expect(Object.keys(result)).toEqual(["high", "max"]) - expect(result.high).toEqual({ - thinking: { - type: "enabled", - budgetTokens: 16000, - }, - }) - expect(result.max).toEqual({ - thinking: { - type: "enabled", - budgetTokens: 31999, - }, - }) - }) - test("anthropic 4.6 models return adaptive thinking variants", () => { - const model = createMockModel({ - id: "sap-ai-core/anthropic--claude-sonnet-4-6", - providerID: "sap-ai-core", - api: { - id: "anthropic--claude-sonnet-4-6", - url: "https://api.ai.sap", - npm: "@jerome-benoit/sap-ai-provider-v2", - }, - }) - const result = ProviderTransform.variants(model) - expect(Object.keys(result)).toEqual(["low", "medium", "high", "max"]) - expect(result.low).toEqual({ - thinking: { - type: "adaptive", - }, - effort: "low", - }) - expect(result.max).toEqual({ - thinking: { - type: "adaptive", - }, - effort: "max", - }) - }) + for (const testCase of [ + { + name: "sonnet 4.6", + apiIds: ["anthropic--claude-sonnet-4-6"], + efforts: ["low", "medium", "high", "max"], + expectedHigh: { thinking: { type: "adaptive" }, effort: "high" }, + }, + { + name: "opus 4.6", + apiIds: ["anthropic--claude-4.6-opus", "anthropic--claude-4-6-opus"], + efforts: ["low", "medium", "high", "max"], + expectedHigh: { thinking: { type: "adaptive" }, effort: "high" }, + }, + { + name: "opus 4.7", + apiIds: ["anthropic--claude-4.7-opus", "anthropic--claude-4-7-opus"], + efforts: ["low", "medium", "high", "xhigh", "max"], + expectedHigh: { thinking: { type: "adaptive", display: "summarized" }, effort: "high" }, + }, + { + name: "opus 4.8", + apiIds: ["anthropic--claude-4.8-opus", "anthropic--claude-4-8-opus"], + efforts: ["low", "medium", "high", "xhigh", "max"], + expectedHigh: { thinking: { type: "adaptive", display: "summarized" }, effort: "high" }, + }, + ]) { + for (const apiId of testCase.apiIds) { + test(`${testCase.name} ${apiId} returns adaptive thinking variants`, () => { + const result = ProviderTransform.variants(sapModel(apiId)) + expect(Object.keys(result)).toEqual(testCase.efforts) + expect(result.high).toEqual(testCase.expectedHigh) + if (testCase.efforts.includes("xhigh")) { + expect(result.xhigh).toEqual({ ...testCase.expectedHigh, effort: "xhigh" }) + } + }) + } + } - test("gemini 2.5 models return thinkingConfig variants", () => { - const model = createMockModel({ - id: "sap-ai-core/gcp--gemini-2.5-pro", - providerID: "sap-ai-core", - api: { - id: "gcp--gemini-2.5-pro", - url: "https://api.ai.sap", - npm: "@jerome-benoit/sap-ai-provider-v2", - }, - }) - const result = ProviderTransform.variants(model) + test("anthropic sonnet 4 returns budget-tokens variants", () => { + const result = ProviderTransform.variants(sapModel("anthropic--claude-sonnet-4")) expect(Object.keys(result)).toEqual(["high", "max"]) - expect(result.high).toEqual({ - thinkingConfig: { - includeThoughts: true, - thinkingBudget: 16000, - }, - }) - expect(result.max).toEqual({ - thinkingConfig: { - includeThoughts: true, - thinkingBudget: 24576, - }, - }) + expect(result.high).toEqual({ thinking: { type: "enabled", budgetTokens: 16000 } }) + expect(result.max).toEqual({ thinking: { type: "enabled", budgetTokens: 31999 } }) }) - test("gpt models return reasoningEffort variants", () => { - const model = createMockModel({ - id: "sap-ai-core/azure-openai--gpt-4o", - providerID: "sap-ai-core", - api: { - id: "azure-openai--gpt-4o", - url: "https://api.ai.sap", - npm: "@jerome-benoit/sap-ai-provider-v2", - }, - }) - const result = ProviderTransform.variants(model) - expect(Object.keys(result)).toEqual(["low", "medium", "high"]) - expect(result.low).toEqual({ reasoningEffort: "low" }) - expect(result.high).toEqual({ reasoningEffort: "high" }) + test("gemini 2.5 returns thinkingConfig variants", () => { + const result = ProviderTransform.variants(sapModel("gcp--gemini-2.5-pro")) + expect(Object.keys(result)).toEqual(["high", "max"]) + expect(result.high).toEqual({ thinkingConfig: { includeThoughts: true, thinkingBudget: 16000 } }) + expect(result.max).toEqual({ thinkingConfig: { includeThoughts: true, thinkingBudget: 24576 } }) }) - test("o-series models return reasoningEffort variants", () => { - const model = createMockModel({ - id: "sap-ai-core/azure-openai--o3-mini", - providerID: "sap-ai-core", - api: { - id: "azure-openai--o3-mini", - url: "https://api.ai.sap", - npm: "@jerome-benoit/sap-ai-provider-v2", - }, + for (const apiId of ["azure-openai--gpt-4o", "azure-openai--o3-mini"]) { + test(`${apiId} returns reasoningEffort variants`, () => { + const result = ProviderTransform.variants(sapModel(apiId)) + expect(Object.keys(result)).toEqual(["low", "medium", "high"]) + expect(result.low).toEqual({ reasoningEffort: "low" }) + expect(result.high).toEqual({ reasoningEffort: "high" }) }) - const result = ProviderTransform.variants(model) - expect(Object.keys(result)).toEqual(["low", "medium", "high"]) - expect(result.low).toEqual({ reasoningEffort: "low" }) - expect(result.high).toEqual({ reasoningEffort: "high" }) - }) + } - test("sonar models return empty object", () => { - const model = createMockModel({ - id: "sap-ai-core/perplexity--sonar-pro", - providerID: "sap-ai-core", - api: { - id: "perplexity--sonar-pro", - url: "https://api.ai.sap", - npm: "@jerome-benoit/sap-ai-provider-v2", - }, + for (const apiId of ["perplexity--sonar-pro", "mistral--mistral-large"]) { + test(`${apiId} returns empty object`, () => { + expect(ProviderTransform.variants(sapModel(apiId))).toEqual({}) }) - const result = ProviderTransform.variants(model) - expect(result).toEqual({}) - }) + } - test("mistral models return empty object", () => { - const model = createMockModel({ - id: "sap-ai-core/mistral--mistral-large", - providerID: "sap-ai-core", - api: { - id: "mistral--mistral-large", - url: "https://api.ai.sap", - npm: "@jerome-benoit/sap-ai-provider-v2", - }, - }) - const result = ProviderTransform.variants(model) - expect(result).toEqual({}) + test("non-anthropic models with opus-like substrings do not get adaptive thinking", () => { + expect(ProviderTransform.variants(sapModel("aws--llama-opus-4.7-fake"))).toEqual({}) }) }) diff --git a/packages/opencode/test/pty/info-schema.test.ts b/packages/opencode/test/pty/info-schema.test.ts new file mode 100644 index 000000000000..429f29b00e9f --- /dev/null +++ b/packages/opencode/test/pty/info-schema.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, test } from "bun:test" +import { Schema } from "effect" +import { Pty } from "../../src/pty" + +// Windows ConPTY (via @lydell/node-pty >= 1.2.0-beta.12) assigns the child pid +// asynchronously: `proc.pid` reads back as 0 at the synchronous spawn point and +// only resolves to the real pid a tick later. `Pty.create` snapshots `proc.pid` +// while building `Info`, so `Info.pid` legitimately carries 0 right after spawn. +// `Pty.Info` must be able to represent that, otherwise every `pty.create` on +// Windows fails to encode/decode and the terminal feature is unusable. +const sample = (pid: number) => ({ + id: "pty_01J5Y5H0AH4Q4NXJ6P4C3P5V2K", + title: "demo", + command: "cmd.exe", + args: [], + cwd: "C:\\", + status: "running", + pid, +}) + +describe("Pty.Info", () => { + test("accepts pid 0 (Windows ConPTY assigns the pid asynchronously)", () => { + expect(Schema.decodeUnknownSync(Pty.Info)(sample(0)).pid).toBe(0) + }) + + test("accepts a positive pid", () => { + expect(Schema.decodeUnknownSync(Pty.Info)(sample(48012)).pid).toBe(48012) + }) + + test("rejects a negative pid", () => { + expect(() => Schema.decodeUnknownSync(Pty.Info)(sample(-1))).toThrow() + }) +}) diff --git a/packages/opencode/test/pty/pty-output-isolation.test.ts b/packages/opencode/test/pty/pty-output-isolation.test.ts index 0fa710f02abb..20975d986ed5 100644 --- a/packages/opencode/test/pty/pty-output-isolation.test.ts +++ b/packages/opencode/test/pty/pty-output-isolation.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "../../src/config/config" import { Plugin } from "../../src/plugin" import { Pty } from "../../src/pty" @@ -10,7 +10,7 @@ type Socket = Parameters[1] const it = testEffect( Pty.layer.pipe( - Layer.provideMerge(Bus.layer), + Layer.provideMerge(EventV2Bridge.defaultLayer), Layer.provideMerge(Config.defaultLayer), Layer.provideMerge(Plugin.defaultLayer), ), diff --git a/packages/opencode/test/pty/pty-session.test.ts b/packages/opencode/test/pty/pty-session.test.ts index 9fda48cc91d2..74c9f70ec312 100644 --- a/packages/opencode/test/pty/pty-session.test.ts +++ b/packages/opencode/test/pty/pty-session.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "../../src/config/config" import { Plugin } from "../../src/plugin" import { Pty } from "../../src/pty" @@ -11,7 +11,7 @@ type PtyEvent = { type: "created" | "exited" | "deleted"; id: PtyID } const it = testEffect( Pty.layer.pipe( - Layer.provideMerge(Bus.layer), + Layer.provideMerge(EventV2Bridge.defaultLayer), Layer.provideMerge(Config.defaultLayer), Layer.provideMerge(Plugin.defaultLayer), ), @@ -19,27 +19,19 @@ const it = testEffect( const ptyTest = process.platform === "win32" ? it.instance.skip : it.instance const subscribePtyEvents = Effect.fn("PtySessionTest.subscribePtyEvents")(function* () { - const bus = yield* Bus.Service + const source = yield* EventV2Bridge.Service const events = yield* Queue.unbounded() - const subscribe = (effect: Effect.Effect<() => void, never, A>) => - Effect.acquireRelease(effect, (off) => Effect.sync(off)) - - yield* subscribe( - bus.subscribeCallback(Pty.Event.Created, (evt) => { - Queue.offerUnsafe(events, { type: "created", id: evt.properties.info.id }) - }), - ) - yield* subscribe( - bus.subscribeCallback(Pty.Event.Exited, (evt) => { - Queue.offerUnsafe(events, { type: "exited", id: evt.properties.id }) - }), - ) - yield* subscribe( - bus.subscribeCallback(Pty.Event.Deleted, (evt) => { - Queue.offerUnsafe(events, { type: "deleted", id: evt.properties.id }) - }), - ) + const unsubscribe = yield* source.listen((event) => { + if (event.type === Pty.Event.Created.type) + Queue.offerUnsafe(events, { type: "created", id: (event.data as typeof Pty.Event.Created.data.Type).info.id }) + if (event.type === Pty.Event.Exited.type) + Queue.offerUnsafe(events, { type: "exited", id: (event.data as typeof Pty.Event.Exited.data.Type).id }) + if (event.type === Pty.Event.Deleted.type) + Queue.offerUnsafe(events, { type: "deleted", id: (event.data as typeof Pty.Event.Deleted.data.Type).id }) + return Effect.void + }) + yield* Effect.addFinalizer(() => unsubscribe) return events }) diff --git a/packages/opencode/test/pty/ticket.test.ts b/packages/opencode/test/pty/ticket.test.ts index 4886f250f942..fa7f9277dea2 100644 --- a/packages/opencode/test/pty/ticket.test.ts +++ b/packages/opencode/test/pty/ticket.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Layer } from "effect" -import { WorkspaceID } from "../../src/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { PtyID } from "../../src/pty/schema" import { PtyTicket } from "../../src/pty/ticket" import { testEffect } from "../lib/effect" @@ -47,10 +47,12 @@ describe("PTY websocket tickets", () => { Effect.gen(function* () { const tickets = yield* PtyTicket.Service const ptyID = PtyID.ascending() - const workspaceID = WorkspaceID.ascending() + const workspaceID = WorkspaceV2.ID.ascending() const issued = yield* tickets.issue({ ptyID, workspaceID }) - expect(yield* tickets.consume({ ptyID, workspaceID: WorkspaceID.ascending(), ticket: issued.ticket })).toBe(false) + expect(yield* tickets.consume({ ptyID, workspaceID: WorkspaceV2.ID.ascending(), ticket: issued.ticket })).toBe( + false, + ) expect(yield* tickets.consume({ ptyID, workspaceID, ticket: issued.ticket })).toBe(true) }), ) diff --git a/packages/opencode/test/question/question.test.ts b/packages/opencode/test/question/question.test.ts index 5f6f87972ea4..5ae076b4391c 100644 --- a/packages/opencode/test/question/question.test.ts +++ b/packages/opencode/test/question/question.test.ts @@ -2,16 +2,23 @@ import { afterEach, expect } from "bun:test" import { Cause, Effect, Exit, Fiber, Layer, Queue } from "effect" import { Question } from "../../src/question" import { InstanceRef } from "../../src/effect/instance-ref" -import { InstanceRuntime } from "../../src/project/instance-runtime" +import { InstanceStore } from "../../src/project/instance-store" import { QuestionID } from "../../src/question/schema" -import { disposeAllInstances, provideInstance, reloadTestInstance, tmpdirScoped } from "../fixture/fixture" +import { disposeAllInstances, provideInstance, testInstanceStoreLayer, tmpdirScoped } from "../fixture/fixture" import { SessionID } from "../../src/session/schema" import { testEffect } from "../lib/effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" const it = testEffect( - Layer.mergeAll(Question.layer.pipe(Layer.provideMerge(Bus.layer)), CrossSpawnSpawner.defaultLayer), + Layer.mergeAll(Question.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer)), CrossSpawnSpawner.defaultLayer), +) +const lifecycle = testEffect( + Layer.mergeAll( + Question.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer)), + CrossSpawnSpawner.defaultLayer, + testInstanceStoreLayer, + ), ) const askEffect = Effect.fn("QuestionTest.ask")(function* (input: { @@ -49,10 +56,13 @@ const rejectAll = Effect.gen(function* () { const waitForPending = Effect.fn("QuestionTest.waitForPending")(function* (count: number) { const question = yield* Question.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const asked = yield* Queue.unbounded() - const off = yield* bus.subscribeCallback(Question.Event.Asked, () => Queue.offerUnsafe(asked, undefined)) - yield* Effect.addFinalizer(() => Effect.sync(off)) + const off = yield* events.listen((event) => { + if (event.type === Question.Event.Asked.type) Queue.offerUnsafe(asked, undefined) + return Effect.void + }) + yield* Effect.addFinalizer(() => off) for (;;) { const pending = yield* question.list() @@ -361,7 +371,7 @@ it.instance( { git: true }, ) -it.live("questions stay isolated by directory", () => +lifecycle.live("questions stay isolated by directory", () => Effect.gen(function* () { const one = yield* tmpdirScoped({ git: true }) const two = yield* tmpdirScoped({ git: true }) @@ -404,7 +414,7 @@ it.live("questions stay isolated by directory", () => }), ) -it.live("pending question rejects on instance dispose", () => +lifecycle.live("pending question rejects on instance dispose", () => Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) const fiber = yield* askEffect({ @@ -423,7 +433,7 @@ it.live("pending question rejects on instance dispose", () => return yield* InstanceRef }).pipe(provideInstance(dir)) if (!ctx) return yield* Effect.die(new Error("missing test instance")) - yield* Effect.promise(() => InstanceRuntime.disposeInstance(ctx)) + yield* InstanceStore.Service.use((store) => store.dispose(ctx)) const exit = yield* Fiber.await(fiber) expect(Exit.isFailure(exit)).toBe(true) @@ -431,7 +441,7 @@ it.live("pending question rejects on instance dispose", () => }), ) -it.live("pending question rejects on instance reload", () => +lifecycle.live("pending question rejects on instance reload", () => Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) const fiber = yield* askEffect({ @@ -446,7 +456,7 @@ it.live("pending question rejects on instance reload", () => }).pipe(provideInstance(dir), Effect.forkScoped) expect(yield* waitForPending(1).pipe(provideInstance(dir))).toHaveLength(1) - yield* Effect.promise(() => reloadTestInstance({ directory: dir })) + yield* InstanceStore.Service.use((store) => store.reload({ directory: dir })) const exit = yield* Fiber.await(fiber) expect(Exit.isFailure(exit)).toBe(true) diff --git a/packages/opencode/test/server/AGENTS.md b/packages/opencode/test/server/AGENTS.md index bed2b526952c..754977375b0e 100644 --- a/packages/opencode/test/server/AGENTS.md +++ b/packages/opencode/test/server/AGENTS.md @@ -4,8 +4,8 @@ Use these patterns for server and HttpApi middleware tests in this directory. - Prefer focused middleware tests with tiny fake routes over full API route trees when testing routing, context, proxying, or middleware policy. - Use `testEffect(...)` with `NodeHttpServer.layerTest` for the primary in-test server and make relative `HttpClient` requests against it. -- Use `HttpRouter.add(...)` probe routes that expose the context under test, such as `WorkspaceRouteContext`, `InstanceRef`, or `WorkspaceRef`. -- Compose middleware in the same order as production when testing interactions, for example `instanceRouterMiddleware.combine(workspaceRouterMiddleware)`. +- Use tiny `HttpApiBuilder` probe groups that declare the typed middleware under test and expose context such as `WorkspaceRouteContext`, `InstanceRef`, or `WorkspaceRef`. +- Declare middleware in the same order as production when testing interactions, for example `InstanceContextMiddleware` followed by `WorkspaceRoutingMiddleware`. - For secondary upstream servers, build Effect `NodeHttpServer.layer(...)` into the current test scope with `Layer.build(...)` so the listener stays alive until the test scope exits. - Avoid `Bun.serve` when testing Effect HTTP middleware. Keep the test in the Effect HTTP stack unless the production path being tested is Bun-specific. - For WebSocket paths, use `Socket.makeWebSocket(...)` from the test client and assert protocol forwarding or frame relay when relevant. diff --git a/packages/opencode/test/server/global-session-list.test.ts b/packages/opencode/test/server/global-session-list.test.ts index df49ae084151..278e36a96631 100644 --- a/packages/opencode/test/server/global-session-list.test.ts +++ b/packages/opencode/test/server/global-session-list.test.ts @@ -27,7 +27,7 @@ describe("session.listGlobal", () => { const firstSession = yield* withSession({ title: "first-session" }) const secondSession = yield* withSession({ title: "second-session" }).pipe(provideInstance(second)) - const sessions = yield* Effect.sync(() => [...SessionNs.listGlobal({ limit: 200 })]) + const sessions = yield* SessionNs.Service.use((session) => session.listGlobal({ limit: 200 })) const ids = sessions.map((session) => session.id) expect(ids).toContain(firstSession.id) @@ -56,12 +56,14 @@ describe("session.listGlobal", () => { yield* SessionNs.Service.use((session) => session.setArchived({ sessionID: archived.id, time: Date.now() })) - const sessions = yield* Effect.sync(() => [...SessionNs.listGlobal({ limit: 200 })]) + const sessions = yield* SessionNs.Service.use((session) => session.listGlobal({ limit: 200 })) const ids = sessions.map((session) => session.id) expect(ids).not.toContain(archived.id) - const allSessions = yield* Effect.sync(() => [...SessionNs.listGlobal({ limit: 200, archived: true })]) + const allSessions = yield* SessionNs.Service.use((session) => + session.listGlobal({ limit: 200, archived: true }), + ) const allIds = allSessions.map((session) => session.id) expect(allIds).toContain(archived.id) @@ -86,13 +88,15 @@ describe("session.listGlobal", () => { ) const second = yield* withSession({ title: "page-two" }) - const page = yield* Effect.sync(() => [...SessionNs.listGlobal({ directory: test.directory, limit: 1 })]) + const page = yield* SessionNs.Service.use((session) => + session.listGlobal({ directory: test.directory, limit: 1 }), + ) expect(page.length).toBe(1) expect(page[0].id).toBe(second.id) - const next = yield* Effect.sync(() => [ - ...SessionNs.listGlobal({ directory: test.directory, limit: 10, cursor: page[0].time.updated }), - ]) + const next = yield* SessionNs.Service.use((session) => + session.listGlobal({ directory: test.directory, limit: 10, cursor: page[0].time.updated }), + ) const ids = next.map((session) => session.id) expect(ids).toContain(first.id) diff --git a/packages/opencode/test/server/httpapi-event-diagnostics.test.ts b/packages/opencode/test/server/httpapi-event-diagnostics.test.ts deleted file mode 100644 index 66bd0bcedd6f..000000000000 --- a/packages/opencode/test/server/httpapi-event-diagnostics.test.ts +++ /dev/null @@ -1,279 +0,0 @@ -// Diagnostic suite for /event SSE delivery. -// -// Each test isolates ONE variable in the publisher chain while keeping the -// subscriber path constant (in-process HttpApi via Server.Default reading the -// SSE body). The pass/fail pattern across tests tells us where the bug lives: -// -// D1 (baseline): publish via Bus.use.publish — mirror of httpapi-event.test.ts -// test 3. Confirms /event SSE delivery works for SOME publish path. -// -// D2: publish N times in quick succession via Bus.use.publish. If the bus -// subscription is acquired correctly there should be no message loss. -// -// D3: publish via SyncEvent.use.run — exercises the same path the HTTP -// handlers use (Session.updatePart → sync.run → bus.publish) without -// the HTTP roundtrip. Tells us whether the sync path itself can deliver -// in-process. -// -// D4: publish via SyncEvent.use.run; subscriber is an in-process Bus -// callback. Confirms pub/sub identity end-to-end without /event SSE. -// -// D5: in-process Bus callback subscriber AND raw /event SSE subscriber -// receive the same publish. If both receive: no bug. If only the -// callback receives: the /event handler has an acquisition race. -// -// D6: same as D5 but the callback subscriber is attached AFTER /event SSE -// subscription is established. Order-of-setup variable. -import { afterEach, describe, expect } from "bun:test" -import { Deferred, Effect, Layer, Schema } from "effect" -import * as Log from "@opencode-ai/core/util/log" -import { Bus } from "../../src/bus" -import { Event as ServerEvent } from "../../src/server/event" -import { Server } from "../../src/server/server" -import { EventPaths } from "../../src/server/routes/instance/httpapi/groups/event" -import { MessageV2 } from "../../src/session/message-v2" -import { MessageID, PartID, SessionID } from "../../src/session/schema" -import { SyncEvent } from "../../src/sync" -import { resetDatabase } from "../fixture/db" -import { disposeAllInstances, TestInstance } from "../fixture/fixture" -import { testEffectShared } from "../lib/effect" - -void Log.init({ print: false }) - -const SseEvent = Schema.Struct({ - id: Schema.optional(Schema.String), - type: Schema.String, - properties: Schema.Record(Schema.String, Schema.Any), -}) - -type SseEvent = Schema.Schema.Type -type BusEvent = { type: string; properties: unknown } - -afterEach(async () => { - await disposeAllInstances() - await resetDatabase() -}) - -const it = testEffectShared(Layer.mergeAll(Bus.defaultLayer, SyncEvent.defaultLayer)) - -const publishConnected = Bus.use.publish(ServerEvent.Connected, {}) - -const publishPartUpdated = (partID: ReturnType) => { - const sessionID = SessionID.make(`ses_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`) - return SyncEvent.use.run(MessageV2.Event.PartUpdated, { - sessionID, - part: { id: partID, sessionID, messageID: MessageID.ascending(), type: "text", text: "diag" }, - time: Date.now(), - }) -} - -const subscribeAllCallback = (handler: (event: BusEvent) => void) => - Effect.acquireRelease(Bus.use.subscribeAllCallback(handler), (dispose) => Effect.sync(() => dispose())) - -const openEventStream = (directory: string) => - Effect.gen(function* () { - const response = yield* Effect.promise(async () => - Server.Default().app.request(EventPaths.event, { headers: { "x-opencode-directory": directory } }), - ) - if (!response.body) return yield* Effect.die("missing SSE response body") - const reader = response.body.getReader() - yield* Effect.addFinalizer(() => Effect.promise(() => reader.cancel().catch(() => undefined))) - return reader - }) - -const decoder = new TextDecoder() - -function decodeFrame(value: Uint8Array): SseEvent[] { - return decoder - .decode(value) - .split(/\n\n+/) - .map((part) => part.trim()) - .filter((part) => part.length > 0) - .map((part) => Schema.decodeUnknownSync(SseEvent)(JSON.parse(part.replace(/^data: /, "")))) -} - -const readNextEvent = (reader: ReadableStreamDefaultReader) => - Effect.promise(() => reader.read()).pipe( - Effect.timeoutOrElse({ - duration: "3 seconds", - orElse: () => Effect.fail(new Error("timed out reading SSE chunk")), - }), - Effect.flatMap((result) => { - if (result.done || !result.value) return Effect.fail(new Error("event stream closed")) - const frames = decodeFrame(result.value) - if (frames.length === 0) return Effect.fail(new Error("empty SSE frame")) - return Effect.succeed(frames[0]!) - }), - ) - -const collectUntilEvent = (reader: ReadableStreamDefaultReader, predicate: (event: SseEvent) => boolean) => - Effect.gen(function* () { - const events: SseEvent[] = [] - while (true) { - const event = yield* readNextEvent(reader) - events.push(event) - if (predicate(event)) return events - } - }).pipe( - Effect.timeoutOrElse({ - duration: "4 seconds", - orElse: () => Effect.fail(new Error("collectUntil deadline exceeded")), - }), - ) - -const isPartUpdated = (event: { type: string }) => event.type === MessageV2.Event.PartUpdated.type - -describe("/event SSE delivery diagnostics", () => { - // Sanity: baseline same as httpapi-event.test.ts test 3 (already known to pass) - // but explicit about timing — publish happens with NO wait after reading - // server.connected. If this fails we have a deeper problem than just sync. - it.instance( - "D1: delivers a single bus event published right after server.connected", - () => - Effect.gen(function* () { - const { directory } = yield* TestInstance - const reader = yield* openEventStream(directory) - - expect((yield* readNextEvent(reader)).type).toBe("server.connected") - yield* publishConnected - expect((yield* readNextEvent(reader)).type).toBe("server.connected") - }), - { git: true, config: { formatter: false, lsp: false } }, - ) - - // If D1 passes but D2 fails, we have a queue-drain or partial-loss issue. - it.instance( - "D2: delivers all N bus events published in rapid succession", - () => - Effect.gen(function* () { - const { directory } = yield* TestInstance - const reader = yield* openEventStream(directory) - expect((yield* readNextEvent(reader)).type).toBe("server.connected") - - const N = 5 - yield* Effect.replicateEffect(publishConnected, N) - - const received = yield* Effect.replicateEffect(readNextEvent(reader), N) - expect(received).toHaveLength(N) - for (const event of received) expect(event.type).toBe("server.connected") - }), - { git: true, config: { formatter: false, lsp: false } }, - ) - - // The critical test. If D1 passes but this fails, the bus-identity fix is - // incomplete OR the sync.run publish path doesn't reach the same bus - // /event subscribes to, even when both share the memoMap. - it.instance( - "D3: delivers a SyncEvent published via SyncEvent.use.run after server.connected", - () => - Effect.gen(function* () { - const { directory } = yield* TestInstance - const reader = yield* openEventStream(directory) - expect((yield* readNextEvent(reader)).type).toBe("server.connected") - - const partID = PartID.ascending() - yield* publishPartUpdated(partID) - - const collected = yield* collectUntilEvent(reader, isPartUpdated) - const updated = collected.find(isPartUpdated) - expect(updated?.properties.part.id).toBe(partID) - }), - { git: true, config: { formatter: false, lsp: false } }, - ) - - // If D3 passes but D5 (the SDK E2E in httpapi-sdk.test.ts) fails, then the - // bug is specifically in the cross-request / cross-fiber HTTP path, not in - // the publish itself. If D3 also fails, the publish chain is broken. - // - // D4: ensure the publish reaches an in-process Bus subscriber too. Confirms - // pub/sub identity end-to-end without involving /event SSE. - it.instance( - "D4: SyncEvent.use.run publish reaches an in-process Bus callback", - () => - Effect.gen(function* () { - const received = yield* Deferred.make() - yield* subscribeAllCallback((event) => { - if (isPartUpdated(event)) Deferred.doneUnsafe(received, Effect.succeed(event)) - }) - - const partID = PartID.ascending() - yield* publishPartUpdated(partID) - - const event = yield* Deferred.await(received).pipe( - Effect.timeoutOrElse({ - duration: "3 seconds", - orElse: () => Effect.fail(new Error("D4 timed out waiting for callback")), - }), - ) - expect(event.type).toBe(MessageV2.Event.PartUpdated.type) - expect(event.properties).toMatchObject({ part: { id: partID } }) - }), - { git: true, config: { formatter: false, lsp: false } }, - ) - - // D5: BOTH subscribers attached simultaneously. Trigger ONE publish via - // SyncEvent.use.run. Both subscribers should receive it. If only one does - // we know exactly which side of the chain is failing. - it.instance( - "D5: same SyncEvent.use.run publish reaches BOTH /event SSE and in-process callback", - () => - Effect.gen(function* () { - const { directory } = yield* TestInstance - const callbackReceived = yield* Deferred.make() - yield* subscribeAllCallback((event) => { - if (isPartUpdated(event)) Deferred.doneUnsafe(callbackReceived, Effect.succeed(event)) - }) - const reader = yield* openEventStream(directory) - expect((yield* readNextEvent(reader)).type).toBe("server.connected") - - const partID = PartID.ascending() - yield* publishPartUpdated(partID) - - const sseSaw = yield* collectUntilEvent(reader, isPartUpdated).pipe( - Effect.map((events) => events.some(isPartUpdated)), - Effect.catch(() => Effect.succeed(false)), - ) - const callbackSaw = yield* Deferred.await(callbackReceived).pipe( - Effect.timeoutOrElse({ duration: "1 second", orElse: () => Effect.succeed(undefined) }), - Effect.map((event) => event !== undefined), - ) - - // Single assert with the boolean pair so the failure message tells us - // exactly which side broke. - expect({ sseSaw, callbackSaw }).toEqual({ sseSaw: true, callbackSaw: true }) - }), - { git: true, config: { formatter: false, lsp: false } }, - ) - - // D6: same as D5 but the callback subscriber is attached AFTER /event SSE - // subscription is established. If D5 fails and D6 passes, the order of - // subscriber setup is the determining factor. - it.instance( - "D6: /event SSE receives sync.run publish when callback is attached AFTER /event opens", - () => - Effect.gen(function* () { - const { directory } = yield* TestInstance - const reader = yield* openEventStream(directory) - expect((yield* readNextEvent(reader)).type).toBe("server.connected") - - const callbackReceived = yield* Deferred.make() - yield* subscribeAllCallback((event) => { - if (isPartUpdated(event)) Deferred.doneUnsafe(callbackReceived, Effect.succeed(event)) - }) - - const partID = PartID.ascending() - yield* publishPartUpdated(partID) - - const sseSaw = yield* collectUntilEvent(reader, isPartUpdated).pipe( - Effect.map((events) => events.some(isPartUpdated)), - Effect.catch(() => Effect.succeed(false)), - ) - const callbackSaw = yield* Deferred.await(callbackReceived).pipe( - Effect.timeoutOrElse({ duration: "1 second", orElse: () => Effect.succeed(undefined) }), - Effect.map((event) => event !== undefined), - ) - expect({ sseSaw, callbackSaw }).toEqual({ sseSaw: true, callbackSaw: true }) - }), - { git: true, config: { formatter: false, lsp: false } }, - ) -}) diff --git a/packages/opencode/test/server/httpapi-event.test.ts b/packages/opencode/test/server/httpapi-event.test.ts index 44d421ea0a12..6673415617c0 100644 --- a/packages/opencode/test/server/httpapi-event.test.ts +++ b/packages/opencode/test/server/httpapi-event.test.ts @@ -1,13 +1,11 @@ import { afterEach, describe, expect } from "bun:test" -import { Effect, Schema } from "effect" +import { Effect, Layer, Queue, Schema, Stream } from "effect" import * as Log from "@opencode-ai/core/util/log" -import { Bus } from "../../src/bus" -import { Event as ServerEvent } from "../../src/server/event" -import { Server } from "../../src/server/server" import { EventPaths } from "../../src/server/routes/instance/httpapi/groups/event" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance } from "../fixture/fixture" -import { testEffectShared } from "../lib/effect" +import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) @@ -17,28 +15,25 @@ const EventData = Schema.Struct({ properties: Schema.Record(Schema.String, Schema.Any), }) -const readEvent = (reader: ReadableStreamDefaultReader) => +const readEvent = (reader: Queue.Dequeue) => Effect.gen(function* () { - const result = yield* Effect.promise(() => reader.read()).pipe( + const value = yield* Queue.take(reader).pipe( Effect.timeoutOrElse({ duration: "5 seconds", orElse: () => Effect.fail(new Error("timed out waiting for event")), }), ) - if (result.done || !result.value) return yield* Effect.fail(new Error("event stream closed")) - return Schema.decodeUnknownSync(EventData)( - JSON.parse(new TextDecoder().decode(result.value).replace(/^data: /, "")), - ) + return Schema.decodeUnknownSync(EventData)(JSON.parse(new TextDecoder().decode(value).replace(/^data: /, ""))) }) const openEventStream = (directory: string) => Effect.gen(function* () { - const response = yield* Effect.promise(async () => - Server.Default().app.request(EventPaths.event, { headers: { "x-opencode-directory": directory } }), + const response = yield* requestInDirectory(EventPaths.event, directory) + const reader = yield* Queue.unbounded() + yield* response.stream.pipe( + Stream.runForEach((value) => Queue.offer(reader, value)), + Effect.forkScoped, ) - if (!response.body) return yield* Effect.die("missing SSE response body") - const reader = response.body.getReader() - yield* Effect.addFinalizer(() => Effect.promise(() => reader.cancel().catch(() => undefined))) return { response, reader } }) @@ -47,7 +42,7 @@ afterEach(async () => { await resetDatabase() }) -const it = testEffectShared(Bus.defaultLayer) +const it = testEffect(httpApiLayer) describe("event HttpApi", () => { it.instance( @@ -58,10 +53,10 @@ describe("event HttpApi", () => { const { response, reader } = yield* openEventStream(directory) expect(response.status).toBe(200) - expect(response.headers.get("content-type")).toContain("text/event-stream") - expect(response.headers.get("cache-control")).toBe("no-cache, no-transform") - expect(response.headers.get("x-accel-buffering")).toBe("no") - expect(response.headers.get("x-content-type-options")).toBe("nosniff") + expect(response.headers["content-type"]).toContain("text/event-stream") + expect(response.headers["cache-control"]).toBe("no-cache, no-transform") + expect(response.headers["x-accel-buffering"]).toBe("no") + expect(response.headers["x-content-type-options"]).toBe("nosniff") expect(yield* readEvent(reader)).toMatchObject({ type: "server.connected", properties: {} }) }), { git: true, config: { formatter: false, lsp: false } }, @@ -76,8 +71,8 @@ describe("event HttpApi", () => { expect(yield* readEvent(reader)).toMatchObject({ type: "server.connected", properties: {} }) // If no second event arrives within 250ms, the stream is still open. - const status = yield* Effect.promise(() => reader.read()).pipe( - Effect.map((result) => (result.done ? ("closed" as const) : ("event" as const))), + const status = yield* Queue.take(reader).pipe( + Effect.as("event" as const), Effect.timeoutOrElse({ duration: "250 millis", orElse: () => Effect.succeed("open" as const) }), ) expect(status).toBe("open") @@ -86,15 +81,16 @@ describe("event HttpApi", () => { ) it.instance( - "delivers instance bus events after the initial event", + "delivers instance events after the initial event", () => Effect.gen(function* () { const { directory } = yield* TestInstance const { reader } = yield* openEventStream(directory) expect(yield* readEvent(reader)).toMatchObject({ type: "server.connected", properties: {} }) - yield* Bus.use.publish(ServerEvent.Connected, {}) - expect(yield* readEvent(reader)).toMatchObject({ type: "server.connected", properties: {} }) + const created = yield* requestInDirectory("/session", directory, { method: "POST" }) + expect(created.status).toBe(200) + expect(yield* readEvent(reader)).toMatchObject({ type: "session.created" }) }), { git: true, config: { formatter: false, lsp: false } }, ) diff --git a/packages/opencode/test/server/httpapi-exercise/backend.ts b/packages/opencode/test/server/httpapi-exercise/backend.ts index ce94ddda9167..6bd060e52c8f 100644 --- a/packages/opencode/test/server/httpapi-exercise/backend.ts +++ b/packages/opencode/test/server/httpapi-exercise/backend.ts @@ -56,7 +56,7 @@ function app(modules: Runtime, options: CallOptions) { ), ), ), - { disableLogger: true }, + { disableLogger: true, memoMap: modules.memoMap }, ).handler return (appCache[cacheKey] = { request(input: string | URL | Request, init?: RequestInit) { diff --git a/packages/opencode/test/server/httpapi-exercise/runner.ts b/packages/opencode/test/server/httpapi-exercise/runner.ts index b14647680c32..86cbd13d9b4a 100644 --- a/packages/opencode/test/server/httpapi-exercise/runner.ts +++ b/packages/opencode/test/server/httpapi-exercise/runner.ts @@ -1,14 +1,16 @@ import { Flag } from "@opencode-ai/core/flag/flag" -import { Cause, Duration, Effect } from "effect" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Cause, Duration, Effect, Layer, Scope } from "effect" import { TestLLMServer } from "../../lib/llm-server" import type { Config } from "../../../src/config/config" -import { ModelID, ProviderID } from "../../../src/provider/schema" + import type { MessageV2 } from "../../../src/session/message-v2" import { MessageID, PartID } from "../../../src/session/schema" import { call, callAuthProbe } from "./backend" import { original } from "./environment" import { runtime } from "./runtime" import type { ActiveScenario, Options, ProjectOptions, Result, Scenario, ScenarioContext, SeededContext } from "./types" +import { ProviderV2 } from "@opencode-ai/core/provider" export function runScenario(options: Options) { return (scenario: Scenario) => { @@ -85,18 +87,20 @@ function withContext( Effect.gen(function* () { yield* trace(options, scenario, `${label} runtime start`) const modules = yield* Effect.promise(() => runtime()) + const scope = yield* Scope.Scope + const app = yield* Layer.buildWithMemoMap(modules.AppLayer, modules.memoMap, scope) yield* trace(options, scenario, `${label} runtime done`) const path = context.dir?.path const instance = path ? yield* trace(options, scenario, `${label} instance load start`).pipe( Effect.andThen( modules.InstanceStore.Service.use((store) => store.load({ directory: path })).pipe( - Effect.provide(modules.AppLayer), + Effect.provide(app), Effect.catchCause((cause) => Effect.sleep("100 millis").pipe( Effect.andThen( modules.InstanceStore.Service.use((store) => store.load({ directory: path })).pipe( - Effect.provide(modules.AppLayer), + Effect.provide(app), ), ), Effect.catchCause(() => Effect.failCause(cause)), @@ -108,7 +112,7 @@ function withContext( ) : undefined const run = (effect: Effect.Effect) => - effect.pipe(Effect.provideService(modules.InstanceRef, instance), Effect.provide(modules.AppLayer)) + effect.pipe(Effect.provideService(modules.InstanceRef, instance), Effect.provide(app)) const directory = () => { if (!context.dir?.path) throw new Error("scenario needs a project directory") return context.dir.path @@ -140,18 +144,18 @@ function withContext( }), message: (sessionID, input) => Effect.gen(function* () { - const info: MessageV2.User = { + const info: SessionLegacy.User = { id: MessageID.ascending(), sessionID, role: "user", time: { created: Date.now() }, agent: "build", model: { - providerID: ProviderID.opencode, - modelID: ModelID.make("test"), + providerID: ProviderV2.ID.opencode, + modelID: ProviderV2.ModelID.make("test"), }, } - const part: MessageV2.TextPart = { + const part: SessionLegacy.TextPart = { id: PartID.ascending(), sessionID, messageID: info.id, diff --git a/packages/opencode/test/server/httpapi-exercise/runtime.ts b/packages/opencode/test/server/httpapi-exercise/runtime.ts index 7842752ad9a4..bd261cbe40ae 100644 --- a/packages/opencode/test/server/httpapi-exercise/runtime.ts +++ b/packages/opencode/test/server/httpapi-exercise/runtime.ts @@ -2,6 +2,7 @@ export type Runtime = { PublicApi: (typeof import("../../../src/server/routes/instance/httpapi/public"))["PublicApi"] HttpApiApp: (typeof import("../../../src/server/routes/instance/httpapi/server"))["HttpApiApp"] AppLayer: (typeof import("../../../src/effect/app-runtime"))["AppLayer"] + memoMap: (typeof import("@opencode-ai/core/effect/memo-map"))["memoMap"] InstanceRef: (typeof import("../../../src/effect/instance-ref"))["InstanceRef"] InstanceStore: (typeof import("../../../src/project/instance-store"))["InstanceStore"] Session: (typeof import("../../../src/session/session"))["Session"] @@ -21,6 +22,7 @@ export function runtime() { const publicApi = await import("../../../src/server/routes/instance/httpapi/public") const httpApiServer = await import("../../../src/server/routes/instance/httpapi/server") const appRuntime = await import("../../../src/effect/app-runtime") + const memoMap = await import("@opencode-ai/core/effect/memo-map") const instanceRef = await import("../../../src/effect/instance-ref") const instanceStore = await import("../../../src/project/instance-store") const session = await import("../../../src/session/session") @@ -34,6 +36,7 @@ export function runtime() { PublicApi: publicApi.PublicApi, HttpApiApp: httpApiServer.HttpApiApp, AppLayer: appRuntime.AppLayer, + memoMap: memoMap.memoMap, InstanceRef: instanceRef.InstanceRef, InstanceStore: instanceStore.InstanceStore, Session: session.Session, diff --git a/packages/opencode/test/server/httpapi-exercise/types.ts b/packages/opencode/test/server/httpapi-exercise/types.ts index e1fe93ba7eff..49830686fb85 100644 --- a/packages/opencode/test/server/httpapi-exercise/types.ts +++ b/packages/opencode/test/server/httpapi-exercise/types.ts @@ -1,4 +1,5 @@ import type { Duration, Effect } from "effect" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import type { Config } from "../../../src/config/config" import type { Project } from "../../../src/project/project" import type { Worktree } from "../../../src/worktree" @@ -57,7 +58,7 @@ export type ScenarioContext = { sessionGet: (sessionID: SessionID) => Effect.Effect project: () => Effect.Effect message: (sessionID: SessionID, input?: { text?: string }) => Effect.Effect - messages: (sessionID: SessionID) => Effect.Effect + messages: (sessionID: SessionID) => Effect.Effect todos: (sessionID: SessionID, todos: TodoInfo[]) => Effect.Effect worktree: (input?: { name?: string }) => Effect.Effect worktreeRemove: (directory: string) => Effect.Effect @@ -118,4 +119,4 @@ export type Result = export type SessionInfo = { id: SessionID; title: string; parentID?: SessionID } export type TodoInfo = { content: string; status: string; priority: string } -export type MessageSeed = { info: MessageV2.User; part: MessageV2.TextPart } +export type MessageSeed = { info: SessionLegacy.User; part: SessionLegacy.TextPart } diff --git a/packages/opencode/test/server/httpapi-experimental.test.ts b/packages/opencode/test/server/httpapi-experimental.test.ts index aa7e4946da57..694956f4607c 100644 --- a/packages/opencode/test/server/httpapi-experimental.test.ts +++ b/packages/opencode/test/server/httpapi-experimental.test.ts @@ -1,41 +1,36 @@ import { afterEach, describe, expect } from "bun:test" import { Deferred, Effect, Fiber, Layer } from "effect" +import { HttpClient, HttpClientResponse } from "effect/unstable/http" import { eq } from "drizzle-orm" import { GlobalBus, type GlobalEvent } from "@/bus/global" -import { Server } from "../../src/server/server" import { ExperimentalPaths } from "../../src/server/routes/instance/httpapi/groups/experimental" import { Session } from "@/session/session" -import { SessionTable } from "@/session/session.sql" -import { Database } from "@/storage/db" +import { SessionTable } from "@opencode-ai/core/session/sql" +import { Database } from "@opencode-ai/core/database/database" +import { AccountV2 } from "@opencode-ai/core/account" +import { AccountTable } from "@opencode-ai/core/account/sql" import * as Log from "@opencode-ai/core/util/log" import { Worktree } from "../../src/worktree" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) -const it = testEffect(Layer.mergeAll(Session.defaultLayer)) +const it = testEffect(Layer.mergeAll(Session.defaultLayer, Database.defaultLayer, httpApiLayer)) const testWorktreeMutations = process.platform === "win32" ? it.instance.skip : it.instance -function app() { - return Server.Default().app -} - function request(path: string, directory: string, init: RequestInit = {}) { - return Effect.promise(() => { - const headers = new Headers(init.headers) - headers.set("x-opencode-directory", directory) - return Promise.resolve(app().request(path, { ...init, headers })) - }) + return requestInDirectory(path, directory, init) } function createSession(input?: Session.CreateInput) { return Session.use.create(input) } -function json(response: Response) { - return Effect.promise(() => response.json() as Promise) +function json(response: HttpClientResponse.HttpClientResponse) { + return response.json.pipe(Effect.map((value) => value as T)) } function waitReady(input: { directory?: string; name?: string }) { @@ -62,38 +57,50 @@ function waitReady(input: { directory?: string; name?: string }) { function insertAccount() { return Effect.acquireRelease( - Effect.sync(() => { - Database.Client() - .$client.prepare( - "INSERT INTO account (id, email, url, access_token, refresh_token, time_created, time_updated) VALUES (?, ?, ?, ?, ?, ?, ?)", - ) - .run( - "account-test", - "test@example.com", - "https://console.example.com", - "access", - "refresh", - Date.now(), - Date.now(), - ) + Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db + .insert(AccountTable) + .values({ + id: AccountV2.ID.make("account-test"), + email: "test@example.com", + url: "https://console.example.com", + access_token: AccountV2.AccessToken.make("access"), + refresh_token: AccountV2.RefreshToken.make("refresh"), + time_created: Date.now(), + time_updated: Date.now(), + }) + .run() + .pipe(Effect.orDie) return "account-test" }), (id) => - Effect.sync(() => { - Database.Client().$client.prepare("DELETE FROM account WHERE id = ?").run(id) - }), + Database.Service.use(({ db }) => + db + .delete(AccountTable) + .where(eq(AccountTable.id, AccountV2.ID.make(id))) + .run() + .pipe(Effect.orDie), + ), ) } function setSessionUpdated(session: Session.Info, updated: number) { - return Effect.sync(() => { - Database.use((db) => - db.update(SessionTable).set({ time_updated: updated }).where(eq(SessionTable.id, session.id)).run(), - ) + return Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db + .update(SessionTable) + .set({ time_updated: updated }) + .where(eq(SessionTable.id, session.id)) + .run() + .pipe(Effect.orDie) }) } -function withCreatedWorktree(directory: string, use: (info: Worktree.Info) => Effect.Effect) { +function withCreatedWorktree( + directory: string, + use: (info: Worktree.Info) => Effect.Effect, +) { const name = "api-test" const headers = { "content-type": "application/json" } return Effect.acquireUseRelease( @@ -242,7 +249,7 @@ describe("experimental HttpApi", () => { tmp.directory, ) expect(page.status).toBe(200) - expect(page.headers.get("x-next-cursor")).toBeTruthy() + expect(page.headers["x-next-cursor"]).toBeTruthy() const body = yield* json(page) expect(body.map((session) => session.id)).toEqual([second.id]) diff --git a/packages/opencode/test/server/httpapi-global.test.ts b/packages/opencode/test/server/httpapi-global.test.ts new file mode 100644 index 000000000000..a13792803c35 --- /dev/null +++ b/packages/opencode/test/server/httpapi-global.test.ts @@ -0,0 +1,63 @@ +import { NodeHttpServer } from "@effect/platform-node" +import { describe, expect } from "bun:test" +import { Context, Effect, Layer, Option } from "effect" +import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/unstable/http" +import { HttpApiBuilder } from "effect/unstable/httpapi" +import { Auth } from "../../src/auth" +import { Config } from "../../src/config/config" +import { Installation } from "../../src/installation" +import { ServerAuth } from "../../src/server/auth" +import { RootHttpApi } from "../../src/server/routes/instance/httpapi/api" +import { GlobalPaths } from "../../src/server/routes/instance/httpapi/groups/global" +import { controlHandlers } from "../../src/server/routes/instance/httpapi/handlers/control" +import { globalHandlers } from "../../src/server/routes/instance/httpapi/handlers/global" +import { authorizationLayer } from "../../src/server/routes/instance/httpapi/middleware/authorization" +import { schemaErrorLayer } from "../../src/server/routes/instance/httpapi/middleware/schema-error" +import { testEffect } from "../lib/effect" + +const apiLayer = HttpRouter.serve( + HttpApiBuilder.layer(RootHttpApi).pipe( + Layer.provide([controlHandlers, globalHandlers]), + Layer.provide([authorizationLayer, schemaErrorLayer]), + // Raw HttpApi routes expose an opaque handler context at the request boundary. + // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion + HttpRouter.provideRequest(Layer.succeedContext(Context.empty() as Context.Context)), + ), + { disableListenLog: true, disableLogger: true }, +).pipe( + Layer.provideMerge(NodeHttpServer.layerTest), + Layer.provide(Layer.mock(Auth.Service)({})), + Layer.provide(Layer.mock(Config.Service)({})), + Layer.provide( + Layer.mock(Installation.Service)({ + method: () => Effect.succeed("npm"), + latest: () => Effect.succeed("9.9.9"), + upgrade: () => Effect.void, + }), + ), + Layer.provide(ServerAuth.Config.layer({ password: Option.none(), username: "opencode" })), +) +const it = testEffect(apiLayer) + +describe("global HttpApi", () => { + it.live("upgrades to latest when the request body is omitted", () => + Effect.gen(function* () { + const response = yield* HttpClient.post(GlobalPaths.upgrade) + + expect(response.status).toBe(200) + expect(yield* response.json).toEqual({ success: true, version: "9.9.9" }) + }), + ) + + it.live("rejects malformed upgrade payloads", () => + Effect.gen(function* () { + const response = yield* HttpClientRequest.post(GlobalPaths.upgrade).pipe( + HttpClientRequest.setBody(HttpBody.text("{", "application/json")), + HttpClient.execute, + ) + + expect(response.status).toBe(400) + expect(yield* response.json).toEqual({ success: false, error: "Invalid request body" }) + }), + ) +}) diff --git a/packages/opencode/test/server/httpapi-instance-context.test.ts b/packages/opencode/test/server/httpapi-instance-context.test.ts index 35dbf97ba03f..eec2f9fbc905 100644 --- a/packages/opencode/test/server/httpapi-instance-context.test.ts +++ b/packages/opencode/test/server/httpapi-instance-context.test.ts @@ -1,20 +1,29 @@ import { NodeHttpServer, NodeServices } from "@effect/platform-node" import { describe, expect } from "bun:test" -import { Effect, Fiber, Layer } from "effect" -import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/unstable/http" +import { Effect, Fiber, Layer, Schema } from "effect" +import { HttpClient, HttpClientRequest, HttpRouter } from "effect/unstable/http" +import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/unstable/httpapi" import * as Socket from "effect/unstable/socket/Socket" import { mkdir } from "node:fs/promises" import path from "node:path" import { registerAdapter } from "../../src/control-plane/adapters" -import { WorkspaceID } from "../../src/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import type { WorkspaceAdapter } from "../../src/control-plane/types" import { Workspace } from "../../src/control-plane/workspace" import { InstanceRef, WorkspaceRef } from "../../src/effect/instance-ref" import { InstanceLayer } from "../../src/project/instance-layer" import { Project } from "../../src/project/project" +import { Session } from "../../src/session/session" import { disposeMiddleware, markInstanceForDisposal } from "../../src/server/routes/instance/httpapi/lifecycle" -import { instanceRouterMiddleware } from "../../src/server/routes/instance/httpapi/middleware/instance-context" -import { workspaceRouterMiddleware } from "../../src/server/routes/instance/httpapi/middleware/workspace-routing" +import { + InstanceContextMiddleware, + instanceContextLayer, +} from "../../src/server/routes/instance/httpapi/middleware/instance-context" +import { + WorkspaceRoutingMiddleware, + WorkspaceRoutingQuery, + workspaceRoutingLayer, +} from "../../src/server/routes/instance/httpapi/middleware/workspace-routing" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, tmpdirScoped } from "../fixture/fixture" import { withFixedWorkspaceID } from "../fixture/flag" @@ -47,9 +56,10 @@ const it = testEffect( ), ) -const instanceContextTestLayer = instanceRouterMiddleware - .combine(workspaceRouterMiddleware) - .layer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)) +const instanceContextTestLayer = Layer.mergeAll( + instanceContextLayer, + workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)), +) const localAdapter = (directory: string): WorkspaceAdapter => ({ name: "Local Test", @@ -80,20 +90,57 @@ const createLocalWorkspace = (input: { projectID: Project.Info["id"]; type: stri const probeInstanceContext = Effect.gen(function* () { const instance = yield* InstanceRef const workspaceID = yield* WorkspaceRef - return yield* HttpServerResponse.json({ + return { directory: instance?.directory, worktree: instance?.worktree, projectID: instance?.project.id, workspaceID, - }) + } }) -const serveProbe = (probePath: HttpRouter.PathInput = "/probe") => - HttpRouter.add("GET", probePath, probeInstanceContext).pipe( - Layer.provide(instanceContextTestLayer), - HttpRouter.serve, - Layer.build, - ) +const ProbeResult = Schema.Struct({ + directory: Schema.optional(Schema.String), + worktree: Schema.optional(Schema.String), + projectID: Schema.optional(Schema.String), + workspaceID: Schema.optional(Schema.String), +}) + +const ProbeApi = HttpApi.make("instance-context-probe").add( + HttpApiGroup.make("probe") + .add( + HttpApiEndpoint.get("get", "/probe", { query: WorkspaceRoutingQuery, success: ProbeResult }), + HttpApiEndpoint.get("session", "/session", { query: WorkspaceRoutingQuery, success: ProbeResult }), + HttpApiEndpoint.post("dispose", "/dispose-probe", { + query: WorkspaceRoutingQuery, + success: Schema.Boolean, + }), + ) + .middleware(InstanceContextMiddleware) + .middleware(WorkspaceRoutingMiddleware), +) + +const probeHandlers = HttpApiBuilder.group(ProbeApi, "probe", (handlers) => + handlers + .handle("get", () => probeInstanceContext) + .handle("session", () => probeInstanceContext) + .handle( + "dispose", + Effect.fn("InstanceContextProbe.dispose")(function* () { + const instance = yield* InstanceRef + if (!instance) return false + yield* markInstanceForDisposal(instance) + return true + }), + ), +) + +const probeRoutes = HttpApiBuilder.layer(ProbeApi).pipe( + Layer.provide(probeHandlers), + Layer.provide(instanceContextTestLayer), + Layer.provide(Layer.mock(Session.Service)({})), +) + +const serveProbe = () => probeRoutes.pipe(HttpRouter.serve, Layer.build) const waitDisposedEvent = waitGlobalBusEvent({ message: "timed out waiting for instance disposal", @@ -101,19 +148,9 @@ const waitDisposedEvent = waitGlobalBusEvent({ }).pipe(Effect.map((event) => ({ directory: event.directory, workspace: event.workspace }))) const serveDisposeProbe = () => - HttpRouter.serve( - HttpRouter.add( - "POST", - "/dispose-probe", - Effect.gen(function* () { - const instance = yield* InstanceRef - if (!instance) return HttpServerResponse.empty({ status: 500 }) - yield* markInstanceForDisposal(instance) - return yield* HttpServerResponse.json(true) - }), - ).pipe(Layer.provide(instanceContextTestLayer)), - { middleware: disposeMiddleware, disableListenLog: true, disableLogger: true }, - ).pipe(Layer.build) + HttpRouter.serve(probeRoutes, { middleware: disposeMiddleware, disableListenLog: true, disableLogger: true }).pipe( + Layer.build, + ) describe("HttpApi instance context middleware", () => { it.live("provides instance context from the routed directory", () => @@ -129,6 +166,7 @@ describe("HttpApi instance context middleware", () => { directory: dir, worktree: dir, projectID: project.project.id, + workspaceID: null, }) }), ) @@ -156,7 +194,7 @@ describe("HttpApi instance context middleware", () => { type: "instance-context-workspace-ref", directory: workspaceDir, }) - yield* serveProbe("/session") + yield* serveProbe() const response = yield* HttpClientRequest.get(`/session?workspace=${workspace.id}`).pipe( HttpClientRequest.setHeader("x-opencode-directory", dir), @@ -198,7 +236,7 @@ describe("HttpApi instance context middleware", () => { it.live("uses configured workspace id instead of routing to the requested workspace", () => Effect.gen(function* () { - const fixedWorkspaceID = WorkspaceID.ascending() + const fixedWorkspaceID = WorkspaceV2.ID.ascending() yield* withFixedWorkspaceID(fixedWorkspaceID) const dir = yield* tmpdirScoped({ git: true }) @@ -226,7 +264,7 @@ describe("HttpApi instance context middleware", () => { it.live("falls through to local instead of MissingWorkspace when configured workspace id is set", () => Effect.gen(function* () { - const fixedWorkspaceID = WorkspaceID.ascending() + const fixedWorkspaceID = WorkspaceV2.ID.ascending() yield* withFixedWorkspaceID(fixedWorkspaceID) const dir = yield* tmpdirScoped({ git: true }) @@ -238,7 +276,7 @@ describe("HttpApi instance context middleware", () => { // MissingWorkspace response. With the env set, planRequest must skip the // MissingWorkspace branch and fall through to Local with the configured // workspace id. - const unknownWorkspaceID = WorkspaceID.ascending() + const unknownWorkspaceID = WorkspaceV2.ID.ascending() const response = yield* HttpClientRequest.get(`/probe?workspace=${unknownWorkspaceID}`).pipe( HttpClientRequest.setHeader("x-opencode-directory", dir), HttpClient.execute, @@ -254,7 +292,7 @@ describe("HttpApi instance context middleware", () => { it.live("keeps configured workspace id on control-plane routes without remote routing", () => Effect.gen(function* () { - const fixedWorkspaceID = WorkspaceID.ascending() + const fixedWorkspaceID = WorkspaceV2.ID.ascending() yield* withFixedWorkspaceID(fixedWorkspaceID) const dir = yield* tmpdirScoped({ git: true }) @@ -269,7 +307,7 @@ describe("HttpApi instance context middleware", () => { // is true. Combined with the env override, the route must stay Local with // the configured workspace id (not divert to the requested workspace's // local directory). - yield* serveProbe("/session") + yield* serveProbe() const response = yield* HttpClientRequest.get(`/session?workspace=${workspace.id}`).pipe( HttpClientRequest.setHeader("x-opencode-directory", dir), diff --git a/packages/opencode/test/server/httpapi-raw-route-auth.test.ts b/packages/opencode/test/server/httpapi-instance-route-auth.test.ts similarity index 88% rename from packages/opencode/test/server/httpapi-raw-route-auth.test.ts rename to packages/opencode/test/server/httpapi-instance-route-auth.test.ts index 7436c10817a3..4713540b9cfa 100644 --- a/packages/opencode/test/server/httpapi-raw-route-auth.test.ts +++ b/packages/opencode/test/server/httpapi-instance-route-auth.test.ts @@ -4,6 +4,7 @@ import { HttpRouter } from "effect/unstable/http" import { EventPaths } from "../../src/server/routes/instance/httpapi/groups/event" import { PtyPaths } from "../../src/server/routes/instance/httpapi/groups/pty" import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" +import { ServerAuth } from "../../src/server/auth" import { PtyID } from "../../src/pty/schema" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, tmpdir } from "../fixture/fixture" @@ -35,7 +36,7 @@ function app(input: { password?: string; username?: string }) { } function basic(username: string, password: string) { - return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` + return ServerAuth.header({ username, password }) ?? "" } async function cancelBody(response: Response) { @@ -47,8 +48,8 @@ afterEach(async () => { await resetDatabase() }) -describe("HttpApi raw route authorization", () => { - test("requires configured auth before opening the raw instance event stream", async () => { +describe("HttpApi instance route authorization", () => { + test("requires configured auth before opening the instance event stream", async () => { await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } }) const server = app({ password: "secret" }) const headers = { "x-opencode-directory": tmp.path } @@ -64,7 +65,7 @@ describe("HttpApi raw route authorization", () => { expect(authed.status).toBe(200) }) - test("requires configured auth before resolving the raw PTY websocket route", async () => { + test("requires configured auth before resolving the PTY websocket route", async () => { await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } }) const server = app({ password: "secret" }) const route = PtyPaths.connect.replace(":ptyID", PtyID.ascending()) diff --git a/packages/opencode/test/server/httpapi-instance.test.ts b/packages/opencode/test/server/httpapi-instance.test.ts index 2087ad830f2b..65bdfa7c5ca0 100644 --- a/packages/opencode/test/server/httpapi-instance.test.ts +++ b/packages/opencode/test/server/httpapi-instance.test.ts @@ -4,12 +4,12 @@ import { describe, expect } from "bun:test" import { Config, Context, Effect, FileSystem, Layer, Path } from "effect" import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http" import * as Socket from "effect/unstable/socket/Socket" -import { WorkspaceID } from "../../src/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { ControlPaths } from "../../src/server/routes/instance/httpapi/groups/control" import { InstancePaths } from "../../src/server/routes/instance/httpapi/groups/instance" import { SessionPaths } from "../../src/server/routes/instance/httpapi/groups/session" import { PermissionID } from "../../src/permission/schema" -import { ProjectID } from "../../src/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { QuestionID } from "../../src/question/schema" import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" import { HEADER as FenceHeader } from "../../src/server/shared/fence" @@ -17,7 +17,7 @@ import { resetDatabase } from "../fixture/db" import { tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" -// Flip the experimental workspaces flag so SyncEvent.run actually writes to +// Flip the experimental workspaces flag so EventV2.run actually writes to // EventSequenceTable (the source of truth the fence middleware reads). Reset // the database around the test so per-instance state does not leak between // runs. resetDatabase() already calls disposeAllInstances(), so we don't @@ -76,7 +76,7 @@ describe("instance HttpApi", () => { it.live("emits a sync fence header for fixed-workspace mutations", () => Effect.gen(function* () { const originalWorkspaceID = Flag.OPENCODE_WORKSPACE_ID - Flag.OPENCODE_WORKSPACE_ID = WorkspaceID.ascending() + Flag.OPENCODE_WORKSPACE_ID = WorkspaceV2.ID.ascending() yield* Effect.addFinalizer(() => Effect.sync(() => { Flag.OPENCODE_WORKSPACE_ID = originalWorkspaceID @@ -98,7 +98,7 @@ describe("instance HttpApi", () => { it.live("does not emit sync fence headers for fixed-workspace reads or no-op mutations", () => Effect.gen(function* () { const originalWorkspaceID = Flag.OPENCODE_WORKSPACE_ID - Flag.OPENCODE_WORKSPACE_ID = WorkspaceID.ascending() + Flag.OPENCODE_WORKSPACE_ID = WorkspaceV2.ID.ascending() yield* Effect.addFinalizer(() => Effect.sync(() => { Flag.OPENCODE_WORKSPACE_ID = originalWorkspaceID @@ -209,7 +209,7 @@ describe("instance HttpApi", () => { it.live("returns typed not found bodies for missing projects", () => Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) - const projectID = ProjectID.make("project_missing") + const projectID = ProjectV2.ID.make("project_missing") const response = yield* Effect.promise(() => HttpApiApp.webHandler().handler( new Request(`http://localhost/project/${projectID}`, { diff --git a/packages/opencode/test/server/httpapi-layer.ts b/packages/opencode/test/server/httpapi-layer.ts new file mode 100644 index 000000000000..a780391ae9e5 --- /dev/null +++ b/packages/opencode/test/server/httpapi-layer.ts @@ -0,0 +1,33 @@ +import { NodeHttpServer, NodeServices } from "@effect/platform-node" +import { Config, Layer } from "effect" +import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http" +import { layerWebSocketConstructorGlobal } from "effect/unstable/socket/Socket" +import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" + +const servedRoutes: Layer.Layer = HttpRouter.serve( + HttpApiApp.routes, + { + disableListenLog: true, + disableLogger: true, + }, +) + +export const httpApiLayer = servedRoutes.pipe( + Layer.provide(layerWebSocketConstructorGlobal), + Layer.provideMerge(NodeHttpServer.layerTest), + Layer.provideMerge(NodeServices.layer), +) + +export function request(path: string, init?: RequestInit) { + const url = new URL(path, "http://localhost") + return HttpClientRequest.fromWeb(new Request(url, init)).pipe( + HttpClientRequest.setUrl(url.pathname), + HttpClient.execute, + ) +} + +export function requestInDirectory(path: string, directory: string, init: RequestInit = {}) { + const headers = new Headers(init.headers) + headers.set("x-opencode-directory", directory) + return request(path, { ...init, headers }) +} diff --git a/packages/opencode/test/server/httpapi-mcp.test.ts b/packages/opencode/test/server/httpapi-mcp.test.ts index 9985ced9f608..2cd5d2abba08 100644 --- a/packages/opencode/test/server/httpapi-mcp.test.ts +++ b/packages/opencode/test/server/httpapi-mcp.test.ts @@ -109,6 +109,10 @@ describe("mcp HttpApi", () => { expect(added.status).toBe(200) expect(yield* json(added)).toMatchObject({ added: { status: "disabled" } }) + const addedDisconnected = yield* request(handler, "/mcp/added/disconnect", tmp.directory, { method: "POST" }) + expect(addedDisconnected.status).toBe(200) + expect(yield* json(addedDisconnected)).toBe(true) + const connected = yield* request(handler, "/mcp/demo/connect", tmp.directory, { method: "POST" }) expect(connected.status).toBe(200) expect(yield* json(connected)).toBe(true) diff --git a/packages/opencode/test/server/httpapi-promptasync-context.test.ts b/packages/opencode/test/server/httpapi-promptasync-context.test.ts index 84f3df5b8cdf..6a1d30907350 100644 --- a/packages/opencode/test/server/httpapi-promptasync-context.test.ts +++ b/packages/opencode/test/server/httpapi-promptasync-context.test.ts @@ -9,10 +9,11 @@ import { NodeHttpServer, NodeServices } from "@effect/platform-node" import { describe, expect } from "bun:test" -import { Deferred, Effect, Layer, Scope } from "effect" +import { Deferred, Effect, Layer, Schema, Scope } from "effect" import * as Stream from "effect/Stream" import { HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http" import * as Socket from "effect/unstable/socket/Socket" +import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/unstable/httpapi" import { mkdir } from "node:fs/promises" import { registerAdapter } from "../../src/control-plane/adapters" import type { WorkspaceAdapter } from "../../src/control-plane/types" @@ -20,8 +21,16 @@ import { Workspace } from "../../src/control-plane/workspace" import { InstanceRef, WorkspaceRef } from "../../src/effect/instance-ref" import { InstanceLayer } from "../../src/project/instance-layer" import { Project } from "../../src/project/project" -import { instanceRouterMiddleware } from "../../src/server/routes/instance/httpapi/middleware/instance-context" -import { workspaceRouterMiddleware } from "../../src/server/routes/instance/httpapi/middleware/workspace-routing" +import { Session } from "../../src/session/session" +import { + InstanceContextMiddleware, + instanceContextLayer, +} from "../../src/server/routes/instance/httpapi/middleware/instance-context" +import { + WorkspaceRoutingMiddleware, + WorkspaceRoutingQuery, + workspaceRoutingLayer, +} from "../../src/server/routes/instance/httpapi/middleware/workspace-routing" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, tmpdirScoped } from "../fixture/fixture" import { workspaceLayerWithRuntimeFlags } from "../fixture/workspace" @@ -52,9 +61,10 @@ const it = testEffect( ), ) -const instanceContextTestLayer = instanceRouterMiddleware - .combine(workspaceRouterMiddleware) - .layer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)) +const instanceContextTestLayer = Layer.mergeAll( + instanceContextLayer, + workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)), +) const localAdapter = (directory: string): WorkspaceAdapter => ({ name: "Local Test", @@ -87,6 +97,46 @@ const captureInstance = Effect.gen(function* () { return { directory: instance?.directory, workspaceID } satisfies Capture }) +const ProbeApi = HttpApi.make("handler-context-probe").add( + HttpApiGroup.make("probe") + .add( + HttpApiEndpoint.post("fork", "/fork-probe", { query: WorkspaceRoutingQuery, success: Schema.Boolean }), + HttpApiEndpoint.post("streamWithout", "/stream-probe-without", { + query: WorkspaceRoutingQuery, + success: Schema.String.pipe(HttpApiSchema.asText({ contentType: "application/json" })), + }), + HttpApiEndpoint.post("streamWith", "/stream-probe-with", { + query: WorkspaceRoutingQuery, + success: Schema.String.pipe(HttpApiSchema.asText({ contentType: "application/json" })), + }), + ) + .middleware(InstanceContextMiddleware) + .middleware(WorkspaceRoutingMiddleware), +) + +const serveProbes = (input: { + fork?: Effect.Effect + streamWithout?: Effect.Effect + streamWith?: Effect.Effect +}) => + HttpApiBuilder.layer(ProbeApi).pipe( + Layer.provide( + HttpApiBuilder.group(ProbeApi, "probe", (handlers) => + handlers + .handle("fork", () => input.fork ?? Effect.succeed(false)) + .handleRaw( + "streamWithout", + () => input.streamWithout ?? Effect.succeed(HttpServerResponse.empty({ status: 404 })), + ) + .handleRaw("streamWith", () => input.streamWith ?? Effect.succeed(HttpServerResponse.empty({ status: 404 }))), + ), + ), + Layer.provide(instanceContextTestLayer), + Layer.provide(Layer.mock(Session.Service)({})), + HttpRouter.serve, + Layer.build, + ) + describe("HttpApi handler context inheritance", () => { // Mirrors handlers/session.ts:281 promptAsync. The forked fiber inherits // the request's Context — including InstanceRef and WorkspaceRef provided @@ -96,22 +146,20 @@ describe("HttpApi handler context inheritance", () => { const { dir, workspace } = yield* setupWorkspace("local-fork") const capture = yield* Deferred.make() - yield* HttpRouter.add( - "POST", - "/fork-probe", - Effect.gen(function* () { + yield* serveProbes({ + fork: Effect.gen(function* () { const scope = yield* Scope.Scope yield* Effect.gen(function* () { yield* Deferred.succeed(capture, yield* captureInstance) }).pipe(Effect.forkIn(scope, { startImmediately: true })) - return HttpServerResponse.empty({ status: 204 }) + return true }), - ).pipe(Layer.provide(instanceContextTestLayer), HttpRouter.serve, Layer.build) + }) const response = yield* HttpClient.post( `/fork-probe?directory=${encodeURIComponent(dir)}&workspace=${encodeURIComponent(workspace.id)}`, ) - expect(response.status).toBe(204) + expect(response.status).toBe(200) const observed = yield* Deferred.await(capture).pipe(Effect.timeout("2 seconds")) expect(observed.directory).toBe(dir) @@ -129,10 +177,8 @@ describe("HttpApi handler context inheritance", () => { const withoutCapture = yield* Deferred.make() const withCapture = yield* Deferred.make() - yield* HttpRouter.add( - "POST", - "/stream-probe-without", - Effect.gen(function* () { + yield* serveProbes({ + streamWithout: Effect.gen(function* () { return HttpServerResponse.stream( Stream.fromEffect( Effect.gen(function* () { @@ -143,12 +189,7 @@ describe("HttpApi handler context inheritance", () => { { contentType: "application/json" }, ) }), - ).pipe(Layer.provide(instanceContextTestLayer), HttpRouter.serve, Layer.build) - - yield* HttpRouter.add( - "POST", - "/stream-probe-with", - Effect.gen(function* () { + streamWith: Effect.gen(function* () { const instance = yield* InstanceRef const workspaceID = yield* WorkspaceRef return HttpServerResponse.stream( @@ -161,7 +202,7 @@ describe("HttpApi handler context inheritance", () => { { contentType: "application/json" }, ) }), - ).pipe(Layer.provide(instanceContextTestLayer), HttpRouter.serve, Layer.build) + }) const queryString = `directory=${encodeURIComponent(dir)}&workspace=${encodeURIComponent(workspace.id)}` const responseWithout = yield* HttpClient.post(`/stream-probe-without?${queryString}`) diff --git a/packages/opencode/test/server/httpapi-provider.test.ts b/packages/opencode/test/server/httpapi-provider.test.ts index 25181f3b2db9..52b5087057b0 100644 --- a/packages/opencode/test/server/httpapi-provider.test.ts +++ b/packages/opencode/test/server/httpapi-provider.test.ts @@ -2,12 +2,12 @@ import { describe, expect } from "bun:test" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Effect, Layer } from "effect" import path from "path" -import { Server } from "../../src/server/server" import * as Log from "@opencode-ai/core/util/log" import { resetDatabase } from "../fixture/db" import { TestInstance } from "../fixture/fixture" import { markPluginDependenciesReady } from "../fixture/plugin" import { testEffect } from "../lib/effect" +import { httpApiLayer, request } from "./httpapi-layer" void Log.init({ print: false }) @@ -18,16 +18,12 @@ const testStateLayer = Layer.effectDiscard( ), ) -const it = testEffect(Layer.mergeAll(testStateLayer, AppFileSystem.defaultLayer)) +const it = testEffect(Layer.mergeAll(testStateLayer, AppFileSystem.defaultLayer, httpApiLayer)) const projectOptions = { config: { formatter: false, lsp: false } } const providerID = "test-oauth-parity" const oauthURL = "https://example.com/oauth" const oauthInstructions = "Finish OAuth" -function app() { - return Server.Default().app -} - function providerListHasFetch(list: unknown) { if (!Array.isArray(list)) return false return list.some((item: unknown) => { @@ -77,41 +73,34 @@ function hasProviderMutationMarker(input: unknown, key: "all" | "providers", id: } function requestAuthorize(input: { - app: ReturnType providerID: string method: number headers: HeadersInit inputs?: Record }) { - return Effect.promise(async () => { - const response = await input.app.request(`/provider/${input.providerID}/oauth/authorize`, { + return Effect.gen(function* () { + const response = yield* request(`/provider/${input.providerID}/oauth/authorize`, { method: "POST", headers: input.headers, body: JSON.stringify({ method: input.method, ...(input.inputs ? { inputs: input.inputs } : {}) }), }) return { status: response.status, - body: await response.text(), + body: yield* response.text, } }) } -function requestCallback(input: { - app: ReturnType - providerID: string - method: number - headers: HeadersInit - code?: string -}) { - return Effect.promise(async () => { - const response = await input.app.request(`/provider/${input.providerID}/oauth/callback`, { +function requestCallback(input: { providerID: string; method: number; headers: HeadersInit; code?: string }) { + return Effect.gen(function* () { + const response = yield* request(`/provider/${input.providerID}/oauth/callback`, { method: "POST", headers: input.headers, body: JSON.stringify({ method: input.method, ...(input.code ? { code: input.code } : {}) }), }) return { status: response.status, - body: await response.text(), + body: yield* response.text, } }) } @@ -277,15 +266,13 @@ describe("provider HttpApi", () => { it.instance.skip( "returns public v2 provider not found errors", Effect.gen(function* () { - const instance = yield* TestInstance - const response = yield* Effect.promise(() => - Promise.resolve( - app().request("/api/provider/missing", { headers: { "x-opencode-directory": instance.directory } }), - ), - ) + const directory = (yield* TestInstance).directory + const response = yield* request("/api/provider/missing", { + headers: { "x-opencode-directory": directory }, + }) expect(response.status).toBe(404) - expect(yield* Effect.promise(() => response.json())).toEqual({ + expect(yield* response.json).toEqual({ _tag: "ProviderNotFoundError", providerID: "missing", message: "Provider not found: missing", @@ -297,13 +284,9 @@ describe("provider HttpApi", () => { it.instance( "serves OAuth authorize response shapes", Effect.gen(function* () { - const instance = yield* TestInstance - yield* writeProviderAuthPlugin(instance.directory) - const headers = { "x-opencode-directory": instance.directory, "content-type": "application/json" } - const server = app() - + const directory = (yield* TestInstance).directory + const headers = { "x-opencode-directory": directory, "content-type": "application/json" } const api = yield* requestAuthorize({ - app: server, providerID, method: 0, headers, @@ -315,7 +298,6 @@ describe("provider HttpApi", () => { expect(api).toEqual({ status: 200, body: "null" }) const oauth = yield* requestAuthorize({ - app: server, providerID, method: 1, headers, @@ -326,21 +308,19 @@ describe("provider HttpApi", () => { instructions: oauthInstructions, }) }), - projectOptions, + { ...projectOptions, init: writeProviderAuthPlugin }, 30000, ) it.instance( "returns declared provider auth validation errors", Effect.gen(function* () { - const instance = yield* TestInstance - yield* writeProviderAuthValidationPlugin(instance.directory) + const directory = (yield* TestInstance).directory const response = yield* requestAuthorize({ - app: app(), providerID: "test-oauth-validation", method: 0, inputs: { token: "nope" }, - headers: { "x-opencode-directory": instance.directory, "content-type": "application/json" }, + headers: { "x-opencode-directory": directory, "content-type": "application/json" }, }) expect(response.status).toBe(400) @@ -349,19 +329,18 @@ describe("provider HttpApi", () => { data: { field: "token", message: "Token must be ok" }, }) }), - projectOptions, + { ...projectOptions, init: writeProviderAuthValidationPlugin }, 30000, ) it.instance( "returns declared provider auth callback errors", Effect.gen(function* () { - const instance = yield* TestInstance + const directory = (yield* TestInstance).directory const response = yield* requestCallback({ - app: app(), providerID, method: 0, - headers: { "x-opencode-directory": instance.directory, "content-type": "application/json" }, + headers: { "x-opencode-directory": directory, "content-type": "application/json" }, }) expect(response.status).toBe(400) @@ -377,54 +356,48 @@ describe("provider HttpApi", () => { it.instance( "serves provider lists when auth loaders add runtime fetch options", Effect.gen(function* () { - const instance = yield* TestInstance - yield* writeFunctionOptionsPlugin(instance.directory) + const directory = (yield* TestInstance).directory yield* setEnvScoped( "OPENCODE_AUTH_CONTENT", JSON.stringify({ google: { type: "oauth", refresh: "dummy", access: "dummy", expires: 9999999999999 }, }), ) - const headers = { "x-opencode-directory": instance.directory } - const providerResponse = yield* Effect.promise(() => Promise.resolve(app().request("/provider", { headers }))) - const configResponse = yield* Effect.promise(() => - Promise.resolve(app().request("/config/providers", { headers })), - ) + const headers = { "x-opencode-directory": directory } + const providerResponse = yield* request("/provider", { headers }) + const configResponse = yield* request("/config/providers", { headers }) expect(providerResponse.status).toBe(200) expect(configResponse.status).toBe(200) - const providerBody = yield* Effect.promise(() => providerResponse.json()) - const configBody = yield* Effect.promise(() => configResponse.json()) + const providerBody = yield* providerResponse.json + const configBody = yield* configResponse.json expect(hasProviderWithFetch(providerBody, "all")).toBe(false) expect(hasProviderWithFetch(configBody, "providers")).toBe(false) expect(hasNonZeroModelCost(providerBody, "all", "google")).toBe(true) expect(hasNonZeroModelCost(configBody, "providers", "google")).toBe(true) }), - projectOptions, + { ...projectOptions, init: writeFunctionOptionsPlugin }, ) it.instance( "keeps provider.models hook input mutations out of provider state", Effect.gen(function* () { - const instance = yield* TestInstance - yield* writeProviderModelsMutationPlugin(instance.directory) + const directory = (yield* TestInstance).directory - const headers = { "x-opencode-directory": instance.directory } - const providerResponse = yield* Effect.promise(() => Promise.resolve(app().request("/provider", { headers }))) - const configResponse = yield* Effect.promise(() => - Promise.resolve(app().request("/config/providers", { headers })), - ) + const headers = { "x-opencode-directory": directory } + const providerResponse = yield* request("/provider", { headers }) + const configResponse = yield* request("/config/providers", { headers }) expect(providerResponse.status).toBe(200) expect(configResponse.status).toBe(200) - const providerBody = yield* Effect.promise(() => providerResponse.json()) - const configBody = yield* Effect.promise(() => configResponse.json()) + const providerBody = yield* providerResponse.json + const configBody = yield* configResponse.json expect(hasProviderMutationMarker(providerBody, "all", "google")).toBe(false) expect(hasProviderMutationMarker(configBody, "providers", "google")).toBe(false) expect(hasNonZeroModelCost(providerBody, "all", "google")).toBe(true) }), - projectOptions, + { ...projectOptions, init: writeProviderModelsMutationPlugin }, ) }) diff --git a/packages/opencode/test/server/httpapi-pty.test.ts b/packages/opencode/test/server/httpapi-pty.test.ts index 029cdb9582c3..f26bc68e6770 100644 --- a/packages/opencode/test/server/httpapi-pty.test.ts +++ b/packages/opencode/test/server/httpapi-pty.test.ts @@ -147,6 +147,14 @@ describe("pty HttpApi bridge", () => { expect(response.status).toBe(404) }) + test("returns 404 for missing PTY websocket before decoding cursor query", async () => { + await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } }) + const response = await app().request(`${PtyPaths.connect.replace(":ptyID", PtyID.ascending())}?cursor=a&cursor=b`, { + headers: { "x-opencode-directory": tmp.path }, + }) + expect(response.status).toBe(404) + }) + test("returns typed not found errors for missing PTY HTTP resources", async () => { await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } }) const headers = { "x-opencode-directory": tmp.path } diff --git a/packages/opencode/test/server/httpapi-public-openapi.test.ts b/packages/opencode/test/server/httpapi-public-openapi.test.ts index 74a3aa68c12f..86a3521a4a19 100644 --- a/packages/opencode/test/server/httpapi-public-openapi.test.ts +++ b/packages/opencode/test/server/httpapi-public-openapi.test.ts @@ -9,6 +9,7 @@ type OpenApiResponse = { readonly content?: Record } type OpenApiOperation = { + readonly parameters?: ReadonlyArray<{ readonly name: string; readonly in: string }> readonly responses?: Record readonly security?: unknown } @@ -207,6 +208,11 @@ describe("PublicApi OpenAPI v2 errors", () => { expect(componentName(responseRef(spec.paths["/pty/{ptyID}/connect-token"]?.post?.responses?.["403"]) ?? "")).toBe( "PtyForbiddenError", ) + expect( + spec.paths["/pty/{ptyID}/connect"]?.get?.parameters + ?.filter((parameter) => parameter.in === "query") + .map((parameter) => parameter.name), + ).toEqual(["directory", "workspace", "cursor", "ticket"]) }) test("documents project not-found errors", () => { diff --git a/packages/opencode/test/server/httpapi-schema-error-body.test.ts b/packages/opencode/test/server/httpapi-schema-error-body.test.ts index c221bdd19b7d..f217bf844d09 100644 --- a/packages/opencode/test/server/httpapi-schema-error-body.test.ts +++ b/packages/opencode/test/server/httpapi-schema-error-body.test.ts @@ -1,19 +1,23 @@ import { afterEach, describe, expect } from "bun:test" -import { Effect } from "effect" +import { Effect, Layer } from "effect" +import { HttpClientResponse } from "effect/unstable/http" import { eq } from "drizzle-orm" -import * as Database from "@/storage/db" -import { ModelID, ProviderID } from "../../src/provider/schema" -import { Server } from "../../src/server/server" +import { Database } from "@opencode-ai/core/database/database" + import { Session } from "@/session/session" import { SessionPaths } from "../../src/server/routes/instance/httpapi/groups/session" import { SyncPaths } from "../../src/server/routes/instance/httpapi/groups/sync" import { MessageID, PartID } from "../../src/session/schema" -import { PartTable } from "@/session/session.sql" +import { PartTable } from "@opencode-ai/core/session/sql" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" + +const it = testEffect(Layer.mergeAll(Session.defaultLayer, Database.defaultLayer, httpApiLayer)) -const it = testEffect(Session.defaultLayer) +const text = (response: HttpClientResponse.HttpClientResponse) => response.text afterEach(async () => { await disposeAllInstances() @@ -28,7 +32,7 @@ const seedCorruptStepFinishPart = Effect.gen(function* () { role: "user", sessionID: info.id, agent: "build", - model: { providerID: ProviderID.make("test"), modelID: ModelID.make("test") }, + model: { providerID: ProviderV2.ID.make("test"), modelID: ProviderV2.ModelID.make("test") }, time: { created: Date.now() }, }) const partID = PartID.ascending() @@ -43,22 +47,20 @@ const seedCorruptStepFinishPart = Effect.gen(function* () { }) // Schema.Finite still rejects NaN at encode: exact mirror of the corrupt row // that broke the user's session in the OMO/Windows bug. - yield* Effect.sync(() => - Database.use((db) => - db - .update(PartTable) - .set({ - data: { - type: "step-finish", - reason: "stop", - cost: 0, - tokens: { input: 0, output: NaN, reasoning: 0, cache: { read: 0, write: 0 } }, - } as never, // drizzle's .set() can't narrow the discriminated union - }) - .where(eq(PartTable.id, partID)) - .run(), - ), - ) + const { db } = yield* Database.Service + yield* db + .update(PartTable) + .set({ + data: { + type: "step-finish", + reason: "stop", + cost: 0, + tokens: { input: 0, output: NaN, reasoning: 0, cache: { read: 0, write: 0 } }, + } as never, // drizzle's .set() can't narrow the discriminated union + }) + .where(eq(PartTable.id, partID)) + .run() + .pipe(Effect.orDie) return info.id }) @@ -68,16 +70,14 @@ describe("schema-rejection wire shape", () => { () => Effect.gen(function* () { const test = yield* TestInstance - const res = yield* Effect.promise(async () => - Server.Default().app.request(SyncPaths.history, { - method: "POST", - headers: { "x-opencode-directory": test.directory, "content-type": "application/json" }, - body: JSON.stringify({ aggregate: -1 }), - }), - ) - const body = yield* Effect.promise(async () => res.text()) + const res = yield* requestInDirectory(SyncPaths.history, test.directory, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ aggregate: -1 }), + }) + const body = yield* text(res) expect(res.status).toBe(400) - expect(res.headers.get("content-type") ?? "").toContain("application/json") + expect(res.headers["content-type"] ?? "").toContain("application/json") const parsed = JSON.parse(body) expect(parsed).toMatchObject({ name: "BadRequest", @@ -96,8 +96,8 @@ describe("schema-rejection wire shape", () => { const test = yield* TestInstance // /find/file?limit=999999 violates the limit constraint check. const url = `/find/file?query=foo&limit=999999&directory=${encodeURIComponent(test.directory)}` - const res = yield* Effect.promise(async () => Server.Default().app.request(url)) - const body = yield* Effect.promise(async () => res.text()) + const res = yield* requestInDirectory(url, test.directory) + const body = yield* text(res) expect(res.status).toBe(400) const parsed = JSON.parse(body) expect(parsed).toMatchObject({ name: "BadRequest", data: { kind: "Query" } }) @@ -110,12 +110,8 @@ describe("schema-rejection wire shape", () => { () => Effect.gen(function* () { const test = yield* TestInstance - const res = yield* Effect.promise(async () => - Server.Default().app.request("/api/session?limit=0", { - headers: { "x-opencode-directory": test.directory }, - }), - ) - const parsed = JSON.parse(yield* Effect.promise(async () => res.text())) + const res = yield* requestInDirectory("/api/session?limit=0", test.directory) + const parsed = JSON.parse(yield* text(res)) expect(res.status).toBe(400) expect(parsed).toMatchObject({ _tag: "InvalidRequestError", kind: "Query" }) expect(parsed.message).toEqual(expect.any(String)) @@ -132,14 +128,12 @@ describe("schema-rejection wire shape", () => { Effect.gen(function* () { const test = yield* TestInstance const huge = "X".repeat(50_000) - const res = yield* Effect.promise(async () => - Server.Default().app.request(SyncPaths.history, { - method: "POST", - headers: { "x-opencode-directory": test.directory, "content-type": "application/json" }, - body: JSON.stringify({ aggregate: huge }), - }), - ) - const body = yield* Effect.promise(async () => res.text()) + const res = yield* requestInDirectory(SyncPaths.history, test.directory, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ aggregate: huge }), + }) + const body = yield* text(res) expect(res.status).toBe(400) // 1 KB cap + small JSON envelope ≈ <2 KB — never tens of KB. expect(body.length).toBeLessThan(2 * 1024) @@ -156,10 +150,10 @@ describe("schema-rejection wire shape", () => { const test = yield* TestInstance const sessionID = yield* seedCorruptStepFinishPart const url = `${SessionPaths.messages.replace(":sessionID", sessionID)}?limit=80&directory=${encodeURIComponent(test.directory)}` - const res = yield* Effect.promise(async () => Server.Default().app.request(url)) - const body = yield* Effect.promise(async () => res.text()) + const res = yield* requestInDirectory(url, test.directory) + const body = yield* text(res) expect(res.status).toBe(400) - expect(res.headers.get("content-type") ?? "").toContain("application/json") + expect(res.headers["content-type"] ?? "").toContain("application/json") const parsed = JSON.parse(body) expect(parsed).toMatchObject({ name: "BadRequest", data: { kind: "Body" } }) // Field path in data.message — what made this PR worth shipping. diff --git a/packages/opencode/test/server/httpapi-sdk.test.ts b/packages/opencode/test/server/httpapi-sdk.test.ts index 6e99fa7b128b..972891f9a4fe 100644 --- a/packages/opencode/test/server/httpapi-sdk.test.ts +++ b/packages/opencode/test/server/httpapi-sdk.test.ts @@ -1,7 +1,8 @@ import { afterEach, describe, expect } from "bun:test" -import { ConfigProvider, Deferred, Effect, Layer } from "effect" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Deferred, Effect, Layer } from "effect" import type * as Scope from "effect/Scope" -import { HttpRouter } from "effect/unstable/http" +import { HttpServer } from "effect/unstable/http" import { ChildProcessSpawner } from "effect/unstable/process" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" @@ -10,11 +11,9 @@ import { createOpencodeClient } from "@opencode-ai/sdk/v2" import { validateSession } from "../../src/cli/cmd/tui/validate-session" import { InstanceBootstrap } from "../../src/project/bootstrap-service" import { InstanceStore } from "../../src/project/instance-store" -import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" -import { Server } from "../../src/server/server" import { MessageID, PartID, SessionID } from "../../src/session/schema" import { MessageV2 } from "../../src/session/message-v2" -import { ModelID, ProviderID } from "../../src/provider/schema" + import type { Config } from "@/config/config" import { Session as SessionNs } from "@/session/session" import { errorMessage } from "../../src/util/error" @@ -24,6 +23,9 @@ import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance, tmpdirScoped } from "../fixture/fixture" import { awaitWithTimeout, testEffect } from "../lib/effect" import { testProviderConfig } from "../lib/test-provider" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { Database } from "@opencode-ai/core/database/database" +import { httpApiLayer } from "./httpapi-layer" const noopBootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void })) const it = testEffect( @@ -31,6 +33,8 @@ const it = testEffect( AppFileSystem.defaultLayer, CrossSpawnSpawner.defaultLayer, InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap)), + Database.defaultLayer, + httpApiLayer, ), ) @@ -45,55 +49,47 @@ type SdkResult = { response: Response; data?: unknown; error?: unknown } type Captured = { status: number; data?: unknown; error?: unknown } type ProjectFixture = { sdk: Sdk; directory: string } type LlmProjectFixture = ProjectFixture & { llm: TestLLMServer["Service"] } -type TestServices = AppFileSystem.Service | ChildProcessSpawner.ChildProcessSpawner | InstanceStore.Service +type TestServices = + | AppFileSystem.Service + | ChildProcessSpawner.ChildProcessSpawner + | InstanceStore.Service + | HttpServer.HttpServer type TestScope = Scope.Scope | TestServices -function app(serverPath: ServerPath, input?: { password?: string; username?: string }) { - Flag.OPENCODE_SERVER_PASSWORD = input?.password - Flag.OPENCODE_SERVER_USERNAME = input?.username - if (serverPath === "default") return Server.Default().app - - const handler = HttpRouter.toWebHandler( - HttpApiApp.routes.pipe( - Layer.provide( - ConfigProvider.layer( - ConfigProvider.fromUnknown({ - OPENCODE_SERVER_PASSWORD: input?.password, - OPENCODE_SERVER_USERNAME: input?.username, - }), - ), - ), - ), - { disableLogger: true }, - ).handler - return { - fetch: (request: Request) => handler(request, HttpApiApp.context), - request(input: string | URL | Request, init?: RequestInit) { - return this.fetch(input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init)) - }, - } -} - function client( serverPath: ServerPath, directory?: string, input?: { password?: string; username?: string; headers?: Record }, ) { - return createOpencodeClient({ - baseUrl: "http://localhost", - directory, - headers: input?.headers, - fetch: serverFetch(serverPath, input), - }) + return serverFetch(serverPath, input).pipe( + Effect.map((fetch) => + createOpencodeClient({ + baseUrl: "http://localhost", + directory, + headers: input?.headers, + fetch, + }), + ), + ) } function serverFetch(serverPath: ServerPath, input?: { password?: string; username?: string }) { - const serverApp = app(serverPath, input) - return Object.assign( - async (request: RequestInfo | URL, init?: RequestInit) => - await serverApp.fetch(request instanceof Request ? request : new Request(request, init)), - { preconnect: globalThis.fetch.preconnect }, - ) satisfies typeof globalThis.fetch + return HttpServer.HttpServer.use((server) => + Effect.sync(() => { + void serverPath + Flag.OPENCODE_SERVER_PASSWORD = input?.password + Flag.OPENCODE_SERVER_USERNAME = input?.username + const baseUrl = HttpServer.formatAddress(server.address) + return Object.assign( + async (request: RequestInfo | URL, init?: RequestInit) => { + const source = request instanceof Request ? request : new Request(request, init) + const url = new URL(source.url) + return globalThis.fetch(new Request(new URL(`${url.pathname}${url.search}`, baseUrl), source)) + }, + { preconnect: globalThis.fetch.preconnect }, + ) satisfies typeof globalThis.fetch + }), + ) } function authorization(username: string, password: string) { @@ -204,22 +200,14 @@ function httpapiInstance( Effect.gen(function* () { const instance = yield* TestInstance yield* options.setup?.(instance.directory) ?? Effect.void - return yield* run({ sdk: client(options.serverPath, instance.directory), directory: instance.directory }) + return yield* run({ sdk: yield* client(options.serverPath, instance.directory), directory: instance.directory }) }), { git: options.git ?? true, config: { formatter: false, lsp: false, ...options.config } }, ) } function serverPathParity(name: string, scenario: (serverPath: ServerPath) => Effect.Effect) { - it.live( - name, - Effect.gen(function* () { - const standard = yield* scenario("default") - yield* resetState() - const raw = yield* scenario("raw") - expect(raw).toEqual(standard) - }), - ) + it.live(name, scenario("raw")) } function withProject( @@ -237,7 +225,7 @@ function withProject( config: { formatter: false, lsp: false, ...options.config }, }) yield* options.setup?.(directory) ?? Effect.void - return yield* run({ sdk: client(serverPath, directory), directory }) + return yield* run({ sdk: yield* client(serverPath, directory), directory }) }) } @@ -310,9 +298,9 @@ function seedMessage(directory: string, sessionID: string) { role: "user", time: { created: Date.now() }, agent: "test", - model: { providerID: ProviderID.make("test"), modelID: ModelID.make("test") }, + model: { providerID: ProviderV2.ID.make("test"), modelID: ProviderV2.ModelID.make("test") }, tools: {}, - } satisfies MessageV2.User) + } satisfies SessionLegacy.User) const part = yield* svc.updatePart({ id: PartID.ascending(), sessionID: id, @@ -338,7 +326,7 @@ describe("HttpApi SDK", () => { httpapi( "uses the generated SDK for global and control routes", Effect.gen(function* () { - const sdk = client("raw") + const sdk = yield* client("raw") const health = yield* call(() => sdk.global.health()) const log = yield* call(() => sdk.app.log({ service: "httpapi-sdk-test", level: "info", message: "hello" })) @@ -380,7 +368,7 @@ describe("HttpApi SDK", () => { serverPathParity("matches generated SDK global and control behavior", (serverPath) => Effect.gen(function* () { - const sdk = client(serverPath) + const sdk = yield* client(serverPath) const health = yield* capture(() => sdk.global.health()) const log = yield* capture(() => sdk.app.log({ service: "sdk-parity", level: "info", message: "hello" })) const invalidAuth = yield* capture(() => sdk.auth.set({ providerID: "test" })) @@ -394,9 +382,11 @@ describe("HttpApi SDK", () => { ) serverPathParity("matches generated SDK global event stream", (serverPath) => - firstEvent((signal) => client(serverPath).global.event({ signal })).pipe( - Effect.map((event) => ({ type: record(record(event).payload).type })), - ), + Effect.gen(function* () { + const sdk = yield* client(serverPath) + const event = yield* firstEvent((signal) => sdk.global.event({ signal })) + return { type: record(record(event).payload).type } + }), ) serverPathParity("matches generated SDK instance event stream", (serverPath) => @@ -441,12 +431,13 @@ describe("HttpApi SDK", () => { withStandardProject(serverPath, ({ directory }) => Effect.gen(function* () { const sessionID = "ses_206f84f18ffeZ6hhD7pFYAiW5T" + const fetch = yield* serverFetch(serverPath) const thrown = yield* captureThrown(() => validateSession({ url: "http://localhost", directory, sessionID, - fetch: serverFetch(serverPath), + fetch, }), ) expect(errorMessage(thrown)).toBe(`Session not found: ${sessionID}`) @@ -460,21 +451,18 @@ describe("HttpApi SDK", () => { { serverPath: "raw", setup: writeStandardFiles }, ({ directory }) => Effect.gen(function* () { - const missing = yield* capture(() => - client("raw", directory, { password: "secret" }).file.read({ path: "hello.txt" }), - ) - const bad = yield* capture(() => - client("raw", directory, { - password: "secret", - headers: { authorization: authorization("opencode", "wrong") }, - }).file.read({ path: "hello.txt" }), - ) - const good = yield* capture(() => - client("raw", directory, { - password: "secret", - headers: { authorization: authorization("opencode", "secret") }, - }).file.read({ path: "hello.txt" }), - ) + const missingSdk = yield* client("raw", directory, { password: "secret" }) + const missing = yield* capture(() => missingSdk.file.read({ path: "hello.txt" })) + const badSdk = yield* client("raw", directory, { + password: "secret", + headers: { authorization: authorization("opencode", "wrong") }, + }) + const bad = yield* capture(() => badSdk.file.read({ path: "hello.txt" })) + const goodSdk = yield* client("raw", directory, { + password: "secret", + headers: { authorization: authorization("opencode", "secret") }, + }) + const good = yield* capture(() => goodSdk.file.read({ path: "hello.txt" })) return { statuses: statuses({ missing, bad, good }), @@ -640,7 +628,7 @@ describe("HttpApi SDK", () => { ), ) - // Regression: SyncEvent must publish on the same ProjectBus the /event handler + // Regression: EventV2 must publish on the same ProjectBus the /event handler // subscribes to, AND the /event stream must forward handler ALS/context into the // body-pump fiber. Drives the full SDK → /event → Session.updatePart → sync.run → // bus.publish → SDK subscriber path. Goes red if either the publisher uses a diff --git a/packages/opencode/test/server/httpapi-session.test.ts b/packages/opencode/test/server/httpapi-session.test.ts index 1e87ddc6b1da..7eac7d4f35c3 100644 --- a/packages/opencode/test/server/httpapi-session.test.ts +++ b/packages/opencode/test/server/httpapi-session.test.ts @@ -1,33 +1,40 @@ import { afterEach, describe, expect } from "bun:test" +import { NodeHttpServer, NodeServices } from "@effect/platform-node" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { mkdir } from "node:fs/promises" import path from "node:path" -import { Cause, Effect, Exit, Layer } from "effect" +import { Cause, Config, Effect, Exit, Layer } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse, HttpRouter, HttpServer } from "effect/unstable/http" +import { layerWebSocketConstructorGlobal } from "effect/unstable/socket/Socket" +import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Flag } from "@opencode-ai/core/flag/flag" import { registerAdapter } from "../../src/control-plane/adapters" import type { WorkspaceAdapter } from "../../src/control-plane/types" import { Workspace } from "../../src/control-plane/workspace" import { PermissionID } from "../../src/permission/schema" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { InstanceBootstrap } from "../../src/project/bootstrap" import { InstanceBootstrap as InstanceBootstrapService } from "../../src/project/bootstrap-service" import { InstanceStore } from "../../src/project/instance-store" import { Project } from "../../src/project/project" -import { Server } from "../../src/server/server" +import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" import * as HttpSessionError from "../../src/server/routes/instance/httpapi/handlers/session-errors" import { SessionPaths } from "../../src/server/routes/instance/httpapi/groups/session" import { Session } from "@/session/session" import { MessageID, PartID, SessionID, type SessionID as SessionIDType } from "../../src/session/schema" import { MessageV2 } from "../../src/session/message-v2" -import { Database } from "@/storage/db" -import { SessionMessageTable, SessionTable } from "@/session/session.sql" -import { SessionMessage } from "@opencode-ai/core/session-message" +import { Database } from "@opencode-ai/core/database/database" +import { SessionMessageTable, SessionTable } from "@opencode-ai/core/session/sql" +import { SessionMessage } from "@opencode-ai/core/session/message" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" import * as DateTime from "effect/DateTime" import * as Log from "@opencode-ai/core/util/log" import { eq } from "drizzle-orm" import { resetDatabase } from "../fixture/db" -import { disposeAllInstances, TestInstance } from "../fixture/fixture" +import { disposeAllInstances, provideInstanceEffect, TestInstance, tmpdirScoped } from "../fixture/fixture" +import { TestLLMServer } from "../lib/llm-server" +import { testProviderConfig } from "../lib/test-provider" import { testEffect } from "../lib/effect" void Log.init({ print: false }) @@ -42,11 +49,28 @@ const instanceStoreLayer = InstanceStore.defaultLayer.pipe( Layer.succeed(InstanceBootstrapService.Service, InstanceBootstrapService.Service.of({ run: Effect.void })), ), ) -const it = testEffect(Layer.mergeAll(instanceStoreLayer, Project.defaultLayer, Session.defaultLayer, workspaceLayer)) - -function app() { - return Server.Default().app -} +const servedRoutes: Layer.Layer = HttpRouter.serve( + HttpApiApp.routes, + { + disableListenLog: true, + disableLogger: true, + }, +) +const httpApiLayer = servedRoutes.pipe( + Layer.provide(layerWebSocketConstructorGlobal), + Layer.provideMerge(NodeHttpServer.layerTest), + Layer.provideMerge(NodeServices.layer), +) +const it = testEffect( + Layer.mergeAll( + instanceStoreLayer, + Project.defaultLayer, + Session.defaultLayer, + workspaceLayer, + Database.defaultLayer, + httpApiLayer, + ), +) function pathFor(path: string, params: Record) { return Object.entries(params).reduce((result, [key, value]) => result.replace(`:${key}`, value), path) @@ -64,7 +88,7 @@ function createTextMessage(sessionID: SessionIDType, text: string) { role: "user", sessionID, agent: "build", - model: { providerID: ProviderID.make("test"), modelID: ModelID.make("test") }, + model: { providerID: ProviderV2.ID.make("test"), modelID: ProviderV2.ModelID.make("test") }, time: { created: Date.now() }, }) const part = yield* svc.updatePart({ @@ -106,7 +130,7 @@ const createLocalWorkspace = (input: { projectID: Project.Info["id"]; type: stri ) const insertLegacyAssistantMessage = (sessionID: SessionIDType, time = 1) => - Effect.sync(() => { + Effect.gen(function* () { const message = new SessionMessage.Assistant({ id: SessionMessage.ID.create(), type: "assistant", @@ -119,90 +143,93 @@ const insertLegacyAssistantMessage = (sessionID: SessionIDType, time = 1) => time: { created: DateTime.makeUnsafe(time) }, content: [], }) - Database.use((db) => - db - .insert(SessionMessageTable) - .values([ - { - id: message.id, - session_id: sessionID, - type: message.type, - time_created: time, - data: { - time: { created: time }, - agent: message.agent, - model: message.model, - content: message.content, - } as NonNullable<(typeof SessionMessageTable.$inferInsert)["data"]>, - }, - ]) - .run(), - ) + const { db } = yield* Database.Service + yield* db + .insert(SessionMessageTable) + .values([ + { + id: message.id, + session_id: sessionID, + type: message.type, + time_created: time, + data: { + time: { created: time }, + agent: message.agent, + model: message.model, + content: message.content, + } as NonNullable<(typeof SessionMessageTable.$inferInsert)["data"]>, + }, + ]) + .run() + .pipe(Effect.orDie) }) const insertCorruptV2Message = (sessionID: SessionIDType, time = 1) => - Effect.sync(() => - Database.use((db) => - db - .insert(SessionMessageTable) - .values([ - { - id: SessionMessage.ID.create(), - session_id: sessionID, - type: "assistant", - time_created: time, - data: {} as NonNullable<(typeof SessionMessageTable.$inferInsert)["data"]>, - }, - ]) - .run(), - ), - ) + Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db + .insert(SessionMessageTable) + .values([ + { + id: SessionMessage.ID.create(), + session_id: sessionID, + type: "assistant", + time_created: time, + data: {} as NonNullable<(typeof SessionMessageTable.$inferInsert)["data"]>, + }, + ]) + .run() + .pipe(Effect.orDie) + }) const setLegacySummaryDiff = (sessionID: SessionIDType) => - Effect.sync(() => - Database.use((db) => - db - .update(SessionTable) - .set({ - summary_additions: 1, - summary_deletions: 0, - summary_files: 1, - summary_diffs: [{ additions: 1, deletions: 0 }], - }) - .where(eq(SessionTable.id, sessionID)) - .run(), - ), - ) + Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db + .update(SessionTable) + .set({ + summary_additions: 1, + summary_deletions: 0, + summary_files: 1, + summary_diffs: [{ additions: 1, deletions: 0 }], + }) + .where(eq(SessionTable.id, sessionID)) + .run() + .pipe(Effect.orDie) + }) const getWorkspaceID = (sessionID: SessionIDType) => - Effect.sync(() => - Database.use((db) => - db - .select({ workspaceID: SessionTable.workspace_id }) - .from(SessionTable) - .where(eq(SessionTable.id, sessionID)) - .get(), - ), - ) + Effect.gen(function* () { + const { db } = yield* Database.Service + return yield* db + .select({ workspaceID: SessionTable.workspace_id }) + .from(SessionTable) + .where(eq(SessionTable.id, sessionID)) + .get() + .pipe(Effect.orDie) + }) const clearSessionPath = (sessionID: SessionIDType) => - Effect.sync(() => - Database.use((db) => db.update(SessionTable).set({ path: null }).where(eq(SessionTable.id, sessionID)).run()), - ) + Effect.gen(function* () { + const { db } = yield* Database.Service + yield* db.update(SessionTable).set({ path: null }).where(eq(SessionTable.id, sessionID)).run().pipe(Effect.orDie) + }) function request(path: string, init?: RequestInit) { - return Effect.promise(async () => app().request(path, init)) + const url = new URL(path, "http://localhost") + return HttpClientRequest.fromWeb(new Request(url, init)).pipe( + HttpClientRequest.setUrl(url.pathname), + HttpClient.execute, + ) } -function json(response: Response) { - return Effect.promise(async () => { - if (response.status !== 200) throw new Error(await response.text()) - return (await response.json()) as T - }) +function json(response: HttpClientResponse.HttpClientResponse) { + if (response.status !== 200) return response.text.pipe(Effect.flatMap((text) => Effect.die(new Error(text)))) + return response.json.pipe(Effect.map((value) => value as T)) } -function responseJson(response: Response) { - return Effect.promise(() => response.json()) +function responseJson(response: HttpClientResponse.HttpClientResponse) { + return response.json } function requestJson(path: string, init?: RequestInit) { @@ -335,8 +362,8 @@ describe("session HttpApi", () => { const messages = yield* request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?limit=1`, { headers, }) - const messagePage = yield* json(messages) - const nextCursor = messages.headers.get("x-next-cursor") + const messagePage = yield* json(messages) + const nextCursor = messages.headers["x-next-cursor"] expect(nextCursor).toBeTruthy() expect(messagePage[0]?.parts[0]).toMatchObject({ type: "text" }) @@ -352,7 +379,7 @@ describe("session HttpApi", () => { ).toBe(400) expect( - yield* requestJson( + yield* requestJson( pathFor(SessionPaths.message, { sessionID: parent.id, messageID: message.info.id }), { headers }, ), @@ -368,6 +395,45 @@ describe("session HttpApi", () => { { git: true, config: { formatter: false, lsp: false } }, ) + it.live("uses the persisted session directory for prompt requests", () => + Effect.gen(function* () { + const llm = yield* TestLLMServer + yield* llm.text("ok", { usage: { input: 1, output: 1 } }) + + const config = testProviderConfig(llm.url) + const sessionDirectory = yield* tmpdirScoped({ git: true, config }) + const requestDirectory = yield* tmpdirScoped({ git: true, config }) + const session = yield* createSession({ title: "directory regression" }).pipe( + provideInstanceEffect(sessionDirectory), + ) + + const response = yield* request( + `${pathFor(SessionPaths.prompt, { sessionID: session.id })}?directory=${encodeURIComponent(requestDirectory)}`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + agent: "build", + model: { providerID: "test", modelID: "test-model" }, + parts: [{ type: "text", text: "which directory?" }], + }), + }, + ) + + expect(response.status).toBe(200) + yield* responseJson(response) + + const messages = yield* Session.use + .messages({ sessionID: session.id }) + .pipe(provideInstanceEffect(sessionDirectory), Effect.orDie) + const assistant = messages.find((message) => message.info.role === "assistant") + expect(assistant?.info.role === "assistant" ? assistant.info.path : undefined).toEqual({ + cwd: sessionDirectory, + root: sessionDirectory, + }) + }).pipe(Effect.provide(TestLLMServer.layer), Effect.provide(CrossSpawnSpawner.defaultLayer)), + ) + it.instance( "returns v2 public request errors for cursor and workspace query failures", () => @@ -602,6 +668,32 @@ describe("session HttpApi", () => { }) expect(forked.id).not.toBe(created.id) + const forkedWithoutContentType = yield* requestJson( + pathFor(SessionPaths.fork, { sessionID: created.id }), + { + method: "POST", + headers: { "x-opencode-directory": test.directory }, + }, + ) + expect(forkedWithoutContentType.id).not.toBe(created.id) + + const invalidFork = yield* request(pathFor(SessionPaths.fork, { sessionID: created.id }), { + method: "POST", + headers, + body: "{", + }) + expect(invalidFork.status).toBe(400) + + const forkedWhitespace = yield* requestJson( + pathFor(SessionPaths.fork, { sessionID: created.id }), + { + method: "POST", + headers, + body: " \n", + }, + ) + expect(forkedWhitespace.id).not.toBe(created.id) + expect( yield* requestJson(pathFor(SessionPaths.abort, { sessionID: created.id }), { method: "POST", @@ -720,9 +812,9 @@ describe("session HttpApi", () => { const response = yield* request(route, { headers }) - expect(response.headers.get("x-next-cursor")).toBeTruthy() - expect(response.headers.get("link")).toContain("limit=1") - expect(response.headers.get("access-control-expose-headers")?.toLowerCase()).toContain("x-next-cursor") + expect(response.headers["x-next-cursor"]).toBeTruthy() + expect(response.headers["link"]).toContain("limit=1") + expect(response.headers["access-control-expose-headers"]?.toLowerCase()).toContain("x-next-cursor") }), { git: true, config: { formatter: false, lsp: false } }, ) @@ -737,7 +829,7 @@ describe("session HttpApi", () => { const first = yield* createTextMessage(session.id, "first") const second = yield* createTextMessage(session.id, "second") - const updated = yield* requestJson( + const updated = yield* requestJson( pathFor(SessionPaths.updatePart, { sessionID: session.id, messageID: first.info.id, diff --git a/packages/opencode/test/server/httpapi-sync.test.ts b/packages/opencode/test/server/httpapi-sync.test.ts index 6a1c1624ccc9..0db044a86a28 100644 --- a/packages/opencode/test/server/httpapi-sync.test.ts +++ b/packages/opencode/test/server/httpapi-sync.test.ts @@ -1,7 +1,6 @@ import { afterEach, describe, expect, mock, spyOn } from "bun:test" -import { Context, Effect } from "effect" +import { Context, Effect, Layer } from "effect" import { Flag } from "@opencode-ai/core/flag/flag" -import { Server } from "../../src/server/server" import { SyncPaths } from "../../src/server/routes/instance/httpapi/groups/sync" import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" import { Session } from "@/session/session" @@ -9,16 +8,13 @@ import * as Log from "@opencode-ai/core/util/log" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) const originalWorkspaces = Flag.OPENCODE_EXPERIMENTAL_WORKSPACES const context = Context.empty() as Context.Context -const it = testEffect(Session.defaultLayer) - -function app() { - return Server.Default().app -} +const it = testEffect(Layer.mergeAll(Session.defaultLayer, httpApiLayer)) afterEach(async () => { mock.restore() @@ -38,23 +34,17 @@ describe("sync HttpApi", () => { const info = spyOn(Log.create({ service: "server.sync" }), "info") const session = yield* Session.use.create({ title: "sync" }) - const started = yield* Effect.promise(() => - Promise.resolve(app().request(SyncPaths.start, { method: "POST", headers })), - ) + const started = yield* requestInDirectory(SyncPaths.start, tmp.directory, { method: "POST", headers }) expect(started.status).toBe(200) - expect(yield* Effect.promise(() => started.json())).toBe(true) + expect(yield* started.json).toBe(true) - const history = yield* Effect.promise(() => - Promise.resolve( - app().request(SyncPaths.history, { - method: "POST", - headers, - body: JSON.stringify({}), - }), - ), - ) + const history = yield* requestInDirectory(SyncPaths.history, tmp.directory, { + method: "POST", + headers, + body: JSON.stringify({}), + }) expect(history.status).toBe(200) - const rows = (yield* Effect.promise(() => history.json())) as Array<{ + const rows = (yield* history.json) as Array<{ id: string aggregate_id: string seq: number @@ -63,28 +53,24 @@ describe("sync HttpApi", () => { }> expect(rows.map((row) => row.aggregate_id)).toContain(session.id) - const replayed = yield* Effect.promise(() => - Promise.resolve( - app().request(SyncPaths.replay, { - method: "POST", - headers, - body: JSON.stringify({ - directory: tmp.directory, - events: rows - .filter((row) => row.aggregate_id === session.id) - .map((row) => ({ - id: row.id, - aggregateID: row.aggregate_id, - seq: row.seq, - type: row.type, - data: row.data, - })), - }), - }), - ), - ) + const replayed = yield* requestInDirectory(SyncPaths.replay, tmp.directory, { + method: "POST", + headers, + body: JSON.stringify({ + directory: tmp.directory, + events: rows + .filter((row) => row.aggregate_id === session.id) + .map((row) => ({ + id: row.id, + aggregateID: row.aggregate_id, + seq: row.seq, + type: row.type, + data: row.data, + })), + }), + }) expect(replayed.status).toBe(200) - expect(yield* Effect.promise(() => replayed.json())).toEqual({ sessionID: session.id }) + expect(yield* replayed.json).toEqual({ sessionID: session.id }) expect(info.mock.calls.some(([message]) => message === "sync replay requested")).toBe(true) expect(info.mock.calls.some(([message]) => message === "sync replay complete")).toBe(true) }), @@ -123,15 +109,11 @@ describe("sync HttpApi", () => { ] for (const item of cases) { - const response = yield* Effect.promise(() => - Promise.resolve( - app().request(item.path, { - method: "POST", - headers, - body: JSON.stringify(item.body), - }), - ), - ) + const response = yield* requestInDirectory(item.path, tmp.directory, { + method: "POST", + headers, + body: JSON.stringify(item.body), + }) expect(response.status).toBe(400) } }), diff --git a/packages/opencode/test/server/httpapi-ui.test.ts b/packages/opencode/test/server/httpapi-ui.test.ts index 1ffa0d200502..72e227d1155d 100644 --- a/packages/opencode/test/server/httpapi-ui.test.ts +++ b/packages/opencode/test/server/httpapi-ui.test.ts @@ -406,6 +406,20 @@ describe("HttpApi UI fallback", () => { }), ) + it.live("accepts basic auth passwords containing colons for the web UI", () => + Effect.gen(function* () { + const response = yield* uiApp({ + password: "sec:ret", + username: "opencode", + disableEmbeddedWebUi: true, + }).request("/", { + headers: { authorization: `Basic ${btoa("opencode:sec:ret")}` }, + }) + + expect(response.status).toBe(200) + }), + ) + // Regression for #25698 (Ope): the browser fetches the PWA manifest and // its icons via flows that don't carry app-managed credentials (the // `` request is not under page-auth control), so the diff --git a/packages/opencode/test/server/httpapi-workspace-routing.test.ts b/packages/opencode/test/server/httpapi-workspace-routing.test.ts index 02a1361ba433..ee27d3e3ac25 100644 --- a/packages/opencode/test/server/httpapi-workspace-routing.test.ts +++ b/packages/opencode/test/server/httpapi-workspace-routing.test.ts @@ -1,6 +1,6 @@ import { NodeHttpServer, NodeServices } from "@effect/platform-node" import { describe, expect } from "bun:test" -import { Context, Effect, Layer, Queue, Ref } from "effect" +import { Context, Effect, Layer, Queue, Ref, Schema, Stream } from "effect" import { FetchHttpClient, HttpClient, @@ -11,22 +11,26 @@ import { HttpServerResponse, } from "effect/unstable/http" import * as Socket from "effect/unstable/socket/Socket" +import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from "effect/unstable/httpapi" import Http from "node:http" import { mkdir } from "node:fs/promises" import path from "node:path" import { registerAdapter } from "../../src/control-plane/adapters" -import { WorkspaceID } from "../../src/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import type { WorkspaceAdapter } from "../../src/control-plane/types" import { Workspace } from "../../src/control-plane/workspace" -import { WorkspaceTable } from "../../src/control-plane/workspace.sql" +import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" +import { Database } from "@opencode-ai/core/database/database" import { Project } from "../../src/project/project" +import { Session } from "../../src/session/session" import { WorkspacePaths } from "../../src/server/routes/instance/httpapi/groups/workspace" import { + WorkspaceRoutingMiddleware, + WorkspaceRoutingQuery, WorkspaceRouteContext, - workspaceRouterMiddleware, + workspaceRoutingLayer, } from "../../src/server/routes/instance/httpapi/middleware/workspace-routing" import { HEADER as FenceHeader } from "../../src/server/shared/fence" -import { Database } from "../../src/storage/db" import { resetDatabase } from "../fixture/db" import { workspaceLayerWithRuntimeFlags } from "../fixture/workspace" import { tmpdirScoped } from "../fixture/fixture" @@ -50,6 +54,7 @@ const it = testEffect( testStateLayer, NodeHttpServer.layerTest, NodeServices.layer, + Database.defaultLayer, Project.defaultLayer, workspaceLayer, Socket.layerWebSocketConstructorGlobal, @@ -60,13 +65,14 @@ type ProxiedRequest = { url: string method: string headers: Record + body: string } type TestHandler = ( request: HttpServerRequest.HttpServerRequest, ) => Effect.Effect -const workspaceRoutingTestLayer = workspaceRouterMiddleware.layer.pipe( +const workspaceRoutingTestLayer = workspaceRoutingLayer.pipe( Layer.provide([Socket.layerWebSocketConstructorGlobal, FetchHttpClient.layer]), ) @@ -160,10 +166,15 @@ const insertRemoteWorkspaceWithoutSync = (input: { type: string url: string }) => - Effect.sync(() => { - const id = WorkspaceID.ascending() + Effect.gen(function* () { + const id = WorkspaceV2.ID.ascending() registerAdapter(input.projectID, input.type, remoteAdapter(path.join(input.dir, `.${input.type}`), input.url)) - Database.use((db) => db.insert(WorkspaceTable).values({ id, type: input.type, project_id: input.projectID }).run()) + const { db } = yield* Database.Service + yield* db + .insert(WorkspaceTable) + .values({ id, type: input.type, project_id: input.projectID }) + .run() + .pipe(Effect.orDie) return id }) @@ -177,7 +188,12 @@ const startRemoteWorkspaceHttpServer = ( // everything else is the request being proxied by the middleware. const sync = syncResponse(request) if (sync) return yield* sync - return yield* handler({ url: request.url, method: request.method, headers: request.headers }) + return yield* handler({ + url: request.url, + method: request.method, + headers: request.headers, + body: yield* request.text, + }) }), ) @@ -203,16 +219,45 @@ const echoWebSocket = (request: HttpServerRequest.HttpServerRequest) => return HttpServerResponse.empty() }) -const serveRouteContextProbe = HttpRouter.add( - "GET", - "/probe", - Effect.gen(function* () { - // The fake route exposes the context installed by the middleware, so tests - // can assert routing decisions without pulling in the production API tree. - const route = yield* WorkspaceRouteContext - return yield* HttpServerResponse.json({ directory: route.directory, workspaceID: route.workspaceID }) - }), -).pipe(Layer.provide(workspaceRoutingTestLayer), HttpRouter.serve, Layer.build) +const ProbeResult = Schema.Struct({ + directory: Schema.String, + workspaceID: Schema.optional(Schema.String), +}) + +const ProbeApi = HttpApi.make("workspace-routing-probe").add( + HttpApiGroup.make("probe") + .add( + HttpApiEndpoint.get("get", "/probe", { query: WorkspaceRoutingQuery, success: ProbeResult }), + HttpApiEndpoint.patch("patch", "/probe", { query: WorkspaceRoutingQuery, success: Schema.Boolean }), + HttpApiEndpoint.get("session", "/session", { query: WorkspaceRoutingQuery, success: ProbeResult }), + HttpApiEndpoint.get("workspace", WorkspacePaths.list, { + query: WorkspaceRoutingQuery, + success: ProbeResult, + }), + ) + .middleware(WorkspaceRoutingMiddleware), +) + +const routeContextResponse = Effect.gen(function* () { + const route = yield* WorkspaceRouteContext + return { directory: route.directory, workspaceID: route.workspaceID } +}) + +const probeHandlers = HttpApiBuilder.group(ProbeApi, "probe", (handlers) => + handlers + .handle("get", () => routeContextResponse) + .handle("patch", () => Effect.succeed(false)) + .handle("session", () => routeContextResponse) + .handle("workspace", () => routeContextResponse), +) + +const serveProbe = HttpApiBuilder.layer(ProbeApi).pipe( + Layer.provide(probeHandlers), + Layer.provide(workspaceRoutingTestLayer), + Layer.provide(Layer.mock(Session.Service)({})), + HttpRouter.serve, + Layer.build, +) describe("HttpApi workspace routing middleware", () => { it.live("proxies remote workspace HTTP requests through the selected workspace target", () => @@ -250,19 +295,20 @@ describe("HttpApi workspace routing middleware", () => { // The local /probe handler should not run. Selecting a remote workspace // should make the middleware call HttpApiProxy.http instead. - yield* HttpRouter.add("PATCH", "/probe", HttpServerResponse.text("route called")).pipe( - Layer.provide(workspaceRoutingTestLayer), - HttpRouter.serve, - Layer.build, - ) + yield* serveProbe + const body = '{"title":"Remote workspace request"}' const response = yield* HttpClientRequest.patch(`/probe?workspace=${workspace.id}&keep=yes`).pipe( HttpClientRequest.setHeaders({ - "content-type": "application/json", "x-opencode-directory": "/secret/path", "x-opencode-workspace": "internal", }), + HttpClientRequest.bodyStream( + Stream.make(new TextEncoder().encode('{"title":"Remote '), new TextEncoder().encode('workspace request"}')), + { contentType: "application/json" }, + ), HttpClient.execute, + Effect.timeout("2 seconds"), ) expect(response.status).toBe(201) @@ -275,6 +321,7 @@ describe("HttpApi workspace routing middleware", () => { expect(forwardedURL?.searchParams.get("keep")).toBe("yes") expect(forwardedURL?.searchParams.get("workspace")).toBeNull() expect(forwarded?.method).toBe("PATCH") + expect(forwarded?.body).toBe(body) expect(forwarded?.headers["content-type"]).toBe("application/json") expect(forwarded?.headers["x-target-auth"]).toBe("secret") expect(forwarded?.headers["x-opencode-directory"]).toBeUndefined() @@ -286,9 +333,11 @@ describe("HttpApi workspace routing middleware", () => { Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) const project = yield* Project.use.fromDirectory(dir) - const workspaceID = WorkspaceID.ascending() + const workspaceID = WorkspaceV2.ID.ascending() const type = "remote-http-fence-target" - const waited = yield* Ref.make<{ workspaceID: WorkspaceID; state: Record } | undefined>(undefined) + const waited = yield* Ref.make<{ workspaceID: WorkspaceV2.ID; state: Record } | undefined>( + undefined, + ) const remoteUrl = yield* startRemoteWorkspaceHttpServer(() => HttpServerResponse.json( @@ -325,9 +374,11 @@ describe("HttpApi workspace routing middleware", () => { startWorkspaceSyncing: () => Effect.die("unused"), }) - yield* HttpRouter.add("PATCH", "/probe", HttpServerResponse.text("route called")).pipe( + yield* HttpApiBuilder.layer(ProbeApi).pipe( + Layer.provide(probeHandlers), Layer.provide(workspaceRoutingTestLayer), Layer.provide(Layer.succeed(Workspace.Service, workspace)), + Layer.provide(Layer.mock(Session.Service)({})), HttpRouter.serve, Layer.build, ) @@ -351,11 +402,7 @@ describe("HttpApi workspace routing middleware", () => { url: "http://127.0.0.1:1/base", }) - yield* HttpRouter.add("GET", "/probe", HttpServerResponse.text("route called")).pipe( - Layer.provide(workspaceRoutingTestLayer), - HttpRouter.serve, - Layer.build, - ) + yield* serveProbe const response = yield* HttpClient.get(`/probe?workspace=${workspaceID}`) @@ -378,11 +425,7 @@ describe("HttpApi workspace routing middleware", () => { // The client connects to the local test server. The middleware should // detect the WebSocket upgrade and proxy it to the remote /base/probe. - yield* HttpRouter.add("GET", "/probe", HttpServerResponse.text("route called")).pipe( - Layer.provide(workspaceRoutingTestLayer), - HttpRouter.serve, - Layer.build, - ) + yield* serveProbe const socket = yield* Socket.makeWebSocket( `${(yield* serverUrl).replace(/^http/, "ws")}/probe?workspace=${workspace.id}`, @@ -403,14 +446,10 @@ describe("HttpApi workspace routing middleware", () => { it.live("returns a missing workspace response for unknown workspace ids", () => Effect.gen(function* () { - const workspaceID = WorkspaceID.ascending("wrk_missing") + const workspaceID = WorkspaceV2.ID.ascending("wrk_missing") // If the middleware resolves the workspace first, this handler is never // reached and the response should be the middleware error response. - yield* HttpRouter.add("GET", "/probe", HttpServerResponse.text("route called")).pipe( - Layer.provide(workspaceRoutingTestLayer), - HttpRouter.serve, - Layer.build, - ) + yield* serveProbe const response = yield* HttpClient.get(`/probe?workspace=${workspaceID}`) @@ -433,14 +472,7 @@ describe("HttpApi workspace routing middleware", () => { // GET /session is a control-plane route: it lists sessions for the main // process and should not be redirected into the selected workspace target. - yield* HttpRouter.add( - "GET", - "/session", - Effect.gen(function* () { - const route = yield* WorkspaceRouteContext - return yield* HttpServerResponse.json({ directory: route.directory, workspaceID: route.workspaceID }) - }), - ).pipe(Layer.provide(workspaceRoutingTestLayer), HttpRouter.serve, Layer.build) + yield* serveProbe const response = yield* HttpClient.get(`/session?workspace=${workspace.id}`) @@ -463,14 +495,7 @@ describe("HttpApi workspace routing middleware", () => { // Workspace CRUD/status routes manage the control plane itself. Selecting // a workspace should preserve the selected id for handlers, but must not // swap the route context to the workspace target directory. - yield* HttpRouter.add( - "GET", - WorkspacePaths.list, - Effect.gen(function* () { - const route = yield* WorkspaceRouteContext - return yield* HttpServerResponse.json({ directory: route.directory, workspaceID: route.workspaceID }) - }), - ).pipe(Layer.provide(workspaceRoutingTestLayer), HttpRouter.serve, Layer.build) + yield* serveProbe const response = yield* HttpClient.get(`${WorkspacePaths.list}?workspace=${workspace.id}`) @@ -484,7 +509,7 @@ describe("HttpApi workspace routing middleware", () => { const dir = yield* tmpdirScoped() const queryDir = path.join(dir, "query-target") const headerDir = path.join(dir, "header-target") - yield* serveRouteContextProbe + yield* serveProbe // Without a selected workspace, the middleware falls back to request // directory hints before using the process cwd. @@ -495,9 +520,9 @@ describe("HttpApi workspace routing middleware", () => { ) expect(queryResponse.status).toBe(200) - expect(yield* queryResponse.json).toEqual({ directory: queryDir }) + expect(yield* queryResponse.json).toEqual({ directory: queryDir, workspaceID: null }) expect(headerResponse.status).toBe(200) - expect(yield* headerResponse.json).toEqual({ directory: headerDir }) + expect(yield* headerResponse.json).toEqual({ directory: headerDir, workspaceID: null }) }), ) @@ -513,7 +538,7 @@ describe("HttpApi workspace routing middleware", () => { directory: workspaceDir, }) - yield* serveRouteContextProbe + yield* serveProbe // /probe is not a control-plane route, so selecting a local workspace // should swap the route context to the workspace target directory. diff --git a/packages/opencode/test/server/httpapi-workspace.test.ts b/packages/opencode/test/server/httpapi-workspace.test.ts index 2e10d325f6ee..15bfe4279798 100644 --- a/packages/opencode/test/server/httpapi-workspace.test.ts +++ b/packages/opencode/test/server/httpapi-workspace.test.ts @@ -1,15 +1,16 @@ import { afterEach, describe, expect, mock } from "bun:test" -import { NodeServices } from "@effect/platform-node" import { mkdir } from "node:fs/promises" import path from "node:path" -import { Effect, Layer } from "effect" +import { Effect, Layer, Stream } from "effect" import { Flag } from "@opencode-ai/core/flag/flag" import { registerAdapter } from "../../src/control-plane/adapters" -import { WorkspaceID } from "../../src/control-plane/schema" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" import type { WorkspaceAdapter } from "../../src/control-plane/types" import { Workspace } from "../../src/control-plane/workspace" import { WorkspacePaths } from "../../src/server/routes/instance/httpapi/groups/workspace" +import { EventPaths } from "../../src/server/routes/instance/httpapi/groups/event" import { Session } from "@/session/session" +import { Database } from "@opencode-ai/core/database/database" import * as Log from "@opencode-ai/core/util/log" import { Server } from "../../src/server/server" import { resetDatabase } from "../fixture/db" @@ -18,8 +19,8 @@ import { InstanceBootstrap } from "../../src/project/bootstrap" import { InstanceStore } from "../../src/project/instance-store" import { Project } from "../../src/project/project" import { InstancePaths } from "../../src/server/routes/instance/httpapi/groups/instance" -import { WorkspaceRef } from "../../src/effect/instance-ref" import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) @@ -28,14 +29,29 @@ const workspaceLayer = Workspace.defaultLayer.pipe( Layer.provide(InstanceStore.defaultLayer), Layer.provide(InstanceBootstrap.defaultLayer), ) -const it = testEffect(Layer.mergeAll(NodeServices.layer, Project.defaultLayer, Session.defaultLayer, workspaceLayer)) +const it = testEffect( + Layer.mergeAll( + Project.defaultLayer, + Session.defaultLayer, + workspaceLayer, + InstanceStore.defaultLayer.pipe(Layer.provide(InstanceBootstrap.defaultLayer)), + Database.defaultLayer, + httpApiLayer, + ), +) function request(path: string, directory: string, init: RequestInit = {}) { - return Effect.promise(() => { - const headers = new Headers(init.headers) - headers.set("x-opencode-directory", directory) - return Promise.resolve(Server.Default().app.request(path, { ...init, headers })) - }) + return requestInDirectory(path, directory, init) +} + +function requestDefault(path: string, directory: string, init: RequestInit = {}) { + return requestInDirectory(path, directory, init) +} + +function requestServer(path: string, directory: string, init: RequestInit = {}) { + const headers = new Headers(init.headers) + headers.set("x-opencode-directory", directory) + return Effect.promise(() => Promise.resolve(Server.Default().app.request(path, { ...init, headers }))) } function localAdapter(directory: string): WorkspaceAdapter { @@ -179,17 +195,17 @@ describe("workspace HttpApi", () => { ]) expect(adapters.status).toBe(200) - expect(yield* Effect.promise(() => adapters.json())).toContainEqual({ + expect(yield* adapters.json).toContainEqual({ type: "worktree", name: "Worktree", description: "Create a git worktree", }) expect(workspaces.status).toBe(200) - expect(yield* Effect.promise(() => workspaces.json())).toEqual([]) + expect(yield* workspaces.json).toEqual([]) expect(status.status).toBe(200) - expect(yield* Effect.promise(() => status.json())).toEqual([]) + expect(yield* status.json).toEqual([]) }), ) @@ -206,7 +222,7 @@ describe("workspace HttpApi", () => { body: JSON.stringify({ type: "local-test", branch: null }), }) expect(created.status).toBe(200) - const workspace = (yield* Effect.promise(() => created.json())) as Workspace.Info + const workspace = (yield* created.json) as Workspace.Info expect(workspace).toMatchObject({ type: "local-test", name: "local-test" }) const session = yield* Session.use.create({}).pipe(provideInstance(dir)) @@ -219,11 +235,11 @@ describe("workspace HttpApi", () => { const removed = yield* request(WorkspacePaths.remove.replace(":id", workspace.id), dir, { method: "DELETE" }) expect(removed.status).toBe(200) - expect(yield* Effect.promise(() => removed.json())).toMatchObject({ id: workspace.id }) + expect(yield* removed.json).toMatchObject({ id: workspace.id }) const listed = yield* request(WorkspacePaths.list, dir) expect(listed.status).toBe(200) - expect(yield* Effect.promise(() => listed.json())).toEqual([]) + expect(yield* listed.json).toEqual([]) }), ) @@ -239,7 +255,7 @@ describe("workspace HttpApi", () => { expect(response.status).toBe(204) const listed = yield* request(WorkspacePaths.list, dir) - expect(yield* Effect.promise(() => listed.json())).toMatchObject([ + expect(yield* listed.json).toMatchObject([ { type, name: "listed-test", @@ -255,7 +271,7 @@ describe("workspace HttpApi", () => { Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) const session = yield* Session.use.create({}).pipe(provideInstance(dir)) - const workspaceID = WorkspaceID.ascending("wrk_missing_warp") + const workspaceID = WorkspaceV2.ID.ascending("wrk_missing_warp") const response = yield* request(WorkspacePaths.warp, dir, { method: "POST", @@ -264,7 +280,7 @@ describe("workspace HttpApi", () => { }) expect(response.status).toBe(404) - expect(yield* Effect.promise(() => response.json())).toEqual({ + expect(yield* response.json).toEqual({ name: "NotFoundError", data: { message: `Workspace not found: ${workspaceID}` }, }) @@ -285,7 +301,7 @@ describe("workspace HttpApi", () => { }) expect(created.status).toBe(200) - expect((yield* Effect.promise(() => created.json())) as Workspace.Info).toMatchObject({ + expect((yield* created.json) as Workspace.Info).toMatchObject({ type: "local-test", name: "local-test", }) @@ -297,7 +313,7 @@ describe("workspace HttpApi", () => { Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true const dir = yield* tmpdirScoped({ git: true }) - const created = yield* request(WorkspacePaths.list, dir, { + const created = yield* requestServer(WorkspacePaths.list, dir, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "worktree", branch: null }), @@ -322,7 +338,7 @@ describe("workspace HttpApi", () => { headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "local-target", branch: null }), }) - const workspace = (yield* Effect.promise(() => created.json())) as Workspace.Info + const workspace = (yield* created.json) as Workspace.Info const url = new URL(`http://localhost${InstancePaths.path}`) url.searchParams.set("workspace", workspace.id) @@ -330,7 +346,7 @@ describe("workspace HttpApi", () => { const response = yield* request(url.toString(), dir) expect(response.status).toBe(200) - expect(yield* Effect.promise(() => response.json())).toMatchObject({ directory: workspaceDir }) + expect(yield* response.json).toMatchObject({ directory: workspaceDir }) yield* request(WorkspacePaths.remove.replace(":id", workspace.id), dir, { method: "DELETE" }) }), ) @@ -344,6 +360,7 @@ describe("workspace HttpApi", () => { proxied.push(request) const url = new URL(request.url) if (url.pathname === "/base/global/event") return eventStreamResponse() + if (url.pathname === "/base/event") return eventStreamResponse() if (url.pathname === "/base/sync/history") return Response.json([]) return new Response( JSON.stringify({ @@ -372,19 +389,19 @@ describe("workspace HttpApi", () => { "x-target-auth": "secret", }), ) - const created = yield* request(WorkspacePaths.list, dir, { + const created = yield* requestDefault(WorkspacePaths.list, dir, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "remote-target", branch: null }), }) - const workspace = (yield* Effect.promise(() => created.json())) as Workspace.Info + const workspace = (yield* created.json) as Workspace.Info const url = new URL("http://localhost/config") url.searchParams.set("workspace", workspace.id) url.searchParams.set("keep", "yes") try { - const response = yield* request(url.toString(), dir, { + const response = yield* requestDefault(url.toString(), dir, { method: "PATCH", headers: { "accept-encoding": "br", @@ -394,10 +411,10 @@ describe("workspace HttpApi", () => { body: JSON.stringify({ $schema: "https://opencode.ai/config.json" }), }) - const responseBody = yield* Effect.promise(() => response.text()) + const responseBody = yield* response.text expect({ status: response.status, body: responseBody }).toMatchObject({ status: 201 }) - expect(response.headers.get("content-length")).toBeNull() - expect(response.headers.get("x-remote")).toBe("yes") + expect(response.headers["content-length"]).toBeUndefined() + expect(response.headers["x-remote"]).toBe("yes") expect(JSON.parse(responseBody)).toEqual({ proxied: true, path: "/base/config", keep: "yes", workspace: null }) const forwarded = proxied.filter((item) => new URL(item.url).pathname === "/base/config") expect(forwarded).toEqual([ @@ -413,9 +430,18 @@ describe("workspace HttpApi", () => { ]) expect(forwarded[0]?.headers).not.toHaveProperty("x-opencode-directory") expect(forwarded[0]?.headers).not.toHaveProperty("x-opencode-workspace") + + const eventURL = new URL(`http://localhost${EventPaths.event}`) + eventURL.searchParams.set("workspace", workspace.id) + const eventResponse = yield* request(eventURL.toString(), dir) + expect(eventResponse.status).toBe(200) + expect(eventResponse.headers["content-type"]).toContain("text/event-stream") + const event = Array.from(yield* eventResponse.stream.pipe(Stream.take(1), Stream.runCollect))[0] + expect(new TextDecoder().decode(event)).toContain("server.connected") + expect(proxied.some((item) => new URL(item.url).pathname === "/base/event")).toBe(true) } finally { void remote.stop(true) - yield* request(WorkspacePaths.remove.replace(":id", workspace.id), dir, { method: "DELETE" }) + yield* requestDefault(WorkspacePaths.remove.replace(":id", workspace.id), dir, { method: "DELETE" }) } }), ) @@ -439,24 +465,29 @@ describe("workspace HttpApi", () => { "remote-session-target", remoteAdapter(path.join(dir, ".remote-session"), `http://127.0.0.1:${remote.port}/base`), ) - const created = yield* request(WorkspacePaths.list, dir, { + const created = yield* requestDefault(WorkspacePaths.list, dir, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "remote-session-target", branch: null }), }) - const workspace = (yield* Effect.promise(() => created.json())) as Workspace.Info - const session = yield* Session.use - .create() - .pipe(Effect.provideService(WorkspaceRef, workspace.id), provideInstance(dir)) + const workspace = (yield* created.json) as Workspace.Info + const sessionResponse = yield* requestDefault("/session", dir, { method: "POST" }) + const session = (yield* sessionResponse.json) as Session.Info + const warped = yield* requestDefault(WorkspacePaths.warp, dir, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ id: workspace.id, sessionID: session.id }), + }) + expect(warped.status).toBe(204) try { - const response = yield* request(`http://localhost/session/${session.id}/message`, dir, { + const response = yield* requestDefault(`http://localhost/session/${session.id}/message`, dir, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ parts: [{ type: "text", text: "hello" }] }), }) - const responseBody = yield* Effect.promise(() => response.text()) + const responseBody = yield* response.text expect({ status: response.status, body: responseBody }).toMatchObject({ status: 200 }) expect(JSON.parse(responseBody)).toEqual({ proxied: true, path: `/base/session/${session.id}/message` }) expect(proxied.filter((item) => new URL(item.url).pathname === `/base/session/${session.id}/message`)).toEqual([ @@ -465,9 +496,19 @@ describe("workspace HttpApi", () => { method: "POST", }), ]) + + const aborted = yield* request(`http://localhost/session/${session.id}/abort`, dir, { method: "POST" }) + expect(aborted.status).toBe(200) + expect(proxied.filter((item) => new URL(item.url).pathname === `/base/session/${session.id}/abort`)).toEqual([ + expect.objectContaining({ + url: `http://127.0.0.1:${remote.port}/base/session/${session.id}/abort`, + method: "POST", + body: "", + }), + ]) } finally { void remote.stop(true) - yield* request(WorkspacePaths.remove.replace(":id", workspace.id), dir, { method: "DELETE" }) + yield* requestDefault(WorkspacePaths.remove.replace(":id", workspace.id), dir, { method: "DELETE" }) } }), ) diff --git a/packages/opencode/test/server/negative-tokens-regression.test.ts b/packages/opencode/test/server/negative-tokens-regression.test.ts index 290023ead756..e79f655fb83a 100644 --- a/packages/opencode/test/server/negative-tokens-regression.test.ts +++ b/packages/opencode/test/server/negative-tokens-regression.test.ts @@ -6,20 +6,21 @@ // strict `NonNegativeInt` schema then made every load of the message list // fail to encode, killing Desktop boot for every user with such a row. import { describe, expect } from "bun:test" -import { Effect } from "effect" +import { Effect, Layer } from "effect" import { eq } from "drizzle-orm" -import { ModelID, ProviderID } from "../../src/provider/schema" -import { Server } from "../../src/server/server" + import { SessionPaths } from "../../src/server/routes/instance/httpapi/groups/session" import { Session } from "@/session/session" import { MessageID, PartID } from "../../src/session/schema" -import * as Database from "@/storage/db" -import { PartTable } from "@/session/session.sql" +import { Database } from "@opencode-ai/core/database/database" +import { PartTable } from "@opencode-ai/core/session/sql" import { resetDatabase } from "../fixture/db" import { TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" -const it = testEffect(Session.defaultLayer) +const it = testEffect(Layer.mergeAll(Session.defaultLayer, Database.defaultLayer, httpApiLayer)) function seedNegativeTokenSession() { return Effect.gen(function* () { @@ -30,7 +31,7 @@ function seedNegativeTokenSession() { role: "user", sessionID: info.id, agent: "build", - model: { providerID: ProviderID.make("test"), modelID: ModelID.make("test") }, + model: { providerID: ProviderV2.ID.make("test"), modelID: ProviderV2.ModelID.make("test") }, time: { created: Date.now() }, }) const partID = PartID.ascending() @@ -46,20 +47,20 @@ function seedNegativeTokenSession() { // Bypass the schema with a direct SQL update to install the // negative `output` value we want to test loading. - Database.use((db) => - db - .update(PartTable) - .set({ - data: { - type: "step-finish", - reason: "stop", - cost: 0, - tokens: { input: 0, output: -42, reasoning: 0, cache: { read: 0, write: 0 } }, - } as never, - }) - .where(eq(PartTable.id, partID)) - .run(), - ) + const { db } = yield* Database.Service + yield* db + .update(PartTable) + .set({ + data: { + type: "step-finish", + reason: "stop", + cost: 0, + tokens: { input: 0, output: -42, reasoning: 0, cache: { read: 0, write: 0 } }, + } as never, + }) + .where(eq(PartTable.id, partID)) + .run() + .pipe(Effect.orDie) return info.id }) @@ -73,7 +74,7 @@ describe("messages endpoint tolerates legacy negative token counts", () => { const test = yield* TestInstance const sessionID = yield* seedNegativeTokenSession() const url = `${SessionPaths.messages.replace(":sessionID", sessionID)}?limit=80&directory=${encodeURIComponent(test.directory)}` - const res = yield* Effect.promise(async () => Server.Default().app.request(url)) + const res = yield* requestInDirectory(url, test.directory) expect(res.status, "messages endpoint 400'd on legacy negative tokens").not.toBe(400) }), { git: true, config: { formatter: false, lsp: false } }, diff --git a/packages/opencode/test/server/project-init-git.test.ts b/packages/opencode/test/server/project-init-git.test.ts index b22777861bc4..fb9118a2fb23 100644 --- a/packages/opencode/test/server/project-init-git.test.ts +++ b/packages/opencode/test/server/project-init-git.test.ts @@ -1,17 +1,18 @@ import { afterEach, describe, expect } from "bun:test" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Effect, Layer } from "effect" +import { HttpClientResponse } from "effect/unstable/http" import path from "path" import { InstanceRef } from "../../src/effect/instance-ref" import { InstanceBootstrap } from "../../src/project/bootstrap-service" import { InstanceStore } from "../../src/project/instance-store" import { GlobalBus, type GlobalEvent } from "../../src/bus/global" import { Snapshot } from "../../src/snapshot" -import { Server } from "../../src/server/server" import * as Log from "@opencode-ai/core/util/log" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) @@ -23,18 +24,16 @@ afterEach(async () => { const noopBootstrap = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void })) const testInstanceStore = InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrap)) -const it = testEffect(Layer.mergeAll(AppFileSystem.defaultLayer, Snapshot.defaultLayer, testInstanceStore)) +const it = testEffect( + Layer.mergeAll(AppFileSystem.defaultLayer, Snapshot.defaultLayer, testInstanceStore, httpApiLayer), +) function request(directory: string, url: string, init: RequestInit = {}) { - return Effect.promise(() => { - const headers = new Headers(init.headers) - headers.set("x-opencode-directory", directory) - return Promise.resolve(Server.Default().app.request(url, { ...init, headers })) - }) + return requestInDirectory(url, directory, init) } -function json(response: Response) { - return Effect.promise(() => response.json() as Promise) +function json(response: HttpClientResponse.HttpClientResponse) { + return response.json.pipe(Effect.map((value) => value as T)) } function collectGlobalEvents() { diff --git a/packages/opencode/test/server/session-actions.test.ts b/packages/opencode/test/server/session-actions.test.ts index 4aca3436cf5a..093ec43c03ed 100644 --- a/packages/opencode/test/server/session-actions.test.ts +++ b/packages/opencode/test/server/session-actions.test.ts @@ -1,14 +1,14 @@ import { afterEach, describe, expect, mock } from "bun:test" -import { Effect } from "effect" -import { Server } from "../../src/server/server" +import { Effect, Layer } from "effect" import { Session as SessionNs } from "@/session/session" import * as Log from "@opencode-ai/core/util/log" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) -const it = testEffect(SessionNs.defaultLayer) +const it = testEffect(Layer.mergeAll(SessionNs.defaultLayer, httpApiLayer)) afterEach(async () => { mock.restore() @@ -16,6 +16,64 @@ afterEach(async () => { }) describe("session action routes", () => { + it.instance( + "session routes expose metadata on create, update, get, and fork", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const headers = { "Content-Type": "application/json" } + + const created = yield* requestInDirectory("/session", test.directory, { + method: "POST", + headers, + body: JSON.stringify({ + title: "meta-session", + metadata: { source: "sdk", trace: { id: "abc" } }, + }), + }) + expect(created.status).toBe(200) + + const session = (yield* created.json) as SessionNs.Info + expect(session.metadata).toEqual({ source: "sdk", trace: { id: "abc" } }) + + const updated = yield* requestInDirectory(`/session/${session.id}`, test.directory, { + method: "PATCH", + headers, + body: JSON.stringify({ metadata: { source: "sdk", trace: { id: "def" }, tags: ["one"] } }), + }) + expect(updated.status).toBe(200) + + const next = (yield* updated.json) as SessionNs.Info + expect(next.metadata).toEqual({ source: "sdk", trace: { id: "def" }, tags: ["one"] }) + + const fetched = yield* requestInDirectory(`/session/${session.id}`, test.directory) + expect(fetched.status).toBe(200) + expect(((yield* fetched.json) as SessionNs.Info).metadata).toEqual(next.metadata) + + const forked = yield* requestInDirectory(`/session/${session.id}/fork`, test.directory, { + method: "POST", + headers, + body: JSON.stringify({}), + }) + expect(forked.status).toBe(200) + + const fork = (yield* forked.json) as SessionNs.Info + expect(fork.metadata).toEqual(next.metadata) + + const reset = yield* requestInDirectory(`/session/${session.id}`, test.directory, { + method: "PATCH", + headers, + body: JSON.stringify({ metadata: {} }), + }) + expect(reset.status).toBe(200) + expect(((yield* reset.json) as SessionNs.Info).metadata).toEqual({}) + + yield* SessionNs.Service.use((svc) => svc.remove(fork.id).pipe(Effect.ignore)) + yield* SessionNs.Service.use((svc) => svc.remove(session.id).pipe(Effect.ignore)) + }), + { git: true }, + ) + it.instance( "abort route returns success", () => @@ -25,17 +83,10 @@ describe("session action routes", () => { SessionNs.use.remove(created.id).pipe(Effect.ignore), ) - const res = yield* Effect.promise(() => - Promise.resolve( - Server.Default().app.request(`/session/${session.id}/abort`, { - method: "POST", - headers: { "x-opencode-directory": test.directory }, - }), - ), - ) + const res = yield* requestInDirectory(`/session/${session.id}/abort`, test.directory, { method: "POST" }) expect(res.status).toBe(200) - expect(yield* Effect.promise(() => res.json())).toBe(true) + expect(yield* res.json).toBe(true) }), { git: true }, ) diff --git a/packages/opencode/test/server/session-diff-missing-patch.test.ts b/packages/opencode/test/server/session-diff-missing-patch.test.ts index cec1dbcd9c56..d77a23380a10 100644 --- a/packages/opencode/test/server/session-diff-missing-patch.test.ts +++ b/packages/opencode/test/server/session-diff-missing-patch.test.ts @@ -4,25 +4,29 @@ * the response was Schema-encoded against `Snapshot.FileDiff` with * `patch: Schema.String` (required), so any session whose stored * `summary_diffs` had a row without `patch` returned HTTP 400 and the - * session never loaded. + * session never loaded. Legacy session-level diffs are no longer surfaced, + * but the endpoint remains compatible and must still return successfully. * * This test inserts a session row with a missing-patch diff entry and - * asserts that GET /session//diff returns 200 with the row intact. + * asserts that GET /session//diff returns 200 with empty data. */ import { afterEach, describe, expect } from "bun:test" import { Effect, Layer } from "effect" -import { Server } from "@/server/server" import { SessionPaths } from "@/server/routes/instance/httpapi/groups/session" import { Session } from "@/session/session" import { Storage } from "@/storage/storage" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { MessageID } from "@/session/schema" +import { ProviderV2 } from "@opencode-ai/core/provider" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" import * as Log from "@opencode-ai/core/util/log" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) -const it = testEffect(Layer.mergeAll(Session.defaultLayer, Storage.defaultLayer)) +const it = testEffect(Layer.mergeAll(Session.defaultLayer, Storage.defaultLayer, httpApiLayer)) afterEach(async () => { await disposeAllInstances() @@ -38,7 +42,7 @@ const withSession = (input?: Parameters[0]) => describe("session diff with missing patch (#26574)", () => { it.instance( - "GET /session//diff returns 200 when summary_diffs row has no patch", + "GET /session//diff ignores legacy session-level diff storage", () => Effect.gen(function* () { const test = yield* TestInstance @@ -51,24 +55,43 @@ describe("session diff with missing patch (#26574)", () => { storage.write(["session_diff", session.id], [{ file: "legacy.txt", additions: 1, deletions: 0 }]), ) - const response = yield* Effect.promise(() => - Promise.resolve( - Server.Default().app.request(pathFor(SessionPaths.diff, { sessionID: session.id }), { - headers: { "x-opencode-directory": test.directory }, - }), - ), + const response = yield* requestInDirectory( + pathFor(SessionPaths.diff, { sessionID: session.id }), + test.directory, ) expect(response.status).toBe(200) - const body = (yield* Effect.promise(() => response.json())) as Array<{ - file: string - patch?: string - additions: number - }> - expect(body).toHaveLength(1) - expect(body[0]?.file).toBe("legacy.txt") - expect(body[0]?.additions).toBe(1) - expect(body[0]?.patch).toBeUndefined() + expect(yield* response.json).toEqual([]) + }), + { git: true, config: { formatter: false, lsp: false } }, + ) + + it.instance( + "GET /session//diff returns requested turn diffs", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const session = yield* withSession({ title: "turn-diff" }) + const messageID = MessageID.ascending() + yield* Session.use.updateMessage({ + id: messageID, + sessionID: session.id, + role: "user", + time: { created: Date.now() }, + agent: "build", + model: { providerID: ProviderV2.ID.make("test"), modelID: ProviderV2.ModelID.make("model") }, + summary: { + diffs: [{ file: "turn.ts", additions: 1, deletions: 0, status: "modified" }], + }, + } satisfies SessionLegacy.User) + + const response = yield* requestInDirectory( + `${pathFor(SessionPaths.diff, { sessionID: session.id })}?messageID=${messageID}`, + test.directory, + ) + + expect(response.status).toBe(200) + expect(yield* response.json).toEqual([{ file: "turn.ts", additions: 1, deletions: 0, status: "modified" }]) }), { git: true, config: { formatter: false, lsp: false } }, ) diff --git a/packages/opencode/test/server/session-list.test.ts b/packages/opencode/test/server/session-list.test.ts index 467ab7c9a5b4..f98f8e42a939 100644 --- a/packages/opencode/test/server/session-list.test.ts +++ b/packages/opencode/test/server/session-list.test.ts @@ -1,28 +1,33 @@ import { afterEach, describe, expect } from "bun:test" import { Effect, Layer } from "effect" +import { Database } from "@opencode-ai/core/database/database" +import { SessionProjector } from "@opencode-ai/core/session/projector" import { Session as SessionNs } from "@/session/session" import * as Log from "@opencode-ai/core/util/log" import { disposeAllInstances, provideInstance, TestInstance } from "../fixture/fixture" import { mkdir } from "fs/promises" import path from "path" -import { Database } from "@/storage/db" -import { SessionTable } from "@/session/session.sql" +import { SessionTable } from "@opencode-ai/core/session/sql" import { eq } from "drizzle-orm" import { testEffect } from "../lib/effect" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { Storage } from "@/storage/storage" -import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" import { BackgroundJob } from "@/background/job" void Log.init({ print: false }) const it = testEffect( - SessionNs.layer.pipe( - Layer.provide(Bus.layer), - Layer.provide(Storage.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), - Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: false })), - Layer.provide(BackgroundJob.defaultLayer), + Layer.mergeAll( + Database.defaultLayer, + SessionNs.layer.pipe( + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(Storage.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(SessionProjector.defaultLayer), + Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: false })), + Layer.provide(BackgroundJob.defaultLayer), + ), ), ) @@ -148,16 +153,19 @@ describe("session.list", () => { provideInstance(path.join(test.directory, "packages", "app")), ) - yield* Effect.sync(() => - Database.use((db) => - db.update(SessionTable).set({ path: null }).where(eq(SessionTable.id, current.id)).run(), - ), - ) - yield* Effect.sync(() => - Database.use((db) => - db.update(SessionTable).set({ path: null }).where(eq(SessionTable.id, sibling.id)).run(), - ), - ) + const { db } = yield* Database.Service + yield* db + .update(SessionTable) + .set({ path: null }) + .where(eq(SessionTable.id, current.id)) + .run() + .pipe(Effect.orDie) + yield* db + .update(SessionTable) + .set({ path: null }) + .where(eq(SessionTable.id, sibling.id)) + .run() + .pipe(Effect.orDie) const pathIDs = (yield* SessionNs.Service.use((session) => session.list({ @@ -227,4 +235,20 @@ describe("session.list", () => { }), { git: true }, ) + + it.instance( + "includes metadata in listed sessions", + () => + Effect.gen(function* () { + const meta = { source: "sdk", trace: { id: "abc" } } + const created = yield* withSession({ title: "meta-session", metadata: meta }) + + const listed = (yield* SessionNs.Service.use((session) => session.list({ search: "meta-session" }))).find( + (item) => item.id === created.id, + ) + + expect(listed?.metadata).toEqual(meta) + }), + { git: true }, + ) }) diff --git a/packages/opencode/test/server/session-messages.test.ts b/packages/opencode/test/server/session-messages.test.ts index 6cd17d25552c..c176c8e03973 100644 --- a/packages/opencode/test/server/session-messages.test.ts +++ b/packages/opencode/test/server/session-messages.test.ts @@ -1,21 +1,24 @@ import { afterEach, describe, expect } from "bun:test" -import { Effect } from "effect" -import { Server } from "../../src/server/server" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Effect, Layer } from "effect" +import { HttpClientResponse } from "effect/unstable/http" import { Session as SessionNs } from "@/session/session" import { MessageV2 } from "../../src/session/message-v2" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { MessageID, PartID, type SessionID } from "../../src/session/schema" import * as Log from "@opencode-ai/core/util/log" import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) -const it = testEffect(SessionNs.defaultLayer) +const it = testEffect(Layer.mergeAll(SessionNs.defaultLayer, httpApiLayer)) const model = { - providerID: ProviderID.make("test"), - modelID: ModelID.make("test"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("test"), } afterEach(async () => { @@ -62,25 +65,25 @@ const fill = Effect.fn("SessionMessagesTest.fill")(function* ( agent: "test", model, tools: {}, - } satisfies MessageV2.User) + } satisfies SessionLegacy.User) yield* session.updatePart({ id: PartID.ascending(), sessionID, messageID: id, type: "text", text: `m${i}`, - } satisfies MessageV2.TextPart) + } satisfies SessionLegacy.TextPart) return id }), ) }) function request(path: string) { - return Effect.promise(() => Promise.resolve(Server.Default().app.request(path))) + return TestInstance.pipe(Effect.flatMap((test) => requestInDirectory(path, test.directory))) } -function json(response: Response) { - return Effect.promise(() => response.json() as Promise) +function json(response: HttpClientResponse.HttpClientResponse) { + return response.json.pipe(Effect.map((body) => body as T)) } describe("session messages endpoint", () => { @@ -93,15 +96,15 @@ describe("session messages endpoint", () => { const a = yield* request(`/session/${session.id}/message?limit=2`) expect(a.status).toBe(200) - const aBody = yield* json(a) + const aBody = yield* json(a) expect(aBody.map((item) => item.info.id)).toEqual(ids.slice(-2)) - const cursor = a.headers.get("x-next-cursor") + const cursor = a.headers["x-next-cursor"] expect(cursor).toBeTruthy() - expect(a.headers.get("link")).toContain('rel="next"') + expect(a.headers["link"]).toContain('rel="next"') const b = yield* request(`/session/${session.id}/message?limit=2&before=${encodeURIComponent(cursor!)}`) expect(b.status).toBe(200) - const bBody = yield* json(b) + const bBody = yield* json(b) expect(bBody.map((item) => item.info.id)).toEqual(ids.slice(-4, -2)) }), ), @@ -117,7 +120,7 @@ describe("session messages endpoint", () => { const res = yield* request(`/session/${session.id}/message`) expect(res.status).toBe(200) - const body = yield* json(res) + const body = yield* json(res) expect(body.map((item) => item.info.id)).toEqual(ids) }), ), @@ -149,7 +152,7 @@ describe("session messages endpoint", () => { const res = yield* request(`/session/${session.id}/message?limit=510`) expect(res.status).toBe(200) - const body = yield* json(res) + const body = yield* json(res) expect(body).toHaveLength(510) }), ), diff --git a/packages/opencode/test/server/session-select.test.ts b/packages/opencode/test/server/session-select.test.ts index 0f3875ae140c..a54a77c3f202 100644 --- a/packages/opencode/test/server/session-select.test.ts +++ b/packages/opencode/test/server/session-select.test.ts @@ -1,14 +1,14 @@ import { describe, expect } from "bun:test" -import { Effect } from "effect" +import { Effect, Layer } from "effect" import { Session } from "@/session/session" import * as Log from "@opencode-ai/core/util/log" -import { Server } from "../../src/server/server" import { TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" void Log.init({ print: false }) -const it = testEffect(Session.defaultLayer) +const it = testEffect(Layer.mergeAll(Session.defaultLayer, httpApiLayer)) describe("tui.selectSession endpoint", () => { it.instance( @@ -18,22 +18,14 @@ describe("tui.selectSession endpoint", () => { const tmp = yield* TestInstance const session = yield* Session.use.create({}) - const app = Server.Default().app - const response = yield* Effect.promise(() => - Promise.resolve( - app.request("/tui/select-session", { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-opencode-directory": tmp.directory, - }, - body: JSON.stringify({ sessionID: session.id }), - }), - ), - ) + const response = yield* requestInDirectory("/tui/select-session", tmp.directory, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sessionID: session.id }), + }) expect(response.status).toBe(200) - const body = yield* Effect.promise(() => response.json()) + const body = yield* response.json expect(body).toBe(true) }), { git: true }, @@ -46,19 +38,11 @@ describe("tui.selectSession endpoint", () => { const tmp = yield* TestInstance const nonExistentSessionID = "ses_nonexistent123" - const app = Server.Default().app - const response = yield* Effect.promise(() => - Promise.resolve( - app.request("/tui/select-session", { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-opencode-directory": tmp.directory, - }, - body: JSON.stringify({ sessionID: nonExistentSessionID }), - }), - ), - ) + const response = yield* requestInDirectory("/tui/select-session", tmp.directory, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sessionID: nonExistentSessionID }), + }) expect(response.status).toBe(404) }), @@ -72,19 +56,11 @@ describe("tui.selectSession endpoint", () => { const tmp = yield* TestInstance const invalidSessionID = "invalid_session_id" - const app = Server.Default().app - const response = yield* Effect.promise(() => - Promise.resolve( - app.request("/tui/select-session", { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-opencode-directory": tmp.directory, - }, - body: JSON.stringify({ sessionID: invalidSessionID }), - }), - ), - ) + const response = yield* requestInDirectory("/tui/select-session", tmp.directory, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sessionID: invalidSessionID }), + }) expect(response.status).toBe(400) }), diff --git a/packages/opencode/test/server/workspace-proxy.test.ts b/packages/opencode/test/server/workspace-proxy.test.ts index 732f2560a27d..869570f62da6 100644 --- a/packages/opencode/test/server/workspace-proxy.test.ts +++ b/packages/opencode/test/server/workspace-proxy.test.ts @@ -112,6 +112,22 @@ describe("HttpApi workspace proxy", () => { }), ) + it.live("proxies bodyless Web mutation requests as an empty body", () => + Effect.gen(function* () { + const url = yield* listenServer( + Effect.fnUntraced(function* (req: HttpServerRequest.HttpServerRequest) { + return yield* HttpServerResponse.json({ method: req.method, body: yield* req.text }) + }), + ) + const request = HttpServerRequest.fromWeb(new Request("http://localhost/session/abc/abort", { method: "POST" })) + const httpClient = yield* HttpClient.HttpClient + const response = yield* HttpApiProxy.http(httpClient, `${url}/session/abc/abort`, undefined, request) + + expect(response.status).toBe(200) + expect(yield* HttpServerResponse.toClientResponse(response).json).toEqual({ method: "POST", body: "" }) + }), + ) + it.live("strips opencode-internal headers and merges extra headers", () => Effect.gen(function* () { let forwarded: Record = {} diff --git a/packages/opencode/test/server/worktree-endpoint-repro.test.ts b/packages/opencode/test/server/worktree-endpoint-repro.test.ts index 747393bbd2eb..62a61858861c 100644 --- a/packages/opencode/test/server/worktree-endpoint-repro.test.ts +++ b/packages/opencode/test/server/worktree-endpoint-repro.test.ts @@ -1,10 +1,9 @@ import { describe, expect } from "bun:test" import { Effect, Layer, Queue } from "effect" -import { HttpRouter } from "effect/unstable/http" import { Flag } from "@opencode-ai/core/flag/flag" import { GlobalBus, type GlobalEvent } from "@/bus/global" import { Worktree } from "@/worktree" -import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" +import { Server } from "../../src/server/server" import { ExperimentalPaths } from "../../src/server/routes/instance/httpapi/groups/experimental" import { WorkspacePaths } from "../../src/server/routes/instance/httpapi/groups/workspace" import { resetDatabase } from "../fixture/db" @@ -30,19 +29,16 @@ const stateLayer = Layer.effectDiscard( const it = testEffect(stateLayer) const worktreeTest = process.platform === "win32" ? it.instance.skip : it.instance -type TestServer = ReturnType +type TestServer = ReturnType["app"] type CreatedWorktree = { directory: string } type ScopedWorktree = { directory: string; body: CreatedWorktree; ready: Effect.Effect } function serverScoped() { - return Effect.acquireRelease( - Effect.sync(() => HttpRouter.toWebHandler(HttpApiApp.routes, { disableLogger: true })), - (server) => Effect.promise(() => server.dispose()).pipe(Effect.ignore), - ) + return Effect.sync(() => Server.Default().app) } function request(server: TestServer, input: string, init?: RequestInit) { - return Effect.promise(() => server.handler(new Request(new URL(input, "http://localhost"), init), HttpApiApp.context)) + return Effect.promise(() => Promise.resolve(server.request(input, init))) } function withRequestTimeout(effect: Effect.Effect, label: string, ms = 5_000) { @@ -228,6 +224,28 @@ describe("worktree endpoint reproduction", () => { { git: true }, ) + worktreeTest( + "direct HttpApi worktree create rejects explicit null payload", + () => + Effect.gen(function* () { + const test = yield* TestInstance + const server = yield* serverScoped() + + const response = yield* request( + server, + `${ExperimentalPaths.worktree}?directory=${encodeURIComponent(test.directory)}`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: "null", + }, + ) + + expect(response.status).toBe(400) + }), + { git: true }, + ) + worktreeTest( "workspace worktree create does not hang", () => diff --git a/packages/opencode/test/session/compaction.test.ts b/packages/opencode/test/session/compaction.test.ts index 55ddc621cac2..9bff89c348ad 100644 --- a/packages/opencode/test/session/compaction.test.ts +++ b/packages/opencode/test/session/compaction.test.ts @@ -1,8 +1,10 @@ import { afterEach, describe, expect, mock, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Database } from "@opencode-ai/core/database/database" +import { EventV2Bridge } from "@/event-v2-bridge" import { APICallError } from "ai" import { Cause, Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect" import * as Stream from "effect/Stream" -import { Bus } from "../../src/bus" import { Config } from "@/config/config" import { Image } from "@/image/image" import { Agent } from "../../src/agent/agent" @@ -18,8 +20,8 @@ import { MessageV2 } from "../../src/session/message-v2" import { MessageID, PartID, SessionID } from "../../src/session/schema" import { SessionStatus } from "../../src/session/status" import { SessionSummary } from "../../src/session/summary" -import { SessionV2 } from "../../src/v2/session" -import { ModelID, ProviderID } from "../../src/provider/schema" +import { SessionV2 } from "@opencode-ai/core/session" + import type { Provider } from "@/provider/provider" import * as SessionProcessorModule from "../../src/session/processor" import { Snapshot } from "../../src/snapshot" @@ -27,10 +29,9 @@ import { ProviderTest } from "../fake/provider" import { testEffect } from "../lib/effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { TestConfig } from "../fixture/config" -import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" -import { EventV2Bridge } from "@/event-v2-bridge" import { LLMEvent, Usage } from "@opencode-ai/llm" +import { ProviderV2 } from "@opencode-ai/core/provider" void Log.init({ print: false }) @@ -44,8 +45,8 @@ const summary = Layer.succeed( ) const ref = { - providerID: ProviderID.make("test"), - modelID: ModelID.make("test-model"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("test-model"), } const usage = (input: ConstructorParameters[0]) => new Usage(input) @@ -229,22 +230,29 @@ const deps = Layer.mergeAll( layer("continue"), Agent.defaultLayer, Plugin.defaultLayer, - Bus.layer, + EventV2Bridge.defaultLayer, Config.defaultLayer, - SyncEvent.defaultLayer, RuntimeFlags.layer({ experimentalEventSystem: true }), + Database.defaultLayer, EventV2Bridge.defaultLayer, ) const env = Layer.mergeAll( SessionNs.defaultLayer, + Database.defaultLayer, + EventV2Bridge.defaultLayer, CrossSpawnSpawner.defaultLayer, SessionCompaction.layer.pipe(Layer.provide(SessionNs.defaultLayer), Layer.provideMerge(deps)), ) const it = testEffect(env) -const compactionEnv = Layer.mergeAll(SessionNs.defaultLayer, CrossSpawnSpawner.defaultLayer) +const compactionEnv = Layer.mergeAll( + SessionNs.defaultLayer, + Database.defaultLayer, + EventV2Bridge.defaultLayer, + CrossSpawnSpawner.defaultLayer, +) const itCompaction = testEffect(compactionEnv) type CompactionProcessOptions = { @@ -260,8 +268,8 @@ function withCompaction(options?: CompactionProcessOptions) { } function compactionProcessLayer(options?: CompactionProcessOptions) { - const bus = Bus.layer - const status = SessionStatus.layer.pipe(Layer.provide(bus)) + const events = EventV2Bridge.defaultLayer + const status = SessionStatus.layer.pipe(Layer.provide(events)) const processor = options?.llm ? SessionProcessorModule.SessionProcessor.layer.pipe( Layer.provide(summary), @@ -270,7 +278,7 @@ function compactionProcessLayer(options?: CompactionProcessOptions) { Layer.provide(status), ) : layer(options?.result ?? "continue") - return Layer.mergeAll(SessionCompaction.layer.pipe(Layer.provide(processor)), processor, bus, status).pipe( + return Layer.mergeAll(SessionCompaction.layer.pipe(Layer.provide(processor)), processor, events, status).pipe( Layer.provide(SessionNs.defaultLayer), Layer.provide((options?.provider ?? wide()).layer), Layer.provide(Snapshot.defaultLayer), @@ -279,9 +287,8 @@ function compactionProcessLayer(options?: CompactionProcessOptions) { Layer.provide(Agent.defaultLayer), Layer.provide(options?.plugin ?? Plugin.defaultLayer), Layer.provide(status), - Layer.provide(bus), + Layer.provide(events), Layer.provide(options?.config ?? Config.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), Layer.provide(RuntimeFlags.layer({ experimentalEventSystem: true })), Layer.provide(EventV2Bridge.defaultLayer), ) @@ -296,7 +303,7 @@ function readCompactionPart(sessionID: SessionID) { .messages({ sessionID }) .pipe( Effect.map((messages) => - messages.at(-2)?.parts.find((item): item is MessageV2.CompactionPart => item.type === "compaction"), + messages.at(-2)?.parts.find((item): item is SessionLegacy.CompactionPart => item.type === "compaction"), ), ) } @@ -585,6 +592,25 @@ describe("session.compaction.create", () => { auto: true, overflow: true, }) + }), + ), + ) + + it.live.skip( + "projects a compaction message to v2 (v2 projector disabled)", + provideTmpdirInstance(() => + Effect.gen(function* () { + const compact = yield* SessionCompaction.Service + const ssn = yield* SessionNs.Service + const info = yield* ssn.create({}) + + yield* compact.create({ + sessionID: info.id, + agent: "build", + model: ref, + auto: true, + overflow: true, + }) const v2 = yield* SessionV2.Service.use((svc) => svc.messages({ sessionID: info.id })).pipe( Effect.provide(SessionV2.defaultLayer), @@ -623,7 +649,7 @@ describe("session.compaction.prune", () => { type: "text", text: "first", }) - const b: MessageV2.Assistant = { + const b: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", sessionID: info.id, @@ -719,7 +745,7 @@ describe("session.compaction.prune", () => { type: "text", text: "first", }) - const b: MessageV2.Assistant = { + const b: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", sessionID: info.id, @@ -821,19 +847,22 @@ describe("session.compaction.process", () => { it.instance( "publishes compacted event on continue", Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const ssn = yield* SessionNs.Service const session = yield* ssn.create({}) const msg = yield* createUserMessage(session.id, "hello") const msgs = yield* ssn.messages({ sessionID: session.id }) const done = yield* Deferred.make() let seen = false - const unsub = yield* bus.subscribeCallback(SessionCompaction.Event.Compacted, (evt) => { - if (evt.properties.sessionID !== session.id) return + const unsub = yield* events.listen((evt) => { + if (evt.type !== SessionCompaction.Event.Compacted.type) return Effect.void + if ((evt.data as typeof SessionCompaction.Event.Compacted.data.Type).sessionID !== session.id) + return Effect.void seen = true Deferred.doneUnsafe(done, Effect.void) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsub)) + yield* Effect.addFinalizer(() => unsub) const result = yield* SessionCompaction.use.process({ parentID: msg.id, @@ -1064,7 +1093,7 @@ describe("session.compaction.process", () => { expect(captured).toContain("zzzz") expect(captured).not.toContain("keep tail") - const filtered = MessageV2.filterCompacted(MessageV2.stream(session.id)) + const filtered = MessageV2.filterCompacted(yield* MessageV2.stream(session.id)) expect(filtered.map((msg) => msg.info.id).slice(0, 3)).toEqual([parent!, expect.any(String), keep.id]) expect(filtered[1]?.info.role).toBe("assistant") expect(filtered[1]?.info.role === "assistant" ? filtered[1].info.summary : false).toBe(true) @@ -1197,17 +1226,19 @@ describe("session.compaction.process", () => { return Effect.gen(function* () { const ssn = yield* SessionNs.Service - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const ready = yield* Deferred.make() const session = yield* ssn.create({}) const msg = yield* createUserMessage(session.id, "hello") const msgs = yield* ssn.messages({ sessionID: session.id }) - const off = yield* bus.subscribeCallback(SessionStatus.Event.Status, (evt) => { - if (evt.properties.sessionID !== session.id) return - if (evt.properties.status.type !== "retry") return + const off = yield* events.listen((evt) => { + if (evt.type !== SessionStatus.Event.Status.type) return Effect.void + const data = evt.data as typeof SessionStatus.Event.Status.data.Type + if (data.sessionID !== session.id || data.status.type !== "retry") return Effect.void Deferred.doneUnsafe(ready, Effect.void) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(off)) + yield* Effect.addFinalizer(() => off) const fiber = yield* SessionCompaction.use .process({ @@ -1405,7 +1436,7 @@ describe("session.compaction.process", () => { yield* createUserMessage(session.id, "latest turn") yield* createCompactionMarker(session.id) - msgs = MessageV2.filterCompacted(MessageV2.stream(session.id)) + msgs = MessageV2.filterCompacted(yield* MessageV2.stream(session.id)) parent = msgs.at(-1)?.info.id expect(parent).toBeTruthy() yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false }) @@ -1441,12 +1472,12 @@ describe("session.compaction.process", () => { const u4 = yield* createUserMessage(session.id, "four") yield* createCompactionMarker(session.id) - msgs = MessageV2.filterCompacted(MessageV2.stream(session.id)) + msgs = MessageV2.filterCompacted(yield* MessageV2.stream(session.id)) parent = msgs.at(-1)?.info.id expect(parent).toBeTruthy() yield* SessionCompaction.use.process({ parentID: parent!, messages: msgs, sessionID: session.id, auto: false }) - const filtered = MessageV2.filterCompacted(MessageV2.stream(session.id)) + const filtered = MessageV2.filterCompacted(yield* MessageV2.stream(session.id)) const ids = filtered.map((msg) => msg.info.id) expect(ids).not.toContain(u1.id) diff --git a/packages/opencode/test/session/instruction.test.ts b/packages/opencode/test/session/instruction.test.ts index 0f9c340dd4c1..3855e9c3a7fb 100644 --- a/packages/opencode/test/session/instruction.test.ts +++ b/packages/opencode/test/session/instruction.test.ts @@ -1,21 +1,23 @@ import { describe, expect, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import path from "path" import { Effect, FileSystem, Layer } from "effect" import { FetchHttpClient } from "effect/unstable/http" import { NodeFileSystem } from "@effect/platform-node" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { AppFileSystem } from "@opencode-ai/core/filesystem" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { Instruction } from "../../src/session/instruction" import type { MessageV2 } from "../../src/session/message-v2" import { MessageID, PartID, SessionID } from "../../src/session/schema" import { Global } from "@opencode-ai/core/global" import { RuntimeFlags } from "../../src/effect/runtime-flags" -import { provideInstance, provideTmpdirInstance, tmpdirScoped } from "../fixture/fixture" +import { provideInstance, provideTmpdirInstance, testInstanceStoreLayer, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { TestConfig } from "../fixture/config" +import { ProviderV2 } from "@opencode-ai/core/provider" -const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer)) +const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, NodeFileSystem.layer, testInstanceStoreLayer)) const configLayer = TestConfig.layer() @@ -61,7 +63,7 @@ const tmpWithFiles = (files: Record) => return dir }) -function loaded(filepath: string): MessageV2.WithParts[] { +function loaded(filepath: string): SessionLegacy.WithParts[] { const sessionID = SessionID.make("session-loaded-1") const messageID = MessageID.make("msg_message-loaded-1") @@ -74,8 +76,8 @@ function loaded(filepath: string): MessageV2.WithParts[] { time: { created: 0 }, agent: "build", model: { - providerID: ProviderID.make("anthropic"), - modelID: ModelID.make("claude-sonnet-4-20250514"), + providerID: ProviderV2.ID.make("anthropic"), + modelID: ProviderV2.ModelID.make("claude-sonnet-4-20250514"), }, }, parts: [ diff --git a/packages/opencode/test/session/llm-native-recorded.test.ts b/packages/opencode/test/session/llm-native-recorded.test.ts index 19d8f6f42ce1..9aa8ce95d600 100644 --- a/packages/opencode/test/session/llm-native-recorded.test.ts +++ b/packages/opencode/test/session/llm-native-recorded.test.ts @@ -1,6 +1,8 @@ import { NodeFileSystem } from "@effect/platform-node" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { ModelsDev } from "@opencode-ai/core/models-dev" +import { LocationServiceMap } from "@opencode-ai/core/location-layer" import { HttpRecorder, Redactor } from "@opencode-ai/http-recorder" import { describe, expect, test } from "bun:test" import { tool, type ModelMessage, type JSONValue } from "ai" @@ -12,7 +14,7 @@ import { Auth } from "@/auth" import { Config } from "@/config/config" import { Plugin } from "@/plugin" import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "@/provider/schema" + import { Filesystem } from "@/util/filesystem" import { LLMEvent, LLMResponse } from "@opencode-ai/llm" import { LLMClient, RequestExecutor, WebSocketExecutor } from "@opencode-ai/llm/route" @@ -24,6 +26,7 @@ import { MessageV2 } from "../../src/session/message-v2" import { MessageID, SessionID } from "../../src/session/schema" import { TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" const FIXTURES_DIR = path.join(import.meta.dir, "../fixtures/recordings") @@ -40,7 +43,7 @@ const replayOpenAIOAuth = { type RecordedScenario = { readonly id: string readonly name: string - readonly providerID: ProviderID + readonly providerID: ProviderV2.ID readonly modelID: string readonly cassette: string readonly protocol: string @@ -87,7 +90,7 @@ function decodeRecordOpenAIOAuth() { } const providerConfig = (input: { - readonly providerID: ProviderID + readonly providerID: ProviderV2.ID readonly name: string readonly env: string[] readonly npm: string @@ -112,7 +115,7 @@ const RECORDED_SCENARIOS = [ { id: "openai-api-key", name: "OpenAI API key", - providerID: ProviderID.openai, + providerID: ProviderV2.ID.openai, modelID: "gpt-4.1-mini", cassette: "session/native-openai-tool-loop", protocol: "openai-responses", @@ -120,7 +123,7 @@ const RECORDED_SCENARIOS = [ canRecord: () => Boolean(envValue("OPENCODE_RECORD_OPENAI_API_KEY", "OPENAI_API_KEY")), config: (model) => providerConfig({ - providerID: ProviderID.openai, + providerID: ProviderV2.ID.openai, name: "OpenAI", env: ["OPENAI_API_KEY"], npm: "@ai-sdk/openai", @@ -135,7 +138,7 @@ const RECORDED_SCENARIOS = [ { id: "openai-oauth", name: "OpenAI OAuth", - providerID: ProviderID.openai, + providerID: ProviderV2.ID.openai, modelID: "gpt-5.5", cassette: "session/native-openai-oauth-tool-loop", protocol: "openai-responses", @@ -146,7 +149,7 @@ const RECORDED_SCENARIOS = [ stableID: "openai-oauth", config: (model) => providerConfig({ - providerID: ProviderID.openai, + providerID: ProviderV2.ID.openai, name: "OpenAI", env: ["OPENAI_API_KEY"], npm: "@ai-sdk/openai", @@ -158,7 +161,7 @@ const RECORDED_SCENARIOS = [ { id: "opencode-proxy", name: "OpenCode proxy", - providerID: ProviderID.opencode, + providerID: ProviderV2.ID.opencode, modelID: "gpt-5.2-codex", cassette: "session/native-zen-tool-loop", protocol: "openai-responses", @@ -166,7 +169,7 @@ const RECORDED_SCENARIOS = [ canRecord: () => Boolean(process.env.OPENCODE_RECORD_CONSOLE_TOKEN && process.env.OPENCODE_RECORD_ZEN_ORG_ID), config: (model) => providerConfig({ - providerID: ProviderID.opencode, + providerID: ProviderV2.ID.opencode, name: "OpenCode Zen", env: ["OPENCODE_CONSOLE_TOKEN"], npm: "@ai-sdk/openai-compatible", @@ -181,7 +184,7 @@ const RECORDED_SCENARIOS = [ { id: "anthropic-api-key", name: "Anthropic API key", - providerID: ProviderID.anthropic, + providerID: ProviderV2.ID.anthropic, modelID: "claude-haiku-4-5-20251001", cassette: "session/native-anthropic-tool-loop", protocol: "anthropic-messages", @@ -189,7 +192,7 @@ const RECORDED_SCENARIOS = [ canRecord: () => Boolean(envValue("OPENCODE_RECORD_ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY")), config: (model) => providerConfig({ - providerID: ProviderID.anthropic, + providerID: ProviderV2.ID.anthropic, name: "Anthropic", env: ["ANTHROPIC_API_KEY"], npm: "@ai-sdk/anthropic", @@ -276,6 +279,7 @@ function recordedNativeLLMLayer(scenario: RecordedScenario) { Layer.provide(Plugin.defaultLayer), Layer.provide(ModelsDev.defaultLayer), Layer.provide(RuntimeFlags.defaultLayer), + Layer.provide(LocationServiceMap.layer), ) // Only the HTTP client is recorded; RequestExecutor and the opencode LLM stack remain real. const recordedClient = LLMClient.layer.pipe( @@ -371,7 +375,7 @@ const driveToolLoop = (scenario: RecordedScenario) => const stableID = scenario.stableID ?? scenario.providerID const sessionID = SessionID.make(`session-recorded-${stableID}-loop`) - const modelID = ModelID.make(model.id) + const modelID = ProviderV2.ModelID.make(model.id) const agent = { name: "test", mode: "primary", @@ -392,7 +396,7 @@ const driveToolLoop = (scenario: RecordedScenario) => time: { created: 0 }, agent: agent.name, model: { providerID: scenario.providerID, modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID, model: resolved, agent, diff --git a/packages/opencode/test/session/llm-native.test.ts b/packages/opencode/test/session/llm-native.test.ts index 076d4c9f789a..29c25d1ad0aa 100644 --- a/packages/opencode/test/session/llm-native.test.ts +++ b/packages/opencode/test/session/llm-native.test.ts @@ -6,13 +6,14 @@ import { Effect, Layer, Stream } from "effect" import { LLMNative } from "@/session/llm/native-request" import { LLMNativeRuntime } from "@/session/llm/native-runtime" import type { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "@/provider/schema" + import { OAUTH_DUMMY_KEY } from "@/auth" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" const baseModel: Provider.Model = { - id: ModelID.make("gpt-5-mini"), - providerID: ProviderID.make("openai"), + id: ProviderV2.ModelID.make("gpt-5-mini"), + providerID: ProviderV2.ID.make("openai"), api: { id: "gpt-5-mini", url: "https://api.openai.com/v1", @@ -62,7 +63,7 @@ const baseModel: Provider.Model = { } const providerInfo: Provider.Info = { - id: ProviderID.make("openai"), + id: ProviderV2.ID.make("openai"), name: "OpenAI", source: "config", env: ["OPENAI_API_KEY"], @@ -354,7 +355,7 @@ describe("session.llm-native.request", () => { const compatible = LLMNative.model({ model: { ...baseModel, - providerID: ProviderID.make("opencode"), + providerID: ProviderV2.ID.make("opencode"), api: { ...baseModel.api, url: "https://ai.example.test/v1", npm: "@ai-sdk/openai-compatible" }, }, apiKey: "test-key", @@ -388,8 +389,8 @@ describe("session.llm-native.request", () => { }) expect( LLMNativeRuntime.status({ - model: { ...baseModel, providerID: ProviderID.make("opencode") }, - provider: { ...providerInfo, id: ProviderID.make("opencode") }, + model: { ...baseModel, providerID: ProviderV2.ID.make("opencode") }, + provider: { ...providerInfo, id: ProviderV2.ID.make("opencode") }, auth: undefined, }), ).toMatchObject({ @@ -400,10 +401,10 @@ describe("session.llm-native.request", () => { LLMNativeRuntime.status({ model: { ...baseModel, - providerID: ProviderID.make("opencode"), + providerID: ProviderV2.ID.make("opencode"), api: { ...baseModel.api, npm: "@ai-sdk/openai-compatible" }, }, - provider: { ...providerInfo, id: ProviderID.make("opencode") }, + provider: { ...providerInfo, id: ProviderV2.ID.make("opencode") }, auth: undefined, }), ).toMatchObject({ @@ -412,8 +413,8 @@ describe("session.llm-native.request", () => { }) expect( LLMNativeRuntime.status({ - model: { ...baseModel, providerID: ProviderID.make("google") }, - provider: { ...providerInfo, id: ProviderID.make("google") }, + model: { ...baseModel, providerID: ProviderV2.ID.make("google") }, + provider: { ...providerInfo, id: ProviderV2.ID.make("google") }, auth: undefined, }), ).toEqual({ type: "unsupported", reason: "provider is not openai, opencode, or anthropic" }) @@ -454,12 +455,12 @@ describe("session.llm-native.request", () => { LLMNativeRuntime.status({ model: { ...baseModel, - providerID: ProviderID.make("anthropic"), + providerID: ProviderV2.ID.make("anthropic"), api: { ...baseModel.api, npm: "@ai-sdk/anthropic", url: "https://api.anthropic.com/v1" }, }, provider: { ...providerInfo, - id: ProviderID.make("anthropic"), + id: ProviderV2.ID.make("anthropic"), name: "Anthropic", env: ["ANTHROPIC_API_KEY"], options: { apiKey: "test-anthropic-key" }, @@ -472,10 +473,10 @@ describe("session.llm-native.request", () => { test("prefers console provider api key over stored opencode auth", () => { expect( LLMNativeRuntime.status({ - model: { ...baseModel, providerID: ProviderID.make("opencode") }, + model: { ...baseModel, providerID: ProviderV2.ID.make("opencode") }, provider: { ...providerInfo, - id: ProviderID.make("opencode"), + id: ProviderV2.ID.make("opencode"), options: { apiKey: "console-token" }, key: "zen-token", }, diff --git a/packages/opencode/test/session/llm.test.ts b/packages/opencode/test/session/llm.test.ts index cd381ecd014e..2376750eeae0 100644 --- a/packages/opencode/test/session/llm.test.ts +++ b/packages/opencode/test/session/llm.test.ts @@ -1,4 +1,5 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import path from "path" import { tool, type ModelMessage } from "ai" import { Cause, Effect, Exit, Fiber, Layer, Stream } from "effect" @@ -13,7 +14,7 @@ import { Provider } from "@/provider/provider" import { ProviderTransform } from "@/provider/transform" import { ModelsDev } from "@opencode-ai/core/models-dev" import { Plugin } from "@/plugin" -import { ProviderID, ModelID } from "../../src/provider/schema" + import { testEffect } from "../lib/effect" import type { Agent } from "../../src/agent/agent" import { MessageV2 } from "../../src/session/message-v2" @@ -22,6 +23,7 @@ import { RuntimeFlags } from "@/effect/runtime-flags" import { Permission } from "@/permission" import { LLMAISDK } from "@/session/llm/ai-sdk" import { Session as SessionNs } from "@/session/session" +import { ProviderV2 } from "@opencode-ai/core/provider" type ConfigModel = NonNullable[string]["models"]>[string] @@ -712,8 +714,8 @@ describe("session.llm.stream", () => { ) const resolved = yield* Provider.use.getModel( - ProviderID.make(vivgridFixture.providerID), - ModelID.make(fixture.model.id), + ProviderV2.ID.make(vivgridFixture.providerID), + ProviderV2.ModelID.make(fixture.model.id), ) const sessionID = SessionID.make("session-test-1") const agent = { @@ -731,8 +733,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make(vivgridFixture.providerID), modelID: resolved.id, variant: "high" }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make(vivgridFixture.providerID), modelID: resolved.id, variant: "high" }, + } satisfies SessionLegacy.User yield* drain({ user, @@ -786,8 +788,8 @@ describe("session.llm.stream", () => { const pending = waitStreamingRequest("/chat/completions") const resolved = yield* Provider.use.getModel( - ProviderID.make(alibabaQwenFixture.providerID), - ModelID.make(fixture.model.id), + ProviderV2.ID.make(alibabaQwenFixture.providerID), + ProviderV2.ModelID.make(fixture.model.id), ) const sessionID = SessionID.make("session-test-service-abort") const agent = { @@ -802,8 +804,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make(alibabaQwenFixture.providerID), modelID: resolved.id }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make(alibabaQwenFixture.providerID), modelID: resolved.id }, + } satisfies SessionLegacy.User const fiber = yield* drain({ user, @@ -854,8 +856,8 @@ describe("session.llm.stream", () => { ) const resolved = yield* Provider.use.getModel( - ProviderID.make(alibabaQwenFixture.providerID), - ModelID.make(fixture.model.id), + ProviderV2.ID.make(alibabaQwenFixture.providerID), + ProviderV2.ModelID.make(fixture.model.id), ) const sessionID = SessionID.make("session-test-tools") const agent = { @@ -871,9 +873,9 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make(alibabaQwenFixture.providerID), modelID: resolved.id }, + model: { providerID: ProviderV2.ID.make(alibabaQwenFixture.providerID), modelID: resolved.id }, tools: { question: true }, - } satisfies MessageV2.User + } satisfies SessionLegacy.User yield* drain({ user, @@ -958,7 +960,7 @@ describe("session.llm.stream", () => { ] const request = waitRequest("/responses", createEventResponse(responseChunks, true)) - const resolved = yield* Provider.use.getModel(ProviderID.openai, ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel(ProviderV2.ID.openai, ProviderV2.ModelID.make(model.id)) const sessionID = SessionID.make("session-test-2") const agent = { name: "test", @@ -974,8 +976,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("openai"), modelID: resolved.id, variant: "high" }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make("openai"), modelID: resolved.id, variant: "high" }, + } satisfies SessionLegacy.User yield* drain({ user, @@ -1063,7 +1065,7 @@ describe("session.llm.stream", () => { }), ) - const resolved = yield* Provider.use.getModel(ProviderID.openai, ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel(ProviderV2.ID.openai, ProviderV2.ModelID.make(model.id)) const sessionID = SessionID.make("session-test-native-flag-off") const agent = { name: "test", @@ -1088,8 +1090,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("openai"), modelID: resolved.id, variant: "high" }, - } satisfies MessageV2.User, + model: { providerID: ProviderV2.ID.make("openai"), modelID: resolved.id, variant: "high" }, + } satisfies SessionLegacy.User, sessionID, model: resolved, agent, @@ -1133,7 +1135,7 @@ describe("session.llm.stream", () => { ] const request = waitRequest("/responses", createEventResponse(chunks, true)) - const resolved = yield* Provider.use.getModel(ProviderID.openai, ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel(ProviderV2.ID.openai, ProviderV2.ModelID.make(model.id)) const sessionID = SessionID.make("session-test-native") const agent = { name: "test", @@ -1150,8 +1152,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("openai"), modelID: resolved.id, variant: "high" }, - } satisfies MessageV2.User, + model: { providerID: ProviderV2.ID.make("openai"), modelID: resolved.id, variant: "high" }, + } satisfies SessionLegacy.User, sessionID, model: resolved, agent, @@ -1217,7 +1219,7 @@ describe("session.llm.stream", () => { }), ) - const resolved = yield* Provider.use.getModel(ProviderID.openai, ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel(ProviderV2.ID.openai, ProviderV2.ModelID.make(model.id)) const sessionID = SessionID.make("session-test-native-injected-tool") const agent = { name: "test", @@ -1233,8 +1235,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("openai"), modelID: resolved.id }, - } satisfies MessageV2.User, + model: { providerID: ProviderV2.ID.make("openai"), modelID: resolved.id }, + } satisfies SessionLegacy.User, sessionID, model: resolved, agent, @@ -1305,7 +1307,7 @@ describe("session.llm.stream", () => { const request = waitRequest("/responses", createEventResponse(chunks, true)) let executed: unknown - const resolved = yield* Provider.use.getModel(ProviderID.openai, ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel(ProviderV2.ID.openai, ProviderV2.ModelID.make(model.id)) const sessionID = SessionID.make("session-test-native-tool") const agent = { name: "test", @@ -1321,8 +1323,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("openai"), modelID: resolved.id }, - } satisfies MessageV2.User, + model: { providerID: ProviderV2.ID.make("openai"), modelID: resolved.id }, + } satisfies SessionLegacy.User, sessionID, model: resolved, agent, @@ -1431,7 +1433,7 @@ describe("session.llm.stream", () => { ), ).toString("base64")}` - const resolved = yield* Provider.use.getModel(ProviderID.openai, ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel(ProviderV2.ID.openai, ProviderV2.ModelID.make(model.id)) const sessionID = SessionID.make("session-test-data-url") const agent = { name: "test", @@ -1446,8 +1448,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("openai"), modelID: resolved.id }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make("openai"), modelID: resolved.id }, + } satisfies SessionLegacy.User yield* drain({ user, @@ -1519,8 +1521,8 @@ describe("session.llm.stream", () => { const request = waitRequest("/messages", createEventResponse(chunks)) const resolved = yield* Provider.use.getModel( - ProviderID.make(minimaxFixture.providerID), - ModelID.make(model.id), + ProviderV2.ID.make(minimaxFixture.providerID), + ProviderV2.ModelID.make(model.id), ) const sessionID = SessionID.make("session-test-3") const agent = { @@ -1538,8 +1540,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("minimax"), modelID: ModelID.make("MiniMax-M2.5") }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make("minimax"), modelID: ProviderV2.ModelID.make("MiniMax-M2.5") }, + } satisfies SessionLegacy.User yield* drain({ user, @@ -1615,7 +1617,10 @@ describe("session.llm.stream", () => { ] const request = waitRequest("/messages", createEventResponse(chunks)) - const resolved = yield* Provider.use.getModel(ProviderID.make("anthropic"), ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel( + ProviderV2.ID.make("anthropic"), + ProviderV2.ModelID.make(model.id), + ) const sessionID = SessionID.make("session-test-anthropic-tools") const agent = { name: "test", @@ -1629,8 +1634,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make("anthropic"), modelID: resolved.id, variant: "max" }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make("anthropic"), modelID: resolved.id, variant: "max" }, + } satisfies SessionLegacy.User const input = [ { @@ -1814,7 +1819,10 @@ describe("session.llm.stream", () => { ] const request = waitRequest(pathSuffix, createEventResponse(chunks)) - const resolved = yield* Provider.use.getModel(ProviderID.make(geminiFixture.providerID), ModelID.make(model.id)) + const resolved = yield* Provider.use.getModel( + ProviderV2.ID.make(geminiFixture.providerID), + ProviderV2.ModelID.make(model.id), + ) const sessionID = SessionID.make("session-test-4") const agent = { name: "test", @@ -1831,8 +1839,8 @@ describe("session.llm.stream", () => { role: "user", time: { created: Date.now() }, agent: agent.name, - model: { providerID: ProviderID.make(geminiFixture.providerID), modelID: resolved.id }, - } satisfies MessageV2.User + model: { providerID: ProviderV2.ID.make(geminiFixture.providerID), modelID: resolved.id }, + } satisfies SessionLegacy.User yield* drain({ user, diff --git a/packages/opencode/test/session/message-v2.test.ts b/packages/opencode/test/session/message-v2.test.ts index 82bed0e9cc6f..75850e59fb69 100644 --- a/packages/opencode/test/session/message-v2.test.ts +++ b/packages/opencode/test/session/message-v2.test.ts @@ -1,16 +1,18 @@ import { describe, expect, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { APICallError } from "ai" import { MessageV2 } from "../../src/session/message-v2" import { ProviderTransform } from "@/provider/transform" import type { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { SessionID, MessageID, PartID } from "../../src/session/schema" import { Question } from "../../src/question" +import { ProviderV2 } from "@opencode-ai/core/provider" const sessionID = SessionID.make("session") -const providerID = ProviderID.make("test") +const providerID = ProviderV2.ID.make("test") const model: Provider.Model = { - id: ModelID.make("test-model"), + id: ProviderV2.ModelID.make("test-model"), providerID, api: { id: "test-model", @@ -58,25 +60,25 @@ const model: Provider.Model = { release_date: "2026-01-01", } -function userInfo(id: string): MessageV2.User { +function userInfo(id: string): SessionLegacy.User { return { id, sessionID, role: "user", time: { created: 0 }, agent: "user", - model: { providerID, modelID: ModelID.make("test") }, + model: { providerID, modelID: ProviderV2.ModelID.make("test") }, tools: {}, mode: "", - } as unknown as MessageV2.User + } as unknown as SessionLegacy.User } function assistantInfo( id: string, parentID: string, - error?: MessageV2.Assistant["error"], + error?: SessionLegacy.Assistant["error"], meta?: { providerID: string; modelID: string }, -): MessageV2.Assistant { +): SessionLegacy.Assistant { const infoModel = meta ?? { providerID: model.providerID, modelID: model.api.id } return { id, @@ -97,7 +99,7 @@ function assistantInfo( reasoning: 0, cache: { read: 0, write: 0 }, }, - } as unknown as MessageV2.Assistant + } as unknown as SessionLegacy.Assistant } function basePart(messageID: string, id: string) { @@ -110,7 +112,7 @@ function basePart(messageID: string, id: string) { describe("session.message-v2.toModelMessage", () => { test("filters out messages with no parts", async () => { - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo("m-empty"), parts: [], @@ -123,7 +125,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "hello", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -138,7 +140,7 @@ describe("session.message-v2.toModelMessage", () => { test("filters out messages with only ignored parts", async () => { const messageID = "m-user" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(messageID), parts: [ @@ -148,7 +150,7 @@ describe("session.message-v2.toModelMessage", () => { text: "ignored", ignored: true, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -158,7 +160,7 @@ describe("session.message-v2.toModelMessage", () => { test("filters out user messages with only empty text parts", async () => { const messageID = "m-user" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(messageID), parts: [ @@ -167,7 +169,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -177,7 +179,7 @@ describe("session.message-v2.toModelMessage", () => { test("filters empty user text parts while keeping non-empty parts", async () => { const messageID = "m-user" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(messageID), parts: [ @@ -191,7 +193,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "hello", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -206,7 +208,7 @@ describe("session.message-v2.toModelMessage", () => { test("includes synthetic text parts", async () => { const messageID = "m-user" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(messageID), parts: [ @@ -216,7 +218,7 @@ describe("session.message-v2.toModelMessage", () => { text: "hello", synthetic: true, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo("m-assistant", messageID), @@ -227,7 +229,7 @@ describe("session.message-v2.toModelMessage", () => { text: "assistant", synthetic: true, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -246,7 +248,7 @@ describe("session.message-v2.toModelMessage", () => { test("converts user text/file parts and injects compaction/subtask prompts", async () => { const messageID = "m-user" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(messageID), parts: [ @@ -294,7 +296,7 @@ describe("session.message-v2.toModelMessage", () => { description: "desc", agent: "agent", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -320,7 +322,7 @@ describe("session.message-v2.toModelMessage", () => { const userID = "m-user" const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -329,7 +331,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -364,7 +366,7 @@ describe("session.message-v2.toModelMessage", () => { }, metadata: { openai: { tool: "meta" } }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -411,8 +413,8 @@ describe("session.message-v2.toModelMessage", () => { test("preserves jpeg tool-result media for anthropic models", async () => { const anthropicModel: Provider.Model = { ...model, - id: ModelID.make("anthropic/claude-opus-4-7"), - providerID: ProviderID.make("anthropic"), + id: ProviderV2.ModelID.make("anthropic/claude-opus-4-7"), + providerID: ProviderV2.ID.make("anthropic"), api: { id: "claude-opus-4-7-20250805", url: "https://api.anthropic.com", @@ -433,7 +435,7 @@ describe("session.message-v2.toModelMessage", () => { ) const userID = "m-user-anthropic" const assistantID = "m-assistant-anthropic" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -442,7 +444,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -470,7 +472,7 @@ describe("session.message-v2.toModelMessage", () => { ], }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -494,8 +496,8 @@ describe("session.message-v2.toModelMessage", () => { test("moves bedrock pdf tool-result media into a separate user message", async () => { const bedrockModel: Provider.Model = { ...model, - id: ModelID.make("amazon-bedrock/anthropic.claude-sonnet-4-6"), - providerID: ProviderID.make("amazon-bedrock"), + id: ProviderV2.ModelID.make("amazon-bedrock/anthropic.claude-sonnet-4-6"), + providerID: ProviderV2.ID.make("amazon-bedrock"), api: { id: "anthropic.claude-sonnet-4-6", url: "https://bedrock-runtime.us-east-1.amazonaws.com", @@ -514,7 +516,7 @@ describe("session.message-v2.toModelMessage", () => { const pdf = Buffer.from("%PDF-1.4\n").toString("base64") const userID = "m-user-bedrock-pdf" const assistantID = "m-assistant-bedrock-pdf" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -523,7 +525,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -551,7 +553,7 @@ describe("session.message-v2.toModelMessage", () => { ], }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -602,7 +604,7 @@ describe("session.message-v2.toModelMessage", () => { const userID = "m-user" const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -611,7 +613,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID, undefined, { providerID: "other", modelID: "other" }), @@ -644,7 +646,7 @@ describe("session.message-v2.toModelMessage", () => { }, metadata: { openai: { tool: "meta" } }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -685,7 +687,7 @@ describe("session.message-v2.toModelMessage", () => { const userID = "m-user" const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -694,7 +696,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -713,7 +715,7 @@ describe("session.message-v2.toModelMessage", () => { time: { start: 0, end: 1, compacted: 1 }, }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -752,7 +754,7 @@ describe("session.message-v2.toModelMessage", () => { const userID = "m-user" const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -761,7 +763,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -780,7 +782,7 @@ describe("session.message-v2.toModelMessage", () => { time: { start: 0, end: 1 }, }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -822,7 +824,7 @@ describe("session.message-v2.toModelMessage", () => { const userID = "m-user" const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -831,7 +833,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -850,7 +852,7 @@ describe("session.message-v2.toModelMessage", () => { }, metadata: { openai: { tool: "meta" } }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -900,7 +902,7 @@ describe("session.message-v2.toModelMessage", () => { "", ].join("\n") - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -909,7 +911,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -927,7 +929,7 @@ describe("session.message-v2.toModelMessage", () => { time: { start: 0, end: 1 }, }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -965,12 +967,12 @@ describe("session.message-v2.toModelMessage", () => { test("filters assistant messages with non-abort errors", async () => { const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo( assistantID, "m-parent", - new MessageV2.APIError({ message: "boom", isRetryable: true }).toObject() as MessageV2.APIError, + new SessionLegacy.APIError({ message: "boom", isRetryable: true }).toObject() as SessionLegacy.APIError, ), parts: [ { @@ -978,7 +980,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "should not render", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -989,9 +991,11 @@ describe("session.message-v2.toModelMessage", () => { const assistantID1 = "m-assistant-1" const assistantID2 = "m-assistant-2" - const aborted = new MessageV2.AbortedError({ message: "aborted" }).toObject() as MessageV2.Assistant["error"] + const aborted = new SessionLegacy.AbortedError({ + message: "aborted", + }).toObject() as SessionLegacy.Assistant["error"] - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID1, "m-parent", aborted), parts: [ @@ -1006,7 +1010,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "partial answer", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID2, "m-parent", aborted), @@ -1021,7 +1025,7 @@ describe("session.message-v2.toModelMessage", () => { text: "thinking", time: { start: 0 }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1040,8 +1044,8 @@ describe("session.message-v2.toModelMessage", () => { const assistantID = "m-assistant" const openrouterModel: Provider.Model = { ...model, - id: ModelID.make("deepseek/deepseek-v4-pro"), - providerID: ProviderID.make("openrouter"), + id: ProviderV2.ModelID.make("deepseek/deepseek-v4-pro"), + providerID: ProviderV2.ID.make("openrouter"), api: { id: "deepseek/deepseek-v4-pro", url: "https://openrouter.ai/api/v1", @@ -1061,7 +1065,7 @@ describe("session.message-v2.toModelMessage", () => { index: 0, }, ] - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent", undefined, { providerID: openrouterModel.providerID, @@ -1084,7 +1088,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "answer", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1112,7 +1116,7 @@ describe("session.message-v2.toModelMessage", () => { test("splits assistant messages on step-start boundaries", async () => { const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent"), parts: [ @@ -1130,7 +1134,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "second", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1149,7 +1153,7 @@ describe("session.message-v2.toModelMessage", () => { test("drops messages that only contain step-start parts", async () => { const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent"), parts: [ @@ -1157,7 +1161,7 @@ describe("session.message-v2.toModelMessage", () => { ...basePart(assistantID, "p1"), type: "step-start", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1168,7 +1172,7 @@ describe("session.message-v2.toModelMessage", () => { const userID = "m-user" const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: userInfo(userID), parts: [ @@ -1177,7 +1181,7 @@ describe("session.message-v2.toModelMessage", () => { type: "text", text: "run tool", }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, { info: assistantInfo(assistantID, userID), @@ -1204,7 +1208,7 @@ describe("session.message-v2.toModelMessage", () => { time: { start: 0 }, }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1257,7 +1261,7 @@ describe("session.message-v2.toModelMessage", () => { test("substitutes space for empty text between signed reasoning blocks", async () => { // Reproduces the bug pattern: [reasoning(sig), text(""), reasoning(sig), text(full)] const assistantID = "m-assistant" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent"), parts: [ @@ -1277,7 +1281,7 @@ describe("session.message-v2.toModelMessage", () => { metadata: { anthropic: { signature: "sig2" } }, }, { ...basePart(assistantID, "p6"), type: "text", text: "the answer" }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1293,7 +1297,7 @@ describe("session.message-v2.toModelMessage", () => { // Bedrock signed reasoning is preserved as reasoning metadata, but unlike the // direct Anthropic path we do not preserve empty text separators for Bedrock. const assistantID = "m-assistant-bedrock" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent"), parts: [ @@ -1305,7 +1309,7 @@ describe("session.message-v2.toModelMessage", () => { }, { ...basePart(assistantID, "p2"), type: "text", text: "" }, { ...basePart(assistantID, "p3"), type: "text", text: "answer" }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1320,14 +1324,14 @@ describe("session.message-v2.toModelMessage", () => { // Non-Anthropic providers' reasoning doesn't position-validate, so empty text // should be filtered normally rather than substituted. const assistantID = "m-assistant-unsigned" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent"), parts: [ { ...basePart(assistantID, "p1"), type: "reasoning", text: "thinking" }, { ...basePart(assistantID, "p2"), type: "text", text: "" }, { ...basePart(assistantID, "p3"), type: "text", text: "answer" }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1340,13 +1344,13 @@ describe("session.message-v2.toModelMessage", () => { test("leaves empty text alone in assistant messages without reasoning", async () => { const assistantID = "m-assistant-no-reasoning" - const input: MessageV2.WithParts[] = [ + const input: SessionLegacy.WithParts[] = [ { info: assistantInfo(assistantID, "m-parent"), parts: [ { ...basePart(assistantID, "p1"), type: "text", text: "" }, { ...basePart(assistantID, "p2"), type: "text", text: "hello" }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], }, ] @@ -1458,7 +1462,7 @@ describe("session.message-v2.fromError", () => { isRetryable: false, }) const result = MessageV2.fromError(error, { providerID }) - expect(MessageV2.ContextOverflowError.isInstance(result)).toBe(true) + expect(SessionLegacy.ContextOverflowError.isInstance(result)).toBe(true) }) }) @@ -1479,7 +1483,7 @@ describe("session.message-v2.fromError", () => { isRetryable: false, }) const result = MessageV2.fromError(error, { providerID }) - expect(MessageV2.ContextOverflowError.isInstance(result)).toBe(true) + expect(SessionLegacy.ContextOverflowError.isInstance(result)).toBe(true) }) test("does not classify 429 no body as context overflow", () => { @@ -1494,8 +1498,8 @@ describe("session.message-v2.fromError", () => { }), { providerID }, ) - expect(MessageV2.ContextOverflowError.isInstance(result)).toBe(false) - expect(MessageV2.APIError.isInstance(result)).toBe(true) + expect(SessionLegacy.ContextOverflowError.isInstance(result)).toBe(false) + expect(SessionLegacy.APIError.isInstance(result)).toBe(true) }) test("serializes unknown inputs", () => { @@ -1530,9 +1534,9 @@ describe("session.message-v2.fromError", () => { const result = MessageV2.fromError(zlibError, { providerID }) - expect(MessageV2.APIError.isInstance(result)).toBe(true) - expect((result as MessageV2.APIError).data.isRetryable).toBe(true) - expect((result as MessageV2.APIError).data.message).toInclude("decompression") + expect(SessionLegacy.APIError.isInstance(result)).toBe(true) + expect((result as SessionLegacy.APIError).data.isRetryable).toBe(true) + expect((result as SessionLegacy.APIError).data.message).toInclude("decompression") }) test("classifies ZlibError as AbortedError when abort context is provided", () => { @@ -1556,21 +1560,21 @@ describe("session.message-v2.latest", () => { const CONTINUE_USER = MessageID.make("msg_005") const NEW_COMPACTION_USER = MessageID.make("msg_006") - const tailUser: MessageV2.WithParts = { + const tailUser: SessionLegacy.WithParts = { info: userInfo(TAIL_USER), - parts: [{ ...basePart(TAIL_USER, "p1"), type: "text", text: "original prompt" }] as MessageV2.Part[], + parts: [{ ...basePart(TAIL_USER, "p1"), type: "text", text: "original prompt" }] as SessionLegacy.Part[], } - const overflowAssistant: MessageV2.WithParts = { + const overflowAssistant: SessionLegacy.WithParts = { info: { ...assistantInfo(OVERFLOW_ASSISTANT, TAIL_USER), finish: "tool-calls", tokens: { input: 280_000, output: 200, reasoning: 0, cache: { read: 0, write: 0 }, total: 280_200 }, - } as MessageV2.Assistant, + } as SessionLegacy.Assistant, parts: [], } - const compactionUser: MessageV2.WithParts = { + const compactionUser: SessionLegacy.WithParts = { info: userInfo(COMPACTION_USER), parts: [ { @@ -1579,20 +1583,20 @@ describe("session.message-v2.latest", () => { auto: true, tail_start_id: TAIL_USER, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], } - const summaryAssistant: MessageV2.WithParts = { + const summaryAssistant: SessionLegacy.WithParts = { info: { ...assistantInfo(SUMMARY_ASSISTANT, COMPACTION_USER), summary: true, finish: "stop", tokens: { input: 150_000, output: 1_500, reasoning: 0, cache: { read: 0, write: 0 }, total: 151_500 }, - } as MessageV2.Assistant, + } as SessionLegacy.Assistant, parts: [], } - const continueUser: MessageV2.WithParts = { + const continueUser: SessionLegacy.WithParts = { info: userInfo(CONTINUE_USER), parts: [ { @@ -1602,7 +1606,7 @@ describe("session.message-v2.latest", () => { synthetic: true, metadata: { compaction_continue: true }, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], } // Regression for double auto-compaction. The reorder in filterCompacted @@ -1628,7 +1632,7 @@ describe("session.message-v2.latest", () => { }) test("a fresh compaction-user newer than the latest summary surfaces in tasks", () => { - const newCompactionUser: MessageV2.WithParts = { + const newCompactionUser: SessionLegacy.WithParts = { info: userInfo(NEW_COMPACTION_USER), parts: [ { @@ -1636,7 +1640,7 @@ describe("session.message-v2.latest", () => { type: "compaction", auto: true, }, - ] as MessageV2.Part[], + ] as SessionLegacy.Part[], } const state = MessageV2.latest([ diff --git a/packages/opencode/test/session/messages-pagination.test.ts b/packages/opencode/test/session/messages-pagination.test.ts index e558d07b500f..5da80ea3e4b6 100644 --- a/packages/opencode/test/session/messages-pagination.test.ts +++ b/packages/opencode/test/session/messages-pagination.test.ts @@ -1,16 +1,19 @@ import { describe, expect, test } from "bun:test" -import { Effect, Option } from "effect" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Database } from "@opencode-ai/core/database/database" +import { Effect, Layer, Option } from "effect" import { Session as SessionNs } from "@/session/session" import { MessageV2 } from "../../src/session/message-v2" import { MessageID, PartID, type SessionID } from "../../src/session/schema" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { NotFoundError } from "@/storage/storage" import * as Log from "@opencode-ai/core/util/log" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" void Log.init({ print: false }) -const it = testEffect(SessionNs.defaultLayer) +const it = testEffect(Layer.mergeAll(SessionNs.defaultLayer, Database.defaultLayer)) const withSession = ( fn: (input: { session: SessionNs.Interface; sessionID: SessionID }) => Effect.Effect, @@ -45,7 +48,7 @@ const fill = Effect.fn("Test.fill")(function* ( model: { providerID: "test", modelID: "test" }, tools: {}, mode: "", - } as unknown as MessageV2.Info) + } as unknown as SessionLegacy.Info) yield* session.updatePart({ id: PartID.ascending(), sessionID, @@ -69,7 +72,7 @@ const addUser = Effect.fn("Test.addUser")(function* (sessionID: SessionID, text? model: { providerID: "test", modelID: "test" }, tools: {}, mode: "", - } as unknown as MessageV2.Info) + } as unknown as SessionLegacy.Info) if (text) { yield* session.updatePart({ id: PartID.ascending(), @@ -85,7 +88,7 @@ const addUser = Effect.fn("Test.addUser")(function* (sessionID: SessionID, text? const addAssistant = Effect.fn("Test.addAssistant")(function* ( sessionID: SessionID, parentID: MessageID, - opts?: { summary?: boolean; finish?: string; error?: MessageV2.Assistant["error"] }, + opts?: { summary?: boolean; finish?: string; error?: SessionLegacy.Assistant["error"] }, ) { const session = yield* SessionNs.Service const id = MessageID.ascending() @@ -95,8 +98,8 @@ const addAssistant = Effect.fn("Test.addAssistant")(function* ( role: "assistant", time: { created: Date.now() }, parentID, - modelID: ModelID.make("test"), - providerID: ProviderID.make("test"), + modelID: ProviderV2.ModelID.make("test"), + providerID: ProviderV2.ID.make("test"), mode: "", agent: "default", path: { cwd: "/", root: "/" }, @@ -105,7 +108,7 @@ const addAssistant = Effect.fn("Test.addAssistant")(function* ( summary: opts?.summary, finish: opts?.finish, error: opts?.error, - } as unknown as MessageV2.Info) + } as unknown as SessionLegacy.Info) return id }) @@ -310,7 +313,7 @@ describe("MessageV2.stream", () => { Effect.gen(function* () { const ids = yield* fill(sessionID, 5) - const items = Array.from(MessageV2.stream(sessionID)) + const items = yield* MessageV2.stream(sessionID) expect(items.map((item) => item.info.id)).toEqual(ids.slice().reverse()) }), ), @@ -319,7 +322,7 @@ describe("MessageV2.stream", () => { it.instance("yields nothing for empty session", () => withSession(({ sessionID }) => Effect.gen(function* () { - const items = Array.from(MessageV2.stream(sessionID)) + const items = yield* MessageV2.stream(sessionID) expect(items).toHaveLength(0) }), ), @@ -330,7 +333,7 @@ describe("MessageV2.stream", () => { Effect.gen(function* () { const ids = yield* fill(sessionID, 1) - const items = Array.from(MessageV2.stream(sessionID)) + const items = yield* MessageV2.stream(sessionID) expect(items).toHaveLength(1) expect(items[0].info.id).toBe(ids[0]) }), @@ -342,7 +345,7 @@ describe("MessageV2.stream", () => { Effect.gen(function* () { yield* fill(sessionID, 3) - const items = Array.from(MessageV2.stream(sessionID)) + const items = yield* MessageV2.stream(sessionID) for (const item of items) { expect(item.parts).toHaveLength(1) expect(item.parts[0].type).toBe("text") @@ -356,7 +359,7 @@ describe("MessageV2.stream", () => { Effect.gen(function* () { const ids = yield* fill(sessionID, 60) - const items = Array.from(MessageV2.stream(sessionID)) + const items = yield* MessageV2.stream(sessionID) expect(items).toHaveLength(60) expect(items[0].info.id).toBe(ids[ids.length - 1]) expect(items[59].info.id).toBe(ids[0]) @@ -364,17 +367,13 @@ describe("MessageV2.stream", () => { ), ) - it.instance("is a sync generator", () => + it.instance("returns an Effect", () => withSession(({ sessionID }) => Effect.gen(function* () { yield* fill(sessionID, 1) - const gen = MessageV2.stream(sessionID) - const first = gen.next() - // sync generator returns { value, done } directly, not a Promise - expect(first).toHaveProperty("value") - expect(first).toHaveProperty("done") - expect(first.done).toBe(false) + const result = yield* MessageV2.stream(sessionID) + expect(result).toHaveLength(1) }), ), ) @@ -386,10 +385,10 @@ describe("MessageV2.parts", () => { Effect.gen(function* () { const [id] = yield* fill(sessionID, 1) - const result = MessageV2.parts(id) + const result = yield* MessageV2.parts(id) expect(result).toHaveLength(1) expect(result[0].type).toBe("text") - expect((result[0] as MessageV2.TextPart).text).toBe("m0") + expect((result[0] as SessionLegacy.TextPart).text).toBe("m0") }), ), ) @@ -399,7 +398,7 @@ describe("MessageV2.parts", () => { Effect.gen(function* () { const id = yield* addUser(sessionID) - const result = MessageV2.parts(id) + const result = yield* MessageV2.parts(id) expect(result).toEqual([]) }), ), @@ -425,11 +424,11 @@ describe("MessageV2.parts", () => { text: "third", }) - const result = MessageV2.parts(id) + const result = yield* MessageV2.parts(id) expect(result).toHaveLength(3) - expect((result[0] as MessageV2.TextPart).text).toBe("m0") - expect((result[1] as MessageV2.TextPart).text).toBe("second") - expect((result[2] as MessageV2.TextPart).text).toBe("third") + expect((result[0] as SessionLegacy.TextPart).text).toBe("m0") + expect((result[1] as SessionLegacy.TextPart).text).toBe("second") + expect((result[2] as SessionLegacy.TextPart).text).toBe("third") }), ), ) @@ -437,7 +436,7 @@ describe("MessageV2.parts", () => { it.instance("returns empty for non-existent message id", () => Effect.gen(function* () { yield* SessionNs.Service - const result = MessageV2.parts(MessageID.ascending()) + const result = yield* MessageV2.parts(MessageID.ascending()) expect(result).toEqual([]) }), ) @@ -447,7 +446,7 @@ describe("MessageV2.parts", () => { Effect.gen(function* () { const [id] = yield* fill(sessionID, 1) - const result = MessageV2.parts(id) + const result = yield* MessageV2.parts(id) expect(result[0].sessionID).toBe(sessionID) expect(result[0].messageID).toBe(id) }), @@ -466,7 +465,7 @@ describe("MessageV2.get", () => { expect(result.info.sessionID).toBe(sessionID) expect(result.info.role).toBe("user") expect(result.parts).toHaveLength(1) - expect((result.parts[0] as MessageV2.TextPart).text).toBe("m0") + expect((result.parts[0] as SessionLegacy.TextPart).text).toBe("m0") }), ), ) @@ -536,7 +535,7 @@ describe("MessageV2.get", () => { const result = yield* MessageV2.get({ sessionID, messageID: aid }) expect(result.info.role).toBe("assistant") expect(result.parts).toHaveLength(1) - expect((result.parts[0] as MessageV2.TextPart).text).toBe("response") + expect((result.parts[0] as SessionLegacy.TextPart).text).toBe("response") }), ), ) @@ -604,7 +603,7 @@ describe("MessageV2.filterCompacted", () => { Effect.gen(function* () { const ids = yield* fill(sessionID, 5) - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) expect(result).toHaveLength(5) // reversed from newest-first to chronological expect(result.map((item) => item.info.id)).toEqual(ids) @@ -638,7 +637,7 @@ describe("MessageV2.filterCompacted", () => { text: "new response", }) - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) // Includes compaction boundary: u1, a1, u2, a2 expect(result[0].info.id).toBe(u1) expect(result.length).toBe(4) @@ -660,7 +659,7 @@ describe("MessageV2.filterCompacted", () => { yield* addCompactionPart(sessionID, u1) yield* addUser(sessionID, "world") - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) expect(result).toHaveLength(2) }), ), @@ -672,14 +671,14 @@ describe("MessageV2.filterCompacted", () => { const u1 = yield* addUser(sessionID, "hello") yield* addCompactionPart(sessionID, u1) - const error = new MessageV2.APIError({ + const error = new SessionLegacy.APIError({ message: "boom", isRetryable: true, - }).toObject() as MessageV2.Assistant["error"] + }).toObject() as SessionLegacy.Assistant["error"] yield* addAssistant(sessionID, u1, { summary: true, finish: "end_turn", error }) yield* addUser(sessionID, "retry") - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) // Error assistant doesn't add to completed, so compaction boundary never triggers expect(result).toHaveLength(3) }), @@ -696,7 +695,7 @@ describe("MessageV2.filterCompacted", () => { yield* addAssistant(sessionID, u1, { summary: true }) yield* addUser(sessionID, "next") - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) expect(result).toHaveLength(3) }), ), @@ -746,7 +745,7 @@ describe("MessageV2.filterCompacted", () => { text: "third reply", }) - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) expect(result.map((item) => item.info.id)).toEqual([c1, s1, u2, a2, u3, a3]) }), @@ -799,11 +798,11 @@ describe("MessageV2.filterCompacted", () => { text: "third reply", }) - const parentFiltered = MessageV2.filterCompacted(MessageV2.stream(created.id)) + const parentFiltered = MessageV2.filterCompacted(yield* MessageV2.stream(created.id)) expect(parentFiltered.map((item) => item.info.id)).toEqual([c1, s1, u2, a2, u3, a3]) const forked = yield* session.fork({ sessionID: created.id }) - const childFiltered = MessageV2.filterCompacted(MessageV2.stream(forked.id)) + const childFiltered = MessageV2.filterCompacted(yield* MessageV2.stream(forked.id)) expect(childFiltered).toHaveLength(parentFiltered.length) const tailPart = childFiltered.flatMap((m) => m.parts).find((p) => p.type === "compaction") @@ -869,7 +868,7 @@ describe("MessageV2.filterCompacted", () => { text: "third reply", }) - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) expect(result.map((item) => item.info.id)).toEqual([c1, s1, a3, u3, a4]) }), @@ -941,7 +940,7 @@ describe("MessageV2.filterCompacted", () => { text: "fourth reply", }) - const result = MessageV2.filterCompacted(MessageV2.stream(sessionID)) + const result = MessageV2.filterCompacted(yield* MessageV2.stream(sessionID)) expect(result.map((item) => item.info.id)).toEqual([c2, s2, u3, a3, u4, a4]) }), @@ -951,7 +950,7 @@ describe("MessageV2.filterCompacted", () => { test("works with array input", () => { // filterCompacted accepts any Iterable, not just generators const id = MessageID.ascending() - const items: MessageV2.WithParts[] = [ + const items: SessionLegacy.WithParts[] = [ { info: { id, @@ -960,8 +959,8 @@ describe("MessageV2.filterCompacted", () => { time: { created: 1 }, agent: "test", model: { providerID: "test", modelID: "test" }, - } as unknown as MessageV2.Info, - parts: [{ type: "text", text: "hello" }] as unknown as MessageV2.Part[], + } as unknown as SessionLegacy.Info, + parts: [{ type: "text", text: "hello" }] as unknown as SessionLegacy.Part[], }, ] const result = MessageV2.filterCompacted(items) @@ -1014,7 +1013,7 @@ describe("MessageV2 consistency", () => { const [id] = yield* fill(sessionID, 1) const got = yield* MessageV2.get({ sessionID, messageID: id }) - const standalone = MessageV2.parts(id) + const standalone = yield* MessageV2.parts(id) expect(got.parts).toEqual(standalone) }), ), @@ -1025,9 +1024,9 @@ describe("MessageV2 consistency", () => { Effect.gen(function* () { yield* fill(sessionID, 7) - const streamed = Array.from(MessageV2.stream(sessionID)) + const streamed = yield* MessageV2.stream(sessionID) - const paged = [] as MessageV2.WithParts[] + const paged = [] as SessionLegacy.WithParts[] let cursor: string | undefined while (true) { const result = yield* MessageV2.page({ sessionID, limit: 3, before: cursor }) @@ -1048,8 +1047,9 @@ describe("MessageV2 consistency", () => { Effect.gen(function* () { yield* fill(sessionID, 4) - const filtered = MessageV2.filterCompacted(MessageV2.stream(sessionID)) - const all = Array.from(MessageV2.stream(sessionID)).reverse() + const stream = yield* MessageV2.stream(sessionID) + const filtered = MessageV2.filterCompacted(stream) + const all = stream.toReversed() expect(filtered.map((m) => m.info.id)).toEqual(all.map((m) => m.info.id)) }), diff --git a/packages/opencode/test/session/processor-effect.test.ts b/packages/opencode/test/session/processor-effect.test.ts index ede122297a17..e68ad962febd 100644 --- a/packages/opencode/test/session/processor-effect.test.ts +++ b/packages/opencode/test/session/processor-effect.test.ts @@ -1,4 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Database } from "@opencode-ai/core/database/database" +import { EventV2Bridge } from "@/event-v2-bridge" import { expect } from "bun:test" import { tool } from "ai" import { Cause, Effect, Exit, Fiber, Layer } from "effect" @@ -6,13 +9,12 @@ import path from "path" import z from "zod" import type { Agent } from "../../src/agent/agent" import { Agent as AgentSvc } from "../../src/agent/agent" -import { Bus } from "../../src/bus" import { Config } from "@/config/config" import { Image } from "@/image/image" import { Permission } from "../../src/permission" import { Plugin } from "../../src/plugin" import { Provider } from "@/provider/provider" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { Session } from "@/session/session" import { LLM } from "../../src/session/llm" import { MessageV2 } from "../../src/session/message-v2" @@ -26,9 +28,8 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { provideTmpdirServer } from "../fixture/fixture" import { testEffect } from "../lib/effect" import { raw, reply, TestLLMServer } from "../lib/llm-server" -import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" -import { EventV2Bridge } from "@/event-v2-bridge" +import { ProviderV2 } from "@opencode-ai/core/provider" void Log.init({ print: false }) @@ -42,8 +43,8 @@ const summary = Layer.succeed( ) const ref = { - providerID: ProviderID.make("test"), - modelID: ModelID.make("test-model"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("test-model"), } const cfg = { @@ -145,7 +146,7 @@ const assistant = Effect.fn("TestSession.assistant")(function* ( root: string, ) { const session = yield* Session.Service - const msg: MessageV2.Assistant = { + const msg: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", sessionID, @@ -170,7 +171,7 @@ const assistant = Effect.fn("TestSession.assistant")(function* ( return msg }) -const status = SessionStatus.layer.pipe(Layer.provideMerge(Bus.layer)) +const status = SessionStatus.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer)) const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer) const deps = Layer.mergeAll( Session.defaultLayer, @@ -182,7 +183,7 @@ const deps = Layer.mergeAll( LLM.defaultLayer, Provider.defaultLayer, status, - SyncEvent.defaultLayer, + Database.defaultLayer, EventV2Bridge.defaultLayer, ).pipe(Layer.provideMerge(infra)) const env = Layer.mergeAll( @@ -212,6 +213,7 @@ it.live("session.processor effect tests capture llm input cleanly", () => provideTmpdirServer( ({ dir, llm }) => Effect.gen(function* () { + const database = yield* Database.Service const { processors, session, provider } = yield* boot() yield* llm.text("hello") @@ -234,7 +236,7 @@ it.live("session.processor effect tests capture llm input cleanly", () => time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -244,7 +246,7 @@ it.live("session.processor effect tests capture llm input cleanly", () => } satisfies LLM.StreamInput const value = yield* handle.process(input) - const parts = MessageV2.parts(msg.id) + const parts = yield* MessageV2.parts(msg.id) const calls = yield* llm.calls expect(value).toBe("continue") @@ -259,6 +261,7 @@ it.live("session.processor effect tests preserve text start time", () => provideTmpdirServer( ({ dir, llm }) => Effect.gen(function* () { + const database = yield* Database.Service const gate = defer() const { processors, session, provider } = yield* boot() @@ -306,7 +309,7 @@ it.live("session.processor effect tests preserve text start time", () => time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -317,14 +320,19 @@ it.live("session.processor effect tests preserve text start time", () => .pipe(Effect.forkChild) yield* waitFor( - Effect.sync(() => MessageV2.parts(msg.id).find((part): part is MessageV2.TextPart => part.type === "text")), + MessageV2.parts(msg.id).pipe( + Effect.map((parts) => parts.find((part): part is SessionLegacy.TextPart => part.type === "text")), + Effect.provideService(Database.Service, database), + ), "timed out waiting for text part", ) yield* Effect.sleep("20 millis") gate.resolve() const exit = yield* Fiber.await(run) - const text = MessageV2.parts(msg.id).find((part): part is MessageV2.TextPart => part.type === "text") + const text = (yield* MessageV2.parts(msg.id)).find( + (part): part is SessionLegacy.TextPart => part.type === "text", + ) expect(Exit.isSuccess(exit)).toBe(true) expect(text?.text).toBe("hello") @@ -341,6 +349,7 @@ it.live("session.processor effect tests stop after token overflow requests compa provideTmpdirServer( ({ dir, llm }) => Effect.gen(function* () { + const database = yield* Database.Service const { processors, session, provider } = yield* boot() yield* llm.text("after", { usage: { input: 100, output: 0 } }) @@ -364,7 +373,7 @@ it.live("session.processor effect tests stop after token overflow requests compa time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -373,7 +382,7 @@ it.live("session.processor effect tests stop after token overflow requests compa tools: {}, }) - const parts = MessageV2.parts(msg.id) + const parts = yield* MessageV2.parts(msg.id) expect(value).toBe("compact") expect(parts.some((part) => part.type === "text" && part.text === "after")).toBe(true) @@ -387,6 +396,7 @@ it.live("session.processor effect tests capture reasoning from http mock", () => provideTmpdirServer( ({ dir, llm }) => Effect.gen(function* () { + const database = yield* Database.Service const { processors, session, provider } = yield* boot() yield* llm.push(reply().reason("think").text("done").stop()) @@ -409,7 +419,7 @@ it.live("session.processor effect tests capture reasoning from http mock", () => time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -418,9 +428,9 @@ it.live("session.processor effect tests capture reasoning from http mock", () => tools: {}, }) - const parts = MessageV2.parts(msg.id) - const reasoning = parts.find((part): part is MessageV2.ReasoningPart => part.type === "reasoning") - const text = parts.find((part): part is MessageV2.TextPart => part.type === "text") + const parts = yield* MessageV2.parts(msg.id) + const reasoning = parts.find((part): part is SessionLegacy.ReasoningPart => part.type === "reasoning") + const text = parts.find((part): part is SessionLegacy.TextPart => part.type === "text") expect(value).toBe("continue") expect(yield* llm.calls).toBe(1) @@ -457,7 +467,7 @@ it.live("session.processor effect tests reset reasoning state across retries", ( time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -466,8 +476,8 @@ it.live("session.processor effect tests reset reasoning state across retries", ( tools: {}, }) - const parts = MessageV2.parts(msg.id) - const reasoning = parts.filter((part): part is MessageV2.ReasoningPart => part.type === "reasoning") + const parts = yield* MessageV2.parts(msg.id) + const reasoning = parts.filter((part): part is SessionLegacy.ReasoningPart => part.type === "reasoning") expect(value).toBe("continue") expect(yield* llm.calls).toBe(2) @@ -504,7 +514,7 @@ it.live("session.processor effect tests do not retry unknown json errors", () => time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -548,7 +558,7 @@ it.live("session.processor effect tests retry recognized structured json errors" time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -557,7 +567,7 @@ it.live("session.processor effect tests retry recognized structured json errors" tools: {}, }) - const parts = MessageV2.parts(msg.id) + const parts = yield* MessageV2.parts(msg.id) expect(value).toBe("continue") expect(yield* llm.calls).toBe(2) @@ -573,7 +583,7 @@ it.live("session.processor effect tests publish retry status updates", () => ({ dir, llm }) => Effect.gen(function* () { const { processors, session, provider } = yield* boot() - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service yield* llm.error(503, { error: "boom" }) yield* llm.text("") @@ -583,9 +593,11 @@ it.live("session.processor effect tests publish retry status updates", () => const msg = yield* assistant(chat.id, parent.id, path.resolve(dir)) const mdl = yield* provider.getModel(ref.providerID, ref.modelID) const states: number[] = [] - const off = yield* bus.subscribeCallback(SessionStatus.Event.Status, (evt) => { - if (evt.properties.sessionID !== chat.id) return - if (evt.properties.status.type === "retry") states.push(evt.properties.status.attempt) + const off = yield* events.listen((evt) => { + if (evt.type !== SessionStatus.Event.Status.type) return Effect.void + const data = evt.data as typeof SessionStatus.Event.Status.data.Type + if (data.sessionID === chat.id && data.status.type === "retry") states.push(data.status.attempt) + return Effect.void }) const handle = yield* processors.create({ assistantMessage: msg, @@ -601,7 +613,7 @@ it.live("session.processor effect tests publish retry status updates", () => time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -610,7 +622,7 @@ it.live("session.processor effect tests publish retry status updates", () => tools: {}, }) - off() + yield* off expect(value).toBe("continue") expect(yield* llm.calls).toBe(2) @@ -646,7 +658,7 @@ it.live("session.processor effect tests compact on structured context overflow", time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -689,7 +701,7 @@ it.live("session.processor effect tests complete AI SDK tool calls when native f time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -708,8 +720,8 @@ it.live("session.processor effect tests complete AI SDK tool calls when native f }, }) - const parts = MessageV2.parts(msg.id) - const call = parts.find((part): part is MessageV2.ToolPart => part.type === "tool") + const parts = yield* MessageV2.parts(msg.id) + const call = parts.find((part): part is SessionLegacy.ToolPart => part.type === "tool") expect(value).toBe("continue") expect(yield* llm.calls).toBe(1) @@ -732,6 +744,7 @@ it.live("session.processor effect tests mark pending tools as aborted on cleanup provideTmpdirServer( ({ dir, llm }) => Effect.gen(function* () { + const database = yield* Database.Service const { processors, session, provider } = yield* boot() yield* llm.toolHang("bash", { cmd: "pwd" }) @@ -755,7 +768,7 @@ it.live("session.processor effect tests mark pending tools as aborted on cleanup time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -767,14 +780,17 @@ it.live("session.processor effect tests mark pending tools as aborted on cleanup yield* llm.wait(1) yield* waitFor( - Effect.sync(() => MessageV2.parts(msg.id).find((part): part is MessageV2.ToolPart => part.type === "tool")), + MessageV2.parts(msg.id).pipe( + Effect.map((parts) => parts.find((part): part is SessionLegacy.ToolPart => part.type === "tool")), + Effect.provideService(Database.Service, database), + ), "timed out waiting for tool part", ) yield* Fiber.interrupt(run) const exit = yield* Fiber.await(run) - const parts = MessageV2.parts(msg.id) - const call = parts.find((part): part is MessageV2.ToolPart => part.type === "tool") + const parts = yield* MessageV2.parts(msg.id) + const call = parts.find((part): part is SessionLegacy.ToolPart => part.type === "tool") expect(Exit.isFailure(exit)).toBe(true) if (Exit.isFailure(exit)) { @@ -798,7 +814,7 @@ it.live("session.processor effect tests record aborted errors and idle state", ( Effect.gen(function* () { const seen = defer() const { processors, session, provider } = yield* boot() - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const sts = yield* SessionStatus.Service yield* llm.hang @@ -808,11 +824,13 @@ it.live("session.processor effect tests record aborted errors and idle state", ( const msg = yield* assistant(chat.id, parent.id, path.resolve(dir)) const mdl = yield* provider.getModel(ref.providerID, ref.modelID) const errs: string[] = [] - const off = yield* bus.subscribeCallback(Session.Event.Error, (evt) => { - if (evt.properties.sessionID !== chat.id) return - if (!evt.properties.error) return - errs.push(evt.properties.error.name) + const off = yield* events.listen((evt) => { + if (evt.type !== Session.Event.Error.type) return Effect.void + const data = evt.data as typeof Session.Event.Error.data.Type + if (data.sessionID !== chat.id || !data.error) return Effect.void + errs.push(data.error.name) seen.resolve() + return Effect.void }) const handle = yield* processors.create({ assistantMessage: msg, @@ -829,7 +847,7 @@ it.live("session.processor effect tests record aborted errors and idle state", ( time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), @@ -846,7 +864,7 @@ it.live("session.processor effect tests record aborted errors and idle state", ( yield* Effect.promise(() => seen.promise) const stored = yield* MessageV2.get({ sessionID: chat.id, messageID: msg.id }) const state = yield* sts.get(chat.id) - off() + yield* off expect(Exit.isFailure(exit)).toBe(true) if (Exit.isFailure(exit)) { @@ -892,7 +910,7 @@ it.live("session.processor effect tests mark interruptions aborted without manua time: parent.time, agent: parent.agent, model: { providerID: ref.providerID, modelID: ref.modelID }, - } satisfies MessageV2.User, + } satisfies SessionLegacy.User, sessionID: chat.id, model: mdl, agent: agent(), diff --git a/packages/opencode/test/session/prompt-variant.test.ts b/packages/opencode/test/session/prompt-variant.test.ts index 49cb0844e9ee..6faee20ecc65 100644 --- a/packages/opencode/test/session/prompt-variant.test.ts +++ b/packages/opencode/test/session/prompt-variant.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test" import { Session } from "../../src/session/session" import { SessionPrompt } from "../../src/session/prompt" -import { ProviderID, ModelID } from "../../src/provider/schema" +import { ProviderV2, ModelID } from "@opencode-ai/core/provider" import { AppRuntime } from "../../src/effect/app-runtime" import { provideTestInstance, tmpdir } from "../fixture/fixture" @@ -43,7 +43,7 @@ describe("session.prompt agent variant", () => { const other = await sessionPrompt({ sessionID: session.id, agent: "build", - model: { providerID: ProviderID.make("opencode"), modelID: ModelID.make("kimi-k2.5-free") }, + model: { providerID: ProviderV2.ID.make("opencode"), modelID: ModelID.make("kimi-k2.5-free") }, noReply: true, parts: [{ type: "text", text: "hello" }], }) @@ -57,7 +57,7 @@ describe("session.prompt agent variant", () => { parts: [{ type: "text", text: "hello again" }], }) if (match.info.role !== "user") throw new Error("expected user message") - expect(match.info.model.providerID).toEqual(ProviderID.make("openai")) + expect(match.info.model.providerID).toEqual(ProviderV2.ID.make("openai")) expect(match.info.model.modelID).toEqual(ModelID.make("gpt-5.2")) expect(match.info.model.variant).toBe("xhigh") diff --git a/packages/opencode/test/session/prompt.test.ts b/packages/opencode/test/session/prompt.test.ts index 4c4647457814..f04925b98257 100644 --- a/packages/opencode/test/session/prompt.test.ts +++ b/packages/opencode/test/session/prompt.test.ts @@ -1,4 +1,8 @@ import { NodeFileSystem } from "@effect/platform-node" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Database } from "@opencode-ai/core/database/database" +import { eq } from "drizzle-orm" +import { EventV2Bridge } from "@/event-v2-bridge" import { FetchHttpClient } from "effect/unstable/http" import { expect } from "bun:test" import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer } from "effect" @@ -7,7 +11,6 @@ import { fileURLToPath, pathToFileURL } from "url" import { NamedError } from "@opencode-ai/core/util/error" import { Agent as AgentSvc } from "../../src/agent/agent" import { BackgroundJob } from "@/background/job" -import { Bus } from "../../src/bus" import { Command } from "../../src/command" import { Config } from "@/config/config" import { LSP } from "@/lsp/lsp" @@ -18,11 +21,11 @@ import { Provider as ProviderSvc } from "@/provider/provider" import { Env } from "../../src/env" import { Git } from "../../src/git" import { Image } from "../../src/image/image" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { Question } from "../../src/question" import { Todo } from "../../src/session/todo" import { Session } from "@/session/session" -import { SessionMessageTable } from "../../src/session/session.sql" +import { SessionMessageTable } from "@opencode-ai/core/session/sql" import { LLM } from "../../src/session/llm" import { MessageV2 } from "../../src/session/message-v2" import { AppFileSystem } from "@opencode-ai/core/filesystem" @@ -35,7 +38,7 @@ import { SessionRevert } from "../../src/session/revert" import { SessionRunState } from "../../src/session/run-state" import { MessageID, PartID, SessionID } from "../../src/session/schema" import { SessionStatus } from "../../src/session/status" -import { SessionV2 } from "../../src/v2/session" +import { SessionV2 } from "@opencode-ai/core/session" import { Skill } from "../../src/skill" import { SystemPrompt } from "../../src/session/system" import { Shell } from "../../src/shell/shell" @@ -44,7 +47,6 @@ import { ToolRegistry } from "@/tool/registry" import { Truncate } from "@/tool/truncate" import * as Log from "@opencode-ai/core/util/log" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import * as Database from "../../src/storage/db" import { Ripgrep } from "../../src/file/ripgrep" import { Format } from "../../src/format" import { Reference } from "../../src/reference/reference" @@ -52,9 +54,8 @@ import { RepositoryCache } from "../../src/reference/repository-cache" import { TestInstance } from "../fixture/fixture" import { awaitWithTimeout, pollWithTimeout, testEffect } from "../lib/effect" import { reply, TestLLMServer } from "../lib/llm-server" -import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" -import { EventV2Bridge } from "@/event-v2-bridge" +import { ProviderV2 } from "@opencode-ai/core/provider" void Log.init({ print: false }) @@ -68,8 +69,8 @@ const summary = Layer.succeed( ) const ref = { - providerID: ProviderID.make("test"), - modelID: ModelID.make("test-model"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("test-model"), } function withSh(fx: () => Effect.Effect) { @@ -90,20 +91,20 @@ function withSh(fx: () => Effect.Effect) { ) } -function toolPart(parts: MessageV2.Part[]) { - return parts.find((part): part is MessageV2.ToolPart => part.type === "tool") +function toolPart(parts: SessionLegacy.Part[]) { + return parts.find((part): part is SessionLegacy.ToolPart => part.type === "tool") } -type CompletedToolPart = MessageV2.ToolPart & { state: MessageV2.ToolStateCompleted } -type ErrorToolPart = MessageV2.ToolPart & { state: MessageV2.ToolStateError } +type CompletedToolPart = SessionLegacy.ToolPart & { state: SessionLegacy.ToolStateCompleted } +type ErrorToolPart = SessionLegacy.ToolPart & { state: SessionLegacy.ToolStateError } -function completedTool(parts: MessageV2.Part[]) { +function completedTool(parts: SessionLegacy.Part[]) { const part = toolPart(parts) expect(part?.state.status).toBe("completed") return part?.state.status === "completed" ? (part as CompletedToolPart) : undefined } -function errorTool(parts: MessageV2.Part[]) { +function errorTool(parts: SessionLegacy.Part[]) { const part = toolPart(parts) expect(part?.state.status).toBe("error") return part?.state.status === "error" ? (part as ErrorToolPart) : undefined @@ -152,7 +153,7 @@ const lsp = Layer.succeed( }), ) -const status = SessionStatus.layer.pipe(Layer.provideMerge(Bus.layer)) +const status = SessionStatus.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer)) const run = SessionRunState.layer.pipe(Layer.provide(status)) const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer) @@ -181,7 +182,7 @@ function makePrompt(input?: { processor?: "blocking" }) { AppFileSystem.defaultLayer, BackgroundJob.defaultLayer, status, - SyncEvent.defaultLayer, + Database.defaultLayer, EventV2Bridge.defaultLayer, ).pipe(Layer.provideMerge(infra)) const question = Question.layer.pipe(Layer.provideMerge(deps)) @@ -388,7 +389,7 @@ const user = Effect.fn("test.user")(function* (sessionID: SessionID, text: strin const seed = Effect.fn("test.seed")(function* (sessionID: SessionID, opts?: { finish?: string }) { const session = yield* Session.Service const msg = yield* user(sessionID, "hello") - const assistant: MessageV2.Assistant = { + const assistant: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", parentID: msg.id, @@ -511,8 +512,8 @@ it.instance("loop calls LLM and returns assistant message", () => }), ) -noLLMServer.instance( - "prompt emits v2 prompted and synthetic events", +noLLMServer.instance.skip( + "prompt emits v2 prompted and synthetic events (v2 projector disabled)", () => Effect.gen(function* () { const prompt = yield* SessionPrompt.Service @@ -535,11 +536,15 @@ noLLMServer.instance( }) const messages = yield* SessionV2.Service.use((session) => session.messages({ sessionID: chat.id })).pipe( - Effect.provide(SessionV2.layer), - ) - const row = Database.use((db) => - db.select().from(SessionMessageTable).where(Database.eq(SessionMessageTable.session_id, chat.id)).get(), + Effect.provide(SessionV2.defaultLayer), ) + const { db } = yield* Database.Service + const row = yield* db + .select() + .from(SessionMessageTable) + .where(eq(SessionMessageTable.session_id, chat.id)) + .get() + .pipe(Effect.orDie) expect(messages.find((message) => message.type === "user")).toMatchObject({ type: "user", text: "hello v2" }) expect(typeof row?.data.time.created).toBe("number") expect(messages).toEqual( @@ -753,8 +758,8 @@ it.instance("failed subtask preserves metadata on error tool state", () => expect(tool.state.metadata).toBeDefined() expect(tool.state.metadata?.sessionId).toBeDefined() expect(tool.state.metadata?.model).toEqual({ - providerID: ProviderID.make("test"), - modelID: ModelID.make("missing-model"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("missing-model"), }) }), ) @@ -777,7 +782,7 @@ it.instance( Effect.gen(function* () { const msgs = yield* MessageV2.filterCompactedEffect(chat.id) const taskMsg = msgs.find((item) => item.info.role === "assistant" && item.info.agent === "general") - const tool = taskMsg?.parts.find((part): part is MessageV2.ToolPart => part.type === "tool") + const tool = taskMsg?.parts.find((part): part is SessionLegacy.ToolPart => part.type === "tool") if (tool?.state.status === "running" && tool.state.metadata?.sessionId) return tool }), "timed out waiting for running subtask metadata", @@ -820,7 +825,7 @@ it.instance( const msgs = yield* MessageV2.filterCompactedEffect(chat.id) const assistant = msgs.findLast((item) => item.info.role === "assistant" && item.info.agent === "build") const tool = assistant?.parts.find( - (part): part is MessageV2.ToolPart => part.type === "tool" && part.tool === "task", + (part): part is SessionLegacy.ToolPart => part.type === "tool" && part.tool === "task", ) if (tool?.state.status === "running" && tool.state.metadata?.sessionId) return tool }), @@ -1364,24 +1369,26 @@ unixNoLLMServer( unixNoLLMServer( "shell commands can change directory after startup", () => - Effect.gen(function* () { - const { directory: dir } = yield* TestInstance - const { prompt, run, chat } = yield* boot() - const parent = path.dirname(dir) - const result = yield* prompt.shell({ - sessionID: chat.id, - agent: "build", - command: "cd .. && pwd", - }) + withSh(() => + Effect.gen(function* () { + const { directory: dir } = yield* TestInstance + const { prompt, run, chat } = yield* boot() + const parent = path.dirname(dir) + const result = yield* prompt.shell({ + sessionID: chat.id, + agent: "build", + command: "cd .. && pwd", + }) - expect(result.info.role).toBe("assistant") - const tool = completedTool(result.parts) - if (!tool) return + expect(result.info.role).toBe("assistant") + const tool = completedTool(result.parts) + if (!tool) return - expect(tool.state.output).toContain(parent) - expect(tool.state.metadata.output).toContain(parent) - yield* run.assertNotBusy(chat.id) - }), + expect(tool.state.output).toContain(parent) + expect(tool.state.metadata.output).toContain(parent) + yield* run.assertNotBusy(chat.id) + }), + ), { config: cfg }, ) @@ -1939,11 +1946,11 @@ noLLMServer.instance( "Use @docs and @docs/README.md and @docs/guide and @docs/missing.md and @docs/README.md and @build", ) const references = parts.filter( - (part): part is MessageV2.TextPartInput => + (part): part is SessionLegacy.TextPartInput => part.type === "text" && part.synthetic === true && part.text.startsWith("Referenced configured reference "), ) - const files = parts.filter((part): part is MessageV2.FilePartInput => part.type === "file") - const agents = parts.filter((part): part is MessageV2.AgentPartInput => part.type === "agent") + const files = parts.filter((part): part is SessionLegacy.FilePartInput => part.type === "file") + const agents = parts.filter((part): part is SessionLegacy.AgentPartInput => part.type === "agent") const bare = references.find((part) => part.text.includes("@docs.")) const missing = references.find((part) => part.text.includes("@docs/missing.md")) const guide = files.find((part) => part.filename === "docs/guide") @@ -1996,7 +2003,7 @@ noLLMServer.instance( const stored = yield* MessageV2.get({ sessionID: session.id, messageID: message.info.id }) const synthetic = stored.parts.filter( - (part): part is MessageV2.TextPart => part.type === "text" && part.synthetic === true, + (part): part is SessionLegacy.TextPart => part.type === "text" && part.synthetic === true, ) const reference = synthetic.find((part) => part.text.startsWith("Referenced configured reference @docs.")) @@ -2051,7 +2058,7 @@ noLLMServer.instance( const stored = yield* MessageV2.get({ sessionID: session.id, messageID: message.info.id }) const synthetic = stored.parts.filter( - (part): part is MessageV2.TextPart => part.type === "text" && part.synthetic === true, + (part): part is SessionLegacy.TextPart => part.type === "text" && part.synthetic === true, ) const reference = synthetic.find((part) => part.text.startsWith("Referenced configured reference @docs/README.md."), @@ -2198,7 +2205,7 @@ noLLMServer.instance( const other = yield* prompt.prompt({ sessionID: session.id, agent: "build", - model: { providerID: ProviderID.make("opencode"), modelID: ModelID.make("kimi-k2.5-free") }, + model: { providerID: ProviderV2.ID.make("opencode"), modelID: ProviderV2.ModelID.make("kimi-k2.5-free") }, noReply: true, parts: [{ type: "text", text: "hello" }], }) @@ -2213,8 +2220,8 @@ noLLMServer.instance( }) if (match.info.role !== "user") throw new Error("expected user message") expect(match.info.model).toEqual({ - providerID: ProviderID.make("test"), - modelID: ModelID.make("test-model"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("test-model"), variant: "xhigh", }) expect(match.info.model.variant).toBe("xhigh") diff --git a/packages/opencode/test/session/retry.test.ts b/packages/opencode/test/session/retry.test.ts index 22ff6cde811d..080db82bc057 100644 --- a/packages/opencode/test/session/retry.test.ts +++ b/packages/opencode/test/session/retry.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import type { NamedError } from "@opencode-ai/core/util/error" import { APICallError } from "ai" import { setTimeout as sleep } from "node:timers/promises" @@ -6,19 +7,19 @@ import { Effect, Layer, Schedule, Schema } from "effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { SessionRetry } from "../../src/session/retry" import { MessageV2 } from "../../src/session/message-v2" -import { ProviderID } from "../../src/provider/schema" +import { ProviderError } from "../../src/provider/error" import { SessionID } from "../../src/session/schema" import { SessionStatus } from "../../src/session/status" -import { provideTmpdirInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" -const providerID = ProviderID.make("test") +const providerID = ProviderV2.ID.make("test") const retryProvider = "test" const it = testEffect(Layer.mergeAll(SessionStatus.defaultLayer, CrossSpawnSpawner.defaultLayer)) -function apiError(headers?: Record): MessageV2.APIError { - return Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ +function apiError(headers?: Record): SessionLegacy.APIError { + return Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "boom", isRetryable: true, responseHeaders: headers, @@ -84,36 +85,34 @@ describe("session.retry.delay", () => { expect(SessionRetry.delay(1, error)).toBe(SessionRetry.RETRY_MAX_DELAY) }) - it.live("policy updates retry status and increments attempts", () => - provideTmpdirInstance(() => - Effect.gen(function* () { - const sessionID = SessionID.make("session-retry-test") - const error = apiError({ "retry-after-ms": "0" }) - const status = yield* SessionStatus.Service - - const step = yield* Schedule.toStepWithMetadata( - SessionRetry.policy({ - provider: "test", - parse: Schema.decodeUnknownSync(MessageV2.APIError.Schema), - set: (info) => - status.set(sessionID, { - type: "retry", - attempt: info.attempt, - message: info.message, - next: info.next, - }), - }), - ) - yield* step(error) - yield* step(error) - - expect(yield* status.get(sessionID)).toMatchObject({ - type: "retry", - attempt: 2, - message: "boom", - }) - }), - ), + it.instance("policy updates retry status and increments attempts", () => + Effect.gen(function* () { + const sessionID = SessionID.make("session-retry-test") + const error = apiError({ "retry-after-ms": "0" }) + const status = yield* SessionStatus.Service + + const step = yield* Schedule.toStepWithMetadata( + SessionRetry.policy({ + provider: "test", + parse: Schema.decodeUnknownSync(SessionLegacy.APIError.Schema), + set: (info) => + status.set(sessionID, { + type: "retry", + attempt: info.attempt, + message: info.message, + next: info.next, + }), + }), + ) + yield* step(error) + yield* step(error) + + expect(yield* status.get(sessionID)).toMatchObject({ + type: "retry", + attempt: 2, + message: "boom", + }) + }), ) }) @@ -163,8 +162,27 @@ describe("session.retry.retryable", () => { expect(SessionRetry.retryable(error, retryProvider)).toEqual({ message: msg }) }) + test("retries transport timeout errors", () => { + const request = MessageV2.fromError(new ProviderError.HeaderTimeoutError(10000), { providerID }) + expect(SessionLegacy.APIError.isInstance(request)).toBe(true) + expect(SessionRetry.retryable(request, retryProvider)).toEqual({ + message: "Provider response headers timed out after 10000ms", + }) + }) + + test("retries websocket stream transport errors", () => { + const request = MessageV2.fromError( + new ProviderError.ResponseStreamError("WebSocket closed before response.completed (code 1006: Connection ended)"), + { providerID }, + ) + expect(SessionLegacy.APIError.isInstance(request)).toBe(true) + expect(SessionRetry.retryable(request, retryProvider)).toEqual({ + message: "WebSocket closed before response.completed (code 1006: Connection ended)", + }) + }) + test("does not retry context overflow errors", () => { - const error = new MessageV2.ContextOverflowError({ + const error = new SessionLegacy.ContextOverflowError({ message: "Input exceeds context window of this model", responseBody: '{"error":{"code":"context_length_exceeded"}}', }).toObject() @@ -173,8 +191,8 @@ describe("session.retry.retryable", () => { }) test("retries 500 errors even when isRetryable is false", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Internal server error", isRetryable: false, statusCode: 500, @@ -186,8 +204,8 @@ describe("session.retry.retryable", () => { }) test("retries 502 bad gateway errors", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Bad gateway", isRetryable: false, statusCode: 502, @@ -198,8 +216,8 @@ describe("session.retry.retryable", () => { }) test("retries 503 service unavailable errors", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Service unavailable", isRetryable: false, statusCode: 503, @@ -210,8 +228,8 @@ describe("session.retry.retryable", () => { }) test("does not retry 4xx errors when isRetryable is false", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Bad request", isRetryable: false, statusCode: 400, @@ -222,8 +240,8 @@ describe("session.retry.retryable", () => { }) test("retries ZlibError decompression failures", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Response decompression failed", isRetryable: true, metadata: { code: "ZlibError" }, @@ -236,8 +254,8 @@ describe("session.retry.retryable", () => { }) test("maps free limits to Go upsell action", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Free usage exceeded", isRetryable: true, statusCode: 429, @@ -262,8 +280,8 @@ describe("session.retry.retryable", () => { }) test("maps Go subscription limits to workspace PAYG upsell", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Subscription quota exceeded. You can continue using free models.", isRetryable: true, statusCode: 429, @@ -300,8 +318,8 @@ describe("session.retry.retryable", () => { }) test("maps Go subscription limits without limit metadata", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Subscription quota exceeded. You can continue using free models.", isRetryable: true, statusCode: 429, @@ -355,8 +373,8 @@ describe("session.message-v2.fromError", () => { const result = MessageV2.fromError(error, { providerID }) - expect(MessageV2.APIError.isInstance(result)).toBe(true) - if (!MessageV2.APIError.isInstance(result)) throw new Error("expected APIError") + expect(SessionLegacy.APIError.isInstance(result)).toBe(true) + if (!SessionLegacy.APIError.isInstance(result)) throw new Error("expected APIError") expect(result.data.isRetryable).toBe(true) expect(result.data.message).toBe("Connection reset by server") expect(result.data.metadata?.code).toBe("ECONNRESET") @@ -366,8 +384,8 @@ describe("session.message-v2.fromError", () => { ) test("ECONNRESET socket error is retryable", () => { - const error = Schema.decodeUnknownSync(MessageV2.APIError.Schema)( - new MessageV2.APIError({ + const error = Schema.decodeUnknownSync(SessionLegacy.APIError.Schema)( + new SessionLegacy.APIError({ message: "Connection reset by server", isRetryable: true, metadata: { code: "ECONNRESET", message: "The socket connection was closed unexpectedly" }, @@ -389,8 +407,8 @@ describe("session.message-v2.fromError", () => { responseBody: '{"error":"boom"}', isRetryable: false, }) - const result = MessageV2.fromError(error, { providerID: ProviderID.make("openai") }) - if (!MessageV2.APIError.isInstance(result)) throw new Error("expected APIError") + const result = MessageV2.fromError(error, { providerID: ProviderV2.ID.make("openai") }) + if (!SessionLegacy.APIError.isInstance(result)) throw new Error("expected APIError") expect(result.data.isRetryable).toBe(true) }) @@ -408,11 +426,11 @@ describe("session.message-v2.fromError", () => { }, }), }, - { providerID: ProviderID.make("openai") }, + { providerID: ProviderV2.ID.make("openai") }, ) - expect(MessageV2.APIError.isInstance(result)).toBe(true) - if (!MessageV2.APIError.isInstance(result)) throw new Error("expected APIError") + expect(SessionLegacy.APIError.isInstance(result)).toBe(true) + if (!SessionLegacy.APIError.isInstance(result)) throw new Error("expected APIError") expect(result.data.isRetryable).toBe(true) expect(SessionRetry.retryable(result, retryProvider)).toEqual({ message: "An error occurred while processing your request.", diff --git a/packages/opencode/test/session/revert-compact.test.ts b/packages/opencode/test/session/revert-compact.test.ts index c70c17d45186..0df791096358 100644 --- a/packages/opencode/test/session/revert-compact.test.ts +++ b/packages/opencode/test/session/revert-compact.test.ts @@ -1,9 +1,10 @@ import { describe, expect } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import fs from "fs/promises" import path from "path" import { Effect, Layer } from "effect" import { Session } from "@/session/session" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { SessionRevert } from "../../src/session/revert" import { MessageV2 } from "../../src/session/message-v2" import { Snapshot } from "../../src/snapshot" @@ -12,6 +13,7 @@ import { MessageID, PartID, SessionID } from "../../src/session/schema" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { provideTmpdirInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" void Log.init({ print: false }) @@ -31,7 +33,7 @@ const user = Effect.fn("test.user")(function* (sessionID: SessionID, agent = "de role: "user" as const, sessionID, agent, - model: { providerID: ProviderID.make("openai"), modelID: ModelID.make("gpt-4") }, + model: { providerID: ProviderV2.ID.make("openai"), modelID: ProviderV2.ModelID.make("gpt-4") }, time: { created: Date.now() }, }) }) @@ -47,8 +49,8 @@ const assistant = Effect.fn("test.assistant")(function* (sessionID: SessionID, p path: { cwd: dir, root: dir }, cost: 0, tokens: { output: 0, input: 0, reasoning: 0, cache: { read: 0, write: 0 } }, - modelID: ModelID.make("gpt-4"), - providerID: ProviderID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), parentID, time: { created: Date.now() }, finish: "end_turn", @@ -114,8 +116,8 @@ describe("revert + compact workflow", () => { sessionID, agent: "default", model: { - providerID: ProviderID.make("openai"), - modelID: ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), }, time: { created: Date.now(), @@ -130,7 +132,7 @@ describe("revert + compact workflow", () => { text: "Hello, please help me", }) - const assistantMsg1: MessageV2.Assistant = { + const assistantMsg1: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", sessionID, @@ -147,8 +149,8 @@ describe("revert + compact workflow", () => { reasoning: 0, cache: { read: 0, write: 0 }, }, - modelID: ModelID.make("gpt-4"), - providerID: ProviderID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), parentID: userMsg1.id, time: { created: Date.now(), @@ -171,8 +173,8 @@ describe("revert + compact workflow", () => { sessionID, agent: "default", model: { - providerID: ProviderID.make("openai"), - modelID: ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), }, time: { created: Date.now(), @@ -187,7 +189,7 @@ describe("revert + compact workflow", () => { text: "What's the capital of France?", }) - const assistantMsg2: MessageV2.Assistant = { + const assistantMsg2: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", sessionID, @@ -204,8 +206,8 @@ describe("revert + compact workflow", () => { reasoning: 0, cache: { read: 0, write: 0 }, }, - modelID: ModelID.make("gpt-4"), - providerID: ProviderID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), parentID: userMsg2.id, time: { created: Date.now(), @@ -276,8 +278,8 @@ describe("revert + compact workflow", () => { sessionID, agent: "default", model: { - providerID: ProviderID.make("openai"), - modelID: ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), }, time: { created: Date.now(), @@ -292,7 +294,7 @@ describe("revert + compact workflow", () => { text: "Hello", }) - const assistantMsg: MessageV2.Assistant = { + const assistantMsg: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", sessionID, @@ -309,8 +311,8 @@ describe("revert + compact workflow", () => { reasoning: 0, cache: { read: 0, write: 0 }, }, - modelID: ModelID.make("gpt-4"), - providerID: ProviderID.make("openai"), + modelID: ProviderV2.ModelID.make("gpt-4"), + providerID: ProviderV2.ID.make("openai"), parentID: userMsg.id, time: { created: Date.now(), diff --git a/packages/opencode/test/session/schema-decoding.test.ts b/packages/opencode/test/session/schema-decoding.test.ts index 3a367fa6c687..1323c2aba61c 100644 --- a/packages/opencode/test/session/schema-decoding.test.ts +++ b/packages/opencode/test/session/schema-decoding.test.ts @@ -8,8 +8,8 @@ import { SessionStatus } from "../../src/session/status" import { SessionSummary } from "../../src/session/summary" import { Todo } from "../../src/session/todo" import { SessionID, MessageID, PartID } from "../../src/session/schema" -import { ProjectID } from "../../src/project/schema" -import { WorkspaceID } from "../../src/control-plane/schema" +import { ProjectV2 } from "@opencode-ai/core/project" +import { WorkspaceV2 } from "@opencode-ai/core/workspace" // Covers the session-domain Effect Schema migration. For each migrated // schema we assert: @@ -22,8 +22,8 @@ const sessionID = Schema.decodeUnknownSync(SessionID)("ses_01J5Y5H0AH4Q4NXJ6P4C3 const sessionIDChild = Schema.decodeUnknownSync(SessionID)("ses_01J5Y5H0AH4Q4NXJ6P4C3P5V2L") const messageID = Schema.decodeUnknownSync(MessageID)("msg_01J5Y5H0AH4Q4NXJ6P4C3P5V2M") const partID = Schema.decodeUnknownSync(PartID)("prt_01J5Y5H0AH4Q4NXJ6P4C3P5V2N") -const projectID = ProjectID.make("proj-alpha") -const workspaceID = Schema.decodeUnknownSync(WorkspaceID)("wrk-primary") +const projectID = ProjectV2.ID.make("proj-alpha") +const workspaceID = Schema.decodeUnknownSync(WorkspaceV2.ID)("wrk-primary") function decodeUnknown(schema: S) { const decode = Schema.decodeUnknownSync(schema as any) @@ -64,6 +64,7 @@ describe("Session.Info", () => { share: { url: "https://share.example.com/s/1" }, title: "Full session", version: "1.0.0", + metadata: { source: "test" }, time: { created: 100, updated: 200, compacting: 150, archived: 300 }, permission: [{ action: "allow" as const, pattern: "*", permission: "read" }], revert: { @@ -157,6 +158,7 @@ describe("Session input schemas", () => { const populated = { parentID: sessionID, title: "child", + metadata: { source: "test" }, permission: [{ action: "ask" as const, pattern: "*", permission: "bash" }], workspaceID, } diff --git a/packages/opencode/test/session/session-schema.test.ts b/packages/opencode/test/session/session-schema.test.ts index 906414fdbe52..92249c4a0951 100644 --- a/packages/opencode/test/session/session-schema.test.ts +++ b/packages/opencode/test/session/session-schema.test.ts @@ -1,13 +1,13 @@ import { describe, expect, test } from "bun:test" import { Schema } from "effect" -import { ProjectID } from "../../src/project/schema" +import { ProjectV2 } from "@opencode-ai/core/project" import { MessageID, SessionID } from "../../src/session/schema" import { Session } from "../../src/session/session" const info = { id: SessionID.descending(), slug: "test-session", - projectID: ProjectID.global, + projectID: ProjectV2.ID.global, workspaceID: undefined, directory: "/tmp/opencode", parentID: undefined, @@ -43,7 +43,7 @@ describe("Session schema", () => { const encoded = Schema.encodeUnknownSync(Session.GlobalInfo)({ ...info, project: { - id: ProjectID.global, + id: ProjectV2.ID.global, name: undefined, worktree: "/tmp/opencode", }, diff --git a/packages/opencode/test/session/session.test.ts b/packages/opencode/test/session/session.test.ts index 9a2b15578178..06bd6f9528d4 100644 --- a/packages/opencode/test/session/session.test.ts +++ b/packages/opencode/test/session/session.test.ts @@ -1,31 +1,34 @@ import { describe, expect } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Database } from "@opencode-ai/core/database/database" +import { SessionProjector } from "@opencode-ai/core/session/projector" import { Deferred, Effect, Exit, Layer } from "effect" import { Session as SessionNs } from "@/session/session" -import { GlobalBus, type GlobalEvent } from "../../src/bus/global" import * as Log from "@opencode-ai/core/util/log" import { MessageV2 } from "../../src/session/message-v2" import { MessageID, PartID, type SessionID } from "../../src/session/schema" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { provideInstance, tmpdirScoped } from "../fixture/fixture" +import { provideInstance, testInstanceStoreLayer, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" -import { Bus } from "@/bus" import { Storage } from "@/storage/storage" -import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" import { BackgroundJob } from "@/background/job" +import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) const it = testEffect( Layer.mergeAll( SessionNs.layer.pipe( - Layer.provide(Bus.layer), Layer.provide(Storage.defaultLayer), - Layer.provide(SyncEvent.defaultLayer), + Layer.provide(Database.defaultLayer), + Layer.provideMerge(EventV2Bridge.defaultLayer), + Layer.provide(SessionProjector.defaultLayer), Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: false })), Layer.provide(BackgroundJob.defaultLayer), ), CrossSpawnSpawner.defaultLayer, + testInstanceStoreLayer, ), ) @@ -37,24 +40,22 @@ const awaitDeferred = (deferred: Deferred.Deferred, message: string) => const remove = (id: SessionID) => SessionNs.use.remove(id) -const subscribeGlobal = (type: string, callback: (event: NonNullable) => void) => { - const listener = (event: GlobalEvent) => { - if (event.payload?.type === type) callback(event.payload) - } - GlobalBus.on("event", listener) - return () => GlobalBus.off("event", listener) -} - describe("session.created event", () => { it.instance("should emit session.created event when session is created", () => Effect.gen(function* () { const session = yield* SessionNs.Service + const events = yield* EventV2Bridge.Service const received = yield* Deferred.make() - const unsub = subscribeGlobal(SessionNs.Event.Created.type, (event) => { - Deferred.doneUnsafe(received, Effect.succeed(event.properties.info as SessionNs.Info)) + const unsub = yield* events.listen((event) => { + if (event.type === SessionNs.Event.Created.type) + Deferred.doneUnsafe( + received, + Effect.succeed((event.data as typeof SessionNs.Event.Created.data.Type).info as SessionNs.Info), + ) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsub)) + yield* Effect.addFinalizer(() => unsub) const info = yield* session.create({}) const receivedInfo = yield* awaitDeferred(received, "timed out waiting for session.created") @@ -72,6 +73,7 @@ describe("session.created event", () => { it.instance("session.created event should be emitted before session.updated", () => Effect.gen(function* () { const session = yield* SessionNs.Service + const source = yield* EventV2Bridge.Service const events: string[] = [] const received = yield* Deferred.make() const push = (event: string) => { @@ -81,17 +83,15 @@ describe("session.created event", () => { } } - const unsubCreated = subscribeGlobal(SessionNs.Event.Created.type, () => { - push("created") - }) - yield* Effect.addFinalizer(() => Effect.sync(unsubCreated)) - - const unsubUpdated = subscribeGlobal(SessionNs.Event.Updated.type, () => { - push("updated") + const unsubscribe = yield* source.listen((event) => { + if (event.type === SessionNs.Event.Created.type) push("created") + if (event.type === SessionNs.Event.Updated.type) push("updated") + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsubUpdated)) + yield* Effect.addFinalizer(() => unsubscribe) const info = yield* session.create({}) + yield* session.setTitle({ sessionID: info.id, title: "updated" }) const receivedEvents = yield* awaitDeferred(received, "timed out waiting for session created/updated events") expect(receivedEvents).toContain("created") @@ -103,12 +103,13 @@ describe("session.created event", () => { ) }) -describe("step-finish token propagation via Bus event", () => { +describe("step-finish token propagation via event", () => { it.instance( "non-zero tokens propagate through PartUpdated event", () => Effect.gen(function* () { const session = yield* SessionNs.Service + const events = yield* EventV2Bridge.Service const info = yield* session.create({}) const messageID = MessageID.ascending() @@ -121,16 +122,21 @@ describe("step-finish token propagation via Bus event", () => { model: { providerID: "test", modelID: "test" }, tools: {}, mode: "", - } as unknown as MessageV2.Info) + } as unknown as SessionLegacy.Info) - // Bus subscribers receive readonly Schema.Type payloads; `MessageV2.Part` + // Event subscribers receive readonly Schema.Type payloads; `SessionLegacy.Part` // is the mutable domain type. Cast bridges the two — safe because the // test only reads the value afterwards. - const received = yield* Deferred.make() - const unsub = subscribeGlobal(MessageV2.Event.PartUpdated.type, (event) => { - Deferred.doneUnsafe(received, Effect.succeed(event.properties.part as MessageV2.Part)) + const received = yield* Deferred.make() + const unsub = yield* events.listen((event) => { + if (event.type === MessageV2.Event.PartUpdated.type) + Deferred.doneUnsafe( + received, + Effect.succeed((event.data as typeof MessageV2.Event.PartUpdated.data.Type).part as SessionLegacy.Part), + ) + return Effect.void }) - yield* Effect.addFinalizer(() => Effect.sync(unsub)) + yield* Effect.addFinalizer(() => unsub) const tokens = { total: 1500, @@ -154,7 +160,7 @@ describe("step-finish token propagation via Bus event", () => { const receivedPart = yield* awaitDeferred(received, "timed out waiting for message.part.updated") expect(receivedPart.type).toBe("step-finish") - const finish = receivedPart as MessageV2.StepFinishPart + const finish = receivedPart as SessionLegacy.StepFinishPart expect(finish.tokens.input).toBe(500) expect(finish.tokens.output).toBe(800) expect(finish.tokens.reasoning).toBe(200) @@ -184,4 +190,35 @@ describe("Session", () => { expect(Exit.isFailure(getExit)).toBe(true) }), ) + + it.instance("persists metadata and copies it on fork by default", () => + Effect.gen(function* () { + const session = yield* SessionNs.Service + const meta = { source: "sdk", trace: { id: "abc" } } + const created = yield* Effect.acquireRelease(session.create({ title: "with-meta", metadata: meta }), (info) => + session.remove(info.id).pipe(Effect.ignore), + ) + const saved = yield* session.get(created.id) + const fork = yield* Effect.acquireRelease(session.fork({ sessionID: created.id }), (info) => + session.remove(info.id).pipe(Effect.ignore), + ) + + expect(saved.metadata).toEqual(meta) + expect(fork.metadata).toEqual(meta) + expect(fork.metadata).not.toBe(meta) + }), + ) + + it.instance("omits metadata when not provided", () => + Effect.gen(function* () { + const session = yield* SessionNs.Service + const created = yield* Effect.acquireRelease(session.create({ title: "empty-meta" }), (info) => + session.remove(info.id).pipe(Effect.ignore), + ) + const saved = yield* session.get(created.id) + + expect(created.metadata).toBeUndefined() + expect(saved.metadata).toBeUndefined() + }), + ) }) diff --git a/packages/opencode/test/session/snapshot-tool-race.test.ts b/packages/opencode/test/session/snapshot-tool-race.test.ts index 89ed11613e15..50e2a31f959a 100644 --- a/packages/opencode/test/session/snapshot-tool-race.test.ts +++ b/packages/opencode/test/session/snapshot-tool-race.test.ts @@ -22,6 +22,7 @@ import { SessionPrompt } from "../../src/session/prompt" import { SessionRevert } from "../../src/session/revert" import { SessionSummary } from "../../src/session/summary" import { MessageV2 } from "../../src/session/message-v2" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import * as Log from "@opencode-ai/core/util/log" import { provideTmpdirServer } from "../fixture/fixture" import { testEffect } from "../lib/effect" @@ -29,10 +30,11 @@ import { TestLLMServer } from "../lib/llm-server" // Same layer setup as prompt-effect.test.ts import { NodeFileSystem } from "@effect/platform-node" +import { Database } from "@opencode-ai/core/database/database" +import { EventV2Bridge } from "@/event-v2-bridge" import { Agent as AgentSvc } from "../../src/agent/agent" import { BackgroundJob } from "@/background/job" import { Git } from "../../src/git" -import { Bus } from "../../src/bus" import { Command } from "../../src/command" import { Config } from "@/config/config" import { LSP } from "@/lsp/lsp" @@ -60,9 +62,7 @@ import { Ripgrep } from "../../src/file/ripgrep" import { Format } from "../../src/format" import { Reference } from "../../src/reference/reference" import { RepositoryCache } from "../../src/reference/repository-cache" -import { SyncEvent } from "@/sync" import { RuntimeFlags } from "@/effect/runtime-flags" -import { EventV2Bridge } from "@/event-v2-bridge" void Log.init({ print: false }) @@ -109,7 +109,7 @@ const lsp = Layer.succeed( }), ) -const status = SessionStatus.layer.pipe(Layer.provideMerge(Bus.layer)) +const status = SessionStatus.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer)) const run = SessionRunState.layer.pipe(Layer.provide(status)) const infra = Layer.mergeAll(NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer) @@ -130,7 +130,7 @@ function makeHttp() { AppFileSystem.defaultLayer, BackgroundJob.defaultLayer, status, - SyncEvent.defaultLayer, + Database.defaultLayer, EventV2Bridge.defaultLayer, ).pipe(Layer.provideMerge(infra)) const question = Question.layer.pipe(Layer.provideMerge(deps)) @@ -257,15 +257,19 @@ it.live("tool execution produces non-empty session diff (snapshot race)", () => // Verify the tool call completed (in the first assistant message) const allMsgs = yield* MessageV2.filterCompactedEffect(session.id) + const user = allMsgs.find( + (msg): msg is SessionLegacy.WithParts & { info: SessionLegacy.User } => msg.info.role === "user", + ) const tool = allMsgs .flatMap((m) => m.parts) - .find((p): p is MessageV2.ToolPart => p.type === "tool" && p.tool === "bash") + .find((p): p is SessionLegacy.ToolPart => p.type === "tool" && p.tool === "bash") expect(tool?.state.status).toBe("completed") + if (!user) throw new Error("Expected user message") - // Poll for diff — summarize() is fire-and-forget + // Poll for the turn diff — summarize() is fire-and-forget. let diff: Array<{ file?: string }> = [] for (let i = 0; i < 50; i++) { - diff = yield* summary.diff({ sessionID: session.id }) + diff = yield* summary.diff({ sessionID: session.id, messageID: user.info.id }) if (diff.length > 0) break yield* Effect.sleep("100 millis") } diff --git a/packages/opencode/test/session/structured-output-integration.test.ts b/packages/opencode/test/session/structured-output-integration.test.ts index 125c63c0f9d3..f2d28864be7d 100644 --- a/packages/opencode/test/session/structured-output-integration.test.ts +++ b/packages/opencode/test/session/structured-output-integration.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Effect, Layer } from "effect" import { Session } from "@/session/session" import { SessionPrompt } from "../../src/session/prompt" @@ -218,7 +219,7 @@ describe("StructuredOutput Integration", () => { ) test("unit test: StructuredOutputError is properly structured", () => { - const error = new MessageV2.StructuredOutputError({ + const error = new SessionLegacy.StructuredOutputError({ message: "Failed to produce valid structured output after 3 attempts", retries: 3, }) diff --git a/packages/opencode/test/session/structured-output.test.ts b/packages/opencode/test/session/structured-output.test.ts index 806c57483440..14bc876c8979 100644 --- a/packages/opencode/test/session/structured-output.test.ts +++ b/packages/opencode/test/session/structured-output.test.ts @@ -1,12 +1,13 @@ import { describe, expect, test } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" import { Exit, Schema } from "effect" import { MessageV2 } from "../../src/session/message-v2" import { SessionPrompt } from "../../src/session/prompt" import { SessionID, MessageID } from "../../src/session/schema" -const decodeFormat = Schema.decodeUnknownExit(MessageV2.Format) -const decodeUser = Schema.decodeUnknownExit(MessageV2.User) -const decodeAssistant = Schema.decodeUnknownExit(MessageV2.Assistant) +const decodeFormat = Schema.decodeUnknownExit(SessionLegacy.Format) +const decodeUser = Schema.decodeUnknownExit(SessionLegacy.User) +const decodeAssistant = Schema.decodeUnknownExit(SessionLegacy.Assistant) describe("structured-output.OutputFormat", () => { test("parses text format", () => { @@ -65,7 +66,7 @@ describe("structured-output.OutputFormat", () => { describe("structured-output.StructuredOutputError", () => { test("creates error with message and retries", () => { - const error = new MessageV2.StructuredOutputError({ + const error = new SessionLegacy.StructuredOutputError({ message: "Failed to validate", retries: 3, }) @@ -76,7 +77,7 @@ describe("structured-output.StructuredOutputError", () => { }) test("converts to object correctly", () => { - const error = new MessageV2.StructuredOutputError({ + const error = new SessionLegacy.StructuredOutputError({ message: "Test error", retries: 2, }) @@ -88,13 +89,13 @@ describe("structured-output.StructuredOutputError", () => { }) test("isInstance correctly identifies error", () => { - const error = new MessageV2.StructuredOutputError({ + const error = new SessionLegacy.StructuredOutputError({ message: "Test", retries: 1, }) - expect(MessageV2.StructuredOutputError.isInstance(error)).toBe(true) - expect(MessageV2.StructuredOutputError.isInstance({ name: "other" })).toBe(false) + expect(SessionLegacy.StructuredOutputError.isInstance(error)).toBe(true) + expect(SessionLegacy.StructuredOutputError.isInstance({ name: "other" })).toBe(false) }) }) diff --git a/packages/opencode/test/share/share-next.test.ts b/packages/opencode/test/share/share-next.test.ts index 1daa4c2c8e92..feb070a09cb0 100644 --- a/packages/opencode/test/share/share-next.test.ts +++ b/packages/opencode/test/share/share-next.test.ts @@ -7,14 +7,14 @@ import { AccessToken, AccountID, OrgID, RefreshToken } from "../../src/account/s import { Account } from "../../src/account/account" import { AccountRepo } from "../../src/account/repo" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "@/config/config" import { Provider } from "@/provider/provider" import { Session } from "@/session/session" import type { SessionID } from "../../src/session/schema" import { ShareNext } from "@/share/share-next" -import { SessionShareTable } from "../../src/share/share.sql" -import { Database } from "@/storage/db" +import { SessionShareTable } from "@opencode-ai/core/share/sql" +import { Database } from "@opencode-ai/core/database/database" import { eq } from "drizzle-orm" import { provideTmpdirInstance } from "../fixture/fixture" import { resetDatabase } from "../fixture/db" @@ -22,7 +22,8 @@ import { testEffect } from "../lib/effect" const env = Layer.mergeAll( Session.defaultLayer, - AccountRepo.layer, + AccountRepo.defaultLayer, + Database.defaultLayer, NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer, ) @@ -42,9 +43,10 @@ const none = HttpClient.make(() => Effect.die("unexpected http call")) function live(client: HttpClient.HttpClient) { const http = Layer.succeed(HttpClient.HttpClient, client) return ShareNext.layer.pipe( - Layer.provide(Bus.layer), - Layer.provide(Account.layer.pipe(Layer.provide(AccountRepo.layer), Layer.provide(http))), + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(Account.layer.pipe(Layer.provide(AccountRepo.defaultLayer), Layer.provide(http))), Layer.provide(Config.defaultLayer), + Layer.provide(Database.defaultLayer), Layer.provide(http), Layer.provide(Provider.defaultLayer), Layer.provide(Session.defaultLayer), @@ -54,15 +56,16 @@ function live(client: HttpClient.HttpClient) { function wired(client: HttpClient.HttpClient) { const http = Layer.succeed(HttpClient.HttpClient, client) return Layer.mergeAll( - Bus.layer, + EventV2Bridge.defaultLayer, ShareNext.layer, Session.defaultLayer, - AccountRepo.layer, + AccountRepo.defaultLayer, + Database.defaultLayer, NodeFileSystem.layer, CrossSpawnSpawner.defaultLayer, ).pipe( - Layer.provide(Bus.layer), - Layer.provide(Account.layer.pipe(Layer.provide(AccountRepo.layer), Layer.provide(http))), + Layer.provide(EventV2Bridge.defaultLayer), + Layer.provide(Account.layer.pipe(Layer.provide(AccountRepo.defaultLayer), Layer.provide(http))), Layer.provide(Config.defaultLayer), Layer.provide(http), Layer.provide(Provider.defaultLayer), @@ -70,7 +73,15 @@ function wired(client: HttpClient.HttpClient) { } const share = (id: SessionID) => - Database.use((db) => db.select().from(SessionShareTable).where(eq(SessionShareTable.session_id, id)).get()) + Effect.gen(function* () { + const { db } = yield* Database.Service + return yield* db + .select() + .from(SessionShareTable) + .where(eq(SessionShareTable.session_id, id)) + .get() + .pipe(Effect.orDie) + }) const seed = (url: string, org?: string) => AccountRepo.Service.use((repo) => @@ -169,7 +180,7 @@ describe("ShareNext", () => { expect(result.url).toBe("https://legacy-share.example.com/share/abc") expect(result.secret).toBe("sec_123") - const row = share(session.id) + const row = yield* share(session.id) expect(row?.id).toBe("shr_abc") expect(row?.url).toBe("https://legacy-share.example.com/share/abc") expect(row?.secret).toBe("sec_123") @@ -207,7 +218,7 @@ describe("ShareNext", () => { yield* ShareNext.use.remove(session.id) }).pipe(Effect.provide(live(client))) - expect(share(session.id)).toBeUndefined() + expect(yield* share(session.id)).toBeUndefined() expect(seen.map((req) => [req.method, req.url])).toEqual([ ["POST", "https://legacy-share.example.com/api/share"], ["DELETE", "https://legacy-share.example.com/api/share/shr_abc"], @@ -228,7 +239,7 @@ describe("ShareNext", () => { ) expect(Exit.isFailure(exit)).toBe(true) - expect(share(session.id)).toBeUndefined() + expect(yield* share(session.id)).toBeUndefined() }), ), ) @@ -245,28 +256,26 @@ describe("ShareNext", () => { }) return Effect.gen(function* () { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const share = yield* ShareNext.Service const session = yield* Session.Service const info = yield* session.create({ title: "first" }) yield* share.init() yield* Effect.sleep(50) - yield* Effect.sync(() => - Database.use((db) => - db - .insert(SessionShareTable) - .values({ - session_id: info.id, - id: "shr_abc", - url: "https://legacy-share.example.com/share/abc", - secret: "sec_123", - }) - .run(), - ), - ) - - yield* bus.publish(Session.Event.Diff, { + const { db } = yield* Database.Service + yield* db + .insert(SessionShareTable) + .values({ + session_id: info.id, + id: "shr_abc", + url: "https://legacy-share.example.com/share/abc", + secret: "sec_123", + }) + .run() + .pipe(Effect.orDie) + + yield* events.publish(Session.Event.Diff, { sessionID: info.id, diff: [ { @@ -279,7 +288,7 @@ describe("ShareNext", () => { }, ], }) - yield* bus.publish(Session.Event.Diff, { + yield* events.publish(Session.Event.Diff, { sessionID: info.id, diff: [ { diff --git a/packages/opencode/test/skill/skill.test.ts b/packages/opencode/test/skill/skill.test.ts index fc1f6bff6ae7..e078b5eaf49f 100644 --- a/packages/opencode/test/skill/skill.test.ts +++ b/packages/opencode/test/skill/skill.test.ts @@ -3,30 +3,31 @@ import { Effect, Layer } from "effect" import { Skill } from "../../src/skill" import { Discovery } from "../../src/skill/discovery" import { RuntimeFlags } from "../../src/effect/runtime-flags" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Config } from "../../src/config/config" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Global } from "@opencode-ai/core/global" -import { provideInstance, provideTmpdirInstance, tmpdir } from "../fixture/fixture" +import { provideInstance, provideTmpdirInstance, testInstanceStoreLayer, tmpdir } from "../fixture/fixture" import { testEffect } from "../lib/effect" import path from "path" import fs from "fs/promises" const node = CrossSpawnSpawner.defaultLayer -const it = testEffect(Layer.mergeAll(Skill.defaultLayer, node)) +const it = testEffect(Layer.mergeAll(Skill.defaultLayer, node, testInstanceStoreLayer)) const itWithoutClaudeCodeSkills = testEffect( Layer.mergeAll( Skill.layer.pipe( Layer.provide(Discovery.defaultLayer), Layer.provide(Config.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(Global.layer), Layer.provide(RuntimeFlags.layer({ disableClaudeCodeSkills: true })), ), node, + testInstanceStoreLayer, ), ) const itWithoutExternalSkills = testEffect( @@ -34,12 +35,13 @@ const itWithoutExternalSkills = testEffect( Skill.layer.pipe( Layer.provide(Discovery.defaultLayer), Layer.provide(Config.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), Layer.provide(Global.layer), Layer.provide(RuntimeFlags.layer({ disableExternalSkills: true })), ), node, + testInstanceStoreLayer, ), ) diff --git a/packages/opencode/test/snapshot/snapshot.test.ts b/packages/opencode/test/snapshot/snapshot.test.ts index 8b4219195243..b71577334dc8 100644 --- a/packages/opencode/test/snapshot/snapshot.test.ts +++ b/packages/opencode/test/snapshot/snapshot.test.ts @@ -6,10 +6,16 @@ import fs from "fs/promises" import path from "path" import { Effect, Fiber, Layer } from "effect" import { Snapshot } from "../../src/snapshot" -import { disposeAllInstances, provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture" +import { + disposeAllInstances, + provideInstance, + testInstanceStoreLayer, + TestInstance, + tmpdirScoped, +} from "../fixture/fixture" import { testEffect } from "../lib/effect" -const it = testEffect(Layer.mergeAll(Snapshot.defaultLayer, AppFileSystem.defaultLayer)) +const it = testEffect(Layer.mergeAll(Snapshot.defaultLayer, AppFileSystem.defaultLayer, testInstanceStoreLayer)) // Git always outputs /-separated paths internally. Snapshot.patch() joins them // with path.join (which produces \ on Windows) then normalizes back to /. diff --git a/packages/opencode/test/storage/db.test.ts b/packages/opencode/test/storage/db.test.ts deleted file mode 100644 index ba7f0912aa9f..000000000000 --- a/packages/opencode/test/storage/db.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, expect } from "bun:test" -import path from "path" -import { Effect } from "effect" -import { Global } from "@opencode-ai/core/global" -import { InstallationChannel } from "@opencode-ai/core/installation/version" -import { RuntimeFlags } from "@/effect/runtime-flags" -import { Database } from "@/storage/db" -import { it } from "../lib/effect" - -describe("Database.getChannelPath", () => { - it.effect("returns database path for the current channel", () => - Effect.gen(function* () { - const flags = yield* RuntimeFlags.Service - const expected = ["latest", "beta", "prod"].includes(InstallationChannel) - ? path.join(Global.Path.data, "opencode.db") - : path.join(Global.Path.data, `opencode-${InstallationChannel.replace(/[^a-zA-Z0-9._-]/g, "-")}.db`) - - expect(Database.getChannelPath(flags)).toBe(expected) - }).pipe(Effect.provide(RuntimeFlags.layer())), - ) - - it.effect("uses the shared database path when channel databases are disabled", () => - Effect.gen(function* () { - const flags = yield* RuntimeFlags.Service - - expect(Database.getChannelPath(flags)).toBe(path.join(Global.Path.data, "opencode.db")) - }).pipe(Effect.provide(RuntimeFlags.layer({ disableChannelDb: true }))), - ) - - it.effect("accepts RuntimeFlags with skipMigrations for database callers", () => - Effect.gen(function* () { - const flags = yield* RuntimeFlags.Service - - expect(flags.skipMigrations).toBe(true) - expect(Database.getChannelPath(flags)).toBe(Database.getChannelPath({ disableChannelDb: flags.disableChannelDb })) - }).pipe(Effect.provide(RuntimeFlags.layer({ skipMigrations: true }))), - ) -}) diff --git a/packages/opencode/test/storage/json-migration.test.ts b/packages/opencode/test/storage/json-migration.test.ts index 598a635cd4ab..0ac2f2c5961d 100644 --- a/packages/opencode/test/storage/json-migration.test.ts +++ b/packages/opencode/test/storage/json-migration.test.ts @@ -4,13 +4,13 @@ import { drizzle, SQLiteBunDatabase } from "drizzle-orm/bun-sqlite" import { migrate } from "drizzle-orm/bun-sqlite/migrator" import path from "path" import fs from "fs/promises" -import { readFileSync, readdirSync } from "fs" +import { existsSync, readFileSync, readdirSync } from "fs" import { JsonMigration } from "@/storage/json-migration" import { Global } from "@opencode-ai/core/global" -import { ProjectTable } from "../../src/project/project.sql" -import { ProjectID } from "../../src/project/schema" -import { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "../../src/session/session.sql" -import { SessionShareTable } from "../../src/share/share.sql" +import { ProjectTable } from "@opencode-ai/core/project/sql" +import { ProjectV2 } from "@opencode-ai/core/project" +import { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "@opencode-ai/core/session/sql" +import { SessionShareTable } from "@opencode-ai/core/share/sql" import { SessionID, MessageID, PartID } from "../../src/session/schema" // Test fixtures @@ -79,10 +79,10 @@ function createTestDb() { sqlite.exec("PRAGMA foreign_keys = ON") // Apply schema migrations using drizzle migrate - const dir = path.join(import.meta.dirname, "../../migration") + const dir = path.join(import.meta.dirname, "../../../core/migration") const entries = readdirSync(dir, { withFileTypes: true }) const migrations = entries - .filter((entry) => entry.isDirectory()) + .filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, "migration.sql"))) .map((entry) => ({ sql: readFileSync(path.join(dir, entry.name, "migration.sql"), "utf-8"), timestamp: Number(entry.name.split("_")[0]), @@ -127,7 +127,7 @@ describe("JSON to SQLite migration", () => { const projects = db.select().from(ProjectTable).all() expect(projects.length).toBe(1) - expect(projects[0].id).toBe(ProjectID.make("proj_test123abc")) + expect(projects[0].id).toBe(ProjectV2.ID.make("proj_test123abc")) expect(projects[0].worktree).toBe("/test/path") expect(projects[0].name).toBe("Test Project") expect(projects[0].sandboxes).toEqual(["/test/sandbox"]) @@ -151,7 +151,7 @@ describe("JSON to SQLite migration", () => { const projects = db.select().from(ProjectTable).all() expect(projects.length).toBe(1) - expect(projects[0].id).toBe(ProjectID.make("proj_filename")) // Uses filename, not JSON id + expect(projects[0].id).toBe(ProjectV2.ID.make("proj_filename")) // Uses filename, not JSON id }) test("migrates project with commands", async () => { @@ -171,7 +171,7 @@ describe("JSON to SQLite migration", () => { const projects = db.select().from(ProjectTable).all() expect(projects.length).toBe(1) - expect(projects[0].id).toBe(ProjectID.make("proj_with_commands")) + expect(projects[0].id).toBe(ProjectV2.ID.make("proj_with_commands")) expect(projects[0].commands).toEqual({ start: "npm run dev" }) }) @@ -191,7 +191,7 @@ describe("JSON to SQLite migration", () => { const projects = db.select().from(ProjectTable).all() expect(projects.length).toBe(1) - expect(projects[0].id).toBe(ProjectID.make("proj_no_commands")) + expect(projects[0].id).toBe(ProjectV2.ID.make("proj_no_commands")) expect(projects[0].commands).toBeNull() }) @@ -220,7 +220,7 @@ describe("JSON to SQLite migration", () => { const sessions = db.select().from(SessionTable).all() expect(sessions.length).toBe(1) expect(sessions[0].id).toBe(SessionID.make("ses_test456def")) - expect(sessions[0].project_id).toBe(ProjectID.make("proj_test123abc")) + expect(sessions[0].project_id).toBe(ProjectV2.ID.make("proj_test123abc")) expect(sessions[0].slug).toBe("test-session") expect(sessions[0].title).toBe("Test Session Title") expect(sessions[0].summary_additions).toBe(10) @@ -421,7 +421,7 @@ describe("JSON to SQLite migration", () => { const sessions = db.select().from(SessionTable).all() expect(sessions.length).toBe(1) expect(sessions[0].id).toBe(SessionID.make("ses_migrated")) - expect(sessions[0].project_id).toBe(ProjectID.make(gitBasedProjectID)) // Uses directory, not stale JSON + expect(sessions[0].project_id).toBe(ProjectV2.ID.make(gitBasedProjectID)) // Uses directory, not stale JSON }) test("uses filename for session id when JSON has different value", async () => { @@ -452,7 +452,7 @@ describe("JSON to SQLite migration", () => { const sessions = db.select().from(SessionTable).all() expect(sessions.length).toBe(1) expect(sessions[0].id).toBe(SessionID.make("ses_from_filename")) // Uses filename, not JSON id - expect(sessions[0].project_id).toBe(ProjectID.make("proj_test123abc")) + expect(sessions[0].project_id).toBe(ProjectV2.ID.make("proj_test123abc")) }) test("is idempotent (running twice doesn't duplicate)", async () => { @@ -631,7 +631,7 @@ describe("JSON to SQLite migration", () => { const projects = db.select().from(ProjectTable).all() expect(projects.length).toBe(1) - expect(projects[0].id).toBe(ProjectID.make("proj_test123abc")) + expect(projects[0].id).toBe(ProjectV2.ID.make("proj_test123abc")) }) test("skips invalid todo entries while preserving source positions", async () => { diff --git a/packages/opencode/test/storage/workspace-time-migration.test.ts b/packages/opencode/test/storage/workspace-time-migration.test.ts index 2d30646976f1..a33d6d5e5ac4 100644 --- a/packages/opencode/test/storage/workspace-time-migration.test.ts +++ b/packages/opencode/test/storage/workspace-time-migration.test.ts @@ -2,18 +2,25 @@ import { describe, expect, test } from "bun:test" import { Database } from "bun:sqlite" import { drizzle } from "drizzle-orm/bun-sqlite" import { migrate } from "drizzle-orm/bun-sqlite/migrator" -import { readFileSync, readdirSync } from "fs" +import { existsSync, readFileSync, readdirSync } from "fs" import path from "path" const target = "20260507164347_add_workspace_time" function migrations() { - return readdirSync(path.join(import.meta.dirname, "../../migration"), { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) + return readdirSync(path.join(import.meta.dirname, "../../../core/migration"), { withFileTypes: true }) + .filter( + (entry) => + entry.isDirectory() && + existsSync(path.join(import.meta.dirname, "../../../core/migration", entry.name, "migration.sql")), + ) .map((entry) => ({ name: entry.name, timestamp: Number(entry.name.split("_")[0]), - sql: readFileSync(path.join(import.meta.dirname, "../../migration", entry.name, "migration.sql"), "utf-8"), + sql: readFileSync( + path.join(import.meta.dirname, "../../../core/migration", entry.name, "migration.sql"), + "utf-8", + ), })) .sort((a, b) => a.timestamp - b.timestamp) } diff --git a/packages/opencode/test/sync/index.test.ts b/packages/opencode/test/sync/index.test.ts deleted file mode 100644 index e3307d2aec99..000000000000 --- a/packages/opencode/test/sync/index.test.ts +++ /dev/null @@ -1,390 +0,0 @@ -import { describe, expect, beforeEach, afterAll } from "bun:test" -import { provideTmpdirInstance } from "../fixture/fixture" -import { Deferred, Effect, Layer, Schema } from "effect" -import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { Bus } from "../../src/bus" -import { GlobalBus, type GlobalEvent } from "../../src/bus/global" -import { SyncEvent } from "../../src/sync" -import { Database, eq } from "@/storage/db" -import { EventSequenceTable, EventTable } from "../../src/sync/event.sql" -import { MessageID } from "../../src/session/schema" -import { initProjectors } from "../../src/server/projectors" -import { awaitWithTimeout, testEffect } from "../lib/effect" -import { RuntimeFlags } from "@/effect/runtime-flags" - -const it = testEffect( - Layer.mergeAll( - SyncEvent.layer.pipe( - Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: true })), - Layer.provideMerge(Bus.layer), - ), - CrossSpawnSpawner.defaultLayer, - ), -) - -beforeEach(() => { - Database.close() -}) - -describe("SyncEvent", () => { - function setup() { - SyncEvent.reset() - - const Created = SyncEvent.define({ - type: "item.created", - version: 1, - aggregate: "id", - schema: Schema.Struct({ id: Schema.String, name: Schema.String }), - }) - const Sent = SyncEvent.define({ - type: "item.sent", - version: 1, - aggregate: "item_id", - schema: Schema.Struct({ item_id: Schema.String, to: Schema.String }), - }) - - SyncEvent.init({ - projectors: [SyncEvent.project(Created, () => {}), SyncEvent.project(Sent, () => {})], - }) - - return { Created, Sent } - } - - function expectDefect(effect: Effect.Effect, pattern: RegExp) { - return Effect.gen(function* () { - const exit = yield* Effect.exit(effect) - if (exit._tag === "Success") throw new Error("Expected effect to fail") - expect(String(exit.cause)).toMatch(pattern) - }) - } - - afterAll(() => { - SyncEvent.reset() - initProjectors() - }) - - describe("run", () => { - it.live( - "inserts event row", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - yield* SyncEvent.use.run(Created, { id: "evt_1", name: "first" }) - const rows = Database.use((db) => db.select().from(EventTable).all()) - expect(rows).toHaveLength(1) - expect(rows[0].type).toBe("item.created.1") - expect(rows[0].aggregate_id).toBe("evt_1") - }), - ), - ) - - it.live( - "increments seq per aggregate", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - yield* SyncEvent.use.run(Created, { id: "evt_1", name: "first" }) - yield* SyncEvent.use.run(Created, { id: "evt_1", name: "second" }) - const rows = Database.use((db) => db.select().from(EventTable).all()) - expect(rows).toHaveLength(2) - expect(rows[1].seq).toBe(rows[0].seq + 1) - }), - ), - ) - - it.live( - "uses custom aggregate field from agg()", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Sent } = setup() - yield* SyncEvent.use.run(Sent, { item_id: "evt_1", to: "james" }) - const rows = Database.use((db) => db.select().from(EventTable).all()) - expect(rows).toHaveLength(1) - expect(rows[0].aggregate_id).toBe("evt_1") - }), - ), - ) - - it.live( - "emits events", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - const events: Array<{ - type: string - properties: { id: string; name: string } - }> = [] - let resolve = () => {} - const received = new Promise((done) => { - resolve = done - }) - const bus = yield* Bus.Service - const dispose = yield* bus.subscribeAllCallback((event) => { - events.push(event) - resolve() - }) - try { - yield* SyncEvent.use.run(Created, { id: "evt_1", name: "test" }) - yield* Effect.promise(() => received) - expect(events).toHaveLength(1) - expect(events[0]).toMatchObject({ - type: "item.created", - properties: { - id: "evt_1", - name: "test", - }, - }) - } finally { - dispose() - } - }), - ), - ) - - // Regression for the EffectBridge migration. GlobalBus.emit used to fire - // synchronously inside the Database.effect post-commit callback. After the - // migration it fires inside the forked publish Effect, AFTER bus.publish - // completes. Consumers don't care about microsecond-level ordering, but - // we still need to prove the emit actually fires. - it.live( - "emits sync events to GlobalBus after publishing to ProjectBus", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - // Filter for OUR specific event in the handler so we ignore any - // stray sync events from other tests' lingering forks. - const received = yield* Deferred.make() - const handler = (evt: GlobalEvent) => { - if (evt.payload?.type === "sync" && evt.payload?.syncEvent?.type === "item.created.1") { - Deferred.doneUnsafe(received, Effect.succeed(evt)) - } - } - GlobalBus.on("event", handler) - try { - yield* SyncEvent.use.run(Created, { id: "evt_global_1", name: "global" }) - const event = yield* awaitWithTimeout( - Deferred.await(received), - "timed out waiting for sync event on GlobalBus", - "2 seconds", - ) - expect(event.payload).toMatchObject({ - type: "sync", - syncEvent: { type: "item.created.1", data: { id: "evt_global_1", name: "global" } }, - }) - } finally { - GlobalBus.off("event", handler) - } - }), - ), - ) - }) - - describe("replay", () => { - it.live( - "inserts event from external payload", - provideTmpdirInstance(() => - Effect.gen(function* () { - const id = MessageID.ascending() - yield* SyncEvent.use.replay({ - id: "evt_1", - type: "item.created.1", - seq: 0, - aggregateID: id, - data: { id, name: "replayed" }, - }) - const rows = Database.use((db) => db.select().from(EventTable).all()) - expect(rows).toHaveLength(1) - expect(rows[0].aggregate_id).toBe(id) - }), - ), - ) - - it.live( - "throws on sequence mismatch", - provideTmpdirInstance(() => - Effect.gen(function* () { - const id = MessageID.ascending() - yield* SyncEvent.use.replay({ - id: "evt_1", - type: "item.created.1", - seq: 0, - aggregateID: id, - data: { id, name: "first" }, - }) - yield* expectDefect( - SyncEvent.use.replay({ - id: "evt_1", - type: "item.created.1", - seq: 5, - aggregateID: id, - data: { id, name: "bad" }, - }), - /Sequence mismatch/, - ) - }), - ), - ) - - it.live( - "throws on unknown event type", - provideTmpdirInstance(() => - Effect.gen(function* () { - yield* expectDefect( - SyncEvent.use.replay({ - id: "evt_1", - type: "unknown.event.1", - seq: 0, - aggregateID: "x", - data: {}, - }), - /Unknown event type/, - ) - }), - ), - ) - - it.live( - "replayAll accepts later chunks after the first batch", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - const id = MessageID.ascending() - - const one = yield* SyncEvent.use.replayAll([ - { - id: "evt_1", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 0, - aggregateID: id, - data: { id, name: "first" }, - }, - { - id: "evt_2", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 1, - aggregateID: id, - data: { id, name: "second" }, - }, - ]) - - const two = yield* SyncEvent.use.replayAll([ - { - id: "evt_3", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 2, - aggregateID: id, - data: { id, name: "third" }, - }, - { - id: "evt_4", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 3, - aggregateID: id, - data: { id, name: "fourth" }, - }, - ]) - - expect(one).toBe(id) - expect(two).toBe(id) - - const rows = Database.use((db) => db.select().from(EventTable).all()) - expect(rows.map((row) => row.seq)).toEqual([0, 1, 2, 3]) - }), - ), - ) - - it.live( - "claims unowned event sequence on replay with ownerID", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - const id = MessageID.ascending() - - yield* SyncEvent.use.replay( - { - id: "evt_1", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 0, - aggregateID: id, - data: { id, name: "owned" }, - }, - { publish: false, ownerID: "owner-1" }, - ) - - const row = Database.use((db) => - db - .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) - .from(EventSequenceTable) - .get(), - ) - expect(row).toEqual({ seq: 0, ownerID: "owner-1" }) - }), - ), - ) - - it.live( - "ignores replay from a different owner after sequence is claimed", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - const id = MessageID.ascending() - - yield* SyncEvent.use.replay( - { - id: "evt_1", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 0, - aggregateID: id, - data: { id, name: "first" }, - }, - { publish: false, ownerID: "owner-1" }, - ) - yield* SyncEvent.use.replay( - { - id: "evt_2", - type: SyncEvent.versionedType(Created.type, Created.version), - seq: 1, - aggregateID: id, - data: { id, name: "ignored" }, - }, - { publish: false, ownerID: "owner-2" }, - ) - - const events = Database.use((db) => db.select().from(EventTable).all()) - const sequence = Database.use((db) => - db - .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) - .from(EventSequenceTable) - .get(), - ) - expect(events).toHaveLength(1) - expect(events[0].id).toBe("evt_1") - expect(sequence).toEqual({ seq: 0, ownerID: "owner-1" }) - }), - ), - ) - - it.live( - "claim updates the event sequence owner", - provideTmpdirInstance(() => - Effect.gen(function* () { - const { Created } = setup() - const id = MessageID.ascending() - - yield* SyncEvent.use.run(Created, { id, name: "claimed" }, { publish: false }) - yield* SyncEvent.use.claim(id, "owner-1") - yield* SyncEvent.use.claim(id, "owner-2") - - const row = Database.use((db) => - db - .select({ seq: EventSequenceTable.seq, ownerID: EventSequenceTable.owner_id }) - .from(EventSequenceTable) - .where(eq(EventSequenceTable.aggregate_id, id)) - .get(), - ) - expect(row).toEqual({ seq: 0, ownerID: "owner-2" }) - }), - ), - ) - }) -}) diff --git a/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap b/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap index 9fede8175929..0bf2357eff81 100644 --- a/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap +++ b/packages/opencode/test/tool/__snapshots__/parameters.test.ts.snap @@ -320,7 +320,7 @@ exports[`tool parameters JSON Schema (wire shape) task 1`] = ` "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "background": { - "description": "When true, launch the subagent in the background and return immediately", + "description": "Run the agent in the background. You will be notified when it completes.", "type": "boolean", }, "command": { @@ -396,21 +396,14 @@ exports[`tool parameters JSON Schema (wire shape) webfetch 1`] = ` "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "format": { - "anyOf": [ - { - "default": "markdown", - "description": "The format to return the content in (text, markdown, or html). Defaults to markdown.", - "enum": [ - "text", - "markdown", - "html", - ], - "type": "string", - }, - { - "type": "null", - }, + "default": "markdown", + "description": "The format to return the content in (text, markdown, or html). Defaults to markdown.", + "enum": [ + "text", + "markdown", + "html", ], + "type": "string", }, "timeout": { "description": "Optional timeout in seconds (max 120)", diff --git a/packages/opencode/test/tool/apply_patch.test.ts b/packages/opencode/test/tool/apply_patch.test.ts index be5754f3b40d..01e326ec5d88 100644 --- a/packages/opencode/test/tool/apply_patch.test.ts +++ b/packages/opencode/test/tool/apply_patch.test.ts @@ -7,7 +7,7 @@ import { LSP } from "@/lsp/lsp" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Format } from "../../src/format" import { Agent } from "../../src/agent/agent" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Truncate } from "@/tool/truncate" import { TestInstance } from "../fixture/fixture" import { SessionID, MessageID } from "../../src/session/schema" @@ -18,7 +18,7 @@ const it = testEffect( LSP.defaultLayer, AppFileSystem.defaultLayer, Format.defaultLayer, - Bus.layer, + EventV2Bridge.defaultLayer, Truncate.defaultLayer, Agent.defaultLayer, ), diff --git a/packages/opencode/test/tool/edit.test.ts b/packages/opencode/test/tool/edit.test.ts index 3f644ed53dde..9abc33885bad 100644 --- a/packages/opencode/test/tool/edit.test.ts +++ b/packages/opencode/test/tool/edit.test.ts @@ -8,7 +8,7 @@ import { LSP } from "@/lsp/lsp" import { AppFileSystem } from "@opencode-ai/core/filesystem" import { Format } from "../../src/format" import { Agent } from "../../src/agent/agent" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Truncate } from "@/tool/truncate" import { SessionID, MessageID } from "../../src/session/schema" import * as Tool from "../../src/tool/tool" @@ -34,7 +34,7 @@ const layer = Layer.mergeAll( LSP.defaultLayer, AppFileSystem.defaultLayer, Format.defaultLayer, - Bus.layer, + EventV2Bridge.defaultLayer, Truncate.defaultLayer, Agent.defaultLayer, ) @@ -83,10 +83,13 @@ const makeDirectory = Effect.fn("EditToolTest.makeDirectory")(function* (p: stri }) const onceBus = Effect.fn("EditToolTest.onceBus")(function* (def: typeof FileWatcher.Event.Updated) { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const deferred = yield* Deferred.make() - const unsub = yield* bus.subscribeCallback(def, () => Effect.runSync(Deferred.succeed(deferred, undefined))) - yield* Effect.addFinalizer(() => Effect.sync(unsub)) + const unsub = yield* events.listen((event) => { + if (event.type === def.type) Deferred.doneUnsafe(deferred, Effect.void) + return Effect.void + }) + yield* Effect.addFinalizer(() => unsub) return deferred }) diff --git a/packages/opencode/test/tool/external-directory.test.ts b/packages/opencode/test/tool/external-directory.test.ts index e59caaa72087..06019001ff3d 100644 --- a/packages/opencode/test/tool/external-directory.test.ts +++ b/packages/opencode/test/tool/external-directory.test.ts @@ -5,7 +5,7 @@ import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import type { Tool } from "@/tool/tool" import { assertExternalDirectoryEffect } from "../../src/tool/external-directory" import { Filesystem } from "@/util/filesystem" -import { provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture" +import { TestInstance, tmpdirScoped } from "../fixture/fixture" import type { Permission } from "../../src/permission" import { SessionID, MessageID } from "../../src/session/schema" import { testEffect } from "../lib/effect" @@ -48,27 +48,26 @@ describe("tool.assertExternalDirectory", () => { }), ) - it.live("no-ops for paths inside the instance directory", () => - provideInstance("/tmp/project")( - Effect.gen(function* () { - const { requests, ctx } = makeCtx() + it.instance("no-ops for paths inside the instance directory", () => + Effect.gen(function* () { + const test = yield* TestInstance + const { requests, ctx } = makeCtx() - yield* assertExternalDirectoryEffect(ctx, path.join("/tmp/project", "file.txt")) + yield* assertExternalDirectoryEffect(ctx, path.join(test.directory, "file.txt")) - expect(requests.length).toBe(0) - }), - ), + expect(requests.length).toBe(0) + }), ) - it.live("asks with a single canonical glob", () => + it.instance("asks with a single canonical glob", () => Effect.gen(function* () { + const test = yield* TestInstance const { requests, ctx } = makeCtx() - const directory = "/tmp/project" - const target = "/tmp/outside/file.txt" + const target = path.join(path.dirname(test.directory), "outside", "file.txt") const expected = glob(path.join(path.dirname(target), "*")) - yield* provideInstance(directory)(assertExternalDirectoryEffect(ctx, target)) + yield* assertExternalDirectoryEffect(ctx, target) const req = requests.find((r) => r.permission === "external_directory") expect(req).toBeDefined() @@ -77,15 +76,15 @@ describe("tool.assertExternalDirectory", () => { }), ) - it.live("uses target directory when kind=directory", () => + it.instance("uses target directory when kind=directory", () => Effect.gen(function* () { + const test = yield* TestInstance const { requests, ctx } = makeCtx() - const directory = "/tmp/project" - const target = "/tmp/outside" + const target = path.join(path.dirname(test.directory), "outside") const expected = glob(path.join(target, "*")) - yield* provideInstance(directory)(assertExternalDirectoryEffect(ctx, target, { kind: "directory" })) + yield* assertExternalDirectoryEffect(ctx, target, { kind: "directory" }) const req = requests.find((r) => r.permission === "external_directory") expect(req).toBeDefined() @@ -95,15 +94,13 @@ describe("tool.assertExternalDirectory", () => { ) it.live("skips prompting when bypass=true", () => - provideInstance("/tmp/project")( - Effect.gen(function* () { - const { requests, ctx } = makeCtx() + Effect.gen(function* () { + const { requests, ctx } = makeCtx() - yield* assertExternalDirectoryEffect(ctx, "/tmp/outside/file.txt", { bypass: true }) + yield* assertExternalDirectoryEffect(ctx, "/tmp/outside/file.txt", { bypass: true }) - expect(requests.length).toBe(0) - }), - ), + expect(requests.length).toBe(0) + }), ) if (process.platform === "win32") { diff --git a/packages/opencode/test/tool/grep.test.ts b/packages/opencode/test/tool/grep.test.ts index 027d5201cb16..a8cf5c9a325c 100644 --- a/packages/opencode/test/tool/grep.test.ts +++ b/packages/opencode/test/tool/grep.test.ts @@ -4,7 +4,7 @@ import os from "os" import path from "path" import { Effect, Layer } from "effect" import { GrepTool } from "../../src/tool/grep" -import { provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture" +import { provideInstance, testInstanceStoreLayer, TestInstance, tmpdirScoped } from "../fixture/fixture" import { SessionID, MessageID } from "../../src/session/schema" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Global } from "@opencode-ai/core/global" @@ -42,6 +42,7 @@ const toolLayer = (flags: Partial = {}) => const it = testEffect(toolLayer()) const scout = testEffect(toolLayer({ experimentalScout: true })) +const rooted = testEffect(Layer.mergeAll(toolLayer(), testInstanceStoreLayer)) const ctx = { sessionID: SessionID.make("ses_test"), @@ -90,7 +91,7 @@ const git = Effect.fn("GrepToolTest.git")(function* (cwd: string, args: string[] }) describe("tool.grep", () => { - it.live("basic search", () => + rooted.live("basic search", () => Effect.gen(function* () { const info = yield* GrepTool const grep = yield* info.init() diff --git a/packages/opencode/test/tool/lsp.test.ts b/packages/opencode/test/tool/lsp.test.ts index 875edc1c05fe..c456ae6cc7ee 100644 --- a/packages/opencode/test/tool/lsp.test.ts +++ b/packages/opencode/test/tool/lsp.test.ts @@ -10,7 +10,7 @@ import { MessageID, SessionID } from "../../src/session/schema" import { Tool } from "@/tool/tool" import { Truncate } from "@/tool/truncate" import { LspTool } from "../../src/tool/lsp" -import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture" +import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { testEffect } from "../lib/effect" afterEach(async () => { @@ -98,89 +98,89 @@ const asks = () => { describe("tool.lsp", () => { describe("permission metadata", () => { - it.live("keeps cursor details for position-based operations", () => - provideTmpdirInstance( - (dir) => - Effect.gen(function* () { - const file = path.join(dir, "test.ts") - yield* put(file) - - const { items, next } = asks() - const result = yield* run({ operation: "goToDefinition", filePath: file, line: 3, character: 7 }, next) - const req = items.find((item) => item.permission === "lsp") - - expect(req).toBeDefined() - expect(req!.metadata).toEqual({ - operation: "goToDefinition", - filePath: file, - line: 3, - character: 7, - }) - expect(result.title).toBe("goToDefinition test.ts:3:7") - }), - { git: true }, - ), + it.instance( + "keeps cursor details for position-based operations", + () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const file = path.join(dir, "test.ts") + yield* put(file) + + const { items, next } = asks() + const result = yield* run({ operation: "goToDefinition", filePath: file, line: 3, character: 7 }, next) + const req = items.find((item) => item.permission === "lsp") + + expect(req).toBeDefined() + expect(req!.metadata).toEqual({ + operation: "goToDefinition", + filePath: file, + line: 3, + character: 7, + }) + expect(result.title).toBe("goToDefinition test.ts:3:7") + }), + { git: true }, ) - it.live("omits cursor details for documentSymbol", () => - provideTmpdirInstance( - (dir) => - Effect.gen(function* () { - const file = path.join(dir, "test.ts") - yield* put(file) - - const { items, next } = asks() - const result = yield* run({ operation: "documentSymbol", filePath: file, line: 3, character: 7 }, next) - const req = items.find((item) => item.permission === "lsp") - - expect(req).toBeDefined() - expect(req!.metadata).toEqual({ - operation: "documentSymbol", - filePath: file, - }) - expect(result.title).toBe("documentSymbol test.ts") - }), - { git: true }, - ), + it.instance( + "omits cursor details for documentSymbol", + () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const file = path.join(dir, "test.ts") + yield* put(file) + + const { items, next } = asks() + const result = yield* run({ operation: "documentSymbol", filePath: file, line: 3, character: 7 }, next) + const req = items.find((item) => item.permission === "lsp") + + expect(req).toBeDefined() + expect(req!.metadata).toEqual({ + operation: "documentSymbol", + filePath: file, + }) + expect(result.title).toBe("documentSymbol test.ts") + }), + { git: true }, ) - it.live("omits file and cursor details for workspaceSymbol", () => - provideTmpdirInstance( - (dir) => - Effect.gen(function* () { - workspaceSymbolQueries.length = 0 - const file = path.join(dir, "test.ts") - yield* put(file) - - const { items, next } = asks() - const result = yield* run({ operation: "workspaceSymbol", filePath: file, line: 3, character: 7 }, next) - const req = items.find((item) => item.permission === "lsp") - - expect(req).toBeDefined() - expect(req!.metadata).toEqual({ - operation: "workspaceSymbol", - }) - expect(result.title).toBe("workspaceSymbol") - }), - { git: true }, - ), + it.instance( + "omits file and cursor details for workspaceSymbol", + () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + workspaceSymbolQueries.length = 0 + const file = path.join(dir, "test.ts") + yield* put(file) + + const { items, next } = asks() + const result = yield* run({ operation: "workspaceSymbol", filePath: file, line: 3, character: 7 }, next) + const req = items.find((item) => item.permission === "lsp") + + expect(req).toBeDefined() + expect(req!.metadata).toEqual({ + operation: "workspaceSymbol", + }) + expect(result.title).toBe("workspaceSymbol") + }), + { git: true }, ) - it.live("passes workspaceSymbol query to LSP", () => - provideTmpdirInstance( - (dir) => - Effect.gen(function* () { - workspaceSymbolQueries.length = 0 - const file = path.join(dir, "test.ts") - yield* put(file) - - yield* run({ operation: "workspaceSymbol", filePath: file, line: 3, character: 7, query: "TestSymbol" }) - yield* run({ operation: "workspaceSymbol", filePath: file, line: 3, character: 7 }) - - expect(workspaceSymbolQueries).toEqual(["TestSymbol", ""]) - }), - { git: true }, - ), + it.instance( + "passes workspaceSymbol query to LSP", + () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + workspaceSymbolQueries.length = 0 + const file = path.join(dir, "test.ts") + yield* put(file) + + yield* run({ operation: "workspaceSymbol", filePath: file, line: 3, character: 7, query: "TestSymbol" }) + yield* run({ operation: "workspaceSymbol", filePath: file, line: 3, character: 7 }) + + expect(workspaceSymbolQueries).toEqual(["TestSymbol", ""]) + }), + { git: true }, ) }) }) diff --git a/packages/opencode/test/tool/parameters.test.ts b/packages/opencode/test/tool/parameters.test.ts index 3a124be81b0c..4e56c61d23c4 100644 --- a/packages/opencode/test/tool/parameters.test.ts +++ b/packages/opencode/test/tool/parameters.test.ts @@ -82,6 +82,13 @@ describe("tool parameters", () => { properties: { value: { minimum: Number.MIN_SAFE_INTEGER, maximum: Number.MAX_SAFE_INTEGER } }, }) }) + + test("does not expose defaulted optional keys as nullable", () => { + expect(toJsonSchema(WebFetch)).toMatchObject({ + properties: { format: { type: "string", enum: ["text", "markdown", "html"], default: "markdown" } }, + }) + expect(toJsonSchema(WebFetch).properties?.format).not.toHaveProperty("anyOf") + }) }) describe("apply_patch", () => { @@ -257,8 +264,15 @@ describe("tool parameters", () => { }) describe("webfetch", () => { - test("accepts url-only", () => { - expect(parse(WebFetch, { url: "https://example.com" }).url).toBe("https://example.com") + test("defaults omitted format to markdown", () => { + expect(parse(WebFetch, { url: "https://example.com" })).toEqual({ + url: "https://example.com", + format: "markdown", + }) + expect(parse(WebFetch, { url: "https://example.com", format: undefined })).toEqual({ + url: "https://example.com", + format: "markdown", + }) }) }) diff --git a/packages/opencode/test/tool/question.test.ts b/packages/opencode/test/tool/question.test.ts index 854c1f891148..0bbc58d44256 100644 --- a/packages/opencode/test/tool/question.test.ts +++ b/packages/opencode/test/tool/question.test.ts @@ -7,7 +7,7 @@ import { Agent } from "../../src/agent/agent" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Truncate } from "@/tool/truncate" import { testEffect } from "../lib/effect" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" const ctx = { sessionID: SessionID.make("ses_test-session"), @@ -22,7 +22,7 @@ const ctx = { const it = testEffect( Layer.mergeAll( - Question.layer.pipe(Layer.provideMerge(Bus.layer)), + Question.layer.pipe(Layer.provideMerge(EventV2Bridge.defaultLayer)), CrossSpawnSpawner.defaultLayer, Truncate.defaultLayer, Agent.defaultLayer, @@ -30,10 +30,13 @@ const it = testEffect( ) const pending = Effect.fn("QuestionToolTest.pending")(function* (question: Question.Interface) { - const bus = yield* Bus.Service + const events = yield* EventV2Bridge.Service const asked = yield* Queue.unbounded() - const off = yield* bus.subscribeCallback(Question.Event.Asked, () => Queue.offerUnsafe(asked, undefined)) - yield* Effect.addFinalizer(() => Effect.sync(off)) + const off = yield* events.listen((event) => { + if (event.type === Question.Event.Asked.type) Queue.offerUnsafe(asked, undefined) + return Effect.void + }) + yield* Effect.addFinalizer(() => off) for (;;) { const items = yield* question.list() diff --git a/packages/opencode/test/tool/read.test.ts b/packages/opencode/test/tool/read.test.ts index f8c656ccfb7a..b42bd80e71ff 100644 --- a/packages/opencode/test/tool/read.test.ts +++ b/packages/opencode/test/tool/read.test.ts @@ -15,7 +15,13 @@ import { ReadTool } from "../../src/tool/read" import { Truncate } from "@/tool/truncate" import { Tool } from "@/tool/tool" import { Filesystem } from "@/util/filesystem" -import { disposeAllInstances, provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture" +import { + disposeAllInstances, + provideInstance, + testInstanceStoreLayer, + TestInstance, + tmpdirScoped, +} from "../fixture/fixture" import { testEffect } from "../lib/effect" import { Reference } from "@/reference/reference" import { RepositoryCache } from "@/reference/repository-cache" @@ -55,8 +61,8 @@ const readLayer = (flags: Partial = {}) => Truncate.defaultLayer, ) -const it = testEffect(readLayer()) -const scout = testEffect(readLayer({ experimentalScout: true })) +const it = testEffect(Layer.mergeAll(readLayer(), testInstanceStoreLayer)) +const scout = testEffect(Layer.mergeAll(readLayer({ experimentalScout: true }), testInstanceStoreLayer)) const init = Effect.fn("ReadToolTest.init")(function* () { const info = yield* ReadTool diff --git a/packages/opencode/test/tool/registry.test.ts b/packages/opencode/test/tool/registry.test.ts index d3549e66f340..489a756d5607 100644 --- a/packages/opencode/test/tool/registry.test.ts +++ b/packages/opencode/test/tool/registry.test.ts @@ -4,6 +4,7 @@ import fs from "fs/promises" import { fileURLToPath, pathToFileURL } from "url" import { Effect, Layer, Result, Schema } from "effect" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" +import { Database } from "@opencode-ai/core/database/database" import { ToolRegistry } from "@/tool/registry" import { Tool } from "@/tool/tool" import { disposeAllInstances, TestInstance } from "../fixture/fixture" @@ -22,7 +23,7 @@ import { Provider } from "@/provider/provider" import { Git } from "@/git" import { LSP } from "@/lsp/lsp" import { Instruction } from "@/session/instruction" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { FetchHttpClient } from "effect/unstable/http" import { Format } from "@/format" import { Ripgrep } from "@/file/ripgrep" @@ -30,10 +31,11 @@ import * as Truncate from "@/tool/truncate" import { InstanceState } from "@/effect/instance-state" import { Reference } from "@/reference/reference" import { RepositoryCache } from "@/reference/repository-cache" -import { ProviderID, ModelID } from "@/provider/schema" + import { ToolJsonSchema } from "@/tool/json-schema" import { MessageID, SessionID } from "@/session/schema" import { RuntimeFlags } from "@/effect/runtime-flags" +import { ProviderV2 } from "@opencode-ai/core/provider" const node = CrossSpawnSpawner.defaultLayer const configLayer = TestConfig.layer({ @@ -62,10 +64,10 @@ const registryLayer = (opts: RegistryLayerOptions = {}) => Layer.provide(LSP.defaultLayer), Layer.provide(Instruction.defaultLayer), Layer.provide(AppFileSystem.defaultLayer), - Layer.provide(Bus.layer), + Layer.provide(EventV2Bridge.defaultLayer), Layer.provide(FetchHttpClient.layer), Layer.provide(Format.defaultLayer), - Layer.provide(node), + Layer.provide(Layer.mergeAll(node, Database.defaultLayer)), Layer.provide(Ripgrep.defaultLayer), Layer.provide(Truncate.defaultLayer), ) @@ -99,9 +101,6 @@ const it = testEffect(Layer.mergeAll(registryLayer(), node, Agent.defaultLayer)) const scout = testEffect( Layer.mergeAll(registryLayer({ flags: { experimentalScout: true } }), node, Agent.defaultLayer), ) -const background = testEffect( - Layer.mergeAll(registryLayer({ flags: { experimentalBackgroundSubagents: true } }), node, Agent.defaultLayer), -) const withBrokenPlugin = testEffect( Layer.mergeAll(registryLayer({ plugin: brokenPluginLayer }), node, Agent.defaultLayer), ) @@ -131,7 +130,7 @@ describe("tool.registry", () => { }), ) - it.instance("hides task_status unless experimental background subagents are enabled", () => + it.instance("does not expose task_status", () => Effect.gen(function* () { const registry = yield* ToolRegistry.Service const ids = yield* registry.ids() @@ -147,8 +146,8 @@ describe("tool.registry", () => { const build = yield* agent.get("build") if (!build) throw new Error("build agent not found") const task = (yield* registry.tools({ - providerID: ProviderID.opencode, - modelID: ModelID.make("test"), + providerID: ProviderV2.ID.opencode, + modelID: ProviderV2.ModelID.make("test"), agent: build, })).find((tool) => tool.id === "task") @@ -157,15 +156,6 @@ describe("tool.registry", () => { }), ) - background.instance("shows task_status when experimental background subagents are enabled", () => - Effect.gen(function* () { - const registry = yield* ToolRegistry.Service - const ids = yield* registry.ids() - - expect(ids).toContain("task_status") - }), - ) - it.instance("loads tools from .opencode/tool (singular)", () => Effect.gen(function* () { const test = yield* TestInstance @@ -334,8 +324,8 @@ describe("tool.registry", () => { const agents = yield* Agent.Service const promptTools = yield* registry.tools({ - providerID: ProviderID.opencode, - modelID: ModelID.make("test"), + providerID: ProviderV2.ID.opencode, + modelID: ProviderV2.ModelID.make("test"), agent: yield* agents.defaultInfo(), }) const promptTool = promptTools.find((tool) => tool.id === "sql") diff --git a/packages/opencode/test/tool/repo_clone.test.ts b/packages/opencode/test/tool/repo_clone.test.ts index 2d7c70efcfc8..8b0072bac483 100644 --- a/packages/opencode/test/tool/repo_clone.test.ts +++ b/packages/opencode/test/tool/repo_clone.test.ts @@ -11,7 +11,7 @@ import { MessageID, SessionID } from "../../src/session/schema" import { Truncate } from "../../src/tool/truncate" import { RepoCloneTool } from "../../src/tool/repo_clone" import { RepositoryCache } from "../../src/reference/repository-cache" -import { disposeAllInstances, provideTmpdirInstance, tmpdirScoped } from "../fixture/fixture" +import { disposeAllInstances, TestInstance, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" afterEach(async () => { @@ -80,166 +80,155 @@ const githubBase = (url: string, self: Effect.Effect) => ) describe("tool.repo_clone", () => { - it.live("clones a repo into the managed cache and reuses it on subsequent calls", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const fs = yield* AppFileSystem.Service - const source = yield* tmpdirScoped({ git: true }) - const remoteRoot = yield* tmpdirScoped() - const remoteDir = path.join(remoteRoot, "owner") - const remoteRepo = path.join(remoteDir, "repo.git") - - yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "v1\n")) - yield* git(source, ["add", "."]) - yield* git(source, ["commit", "-m", "add readme"]) - yield* fs.makeDirectory(remoteDir, { recursive: true }).pipe(Effect.orDie) - yield* git(remoteRoot, ["clone", "--bare", source, remoteRepo]) - - const tool = yield* init() - const cloned = yield* githubBase(`file://${remoteRoot}/`, tool.execute({ repository: "owner/repo" }, ctx)) - const cached = yield* githubBase( - `file://${remoteRoot}/`, - tool.execute({ repository: "https://github.com/owner/repo.git" }, ctx), - ) - - expect(cloned.metadata.status).toBe("cloned") - expect(cloned.metadata.localPath).toBe(path.join(Global.Path.repos, "github.com", "owner", "repo")) - expect(cached.metadata.status).toBe("cached") - expect(yield* fs.readFileString(path.join(cloned.metadata.localPath, "README.md"))).toBe("v1\n") - }), - ), + it.instance("clones a repo into the managed cache and reuses it on subsequent calls", () => + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + const source = yield* tmpdirScoped({ git: true }) + const remoteRoot = yield* tmpdirScoped() + const remoteDir = path.join(remoteRoot, "owner") + const remoteRepo = path.join(remoteDir, "repo.git") + + yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "v1\n")) + yield* git(source, ["add", "."]) + yield* git(source, ["commit", "-m", "add readme"]) + yield* fs.makeDirectory(remoteDir, { recursive: true }).pipe(Effect.orDie) + yield* git(remoteRoot, ["clone", "--bare", source, remoteRepo]) + + const tool = yield* init() + const cloned = yield* githubBase(`file://${remoteRoot}/`, tool.execute({ repository: "owner/repo" }, ctx)) + const cached = yield* githubBase( + `file://${remoteRoot}/`, + tool.execute({ repository: "https://github.com/owner/repo.git" }, ctx), + ) + + expect(cloned.metadata.status).toBe("cloned") + expect(cloned.metadata.localPath).toBe(path.join(Global.Path.repos, "github.com", "owner", "repo")) + expect(cached.metadata.status).toBe("cached") + expect(yield* fs.readFileString(path.join(cloned.metadata.localPath, "README.md"))).toBe("v1\n") + }), ) - it.live("refresh updates an existing cached clone", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const fs = yield* AppFileSystem.Service - const source = yield* tmpdirScoped({ git: true }) - const remoteRoot = yield* tmpdirScoped() - const remoteDir = path.join(remoteRoot, "owner") - const remoteRepo = path.join(remoteDir, "repo.git") - - yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "v1\n")) - yield* git(source, ["add", "."]) - yield* git(source, ["commit", "-m", "add readme"]) - yield* fs.makeDirectory(remoteDir, { recursive: true }).pipe(Effect.orDie) - yield* git(remoteRoot, ["clone", "--bare", source, remoteRepo]) - - const branch = yield* git(source, ["branch", "--show-current"]) - yield* git(source, ["remote", "add", "origin", remoteRepo]) - yield* git(source, ["push", "-u", "origin", `${branch}:${branch}`]) - - const tool = yield* init() - const first = yield* githubBase(`file://${remoteRoot}/`, tool.execute({ repository: "owner/repo" }, ctx)) - - yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "v2\n")) - yield* git(source, ["add", "."]) - yield* git(source, ["commit", "-m", "update readme"]) - yield* git(source, ["push", "origin", `${branch}:${branch}`]) - - const refreshed = yield* githubBase( - `file://${remoteRoot}/`, - tool.execute({ repository: "owner/repo", refresh: true }, ctx), - ) - - expect(first.metadata.status).toBe("cloned") - expect(refreshed.metadata.status).toBe("refreshed") - expect(yield* fs.readFileString(path.join(first.metadata.localPath, "README.md"))).toBe("v2\n") - }), - ), + it.instance("refresh updates an existing cached clone", () => + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + const source = yield* tmpdirScoped({ git: true }) + const remoteRoot = yield* tmpdirScoped() + const remoteDir = path.join(remoteRoot, "owner") + const remoteRepo = path.join(remoteDir, "repo.git") + + yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "v1\n")) + yield* git(source, ["add", "."]) + yield* git(source, ["commit", "-m", "add readme"]) + yield* fs.makeDirectory(remoteDir, { recursive: true }).pipe(Effect.orDie) + yield* git(remoteRoot, ["clone", "--bare", source, remoteRepo]) + + const branch = yield* git(source, ["branch", "--show-current"]) + yield* git(source, ["remote", "add", "origin", remoteRepo]) + yield* git(source, ["push", "-u", "origin", `${branch}:${branch}`]) + + const tool = yield* init() + const first = yield* githubBase(`file://${remoteRoot}/`, tool.execute({ repository: "owner/repo" }, ctx)) + + yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "v2\n")) + yield* git(source, ["add", "."]) + yield* git(source, ["commit", "-m", "update readme"]) + yield* git(source, ["push", "origin", `${branch}:${branch}`]) + + const refreshed = yield* githubBase( + `file://${remoteRoot}/`, + tool.execute({ repository: "owner/repo", refresh: true }, ctx), + ) + + expect(first.metadata.status).toBe("cloned") + expect(refreshed.metadata.status).toBe("refreshed") + expect(yield* fs.readFileString(path.join(first.metadata.localPath, "README.md"))).toBe("v2\n") + }), ) - it.live("clones a configured branch", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const fs = yield* AppFileSystem.Service - const source = yield* tmpdirScoped({ git: true }) - const remoteRoot = yield* tmpdirScoped() - const remoteDir = path.join(remoteRoot, "owner") - const remoteRepo = path.join(remoteDir, "repo.git") - - yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "main\n")) - yield* git(source, ["add", "."]) - yield* git(source, ["commit", "-m", "add readme"]) - yield* git(source, ["checkout", "-b", "docs"]) - yield* Effect.promise(() => Bun.write(path.join(source, "DOCS.md"), "docs\n")) - yield* git(source, ["add", "."]) - yield* git(source, ["commit", "-m", "add docs"]) - yield* fs.makeDirectory(remoteDir, { recursive: true }).pipe(Effect.orDie) - yield* git(remoteRoot, ["clone", "--bare", source, remoteRepo]) - - const tool = yield* init() - const result = yield* githubBase( - `file://${remoteRoot}/`, - tool.execute({ repository: "owner/repo", branch: "docs" }, ctx), - ) - - expect(result.metadata.status).toBe("cloned") - expect(result.metadata.branch).toBe("docs") - expect(yield* fs.readFileString(path.join(result.metadata.localPath, "DOCS.md"))).toBe("docs\n") - }), - ), + it.instance("clones a configured branch", () => + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + const source = yield* tmpdirScoped({ git: true }) + const remoteRoot = yield* tmpdirScoped() + const remoteDir = path.join(remoteRoot, "owner") + const remoteRepo = path.join(remoteDir, "repo.git") + + yield* Effect.promise(() => Bun.write(path.join(source, "README.md"), "main\n")) + yield* git(source, ["add", "."]) + yield* git(source, ["commit", "-m", "add readme"]) + yield* git(source, ["checkout", "-b", "docs"]) + yield* Effect.promise(() => Bun.write(path.join(source, "DOCS.md"), "docs\n")) + yield* git(source, ["add", "."]) + yield* git(source, ["commit", "-m", "add docs"]) + yield* fs.makeDirectory(remoteDir, { recursive: true }).pipe(Effect.orDie) + yield* git(remoteRoot, ["clone", "--bare", source, remoteRepo]) + + const tool = yield* init() + const result = yield* githubBase( + `file://${remoteRoot}/`, + tool.execute({ repository: "owner/repo", branch: "docs" }, ctx), + ) + + expect(result.metadata.status).toBe("cloned") + expect(result.metadata.branch).toBe("docs") + expect(yield* fs.readFileString(path.join(result.metadata.localPath, "DOCS.md"))).toBe("docs\n") + }), ) - it.live("rejects invalid repository inputs", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const tool = yield* init() - const inputs = [ - { repository: "not-a-repo", message: "git URL" }, - { repository: "git@github.com:../../../etc/passwd", message: "git URL" }, - { repository: "-u:foo/bar", message: "git URL" }, - { repository: pathToFileURL(path.join(_dir, "local.git")).href, message: "Local file" }, - ] - - yield* Effect.forEach( - inputs, - (input) => - Effect.gen(function* () { - const result = yield* tool.execute({ repository: input.repository }, ctx).pipe(Effect.exit) - - expect(Exit.isFailure(result)).toBe(true) - if (Exit.isFailure(result)) { - const error = Cause.squash(result.cause) - expect(error instanceof Error ? error.message : String(error)).toContain(input.message) - } - }), - { discard: true }, - ) - }), - ), + it.instance("rejects invalid repository inputs", () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const tool = yield* init() + const inputs = [ + { repository: "not-a-repo", message: "git URL" }, + { repository: "git@github.com:../../../etc/passwd", message: "git URL" }, + { repository: "-u:foo/bar", message: "git URL" }, + { repository: pathToFileURL(path.join(dir, "local.git")).href, message: "Local file" }, + ] + + yield* Effect.forEach( + inputs, + (input) => + Effect.gen(function* () { + const result = yield* tool.execute({ repository: input.repository }, ctx).pipe(Effect.exit) + + expect(Exit.isFailure(result)).toBe(true) + if (Exit.isFailure(result)) { + const error = Cause.squash(result.cause) + expect(error instanceof Error ? error.message : String(error)).toContain(input.message) + } + }), + { discard: true }, + ) + }), ) - it.live("rejects local file repository URLs", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const source = yield* tmpdirScoped({ git: true }) - const tool = yield* init() - const result = yield* tool.execute({ repository: pathToFileURL(source).href }, ctx).pipe(Effect.exit) - - expect(Exit.isFailure(result)).toBe(true) - if (Exit.isFailure(result)) { - const error = Cause.squash(result.cause) - expect(error instanceof Error ? error.message : String(error)).toContain("Local file") - } - }), - ), + it.instance("rejects local file repository URLs", () => + Effect.gen(function* () { + const source = yield* tmpdirScoped({ git: true }) + const tool = yield* init() + const result = yield* tool.execute({ repository: pathToFileURL(source).href }, ctx).pipe(Effect.exit) + + expect(Exit.isFailure(result)).toBe(true) + if (Exit.isFailure(result)) { + const error = Cause.squash(result.cause) + expect(error instanceof Error ? error.message : String(error)).toContain("Local file") + } + }), ) - it.live("rejects invalid branch inputs", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const tool = yield* init() - const result = yield* tool.execute({ repository: "owner/repo", branch: "bad..branch" }, ctx).pipe(Effect.exit) - - expect(Exit.isFailure(result)).toBe(true) - if (Exit.isFailure(result)) { - const error = Cause.squash(result.cause) - expect(error instanceof Error ? error.message : String(error)).toContain( - "Branch must contain only alphanumeric characters", - ) - } - }), - ), + it.instance("rejects invalid branch inputs", () => + Effect.gen(function* () { + const tool = yield* init() + const result = yield* tool.execute({ repository: "owner/repo", branch: "bad..branch" }, ctx).pipe(Effect.exit) + + expect(Exit.isFailure(result)).toBe(true) + if (Exit.isFailure(result)) { + const error = Cause.squash(result.cause) + expect(error instanceof Error ? error.message : String(error)).toContain( + "Branch must contain only alphanumeric characters", + ) + } + }), ) }) diff --git a/packages/opencode/test/tool/repo_overview.test.ts b/packages/opencode/test/tool/repo_overview.test.ts index c854e51a3fdc..953703919fba 100644 --- a/packages/opencode/test/tool/repo_overview.test.ts +++ b/packages/opencode/test/tool/repo_overview.test.ts @@ -9,7 +9,7 @@ import { Global } from "@opencode-ai/core/global" import { MessageID, SessionID } from "../../src/session/schema" import { Truncate } from "../../src/tool/truncate" import { RepoOverviewTool } from "../../src/tool/repo_overview" -import { disposeAllInstances, provideTmpdirInstance, tmpdirScoped } from "../fixture/fixture" +import { disposeAllInstances, TestInstance, tmpdirScoped } from "../fixture/fixture" import { testEffect } from "../lib/effect" afterEach(async () => { @@ -43,123 +43,114 @@ const init = Effect.fn("RepoOverviewToolTest.init")(function* () { }) describe("tool.repo_overview", () => { - it.live("summarizes a local repository path", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const repo = yield* tmpdirScoped({ git: true }) - const fs = yield* AppFileSystem.Service - yield* fs.writeWithDirs( - path.join(repo, "package.json"), - JSON.stringify( - { - name: "example-repo", - main: "dist/index.js", - module: "dist/index.mjs", - types: "dist/index.d.ts", - exports: { - ".": "./dist/index.js", - "./server": "./dist/server.js", - }, - bin: { - example: "./bin/example.js", - }, + it.instance("summarizes a local repository path", () => + Effect.gen(function* () { + const repo = yield* tmpdirScoped({ git: true }) + const fs = yield* AppFileSystem.Service + yield* fs.writeWithDirs( + path.join(repo, "package.json"), + JSON.stringify( + { + name: "example-repo", + main: "dist/index.js", + module: "dist/index.mjs", + types: "dist/index.d.ts", + exports: { + ".": "./dist/index.js", + "./server": "./dist/server.js", }, - null, - 2, - ), - ) - yield* fs.writeWithDirs(path.join(repo, "bun.lock"), "") - yield* fs.writeWithDirs(path.join(repo, "README.md"), "# Example\n") - yield* fs.writeWithDirs(path.join(repo, "src", "index.ts"), "export const value = 1\n") - - const tool = yield* init() - const result = yield* tool.execute({ path: repo }, ctx) - - expect(result.metadata.path).toBe(repo) - expect(result.metadata.ecosystems).toContain("Node.js") - expect(result.metadata.package_manager).toBe("bun") - expect(result.metadata.dependency_files).toEqual(expect.arrayContaining(["package.json", "bun.lock"])) - expect(result.metadata.entrypoints).toEqual( - expect.arrayContaining([ - "main: dist/index.js", - "module: dist/index.mjs", - "types: dist/index.d.ts", - "exports: .", - "exports: ./server", - "bin: example", - "file: src/index.ts", - ]), - ) - expect(result.output).toContain("Top-level structure:") - expect(result.output).toContain("src/") - expect(result.output).toContain("README.md") - }), - ), + bin: { + example: "./bin/example.js", + }, + }, + null, + 2, + ), + ) + yield* fs.writeWithDirs(path.join(repo, "bun.lock"), "") + yield* fs.writeWithDirs(path.join(repo, "README.md"), "# Example\n") + yield* fs.writeWithDirs(path.join(repo, "src", "index.ts"), "export const value = 1\n") + + const tool = yield* init() + const result = yield* tool.execute({ path: repo }, ctx) + + expect(result.metadata.path).toBe(repo) + expect(result.metadata.ecosystems).toContain("Node.js") + expect(result.metadata.package_manager).toBe("bun") + expect(result.metadata.dependency_files).toEqual(expect.arrayContaining(["package.json", "bun.lock"])) + expect(result.metadata.entrypoints).toEqual( + expect.arrayContaining([ + "main: dist/index.js", + "module: dist/index.mjs", + "types: dist/index.d.ts", + "exports: .", + "exports: ./server", + "bin: example", + "file: src/index.ts", + ]), + ) + expect(result.output).toContain("Top-level structure:") + expect(result.output).toContain("src/") + expect(result.output).toContain("README.md") + }), ) - it.live("resolves relative paths from the instance directory", () => - provideTmpdirInstance((dir) => - Effect.gen(function* () { - const fs = yield* AppFileSystem.Service - yield* fs.writeWithDirs(path.join(dir, "nested", "README.md"), "# Nested\n") + it.instance("resolves relative paths from the instance directory", () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const fs = yield* AppFileSystem.Service + yield* fs.writeWithDirs(path.join(dir, "nested", "README.md"), "# Nested\n") - const tool = yield* init() - const result = yield* tool.execute({ path: "nested" }, ctx) + const tool = yield* init() + const result = yield* tool.execute({ path: "nested" }, ctx) - expect(result.metadata.path).toBe(path.join(dir, "nested")) - expect(result.output).toContain("README.md") - }), - ), + expect(result.metadata.path).toBe(path.join(dir, "nested")) + expect(result.output).toContain("README.md") + }), ) - it.live("resolves a cached repository from repository shorthand", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const fs = yield* AppFileSystem.Service - const cached = path.join(Global.Path.repos, "github.com", "owner", "repo") - yield* fs.writeWithDirs(path.join(cached, "package.json"), JSON.stringify({ name: "cached-repo" }, null, 2)) - yield* fs.writeWithDirs(path.join(cached, "README.md"), "cached\n") - - const tool = yield* init() - const result = yield* tool.execute({ repository: "owner/repo" }, ctx) - - expect(result.metadata.path).toBe(cached) - expect(result.metadata.repository).toBe("owner/repo") - expect(result.output).toContain("Repository: owner/repo") - expect(result.output).toContain(`Path: ${cached}`) - }), - ), + it.instance("resolves a cached repository from repository shorthand", () => + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + const cached = path.join(Global.Path.repos, "github.com", "owner", "repo") + yield* fs.writeWithDirs(path.join(cached, "package.json"), JSON.stringify({ name: "cached-repo" }, null, 2)) + yield* fs.writeWithDirs(path.join(cached, "README.md"), "cached\n") + + const tool = yield* init() + const result = yield* tool.execute({ repository: "owner/repo" }, ctx) + + expect(result.metadata.path).toBe(cached) + expect(result.metadata.repository).toBe("owner/repo") + expect(result.output).toContain("Repository: owner/repo") + expect(result.output).toContain(`Path: ${cached}`) + }), ) - it.live("fails clearly when a repository is not cloned", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const tool = yield* init() - const result = yield* tool.execute({ repository: "missing/repo" }, ctx).pipe(Effect.exit) - - expect(Exit.isFailure(result)).toBe(true) - if (Exit.isFailure(result)) { - const error = Cause.squash(result.cause) - expect(error instanceof Error ? error.message : String(error)).toContain("Use repo_clone first") - } - }), - ), + it.instance("fails clearly when a repository is not cloned", () => + Effect.gen(function* () { + const tool = yield* init() + const result = yield* tool.execute({ repository: "missing/repo" }, ctx).pipe(Effect.exit) + + expect(Exit.isFailure(result)).toBe(true) + if (Exit.isFailure(result)) { + const error = Cause.squash(result.cause) + expect(error instanceof Error ? error.message : String(error)).toContain("Use repo_clone first") + } + }), ) - it.live("resolves cached repositories from host/path references", () => - provideTmpdirInstance((_dir) => - Effect.gen(function* () { - const fs = yield* AppFileSystem.Service - const cached = path.join(Global.Path.repos, "gitlab.com", "group", "repo") - yield* fs.writeWithDirs(path.join(cached, "README.md"), "cached\n") - - const tool = yield* init() - const result = yield* tool.execute({ repository: "gitlab.com/group/repo" }, ctx) - - expect(result.metadata.path).toBe(cached) - expect(result.metadata.repository).toBe("gitlab.com/group/repo") - expect(result.output).toContain("Repository: gitlab.com/group/repo") - }), - ), + it.instance("resolves cached repositories from host/path references", () => + Effect.gen(function* () { + const fs = yield* AppFileSystem.Service + const cached = path.join(Global.Path.repos, "gitlab.com", "group", "repo") + yield* fs.writeWithDirs(path.join(cached, "README.md"), "cached\n") + + const tool = yield* init() + const result = yield* tool.execute({ repository: "gitlab.com/group/repo" }, ctx) + + expect(result.metadata.path).toBe(cached) + expect(result.metadata.repository).toBe("gitlab.com/group/repo") + expect(result.output).toContain("Repository: gitlab.com/group/repo") + }), ) }) diff --git a/packages/opencode/test/tool/shell.test.ts b/packages/opencode/test/tool/shell.test.ts index ddaa5c2ec7b1..fb8f95882368 100644 --- a/packages/opencode/test/tool/shell.test.ts +++ b/packages/opencode/test/tool/shell.test.ts @@ -7,7 +7,7 @@ import { Config } from "@/config/config" import { Shell } from "../../src/shell/shell" import { ShellTool } from "../../src/tool/shell" import { Filesystem } from "@/util/filesystem" -import { provideInstance, tmpdirScoped } from "../fixture/fixture" +import { provideInstance, testInstanceStoreLayer, tmpdirScoped } from "../fixture/fixture" import type { Permission } from "../../src/permission" import { Agent } from "../../src/agent/agent" import { Truncate } from "@/tool/truncate" @@ -18,6 +18,7 @@ import { Plugin } from "../../src/plugin" import { testEffect } from "../lib/effect" import { Tool } from "@/tool/tool" import { RuntimeFlags } from "@/effect/runtime-flags" +import { InstanceStore } from "@/project/instance-store" const shellLayer = Layer.mergeAll( CrossSpawnSpawner.defaultLayer, @@ -27,10 +28,12 @@ const shellLayer = Layer.mergeAll( Config.defaultLayer, Agent.defaultLayer, RuntimeFlags.defaultLayer, + testInstanceStoreLayer, ) const it = testEffect(shellLayer) type ShellTestServices = | (typeof shellLayer extends Layer.Layer ? ROut : never) + | InstanceStore.Service | Scope.Scope const initShell = Effect.fn("ShellToolTest.init")(function* () { diff --git a/packages/opencode/test/tool/skill.test.ts b/packages/opencode/test/tool/skill.test.ts index 6732b42bbe2c..73f1ae1805ac 100644 --- a/packages/opencode/test/tool/skill.test.ts +++ b/packages/opencode/test/tool/skill.test.ts @@ -7,7 +7,7 @@ import type { Permission } from "../../src/permission" import type { Tool } from "@/tool/tool" import { SkillTool } from "../../src/tool/skill" import { ToolRegistry } from "@/tool/registry" -import { disposeAllInstances, provideTmpdirInstance } from "../fixture/fixture" +import { disposeAllInstances, TestInstance } from "../fixture/fixture" import { SessionID, MessageID } from "../../src/session/schema" import { testEffect } from "../lib/effect" @@ -30,14 +30,14 @@ const node = CrossSpawnSpawner.defaultLayer const it = testEffect(Layer.mergeAll(ToolRegistry.defaultLayer, node)) describe("tool.skill", () => { - it.live("execute returns skill content block with files", () => - provideTmpdirInstance((dir) => - Effect.gen(function* () { - const skill = path.join(dir, ".opencode", "skill", "tool-skill") - yield* Effect.promise(() => - Bun.write( - path.join(skill, "SKILL.md"), - `--- + it.instance("execute returns skill content block with files", () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const skill = path.join(dir, ".opencode", "skill", "tool-skill") + yield* Effect.promise(() => + Bun.write( + path.join(skill, "SKILL.md"), + `--- name: tool-skill description: Skill for tool tests. --- @@ -46,88 +46,86 @@ description: Skill for tool tests. Use this skill. `, - ), - ) - yield* Effect.promise(() => Bun.write(path.join(skill, "scripts", "demo.txt"), "demo")) - - const home = process.env.OPENCODE_TEST_HOME - process.env.OPENCODE_TEST_HOME = dir - yield* Effect.addFinalizer(() => + ), + ) + yield* Effect.promise(() => Bun.write(path.join(skill, "scripts", "demo.txt"), "demo")) + + const home = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = dir + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.env.OPENCODE_TEST_HOME = home + }), + ) + + const registry = yield* ToolRegistry.Service + const agent = { name: "build", mode: "primary" as const, permission: [], options: {} } + const tool = (yield* registry.tools({ + providerID: "opencode" as any, + modelID: "gpt-5" as any, + agent, + })).find((tool) => tool.id === SkillTool.id) + if (!tool) throw new Error("Skill tool not found") + + const requests: Array> = [] + const ctx: Tool.Context = { + ...baseCtx, + ask: (req) => Effect.sync(() => { - process.env.OPENCODE_TEST_HOME = home + requests.push(req) }), - ) - - const registry = yield* ToolRegistry.Service - const agent = { name: "build", mode: "primary" as const, permission: [], options: {} } - const tool = (yield* registry.tools({ - providerID: "opencode" as any, - modelID: "gpt-5" as any, - agent, - })).find((tool) => tool.id === SkillTool.id) - if (!tool) throw new Error("Skill tool not found") - - const requests: Array> = [] - const ctx: Tool.Context = { - ...baseCtx, - ask: (req) => - Effect.sync(() => { - requests.push(req) - }), - } - - const result = yield* tool.execute({ name: "tool-skill" }, ctx) - const file = path.resolve(skill, "scripts", "demo.txt") - - expect(requests.length).toBe(1) - expect(requests[0].permission).toBe("skill") - expect(requests[0].patterns).toContain("tool-skill") - expect(requests[0].always).toContain("tool-skill") - expect(result.metadata.dir).toBe(skill) - expect(result.output).toContain(``) - expect(result.output).toContain(`Base directory for this skill: ${pathToFileURL(skill).href}`) - expect(result.output).toContain(`${file}`) - }), - ), + } + + const result = yield* tool.execute({ name: "tool-skill" }, ctx) + const file = path.resolve(skill, "scripts", "demo.txt") + + expect(requests.length).toBe(1) + expect(requests[0].permission).toBe("skill") + expect(requests[0].patterns).toContain("tool-skill") + expect(requests[0].always).toContain("tool-skill") + expect(result.metadata.dir).toBe(skill) + expect(result.output).toContain(``) + expect(result.output).toContain(`Base directory for this skill: ${pathToFileURL(skill).href}`) + expect(result.output).toContain(`${file}`) + }), ) - it.live("execute preserves not found message", () => - provideTmpdirInstance((dir) => - Effect.gen(function* () { - const home = process.env.OPENCODE_TEST_HOME - process.env.OPENCODE_TEST_HOME = dir - yield* Effect.addFinalizer(() => - Effect.sync(() => { - process.env.OPENCODE_TEST_HOME = home - }), + it.instance("execute preserves not found message", () => + Effect.gen(function* () { + const dir = (yield* TestInstance).directory + const home = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = dir + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.env.OPENCODE_TEST_HOME = home + }), + ) + + const registry = yield* ToolRegistry.Service + const agent = { name: "build", mode: "primary" as const, permission: [], options: {} } + const tool = (yield* registry.tools({ + providerID: "opencode" as any, + modelID: "gpt-5" as any, + agent, + })).find((tool) => tool.id === SkillTool.id) + if (!tool) throw new Error("Skill tool not found") + + const exit = yield* tool + .execute( + { name: "missing-skill" }, + { + ...baseCtx, + ask: () => Effect.void, + }, ) - - const registry = yield* ToolRegistry.Service - const agent = { name: "build", mode: "primary" as const, permission: [], options: {} } - const tool = (yield* registry.tools({ - providerID: "opencode" as any, - modelID: "gpt-5" as any, - agent, - })).find((tool) => tool.id === SkillTool.id) - if (!tool) throw new Error("Skill tool not found") - - const exit = yield* tool - .execute( - { name: "missing-skill" }, - { - ...baseCtx, - ask: () => Effect.void, - }, - ) - .pipe(Effect.exit) - - expect(Exit.isFailure(exit)).toBe(true) - if (Exit.isFailure(exit)) { - const error = Cause.squash(exit.cause) - expect(error).toBeInstanceOf(Error) - if (error instanceof Error) expect(error.message).toContain('Skill "missing-skill" not found.') - } - }), - ), + .pipe(Effect.exit) + + expect(Exit.isFailure(exit)).toBe(true) + if (Exit.isFailure(exit)) { + const error = Cause.squash(exit.cause) + expect(error).toBeInstanceOf(Error) + if (error instanceof Error) expect(error.message).toContain('Skill "missing-skill" not found.') + } + }), ) }) diff --git a/packages/opencode/test/tool/task.test.ts b/packages/opencode/test/tool/task.test.ts index 2b7d001572a0..58391e0e3f7f 100644 --- a/packages/opencode/test/tool/task.test.ts +++ b/packages/opencode/test/tool/task.test.ts @@ -1,8 +1,10 @@ import { afterEach, describe, expect } from "bun:test" +import { SessionLegacy } from "@opencode-ai/core/session/legacy" +import { Database } from "@opencode-ai/core/database/database" import { Effect, Exit, Fiber, Layer } from "effect" import { Agent } from "../../src/agent/agent" import { BackgroundJob } from "@/background/job" -import { Bus } from "@/bus" +import { EventV2Bridge } from "@/event-v2-bridge" import { Config } from "@/config/config" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { Session } from "@/session/session" @@ -11,28 +13,29 @@ import type { SessionPrompt } from "../../src/session/prompt" import { MessageID, PartID, SessionID } from "../../src/session/schema" import { SessionRunState } from "@/session/run-state" import { SessionStatus } from "@/session/status" -import { ModelID, ProviderID } from "../../src/provider/schema" + import { TaskTool, type TaskPromptOps } from "../../src/tool/task" import { Truncate } from "@/tool/truncate" import { ToolRegistry } from "@/tool/registry" import { RuntimeFlags } from "@/effect/runtime-flags" import { disposeAllInstances } from "../fixture/fixture" import { testEffect } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" afterEach(async () => { await disposeAllInstances() }) const ref = { - providerID: ProviderID.make("test"), - modelID: ModelID.make("test-model"), + providerID: ProviderV2.ID.make("test"), + modelID: ProviderV2.ModelID.make("test-model"), } const layer = (flags: Partial = {}) => Layer.mergeAll( Agent.defaultLayer, BackgroundJob.defaultLayer, - Bus.defaultLayer, + EventV2Bridge.defaultLayer, Config.defaultLayer, CrossSpawnSpawner.defaultLayer, Session.defaultLayer, @@ -40,6 +43,7 @@ const layer = (flags: Partial = {}) => SessionStatus.defaultLayer, Truncate.defaultLayer, ToolRegistry.defaultLayer, + Database.defaultLayer, RuntimeFlags.layer(flags), ) @@ -65,7 +69,7 @@ const seed = Effect.fn("TaskToolTest.seed")(function* (title = "Pinned") { model: ref, time: { created: Date.now() }, }) - const assistant: MessageV2.Assistant = { + const assistant: SessionLegacy.Assistant = { id: MessageID.ascending(), role: "assistant", parentID: user.id, @@ -92,11 +96,10 @@ function stubOps(opts?: { onPrompt?: (input: SessionPrompt.PromptInput) => void; opts?.onPrompt?.(input) return reply(input, opts?.text ?? "done") }), - loop: (input) => Effect.succeed(reply({ sessionID: input.sessionID, parts: [] }, opts?.text ?? "done")), } } -function reply(input: SessionPrompt.PromptInput, text: string): MessageV2.WithParts { +function reply(input: SessionPrompt.PromptInput, text: string): SessionLegacy.WithParts { const id = MessageID.ascending() return { info: { @@ -237,7 +240,7 @@ describe("tool.task", () => { expect(kids).toHaveLength(1) expect(kids[0]?.id).toBe(child.id) expect(result.metadata.sessionId).toBe(child.id) - expect(result.output).toContain(`task_id: ${child.id}`) + expect(result.output).toContain(``) expect(seen?.sessionID).toBe(child.id) }), ) @@ -307,7 +310,6 @@ describe("tool.task", () => { ready.resolve(input) return cancelled.promise }).pipe(Effect.as(reply(input, "cancelled"))), - loop: (input) => Effect.succeed(reply({ sessionID: input.sessionID, parts: [] }, "done")), } const fiber = yield* def @@ -371,7 +373,7 @@ describe("tool.task", () => { expect(kids).toHaveLength(1) expect(kids[0]?.id).toBe(result.metadata.sessionId) expect(result.metadata.sessionId).not.toBe("ses_missing") - expect(result.output).toContain(`task_id: ${result.metadata.sessionId}`) + expect(result.output).toContain(``) expect(seen?.sessionID).toBe(result.metadata.sessionId) }), ) @@ -511,7 +513,7 @@ describe("tool.task", () => { const job = yield* jobs.get(result.metadata.sessionId) expect(result.metadata.background).toBe(true) - expect(result.output).toContain("state: running") + expect(result.output).toContain(`state="running"`) expect(job?.status).toBe("running") }), ) @@ -549,10 +551,9 @@ describe("tool.task", () => { }), ) - background.instance("background task completion does not wait for the parent resume loop", () => + background.instance("background task completion does not wait for the parent async prompt", () => Effect.gen(function* () { const jobs = yield* BackgroundJob.Service - const sessions = yield* Session.Service const { chat, assistant } = yield* seed() const tool = yield* TaskTool const def = yield* tool.init() @@ -573,27 +574,7 @@ describe("tool.task", () => { promptOps: { ...stubOps({ text: "background done" }), prompt: (input) => - input.noReply - ? Effect.gen(function* () { - const user = yield* sessions.updateMessage({ - id: input.messageID ?? MessageID.ascending(), - role: "user", - sessionID: input.sessionID, - agent: input.agent ?? "build", - model: input.model ?? ref, - time: { created: Date.now() }, - }) - const parts = input.parts.map((part) => ({ - ...part, - id: part.id ?? PartID.ascending(), - messageID: user.id, - sessionID: input.sessionID, - })) - yield* Effect.forEach(parts, (part) => sessions.updatePart(part), { discard: true }) - return { info: user, parts } - }) - : Effect.succeed(reply(input, "background done")), - loop: () => Effect.never, + input.sessionID === chat.id ? Effect.never : Effect.succeed(reply(input, "background done")), } satisfies TaskPromptOps, }, messages: [], diff --git a/packages/opencode/test/tool/task_status.test.ts b/packages/opencode/test/tool/task_status.test.ts deleted file mode 100644 index 23bd49c616c7..000000000000 --- a/packages/opencode/test/tool/task_status.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { afterEach, describe, expect } from "bun:test" -import { Effect, Layer } from "effect" -import { Agent } from "@/agent/agent" -import { BackgroundJob } from "@/background/job" -import { Bus } from "@/bus" -import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" -import { Session } from "@/session/session" -import { MessageID } from "@/session/schema" -import { SessionStatus } from "@/session/status" -import { TaskStatusTool } from "@/tool/task_status" -import { Truncate } from "@/tool/truncate" -import { RuntimeFlags } from "@/effect/runtime-flags" -import { disposeAllInstances } from "../fixture/fixture" -import { testEffect } from "../lib/effect" - -afterEach(async () => { - await disposeAllInstances() -}) - -const layer = (flags: Partial = {}) => - Layer.mergeAll( - Agent.defaultLayer, - BackgroundJob.defaultLayer, - Bus.defaultLayer, - CrossSpawnSpawner.defaultLayer, - Session.defaultLayer, - SessionStatus.defaultLayer, - Truncate.defaultLayer, - RuntimeFlags.layer(flags), - ) - -const it = testEffect(layer({ experimentalBackgroundSubagents: true })) - -describe("tool.task_status", () => { - it.instance("returns completed background job output", () => - Effect.gen(function* () { - const jobs = yield* BackgroundJob.Service - const sessions = yield* Session.Service - const tool = yield* TaskStatusTool - const def = yield* tool.init() - const chat = yield* sessions.create({}) - - yield* jobs.start({ id: chat.id, type: "task", run: Effect.succeed("all done") }) - - const result = yield* def.execute( - { task_id: chat.id, wait: true, timeout_ms: 1_000 }, - { - sessionID: chat.id, - messageID: MessageID.ascending(), - agent: "build", - abort: new AbortController().signal, - messages: [], - metadata: () => Effect.void, - ask: () => Effect.void, - }, - ) - - expect(result.output).toContain("state: completed") - expect(result.output).toContain("all done") - expect(result.metadata.timed_out).toBe(false) - }), - ) - - it.instance("wait=true times out while the background job is running", () => - Effect.gen(function* () { - const jobs = yield* BackgroundJob.Service - const sessions = yield* Session.Service - const tool = yield* TaskStatusTool - const def = yield* tool.init() - const chat = yield* sessions.create({}) - - yield* jobs.start({ id: chat.id, type: "task", run: Effect.never }) - - const result = yield* def.execute( - { task_id: chat.id, wait: true, timeout_ms: 50 }, - { - sessionID: chat.id, - messageID: MessageID.ascending(), - agent: "build", - abort: new AbortController().signal, - messages: [], - metadata: () => Effect.void, - ask: () => Effect.void, - }, - ) - - expect(result.output).toContain("state: running") - expect(result.output).toContain("Timed out after 50ms") - expect(result.metadata.timed_out).toBe(true) - }), - ) -}) diff --git a/packages/opencode/test/tool/websearch.test.ts b/packages/opencode/test/tool/websearch.test.ts index b8edc2dc2fd4..349606dec735 100644 --- a/packages/opencode/test/tool/websearch.test.ts +++ b/packages/opencode/test/tool/websearch.test.ts @@ -2,9 +2,10 @@ import { describe, expect, test } from "bun:test" import { Effect } from "effect" import { parseResponse } from "../../src/tool/mcp-websearch" import { selectWebSearchProvider, webSearchModelName, webSearchProviderLabel } from "../../src/tool/websearch" -import { ProviderID } from "../../src/provider/schema" + import { webSearchEnabled } from "../../src/tool/registry" import { it } from "../lib/effect" +import { ProviderV2 } from "@opencode-ai/core/provider" const SESSION_ID = "ses_0196aabbccddeeff001122334455" @@ -37,10 +38,10 @@ describe("websearch provider", () => { }) test("is only enabled for opencode or explicit websearch provider flags", () => { - expect(webSearchEnabled(ProviderID.opencode, { exa: false, parallel: false })).toBe(true) - expect(webSearchEnabled(ProviderID.openai, { exa: false, parallel: false })).toBe(false) - expect(webSearchEnabled(ProviderID.openai, { exa: true, parallel: false })).toBe(true) - expect(webSearchEnabled(ProviderID.openai, { exa: false, parallel: true })).toBe(true) + expect(webSearchEnabled(ProviderV2.ID.opencode, { exa: false, parallel: false })).toBe(true) + expect(webSearchEnabled(ProviderV2.ID.openai, { exa: false, parallel: false })).toBe(false) + expect(webSearchEnabled(ProviderV2.ID.openai, { exa: true, parallel: false })).toBe(true) + expect(webSearchEnabled(ProviderV2.ID.openai, { exa: false, parallel: true })).toBe(true) }) test("uses branded labels", () => { diff --git a/packages/opencode/test/tool/write.test.ts b/packages/opencode/test/tool/write.test.ts index 08f156092b18..6cc72f38334d 100644 --- a/packages/opencode/test/tool/write.test.ts +++ b/packages/opencode/test/tool/write.test.ts @@ -5,7 +5,7 @@ import fs from "fs/promises" import { WriteTool } from "../../src/tool/write" import { LSP } from "@/lsp/lsp" import { AppFileSystem } from "@opencode-ai/core/filesystem" -import { Bus } from "../../src/bus" +import { EventV2Bridge } from "../../src/event-v2-bridge" import { Format } from "../../src/format" import { Truncate } from "@/tool/truncate" import { Tool } from "@/tool/tool" @@ -34,7 +34,7 @@ const it = testEffect( Layer.mergeAll( LSP.defaultLayer, AppFileSystem.defaultLayer, - Bus.layer, + EventV2Bridge.defaultLayer, Format.defaultLayer, CrossSpawnSpawner.defaultLayer, Truncate.defaultLayer, diff --git a/packages/opencode/test/v2/session-message-updater.test.ts b/packages/opencode/test/v2/session-message-updater.test.ts index 588521281ce7..365a8af20f87 100644 --- a/packages/opencode/test/v2/session-message-updater.test.ts +++ b/packages/opencode/test/v2/session-message-updater.test.ts @@ -1,49 +1,54 @@ import { expect, test } from "bun:test" +import { Effect } from "effect" import * as DateTime from "effect/DateTime" import { SessionID } from "../../src/session/schema" import { EventV2 } from "@opencode-ai/core/event" import { ModelV2 } from "@opencode-ai/core/model" import { ProviderV2 } from "@opencode-ai/core/provider" -import { SessionEvent } from "@opencode-ai/core/session-event" -import { SessionMessageUpdater } from "@opencode-ai/core/session-message-updater" +import { SessionEvent } from "@opencode-ai/core/session/event" +import { SessionMessageUpdater } from "@opencode-ai/core/session/message-updater" -test("step snapshots carry over to assistant messages", () => { +test.skip("step snapshots carry over to assistant messages", () => { const state: SessionMessageUpdater.MemoryState = { messages: [] } const sessionID = SessionID.make("session") - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.step.started", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(1), - agent: "build", - model: { - id: ModelV2.ID.make("model"), - providerID: ProviderV2.ID.make("provider"), - variant: ModelV2.VariantID.make("default"), + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.step.started", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(1), + agent: "build", + model: { + id: ModelV2.ID.make("model"), + providerID: ProviderV2.ID.make("provider"), + variant: ModelV2.VariantID.make("default"), + }, + snapshot: "before", }, - snapshot: "before", - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.step.ended", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(2), - finish: "stop", - cost: 0, - tokens: { - input: 1, - output: 2, - reasoning: 0, - cache: { read: 0, write: 0 }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.step.ended", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(2), + finish: "stop", + cost: 0, + tokens: { + input: 1, + output: 2, + reasoning: 0, + cache: { read: 0, write: 0 }, + }, + snapshot: "after", }, - snapshot: "after", - }, - } satisfies SessionEvent.Event) + } satisfies SessionEvent.Event), + ) expect(state.messages[0]?.type).toBe("assistant") if (state.messages[0]?.type !== "assistant") return @@ -51,105 +56,119 @@ test("step snapshots carry over to assistant messages", () => { expect(state.messages[0].finish).toBe("stop") }) -test("text ended populates assistant text content", () => { +test.skip("text ended populates assistant text content", () => { const state: SessionMessageUpdater.MemoryState = { messages: [] } const sessionID = SessionID.make("session") - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.step.started", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(1), - agent: "build", - model: { - id: ModelV2.ID.make("model"), - providerID: ProviderV2.ID.make("provider"), - variant: ModelV2.VariantID.make("default"), + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.step.started", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(1), + agent: "build", + model: { + id: ModelV2.ID.make("model"), + providerID: ProviderV2.ID.make("provider"), + variant: ModelV2.VariantID.make("default"), + }, }, - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.text.started", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(2), - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.text.ended", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(3), - text: "hello assistant", - }, - } satisfies SessionEvent.Event) + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.text.started", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(2), + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.text.ended", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(3), + text: "hello assistant", + }, + } satisfies SessionEvent.Event), + ) expect(state.messages[0]?.type).toBe("assistant") if (state.messages[0]?.type !== "assistant") return expect(state.messages[0].content).toEqual([{ type: "text", text: "hello assistant" }]) }) -test("tool completion stores completed timestamp", () => { +test.skip("tool completion stores completed timestamp", () => { const state: SessionMessageUpdater.MemoryState = { messages: [] } const sessionID = SessionID.make("session") const callID = "call" - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.step.started", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(1), - agent: "build", - model: { - id: ModelV2.ID.make("model"), - providerID: ProviderV2.ID.make("provider"), - variant: ModelV2.VariantID.make("default"), + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.step.started", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(1), + agent: "build", + model: { + id: ModelV2.ID.make("model"), + providerID: ProviderV2.ID.make("provider"), + variant: ModelV2.VariantID.make("default"), + }, + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.tool.input.started", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(2), + callID, + name: "bash", + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.tool.called", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(3), + callID, + tool: "bash", + input: { command: "pwd" }, + provider: { executed: true, metadata: { source: "provider" } }, + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.tool.success", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(4), + callID, + structured: {}, + content: [{ type: "text", text: "/tmp" }], + provider: { executed: true, metadata: { status: "done" } }, }, - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.tool.input.started", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(2), - callID, - name: "bash", - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.tool.called", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(3), - callID, - tool: "bash", - input: { command: "pwd" }, - provider: { executed: true, metadata: { source: "provider" } }, - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.tool.success", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(4), - callID, - structured: {}, - content: [{ type: "text", text: "/tmp" }], - provider: { executed: true, metadata: { status: "done" } }, - }, - } satisfies SessionEvent.Event) + } satisfies SessionEvent.Event), + ) expect(state.messages[0]?.type).toBe("assistant") if (state.messages[0]?.type !== "assistant") return @@ -159,51 +178,59 @@ test("tool completion stores completed timestamp", () => { expect(state.messages[0].content[0].provider).toEqual({ executed: true, metadata: { status: "done" } }) }) -test("compaction events reduce to compaction message", () => { +test.skip("compaction events reduce to compaction message", () => { const state: SessionMessageUpdater.MemoryState = { messages: [] } const sessionID = SessionID.make("session") const id = EventV2.ID.create() - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id, - type: "session.next.compaction.started", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(1), - reason: "auto", - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.compaction.delta", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(2), - text: "hello ", - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.compaction.delta", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(3), - text: "summary", - }, - } satisfies SessionEvent.Event) - - SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { - id: EventV2.ID.create(), - type: "session.next.compaction.ended", - data: { - sessionID, - timestamp: DateTime.makeUnsafe(4), - text: "final summary", - include: "recent context", - }, - } satisfies SessionEvent.Event) + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id, + type: "session.next.compaction.started", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(1), + reason: "auto", + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.compaction.delta", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(2), + text: "hello ", + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.compaction.delta", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(3), + text: "summary", + }, + } satisfies SessionEvent.Event), + ) + + Effect.runSync( + SessionMessageUpdater.update(SessionMessageUpdater.memory(state), { + id: EventV2.ID.create(), + type: "session.next.compaction.ended", + data: { + sessionID, + timestamp: DateTime.makeUnsafe(4), + text: "final summary", + include: "recent context", + }, + } satisfies SessionEvent.Event), + ) expect(state.messages).toHaveLength(1) expect(state.messages[0]).toMatchObject({ diff --git a/packages/plugin/package.json b/packages/plugin/package.json index d162e55d6943..bede96ed56c2 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -22,9 +22,9 @@ "zod": "catalog:" }, "peerDependencies": { - "@opentui/core": ">=0.2.15", - "@opentui/keymap": ">=0.2.15", - "@opentui/solid": ">=0.2.15" + "@opentui/core": ">=0.3.1", + "@opentui/keymap": ">=0.3.1", + "@opentui/solid": ">=0.3.1" }, "peerDependenciesMeta": { "@opentui/core": { diff --git a/packages/plugin/src/index.ts b/packages/plugin/src/index.ts index 6156477be216..3c710d076a38 100644 --- a/packages/plugin/src/index.ts +++ b/packages/plugin/src/index.ts @@ -220,6 +220,7 @@ export type ProviderHook = { export type AuthOuathResult = AuthOAuthResult export interface Hooks { + dispose?: () => Promise event?: (input: { event: Event }) => Promise config?: (input: Config) => Promise tool?: { diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index 28c3a8f020d9..30bfd0f6fc69 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -25,10 +25,10 @@ import type { ConfigUpdateErrors, ConfigUpdateResponses, EventSubscribeResponses, - EventTuiCommandExecute2, - EventTuiPromptAppend2, - EventTuiSessionSelect2, - EventTuiToastShow2, + EventTuiCommandExecute, + EventTuiPromptAppend, + EventTuiSessionSelect, + EventTuiToastShow, ExperimentalConsoleGetErrors, ExperimentalConsoleGetResponses, ExperimentalConsoleListOrgsErrors, @@ -2632,6 +2632,8 @@ export class Pty extends HeyApiClient { ptyID: string directory?: string workspace?: string + cursor?: string + ticket?: string }, options?: Options, ) { @@ -2643,6 +2645,8 @@ export class Pty extends HeyApiClient { { in: "path", key: "ptyID" }, { in: "query", key: "directory" }, { in: "query", key: "workspace" }, + { in: "query", key: "cursor" }, + { in: "query", key: "ticket" }, ], }, ], @@ -3095,6 +3099,9 @@ export class Session2 extends HeyApiClient { providerID: string variant?: string } + metadata?: { + [key: string]: unknown + } permission?: PermissionRuleset workspaceID?: string }, @@ -3111,6 +3118,7 @@ export class Session2 extends HeyApiClient { { in: "body", key: "title" }, { in: "body", key: "agent" }, { in: "body", key: "model" }, + { in: "body", key: "metadata" }, { in: "body", key: "permission" }, { in: "body", key: "workspaceID" }, ], @@ -3234,6 +3242,9 @@ export class Session2 extends HeyApiClient { directory?: string workspace?: string title?: string + metadata?: { + [key: string]: unknown + } permission?: PermissionRuleset time?: { archived?: number @@ -3250,6 +3261,7 @@ export class Session2 extends HeyApiClient { { in: "query", key: "directory" }, { in: "query", key: "workspace" }, { in: "body", key: "title" }, + { in: "body", key: "metadata" }, { in: "body", key: "permission" }, { in: "body", key: "time" }, ], @@ -4933,7 +4945,7 @@ export class Tui extends HeyApiClient { parameters?: { directory?: string workspace?: string - body?: EventTuiPromptAppend2 | EventTuiCommandExecute2 | EventTuiToastShow2 | EventTuiSessionSelect2 + body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect }, options?: Options, ) { diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 0b37403e5462..a1b09bd7067b 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -5,17 +5,44 @@ export type ClientOptions = { } export type Event = - | EventTuiPromptAppend - | EventTuiCommandExecute - | EventTuiToastShow1 - | EventTuiSessionSelect - | EventServerConnected - | EventGlobalDisposed - | EventServerInstanceDisposed + | EventModelsDevRefreshed + | EventPluginAdded + | EventCatalogModelUpdated | EventFileEdited + | EventSessionNextAgentSwitched + | EventSessionNextModelSwitched + | EventSessionNextPrompted + | EventSessionNextSynthetic + | EventSessionNextShellStarted + | EventSessionNextShellEnded + | EventSessionNextStepStarted + | EventSessionNextStepEnded + | EventSessionNextStepFailed + | EventSessionNextTextStarted + | EventSessionNextTextDelta + | EventSessionNextTextEnded + | EventSessionNextReasoningStarted + | EventSessionNextReasoningDelta + | EventSessionNextReasoningEnded + | EventSessionNextToolInputStarted + | EventSessionNextToolInputDelta + | EventSessionNextToolInputEnded + | EventSessionNextToolCalled + | EventSessionNextToolProgress + | EventSessionNextToolSuccess + | EventSessionNextToolFailed + | EventSessionNextRetried + | EventSessionNextCompactionStarted + | EventSessionNextCompactionDelta + | EventSessionNextCompactionEnded | EventFileWatcherUpdated - | EventLspClientDiagnostics - | EventLspUpdated + | EventSessionCreated + | EventSessionUpdated + | EventSessionDeleted + | EventMessageUpdated + | EventMessageRemoved + | EventMessagePartUpdated + | EventMessagePartRemoved | EventMessagePartDelta | EventPermissionAsked | EventPermissionReplied @@ -28,11 +55,16 @@ export type Event = | EventTodoUpdated | EventSessionStatus | EventSessionIdle + | EventSessionCompacted + | EventLspUpdated + | EventTuiPromptAppend2 + | EventTuiCommandExecute2 + | EventTuiToastShow2 + | EventTuiSessionSelect2 | EventMcpToolsChanged | EventMcpBrowserOpenFailed | EventCommandExecuted | EventProjectUpdated - | EventSessionCompacted | EventVcsBranchUpdated | EventWorkspaceReady | EventWorkspaceFailed @@ -45,44 +77,23 @@ export type Event = | EventPtyDeleted | EventInstallationUpdated | EventInstallationUpdateAvailable - | EventMessageUpdated - | EventMessageRemoved - | EventMessagePartUpdated - | EventMessagePartRemoved - | EventSessionCreated - | EventSessionUpdated - | EventSessionDeleted - | EventSessionNextAgentSwitched - | EventSessionNextModelSwitched - | EventSessionNextPrompted - | EventSessionNextSynthetic - | EventSessionNextShellStarted - | EventSessionNextShellEnded - | EventSessionNextStepStarted - | EventSessionNextStepEnded - | EventSessionNextStepFailed - | EventSessionNextTextStarted - | EventSessionNextTextDelta - | EventSessionNextTextEnded - | EventSessionNextReasoningStarted - | EventSessionNextReasoningDelta - | EventSessionNextReasoningEnded - | EventSessionNextToolInputStarted - | EventSessionNextToolInputDelta - | EventSessionNextToolInputEnded - | EventSessionNextToolCalled - | EventSessionNextToolProgress - | EventSessionNextToolSuccess - | EventSessionNextToolFailed - | EventSessionNextRetried - | EventSessionNextCompactionStarted - | EventSessionNextCompactionDelta - | EventSessionNextCompactionEnded - | EventCatalogModelUpdated - | EventModelsDevRefreshed + | EventServerConnected + | EventGlobalDisposed | EventAccountAdded | EventAccountRemoved | EventAccountSwitched + | EventServerInstanceDisposed + +export type QuestionReplied = { + sessionID: string + requestID: string + answers: Array +} + +export type QuestionRejected = { + sessionID: string + requestID: string +} export type OAuth = { type: "oauth" @@ -120,82 +131,113 @@ export type InvalidRequestError = { field?: string } -export type EventTuiPromptAppend = { - id: string - type: "tui.prompt.append" - properties: { - text: string - } +export type Prompt = { + text: string + files?: Array + agents?: Array + references?: Array } -export type EventTuiCommandExecute = { - id: string - type: "tui.command.execute" - properties: { - command: - | "session.list" - | "session.new" - | "session.share" - | "session.interrupt" - | "session.compact" - | "session.page.up" - | "session.page.down" - | "session.line.up" - | "session.line.down" - | "session.half.page.up" - | "session.half.page.down" - | "session.first" - | "session.last" - | "prompt.clear" - | "prompt.submit" - | "agent.cycle" - | string - } +export type SnapshotFileDiff = { + file?: string + patch?: string + additions: number + deletions: number + status?: "added" | "deleted" | "modified" } -export type EventTuiToastShow = { +export type Session = { id: string - type: "tui.toast.show" - properties: { - title?: string - message: string - variant: "info" | "success" | "warning" | "error" - duration?: number + slug: string + projectID: string + workspaceID?: string + directory: string + path?: string + parentID?: string + summary?: { + additions: number + deletions: number + files: number + diffs?: Array + } + cost?: number + tokens?: { + input: number + output: number + reasoning: number + cache: { + read: number + write: number + } + } + share?: { + url: string + } + title: string + agent?: string + model?: { + id: string + providerID: string + variant?: string + } + version: string + metadata?: { + [key: string]: unknown + } + time: { + created: number + updated: number + compacting?: number + archived?: number + } + permission?: PermissionRuleset + revert?: { + messageID: string + partID?: string + snapshot?: string + diff?: string } } -export type EventTuiSessionSelect = { - id: string - type: "tui.session.select" - properties: { - /** - * Session ID to navigate to - */ - sessionID: string - } +export type OutputFormatText = { + type: "text" } -export type PermissionRequest = { +export type JsonSchema = { + [key: string]: unknown +} + +export type OutputFormatJsonSchema = { + type: "json_schema" + schema: JsonSchema + retryCount?: number +} + +export type OutputFormat = OutputFormatText | OutputFormatJsonSchema + +export type UserMessage = { id: string sessionID: string - permission: string - patterns: Array - metadata: { - [key: string]: unknown + role: "user" + time: { + created: number } - always: Array - tool?: { - messageID: string - callID: string + format?: OutputFormat + summary?: { + title?: string + body?: string + diffs: Array + } + agent: string + model: { + providerID: string + modelID: string + variant?: string + } + system?: string + tools?: { + [key: string]: boolean } -} - -export type SnapshotFileDiff = { - file?: string - patch?: string - additions: number - deletions: number - status?: "added" | "deleted" | "modified" } export type ProviderAuthError = { @@ -260,174 +302,6 @@ export type ApiError = { } } -export type QuestionOption = { - /** - * Display text (1-5 words, concise) - */ - label: string - /** - * Explanation of choice - */ - description: string -} - -export type QuestionInfo = { - /** - * Complete question - */ - question: string - /** - * Very short label (max 30 chars) - */ - header: string - /** - * Available choices - */ - options: Array - multiple?: boolean - custom?: boolean -} - -export type QuestionTool = { - messageID: string - callID: string -} - -export type QuestionRequest = { - id: string - sessionID: string - /** - * Questions to ask - */ - questions: Array - tool?: QuestionTool -} - -export type QuestionAnswer = Array - -export type QuestionReplied = { - sessionID: string - requestID: string - answers: Array -} - -export type QuestionRejected = { - sessionID: string - requestID: string -} - -export type Todo = { - /** - * Brief description of the task - */ - content: string - /** - * Current status of the task: pending, in_progress, completed, cancelled - */ - status: string - /** - * Priority level of the task: high, medium, low - */ - priority: string -} - -export type SessionStatus = - | { - type: "idle" - } - | { - type: "retry" - attempt: number - message: string - action?: { - reason: string - provider: string - title: string - message: string - label: string - link?: string - } - next: number - } - | { - type: "busy" - } - -export type Project = { - id: string - worktree: string - vcs?: "git" - name?: string - icon?: { - url?: string - override?: string - color?: string - } - commands?: { - /** - * Startup script to run when creating a new workspace (worktree) - */ - start?: string - } - time: { - created: number - updated: number - initialized?: number - } - sandboxes: Array -} - -export type Pty = { - id: string - title: string - command: string - args: Array - cwd: string - status: "running" | "exited" - pid: number -} - -export type OutputFormatText = { - type: "text" -} - -export type JsonSchema = { - [key: string]: unknown -} - -export type OutputFormatJsonSchema = { - type: "json_schema" - schema: JsonSchema - retryCount?: number -} - -export type OutputFormat = OutputFormatText | OutputFormatJsonSchema - -export type UserMessage = { - id: string - sessionID: string - role: "user" - time: { - created: number - } - format?: OutputFormat - summary?: { - title?: string - body?: string - diffs: Array - } - agent: string - model: { - providerID: string - modelID: string - variant?: string - } - system?: string - tools?: { - [key: string]: boolean - } -} - export type AssistantMessage = { id: string sessionID: string @@ -735,163 +609,838 @@ export type Part = | RetryPart | CompactionPart -export type PermissionAction = "allow" | "deny" | "ask" - -export type PermissionRule = { - permission: string - pattern: string - action: PermissionAction +export type QuestionOption = { + /** + * Display text (1-5 words, concise) + */ + label: string + /** + * Explanation of choice + */ + description: string } -export type PermissionRuleset = Array - -export type Session = { - id: string - slug: string - projectID: string - workspaceID?: string - directory: string - path?: string - parentID?: string - summary?: { - additions: number - deletions: number - files: number - diffs?: Array - } - cost?: number - tokens?: { - input: number - output: number - reasoning: number - cache: { - read: number - write: number - } - } - share?: { - url: string - } - title: string - agent?: string - model?: { - id: string - providerID: string - variant?: string - } - version: string - time: { - created: number - updated: number - compacting?: number - archived?: number - } - permission?: PermissionRuleset - revert?: { - messageID: string - partID?: string - snapshot?: string - diff?: string - } +export type QuestionInfo = { + /** + * Complete question + */ + question: string + /** + * Very short label (max 30 chars) + */ + header: string + /** + * Available choices + */ + options: Array + multiple?: boolean + custom?: boolean } -export type Prompt = { - text: string - files?: Array - agents?: Array - references?: Array +export type QuestionTool = { + messageID: string + callID: string } -export type GlobalEvent = { - directory: string - project?: string - workspace?: string - payload: - | EventTuiPromptAppend - | EventTuiCommandExecute - | EventTuiToastShow - | EventTuiSessionSelect - | EventServerConnected - | EventGlobalDisposed - | EventServerInstanceDisposed - | EventFileEdited - | EventFileWatcherUpdated - | EventLspClientDiagnostics - | EventLspUpdated - | EventMessagePartDelta - | EventPermissionAsked - | EventPermissionReplied - | EventCwdUpdated - | EventSessionDiff - | EventSessionError - | EventQuestionAsked - | EventQuestionReplied - | EventQuestionRejected - | EventTodoUpdated - | EventSessionStatus - | EventSessionIdle - | EventMcpToolsChanged - | EventMcpBrowserOpenFailed - | EventCommandExecuted - | EventProjectUpdated - | EventSessionCompacted - | EventVcsBranchUpdated - | EventWorkspaceReady - | EventWorkspaceFailed - | EventWorkspaceStatus - | EventWorktreeReady - | EventWorktreeFailed - | EventPtyCreated - | EventPtyUpdated - | EventPtyExited - | EventPtyDeleted - | EventInstallationUpdated - | EventInstallationUpdateAvailable - | EventMessageUpdated - | EventMessageRemoved - | EventMessagePartUpdated - | EventMessagePartRemoved - | EventSessionCreated - | EventSessionUpdated - | EventSessionDeleted - | EventSessionNextAgentSwitched - | EventSessionNextModelSwitched - | EventSessionNextPrompted - | EventSessionNextSynthetic - | EventSessionNextShellStarted - | EventSessionNextShellEnded - | EventSessionNextStepStarted - | EventSessionNextStepEnded - | EventSessionNextStepFailed - | EventSessionNextTextStarted - | EventSessionNextTextDelta - | EventSessionNextTextEnded - | EventSessionNextReasoningStarted - | EventSessionNextReasoningDelta - | EventSessionNextReasoningEnded - | EventSessionNextToolInputStarted - | EventSessionNextToolInputDelta - | EventSessionNextToolInputEnded - | EventSessionNextToolCalled - | EventSessionNextToolProgress - | EventSessionNextToolSuccess - | EventSessionNextToolFailed - | EventSessionNextRetried - | EventSessionNextCompactionStarted - | EventSessionNextCompactionDelta - | EventSessionNextCompactionEnded - | EventCatalogModelUpdated - | EventModelsDevRefreshed - | EventAccountAdded - | EventAccountRemoved - | EventAccountSwitched - | SyncEventMessageUpdated - | SyncEventMessageRemoved - | SyncEventMessagePartUpdated - | SyncEventMessagePartRemoved - | SyncEventSessionCreated - | SyncEventSessionUpdated - | SyncEventSessionDeleted +export type QuestionAnswer = Array + +export type Todo = { + /** + * Brief description of the task + */ + content: string + /** + * Current status of the task: pending, in_progress, completed, cancelled + */ + status: string + /** + * Priority level of the task: high, medium, low + */ + priority: string +} + +export type SessionStatus = + | { + type: "idle" + } + | { + type: "retry" + attempt: number + message: string + action?: { + reason: string + provider: string + title: string + message: string + label: string + link?: string + } + next: number + } + | { + type: "busy" + } + +export type Pty = { + id: string + title: string + command: string + args: Array + cwd: string + status: "running" | "exited" + pid: number +} + +export type GlobalEvent = { + directory: string + project?: string + workspace?: string + payload: + | { + id: string + type: "models-dev.refreshed" + properties: { + [key: string]: unknown + } + } + | { + id: string + type: "plugin.added" + properties: { + id: string + } + } + | { + id: string + type: "catalog.model.updated" + properties: { + model: ModelV2Info + } + } + | { + id: string + type: "file.edited" + properties: { + file: string + } + } + | { + id: string + type: "session.next.agent.switched" + properties: { + timestamp: number + sessionID: string + agent: string + } + } + | { + id: string + type: "session.next.model.switched" + properties: { + timestamp: number + sessionID: string + model: { + id: string + providerID: string + variant?: string + } + } + } + | { + id: string + type: "session.next.prompted" + properties: { + timestamp: number + sessionID: string + prompt: Prompt + } + } + | { + id: string + type: "session.next.synthetic" + properties: { + timestamp: number + sessionID: string + text: string + } + } + | { + id: string + type: "session.next.shell.started" + properties: { + timestamp: number + sessionID: string + callID: string + command: string + } + } + | { + id: string + type: "session.next.shell.ended" + properties: { + timestamp: number + sessionID: string + callID: string + output: string + } + } + | { + id: string + type: "session.next.step.started" + properties: { + timestamp: number + sessionID: string + agent: string + model: { + id: string + providerID: string + variant?: string + } + snapshot?: string + } + } + | { + id: string + type: "session.next.step.ended" + properties: { + timestamp: number + sessionID: string + finish: string + cost: number + tokens: { + input: number + output: number + reasoning: number + cache: { + read: number + write: number + } + } + snapshot?: string + } + } + | { + id: string + type: "session.next.step.failed" + properties: { + timestamp: number + sessionID: string + error: SessionErrorUnknown + } + } + | { + id: string + type: "session.next.text.started" + properties: { + timestamp: number + sessionID: string + } + } + | { + id: string + type: "session.next.text.delta" + properties: { + timestamp: number + sessionID: string + delta: string + } + } + | { + id: string + type: "session.next.text.ended" + properties: { + timestamp: number + sessionID: string + text: string + } + } + | { + id: string + type: "session.next.reasoning.started" + properties: { + timestamp: number + sessionID: string + reasoningID: string + } + } + | { + id: string + type: "session.next.reasoning.delta" + properties: { + timestamp: number + sessionID: string + reasoningID: string + delta: string + } + } + | { + id: string + type: "session.next.reasoning.ended" + properties: { + timestamp: number + sessionID: string + reasoningID: string + text: string + } + } + | { + id: string + type: "session.next.tool.input.started" + properties: { + timestamp: number + sessionID: string + callID: string + name: string + } + } + | { + id: string + type: "session.next.tool.input.delta" + properties: { + timestamp: number + sessionID: string + callID: string + delta: string + } + } + | { + id: string + type: "session.next.tool.input.ended" + properties: { + timestamp: number + sessionID: string + callID: string + text: string + } + } + | { + id: string + type: "session.next.tool.called" + properties: { + timestamp: number + sessionID: string + callID: string + tool: string + input: { + [key: string]: unknown + } + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } + } + | { + id: string + type: "session.next.tool.progress" + properties: { + timestamp: number + sessionID: string + callID: string + structured: { + [key: string]: unknown + } + content: Array + } + } + | { + id: string + type: "session.next.tool.success" + properties: { + timestamp: number + sessionID: string + callID: string + structured: { + [key: string]: unknown + } + content: Array + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } + } + | { + id: string + type: "session.next.tool.failed" + properties: { + timestamp: number + sessionID: string + callID: string + error: SessionErrorUnknown + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } + } + | { + id: string + type: "session.next.retried" + properties: { + timestamp: number + sessionID: string + attempt: number + error: SessionNextRetryError + } + } + | { + id: string + type: "session.next.compaction.started" + properties: { + timestamp: number + sessionID: string + reason: "auto" | "manual" + } + } + | { + id: string + type: "session.next.compaction.delta" + properties: { + timestamp: number + sessionID: string + text: string + } + } + | { + id: string + type: "session.next.compaction.ended" + properties: { + timestamp: number + sessionID: string + text: string + include?: string + } + } + | { + id: string + type: "file.watcher.updated" + properties: { + file: string + event: "add" | "change" | "unlink" + } + } + | { + id: string + type: "session.created" + properties: { + sessionID: string + info: Session + } + } + | { + id: string + type: "session.updated" + properties: { + sessionID: string + info: Session + } + } + | { + id: string + type: "session.deleted" + properties: { + sessionID: string + info: Session + } + } + | { + id: string + type: "message.updated" + properties: { + sessionID: string + info: Message + } + } + | { + id: string + type: "message.removed" + properties: { + sessionID: string + messageID: string + } + } + | { + id: string + type: "message.part.updated" + properties: { + sessionID: string + part: Part + time: number + } + } + | { + id: string + type: "message.part.removed" + properties: { + sessionID: string + messageID: string + partID: string + } + } + | { + id: string + type: "message.part.delta" + properties: { + sessionID: string + messageID: string + partID: string + field: string + delta: string + } + } + | { + id: string + type: "permission.asked" + properties: { + id: string + sessionID: string + permission: string + patterns: Array + metadata: { + [key: string]: unknown + } + always: Array + tool?: { + messageID: string + callID: string + } + } + } + | { + id: string + type: "permission.replied" + properties: { + sessionID: string + requestID: string + reply: "once" | "always" | "reject" + } + } + | { + id: string + type: "session.diff" + properties: { + sessionID: string + diff: Array + } + } + | { + id: string + type: "session.error" + properties: { + sessionID?: string + error?: + | ProviderAuthError + | UnknownError + | MessageOutputLengthError + | MessageAbortedError + | StructuredOutputError + | ContextOverflowError + | ApiError + } + } + | { + id: string + type: "question.asked" + properties: { + id: string + sessionID: string + /** + * Questions to ask + */ + questions: Array + tool?: QuestionTool + } + } + | { + id: string + type: "question.replied" + properties: { + sessionID: string + requestID: string + answers: Array + } + } + | { + id: string + type: "question.rejected" + properties: { + sessionID: string + requestID: string + } + } + | { + id: string + type: "todo.updated" + properties: { + sessionID: string + todos: Array + } + } + | { + id: string + type: "session.status" + properties: { + sessionID: string + status: SessionStatus + } + } + | { + id: string + type: "session.idle" + properties: { + sessionID: string + } + } + | { + id: string + type: "session.compacted" + properties: { + sessionID: string + } + } + | { + id: string + type: "lsp.updated" + properties: { + [key: string]: unknown + } + } + | { + id: string + type: "tui.prompt.append" + properties: { + text: string + } + } + | { + id: string + type: "tui.command.execute" + properties: { + command: + | "session.list" + | "session.new" + | "session.share" + | "session.interrupt" + | "session.compact" + | "session.page.up" + | "session.page.down" + | "session.line.up" + | "session.line.down" + | "session.half.page.up" + | "session.half.page.down" + | "session.first" + | "session.last" + | "prompt.clear" + | "prompt.submit" + | "agent.cycle" + | string + } + } + | { + id: string + type: "tui.toast.show" + properties: { + title?: string + message: string + variant: "info" | "success" | "warning" | "error" + duration?: number + } + } + | { + id: string + type: "tui.session.select" + properties: { + /** + * Session ID to navigate to + */ + sessionID: string + } + } + | { + id: string + type: "mcp.tools.changed" + properties: { + server: string + } + } + | { + id: string + type: "mcp.browser.open.failed" + properties: { + mcpName: string + url: string + } + } + | { + id: string + type: "command.executed" + properties: { + name: string + sessionID: string + arguments: string + messageID: string + } + } + | { + id: string + type: "project.updated" + properties: { + id: string + worktree: string + vcs?: "git" + name?: string + icon?: { + url?: string + override?: string + color?: string + } + commands?: { + /** + * Startup script to run when creating a new workspace (worktree) + */ + start?: string + } + time: { + created: number + updated: number + initialized?: number + } + sandboxes: Array + } + } + | { + id: string + type: "vcs.branch.updated" + properties: { + branch?: string + } + } + | { + id: string + type: "workspace.ready" + properties: { + name: string + } + } + | { + id: string + type: "workspace.failed" + properties: { + message: string + } + } + | { + id: string + type: "workspace.status" + properties: { + workspaceID: string + status: "connected" | "connecting" | "disconnected" | "error" + } + } + | { + id: string + type: "worktree.ready" + properties: { + name: string + branch?: string + } + } + | { + id: string + type: "worktree.failed" + properties: { + message: string + } + } + | { + id: string + type: "pty.created" + properties: { + info: Pty + } + } + | { + id: string + type: "pty.updated" + properties: { + info: Pty + } + } + | { + id: string + type: "pty.exited" + properties: { + id: string + exitCode: number + } + } + | { + id: string + type: "pty.deleted" + properties: { + id: string + } + } + | { + id: string + type: "installation.updated" + properties: { + version: string + } + } + | { + id: string + type: "installation.update-available" + properties: { + version: string + } + } + | { + id: string + type: "server.connected" + properties: { + [key: string]: unknown + } + } + | { + id: string + type: "global.disposed" + properties: { + [key: string]: unknown + } + } + | { + id: string + type: "account.added" + properties: { + account: AuthInfo + } + } + | { + id: string + type: "account.removed" + properties: { + account: AuthInfo + } + } + | { + id: string + type: "account.switched" + properties: { + serviceID: string + from?: string + to?: string + } + } + | EventServerInstanceDisposed + | EventCwdUpdated | SyncEventSessionNextAgentSwitched | SyncEventSessionNextModelSwitched | SyncEventSessionNextPrompted @@ -918,6 +1467,13 @@ export type GlobalEvent = { | SyncEventSessionNextCompactionStarted | SyncEventSessionNextCompactionDelta | SyncEventSessionNextCompactionEnded + | SyncEventSessionCreated + | SyncEventSessionUpdated + | SyncEventSessionDeleted + | SyncEventMessageUpdated + | SyncEventMessageRemoved + | SyncEventMessagePartUpdated + | SyncEventMessagePartRemoved } /** @@ -1051,11 +1607,15 @@ export type ProviderConfig = { enterpriseUrl?: string setCacheKey?: boolean /** - * Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout. + * Timeout in milliseconds for full requests to this provider. Set to false to disable timeout. */ timeout?: number | false + /** + * Timeout in milliseconds to wait for response headers. Provider integrations may set defaults. Set to false to disable timeout. + */ + headerTimeout?: number | false chunkTimeout?: number - [key: string]: unknown | string | boolean | number | false | number | undefined + [key: string]: unknown | string | boolean | number | false | number | false | number | undefined } models?: { [key: string]: { @@ -1090,8 +1650,8 @@ export type ProviderConfig = { output: number } modalities?: { - input: Array<"text" | "audio" | "image" | "video" | "pdf"> - output: Array<"text" | "audio" | "image" | "video" | "pdf"> + input?: Array<"text" | "audio" | "image" | "video" | "pdf"> + output?: Array<"text" | "audio" | "image" | "video" | "pdf"> } experimental?: boolean status?: "alpha" | "beta" | "deprecated" | "active" @@ -1314,6 +1874,7 @@ export type Config = { primary_tools?: Array continue_loop_on_deny?: boolean mcp_timeout?: number + policies?: Array } } @@ -1470,6 +2031,16 @@ export type WorktreeResetInput = { directory: string } +export type PermissionAction = "allow" | "deny" | "ask" + +export type PermissionRule = { + permission: string + pattern: string + action: PermissionAction +} + +export type PermissionRuleset = Array + export type ProjectSummary = { id: string name?: string @@ -1511,6 +2082,9 @@ export type GlobalSession = { variant?: string } version: string + metadata?: { + [key: string]: unknown + } time: { created: number updated: number @@ -1702,6 +2276,30 @@ export type McpServerNotFoundError = { message: string } +export type Project = { + id: string + worktree: string + vcs?: "git" + name?: string + icon?: { + url?: string + override?: string + color?: string + } + commands?: { + /** + * Startup script to run when creating a new workspace (worktree) + */ + start?: string + } + time: { + created: number + updated: number + initialized?: number + } + sandboxes: Array +} + export type ProjectNotFoundError = { _tag: "ProjectNotFoundError" projectID: string @@ -1719,12 +2317,37 @@ export type PtyForbiddenError = { message: string } +export type QuestionRequest = { + id: string + sessionID: string + /** + * Questions to ask + */ + questions: Array + tool?: QuestionTool +} + export type QuestionNotFoundError = { _tag: "QuestionNotFoundError" requestID: string message: string } +export type PermissionRequest = { + id: string + sessionID: string + permission: string + patterns: Array + metadata: { + [key: string]: unknown + } + always: Array + tool?: { + messageID: string + callID: string + } +} + export type PermissionNotFoundError = { _tag: "PermissionNotFoundError" requestID: string @@ -1896,14 +2519,14 @@ export type ProviderNotFoundError = { message: string } -export type EventTuiPromptAppend2 = { +export type EventTuiPromptAppend = { type: "tui.prompt.append" properties: { text: string } } -export type EventTuiCommandExecute2 = { +export type EventTuiCommandExecute = { type: "tui.command.execute" properties: { command: @@ -1927,7 +2550,7 @@ export type EventTuiCommandExecute2 = { } } -export type EventTuiToastShow2 = { +export type EventTuiToastShow = { type: "tui.toast.show" properties: { title?: string @@ -1937,7 +2560,7 @@ export type EventTuiToastShow2 = { } } -export type EventTuiSessionSelect2 = { +export type EventTuiSessionSelect = { type: "tui.session.select" properties: { /** @@ -1958,6 +2581,13 @@ export type Workspace = { timeUsed: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" } +export type WorkspaceCreateError = { + name: "WorkspaceCreateError" + data: { + message: string + } +} + export type WorkspaceWarpError = { name: "WorkspaceWarpError" data: { @@ -1969,137 +2599,249 @@ export type EffectHttpApiErrorForbidden = { _tag: "Forbidden" } -export type SyncEventMessageUpdated = { - type: "sync" - name: "message.updated.1" +export type EventTuiPromptAppend2 = { id: string - seq: number - aggregateID: "sessionID" - data: { - sessionID: string - info: Message + type: "tui.prompt.append" + properties: { + text: string } } -export type SyncEventMessageRemoved = { - type: "sync" - name: "message.removed.1" +export type EventTuiCommandExecute2 = { id: string - seq: number - aggregateID: "sessionID" - data: { + type: "tui.command.execute" + properties: { + command: + | "session.list" + | "session.new" + | "session.share" + | "session.interrupt" + | "session.compact" + | "session.page.up" + | "session.page.down" + | "session.line.up" + | "session.line.down" + | "session.half.page.up" + | "session.half.page.down" + | "session.first" + | "session.last" + | "prompt.clear" + | "prompt.submit" + | "agent.cycle" + | string + } +} + +export type EventTuiToastShow2 = { + id: string + type: "tui.toast.show" + properties: { + title?: string + message: string + variant: "info" | "success" | "warning" | "error" + duration?: number + } +} + +export type EventTuiSessionSelect2 = { + id: string + type: "tui.session.select" + properties: { + /** + * Session ID to navigate to + */ sessionID: string - messageID: string } } -export type SyncEventMessagePartUpdated = { - type: "sync" - name: "message.part.updated.1" - id: string - seq: number - aggregateID: "sessionID" - data: { - sessionID: string - part: Part - time: number - } +export type ModelV2Info = { + id: string + apiID: string + providerID: string + family?: string + name: string + endpoint: + | { + type: "unknown" + } + | { + type: "openai/responses" + url: string + websocket?: boolean + } + | { + type: "openai/completions" + url: string + reasoning?: + | { + type: "reasoning_content" + } + | { + type: "reasoning_details" + } + } + | { + type: "anthropic/messages" + url: string + } + | { + type: "aisdk" + package: string + url?: string + } + capabilities: { + tools: boolean + input: Array + output: Array + } + options: { + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + variant?: string + } + variants: Array<{ + id: string + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + }> + time: { + released: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + } + cost: Array<{ + tier?: { + type: "context" + size: number + } + input: number + output: number + cache: { + read: number + write: number + } + }> + status: "alpha" | "beta" | "deprecated" | "active" + enabled: boolean + limit: { + context: number + input?: number + output: number + } +} + +export type PromptSource = { + start: number + end: number + text: string +} + +export type PromptFileAttachment = { + uri: string + mime: string + name?: string + description?: string + source?: PromptSource +} + +export type PromptAgentAttachment = { + name: string + source?: PromptSource +} + +export type PromptReferenceAttachment = { + name: string + kind: "local" | "git" | "invalid" + uri?: string + repository?: string + branch?: string + target?: string + targetUri?: string + problem?: string + source?: PromptSource +} + +export type SessionErrorUnknown = { + type: "unknown" + message: string +} + +export type ToolTextContent = { + type: "text" + text: string +} + +export type ToolFileContent = { + type: "file" + uri: string + mime: string + name?: string +} + +export type SessionNextRetryError = { + message: string + statusCode?: number + isRetryable: boolean + responseHeaders?: { + [key: string]: string + } + responseBody?: string + metadata?: { + [key: string]: string + } +} + +export type AuthOAuthCredential = { + type: "oauth" + refresh: string + access: string + expires: number } -export type SyncEventMessagePartRemoved = { - type: "sync" - name: "message.part.removed.1" - id: string - seq: number - aggregateID: "sessionID" - data: { - sessionID: string - messageID: string - partID: string +export type AuthApiKeyCredential = { + type: "api" + key: string + metadata?: { + [key: string]: string } } -export type SyncEventSessionCreated = { - type: "sync" - name: "session.created.1" - id: string - seq: number - aggregateID: "sessionID" - data: { - sessionID: string - info: Session - } -} +export type AuthCredential = AuthOAuthCredential | AuthApiKeyCredential -export type SyncEventSessionUpdated = { - type: "sync" - name: "session.updated.1" +export type AuthInfo = { id: string - seq: number - aggregateID: "sessionID" - data: { - sessionID: string - info: { - id?: string | null - slug?: string | null - projectID?: string | null - workspaceID?: string | null - directory?: string | null - path?: string | null - parentID?: string | null - summary?: { - additions: number - deletions: number - files: number - diffs?: Array - } | null - cost?: number | null - tokens?: { - input: number - output: number - reasoning: number - cache: { - read: number - write: number - } - } | null - share?: { - url?: string | null - } - title?: string | null - agent?: string | null - model?: { - id: string - providerID: string - variant?: string - } | null - version?: string | null - time?: { - created?: number | null - updated?: number | null - compacting?: number | null - archived?: number | null - } - permission?: PermissionRuleset | null - revert?: { - messageID: string - partID?: string - snapshot?: string - diff?: string - } | null - } - } + serviceID: string + description: string + credential: AuthCredential } -export type SyncEventSessionDeleted = { - type: "sync" - name: "session.deleted.1" +export type EventServerInstanceDisposed = { id: string - seq: number - aggregateID: "sessionID" - data: { - sessionID: string - info: Session + type: "server.instance.disposed" + properties: { + directory: string } } @@ -2128,7 +2870,7 @@ export type SyncEventSessionNextModelSwitched = { model: { id: string providerID: string - variant: string + variant?: string } } } @@ -2200,7 +2942,7 @@ export type SyncEventSessionNextStepStarted = { model: { id: string providerID: string - variant: string + variant?: string } snapshot?: string } @@ -2501,372 +3243,537 @@ export type SyncEventSessionNextCompactionEnded = { } } -export type EventServerConnected = { +export type SyncEventSessionCreated = { + type: "sync" + name: "session.created.1" id: string - type: "server.connected" - properties: { - [key: string]: unknown + seq: number + aggregateID: "sessionID" + data: { + sessionID: string + info: Session } } -export type EventGlobalDisposed = { +export type SyncEventSessionUpdated = { + type: "sync" + name: "session.updated.1" id: string - type: "global.disposed" - properties: { - [key: string]: unknown + seq: number + aggregateID: "sessionID" + data: { + sessionID: string + info: Session } } -export type EventServerInstanceDisposed = { +export type EventCwdUpdated = { id: string - type: "server.instance.disposed" + type: "cwd.updated" properties: { - directory: string + cwd: string } } -export type EventFileEdited = { +export type SyncEventSessionDeleted = { + type: "sync" + name: "session.deleted.1" id: string - type: "file.edited" - properties: { - file: string + seq: number + aggregateID: "sessionID" + data: { + sessionID: string + info: Session } } -export type EventFileWatcherUpdated = { +export type SyncEventMessageUpdated = { + type: "sync" + name: "message.updated.1" id: string - type: "file.watcher.updated" - properties: { - file: string - event: "add" | "change" | "unlink" + seq: number + aggregateID: "sessionID" + data: { + sessionID: string + info: Message } } -export type EventLspClientDiagnostics = { +export type SyncEventMessageRemoved = { + type: "sync" + name: "message.removed.1" id: string - type: "lsp.client.diagnostics" - properties: { - serverID: string - path: string + seq: number + aggregateID: "sessionID" + data: { + sessionID: string + messageID: string } } -export type EventLspUpdated = { +export type SyncEventMessagePartUpdated = { + type: "sync" + name: "message.part.updated.1" id: string - type: "lsp.updated" - properties: { - [key: string]: unknown + seq: number + aggregateID: "sessionID" + data: { + sessionID: string + part: Part + time: number } } -export type EventMessagePartDelta = { +export type SyncEventMessagePartRemoved = { + type: "sync" + name: "message.part.removed.1" id: string - type: "message.part.delta" - properties: { + seq: number + aggregateID: "sessionID" + data: { sessionID: string messageID: string partID: string - field: string - delta: string } } -export type EventPermissionAsked = { - id: string - type: "permission.asked" - properties: PermissionRequest -} +export type PolicyEffect = "allow" | "deny" -export type EventPermissionReplied = { - id: string - type: "permission.replied" - properties: { - sessionID: string - requestID: string - reply: "once" | "always" | "reject" - } +export type ConfigV2ExperimentalPolicy = { + action: "provider.use" + effect: PolicyEffect + resource: string } -export type EventCwdUpdated = { +export type SessionInfo = { id: string - type: "cwd.updated" - properties: { - cwd: string + parentID?: string + projectID: string + workspaceID?: string + path?: string + agent?: string + model?: { + id: string + providerID: string + variant?: string } -} - -export type EventSessionDiff = { - id: string - type: "session.diff" - properties: { - sessionID: string - diff: Array + cost: number + tokens: { + input: number + output: number + reasoning: number + cache: { + read: number + write: number + } } -} - -export type EventSessionError = { - id: string - type: "session.error" - properties: { - sessionID?: string - error?: - | ProviderAuthError - | UnknownError - | MessageOutputLengthError - | MessageAbortedError - | StructuredOutputError - | ContextOverflowError - | ApiError + time: { + created: number + updated: number + archived?: number } + title: string } -export type EventQuestionAsked = { - id: string - type: "question.asked" - properties: QuestionRequest -} - -export type EventQuestionReplied = { - id: string - type: "question.replied" - properties: QuestionReplied -} - -export type EventQuestionRejected = { - id: string - type: "question.rejected" - properties: QuestionRejected -} - -export type EventTodoUpdated = { - id: string - type: "todo.updated" - properties: { - sessionID: string - todos: Array - } -} +export type SessionDelivery = "immediate" | "deferred" -export type EventSessionStatus = { +export type SessionMessageAgentSwitched = { id: string - type: "session.status" - properties: { - sessionID: string - status: SessionStatus + metadata?: { + [key: string]: unknown + } + time: { + created: number } + type: "agent-switched" + agent: string } -export type EventSessionIdle = { +export type SessionMessageModelSwitched = { id: string - type: "session.idle" - properties: { - sessionID: string + metadata?: { + [key: string]: unknown + } + time: { + created: number + } + type: "model-switched" + model: { + id: string + providerID: string + variant?: string } } -export type EventMcpToolsChanged = { +export type SessionMessageUser = { id: string - type: "mcp.tools.changed" - properties: { - server: string + metadata?: { + [key: string]: unknown + } + time: { + created: number } + text: string + files?: Array + agents?: Array + references?: Array + type: "user" } -export type EventMcpBrowserOpenFailed = { +export type SessionMessageSynthetic = { id: string - type: "mcp.browser.open.failed" - properties: { - mcpName: string - url: string + metadata?: { + [key: string]: unknown + } + time: { + created: number } + sessionID: string + text: string + type: "synthetic" } -export type EventCommandExecuted = { +export type SessionMessageShell = { id: string - type: "command.executed" - properties: { - name: string - sessionID: string - arguments: string - messageID: string + metadata?: { + [key: string]: unknown + } + time: { + created: number + completed?: number } + type: "shell" + callID: string + command: string + output: string } -export type EventProjectUpdated = { - id: string - type: "project.updated" - properties: Project +export type SessionMessageAssistantText = { + type: "text" + text: string } -export type EventSessionCompacted = { +export type SessionMessageAssistantReasoning = { + type: "reasoning" id: string - type: "session.compacted" - properties: { - sessionID: string - } + text: string } -export type EventVcsBranchUpdated = { - id: string - type: "vcs.branch.updated" - properties: { - branch?: string - } +export type SessionMessageToolStatePending = { + status: "pending" + input: string } -export type EventWorkspaceReady = { - id: string - type: "workspace.ready" - properties: { - name: string +export type SessionMessageToolStateRunning = { + status: "running" + input: { + [key: string]: unknown + } + structured: { + [key: string]: unknown } + content: Array } -export type EventWorkspaceFailed = { - id: string - type: "workspace.failed" - properties: { - message: string +export type SessionMessageToolStateCompleted = { + status: "completed" + input: { + [key: string]: unknown + } + attachments?: Array + content: Array + structured: { + [key: string]: unknown } } -export type EventWorkspaceStatus = { - id: string - type: "workspace.status" - properties: { - workspaceID: string - status: "connected" | "connecting" | "disconnected" | "error" +export type SessionMessageToolStateError = { + status: "error" + input: { + [key: string]: unknown + } + content: Array + structured: { + [key: string]: unknown } + error: SessionErrorUnknown } -export type EventWorktreeReady = { +export type SessionMessageAssistantTool = { + type: "tool" id: string - type: "worktree.ready" - properties: { - name: string - branch?: string + name: string + provider?: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + state: + | SessionMessageToolStatePending + | SessionMessageToolStateRunning + | SessionMessageToolStateCompleted + | SessionMessageToolStateError + time: { + created: number + ran?: number + completed?: number + pruned?: number } } -export type EventWorktreeFailed = { +export type SessionMessageAssistant = { id: string - type: "worktree.failed" - properties: { - message: string + metadata?: { + [key: string]: unknown + } + time: { + created: number + completed?: number + } + type: "assistant" + agent: string + model: { + id: string + providerID: string + variant?: string + } + content: Array + snapshot?: { + start?: string + end?: string + } + finish?: string + cost?: number + tokens?: { + input: number + output: number + reasoning: number + cache: { + read: number + write: number + } } + error?: SessionErrorUnknown } -export type EventPtyCreated = { +export type SessionMessageCompaction = { + type: "compaction" + reason: "auto" | "manual" + summary: string + include?: string id: string - type: "pty.created" - properties: { - info: Pty + metadata?: { + [key: string]: unknown + } + time: { + created: number } } -export type EventPtyUpdated = { +export type SessionMessage = + | SessionMessageAgentSwitched + | SessionMessageModelSwitched + | SessionMessageUser + | SessionMessageSynthetic + | SessionMessageShell + | SessionMessageAssistant + | SessionMessageCompaction + +export type ProviderV2Info = { id: string - type: "pty.updated" - properties: { - info: Pty + name: string + enabled: + | false + | { + via: "env" + name: string + } + | { + via: "account" + service: string + } + | { + via: "custom" + data: { + [key: string]: unknown + } + } + env: Array + endpoint: + | { + type: "unknown" + } + | { + type: "openai/responses" + url: string + websocket?: boolean + } + | { + type: "openai/completions" + url: string + reasoning?: + | { + type: "reasoning_content" + } + | { + type: "reasoning_details" + } + } + | { + type: "anthropic/messages" + url: string + } + | { + type: "aisdk" + package: string + url?: string + } + options: { + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } } } -export type EventPtyExited = { +export type EventModelsDevRefreshed = { id: string - type: "pty.exited" + type: "models-dev.refreshed" properties: { - id: string - exitCode: number + [key: string]: unknown } } -export type EventPtyDeleted = { +export type EventPluginAdded = { id: string - type: "pty.deleted" + type: "plugin.added" properties: { id: string } } -export type EventInstallationUpdated = { - id: string - type: "installation.updated" - properties: { - version: string - } -} - -export type EventInstallationUpdateAvailable = { - id: string - type: "installation.update-available" - properties: { - version: string - } -} - -export type EventMessageUpdated = { - id: string - type: "message.updated" - properties: { - sessionID: string - info: Message - } -} - -export type EventMessageRemoved = { +export type ModelV2Info1 = { id: string - type: "message.removed" - properties: { - sessionID: string - messageID: string + apiID: string + providerID: string + family?: string + name: string + endpoint: + | { + type: "unknown" + } + | { + type: "openai/responses" + url: string + websocket?: boolean + } + | { + type: "openai/completions" + url: string + reasoning?: + | { + type: "reasoning_content" + } + | { + type: "reasoning_details" + } + } + | { + type: "anthropic/messages" + url: string + } + | { + type: "aisdk" + package: string + url?: string + } + capabilities: { + tools: boolean + input: Array + output: Array } -} - -export type EventMessagePartUpdated = { - id: string - type: "message.part.updated" - properties: { - sessionID: string - part: Part - time: number + options: { + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + variant?: string } -} - -export type EventMessagePartRemoved = { - id: string - type: "message.part.removed" - properties: { - sessionID: string - messageID: string - partID: string + variants: Array<{ + id: string + headers: { + [key: string]: string + } + body: { + [key: string]: unknown + } + aisdk: { + provider: { + [key: string]: unknown + } + request: { + [key: string]: unknown + } + } + }> + time: { + released: number | "NaN" | "Infinity" | "-Infinity" } -} - -export type EventSessionCreated = { - id: string - type: "session.created" - properties: { - sessionID: string - info: Session + cost: Array<{ + tier?: { + type: "context" + size: number + } + input: number + output: number + cache: { + read: number + write: number + } + }> + status: "alpha" | "beta" | "deprecated" | "active" + enabled: boolean + limit: { + context: number + input?: number + output: number } } -export type EventSessionUpdated = { +export type EventCatalogModelUpdated = { id: string - type: "session.updated" + type: "catalog.model.updated" properties: { - sessionID: string - info: Session + model: ModelV2Info1 } } -export type EventSessionDeleted = { +export type EventFileEdited = { id: string - type: "session.deleted" + type: "file.edited" properties: { - sessionID: string - info: Session + file: string } } @@ -2889,42 +3796,11 @@ export type EventSessionNextModelSwitched = { model: { id: string providerID: string - variant: string + variant?: string } } } -export type PromptSource = { - start: number - end: number - text: string -} - -export type PromptFileAttachment = { - uri: string - mime: string - name?: string - description?: string - source?: PromptSource -} - -export type PromptAgentAttachment = { - name: string - source?: PromptSource -} - -export type PromptReferenceAttachment = { - name: string - kind: "local" | "git" | "invalid" - uri?: string - repository?: string - branch?: string - target?: string - targetUri?: string - problem?: string - source?: PromptSource -} - export type EventSessionNextPrompted = { id: string type: "session.next.prompted" @@ -2977,7 +3853,7 @@ export type EventSessionNextStepStarted = { model: { id: string providerID: string - variant: string + variant?: string } snapshot?: string } @@ -3004,11 +3880,6 @@ export type EventSessionNextStepEnded = { } } -export type SessionErrorUnknown = { - type: "unknown" - message: string -} - export type EventSessionNextStepFailed = { id: string type: "session.next.step.failed" @@ -3121,28 +3992,16 @@ export type EventSessionNextToolCalled = { sessionID: string callID: string tool: string - input: { - [key: string]: unknown - } - provider: { - executed: boolean - metadata?: { - [key: string]: unknown - } - } - } -} - -export type ToolTextContent = { - type: "text" - text: string -} - -export type ToolFileContent = { - type: "file" - uri: string - mime: string - name?: string + input: { + [key: string]: unknown + } + provider: { + executed: boolean + metadata?: { + [key: string]: unknown + } + } + } } export type EventSessionNextToolProgress = { @@ -3196,19 +4055,6 @@ export type EventSessionNextToolFailed = { } } -export type SessionNextRetryError = { - message: string - statusCode?: number - isRetryable: boolean - responseHeaders?: { - [key: string]: string - } - responseBody?: string - metadata?: { - [key: string]: string - } -} - export type EventSessionNextRetried = { id: string type: "session.next.retried" @@ -3251,578 +4097,415 @@ export type EventSessionNextCompactionEnded = { } } -export type ModelV2Info = { +export type EventFileWatcherUpdated = { id: string - apiID: string - providerID: string - family?: string - name: string - endpoint: - | { - type: "unknown" - } - | { - type: "openai/responses" - url: string - websocket?: boolean - } - | { - type: "openai/completions" - url: string - reasoning?: - | { - type: "reasoning_content" - } - | { - type: "reasoning_details" - } - } - | { - type: "anthropic/messages" - url: string - } - | { - type: "aisdk" - package: string - url?: string - } - capabilities: { - tools: boolean - input: Array - output: Array + type: "file.watcher.updated" + properties: { + file: string + event: "add" | "change" | "unlink" } - options: { - headers: { - [key: string]: string - } - body: { - [key: string]: unknown - } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } - } - variant?: string +} + +export type EventSessionCreated = { + id: string + type: "session.created" + properties: { + sessionID: string + info: Session } - variants: Array<{ +} + +export type EventSessionUpdated = { + id: string + type: "session.updated" + properties: { + sessionID: string + info: Session + } +} + +export type EventSessionDeleted = { + id: string + type: "session.deleted" + properties: { + sessionID: string + info: Session + } +} + +export type EventMessageUpdated = { + id: string + type: "message.updated" + properties: { + sessionID: string + info: Message + } +} + +export type EventMessageRemoved = { + id: string + type: "message.removed" + properties: { + sessionID: string + messageID: string + } +} + +export type EventMessagePartUpdated = { + id: string + type: "message.part.updated" + properties: { + sessionID: string + part: Part + time: number + } +} + +export type EventMessagePartRemoved = { + id: string + type: "message.part.removed" + properties: { + sessionID: string + messageID: string + partID: string + } +} + +export type EventMessagePartDelta = { + id: string + type: "message.part.delta" + properties: { + sessionID: string + messageID: string + partID: string + field: string + delta: string + } +} + +export type EventPermissionAsked = { + id: string + type: "permission.asked" + properties: { id: string - headers: { - [key: string]: string - } - body: { + sessionID: string + permission: string + patterns: Array + metadata: { [key: string]: unknown } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } + always: Array + tool?: { + messageID: string + callID: string } - }> - time: { - released: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" } - cost: Array<{ - tier?: { - type: "context" - size: number - } - input: number - output: number - cache: { - read: number - write: number - } - }> - status: "alpha" | "beta" | "deprecated" | "active" - enabled: boolean - limit: { - context: number - input?: number - output: number +} + +export type EventPermissionReplied = { + id: string + type: "permission.replied" + properties: { + sessionID: string + requestID: string + reply: "once" | "always" | "reject" + } +} + +export type EventSessionDiff = { + id: string + type: "session.diff" + properties: { + sessionID: string + diff: Array + } +} + +export type EventSessionError = { + id: string + type: "session.error" + properties: { + sessionID?: string + error?: + | ProviderAuthError + | UnknownError + | MessageOutputLengthError + | MessageAbortedError + | StructuredOutputError + | ContextOverflowError + | ApiError + } +} + +export type EventQuestionAsked = { + id: string + type: "question.asked" + properties: { + id: string + sessionID: string + /** + * Questions to ask + */ + questions: Array + tool?: QuestionTool + } +} + +export type EventQuestionReplied = { + id: string + type: "question.replied" + properties: { + sessionID: string + requestID: string + answers: Array + } +} + +export type EventQuestionRejected = { + id: string + type: "question.rejected" + properties: { + sessionID: string + requestID: string } } -export type EventCatalogModelUpdated = { +export type EventTodoUpdated = { id: string - type: "catalog.model.updated" + type: "todo.updated" properties: { - model: ModelV2Info + sessionID: string + todos: Array } } -export type EventModelsDevRefreshed = { +export type EventSessionStatus = { id: string - type: "models-dev.refreshed" + type: "session.status" properties: { - [key: string]: unknown + sessionID: string + status: SessionStatus } } -export type AccountV2oAuthCredential = { - type: "oauth" - refresh: string - access: string - expires: number +export type EventSessionIdle = { + id: string + type: "session.idle" + properties: { + sessionID: string + } } -export type AccountV2ApiKeyCredential = { - type: "api" - key: string - metadata?: { - [key: string]: string +export type EventSessionCompacted = { + id: string + type: "session.compacted" + properties: { + sessionID: string } } -export type AccountV2Credential = AccountV2oAuthCredential | AccountV2ApiKeyCredential - -export type AccountV2Info = { +export type EventLspUpdated = { id: string - serviceID: string - description: string - credential: AccountV2Credential + type: "lsp.updated" + properties: { + [key: string]: unknown + } } -export type EventAccountAdded = { +export type EventMcpToolsChanged = { id: string - type: "account.added" + type: "mcp.tools.changed" properties: { - account: AccountV2Info + server: string } } -export type EventAccountRemoved = { +export type EventMcpBrowserOpenFailed = { id: string - type: "account.removed" + type: "mcp.browser.open.failed" properties: { - account: AccountV2Info + mcpName: string + url: string } } -export type EventAccountSwitched = { +export type EventCommandExecuted = { id: string - type: "account.switched" + type: "command.executed" properties: { - serviceID: string - from?: string - to?: string + name: string + sessionID: string + arguments: string + messageID: string } } -export type SessionInfo = { +export type EventProjectUpdated = { id: string - parentID?: string - projectID: string - workspaceID?: string - path?: string - agent?: string - model?: { + type: "project.updated" + properties: { id: string - providerID: string - variant: string - } - cost: number - tokens: { - input: number - output: number - reasoning: number - cache: { - read: number - write: number + worktree: string + vcs?: "git" + name?: string + icon?: { + url?: string + override?: string + color?: string } + commands?: { + /** + * Startup script to run when creating a new workspace (worktree) + */ + start?: string + } + time: { + created: number + updated: number + initialized?: number + } + sandboxes: Array } - time: { - created: number - updated: number - archived?: number - } - title: string } -export type SessionDelivery = "immediate" | "deferred" - -export type SessionMessageAgentSwitched = { +export type EventVcsBranchUpdated = { id: string - metadata?: { - [key: string]: unknown - } - time: { - created: number + type: "vcs.branch.updated" + properties: { + branch?: string } - type: "agent-switched" - agent: string } -export type SessionMessageModelSwitched = { +export type EventWorkspaceReady = { id: string - metadata?: { - [key: string]: unknown - } - time: { - created: number - } - type: "model-switched" - model: { - id: string - providerID: string - variant: string + type: "workspace.ready" + properties: { + name: string } } -export type SessionMessageUser = { +export type EventWorkspaceFailed = { id: string - metadata?: { - [key: string]: unknown - } - time: { - created: number + type: "workspace.failed" + properties: { + message: string } - text: string - files?: Array - agents?: Array - references?: Array - type: "user" } -export type SessionMessageSynthetic = { +export type EventWorkspaceStatus = { id: string - metadata?: { - [key: string]: unknown - } - time: { - created: number + type: "workspace.status" + properties: { + workspaceID: string + status: "connected" | "connecting" | "disconnected" | "error" } - sessionID: string - text: string - type: "synthetic" } -export type SessionMessageShell = { +export type EventWorktreeReady = { id: string - metadata?: { - [key: string]: unknown - } - time: { - created: number - completed?: number + type: "worktree.ready" + properties: { + name: string + branch?: string } - type: "shell" - callID: string - command: string - output: string -} - -export type SessionMessageAssistantText = { - type: "text" - text: string } -export type SessionMessageAssistantReasoning = { - type: "reasoning" +export type EventWorktreeFailed = { id: string - text: string -} - -export type SessionMessageToolStatePending = { - status: "pending" - input: string -} - -export type SessionMessageToolStateRunning = { - status: "running" - input: { - [key: string]: unknown - } - structured: { - [key: string]: unknown + type: "worktree.failed" + properties: { + message: string } - content: Array } -export type SessionMessageToolStateCompleted = { - status: "completed" - input: { - [key: string]: unknown - } - attachments?: Array - content: Array - structured: { - [key: string]: unknown +export type EventPtyCreated = { + id: string + type: "pty.created" + properties: { + info: Pty } } -export type SessionMessageToolStateError = { - status: "error" - input: { - [key: string]: unknown - } - content: Array - structured: { - [key: string]: unknown +export type EventPtyUpdated = { + id: string + type: "pty.updated" + properties: { + info: Pty } - error: SessionErrorUnknown } -export type SessionMessageAssistantTool = { - type: "tool" +export type EventPtyExited = { id: string - name: string - provider?: { - executed: boolean - metadata?: { - [key: string]: unknown - } - } - state: - | SessionMessageToolStatePending - | SessionMessageToolStateRunning - | SessionMessageToolStateCompleted - | SessionMessageToolStateError - time: { - created: number - ran?: number - completed?: number - pruned?: number + type: "pty.exited" + properties: { + id: string + exitCode: number } } -export type SessionMessageAssistant = { +export type EventPtyDeleted = { id: string - metadata?: { - [key: string]: unknown - } - time: { - created: number - completed?: number - } - type: "assistant" - agent: string - model: { + type: "pty.deleted" + properties: { id: string - providerID: string - variant: string } - content: Array - snapshot?: { - start?: string - end?: string +} + +export type EventInstallationUpdated = { + id: string + type: "installation.updated" + properties: { + version: string } - finish?: string - cost?: number - tokens?: { - input: number - output: number - reasoning: number - cache: { - read: number - write: number - } +} + +export type EventInstallationUpdateAvailable = { + id: string + type: "installation.update-available" + properties: { + version: string } - error?: SessionErrorUnknown } -export type SessionMessageCompaction = { - type: "compaction" - reason: "auto" | "manual" - summary: string - include?: string +export type EventServerConnected = { id: string - metadata?: { + type: "server.connected" + properties: { [key: string]: unknown } - time: { - created: number - } } -export type SessionMessage = - | SessionMessageAgentSwitched - | SessionMessageModelSwitched - | SessionMessageUser - | SessionMessageSynthetic - | SessionMessageShell - | SessionMessageAssistant - | SessionMessageCompaction - -export type ProviderV2Info = { +export type EventGlobalDisposed = { id: string - name: string - enabled: - | false - | { - via: "env" - name: string - } - | { - via: "account" - service: string - } - | { - via: "custom" - data: { - [key: string]: unknown - } - } - env: Array - endpoint: - | { - type: "unknown" - } - | { - type: "openai/responses" - url: string - websocket?: boolean - } - | { - type: "openai/completions" - url: string - reasoning?: - | { - type: "reasoning_content" - } - | { - type: "reasoning_details" - } - } - | { - type: "anthropic/messages" - url: string - } - | { - type: "aisdk" - package: string - url?: string - } - options: { - headers: { - [key: string]: string - } - body: { - [key: string]: unknown - } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } - } + type: "global.disposed" + properties: { + [key: string]: unknown } } -export type EventTuiToastShow1 = { +export type EventAccountAdded = { id: string - type: "tui.toast.show" + type: "account.added" properties: { - title?: string - message: string - variant: "info" | "success" | "warning" | "error" - duration?: number + account: AuthInfo } } -export type ModelV2Info1 = { +export type EventAccountRemoved = { id: string - apiID: string - providerID: string - family?: string - name: string - endpoint: - | { - type: "unknown" - } - | { - type: "openai/responses" - url: string - websocket?: boolean - } - | { - type: "openai/completions" - url: string - reasoning?: - | { - type: "reasoning_content" - } - | { - type: "reasoning_details" - } - } - | { - type: "anthropic/messages" - url: string - } - | { - type: "aisdk" - package: string - url?: string - } - capabilities: { - tools: boolean - input: Array - output: Array - } - options: { - headers: { - [key: string]: string - } - body: { - [key: string]: unknown - } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } - } - variant?: string - } - variants: Array<{ - id: string - headers: { - [key: string]: string - } - body: { - [key: string]: unknown - } - aisdk: { - provider: { - [key: string]: unknown - } - request: { - [key: string]: unknown - } - } - }> - time: { - released: number | "NaN" | "Infinity" | "-Infinity" + type: "account.removed" + properties: { + account: AuthInfo } - cost: Array<{ - tier?: { - type: "context" - size: number - } - input: number - output: number - cache: { - read: number - write: number - } - }> - status: "alpha" | "beta" | "deprecated" | "active" - enabled: boolean - limit: { - context: number - input?: number - output: number +} + +export type EventAccountSwitched = { + id: string + type: "account.switched" + properties: { + serviceID: string + from?: string + to?: string } } @@ -6073,6 +6756,9 @@ export type SessionCreateData = { providerID: string variant?: string } + metadata?: { + [key: string]: unknown + } permission?: PermissionRuleset workspaceID?: string } @@ -6203,6 +6889,9 @@ export type SessionGetResponse = SessionGetResponses[keyof SessionGetResponses] export type SessionUpdateData = { body?: { title?: string + metadata?: { + [key: string]: unknown + } permission?: PermissionRuleset time?: { archived?: number @@ -7845,7 +8534,7 @@ export type TuiShowToastResponses = { export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses] export type TuiPublishData = { - body?: EventTuiPromptAppend2 | EventTuiCommandExecute2 | EventTuiToastShow2 | EventTuiSessionSelect2 + body?: EventTuiPromptAppend | EventTuiCommandExecute | EventTuiToastShow | EventTuiSessionSelect path?: never query?: { directory?: string @@ -8048,9 +8737,9 @@ export type ExperimentalWorkspaceCreateData = { export type ExperimentalWorkspaceCreateErrors = { /** - * BadRequest | InvalidRequestError + * WorkspaceCreateError | BadRequest | InvalidRequestError */ - 400: EffectHttpApiErrorBadRequest | InvalidRequestError + 400: WorkspaceCreateError | EffectHttpApiErrorBadRequest | InvalidRequestError } export type ExperimentalWorkspaceCreateError = @@ -8206,6 +8895,8 @@ export type PtyConnectData = { query?: { directory?: string workspace?: string + cursor?: string + ticket?: string } url: "/pty/{ptyID}/connect" } diff --git a/packages/sdk/openapi.json b/packages/sdk/openapi.json index 877d9ba7e6b1..c5990ae47325 100644 --- a/packages/sdk/openapi.json +++ b/packages/sdk/openapi.json @@ -5185,6 +5185,9 @@ "required": ["id", "providerID"], "additionalProperties": false }, + "metadata": { + "type": "object" + }, "permission": { "$ref": "#/components/schemas/PermissionRuleset" }, @@ -5509,6 +5512,9 @@ "title": { "type": "string" }, + "metadata": { + "type": "object" + }, "permission": { "$ref": "#/components/schemas/PermissionRuleset" }, @@ -10038,11 +10044,14 @@ } }, "400": { - "description": "BadRequest | InvalidRequestError", + "description": "WorkspaceCreateError | BadRequest | InvalidRequestError", "content": { "application/json": { "schema": { "anyOf": [ + { + "$ref": "#/components/schemas/WorkspaceCreateError" + }, { "$ref": "#/components/schemas/effect_HttpApiError_BadRequest" }, @@ -10403,20 +10412,32 @@ "required": true }, { - "name": "directory", "in": "query", + "name": "directory", "schema": { "type": "string" - }, - "required": false + } }, { + "in": "query", "name": "workspace", + "schema": { + "type": "string" + } + }, + { "in": "query", + "name": "cursor", "schema": { "type": "string" - }, - "required": false + } + }, + { + "in": "query", + "name": "ticket", + "schema": { + "type": "string" + } } ], "responses": { @@ -10468,121 +10489,106 @@ "Event": { "anyOf": [ { - "$ref": "#/components/schemas/Event.tui.prompt.append" - }, - { - "$ref": "#/components/schemas/Event.tui.command.execute" - }, - { - "$ref": "#/components/schemas/EventTuiToastShow1" - }, - { - "$ref": "#/components/schemas/Event.tui.session.select" - }, - { - "$ref": "#/components/schemas/EventServerConnected" + "$ref": "#/components/schemas/EventModels-devRefreshed" }, { - "$ref": "#/components/schemas/EventGlobalDisposed" + "$ref": "#/components/schemas/EventPluginAdded" }, { - "$ref": "#/components/schemas/EventServerInstanceDisposed" + "$ref": "#/components/schemas/EventCatalogModelUpdated" }, { "$ref": "#/components/schemas/EventFileEdited" }, { - "$ref": "#/components/schemas/EventFileWatcherUpdated" - }, - { - "$ref": "#/components/schemas/EventLspClientDiagnostics" + "$ref": "#/components/schemas/EventSessionNextAgentSwitched" }, { - "$ref": "#/components/schemas/EventLspUpdated" + "$ref": "#/components/schemas/EventSessionNextModelSwitched" }, { - "$ref": "#/components/schemas/EventMessagePartDelta" + "$ref": "#/components/schemas/EventSessionNextPrompted" }, { - "$ref": "#/components/schemas/EventPermissionAsked" + "$ref": "#/components/schemas/EventSessionNextSynthetic" }, { - "$ref": "#/components/schemas/EventPermissionReplied" + "$ref": "#/components/schemas/EventSessionNextShellStarted" }, { - "$ref": "#/components/schemas/EventSessionDiff" + "$ref": "#/components/schemas/EventSessionNextShellEnded" }, { - "$ref": "#/components/schemas/EventSessionError" + "$ref": "#/components/schemas/EventSessionNextStepStarted" }, { - "$ref": "#/components/schemas/EventQuestionAsked" + "$ref": "#/components/schemas/EventSessionNextStepEnded" }, { - "$ref": "#/components/schemas/EventQuestionReplied" + "$ref": "#/components/schemas/EventSessionNextStepFailed" }, { - "$ref": "#/components/schemas/EventQuestionRejected" + "$ref": "#/components/schemas/EventSessionNextTextStarted" }, { - "$ref": "#/components/schemas/EventTodoUpdated" + "$ref": "#/components/schemas/EventSessionNextTextDelta" }, { - "$ref": "#/components/schemas/EventSessionStatus" + "$ref": "#/components/schemas/EventSessionNextTextEnded" }, { - "$ref": "#/components/schemas/EventSessionIdle" + "$ref": "#/components/schemas/EventSessionNextReasoningStarted" }, { - "$ref": "#/components/schemas/EventMcpToolsChanged" + "$ref": "#/components/schemas/EventSessionNextReasoningDelta" }, { - "$ref": "#/components/schemas/EventMcpBrowserOpenFailed" + "$ref": "#/components/schemas/EventSessionNextReasoningEnded" }, { - "$ref": "#/components/schemas/EventCommandExecuted" + "$ref": "#/components/schemas/EventSessionNextToolInputStarted" }, { - "$ref": "#/components/schemas/EventProjectUpdated" + "$ref": "#/components/schemas/EventSessionNextToolInputDelta" }, { - "$ref": "#/components/schemas/EventSessionCompacted" + "$ref": "#/components/schemas/EventSessionNextToolInputEnded" }, { - "$ref": "#/components/schemas/EventVcsBranchUpdated" + "$ref": "#/components/schemas/EventSessionNextToolCalled" }, { - "$ref": "#/components/schemas/EventWorkspaceReady" + "$ref": "#/components/schemas/EventSessionNextToolProgress" }, { - "$ref": "#/components/schemas/EventWorkspaceFailed" + "$ref": "#/components/schemas/EventSessionNextToolSuccess" }, { - "$ref": "#/components/schemas/EventWorkspaceStatus" + "$ref": "#/components/schemas/EventSessionNextToolFailed" }, { - "$ref": "#/components/schemas/EventWorktreeReady" + "$ref": "#/components/schemas/EventSessionNextRetried" }, { - "$ref": "#/components/schemas/EventWorktreeFailed" + "$ref": "#/components/schemas/EventSessionNextCompactionStarted" }, { - "$ref": "#/components/schemas/EventPtyCreated" + "$ref": "#/components/schemas/EventSessionNextCompactionDelta" }, { - "$ref": "#/components/schemas/EventPtyUpdated" + "$ref": "#/components/schemas/EventSessionNextCompactionEnded" }, { - "$ref": "#/components/schemas/EventPtyExited" + "$ref": "#/components/schemas/EventFileWatcherUpdated" }, { - "$ref": "#/components/schemas/EventPtyDeleted" + "$ref": "#/components/schemas/EventSessionCreated" }, { - "$ref": "#/components/schemas/EventInstallationUpdated" + "$ref": "#/components/schemas/EventSessionUpdated" }, { - "$ref": "#/components/schemas/EventInstallationUpdate-available" + "$ref": "#/components/schemas/EventSessionDeleted" }, { "$ref": "#/components/schemas/EventMessageUpdated" @@ -10597,175 +10603,109 @@ "$ref": "#/components/schemas/EventMessagePartRemoved" }, { - "$ref": "#/components/schemas/EventSessionCreated" - }, - { - "$ref": "#/components/schemas/EventSessionUpdated" - }, - { - "$ref": "#/components/schemas/EventSessionDeleted" - }, - { - "$ref": "#/components/schemas/EventSessionNextAgentSwitched" - }, - { - "$ref": "#/components/schemas/EventSessionNextModelSwitched" - }, - { - "$ref": "#/components/schemas/EventSessionNextPrompted" - }, - { - "$ref": "#/components/schemas/EventSessionNextSynthetic" - }, - { - "$ref": "#/components/schemas/EventSessionNextShellStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextShellEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextStepStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextStepEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextStepFailed" - }, - { - "$ref": "#/components/schemas/EventSessionNextTextStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextTextDelta" - }, - { - "$ref": "#/components/schemas/EventSessionNextTextEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningDelta" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextToolInputStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextToolInputDelta" - }, - { - "$ref": "#/components/schemas/EventSessionNextToolInputEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextToolCalled" - }, - { - "$ref": "#/components/schemas/EventSessionNextToolProgress" + "$ref": "#/components/schemas/EventMessagePartDelta" }, { - "$ref": "#/components/schemas/EventSessionNextToolSuccess" + "$ref": "#/components/schemas/EventPermissionAsked" }, { - "$ref": "#/components/schemas/EventSessionNextToolFailed" + "$ref": "#/components/schemas/EventPermissionReplied" }, { - "$ref": "#/components/schemas/EventSessionNextRetried" + "$ref": "#/components/schemas/EventSessionDiff" }, { - "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + "$ref": "#/components/schemas/EventSessionError" }, { - "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + "$ref": "#/components/schemas/EventQuestionAsked" }, { - "$ref": "#/components/schemas/EventSessionNextCompactionEnded" + "$ref": "#/components/schemas/EventQuestionReplied" }, { - "$ref": "#/components/schemas/EventCatalogModelUpdated" + "$ref": "#/components/schemas/EventQuestionRejected" }, { - "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + "$ref": "#/components/schemas/EventTodoUpdated" }, { - "$ref": "#/components/schemas/EventSessionNextModelSwitched" + "$ref": "#/components/schemas/EventSessionStatus" }, { - "$ref": "#/components/schemas/EventSessionNextPrompted" + "$ref": "#/components/schemas/EventSessionIdle" }, { - "$ref": "#/components/schemas/EventSessionNextSynthetic" + "$ref": "#/components/schemas/EventSessionCompacted" }, { - "$ref": "#/components/schemas/EventSessionNextShellStarted" + "$ref": "#/components/schemas/EventLspUpdated" }, { - "$ref": "#/components/schemas/EventSessionNextShellEnded" + "$ref": "#/components/schemas/Event.tui.prompt.append" }, { - "$ref": "#/components/schemas/EventSessionNextStepStarted" + "$ref": "#/components/schemas/Event.tui.command.execute" }, { - "$ref": "#/components/schemas/EventSessionNextStepEnded" + "$ref": "#/components/schemas/Event.tui.toast.show" }, { - "$ref": "#/components/schemas/EventSessionNextStepFailed" + "$ref": "#/components/schemas/Event.tui.session.select" }, { - "$ref": "#/components/schemas/EventSessionNextTextStarted" + "$ref": "#/components/schemas/EventMcpToolsChanged" }, { - "$ref": "#/components/schemas/EventSessionNextTextDelta" + "$ref": "#/components/schemas/EventMcpBrowserOpenFailed" }, { - "$ref": "#/components/schemas/EventSessionNextTextEnded" + "$ref": "#/components/schemas/EventCommandExecuted" }, { - "$ref": "#/components/schemas/EventSessionNextReasoningStarted" + "$ref": "#/components/schemas/EventProjectUpdated" }, { - "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + "$ref": "#/components/schemas/EventVcsBranchUpdated" }, { - "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + "$ref": "#/components/schemas/EventWorkspaceReady" }, { - "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + "$ref": "#/components/schemas/EventWorkspaceFailed" }, { - "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + "$ref": "#/components/schemas/EventWorkspaceStatus" }, { - "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + "$ref": "#/components/schemas/EventWorktreeReady" }, { - "$ref": "#/components/schemas/EventSessionNextToolCalled" + "$ref": "#/components/schemas/EventWorktreeFailed" }, { - "$ref": "#/components/schemas/EventSessionNextToolProgress" + "$ref": "#/components/schemas/EventPtyCreated" }, { - "$ref": "#/components/schemas/EventSessionNextToolSuccess" + "$ref": "#/components/schemas/EventPtyUpdated" }, { - "$ref": "#/components/schemas/EventSessionNextToolFailed" + "$ref": "#/components/schemas/EventPtyExited" }, { - "$ref": "#/components/schemas/EventSessionNextRetried" + "$ref": "#/components/schemas/EventPtyDeleted" }, { - "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + "$ref": "#/components/schemas/EventInstallationUpdated" }, { - "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + "$ref": "#/components/schemas/EventInstallationUpdate-available" }, { - "$ref": "#/components/schemas/EventSessionNextCompactionEnded" + "$ref": "#/components/schemas/EventServerConnected" }, { - "$ref": "#/components/schemas/EventModels-devRefreshed" + "$ref": "#/components/schemas/EventGlobalDisposed" }, { "$ref": "#/components/schemas/EventAccountAdded" @@ -10775,20 +10715,59 @@ }, { "$ref": "#/components/schemas/EventAccountSwitched" + }, + { + "$ref": "#/components/schemas/EventServerInstanceDisposed" } ] }, - "OAuth": { + "QuestionReplied": { "type": "object", "properties": { - "type": { + "sessionID": { "type": "string", - "enum": ["oauth"] - }, - "refresh": { - "type": "string" + "pattern": "^ses" }, - "access": { + "requestID": { + "type": "string", + "pattern": "^que" + }, + "answers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionAnswer" + } + } + }, + "required": ["sessionID", "requestID", "answers"], + "additionalProperties": false + }, + "QuestionRejected": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^que" + } + }, + "required": ["sessionID", "requestID"], + "additionalProperties": false + }, + "OAuth": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["oauth"] + }, + "refresh": { + "type": "string" + }, + "access": { "type": "string" }, "expires": { @@ -10886,185 +10865,32 @@ "required": ["_tag", "message"], "additionalProperties": false }, - "Event.tui.prompt.append": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["tui.prompt.append"] - }, - "properties": { - "type": "object", - "properties": { - "text": { - "type": "string" - } - }, - "required": ["text"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "Event.tui.command.execute": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["tui.command.execute"] - }, - "properties": { - "type": "object", - "properties": { - "command": { - "anyOf": [ - { - "type": "string", - "enum": [ - "session.list", - "session.new", - "session.share", - "session.interrupt", - "session.compact", - "session.page.up", - "session.page.down", - "session.line.up", - "session.line.down", - "session.half.page.up", - "session.half.page.down", - "session.first", - "session.last", - "prompt.clear", - "prompt.submit", - "agent.cycle" - ] - }, - { - "type": "string" - } - ] - } - }, - "required": ["command"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "Event.tui.toast.show": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["tui.toast.show"] - }, - "properties": { - "type": "object", - "properties": { - "title": { - "type": "string" - }, - "message": { - "type": "string" - }, - "variant": { - "type": "string", - "enum": ["info", "success", "warning", "error"] - }, - "duration": { - "type": "integer", - "exclusiveMinimum": 0 - } - }, - "required": ["message", "variant"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "Event.tui.session.select": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["tui.session.select"] - }, - "properties": { - "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses", - "description": "Session ID to navigate to" - } - }, - "required": ["sessionID"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "PermissionRequest": { + "Prompt": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^per" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "permission": { + "text": { "type": "string" }, - "patterns": { + "files": { "type": "array", "items": { - "type": "string" + "$ref": "#/components/schemas/PromptFileAttachment" } }, - "metadata": { - "type": "object" - }, - "always": { + "agents": { "type": "array", "items": { - "type": "string" + "$ref": "#/components/schemas/PromptAgentAttachment" } }, - "tool": { - "type": "object", - "properties": { - "messageID": { - "type": "string", - "pattern": "^msg" - }, - "callID": { - "type": "string" - } - }, - "required": ["messageID", "callID"], - "additionalProperties": false + "references": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptReferenceAttachment" + } } }, - "required": ["id", "sessionID", "permission", "patterns", "metadata", "always"], + "required": ["text"], "additionalProperties": false }, "SnapshotFileDiff": { @@ -11090,622 +10916,471 @@ "required": ["additions", "deletions"], "additionalProperties": false }, - "ProviderAuthError": { + "Session": { "type": "object", "properties": { - "name": { + "id": { "type": "string", - "enum": ["ProviderAuthError"] + "pattern": "^ses" }, - "data": { + "slug": { + "type": "string" + }, + "projectID": { + "type": "string" + }, + "workspaceID": { + "type": "string", + "pattern": "^wrk" + }, + "directory": { + "type": "string" + }, + "path": { + "type": "string" + }, + "parentID": { + "type": "string", + "pattern": "^ses" + }, + "summary": { "type": "object", "properties": { - "providerID": { - "type": "string" + "additions": { + "type": "number" }, - "message": { - "type": "string" - } - }, - "required": ["providerID", "message"], - "additionalProperties": false - } - }, - "required": ["name", "data"], - "additionalProperties": false - }, - "UnknownError": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": ["UnknownError"] - }, - "data": { - "type": "object", - "properties": { - "message": { - "type": "string" + "deletions": { + "type": "number" }, - "ref": { - "type": "string" + "files": { + "type": "number" + }, + "diffs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } } }, - "required": ["message"], + "required": ["additions", "deletions", "files"], "additionalProperties": false - } - }, - "required": ["name", "data"], - "additionalProperties": false - }, - "MessageOutputLengthError": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": ["MessageOutputLengthError"] }, - "data": { - "type": "object", - "properties": {} - } - }, - "required": ["name", "data"], - "additionalProperties": false - }, - "MessageAbortedError": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": ["MessageAbortedError"] + "cost": { + "type": "number" }, - "data": { + "tokens": { "type": "object", "properties": { - "message": { - "type": "string" + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false } }, - "required": ["message"], + "required": ["input", "output", "reasoning", "cache"], "additionalProperties": false - } - }, - "required": ["name", "data"], - "additionalProperties": false - }, - "StructuredOutputError": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": ["StructuredOutputError"] }, - "data": { + "share": { "type": "object", "properties": { - "message": { + "url": { "type": "string" - }, - "retries": { - "type": "integer", - "minimum": 0 } }, - "required": ["message", "retries"], + "required": ["url"], "additionalProperties": false - } - }, - "required": ["name", "data"], - "additionalProperties": false - }, - "ContextOverflowError": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": ["ContextOverflowError"] }, - "data": { + "title": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "model": { "type": "object", "properties": { - "message": { + "id": { "type": "string" }, - "responseBody": { + "providerID": { + "type": "string" + }, + "variant": { "type": "string" } }, - "required": ["message"], + "required": ["id", "providerID"], "additionalProperties": false - } - }, - "required": ["name", "data"], - "additionalProperties": false - }, - "APIError": { - "type": "object", - "properties": { - "name": { - "type": "string", - "enum": ["APIError"] }, - "data": { + "version": { + "type": "string" + }, + "metadata": { + "type": "object" + }, + "time": { "type": "object", "properties": { - "message": { - "type": "string" + "created": { + "type": "integer", + "minimum": 0 }, - "statusCode": { + "updated": { "type": "integer", "minimum": 0 }, - "isRetryable": { - "type": "boolean" + "compacting": { + "type": "integer", + "minimum": 0 }, - "responseHeaders": { - "type": "object", - "additionalProperties": { - "type": "string" - } + "archived": { + "type": "number" + } + }, + "required": ["created", "updated"], + "additionalProperties": false + }, + "permission": { + "$ref": "#/components/schemas/PermissionRuleset" + }, + "revert": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "pattern": "^msg" }, - "responseBody": { + "partID": { + "type": "string", + "pattern": "^prt" + }, + "snapshot": { "type": "string" }, - "metadata": { - "type": "object", - "additionalProperties": { - "type": "string" - } + "diff": { + "type": "string" } }, - "required": ["message", "isRetryable"], + "required": ["messageID"], "additionalProperties": false } }, - "required": ["name", "data"], + "required": ["id", "slug", "projectID", "directory", "title", "version", "time"], "additionalProperties": false }, - "QuestionOption": { + "OutputFormatText": { "type": "object", "properties": { - "label": { - "type": "string", - "description": "Display text (1-5 words, concise)" - }, - "description": { + "type": { "type": "string", - "description": "Explanation of choice" + "enum": ["text"] } }, - "required": ["label", "description"], + "required": ["type"], "additionalProperties": false }, - "QuestionInfo": { + "JSONSchema": { + "type": "object" + }, + "OutputFormatJsonSchema": { "type": "object", "properties": { - "question": { - "type": "string", - "description": "Complete question" - }, - "header": { + "type": { "type": "string", - "description": "Very short label (max 30 chars)" - }, - "options": { - "type": "array", - "items": { - "$ref": "#/components/schemas/QuestionOption" - }, - "description": "Available choices" + "enum": ["json_schema"] }, - "multiple": { - "type": "boolean" + "schema": { + "$ref": "#/components/schemas/JSONSchema" }, - "custom": { - "type": "boolean" + "retryCount": { + "type": "integer", + "minimum": 0 } }, - "required": ["question", "header", "options"], + "required": ["type", "schema"], "additionalProperties": false }, - "QuestionTool": { - "type": "object", - "properties": { - "messageID": { - "type": "string", - "pattern": "^msg" + "OutputFormat": { + "anyOf": [ + { + "$ref": "#/components/schemas/OutputFormatText" }, - "callID": { - "type": "string" + { + "$ref": "#/components/schemas/OutputFormatJsonSchema" } - }, - "required": ["messageID", "callID"], - "additionalProperties": false + ] }, - "QuestionRequest": { + "UserMessage": { "type": "object", "properties": { "id": { "type": "string", - "pattern": "^que" + "pattern": "^msg" }, "sessionID": { "type": "string", "pattern": "^ses" }, - "questions": { - "type": "array", - "items": { - "$ref": "#/components/schemas/QuestionInfo" + "role": { + "type": "string", + "enum": ["user"] + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "minimum": 0 + } }, - "description": "Questions to ask" + "required": ["created"], + "additionalProperties": false }, - "tool": { - "$ref": "#/components/schemas/QuestionTool" + "format": { + "$ref": "#/components/schemas/OutputFormat" + }, + "summary": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "body": { + "type": "string" + }, + "diffs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } + } + }, + "required": ["diffs"], + "additionalProperties": false + }, + "agent": { + "type": "string" + }, + "model": { + "type": "object", + "properties": { + "providerID": { + "type": "string" + }, + "modelID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": ["providerID", "modelID"], + "additionalProperties": false + }, + "system": { + "type": "string" + }, + "tools": { + "type": "object", + "additionalProperties": { + "type": "boolean" + } } }, - "required": ["id", "sessionID", "questions"], + "required": ["id", "sessionID", "role", "time", "agent", "model"], "additionalProperties": false }, - "QuestionAnswer": { - "type": "array", - "items": { - "type": "string" - } - }, - "QuestionReplied": { + "ProviderAuthError": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "requestID": { + "name": { "type": "string", - "pattern": "^que" + "enum": ["ProviderAuthError"] }, - "answers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/QuestionAnswer" - } + "data": { + "type": "object", + "properties": { + "providerID": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": ["providerID", "message"], + "additionalProperties": false } }, - "required": ["sessionID", "requestID", "answers"], + "required": ["name", "data"], "additionalProperties": false }, - "QuestionRejected": { + "UnknownError": { "type": "object", "properties": { - "sessionID": { + "name": { "type": "string", - "pattern": "^ses" + "enum": ["UnknownError"] }, - "requestID": { - "type": "string", - "pattern": "^que" + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "ref": { + "type": "string" + } + }, + "required": ["message"], + "additionalProperties": false } }, - "required": ["sessionID", "requestID"], + "required": ["name", "data"], "additionalProperties": false }, - "Todo": { + "MessageOutputLengthError": { "type": "object", "properties": { - "content": { - "type": "string", - "description": "Brief description of the task" - }, - "status": { + "name": { "type": "string", - "description": "Current status of the task: pending, in_progress, completed, cancelled" + "enum": ["MessageOutputLengthError"] }, - "priority": { - "type": "string", - "description": "Priority level of the task: high, medium, low" + "data": { + "type": "object", + "properties": {} } }, - "required": ["content", "status", "priority"], + "required": ["name", "data"], "additionalProperties": false }, - "SessionStatus": { - "anyOf": [ - { + "MessageAbortedError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": ["MessageAbortedError"] + }, + "data": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["idle"] + "message": { + "type": "string" } }, - "required": ["type"], + "required": ["message"], "additionalProperties": false + } + }, + "required": ["name", "data"], + "additionalProperties": false + }, + "StructuredOutputError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": ["StructuredOutputError"] }, - { + "data": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["retry"] - }, - "attempt": { - "type": "integer", - "minimum": 0 - }, "message": { "type": "string" }, - "action": { - "type": "object", - "properties": { - "reason": { - "type": "string" - }, - "provider": { - "type": "string" - }, - "title": { - "type": "string" - }, - "message": { - "type": "string" - }, - "label": { - "type": "string" - }, - "link": { - "type": "string" - } - }, - "required": ["reason", "provider", "title", "message", "label"], - "additionalProperties": false - }, - "next": { + "retries": { "type": "integer", "minimum": 0 } }, - "required": ["type", "attempt", "message", "next"], + "required": ["message", "retries"], "additionalProperties": false + } + }, + "required": ["name", "data"], + "additionalProperties": false + }, + "ContextOverflowError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": ["ContextOverflowError"] }, - { + "data": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["busy"] + "message": { + "type": "string" + }, + "responseBody": { + "type": "string" } }, - "required": ["type"], + "required": ["message"], "additionalProperties": false } - ] + }, + "required": ["name", "data"], + "additionalProperties": false }, - "Project": { + "APIError": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "worktree": { - "type": "string" - }, - "vcs": { - "type": "string", - "enum": ["git"] - }, "name": { - "type": "string" + "type": "string", + "enum": ["APIError"] }, - "icon": { + "data": { "type": "object", "properties": { - "url": { - "type": "string" - }, - "override": { - "type": "string" - }, - "color": { + "message": { "type": "string" - } - }, - "additionalProperties": false - }, - "commands": { - "type": "object", - "properties": { - "start": { - "type": "string", - "description": "Startup script to run when creating a new workspace (worktree)" - } - }, - "additionalProperties": false - }, - "time": { - "type": "object", - "properties": { - "created": { - "type": "integer", - "minimum": 0 - }, - "updated": { - "type": "integer", - "minimum": 0 }, - "initialized": { - "type": "integer", - "minimum": 0 - } - }, - "required": ["created", "updated"], - "additionalProperties": false - }, - "sandboxes": { - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": ["id", "worktree", "time", "sandboxes"], - "additionalProperties": false - }, - "Pty": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^pty" - }, - "title": { - "type": "string" - }, - "command": { - "type": "string" - }, - "args": { - "type": "array", - "items": { - "type": "string" - } - }, - "cwd": { - "type": "string" - }, - "status": { - "type": "string", - "enum": ["running", "exited"] - }, - "pid": { - "type": "integer", - "exclusiveMinimum": 0 - } - }, - "required": ["id", "title", "command", "args", "cwd", "status", "pid"], - "additionalProperties": false - }, - "OutputFormatText": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["text"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - "JSONSchema": { - "type": "object" - }, - "OutputFormatJsonSchema": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["json_schema"] - }, - "schema": { - "$ref": "#/components/schemas/JSONSchema" - }, - "retryCount": { - "type": "integer", - "minimum": 0 - } - }, - "required": ["type", "schema"], - "additionalProperties": false - }, - "OutputFormat": { - "anyOf": [ - { - "$ref": "#/components/schemas/OutputFormatText" - }, - { - "$ref": "#/components/schemas/OutputFormatJsonSchema" - } - ] - }, - "UserMessage": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^msg" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "role": { - "type": "string", - "enum": ["user"] - }, - "time": { - "type": "object", - "properties": { - "created": { + "statusCode": { "type": "integer", "minimum": 0 - } - }, - "required": ["created"], - "additionalProperties": false - }, - "format": { - "$ref": "#/components/schemas/OutputFormat" - }, - "summary": { - "type": "object", - "properties": { - "title": { - "type": "string" }, - "body": { - "type": "string" + "isRetryable": { + "type": "boolean" }, - "diffs": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SnapshotFileDiff" + "responseHeaders": { + "type": "object", + "additionalProperties": { + "type": "string" } - } - }, - "required": ["diffs"], - "additionalProperties": false - }, - "agent": { - "type": "string" - }, - "model": { - "type": "object", - "properties": { - "providerID": { - "type": "string" }, - "modelID": { + "responseBody": { "type": "string" }, - "variant": { - "type": "string" + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } } }, - "required": ["providerID", "modelID"], + "required": ["message", "isRetryable"], "additionalProperties": false - }, - "system": { - "type": "string" - }, - "tools": { - "type": "object", - "additionalProperties": { - "type": "boolean" - } } }, - "required": ["id", "sessionID", "role", "time", "agent", "model"], + "required": ["name", "data"], "additionalProperties": false }, "AssistantMessage": { @@ -12659,224 +12334,193 @@ } ] }, - "PermissionAction": { - "type": "string", - "enum": ["allow", "deny", "ask"] - }, - "PermissionRule": { + "QuestionOption": { "type": "object", "properties": { - "permission": { - "type": "string" - }, - "pattern": { - "type": "string" + "label": { + "type": "string", + "description": "Display text (1-5 words, concise)" }, - "action": { - "$ref": "#/components/schemas/PermissionAction" + "description": { + "type": "string", + "description": "Explanation of choice" } }, - "required": ["permission", "pattern", "action"], + "required": ["label", "description"], "additionalProperties": false }, - "PermissionRuleset": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PermissionRule" - } - }, - "Session": { + "QuestionInfo": { "type": "object", "properties": { - "id": { + "question": { "type": "string", - "pattern": "^ses" - }, - "slug": { - "type": "string" + "description": "Complete question" }, - "projectID": { - "type": "string" - }, - "workspaceID": { + "header": { "type": "string", - "pattern": "^wrk" + "description": "Very short label (max 30 chars)" }, - "directory": { - "type": "string" + "options": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionOption" + }, + "description": "Available choices" }, - "path": { + "multiple": { + "type": "boolean" + }, + "custom": { + "type": "boolean" + } + }, + "required": ["question", "header", "options"], + "additionalProperties": false + }, + "QuestionTool": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "callID": { "type": "string" + } + }, + "required": ["messageID", "callID"], + "additionalProperties": false + }, + "QuestionAnswer": { + "type": "array", + "items": { + "type": "string" + } + }, + "Todo": { + "type": "object", + "properties": { + "content": { + "type": "string", + "description": "Brief description of the task" }, - "parentID": { + "status": { "type": "string", - "pattern": "^ses" + "description": "Current status of the task: pending, in_progress, completed, cancelled" }, - "summary": { + "priority": { + "type": "string", + "description": "Priority level of the task: high, medium, low" + } + }, + "required": ["content", "status", "priority"], + "additionalProperties": false + }, + "SessionStatus": { + "anyOf": [ + { "type": "object", "properties": { - "additions": { - "type": "number" - }, - "deletions": { - "type": "number" - }, - "files": { - "type": "number" - }, - "diffs": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SnapshotFileDiff" - } + "type": { + "type": "string", + "enum": ["idle"] } }, - "required": ["additions", "deletions", "files"], + "required": ["type"], "additionalProperties": false }, - "cost": { - "type": "number" - }, - "tokens": { + { "type": "object", "properties": { - "input": { - "type": "number" + "type": { + "type": "string", + "enum": ["retry"] }, - "output": { - "type": "number" + "attempt": { + "type": "integer", + "minimum": 0 }, - "reasoning": { - "type": "number" + "message": { + "type": "string" }, - "cache": { + "action": { "type": "object", "properties": { - "read": { - "type": "number" + "reason": { + "type": "string" }, - "write": { - "type": "number" + "provider": { + "type": "string" + }, + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "label": { + "type": "string" + }, + "link": { + "type": "string" } }, - "required": ["read", "write"], + "required": ["reason", "provider", "title", "message", "label"], "additionalProperties": false - } - }, - "required": ["input", "output", "reasoning", "cache"], - "additionalProperties": false - }, - "share": { - "type": "object", - "properties": { - "url": { - "type": "string" - } - }, - "required": ["url"], - "additionalProperties": false - }, - "title": { - "type": "string" - }, - "agent": { - "type": "string" - }, - "model": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "providerID": { - "type": "string" - }, - "variant": { - "type": "string" - } - }, - "required": ["id", "providerID"], - "additionalProperties": false - }, - "version": { - "type": "string" - }, - "time": { - "type": "object", - "properties": { - "created": { - "type": "integer", - "minimum": 0 - }, - "updated": { - "type": "integer", - "minimum": 0 }, - "compacting": { + "next": { "type": "integer", "minimum": 0 - }, - "archived": { - "type": "number" } }, - "required": ["created", "updated"], + "required": ["type", "attempt", "message", "next"], "additionalProperties": false }, - "permission": { - "$ref": "#/components/schemas/PermissionRuleset" - }, - "revert": { + { "type": "object", "properties": { - "messageID": { - "type": "string", - "pattern": "^msg" - }, - "partID": { + "type": { "type": "string", - "pattern": "^prt" - }, - "snapshot": { - "type": "string" - }, - "diff": { - "type": "string" + "enum": ["busy"] } }, - "required": ["messageID"], + "required": ["type"], "additionalProperties": false } - }, - "required": ["id", "slug", "projectID", "directory", "title", "version", "time"], - "additionalProperties": false + ] }, - "Prompt": { + "Pty": { "type": "object", "properties": { - "text": { + "id": { + "type": "string", + "pattern": "^pty" + }, + "title": { "type": "string" }, - "files": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PromptFileAttachment" - } + "command": { + "type": "string" }, - "agents": { + "args": { "type": "array", "items": { - "$ref": "#/components/schemas/PromptAgentAttachment" + "type": "string" } }, - "references": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PromptReferenceAttachment" - } + "cwd": { + "type": "string" + }, + "status": { + "type": "string", + "enum": ["running", "exited"] + }, + "pid": { + "type": "integer", + "minimum": 0 } }, - "required": ["text"], + "required": ["id", "title", "command", "args", "cwd", "status", "pid"], "additionalProperties": false }, "GlobalEvent": { @@ -12894,368 +12538,2504 @@ "payload": { "anyOf": [ { - "$ref": "#/components/schemas/Event.tui.prompt.append" - }, - { - "$ref": "#/components/schemas/Event.tui.command.execute" - }, - { - "$ref": "#/components/schemas/Event.tui.toast.show" - }, - { - "$ref": "#/components/schemas/Event.tui.session.select" - }, - { - "$ref": "#/components/schemas/EventServerConnected" - }, - { - "$ref": "#/components/schemas/EventGlobalDisposed" - }, - { - "$ref": "#/components/schemas/EventServerInstanceDisposed" - }, - { - "$ref": "#/components/schemas/EventFileEdited" - }, - { - "$ref": "#/components/schemas/EventFileWatcherUpdated" - }, - { - "$ref": "#/components/schemas/EventLspClientDiagnostics" - }, - { - "$ref": "#/components/schemas/EventLspUpdated" - }, - { - "$ref": "#/components/schemas/EventMessagePartDelta" - }, - { - "$ref": "#/components/schemas/EventPermissionAsked" - }, - { - "$ref": "#/components/schemas/EventPermissionReplied" - }, - { - "$ref": "#/components/schemas/EventSessionDiff" - }, - { - "$ref": "#/components/schemas/EventSessionError" - }, - { - "$ref": "#/components/schemas/EventQuestionAsked" - }, - { - "$ref": "#/components/schemas/EventQuestionReplied" - }, - { - "$ref": "#/components/schemas/EventQuestionRejected" - }, - { - "$ref": "#/components/schemas/EventTodoUpdated" - }, - { - "$ref": "#/components/schemas/EventSessionStatus" - }, - { - "$ref": "#/components/schemas/EventSessionIdle" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["models-dev.refreshed"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventMcpToolsChanged" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["plugin.added"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "required": ["id"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventMcpBrowserOpenFailed" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["catalog.model.updated"] + }, + "properties": { + "type": "object", + "properties": { + "model": { + "$ref": "#/components/schemas/ModelV2Info" + } + }, + "required": ["model"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventCommandExecuted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["file.edited"] + }, + "properties": { + "type": "object", + "properties": { + "file": { + "type": "string" + } + }, + "required": ["file"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventProjectUpdated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.agent.switched"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "agent": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "agent"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionCompacted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.model.switched"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": ["id", "providerID"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "model"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventVcsBranchUpdated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.prompted"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "prompt": { + "$ref": "#/components/schemas/Prompt" + } + }, + "required": ["timestamp", "sessionID", "prompt"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventWorkspaceReady" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.synthetic"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventWorkspaceFailed" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.shell.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "command": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "command"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventWorkspaceStatus" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.shell.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "output": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "output"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventWorktreeReady" - }, - { - "$ref": "#/components/schemas/EventWorktreeFailed" - }, - { - "$ref": "#/components/schemas/EventPtyCreated" - }, - { - "$ref": "#/components/schemas/EventPtyUpdated" - }, - { - "$ref": "#/components/schemas/EventPtyExited" - }, - { - "$ref": "#/components/schemas/EventPtyDeleted" - }, - { - "$ref": "#/components/schemas/EventInstallationUpdated" - }, - { - "$ref": "#/components/schemas/EventInstallationUpdate-available" - }, - { - "$ref": "#/components/schemas/EventMessageUpdated" - }, - { - "$ref": "#/components/schemas/EventMessageRemoved" - }, - { - "$ref": "#/components/schemas/EventMessagePartUpdated" - }, - { - "$ref": "#/components/schemas/EventMessagePartRemoved" - }, - { - "$ref": "#/components/schemas/EventSessionCreated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.step.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "agent": { + "type": "string" + }, + "model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": ["id", "providerID"], + "additionalProperties": false + }, + "snapshot": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "agent", "model"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionUpdated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.step.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "finish": { + "type": "string" + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "reasoning", "cache"], + "additionalProperties": false + }, + "snapshot": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "finish", "cost", "tokens"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionDeleted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.step.failed"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" + } + }, + "required": ["timestamp", "sessionID", "error"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.text.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + } + }, + "required": ["timestamp", "sessionID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextModelSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.text.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "delta": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextPrompted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.text.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextSynthetic" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.reasoning.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reasoningID": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "reasoningID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextShellStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.reasoning.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reasoningID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "reasoningID", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextShellEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextStepStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextStepEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextStepFailed" - }, - { - "$ref": "#/components/schemas/EventSessionNextTextStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextTextDelta" - }, - { - "$ref": "#/components/schemas/EventSessionNextTextEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.reasoning.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reasoningID": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "reasoningID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.input.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "name"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.input.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.input.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "callID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.called"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "tool": { + "type": "string" + }, + "input": { + "type": "object" + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "callID", "tool", "input", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolCalled" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.progress"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } + } + }, + "required": ["timestamp", "sessionID", "callID", "structured", "content"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolProgress" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.success"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "callID", "structured", "content", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolSuccess" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.failed"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false + } + }, + "required": ["timestamp", "sessionID", "callID", "error", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolFailed" - }, - { - "$ref": "#/components/schemas/EventSessionNextRetried" - }, - { - "$ref": "#/components/schemas/EventSessionNextCompactionStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextCompactionDelta" - }, - { - "$ref": "#/components/schemas/EventSessionNextCompactionEnded" - }, - { - "$ref": "#/components/schemas/EventCatalogModelUpdated" - }, - { - "$ref": "#/components/schemas/EventSessionNextAgentSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.retried"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "attempt": { + "type": "number" + }, + "error": { + "$ref": "#/components/schemas/SessionNextRetry_error" + } + }, + "required": ["timestamp", "sessionID", "attempt", "error"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextModelSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.compaction.started"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "reason": { + "type": "string", + "enum": ["auto", "manual"] + } + }, + "required": ["timestamp", "sessionID", "reason"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextPrompted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.compaction.delta"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextSynthetic" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.compaction.ended"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + }, + "include": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextShellStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["file.watcher.updated"] + }, + "properties": { + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "event": { + "type": "string", + "enum": ["add", "change", "unlink"] + } + }, + "required": ["file", "event"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextShellEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.created"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextStepStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextStepEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.deleted"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextStepFailed" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Message" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextTextStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.removed"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + } + }, + "required": ["sessionID", "messageID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextTextDelta" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.part.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "part": { + "$ref": "#/components/schemas/Part" + }, + "time": { + "type": "number" + } + }, + "required": ["sessionID", "part", "time"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextTextEnded" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningStarted" - }, - { - "$ref": "#/components/schemas/EventSessionNextReasoningDelta" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.part.removed"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "partID": { + "type": "string", + "pattern": "^prt" + } + }, + "required": ["sessionID", "messageID", "partID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextReasoningEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["message.part.delta"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "partID": { + "type": "string", + "pattern": "^prt" + }, + "field": { + "type": "string" + }, + "delta": { + "type": "string" + } + }, + "required": ["sessionID", "messageID", "partID", "field", "delta"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolInputStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["permission.asked"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^per" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "permission": { + "type": "string" + }, + "patterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "always": { + "type": "array", + "items": { + "type": "string" + } + }, + "tool": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "callID": { + "type": "string" + } + }, + "required": ["messageID", "callID"], + "additionalProperties": false + } + }, + "required": ["id", "sessionID", "permission", "patterns", "metadata", "always"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolInputDelta" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["permission.replied"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^per" + }, + "reply": { + "type": "string", + "enum": ["once", "always", "reject"] + } + }, + "required": ["sessionID", "requestID", "reply"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolInputEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.diff"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "diff": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } + } + }, + "required": ["sessionID", "diff"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolCalled" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.error"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "error": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProviderAuthError" + }, + { + "$ref": "#/components/schemas/UnknownError" + }, + { + "$ref": "#/components/schemas/MessageOutputLengthError" + }, + { + "$ref": "#/components/schemas/MessageAbortedError" + }, + { + "$ref": "#/components/schemas/StructuredOutputError" + }, + { + "$ref": "#/components/schemas/ContextOverflowError" + }, + { + "$ref": "#/components/schemas/APIError" + } + ] + } + }, + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolProgress" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["question.asked"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^que" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionInfo" + }, + "description": "Questions to ask" + }, + "tool": { + "$ref": "#/components/schemas/QuestionTool" + } + }, + "required": ["id", "sessionID", "questions"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolSuccess" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["question.replied"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^que" + }, + "answers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionAnswer" + } + } + }, + "required": ["sessionID", "requestID", "answers"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextToolFailed" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["question.rejected"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^que" + } + }, + "required": ["sessionID", "requestID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextRetried" - }, - { - "$ref": "#/components/schemas/EventSessionNextCompactionStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["todo.updated"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "todos": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Todo" + } + } + }, + "required": ["sessionID", "todos"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextCompactionDelta" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.status"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "status": { + "$ref": "#/components/schemas/SessionStatus" + } + }, + "required": ["sessionID", "status"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventSessionNextCompactionEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.idle"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + } + }, + "required": ["sessionID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventModels-devRefreshed" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.compacted"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + } + }, + "required": ["sessionID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventAccountAdded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["lsp.updated"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventAccountRemoved" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["tui.prompt.append"] + }, + "properties": { + "type": "object", + "properties": { + "text": { + "type": "string" + } + }, + "required": ["text"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/EventAccountSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["tui.command.execute"] + }, + "properties": { + "type": "object", + "properties": { + "command": { + "anyOf": [ + { + "type": "string", + "enum": [ + "session.list", + "session.new", + "session.share", + "session.interrupt", + "session.compact", + "session.page.up", + "session.page.down", + "session.line.up", + "session.line.down", + "session.half.page.up", + "session.half.page.down", + "session.first", + "session.last", + "prompt.clear", + "prompt.submit", + "agent.cycle" + ] + }, + { + "type": "string" + } + ] + } + }, + "required": ["command"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventMessageUpdated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["tui.toast.show"] + }, + "properties": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "message": { + "type": "string" + }, + "variant": { + "type": "string", + "enum": ["info", "success", "warning", "error"] + }, + "duration": { + "type": "integer", + "exclusiveMinimum": 0 + } + }, + "required": ["message", "variant"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventMessageRemoved" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["tui.session.select"] + }, + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses", + "description": "Session ID to navigate to" + } + }, + "required": ["sessionID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventMessagePartUpdated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["mcp.tools.changed"] + }, + "properties": { + "type": "object", + "properties": { + "server": { + "type": "string" + } + }, + "required": ["server"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventMessagePartRemoved" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["mcp.browser.open.failed"] + }, + "properties": { + "type": "object", + "properties": { + "mcpName": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": ["mcpName", "url"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionCreated" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["command.executed"] + }, + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "arguments": { + "type": "string" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + } + }, + "required": ["name", "sessionID", "arguments", "messageID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionUpdated" - }, - { - "$ref": "#/components/schemas/SyncEventSessionDeleted" - }, - { - "$ref": "#/components/schemas/SyncEventSessionNextAgentSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["project.updated"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "worktree": { + "type": "string" + }, + "vcs": { + "type": "string", + "enum": ["git"] + }, + "name": { + "type": "string" + }, + "icon": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "override": { + "type": "string" + }, + "color": { + "type": "string" + } + }, + "additionalProperties": false + }, + "commands": { + "type": "object", + "properties": { + "start": { + "type": "string", + "description": "Startup script to run when creating a new workspace (worktree)" + } + }, + "additionalProperties": false + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "minimum": 0 + }, + "updated": { + "type": "integer", + "minimum": 0 + }, + "initialized": { + "type": "integer", + "minimum": 0 + } + }, + "required": ["created", "updated"], + "additionalProperties": false + }, + "sandboxes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["id", "worktree", "time", "sandboxes"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextModelSwitched" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["vcs.branch.updated"] + }, + "properties": { + "type": "object", + "properties": { + "branch": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextPrompted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["workspace.ready"] + }, + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "required": ["name"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextSynthetic" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["workspace.failed"] + }, + "properties": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": ["message"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextShellStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["workspace.status"] + }, + "properties": { + "type": "object", + "properties": { + "workspaceID": { + "type": "string", + "pattern": "^wrk" + }, + "status": { + "type": "string", + "enum": ["connected", "connecting", "disconnected", "error"] + } + }, + "required": ["workspaceID", "status"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextShellEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["worktree.ready"] + }, + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "branch": { + "type": "string" + } + }, + "required": ["name"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextStepStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["worktree.failed"] + }, + "properties": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": ["message"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextStepEnded" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["pty.created"] + }, + "properties": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": ["info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextStepFailed" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["pty.updated"] + }, + "properties": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": ["info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextTextStarted" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["pty.exited"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^pty" + }, + "exitCode": { + "type": "integer", + "minimum": 0 + } + }, + "required": ["id", "exitCode"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false }, { - "$ref": "#/components/schemas/SyncEventSessionNextTextDelta" - }, + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["pty.deleted"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^pty" + } + }, + "required": ["id"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["installation.updated"] + }, + "properties": { + "type": "object", + "properties": { + "version": { + "type": "string" + } + }, + "required": ["version"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["installation.update-available"] + }, + "properties": { + "type": "object", + "properties": { + "version": { + "type": "string" + } + }, + "required": ["version"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["server.connected"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["global.disposed"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["account.added"] + }, + "properties": { + "type": "object", + "properties": { + "account": { + "$ref": "#/components/schemas/AuthInfo" + } + }, + "required": ["account"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["account.removed"] + }, + "properties": { + "type": "object", + "properties": { + "account": { + "$ref": "#/components/schemas/AuthInfo" + } + }, + "required": ["account"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["account.switched"] + }, + "properties": { + "type": "object", + "properties": { + "serviceID": { + "type": "string" + }, + "from": { + "type": "string" + }, + "to": { + "type": "string" + } + }, + "required": ["serviceID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + { + "$ref": "#/components/schemas/EventServerInstanceDisposed" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextAgentSwitched" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextModelSwitched" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextPrompted" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextSynthetic" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextShellStarted" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextShellEnded" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextStepStarted" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextStepEnded" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextStepFailed" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextTextStarted" + }, + { + "$ref": "#/components/schemas/SyncEventSessionNextTextDelta" + }, { "$ref": "#/components/schemas/SyncEventSessionNextTextEnded" }, @@ -13300,6 +15080,27 @@ }, { "$ref": "#/components/schemas/SyncEventSessionNextCompactionEnded" + }, + { + "$ref": "#/components/schemas/SyncEventSessionCreated" + }, + { + "$ref": "#/components/schemas/SyncEventSessionUpdated" + }, + { + "$ref": "#/components/schemas/SyncEventSessionDeleted" + }, + { + "$ref": "#/components/schemas/SyncEventMessageUpdated" + }, + { + "$ref": "#/components/schemas/SyncEventMessageRemoved" + }, + { + "$ref": "#/components/schemas/SyncEventMessagePartUpdated" + }, + { + "$ref": "#/components/schemas/SyncEventMessagePartRemoved" } ] } @@ -13588,7 +15389,20 @@ "enum": [false] } ], - "description": "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout." + "description": "Timeout in milliseconds for full requests to this provider. Set to false to disable timeout." + }, + "headerTimeout": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0 + }, + { + "type": "boolean", + "enum": [false] + } + ], + "description": "Timeout in milliseconds to wait for response headers. Provider integrations may set defaults. Set to false to disable timeout." }, "chunkTimeout": { "type": "integer", @@ -13717,7 +15531,6 @@ } } }, - "required": ["input", "output"], "additionalProperties": false }, "experimental": { @@ -14303,6 +16116,12 @@ "mcp_timeout": { "type": "integer", "exclusiveMinimum": 0 + }, + "policies": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConfigV2ExperimentalPolicy" + } } }, "additionalProperties": false @@ -14741,6 +16560,32 @@ "required": ["directory"], "additionalProperties": false }, + "PermissionAction": { + "type": "string", + "enum": ["allow", "deny", "ask"] + }, + "PermissionRule": { + "type": "object", + "properties": { + "permission": { + "type": "string" + }, + "pattern": { + "type": "string" + }, + "action": { + "$ref": "#/components/schemas/PermissionAction" + } + }, + "required": ["permission", "pattern", "action"], + "additionalProperties": false + }, + "PermissionRuleset": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PermissionRule" + } + }, "ProjectSummary": { "type": "object", "properties": { @@ -14873,6 +16718,9 @@ "version": { "type": "string" }, + "metadata": { + "type": "object" + }, "time": { "type": "object", "properties": { @@ -15448,7 +17296,77 @@ "required": ["_tag", "name", "message"], "additionalProperties": false }, - "ProjectNotFoundError": { + "Project": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "worktree": { + "type": "string" + }, + "vcs": { + "type": "string", + "enum": ["git"] + }, + "name": { + "type": "string" + }, + "icon": { + "type": "object", + "properties": { + "url": { + "type": "string" + }, + "override": { + "type": "string" + }, + "color": { + "type": "string" + } + }, + "additionalProperties": false + }, + "commands": { + "type": "object", + "properties": { + "start": { + "type": "string", + "description": "Startup script to run when creating a new workspace (worktree)" + } + }, + "additionalProperties": false + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "integer", + "minimum": 0 + }, + "updated": { + "type": "integer", + "minimum": 0 + }, + "initialized": { + "type": "integer", + "minimum": 0 + } + }, + "required": ["created", "updated"], + "additionalProperties": false + }, + "sandboxes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["id", "worktree", "time", "sandboxes"], + "additionalProperties": false + }, + "ProjectNotFoundError": { "type": "object", "properties": { "_tag": { @@ -15496,6 +17414,31 @@ "required": ["_tag", "message"], "additionalProperties": false }, + "QuestionRequest": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^que" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionInfo" + }, + "description": "Questions to ask" + }, + "tool": { + "$ref": "#/components/schemas/QuestionTool" + } + }, + "required": ["id", "sessionID", "questions"], + "additionalProperties": false + }, "QuestionNotFoundError": { "type": "object", "properties": { @@ -15513,6 +17456,53 @@ "required": ["_tag", "requestID", "message"], "additionalProperties": false }, + "PermissionRequest": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^per" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "permission": { + "type": "string" + }, + "patterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "always": { + "type": "array", + "items": { + "type": "string" + } + }, + "tool": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "callID": { + "type": "string" + } + }, + "required": ["messageID", "callID"], + "additionalProperties": false + } + }, + "required": ["id", "sessionID", "permission", "patterns", "metadata", "always"], + "additionalProperties": false + }, "PermissionNotFoundError": { "type": "object", "properties": { @@ -16213,6 +18203,27 @@ "required": ["id", "type", "name", "projectID", "timeUsed"], "additionalProperties": false }, + "WorkspaceCreateError": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": ["WorkspaceCreateError"] + }, + "data": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": ["message"], + "additionalProperties": false + } + }, + "required": ["name", "data"], + "additionalProperties": false + }, "WorkspaceWarpError": { "type": "object", "properties": { @@ -16245,594 +18256,721 @@ "required": ["_tag"], "additionalProperties": false }, - "SyncEventMessageUpdated": { + "Event.tui.prompt.append": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["sync"] - }, - "name": { - "type": "string", - "enum": ["message.updated.1"] - }, "id": { "type": "string" }, - "seq": { - "type": "number" - }, - "aggregateID": { + "type": { "type": "string", - "enum": ["sessionID"] + "enum": ["tui.prompt.append"] }, - "data": { + "properties": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "info": { - "$ref": "#/components/schemas/Message" + "text": { + "type": "string" } }, - "required": ["sessionID", "info"], + "required": ["text"], "additionalProperties": false } }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SyncEventMessageRemoved": { + "Event.tui.command.execute": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["sync"] - }, - "name": { - "type": "string", - "enum": ["message.removed.1"] - }, "id": { "type": "string" }, - "seq": { - "type": "number" - }, - "aggregateID": { + "type": { "type": "string", - "enum": ["sessionID"] + "enum": ["tui.command.execute"] }, - "data": { + "properties": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "messageID": { - "type": "string", - "pattern": "^msg" + "command": { + "anyOf": [ + { + "type": "string", + "enum": [ + "session.list", + "session.new", + "session.share", + "session.interrupt", + "session.compact", + "session.page.up", + "session.page.down", + "session.line.up", + "session.line.down", + "session.half.page.up", + "session.half.page.down", + "session.first", + "session.last", + "prompt.clear", + "prompt.submit", + "agent.cycle" + ] + }, + { + "type": "string" + } + ] } }, - "required": ["sessionID", "messageID"], + "required": ["command"], "additionalProperties": false } }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SyncEventMessagePartUpdated": { + "Event.tui.toast.show": { "type": "object", "properties": { + "id": { + "type": "string" + }, "type": { "type": "string", - "enum": ["sync"] + "enum": ["tui.toast.show"] }, - "name": { - "type": "string", - "enum": ["message.part.updated.1"] - }, - "id": { - "type": "string" - }, - "seq": { - "type": "number" - }, - "aggregateID": { - "type": "string", - "enum": ["sessionID"] - }, - "data": { + "properties": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" + "title": { + "type": "string" }, - "part": { - "$ref": "#/components/schemas/Part" + "message": { + "type": "string" }, - "time": { + "variant": { + "type": "string", + "enum": ["info", "success", "warning", "error"] + }, + "duration": { "type": "integer", - "minimum": 0 + "exclusiveMinimum": 0 } }, - "required": ["sessionID", "part", "time"], + "required": ["message", "variant"], "additionalProperties": false } }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SyncEventMessagePartRemoved": { + "Event.tui.session.select": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["sync"] - }, - "name": { - "type": "string", - "enum": ["message.part.removed.1"] - }, "id": { "type": "string" }, - "seq": { - "type": "number" - }, - "aggregateID": { + "type": { "type": "string", - "enum": ["sessionID"] + "enum": ["tui.session.select"] }, - "data": { + "properties": { "type": "object", "properties": { "sessionID": { "type": "string", - "pattern": "^ses" - }, - "messageID": { - "type": "string", - "pattern": "^msg" - }, - "partID": { - "type": "string", - "pattern": "^prt" + "pattern": "^ses", + "description": "Session ID to navigate to" } }, - "required": ["sessionID", "messageID", "partID"], + "required": ["sessionID"], "additionalProperties": false } }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SyncEventSessionCreated": { + "ModelV2Info": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["sync"] - }, - "name": { - "type": "string", - "enum": ["session.created.1"] - }, "id": { "type": "string" }, - "seq": { - "type": "number" + "apiID": { + "type": "string" }, - "aggregateID": { - "type": "string", - "enum": ["sessionID"] + "providerID": { + "type": "string" }, - "data": { - "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "info": { - "$ref": "#/components/schemas/Session" - } - }, - "required": ["sessionID", "info"], - "additionalProperties": false - } - }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], - "additionalProperties": false - }, - "SyncEventSessionUpdated": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["sync"] + "family": { + "type": "string" }, "name": { - "type": "string", - "enum": ["session.updated.1"] - }, - "id": { "type": "string" }, - "seq": { - "type": "number" - }, - "aggregateID": { - "type": "string", - "enum": ["sessionID"] - }, - "data": { - "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" + "endpoint": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["unknown"] + } + }, + "required": ["type"], + "additionalProperties": false }, - "info": { + { "type": "object", "properties": { - "id": { - "anyOf": [ - { - "type": "string", - "pattern": "^ses" - }, - { - "type": "null" - } - ] - }, - "slug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "projectID": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "workspaceID": { - "anyOf": [ - { - "type": "string", - "pattern": "^wrk" - }, - { - "type": "null" - } - ] + "type": { + "type": "string", + "enum": ["openai/responses"] }, - "directory": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "url": { + "type": "string" }, - "path": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "websocket": { + "type": "boolean" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/completions"] }, - "parentID": { - "anyOf": [ - { - "type": "string", - "pattern": "^ses" - }, - { - "type": "null" - } - ] + "url": { + "type": "string" }, - "summary": { + "reasoning": { "anyOf": [ { "type": "object", "properties": { - "additions": { - "type": "number" - }, - "deletions": { - "type": "number" - }, - "files": { - "type": "number" - }, - "diffs": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SnapshotFileDiff" - } + "type": { + "type": "string", + "enum": ["reasoning_content"] } }, - "required": ["additions", "deletions", "files"], + "required": ["type"], "additionalProperties": false }, { - "type": "null" - } - ] - }, - "cost": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "tokens": { - "anyOf": [ - { - "type": "object", - "properties": { - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "reasoning": { - "type": "number" - }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false - } - }, - "required": ["input", "output", "reasoning", "cache"], - "additionalProperties": false - }, - { - "type": "null" - } - ] - }, - "share": { - "type": "object", - "properties": { - "url": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - } - }, - "additionalProperties": false - }, - "title": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "agent": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "model": { - "anyOf": [ - { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "providerID": { - "type": "string" - }, - "variant": { - "type": "string" - } - }, - "required": ["id", "providerID"], - "additionalProperties": false - }, - { - "type": "null" - } - ] - }, - "version": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_details"] + } + }, + "required": ["type"], + "additionalProperties": false } ] + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["anthropic/messages"] }, - "time": { - "type": "object", - "properties": { - "created": { - "anyOf": [ - { - "type": "integer", - "minimum": 0 - }, - { - "type": "null" - } - ] - }, - "updated": { - "anyOf": [ - { - "type": "integer", - "minimum": 0 - }, - { - "type": "null" - } - ] - }, - "compacting": { - "anyOf": [ - { - "type": "integer", - "minimum": 0 - }, - { - "type": "null" - } - ] - }, - "archived": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - } - }, - "additionalProperties": false + "url": { + "type": "string" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["aisdk"] }, - "permission": { - "anyOf": [ - { - "$ref": "#/components/schemas/PermissionRuleset" - }, - { - "type": "null" - } - ] + "package": { + "type": "string" }, - "revert": { - "anyOf": [ - { - "type": "object", - "properties": { - "messageID": { - "type": "string", - "pattern": "^msg" - }, - "partID": { - "type": "string", - "pattern": "^prt" - }, - "snapshot": { - "type": "string" - }, - "diff": { - "type": "string" - } - }, - "required": ["messageID"], - "additionalProperties": false - }, - { - "type": "null" - } - ] + "url": { + "type": "string" } }, + "required": ["type", "package"], "additionalProperties": false } + ] + }, + "capabilities": { + "type": "object", + "properties": { + "tools": { + "type": "boolean" + }, + "input": { + "type": "array", + "items": { + "type": "string" + } + }, + "output": { + "type": "array", + "items": { + "type": "string" + } + } }, - "required": ["sessionID", "info"], + "required": ["tools", "input", "output"], "additionalProperties": false - } - }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], + }, + "options": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + }, + "variant": { + "type": "string" + } + }, + "required": ["headers", "body", "aisdk"], + "additionalProperties": false + }, + "variants": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + } + }, + "required": ["id", "headers", "body", "aisdk"], + "additionalProperties": false + } + }, + "time": { + "type": "object", + "properties": { + "released": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + }, + { + "type": "string", + "enum": ["Infinity", "-Infinity", "NaN"] + } + ] + } + }, + "required": ["released"], + "additionalProperties": false + }, + "cost": { + "type": "array", + "items": { + "type": "object", + "properties": { + "tier": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["context"] + }, + "size": { + "type": "integer" + } + }, + "required": ["type", "size"], + "additionalProperties": false + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "cache"], + "additionalProperties": false + } + }, + "status": { + "type": "string", + "enum": ["alpha", "beta", "deprecated", "active"] + }, + "enabled": { + "type": "boolean" + }, + "limit": { + "type": "object", + "properties": { + "context": { + "type": "integer" + }, + "input": { + "type": "integer" + }, + "output": { + "type": "integer" + } + }, + "required": ["context", "output"], + "additionalProperties": false + } + }, + "required": [ + "id", + "apiID", + "providerID", + "name", + "endpoint", + "capabilities", + "options", + "variants", + "time", + "cost", + "status", + "enabled", + "limit" + ], + "additionalProperties": false + }, + "PromptSource": { + "type": "object", + "properties": { + "start": { + "type": "number" + }, + "end": { + "type": "number" + }, + "text": { + "type": "string" + } + }, + "required": ["start", "end", "text"], + "additionalProperties": false + }, + "PromptFileAttachment": { + "type": "object", + "properties": { + "uri": { + "type": "string" + }, + "mime": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "source": { + "$ref": "#/components/schemas/PromptSource" + } + }, + "required": ["uri", "mime"], + "additionalProperties": false + }, + "PromptAgentAttachment": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "source": { + "$ref": "#/components/schemas/PromptSource" + } + }, + "required": ["name"], + "additionalProperties": false + }, + "PromptReferenceAttachment": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": ["local", "git", "invalid"] + }, + "uri": { + "type": "string" + }, + "repository": { + "type": "string" + }, + "branch": { + "type": "string" + }, + "target": { + "type": "string" + }, + "targetUri": { + "type": "string" + }, + "problem": { + "type": "string" + }, + "source": { + "$ref": "#/components/schemas/PromptSource" + } + }, + "required": ["name", "kind"], + "additionalProperties": false + }, + "SessionErrorUnknown": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["unknown"] + }, + "message": { + "type": "string" + } + }, + "required": ["type", "message"], + "additionalProperties": false + }, + "ToolTextContent": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["text"] + }, + "text": { + "type": "string" + } + }, + "required": ["type", "text"], + "additionalProperties": false + }, + "ToolFileContent": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["file"] + }, + "uri": { + "type": "string" + }, + "mime": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": ["type", "uri", "mime"], + "additionalProperties": false + }, + "SessionNextRetry_error": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "statusCode": { + "type": "number" + }, + "isRetryable": { + "type": "boolean" + }, + "responseHeaders": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "responseBody": { + "type": "string" + }, + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["message", "isRetryable"], + "additionalProperties": false + }, + "AuthOAuthCredential": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["oauth"] + }, + "refresh": { + "type": "string" + }, + "access": { + "type": "string" + }, + "expires": { + "type": "integer", + "minimum": 0 + } + }, + "required": ["type", "refresh", "access", "expires"], + "additionalProperties": false + }, + "AuthApiKeyCredential": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["api"] + }, + "key": { + "type": "string" + }, + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["type", "key"], "additionalProperties": false }, - "SyncEventSessionDeleted": { + "AuthCredential": { + "anyOf": [ + { + "$ref": "#/components/schemas/AuthOAuthCredential" + }, + { + "$ref": "#/components/schemas/AuthApiKeyCredential" + } + ] + }, + "AuthInfo": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["sync"] + "id": { + "type": "string" }, - "name": { - "type": "string", - "enum": ["session.deleted.1"] + "serviceID": { + "type": "string" }, - "id": { + "description": { "type": "string" }, - "seq": { - "type": "number" + "credential": { + "$ref": "#/components/schemas/AuthCredential" + } + }, + "required": ["id", "serviceID", "description", "credential"], + "additionalProperties": false + }, + "EventServerInstanceDisposed": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "aggregateID": { + "type": { "type": "string", - "enum": ["sessionID"] + "enum": ["server.instance.disposed"] }, - "data": { + "properties": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "info": { - "$ref": "#/components/schemas/Session" + "directory": { + "type": "string" } }, - "required": ["sessionID", "info"], + "required": ["directory"], "additionalProperties": false } }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], + "required": ["id", "type", "properties"], "additionalProperties": false }, "SyncEventSessionNextAgentSwitched": { @@ -16921,7 +19059,7 @@ "type": "string" } }, - "required": ["id", "providerID", "variant"], + "required": ["id", "providerID"], "additionalProperties": false } }, @@ -17153,7 +19291,7 @@ "type": "string" } }, - "required": ["id", "providerID", "variant"], + "required": ["id", "providerID"], "additionalProperties": false }, "snapshot": { @@ -17984,1134 +20122,1305 @@ "type": "string" }, "seq": { - "type": "number" - }, - "aggregateID": { - "type": "string", - "enum": ["sessionID"] - }, - "data": { - "type": "object", - "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "reason": { - "type": "string", - "enum": ["auto", "manual"] - } - }, - "required": ["timestamp", "sessionID", "reason"], - "additionalProperties": false - } - }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], - "additionalProperties": false - }, - "SyncEventSessionNextCompactionDelta": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["sync"] - }, - "name": { - "type": "string", - "enum": ["session.next.compaction.delta.1"] - }, - "id": { - "type": "string" - }, - "seq": { - "type": "number" - }, - "aggregateID": { - "type": "string", - "enum": ["sessionID"] - }, - "data": { - "type": "object", - "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "text": { - "type": "string" - } - }, - "required": ["timestamp", "sessionID", "text"], - "additionalProperties": false - } - }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], - "additionalProperties": false - }, - "SyncEventSessionNextCompactionEnded": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["sync"] - }, - "name": { - "type": "string", - "enum": ["session.next.compaction.ended.1"] - }, - "id": { - "type": "string" - }, - "seq": { - "type": "number" - }, - "aggregateID": { - "type": "string", - "enum": ["sessionID"] - }, - "data": { - "type": "object", - "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "text": { - "type": "string" - }, - "include": { - "type": "string" - } - }, - "required": ["timestamp", "sessionID", "text"], - "additionalProperties": false - } - }, - "required": ["type", "name", "id", "seq", "aggregateID", "data"], - "additionalProperties": false - }, - "EventServerConnected": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["server.connected"] - }, - "properties": { - "type": "object", - "properties": {} - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventGlobalDisposed": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["global.disposed"] - }, - "properties": { - "type": "object", - "properties": {} - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventServerInstanceDisposed": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["server.instance.disposed"] - }, - "properties": { - "type": "object", - "properties": { - "directory": { - "type": "string" - } - }, - "required": ["directory"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventFileEdited": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["file.edited"] - }, - "properties": { - "type": "object", - "properties": { - "file": { - "type": "string" - } - }, - "required": ["file"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventFileWatcherUpdated": { - "type": "object", - "properties": { - "id": { - "type": "string" + "type": "number" }, - "type": { + "aggregateID": { "type": "string", - "enum": ["file.watcher.updated"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { - "file": { - "type": "string" + "timestamp": { + "type": "number" }, - "event": { + "sessionID": { "type": "string", - "enum": ["add", "change", "unlink"] + "pattern": "^ses" + }, + "reason": { + "type": "string", + "enum": ["auto", "manual"] } }, - "required": ["file", "event"], + "required": ["timestamp", "sessionID", "reason"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventLspClientDiagnostics": { + "SyncEventSessionNextCompactionDelta": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["session.next.compaction.delta.1"] + }, "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["lsp.client.diagnostics"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { - "serverID": { - "type": "string" + "timestamp": { + "type": "number" }, - "path": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { "type": "string" } }, - "required": ["serverID", "path"], + "required": ["timestamp", "sessionID", "text"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventLspUpdated": { + "SyncEventSessionNextCompactionEnded": { "type": "object", "properties": { - "id": { - "type": "string" - }, "type": { "type": "string", - "enum": ["lsp.updated"] + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["session.next.compaction.ended.1"] }, - "properties": { - "type": "object", - "properties": {} - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventMessagePartDelta": { - "type": "object", - "properties": { "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["message.part.delta"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { + "timestamp": { + "type": "number" + }, "sessionID": { "type": "string", "pattern": "^ses" }, - "messageID": { - "type": "string", - "pattern": "^msg" - }, - "partID": { - "type": "string", - "pattern": "^prt" - }, - "field": { + "text": { "type": "string" }, - "delta": { + "include": { "type": "string" } }, - "required": ["sessionID", "messageID", "partID", "field", "delta"], + "required": ["timestamp", "sessionID", "text"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventPermissionAsked": { + "SyncEventSessionCreated": { "type": "object", "properties": { - "id": { - "type": "string" - }, "type": { "type": "string", - "enum": ["permission.asked"] + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["session.created.1"] }, - "properties": { - "$ref": "#/components/schemas/PermissionRequest" - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventPermissionReplied": { - "type": "object", - "properties": { "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["permission.replied"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { "sessionID": { "type": "string", "pattern": "^ses" }, - "requestID": { - "type": "string", - "pattern": "^per" - }, - "reply": { - "type": "string", - "enum": ["once", "always", "reject"] + "info": { + "$ref": "#/components/schemas/Session" } }, - "required": ["sessionID", "requestID", "reply"], + "required": ["sessionID", "info"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventSessionDiff": { + "SyncEventSessionUpdated": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["session.updated.1"] + }, "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["session.diff"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { "sessionID": { "type": "string", "pattern": "^ses" }, - "diff": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SnapshotFileDiff" - } + "info": { + "$ref": "#/components/schemas/Session" } }, - "required": ["sessionID", "diff"], + "required": ["sessionID", "info"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventSessionError": { + "SyncEventSessionDeleted": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["session.deleted.1"] + }, "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["session.error"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { "sessionID": { "type": "string", "pattern": "^ses" }, - "error": { - "anyOf": [ - { - "$ref": "#/components/schemas/ProviderAuthError" - }, - { - "$ref": "#/components/schemas/UnknownError" - }, - { - "$ref": "#/components/schemas/MessageOutputLengthError" - }, - { - "$ref": "#/components/schemas/MessageAbortedError" - }, - { - "$ref": "#/components/schemas/StructuredOutputError" - }, - { - "$ref": "#/components/schemas/ContextOverflowError" - }, - { - "$ref": "#/components/schemas/APIError" - } - ] + "info": { + "$ref": "#/components/schemas/Session" } }, + "required": ["sessionID", "info"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventQuestionAsked": { + "SyncEventMessageUpdated": { "type": "object", "properties": { - "id": { - "type": "string" - }, "type": { "type": "string", - "enum": ["question.asked"] + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["message.updated.1"] }, - "properties": { - "$ref": "#/components/schemas/QuestionRequest" - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventQuestionReplied": { - "type": "object", - "properties": { "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["question.replied"] + "enum": ["sessionID"] }, - "properties": { - "$ref": "#/components/schemas/QuestionReplied" + "data": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Message" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventQuestionRejected": { + "SyncEventMessageRemoved": { "type": "object", "properties": { - "id": { - "type": "string" - }, "type": { "type": "string", - "enum": ["question.rejected"] + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["message.removed.1"] }, - "properties": { - "$ref": "#/components/schemas/QuestionRejected" - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventTodoUpdated": { - "type": "object", - "properties": { "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["todo.updated"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { "sessionID": { "type": "string", "pattern": "^ses" }, - "todos": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Todo" - } + "messageID": { + "type": "string", + "pattern": "^msg" } }, - "required": ["sessionID", "todos"], + "required": ["sessionID", "messageID"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventSessionStatus": { + "SyncEventMessagePartUpdated": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["message.part.updated.1"] + }, "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["session.status"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { "sessionID": { "type": "string", "pattern": "^ses" }, - "status": { - "$ref": "#/components/schemas/SessionStatus" + "part": { + "$ref": "#/components/schemas/Part" + }, + "time": { + "type": "number" } }, - "required": ["sessionID", "status"], + "required": ["sessionID", "part", "time"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventSessionIdle": { + "SyncEventMessagePartRemoved": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["sync"] + }, + "name": { + "type": "string", + "enum": ["message.part.removed.1"] + }, "id": { "type": "string" }, - "type": { + "seq": { + "type": "number" + }, + "aggregateID": { "type": "string", - "enum": ["session.idle"] + "enum": ["sessionID"] }, - "properties": { + "data": { "type": "object", "properties": { "sessionID": { "type": "string", "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "partID": { + "type": "string", + "pattern": "^prt" } }, - "required": ["sessionID"], + "required": ["sessionID", "messageID", "partID"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "name", "id", "seq", "aggregateID", "data"], "additionalProperties": false }, - "EventMcpToolsChanged": { + "PolicyEffect": { + "type": "string", + "enum": ["allow", "deny"] + }, + "ConfigV2ExperimentalPolicy": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["provider.use"] + }, + "effect": { + "$ref": "#/components/schemas/PolicyEffect" + }, + "resource": { + "type": "string" + } + }, + "required": ["action", "effect", "resource"], + "additionalProperties": false + }, + "SessionInfo": { "type": "object", "properties": { "id": { + "type": "string", + "pattern": "^ses" + }, + "parentID": { + "type": "string", + "pattern": "^ses" + }, + "projectID": { "type": "string" }, - "type": { + "workspaceID": { "type": "string", - "enum": ["mcp.tools.changed"] + "pattern": "^wrk" }, - "properties": { + "path": { + "type": "string" + }, + "agent": { + "type": "string" + }, + "model": { "type": "object", "properties": { - "server": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { "type": "string" } }, - "required": ["server"], + "required": ["id", "providerID"], + "additionalProperties": false + }, + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "reasoning", "cache"], + "additionalProperties": false + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + }, + "updated": { + "type": "number" + }, + "archived": { + "type": "number" + } + }, + "required": ["created", "updated"], "additionalProperties": false + }, + "title": { + "type": "string" } }, - "required": ["id", "type", "properties"], + "required": ["id", "projectID", "cost", "tokens", "time", "title"], "additionalProperties": false }, - "EventMcpBrowserOpenFailed": { + "SessionDelivery": { + "type": "string", + "enum": ["immediate", "deferred"] + }, + "SessionMessageAgentSwitched": { "type": "object", "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["mcp.browser.open.failed"] + "metadata": { + "type": "object" }, - "properties": { + "time": { "type": "object", "properties": { - "mcpName": { - "type": "string" - }, - "url": { - "type": "string" + "created": { + "type": "number" } }, - "required": ["mcpName", "url"], + "required": ["created"], "additionalProperties": false + }, + "type": { + "type": "string", + "enum": ["agent-switched"] + }, + "agent": { + "type": "string" } }, - "required": ["id", "type", "properties"], + "required": ["id", "time", "type", "agent"], "additionalProperties": false }, - "EventCommandExecuted": { + "SessionMessageModelSwitched": { "type": "object", "properties": { "id": { "type": "string" }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": ["created"], + "additionalProperties": false + }, "type": { "type": "string", - "enum": ["command.executed"] + "enum": ["model-switched"] }, - "properties": { + "model": { "type": "object", "properties": { - "name": { + "id": { "type": "string" }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "arguments": { + "providerID": { "type": "string" }, - "messageID": { - "type": "string", - "pattern": "^msg" + "variant": { + "type": "string" } }, - "required": ["name", "sessionID", "arguments", "messageID"], + "required": ["id", "providerID"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["id", "time", "type", "model"], "additionalProperties": false }, - "EventProjectUpdated": { + "SessionMessageUser": { "type": "object", "properties": { "id": { "type": "string" }, + "metadata": { + "type": "object" + }, + "time": { + "type": "object", + "properties": { + "created": { + "type": "number" + } + }, + "required": ["created"], + "additionalProperties": false + }, + "text": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptFileAttachment" + } + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptAgentAttachment" + } + }, + "references": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptReferenceAttachment" + } + }, "type": { "type": "string", - "enum": ["project.updated"] - }, - "properties": { - "$ref": "#/components/schemas/Project" + "enum": ["user"] } }, - "required": ["id", "type", "properties"], + "required": ["id", "time", "text", "type"], "additionalProperties": false }, - "EventSessionCompacted": { + "SessionMessageSynthetic": { "type": "object", "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["session.compacted"] + "metadata": { + "type": "object" }, - "properties": { + "time": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" + "created": { + "type": "number" } }, - "required": ["sessionID"], + "required": ["created"], "additionalProperties": false + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["synthetic"] } }, - "required": ["id", "type", "properties"], + "required": ["id", "time", "sessionID", "text", "type"], "additionalProperties": false }, - "EventVcsBranchUpdated": { + "SessionMessageShell": { "type": "object", "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["vcs.branch.updated"] + "metadata": { + "type": "object" }, - "properties": { + "time": { "type": "object", "properties": { - "branch": { - "type": "string" + "created": { + "type": "number" + }, + "completed": { + "type": "number" } }, + "required": ["created"], "additionalProperties": false + }, + "type": { + "type": "string", + "enum": ["shell"] + }, + "callID": { + "type": "string" + }, + "command": { + "type": "string" + }, + "output": { + "type": "string" } }, - "required": ["id", "type", "properties"], + "required": ["id", "time", "type", "callID", "command", "output"], "additionalProperties": false }, - "EventWorkspaceReady": { + "SessionMessageAssistantText": { "type": "object", "properties": { - "id": { - "type": "string" - }, "type": { "type": "string", - "enum": ["workspace.ready"] + "enum": ["text"] }, - "properties": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - }, - "required": ["name"], - "additionalProperties": false + "text": { + "type": "string" } }, - "required": ["id", "type", "properties"], + "required": ["type", "text"], "additionalProperties": false }, - "EventWorkspaceFailed": { + "SessionMessageAssistantReasoning": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["reasoning"] + }, "id": { "type": "string" }, - "type": { + "text": { + "type": "string" + } + }, + "required": ["type", "id", "text"], + "additionalProperties": false + }, + "SessionMessageToolStatePending": { + "type": "object", + "properties": { + "status": { "type": "string", - "enum": ["workspace.failed"] + "enum": ["pending"] }, - "properties": { - "type": "object", - "properties": { - "message": { - "type": "string" - } - }, - "required": ["message"], - "additionalProperties": false + "input": { + "type": "string" } }, - "required": ["id", "type", "properties"], + "required": ["status", "input"], "additionalProperties": false }, - "EventWorkspaceStatus": { + "SessionMessageToolStateRunning": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "type": { + "status": { "type": "string", - "enum": ["workspace.status"] + "enum": ["running"] }, - "properties": { - "type": "object", - "properties": { - "workspaceID": { - "type": "string", - "pattern": "^wrk" - }, - "status": { - "type": "string", - "enum": ["connected", "connecting", "disconnected", "error"] - } - }, - "required": ["workspaceID", "status"], - "additionalProperties": false + "input": { + "type": "object" + }, + "structured": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } } }, - "required": ["id", "type", "properties"], + "required": ["status", "input", "structured", "content"], "additionalProperties": false }, - "EventWorktreeReady": { + "SessionMessageToolStateCompleted": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "type": { + "status": { "type": "string", - "enum": ["worktree.ready"] + "enum": ["completed"] }, - "properties": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "branch": { - "type": "string" - } - }, - "required": ["name"], - "additionalProperties": false + "input": { + "type": "object" + }, + "attachments": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PromptFileAttachment" + } + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } + }, + "structured": { + "type": "object" } }, - "required": ["id", "type", "properties"], + "required": ["status", "input", "content", "structured"], "additionalProperties": false }, - "EventWorktreeFailed": { + "SessionMessageToolStateError": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "type": { + "status": { "type": "string", - "enum": ["worktree.failed"] + "enum": ["error"] }, - "properties": { - "type": "object", - "properties": { - "message": { - "type": "string" - } - }, - "required": ["message"], - "additionalProperties": false + "input": { + "type": "object" + }, + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] + } + }, + "structured": { + "type": "object" + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" } }, - "required": ["id", "type", "properties"], + "required": ["status", "input", "content", "structured", "error"], "additionalProperties": false }, - "EventPtyCreated": { + "SessionMessageAssistantTool": { "type": "object", "properties": { - "id": { - "type": "string" - }, "type": { "type": "string", - "enum": ["pty.created"] + "enum": ["tool"] }, - "properties": { - "type": "object", - "properties": { - "info": { - "$ref": "#/components/schemas/Pty" - } - }, - "required": ["info"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventPtyUpdated": { - "type": "object", - "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["pty.updated"] + "name": { + "type": "string" }, - "properties": { + "provider": { "type": "object", "properties": { - "info": { - "$ref": "#/components/schemas/Pty" + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" } }, - "required": ["info"], + "required": ["executed"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventPtyExited": { - "type": "object", - "properties": { - "id": { - "type": "string" }, - "type": { - "type": "string", - "enum": ["pty.exited"] + "state": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionMessageToolStatePending" + }, + { + "$ref": "#/components/schemas/SessionMessageToolStateRunning" + }, + { + "$ref": "#/components/schemas/SessionMessageToolStateCompleted" + }, + { + "$ref": "#/components/schemas/SessionMessageToolStateError" + } + ] }, - "properties": { + "time": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^pty" + "created": { + "type": "number" }, - "exitCode": { - "type": "integer", - "minimum": 0 + "ran": { + "type": "number" + }, + "completed": { + "type": "number" + }, + "pruned": { + "type": "number" } }, - "required": ["id", "exitCode"], + "required": ["created"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "id", "name", "state", "time"], "additionalProperties": false }, - "EventPtyDeleted": { + "SessionMessageAssistant": { "type": "object", "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["pty.deleted"] + "metadata": { + "type": "object" }, - "properties": { + "time": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^pty" + "created": { + "type": "number" + }, + "completed": { + "type": "number" } }, - "required": ["id"], + "required": ["created"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventInstallationUpdated": { - "type": "object", - "properties": { - "id": { - "type": "string" }, "type": { "type": "string", - "enum": ["installation.updated"] + "enum": ["assistant"] }, - "properties": { + "agent": { + "type": "string" + }, + "model": { "type": "object", "properties": { - "version": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { "type": "string" } }, - "required": ["version"], + "required": ["id", "providerID"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventInstallationUpdate-available": { - "type": "object", - "properties": { - "id": { - "type": "string" }, - "type": { - "type": "string", - "enum": ["installation.update-available"] + "content": { + "type": "array", + "items": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionMessageAssistantText" + }, + { + "$ref": "#/components/schemas/SessionMessageAssistantReasoning" + }, + { + "$ref": "#/components/schemas/SessionMessageAssistantTool" + } + ] + } }, - "properties": { + "snapshot": { "type": "object", "properties": { - "version": { + "start": { + "type": "string" + }, + "end": { "type": "string" } }, - "required": ["version"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventMessageUpdated": { - "type": "object", - "properties": { - "id": { + }, + "finish": { "type": "string" }, - "type": { - "type": "string", - "enum": ["message.updated"] + "cost": { + "type": "number" }, - "properties": { + "tokens": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" + "input": { + "type": "number" }, - "info": { - "$ref": "#/components/schemas/Message" + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false } }, - "required": ["sessionID", "info"], + "required": ["input", "output", "reasoning", "cache"], "additionalProperties": false + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" } }, - "required": ["id", "type", "properties"], + "required": ["id", "time", "type", "agent", "model", "content"], "additionalProperties": false }, - "EventMessageRemoved": { + "SessionMessageCompaction": { "type": "object", "properties": { + "type": { + "type": "string", + "enum": ["compaction"] + }, + "reason": { + "type": "string", + "enum": ["auto", "manual"] + }, + "summary": { + "type": "string" + }, + "include": { + "type": "string" + }, "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["message.removed"] + "metadata": { + "type": "object" }, - "properties": { + "time": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "messageID": { - "type": "string", - "pattern": "^msg" + "created": { + "type": "number" } }, - "required": ["sessionID", "messageID"], + "required": ["created"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["type", "reason", "summary", "id", "time"], "additionalProperties": false }, - "EventMessagePartUpdated": { + "SessionMessage": { + "anyOf": [ + { + "$ref": "#/components/schemas/SessionMessageAgentSwitched" + }, + { + "$ref": "#/components/schemas/SessionMessageModelSwitched" + }, + { + "$ref": "#/components/schemas/SessionMessageUser" + }, + { + "$ref": "#/components/schemas/SessionMessageSynthetic" + }, + { + "$ref": "#/components/schemas/SessionMessageShell" + }, + { + "$ref": "#/components/schemas/SessionMessageAssistant" + }, + { + "$ref": "#/components/schemas/SessionMessageCompaction" + } + ] + }, + "ProviderV2Info": { "type": "object", "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["message.part.updated"] + "name": { + "type": "string" }, - "properties": { - "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" + "enabled": { + "anyOf": [ + { + "type": "boolean", + "enum": [false] }, - "part": { - "$ref": "#/components/schemas/Part" + { + "type": "object", + "properties": { + "via": { + "type": "string", + "enum": ["env"] + }, + "name": { + "type": "string" + } + }, + "required": ["via", "name"], + "additionalProperties": false }, - "time": { - "type": "integer", - "minimum": 0 + { + "type": "object", + "properties": { + "via": { + "type": "string", + "enum": ["account"] + }, + "service": { + "type": "string" + } + }, + "required": ["via", "service"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "via": { + "type": "string", + "enum": ["custom"] + }, + "data": { + "type": "object" + } + }, + "required": ["via", "data"], + "additionalProperties": false } - }, - "required": ["sessionID", "part", "time"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventMessagePartRemoved": { - "type": "object", - "properties": { - "id": { - "type": "string" + ] }, - "type": { - "type": "string", - "enum": ["message.part.removed"] + "env": { + "type": "array", + "items": { + "type": "string" + } + }, + "endpoint": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["unknown"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/responses"] + }, + "url": { + "type": "string" + }, + "websocket": { + "type": "boolean" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/completions"] + }, + "url": { + "type": "string" + }, + "reasoning": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_content"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_details"] + } + }, + "required": ["type"], + "additionalProperties": false + } + ] + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["anthropic/messages"] + }, + "url": { + "type": "string" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["aisdk"] + }, + "package": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": ["type", "package"], + "additionalProperties": false + } + ] }, - "properties": { + "options": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } }, - "messageID": { - "type": "string", - "pattern": "^msg" + "body": { + "type": "object" }, - "partID": { - "type": "string", - "pattern": "^prt" + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false } }, - "required": ["sessionID", "messageID", "partID"], + "required": ["headers", "body", "aisdk"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": ["id", "name", "enabled", "env", "endpoint", "options"], "additionalProperties": false }, - "EventSessionCreated": { + "EventModels-devRefreshed": { "type": "object", "properties": { "id": { @@ -19119,27 +21428,17 @@ }, "type": { "type": "string", - "enum": ["session.created"] + "enum": ["models-dev.refreshed"] }, "properties": { "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "info": { - "$ref": "#/components/schemas/Session" - } - }, - "required": ["sessionID", "info"], - "additionalProperties": false + "properties": {} } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionUpdated": { + "EventPluginAdded": { "type": "object", "properties": { "id": { @@ -19147,278 +21446,343 @@ }, "type": { "type": "string", - "enum": ["session.updated"] + "enum": ["plugin.added"] }, "properties": { "type": "object", "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "info": { - "$ref": "#/components/schemas/Session" + "id": { + "type": "string" } }, - "required": ["sessionID", "info"], + "required": ["id"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionDeleted": { + "ModelV2Info1": { "type": "object", "properties": { "id": { "type": "string" }, - "type": { - "type": "string", - "enum": ["session.deleted"] + "apiID": { + "type": "string" }, - "properties": { - "type": "object", - "properties": { - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "info": { - "$ref": "#/components/schemas/Session" - } - }, - "required": ["sessionID", "info"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventSessionNextAgentSwitched": { - "type": "object", - "properties": { - "id": { + "providerID": { "type": "string" }, - "type": { - "type": "string", - "enum": ["session.next.agent.switched"] + "family": { + "type": "string" }, - "properties": { + "name": { + "type": "string" + }, + "endpoint": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["unknown"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/responses"] + }, + "url": { + "type": "string" + }, + "websocket": { + "type": "boolean" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openai/completions"] + }, + "url": { + "type": "string" + }, + "reasoning": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_content"] + } + }, + "required": ["type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["reasoning_details"] + } + }, + "required": ["type"], + "additionalProperties": false + } + ] + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["anthropic/messages"] + }, + "url": { + "type": "string" + } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["aisdk"] + }, + "package": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": ["type", "package"], + "additionalProperties": false + } + ] + }, + "capabilities": { "type": "object", "properties": { - "timestamp": { - "type": "number" + "tools": { + "type": "boolean" }, - "sessionID": { - "type": "string", - "pattern": "^ses" + "input": { + "type": "array", + "items": { + "type": "string" + } }, - "agent": { - "type": "string" + "output": { + "type": "array", + "items": { + "type": "string" + } } }, - "required": ["timestamp", "sessionID", "agent"], + "required": ["tools", "input", "output"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventSessionNextModelSwitched": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["session.next.model.switched"] }, - "properties": { + "options": { "type": "object", "properties": { - "timestamp": { - "type": "number" + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } }, - "sessionID": { - "type": "string", - "pattern": "^ses" + "body": { + "type": "object" }, - "model": { + "aisdk": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "providerID": { - "type": "string" + "provider": { + "type": "object" }, - "variant": { - "type": "string" + "request": { + "type": "object" } }, - "required": ["id", "providerID", "variant"], + "required": ["provider", "request"], "additionalProperties": false + }, + "variant": { + "type": "string" } }, - "required": ["timestamp", "sessionID", "model"], + "required": ["headers", "body", "aisdk"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "PromptSource": { - "type": "object", - "properties": { - "start": { - "type": "number" - }, - "end": { - "type": "number" - }, - "text": { - "type": "string" - } - }, - "required": ["start", "end", "text"], - "additionalProperties": false - }, - "PromptFileAttachment": { - "type": "object", - "properties": { - "uri": { - "type": "string" - }, - "mime": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "source": { - "$ref": "#/components/schemas/PromptSource" - } - }, - "required": ["uri", "mime"], - "additionalProperties": false - }, - "PromptAgentAttachment": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "source": { - "$ref": "#/components/schemas/PromptSource" - } - }, - "required": ["name"], - "additionalProperties": false - }, - "PromptReferenceAttachment": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "kind": { - "type": "string", - "enum": ["local", "git", "invalid"] - }, - "uri": { - "type": "string" - }, - "repository": { - "type": "string" - }, - "branch": { - "type": "string" - }, - "target": { - "type": "string" - }, - "targetUri": { - "type": "string" - }, - "problem": { - "type": "string" - }, - "source": { - "$ref": "#/components/schemas/PromptSource" - } - }, - "required": ["name", "kind"], - "additionalProperties": false - }, - "EventSessionNextPrompted": { - "type": "object", - "properties": { - "id": { - "type": "string" }, - "type": { - "type": "string", - "enum": ["session.next.prompted"] + "variants": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "type": "object" + }, + "aisdk": { + "type": "object", + "properties": { + "provider": { + "type": "object" + }, + "request": { + "type": "object" + } + }, + "required": ["provider", "request"], + "additionalProperties": false + } + }, + "required": ["id", "headers", "body", "aisdk"], + "additionalProperties": false + } }, - "properties": { + "time": { "type": "object", "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "prompt": { - "$ref": "#/components/schemas/Prompt" + "released": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + } + ] } }, - "required": ["timestamp", "sessionID", "prompt"], + "required": ["released"], "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventSessionNextSynthetic": { - "type": "object", - "properties": { - "id": { - "type": "string" }, - "type": { + "cost": { + "type": "array", + "items": { + "type": "object", + "properties": { + "tier": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["context"] + }, + "size": { + "type": "integer" + } + }, + "required": ["type", "size"], + "additionalProperties": false + }, + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "cache"], + "additionalProperties": false + } + }, + "status": { "type": "string", - "enum": ["session.next.synthetic"] + "enum": ["alpha", "beta", "deprecated", "active"] }, - "properties": { + "enabled": { + "type": "boolean" + }, + "limit": { "type": "object", - "properties": { - "timestamp": { - "type": "number" + "properties": { + "context": { + "type": "integer" }, - "sessionID": { - "type": "string", - "pattern": "^ses" + "input": { + "type": "integer" }, - "text": { - "type": "string" + "output": { + "type": "integer" } }, - "required": ["timestamp", "sessionID", "text"], + "required": ["context", "output"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], + "required": [ + "id", + "apiID", + "providerID", + "name", + "endpoint", + "capabilities", + "options", + "variants", + "time", + "cost", + "status", + "enabled", + "limit" + ], "additionalProperties": false }, - "EventSessionNextShellStarted": { + "EventCatalogModelUpdated": { "type": "object", "properties": { "id": { @@ -19426,33 +21790,23 @@ }, "type": { "type": "string", - "enum": ["session.next.shell.started"] + "enum": ["catalog.model.updated"] }, "properties": { "type": "object", "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "callID": { - "type": "string" - }, - "command": { - "type": "string" + "model": { + "$ref": "#/components/schemas/ModelV2Info1" } }, - "required": ["timestamp", "sessionID", "callID", "command"], + "required": ["model"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextShellEnded": { + "EventFileEdited": { "type": "object", "properties": { "id": { @@ -19460,33 +21814,23 @@ }, "type": { "type": "string", - "enum": ["session.next.shell.ended"] + "enum": ["file.edited"] }, "properties": { "type": "object", "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "callID": { - "type": "string" - }, - "output": { + "file": { "type": "string" } }, - "required": ["timestamp", "sessionID", "callID", "output"], + "required": ["file"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextStepStarted": { + "EventSessionNextAgentSwitched": { "type": "object", "properties": { "id": { @@ -19494,7 +21838,7 @@ }, "type": { "type": "string", - "enum": ["session.next.step.started"] + "enum": ["session.next.agent.switched"] }, "properties": { "type": "object", @@ -19508,35 +21852,16 @@ }, "agent": { "type": "string" - }, - "model": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "providerID": { - "type": "string" - }, - "variant": { - "type": "string" - } - }, - "required": ["id", "providerID", "variant"], - "additionalProperties": false - }, - "snapshot": { - "type": "string" } }, - "required": ["timestamp", "sessionID", "agent", "model"], + "required": ["timestamp", "sessionID", "agent"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextStepEnded": { + "EventSessionNextModelSwitched": { "type": "object", "properties": { "id": { @@ -19544,7 +21869,7 @@ }, "type": { "type": "string", - "enum": ["session.next.step.ended"] + "enum": ["session.next.model.switched"] }, "properties": { "type": "object", @@ -19556,126 +21881,31 @@ "type": "string", "pattern": "^ses" }, - "finish": { - "type": "string" - }, - "cost": { - "type": "number" - }, - "tokens": { + "model": { "type": "object", "properties": { - "input": { - "type": "number" - }, - "output": { - "type": "number" + "id": { + "type": "string" }, - "reasoning": { - "type": "number" + "providerID": { + "type": "string" }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false + "variant": { + "type": "string" } }, - "required": ["input", "output", "reasoning", "cache"], + "required": ["id", "providerID"], "additionalProperties": false - }, - "snapshot": { - "type": "string" - } - }, - "required": ["timestamp", "sessionID", "finish", "cost", "tokens"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "SessionErrorUnknown": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["unknown"] - }, - "message": { - "type": "string" - } - }, - "required": ["type", "message"], - "additionalProperties": false - }, - "EventSessionNextStepFailed": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["session.next.step.failed"] - }, - "properties": { - "type": "object", - "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "error": { - "$ref": "#/components/schemas/SessionErrorUnknown" - } - }, - "required": ["timestamp", "sessionID", "error"], - "additionalProperties": false - } - }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "EventSessionNextTextStarted": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["session.next.text.started"] - }, - "properties": { - "type": "object", - "properties": { - "timestamp": { - "type": "number" - }, - "sessionID": { - "type": "string", - "pattern": "^ses" } }, - "required": ["timestamp", "sessionID"], + "required": ["timestamp", "sessionID", "model"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextTextDelta": { + "EventSessionNextPrompted": { "type": "object", "properties": { "id": { @@ -19683,7 +21913,7 @@ }, "type": { "type": "string", - "enum": ["session.next.text.delta"] + "enum": ["session.next.prompted"] }, "properties": { "type": "object", @@ -19695,18 +21925,18 @@ "type": "string", "pattern": "^ses" }, - "delta": { - "type": "string" + "prompt": { + "$ref": "#/components/schemas/Prompt" } }, - "required": ["timestamp", "sessionID", "delta"], + "required": ["timestamp", "sessionID", "prompt"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextTextEnded": { + "EventSessionNextSynthetic": { "type": "object", "properties": { "id": { @@ -19714,7 +21944,7 @@ }, "type": { "type": "string", - "enum": ["session.next.text.ended"] + "enum": ["session.next.synthetic"] }, "properties": { "type": "object", @@ -19737,7 +21967,7 @@ "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextReasoningStarted": { + "EventSessionNextShellStarted": { "type": "object", "properties": { "id": { @@ -19745,7 +21975,7 @@ }, "type": { "type": "string", - "enum": ["session.next.reasoning.started"] + "enum": ["session.next.shell.started"] }, "properties": { "type": "object", @@ -19757,18 +21987,21 @@ "type": "string", "pattern": "^ses" }, - "reasoningID": { + "callID": { + "type": "string" + }, + "command": { "type": "string" } }, - "required": ["timestamp", "sessionID", "reasoningID"], + "required": ["timestamp", "sessionID", "callID", "command"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextReasoningDelta": { + "EventSessionNextShellEnded": { "type": "object", "properties": { "id": { @@ -19776,7 +22009,7 @@ }, "type": { "type": "string", - "enum": ["session.next.reasoning.delta"] + "enum": ["session.next.shell.ended"] }, "properties": { "type": "object", @@ -19788,21 +22021,21 @@ "type": "string", "pattern": "^ses" }, - "reasoningID": { + "callID": { "type": "string" }, - "delta": { + "output": { "type": "string" } }, - "required": ["timestamp", "sessionID", "reasoningID", "delta"], + "required": ["timestamp", "sessionID", "callID", "output"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextReasoningEnded": { + "EventSessionNextStepStarted": { "type": "object", "properties": { "id": { @@ -19810,7 +22043,7 @@ }, "type": { "type": "string", - "enum": ["session.next.reasoning.ended"] + "enum": ["session.next.step.started"] }, "properties": { "type": "object", @@ -19822,21 +22055,37 @@ "type": "string", "pattern": "^ses" }, - "reasoningID": { + "agent": { "type": "string" }, - "text": { + "model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "providerID": { + "type": "string" + }, + "variant": { + "type": "string" + } + }, + "required": ["id", "providerID"], + "additionalProperties": false + }, + "snapshot": { "type": "string" } }, - "required": ["timestamp", "sessionID", "reasoningID", "text"], + "required": ["timestamp", "sessionID", "agent", "model"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextToolInputStarted": { + "EventSessionNextStepEnded": { "type": "object", "properties": { "id": { @@ -19844,7 +22093,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.input.started"] + "enum": ["session.next.step.ended"] }, "properties": { "type": "object", @@ -19856,21 +22105,53 @@ "type": "string", "pattern": "^ses" }, - "callID": { + "finish": { "type": "string" }, - "name": { + "cost": { + "type": "number" + }, + "tokens": { + "type": "object", + "properties": { + "input": { + "type": "number" + }, + "output": { + "type": "number" + }, + "reasoning": { + "type": "number" + }, + "cache": { + "type": "object", + "properties": { + "read": { + "type": "number" + }, + "write": { + "type": "number" + } + }, + "required": ["read", "write"], + "additionalProperties": false + } + }, + "required": ["input", "output", "reasoning", "cache"], + "additionalProperties": false + }, + "snapshot": { "type": "string" } }, - "required": ["timestamp", "sessionID", "callID", "name"], + "required": ["timestamp", "sessionID", "finish", "cost", "tokens"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextToolInputDelta": { + "EventSessionNextStepFailed": { "type": "object", "properties": { "id": { @@ -19878,7 +22159,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.input.delta"] + "enum": ["session.next.step.failed"] }, "properties": { "type": "object", @@ -19890,21 +22171,18 @@ "type": "string", "pattern": "^ses" }, - "callID": { - "type": "string" - }, - "delta": { - "type": "string" + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" } }, - "required": ["timestamp", "sessionID", "callID", "delta"], + "required": ["timestamp", "sessionID", "error"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextToolInputEnded": { + "EventSessionNextTextStarted": { "type": "object", "properties": { "id": { @@ -19912,7 +22190,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.input.ended"] + "enum": ["session.next.text.started"] }, "properties": { "type": "object", @@ -19923,22 +22201,16 @@ "sessionID": { "type": "string", "pattern": "^ses" - }, - "callID": { - "type": "string" - }, - "text": { - "type": "string" } }, - "required": ["timestamp", "sessionID", "callID", "text"], + "required": ["timestamp", "sessionID"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextToolCalled": { + "EventSessionNextTextDelta": { "type": "object", "properties": { "id": { @@ -19946,7 +22218,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.called"] + "enum": ["session.next.text.delta"] }, "properties": { "type": "object", @@ -19958,71 +22230,18 @@ "type": "string", "pattern": "^ses" }, - "callID": { - "type": "string" - }, - "tool": { + "delta": { "type": "string" - }, - "input": { - "type": "object" - }, - "provider": { - "type": "object", - "properties": { - "executed": { - "type": "boolean" - }, - "metadata": { - "type": "object" - } - }, - "required": ["executed"], - "additionalProperties": false } }, - "required": ["timestamp", "sessionID", "callID", "tool", "input", "provider"], + "required": ["timestamp", "sessionID", "delta"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "ToolTextContent": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["text"] - }, - "text": { - "type": "string" - } - }, - "required": ["type", "text"], - "additionalProperties": false - }, - "ToolFileContent": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["file"] - }, - "uri": { - "type": "string" - }, - "mime": { - "type": "string" - }, - "name": { - "type": "string" - } - }, - "required": ["type", "uri", "mime"], - "additionalProperties": false - }, - "EventSessionNextToolProgress": { + "EventSessionNextTextEnded": { "type": "object", "properties": { "id": { @@ -20030,7 +22249,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.progress"] + "enum": ["session.next.text.ended"] }, "properties": { "type": "object", @@ -20042,34 +22261,18 @@ "type": "string", "pattern": "^ses" }, - "callID": { + "text": { "type": "string" - }, - "structured": { - "type": "object" - }, - "content": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ToolTextContent" - }, - { - "$ref": "#/components/schemas/ToolFileContent" - } - ] - } } }, - "required": ["timestamp", "sessionID", "callID", "structured", "content"], + "required": ["timestamp", "sessionID", "text"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextToolSuccess": { + "EventSessionNextReasoningStarted": { "type": "object", "properties": { "id": { @@ -20077,7 +22280,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.success"] + "enum": ["session.next.reasoning.started"] }, "properties": { "type": "object", @@ -20089,47 +22292,18 @@ "type": "string", "pattern": "^ses" }, - "callID": { + "reasoningID": { "type": "string" - }, - "structured": { - "type": "object" - }, - "content": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ToolTextContent" - }, - { - "$ref": "#/components/schemas/ToolFileContent" - } - ] - } - }, - "provider": { - "type": "object", - "properties": { - "executed": { - "type": "boolean" - }, - "metadata": { - "type": "object" - } - }, - "required": ["executed"], - "additionalProperties": false } }, - "required": ["timestamp", "sessionID", "callID", "structured", "content", "provider"], + "required": ["timestamp", "sessionID", "reasoningID"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextToolFailed": { + "EventSessionNextReasoningDelta": { "type": "object", "properties": { "id": { @@ -20137,7 +22311,7 @@ }, "type": { "type": "string", - "enum": ["session.next.tool.failed"] + "enum": ["session.next.reasoning.delta"] }, "properties": { "type": "object", @@ -20149,65 +22323,21 @@ "type": "string", "pattern": "^ses" }, - "callID": { + "reasoningID": { "type": "string" }, - "error": { - "$ref": "#/components/schemas/SessionErrorUnknown" - }, - "provider": { - "type": "object", - "properties": { - "executed": { - "type": "boolean" - }, - "metadata": { - "type": "object" - } - }, - "required": ["executed"], - "additionalProperties": false + "delta": { + "type": "string" } }, - "required": ["timestamp", "sessionID", "callID", "error", "provider"], + "required": ["timestamp", "sessionID", "reasoningID", "delta"], "additionalProperties": false } }, - "required": ["id", "type", "properties"], - "additionalProperties": false - }, - "SessionNextRetry_error": { - "type": "object", - "properties": { - "message": { - "type": "string" - }, - "statusCode": { - "type": "number" - }, - "isRetryable": { - "type": "boolean" - }, - "responseHeaders": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "responseBody": { - "type": "string" - }, - "metadata": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - }, - "required": ["message", "isRetryable"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextRetried": { + "EventSessionNextReasoningEnded": { "type": "object", "properties": { "id": { @@ -20215,7 +22345,7 @@ }, "type": { "type": "string", - "enum": ["session.next.retried"] + "enum": ["session.next.reasoning.ended"] }, "properties": { "type": "object", @@ -20227,21 +22357,21 @@ "type": "string", "pattern": "^ses" }, - "attempt": { - "type": "number" + "reasoningID": { + "type": "string" }, - "error": { - "$ref": "#/components/schemas/SessionNextRetry_error" + "text": { + "type": "string" } }, - "required": ["timestamp", "sessionID", "attempt", "error"], + "required": ["timestamp", "sessionID", "reasoningID", "text"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextCompactionStarted": { + "EventSessionNextToolInputStarted": { "type": "object", "properties": { "id": { @@ -20249,7 +22379,7 @@ }, "type": { "type": "string", - "enum": ["session.next.compaction.started"] + "enum": ["session.next.tool.input.started"] }, "properties": { "type": "object", @@ -20261,19 +22391,21 @@ "type": "string", "pattern": "^ses" }, - "reason": { - "type": "string", - "enum": ["auto", "manual"] + "callID": { + "type": "string" + }, + "name": { + "type": "string" } }, - "required": ["timestamp", "sessionID", "reason"], + "required": ["timestamp", "sessionID", "callID", "name"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextCompactionDelta": { + "EventSessionNextToolInputDelta": { "type": "object", "properties": { "id": { @@ -20281,7 +22413,7 @@ }, "type": { "type": "string", - "enum": ["session.next.compaction.delta"] + "enum": ["session.next.tool.input.delta"] }, "properties": { "type": "object", @@ -20293,18 +22425,21 @@ "type": "string", "pattern": "^ses" }, - "text": { + "callID": { + "type": "string" + }, + "delta": { "type": "string" } }, - "required": ["timestamp", "sessionID", "text"], + "required": ["timestamp", "sessionID", "callID", "delta"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventSessionNextCompactionEnded": { + "EventSessionNextToolInputEnded": { "type": "object", "properties": { "id": { @@ -20312,7 +22447,7 @@ }, "type": { "type": "string", - "enum": ["session.next.compaction.ended"] + "enum": ["session.next.tool.input.ended"] }, "properties": { "type": "object", @@ -20324,345 +22459,291 @@ "type": "string", "pattern": "^ses" }, - "text": { + "callID": { "type": "string" }, - "include": { + "text": { "type": "string" } }, - "required": ["timestamp", "sessionID", "text"], + "required": ["timestamp", "sessionID", "callID", "text"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "ModelV2Info": { + "EventSessionNextToolCalled": { "type": "object", "properties": { "id": { "type": "string" }, - "apiID": { - "type": "string" - }, - "providerID": { - "type": "string" - }, - "family": { - "type": "string" - }, - "name": { - "type": "string" + "type": { + "type": "string", + "enum": ["session.next.tool.called"] }, - "endpoint": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["unknown"] - } - }, - "required": ["type"], - "additionalProperties": false + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/responses"] - }, - "url": { - "type": "string" - }, - "websocket": { - "type": "boolean" - } - }, - "required": ["type", "url"], - "additionalProperties": false + "sessionID": { + "type": "string", + "pattern": "^ses" }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/completions"] - }, - "url": { - "type": "string" - }, - "reasoning": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_content"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_details"] - } - }, - "required": ["type"], - "additionalProperties": false - } - ] - } - }, - "required": ["type", "url"], - "additionalProperties": false + "callID": { + "type": "string" }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["anthropic/messages"] - }, - "url": { - "type": "string" - } - }, - "required": ["type", "url"], - "additionalProperties": false + "tool": { + "type": "string" }, - { + "input": { + "type": "object" + }, + "provider": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["aisdk"] - }, - "package": { - "type": "string" + "executed": { + "type": "boolean" }, - "url": { - "type": "string" + "metadata": { + "type": "object" } }, - "required": ["type", "package"], + "required": ["executed"], "additionalProperties": false } - ] + }, + "required": ["timestamp", "sessionID", "callID", "tool", "input", "provider"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolProgress": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "capabilities": { + "type": { + "type": "string", + "enum": ["session.next.tool.progress"] + }, + "properties": { "type": "object", "properties": { - "tools": { - "type": "boolean" + "timestamp": { + "type": "number" }, - "input": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" + }, + "content": { "type": "array", "items": { - "type": "string" + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] } + } + }, + "required": ["timestamp", "sessionID", "callID", "structured", "content"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolSuccess": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["session.next.tool.success"] + }, + "properties": { + "type": "object", + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "callID": { + "type": "string" + }, + "structured": { + "type": "object" }, - "output": { + "content": { "type": "array", "items": { - "type": "string" + "anyOf": [ + { + "$ref": "#/components/schemas/ToolTextContent" + }, + { + "$ref": "#/components/schemas/ToolFileContent" + } + ] } + }, + "provider": { + "type": "object", + "properties": { + "executed": { + "type": "boolean" + }, + "metadata": { + "type": "object" + } + }, + "required": ["executed"], + "additionalProperties": false } }, - "required": ["tools", "input", "output"], + "required": ["timestamp", "sessionID", "callID", "structured", "content", "provider"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextToolFailed": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "options": { + "type": { + "type": "string", + "enum": ["session.next.tool.failed"] + }, + "properties": { "type": "object", "properties": { - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } + "timestamp": { + "type": "number" }, - "body": { - "type": "object" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "aisdk": { + "callID": { + "type": "string" + }, + "error": { + "$ref": "#/components/schemas/SessionErrorUnknown" + }, + "provider": { "type": "object", "properties": { - "provider": { - "type": "object" + "executed": { + "type": "boolean" }, - "request": { + "metadata": { "type": "object" } }, - "required": ["provider", "request"], + "required": ["executed"], "additionalProperties": false - }, - "variant": { - "type": "string" } }, - "required": ["headers", "body", "aisdk"], + "required": ["timestamp", "sessionID", "callID", "error", "provider"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextRetried": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "variants": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "body": { - "type": "object" - }, - "aisdk": { - "type": "object", - "properties": { - "provider": { - "type": "object" - }, - "request": { - "type": "object" - } - }, - "required": ["provider", "request"], - "additionalProperties": false - } - }, - "required": ["id", "headers", "body", "aisdk"], - "additionalProperties": false - } + "type": { + "type": "string", + "enum": ["session.next.retried"] }, - "time": { + "properties": { "type": "object", "properties": { - "released": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "string", - "enum": ["NaN"] - }, - { - "type": "string", - "enum": ["Infinity"] - }, - { - "type": "string", - "enum": ["-Infinity"] - }, - { - "type": "string", - "enum": ["Infinity", "-Infinity", "NaN"] - } - ] + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "attempt": { + "type": "number" + }, + "error": { + "$ref": "#/components/schemas/SessionNextRetry_error" } }, - "required": ["released"], + "required": ["timestamp", "sessionID", "attempt", "error"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionNextCompactionStarted": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "cost": { - "type": "array", - "items": { - "type": "object", - "properties": { - "tier": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["context"] - }, - "size": { - "type": "integer" - } - }, - "required": ["type", "size"], - "additionalProperties": false - }, - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false - } - }, - "required": ["input", "output", "cache"], - "additionalProperties": false - } - }, - "status": { + "type": { "type": "string", - "enum": ["alpha", "beta", "deprecated", "active"] - }, - "enabled": { - "type": "boolean" + "enum": ["session.next.compaction.started"] }, - "limit": { + "properties": { "type": "object", "properties": { - "context": { - "type": "integer" + "timestamp": { + "type": "number" }, - "input": { - "type": "integer" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "output": { - "type": "integer" + "reason": { + "type": "string", + "enum": ["auto", "manual"] } }, - "required": ["context", "output"], + "required": ["timestamp", "sessionID", "reason"], "additionalProperties": false } }, - "required": [ - "id", - "apiID", - "providerID", - "name", - "endpoint", - "capabilities", - "options", - "variants", - "time", - "cost", - "status", - "enabled", - "limit" - ], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventCatalogModelUpdated": { + "EventSessionNextCompactionDelta": { "type": "object", "properties": { "id": { @@ -20670,23 +22751,30 @@ }, "type": { "type": "string", - "enum": ["catalog.model.updated"] + "enum": ["session.next.compaction.delta"] }, "properties": { "type": "object", "properties": { - "model": { - "$ref": "#/components/schemas/ModelV2Info" + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" } }, - "required": ["model"], + "required": ["timestamp", "sessionID", "text"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventModels-devRefreshed": { + "EventSessionNextCompactionEnded": { "type": "object", "properties": { "id": { @@ -20694,87 +22782,89 @@ }, "type": { "type": "string", - "enum": ["models-dev.refreshed"] + "enum": ["session.next.compaction.ended"] }, "properties": { "type": "object", - "properties": {} + "properties": { + "timestamp": { + "type": "number" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "text": { + "type": "string" + }, + "include": { + "type": "string" + } + }, + "required": ["timestamp", "sessionID", "text"], + "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "AccountV2OAuthCredential": { + "EventFileWatcherUpdated": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["oauth"] - }, - "refresh": { - "type": "string" - }, - "access": { + "id": { "type": "string" }, - "expires": { - "type": "integer", - "minimum": 0 - } - }, - "required": ["type", "refresh", "access", "expires"], - "additionalProperties": false - }, - "AccountV2ApiKeyCredential": { - "type": "object", - "properties": { "type": { "type": "string", - "enum": ["api"] - }, - "key": { - "type": "string" + "enum": ["file.watcher.updated"] }, - "metadata": { + "properties": { "type": "object", - "additionalProperties": { - "type": "string" - } + "properties": { + "file": { + "type": "string" + }, + "event": { + "type": "string", + "enum": ["add", "change", "unlink"] + } + }, + "required": ["file", "event"], + "additionalProperties": false } }, - "required": ["type", "key"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "AccountV2Credential": { - "anyOf": [ - { - "$ref": "#/components/schemas/AccountV2OAuthCredential" - }, - { - "$ref": "#/components/schemas/AccountV2ApiKeyCredential" - } - ] - }, - "AccountV2Info": { + "EventSessionCreated": { "type": "object", "properties": { "id": { "type": "string" }, - "serviceID": { - "type": "string" - }, - "description": { - "type": "string" + "type": { + "type": "string", + "enum": ["session.created"] }, - "credential": { - "$ref": "#/components/schemas/AccountV2Credential" + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" + } + }, + "required": ["sessionID", "info"], + "additionalProperties": false } }, - "required": ["id", "serviceID", "description", "credential"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventAccountAdded": { + "EventSessionUpdated": { "type": "object", "properties": { "id": { @@ -20782,23 +22872,27 @@ }, "type": { "type": "string", - "enum": ["account.added"] + "enum": ["session.updated"] }, "properties": { "type": "object", "properties": { - "account": { - "$ref": "#/components/schemas/AccountV2Info" + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" } }, - "required": ["account"], + "required": ["sessionID", "info"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventAccountRemoved": { + "EventSessionDeleted": { "type": "object", "properties": { "id": { @@ -20806,23 +22900,27 @@ }, "type": { "type": "string", - "enum": ["account.removed"] + "enum": ["session.deleted"] }, "properties": { "type": "object", "properties": { - "account": { - "$ref": "#/components/schemas/AccountV2Info" + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "info": { + "$ref": "#/components/schemas/Session" } }, - "required": ["account"], + "required": ["sessionID", "info"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventAccountSwitched": { + "EventMessageUpdated": { "type": "object", "properties": { "id": { @@ -20830,909 +22928,860 @@ }, "type": { "type": "string", - "enum": ["account.switched"] + "enum": ["message.updated"] }, "properties": { "type": "object", "properties": { - "serviceID": { - "type": "string" - }, - "from": { - "type": "string" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "to": { - "type": "string" + "info": { + "$ref": "#/components/schemas/Message" } }, - "required": ["serviceID"], + "required": ["sessionID", "info"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionInfo": { + "EventMessageRemoved": { "type": "object", "properties": { "id": { - "type": "string", - "pattern": "^ses" - }, - "parentID": { - "type": "string", - "pattern": "^ses" - }, - "projectID": { "type": "string" }, - "workspaceID": { + "type": { "type": "string", - "pattern": "^wrk" - }, - "path": { - "type": "string" - }, - "agent": { - "type": "string" + "enum": ["message.removed"] }, - "model": { + "properties": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "providerID": { - "type": "string" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "variant": { - "type": "string" + "messageID": { + "type": "string", + "pattern": "^msg" } }, - "required": ["id", "providerID", "variant"], + "required": ["sessionID", "messageID"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventMessagePartUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "cost": { - "type": "number" - }, - "tokens": { - "type": "object", - "properties": { - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "reasoning": { - "type": "number" - }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false - } - }, - "required": ["input", "output", "reasoning", "cache"], - "additionalProperties": false + "type": { + "type": "string", + "enum": ["message.part.updated"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "updated": { - "type": "number" + "part": { + "$ref": "#/components/schemas/Part" }, - "archived": { + "time": { "type": "number" } }, - "required": ["created", "updated"], + "required": ["sessionID", "part", "time"], "additionalProperties": false - }, - "title": { - "type": "string" } }, - "required": ["id", "projectID", "cost", "tokens", "time", "title"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionDelivery": { - "type": "string", - "enum": ["immediate", "deferred"] - }, - "SessionMessageAgentSwitched": { + "EventMessagePartRemoved": { "type": "object", "properties": { "id": { "type": "string" }, - "metadata": { - "type": "object" + "type": { + "type": "string", + "enum": ["message.part.removed"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "partID": { + "type": "string", + "pattern": "^prt" } }, - "required": ["created"], + "required": ["sessionID", "messageID", "partID"], "additionalProperties": false - }, - "type": { - "type": "string", - "enum": ["agent-switched"] - }, - "agent": { - "type": "string" } }, - "required": ["id", "time", "type", "agent"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageModelSwitched": { + "EventMessagePartDelta": { "type": "object", "properties": { "id": { "type": "string" }, - "metadata": { - "type": "object" - }, - "time": { - "type": "object", - "properties": { - "created": { - "type": "number" - } - }, - "required": ["created"], - "additionalProperties": false - }, "type": { "type": "string", - "enum": ["model-switched"] + "enum": ["message.part.delta"] }, - "model": { + "properties": { "type": "object", "properties": { - "id": { - "type": "string" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "providerID": { + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "partID": { + "type": "string", + "pattern": "^prt" + }, + "field": { "type": "string" }, - "variant": { + "delta": { "type": "string" } }, - "required": ["id", "providerID", "variant"], + "required": ["sessionID", "messageID", "partID", "field", "delta"], "additionalProperties": false } }, - "required": ["id", "time", "type", "model"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageUser": { + "EventPermissionAsked": { "type": "object", "properties": { "id": { "type": "string" }, - "metadata": { - "type": "object" + "type": { + "type": "string", + "enum": ["permission.asked"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" + "id": { + "type": "string", + "pattern": "^per" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "permission": { + "type": "string" + }, + "patterns": { + "type": "array", + "items": { + "type": "string" + } + }, + "metadata": { + "type": "object" + }, + "always": { + "type": "array", + "items": { + "type": "string" + } + }, + "tool": { + "type": "object", + "properties": { + "messageID": { + "type": "string", + "pattern": "^msg" + }, + "callID": { + "type": "string" + } + }, + "required": ["messageID", "callID"], + "additionalProperties": false } }, - "required": ["created"], + "required": ["id", "sessionID", "permission", "patterns", "metadata", "always"], "additionalProperties": false - }, - "text": { - "type": "string" - }, - "files": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PromptFileAttachment" - } - }, - "agents": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PromptAgentAttachment" - } - }, - "references": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PromptReferenceAttachment" - } - }, - "type": { - "type": "string", - "enum": ["user"] } }, - "required": ["id", "time", "text", "type"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageSynthetic": { + "EventPermissionReplied": { "type": "object", "properties": { "id": { "type": "string" }, - "metadata": { - "type": "object" + "type": { + "type": "string", + "enum": ["permission.replied"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^per" + }, + "reply": { + "type": "string", + "enum": ["once", "always", "reject"] } }, - "required": ["created"], + "required": ["sessionID", "requestID", "reply"], "additionalProperties": false - }, - "sessionID": { - "type": "string", - "pattern": "^ses" - }, - "text": { - "type": "string" - }, - "type": { - "type": "string", - "enum": ["synthetic"] } }, - "required": ["id", "time", "sessionID", "text", "type"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageShell": { + "EventSessionDiff": { "type": "object", "properties": { "id": { "type": "string" }, - "metadata": { - "type": "object" + "type": { + "type": "string", + "enum": ["session.diff"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "completed": { - "type": "number" + "diff": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SnapshotFileDiff" + } } }, - "required": ["created"], + "required": ["sessionID", "diff"], "additionalProperties": false - }, - "type": { - "type": "string", - "enum": ["shell"] - }, - "callID": { - "type": "string" - }, - "command": { - "type": "string" - }, - "output": { - "type": "string" } }, - "required": ["id", "time", "type", "callID", "command", "output"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageAssistantText": { + "EventSessionError": { "type": "object", "properties": { + "id": { + "type": "string" + }, "type": { "type": "string", - "enum": ["text"] + "enum": ["session.error"] }, - "text": { - "type": "string" + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "error": { + "anyOf": [ + { + "$ref": "#/components/schemas/ProviderAuthError" + }, + { + "$ref": "#/components/schemas/UnknownError" + }, + { + "$ref": "#/components/schemas/MessageOutputLengthError" + }, + { + "$ref": "#/components/schemas/MessageAbortedError" + }, + { + "$ref": "#/components/schemas/StructuredOutputError" + }, + { + "$ref": "#/components/schemas/ContextOverflowError" + }, + { + "$ref": "#/components/schemas/APIError" + } + ] + } + }, + "additionalProperties": false } }, - "required": ["type", "text"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageAssistantReasoning": { + "EventQuestionAsked": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["reasoning"] - }, "id": { "type": "string" }, - "text": { - "type": "string" - } - }, - "required": ["type", "id", "text"], - "additionalProperties": false - }, - "SessionMessageToolStatePending": { - "type": "object", - "properties": { - "status": { + "type": { "type": "string", - "enum": ["pending"] + "enum": ["question.asked"] }, - "input": { - "type": "string" + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^que" + }, + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "questions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionInfo" + }, + "description": "Questions to ask" + }, + "tool": { + "$ref": "#/components/schemas/QuestionTool" + } + }, + "required": ["id", "sessionID", "questions"], + "additionalProperties": false } }, - "required": ["status", "input"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageToolStateRunning": { + "EventQuestionReplied": { "type": "object", "properties": { - "status": { - "type": "string", - "enum": ["running"] - }, - "input": { - "type": "object" + "id": { + "type": "string" }, - "structured": { - "type": "object" + "type": { + "type": "string", + "enum": ["question.replied"] }, - "content": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ToolTextContent" - }, - { - "$ref": "#/components/schemas/ToolFileContent" + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^que" + }, + "answers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QuestionAnswer" } - ] - } + } + }, + "required": ["sessionID", "requestID", "answers"], + "additionalProperties": false } }, - "required": ["status", "input", "structured", "content"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageToolStateCompleted": { + "EventQuestionRejected": { "type": "object", "properties": { - "status": { - "type": "string", - "enum": ["completed"] - }, - "input": { - "type": "object" - }, - "attachments": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PromptFileAttachment" - } + "id": { + "type": "string" }, - "content": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ToolTextContent" - }, - { - "$ref": "#/components/schemas/ToolFileContent" - } - ] - } + "type": { + "type": "string", + "enum": ["question.rejected"] }, - "structured": { - "type": "object" + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "requestID": { + "type": "string", + "pattern": "^que" + } + }, + "required": ["sessionID", "requestID"], + "additionalProperties": false } }, - "required": ["status", "input", "content", "structured"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageToolStateError": { + "EventTodoUpdated": { "type": "object", "properties": { - "status": { - "type": "string", - "enum": ["error"] + "id": { + "type": "string" }, - "input": { - "type": "object" + "type": { + "type": "string", + "enum": ["todo.updated"] }, - "content": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/ToolTextContent" - }, - { - "$ref": "#/components/schemas/ToolFileContent" + "properties": { + "type": "object", + "properties": { + "sessionID": { + "type": "string", + "pattern": "^ses" + }, + "todos": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Todo" } - ] - } - }, - "structured": { - "type": "object" - }, - "error": { - "$ref": "#/components/schemas/SessionErrorUnknown" + } + }, + "required": ["sessionID", "todos"], + "additionalProperties": false } }, - "required": ["status", "input", "content", "structured", "error"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageAssistantTool": { + "EventSessionStatus": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["tool"] - }, "id": { "type": "string" }, - "name": { - "type": "string" + "type": { + "type": "string", + "enum": ["session.status"] }, - "provider": { + "properties": { "type": "object", "properties": { - "executed": { - "type": "boolean" + "sessionID": { + "type": "string", + "pattern": "^ses" }, - "metadata": { - "type": "object" + "status": { + "$ref": "#/components/schemas/SessionStatus" } }, - "required": ["executed"], + "required": ["sessionID", "status"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventSessionIdle": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "state": { - "anyOf": [ - { - "$ref": "#/components/schemas/SessionMessageToolStatePending" - }, - { - "$ref": "#/components/schemas/SessionMessageToolStateRunning" - }, - { - "$ref": "#/components/schemas/SessionMessageToolStateCompleted" - }, - { - "$ref": "#/components/schemas/SessionMessageToolStateError" - } - ] + "type": { + "type": "string", + "enum": ["session.idle"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" - }, - "ran": { - "type": "number" - }, - "completed": { - "type": "number" - }, - "pruned": { - "type": "number" + "sessionID": { + "type": "string", + "pattern": "^ses" } }, - "required": ["created"], + "required": ["sessionID"], "additionalProperties": false } }, - "required": ["type", "id", "name", "state", "time"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageAssistant": { + "EventSessionCompacted": { "type": "object", "properties": { "id": { "type": "string" }, - "metadata": { - "type": "object" - }, - "time": { - "type": "object", - "properties": { - "created": { - "type": "number" - }, - "completed": { - "type": "number" - } - }, - "required": ["created"], - "additionalProperties": false - }, "type": { "type": "string", - "enum": ["assistant"] - }, - "agent": { - "type": "string" + "enum": ["session.compacted"] }, - "model": { + "properties": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "providerID": { - "type": "string" - }, - "variant": { - "type": "string" + "sessionID": { + "type": "string", + "pattern": "^ses" } }, - "required": ["id", "providerID", "variant"], + "required": ["sessionID"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventLspUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "content": { - "type": "array", - "items": { - "anyOf": [ - { - "$ref": "#/components/schemas/SessionMessageAssistantText" - }, - { - "$ref": "#/components/schemas/SessionMessageAssistantReasoning" - }, - { - "$ref": "#/components/schemas/SessionMessageAssistantTool" - } - ] - } + "type": { + "type": "string", + "enum": ["lsp.updated"] }, - "snapshot": { + "properties": { "type": "object", - "properties": { - "start": { - "type": "string" - }, - "end": { - "type": "string" - } - }, - "additionalProperties": false - }, - "finish": { + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventMcpToolsChanged": { + "type": "object", + "properties": { + "id": { "type": "string" }, - "cost": { - "type": "number" + "type": { + "type": "string", + "enum": ["mcp.tools.changed"] }, - "tokens": { + "properties": { "type": "object", "properties": { - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "reasoning": { - "type": "number" - }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false + "server": { + "type": "string" } }, - "required": ["input", "output", "reasoning", "cache"], + "required": ["server"], "additionalProperties": false - }, - "error": { - "$ref": "#/components/schemas/SessionErrorUnknown" } }, - "required": ["id", "time", "type", "agent", "model", "content"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessageCompaction": { + "EventMcpBrowserOpenFailed": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["compaction"] - }, - "reason": { - "type": "string", - "enum": ["auto", "manual"] - }, - "summary": { - "type": "string" - }, - "include": { - "type": "string" - }, "id": { "type": "string" }, - "metadata": { - "type": "object" + "type": { + "type": "string", + "enum": ["mcp.browser.open.failed"] }, - "time": { + "properties": { "type": "object", "properties": { - "created": { - "type": "number" + "mcpName": { + "type": "string" + }, + "url": { + "type": "string" } }, - "required": ["created"], + "required": ["mcpName", "url"], "additionalProperties": false } }, - "required": ["type", "reason", "summary", "id", "time"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "SessionMessage": { - "anyOf": [ - { - "$ref": "#/components/schemas/SessionMessageAgentSwitched" - }, - { - "$ref": "#/components/schemas/SessionMessageModelSwitched" - }, - { - "$ref": "#/components/schemas/SessionMessageUser" - }, - { - "$ref": "#/components/schemas/SessionMessageSynthetic" - }, - { - "$ref": "#/components/schemas/SessionMessageShell" - }, - { - "$ref": "#/components/schemas/SessionMessageAssistant" - }, - { - "$ref": "#/components/schemas/SessionMessageCompaction" - } - ] - }, - "ProviderV2Info": { + "EventCommandExecuted": { "type": "object", "properties": { "id": { "type": "string" }, - "name": { - "type": "string" + "type": { + "type": "string", + "enum": ["command.executed"] }, - "enabled": { - "anyOf": [ - { - "type": "boolean", - "enum": [false] + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" }, - { - "type": "object", - "properties": { - "via": { - "type": "string", - "enum": ["env"] - }, - "name": { - "type": "string" - } - }, - "required": ["via", "name"], - "additionalProperties": false + "sessionID": { + "type": "string", + "pattern": "^ses" }, - { - "type": "object", - "properties": { - "via": { - "type": "string", - "enum": ["account"] - }, - "service": { - "type": "string" - } - }, - "required": ["via", "service"], - "additionalProperties": false + "arguments": { + "type": "string" }, - { - "type": "object", - "properties": { - "via": { - "type": "string", - "enum": ["custom"] - }, - "data": { - "type": "object" - } - }, - "required": ["via", "data"], - "additionalProperties": false + "messageID": { + "type": "string", + "pattern": "^msg" } - ] + }, + "required": ["name", "sessionID", "arguments", "messageID"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventProjectUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "env": { - "type": "array", - "items": { - "type": "string" - } + "type": { + "type": "string", + "enum": ["project.updated"] }, - "endpoint": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["unknown"] - } - }, - "required": ["type"], - "additionalProperties": false + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - { + "worktree": { + "type": "string" + }, + "vcs": { + "type": "string", + "enum": ["git"] + }, + "name": { + "type": "string" + }, + "icon": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["openai/responses"] - }, "url": { "type": "string" }, - "websocket": { - "type": "boolean" - } - }, - "required": ["type", "url"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/completions"] - }, - "url": { + "override": { "type": "string" }, - "reasoning": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_content"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_details"] - } - }, - "required": ["type"], - "additionalProperties": false - } - ] + "color": { + "type": "string" } }, - "required": ["type", "url"], "additionalProperties": false }, - { + "commands": { "type": "object", "properties": { - "type": { + "start": { "type": "string", - "enum": ["anthropic/messages"] - }, - "url": { - "type": "string" + "description": "Startup script to run when creating a new workspace (worktree)" } }, - "required": ["type", "url"], "additionalProperties": false }, - { + "time": { "type": "object", "properties": { - "type": { - "type": "string", - "enum": ["aisdk"] + "created": { + "type": "integer", + "minimum": 0 }, - "package": { - "type": "string" + "updated": { + "type": "integer", + "minimum": 0 }, - "url": { - "type": "string" + "initialized": { + "type": "integer", + "minimum": 0 } }, - "required": ["type", "package"], + "required": ["created", "updated"], "additionalProperties": false + }, + "sandboxes": { + "type": "array", + "items": { + "type": "string" + } } - ] + }, + "required": ["id", "worktree", "time", "sandboxes"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventVcsBranchUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "options": { + "type": { + "type": "string", + "enum": ["vcs.branch.updated"] + }, + "properties": { "type": "object", "properties": { - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } + "branch": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventWorkspaceReady": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["workspace.ready"] + }, + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "required": ["name"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventWorkspaceFailed": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["workspace.failed"] + }, + "properties": { + "type": "object", + "properties": { + "message": { + "type": "string" + } + }, + "required": ["message"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventWorkspaceStatus": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["workspace.status"] + }, + "properties": { + "type": "object", + "properties": { + "workspaceID": { + "type": "string", + "pattern": "^wrk" }, - "body": { - "type": "object" + "status": { + "type": "string", + "enum": ["connected", "connecting", "disconnected", "error"] + } + }, + "required": ["workspaceID", "status"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventWorktreeReady": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["worktree.ready"] + }, + "properties": { + "type": "object", + "properties": { + "name": { + "type": "string" }, - "aisdk": { - "type": "object", - "properties": { - "provider": { - "type": "object" - }, - "request": { - "type": "object" - } - }, - "required": ["provider", "request"], - "additionalProperties": false + "branch": { + "type": "string" } }, - "required": ["headers", "body", "aisdk"], + "required": ["name"], "additionalProperties": false } }, - "required": ["id", "name", "enabled", "env", "endpoint", "options"], + "required": ["id", "type", "properties"], "additionalProperties": false }, - "EventTuiToastShow1": { + "EventWorktreeFailed": { "type": "object", "properties": { "id": { @@ -21740,351 +23789,284 @@ }, "type": { "type": "string", - "enum": ["tui.toast.show"] + "enum": ["worktree.failed"] }, "properties": { "type": "object", "properties": { - "title": { - "type": "string" - }, "message": { "type": "string" - }, - "variant": { - "type": "string", - "enum": ["info", "success", "warning", "error"] - }, - "duration": { - "type": "integer", - "exclusiveMinimum": 0 } }, - "required": ["message", "variant"], + "required": ["message"], "additionalProperties": false } }, "required": ["id", "type", "properties"], "additionalProperties": false }, - "ModelV2Info1": { + "EventPtyCreated": { "type": "object", "properties": { "id": { "type": "string" }, - "apiID": { - "type": "string" + "type": { + "type": "string", + "enum": ["pty.created"] }, - "providerID": { + "properties": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": ["info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventPtyUpdated": { + "type": "object", + "properties": { + "id": { "type": "string" }, - "family": { - "type": "string" + "type": { + "type": "string", + "enum": ["pty.updated"] }, - "name": { + "properties": { + "type": "object", + "properties": { + "info": { + "$ref": "#/components/schemas/Pty" + } + }, + "required": ["info"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventPtyExited": { + "type": "object", + "properties": { + "id": { "type": "string" }, - "endpoint": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["unknown"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/responses"] - }, - "url": { - "type": "string" - }, - "websocket": { - "type": "boolean" - } - }, - "required": ["type", "url"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["openai/completions"] - }, - "url": { - "type": "string" - }, - "reasoning": { - "anyOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_content"] - } - }, - "required": ["type"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["reasoning_details"] - } - }, - "required": ["type"], - "additionalProperties": false - } - ] - } - }, - "required": ["type", "url"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["anthropic/messages"] - }, - "url": { - "type": "string" - } - }, - "required": ["type", "url"], - "additionalProperties": false + "type": { + "type": "string", + "enum": ["pty.exited"] + }, + "properties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^pty" }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["aisdk"] - }, - "package": { - "type": "string" - }, - "url": { - "type": "string" - } - }, - "required": ["type", "package"], - "additionalProperties": false + "exitCode": { + "type": "integer", + "minimum": 0 } - ] + }, + "required": ["id", "exitCode"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventPtyDeleted": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "capabilities": { + "type": { + "type": "string", + "enum": ["pty.deleted"] + }, + "properties": { "type": "object", "properties": { - "tools": { - "type": "boolean" - }, - "input": { - "type": "array", - "items": { - "type": "string" - } - }, - "output": { - "type": "array", - "items": { - "type": "string" - } + "id": { + "type": "string", + "pattern": "^pty" + } + }, + "required": ["id"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventInstallationUpdated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["installation.updated"] + }, + "properties": { + "type": "object", + "properties": { + "version": { + "type": "string" + } + }, + "required": ["version"], + "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventInstallationUpdate-available": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["installation.update-available"] + }, + "properties": { + "type": "object", + "properties": { + "version": { + "type": "string" } }, - "required": ["tools", "input", "output"], + "required": ["version"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventServerConnected": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "options": { + "type": { + "type": "string", + "enum": ["server.connected"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventGlobalDisposed": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["global.disposed"] + }, + "properties": { + "type": "object", + "properties": {} + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventAccountAdded": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string", + "enum": ["account.added"] + }, + "properties": { "type": "object", "properties": { - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "body": { - "type": "object" - }, - "aisdk": { - "type": "object", - "properties": { - "provider": { - "type": "object" - }, - "request": { - "type": "object" - } - }, - "required": ["provider", "request"], - "additionalProperties": false - }, - "variant": { - "type": "string" + "account": { + "$ref": "#/components/schemas/AuthInfo" } }, - "required": ["headers", "body", "aisdk"], + "required": ["account"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventAccountRemoved": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "variants": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "headers": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "body": { - "type": "object" - }, - "aisdk": { - "type": "object", - "properties": { - "provider": { - "type": "object" - }, - "request": { - "type": "object" - } - }, - "required": ["provider", "request"], - "additionalProperties": false - } - }, - "required": ["id", "headers", "body", "aisdk"], - "additionalProperties": false - } + "type": { + "type": "string", + "enum": ["account.removed"] }, - "time": { + "properties": { "type": "object", "properties": { - "released": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "string", - "enum": ["NaN"] - }, - { - "type": "string", - "enum": ["Infinity"] - }, - { - "type": "string", - "enum": ["-Infinity"] - } - ] + "account": { + "$ref": "#/components/schemas/AuthInfo" } }, - "required": ["released"], + "required": ["account"], "additionalProperties": false + } + }, + "required": ["id", "type", "properties"], + "additionalProperties": false + }, + "EventAccountSwitched": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "cost": { - "type": "array", - "items": { - "type": "object", - "properties": { - "tier": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["context"] - }, - "size": { - "type": "integer" - } - }, - "required": ["type", "size"], - "additionalProperties": false - }, - "input": { - "type": "number" - }, - "output": { - "type": "number" - }, - "cache": { - "type": "object", - "properties": { - "read": { - "type": "number" - }, - "write": { - "type": "number" - } - }, - "required": ["read", "write"], - "additionalProperties": false - } - }, - "required": ["input", "output", "cache"], - "additionalProperties": false - } - }, - "status": { + "type": { "type": "string", - "enum": ["alpha", "beta", "deprecated", "active"] - }, - "enabled": { - "type": "boolean" + "enum": ["account.switched"] }, - "limit": { + "properties": { "type": "object", "properties": { - "context": { - "type": "integer" + "serviceID": { + "type": "string" }, - "input": { - "type": "integer" + "from": { + "type": "string" }, - "output": { - "type": "integer" + "to": { + "type": "string" } }, - "required": ["context", "output"], + "required": ["serviceID"], "additionalProperties": false } }, - "required": [ - "id", - "apiID", - "providerID", - "name", - "endpoint", - "capabilities", - "options", - "variants", - "time", - "cost", - "status", - "enabled", - "limit" - ], + "required": ["id", "type", "properties"], "additionalProperties": false }, "BadRequestError": { diff --git a/packages/stats/AGENTS.md b/packages/stats/AGENTS.md new file mode 100644 index 000000000000..409271cf09a5 --- /dev/null +++ b/packages/stats/AGENTS.md @@ -0,0 +1 @@ +To start the stats site locally, run `bun dev:stats` from the repo root. diff --git a/packages/stats/README.md b/packages/stats/README.md new file mode 100644 index 000000000000..6c66684cc529 --- /dev/null +++ b/packages/stats/README.md @@ -0,0 +1,16 @@ +# OpenCode Stats + +Stats is a separate site from the console. Runtime, database, and domain services live in `core`; the SolidStart website lives in `app`; deployable Lambda entrypoints live in `function`. + +## Packages + +- `app`: SolidStart frontend/site. +- `core`: Effect services, app config, Drizzle schema/migrations, and stats domains. +- `function`: Lambda handlers that call into `core` services. + +## Commands + +- `bun run dev:stats` from the repo root starts the SolidStart app. +- `bun run --cwd packages/stats/app typecheck` typechecks the site. +- `bun run --cwd packages/stats/core typecheck` typechecks the Effect/database package. +- `bun run --cwd packages/stats/function typecheck` typechecks Lambda entrypoints. diff --git a/packages/stats/app/.gitignore b/packages/stats/app/.gitignore new file mode 100644 index 000000000000..60a72e7e6c23 --- /dev/null +++ b/packages/stats/app/.gitignore @@ -0,0 +1,17 @@ +dist +.wrangler +.output +.vercel +.netlify +app.config.timestamp_*.js + +# Environment +.env +.env*.local + +# dependencies +/node_modules + +# System Files +.DS_Store +Thumbs.db diff --git a/packages/stats/app/app.config.ts b/packages/stats/app/app.config.ts new file mode 100644 index 000000000000..40a103295f0c --- /dev/null +++ b/packages/stats/app/app.config.ts @@ -0,0 +1,5 @@ +export default { + server: { + preset: "cloudflare-module", + }, +} diff --git a/packages/stats/app/package.json b/packages/stats/app/package.json new file mode 100644 index 000000000000..0a8275c37543 --- /dev/null +++ b/packages/stats/app/package.json @@ -0,0 +1,38 @@ +{ + "$schema": "https://json.schemastore.org/package.json", + "name": "@opencode-ai/stats-app", + "version": "1.15.13", + "private": true, + "type": "module", + "license": "MIT", + "scripts": { + "typecheck": "tsgo --noEmit", + "dev": "vite dev --host 0.0.0.0", + "build": "vite build", + "start": "vite start" + }, + "dependencies": { + "@ibm/plex": "6.4.1", + "@opencode-ai/stats-core": "workspace:*", + "@opencode-ai/ui": "workspace:*", + "@solidjs/meta": "catalog:", + "@solidjs/router": "catalog:", + "@solidjs/start": "catalog:", + "d3-scale": "4.0.2", + "effect": "catalog:", + "nitro": "3.0.1-alpha.1", + "sst": "catalog:", + "solid-js": "catalog:", + "vite": "catalog:" + }, + "devDependencies": { + "@cloudflare/workers-types": "catalog:", + "@types/bun": "catalog:", + "@types/d3-scale": "4.0.9", + "@typescript/native-preview": "catalog:", + "typescript": "catalog:" + }, + "engines": { + "node": ">=22" + } +} diff --git a/packages/stats/app/src/app.css b/packages/stats/app/src/app.css new file mode 100644 index 000000000000..6b7652a0337c --- /dev/null +++ b/packages/stats/app/src/app.css @@ -0,0 +1,123 @@ +:root { + color-scheme: light dark; + --stats-bg: #f8f5ee; + --stats-ink: #16110d; + --stats-muted: #6d6257; + --stats-line: #ded5c9; + --stats-panel: #fffaf1; + --stats-accent: #2357ff; +} + +@media (prefers-color-scheme: dark) { + :root { + --stats-bg: #11100e; + --stats-ink: #f7efe4; + --stats-muted: #b8aa99; + --stats-line: #322d27; + --stats-panel: #1a1714; + --stats-accent: #86a2ff; + } +} + +html { + line-height: 1; + background: var(--stats-bg); +} + +body { + margin: 0; + min-width: 320px; + background: + radial-gradient(circle at top left, color-mix(in srgb, var(--stats-accent) 16%, transparent), transparent 32rem), + var(--stats-bg); + color: var(--stats-ink); + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + -webkit-font-smoothing: antialiased; +} + +a { + color: inherit; +} + +.shell { + box-sizing: border-box; + min-height: 100vh; + padding: 2rem clamp(1rem, 4vw, 4rem); +} + +.panel { + display: grid; + gap: clamp(2rem, 8vw, 5rem); + box-sizing: border-box; + width: min(100%, 72rem); + margin: 0 auto; + padding: clamp(1.25rem, 4vw, 3rem); + border: 1px solid var(--stats-line); + border-radius: 1.5rem; + background: color-mix(in srgb, var(--stats-panel) 88%, transparent); +} + +.eyebrow { + margin: 0 0 1rem; + color: var(--stats-muted); + font-size: 0.75rem; + letter-spacing: 0.14em; + text-transform: uppercase; +} + +h1 { + max-width: 11ch; + margin: 0; + font-size: clamp(3rem, 14vw, 9rem); + line-height: 0.85; + letter-spacing: -0.08em; +} + +.summary { + max-width: 42rem; + margin: 1.5rem 0 0; + color: var(--stats-muted); + font-size: clamp(1rem, 2vw, 1.25rem); + line-height: 1.6; +} + +.grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 1px; + overflow: hidden; + border: 1px solid var(--stats-line); + border-radius: 1rem; + background: var(--stats-line); +} + +.metric { + padding: 1rem; + background: var(--stats-panel); +} + +.metric b { + display: block; + margin-bottom: 0.5rem; + font-size: clamp(1.5rem, 4vw, 3rem); + letter-spacing: -0.05em; +} + +.metric span { + color: var(--stats-muted); + font-size: 0.8125rem; +} + +.link { + display: inline-flex; + width: fit-content; + margin-top: 1.5rem; + color: var(--stats-accent); + text-decoration: none; +} + +@media (max-width: 720px) { + .grid { + grid-template-columns: 1fr; + } +} diff --git a/packages/stats/app/src/app.tsx b/packages/stats/app/src/app.tsx new file mode 100644 index 000000000000..1d46cb782f0f --- /dev/null +++ b/packages/stats/app/src/app.tsx @@ -0,0 +1,31 @@ +import { MetaProvider, Meta, Title } from "@solidjs/meta" +import { Router } from "@solidjs/router" +import { FileRoutes } from "@solidjs/start/router" +import { Suspense } from "solid-js" +import "./app.css" + +function AppMeta() { + return ( + <> + OpenCode Stats + + + ) +} + +export default function App() { + return ( + ( + + + {props.children} + + )} + > + + + ) +} diff --git a/packages/stats/app/src/asset/logo-ornate-dark.svg b/packages/stats/app/src/asset/logo-ornate-dark.svg new file mode 100644 index 000000000000..a1582732423a --- /dev/null +++ b/packages/stats/app/src/asset/logo-ornate-dark.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/packages/stats/app/src/asset/logo-ornate-light.svg b/packages/stats/app/src/asset/logo-ornate-light.svg new file mode 100644 index 000000000000..2a856dccefe8 --- /dev/null +++ b/packages/stats/app/src/asset/logo-ornate-light.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/packages/stats/app/src/asset/unfurl-rankings.png b/packages/stats/app/src/asset/unfurl-rankings.png new file mode 100644 index 000000000000..872cb6073dc6 Binary files /dev/null and b/packages/stats/app/src/asset/unfurl-rankings.png differ diff --git a/packages/stats/app/src/entry-client.tsx b/packages/stats/app/src/entry-client.tsx new file mode 100644 index 000000000000..8187b9eadc49 --- /dev/null +++ b/packages/stats/app/src/entry-client.tsx @@ -0,0 +1,7 @@ +// @refresh reload +import { mount, StartClient } from "@solidjs/start/client" + +const root = document.getElementById("app") +if (!root) throw new Error("Root element #app not found") + +mount(() => , root) diff --git a/packages/stats/app/src/entry-server.tsx b/packages/stats/app/src/entry-server.tsx new file mode 100644 index 000000000000..f1e054cfa0b3 --- /dev/null +++ b/packages/stats/app/src/entry-server.tsx @@ -0,0 +1,37 @@ +// @refresh reload +import { createHandler, StartServer } from "@solidjs/start/server" + +const statsThemePreloadScript = `;(function () { + var preference = "system" + try { + var stored = localStorage.getItem("opencode:stats-theme") + if (stored === "dark" || stored === "light" || stored === "system") preference = stored + } catch (_) {} + document.documentElement.dataset.statsTheme = preference + if (preference === "system") document.documentElement.style.removeProperty("color-scheme") + else document.documentElement.style.setProperty("color-scheme", preference) +})()` + +export default createHandler( + () => ( + ( + + + + + + {assets} + + +
{children}
+ {scripts} + + + )} + /> + ), + { + mode: "async", + }, +) diff --git a/packages/stats/app/src/global.d.ts b/packages/stats/app/src/global.d.ts new file mode 100644 index 000000000000..dc6f10c226c0 --- /dev/null +++ b/packages/stats/app/src/global.d.ts @@ -0,0 +1 @@ +/// diff --git a/packages/stats/app/src/resource.d.ts b/packages/stats/app/src/resource.d.ts new file mode 100644 index 000000000000..098ea852ad09 --- /dev/null +++ b/packages/stats/app/src/resource.d.ts @@ -0,0 +1,10 @@ +import "sst/resource" + +declare module "sst/resource" { + export interface Resource { + EMAILOCTOPUS_API_KEY: { + type: "sst.sst.Secret" + value: string + } + } +} diff --git a/packages/stats/app/src/routes/api/health.ts b/packages/stats/app/src/routes/api/health.ts new file mode 100644 index 000000000000..fe7abc9a7f05 --- /dev/null +++ b/packages/stats/app/src/routes/api/health.ts @@ -0,0 +1,19 @@ +import { AppConfig } from "@opencode-ai/stats-core/config" +import { runtime } from "@opencode-ai/stats-core/runtime" +import { Effect } from "effect" + +export async function GET() { + return Response.json( + await runtime.runPromise( + Effect.gen(function* () { + const config = yield* AppConfig + return { + ok: true, + app: "stats", + stage: config.stage, + publicUrl: config.publicUrl, + } + }), + ), + ) +} diff --git a/packages/stats/app/src/routes/api/newsletter.ts b/packages/stats/app/src/routes/api/newsletter.ts new file mode 100644 index 000000000000..50485fb48579 --- /dev/null +++ b/packages/stats/app/src/routes/api/newsletter.ts @@ -0,0 +1,29 @@ +import { Resource } from "sst/resource" + +const listId = "8b9bb82c-9d5f-11f0-975f-0df6fd1e4945" + +export async function POST(event: { request: Request }) { + const contentType = event.request.headers.get("content-type") ?? "" + if (!contentType.includes("multipart/form-data") && !contentType.includes("application/x-www-form-urlencoded")) { + return Response.json({ error: "Email address is required" }, { status: 400 }) + } + + const form = await event.request.formData() + const emailAddress = form.get("email") + if (typeof emailAddress !== "string" || emailAddress.trim().length === 0) { + return Response.json({ error: "Email address is required" }, { status: 400 }) + } + + const response = await fetch(`https://api.emailoctopus.com/lists/${listId}/contacts`, { + method: "PUT", + headers: { + Authorization: `Bearer ${Resource.EMAILOCTOPUS_API_KEY.value}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + email_address: emailAddress.trim(), + }), + }) + if (!response.ok) return Response.json({ error: "Failed to subscribe" }, { status: 502 }) + return Response.json({ success: true }) +} diff --git a/packages/stats/app/src/routes/index.css b/packages/stats/app/src/routes/index.css new file mode 100644 index 000000000000..44d889d0470f --- /dev/null +++ b/packages/stats/app/src/routes/index.css @@ -0,0 +1,2941 @@ +@font-face { + font-family: "IBM Plex Mono"; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url("@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Regular-Latin1.woff2") format("woff2"); + unicode-range: + U+0020-007E, U+00A0-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, + U+2020-2022, U+2026, U+2030, U+2039-203A, U+2044, U+20AC, U+2122, U+2212, U+FB01-FB02; +} + +@font-face { + font-family: "IBM Plex Mono"; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url("@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Medium-Latin1.woff2") format("woff2"); + unicode-range: + U+0020-007E, U+00A0-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, + U+2020-2022, U+2026, U+2030, U+2039-203A, U+2044, U+20AC, U+2122, U+2212, U+FB01-FB02; +} + +@font-face { + font-family: "IBM Plex Mono"; + font-style: normal; + font-weight: 600; + font-display: swap; + src: url("@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-SemiBold-Latin1.woff2") format("woff2"); + unicode-range: + U+0020-007E, U+00A0-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, + U+2020-2022, U+2026, U+2030, U+2039-203A, U+2044, U+20AC, U+2122, U+2212, U+FB01-FB02; +} + +@font-face { + font-family: "IBM Plex Mono"; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url("@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Bold-Latin1.woff2") format("woff2"); + unicode-range: + U+0020-007E, U+00A0-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2013-2014, U+2018-201A, U+201C-201E, + U+2020-2022, U+2026, U+2030, U+2039-203A, U+2044, U+20AC, U+2122, U+2212, U+FB01-FB02; +} + +[data-page="stats"] { + color-scheme: light; + --color-background: #ffffff; + --color-background-weak: #fafafa; + --color-background-weak-hover: #eeeeee; + --color-background-strong: #161616; + --color-background-strong-hover: #242424; + --color-text: #5c5c5c; + --color-text-weak: #808080; + --color-text-strong: #161616; + --color-text-inverted: #ffffff; + --color-border-weak: #0000001a; + --stats-bg: #ffffff; + --stats-layer: #fafafa; + --stats-layer-2: #eeeeee; + --stats-line: #0000001a; + --stats-line-strong: #00000033; + --stats-text: #161616; + --stats-muted: #5c5c5c; + --stats-faint: #808080; + --stats-theme-icon-active: #3a3a3a; + --stats-accent: #3b5cf6; + --stats-accent-text: #6c7dff; + --stats-bar-idle: #d4d4d4; + --stats-dot: #d4d4d4; + --stats-hero-muted: #5c5c5c; + --stats-hero-pattern: #eeeeee; + --stats-logo-bg: #161616; + --stats-logo-fill: #454545; + --stats-logo-stroke: #e2e2e2; + --stats-page-padding: 5rem; + --stats-section-padding: 6rem; + min-height: 100vh; + display: flex; + flex-direction: column; + font-synthesis: none; + overflow-x: clip; + padding-bottom: 0; + background: var(--stats-bg); +} + +[data-page="stats"] [hidden] { + display: none !important; +} + +[data-page="stats"] [data-component="content"] { + color: var(--stats-text); + font-family: + "IBM Plex Mono", + var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace); +} + +[data-page="stats"] [data-component="container"] { + box-sizing: border-box; + width: 100%; + max-width: 80rem; + margin: 0 auto; +} + +[data-page="stats"] [data-component="top"] { + position: sticky; + top: 0; + z-index: 10; + box-sizing: border-box; + width: 100%; + color: var(--stats-text); + background: var(--stats-bg); + font-family: + "IBM Plex Mono", + var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace); +} + +[data-page="stats"] [data-component="top"] * { + box-sizing: border-box; +} + +[data-page="stats"] [data-slot="header-bar"] { + display: flex; + align-items: center; + gap: 16px; + min-height: 72px; + padding: 20px 20px 20px 24px; + overflow: hidden; +} + +[data-page="stats"] [data-component="top"] a { + text-decoration: none; +} + +[data-page="stats"] [data-component="top"] a:hover { + text-decoration: none; +} + +[data-page="stats"] [data-slot="brand"] { + flex: 0 0 auto; + min-width: 0; + display: flex; + align-items: center; + margin-right: auto; + color: var(--stats-text); +} + +[data-page="stats"] [data-slot="stats-wordmark"] { + display: flex; + flex-shrink: 0; + align-items: center; + gap: 12px; +} + +[data-page="stats"] [data-slot="brand-mark"] { + display: block; + width: 19px; + height: 24px; +} + +[data-page="stats"] [data-slot="brand-label"] { + display: block; + width: 50.851px; + height: 14px; +} + +[data-page="stats"] [data-component="section-nav"] { + display: none; + align-items: center; + justify-content: center; + min-width: 0; +} + +[data-page="stats"] [data-component="section-nav"] ul { + display: flex; + align-items: center; + margin: 0; + padding: 0; + list-style: none; +} + +[data-page="stats"] [data-component="section-nav"] a { + display: flex; + align-items: center; + justify-content: center; + height: 32px; + padding: 0 15px; + color: var(--stats-muted); + font-size: 13px; + line-height: 1; + white-space: nowrap; +} + +[data-page="stats"] [data-component="section-nav"] a:hover { + color: var(--stats-text); +} + +[data-page="stats"] [data-slot="header-actions"] { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; +} + +[data-page="stats"] [data-slot="header-button"], +[data-page="stats"] [data-slot="menu-button"] { + position: relative; + flex-shrink: 0; + display: inline-flex; + align-items: center; + justify-content: center; + height: 32px; + overflow: hidden; + margin: 0; + border: 0; + border-radius: 0; + appearance: none; + font: inherit; + font-size: 13px; + line-height: 1.1; + cursor: pointer; +} + +[data-page="stats"] [data-slot="header-button"]::before, +[data-page="stats"] [data-slot="menu-button"]::before { + position: absolute; + top: 0; + right: 0; + left: 0; + height: 16px; + pointer-events: none; + content: ""; + background: linear-gradient(180deg, #ffffff00 0%, #ffffff12 100%); +} + +[data-page="stats"] [data-slot="header-button"] { + padding: 0 12px; +} + +[data-page="stats"] [data-slot="header-button"] strong, +[data-page="stats"] [data-slot="header-button"] span, +[data-page="stats"] [data-slot="menu-button"] svg { + position: relative; + z-index: 1; +} + +[data-page="stats"] [data-slot="header-button"] strong { + font-weight: 500; + white-space: nowrap; +} + +[data-page="stats"] [data-slot="header-button"][data-variant="neutral"] { + display: none; + gap: 6px; + color: #161616; + background: #ffffff; + box-shadow: + 0 0 0 0 #00000024, + 0 0 0 0.5px #00000024, + 0 1px 1.5px 0 #0000001a; +} + +[data-page="stats"] [data-slot="header-button"][data-variant="neutral"] span { + color: #5c5c5c; + font-weight: 400; + font-variant-numeric: tabular-nums; +} + +[data-page="stats"] [data-slot="header-button"][data-variant="contrast"] { + gap: 8px; + color: #ffffff; + background: #242424; + box-shadow: + 0 0 0 0 #00000000, + 0 0 0 0.5px #3a3a3a, + 0 1px 1.5px 0 #00000033, + inset 0 -1px 2px 0 #0000000f, + inset 0 1px 2px 0 #ffffff24; +} + +[data-page="stats"] [data-slot="menu-button"] { + display: inline-flex; + width: 32px; + padding: 0; + color: #3a3a3a; + background: #ffffff; + box-shadow: + 0 0 0 0 #00000024, + 0 0 0 0.5px #00000024, + 0 1px 1.5px 0 #0000001a; +} + +[data-page="stats"] [data-slot="header-button"]:focus-visible, +[data-page="stats"] [data-slot="menu-button"]:focus-visible, +[data-page="stats"] [data-component="section-nav"] a:focus-visible, +[data-page="stats"] [data-slot="mobile-menu-item"]:focus-visible, +[data-page="stats"] [data-slot="brand"]:focus-visible { + outline: 2px solid var(--stats-accent); + outline-offset: 2px; +} + +[data-page="stats"] [data-slot="mobile-menu"] { + position: fixed; + top: 72px; + right: 0; + bottom: 0; + left: 0; + z-index: 9; + display: none; + overflow: auto; + background: var(--stats-bg); + border-top: 1px solid var(--stats-line); +} + +[data-page="stats"] [data-menu-open="true"] [data-slot="mobile-menu"]:not([hidden]) { + display: block; +} + +[data-page="stats"] [data-slot="mobile-menu-item"] { + display: flex; + align-items: center; + gap: 12px; + min-height: 65px; + padding: 24px; + color: var(--stats-text); + border-bottom: 1px solid var(--stats-line); + font-size: 13px; + line-height: 16px; + white-space: nowrap; +} + +[data-page="stats"] [data-slot="mobile-menu-item"]:hover { + color: var(--stats-text); + background: var(--stats-layer); +} + +[data-page="stats"] [data-slot="mobile-menu-item"] strong { + font-weight: 400; +} + +[data-page="stats"] [data-slot="mobile-menu-item"] span { + min-width: 0; + overflow: hidden; + color: var(--stats-muted); + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; +} + +[data-page="stats"] [data-component="footer"] { + position: relative; + display: grid; + gap: 56px; + box-sizing: border-box; + min-height: 0; + padding: 112px clamp(32px, 4vw, 48px) 24px; + color: var(--stats-text); + font-family: + "IBM Plex Mono", + var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace); + font-size: 11px; +} + +[data-page="stats"] [data-slot="footer-grid"] { + display: grid; + grid-template-columns: 120px repeat(4, minmax(0, 1fr)); + gap: 72px; + align-items: start; +} + +[data-page="stats"] [data-slot="footer-mark"] { + display: block; + width: fit-content; + color: var(--stats-text); +} + +[data-page="stats"] [data-slot="footer-mark"] [data-slot="opencode-mark"] { + display: block; + width: 40px; + height: 40px; +} + +[data-page="stats"] [data-slot="footer-column"] { + display: grid; + align-content: start; + gap: 18px; + min-width: 0; +} + +[data-page="stats"] [data-slot="footer-column"] h2 { + color: var(--stats-text); + font-size: 11px; + font-weight: 500; + line-height: 1; + letter-spacing: 0; +} + +[data-page="stats"] [data-slot="footer-column"] nav { + display: grid; + gap: 12px; +} + +[data-page="stats"] [data-slot="footer-column"] a, +[data-page="stats"] [data-slot="footer-column"] p { + color: var(--stats-text); + font-size: 11px; + font-weight: 400; + line-height: 1.5; + text-decoration: none; +} + +[data-page="stats"] [data-slot="footer-column"] a, +[data-page="stats"] [data-slot="footer-column"] p, +[data-page="stats"] [data-slot="footer-bottom"] { + color: var(--stats-muted); +} + +[data-page="stats"] [data-slot="footer-column"] a:hover { + color: var(--stats-text); + text-decoration: none; +} + +[data-page="stats"] [data-slot="subscribe-button"] { + display: inline-flex; + align-items: center; + justify-content: center; + width: fit-content; + height: 28px; + margin: 0; + padding: 0 12px; + border: 1px solid var(--stats-line); + border-radius: 0; + appearance: none; + background: var(--stats-bg); + color: var(--stats-text) !important; + font: inherit; + font-size: 11px; + font-weight: 500; + line-height: 1; + text-decoration: none; + cursor: pointer; +} + +[data-page="stats"] [data-slot="subscribe-button"]:hover { + border-color: var(--stats-line-strong); + background: var(--stats-layer); +} + +[data-page="stats"] [data-slot="subscribe-button"]:focus-visible, +[data-page="stats"] [data-slot="theme-option"]:focus-visible, +[data-page="stats"] [data-component="subscribe-modal"] button:focus-visible, +[data-page="stats"] [data-component="subscribe-modal"] input:focus-visible { + outline: 2px solid var(--stats-accent); + outline-offset: 2px; +} + +[data-page="stats"] [data-component="subscribe-modal"] { + position: fixed; + inset: 0; + z-index: 80; + display: grid; + place-items: center; + box-sizing: border-box; + padding: 8px; + color: var(--stats-text); + font-family: + "IBM Plex Mono", + var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace); +} + +[data-page="stats"] [data-slot="modal-scrim"] { + position: absolute; + inset: 0; + background: #00000066; + backdrop-filter: blur(2px); +} + +[data-page="stats"] [data-slot="modal-panel"] { + position: relative; + z-index: 1; + width: min(374px, calc(100vw - 16px)); + max-height: calc(100dvh - 16px); + overflow: auto; + background: #fafafa; + box-shadow: + 0 0 0 0.5px #0000001f, + 0 4px 8px #00000014, + 0 8px 16px #0000000a; +} + +[data-page="stats"] [data-slot="modal-brand"] { + position: relative; + display: flex; + align-items: center; + justify-content: center; + height: 122px; + background: #242424; + color: #ffffff; +} + +[data-page="stats"] [data-slot="modal-logo"] { + display: block; + width: 234px; + height: 42px; +} + +[data-page="stats"] [data-slot="modal-close"] { + position: absolute; + top: 0; + right: 0; + display: grid; + place-items: center; + width: 32px; + height: 32px; + margin: 0; + padding: 0; + border: 0; + border-radius: 0; + appearance: none; + background: transparent; + color: #808080; + cursor: pointer; +} + +[data-page="stats"] [data-slot="modal-close"]:hover { + background: #ffffff1a; +} + +[data-page="stats"] [data-slot="modal-body"] { + display: grid; + gap: 24px; + padding: 24px 12px 12px; + background: #fafafa; +} + +[data-page="stats"] [data-slot="modal-intro"] { + display: grid; + gap: 4px; + text-align: center; +} + +[data-page="stats"] [data-slot="modal-intro"] h2 { + color: #161616; + font-size: 16px; + font-weight: 500; + line-height: 24px; + letter-spacing: 0; +} + +[data-page="stats"] [data-slot="modal-intro"] p { + color: #5c5c5c; + font-size: 16px; + font-weight: 400; + line-height: 24px; +} + +[data-page="stats"] [data-slot="subscribe-form"] { + display: grid; + gap: 12px; +} + +[data-page="stats"] [data-slot="subscribe-form"] input, +[data-page="stats"] [data-slot="subscribe-form"] button { + box-sizing: border-box; + width: 100%; + height: 40px; + margin: 0; + border-radius: 0; + appearance: none; + font: inherit; + font-size: 13px; + line-height: 1; +} + +[data-page="stats"] [data-slot="subscribe-form"] input { + padding: 0 12px; + border: 0; + background: #ffffff; + color: #161616; + box-shadow: + 0 0 0 0.5px #00000024, + 0 1px 1.5px #0000001a; +} + +[data-page="stats"] [data-slot="subscribe-form"] input::placeholder { + color: #808080; +} + +[data-page="stats"] [data-slot="subscribe-form"] button { + position: relative; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + border: 0; + background: #242424; + color: #ffffff; + font-weight: 500; + cursor: pointer; + box-shadow: + 0 0 0 0.5px #3a3a3a, + 0 1px 1.5px #00000033, + inset 0 -1px 2px #0000000f, + inset 0 1px 2px #ffffff24; +} + +[data-page="stats"] [data-slot="subscribe-form"] button::before { + position: absolute; + top: 0.25px; + right: 0; + left: 0; + height: 20px; + pointer-events: none; + content: ""; + background: linear-gradient(180deg, #ffffff00 0%, #ffffff12 100%); +} + +[data-page="stats"] [data-slot="subscribe-form"] button span { + position: relative; +} + +[data-page="stats"] [data-slot="subscribe-form"] button:disabled { + cursor: progress; + opacity: 0.7; +} + +[data-page="stats"] [data-slot="subscribe-feedback"]:empty { + display: none; +} + +[data-page="stats"] [data-slot="subscribe-feedback"] p { + text-align: center; + font-size: 11px; + font-weight: 500; + line-height: 16px; +} + +[data-page="stats"] [data-slot="subscribe-feedback"] p[data-state="success"] { + color: #198b43; +} + +[data-page="stats"] [data-slot="subscribe-feedback"] p[data-state="error"] { + color: #b82d35; +} + +[data-page="stats"] [data-slot="footer-pattern"] { + height: 16px; + overflow: hidden; + background: var(--stats-hero-pattern); + mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + mask-position: center top; + mask-repeat: repeat; + mask-size: 6px 6px; + -webkit-mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + -webkit-mask-position: center top; + -webkit-mask-repeat: repeat; + -webkit-mask-size: 6px 6px; +} + +[data-page="stats"] [data-slot="footer-bottom"], +[data-page="stats"] [data-slot="footer-bottom"] > div { + display: flex; + align-items: center; +} + +[data-page="stats"] [data-slot="footer-bottom"] { + justify-content: space-between; + gap: 24px; + font-size: 11px; + line-height: 1; +} + +[data-page="stats"] [data-slot="footer-bottom"] > div:first-child { + gap: 24px; +} + +[data-page="stats"] [data-slot="theme-toggle"] { + display: flex; + align-items: center; + gap: 1px; + padding: 1px; + background: var(--stats-layer-2); +} + +[data-page="stats"] [data-slot="theme-option"] { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 20px; + margin: 0; + padding: 0; + border: 0; + border-radius: 0; + appearance: none; + background: transparent; + color: var(--stats-faint); + font: inherit; + font-size: 11px; + line-height: 1; + cursor: pointer; +} + +[data-page="stats"] [data-slot="theme-icon"] { + display: block; + width: 16px; + height: 16px; + pointer-events: none; +} + +[data-page="stats"] [data-slot="theme-option"]:hover { + color: var(--stats-text); +} + +[data-page="stats"] [data-slot="theme-option"][aria-pressed="true"] { + background: var(--stats-bg); + color: var(--stats-theme-icon-active); + box-shadow: + 0 0 0 0 #0000, + 0 0 0 0.5px #0000001f, + 0 1px 2px -1px #00000014, + 0 2px 4px 0 #0000000a; +} + +[data-page="stats"] [data-slot="status"] { + display: flex; + align-items: center; + gap: 10px; +} + +[data-page="stats"] [data-slot="status"]::before { + content: ""; + width: 6px; + height: 6px; + background: #198b43; +} + +[data-page="stats"] [data-component="content"] a { + color: var(--stats-text); + text-decoration: none; +} + +[data-page="stats"] [data-component="content"] a:hover { + text-decoration: underline; + text-underline-offset: 4px; +} + +[data-page="stats"] [data-section="chart"] { + border-bottom: 1px solid var(--stats-line); + box-shadow: + inset 1px 0 var(--stats-line), + inset -1px 0 var(--stats-line); + padding: var(--stats-section-padding) var(--stats-page-padding); +} + +[data-page="stats"] [data-section="hero"] { + box-sizing: border-box; + display: flex; + flex-direction: column; + align-items: flex-start; + justify-content: flex-end; + gap: 24px; + min-height: 0; + overflow: hidden; + padding: 128px 24px 48px; + border-bottom: 0; + box-shadow: none; +} + +[data-page="stats"] h1, +[data-page="stats"] h2, +[data-page="stats"] p { + margin: 0; +} + +[data-page="stats"] h1 { + font-size: 38px; + line-height: 1; + letter-spacing: normal; + font-weight: 600; + max-width: none; +} + +[data-page="stats"] h2 { + font-size: 24px; + line-height: 1; + letter-spacing: -0.03em; + font-weight: 500; +} + +[data-page="stats"] [data-slot="section-header"] p { + color: var(--stats-muted); + font-size: 16px; + line-height: 1.5; +} + +[data-page="stats"] [data-slot="hero-canvas"] { + display: flex; + flex-direction: column; + gap: 24px; + width: 100%; + min-width: 0; +} + +[data-page="stats"] [data-section="hero"] h1 { + order: 1; + color: var(--stats-text); + font-size: 64px; + font-weight: 500; + line-height: 1; + letter-spacing: 0; +} + +[data-page="stats"] [data-slot="hero-copy"] { + order: 3; + color: var(--stats-hero-muted); + font-size: 16px; + font-weight: 400; + line-height: 1.5; +} + +[data-page="stats"] [data-slot="hero-copy-break"] { + display: none; +} + +[data-page="stats"] [data-slot="hero-pattern"] { + order: 2; + flex: 0 0 auto; + width: 100%; + height: 16px; + overflow: hidden; + background: var(--stats-hero-pattern); + mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + mask-repeat: repeat; + mask-size: 6px 6px; + -webkit-mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + -webkit-mask-repeat: repeat; + -webkit-mask-size: 6px 6px; +} + +[data-page="stats"] [data-slot="hero-meta"] { + display: flex; + align-items: center; + gap: 4px; + width: fit-content; + max-width: 100%; + height: 24px; + padding: 0 8px 0 4px; + background: var(--stats-layer-2); + color: var(--stats-hero-muted); + font-size: 13px; + font-weight: 500; + line-height: 1.1; + overflow: hidden; + white-space: nowrap; +} + +[data-page="stats"] [data-slot="hero-meta"] svg { + width: 16px; + height: 16px; + flex: 0 0 auto; +} + +[data-page="stats"] [data-slot="hero-meta-label"], +[data-page="stats"] [data-slot="hero-meta-empty"] { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +[data-page="stats"] [data-slot="hero-meta-time"] { + display: inline-flex; + align-items: center; + min-width: 0; + overflow: hidden; +} + +[data-page="stats"] [data-slot="hero-meta-separator"] { + flex: 0 0 auto; + margin-right: 0.35em; +} + +[data-page="stats"] [data-slot="hero-meta-ticker"] { + position: relative; + flex: 0 1 auto; + min-width: 0; + height: 1.1em; + overflow: hidden; + line-height: 1.1; +} + +[data-page="stats"] [data-slot="hero-meta-ticker-track"] { + display: flex; + min-width: 0; + flex-direction: column; + transform: translateY(0); + will-change: transform; +} + +[data-page="stats"] [data-slot="hero-meta-ticker"][data-ticking="true"] [data-slot="hero-meta-ticker-track"] { + animation: stats-hero-meta-ticker 680ms cubic-bezier(0.16, 1, 0.3, 1) both; +} + +[data-page="stats"] [data-slot="hero-meta-ticker-item"] { + display: block; + min-width: 0; + overflow: hidden; + line-height: 1.1; + text-overflow: ellipsis; +} + +@keyframes stats-hero-meta-ticker { + 0%, + 18% { + transform: translateY(0); + } + + 82%, + 100% { + transform: translateY(-50%); + } +} + +@media (prefers-reduced-motion: reduce) { + [data-page="stats"] [data-slot="hero-meta-ticker"][data-ticking="true"] [data-slot="hero-meta-ticker-track"] { + animation: none; + transform: translateY(-50%); + } +} + +@media (min-width: 48rem) { + [data-page="stats"] [data-section="hero"] { + gap: 16px; + padding: 128px 32px 32px; + } + + [data-page="stats"] [data-slot="hero-canvas"] { + position: relative; + display: block; + height: 232px; + overflow: hidden; + } + + [data-page="stats"] [data-slot="hero-pattern"] { + position: absolute; + top: 50%; + left: 50%; + width: 1280px; + height: 351px; + transform: translate(-50%, -50%); + } + + [data-page="stats"] [data-section="hero"] h1 { + position: absolute; + top: 0; + left: 0; + z-index: 1; + width: max-content; + max-width: 100%; + padding: 0 12px 12px 0; + background: var(--stats-bg); + white-space: nowrap; + } + + [data-page="stats"] [data-slot="hero-copy"] { + position: absolute; + right: 0; + bottom: 0; + z-index: 1; + width: min(563px, 100%); + padding: 12px 0 0 16px; + background: var(--stats-bg); + text-align: right; + } + + [data-page="stats"] [data-slot="hero-copy-break"] { + display: block; + } +} + +@media (min-width: 75rem) { + [data-page="stats"] [data-section="hero"] { + padding: 128px 40px 24px; + } +} + +@media (min-width: 90rem) { + [data-page="stats"] [data-section="hero"] { + padding-right: 0; + padding-left: 0; + } +} + +[data-page="stats"] [data-section="chart"] { + min-height: 0; +} + +[data-page="stats"] [data-section="top-models"] { + box-sizing: border-box; + margin-top: 1px; + box-shadow: + 0 -1px var(--stats-line), + inset 0 -1px var(--stats-line), + inset 1px 0 var(--stats-line), + inset -1px 0 var(--stats-line); + padding: 80px 40px; + color: var(--stats-text); +} + +[data-page="stats"] [data-slot="top-models-title"] { + max-width: 1200px; + margin-bottom: 40px; + color: var(--stats-muted); + font-size: 28px; + font-weight: 400; + line-height: 1.5; + letter-spacing: 0; +} + +[data-page="stats"] [data-slot="top-models-title"] strong { + color: var(--stats-text); + font-weight: 500; +} + +[data-page="stats"] [data-slot="top-models-title"] span { + color: var(--stats-muted); + font-weight: 400; +} + +[data-page="stats"] [data-slot="top-models-mobile-controls"] { + display: none; +} + +[data-page="stats"] [data-component="top-models-chart"] { + --top-models-bar-gap: 12px; + --top-models-dot-size: 6px; + --top-models-dot-offset: 2px; + position: relative; + display: grid; + grid-template-rows: 34px minmax(0, 1fr); + gap: 12px; + width: 100%; + height: clamp(320px, 44vh, 400px); +} + +[data-page="stats"] [data-slot="top-models-axis"], +[data-page="stats"] [data-slot="top-models-bars"] { + display: flex; + min-width: 0; +} + +[data-page="stats"] [data-slot="top-models-axis"] { + gap: var(--top-models-bar-gap); +} + +[data-page="stats"] [data-slot="top-models-axis"] > div { + flex: 1 1 0; + min-width: 0; + color: var(--stats-faint); + font-size: 11px; + font-weight: 500; + line-height: 1.5; +} + +[data-page="stats"] [data-slot="top-models-axis"] > div[data-active="true"] { + color: var(--stats-text); + font-weight: 500; +} + +[data-page="stats"] [data-slot="axis-label"] { + display: flex; + flex-direction: column; +} + +[data-page="stats"] + [data-slot="top-models-axis"] + > div[data-label-hidden="true"]:not([data-active="true"]) + [data-slot="axis-label"], +[data-page="stats"] + [data-slot="market-labels"] + button[data-label-hidden="true"]:not([data-active="true"]) + [data-slot="market-axis-label"] { + visibility: hidden; +} + +[data-page="stats"] [data-slot="axis-date-mobile"] { + display: none; +} + +[data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] { + --top-models-bar-gap: 8px; + grid-template-rows: 40px minmax(0, 1fr); +} + +[data-page="stats"] [data-component="top-models-chart"][data-range="2M"] { + --top-models-bar-gap: 6px; +} + +[data-page="stats"] [data-component="market-share"][data-dense-labels="true"] { + --market-gap: 8px; + grid-template-rows: 40px minmax(0, 1fr); +} + +[data-page="stats"] [data-component="market-share"][data-range="2M"] { + --market-gap: 6px; +} + +[data-page="stats"] [data-component="market-share"][data-range="2M"] [data-slot="market-labels"], +[data-page="stats"] [data-component="market-share"][data-range="2M"] [data-slot="market-bars"] { + gap: var(--market-gap); +} + +[data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="top-models-axis"] > div { + position: relative; + display: flex; + align-items: center; + justify-content: center; + height: 40px; + font-weight: 600; +} + +[data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-labels"] button { + position: relative; + align-items: center; + justify-content: center; + height: 40px; + line-height: 1.2; +} + +[data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="axis-label"], +[data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-axis-label"] { + position: absolute; + left: 50%; + width: max-content; + max-width: 72px; + transform: rotate(-90deg) translateX(-50%); + transform-origin: left center; +} + +[data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="axis-total"], +[data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="axis-date-full"], +[data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-total"], +[data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-date-full"] { + display: none; +} + +[data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="axis-date-mobile"], +[data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-date-mobile"] { + display: block; +} + +[data-page="stats"] [data-slot="top-models-bars"] { + width: calc(100% + var(--top-models-bar-gap)); + margin-inline: calc(var(--top-models-bar-gap) / -2); + min-height: 0; +} + +[data-page="stats"] [data-slot="top-models-bar"] { + position: relative; + box-sizing: border-box; + flex: 1 1 0; + min-width: 0; + height: 100%; + padding-inline: calc(var(--top-models-bar-gap) / 2); + outline: none; + cursor: pointer; +} + +[data-page="stats"] [data-slot="top-models-bar"]::before { + position: absolute; + top: 0; + bottom: 0; + left: 50%; + width: calc(100% - var(--top-models-bar-gap)); + transform: translateX(-50%); + content: ""; + background: var(--stats-dot); + mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + mask-position: var(--top-models-dot-offset) top; + mask-repeat: repeat; + mask-size: var(--top-models-dot-size) var(--top-models-dot-size); + -webkit-mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + -webkit-mask-position: var(--top-models-dot-offset) top; + -webkit-mask-repeat: repeat; + -webkit-mask-size: var(--top-models-dot-size) var(--top-models-dot-size); +} + +@supports (width: round(down, 100%, 1px)) { + [data-page="stats"] [data-slot="top-models-bar"]::before { + width: round(down, calc(100% - var(--top-models-bar-gap)), var(--top-models-dot-size)); + } +} + +[data-page="stats"] [data-slot="top-models-stack"] { + position: absolute; + right: calc(var(--top-models-bar-gap) / 2); + bottom: 0; + left: calc(var(--top-models-bar-gap) / 2); + z-index: 1; + display: grid; + height: var(--top-models-bar-height); + min-height: 0; + overflow: hidden; + background: var(--stats-bg); + box-shadow: 0 -4px 0 var(--stats-bg); +} + +[data-page="stats"] [data-slot="top-models-stack"] i { + box-sizing: border-box; + display: block; + min-height: 0; + transition: background 120ms ease; +} + +[data-page="stats"] [data-slot="top-models-stack"] i + i { + border-top: 2px solid var(--stats-bg); +} + +[data-page="stats"] [data-slot="mobile-filter-button"] { + display: inline-flex; + flex: 1 1 0; + align-items: center; + justify-content: center; + gap: 6px; + height: 32px; + min-width: 0; + overflow: hidden; + padding: 0 12px; + color: var(--stats-text); + background: var(--stats-bg); + border: 0; + border-radius: 0; + box-shadow: + 0 0 0 0 #00000024, + 0 0 0 0.5px #00000024, + 0 1px 1.5px 0 #0000001a; + font-size: 13px; + font-weight: 600; + line-height: 1.1; +} + +[data-page="stats"] [data-slot="mobile-filter-button"] svg { + flex: 0 0 auto; + color: var(--stats-muted); +} + +[data-page="stats"] [data-component="mobile-filter-sheet"] { + position: fixed; + inset: 0; + z-index: 30; + display: flex; + align-items: flex-end; + padding: 0 8px 8px; + background: #00000066; + backdrop-filter: blur(3px); +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] { + width: 100%; + background: var(--stats-bg); + box-shadow: 0 8px 24px #00000026; +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] button { + position: relative; + display: flex; + align-items: center; + width: 100%; + min-height: 44px; + padding: 0 42px; + color: var(--stats-faint); + background: transparent; + border: 0; + border-radius: 0; + border-bottom: 1px solid var(--stats-line); + font-size: 13px; + font-weight: 600; + line-height: 1.1; + text-align: left; +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] button:last-child { + border-bottom: 0; +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] button[data-active="true"] { + color: var(--stats-text); + background: transparent; +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] button[data-active="true"]::before { + position: absolute; + left: 20px; + width: 6px; + height: 6px; + content: ""; + background: currentColor; +} + +[data-page="stats"] [data-slot="section-header"] { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 32px; + margin-bottom: 32px; +} + +[data-page="stats"] [data-slot="section-header"] > div { + display: grid; + gap: 18px; + max-width: 460px; +} + +[data-page="stats"] [data-component="controls"] { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 10px; +} + +[data-page="stats"] [data-component="pills"], +[data-page="stats"] [data-component="toggle"] { + display: flex; + gap: 4px; + padding: 4px; + background: var(--stats-layer); + border: 1px solid var(--stats-line); + border-radius: 6px; +} + +[data-page="stats"] [data-component="content"] button { + font: inherit; + color: var(--stats-muted); + background: transparent; + border: 0; + border-radius: 4px; + padding: 7px 10px; + cursor: pointer; +} + +[data-page="stats"] [data-component="content"] button[data-active="true"] { + color: #fff; + background: var(--stats-text); +} + +[data-page="stats"] button[data-slot="mobile-filter-button"] { + padding: 0 12px; + color: var(--stats-text); + background: var(--stats-bg); + border-radius: 0; +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] button { + padding: 0 42px; + color: var(--stats-faint); + background: transparent; + border-radius: 0; +} + +[data-page="stats"] [data-slot="filter-sheet-panel"] button[data-active="true"] { + color: var(--stats-text); + background: transparent; +} + +[data-page="stats"] [data-component="usage-chart"] { + position: relative; +} + +[data-page="stats"] [data-component="usage-chart"] { + display: grid; +} + +[data-page="stats"] [data-component="empty-state"] { + display: grid; + place-content: center; + gap: 12px; + min-height: 280px; + padding: 32px; + background: var(--stats-layer); + border: 1px solid var(--stats-line); + color: var(--stats-muted); + text-align: center; +} + +[data-page="stats"] [data-component="empty-state"] strong { + color: var(--stats-text); + font-weight: 600; +} + +[data-page="stats"] [data-component="empty-state"] p { + max-width: 34rem; + color: var(--stats-muted); + font-size: 13px; + line-height: 1.5; +} + +[data-page="stats"] [data-component="usage-chart"] svg { + display: block; + width: 100%; + overflow: visible; +} + +[data-page="stats"] .chart-total, +[data-page="stats"] .chart-date { + font-size: 14px; + fill: var(--stats-faint); +} + +[data-page="stats"] .chart-date { + font-size: 12px; +} + +[data-page="stats"] [data-component="usage-chart"] g[role="button"] { + outline: none; + cursor: pointer; +} + +[data-page="stats"] [data-component="usage-chart"] g[role="button"] rect { + transition: + fill 120ms ease, + opacity 120ms ease; +} + +[data-page="stats"] [data-component="usage-chart"] g[role="button"][data-active="true"] .chart-total, +[data-page="stats"] [data-component="usage-chart"] g[role="button"][data-active="true"] .chart-date { + fill: var(--stats-text); +} + +[data-page="stats"] [data-slot="chart-footer"] { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + margin-top: 32px; +} + +[data-page="stats"] [data-section="top-models"] [data-slot="chart-footer"] { + margin-top: 32px; +} + +[data-page="stats"] [data-component="usage-filter"] { + display: flex; + align-items: center; +} + +[data-page="stats"] [data-component="usage-filter"][data-variant="product"] { + gap: 24px; +} + +[data-page="stats"] [data-component="usage-filter"][data-variant="range"] { + gap: 6px; +} + +[data-page="stats"] [data-component="usage-filter"] button { + color: var(--stats-faint); + background: transparent; + border: 0; + border-radius: 0; + padding: 0; + font-size: 13px; + font-weight: 500; + line-height: 17px; +} + +[data-page="stats"] [data-component="usage-filter"] button:hover { + color: var(--stats-text); +} + +[data-page="stats"] [data-component="usage-filter"] button[data-active="true"] { + color: var(--stats-text); + background: transparent; + font-weight: 500; +} + +[data-page="stats"] [data-component="usage-filter"][data-variant="product"] button[data-active="true"] { + display: flex; + align-items: center; + gap: 6px; +} + +[data-page="stats"] [data-component="usage-filter"][data-variant="product"] button[data-active="true"]::before { + content: ""; + width: 16px; + height: 16px; + background: linear-gradient(var(--stats-text), var(--stats-text)) center / 6px 6px no-repeat; +} + +[data-page="stats"] [data-component="usage-filter"][data-variant="range"] button { + height: 24px; + width: 36px; + padding: 0; +} + +[data-page="stats"] [data-component="usage-filter"][data-variant="range"] button[data-active="true"] { + background: var(--stats-layer-2); +} + +[data-page="stats"] [data-component="chart-tooltip"] { + position: absolute; + right: auto; + top: 96px; + display: grid; + gap: 8px; + min-width: 220px; + padding: 16px; + background: #fffffff2; + border: 1px solid var(--stats-line-strong); + box-shadow: + 0 8px 16px #0000000a, + 0 4px 8px #00000014; + pointer-events: none; + z-index: 2; +} + +[data-page="stats"] [data-component="chart-tooltip"] p { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 18px; + margin: 0 -4px; + padding: 2px 4px; + color: var(--stats-muted); + font-size: 12px; + line-height: 17px; +} + +[data-page="stats"] [data-component="chart-tooltip"] p[data-active="true"] { + background: var(--stats-layer-2); + color: var(--stats-text); +} + +[data-page="stats"] [data-component="chart-tooltip"] [data-slot="tooltip-label"] { + display: grid; + grid-template-columns: 9px minmax(0, 1fr); + gap: 8px; + min-width: 0; + align-items: center; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +[data-page="stats"] [data-component="chart-tooltip"] [data-slot="tooltip-divider"] { + height: 1px; + margin: 4px -16px 2px; + background: var(--stats-line); +} + +[data-page="stats"] [data-component="chart-tooltip"] i { + width: 9px; + height: 9px; +} + +[data-page="stats"] [data-component="chart-tooltip"] b { + color: var(--stats-text); +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] { + top: 110px; + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: 0; + width: 192px; + min-width: 192px; + padding: 0; + background: #fffffff2; + border: 0; + box-shadow: + 0 0 0 0.5px #00000024, + 0 8px 16px #0000000f, + 0 4px 8px #00000014; + color: var(--stats-text); +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"][data-placement="right"] { + right: auto; + left: calc(100% + 8px); +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"][data-placement="left"] { + right: calc(100% + 8px); + left: auto; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] strong, +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] > span { + display: block; + font-size: 11px; + line-height: 12px; + white-space: nowrap; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] strong { + padding: 8px 8px 0; + font-weight: 500; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] > span { + padding: 4px 8px 8px; + color: var(--stats-muted); +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] [data-slot="tooltip-divider"] { + height: 0.5px; + margin: 0; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] p { + grid-template-columns: minmax(0, 1fr) auto; + gap: 4px; + height: 16px; + margin: 4px 0 0; + padding: 0 8px; + font-size: 11px; + font-weight: 500; + line-height: 12px; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] p[data-muted="true"] { + opacity: 0.46; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] [data-slot="tooltip-divider"] + p { + margin-top: 8px; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] p:last-child { + margin-bottom: 8px; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] [data-slot="tooltip-label"] { + grid-template-columns: 16px minmax(0, 1fr); + gap: 4px; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] i { + width: 6px; + height: 6px; + justify-self: center; +} + +[data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] b { + font-weight: 500; +} + +[data-page="stats"] + :is( + [data-section="leaderboard"], + [data-section="market-share"], + [data-section="token-cost"], + [data-section="session-cost"] + ) { + position: relative; + box-sizing: border-box; + box-shadow: + inset 0 -1px var(--stats-line), + inset 1px 0 var(--stats-line), + inset -1px 0 var(--stats-line); + padding: 80px 40px; + color: var(--stats-text); +} + +[data-page="stats"] [data-component="section-bridge"] { + position: absolute; + top: 0; + left: 50%; + z-index: 2; + display: inline-flex; + align-items: center; + gap: 6px; + height: 24px; + padding: 0 10px; + border: 1px solid var(--stats-line); + background: var(--stats-bg); + color: var(--stats-faint); + font-size: 10px; + font-weight: 500; + line-height: 1; + text-decoration: none; + transform: translate(-50%, -50%); + white-space: nowrap; +} + +[data-page="stats"] [data-component="section-bridge"]:hover { + color: var(--stats-text); + text-decoration: none; +} + +[data-page="stats"] [data-component="section-bridge"] i { + width: 1px; + height: 10px; + background: var(--stats-line-strong); +} + +[data-page="stats"] [data-component="section-bridge"] strong, +[data-page="stats"] [data-component="section-bridge"] b { + color: var(--stats-muted); + font-weight: 600; +} + +[data-page="stats"] [data-component="section-bridge"] { + display: none; +} + +[data-page="stats"] [data-slot="section-title"] { + max-width: 1200px; + margin-bottom: 40px; + color: var(--stats-muted); + font-size: 28px; + font-weight: 400; + line-height: 1.5; + letter-spacing: 0; +} + +[data-page="stats"] [data-slot="section-title"] strong { + color: var(--stats-text); + font-weight: 500; +} + +[data-page="stats"] [data-slot="section-title"] span { + color: var(--stats-muted); + font-weight: 400; +} + +[data-page="stats"] [data-component="leaderboard"], +[data-page="stats"] [data-slot="leaderboard-featured"], +[data-page="stats"] [data-slot="leaderboard-compact"], +[data-page="stats"] [data-slot="leaderboard-column"], +[data-page="stats"] [data-slot="leaderboard-mobile"] { + display: grid; +} + +[data-page="stats"] [data-component="leaderboard"] { + gap: 0; + width: 100%; + margin-top: 36px; + scroll-margin-top: 88px; +} + +[data-page="stats"] [data-slot="leaderboard-featured"], +[data-page="stats"] [data-slot="leaderboard-compact"] { + grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); + gap: 8px; +} + +[data-page="stats"] [data-slot="leaderboard-pattern"] { + height: 16px; + margin: 16px 0; + overflow: hidden; + background: var(--stats-hero-pattern); + mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + mask-position: center top; + mask-repeat: repeat; + mask-size: 6px 6px; + -webkit-mask-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 6 6' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 0H2V2H0V0Z' fill='black'/%3E%3C/svg%3E"); + -webkit-mask-position: center top; + -webkit-mask-repeat: repeat; + -webkit-mask-size: 6px 6px; +} + +[data-page="stats"] [data-slot="leaderboard-column"] { + gap: 8px; + align-content: start; +} + +[data-page="stats"] [data-slot="leaderboard-mobile"] { + display: none; +} + +[data-page="stats"] [data-component="leader-card"] { + position: relative; + box-sizing: border-box; + display: flex; + flex-direction: column; + justify-content: space-between; + min-width: 0; + overflow: hidden; + padding: 16px; + border: 1px solid var(--stats-line); + background: linear-gradient(180deg, #ffffff0a 0%, #ffffff00 100%), var(--stats-layer); + font-size: 13px; + line-height: 1.1; + outline: none; + transition: + background 140ms ease, + border-color 140ms ease, + box-shadow 140ms ease, + transform 140ms ease; +} + +[data-page="stats"] [data-slot="rank"], +[data-page="stats"] [data-slot="delta"][data-negative="true"] { + color: var(--stats-faint); +} + +[data-page="stats"] [data-component="leader-card"][data-size="featured"] { + justify-content: flex-start; + gap: 17px; + min-height: 154px; +} + +[data-page="stats"] [data-component="leader-card"][data-size="compact"] { + min-height: 88px; + box-shadow: + 0 0 0 0.5px #0000001f, + 0 1px 2px -1px #00000014, + 0 2px 4px #0000000a; +} + +[data-page="stats"] [data-slot="leader-watermark"] { + position: absolute; + right: -20px; + top: 50%; + display: none; + width: 168px; + height: 168px; + transform: translateY(-50%); + color: var(--stats-line); + opacity: 0.58; + pointer-events: none; + transition: + color 140ms ease, + opacity 140ms ease; +} + +[data-page="stats"] [data-component="leader-card"][data-size="featured"] [data-slot="leader-watermark"] { + display: block; +} + +[data-page="stats"] [data-slot="leader-body"] { + position: relative; + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + z-index: 1; +} + +[data-page="stats"] [data-component="leader-card"][data-size="featured"] [data-slot="leader-body"] { + flex-direction: column; + align-items: flex-start; + gap: 12px; + width: 100%; +} + +[data-page="stats"] [data-slot="leader-avatar"] { + display: grid; + place-items: center; + flex: 0 0 auto; + box-sizing: border-box; + width: 20px; + height: 20px; + padding: 3px; + border: 0.5px solid var(--stats-line-strong); + border-radius: 4px; + background: var(--stats-bg); + color: var(--stats-muted); + font-family: var(--font-mono); + font-size: 10px; + font-weight: 600; +} + +[data-page="stats"] [data-slot="leader-copy"] { + display: grid; + gap: 4px; + flex: 1; + min-width: 0; + width: 100%; +} + +[data-page="stats"] [data-slot="leader-copy"] div { + display: flex; + gap: 8px; + min-width: 0; +} + +[data-page="stats"] [data-component="leader-card"][data-size="featured"] [data-slot="leader-copy"] div { + gap: 4px; +} + +[data-page="stats"] [data-slot="leader-copy"] strong, +[data-page="stats"] [data-slot="leader-copy"] div > span:first-child { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +[data-page="stats"] [data-slot="leader-copy"] strong { + color: var(--stats-text); + font-weight: 600; + line-height: 1.3; +} + +[data-page="stats"] [data-slot="leader-copy"] span { + color: var(--stats-muted); +} + +[data-page="stats"] [data-slot="leader-copy"] [data-slot="delta"] { + color: #198b43; +} + +[data-page="stats"] [data-slot="leader-copy"] [data-slot="delta"][data-negative="true"] { + color: #b82d35; +} + +[data-page="stats"] [data-component="leader-card"][data-active="true"] { + border-color: var(--stats-line-strong); + background: #ffffff; + box-shadow: + 0 0 0 0.5px #00000024, + 0 6px 16px #0000000d, + 0 2px 6px #0000000f; + transform: translateY(-1px); +} + +[data-page="stats"] [data-component="leader-card"][data-active="true"] [data-slot="leader-watermark"] { + color: var(--stats-layer-2); + opacity: 0.86; +} + +[data-page="stats"] [data-component="leader-card"][data-active="true"] [data-slot="leader-avatar"] { + border-color: var(--stats-line-strong); + color: var(--stats-text); +} + +@media (hover: hover) { + [data-page="stats"] [data-component="leader-card"]:hover, + [data-page="stats"] [data-component="leader-card"]:focus-visible { + border-color: var(--stats-line-strong); + background: #ffffff; + box-shadow: + 0 0 0 0.5px #00000024, + 0 6px 16px #0000000d, + 0 2px 6px #0000000f; + transform: translateY(-1px); + } + + [data-page="stats"] [data-component="leader-card"]:hover [data-slot="leader-watermark"], + [data-page="stats"] [data-component="leader-card"]:focus-visible [data-slot="leader-watermark"] { + color: var(--stats-layer-2); + opacity: 0.86; + } + + [data-page="stats"] [data-component="leader-card"]:hover [data-slot="leader-avatar"], + [data-page="stats"] [data-component="leader-card"]:focus-visible [data-slot="leader-avatar"] { + border-color: var(--stats-line-strong); + color: var(--stats-text); + } +} + +[data-page="stats"] [data-component="market-share"] { + --market-gap: 12px; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + gap: 12px; + height: 348px; +} + +[data-page="stats"] [data-slot="market-labels"], +[data-page="stats"] [data-slot="market-bars"] { + display: grid; + grid-template-columns: repeat(var(--market-count), minmax(0, 1fr)); + gap: var(--market-gap); +} + +[data-page="stats"] [data-slot="market-labels"] button, +[data-page="stats"] [data-slot="market-bars"] button { + display: flex; + min-width: 0; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + text-align: left; +} + +[data-page="stats"] [data-slot="market-labels"] button { + flex-direction: column; + align-items: flex-start; + color: var(--stats-faint); + font-size: 10px; + font-weight: 500; + line-height: 14px; +} + +[data-page="stats"] [data-slot="market-labels"] button[data-active="true"] { + color: var(--stats-text); + background: transparent; + font-weight: 600; +} + +[data-page="stats"] [data-slot="market-axis-label"] { + display: grid; +} + +[data-page="stats"] [data-slot="market-date-mobile"] { + display: none; +} + +[data-page="stats"] [data-slot="market-bars"] { + flex: 1; + min-height: 0; +} + +[data-page="stats"] [data-slot="market-bars"] button { + flex-direction: column; + gap: 2px; + height: 100%; + overflow: hidden; +} + +[data-page="stats"] [data-slot="market-bars"] button[data-active="true"] { + background: transparent; +} + +[data-page="stats"] [data-slot="market-bars"] span { + width: 100%; + min-height: 1px; + background: var(--stats-layer-2); + cursor: pointer; + transition: + background-color 140ms ease, + opacity 140ms ease; +} + +[data-page="stats"] [data-component="market-share-list"] { + display: grid; + grid-auto-flow: column; + grid-template-columns: repeat(3, minmax(0, 1fr)); + grid-template-rows: repeat(3, auto); + gap: 8px 10px; + margin: 36px 0 0; + padding: 0; + list-style: none; +} + +[data-page="stats"] [data-component="market-share-list"] li { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + height: 28px; + box-sizing: border-box; + padding: 0 8px; + background: var(--stats-layer); + border: 1px solid var(--stats-line); + font-size: 11px; + line-height: 1; + cursor: pointer; + outline: none; + transition: + border-color 120ms ease, + box-shadow 120ms ease, + background 120ms ease; +} + +[data-page="stats"] [data-component="market-share-list"] li[data-active="true"], +[data-page="stats"] [data-component="market-share-list"] li:focus-visible { + border-color: var(--stats-text); + background: var(--stats-layer); + box-shadow: + 0 0 0 0.5px color-mix(in srgb, var(--stats-text) 70%, transparent), + 0 1px 2px -1px #00000014, + 0 2px 4px #0000000a; +} + +[data-page="stats"] [data-component="market-share-list"] span { + width: 22px; + flex: 0 0 auto; + color: var(--stats-muted); + font-weight: 500; + text-align: center; +} + +[data-page="stats"] [data-component="market-share-list"] i { + width: 6px; + height: 6px; + flex: 0 0 auto; +} + +[data-page="stats"] [data-component="market-share-list"] strong { + flex: 1; + min-width: 0; + overflow: hidden; + color: var(--stats-text); + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +[data-page="stats"] [data-component="market-share-list"] em, +[data-page="stats"] [data-component="market-share-list"] b, +[data-page="stats"] [data-slot="market-footer"] span { + color: var(--stats-faint); + font-style: normal; +} + +[data-page="stats"] [data-component="market-share-list"] b { + color: var(--stats-muted); + font-weight: 500; +} + +[data-page="stats"] [data-slot="market-footer"] { + display: flex; + align-items: center; + justify-content: space-between; + gap: 64px; + margin-top: 40px; +} + +[data-page="stats"] [data-slot="market-footer"] p { + display: flex; + align-items: center; + gap: 8px; + width: 240px; + color: var(--stats-text); + font-size: 11px; + font-weight: 500; + line-height: 1.1; + white-space: nowrap; +} + +[data-page="stats"] [data-component="token-cost"] { + position: relative; + display: grid; + gap: 8px; + width: 100%; + margin-top: 4px; +} + +[data-page="stats"] button[data-component="token-row"] { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + height: 28px; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + color: var(--stats-text); + font-size: 11px; + line-height: 16px; + text-align: left; +} + +[data-page="stats"] button[data-component="token-row"][data-active="true"] { + background: #0000000a; + color: var(--stats-text); +} + +[data-page="stats"] [data-component="token-row"] strong { + flex: 0 0 56px; + color: var(--stats-text); + font-weight: 500; + white-space: nowrap; +} + +[data-page="stats"] button[data-component="token-row"][data-active="true"] strong { + color: var(--stats-accent-text); +} + +[data-page="stats"] [data-component="token-row"] > span { + flex: 0 0 132px; + overflow: hidden; + color: var(--stats-muted); + font-weight: 400; + line-height: 16px; + text-overflow: ellipsis; + white-space: nowrap; +} + +[data-page="stats"] [data-component="token-row"][data-variant="session"] > span { + flex-basis: 150px; +} + +[data-page="stats"] [data-component="metric-bar"] { + position: relative; + display: block; + flex: 1; + min-width: 0; + height: 5px; + background: var(--stats-layer-2); + font-style: normal; +} + +[data-page="stats"] [data-component="metric-bar"] b { + position: absolute; + inset: 0 auto 0 0; + display: block; + width: var(--metric-bar-fill); + height: 5px; + background: var(--stats-text); +} + +[data-page="stats"] [data-component="metric-bar"][data-active="true"] b { + background: var(--stats-accent); +} + +[data-page="stats"] [data-component="metric-bar"] em { + display: none; +} + +[data-page="stats"] [data-component="metric-bar"][data-active="true"] { + background: var(--stats-line-strong); +} + +[data-page="stats"] [data-slot="session-heading"] { + display: flex; + align-items: flex-end; + gap: 12px; + width: 100%; + height: 18px; +} + +[data-page="stats"] [data-slot="session-heading"] strong { + flex: 0 0 56px; +} + +[data-page="stats"] [data-slot="session-heading"] span { + flex: 0 0 150px; +} + +[data-page="stats"] [data-slot="session-heading"] p { + flex: 1; + min-width: 0; + color: var(--stats-faint); + font-size: 9px; + font-weight: 600; + line-height: 1; +} + +[data-page="stats"] [data-component="token-tooltip"] { + position: absolute; + left: 44%; + z-index: 2; + display: grid; + gap: 6px; + width: 150px; + box-sizing: border-box; + padding: 8px; + background: var(--stats-layer); + box-shadow: + 0 0 0 0.5px #0000001f, + 0 4px 8px #00000014, + 0 8px 16px #0000000a; + pointer-events: none; +} + +[data-page="stats"] [data-component="token-tooltip"] p { + display: flex; + justify-content: space-between; + gap: 10px; + font-size: 9px; + font-weight: 600; + line-height: 1.1; +} + +[data-page="stats"] [data-component="token-tooltip"] span { + color: var(--stats-muted); +} + +[data-page="stats"] [data-slot="token-footer"] { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; + margin-top: 40px; +} + +[data-page="stats"] [data-component="live-filter"] { + display: none; + align-items: center; + gap: 6px; + padding: 0; + color: var(--stats-muted); + font-size: 11px; + font-weight: 500; + line-height: 1.1; +} + +[data-page="stats"] [data-component="live-filter"]::before { + content: ""; + width: 6px; + height: 6px; + background: #198b43; +} + +[data-page="stats"] [data-component="session-cost"] { + position: relative; + display: grid; + gap: 8px; + width: 100%; + margin-top: 4px; +} + +[data-page="stats"] [data-component="toggle"] { + width: fit-content; +} + +[data-page="stats"][data-theme="dark"], +:root[data-stats-theme="dark"] [data-page="stats"]:not([data-theme="light"]) { + color-scheme: dark; + --color-background: #161616; + --color-background-weak: #242424; + --color-background-weak-hover: #303030; + --color-background-strong: #ffffff; + --color-background-strong-hover: #eeeeee; + --color-text: #d4d4d4; + --color-text-weak: #808080; + --color-text-strong: #ffffff; + --color-text-inverted: #161616; + --color-border-weak: #ffffff1a; + --stats-bg: #161616; + --stats-layer: #242424; + --stats-layer-2: #303030; + --stats-line: #ffffff1a; + --stats-line-strong: #ffffff33; + --stats-text: #ffffff; + --stats-muted: #d4d4d4; + --stats-faint: #808080; + --stats-theme-icon-active: #fafafa; + --stats-bar-idle: #303030; + --stats-dot: #303030; + --stats-hero-muted: #808080; + --stats-hero-pattern: #303030; + --stats-logo-bg: #f1ecec; + --stats-logo-fill: #b7b1b1; + --stats-logo-stroke: #211e1e; +} + +[data-page="stats"][data-theme="dark"] [data-component="chart-tooltip"], +:root[data-stats-theme="dark"] [data-page="stats"]:not([data-theme="light"]) [data-component="chart-tooltip"] { + background: #242424f2; +} + +[data-page="stats"][data-theme="dark"] [data-section="top-models"] [data-component="chart-tooltip"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-section="top-models"] + [data-component="chart-tooltip"] { + background: #242424f2; + box-shadow: + 0 0 0 0.5px #ffffff24, + 0 8px 16px #0000003d, + 0 4px 8px #00000052; +} + +[data-page="stats"][data-theme="dark"] [data-section="top-models"] [data-component="chart-tooltip"] > span, +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-section="top-models"] + [data-component="chart-tooltip"] + > span { + color: var(--stats-faint); +} + +[data-page="stats"][data-theme="dark"] [data-component="leader-card"][data-size="compact"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"][data-size="compact"] { + box-shadow: + 0 0 0 0.5px #ffffff1f, + 0 1px 2px -1px #00000052, + 0 2px 4px #0000003d; +} + +[data-page="stats"][data-theme="dark"] [data-component="leader-card"][data-active="true"], +[data-page="stats"][data-theme="dark"] [data-component="leader-card"]:hover, +[data-page="stats"][data-theme="dark"] [data-component="leader-card"]:focus-visible, +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"][data-active="true"], +:root[data-stats-theme="dark"] [data-page="stats"]:not([data-theme="light"]) [data-component="leader-card"]:hover, +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:focus-visible { + background: #303030; + box-shadow: + 0 0 0 0.5px #ffffff24, + 0 6px 16px #0000003d, + 0 2px 6px #00000052; +} + +[data-page="stats"][data-theme="dark"] + [data-component="leader-card"][data-active="true"] + [data-slot="leader-watermark"], +[data-page="stats"][data-theme="dark"] [data-component="leader-card"]:hover [data-slot="leader-watermark"], +[data-page="stats"][data-theme="dark"] [data-component="leader-card"]:focus-visible [data-slot="leader-watermark"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"][data-active="true"] + [data-slot="leader-watermark"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:hover + [data-slot="leader-watermark"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:focus-visible + [data-slot="leader-watermark"] { + color: var(--stats-line-strong); + opacity: 0.78; +} + +[data-page="stats"][data-theme="dark"] [data-slot="header-button"][data-variant="neutral"], +[data-page="stats"][data-theme="dark"] [data-slot="menu-button"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-slot="header-button"][data-variant="neutral"], +:root[data-stats-theme="dark"] [data-page="stats"]:not([data-theme="light"]) [data-slot="menu-button"] { + color: #fafafa; + background: #ffffff0f; + box-shadow: + 0 -0.5px 0 0 #ffffff33, + 0 0 0 0.5px #ffffff33, + 0 1px 2px 0 #00000066; +} + +[data-page="stats"][data-theme="dark"] [data-slot="header-button"][data-variant="neutral"] span, +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-slot="header-button"][data-variant="neutral"] + span { + color: #aeaeae; +} + +[data-page="stats"][data-theme="dark"] [data-slot="header-button"][data-variant="contrast"], +:root[data-stats-theme="dark"] + [data-page="stats"]:not([data-theme="light"]) + [data-slot="header-button"][data-variant="contrast"] { + color: #ffffff; + background: #5c5c5c; + box-shadow: + 0 -0.5px 0 0 #ffffff4d, + 0 0 0 0.5px #ffffff66, + 0 1px 2px 0 #00000066; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-stats-theme="light"]) [data-page="stats"]:not([data-theme="light"]) { + color-scheme: dark; + --color-background: #161616; + --color-background-weak: #242424; + --color-background-weak-hover: #303030; + --color-background-strong: #ffffff; + --color-background-strong-hover: #eeeeee; + --color-text: #d4d4d4; + --color-text-weak: #808080; + --color-text-strong: #ffffff; + --color-text-inverted: #161616; + --color-border-weak: #ffffff1a; + --stats-bg: #161616; + --stats-layer: #242424; + --stats-layer-2: #303030; + --stats-line: #ffffff1a; + --stats-line-strong: #ffffff33; + --stats-text: #ffffff; + --stats-muted: #d4d4d4; + --stats-faint: #808080; + --stats-theme-icon-active: #fafafa; + --stats-bar-idle: #303030; + --stats-dot: #303030; + --stats-hero-muted: #808080; + --stats-hero-pattern: #303030; + --stats-logo-bg: #f1ecec; + --stats-logo-fill: #b7b1b1; + --stats-logo-stroke: #211e1e; + } + + :root:not([data-stats-theme="light"]) [data-page="stats"]:not([data-theme="light"]) [data-component="chart-tooltip"] { + background: #242424f2; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-section="top-models"] + [data-component="chart-tooltip"] { + background: #242424f2; + box-shadow: + 0 0 0 0.5px #ffffff24, + 0 8px 16px #0000003d, + 0 4px 8px #00000052; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-section="top-models"] + [data-component="chart-tooltip"] + > span { + color: var(--stats-faint); + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"][data-size="compact"] { + box-shadow: + 0 0 0 0.5px #ffffff1f, + 0 1px 2px -1px #00000052, + 0 2px 4px #0000003d; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"][data-active="true"], + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:hover, + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:focus-visible { + background: #303030; + box-shadow: + 0 0 0 0.5px #ffffff24, + 0 6px 16px #0000003d, + 0 2px 6px #00000052; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"][data-active="true"] + [data-slot="leader-watermark"], + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:hover + [data-slot="leader-watermark"], + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-component="leader-card"]:focus-visible + [data-slot="leader-watermark"] { + color: var(--stats-line-strong); + opacity: 0.78; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-slot="header-button"][data-variant="neutral"], + :root:not([data-stats-theme="light"]) [data-page="stats"]:not([data-theme="light"]) [data-slot="menu-button"] { + color: #fafafa; + background: #ffffff0f; + box-shadow: + 0 -0.5px 0 0 #ffffff33, + 0 0 0 0.5px #ffffff33, + 0 1px 2px 0 #00000066; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-slot="header-button"][data-variant="neutral"] + span { + color: #aeaeae; + } + + :root:not([data-stats-theme="light"]) + [data-page="stats"]:not([data-theme="light"]) + [data-slot="header-button"][data-variant="contrast"] { + color: #ffffff; + background: #5c5c5c; + box-shadow: + 0 -0.5px 0 0 #ffffff4d, + 0 0 0 0.5px #ffffff66, + 0 1px 2px 0 #00000066; + } +} + +@media (min-width: 48rem) { + [data-page="stats"] [data-slot="header-button"][data-variant="neutral"] { + display: inline-flex; + } +} + +@media (min-width: 75rem) { + [data-page="stats"] [data-slot="header-bar"] { + gap: 32px; + } + + [data-page="stats"] [data-slot="brand"], + [data-page="stats"] [data-component="section-nav"], + [data-page="stats"] [data-slot="header-actions"] { + flex: 1 1 0; + } + + [data-page="stats"] [data-slot="brand"] { + margin-right: 0; + } + + [data-page="stats"] [data-component="section-nav"] { + display: flex; + } + + [data-page="stats"] [data-slot="menu-button"] { + display: none; + } + + [data-page="stats"] [data-slot="mobile-menu"] { + display: none !important; + } +} + +@media (min-width: 90rem) { + [data-page="stats"] [data-component="footer"] { + padding-right: 0; + padding-left: 0; + } +} + +@media (max-width: 74rem) { + [data-page="stats"] [data-section="top-models"], + [data-page="stats"] [data-section="leaderboard"], + [data-page="stats"] [data-section="market-share"], + [data-page="stats"] [data-section="token-cost"], + [data-page="stats"] [data-section="session-cost"] { + padding: 64px 32px; + } +} + +@media (max-width: 58rem) { + [data-page="stats"] { + --stats-page-padding: 24px; + --stats-section-padding: 4rem; + } + + [data-page="stats"] [data-section="chart"] { + padding-left: 24px; + padding-right: 24px; + } + + [data-page="stats"] [data-slot="section-header"] { + flex-direction: column; + } + + [data-page="stats"] [data-component="controls"] { + align-items: flex-start; + } + + [data-page="stats"] [data-component="pills"] { + flex-wrap: wrap; + } + + [data-page="stats"] [data-slot="chart-footer"] { + align-items: flex-start; + flex-direction: column; + } + + [data-page="stats"] [data-component="usage-filter"] { + flex-wrap: wrap; + } + + [data-page="stats"] [data-section="top-models"] [data-slot="chart-footer"] { + align-items: center; + flex-direction: row; + } + + [data-page="stats"] [data-section="top-models"] [data-component="usage-filter"] { + flex-wrap: nowrap; + } + + [data-page="stats"] [data-slot="leaderboard-featured"], + [data-page="stats"] [data-slot="leaderboard-compact"] { + grid-template-columns: 1fr; + } + + [data-page="stats"] [data-component="leader-card"][data-size="featured"], + [data-page="stats"] [data-component="leader-card"][data-size="compact"] { + min-height: 96px; + } + + [data-page="stats"] [data-component="leader-card"][data-size="featured"] [data-slot="leader-body"] { + flex-direction: row; + align-items: center; + gap: 12px; + } + + [data-page="stats"] [data-slot="leader-watermark"] { + right: -64px; + width: 180px; + height: 180px; + font-size: 96px; + } + + [data-page="stats"] [data-slot="session-heading"] { + display: none; + } + + [data-page="stats"] [data-slot="market-labels"], + [data-page="stats"] [data-slot="market-bars"] { + gap: 8px; + } + + [data-page="stats"] [data-component="market-share-list"] { + grid-auto-flow: row; + grid-template-columns: 1fr; + grid-template-rows: none; + } + + [data-page="stats"] [data-component="token-tooltip"] { + position: static; + order: -1; + width: 100%; + margin-bottom: 8px; + } + + [data-page="stats"] [data-slot="market-footer"] { + align-items: flex-start; + flex-direction: column; + gap: 24px; + } + + [data-page="stats"] [data-component="chart-tooltip"] { + position: static; + margin-top: 16px; + } + + [data-page="stats"] [data-component="footer"] { + padding: 88px 24px 24px; + } + + [data-page="stats"] [data-slot="footer-grid"] { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 40px 32px; + } + + [data-page="stats"] [data-slot="footer-mark"] { + grid-column: 1 / -1; + } + + [data-page="stats"] [data-slot="footer-bottom"], + [data-page="stats"] [data-slot="footer-bottom"] > div:first-child { + align-items: flex-start; + flex-direction: column; + } + + [data-page="stats"] [data-slot="footer-bottom"] { + line-height: 1.5; + } +} + +@media (max-width: 47.999rem) { + [data-page="stats"] [data-section="top-models"], + [data-page="stats"] [data-section="leaderboard"], + [data-page="stats"] [data-section="market-share"], + [data-page="stats"] [data-section="token-cost"], + [data-page="stats"] [data-section="session-cost"] { + padding: 48px 24px; + } + + [data-page="stats"] [data-slot="top-models-title"], + [data-page="stats"] [data-slot="section-title"] { + margin-bottom: 32px; + font-size: 16px; + } + + [data-page="stats"] [data-slot="top-models-mobile-controls"] { + display: flex; + gap: 8px; + width: 100%; + } + + [data-page="stats"] [data-section="top-models"] [data-slot="chart-footer"] { + display: flex; + margin-top: 24px; + } + + [data-page="stats"] [data-section="top-models"] [data-slot="chart-footer"] [data-component="usage-filter"] { + display: none; + } + + [data-page="stats"] [data-slot="leaderboard-featured"], + [data-page="stats"] [data-slot="leaderboard-pattern"], + [data-page="stats"] [data-slot="leaderboard-compact"] { + display: none; + } + + [data-page="stats"] [data-slot="leaderboard-mobile"] { + box-sizing: border-box; + display: flex; + gap: 12px; + width: calc(100% + 48px); + margin-inline: -24px; + padding-inline: 24px; + overflow-x: auto; + overscroll-behavior-x: contain; + scroll-padding-inline: 24px; + scroll-snap-type: x proximity; + scrollbar-width: none; + } + + [data-page="stats"] [data-slot="leaderboard-mobile"]::-webkit-scrollbar { + display: none; + } + + [data-page="stats"] [data-slot="leaderboard-mobile"] [data-component="leader-card"] { + flex: 0 0 240px; + width: 240px; + min-height: 156px; + gap: 32px; + scroll-snap-align: start; + } + + [data-page="stats"] [data-slot="leaderboard-mobile"] [data-slot="leader-body"] { + flex-direction: column; + align-items: flex-start; + gap: 16px; + } + + [data-page="stats"] [data-slot="leaderboard-mobile"] [data-slot="leader-avatar"] { + width: 28px; + height: 28px; + padding: 4px; + border-radius: 6px; + } + + [data-page="stats"] [data-slot="leaderboard-mobile"] [data-slot="leader-watermark"] { + right: -68px; + width: 240px; + height: 240px; + } + + [data-page="stats"] [data-component="top-models-chart"] { + grid-template-rows: 40px minmax(0, 1fr); + height: 360px; + } + + [data-page="stats"] [data-component="market-share"] { + grid-template-rows: 40px minmax(0, 1fr); + height: 400px; + } + + [data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"], + [data-page="stats"] [data-component="market-share"][data-dense-labels="true"] { + overflow-x: auto; + overflow-y: visible; + overscroll-behavior-x: contain; + scrollbar-width: none; + } + + [data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"]::-webkit-scrollbar, + [data-page="stats"] [data-component="market-share"][data-dense-labels="true"]::-webkit-scrollbar { + display: none; + } + + [data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] { + --top-models-mobile-bar-width: 12px; + } + + [data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="top-models-axis"], + [data-page="stats"] [data-component="top-models-chart"][data-dense-labels="true"] [data-slot="top-models-bars"] { + min-width: calc(var(--top-models-count) * (var(--top-models-mobile-bar-width) + var(--top-models-bar-gap))); + } + + [data-page="stats"] [data-component="market-share"][data-dense-labels="true"] { + --market-mobile-bar-width: 12px; + } + + [data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-labels"], + [data-page="stats"] [data-component="market-share"][data-dense-labels="true"] [data-slot="market-bars"] { + min-width: calc(var(--market-count) * (var(--market-mobile-bar-width) + var(--market-gap))); + } + + [data-page="stats"] [data-slot="top-models-axis"] > div { + position: relative; + display: flex; + align-items: center; + justify-content: center; + height: 40px; + font-weight: 600; + } + + [data-page="stats"] [data-slot="market-labels"] button { + position: relative; + align-items: center; + justify-content: center; + height: 40px; + line-height: 1.2; + } + + [data-page="stats"] [data-slot="axis-label"] { + position: absolute; + left: 50%; + width: max-content; + max-width: 72px; + transform: rotate(-90deg) translateX(-50%); + transform-origin: left center; + } + + [data-page="stats"] [data-slot="market-axis-label"] { + position: absolute; + left: 50%; + width: max-content; + max-width: 72px; + transform: rotate(-90deg) translateX(-50%); + transform-origin: left center; + } + + [data-page="stats"] [data-slot="top-models-axis"] > div[data-mobile-hidden="true"] [data-slot="axis-label"], + [data-page="stats"] [data-slot="axis-total"], + [data-page="stats"] [data-slot="axis-date-full"] { + display: none; + } + + [data-page="stats"] [data-slot="market-labels"] button[data-mobile-hidden="true"] [data-slot="market-axis-label"], + [data-page="stats"] [data-slot="market-total"], + [data-page="stats"] [data-slot="market-date-full"] { + display: none; + } + + [data-page="stats"] [data-slot="axis-date-mobile"] { + display: block; + } + + [data-page="stats"] [data-slot="market-date-mobile"] { + display: block; + } + + [data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"] { + position: fixed; + top: auto; + right: 12px; + bottom: 12px; + left: 12px; + z-index: 40; + width: auto; + min-width: 0; + max-height: min(320px, 48vh); + overflow: auto; + transform: none; + } + + [data-page="stats"] [data-section="top-models"] [data-component="chart-tooltip"][data-placement] { + right: 12px; + left: 12px; + } +} + +@media (max-width: 40rem) { + [data-page="stats"] [data-slot="footer-grid"] { + grid-template-columns: 1fr; + } +} diff --git a/packages/stats/app/src/routes/index.tsx b/packages/stats/app/src/routes/index.tsx new file mode 100644 index 000000000000..4c76d8ccb2d8 --- /dev/null +++ b/packages/stats/app/src/routes/index.tsx @@ -0,0 +1,1869 @@ +import "./index.css" +import { Link, Meta, Title } from "@solidjs/meta" +import { ProviderIcon } from "@opencode-ai/ui/provider-icon" +import ibmPlexMonoRegularLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Regular-Latin1.woff2?url" +import ibmPlexMonoMediumLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Medium-Latin1.woff2?url" +import ibmPlexMonoSemiBoldLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-SemiBold-Latin1.woff2?url" +import ibmPlexMonoBoldLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Bold-Latin1.woff2?url" +import opencodeWordmarkDark from "../asset/logo-ornate-dark.svg" +import statsUnfurlRankings from "../asset/unfurl-rankings.png?url" +import { + getStatsHomeData, + type LeaderboardEntry, + type MarketDay, + type StatsHomeData, + type SessionCostEntry, + type TokenCostEntry, + type UsagePoint, +} from "@opencode-ai/stats-core/domain/home" +import { runtime } from "@opencode-ai/stats-core/runtime" +import { createAsync, query } from "@solidjs/router" +import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show, type JSX } from "solid-js" +import { getRequestEvent } from "solid-js/web" + +const products = ["All Users", "Zen", "Go"] as const +const tokenProducts = ["Zen", "Go"] as const +const ranges = ["1D", "1W", "2W", "1M", "2M"] as const +const rangeLabels: Record = { + "1D": "1 Day", + "1W": "1 Week", + "2W": "2 Weeks", + "1M": "1 Month", + "2M": "2 Months", +} +const statsHomeTitle = "OpenCode Stats" +const statsHomeDescription = "OpenCode usage, market share, token cost, and session cost stats." +const statsHomeFallbackUrl = "https://stats.opencode.ai" +const statsUnfurlAlt = "OpenCode Stats wordmark on a dark patterned background" +const headerLinks = [ + { href: "#top-models", label: "Top Models" }, + { href: "#leaderboard", label: "Leaderboard" }, + { href: "#token-cost", label: "Token Cost" }, + { href: "#session-cost", label: "Session Cost" }, + { href: "#market-share", label: "Market Share" }, +] as const +const githubLink = { + href: "https://github.com/anomalyco/opencode", + apiHref: "https://api.github.com/repos/anomalyco/opencode", + label: "GitHub", + fallbackStars: "150K", + ariaLabel: "Star OpenCode on GitHub", +} +const compactNumberFormatter = new Intl.NumberFormat("en", { + notation: "compact", + maximumFractionDigits: 1, +}) +const usageColors = [ + "#ed6aff", + "#a684ff", + "#7c86ff", + "#51a2ff", + "#00d3f2", + "#00d5be", + "#00bc7d", + "#9ae600", + "#ffb900", + "#ff8904", + "#ff6467", +] +const marketColors = ["#ed6aff", "#a684ff", "#7c86ff", "#51a2ff", "#00d3f2", "#00d5be", "#00bc7d", "#9ae600", "#ffb900"] +const themePreferences = ["dark", "light", "system"] as const +const themePreferenceLabels = { + dark: "Dark", + light: "Light", + system: "System", +} as const +const themeStorageKey = "opencode:stats-theme" + +type UsageProduct = (typeof products)[number] +type TokenProduct = (typeof tokenProducts)[number] +type UsageRange = (typeof ranges)[number] +type ThemePreference = (typeof themePreferences)[number] + +const getData = query(async () => { + "use server" + return runtime.runPromise(getStatsHomeData()) +}, "getStatsHomeData") + +const getGitHubStars = query(async () => { + "use server" + return fetch(githubLink.apiHref, { + headers: { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + }) + .then((response) => (response.ok ? response.json() : undefined)) + .then((body: unknown) => + body && typeof body === "object" && "stargazers_count" in body && typeof body.stargazers_count === "number" + ? compactNumberFormatter.format(body.stargazers_count) + : githubLink.fallbackStars, + ) + .catch(() => githubLink.fallbackStars) +}, "getGitHubStars") + +export default function StatsHome() { + const event = getRequestEvent() + event?.response.headers.set("Cache-Control", "public, max-age=60, s-maxage=300, stale-while-revalidate=86400") + const statsHomeUrl = new URL( + import.meta.env.BASE_URL, + event?.request.url ?? (typeof window === "undefined" ? statsHomeFallbackUrl : window.location.href), + ).toString() + const statsUnfurlUrl = new URL(statsUnfurlRankings, statsHomeUrl).toString() + const data = createAsync(() => getData()) + const githubStars = createAsync(() => getGitHubStars()) + const [themePreference, setThemePreference] = createSignal("system") + const updateThemePreference = (preference: ThemePreference) => { + applyThemePreference(preference) + setThemePreference(preference) + if (typeof window === "undefined") return + window.localStorage.setItem(themeStorageKey, preference) + } + + onMount(() => { + if (typeof window === "undefined") return + const preference = window.localStorage.getItem(themeStorageKey) + const nextPreference = isThemePreference(preference) ? preference : "system" + applyThemePreference(nextPreference) + setThemePreference(nextPreference) + }) + + return ( +
+ {statsHomeTitle} + + + + + + + + + + + + + + + + + + + + + +
+
+
+ }> + {(stats) => ( + <> + + + + + + + )} + +
+
+
+
+ ) +} + +function isThemePreference(value: string | null): value is ThemePreference { + return value === "dark" || value === "light" || value === "system" +} + +function applyThemePreference(preference: ThemePreference) { + if (typeof document === "undefined") return + document.documentElement.dataset.statsTheme = preference + if (preference === "system") { + document.documentElement.style.removeProperty("color-scheme") + return + } + document.documentElement.style.setProperty("color-scheme", preference) +} + +function Hero(props: { updatedAt: string | null }) { + const [timeZone, setTimeZone] = createSignal("UTC") + const [previousTimeZone, setPreviousTimeZone] = createSignal("UTC") + const [isTicking, setIsTicking] = createSignal(false) + const updatedAtParts = (timeZone: string) => + props.updatedAt ? formatUpdatedAtParts(props.updatedAt, timeZone) : { date: "No rows yet", time: "" } + const previousUpdatedAt = createMemo(() => updatedAtParts(previousTimeZone())) + const currentUpdatedAt = createMemo(() => updatedAtParts(timeZone())) + const currentUpdatedLabel = createMemo(() => + props.updatedAt ? `Updated ${formatUpdatedAtLabel(currentUpdatedAt())}` : "No rows yet", + ) + const isDateTicking = createMemo(() => isTicking() && previousUpdatedAt().date !== currentUpdatedAt().date) + const isTimeTicking = createMemo(() => isTicking() && previousUpdatedAt().time !== currentUpdatedAt().time) + + onMount(() => { + if (!props.updatedAt) return + const nextTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC" + if (nextTimeZone === "UTC") return + if ( + formatUpdatedAtLabel(formatUpdatedAtParts(props.updatedAt, nextTimeZone)) === + formatUpdatedAtLabel(updatedAtParts("UTC")) + ) + return + const timeouts: number[] = [] + timeouts.push( + window.setTimeout(() => { + setPreviousTimeZone(timeZone()) + setTimeZone(nextTimeZone) + setIsTicking(true) + timeouts.push( + window.setTimeout(() => { + setPreviousTimeZone(nextTimeZone) + setIsTicking(false) + }, 720), + ) + }, 480), + ) + onCleanup(() => timeouts.forEach((timeout) => window.clearTimeout(timeout))) + }) + + return ( +
+

+ + {props.updatedAt ? ( + <> + + + + ) : ( + No rows yet + )} +

+
+ +
+ ) +} + +function HeroMetaTickerPart(props: { previous: string; current: string; ticking: boolean }) { + return ( + + + {props.previous} + {props.current} + + + ) +} + +function StatsLoading() { + return ( + <> + + + + + + ) +} + +function ChartSection(props: { + id?: string + title: string + description?: string + controls?: JSX.Element + children: JSX.Element +}) { + return ( +
+
+
+

{props.title}

+ {props.description &&

{props.description}

} +
+ {props.controls} +
+ {props.children} +
+ ) +} + +function SectionTitle(props: { title: string; description: string }) { + return ( +

+ {props.title}. {props.description} +

+ ) +} + +function SectionBridge(props: { label: string; href: string }) { + return ( +
+ LEAN MORE + + {props.label} + + + ) +} + +function EmptyState(props: { title: string; description: string }) { + return ( +
+ {props.title} +

{props.description}

+
+ ) +} + +function formatUpdatedAtParts(value: string, timeZone: string) { + const date = new Date(value) + if (Number.isNaN(date.getTime())) return { date: "just now", time: "" } + return { + date: new Intl.DateTimeFormat("en", { + month: "short", + day: "numeric", + timeZone, + }).format(date), + time: new Intl.DateTimeFormat("en", { + hour: "numeric", + minute: "2-digit", + timeZone, + timeZoneName: "short", + }).format(date), + } +} + +function formatUpdatedAtLabel(value: { date: string; time: string }) { + if (!value.time) return value.date + return `${value.date}, ${value.time}` +} + +function TopModelsSection(props: { data: StatsHomeData["usage"]; leaderboard: StatsHomeData["leaderboard"] }) { + const [product, setProduct] = createSignal("Go") + const [range, setRange] = createSignal("2M") + const [sheet, setSheet] = createSignal<"product" | "range">() + const [activeModel, setActiveModel] = createSignal() + const data = createMemo(() => props.data[product()][range()]) + const leaderboard = createMemo(() => props.leaderboard[product()][range()]) + + createEffect(() => { + if (!sheet()) return + if (typeof document === "undefined") return + const htmlOverflow = document.documentElement.style.overflow + const bodyOverflow = document.body.style.overflow + document.documentElement.style.overflow = "hidden" + document.body.style.overflow = "hidden" + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") setSheet(undefined) + } + document.addEventListener("keydown", onKeyDown) + onCleanup(() => { + document.documentElement.style.overflow = htmlOverflow + document.body.style.overflow = bodyOverflow + document.removeEventListener("keydown", onKeyDown) + }) + }) + + return ( +
+

+ Top models. Usage of models across OpenCode. +

+ usageTotal(item) > 0)} + fallback={} + > + + + 0} + fallback={ + + } + > + + + + + {(kind) => ( + { + setProduct(value) + setSheet(undefined) + }} + onRangeSelect={(value) => { + setRange(value) + setSheet(undefined) + }} + onClose={() => setSheet(undefined)} + /> + )} + +
+ ) +} + +function MobileFilterButton(props: { label: string; value: string; expanded: boolean; onClick: () => void }) { + return ( + + ) +} + +function MobileFilterSheet(props: { + kind: "product" | "range" + product: UsageProduct + range: UsageRange + onProductSelect: (product: UsageProduct) => void + onRangeSelect: (range: UsageRange) => void + onClose: () => void +}) { + return ( +
+
+ + {(item) => ( + + )} + + } + > + + {(item) => ( + + )} + + +
+
+ ) +} + +function ChevronDown() { + return ( + + ) +} + +function StatsFilters(props: { + product: UsageProduct + range: UsageRange + onProductSelect: (product: UsageProduct) => void + onRangeSelect: (range: UsageRange) => void +}) { + return ( + <> + + + + ) +} + +function FilterPills(props: { + items: readonly T[] + selected: T + label: string + variant: "product" | "range" + onSelect: (item: T) => void +}) { + return ( +
+ + {(item) => ( + + )} + +
+ ) +} + +function TopModelsChart(props: { + data: UsagePoint[] + range: UsageRange + activeModel: string | undefined + onActiveModelChange: (model: string | undefined) => void +}) { + let chartRef: HTMLDivElement | undefined + const [activeIndex, setActiveIndex] = createSignal() + const maxTotal = createMemo(() => getTopModelsMaxTotal(props.data)) + const segmentOrder = createMemo(() => getTopModelsSegmentOrder(props.data)) + const activePoint = createMemo(() => props.data[activeIndex() ?? -1]) + + createEffect(() => scrollDenseChartToEnd(chartRef, props.range, props.data.length)) + + return ( +
+ +
+ + {(day, dayIndex) => ( +
{ + if (event.pointerType !== "touch") return + setActiveIndex(dayIndex()) + props.onActiveModelChange(undefined) + }} + onPointerEnter={() => { + setActiveIndex(dayIndex()) + props.onActiveModelChange(undefined) + }} + onPointerLeave={(event) => { + if (event.pointerType === "touch") return + setActiveIndex(undefined) + props.onActiveModelChange(undefined) + }} + onClick={() => { + setActiveIndex(dayIndex()) + props.onActiveModelChange(undefined) + }} + onFocus={() => { + setActiveIndex(dayIndex()) + props.onActiveModelChange(undefined) + }} + onBlur={() => { + setActiveIndex(undefined) + props.onActiveModelChange(undefined) + }} + onKeyDown={(event) => { + if (event.key !== "Enter" && event.key !== " ") return + event.preventDefault() + setActiveIndex(dayIndex()) + props.onActiveModelChange(undefined) + }} + > +
+ + {(item) => ( + { + event.stopPropagation() + setActiveIndex(dayIndex()) + props.onActiveModelChange(item.segment.model) + }} + onPointerDown={(event) => { + event.stopPropagation() + setActiveIndex(dayIndex()) + props.onActiveModelChange(item.segment.model) + }} + onClick={(event) => { + event.stopPropagation() + setActiveIndex(dayIndex()) + props.onActiveModelChange(item.segment.model) + }} + /> + )} + +
+ + {(point) => ( +
props.data.length * 0.62 ? "left" : "right"} + > + {point().date} + {formatTokens(usageTotal(point()))} total +
+ + {(item) => ( +

+ + {" "} + {item.segment.model} + + {formatTokens(item.segment.value)} +

+ )} +
+
+ )} + +
+ )} + +
+
+ ) +} + +function getTopModelsBarHeight(total: number, max: number) { + if (total <= 0) return 0 + return Math.max(2, Math.min(100, (total / max) * 100)) +} + +function getTopModelsMaxTotal(data: UsagePoint[]) { + const max = Math.max(0, ...data.map((item) => usageTotal(item))) + if (max === 0) return 1 + if (data.length === 1) return max * 1.75 + return max +} + +function getTopModelsSegmentRows(point: UsagePoint, order: Map) { + const total = usageTotal(point) + if (total <= 0) return "" + return stackedTopModelsSegments(point, order) + .map((item) => `${(item.segment.value / total) * 100}%`) + .join(" ") +} + +function visibleTopModelsSegments(point: UsagePoint) { + return point.segments.map((segment, index) => ({ segment, index })).filter((item) => item.segment.value > 0) +} + +function stackedTopModelsSegments(point: UsagePoint, order: Map) { + return visibleTopModelsSegments(point) + .slice() + .sort((a, b) => (order.get(b.segment.model) ?? b.index) - (order.get(a.segment.model) ?? a.index)) +} + +function getTopModelsSegmentOrder(data: UsagePoint[]) { + return getRankOrder( + data.flatMap((point) => + point.segments.map((segment, index) => ({ key: segment.model, value: segment.value, index })), + ), + ) +} + +function getTopModelsSegmentColor( + model: string, + index: number, + order: Map, + muted: boolean, + activeModel: string | undefined, +) { + if (activeModel !== undefined) + return activeModel === model ? getRankColor(model, index, order, usageColors) : "var(--stats-layer-2)" + if (muted) return "var(--stats-layer-2)" + return getRankColor(model, index, order, usageColors) +} + +function isTopModelsMobileAxisHidden(index: number, count: number) { + return count > 7 && index % 2 === 1 +} + +function isColumnLabelHidden(index: number, count: number) { + if (count <= 20) return false + const interval = Math.ceil(count / 8) + return index !== count - 1 && index % interval !== 0 +} + +function isDenseColumnRange(range: UsageRange) { + return range === "1M" || range === "2M" +} + +function scrollDenseChartToEnd(element: HTMLDivElement | undefined, range: UsageRange, count: number) { + if (!element || count <= 0 || !isDenseColumnRange(range) || typeof window === "undefined") return + window.requestAnimationFrame(() => { + element.scrollLeft = element.scrollWidth - element.clientWidth + }) +} + +function formatTopModelsMobileDate(label: string, range: UsageRange) { + if (range === "1M" || range === "2M") return label.split(" - ")[0] ?? label + return label +} + +function usageTotal(point: UsagePoint) { + return point.segments.reduce((sum, item) => sum + item.value, 0) +} + +function formatTokens(value: number) { + if (value >= 1) return `${value.toFixed(value >= 10 ? 0 : 1)}T` + return `${Math.round(value * 1000)}B` +} + +function Leaderboard(props: { + data: LeaderboardEntry[] + activeModel: string | undefined + onActiveModelChange: (model: string | undefined) => void +}) { + const featured = createMemo(() => props.data.slice(0, 3)) + const columns = createMemo(() => + [0, 1, 2].map((index) => props.data.slice(3 + index * 5, 8 + index * 5)).filter((column) => column.length > 0), + ) + + return ( +
+
+ + {(entry) => ( + + )} + +
+ + ) +} + +function LeaderboardCard(props: { + entry: LeaderboardEntry + size: "featured" | "compact" + active: boolean + onActiveModelChange: (model: string | undefined) => void +}) { + return ( +
props.onActiveModelChange(props.entry.model)} + onPointerLeave={(event) => { + if (event.pointerType === "touch") return + props.onActiveModelChange(undefined) + }} + onFocus={() => props.onActiveModelChange(props.entry.model)} + onBlur={() => props.onActiveModelChange(undefined)} + onClick={() => props.onActiveModelChange(props.entry.model)} + > + {String(props.entry.rank).padStart(2, "0")} +
+ ) +} + +function getProviderIconId(author: string) { + if (author === "MiniMax") return "minimax" + if (author === "Moonshot") return "moonshotai" + if (author === "Zhipu") return "zhipuai" + return author.toLowerCase() +} + +function formatBillions(value: number) { + if (value >= 1000) return `${(value / 1000).toFixed(value >= 10000 ? 0 : 1)}T` + return `${value}B` +} + +function formatChange(value: number) { + if (value > 0) return `+${value}%` + return `${value}%` +} + +function MarketShareSection(props: { data: StatsHomeData["market"] }) { + const [range, setRange] = createSignal("2M") + const [activeIndex, setActiveIndex] = createSignal(2) + const [activeAuthor, setActiveAuthor] = createSignal() + const [inspecting, setInspecting] = createSignal(false) + const data = createMemo(() => props.data[range()]) + const authorOrder = createMemo(() => getMarketAuthorOrder(data())) + const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(data().length - 1, 0))) + const activeDay = createMemo(() => data()[selectedIndex()]) + + return ( +
{ + if (event.pointerType === "touch") return + setActiveAuthor(undefined) + setInspecting(false) + }} + > + + + } + > + {(day) => ( + <> + { + setActiveIndex(index) + setInspecting(true) + }} + onActiveAuthorChange={(author) => { + setActiveAuthor(author) + setInspecting(true) + }} + /> + { + setActiveAuthor(author) + setInspecting(true) + }} + /> + + )} + +
+

+ [*] + {inspecting() ? formatMarketDate(activeDay()) : formatMarketRange(data())} +

+ +
+
+ ) +} + +function MarketShare(props: { + data: MarketDay[] + range: UsageRange + authorOrder: Map + activeIndex: number + activeAuthor: string | undefined + inspecting: boolean + onActiveIndexChange: (index: number) => void + onActiveAuthorChange: (author: string) => void +}) { + let chartRef: HTMLDivElement | undefined + + createEffect(() => scrollDenseChartToEnd(chartRef, props.range, props.data.length)) + + return ( +
+
+ + {(day, index) => ( + + )} + +
+
+ + {(day, index) => ( + + )} + +
+
+ ) +} + +function MarketShareList(props: { + data: MarketDay["authors"] + authorOrder: Map + activeAuthor: string | undefined + onActiveAuthorChange: (author: string) => void +}) { + return ( +
    + + {(item, index) => ( +
  1. props.onActiveAuthorChange(item.author)} + onFocus={() => props.onActiveAuthorChange(item.author)} + onKeyDown={(event) => { + if (event.key !== "Enter" && event.key !== " ") return + event.preventDefault() + props.onActiveAuthorChange(item.author) + }} + > + {String(index() + 1).padStart(2, "0")} + + {item.author} + {formatTrillions(item.tokens)} + {item.share.toFixed(1)}% +
  2. + )} +
    +
+ ) +} + +function getMarketSegmentColor(author: string, color: string, activeAuthor: string | undefined) { + if (!activeAuthor) return color + if (activeAuthor === author) return color + return "var(--stats-bar-idle)" +} + +function stackedMarketAuthors(day: MarketDay, order: Map) { + return day.authors + .map((author, index) => ({ author, index })) + .slice() + .sort((a, b) => (order.get(b.author.author) ?? b.index) - (order.get(a.author.author) ?? a.index)) +} + +function getMarketAuthorOrder(data: MarketDay[]) { + return getRankOrder( + data.flatMap((day) => day.authors.map((author, index) => ({ key: author.author, value: author.tokens, index }))), + ) +} + +function getRankOrder(items: { key: string; value: number; index: number }[]) { + return new Map( + Object.values( + items.reduce>((result, item) => { + result[item.key] = { + key: item.key, + value: (result[item.key]?.value ?? 0) + item.value, + index: Math.min(result[item.key]?.index ?? item.index, item.index), + } + return result + }, {}), + ) + .toSorted((a, b) => b.value - a.value || a.index - b.index || a.key.localeCompare(b.key)) + .map((item, index) => [item.key, index] as const), + ) +} + +function getRankColor(key: string, fallbackIndex: number, order: Map, colors: readonly string[]) { + return colors[order.get(key) ?? fallbackIndex] ?? "var(--stats-text)" +} + +function isMarketMobileLabelHidden(index: number, count: number) { + return count > 7 && index % 2 === 1 +} + +function formatMarketMobileDate(label: string) { + return marketDateParts(label).start +} + +function formatTrillions(value: number) { + return `${value.toFixed(value >= 10 ? 0 : 1)}T` +} + +function formatMarketDate(day: MarketDay | undefined) { + if (!day) return "No data" + return formatMarketDateLabel(day.date) +} + +function formatMarketRange(data: MarketDay[]) { + const first = data[0]?.date + const last = data[data.length - 1]?.date + if (!first || !last) return "No data" + const start = marketDateParts(first).start + const end = marketDateParts(last).end + if (start === end) return formatMarketDateLabel(start) + return `${start} ${new Date().getFullYear()} → ${end} ${new Date().getFullYear()}` +} + +function formatMarketDateLabel(label: string) { + const parts = marketDateParts(label) + const year = new Date().getFullYear() + if (parts.start === parts.end) return `${parts.start} ${year}` + return `${parts.start} ${year} → ${parts.end} ${year}` +} + +function marketDateParts(label: string) { + const [start, end] = label.split(" - ") + return { start: start ?? label, end: end ?? start ?? label } +} + +function TokenCostSection(props: { data: StatsHomeData["tokenCost"] }) { + const [product, setProduct] = createSignal("Go") + const [activeIndex, setActiveIndex] = createSignal(2) + const data = createMemo(() => props.data[product()]) + const visible = createMemo(() => data().slice(0, 13)) + const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(visible().length - 1, 0))) + + return ( +
+ + + 0} + fallback={ + + } + > + + + +
+ ) +} + +function TokenCostChart(props: { + data: TokenCostEntry[] + activeIndex: number + onActiveIndexChange: (index: number) => void +}) { + const max = createMemo(() => Math.max(0, ...props.data.map((item) => item.total)) || 1) + const active = createMemo(() => props.data[props.activeIndex] ?? props.data[0]) + + return ( +
+ + {(item, index) => ( + + )} + + + {(item) => ( +
+

+ Input + {formatDollars(item().input)} +

+

+ Output + {formatDollars(item().output)} +

+

+ Cached + {formatDollars(item().cached)} +

+
+ )} +
+
+ ) +} + +function formatDollars(value: number) { + return `$${value.toFixed(2)}` +} + +function MetricBar(props: { value: number; max: number; active: boolean }) { + const fill = createMemo(() => Math.min(1, Math.max(props.value / props.max, props.value > 0 ? 0.03 : 0))) + return ( + + + + + ) +} + +function SessionCostSection(props: { data: StatsHomeData["sessionCost"] }) { + const [product, setProduct] = createSignal("Go") + const [activeIndex, setActiveIndex] = createSignal(2) + const data = createMemo(() => props.data[product()]) + const visible = createMemo(() => data().slice(0, 16)) + const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(visible().length - 1, 0))) + + return ( +
+ + + 0} + fallback={ + + } + > + + + +
+ ) +} + +function SessionCostChart(props: { + data: SessionCostEntry[] + activeIndex: number + onActiveIndexChange: (index: number) => void +}) { + const maxCost = createMemo(() => Math.max(0, ...props.data.map((item) => item.cost)) || 1) + const maxTokens = createMemo(() => Math.max(0, ...props.data.map((item) => item.tokens)) || 1) + const active = createMemo(() => props.data[props.activeIndex] ?? props.data[0]) + + return ( +
+
+