diff --git a/.github/release/plan-release.sh b/.github/release/plan-release.sh index 1febdebc1349..62876f6f8c07 100755 --- a/.github/release/plan-release.sh +++ b/.github/release/plan-release.sh @@ -3,7 +3,7 @@ # (INPUT_BUMP, INPUT_VERSION) only, and writes them to $GITHUB_OUTPUT. Nothing here reads repository files. # # push or dispatch on dev -> dev 0.0.0-dev- npm tag dev, desktop -# dispatch on dev with bump/version -> latest x.y.z npm tag latest, releasers only +# dispatch on dev with bump/version -> latest x.y.z npm tag latest, releasers only, notes required # push or dispatch on beta -> beta 0.0.0-beta- desktop only # pull_request -> pr 0.0.0-pr- everything, dry run # @@ -20,6 +20,10 @@ case "$GITHUB_EVENT_NAME:$GITHUB_REF:$versioned" in *) die "$GITHUB_EVENT_NAME on $GITHUB_REF cannot publish (versioned: $versioned)" ;; esac +if [ "$channel" = latest ] && [ -z "${INPUT_RELEASE_NOTES//[[:space:]]/}" ]; then + die "Stable releases need release notes; generate them with ./script/release.ts --print" +fi + if [ "$channel" = latest ]; then actor=${GITHUB_TRIGGERING_ACTOR:-${GITHUB_ACTOR:-}} [ -n "$actor" ] || die "Stable releases can only be started by releasers; the triggering actor is unknown" diff --git a/.github/release/publish-discord.sh b/.github/release/publish-discord.sh new file mode 100755 index 000000000000..790428ab2ff8 --- /dev/null +++ b/.github/release/publish-discord.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# publish-discord.sh: announces the v release in Discord with OPENCODE_RELEASE_NOTES (DISCORD_WEBHOOK). +# Discord caps an embed description at 4096 characters, so longer notes are cut and link to the GitHub release. +. "$(dirname "$0")/lib.sh" + +tag="v$OPENCODE_VERSION" +payload=$(jq -n --arg tag "$tag" --arg notes "${OPENCODE_RELEASE_NOTES:-}" \ + --arg url "https://github.com/$GITHUB_REPOSITORY/releases/tag/$tag" ' + ($notes | if length > 4000 then .[:4000] + "\n\n[Full release notes](\($url))" else . end) as $description | + { + allowed_mentions: {parse: []}, + embeds: [{title: "OpenCode V2 \($tag)", url: $url, description: $description, color: 2829099}] + }') +echo "$payload" | jq . +if dry_run; then exit 0; fi + +test -n "${DISCORD_WEBHOOK:-}" || die "DISCORD_WEBHOOK is not set" +curl -fsS --retry 3 -H "Content-Type: application/json" -d "$payload" "$DISCORD_WEBHOOK" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cd560df277ab..3c0a05594e76 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,7 @@ on: required: false type: string release_notes: - description: "Reviewed V2 release notes for CHANGELOG.md and the GitHub release (optional)" + description: "Reviewed V2 release notes for CHANGELOG.md and the GitHub release (required with bump or version)" required: false type: string @@ -72,6 +72,7 @@ jobs: GH_TOKEN: ${{ github.token }} # reads the triggering actor's repository role for stable releases INPUT_BUMP: ${{ inputs.bump }} INPUT_VERSION: ${{ inputs.version }} + INPUT_RELEASE_NOTES: ${{ inputs.release_notes }} # A versioned release builds from a commit with its versions and changelog on the dispatched dev commit, # tagged v. Runs git only. @@ -733,6 +734,22 @@ jobs: GH_REPO: ${{ github.repository }} OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} + publish-discord: + needs: [plan, publish-github-release] + if: ${{ !cancelled() && !failure() && needs.plan.outputs.release == 'true' }} + runs-on: ubuntu-24.04 + environment: ${{ needs.plan.outputs.dry_run != 'true' && 'release' || '' }} + permissions: + contents: read + env: *env + steps: + - *checkout-release + - name: Publish + run: bash .github/release/publish-discord.sh + env: + DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} + OPENCODE_RELEASE_NOTES: ${{ inputs.release_notes }} + # Brings the release commit back to dev. Pushing to dev is blocked by rulesets, so it opens a PR. publish-version-pr: needs: [plan, tag, publish-npm, publish-cli, publish-desktop, publish-github-release] diff --git a/.gitignore b/.gitignore index 477fdab9d85f..1b2296b95730 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,6 @@ target # Local dev files opencode-dev -UPCOMING_CHANGELOG.md RELEASE_REVIEW.md logs/ *.bun-build diff --git a/.opencode/command/changelog.md b/.opencode/command/changelog.md deleted file mode 100644 index b28d963d005a..000000000000 --- a/.opencode/command/changelog.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -model: opencode/gpt-5.4 ---- - -Create `UPCOMING_CHANGELOG.md` from the structured changelog input below. -If `UPCOMING_CHANGELOG.md` already exists, ignore its current contents completely. -Do not preserve, merge, or reuse text from the existing file. - -The input already contains the exact commit range since the last non-draft release. -The commits are already filtered to the release-relevant packages and grouped into -the release sections. Do not fetch GitHub releases, PRs, or build your own commit list. -The input may also include a `## Community Contributors Input` section. - -Before writing any entry you keep, inspect the real diff with -`git show --stat --format='' ` or `git show --format='' ` so you can -understand the actual code changes and not just the commit message (they may be misleading). -Do not use `git log` or author metadata when deciding attribution. - -Rules: - -- Write the final file with release sections in this order: - `## Core`, `## TUI`, `## Desktop`, `## SDK`, `## Extensions` -- Only include sections that have at least one notable entry -- Within each release section, keep bug fixes grouped under `### Bugfixes` -- Keep other notable entries under `### Improvements` when a section has bug fixes too -- Omit empty subsections -- Keep one bullet per commit you keep -- Skip commits that are entirely internal, CI, tests, refactors, or otherwise not user-facing -- Start each bullet with a capital letter -- Prefer what changed for users over what code changed internally -- Do not copy raw commit prefixes like `fix:` or `feat:` or trailing PR numbers like `(#123)` -- Community attribution is deterministic: only preserve an existing `(@username)` suffix from the changelog input -- If an input bullet has no `(@username)` suffix, do not add one -- Never add a new `(@username)` suffix from `git show`, commit authors, names, or email addresses -- If no notable entries remain and there is no contributor block, write exactly `No notable changes.` -- If no notable entries remain but there is a contributor block, omit all release sections and return only the contributor block -- If the input contains `## Community Contributors Input`, append the block below that heading to the end of the final file verbatim -- Do not add, remove, rewrite, or reorder contributor names or commit titles in that block -- Do not derive the thank-you section from the main summary bullets -- Do not include the heading `## Community Contributors Input` in the final file -- Focus on writing the least words to get your point across - users will skim read the changelog, so we should be precise - -**Importantly, the changelog is for users (who are at least slightly technical), they may use the TUI, Desktop, SDK, Plugins and so forth. Be thorough in understanding flow on effects may not be immediately apparent. e.g. a package upgrade looks internal but may patch a bug. Or a refactor may also stabilise some race condition that fixes bugs for users. The PR title/body + commit message will give you the authors context, usually containing the outcome not just technical detail** - - - -!`bun script/raw-changelog.ts $ARGUMENTS` - - diff --git a/bun.lock b/bun.lock index b5902b764492..72fdd109a462 100644 --- a/bun.lock +++ b/bun.lock @@ -219,10 +219,10 @@ "@solidjs/router": "catalog:", "@solidjs/start": "catalog:", "aws4fetch": "1.0.20", - "nitro": "3.0.1-alpha.1", + "nitro": "3.0.260903-beta", "number-flow": "0.6.2", "solid-js": "catalog:", - "vite": "catalog:", + "vite": "8.2.4", "zod": "catalog:", }, "devDependencies": { @@ -256,6 +256,7 @@ "@lydell/node-pty": "catalog:", "@modelcontextprotocol/client": "2.3.1", "@modelcontextprotocol/core": "2.3.1", + "@modelcontextprotocol/server": "2.3.1", "@opencode/ai": "workspace:*", "@opencode/codemode": "workspace:*", "@opencode/plugin": "workspace:*", @@ -285,9 +286,9 @@ }, "devDependencies": { "@ai-sdk/openai-compatible": "2.0.41", + "@anthropic-ai/claude-agent-sdk": "0.3.301", "@effect/platform-node": "catalog:", "@effect/sql-sqlite-bun": "catalog:", - "@modelcontextprotocol/server": "2.3.1", "@opencode/http-recorder": "workspace:*", "@parcel/watcher-darwin-arm64": "2.5.1", "@parcel/watcher-darwin-x64": "2.5.1", @@ -304,6 +305,12 @@ "drizzle-kit": "catalog:", "fast-check": "catalog:", }, + "peerDependencies": { + "@anthropic-ai/claude-agent-sdk": "0.3.301", + }, + "optionalPeers": [ + "@anthropic-ai/claude-agent-sdk", + ], }, "packages/desktop": { "name": "@opencode/desktop", @@ -517,8 +524,8 @@ }, "peerDependencies": { "@opencode/theme": "workspace:*", - "@opentui/core": "0.7.0", - "@opentui/solid": "0.7.0", + "@opentui/core": ">=0.8.0", + "@opentui/solid": ">=0.8.0", "electron": "*", "solid-js": ">=1.9.0", "vite": ">=6", @@ -728,10 +735,10 @@ "d3-scale": "4.0.2", "effect": "catalog:", "i18n-iso-countries": "7.14.0", - "nitro": "3.0.1-alpha.1", + "nitro": "3.0.260903-beta", "solid-js": "catalog:", "sst": "catalog:", - "vite": "catalog:", + "vite": "8.2.4", }, "devDependencies": { "@types/bun": "catalog:", @@ -1022,9 +1029,9 @@ "overrides": { "@astrojs/starlight": "catalog:", "@effect/platform-node-shared": "catalog:", - "@opentui/core": "0.7.0", - "@opentui/keymap": "0.7.0", - "@opentui/solid": "0.7.0", + "@opentui/core": "catalog:", + "@opentui/keymap": "catalog:", + "@opentui/solid": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:", "astro": "catalog:", @@ -1045,9 +1052,9 @@ "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", "@octokit/rest": "22.0.0", - "@opentui/core": "0.7.0", - "@opentui/keymap": "0.7.0", - "@opentui/solid": "0.7.0", + "@opentui/core": "0.8.0", + "@opentui/keymap": "0.8.0", + "@opentui/solid": "0.8.0", "@pierre/diffs": "1.6.1", "@pierre/highlights": "0.2.0", "@playwright/test": "1.60.0", @@ -1059,7 +1066,7 @@ "@solid-primitives/storage": "4.4.0", "@solidjs/meta": "0.29.4", "@solidjs/router": "1.0.0", - "@solidjs/start": "https://pkg.pr.new/@solidjs/start@dfb2020", + "@solidjs/start": "2.1.0", "@standard-schema/spec": "1.1.0", "@tailwindcss/vite": "4.1.11", "@tanstack/solid-virtual": "3.13.37", @@ -1110,7 +1117,25 @@ "@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="], - "@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.71.2", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-TGNDEUuEstk/DKu0/TflXAEt+p+p/WhTlFzEnoosvbaDU2LTjm42igSdlL0VijrKpWejtOKxX0b8A7uc+XiSAQ=="], + "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.301", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.301", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.301", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.301", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.301", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.301", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.301", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.301", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.301" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-mAe4zIFRL9BejcFHQVc+D0gxrMR/7mDt5GgdekfWB2DNWZebHoeGhgP2R3rZ/BcEZnW10nSGV2IwWyywwZw83Q=="], + + "@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.301", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Hva/QZr94pm9mN6Trz59XGLgRPn8zLPrghRK8/MsvLCTrCzD1CNd9Pe1pUV1woTX29qPOGP3xRU3Mgm2LhIL7A=="], + + "@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.301", "", { "os": "darwin", "cpu": "x64" }, "sha512-k6jNdu9eEhkPLTPTwHTn3rbIpKHm0mcndkS4wAZtQehCIFc69tmZZ4yeEtQ4eZ2jR0+6ttLtRy+5Q82Q6Ohm0Q=="], + + "@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.301", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-Uqjy+YD6ImvelrFs7WHRMboT3BqknGLrDSdiejDqzFk62TZZOqIH9OFHyiyvHexoO31CpDEcn+d7LB+SgpNurA=="], + + "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.301", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-C1+q1cYZY2bYxDYCfHHaq9ToGMTO/6FdbB0JShyPCyAt0lrRC+myNgsvPq/0ZsrtPWbcbrpX6QgbsFn2QzEWcw=="], + + "@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.301", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-V0zrxg59pBSp6PXPD70m/nRwUApKM/q5SJdeHq2ZAn7mcAr/GIBRoBEAIrA2kOAK9EkIyjKNKkrwuOVeyId/lA=="], + + "@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.301", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-qmHolcb+CgzYc4rfZrJd5iEIzOPRPz2edJBH+8V4W4R+bswsNaqf59NBkrDt3GdfmGr42touHYJ/4dV+g/b5eQ=="], + + "@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.301", "", { "os": "win32", "cpu": "arm64" }, "sha512-V/iwQ3/wcxeQaycw2Daym9CzxssjYXIWtQJEFoU+Zrck3++2lD24KxFK0pwB3f258/uwdKoAM0x5p7+FEMRzwQ=="], + + "@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.301", "", { "os": "win32", "cpu": "x64" }, "sha512-FJe1o2nt+K7mQ7KG5VdEoCEo3HtUmEeITCn6ZswKGEHmgmZDogDnExQ649+IYuRXpW5dAQlYqdWaEA6cvtmoXA=="], + + "@anthropic-ai/sdk": ["@anthropic-ai/sdk@1.3.0", "", { "dependencies": { "@opentelemetry/api": "^1.4.1", "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-k7z9BlLLPxfZH+ov7dS6EnaN/wiZeV8YNT1LZfrpAHIy7oY7pHr4UzirF9f2OlHtFEnRBOX+AZQ91Y5fK+TPTw=="], "@anycable/core": ["@anycable/core@0.9.2", "", { "dependencies": { "nanoevents": "^7.0.1" } }, "sha512-x5ZXDcW/N4cxWl93CnbHs/u7qq4793jS2kNPWm+duPrXlrva+ml2ZGT7X9tuOBKzyIHf60zWCdIK7TUgMPAwXA=="], @@ -1546,11 +1571,11 @@ "@emmetio/stream-reader-utils": ["@emmetio/stream-reader-utils@0.1.0", "", {}, "sha512-ZsZ2I9Vzso3Ho/pjZFsmmZ++FWeEd/txqybHTm4OgaZzdS8V9V/YYWQwg5TC38Z7uLWUV1vavpLLbjJtKubR1A=="], - "@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" } }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], + "@emnapi/core": ["@emnapi/core@1.11.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA=="], - "@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], + "@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="], - "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], @@ -1660,6 +1685,8 @@ "@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="], + "@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="], + "@ibm/plex": ["@ibm/plex@6.4.1", "", { "dependencies": { "@ibm/telemetry-js": "^1.5.1" } }, "sha512-fnsipQywHt3zWvsnlyYKMikcVI7E2fEwpiPnIHFqlbByXVfQfANAAeJk1IV4mNnxhppUIDlhU0TzwYwL++Rn2g=="], "@ibm/telemetry-js": ["@ibm/telemetry-js@1.11.0", "", { "bin": { "ibmtelemetry": "dist/collect.js" } }, "sha512-RO/9j+URJnSfseWg9ZkEX9p+a3Ousd33DBU7rOafoZB08RqdzxFVYJ2/iM50dkBuD0o7WX7GYt1sLbNgCoE+pA=="], @@ -1772,11 +1799,13 @@ "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.3.1", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], + "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.3.1", "", { "dependencies": { "@modelcontextprotocol/core": "2.3.1", "zod": "^4.2.0" } }, "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw=="], "@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="], - "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="], + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.5", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA=="], "@noble/hashes": ["@noble/hashes@2.3.0", "", {}, "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ=="], @@ -1988,27 +2017,27 @@ "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="], - "@opentui/core": ["@opentui/core@0.7.0", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.7.0", "@opentui/core-darwin-x64": "0.7.0", "@opentui/core-linux-arm64": "0.7.0", "@opentui/core-linux-arm64-musl": "0.7.0", "@opentui/core-linux-x64": "0.7.0", "@opentui/core-linux-x64-musl": "0.7.0", "@opentui/core-win32-arm64": "0.7.0", "@opentui/core-win32-x64": "0.7.0" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-2iWBw9oo+ZJfPbOWeTLXfDV63yTDRfclxltI4IgTa6n7OB90x5xplLMH3y9DXhnWibzTui00GbK3ZCwKfUU1SQ=="], + "@opentui/core": ["@opentui/core@0.8.0", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.8.0", "@opentui/core-darwin-x64": "0.8.0", "@opentui/core-linux-arm64": "0.8.0", "@opentui/core-linux-arm64-musl": "0.8.0", "@opentui/core-linux-x64": "0.8.0", "@opentui/core-linux-x64-musl": "0.8.0", "@opentui/core-win32-arm64": "0.8.0", "@opentui/core-win32-x64": "0.8.0" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-LwnIT7k+rGelridv7390enJXZpNuQYKIS3NdttJyoLPjbRFPyHnAKkCHk6X8MRS64vcSjOeVq9sl7XLWII16jQ=="], - "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.7.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-meEyZVUeCIauqHLWo/IsSlKzZPTnGIEjRLigefSZbrSAcOiMryd3OcUWvSByIXpYb9UPOpW0YxKKfVwepb9u2A=="], + "@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.8.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Cp+BL1DsRZhUG56AuyXlH8DA4dsKfZ3Qgh1XMYDGokkC4p9uv8kdNNhyzmURAFa2LK77XqVv1Zhwr/6DqqpMlw=="], - "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.7.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-hZQ4OfAua5CtUv3hpZ81zhNTTLULbg0leQ/3eupjefityGP6163eS56IzymTWuiM/mVD/7Ad5bicH0I2JXhr1g=="], + "@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.8.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Jp4pzdIuKsS3XYq9xuWuAO52tTj9gnWeeoI3bg456CF6XnY2yQMasWOd/WmjfvYfAaJzGDFa4DNXhByBMPVuTw=="], - "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.7.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-/u+Kalzkz8NntUW5zjypgt9fnzeKohLG9YMEas7n98KvyaYScrtO4Mdj5iv/STNB3IfocJOChzYAbO6C8TmlPQ=="], + "@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.8.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-b6D/VP9y0Z18tO86GSTp9BBykgR6r5CQM1ol9UMJfUt+PjN5HGksbOCDTMIQufXvt4WIUFHrSBProysJRFzbYw=="], - "@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.7.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-BkTn+WLf9OPR4KhBnuOki+R/cgk2qwbL49eQn5fEYPeiJD4HPalGbEZDea59UjwNEJ7rqKq2yuPAXQjkDZ6y3w=="], + "@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.8.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-8ZPl/2DChcS7XIVRPIazigXaMNyxa2bwvuzPprNbzT0+cVJLIoGC19pjiV3bI3oVXBPVMNqgIcppOrEHBhlouw=="], - "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.7.0", "", { "os": "linux", "cpu": "x64" }, "sha512-OD2tGl1r27zcgCsuc+TYU5e+qhrbsRSI0YUBEb0ebQo8P6Ps2FL9LFenH9om4fddCh06G9Zd45ekJMhlDrGD3Q=="], + "@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.8.0", "", { "os": "linux", "cpu": "x64" }, "sha512-aXBNIdE6iMf58/Tdnd6UzXeFjYfaHzQ6E0nukjLe2ir41/meJJYEAHUQ62EBr/gxvuCNZHTBQB4T9BzF7PdENQ=="], - "@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.7.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-HrJbcAIuayzQmWVzv+cjez37fNHL9FDoHmjwxAb4iK5GTjl89FZCxeKopyua14RA6WpP8/zUJQi8U16mm6XptA=="], + "@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.8.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-xGEYw6wkX0sPwPx6RosQZanuWF0+5cIup2alhHHQQfKJkcLS8r8NBWlcy2LK9CoEWH6SBtNXC+9Y5IrryCOvJQ=="], - "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.7.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8yqBoRsDbvKl2kGX0O8t5kpnVEnbzs+2qUZlJ8sbeA3Z+73WFj36G+clUIMVxpspOu78iKXlD84NIwTxjZUPKw=="], + "@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.8.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-XtK0QMyIiqeDmrIyyAXqqp7TKaRGaWnBlbnEsNrkRLrgP+aLwRhRSHdafxi+RMqj3h9qOlb1MgnPal1kx7wP4g=="], - "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.7.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OfNAX7fNFHhOiiojUkIjhVOZf+IDjpbpT5G7HrxGqhlZ+n4jITrrJzACHctteWbMUYcibieJzIIoKuLdmD5I+w=="], + "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.8.0", "", { "os": "win32", "cpu": "x64" }, "sha512-P5X2RcDDntIJ4q1WvQawGWCae5BzHrm50PMy7+PZ3Su8GGwnaCQ5xRHvDIQfhki8pZMo2SoTOkpStR0Wj1QoXQ=="], - "@opentui/keymap": ["@opentui/keymap@0.7.0", "", { "dependencies": { "@opentui/core": "0.7.0" }, "peerDependencies": { "@opentui/react": "0.7.0", "@opentui/solid": "0.7.0", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-2IqUnLP+SCZR7+LXRL/7/DGFyaAR6r9y16H5oQVdRTfbACxAjszOaq2iZDEzHp1HVtamQRqEfteuaLEDwmO3kg=="], + "@opentui/keymap": ["@opentui/keymap@0.8.0", "", { "dependencies": { "@opentui/core": "0.8.0" }, "peerDependencies": { "@opentui/react": "0.8.0", "@opentui/solid": "0.8.0", "react": ">=19.2.0", "solid-js": "^1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-Kv00d1Bw/9U1ORM5fJyn9PQ9LbZi+Q7m9jO2EhyBeNAienSKb4PAjdcu9di6jxhkqt6jG+FXyndoemED8TzK4A=="], - "@opentui/solid": ["@opentui/solid@0.7.0", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.7.0", "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-S6SNZGRykV02UjNbM+f/6lSeAPN3dfEbjcK1jAAdFCfa+EVhJqcJVyaJgtwHLU9fI6c/O1VKXPzbbFYj2RhNVQ=="], + "@opentui/solid": ["@opentui/solid@0.8.0", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.8.0", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.16", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "^1.9.12" } }, "sha512-fk035Q9iGXFgpkXSbpdyWYnT1jFuY0gOhzxaqBXDVtuWrQPB5MRxUxXHgESIMXJPsMTROIjOcKuW+PPhsakpnw=="], "@opentunnel/client": ["@opentunnel/client@0.6.1", "", { "dependencies": { "@opentunnel/protocol": "0.6.1" }, "peerDependencies": { "effect": "^4.0.0", "undici": ">=7.0.0" }, "optionalPeers": ["undici"] }, "sha512-OuVNlWywQebIXCtkixjVHebOsR3KFRxJ0DSZry6Dzj4hHaHIf3eTVmQ7VwLCjuVmw+ctU2qHIP6RxuAPr07WDw=="], @@ -2016,67 +2045,47 @@ "@oslojs/encoding": ["@oslojs/encoding@1.1.0", "", {}, "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ=="], - "@oxc-minify/binding-android-arm64": ["@oxc-minify/binding-android-arm64@0.96.0", "", { "os": "android", "cpu": "arm64" }, "sha512-lzeIEMu/v6Y+La5JSesq4hvyKtKBq84cgQpKYTYM/yGuNk2tfd5Ha31hnC+mTh48lp/5vZH+WBfjVUjjINCfug=="], + "@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.141.0", "", { "os": "android", "cpu": "arm" }, "sha512-jk7086MFvR/T4DG9IY7MKBVt1PMxvSZoz/TvnifodvS0pjghVwJHRttnAExhlwdMOgHv1TmLdENnbNpYk2zjvA=="], - "@oxc-minify/binding-darwin-arm64": ["@oxc-minify/binding-darwin-arm64@0.96.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-i0LkJAUXb4BeBFrJQbMKQPoxf8+cFEffDyLSb7NEzzKuPcH8qrVsnEItoOzeAdYam8Sr6qCHVwmBNEQzl7PWpw=="], + "@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.141.0", "", { "os": "android", "cpu": "arm64" }, "sha512-a4XDQ27ZT7e7zwAlxJDTiCA7IBGWDuy2+MhFq85Of7XlBSmpkfcBFml11q0Zx6f7RMuI0B4xCtt2ytBS4yOptg=="], - "@oxc-minify/binding-darwin-x64": ["@oxc-minify/binding-darwin-x64@0.96.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-C5vI0WPR+KPIFAD5LMOJk2J8iiT+Nv65vDXmemzXEXouzfEOLYNqnW+u6NSsccpuZHHWAiLyPFkYvKFduveAUQ=="], + "@oxc-parser/binding-darwin-arm64": ["@oxc-parser/binding-darwin-arm64@0.141.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-m/kVk6rzYmBeHYnz+1Y5fod00AVTTxMbC71azFfm/zjx1j9XxwKtA0+VfkKuVMC8rbghb9TtfevnuWZa9OuPEg=="], - "@oxc-minify/binding-freebsd-x64": ["@oxc-minify/binding-freebsd-x64@0.96.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-3//5DNx+xUjVBMLLk2sl6hfe4fwfENJtjVQUBXjxzwPuv8xgZUqASG4cRG3WqG5Qe8dV6SbCI4EgKQFjO4KCZA=="], + "@oxc-parser/binding-darwin-x64": ["@oxc-parser/binding-darwin-x64@0.141.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-o0X+6KZlfucWU/v5oKRQPwdFXsXAjW8jmpo/Gpw/qyKsbKtlfkHoeH9Bjp/m13TwjewvJnCkwF0DWzgpC4HjTQ=="], - "@oxc-minify/binding-linux-arm-gnueabihf": ["@oxc-minify/binding-linux-arm-gnueabihf@0.96.0", "", { "os": "linux", "cpu": "arm" }, "sha512-WXChFKV7VdDk1NePDK1J31cpSvxACAVztJ7f7lJVYBTkH+iz5D0lCqPcE7a9eb7nC3xvz4yk7DM6dA9wlUQkQg=="], + "@oxc-parser/binding-freebsd-x64": ["@oxc-parser/binding-freebsd-x64@0.141.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-W5KbTnNkTMMMylqj6dYqnsXvkmESVPodPKYLJ5zdzIPdl9fUJtolkpUeSzYEbGGYB4a4A4avl3EePnZ/wLIdJg=="], - "@oxc-minify/binding-linux-arm-musleabihf": ["@oxc-minify/binding-linux-arm-musleabihf@0.96.0", "", { "os": "linux", "cpu": "arm" }, "sha512-7B18glYMX4Z/YoqgE3VRLs/2YhVLxlxNKSgrtsRpuR8xv58xca+hEhiFwZN1Rn+NSMZ29Z33LWD7iYWnqYFvRA=="], + "@oxc-parser/binding-linux-arm-gnueabihf": ["@oxc-parser/binding-linux-arm-gnueabihf@0.141.0", "", { "os": "linux", "cpu": "arm" }, "sha512-g3dtbJa8zeOGK36Sr9cQavsdi5H/ie2hVjrSjIxsNAR1qZA40ZYVXnfdfoMAlq8CmB9qFL1yhsSCUHeNmdmt8w=="], - "@oxc-minify/binding-linux-arm64-gnu": ["@oxc-minify/binding-linux-arm64-gnu@0.96.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-Yl+KcTldsEJNcaYxxonwAXZ2q3gxIzn3kXYQWgKWdaGIpNhOCWqF+KE5WLsldoh5Ro5SHtomvb8GM6cXrIBMog=="], + "@oxc-parser/binding-linux-arm-musleabihf": ["@oxc-parser/binding-linux-arm-musleabihf@0.141.0", "", { "os": "linux", "cpu": "arm" }, "sha512-e6hwQqd+3lvP13G2jxvFpoA7dzHcFLN+Mq47JCVMtdNHbbyBRo756JCtbbJH6ca8inTfyqZoqBmS3vhQlzAK2w=="], - "@oxc-minify/binding-linux-arm64-musl": ["@oxc-minify/binding-linux-arm64-musl@0.96.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-rNqoFWOWaxwMmUY5fspd/h5HfvgUlA3sv9CUdA2MpnHFiyoJNovR7WU8tGh+Yn0qOAs0SNH0a05gIthHig14IA=="], + "@oxc-parser/binding-linux-arm64-gnu": ["@oxc-parser/binding-linux-arm64-gnu@0.141.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-vXz2BLAuypA+4MLyBg94pzEo6THVnzYnCtAjXoihIIQo0t2pnp/AmW+SH1EI+4VbuJnC//KplIJ5yyaCGua4jA=="], - "@oxc-minify/binding-linux-riscv64-gnu": ["@oxc-minify/binding-linux-riscv64-gnu@0.96.0", "", { "os": "linux", "cpu": "none" }, "sha512-3paajIuzGnukHwSI3YBjYVqbd72pZd8NJxaayaNFR0AByIm8rmIT5RqFXbq8j2uhtpmNdZRXiu0em1zOmIScWA=="], + "@oxc-parser/binding-linux-arm64-musl": ["@oxc-parser/binding-linux-arm64-musl@0.141.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-jMkS/EztNW34HKsXIaT/SoHcmtocq/vWhwFOVduF9kduuuRIVwfwQ6uxzIO+qPKSXdd2TXt54of0BJ2zFMXnmw=="], - "@oxc-minify/binding-linux-s390x-gnu": ["@oxc-minify/binding-linux-s390x-gnu@0.96.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-9ESrpkB2XG0lQ89JlsxlZa86iQCOs+jkDZLl6O+u5wb7ynUy21bpJJ1joauCOSYIOUlSy3+LbtJLiqi7oSQt5Q=="], + "@oxc-parser/binding-linux-ppc64-gnu": ["@oxc-parser/binding-linux-ppc64-gnu@0.141.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-vo+MR+n3zQJ6Mq92hiP084NZcgDv5iJlVR02gMf28neMvVT1tKVm7VeiW/DxhdqOi3QLeaXIk9cUcLL1qrkngw=="], - "@oxc-minify/binding-linux-x64-gnu": ["@oxc-minify/binding-linux-x64-gnu@0.96.0", "", { "os": "linux", "cpu": "x64" }, "sha512-UMM1jkns+p+WwwmdjC5giI3SfR2BCTga18x3C0cAu6vDVf4W37uTZeTtSIGmwatTBbgiq++Te24/DE0oCdm1iQ=="], + "@oxc-parser/binding-linux-riscv64-gnu": ["@oxc-parser/binding-linux-riscv64-gnu@0.141.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-oh80w+7RuiO5gBp9Jnoa/H8Qlt3JsHL2MkW+0dwEdlDMdslVZX/YsekSK6EeyEenY66/mhCfypsNATQ7Ph3qlQ=="], - "@oxc-minify/binding-linux-x64-musl": ["@oxc-minify/binding-linux-x64-musl@0.96.0", "", { "os": "linux", "cpu": "x64" }, "sha512-8b1naiC7MdP7xeMi7cQ5tb9W1rZAP9Qz/jBRqp1Y5EOZ1yhSGnf1QWuZ/0pCc+XiB9vEHXEY3Aki/H+86m2eOg=="], + "@oxc-parser/binding-linux-riscv64-musl": ["@oxc-parser/binding-linux-riscv64-musl@0.141.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-LOyEmFA8sCnYbEXP1+iQvCC/P1YXHMA/t6x1Ksp0Y9VwhLFsiBJFzV1zIxrOIE2LKaGGhDjQ29xq9cbq6omDXA=="], - "@oxc-minify/binding-wasm32-wasi": ["@oxc-minify/binding-wasm32-wasi@0.96.0", "", { "dependencies": { "@napi-rs/wasm-runtime": "^1.0.7" }, "cpu": "none" }, "sha512-bjGDjkGzo3GWU9Vg2qiFUrfoo5QxojPNV/2RHTlbIB5FWkkV4ExVjsfyqihFiAuj0NXIZqd2SAiEq9htVd3RFw=="], + "@oxc-parser/binding-linux-s390x-gnu": ["@oxc-parser/binding-linux-s390x-gnu@0.141.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-3wnwk/l1CvszVE5TJR1wSl/zSEfydRqrNhn6s7Vr9IzSJpUQIroqVsIoPARHRFA+FQwkxAFDAHDAasa7v8OobQ=="], - "@oxc-minify/binding-win32-arm64-msvc": ["@oxc-minify/binding-win32-arm64-msvc@0.96.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-4L4DlHUT47qMWQuTyUghpncR3NZHWtxvd0G1KgSjVgXf+cXzFdWQCWZZtCU0yrmOoVCNUf4S04IFCJyAe+Ie7A=="], + "@oxc-parser/binding-linux-x64-gnu": ["@oxc-parser/binding-linux-x64-gnu@0.141.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-qtyQVAAebFq57B2tifTlel3TgGqUtsYNI/e+p6aya9rN9lOZVTDvr215fGYSA9XWooxzMxDiVxkBLk2jQHbsOQ=="], - "@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-linux-x64-musl": ["@oxc-parser/binding-linux-x64-musl@0.141.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-SkGV1nKw40roEc94pv5EaaeH2ay14G6+roe8Q0wIUC1LcEKxzKW921h7+ZuZX0D3q2Mb/7aSFmxEVqnko3lPRw=="], - "@oxc-project/types": ["@oxc-project/types@0.146.0", "", {}, "sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA=="], + "@oxc-parser/binding-openharmony-arm64": ["@oxc-parser/binding-openharmony-arm64@0.141.0", "", { "os": "none", "cpu": "arm64" }, "sha512-cVgDM7n8QziQqOaP5hNgUYfMG7S/ZeuPxFWXnnHRv7rh025COk0rfQ6eEdKG3j/GaUuyvNZN4ifF1J8KmuXLLA=="], - "@oxc-transform/binding-android-arm64": ["@oxc-transform/binding-android-arm64@0.96.0", "", { "os": "android", "cpu": "arm64" }, "sha512-wOm+ZsqFvyZ7B9RefUMsj0zcXw77Z2pXA51nbSQyPXqr+g0/pDGxriZWP8Sdpz/e4AEaKPA9DvrwyOZxu7GRDQ=="], + "@oxc-parser/binding-wasm32-wasi": ["@oxc-parser/binding-wasm32-wasi@0.141.0", "", { "dependencies": { "@emnapi/core": "1.11.2", "@emnapi/runtime": "1.11.2", "@napi-rs/wasm-runtime": "^1.1.6" }, "cpu": "none" }, "sha512-HggH++Fkn3OilBn+bs3jpgIFQa34oMAyUUHy0vpGum+gt1Eb5nyLc8dNU/RAPSw6lsLrx7ncKtHSZE+3Sp0l2g=="], - "@oxc-transform/binding-darwin-arm64": ["@oxc-transform/binding-darwin-arm64@0.96.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-td1sbcvzsyuoNRiNdIRodPXRtFFwxzPpC/6/yIUtRRhKn30XQcizxupIvQQVpJWWchxkphbBDh6UN+u+2CJ8Zw=="], + "@oxc-parser/binding-win32-arm64-msvc": ["@oxc-parser/binding-win32-arm64-msvc@0.141.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-KLSEH9GwgbrqbJOjtGHt9STw96s+78yDzp7IDN8Lno+7Ut9sNBfZ4jYZIz4mD50qmWUjoOI7i9I6UENbhNbMZQ=="], - "@oxc-transform/binding-darwin-x64": ["@oxc-transform/binding-darwin-x64@0.96.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-xgqxnqhPYH2NYkgbqtnCJfhbXvxIf/pnhF/ig5UBK8PYpCEWIP/cfLpQRQ9DcQnRfuxi7RMIF6LdmB1AiS6Fkg=="], + "@oxc-parser/binding-win32-ia32-msvc": ["@oxc-parser/binding-win32-ia32-msvc@0.141.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-9UVWUOOCI/1YkiSSNjg2zyBJYM9E/t1A/8GNobd48JDn/fQ6mzxcVO3H08jb3rAaW/B1VBf8eCORTvSsO9T08g=="], - "@oxc-transform/binding-freebsd-x64": ["@oxc-transform/binding-freebsd-x64@0.96.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-1i67OXdl/rvSkcTXqDlh6qGRXYseEmf0rl/R+/i88scZ/o3A+FzlX56sThuaPzSSv9eVgesnoYUjIBJELFc1oA=="], + "@oxc-parser/binding-win32-x64-msvc": ["@oxc-parser/binding-win32-x64-msvc@0.141.0", "", { "os": "win32", "cpu": "x64" }, "sha512-HI/wsvbWT5RHHw5c37D0fEgeTd8/1Q4OJs5jUmEBc17VZFG6SsCIe4barq7NsAPPks/JW+3ayi3Rp+PQI5h4Kg=="], - "@oxc-transform/binding-linux-arm-gnueabihf": ["@oxc-transform/binding-linux-arm-gnueabihf@0.96.0", "", { "os": "linux", "cpu": "arm" }, "sha512-9MJBs0SWODsqyzO3eAnacXgJ/sZu1xqinjEwBzkcZ3tQI8nKhMADOzu2NzbVWDWujeoC8DESXaO08tujvUru+Q=="], - - "@oxc-transform/binding-linux-arm-musleabihf": ["@oxc-transform/binding-linux-arm-musleabihf@0.96.0", "", { "os": "linux", "cpu": "arm" }, "sha512-BQom57I2ScccixljNYh2Wy+5oVZtF1LXiiUPxSLtDHbsanpEvV/+kzCagQpTjk1BVzSQzOxfEUWjvL7mY53pRQ=="], - - "@oxc-transform/binding-linux-arm64-gnu": ["@oxc-transform/binding-linux-arm64-gnu@0.96.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-kaqvUzNu8LL4aBSXqcqGVLFG13GmJEplRI2+yqzkgAItxoP/LfFMdEIErlTWLGyBwd0OLiNMHrOvkcCQRWadVg=="], - - "@oxc-transform/binding-linux-arm64-musl": ["@oxc-transform/binding-linux-arm64-musl@0.96.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-EiG/L3wEkPgTm4p906ufptyblBgtiQWTubGg/JEw82f8uLRroayr5zhbUqx40EgH037a3SfJthIyLZi7XPRFJw=="], - - "@oxc-transform/binding-linux-riscv64-gnu": ["@oxc-transform/binding-linux-riscv64-gnu@0.96.0", "", { "os": "linux", "cpu": "none" }, "sha512-r01CY6OxKGtVeYnvH4mGmtkQMlLkXdPWWNXwo5o7fE2s/fgZPMpqh8bAuXEhuMXipZRJrjxTk1+ZQ4KCHpMn3Q=="], - - "@oxc-transform/binding-linux-s390x-gnu": ["@oxc-transform/binding-linux-s390x-gnu@0.96.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-4djg2vYLGbVeS8YiA2K4RPPpZE4fxTGCX5g/bOMbCYyirDbmBAIop4eOAj8vOA9i1CcWbDtmp+PVJ1dSw7f3IQ=="], - - "@oxc-transform/binding-linux-x64-gnu": ["@oxc-transform/binding-linux-x64-gnu@0.96.0", "", { "os": "linux", "cpu": "x64" }, "sha512-f6pcWVz57Y8jXa2OS7cz3aRNuks34Q3j61+3nQ4xTE8H1KbalcEvHNmM92OEddaJ8QLs9YcE0kUC6eDTbY34+A=="], - - "@oxc-transform/binding-linux-x64-musl": ["@oxc-transform/binding-linux-x64-musl@0.96.0", "", { "os": "linux", "cpu": "x64" }, "sha512-NSiRtFvR7Pbhv3mWyPMkTK38czIjcnK0+K5STo3CuzZRVbX1TM17zGdHzKBUHZu7v6IQ6/XsQ3ELa1BlEHPGWQ=="], - - "@oxc-transform/binding-wasm32-wasi": ["@oxc-transform/binding-wasm32-wasi@0.96.0", "", { "dependencies": { "@napi-rs/wasm-runtime": "^1.0.7" }, "cpu": "none" }, "sha512-A91ARLiuZHGN4hBds9s7bW3czUuLuHLsV+cz44iF9j8e1zX9m2hNGXf/acQRbg/zcFUXmjz5nmk8EkZyob876w=="], - - "@oxc-transform/binding-win32-arm64-msvc": ["@oxc-transform/binding-win32-arm64-msvc@0.96.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-IedJf40djKgDObomhYjdRAlmSYUEdfqX3A3M9KfUltl9AghTBBLkTzUMA7O09oo71vYf5TEhbFM7+Vn5vqw7AQ=="], - - "@oxc-transform/binding-win32-x64-msvc": ["@oxc-transform/binding-win32-x64-msvc@0.96.0", "", { "os": "win32", "cpu": "x64" }, "sha512-0fI0P0W7bSO/GCP/N5dkmtB9vBqCA4ggo1WmXTnxNJVmFFOtcA1vYm1I9jl8fxo+sucW2WnlpnI4fjKdo3JKxA=="], + "@oxc-project/types": ["@oxc-project/types@0.146.0", "", {}, "sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA=="], "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.60.0", "", { "os": "android", "cpu": "arm" }, "sha512-YdeJKaZckDQL1qa62a1aKq/goyq48aX3yOxaaWqWb4sau4Ee4IiLbamftNLU3zbePky6QsDj6thnSSzHRBjDfA=="], @@ -2436,10 +2445,12 @@ "@solidjs/router": ["@solidjs/router@1.0.0", "", { "peerDependencies": { "solid-js": "^1.8.6" } }, "sha512-cCSk1hvgCowiMa9bzzYWHiLu1U4E22+DfJe6/rOwAyECKrxc3jrd5QnoW3sDDJtW+e077cz/M67bPl3DqOBw1Q=="], - "@solidjs/start": ["@solidjs/start@https://pkg.pr.new/@solidjs/start@dfb2020", { "dependencies": { "@babel/core": "^7.28.3", "@babel/traverse": "^7.28.3", "@babel/types": "^7.28.5", "@solidjs/meta": "^0.29.4", "@tanstack/server-functions-plugin": "1.134.5", "@types/babel__traverse": "^7.28.0", "@types/micromatch": "^4.0.9", "cookie-es": "^2.0.0", "defu": "^6.1.4", "error-stack-parser": "^2.1.4", "es-module-lexer": "^1.7.0", "esbuild": "^0.25.3", "fast-glob": "^3.3.3", "h3": "npm:h3@2.0.1-rc.4", "html-to-image": "^1.11.13", "micromatch": "^4.0.8", "path-to-regexp": "^8.2.0", "pathe": "^2.0.3", "radix3": "^1.1.2", "seroval": "^1.3.2", "seroval-plugins": "^1.2.1", "shiki": "^1.26.1", "solid-js": "^1.9.9", "source-map-js": "^1.2.1", "srvx": "^0.9.1", "terracotta": "^1.0.6", "vite": "7.1.10", "vite-plugin-solid": "^2.11.9", "vitest": "^4.0.10" } }, "sha512-7JjjA49VGNOsMRI8QRUhVudZmv0CnJ18SliSgK1ojszs/c3ijftgVkzvXdkSLN4miDTzbkXewf65D6ZBo6W+GQ=="], + "@solidjs/start": ["@solidjs/start@2.1.0", "", { "dependencies": { "@babel/core": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/trace-mapping": "^0.3.31", "@solidjs/meta": "^0.29.4", "@types/babel__traverse": "^7.28.0", "@types/micromatch": "^4.0.10", "cookie-es": "^3.1.1", "defu": "^6.1.7", "error-stack-parser-es": "^2.0.1", "fast-glob": "^3.3.3", "h3": "^2.0.1-rc.26", "html-to-image": "^1.11.13", "micromatch": "^4.0.8", "oxc-parser": "^0.141.0", "path-to-regexp": "^8.4.2", "pathe": "^2.0.3", "radix3": "^1.1.2", "seroval": "^1.6.11", "seroval-plugins": "^1.6.11", "shiki": "^4.3.1", "srvx": "^0.12.4", "terracotta": "^1.2.4", "vite-plugin-solid": "^2.11.13" }, "peerDependencies": { "@solidjs/router": ">=0.16.0 <2.0.0-0", "solid-js": "^1.9.15", "vite": "^8 || ^9" }, "optionalPeers": ["@solidjs/router"] }, "sha512-WxYkBPmjnrP30ODWLui8QVPki80puvsKZ5jOmy0m/t7mZsmhY0IBHpra8n+UQoMFgvvJkaAJS+DJqPFzmoKf+Q=="], "@speed-highlight/core": ["@speed-highlight/core@1.2.24", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="], + "@stablelib/base64": ["@stablelib/base64@1.0.1", "", {}, "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="], + "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], "@swc/helpers": ["@swc/helpers@0.5.23", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="], @@ -2476,14 +2487,8 @@ "@tailwindcss/vite": ["@tailwindcss/vite@4.3.3", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="], - "@tanstack/directive-functions-plugin": ["@tanstack/directive-functions-plugin@1.134.5", "", { "dependencies": { "@babel/code-frame": "7.27.1", "@babel/core": "^7.27.7", "@babel/traverse": "^7.27.7", "@babel/types": "^7.27.7", "@tanstack/router-utils": "1.133.19", "babel-dead-code-elimination": "^1.0.10", "pathe": "^2.0.3", "tiny-invariant": "^1.3.3" }, "peerDependencies": { "vite": ">=6.0.0 || >=7.0.0" } }, "sha512-J3oawV8uBRBbPoLgMdyHt+LxzTNuWRKNJJuCLWsm/yq6v0IQSvIVCgfD2+liIiSnDPxGZ8ExduPXy8IzS70eXw=="], - "@tanstack/query-core": ["@tanstack/query-core@5.91.2", "", {}, "sha512-Uz2pTgPC1mhqrrSGg18RKCWT/pkduAYtxbcyIyKBhw7dTWjXZIzqmpzO2lBkyWr4hlImQgpu1m1pei3UnkFRWw=="], - "@tanstack/router-utils": ["@tanstack/router-utils@1.133.19", "", { "dependencies": { "@babel/core": "^7.27.4", "@babel/generator": "^7.27.5", "@babel/parser": "^7.27.5", "@babel/preset-typescript": "^7.27.1", "ansis": "^4.1.0", "diff": "^8.0.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.15" } }, "sha512-WEp5D2gPxvlLDRXwD/fV7RXjYtqaqJNXKB/L6OyZEbT+9BG/Ib2d7oG9GSUZNNMGPGYAlhBUOi3xutySsk6rxA=="], - - "@tanstack/server-functions-plugin": ["@tanstack/server-functions-plugin@1.134.5", "", { "dependencies": { "@babel/code-frame": "7.27.1", "@babel/core": "^7.27.7", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-syntax-typescript": "^7.27.1", "@babel/template": "^7.27.2", "@babel/traverse": "^7.27.7", "@babel/types": "^7.27.7", "@tanstack/directive-functions-plugin": "1.134.5", "babel-dead-code-elimination": "^1.0.9", "tiny-invariant": "^1.3.3" } }, "sha512-2sWxq70T+dOEUlE3sHlXjEPhaFZfdPYlWTSkHchWXrFGw2YOAa+hzD6L9wHMjGDQezYd03ue8tQlHG+9Jzbzgw=="], - "@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=="], "@tanstack/solid-virtual": ["@tanstack/solid-virtual@3.13.37", "", { "dependencies": { "@tanstack/virtual-core": "3.17.8" }, "peerDependencies": { "solid-js": "^1.3.0" } }, "sha512-RxJC8n/6nnFHcPvDGMg7ZkqSzCVUco4JNw3ctIChj1HjoKs5I9wt5nsU+DUVtMVEiMfizUxOAx4TPIN8SHjxUQ=="], @@ -2530,8 +2535,6 @@ "@types/cacheable-request": ["@types/cacheable-request@6.0.3", "", { "dependencies": { "@types/http-cache-semantics": "*", "@types/keyv": "^3.1.4", "@types/node": "*", "@types/responselike": "^1.0.0" } }, "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw=="], - "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - "@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=="], @@ -2540,8 +2543,6 @@ "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], - "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], - "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], "@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="], @@ -2658,20 +2659,6 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.3.3", "", {}, "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg=="], - "@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="], - - "@vitest/mocker": ["@vitest/mocker@4.1.11", "", { "dependencies": { "@vitest/spy": "4.1.11", "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-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="], - - "@vitest/pretty-format": ["@vitest/pretty-format@4.1.11", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw=="], - - "@vitest/runner": ["@vitest/runner@4.1.11", "", { "dependencies": { "@vitest/utils": "4.1.11", "pathe": "^2.0.3" } }, "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw=="], - - "@vitest/snapshot": ["@vitest/snapshot@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog=="], - - "@vitest/spy": ["@vitest/spy@4.1.11", "", {}, "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA=="], - - "@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - "@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=="], "@volar/language-core": ["@volar/language-core@2.4.28", "", { "dependencies": { "@volar/source-map": "2.4.28" } }, "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ=="], @@ -2720,6 +2707,8 @@ "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + "acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="], "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], @@ -2734,6 +2723,8 @@ "ajv-draft-04": ["ajv-draft-04@1.0.0", "", { "peerDependencies": { "ajv": "^8.5.0" }, "optionalPeers": ["ajv"] }, "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw=="], + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + "ajv-i18n": ["ajv-i18n@4.2.0", "", { "peerDependencies": { "ajv": "^8.0.0-beta.0" } }, "sha512-v/ei2UkCEeuKNXh8RToiFsUclmU+G57LO1Oo22OagNMENIw+Yb8eMwvHu7Vn9fmkjJyv6XclhJ8TbuigSglPkg=="], "am-i-vibing": ["am-i-vibing@0.5.0", "", { "dependencies": { "process-ancestry": "^0.1.0" }, "bin": { "am-i-vibing": "dist/cli.mjs" } }, "sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA=="], @@ -2744,8 +2735,6 @@ "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - "ansis": ["ansis@4.3.1", "", {}, "sha512-BJ8/l4R5LRE7hW9WdSuGYrLSHi2ynxeFpDFbH0K/CgNeY/tyhk+vO6TYxXC5r5CpUhNVX310xzPsN/H9lCdfOA=="], - "anymatch": ["anymatch@3.1.3", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="], "app-builder-lib": ["app-builder-lib@26.15.7", "", { "dependencies": { "@electron/asar": "3.4.1", "@electron/fuses": "^1.8.0", "@electron/get": "^3.0.0", "@electron/notarize": "2.5.0", "@electron/osx-sign": "1.3.3", "@electron/rebuild": "^4.0.4", "@electron/universal": "2.0.3", "@malept/flatpak-bundler": "^0.4.0", "@noble/hashes": "^2.2.0", "@peculiar/webcrypto": "^1.7.1", "@types/fs-extra": "9.0.13", "ajv": "^8.18.0", "asn1js": "^3.0.10", "async-exit-hook": "^2.0.1", "builder-util": "26.15.3", "builder-util-runtime": "9.7.0", "chromium-pickle-js": "^0.2.0", "ci-info": "4.3.1", "debug": "^4.3.4", "dotenv": "^16.4.5", "dotenv-expand": "^11.0.6", "ejs": "^3.1.8", "electron-publish": "26.15.3", "fs-extra": "^10.1.0", "hosted-git-info": "^4.1.0", "isbinaryfile": "^5.0.0", "jiti": "^2.4.2", "js-yaml": "^4.1.0", "json5": "^2.2.3", "lazy-val": "^1.0.5", "minimatch": "^10.2.5", "pkijs": "^3.4.0", "plist": "3.1.0", "proper-lockfile": "^4.1.2", "resedit": "^1.7.0", "semver": "~7.7.3", "tar": "^7.5.7", "temp-file": "^3.4.0", "tiny-async-pool": "1.3.0", "unzipper": "^0.12.3", "which": "^5.0.0" }, "peerDependencies": { "dmg-builder": "26.15.7", "electron-builder-squirrel-windows": "26.15.7" } }, "sha512-C7APoYISPExUmrEntNhDpz9Tccb4uWuEDfLaC0WPPc7/pwzz0WZGznCz/ycPfkkzw6tKOalceD8g6TgHmVz1QA=="], @@ -2764,8 +2753,6 @@ "asn1js": ["asn1js@3.0.10", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.1.5", "tslib": "^2.8.1" } }, "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg=="], - "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - "astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="], "astro": ["astro@7.3.8", "", { "dependencies": { "@astrojs/compiler-rs": "^0.5.1", "@astrojs/internal-helpers": "0.12.0", "@astrojs/markdown-satteri": "0.4.3", "@astrojs/telemetry": "3.3.3", "@capsizecss/unpack": "^4.0.1", "@clack/prompts": "^1.8.1", "@oslojs/encoding": "^1.1.0", "am-i-vibing": "^0.5.0", "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", "clsx": "^2.1.1", "common-ancestor-path": "^2.0.0", "cookie": "^2.0.1", "devalue": "^5.9.4", "diff": "^9.0.0", "dset": "^3.1.4", "es-module-lexer": "^3.0.2", "find-proc": "0.2.0", "flattie": "^1.1.1", "fontace": "~0.4.1", "get-tsconfig": "5.0.0-beta.6", "github-slugger": "^2.0.0", "html-escaper": "3.0.3", "http-cache-semantics": "^4.2.0", "jsonc-parser": "^3.3.1", "magic-string": "^1.4.2", "magicast": "^0.5.5", "mrmime": "^2.0.1", "neotraverse": "^1.0.1", "obug": "^3.0.0", "p-limit": "^7.3.3", "p-queue": "^9.3.3", "package-manager-detector": "^1.8.0", "piccolore": "^0.1.3", "picomatch": "^4.0.7", "rolldown": "^1.2.11", "shiki": "^4.4.3", "smol-toml": "^1.9.0", "svgo": "^4.1.0", "tinyclip": "^1.0.3", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "ultrahtml": "^1.7.0", "unifont": "~0.7.5", "unstorage": "^1.17.5", "verkit": "^0.5.0", "vite": "^8.3.1", "vitefu": "^1.1.3", "xxhash-wasm": "^1.1.0", "yargs-parser": "^22.0.0", "zod": "^4.6.5" }, "optionalDependencies": { "sharp": "^0.35.4" }, "peerDependencies": { "@astrojs/markdown-remark": "^7.3.0" }, "optionalPeers": ["@astrojs/markdown-remark"], "bin": { "astro": "./bin/astro.mjs" } }, "sha512-LHzDHSaV+YzZiR3EFndDYTLLeNeuMtP1qX1FLcCNUUHOCqTTIWPczy2UV3zpA5VqvJe5cWZolqM9Z8JFqR2i9w=="], @@ -2794,8 +2781,6 @@ "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], - "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.10", "", { "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-lxve6Y02YiZTldB7efKpnbf1BH00XCFZNYYW235jSGsYaJNFtHrYlKV6/O+miHbjqpIr9FTe5+0no4hofAMbfA=="], "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=="], @@ -2830,6 +2815,8 @@ "bluebird": ["bluebird@3.7.2", "", {}, "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg=="], + "body-parser": ["body-parser@2.4.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="], + "boolbase": ["boolbase@1.0.0", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="], "boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="], @@ -2860,6 +2847,8 @@ "bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="], + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + "bytestreamjs": ["bytestreamjs@2.0.1", "", {}, "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ=="], "cac": ["cac@7.0.0", "", {}, "sha512-tixWYgm5ZoOD+3g6UTea91eow5z6AAHaho3g0V9CNSNb45gM8SmflpAc+GRd1InC4AqN/07Unrgp56Y94N9hJQ=="], @@ -2880,8 +2869,6 @@ "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], - "chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], - "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], @@ -2952,25 +2939,31 @@ "consola": ["consola@3.4.2", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="], - "content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "content-disposition": ["content-disposition@2.0.1", "", {}, "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog=="], + + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], "cookie": ["cookie@2.0.1", "", {}, "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w=="], - "cookie-es": ["cookie-es@2.0.1", "", {}, "sha512-aVf4A4hI2w70LnF7GG+7xDQUkliwiXWXFvTjkip4+b64ygDQ2sJPRSKFDHbxn8o0xu9QzPkMuuiWIXyFSE2slA=="], + "cookie-es": ["cookie-es@3.1.1", "", {}, "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg=="], + + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], "core-js-compat": ["core-js-compat@3.50.0", "", { "dependencies": { "browserslist": "^4.28.7" } }, "sha512-XGpFGbMLHwSt74YLTKho7Ib242qi6O8MSX+sRokV4oz7iKXvQWGYZthjIhjRGMxjzVkAubBO512dKGYcefmX3Q=="], "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], + "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], + "cross-dirname": ["cross-dirname@0.1.0", "", {}, "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q=="], "cross-fetch": ["cross-fetch@3.2.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q=="], "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], - "crossws": ["crossws@0.4.10", "", { "peerDependencies": { "srvx": ">=0.11.5" }, "optionalPeers": ["srvx"] }, "sha512-pz3oubH/dt12KjqsUB0IuXW4nwRDQ583iDsP4555Cpdqx0NoU7pGlWBcayyFI8f/l/idRpgjMEfwuOxSWJYlIA=="], + "crossws": ["crossws@0.4.15", "", { "peerDependencies": { "srvx": ">=0.11.5" }, "optionalPeers": ["srvx"] }, "sha512-NsUOpDZosz7nyI+qEIl05yaiXOWaXH2oTeM+XBWtiSWZtb5rzcIsl1AST/HzM2jzUn76eFuyrkn83E6iSBRUvw=="], "crypto-random-string": ["crypto-random-string@2.0.0", "", {}, "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA=="], @@ -3012,7 +3005,7 @@ "data-view-byte-offset": ["data-view-byte-offset@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-data-view": "^1.0.1" } }, "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ=="], - "db0": ["db0@0.3.4", "", { "peerDependencies": { "@electric-sql/pglite": "*", "@libsql/client": "*", "better-sqlite3": "*", "drizzle-orm": "*", "mysql2": "*", "sqlite3": "*" }, "optionalPeers": ["@electric-sql/pglite", "@libsql/client", "better-sqlite3", "drizzle-orm", "mysql2", "sqlite3"] }, "sha512-RiXXi4WaNzPTHEOu8UPQKMooIbqOEyqA1t7Z6MsdxSCeb8iUC9ko3LcmsLmeUt2SM5bctfArZKkRQggKZz7JNw=="], + "db0": ["db0@0.4.1", "", {}, "sha512-6RBY/bSn42UrqATwsiULj2uYFyEykB3XeA/NLIVQeHNXlYV6D4Idxx3/aa6k5Y45Dwzx7sygeLotnqHWSeURYA=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], @@ -3040,6 +3033,8 @@ "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], "destr": ["destr@2.0.5", "", {}, "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA=="], @@ -3094,6 +3089,8 @@ "ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="], + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + "effect": ["effect@4.0.6", "", {}, "sha512-Tc3mkzuLR6t6P9dhLt0D2GrxYtmU5td4XEJEiXCmILz53IRIfJyHsKZWjTA3xEjiwpNTtXBgI4iqYPxMztBDrw=="], "ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="], @@ -3126,7 +3123,7 @@ "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], - "emoji-regex-xs": ["emoji-regex-xs@1.0.0", "", {}, "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg=="], + "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], @@ -3142,11 +3139,11 @@ "env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], - "err-code": ["err-code@2.0.3", "", {}, "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA=="], + "env-runner": ["env-runner@0.2.3", "", { "dependencies": { "crossws": "^0.4.12", "exsolve": "^1.1.1", "httpxy": "^0.5.5", "srvx": "^1.0.5" }, "bin": { "env-runner": "./dist/cli.mjs" } }, "sha512-S8EFBKyznRwPVwayK187cYjvnpgC92xy+q0BIF++V965pfjMVVRbQ/HoTYGA/1EHmZ7E68k6Heq+4WnvVhOL5w=="], - "error-stack-parser": ["error-stack-parser@2.1.4", "", { "dependencies": { "stackframe": "^1.3.4" } }, "sha512-Sk5V6wVazPhq5MhpO+AUxJn5x7XSXGl1R93Vn7i+zS15KDVxQijejNCrz8340/2bgLBjR9GtEG8ZVKONDjcqGQ=="], + "err-code": ["err-code@2.0.3", "", {}, "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA=="], - "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], + "error-stack-parser-es": ["error-stack-parser-es@2.0.1", "", {}, "sha512-J36ntO+rMQVRuR/umlmxmfLi4TpWwtmTnHoJoXTiC2xDNazs0VDPKcX6pbhZMDd2HFtH9isMBJXMdbki+A++Pg=="], "es-abstract": ["es-abstract@1.24.2", "", { "dependencies": { "array-buffer-byte-length": "^1.0.2", "arraybuffer.prototype.slice": "^1.0.4", "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "data-view-buffer": "^1.0.2", "data-view-byte-length": "^1.0.2", "data-view-byte-offset": "^1.0.1", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "es-set-tostringtag": "^2.1.0", "es-to-primitive": "^1.3.0", "function.prototype.name": "^1.1.8", "get-intrinsic": "^1.3.0", "get-proto": "^1.0.1", "get-symbol-description": "^1.1.0", "globalthis": "^1.0.4", "gopd": "^1.2.0", "has-property-descriptors": "^1.0.2", "has-proto": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "internal-slot": "^1.1.0", "is-array-buffer": "^3.0.5", "is-callable": "^1.2.7", "is-data-view": "^1.0.2", "is-negative-zero": "^2.0.3", "is-regex": "^1.2.1", "is-set": "^2.0.3", "is-shared-array-buffer": "^1.0.4", "is-string": "^1.1.1", "is-typed-array": "^1.1.15", "is-weakref": "^1.1.1", "math-intrinsics": "^1.1.0", "object-inspect": "^1.13.4", "object-keys": "^1.1.1", "object.assign": "^4.1.7", "own-keys": "^1.0.1", "regexp.prototype.flags": "^1.5.4", "safe-array-concat": "^1.1.3", "safe-push-apply": "^1.0.0", "safe-regex-test": "^1.1.0", "set-proto": "^1.0.0", "stop-iteration-iterator": "^1.1.0", "string.prototype.trim": "^1.2.10", "string.prototype.trimend": "^1.0.9", "string.prototype.trimstart": "^1.0.8", "typed-array-buffer": "^1.0.3", "typed-array-byte-length": "^1.0.3", "typed-array-byte-offset": "^1.0.4", "typed-array-length": "^1.0.7", "unbox-primitive": "^1.1.0", "which-typed-array": "^1.1.19" } }, "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg=="], @@ -3156,7 +3153,7 @@ "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], - "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], + "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], @@ -3176,6 +3173,8 @@ "escape-goat": ["escape-goat@4.0.0", "", {}, "sha512-2Sd4ShcWxbx6OY1IHyla/CVNwvg7XwZVoXZHcSu9w9SReNP1EzzD5T8NWKIR38fIqEns9kDWKUQTXXAmlDrdPg=="], + "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], "esm-env": ["esm-env@1.2.2", "", {}, "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA=="], @@ -3200,6 +3199,8 @@ "eta": ["eta@4.6.0", "", {}, "sha512-lW6is4T1NFOYnmqGZIfvixqj7A7sSvScF+DN8EK6K58xI5MZ5UvYe0GjopxOXQtZvUn4eDdVuZ8XSoYWTMEKwA=="], + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], @@ -3210,12 +3211,16 @@ "exit-hook": ["exit-hook@2.2.1", "", {}, "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw=="], - "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], - "exponential-backoff": ["exponential-backoff@3.1.3", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="], + "express": ["express@5.3.0", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", "content-disposition": "^2.0.1", "content-type": "^2.0.0", "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.8", "qs": "^6.16.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.1.0", "vary": "^1.1.2" } }, "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g=="], + + "express-rate-limit": ["express-rate-limit@8.7.1", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA=="], + "expressive-code": ["expressive-code@0.44.2", "", { "dependencies": { "@expressive-code/core": "^0.44.2", "@expressive-code/plugin-frames": "^0.44.2", "@expressive-code/plugin-shiki": "^0.44.2", "@expressive-code/plugin-text-markers": "^0.44.2" } }, "sha512-MLNghkvhyFgVW4oCD5DxBuYnnTXIf0PygzGmfT6OZeOOYWh/D4sH1j931biElkA5RG/J9wY/iuSMGAPF5vzHOg=="], + "exsolve": ["exsolve@1.1.3", "", {}, "sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA=="], + "ext-list": ["ext-list@2.2.2", "", { "dependencies": { "mime-db": "^1.28.0" } }, "sha512-u+SQgsubraE6zItfVA0tBuCBhfU9ogSRnsvygI7wht9TS510oLkBRXBsqopeUG/GBOIQyKZO9wjTqIu/sf5zFA=="], "ext-name": ["ext-name@5.0.0", "", { "dependencies": { "ext-list": "^2.0.0", "sort-keys-length": "^1.0.0" } }, "sha512-yblEwXAbGv1VQDmow7s38W77hzAgJAO50ztBLMcUyUBfxv1HC+LGwtiEN+Co6LtlqT/5uwVOxsD4TNIilWhwdQ=="], @@ -3232,6 +3237,8 @@ "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + "fast-sha256": ["fast-sha256@1.3.0", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="], + "fast-string-truncated-width": ["fast-string-truncated-width@3.0.3", "", {}, "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g=="], "fast-string-width": ["fast-string-width@3.0.2", "", { "dependencies": { "fast-string-truncated-width": "^3.0.2" } }, "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg=="], @@ -3252,6 +3259,8 @@ "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + "find-babel-config": ["find-babel-config@2.1.2", "", { "dependencies": { "json5": "^2.2.3" } }, "sha512-ZfZp1rQyp4gyuxqt1ZqjFGVeVBvmpURMqdIWXbPRfB97Bf6BzdK/xSIbylEINzQ0kB5tlDQfn9HkNXXWsqTqLg=="], "find-proc": ["find-proc@0.2.0", "", {}, "sha512-a6h2nTrgB3g5Wrn4au9Ux4kMk7IJtyF6oA8uGn+mk3weLZssUtc1cp6meHIzzuW2o1srrBAxzkmXLbqjRkgB6w=="], @@ -3276,6 +3285,10 @@ "formdata-polyfill": ["formdata-polyfill@4.0.10", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="], + "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], + + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + "fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="], "fs-minipass": ["fs-minipass@3.0.3", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw=="], @@ -3350,7 +3363,7 @@ "gtoken": ["gtoken@8.0.0", "", { "dependencies": { "gaxios": "^7.0.0", "jws": "^4.0.0" } }, "sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw=="], - "h3": ["h3@2.0.1-rc.4", "", { "dependencies": { "rou3": "^0.7.8", "srvx": "^0.9.1" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"] }, "sha512-vZq8pEUp6THsXKXrUXX44eOqfChic2wVQ1GlSzQCBr7DeFBkfIZAo2WyNND4GSv54TAa0E4LYIK73WSPdgKUgw=="], + "h3": ["h3@2.0.7", "", { "dependencies": { "rou3": "^1.0.0", "srvx": "^1.0.6" }, "peerDependencies": { "crossws": "^0.4.12", "ocache": ">=0.3.0" }, "optionalPeers": ["crossws", "ocache"], "bin": { "h3": "./bin/h3.mjs" } }, "sha512-00SVloxtViij9/JBsc/Ayd9H7GLXWB0KRfkReWG0dDwuUFKUKRrNGM3Csu+KZgppi5DD8Y1KpnfjtudWaRCoiQ=="], "happy-dom": ["happy-dom@20.11.1", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-XSt8tMzbW9ymE7687xztkO1ckR7qJNQ3LywY9vlYGhGi3zXrGBHuUo2Cl1ztZaICW+1eAGdkLbj6iwVqDT33kg=="], @@ -3414,6 +3427,8 @@ "hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="], + "hookable": ["hookable@6.1.2", "", {}, "sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg=="], + "hosted-git-info": ["hosted-git-info@4.1.0", "", { "dependencies": { "lru-cache": "^6.0.0" } }, "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA=="], "html-entities": ["html-entities@2.3.3", "", {}, "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA=="], @@ -3430,6 +3445,8 @@ "http-cache-semantics": ["http-cache-semantics@4.3.0", "", {}, "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA=="], + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + "http-link-header": ["http-link-header@1.1.4", "", {}, "sha512-xT3GPW6/ZbGuw4UvwHqErSCEjNUlwbQJuZn9/q5U4WEKfp2kENVCAlousG1zLxHeaQ/ffOHUNpWamvkbBW0eNw=="], "http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], @@ -3438,6 +3455,8 @@ "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "httpxy": ["httpxy@0.5.5", "", {}, "sha512-uDjmnPyp1q4Sgzf3w+J/Fc6UqcCEj0x4Wjp7OqK5dGhNeDgpyrAmnS6ey8QWrX3SWDon2DMKf9sBa5X9+CVyMA=="], + "humanize-ms": ["humanize-ms@1.2.1", "", { "dependencies": { "ms": "^2.0.0" } }, "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ=="], "husky": ["husky@9.1.7", "", { "bin": { "husky": "bin.js" } }, "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA=="], @@ -3474,6 +3493,8 @@ "ip-address": ["ip-address@10.7.4", "", {}, "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg=="], + "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + "iron-webcrypto": ["iron-webcrypto@1.2.1", "", {}, "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg=="], "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], @@ -3536,6 +3557,8 @@ "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + "is-regex": ["is-regex@1.2.1", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="], "is-regexp": ["is-regexp@1.0.0", "", {}, "sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA=="], @@ -3604,6 +3627,8 @@ "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], + "json-stringify-nice": ["json-stringify-nice@1.1.4", "", {}, "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw=="], "json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="], @@ -3766,8 +3791,12 @@ "mdurl": ["mdurl@1.0.1", "", {}, "sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g=="], + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], + "merge-anything": ["merge-anything@5.1.7", "", { "dependencies": { "is-what": "^4.1.8" } }, "sha512-eRtbOb1N5iyH0tkQDAoQ4Ipsp/5qSR79Dzrz8hEPxRX10RWWR/iQXdoKmBSRCThY1Fh5EhISDtpSc93fpxUniQ=="], + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], + "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], "micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="], @@ -3898,9 +3927,9 @@ "neotraverse": ["neotraverse@1.0.1", "", {}, "sha512-WmmLty1YWwJl9yZi77v2dVIV6X2kuYV8YYBI/G3LWGKdGHmHUvL1z7FW0iDvEvGAwNEoc5x1tOOOyDnf5jJw/w=="], - "nf3": ["nf3@0.1.12", "", {}, "sha512-qbMXT7RTGh74MYWPeqTIED8nDW70NXOULVHpdWcdZ7IVHVnAsMV9fNugSNnvooipDc1FMOzpis7T9nXJEbJhvQ=="], + "nf3": ["nf3@0.3.24", "", {}, "sha512-HxLK4bo+5jNsEETZp4w3tJblHOA9MCBY14IN9nZJJV8JDxt9yNIYxuBuLMjTAR5GFa3HL61+8VQDUrXv3/C8fw=="], - "nitro": ["nitro@3.0.1-alpha.1", "", { "dependencies": { "consola": "^3.4.2", "crossws": "^0.4.1", "db0": "^0.3.4", "h3": "2.0.1-rc.5", "jiti": "^2.6.1", "nf3": "^0.1.10", "ofetch": "^2.0.0-alpha.3", "ohash": "^2.0.11", "oxc-minify": "^0.96.0", "oxc-transform": "^0.96.0", "srvx": "^0.9.5", "undici": "^7.16.0", "unenv": "^2.0.0-rc.24", "unstorage": "^2.0.0-alpha.4" }, "peerDependencies": { "rolldown": "*", "rollup": "^4", "vite": "^7", "xml2js": "^0.6.2" }, "optionalPeers": ["rolldown", "rollup", "vite", "xml2js"], "bin": { "nitro": "dist/cli/index.mjs" } }, "sha512-U4AxIsXxdkxzkFrK0XAw0e5Qbojk8jQ50MjjRBtBakC4HurTtQoiZvF+lSe382jhuQZCfAyywGWOFa9QzXLFaw=="], + "nitro": ["nitro@3.0.260903-beta", "", { "dependencies": { "consola": "^3.4.2", "crossws": "^0.4.12", "db0": "^0.4.1", "env-runner": "^0.2.1", "h3": "^2.0.1-rc.31", "hookable": "^6.1.1", "nf3": "^0.3.24", "ocache": "^0.3.0", "rolldown": "^1.2.7", "rou3": "^0.9.2", "srvx": "^1.0.3", "unenv": "^2.0.0-rc.24", "unstorage": "^2.0.0-alpha.10" }, "bin": { "nitro": "dist/cli/index.mjs" } }, "sha512-54gANPi62O8rfMvepiJUVuIzEIinYfpeHbebywlLxvVTgIYXDwSvpaU9Id+0sJOBjBx0wC1/CVYXJkH7SY+l0g=="], "nlcst-to-string": ["nlcst-to-string@4.0.0", "", { "dependencies": { "@types/nlcst": "^2.0.0" } }, "sha512-YKLBCcUYKAg0FNlOBT6aI91qFmSiFKiluk655WzPF+DDMA02qIyy8uiRqI8QXtcFpEvll12LpL5MXqEmAZ+dcA=="], @@ -3950,6 +3979,8 @@ "number-flow": ["number-flow@0.6.2", "", { "dependencies": { "esm-env": "^1.1.4" } }, "sha512-MCnImG4Q5vPwhSXnov56nOuyyKn6LC+Qd7II1UiKc+ACRtug5iAtn0+CwXNxM38AC5lSowEY+oYEtZX2qMnUyw=="], + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + "object-hash": ["object-hash@2.2.0", "", {}, "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw=="], "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], @@ -3960,12 +3991,16 @@ "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], - "ofetch": ["ofetch@2.0.0-alpha.3", "", {}, "sha512-zpYTCs2byOuft65vI3z43Dd6iSdFbOZZLb9/d21aCpx2rGastVU9dOCv0lu4ykc1Ur1anAYjDi3SUvR0vq50JA=="], + "ocache": ["ocache@0.3.1", "", {}, "sha512-qeBrhQ0ly6tgXsakgNwLx6diRUppJZIcV5OjVGa5yp9HzztutkaGDDXJqVMo1fKWz5fNDtTp3iPU2fuhHf0+Lg=="], + + "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=="], "ohash": ["ohash@2.0.12", "", {}, "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw=="], "oidc-token-hash": ["oidc-token-hash@5.2.0", "", {}, "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw=="], + "on-finished": ["on-finished@2.4.2", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ=="], + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], "oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="], @@ -3980,9 +4015,7 @@ "own-keys": ["own-keys@1.0.2", "", { "dependencies": { "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "object-keys": "^1.1.1", "safe-push-apply": "^1.0.0" } }, "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg=="], - "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-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=="], + "oxc-parser": ["oxc-parser@0.141.0", "", { "dependencies": { "@oxc-project/types": "^0.141.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.141.0", "@oxc-parser/binding-android-arm64": "0.141.0", "@oxc-parser/binding-darwin-arm64": "0.141.0", "@oxc-parser/binding-darwin-x64": "0.141.0", "@oxc-parser/binding-freebsd-x64": "0.141.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.141.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.141.0", "@oxc-parser/binding-linux-arm64-gnu": "0.141.0", "@oxc-parser/binding-linux-arm64-musl": "0.141.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.141.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.141.0", "@oxc-parser/binding-linux-riscv64-musl": "0.141.0", "@oxc-parser/binding-linux-s390x-gnu": "0.141.0", "@oxc-parser/binding-linux-x64-gnu": "0.141.0", "@oxc-parser/binding-linux-x64-musl": "0.141.0", "@oxc-parser/binding-openharmony-arm64": "0.141.0", "@oxc-parser/binding-wasm32-wasi": "0.141.0", "@oxc-parser/binding-win32-arm64-msvc": "0.141.0", "@oxc-parser/binding-win32-ia32-msvc": "0.141.0", "@oxc-parser/binding-win32-x64-msvc": "0.141.0" } }, "sha512-uFkGGr1KMWd6aWv9UAqooYrN78trw8MWWmoPvgWokfBEUq1+eiIQ+qfj3wokhy0fxtZWZk+0dHoS7/yRTJtd6w=="], "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=="], @@ -4016,6 +4049,8 @@ "parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + "path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="], "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], @@ -4096,6 +4131,8 @@ "property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="], + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], + "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], @@ -4112,12 +4149,18 @@ "qr-scanner": ["qr-scanner@1.4.2", "", { "dependencies": { "@types/offscreencanvas": "^2019.6.4" } }, "sha512-kV1yQUe2FENvn59tMZW6mOVfpq9mGxGf8l6+EGaXUOd4RBOLg7tRC83OrirM5AtDvZRpdjdlXURsHreAOSPOUw=="], + "qs": ["qs@6.16.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg=="], + "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], "quick-lru": ["quick-lru@5.1.1", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="], "radix3": ["radix3@1.1.2", "", {}, "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA=="], + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], + + "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=="], + "react": ["react@19.2.8", "", {}, "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw=="], "react-dom": ["react-dom@19.2.8", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.8" } }, "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ=="], @@ -4234,7 +4277,9 @@ "rollup": ["rollup@4.62.4", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.62.4", "@rollup/rollup-android-arm64": "4.62.4", "@rollup/rollup-darwin-arm64": "4.62.4", "@rollup/rollup-darwin-x64": "4.62.4", "@rollup/rollup-freebsd-arm64": "4.62.4", "@rollup/rollup-freebsd-x64": "4.62.4", "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", "@rollup/rollup-linux-arm-musleabihf": "4.62.4", "@rollup/rollup-linux-arm64-gnu": "4.62.4", "@rollup/rollup-linux-arm64-musl": "4.62.4", "@rollup/rollup-linux-loong64-gnu": "4.62.4", "@rollup/rollup-linux-loong64-musl": "4.62.4", "@rollup/rollup-linux-ppc64-gnu": "4.62.4", "@rollup/rollup-linux-ppc64-musl": "4.62.4", "@rollup/rollup-linux-riscv64-gnu": "4.62.4", "@rollup/rollup-linux-riscv64-musl": "4.62.4", "@rollup/rollup-linux-s390x-gnu": "4.62.4", "@rollup/rollup-linux-x64-gnu": "4.62.4", "@rollup/rollup-linux-x64-musl": "4.62.4", "@rollup/rollup-openbsd-x64": "4.62.4", "@rollup/rollup-openharmony-arm64": "4.62.4", "@rollup/rollup-win32-arm64-msvc": "4.62.4", "@rollup/rollup-win32-ia32-msvc": "4.62.4", "@rollup/rollup-win32-x64-gnu": "4.62.4", "@rollup/rollup-win32-x64-msvc": "4.62.4", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg=="], - "rou3": ["rou3@0.7.12", "", {}, "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg=="], + "rou3": ["rou3@0.9.2", "", {}, "sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ=="], + + "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], "run-applescript": ["run-applescript@7.1.0", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="], @@ -4266,6 +4311,8 @@ "semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="], + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + "serialize-error": ["serialize-error@7.0.1", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="], "serialize-javascript": ["serialize-javascript@7.1.0", "", {}, "sha512-RNEqWOyhhUQYN9V1GfHwu9AR/g+NTciH6Z5u3/no6X3/w+04J2lVDL+svFQVXgXrEGBMG2puMVN3gq2SNGuTGw=="], @@ -4274,12 +4321,16 @@ "seroval-plugins": ["seroval-plugins@1.6.11", "", { "peerDependencies": { "seroval": "^1.0" } }, "sha512-LmB3nd8pL39jKHKvnpTUjcjBtNwR8MLty/ydAR8qbfXt5j6/6KqR1atuw8cVmD2/lDxAkvAwq5tI/HsisD9Fqg=="], + "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=="], + "set-function-length": ["set-function-length@1.2.2", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="], "set-function-name": ["set-function-name@2.0.2", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "functions-have-names": "^1.2.3", "has-property-descriptors": "^1.0.2" } }, "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ=="], "set-proto": ["set-proto@1.0.0", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0" } }, "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw=="], + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], @@ -4296,8 +4347,6 @@ "side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="], - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], - "signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], "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=="], @@ -4368,7 +4417,7 @@ "sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], - "srvx": ["srvx@0.9.8", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-RZaxTKJEE/14HYn8COLuUOJAt0U55N9l1Xf6jj+T0GoA01EUH1Xz5JtSUOI+EHn+AEgPCVn7gk6jHJffrr06fQ=="], + "srvx": ["srvx@0.12.8", "", { "bin": { "srvx": "./bin/srvx.mjs" } }, "sha512-7k9HoDhluTlD7UJ+F+OopZoPZXB2J8f/5nW2VMLaB8KsSlZlRQxyyoX0hWEQCxB+F+3ZvB5QX3LqB6xSBRfxQQ=="], "ssri": ["ssri@13.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ=="], @@ -4390,13 +4439,11 @@ "sst-win32-x86": ["sst-win32-x86@4.13.1", "", { "os": "win32", "cpu": "none" }, "sha512-YPxBVdac/MsrzwlC6pF0NrrvMcmfdBLYjv7MbzHc5jNh1FQ1WPh6bdWQqgv0KD9EQTNLLEkej0beydgUvcCWJg=="], - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "stackframe": ["stackframe@1.3.4", "", {}, "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw=="], + "standardwebhooks": ["standardwebhooks@1.1.1", "", { "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ=="], "stat-mode": ["stat-mode@1.0.0", "", {}, "sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg=="], - "std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="], + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], "stop-iteration-iterator": ["stop-iteration-iterator@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "internal-slot": "^1.1.0" } }, "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ=="], @@ -4460,7 +4507,7 @@ "tempy": ["tempy@0.6.0", "", { "dependencies": { "is-stream": "^2.0.0", "temp-dir": "^2.0.0", "type-fest": "^0.16.0", "unique-string": "^2.0.0" } }, "sha512-G13vtMYPT/J8A4X2SjdtBTphZlrp1gKv6hZiOjw14RCWg6GbHuQBGtjlx75xLbYV/wEc0D7G5K4rxKP/cXk8Bw=="], - "terracotta": ["terracotta@1.1.1", "", { "dependencies": { "solid-use": "^0.9.1" }, "peerDependencies": { "solid-js": "^1.8" } }, "sha512-Sa6wnvkGMFmPq8N/wQb2aKkIW2eXH0LJvUOEk6QZLBEjqy+LsbzAOpDuqEfOmfA/hexssE6eQve2i1IIOeOh4g=="], + "terracotta": ["terracotta@1.3.1", "", { "dependencies": { "solid-use": "^0.9.1" }, "peerDependencies": { "solid-js": "^1.8" } }, "sha512-8HNvzQbgp2KiK8CiaQayhEQrjW97n9K1Exfj2+TMLVrHTmGXBJ61QypXlGa+xf5Gc7gzrAIysnmy/7qkUyN8Ow=="], "terser": ["terser@5.50.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-CN9BVxWhgS/hRxtUMjtC2uRWSTcSfQFHMDWma6sKKfIivCD91sM+FOPfvwoaRMqCSrUpe1nv3jDamd9eEQ4y+w=="], @@ -4470,20 +4517,14 @@ "tiny-inflate": ["tiny-inflate@1.0.3", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="], - "tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="], - "tiny-typed-emitter": ["tiny-typed-emitter@2.1.0", "", {}, "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA=="], - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], - "tinyclip": ["tinyclip@1.0.3", "", {}, "sha512-nTv2raKFMzGG6JJp0lpNDsRPdfFE6UHlu2rVEjXo8vkx1ZS3LW2CVXqIaLu8xZlu+6tbFs9V58Qc/Jmk/Ii7wA=="], "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - "tinyrainbow": ["tinyrainbow@3.1.1", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="], - "tldts-core": ["tldts-core@7.4.11", "", {}, "sha512-CW3WN2rIIE/Of21mulhgnGOwoDyEFNygyIBOONSdyAuSATgMMUCpLeUlB+E8sAwA5xRV9hYPl+kyZ9citHCaKg=="], "tldts-icann": ["tldts-icann@7.4.11", "", { "dependencies": { "tldts-core": "^7.4.11" } }, "sha512-1p+NDJ7FUYCliESmsQl9EW5Um8JIyFheiy6Y6ZoHho27d+TLAGFa0gMf1VOVy02vNY1aQo6xeKiaGj45+7P+PA=="], @@ -4496,6 +4537,8 @@ "toad-cache": ["toad-cache@3.7.4", "", {}, "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg=="], + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + "toolbeam-docs-theme": ["toolbeam-docs-theme@0.4.8", "", { "peerDependencies": { "@astrojs/starlight": "^0.34.3", "astro": "^5.7.13" } }, "sha512-b+5ynEFp4Woe5a22hzNQm42lD23t13ZMihVxHbzjA50zdcM9aOSJTIjdJ0PDSd4/50HbBXcpHiQsz6rM4N88ww=="], "tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], @@ -4520,6 +4563,8 @@ "type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="], + "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=="], + "typed-array-buffer": ["typed-array-buffer@1.0.3", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-typed-array": "^1.1.14" } }, "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw=="], "typed-array-byte-length": ["typed-array-byte-length@1.0.3", "", { "dependencies": { "call-bind": "^1.0.8", "for-each": "^0.3.3", "gopd": "^1.2.0", "has-proto": "^1.2.0", "is-typed-array": "^1.1.14" } }, "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg=="], @@ -4590,7 +4635,9 @@ "universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], - "unstorage": ["unstorage@2.0.0-alpha.7", "", { "peerDependencies": { "@azure/app-configuration": "^1.11.0", "@azure/cosmos": "^4.9.1", "@azure/data-tables": "^13.3.2", "@azure/identity": "^4.13.0", "@azure/keyvault-secrets": "^4.10.0", "@azure/storage-blob": "^12.31.0", "@capacitor/preferences": "^6 || ^7 || ^8", "@deno/kv": ">=0.13.0", "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0", "@planetscale/database": "^1.19.0", "@upstash/redis": "^1.36.2", "@vercel/blob": ">=0.27.3", "@vercel/functions": "^2.2.12 || ^3.0.0", "@vercel/kv": "^1.0.1", "aws4fetch": "^1.0.20", "chokidar": "^4 || ^5", "db0": ">=0.3.4", "idb-keyval": "^6.2.2", "ioredis": "^5.9.3", "lru-cache": "^11.2.6", "mongodb": "^6 || ^7", "ofetch": "*", "uploadthing": "^7.7.4" }, "optionalPeers": ["@azure/app-configuration", "@azure/cosmos", "@azure/data-tables", "@azure/identity", "@azure/keyvault-secrets", "@azure/storage-blob", "@capacitor/preferences", "@deno/kv", "@netlify/blobs", "@planetscale/database", "@upstash/redis", "@vercel/blob", "@vercel/functions", "@vercel/kv", "aws4fetch", "chokidar", "db0", "idb-keyval", "ioredis", "lru-cache", "mongodb", "ofetch", "uploadthing"] }, "sha512-ELPztchk2zgFJnakyodVY3vJWGW9jy//keJ32IOJVGUMyaPydwcA1FtVvWqT0TNRch9H+cMNEGllfVFfScImog=="], + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + + "unstorage": ["unstorage@2.0.0-beta.0", "", {}, "sha512-VeTY+zQ3ozrNtIFBRQRuSwanHdpuRH+4t/ZzchZIVQO8/oKq2xl7fJ9c+z76tWJDW/BEXSEuzpHOxqoAl6B64A=="], "unused-filename": ["unused-filename@4.0.1", "", { "dependencies": { "escape-string-regexp": "^5.0.0", "path-exists": "^5.0.0" } }, "sha512-ZX6U1J04K1FoSUeoX1OicAhw4d0aro2qo+L8RhJkiGTNtBNkd/Fi1Wxoc9HzcVu6HfOzm0si/N15JjxFmD1z6A=="], @@ -4608,6 +4655,8 @@ "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + "verkit": ["verkit@0.5.0", "", {}, "sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g=="], "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], @@ -4626,8 +4675,6 @@ "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.11", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "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.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "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-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="], - "volar-service-css": ["volar-service-css@0.0.71", "", { "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-wRRFt9BpjMKCazcgOh67MSjUjiWUCAh99DyYSDIOTuxaRjEtDC7PpB0k1Y1wbJIW/pVtMUSVbpPo3UGSm0Byxw=="], "volar-service-emmet": ["volar-service-emmet@0.0.71", "", { "dependencies": { "@emmetio/css-parser": "^0.4.1", "@emmetio/html-matcher": "^1.3.0", "@vscode/emmet-helper": "^2.9.3", "vscode-uri": "^3.0.8" }, "peerDependencies": { "@volar/language-service": "~2.4.0" }, "optionalPeers": ["@volar/language-service"] }, "sha512-zqjzt6bN95e3CUstBm0PBFAJnrfz0ZAARka87fart46/gNCLLuP3Vujy8V/J8HEziTFLnfkgIASLFYPUhonJcA=="], @@ -4694,8 +4741,6 @@ "which-typed-array": ["which-typed-array@1.1.22", "", { "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-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw=="], - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], - "workbox-background-sync": ["workbox-background-sync@7.4.1", "", { "dependencies": { "idb": "^7.0.1", "workbox-core": "7.4.1" } }, "sha512-HhT7KE8tOWDm02wRNshXUnUPofMlhenF2DBdUnDPOubhizzPeItkYTmAB6td1Z2cjYPa98vzEiPLEuzn5hN66g=="], "workbox-broadcast-update": ["workbox-broadcast-update@7.4.1", "", { "dependencies": { "workbox-core": "7.4.1" } }, "sha512-uAlgslKLvbQY+suirIdnBCSYrcgBhjp81Nj4l1lj/Jmj0MJO2CJERnCJjT0GFVwmReV0N+zs78K6gqd5gr9/+A=="], @@ -4772,6 +4817,8 @@ "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], "@ai-sdk/openai-compatible/@ai-sdk/provider": ["@ai-sdk/provider@3.0.8", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ=="], @@ -4780,11 +4827,15 @@ "@ai-sdk/provider-utils/undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], + "@anthropic-ai/sdk/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], + + "@astrojs/astro2tsx/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" } }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], + "@astrojs/astro2tsx/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.4", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-AJxoUD2/15ESHbvpcyjU274nsAPLuOtPHCk0vKJM5pj//Fg/B1FXNWjPnXTT9PymCYYiHo4zPj0ZomXBKhoy7g=="], - "@astrojs/compiler-binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + "@astrojs/compiler-binding-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" } }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], - "@astrojs/compiler-binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.5", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA=="], + "@astrojs/compiler-binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], "@astrojs/internal-helpers/js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], @@ -4802,8 +4853,6 @@ "@astrojs/mdx/acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], - "@astrojs/mdx/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], - "@astrojs/solid-js/vite": ["vite@8.3.4", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.29", "rolldown": "~1.2.12", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.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", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ=="], "@astrojs/starlight/@astrojs/markdown-satteri": ["@astrojs/markdown-satteri@0.3.8", "", { "dependencies": { "@astrojs/internal-helpers": "0.10.4", "@astrojs/prism": "4.0.2", "github-slugger": "^2.0.0", "satteri": "^0.10.3" } }, "sha512-n8ItpFTCmlDsVR5+rwDmehSf+jFCYLWmZiisZNGuF7xILqYhsVeBfcha4qgS2Seq3fAc9Tm58ZVrvqFQ6RQgRQ=="], @@ -4830,7 +4879,7 @@ "@bruits/satteri-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], - "@bruits/satteri-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.5", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA=="], + "@bruits/satteri-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], "@cloudflare/vite-plugin/miniflare": ["miniflare@5.20260811.1-alpha", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.2", "undici": "7.29.0", "workerd": "1.20260811.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-DtOG0BeanIxs2sH0smFvExZD89cBQwGckbHiFkRJrrNAUu3NGClZkUxqu+zy7HYfKBAgq935EMY49vIPm3JVdA=="], @@ -4880,6 +4929,8 @@ "@modelcontextprotocol/client/jose": ["jose@6.2.9", "", {}, "sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA=="], + "@modelcontextprotocol/sdk/jose": ["jose@6.2.9", "", {}, "sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA=="], + "@npmcli/arborist/hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], "@npmcli/config/ci-info": ["ci-info@4.4.0", "", {}, "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg=="], @@ -4906,14 +4957,14 @@ "@octokit/request/@octokit/types": ["@octokit/types@17.0.0", "", { "dependencies": { "@octokit/openapi-types": "^28.0.0" } }, "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q=="], + "@octokit/request/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "@octokit/request-error/@octokit/types": ["@octokit/types@17.0.0", "", { "dependencies": { "@octokit/openapi-types": "^28.0.0" } }, "sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q=="], "@opencode/cli/vite": ["vite@7.3.7", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.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-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA=="], "@opencode/cli/vite-plugin-solid": ["vite-plugin-solid@2.11.10", "", { "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" }, "optionalPeers": ["@testing-library/jest-dom"] }, "sha512-Yr1dQybmtDtDAHkii6hXuc1oVH9CPcS/Zb2jN/P36qqcrkNnVPsMTzQ06jyzFPFjj3U1IYKMVt/9ZqcwGCEbjw=="], - "@opencode/console-app/vite": ["vite@7.3.7", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.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-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA=="], - "@opencode/console-app/wrangler": ["wrangler@4.50.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.0", "@cloudflare/unenv-preset": "2.7.11", "blake3-wasm": "2.1.5", "esbuild": "0.25.4", "miniflare": "4.20251118.1", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20251118.0" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20251118.0" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-+nuZuHZxDdKmAyXOSrHlciGshCoAPiy5dM+t6mEohWm7HpXvTHmWQGUf/na9jjWlWJHCJYOWzkA1P5HBJqrIEA=="], "@opencode/gui-plugins/vite": ["vite@7.3.7", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.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-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA=="], @@ -4928,8 +4979,6 @@ "@opencode/session-ui/vite-plugin-solid": ["vite-plugin-solid@2.11.10", "", { "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" }, "optionalPeers": ["@testing-library/jest-dom"] }, "sha512-Yr1dQybmtDtDAHkii6hXuc1oVH9CPcS/Zb2jN/P36qqcrkNnVPsMTzQ06jyzFPFjj3U1IYKMVt/9ZqcwGCEbjw=="], - "@opencode/stats-app/vite": ["vite@7.3.7", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.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-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA=="], - "@opencode/stories/@tailwindcss/vite": ["@tailwindcss/vite@4.1.11", "", { "dependencies": { "@tailwindcss/node": "4.1.11", "@tailwindcss/oxide": "4.1.11", "tailwindcss": "4.1.11" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7" } }, "sha512-RHYhrR3hku0MJFRV+fN2gNbDNEh3dwKvY8XJvTxCSXeMOsCRSr+uKvDWQcbizrHgjML6ZmTE5OwMrl5wKcujCw=="], "@opencode/stories/vite": ["vite@7.3.7", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.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-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA=="], @@ -4960,7 +5009,7 @@ "@opentui/core/marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="], - "@opentui/solid/babel-preset-solid": ["babel-preset-solid@1.9.12", "", { "dependencies": { "babel-plugin-jsx-dom-expressions": "^0.40.6" }, "peerDependencies": { "@babel/core": "^7.0.0", "solid-js": "^1.9.12" }, "optionalPeers": ["solid-js"] }, "sha512-LLqnuKVDlKpyBlMPcH6qEvs/wmS9a+NczppxJ3ryS/c0O5IiSFOIBQi9GzyiGDSbcJpx4Gr87jyFTos1MyEuWg=="], + "@opentui/solid/babel-preset-solid": ["babel-preset-solid@1.9.16", "", { "dependencies": { "babel-plugin-jsx-dom-expressions": "^0.40.11" }, "peerDependencies": { "@babel/core": "^7.0.0", "solid-js": "^1.9.16" }, "optionalPeers": ["solid-js"] }, "sha512-+0h40Qk2oBfkQ4OGDBHIDtvq/XQiOnCfzjNHmMxriAr8MmdsaIbyJgqYglDs4d70sF8O08sSpx61TKdpUt3oRw=="], "@parcel/watcher/detect-libc": ["detect-libc@1.0.3", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="], @@ -4998,14 +5047,6 @@ "@solidjs/start/path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], - "@solidjs/start/seroval": ["seroval@1.5.6", "", {}, "sha512-rVQVWjjSvlINzaQPZH5JFqsqEsIWdTxY3iJZCnTL/5gQbXIRooVZKI60tVCkOVfzcRPejboxO2t0P89dg5mQaA=="], - - "@solidjs/start/seroval-plugins": ["seroval-plugins@1.5.6", "", { "peerDependencies": { "seroval": "^1.0" } }, "sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ=="], - - "@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=="], - "@tailwindcss/node/lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], @@ -5020,12 +5061,6 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], - "@tanstack/directive-functions-plugin/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], - - "@tanstack/router-utils/diff": ["diff@8.0.3", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="], - - "@tanstack/server-functions-plugin/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], - "@vscode/emmet-helper/jsonc-parser": ["jsonc-parser@2.3.1", "", {}, "sha512-H8jvkz1O50L3dMZCsLqiuB2tA7muqbSg1AtGEkN0leAqGjsUzDJir3Zwr02BhqdcITPg3ei3mZ+HjMocAknhhg=="], "anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], @@ -5066,6 +5101,8 @@ "babel-plugin-polyfill-corejs2/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "builder-util/js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], "chromium-bidi/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], @@ -5104,8 +5141,14 @@ "enquirer/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + "env-runner/srvx": ["srvx@1.0.6", "", { "bin": { "srvx": "./bin/srvx.mjs" } }, "sha512-QeTKgAhk8OSsfeq60bl3wuVs9PmBftzmk7owBInA/F1YQne+TRw0UcPymNpURldAmx8hfmM2PNNGH/zgo3GpLA=="], + "esast-util-from-js/acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], + "express/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "express/cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], + "fetch-blob/web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="], "ffi-rs/@yuuang/ffi-rs-darwin-arm64": ["@yuuang/ffi-rs-darwin-arm64@1.3.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-OueBlUFBT9IwD9pQnoYs0UszRBEySskfrEPXXfvKfGjL/DXnfn6kUheQ3oIP6sSmshVGNQUwrTCPo6feAa4QjA=="], @@ -5130,14 +5173,18 @@ "gcp-metadata/google-logging-utils": ["google-logging-utils@1.1.3", "", {}, "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA=="], + "gitlab-ai-provider/@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.71.2", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-TGNDEUuEstk/DKu0/TflXAEt+p+p/WhTlFzEnoosvbaDU2LTjm42igSdlL0VijrKpWejtOKxX0b8A7uc+XiSAQ=="], + "gitlab-ai-provider/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + "h3/rou3": ["rou3@1.0.0", "", {}, "sha512-ySeaQkSrua+ut9g+65I7FHqOFBaY8tV0FmccXItoq0q21se32Q3u4YiW7/RqXSosWgYJaaKwRHXy3BST9PeCNQ=="], + + "h3/srvx": ["srvx@1.0.6", "", { "bin": { "srvx": "./bin/srvx.mjs" } }, "sha512-QeTKgAhk8OSsfeq60bl3wuVs9PmBftzmk7owBInA/F1YQne+TRw0UcPymNpURldAmx8hfmM2PNNGH/zgo3GpLA=="], + "hosted-git-info/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], "htmlparser2/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], - "import-in-the-middle/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], - "is-inside-container/is-docker": ["is-docker@3.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="], "is-wsl/is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], @@ -5160,9 +5207,9 @@ "minipass-pipeline/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], - "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=="], + "nitro/rolldown": ["rolldown@1.2.14", "", { "dependencies": { "@oxc-project/types": "=0.154.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.14", "@rolldown/binding-android-arm64": "1.2.14", "@rolldown/binding-darwin-arm64": "1.2.14", "@rolldown/binding-darwin-x64": "1.2.14", "@rolldown/binding-freebsd-x64": "1.2.14", "@rolldown/binding-linux-arm-gnueabihf": "1.2.14", "@rolldown/binding-linux-arm64-gnu": "1.2.14", "@rolldown/binding-linux-arm64-musl": "1.2.14", "@rolldown/binding-linux-ppc64-gnu": "1.2.14", "@rolldown/binding-linux-s390x-gnu": "1.2.14", "@rolldown/binding-linux-x64-gnu": "1.2.14", "@rolldown/binding-linux-x64-musl": "1.2.14", "@rolldown/binding-openharmony-arm64": "1.2.14", "@rolldown/binding-win32-arm64-msvc": "1.2.14", "@rolldown/binding-win32-x64-msvc": "1.2.14" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw=="], - "nitro/undici": ["undici@7.30.1", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="], + "nitro/srvx": ["srvx@1.0.6", "", { "bin": { "srvx": "./bin/srvx.mjs" } }, "sha512-QeTKgAhk8OSsfeq60bl3wuVs9PmBftzmk7owBInA/F1YQne+TRw0UcPymNpURldAmx8hfmM2PNNGH/zgo3GpLA=="], "node-gyp/undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], @@ -5174,6 +5221,8 @@ "openid-client/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], + "oxc-parser/@oxc-project/types": ["@oxc-project/types@0.141.0", "", {}, "sha512-S4as7z0j0xQkXcJlyY5ehntwK8/wRkQb9Cyqw+J/N2rkWGQGK0SxD6X6DhQTc7qsxVTBxXbxZtBJh3mr3PtIzQ=="], + "p-locate/p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], @@ -5200,6 +5249,8 @@ "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=="], + "safe-array-concat/isarray": ["isarray@2.0.5", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="], "safe-push-apply/isarray": ["isarray@2.0.5", "", {}, "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="], @@ -5240,6 +5291,8 @@ "tiny-async-pool/semver": ["semver@5.7.2", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="], + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "unused-filename/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], "unused-filename/path-exists": ["path-exists@5.0.0", "", {}, "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ=="], @@ -5252,12 +5305,6 @@ "vite-plugin-icons-spritesheet/tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], - "vitest/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], - - "vitest/obug": ["obug@2.1.4", "", {}, "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA=="], - - "vitest/tinyexec": ["tinyexec@1.3.0", "", {}, "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ=="], - "vscode-languageserver/vscode-languageserver-protocol": ["vscode-languageserver-protocol@3.17.5", "", { "dependencies": { "vscode-jsonrpc": "8.2.0", "vscode-languageserver-types": "3.17.5" } }, "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg=="], "vscode-languageserver-protocol/vscode-jsonrpc": ["vscode-jsonrpc@9.0.1", "", {}, "sha512-rfuA6T75H6m5EkbhtEPzre9pT0HPcDI2MMy4+nPFIBks5J8JBAUHD4tRYSgaBOijIEC7SRkC1kKyXTLqbmh9jw=="], @@ -5300,6 +5347,12 @@ "youch/cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + "youch-core/error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], + + "@astrojs/astro2tsx/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + + "@astrojs/compiler-binding-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + "@astrojs/internal-helpers/js-yaml/argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], "@astrojs/markdown-remark/@astrojs/internal-helpers/yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], @@ -5344,8 +5397,6 @@ "@babel/helper-compilation-targets/lru-cache/yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], - "@bruits/satteri-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], - "@cloudflare/vite-plugin/miniflare/sharp": ["sharp@0.35.2", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.4" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.2", "@img/sharp-darwin-x64": "0.35.2", "@img/sharp-freebsd-wasm32": "0.35.2", "@img/sharp-libvips-darwin-arm64": "1.3.1", "@img/sharp-libvips-darwin-x64": "1.3.1", "@img/sharp-libvips-linux-arm": "1.3.1", "@img/sharp-libvips-linux-arm64": "1.3.1", "@img/sharp-libvips-linux-ppc64": "1.3.1", "@img/sharp-libvips-linux-riscv64": "1.3.1", "@img/sharp-libvips-linux-s390x": "1.3.1", "@img/sharp-libvips-linux-x64": "1.3.1", "@img/sharp-libvips-linuxmusl-arm64": "1.3.1", "@img/sharp-libvips-linuxmusl-x64": "1.3.1", "@img/sharp-linux-arm": "0.35.2", "@img/sharp-linux-arm64": "0.35.2", "@img/sharp-linux-ppc64": "0.35.2", "@img/sharp-linux-riscv64": "0.35.2", "@img/sharp-linux-s390x": "0.35.2", "@img/sharp-linux-x64": "0.35.2", "@img/sharp-linuxmusl-arm64": "0.35.2", "@img/sharp-linuxmusl-x64": "0.35.2", "@img/sharp-webcontainers-wasm32": "0.35.2", "@img/sharp-win32-arm64": "0.35.2", "@img/sharp-win32-ia32": "0.35.2", "@img/sharp-win32-x64": "0.35.2" } }, "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w=="], "@cloudflare/vite-plugin/miniflare/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="], @@ -5422,6 +5473,8 @@ "@opentelemetry/instrumentation/@opentelemetry/api-logs/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], + "@opentui/solid/babel-preset-solid/babel-plugin-jsx-dom-expressions": ["babel-plugin-jsx-dom-expressions@0.40.11", "", { "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-k7TkOv7uVYnrq/bYyVvG5cWOC9IObAGfmyW3aMkG8l2sq2qt/5THkUBja69PMLEGGi8G+fXB2Fh7eS4OwZRBoQ=="], + "@puppeteer/browsers/yargs/cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="], "@puppeteer/browsers/yargs/string-width": ["string-width@8.2.2", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg=="], @@ -5436,18 +5489,6 @@ "@sentry/node/@opentelemetry/sdk-trace-base/@opentelemetry/resources": ["@opentelemetry/resources@2.11.0", "", { "dependencies": { "@opentelemetry/core": "2.11.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA=="], - "@solidjs/start/shiki/@shikijs/core": ["@shikijs/core@1.29.2", "", { "dependencies": { "@shikijs/engine-javascript": "1.29.2", "@shikijs/engine-oniguruma": "1.29.2", "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.4" } }, "sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ=="], - - "@solidjs/start/shiki/@shikijs/engine-javascript": ["@shikijs/engine-javascript@1.29.2", "", { "dependencies": { "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1", "oniguruma-to-es": "^2.2.0" } }, "sha512-iNEZv4IrLYPv64Q6k7EPpOCE/nuvGiKl7zxdq0WFuRPF5PAE9PRo2JGq/d8crLusM59BRemJ4eOqrFrC4wiQ+A=="], - - "@solidjs/start/shiki/@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@1.29.2", "", { "dependencies": { "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1" } }, "sha512-7iiOx3SG8+g1MnlzZVDYiaeHe7Ez2Kf2HrJzdmGwkRisT7r4rak0e655AcM/tF9JG/kg5fMNYlLLKglbN7gBqA=="], - - "@solidjs/start/shiki/@shikijs/langs": ["@shikijs/langs@1.29.2", "", { "dependencies": { "@shikijs/types": "1.29.2" } }, "sha512-FIBA7N3LZ+223U7cJDUYd5shmciFQlYkFXlkKVaHsCPgfVLiO+e12FmQE6Tf9vuyEsFe3dIl8qGWKXgEHL9wmQ=="], - - "@solidjs/start/shiki/@shikijs/themes": ["@shikijs/themes@1.29.2", "", { "dependencies": { "@shikijs/types": "1.29.2" } }, "sha512-i9TNZlsq4uoyqSbluIcZkmPL9Bfi3djVxRnofUHwvx/h6SRW3cwgBC5SML7vsDcWyukY0eCzVN980rqP6qNl9g=="], - - "@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=="], - "@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="], "@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="], @@ -5518,8 +5559,6 @@ "astro/unstorage/h3": ["h3@1.15.11", "", { "dependencies": { "cookie-es": "^1.2.3", "crossws": "^0.3.5", "defu": "^6.1.6", "destr": "^2.0.5", "iron-webcrypto": "^1.2.1", "node-mock-http": "^1.0.4", "radix3": "^1.1.2", "ufo": "^1.6.3", "uncrypto": "^0.1.3" } }, "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg=="], - "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=="], - "astro/vite/postcss": ["postcss@8.5.31", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="], "babel-plugin-module-resolver/glob/minimatch": ["minimatch@8.0.7", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-V+1uQNdzybxa14e/p00HZnQNNcTjnRJjDxg2V8wtkjFctq4M7hXFws4oekyTP0Jebeq7QYtpFyOeBAjc88zvYg=="], @@ -5614,6 +5653,38 @@ "minipass-pipeline/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], + "nitro/rolldown/@oxc-project/types": ["@oxc-project/types@0.154.0", "", {}, "sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA=="], + + "nitro/rolldown/@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.14", "", { "os": "android", "cpu": "arm" }, "sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg=="], + + "nitro/rolldown/@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.14", "", { "os": "android", "cpu": "arm64" }, "sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ=="], + + "nitro/rolldown/@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw=="], + + "nitro/rolldown/@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA=="], + + "nitro/rolldown/@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.14", "", { "os": "freebsd", "cpu": "x64" }, "sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA=="], + + "nitro/rolldown/@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.14", "", { "os": "linux", "cpu": "arm" }, "sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg=="], + + "nitro/rolldown/@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.14", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ=="], + + "nitro/rolldown/@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.14", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg=="], + + "nitro/rolldown/@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.14", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q=="], + + "nitro/rolldown/@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.14", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A=="], + + "nitro/rolldown/@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.14", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg=="], + + "nitro/rolldown/@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.14", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg=="], + + "nitro/rolldown/@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.14", "", { "os": "none", "cpu": "arm64" }, "sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q=="], + + "nitro/rolldown/@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA=="], + + "nitro/rolldown/@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.14", "", { "os": "win32", "cpu": "x64" }, "sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ=="], + "node-html-parser/css-select/css-what": ["css-what@6.2.2", "", {}, "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA=="], "openid-client/lru-cache/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], @@ -5700,6 +5771,10 @@ "@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], + "@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], + + "@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="], + "@astrojs/mdx/@astrojs/internal-helpers/js-yaml/argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], "@astrojs/solid-js/vite/postcss/nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], @@ -5968,12 +6043,12 @@ "@opencode/web/@astrojs/check/yargs/yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], + "@opentui/solid/babel-preset-solid/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=="], + "@puppeteer/browsers/yargs/cliui/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=="], "@puppeteer/browsers/yargs/cliui/wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], - "@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=="], - "astro/unstorage/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], "astro/unstorage/h3/cookie-es": ["cookie-es@1.2.3", "", {}, "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw=="], @@ -6006,10 +6081,12 @@ "yargs/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], - "@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], - "@astrojs/starlight/@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], + "@astrojs/starlight/@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], + + "@astrojs/starlight/@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="], + "@cloudflare/vite-plugin/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.2", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw=="], "@cloudflare/vite-plugin/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.2", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw=="], @@ -6090,10 +6167,6 @@ "@puppeteer/browsers/yargs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], - "@solidjs/start/shiki/@shikijs/engine-javascript/oniguruma-to-es/regex": ["regex@5.1.1", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-dN5I359AVGPnwzJm2jN1k0W9LPZ+ePvoOeVMMfqIMFz53sSwXkxaJoxr50ptnsC771lK95BnTrVSZxq0b9yCGw=="], - - "@solidjs/start/shiki/@shikijs/engine-javascript/oniguruma-to-es/regex-recursion": ["regex-recursion@5.1.1", "", { "dependencies": { "regex": "^5.1.1", "regex-utilities": "^2.3.0" } }, "sha512-ae7SBCbzVNrIjgSbh7wMznPcQel1DNlDtzensnFxpiNpXt1U2ju/bHugH422r+4LAVS1FpW1YCwilmnNsjum9w=="], - "babel-plugin-module-resolver/glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], "pkg-up/find-up/locate-path/p-locate/p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], @@ -6106,8 +6179,6 @@ "temp/rimraf/glob/minimatch/brace-expansion": ["brace-expansion@1.1.21", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw=="], - "@astrojs/starlight/@astrojs/markdown-satteri/satteri/@bruits/satteri-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], - "@cloudflare/vite-plugin/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], "@cloudflare/vite-plugin/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], diff --git a/package.json b/package.json index 3fad5414c6a1..231f530de280 100644 --- a/package.json +++ b/package.json @@ -53,9 +53,9 @@ "@types/bun": "1.4.3", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", - "@opentui/core": "0.7.0", - "@opentui/keymap": "0.7.0", - "@opentui/solid": "0.7.0", + "@opentui/core": "0.8.0", + "@opentui/keymap": "0.8.0", + "@opentui/solid": "0.8.0", "@tanstack/solid-virtual": "3.13.37", "@standard-schema/spec": "1.1.0", "@kobalte/core": "0.13.13", @@ -102,7 +102,7 @@ "vite": "7.3.7", "@solidjs/meta": "0.29.4", "@solidjs/router": "1.0.0", - "@solidjs/start": "https://pkg.pr.new/@solidjs/start@dfb2020", + "@solidjs/start": "2.1.0", "@sentry/solid": "10.71.0", "@sentry/vite-plugin": "5.4.0", "solid-js": "1.9.17", @@ -149,9 +149,9 @@ "electron" ], "overrides": { - "@opentui/core": "0.7.0", - "@opentui/keymap": "0.7.0", - "@opentui/solid": "0.7.0", + "@opentui/core": "catalog:", + "@opentui/keymap": "catalog:", + "@opentui/solid": "catalog:", "@effect/platform-node-shared": "catalog:", "@types/bun": "catalog:", "@types/node": "catalog:", diff --git a/packages/ai/AGENTS.md b/packages/ai/AGENTS.md index ca85b9017645..fdc73eb52be2 100644 --- a/packages/ai/AGENTS.md +++ b/packages/ai/AGENTS.md @@ -7,6 +7,7 @@ - **One canonical model.** The Schema classes in `src/schema/` are the data model. Do not add a parallel shape or a second construction path. - **Independent of Session.** Auth, permissions, plugins, and orchestration belong in Core. `LLM.stream`/`LLM.generate` run exactly one model call. - **Reuse protocols.** Providers compose existing protocols with `Route.make(...)` instead of cloning them. +- **One API, two runtimes.** Every `LLM`, `Image` and `Decision` operation has an `ai.*` twin with the same name, overloads, input and options (plus `signal`); keep `test/promise-parity.types.ts` passing. ## Code style diff --git a/packages/ai/README.md b/packages/ai/README.md index d5ac6503d434..ef9ebbf1076d 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -1,6 +1,7 @@ # @opencode/ai -Schema-first APIs for text, images, video, speech, transcription, and decisions, built with Effect. +Schema-first APIs for text, images, and decisions, built with Effect. Video, speech, transcription, extraction, and +realtime voice are [experimental](#experimental). `@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file` and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed: @@ -55,16 +56,16 @@ Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployme `stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs. `until` is checked after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running -them. `AI.tool` takes a plain `async` execute; a throw or rejection goes back to the model as an error result, and +them. `tool` takes a plain `async` execute; a throw or rejection goes back to the model as an error result, and `signal` aborts when the loop is interrupted. -`Tool.make` from `@opencode/ai/effect` is the Effect form, with a validated `success` schema: +`tool` from `@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute: ```ts import { readFile } from "node:fs/promises" import { Schema } from "effect" -import { AI } from "@opencode/ai" +import { tool } from "@opencode/ai" -const read_file = AI.tool({ +const read_file = tool({ description: "Read a UTF-8 file.", parameters: Schema.Struct({ path: Schema.String }), execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }), @@ -87,7 +88,7 @@ A tool with exactly one required string parameter can set `freeform`, so the mod instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `lark` grammar. ```ts -const run_code = AI.tool({ +const run_code = tool({ description: "Run JavaScript", parameters: Schema.Struct({ code: Schema.String }), freeform: { type: "lark", grammar: JS_GRAMMAR }, @@ -165,8 +166,8 @@ Raw usage is preserved in `usage.providerMetadata.google`. `inputTokens` follows `contextTokens` uses its full `raw_prompt_token` count when supplied. These can differ substantially with server-side continuation. Explicit caches, hosted tools, and generated media are not supported by this initial protocol. -The same configured facade names image, video, speech, and transcription models. `Image.generate` resolves the -provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes: +The same configured facade names image models (and the experimental video, speech, and transcription models). +`Image.generate` resolves the provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes: ```ts import { NodeFileSystem } from "@effect/platform-node" @@ -309,38 +310,6 @@ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev") OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`. -### Extraction (experimental) - -Extraction models read typed values out of text instead of answering questions with probabilities. A field of type -`text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to -match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today, so it lives under -`@opencode/ai/experimental`. - -```ts -import { ai } from "@opencode/ai" -import { Extraction } from "@opencode/ai/experimental" -import { CloudflareWorkersAI } from "@opencode/ai/providers" - -const response = await ai.run( - Extraction.generate({ - model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"), - input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.", - fields: { - invoiceNumber: { type: "text" }, - dueDate: { type: "date", instructions: "Issue date plus the net payment days" }, - total: { type: "number", decimals: 2, unit: "USD" }, - contacts: { type: "list", items: "text" }, - }, - }), -) -response.answers.total.value // 1080, or null when the input does not say -``` - -Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and -forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to -Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AIClient.layer`). Images are not supported -yet. - ## Alibaba Cloud Model Studio `Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select @@ -910,7 +879,42 @@ const program = Effect.gen(function* () { The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes. -## Video generation +## Public API + +Everything below is exported from `@opencode/ai/effect` unless noted. + +- **`LLM.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes. +- **`LLM.generate` / `LLM.stream`** — run direct input or an `LLMRequest` through `LLMClient` for one-import use. +- **`LLM.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools. +- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model. +- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model. +- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams. +- **`Image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. +- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`. +- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests. +- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes. +- **`Decision.request` / `Decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer. +- **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer. +- **`@opencode/ai`** (Promise root) — `AI.make({ layer?, clients? })` and a default `ai` client exposing `llm`, `image`, and `decision` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. +- **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental). + +## Experimental + +These APIs may change without compatibility guarantees. The Effect API is exported from `@opencode/ai/experimental`, +the Promise client exposes it under `ai.experimental`, and test layers come from `@opencode/ai/experimental/testing`. + +- **`Video`**, **`Speech`**, and **`Transcription`** — media generation and speech-to-text, with `VideoClient`, + `SpeechClient`, and `TranscriptionClient` as their Effect services. Promise: `ai.experimental.video`, `.speech`, and + `.transcription`. Testing: `TestVideo`, `TestSpeech`, and `TestTranscription`. +- **`Extraction`** — typed values read out of text. +- **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or + a short-lived WebSocket URL and token. + +The provider selectors for these modalities (`.video(...)`, `.speech(...)`, `.transcription(...)`, +`.experimental.extraction(...)`) and their protocol entrypoints (such as `@opencode/ai/protocols/openai-speech`) are +part of the same experimental surface. + +### Video generation Video mirrors `Image` with one difference: every provider is asynchronous, so the route is a submit-then-poll `Generation`. Models come from `.video(...)` selectors on the `Google` (Veo), `XAI`, and `Runway` facades. @@ -919,7 +923,7 @@ Common fields (`frames`, `references`, `video`, `durationSeconds`, `aspect`, `re under `providerOptions`, inferred from the selected model. ```ts -import { Video } from "@opencode/ai/effect" +import { Video } from "@opencode/ai/experimental" import { Google, Runway } from "@opencode/ai/providers" const google = Google.configure({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY }) @@ -981,9 +985,9 @@ Provider notes: - **Runway** expects pixel ratios in `aspect` for most models (`"1280:720"`), pins `X-Runway-Version`, reports `usage: { type: "credits" }`, and its output URLs expire after 24–48 hours. -The promise client exposes the same surface: `ai.video.start(...)` resolves to a handle with `await`, `events`, -`result`, `refresh`, `cancel`, and `token`; `ai.video.generate`, `ai.video.resume(model, token)`, and -`ai.video.stream` mirror the Effect API. The handle's `status` and `progress` are a snapshot from when it was +The promise client exposes the same surface: `ai.experimental.video.start(...)` resolves to a handle with `await`, `events`, +`result`, `refresh`, `cancel`, and `token`; `ai.experimental.video.generate`, `ai.experimental.video.resume(model, token)`, and +`ai.experimental.video.stream` mirror the Effect API. The handle's `status` and `progress` are a snapshot from when it was created; `refresh()` resolves to a new handle. Every promise method and stream accepts `{ signal }`: like `fetch`, aborting rejects the Promise or throws from the `for await` loop with `signal.reason` (an `AbortError` `DOMException` unless `abort(reason)` passed one), while `break` stops a stream without throwing. @@ -991,13 +995,13 @@ unless `abort(reason)` passed one), while `break` stops a stream without throwin ```ts import { ai } from "@opencode/ai" -const generation = await ai.video.start({ model, prompt }) +const generation = await ai.experimental.video.start({ model, prompt }) for await (const event of generation.events({ poll: { interval: 10_000 } })) console.log(event.type) const video = await generation.result({ signal }) await ai.write(video.video, "./kite.mp4") ``` -## Speech generation +### Speech generation Speech (text-to-speech) is one request whose response is parsed incrementally, so every route supports both `Speech.generate` (the whole file) and `Speech.stream` (audio chunks as they arrive). Models come from `.speech(...)` @@ -1006,7 +1010,8 @@ selectors on the `OpenAI`, `Google` (Gemini TTS), `ElevenLabs`, `Cartesia`, and before any network call; provider-native controls live under `providerOptions`, inferred from the selected model. ```ts -import { Media, Speech, SpeechClient, SpeechEvent } from "@opencode/ai/effect" +import { Media } from "@opencode/ai/effect" +import { Speech, SpeechEvent } from "@opencode/ai/experimental" import { ElevenLabs, OpenAI } from "@opencode/ai/providers" const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }) @@ -1068,20 +1073,20 @@ Provider notes: and `providerOptions` lower to query parameters (`encoding`, `container`, `sample_rate`, `bit_rate`); `pcm` is `linear16` without a container. Auth is `Authorization: Token `. -The promise client mirrors the Effect API; `ai.speech.stream` is an `AsyncIterable`. +The promise client mirrors the Effect API; `ai.experimental.speech.stream` is an `AsyncIterable`. ```ts import { ai } from "@opencode/ai" -const response = await ai.speech.generate({ model, text: "Hello from OpenCode.", voice: "coral" }) +const response = await ai.experimental.speech.generate({ model, text: "Hello from OpenCode.", voice: "coral" }) await ai.write(response.audio, "hello.mp3") -for await (const event of ai.speech.stream({ model, text: "Hello from OpenCode.", voice: "coral" })) { +for await (const event of ai.experimental.speech.stream({ model, text: "Hello from OpenCode.", voice: "coral" })) { if (event.type === "audio-delta") player.write(event.chunk) } ``` -## Transcription +### Transcription Transcription (speech-to-text) is the one modality whose providers use every route kind: OpenAI and Gemini stream, Deepgram and ElevenLabs answer inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream` @@ -1093,7 +1098,8 @@ any network call; a route may return more than asked. ```ts import { Console, Effect, Stream } from "effect" -import { Media, Transcription, TranscriptionEvent } from "@opencode/ai/effect" +import { Media } from "@opencode/ai/effect" +import { Transcription, TranscriptionEvent } from "@opencode/ai/experimental" import { AssemblyAI, Deepgram, OpenAI } from "@opencode/ai/providers" const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY }) @@ -1146,33 +1152,43 @@ The promise client mirrors the Effect API: ```ts const audio = await ai.file("./call.mp3") -const text = (await ai.transcription.generate({ model, audio })).text -for await (const event of ai.transcription.stream({ model, audio })) if (event.type === "text-delta") write(event.delta) -const generation = await ai.transcription.start({ model: assemblyai, audio }) +const text = (await ai.experimental.transcription.generate({ model, audio })).text +for await (const event of ai.experimental.transcription.stream({ model, audio })) + if (event.type === "text-delta") write(event.delta) +const generation = await ai.experimental.transcription.start({ model: assemblyai, audio }) const transcript = await generation.await({ poll: { interval: 3_000 } }) ``` -## Public API +### Extraction -Everything below is exported from `@opencode/ai/effect` unless noted. +Extraction models read typed values out of text instead of answering questions with probabilities. A field of type +`text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to +match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today. -- **`LLM.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes. -- **`LLM.generate` / `LLM.stream`** — run direct input or an `LLMRequest` through `LLMClient` for one-import use. -- **`LLM.loop`** — stream model calls, running `Tool.make(...)` tools between them until the model stops calling tools. -- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model. -- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model. -- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams. -- **`Image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. -- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`. -- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests. -- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes. -- **`Video.request` / `generate` / `stream` / `start` / `resume`** — queued video generation through a provider-neutral request; `VideoClient` is its Effect service and layer. -- **`Speech.request` / `Speech.generate` / `Speech.stream`** — text-to-speech through a provider-neutral request; `SpeechClient` is its Effect service and layer. -- **`Transcription.request` / `generate` / `stream` / `start` / `resume`** — speech-to-text over inline, streaming, and queued routes; `TranscriptionClient` is its Effect service and layer. -- **`Decision.request` / `Decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer. -- **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer. -- **`@opencode/ai`** (Promise root) — `AI.make({ layer?, clients? })` and a default `ai` client exposing `llm`, `image`, `video`, `speech`, `transcription`, and `decision` as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. -- **`@opencode/ai/experimental`** — APIs that may still change: `Extraction` (typed values read out of text) and `Realtime` (`Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or a short-lived WebSocket URL and token). +```ts +import { ai } from "@opencode/ai" +import { Extraction } from "@opencode/ai/experimental" +import { CloudflareWorkersAI } from "@opencode/ai/providers" + +const response = await ai.run( + Extraction.generate({ + model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"), + input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.", + fields: { + invoiceNumber: { type: "text" }, + dueDate: { type: "date", instructions: "Issue date plus the net payment days" }, + total: { type: "number", decimals: 2, unit: "USD" }, + contacts: { type: "list", items: "text" }, + }, + }), +) +response.answers.total.value // 1080, or null when the input does not say +``` + +Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and +forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to +Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AIClient.layer`). Images are not supported +yet. ## Testing @@ -1218,7 +1234,7 @@ For explicit compaction, script a `CompactionResponse` through `push`, `always`, For `compact(request, { mechanism: "trigger" })`, script a `CompactionCheckpointResponse` instead. It carries `checkpoint`, `responseID`, and optional `usage`. Endpoint and trigger calls reject each other's fixtures; both share the same queue, gates, lazy recording, and fallback controls. -`TestImage`, `TestVideo`, `TestSpeech`, `TestTranscription`, and `TestDecision` follow the same pattern: `testLayer()` provides the modality's client and `Test`, with the same `push`, `always`, `serve`, `requests`, `wait`, and `gate` controls. Script an `ImageResponse` (or the modality's response) or an `AIError`. `stream` expands the response into its events, and `start` returns an already finished generation that `resume` accepts by token. Decision responses are returned as scripted, without checking the answers against the questions. +`TestImage` and `TestDecision` (and `TestVideo`, `TestSpeech`, and `TestTranscription` from `@opencode/ai/experimental/testing`) follow the same pattern: `testLayer()` provides the modality's client and `Test`, with the same `push`, `always`, `serve`, `requests`, `wait`, and `gate` controls. Script an `ImageResponse` (or the modality's response) or an `AIError`. `stream` expands the response into its events, and `start` returns an already finished generation that `resume` accepts by token. Decision responses are returned as scripted, without checking the answers against the questions. The Promise client accepts the same layers as `AI.make({ clients: TestImage.testLayer() })`; `ai.run(TestImage.Test.use(...))` reaches the controls. diff --git a/packages/ai/example/tutorial.ts b/packages/ai/example/tutorial.ts index 216903cf810d..ca522ca381f8 100644 --- a/packages/ai/example/tutorial.ts +++ b/packages/ai/example/tutorial.ts @@ -1,7 +1,8 @@ import { Config, Effect, Formatter, Schema, Stream } from "effect" import { HttpClientResponse } from "effect/http" import { NodeFileSystem } from "@effect/platform-node" -import { AIClient, Image, LLM, LLMRequest, Media, Message, ProviderID, Tool, ToolRuntime } from "@opencode/ai/effect" +import { AIClient, Image, LLM, LLMRequest, Media, Message, ProviderID, ToolRuntime } from "@opencode/ai/effect" +import { toDefinitions, tool } from "@opencode/ai/effect" import { Route, Auth, Endpoint, Framing, Protocol, RequestExecutor } from "@opencode/ai/route" import { OpenAI } from "@opencode/ai/providers" @@ -86,7 +87,7 @@ const streamText = LLM.stream(request).pipe( // advertise definitions on the request, stream one turn, dispatch local calls, // then persist/build follow-up history in the enclosing product flow. const tools = { - get_weather: Tool.make({ + get_weather: tool({ description: "Get current weather for a city.", parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ forecast: Schema.String }), @@ -99,7 +100,7 @@ const streamWithTools = Effect.gen(function* () { model, prompt: "Use get_weather for San Francisco, then answer in one sentence.", generation: { maxTokens: 80, temperature: 0 }, - tools: Tool.toDefinitions(tools), + tools: toDefinitions(tools), }) const events = Array.from(yield* LLM.stream(request).pipe(Stream.runCollect)) for (const event of events) { diff --git a/packages/ai/package.json b/packages/ai/package.json index 9bbb195c745d..d97ea99c21e6 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -20,6 +20,7 @@ "./effect": "./src/effect.ts", "./testing": "./src/testing.ts", "./experimental": "./src/experimental.ts", + "./experimental/testing": "./src/experimental/testing.ts", "./route": "./src/route.ts", "./providers": "./src/providers.ts", "./providers/alibaba": "./src/providers/alibaba.ts", diff --git a/packages/ai/src/decision.ts b/packages/ai/src/decision.ts index 2d1df43d39d1..6a0daa9ff4b2 100644 --- a/packages/ai/src/decision.ts +++ b/packages/ai/src/decision.ts @@ -308,7 +308,6 @@ export function request(input: DecisionRequest | DecisionRequestInput) { export function generate( input: DecisionRequestInput, ): Effect.Effect, AIError, Service> -export function generate(input: DecisionRequest): Effect.Effect export function generate(input: DecisionRequest | DecisionRequestInput) { return tryRequest(() => request(input)).pipe(Effect.flatMap(DecisionClient.generate)) } diff --git a/packages/ai/src/effect.ts b/packages/ai/src/effect.ts index be732ba346a8..3daaa60e07d0 100644 --- a/packages/ai/src/effect.ts +++ b/packages/ai/src/effect.ts @@ -116,63 +116,6 @@ export type { ImageRoute, } from "./image.js" export { Image } from "./image.js" -export { VideoClient } from "./video-client.js" -export { - VideoAspectRatio, - VideoEvent, - VideoFrames, - VideoModel, - VideoModelSchema, - VideoRequest, - VideoResponse, -} from "./video.js" -export type { - VideoModelOptions, - VideoOptions, - VideoRequestFor, - VideoRequestInput, - VideoResolution, - VideoRoute, -} from "./video.js" -export { Video } from "./video.js" -export { SpeechClient } from "./speech-client.js" -export { - SpeechEvent, - SpeechModel, - SpeechModelSchema, - SpeechRequest, - SpeechResponse, - SpeechTimestamp, - SpeechVoice, -} from "./speech.js" -export type { - SpeechFormat, - SpeechModelOptions, - SpeechOptions, - SpeechRequestFor, - SpeechRequestInput, - SpeechRoute, -} from "./speech.js" -export { Speech } from "./speech.js" -export { TranscriptionClient } from "./transcription-client.js" -export { - TranscriptionEvent, - TranscriptionModel, - TranscriptionModelSchema, - TranscriptionRequest, - TranscriptionResponse, - TranscriptionSegment, - TranscriptionTimestamps, - TranscriptionWord, -} from "./transcription.js" -export type { - TranscriptionModelOptions, - TranscriptionOptions, - TranscriptionRequestFor, - TranscriptionRequestInput, - TranscriptionRoute, -} from "./transcription.js" -export { Transcription } from "./transcription.js" export { DecisionClient } from "./decision-client.js" export { ChoiceAnswer, @@ -221,18 +164,16 @@ export type { Snapshot as GenerationSnapshot, Status as GenerationStatus, } from "./generation.js" -export { Tool, ToolFailure, emptyInputJsonSchema, toDefinitions } from "./tool.js" +export { ToolFailure, emptyInputJsonSchema, toDefinitions, tool } from "./tool.js" export { ToolRuntime } from "./tool-runtime.js" export type { DispatchResult as ToolDispatchResult, ToolSettlement } from "./tool-runtime.js" export type { - AnyExecutableTool, - AnyTool, ExecutableTool, - ExecutableTools, - Definition as ToolShape, + Tool, ToolExecute, ToolExecuteContext, ToolModelOutputInput, + ToolOptions, Tools, ToolSchema, ToolToModelOutput, diff --git a/packages/ai/src/experimental.ts b/packages/ai/src/experimental.ts index c54af26af6d1..77abd0776e62 100644 --- a/packages/ai/src/experimental.ts +++ b/packages/ai/src/experimental.ts @@ -1,3 +1,60 @@ +export { VideoClient } from "./video-client.js" +export { + VideoAspectRatio, + VideoEvent, + VideoFrames, + VideoModel, + VideoModelSchema, + VideoRequest, + VideoResponse, +} from "./video.js" +export type { + VideoModelOptions, + VideoOptions, + VideoRequestFor, + VideoRequestInput, + VideoResolution, + VideoRoute, +} from "./video.js" +export { Video } from "./video.js" +export { SpeechClient } from "./speech-client.js" +export { + SpeechEvent, + SpeechModel, + SpeechModelSchema, + SpeechRequest, + SpeechResponse, + SpeechTimestamp, + SpeechVoice, +} from "./speech.js" +export type { + SpeechFormat, + SpeechModelOptions, + SpeechOptions, + SpeechRequestFor, + SpeechRequestInput, + SpeechRoute, +} from "./speech.js" +export { Speech } from "./speech.js" +export { TranscriptionClient } from "./transcription-client.js" +export { + TranscriptionEvent, + TranscriptionModel, + TranscriptionModelSchema, + TranscriptionRequest, + TranscriptionResponse, + TranscriptionSegment, + TranscriptionTimestamps, + TranscriptionWord, +} from "./transcription.js" +export type { + TranscriptionModelOptions, + TranscriptionOptions, + TranscriptionRequestFor, + TranscriptionRequestInput, + TranscriptionRoute, +} from "./transcription.js" +export { Transcription } from "./transcription.js" export { Extraction, ExtractionModel, ExtractionRequest, ExtractionResponse } from "./experimental/extraction.js" export type { ExtractionAnswerFor, diff --git a/packages/ai/src/experimental/testing.ts b/packages/ai/src/experimental/testing.ts new file mode 100644 index 000000000000..44cbc9dfb30e --- /dev/null +++ b/packages/ai/src/experimental/testing.ts @@ -0,0 +1,3 @@ +export { TestSpeech } from "../testing/speech.js" +export { TestTranscription } from "../testing/transcription.js" +export { TestVideo } from "../testing/video.js" diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index 7c01a0144ade..1a54a2fd38a3 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -10,6 +10,7 @@ import { type CheckpointRequest, type CompactionRequest, type EndpointCompactOptions, + type StreamOptions, type TriggerCompactOptions, } from "./route/client.js" import { RequestExecutor } from "./route/executor.js" @@ -35,7 +36,8 @@ import { type TranscriptionRequest, type TranscriptionRequestInput, } from "./transcription.js" -import { Tool, ToolFailure, type FreeformOption, type ToolExecuteContext, type ToolSchema } from "./tool.js" +import { ToolFailure, build } from "./tool.js" +import type { NoExecute, ToolExecuteContext, ToolOptions, ToolSchema } from "./tool.js" import { fileMediaType } from "./utils/media-type.js" import { Video, type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js" @@ -62,6 +64,8 @@ export type Services = AIClient.Services * new handle rather than updating this one. */ export type GenerationHandle = Snapshot & { + readonly snapshot: Snapshot + readonly terminal: boolean /** Serializable JSON; pass it back to `resume` from another process. */ readonly token: unknown readonly await: (options?: AwaitOptions & RunOptions) => Promise @@ -144,9 +148,11 @@ export const make = (options: Options = {}) => { const handle = (generation: Generation): GenerationHandle => ({ ...generation.snapshot, + snapshot: generation.snapshot, + terminal: generation.terminal, token: generation.token, - await: (options) => run(generation.await({ poll: options?.poll }), options), - events: (options) => iterate(generation.events({ poll: options?.poll }), options), + await: (options) => run(generation.await(options), options), + events: (options) => iterate(generation.events(options), options), result: (options) => run(generation.result(), options), refresh: (options) => run(generation.refresh(), options).then(handle), cancel: (options) => run(generation.cancel(), options), @@ -192,76 +198,38 @@ export const make = (options: Options = {}) => { }, llm: { request: LLM.request, - generate: (input: RequestInput | LLMRequest, options?: RunOptions) => - run(LLM.generate(input), options), - stream: (input: RequestInput | LLMRequest, options?: RunOptions) => - iterate(LLM.stream(input), options), + generate: ( + input: RequestInput | LLMRequest, + options?: StreamOptions & RunOptions, + ) => run(LLM.generate(input, options), options), + stream: ( + input: RequestInput | LLMRequest, + options?: StreamOptions & RunOptions, + ) => iterate(LLM.stream(input, options), options), /** Stream model calls, running their tool calls, until the model stops calling tools or `until` is true. */ - loop: (input: LoopInput, options?: RunOptions) => - iterate(LLM.loop(input), options), + loop: (input: LoopInput, options?: StreamOptions & RunOptions) => + iterate(LLM.loop(input, options), options), /** Decode the model's output against `schema` (or `jsonSchema`, unvalidated) like `LLM.generateObject`. */ generateObject, /** Compact a Responses request like `LLMClient.compact`: a replacement window, or a checkpoint with `mechanism: "trigger"`. */ compact, + canCompact: LLMClient.canCompact, }, image: { request: Image.request, generate: ( input: ImageRequestInput | ImageRequest, options?: AwaitOptions & RunOptions, - ) => run(Image.generate(input, { poll: options?.poll }), options), + ) => run(Image.generate(input, options), options), stream: ( input: ImageRequestInput | ImageRequest, options?: AwaitOptions & RunOptions, - ) => iterate(Image.stream(input, { poll: options?.poll }), options), + ) => iterate(Image.stream(input, options), options), start: (input: ImageRequestInput | ImageRequest, options?: RunOptions) => run(Image.start(input), options).then(handle), resume: (model: ImageModel, token: unknown, options?: RunOptions) => run(Image.resume(model, token), options).then(handle), }, - video: { - request: Video.request, - start: (input: VideoRequestInput | VideoRequest, options?: RunOptions) => - run(Video.start(input), options).then(handle), - generate: ( - input: VideoRequestInput | VideoRequest, - options?: AwaitOptions & RunOptions, - ) => run(Video.generate(input, { poll: options?.poll }), options), - resume: (model: VideoModel, token: unknown, options?: RunOptions) => - run(Video.resume(model, token), options).then(handle), - stream: ( - input: VideoRequestInput | VideoRequest, - options?: AwaitOptions & RunOptions, - ) => iterate(Video.stream(input, { poll: options?.poll }), options), - }, - speech: { - request: Speech.request, - generate: ( - input: SpeechRequestInput | SpeechRequest, - options?: RunOptions, - ) => run(Speech.generate(input), options), - stream: ( - input: SpeechRequestInput | SpeechRequest, - options?: RunOptions, - ) => iterate(Speech.stream(input), options), - }, - transcription: { - request: Transcription.request, - generate: ( - input: TranscriptionRequestInput | TranscriptionRequest, - options?: AwaitOptions & RunOptions, - ) => run(Transcription.generate(input, { poll: options?.poll }), options), - stream: ( - input: TranscriptionRequestInput | TranscriptionRequest, - options?: AwaitOptions & RunOptions, - ) => iterate(Transcription.stream(input, { poll: options?.poll }), options), - start: ( - input: TranscriptionRequestInput | TranscriptionRequest, - options?: RunOptions, - ) => run(Transcription.start(input), options).then(handle), - resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => - run(Transcription.resume(model, token), options).then(handle), - }, decision: { request: Decision.request, generate: ( @@ -269,6 +237,52 @@ export const make = (options: Options = {}) => { options?: RunOptions, ) => run(Decision.generate(input), options), }, + /** Experimental: may change without compatibility guarantees. */ + experimental: { + speech: { + request: Speech.request, + generate: ( + input: SpeechRequestInput | SpeechRequest, + options?: RunOptions, + ) => run(Speech.generate(input), options), + stream: ( + input: SpeechRequestInput | SpeechRequest, + options?: RunOptions, + ) => iterate(Speech.stream(input), options), + }, + transcription: { + request: Transcription.request, + generate: ( + input: TranscriptionRequestInput | TranscriptionRequest, + options?: AwaitOptions & RunOptions, + ) => run(Transcription.generate(input, { poll: options?.poll }), options), + stream: ( + input: TranscriptionRequestInput | TranscriptionRequest, + options?: AwaitOptions & RunOptions, + ) => iterate(Transcription.stream(input, { poll: options?.poll }), options), + start: ( + input: TranscriptionRequestInput | TranscriptionRequest, + options?: RunOptions, + ) => run(Transcription.start(input), options).then(handle), + resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => + run(Transcription.resume(model, token), options).then(handle), + }, + video: { + request: Video.request, + start: (input: VideoRequestInput | VideoRequest, options?: RunOptions) => + run(Video.start(input), options).then(handle), + generate: ( + input: VideoRequestInput | VideoRequest, + options?: AwaitOptions & RunOptions, + ) => run(Video.generate(input, { poll: options?.poll }), options), + resume: (model: VideoModel, token: unknown, options?: RunOptions) => + run(Video.resume(model, token), options).then(handle), + stream: ( + input: VideoRequestInput | VideoRequest, + options?: AwaitOptions & RunOptions, + ) => iterate(Video.stream(input, { poll: options?.poll }), options), + }, + }, dispose: () => runtime.dispose(), } } @@ -278,32 +292,33 @@ export type Client = ReturnType> const fileError = (message: string, cause: unknown) => new AIError({ reason: new InvalidRequestError({ message, cause }) }) -/** - * Promise counterpart of `Tool.make` for `ai.llm.loop`. A throw or rejection becomes the error result the model sees, the - * returned value is sent unvalidated (`undefined` as `null`), and `signal` aborts when the loop is interrupted. - */ -export const tool = >(config: { - readonly description: string - readonly parameters: Parameters - readonly freeform?: FreeformOption - readonly execute: ( - params: Schema.Schema.Type, - context: Partial & { readonly signal: AbortSignal }, - ) => unknown -}) => - Tool.make({ - description: config.description, - parameters: config.parameters, - success: Schema.Unknown, - freeform: config.freeform, - execute: (params, context) => - Effect.tryPromise({ - try: async (signal) => (await config.execute(params, { ...context, signal })) ?? null, - catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }), - }), - }) +/** `tool` from `@opencode/ai/effect`, with an `execute` that returns a value or a Promise and throws to fail. */ +export const tool = < + Parameters extends ToolSchema = typeof Schema.Unknown, + Success extends ToolSchema = typeof Schema.Unknown, + Result extends Schema.Schema.Type | PromiseLike> | NoExecute = NoExecute, +>( + config: ToolOptions< + Parameters, + Success, + (params: Schema.Schema.Type, context: Partial & { signal: AbortSignal }) => Result + >, +) => { + const execute = config.execute + return build( + config, + execute && + ((params, context) => + Effect.tryPromise({ + try: async (signal) => execute(params, { ...context, signal }), + catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }), + })), + ) +} /** Default client over `RequestExecutor.fetchLayer` for scripts; the runtime builds its layer on first use. */ export const ai = make() +export { AIError } from "./schema/index.js" export * as AI from "./index.js" +export type { ExecutableTool, Tool, ToolOptions, Tools } from "./tool.js" diff --git a/packages/ai/src/llm.ts b/packages/ai/src/llm.ts index 8bac475a4a92..102d3ceb9c80 100644 --- a/packages/ai/src/llm.ts +++ b/packages/ai/src/llm.ts @@ -17,8 +17,9 @@ import { type ContentPart, type LanguageModelProviderOptions, type ToolEntryInput, + withPartial, } from "./schema/index.js" -import { make as makeTool, toDefinitions, type ExecutableTools, type ToolSchema } from "./tool.js" +import { tool, toDefinitions, type ExecutableTool, type Tool, type ToolSchema } from "./tool.js" import { ToolRuntime } from "./tool-runtime.js" /** Input accepted by `LLM.request`, normalized into the canonical `LLMRequest` class. */ @@ -57,7 +58,7 @@ export type LoopInput, "tools" > & { - readonly tools: ExecutableTools + readonly tools: Record /** Called after each step that has tool calls; returning `true` ends the loop without running them. */ readonly until?: (state: { readonly steps: ReadonlyArray }) => boolean } @@ -74,18 +75,19 @@ export function loop(input: LoopInput, options?: StreamOptions) { const { tools, until, ...rest } = input const step = (request: LLMRequest, steps: ReadonlyArray): Stream.Stream => Stream.suspend(() => { - const events: LLMEvent[] = [] + let state = LLMResponse.empty() return LLMClient.stream(request, options).pipe( Stream.map((event) => event.type === "step-start" || event.type === "step-finish" ? { ...event, index: steps.length } : event, ), - Stream.tap((event) => Effect.sync(() => events.push(event))), + Stream.tap((event) => Effect.sync(() => (state = LLMResponse.reduce(state, event)))), + Stream.mapError((error) => withPartial(error, LLMResponse.partial(state))), Stream.concat( Stream.unwrap( Effect.gen(function* () { - const response = LLMResponse.fromEvents(events) + const response = LLMResponse.complete(state) const calls = response?.toolCalls.filter((call) => call.providerExecuted !== true) ?? [] - if (!response || calls.length === 0 || events.some(LLMEvent.is.providerError)) return Stream.empty + if (!response || calls.length === 0 || state.events.some(LLMEvent.is.providerError)) return Stream.empty const done = [...steps, response] if (until?.({ steps: done })) return Stream.empty const results = yield* Effect.forEach(calls, (call) => ToolRuntime.dispatch(tools, call), { @@ -185,10 +187,7 @@ export interface GenerateObjectDynamicOptions, -) { +const runGenerateObject = Effect.fn("LLM.generateObject")(function* (options: GenerateObjectBase, tool: Tool) { const baseRequest = request(options) const generateRequest = LLMRequest.update(baseRequest, { tools: toDefinitions({ [GENERATE_OBJECT_TOOL_NAME]: tool }), @@ -196,21 +195,22 @@ const runGenerateObject = Effect.fn("LLM.generateObject")(function* ( }) const response = yield* LLMClient.generate(generateRequest) const call = response.toolCalls.find((event) => event.name === GENERATE_OBJECT_TOOL_NAME) - if (!call) - return yield* new AIError({ - reason: new InvalidProviderOutputError({ - message: `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`, - }), - }) + const invalidOutput = (reason: InvalidProviderOutputError) => new AIError({ reason, partial: response }) + if (!call) { + const message = + response.finishReason.normalized === "length" + ? "generateObject: output hit the token limit before the forced tool call completed" + : `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool` + return yield* invalidOutput(new InvalidProviderOutputError({ message })) + } const object = yield* tool._decode(call.input).pipe( - Effect.mapError( - (error) => - new AIError({ - reason: new InvalidProviderOutputError({ - message: `generateObject: tool input failed schema decode: ${error.message}`, - cause: error, - }), + Effect.mapError((error) => + invalidOutput( + new InvalidProviderOutputError({ + message: `generateObject: tool input failed schema decode: ${error.message}`, + cause: error, }), + ), ), ) return new GenerateObjectResponse(object, response) @@ -237,23 +237,8 @@ export function generateObject> | GenerateObjectDynamicOptions) { if ("schema" in options) { const { schema, ...rest } = options - return runGenerateObject( - rest, - makeTool({ - description: GENERATE_OBJECT_TOOL_DESCRIPTION, - parameters: schema, - success: Schema.Unknown as ToolSchema, - execute: () => Effect.void, - }), - ) + return runGenerateObject(rest, tool({ description: GENERATE_OBJECT_TOOL_DESCRIPTION, parameters: schema })) } const { jsonSchema, ...rest } = options - return runGenerateObject( - rest, - makeTool({ - description: GENERATE_OBJECT_TOOL_DESCRIPTION, - jsonSchema, - execute: () => Effect.void, - }), - ) + return runGenerateObject(rest, tool({ description: GENERATE_OBJECT_TOOL_DESCRIPTION, jsonSchema })) } diff --git a/packages/ai/src/protocols/assemblyai-transcription.ts b/packages/ai/src/protocols/assemblyai-transcription.ts index 6446b04f4821..0287f31799d3 100644 --- a/packages/ai/src/protocols/assemblyai-transcription.ts +++ b/packages/ai/src/protocols/assemblyai-transcription.ts @@ -133,7 +133,7 @@ const decodeStart = Effect.fn("AssemblyAITranscription.decodeStart")(function* ( response: HttpClientResponse.HttpClientResponse, ) { const output = yield* decodeTranscript(response) - const status = yield* MediaProtocol.status(STATUS, output.value.status, output) + const status = MediaProtocol.status(STATUS, output.value.status) return { token: { transcriptID: output.value.id }, snapshot: { id: output.value.id, status } } }) @@ -142,7 +142,7 @@ const decodeStatus = Effect.fn("AssemblyAITranscription.decodeStatus")(function* context: MediaProtocol.PollContext, ) { const output = yield* decodeTranscript(response) - const status = yield* MediaProtocol.status(STATUS, output.value.status, output) + const status = MediaProtocol.status(STATUS, output.value.status) return { id: context.token.transcriptID, status } }) @@ -154,7 +154,7 @@ const decodeResult = Effect.fn("AssemblyAITranscription.decodeResult")(function* ) { const output = yield* decodeTranscript(response) const transcript = output.value - const status = yield* MediaProtocol.status(STATUS, transcript.status, output) + const status = MediaProtocol.status(STATUS, transcript.status) const error = transcript.error ?? undefined if (status === "failed") return yield* output.ended("failed", `${route.name} transcription failed${error === undefined ? "" : `: ${error}`}`) diff --git a/packages/ai/src/protocols/open-responses.ts b/packages/ai/src/protocols/open-responses.ts index 7e5b54126f16..c07db846e972 100644 --- a/packages/ai/src/protocols/open-responses.ts +++ b/packages/ai/src/protocols/open-responses.ts @@ -52,7 +52,7 @@ export const OpenResponsesInputImage = Schema.Struct({ }) export const OpenResponsesInputFile = Schema.Struct({ type: Schema.tag("input_file"), - filename: Schema.String, + filename: Schema.optional(Schema.String), detail: Schema.optional(Schema.String), file_data: Schema.optional(Schema.String), file_url: Schema.optional(Schema.String), @@ -590,11 +590,12 @@ const lowerMedia = Effect.fnUntraced(function* (part: MediaPart, request: LLMReq const location = url ?? (yield* ProviderShared.requireInlineMedia(adapter.name, part.media)).dataUrl if (part.media.kind !== "image") { if (part.media.kind === "video") return { type: "input_video" as const, video_url: location } + if (url) return { type: "input_file" as const, file_url: url, detail } return { type: "input_file" as const, filename: part.filename ?? (mime === "application/pdf" ? "document.pdf" : "file"), detail, - ...(url ? { file_url: url } : { file_data: location }), + file_data: location, } } return { diff --git a/packages/ai/src/protocols/runway-video.ts b/packages/ai/src/protocols/runway-video.ts index 4bddd4ba1372..50cf94c4490a 100644 --- a/packages/ai/src/protocols/runway-video.ts +++ b/packages/ai/src/protocols/runway-video.ts @@ -121,7 +121,7 @@ const decodeStatus = Effect.fn("RunwayVideo.decodeStatus")(function* ( context: MediaProtocol.PollContext, ) { const output = yield* decodeTask(response) - const status = yield* MediaProtocol.status(STATUS, output.value.status, output) + const status = MediaProtocol.status(STATUS, output.value.status) return { id: context.token.taskID, status, progress: output.value.progress ?? undefined } }) @@ -131,7 +131,7 @@ const decodeResult = Effect.fn("RunwayVideo.decodeResult")(function* ( ) { const output = yield* decodeTask(response) const task = output.value - const status = yield* MediaProtocol.status(STATUS, task.status, output) + const status = MediaProtocol.status(STATUS, task.status) if (status === "failed") { const code = task.failureCode ?? undefined const message = `${route.name} task failed${code === undefined ? "" : ` (${code})`}${task.failure ? `: ${task.failure}` : ""}` diff --git a/packages/ai/src/protocols/xai-video.ts b/packages/ai/src/protocols/xai-video.ts index 3e1d53059e25..4017d853f24f 100644 --- a/packages/ai/src/protocols/xai-video.ts +++ b/packages/ai/src/protocols/xai-video.ts @@ -132,7 +132,7 @@ const decodeStatus = Effect.fn("XAIVideo.decodeStatus")(function* ( context: MediaProtocol.PollContext, ) { const output = yield* decodeVideoStatus(response) - const status = yield* MediaProtocol.status(STATUS, output.value.status, output) + const status = MediaProtocol.status(STATUS, output.value.status) return { id: context.token.requestID, status, progress: fraction(output.value.progress) } }) @@ -142,7 +142,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* ( ) { const output = yield* decodeVideoStatus(response) const decoded = output.value - const status = yield* MediaProtocol.status(STATUS, decoded.status, output) + const status = MediaProtocol.status(STATUS, decoded.status) if (status === "running") return yield* output.pending(context.token.requestID) if (status === "failed") { const code = decoded.error?.code ?? undefined diff --git a/packages/ai/src/providers/openrouter.ts b/packages/ai/src/providers/openrouter.ts index 09c042a98e8b..5ca224653290 100644 --- a/packages/ai/src/providers/openrouter.ts +++ b/packages/ai/src/providers/openrouter.ts @@ -8,6 +8,7 @@ import type { ProviderPackage } from "../provider-package.js" import { SystemOne } from "../protocols/system-one.js" import { OpenAIImages, type OpenAIImageSizing } from "../protocols/openai-images.js" import { MediaRoute } from "../route/media.js" +import { HttpTransport } from "../route/transport/index.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponses } from "../protocols/open-responses.js" import { cacheControl } from "../protocols/utils/cache.js" @@ -74,6 +75,9 @@ export interface OpenRouterOptions { export type OpenRouterProviderOptionsInput = OpenRouterOptions +export type OpenRouterResponsesProviderOptionsInput = OpenResponsesProviderOptionsInput & + Pick + export interface OpenRouterDecisionOptions { readonly [key: string]: unknown readonly provider?: OpenRouterProviderRouting @@ -85,7 +89,7 @@ export interface OpenRouterDecisionOptions { export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string - readonly providerOptions?: OpenRouterProviderOptionsInput | OpenResponsesProviderOptionsInput + readonly providerOptions?: OpenRouterProviderOptionsInput | OpenRouterResponsesProviderOptionsInput } export type Settings = ProviderPackage.Settings & @@ -94,14 +98,18 @@ export type Settings = ProviderPackage readonly baseURL?: string } -const Options = Schema.Struct({ - usage: lenient(Schema.Union([Schema.Boolean, JsonObject])), +const SharedOptions = Schema.Struct({ models: lenient(Schema.Array(Schema.String)), provider: lenient(JsonObject), plugins: lenient(Schema.Array(JsonObject)), - web_search_options: lenient(JsonObject), debug: lenient(JsonObject), user: lenient(Schema.String), +}) + +const Options = Schema.Struct({ + ...SharedOptions.fields, + usage: lenient(Schema.Union([Schema.Boolean, JsonObject])), + web_search_options: lenient(JsonObject), reasoning: lenient(JsonObject), }) const decodeOptions = Schema.decodeUnknownSync(Options) @@ -166,12 +174,8 @@ const bodyOptions = (body: OpenAIChat.OpenAIChatBody, input: unknown, maxTokens: ...options, ...body, ...(usage !== undefined ? { usage } : {}), - ...(known.models !== undefined ? { models: known.models } : {}), - ...(known.provider !== undefined ? { provider: known.provider } : {}), - ...(known.plugins !== undefined ? { plugins: known.plugins } : {}), + ...sharedOptions(known), ...(known.web_search_options !== undefined ? { web_search_options: known.web_search_options } : {}), - ...(known.debug !== undefined ? { debug: known.debug } : {}), - ...(known.user !== undefined ? { user: known.user } : {}), ...(known.reasoning !== undefined ? { reasoning: fitReasoning(known.reasoning, maxTokens) } : {}), } } @@ -191,6 +195,32 @@ const imageSizing: OpenAIImageSizing = (request) => { } } +const sharedOptions = (known: typeof SharedOptions.Type) => ({ + ...(known.models !== undefined ? { models: known.models } : {}), + ...(known.provider !== undefined ? { provider: known.provider } : {}), + ...(known.plugins !== undefined ? { plugins: known.plugins } : {}), + ...(known.debug !== undefined ? { debug: known.debug } : {}), + ...(known.user !== undefined ? { user: known.user } : {}), +}) + +const OpenRouterResponsesBody = Schema.Struct({ + ...OpenResponses.OpenResponsesBody.fields, + ...SharedOptions.fields, +}) +type OpenRouterResponsesBody = Schema.Schema.Type + +const responsesProtocol = Protocol.make({ + id: "openrouter-responses", + body: { + schema: OpenRouterResponsesBody, + from: (request) => + OpenResponses.fromRequest(request).pipe( + Effect.map((body) => ({ ...body, ...sharedOptions(decodeOptions(request.providerOptions ?? {})) })), + ), + }, + stream: OpenResponses.protocol.stream, +}) + export const route = Route.make({ id: ADAPTER, provider: id, @@ -204,9 +234,9 @@ const responsesRoute = Route.make({ id: "openrouter-responses", provider: id, providerMetadataKey: "openrouter", - protocol: OpenResponses.protocol, + protocol: responsesProtocol, endpoint: Endpoint.path("/responses", { baseURL }), - transport: OpenResponses.httpTransport, + transport: HttpTransport.sseJson.with(), defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) @@ -247,7 +277,7 @@ export const configure = (input: Config = {}) => { model: (modelID: string | ModelID) => chatRoute.model({ id: modelID, compatibility: { supportsPromptCacheKey: true } }), responses: (modelID: string | ModelID) => - configuredResponses.model({ id: modelID }), + configuredResponses.model({ id: modelID }), image, decision, configure, @@ -261,8 +291,8 @@ export const responses = provider.responses export const model: ProviderPackage.Model = (modelID, settings) => configure(config(settings)).model(modelID) export const responsesModel: ProviderPackage.Model< - Settings, - OpenResponsesProviderOptionsInput + Settings, + OpenRouterResponsesProviderOptionsInput > = (modelID, settings) => configure(config(settings)).responses(modelID) export const imageModel = (modelID: string, settings?: Settings) => { const input = config(settings) diff --git a/packages/ai/src/providers/openrouter/responses.ts b/packages/ai/src/providers/openrouter/responses.ts index 34a9c7f2e13b..efabaea27ded 100644 --- a/packages/ai/src/providers/openrouter/responses.ts +++ b/packages/ai/src/providers/openrouter/responses.ts @@ -1,4 +1,3 @@ -import type { OpenResponsesProviderOptionsInput } from "../open-responses-options.js" import type { OpenRouter } from "../openrouter.js" export { responsesModel as model } from "../openrouter.js" -export type Settings = OpenRouter.Settings +export type Settings = OpenRouter.Settings diff --git a/packages/ai/src/route/client.ts b/packages/ai/src/route/client.ts index 6b763f9d77cb..9693419a47b3 100644 --- a/packages/ai/src/route/client.ts +++ b/packages/ai/src/route/client.ts @@ -30,6 +30,7 @@ import { mergeGenerationOptions, mergeHttpOptions, mergeProviderOptions, + withPartial, } from "../schema/index.js" export interface RouteBody { @@ -629,12 +630,19 @@ const streamRequestWith = (runtime: TransportRuntime) => (request: LLMRequest, o }), ) -const generateWith = (stream: Interface["stream"]) => +export const generateWith = (stream: Interface["stream"]) => Effect.fn("LLM.generate")(function* (request: LLMRequest, options?: StreamOptions) { - const state = yield* stream(request, options).pipe(Stream.runFold(LLMResponse.empty, LLMResponse.reduce)) + let state = LLMResponse.empty() + yield* stream(request, options).pipe( + Stream.runForEach((event) => Effect.sync(() => (state = LLMResponse.reduce(state, event)))), + Effect.mapError((error) => withPartial(error, LLMResponse.partial(state))), + ) const response = LLMResponse.complete(state) if (response) return response - return yield* incompleteStreamError(`${request.model.provider}/${request.model.route.id}`) + return yield* withPartial( + incompleteStreamError(`${request.model.provider}/${request.model.route.id}`), + LLMResponse.partial(state), + ) }) export function stream(request: LLMRequest, options?: StreamOptions): Stream.Stream { diff --git a/packages/ai/src/route/media-protocol.ts b/packages/ai/src/route/media-protocol.ts index ea73cdb79923..64dd034c692f 100644 --- a/packages/ai/src/route/media-protocol.ts +++ b/packages/ai/src/route/media-protocol.ts @@ -309,17 +309,9 @@ export const identity = (input: { readonly id: string; readonly name: string; re export type Identity = ReturnType -export type Output = Effect.Success> - -/** Map a provider status string through the protocol's table; unknown values are an invalid provider document. */ -export const status = >( - table: Table, - raw: string, - output: Output, -): Effect.Effect => { - if (!Object.hasOwn(table, raw)) return Effect.fail(output.invalid(`Unknown generation status "${raw}"`)) - return Effect.succeed(table[raw]) -} +/** Map a provider status string through the protocol's table; unknown values keep the generation running. */ +export const status = (table: Readonly>, raw: string): Status => + Object.hasOwn(table, raw) ? table[raw] : "running" /** Map a provider error code through the protocol's table; missing or unmapped codes are `ProviderInternal`. */ export const failure = (table: Readonly>, code: string | number | undefined): Failure => diff --git a/packages/ai/src/schema/errors.ts b/packages/ai/src/schema/errors.ts index 4c6ab9d1c445..9c0e07a3f2f2 100644 --- a/packages/ai/src/schema/errors.ts +++ b/packages/ai/src/schema/errors.ts @@ -2,6 +2,7 @@ import { Schema } from "effect" import { NonNegativeInt } from "@opencode/schema" import { Tool } from "@opencode/schema/tool" import { ModelID, ProviderID, RouteID } from "./ids.js" +import type { LLMResponse } from "./events.js" export const ProviderFailureClassification = Schema.Literals(["context-overflow", "payload-too-large"]) export type ProviderFailureClassification = typeof ProviderFailureClassification.Type @@ -163,12 +164,23 @@ export class AIError extends Schema.TaggedError()("AI.Error", { reason: AIErrorReason, }) { override readonly cause = this.reason + /** Output that arrived before `generate`, `generateObject` or a `loop` step failed. Not in the schema, so encoding omits it. */ + readonly partial?: LLMResponse + + constructor(props: Pick) { + super({ reason: props.reason }) + this.partial = props.partial + } override get message(): string { return this.reason.message } } +/** Return `error` with `partial` attached, or unchanged when there is no partial output. */ +export const withPartial = (error: AIError, partial: LLMResponse | undefined) => + partial === undefined ? error : new AIError({ reason: error.reason, partial }) + /** * Failure type for tool execute handlers. Handlers must map their internal * errors to this shape; the runtime catches `ToolFailure`s and surfaces them diff --git a/packages/ai/src/schema/events.ts b/packages/ai/src/schema/events.ts index 6d15eb6dee73..24e1b81a2a54 100644 --- a/packages/ai/src/schema/events.ts +++ b/packages/ai/src/schema/events.ts @@ -756,6 +756,12 @@ export namespace LLMResponse { /** Convenience reducer for callers that already have a collected event list. */ export const fromEvents = (events: ReadonlyArray) => complete(events.reduce(reduce, empty())) + /** Output that arrived before a failure, or `undefined` if only `step-start` did; an unfinished response reports `error`. */ + export const partial = (state: State) => + state.events.every(LLMEvent.is.stepStart) + ? undefined + : complete({ ...state, finishReason: state.finishReason ?? { normalized: "error" } }) + /** Concatenate assistant text from a response or collected event list. */ export const text = (response: Output) => responseText(response.events) diff --git a/packages/ai/src/testing.ts b/packages/ai/src/testing.ts index ffa6d6d8ac18..ef8a5ce97b32 100644 --- a/packages/ai/src/testing.ts +++ b/packages/ai/src/testing.ts @@ -2,12 +2,10 @@ export * as TestLLM from "./testing.js" export { compileRequest } from "./route/client.js" export { TestDecision } from "./testing/decision.js" export { TestImage } from "./testing/image.js" -export { TestSpeech } from "./testing/speech.js" -export { TestTranscription } from "./testing/transcription.js" -export { TestVideo } from "./testing/video.js" import { LLMClient, + generateWith, type CompactionRequest, type CheckpointRequest, type EndpointCompactOptions, @@ -15,7 +13,6 @@ import { } from "./route/client.js" import { LLMEvent, - LLMResponse, CompactionResponse, CompactionCheckpointResponse, type FinishReasonDetails, @@ -83,7 +80,7 @@ export const textWithUsage = (value: string, id: string, inputTokens: number) => ...textEvents(value, id), ) -export const tool = (id: string, name: string, input: unknown) => toolCalls(LLMEvent.toolCall({ id, name, input })) +export const toolCall = (id: string, name: string, input: unknown) => toolCalls(LLMEvent.toolCall({ id, name, input })) export const failAfter = (error: AIError, ...events: readonly LLMEvent[]) => Stream.fromIterable(events).pipe(Stream.concat(Stream.fail(error))) @@ -131,15 +128,7 @@ const make = (options: LayerOptions) => ...script.controls, compact, stream, - generate: (request) => - stream(request).pipe( - Stream.runFold(LLMResponse.empty, LLMResponse.reduce), - Effect.flatMap((state) => { - const response = LLMResponse.complete(state) - if (response) return Effect.succeed(response) - return Effect.die("TestLLM response ended without a terminal finish event") - }), - ), + generate: generateWith(stream), }) }) diff --git a/packages/ai/src/tool-runtime.ts b/packages/ai/src/tool-runtime.ts index f7ea40aa58f3..44056b189d7b 100644 --- a/packages/ai/src/tool-runtime.ts +++ b/packages/ai/src/tool-runtime.ts @@ -8,7 +8,7 @@ import { type ToolOutput as ToolOutputType, type ToolResultValue as ToolResultValueType, } from "./schema/index.js" -import { type AnyTool, type Tools } from "./tool.js" +import { type Tool, type Tools } from "./tool.js" export interface ToolSettlement { readonly result: ToolResultValueType @@ -41,7 +41,7 @@ export const dispatch = (tools: Tools, call: ToolCallPart): Effect.Effect => +const decodeAndExecute = (tool: Tool, call: ToolCallPart): Effect.Effect => tool._decode(call.input).pipe( Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })), Effect.flatMap((decoded) => diff --git a/packages/ai/src/tool.ts b/packages/ai/src/tool.ts index 9fd9da30f25c..22e71ac65b35 100644 --- a/packages/ai/src/tool.ts +++ b/packages/ai/src/tool.ts @@ -1,5 +1,5 @@ import { Effect, JsonSchema, Schema } from "effect" -import { Tool } from "@opencode/schema/tool" +import type { Content } from "@opencode/schema/tool" import type { Freeform, ToolCallPart, @@ -34,7 +34,7 @@ export interface ToolModelOutputInput { export type ToolToModelOutput, Success extends ToolSchema> = ( input: ToolModelOutputInput, Success["Encoded"]>, -) => ReadonlyArray +) => ReadonlyArray type FreeformField = { [K in keyof T]-?: [Exclude] extends [never] @@ -46,12 +46,13 @@ type FreeformField = { : never }[keyof T] -/** `Freeform` when the parameters are exactly one required string field, otherwise `undefined`. */ -export type FreeformOption> = [ - FreeformField>, -] extends [never] - ? undefined - : Freeform +/** `Freeform` for exactly one required string parameter or unknown ones (`jsonSchema`), otherwise `undefined`. */ +export type FreeformOption> = + unknown extends Schema.Schema.Type + ? Freeform + : [FreeformField>] extends [never] + ? undefined + : Freeform /** * A type-safe LLM tool. Each tool bundles its own description, parameter @@ -65,7 +66,7 @@ export type FreeformOption> = [ * Internally each tool also carries memoized codecs and a precomputed * `ToolDefinition` so callers do not rebuild them per invocation. */ -export interface Definition, Success extends ToolSchema> { +export interface Tool = any, Success extends ToolSchema = any> { readonly description: string readonly parameters: Parameters readonly success: Success @@ -74,133 +75,102 @@ export interface Definition, Success extends readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown /** @internal */ readonly _decode: (input: unknown) => Effect.Effect, Schema.SchemaError> + // Method syntax keeps these parameters bivariant, so a concrete tool stays assignable to `ExecutableTool`. /** @internal */ - readonly _encode: (value: Schema.Schema.Type) => Effect.Effect + _encode(value: Schema.Schema.Type): Effect.Effect /** @internal */ - readonly _project: ( - parameters: Schema.Schema.Type, - id: ToolCallPart["id"], - output: unknown, - ) => ToolOutputType + _project(parameters: Schema.Schema.Type, id: ToolCallPart["id"], output: unknown): ToolOutputType /** @internal */ readonly _legacyResult: boolean /** @internal */ readonly _definition: ToolDefinitionClass } -export type AnyTool = Definition - -export type ExecutableTool, Success extends ToolSchema> = Definition< +/** A tool with an `execute` handler, which `LLM.loop` and `ToolRuntime.dispatch` can run. */ +export type ExecutableTool = any, Success extends ToolSchema = any> = Tool< Parameters, Success > & { readonly execute: ToolExecute } -export type AnyExecutableTool = ExecutableTool - -export type ExecutableTools = Record - -type TypedToolConfig = { - readonly description: string - readonly parameters: ToolSchema - readonly success: ToolSchema - readonly freeform?: Freeform - readonly execute?: ToolExecute, ToolSchema> - readonly toModelOutput?: ToolToModelOutput, ToolSchema> - readonly toStructuredOutput?: (output: unknown) => unknown -} - -type DynamicToolConfig = { - readonly description: string - readonly jsonSchema: JsonSchema.JsonSchema - readonly outputSchema?: JsonSchema.JsonSchema - readonly freeform?: Freeform - readonly execute?: (params: unknown, context?: ToolExecuteContext) => Effect.Effect - readonly toModelOutput?: (input: ToolModelOutputInput) => ReadonlyArray - readonly toStructuredOutput?: (output: unknown) => unknown -} - /** - * Constructs a tool. Two input modes: - * - * 1. **Typed** — pass Effect `parameters` and `success` Schemas; inputs and - * outputs are statically typed and decoded/encoded automatically. - * - * ```ts - * Tool.make({ - * description: "Get current weather", - * parameters: Schema.Struct({ city: Schema.String }), - * success: Schema.Struct({ temperature: Schema.Number }), - * execute: ({ city }) => Effect.succeed({ temperature: 22 }), - * }) - * ``` - * - * 2. **Dynamic** — pass raw JSON Schema as `jsonSchema`. Use this when the - * schema comes from an external source (MCP server, plugin manifest, - * dynamic config) and is not known at compile time. Inputs are typed as - * `unknown`; the handler is responsible for any validation it needs. - * - * ```ts - * Tool.make({ - * description: "Look something up", - * jsonSchema: { type: "object", properties: { ... } }, - * execute: (params) => Effect.succeed(...), - * }) - * ``` - * - * In both modes the produced tool flows through `toDefinitions(...)` - * identically. + * Options for `tool`, where `Execute` is the only part that differs between the Effect and Promise clients. Pass + * Effect `parameters` (and optionally a `success` schema that validates the result, otherwise it is sent as is with + * `undefined` as `null`), or raw `jsonSchema` known only at runtime, such as an MCP tool's. Omit `execute` to declare + * a tool the model can call without running it here. */ -export function make, Success extends ToolSchema>(config: { +export type ToolOptions< + Parameters extends ToolSchema, + Success extends ToolSchema, + Execute = ToolExecute, +> = { readonly description: string - readonly parameters: Parameters - readonly success: Success readonly freeform?: FreeformOption - readonly execute: ToolExecute + readonly execute?: Execute readonly toModelOutput?: ToolToModelOutput readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown -}): ExecutableTool -export function make, Success extends ToolSchema>(config: { - readonly description: string - readonly parameters: Parameters - readonly success: Success - readonly freeform?: FreeformOption - readonly execute?: undefined - readonly toModelOutput?: ToolToModelOutput - readonly toStructuredOutput?: (output: Success["Encoded"]) => unknown -}): Definition -export function make(config: { - readonly description: string - readonly jsonSchema: JsonSchema.JsonSchema - readonly outputSchema?: JsonSchema.JsonSchema - readonly freeform?: Freeform - readonly execute: (params: unknown, context?: ToolExecuteContext) => Effect.Effect - readonly toModelOutput?: (input: ToolModelOutputInput) => ReadonlyArray - readonly toStructuredOutput?: (output: unknown) => unknown -}): AnyExecutableTool -export function make(config: { - readonly description: string - readonly jsonSchema: JsonSchema.JsonSchema - readonly outputSchema?: JsonSchema.JsonSchema - readonly freeform?: Freeform - readonly execute?: undefined - readonly toModelOutput?: (input: ToolModelOutputInput) => ReadonlyArray - readonly toStructuredOutput?: (output: unknown) => unknown -}): AnyTool -export function make(config: TypedToolConfig | DynamicToolConfig): AnyTool { - if ("jsonSchema" in config) { +} & ( + | { readonly parameters: Parameters; readonly success?: Success } + | { readonly jsonSchema: JsonSchema.JsonSchema; readonly outputSchema?: JsonSchema.JsonSchema } +) + +/** + * Constructs a tool whose `execute` returns an Effect that fails with `ToolFailure`. + * + * ```ts + * tool({ + * description: "Get current weather", + * parameters: Schema.Struct({ city: Schema.String }), + * success: Schema.Struct({ temperature: Schema.Number }), + * execute: ({ city }) => Effect.succeed({ temperature: 22 }), + * }) + * ``` + */ +export const tool = < + Parameters extends ToolSchema = typeof Schema.Unknown, + Success extends ToolSchema = typeof Schema.Unknown, + Result extends Effect.Effect, ToolFailure> | NoExecute = NoExecute, +>( + config: ToolOptions< + Parameters, + Success, + (params: Schema.Schema.Type, context?: ToolExecuteContext) => Result + >, +) => build(config, config.execute) + +declare const noExecute: unique symbol +/** @internal The inferred `execute` result when `execute` is omitted; no function can return it. */ +export type NoExecute = { readonly [noExecute]: never } + +/** @internal Builds a tool for both clients from its options and an Effect `execute`. */ +export function build, Success extends ToolSchema, Result>( + config: ToolOptions Result>, + execute: ((params: Schema.Schema.Type, context?: ToolExecuteContext) => unknown) | undefined, +): 0 extends 1 & Result // `any` + ? ExecutableTool + : [Result, NoExecute] extends [NoExecute, Result] + ? Tool + : ExecutableTool +export function build( + config: ToolOptions, ToolSchema, unknown>, + execute: ((params: any, context?: ToolExecuteContext) => any) | undefined, +): Tool { + const shared = { + description: config.description, + execute, + toModelOutput: config.toModelOutput, + toStructuredOutput: config.toStructuredOutput, + _project: (parameters: unknown, id: ToolCallPart["id"], output: unknown) => + project(config.toModelOutput, config.toStructuredOutput, parameters, id, output), + } + if ("jsonSchema" in config) return { - description: config.description, - parameters: Schema.Unknown as ToolSchema, - success: Schema.Unknown as ToolSchema, - execute: config.execute, - toModelOutput: config.toModelOutput, - toStructuredOutput: config.toStructuredOutput, + ...shared, + parameters: Schema.Unknown, + success: Schema.Unknown, _decode: Effect.succeed, _encode: Effect.succeed, - _project: (parameters, id, output) => - project(config.toModelOutput, config.toStructuredOutput, parameters, id, output), _legacyResult: config.toModelOutput === undefined && config.toStructuredOutput === undefined, _definition: definition({ name: "", @@ -210,24 +180,18 @@ export function make(config: TypedToolConfig | DynamicToolConfig): AnyTool { freeform: config.freeform, }), } - } return { - description: config.description, + ...shared, parameters: config.parameters, - success: config.success, - execute: config.execute, - toModelOutput: config.toModelOutput, - toStructuredOutput: config.toStructuredOutput, + success: config.success ?? Schema.Unknown, _decode: Schema.decodeUnknownEffect(config.parameters), - _encode: Schema.encodeEffect(config.success), - _project: (parameters, id, output) => - project(config.toModelOutput, config.toStructuredOutput, parameters, id, output), + _encode: config.success ? Schema.encodeEffect(config.success) : (value) => Effect.succeed(value ?? null), _legacyResult: false, _definition: definition({ name: "", description: config.description, inputSchema: emptyInputJsonSchema(config.parameters) ?? toJsonSchema(config.parameters), - outputSchema: toJsonSchema(config.success), + outputSchema: config.success && toJsonSchema(config.success), freeform: config.freeform, }), } @@ -236,7 +200,7 @@ export function make(config: TypedToolConfig | DynamicToolConfig): AnyTool { /** * A record of named tools. The record key becomes the tool name on the wire. */ -export type Tools = Record +export type Tools = Record /** * Convert a tools record into the `ToolDefinition[]` shape that @@ -289,7 +253,7 @@ const toJsonSchema = (schema: Schema.Top): JsonSchema.JsonSchema => { } const project = ( - toModelOutput: ((input: ToolModelOutputInput) => ReadonlyArray) | undefined, + toModelOutput: ((input: ToolModelOutputInput) => ReadonlyArray) | undefined, toStructuredOutput: ((output: unknown) => unknown) | undefined, parameters: unknown, id: ToolCallPart["id"], @@ -301,5 +265,3 @@ const project = ( ) export { ToolFailure } - -export * as Tool from "./tool.js" diff --git a/packages/ai/test/error-partial.test.ts b/packages/ai/test/error-partial.test.ts new file mode 100644 index 000000000000..0c018bc856b1 --- /dev/null +++ b/packages/ai/test/error-partial.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Schema, Stream } from "effect" +import { LanguageModel, LLM, LLMEvent, ProviderInternalError, tool } from "../src/effect.js" +import { AI, AIError } from "../src/index.js" +import { OpenAIChat } from "../src/protocols/openai-chat.js" +import { TestLLM } from "../src/testing.js" +import { testEffect } from "./lib/effect.js" + +const model = LanguageModel.make({ id: "fictional-model", provider: "fixture", route: OpenAIChat.route }) +const it = testEffect(TestLLM.testLayer()) +const overloaded = new AIError({ reason: new ProviderInternalError({ message: "Overloaded" }) }) + +const textThenFail = TestLLM.failAfter( + overloaded, + LLMEvent.stepStart({ index: 0 }), + LLMEvent.textStart({ id: "text-0" }), + LLMEvent.textDelta({ id: "text-0", text: "Partial answer" }), + LLMEvent.stepFinish({ + index: 0, + reason: { normalized: "stop" }, + usage: { inputTokens: 5, nonCachedInputTokens: 5, outputTokens: 2 }, + }), +) + +describe("AIError.partial", () => { + it.effect("generate keeps the output that arrived before a mid-stream failure", () => + Effect.gen(function* () { + const client = yield* TestLLM.Test + yield* client.push(textThenFail) + + const error = yield* LLM.generate({ model, prompt: "Hello" }).pipe(Effect.flip) + + expect(error.reason).toBe(overloaded.reason) + expect(error.partial?.text).toBe("Partial answer") + expect(error.partial?.message.content).toEqual([{ type: "text", text: "Partial answer" }]) + expect(error.partial?.usage?.outputTokens).toBe(2) + expect(error.partial?.finishReason).toEqual({ normalized: "error" }) + }), + ) + + it.effect("generate keeps the same error when the failure comes before any output", () => + Effect.gen(function* () { + const client = yield* TestLLM.Test + yield* client.push(TestLLM.failAfter(overloaded, LLMEvent.stepStart({ index: 0 }))) + + expect(yield* LLM.generate({ model, prompt: "Hello" }).pipe(Effect.flip)).toBe(overloaded) + }), + ) + + it.effect("generateObject keeps the raw output when the token limit cuts off the forced tool call", () => + Effect.gen(function* () { + const client = yield* TestLLM.Test + yield* client.push( + TestLLM.complete( + { reason: { normalized: "length" } }, + LLMEvent.textStart({ id: "text-0" }), + LLMEvent.textDelta({ id: "text-0", text: "Thinking about the answer" }), + ), + ) + + const error = yield* LLM.generateObject({ + model, + prompt: "Answer", + schema: Schema.Struct({ answer: Schema.String }), + }).pipe(Effect.flip) + + expect(error.message).toContain("token limit") + expect(error.partial?.text).toBe("Thinking about the answer") + expect(error.partial?.finishReason.normalized).toBe("length") + }), + ) + + it.effect("loop reports only the failed step as partial", () => + Effect.gen(function* () { + const client = yield* TestLLM.Test + yield* client.push(TestLLM.toolCall("call-1", "echo", { value: "hi" })) + yield* client.push(textThenFail) + + const echo = tool({ + description: "Echo a value.", + parameters: Schema.Struct({ value: Schema.String }), + success: Schema.String, + execute: ({ value }) => Effect.succeed(value), + }) + const error = yield* LLM.loop({ model, prompt: "Echo hi.", tools: { echo } }).pipe(Stream.runDrain, Effect.flip) + + expect(error.partial?.text).toBe("Partial answer") + expect(error.partial?.toolCalls).toEqual([]) + }), + ) +}) + +describe("AIError.partial from the promise client", () => { + test("rejects with the root-exported AIError carrying partial", async () => { + const ai = AI.make({ clients: TestLLM.testLayer({ fallback: textThenFail }) }) + + const error = await ai.llm.generate({ model, prompt: "Hello" }).catch((error: unknown) => error) + + expect(error).toBeInstanceOf(AIError) + expect(error instanceof AIError && error.partial?.text).toBe("Partial answer") + await ai.dispose() + }) +}) diff --git a/packages/ai/test/exports.test.ts b/packages/ai/test/exports.test.ts index dce07d590055..9dbe9d8c681b 100644 --- a/packages/ai/test/exports.test.ts +++ b/packages/ai/test/exports.test.ts @@ -12,13 +12,8 @@ import { LLM, LLMClient, Media, - Speech, - SpeechClient, - SpeechEvent, - TranscriptionClient, - Video, - VideoClient, } from "@opencode/ai/effect" +import { Speech, SpeechClient, SpeechEvent, TranscriptionClient, Video, VideoClient } from "@opencode/ai/experimental" import { Route, Protocol, RequestExecutor, WebSocketTransport } from "@opencode/ai/route" import { Alibaba, diff --git a/packages/ai/test/generate-object.test.ts b/packages/ai/test/generate-object.test.ts index cb4486a6300c..852f0c66f821 100644 --- a/packages/ai/test/generate-object.test.ts +++ b/packages/ai/test/generate-object.test.ts @@ -3,7 +3,7 @@ import { Effect, Schema } from "effect" import { LLM } from "../src/effect.js" import * as OpenAIChat from "../src/protocols/openai-chat.js" import { Auth } from "../src/route.js" -import { Tool, toDefinitions } from "../src/tool.js" +import { toDefinitions, tool } from "../src/tool.js" import { it } from "./lib/effect.js" import { dynamicResponse } from "./lib/http.js" import { finishChunk, toolCallChunk } from "./lib/openai-chunks.js" @@ -26,14 +26,14 @@ const Json = Schema.fromJsonString(Schema.Unknown) const decodeJson = Schema.decodeUnknownSync(Json) const decodeBody = (text: string): OpenAIChatBody => decodeJson(text) as OpenAIChatBody -describe("Tool.make (dynamic JSON Schema)", () => { +describe("tool (dynamic JSON Schema)", () => { test("forwards JSON Schema and description through toDefinitions", () => { const jsonSchema = { type: "object" as const, properties: { city: { type: "string" } }, required: ["city"], } - const lookup = Tool.make({ + const lookup = tool({ description: "Look up something", jsonSchema, execute: () => Effect.succeed({ ok: true }), @@ -47,7 +47,7 @@ describe("Tool.make (dynamic JSON Schema)", () => { it.effect("execute receives the raw input untouched", () => Effect.gen(function* () { const seen: unknown[] = [] - const tool = Tool.make({ + const echo = tool({ description: "echo", jsonSchema: { type: "object" }, execute: (params) => @@ -56,7 +56,7 @@ describe("Tool.make (dynamic JSON Schema)", () => { return { ok: true } }), }) - const result = yield* tool.execute({ hello: "world" }) + const result = yield* echo.execute({ hello: "world" }) expect(seen).toEqual([{ hello: "world" }]) expect(result).toEqual({ ok: true }) }), diff --git a/packages/ai/test/loop-tools.types.ts b/packages/ai/test/loop-tools.types.ts new file mode 100644 index 000000000000..dce970821b6c --- /dev/null +++ b/packages/ai/test/loop-tools.types.ts @@ -0,0 +1,57 @@ +import { Effect, Schema } from "effect" +import { LLM, tool } from "../src/effect.js" +import * as OpenAIChat from "../src/protocols/openai-chat.js" +import { Auth } from "../src/route.js" +import { AI, ai } from "../src/index.js" + +const model = OpenAIChat.route.with({ auth: Auth.bearer("fixture") }).model({ id: "gpt-4o-mini" }) + +const add = AI.tool({ + description: "Add two numbers.", + parameters: Schema.Struct({ a: Schema.Number, b: Schema.Number }), + execute: (input) => input.a + input.b, +}) + +const echo = AI.tool({ + description: "Echo text.", + parameters: Schema.String, + execute: (input) => input.toUpperCase(), +}) + +const weather = tool({ + description: "Get weather.", + parameters: Schema.Struct({ city: Schema.String }), + success: Schema.Struct({ forecast: Schema.String }), + execute: (input) => Effect.succeed({ forecast: input.city }), +}) + +const shout = tool({ + description: "Shout text.", + parameters: Schema.String, + success: Schema.String, + execute: (input) => Effect.succeed(input.toUpperCase()), +}) + +const schemaOnly = tool({ + description: "Get weather.", + parameters: Schema.Struct({ city: Schema.String }), + success: Schema.Struct({ forecast: Schema.String }), +}) + +ai.llm.loop({ model, prompt: "Add 2 and 3.", tools: { add } }) +ai.llm.loop({ model, prompt: "Get weather.", tools: { weather } }) +ai.llm.loop({ model, prompt: "Use any tool.", tools: { add, echo, weather, shout } }) +LLM.loop({ model, prompt: "Add 2 and 3.", tools: { add } }) +LLM.loop({ model, prompt: "Get weather.", tools: { weather } }) +LLM.loop({ model, prompt: "Use any tool.", tools: { add, echo, weather, shout } }) + +// @ts-expect-error The loop runs tools, so each one needs an execute handler. +LLM.loop({ model, prompt: "Get weather.", tools: { schemaOnly } }) + +const unavailable = () => { + throw new Error("Unavailable.") +} +const fail = AI.tool({ description: "Fail.", parameters: Schema.String, execute: unavailable }) +const parse = AI.tool({ description: "Parse.", parameters: Schema.String, execute: (text) => JSON.parse(text) }) +const inspect = tool({ description: "Inspect.", parameters: Schema.String, execute: () => Effect.succeed(1) }) +ai.llm.loop({ model, prompt: "Fail.", tools: { fail, parse, inspect } }) diff --git a/packages/ai/test/loop.test.ts b/packages/ai/test/loop.test.ts index e78e68952b67..2161d34d8067 100644 --- a/packages/ai/test/loop.test.ts +++ b/packages/ai/test/loop.test.ts @@ -1,6 +1,7 @@ import { describe, expect } from "bun:test" import { Effect, Schema, Stream } from "effect" -import { LanguageModel, LLM, LLMEvent, Tool, ToolFailure } from "../src/effect.js" +import { LanguageModel, LLM, LLMEvent, ToolFailure, tool } from "../src/effect.js" +import { AI } from "../src/index.js" import { OpenAIChat } from "../src/protocols/openai-chat.js" import { TestLLM } from "../src/testing.js" import { testEffect } from "./lib/effect.js" @@ -8,7 +9,7 @@ import { testEffect } from "./lib/effect.js" const model = LanguageModel.make({ id: "fictional-model", provider: "fixture", route: OpenAIChat.route }) const it = testEffect(TestLLM.testLayer()) -const read_file = Tool.make({ +const read_file = tool({ description: "Read a file.", parameters: Schema.Struct({ path: Schema.String }), success: Schema.String, @@ -61,7 +62,7 @@ describe("LLM.loop", () => { Effect.gen(function* () { const client = yield* TestLLM.Test yield* client.push( - TestLLM.tool("call-1", "read_file", { path: "missing.txt" }), + TestLLM.toolCall("call-1", "read_file", { path: "missing.txt" }), TestLLM.text("That file does not exist.", "text-1"), ) @@ -78,10 +79,39 @@ describe("LLM.loop", () => { }), ) + it.effect("runs Promise tools, validating success and projecting toModelOutput", () => + Effect.gen(function* () { + const client = yield* TestLLM.Test + yield* client.push( + TestLLM.toolCalls( + LLMEvent.toolCall({ id: "call-1", name: "add", input: { a: 2, b: 3 } }), + LLMEvent.toolCall({ id: "call-2", name: "add", input: { a: -1, b: 0 } }), + ), + TestLLM.text("Done.", "text-1"), + ) + const add = AI.tool({ + description: "Add two numbers.", + parameters: Schema.Struct({ a: Schema.Number, b: Schema.Number }), + success: Schema.Number, + execute: async ({ a, b }) => (a < 0 ? "negative" : a + b) as number, + toModelOutput: ({ output }) => [{ type: "text", text: `sum=${output}` }], + }) + + const events = yield* LLM.loop({ model, prompt: "Add.", tools: { add } }).pipe(Stream.runCollect) + + expect(Array.from(events).filter(LLMEvent.is.toolResult)).toEqual([ + expect.objectContaining({ id: "call-1", result: { type: "text", value: "sum=5" } }), + expect.objectContaining({ + result: { type: "error", value: expect.stringContaining("invalid value for its success schema") }, + }), + ]) + }), + ) + it.effect("stops when until returns true without running that step's tools", () => Effect.gen(function* () { const client = yield* TestLLM.Test - yield* client.always(TestLLM.tool("call-1", "read_file", { path: "a.txt" })) + yield* client.always(TestLLM.toolCall("call-1", "read_file", { path: "a.txt" })) const seen: number[] = [] const events = yield* collect(({ steps }) => { diff --git a/packages/ai/test/promise-parity.types.ts b/packages/ai/test/promise-parity.types.ts new file mode 100644 index 000000000000..0d41449eb7fe --- /dev/null +++ b/packages/ai/test/promise-parity.types.ts @@ -0,0 +1,78 @@ +import type { Effect, Stream } from "effect" +import type { Client, GenerationHandle } from "../src/index.js" +import type { Decision, Generation, Image, LLM, LLMClient } from "../src/effect.js" +import type { Speech, Transcription, Video } from "../src/experimental.js" + +// The Promise client mirrors the Effect API: same methods, same arguments, same results. The only allowed differences +// are `signal` on the options bag, Promise for Effect, AsyncIterable for Stream and GenerationHandle for Generation. + +type Equal = [A, B] extends [B, A] ? true : false +type Assert> = T + +/** The Effect operations each `ai.*` namespace mirrors. Adding an operation here, or on `LLM`, fails until `ai` has it. */ +export type Surface = { + readonly llm: Operations & Pick + readonly image: typeof Image + readonly decision: typeof Decision + readonly speech: typeof Speech + readonly transcription: typeof Transcription + readonly video: typeof Video +} + +type Operations = { [K in keyof M as M[K] extends (...args: never) => unknown ? K : never]: M[K] } + +type Signatures = F extends { + (...args: infer A1): infer R1 + (...args: infer A2): infer R2 + (...args: infer A3): infer R3 +} + ? [A1, R1] | [A2, R2] | [A3, R3] + : F extends { (...args: infer A1): infer R1; (...args: infer A2): infer R2 } + ? [A1, R1] | [A2, R2] + : F extends (...args: infer A) => infer R + ? [A, R] + : never + +type Positional

= P extends readonly [infer A, ...infer Rest] ? [WithoutSignal, ...Positional] : [] +// Paired with its keys: an options bag of optional fields is otherwise assignable to `{}` and back. +type Options

= P extends readonly [unknown, ...infer Rest] + ? Options + : P extends readonly [(infer O)?] + ? Keyed>> + : Keyed<{}> +type Keyed = [keyof T, T] +type WithoutSignal = T extends { readonly signal?: AbortSignal } ? Omit : T + +type Promised = + R extends Effect.Effect, infer _E, infer _R> + ? Promise> + : R extends Effect.Effect + ? Promise + : R extends Stream.Stream + ? AsyncIterable + : R + +type EffectShape = + Signatures extends infer S ? (S extends [infer A, infer R] ? [Positional, Options, Promised] : never) : never +type PromiseShape = + Signatures extends infer S ? (S extends [infer A, infer R] ? [Positional, Options, R] : never) : never + +export type Drift = { + readonly [K in keyof Promise | keyof Effect]: K extends keyof Promise + ? K extends keyof Effect + ? Equal, EffectShape> + : "missing in Effect" + : "missing in Promise" +} + +type Same = [Exclude | Exclude] extends [never] ? true : { readonly drift: Exclude | Exclude } + +export type Checks = [ + Assert<{ handle: Same, Exclude, "route">> }>, + Assert>, + Assert>, + Assert>, + Assert>, + Assert>, + Assert>, +] diff --git a/packages/ai/test/promise.test.ts b/packages/ai/test/promise.test.ts index 5ce3beb85bc8..3d03eb8f65da 100644 --- a/packages/ai/test/promise.test.ts +++ b/packages/ai/test/promise.test.ts @@ -4,8 +4,9 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { Effect, Layer, Schema } from "effect" import { HttpClientRequest } from "effect/http" -import { AIError, LLMEvent, Media, SpeechEvent, TranscriptionEvent } from "../src/effect.js" -import { RequestExecutor } from "../src/route.js" +import { AIError, LLMEvent, Media } from "../src/effect.js" +import { SpeechEvent, TranscriptionEvent } from "../src/experimental.js" +import { RequestExecutor, type StreamOptions } from "../src/route.js" import { AI } from "../src/index.js" import { AssemblyAI, OpenAI, Runway } from "../src/providers.js" import { handlerLayer, json } from "./lib/http.js" @@ -174,7 +175,7 @@ describe("AI promise client", () => { const ai = AI.make({ layer: executor(seen) }) const model = Runway.configure({ apiKey: "test", baseURL: "https://runway.test/v1" }).video("gen4.5") - const generation = await ai.video.start({ model, prompt: "A kite" }) + const generation = await ai.experimental.video.start({ model, prompt: "A kite" }) expect(generation.id).toBe("task_1") expect(generation.status).toBe("queued") expect(generation.token).toEqual({ taskID: "task_1" }) @@ -188,12 +189,12 @@ describe("AI promise client", () => { expect(response.video.source).toMatchObject({ type: "url", url: "https://runway.test/out.mp4" }) expect(response.usage).toEqual({ type: "credits", credits: 5 }) - const resumed = await ai.video.resume(model, JSON.parse(JSON.stringify(generation.token))) + const resumed = await ai.experimental.video.resume(model, JSON.parse(JSON.stringify(generation.token))) expect(resumed.status).toBe("completed") expect((await resumed.await()).videos).toHaveLength(1) const events: Array = [] - for await (const event of ai.video.stream({ model, prompt: "A kite" }, { poll: { interval: 10 } })) { + for await (const event of ai.experimental.video.stream({ model, prompt: "A kite" }, { poll: { interval: 10 } })) { events.push(event.type) } expect(events).toEqual(["video", "finish"]) @@ -203,10 +204,45 @@ describe("AI promise client", () => { await ai.dispose() }) + test("forwards per-call options to generate, stream, and loop, and checks compaction support", async () => { + const seen: Array = [] + const ai = AI.make({ layer: executor([]) }) + const options: StreamOptions = { + http: (request, handler) => { + seen.push(request.url) + return handler(request) + }, + } + const request = { model: openai.chat("gpt-4o-mini"), prompt: "Say hello." } + + expect((await ai.llm.generate(request, options)).text).toBe("Hello world") + await Array.fromAsync(ai.llm.stream(request, options)) + await Array.fromAsync(ai.llm.loop({ ...request, tools: {} }, options)) + expect(seen).toEqual(Array(3).fill("https://openai.test/v1/chat/completions")) + + const responses = ai.llm.request({ model: openai.responses("gpt-5"), prompt: "Hello" }) + expect(ai.llm.canCompact(responses)).toBe(true) + expect(ai.llm.canCompact(responses, { mechanism: "trigger" })).toBe(true) + expect(ai.llm.canCompact(ai.llm.request(request))).toBe(false) + await ai.dispose() + }) + + test("exposes a generation's snapshot and terminal state", async () => { + const ai = AI.make({ layer: executor([]) }) + const model = Runway.configure({ apiKey: "test", baseURL: "https://runway.test/v1" }).video("gen4.5") + const generation = await ai.experimental.video.start({ model, prompt: "A kite" }) + expect(generation.snapshot).toEqual({ id: "task_1", status: "queued", progress: undefined, position: undefined }) + expect(generation.terminal).toBe(false) + const refreshed = await generation.refresh() + expect(refreshed.terminal).toBe(false) + expect((await refreshed.refresh()).terminal).toBe(true) + await ai.dispose() + }) + test("observes a started generation's events and fetches its result", async () => { const ai = AI.make({ layer: executor([]) }) const model = Runway.configure({ apiKey: "test", baseURL: "https://runway.test/v1" }).video("gen4.5") - const generation = await ai.video.start({ model, prompt: "A kite" }) + const generation = await ai.experimental.video.start({ model, prompt: "A kite" }) const events: Array = [] for await (const event of generation.events({ poll: { interval: 10 } })) events.push(event.type) @@ -239,11 +275,16 @@ describe("AI promise client", () => { const bytes = Media.bytes(Uint8Array.from([0x49, 0x44, 0x33]), "audio/mpeg") expect( - (await ai.transcription.generate({ model: openai.transcription("gpt-4o-mini-transcribe"), audio: bytes })).text, + ( + await ai.experimental.transcription.generate({ + model: openai.transcription("gpt-4o-mini-transcribe"), + audio: bytes, + }) + ).text, ).toBe("Hello there.") const deltas: Array = [] - for await (const event of ai.transcription.stream({ + for await (const event of ai.experimental.transcription.stream({ model: openai.transcription("gpt-4o-mini-transcribe"), audio: bytes, })) @@ -253,7 +294,7 @@ describe("AI promise client", () => { const model = AssemblyAI.configure({ apiKey: "test", baseURL: "https://assemblyai.test" }).transcription( "universal-2", ) - const generation = await ai.transcription.start({ model, audio }) + const generation = await ai.experimental.transcription.start({ model, audio }) expect(generation.token).toEqual({ transcriptID: "tr_1" }) expect((await generation.await({ poll: { interval: 10 } })).text).toBe("Hello there.") await ai.dispose() @@ -263,11 +304,12 @@ describe("AI promise client", () => { const ai = AI.make({ layer: executor([]) }) const model = openai.speech("gpt-4o-mini-tts") - const response = await ai.speech.generate({ model, text: "Hello", voice: "coral", format: "pcm" }) + const response = await ai.experimental.speech.generate({ model, text: "Hello", voice: "coral", format: "pcm" }) expect(await ai.run(response.audio.bytes())).toEqual(Uint8Array.from([1, 2, 3])) const events: Array = [] - for await (const event of ai.speech.stream({ model, text: "Hello", voice: "coral" })) events.push(event) + for await (const event of ai.experimental.speech.stream({ model, text: "Hello", voice: "coral" })) + events.push(event) expect(events.map((event) => event.type)).toEqual(["audio-delta", "audio-delta", "finish"]) const finish = events.find(SpeechEvent.is.finish) expect(await ai.run(finish!.audio.bytes())).toEqual(Uint8Array.from([1, 2, 3])) @@ -326,7 +368,10 @@ describe("AI promise client", () => { ).toBe(reason) const preAborted = await Array.fromAsync( - ai.speech.stream({ model: openai.speech("gpt-4o-mini-tts"), text: "Hello" }, { signal: aborted.signal }), + ai.experimental.speech.stream( + { model: openai.speech("gpt-4o-mini-tts"), text: "Hello" }, + { signal: aborted.signal }, + ), ).catch((error: unknown) => error) expect(preAborted).toBe(aborted.signal.reason) expect(preAborted).toMatchObject({ name: "AbortError" }) @@ -346,7 +391,7 @@ describe("AI promise client", () => { expect(midStreamFailure).toMatchObject({ name: "AbortError" }) const model = Runway.configure({ apiKey: "test", baseURL: "https://runway.test/v1" }).video("gen4.5") - const generation = await ai.video.start({ model, prompt: "A kite" }) + const generation = await ai.experimental.video.start({ model, prompt: "A kite" }) const polling = new AbortController() const events: Array = [] const eventsFailure = await Array.fromAsync( @@ -509,8 +554,8 @@ describe("AI promise client", () => { test("the default client is created lazily and can be disposed", async () => { expect(typeof AI.ai.llm.generate).toBe("function") expect(typeof AI.ai.image.generate).toBe("function") - expect(typeof AI.ai.video.start).toBe("function") - expect(typeof AI.ai.speech.generate).toBe("function") + expect(typeof AI.ai.experimental.video.start).toBe("function") + expect(typeof AI.ai.experimental.speech.generate).toBe("function") await AI.ai.dispose() }) }) diff --git a/packages/ai/test/provider-options/openrouter.types.ts b/packages/ai/test/provider-options/openrouter.types.ts index ce1741711dda..ad1a7375e60f 100644 --- a/packages/ai/test/provider-options/openrouter.types.ts +++ b/packages/ai/test/provider-options/openrouter.types.ts @@ -31,3 +31,25 @@ LLM.request({ // @ts-expect-error OpenRouter usage must be boolean or an option record. providerOptions: { usage: "yes" }, }) + +const responses = OpenRouter.provider.responses("openai/gpt-5.4") + +LLM.request({ + model: responses, + prompt: "Hello", + providerOptions: { + reasoningEffort: "low", + models: ["openai/gpt-5.4-mini"], + provider: { only: ["openai"], sort: "future-sort", data_collection: "future-policy" }, + plugins: [{ id: "future-plugin", enabled: true }], + debug: { echo_upstream_body: true }, + user: "user_123", + }, +}) + +LLM.request({ + model: responses, + prompt: "Hello", + // @ts-expect-error OpenRouter fallback models must be a list of model IDs. + providerOptions: { models: "openai/gpt-5.4-mini" }, +}) diff --git a/packages/ai/test/provider-package.test.ts b/packages/ai/test/provider-package.test.ts index e2b02ddcbcca..46e1877b6008 100644 --- a/packages/ai/test/provider-package.test.ts +++ b/packages/ai/test/provider-package.test.ts @@ -60,9 +60,24 @@ describe("provider package entrypoints", () => { test("maps OpenRouter, DigitalOcean and Venice Responses entrypoints onto provider-owned routes", async () => { const providers = [ - ["openrouter", "https://openrouter.ai/api/v1", await import("@opencode/ai/providers/openrouter/responses")], - ["digitalocean", "https://inference.do-ai.run/v1", await import("@opencode/ai/providers/digitalocean/responses")], - ["venice", "https://api.venice.ai/api/v1", await import("@opencode/ai/providers/venice/responses")], + [ + "openrouter", + "https://openrouter.ai/api/v1", + "openrouter-responses", + await import("@opencode/ai/providers/openrouter/responses"), + ], + [ + "digitalocean", + "https://inference.do-ai.run/v1", + "open-responses", + await import("@opencode/ai/providers/digitalocean/responses"), + ], + [ + "venice", + "https://api.venice.ai/api/v1", + "open-responses", + await import("@opencode/ai/providers/venice/responses"), + ], ] as const const settings = { apiKey: "fixture", @@ -70,11 +85,11 @@ describe("provider package entrypoints", () => { body: { future_option: true }, reasoningEffort: "low", } - for (const [provider, baseURL, module] of providers) { + for (const [provider, baseURL, protocol, module] of providers) { const selected = module.model("gpt-5.4", settings) expect(selected.provider).toBe(provider) expect(selected.route.id).toBe(`${provider}-responses`) - expect(selected.route.protocol).toBe("open-responses") + expect(selected.route.protocol).toBe(protocol) expect(selected.route.endpoint).toMatchObject({ baseURL, path: "/responses" }) expect(selected.route.defaults.headers).toEqual(settings.headers) expect(selected.route.defaults.http?.body).toEqual(settings.body) diff --git a/packages/ai/test/provider/assemblyai-transcription.recorded.test.ts b/packages/ai/test/provider/assemblyai-transcription.recorded.test.ts index 65176f7cd9b2..42bcb1c619ad 100644 --- a/packages/ai/test/provider/assemblyai-transcription.recorded.test.ts +++ b/packages/ai/test/provider/assemblyai-transcription.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Transcription } from "../../src/effect.js" +import { Transcription } from "../../src/experimental.js" import { AssemblyAI } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TRANSCRIPT, audio, audioRecording } from "./transcription-recording.js" diff --git a/packages/ai/test/provider/bedrock-converse.test.ts b/packages/ai/test/provider/bedrock-converse.test.ts index d2dcada6319c..fe2e2ecf0c8c 100644 --- a/packages/ai/test/provider/bedrock-converse.test.ts +++ b/packages/ai/test/provider/bedrock-converse.test.ts @@ -13,11 +13,11 @@ import { LLMEvent, LLMRequest, Message, - Tool, ToolCallPart, ToolChoice, ToolDefinition, ToolRuntime, + tool, } from "../../src/effect.js" import { LLMClient } from "../../src/route.js" import { compileRequest } from "../../src/route/client.js" @@ -1092,7 +1092,7 @@ describe("Bedrock Converse route", () => { expect(call.name).toBe("browser.tabs.open") const dispatched = yield* ToolRuntime.dispatch( { - browser_tabs_open: Tool.make({ + browser_tabs_open: tool({ description: "Open a tab", parameters: Schema.Struct({}), success: Schema.String, diff --git a/packages/ai/test/provider/cartesia-speech.recorded.test.ts b/packages/ai/test/provider/cartesia-speech.recorded.test.ts index bf112d0f35c2..faa0746be72f 100644 --- a/packages/ai/test/provider/cartesia-speech.recorded.test.ts +++ b/packages/ai/test/provider/cartesia-speech.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Speech, SpeechEvent } from "../../src/effect.js" +import { Speech, SpeechEvent } from "../../src/experimental.js" import { Cartesia } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TEXT, collectSpeech } from "./speech-recording.js" diff --git a/packages/ai/test/provider/deepgram-speech.recorded.test.ts b/packages/ai/test/provider/deepgram-speech.recorded.test.ts index fee287306bb4..c2dc19e2a894 100644 --- a/packages/ai/test/provider/deepgram-speech.recorded.test.ts +++ b/packages/ai/test/provider/deepgram-speech.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Speech } from "../../src/effect.js" +import { Speech } from "../../src/experimental.js" import { Deepgram } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TEXT, collectSpeech } from "./speech-recording.js" diff --git a/packages/ai/test/provider/deepgram-transcription.recorded.test.ts b/packages/ai/test/provider/deepgram-transcription.recorded.test.ts index fb38b989e54e..f127d0f2d651 100644 --- a/packages/ai/test/provider/deepgram-transcription.recorded.test.ts +++ b/packages/ai/test/provider/deepgram-transcription.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Stream } from "effect" -import { Transcription } from "../../src/effect.js" +import { Transcription } from "../../src/experimental.js" import { Deepgram } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TRANSCRIPT, audio, audioRecording, dialog } from "./transcription-recording.js" diff --git a/packages/ai/test/provider/elevenlabs-speech.recorded.test.ts b/packages/ai/test/provider/elevenlabs-speech.recorded.test.ts index fd8c778bd1a4..421a60a04e2d 100644 --- a/packages/ai/test/provider/elevenlabs-speech.recorded.test.ts +++ b/packages/ai/test/provider/elevenlabs-speech.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Speech, SpeechEvent } from "../../src/effect.js" +import { Speech, SpeechEvent } from "../../src/experimental.js" import { ElevenLabs } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TEXT, collectSpeech } from "./speech-recording.js" diff --git a/packages/ai/test/provider/elevenlabs-transcription.recorded.test.ts b/packages/ai/test/provider/elevenlabs-transcription.recorded.test.ts index d36f9b26c8b8..e6969eb8ab36 100644 --- a/packages/ai/test/provider/elevenlabs-transcription.recorded.test.ts +++ b/packages/ai/test/provider/elevenlabs-transcription.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Stream } from "effect" -import { Transcription } from "../../src/effect.js" +import { Transcription } from "../../src/experimental.js" import { ElevenLabs } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TRANSCRIPT, audio, audioRecording, dialog } from "./transcription-recording.js" diff --git a/packages/ai/test/provider/explicit-compaction.test.ts b/packages/ai/test/provider/explicit-compaction.test.ts index 0574132585e2..326a53abce5b 100644 --- a/packages/ai/test/provider/explicit-compaction.test.ts +++ b/packages/ai/test/provider/explicit-compaction.test.ts @@ -198,7 +198,7 @@ const retainedItems = [ content: [ { type: "input_image", image_url: "https://example.com/image.png" }, { type: "input_file", filename: "report.pdf", file_data: "data:application/pdf;base64,cGRm", detail: "high" }, - { type: "input_file", filename: "other.pdf", file_url: "https://example.com/report.pdf", detail: "low" }, + { type: "input_file", file_url: "https://example.com/report.pdf", detail: "low" }, ], }, checkpoint, diff --git a/packages/ai/test/provider/freeform-tools.test.ts b/packages/ai/test/provider/freeform-tools.test.ts index 26027dfc51af..c571488c4050 100644 --- a/packages/ai/test/provider/freeform-tools.test.ts +++ b/packages/ai/test/provider/freeform-tools.test.ts @@ -21,7 +21,7 @@ import * as Venice from "../../src/providers/venice.js" import * as VercelAIGateway from "../../src/providers/vercel-ai-gateway.js" import { LLMClient } from "../../src/route.js" import { compileRequest } from "../../src/route/client.js" -import { Tool } from "../../src/tool.js" +import { tool } from "../../src/tool.js" import { it } from "../lib/effect.js" import { fixedResponse } from "../lib/http.js" import { sseEvents } from "../lib/sse.js" @@ -30,7 +30,7 @@ const GRAMMAR = 'start: "ZZ" /[0-9]{3}/' const tools = (freeform?: Freeform) => toDefinitions({ - run: Tool.make({ + run: tool({ description: "Run code", parameters: Schema.Struct({ code: Schema.String }), success: Schema.String, @@ -303,7 +303,7 @@ describe("freeform tools", () => { it.effect("rejects freeform tools without exactly one required string parameter", () => Effect.sync(() => { const make = (parameters: Schema.Struct) => - Tool.make({ + tool({ description: "Run code", jsonSchema: Schema.toJsonSchemaDocument(parameters).schema, freeform: { type: "text" }, diff --git a/packages/ai/test/provider/google-speech.recorded.test.ts b/packages/ai/test/provider/google-speech.recorded.test.ts index 4406ec80a290..3e162ca9456c 100644 --- a/packages/ai/test/provider/google-speech.recorded.test.ts +++ b/packages/ai/test/provider/google-speech.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Speech } from "../../src/effect.js" +import { Speech } from "../../src/experimental.js" import { Google } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TEXT, collectSpeech } from "./speech-recording.js" diff --git a/packages/ai/test/provider/google-transcription.recorded.test.ts b/packages/ai/test/provider/google-transcription.recorded.test.ts index 966c51ee04c4..b3d3ffc90b46 100644 --- a/packages/ai/test/provider/google-transcription.recorded.test.ts +++ b/packages/ai/test/provider/google-transcription.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Stream } from "effect" -import { Transcription, TranscriptionEvent } from "../../src/effect.js" +import { Transcription, TranscriptionEvent } from "../../src/experimental.js" import { Google } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TRANSCRIPT, audio, audioRecording, dialog } from "./transcription-recording.js" diff --git a/packages/ai/test/provider/google-video.recorded.test.ts b/packages/ai/test/provider/google-video.recorded.test.ts index 5f9c5e0cee95..3704601ddc57 100644 --- a/packages/ai/test/provider/google-video.recorded.test.ts +++ b/packages/ai/test/provider/google-video.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Video } from "../../src/effect.js" +import { Video } from "../../src/experimental.js" import { Google } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { queuedPoll } from "./queued-recording.js" diff --git a/packages/ai/test/provider/openai-responses.test.ts b/packages/ai/test/provider/openai-responses.test.ts index 661897121598..0f95ce50b3ef 100644 --- a/packages/ai/test/provider/openai-responses.test.ts +++ b/packages/ai/test/provider/openai-responses.test.ts @@ -1874,7 +1874,7 @@ describe("OpenAI Responses route", () => { expect(expectToolOutput(prepared.body).output).toEqual([ { type: "input_image", image_url: "https://example.com/image.png" }, - { type: "input_file", filename: "report.pdf", file_url: "https://example.com/report.pdf" }, + { type: "input_file", file_url: "https://example.com/report.pdf" }, ]) }), ) @@ -5130,7 +5130,7 @@ describe("OpenAI Responses route", () => { role: "user", content: [ { type: "input_image", image_url: "https://example.com/image.png" }, - { type: "input_file", filename: "report.pdf", file_url: "https://example.com/report.pdf" }, + { type: "input_file", file_url: "https://example.com/report.pdf" }, ], }, ]) diff --git a/packages/ai/test/provider/openai-speech.recorded.test.ts b/packages/ai/test/provider/openai-speech.recorded.test.ts index e97b67304dd6..9651e31d3fec 100644 --- a/packages/ai/test/provider/openai-speech.recorded.test.ts +++ b/packages/ai/test/provider/openai-speech.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Speech } from "../../src/effect.js" +import { Speech } from "../../src/experimental.js" import { OpenAI } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TEXT, collectSpeech } from "./speech-recording.js" diff --git a/packages/ai/test/provider/openai-transcription.recorded.test.ts b/packages/ai/test/provider/openai-transcription.recorded.test.ts index a84c6bcfbc57..766c3b1b31dd 100644 --- a/packages/ai/test/provider/openai-transcription.recorded.test.ts +++ b/packages/ai/test/provider/openai-transcription.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Stream } from "effect" -import { Transcription, TranscriptionEvent } from "../../src/effect.js" +import { Transcription, TranscriptionEvent } from "../../src/experimental.js" import { OpenAI } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { TRANSCRIPT, audio, audioRecording } from "./transcription-recording.js" diff --git a/packages/ai/test/provider/openrouter.test.ts b/packages/ai/test/provider/openrouter.test.ts index 22eb27c4e8f8..16e1b65b2821 100644 --- a/packages/ai/test/provider/openrouter.test.ts +++ b/packages/ai/test/provider/openrouter.test.ts @@ -5,7 +5,7 @@ import { LLMClient } from "../../src/route.js" import { compileRequest } from "../../src/route/client.js" import * as OpenRouter from "../../src/providers/openrouter.js" import { it } from "../lib/effect.js" -import { fixedResponse } from "../lib/http.js" +import { dynamicResponse, fixedResponse } from "../lib/http.js" import { sseEvents } from "../lib/sse.js" describe("OpenRouter", () => { @@ -391,6 +391,46 @@ describe("OpenRouter", () => { }), ) + it.effect("sends OpenRouter routing options on the Responses route", () => + LLMClient.generate( + LLM.request({ + model: OpenRouter.configure({ + apiKey: "test-key", + providerOptions: { + models: ["openai/gpt-5.4-mini"], + provider: { only: ["openai"], allow_fallbacks: false }, + plugins: [{ id: "response-healing" }], + debug: { echo_upstream_body: true }, + user: "user_123", + reasoningEffort: "low", + }, + }).responses("openai/gpt-5.4"), + prompt: "Hello", + }), + ).pipe( + Effect.provide( + dynamicResponse((input) => + Effect.sync(() => { + expect(input.request.url).toBe("https://openrouter.ai/api/v1/responses") + expect(JSON.parse(input.text)).toMatchObject({ + model: "openai/gpt-5.4", + store: false, + reasoning: { effort: "low" }, + models: ["openai/gpt-5.4-mini"], + provider: { only: ["openai"], allow_fallbacks: false }, + plugins: [{ id: "response-healing" }], + debug: { echo_upstream_body: true }, + user: "user_123", + }) + return input.respond(sseEvents({ type: "response.completed", response: { id: "resp_1" } }), { + headers: { "content-type": "text/event-stream" }, + }) + }), + ), + ), + ), + ) + it.effect("omits the prompt cache key when caching is disabled", () => Effect.gen(function* () { const prepared = yield* compileRequest( diff --git a/packages/ai/test/provider/pdf.recorded.test.ts b/packages/ai/test/provider/pdf.recorded.test.ts index 2106ab76fe82..8d930235b0bb 100644 --- a/packages/ai/test/provider/pdf.recorded.test.ts +++ b/packages/ai/test/provider/pdf.recorded.test.ts @@ -3,7 +3,7 @@ import { Effect, Schema, Stream } from "effect" import { LLM, LLMResponse, Message, ToolDefinition, type LanguageModel, Media } from "../../src/effect.js" import { AmazonBedrock, Anthropic, Google, OpenAI, XAI } from "../../src/providers.js" import { LLMClient } from "../../src/route.js" -import { Tool } from "../../src/tool.js" +import { tool } from "../../src/tool.js" import { runTools } from "../lib/tool-runtime.js" import { recordedTests } from "../recorded-test.js" @@ -89,7 +89,7 @@ const readPdf = ToolDefinition.make({ description: "Read the attached PDF.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, }) -const readPdfRuntime = Tool.make({ +const readPdfRuntime = tool({ description: readPdf.description, parameters: Schema.Struct({ path: Schema.String }), success: Schema.String, diff --git a/packages/ai/test/provider/responses-routes.recorded.test.ts b/packages/ai/test/provider/responses-routes.recorded.test.ts index 203d6e78e120..30bbfbe14edd 100644 --- a/packages/ai/test/provider/responses-routes.recorded.test.ts +++ b/packages/ai/test/provider/responses-routes.recorded.test.ts @@ -3,12 +3,12 @@ import { Effect, Schema } from "effect" import { LLM, LLMEvent, toDefinitions } from "../../src/effect.js" import { DigitalOcean, OpenRouter, Venice } from "../../src/providers.js" import { LLMClient } from "../../src/route.js" -import { Tool } from "../../src/tool.js" +import { tool } from "../../src/tool.js" import { expectWeatherToolLoop, runWeatherToolLoop, weatherToolLoopRequest } from "../recorded-scenarios.js" import { recordedTests } from "../recorded-test.js" const run = toDefinitions({ - run: Tool.make({ + run: tool({ description: "Run a Python snippet.", parameters: Schema.Struct({ code: Schema.String }), success: Schema.String, diff --git a/packages/ai/test/provider/runway-video.recorded.test.ts b/packages/ai/test/provider/runway-video.recorded.test.ts index e14cb4d31baa..44e558e50a01 100644 --- a/packages/ai/test/provider/runway-video.recorded.test.ts +++ b/packages/ai/test/provider/runway-video.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { Video } from "../../src/effect.js" +import { Video } from "../../src/experimental.js" import { Runway } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { queuedPoll } from "./queued-recording.js" diff --git a/packages/ai/test/provider/speech-recording.ts b/packages/ai/test/provider/speech-recording.ts index 3b6a165b48c4..d5d4cc1bb9f7 100644 --- a/packages/ai/test/provider/speech-recording.ts +++ b/packages/ai/test/provider/speech-recording.ts @@ -1,6 +1,6 @@ import { expect } from "bun:test" import { Effect, Stream } from "effect" -import { SpeechEvent } from "../../src/effect.js" +import { SpeechEvent } from "../../src/experimental.js" export const TEXT = "Hello from OpenCode." diff --git a/packages/ai/test/provider/xai-video.recorded.test.ts b/packages/ai/test/provider/xai-video.recorded.test.ts index 2dbd7142bd8b..31cad80d0cd2 100644 --- a/packages/ai/test/provider/xai-video.recorded.test.ts +++ b/packages/ai/test/provider/xai-video.recorded.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect, Stream } from "effect" -import { Video } from "../../src/effect.js" +import { Video } from "../../src/experimental.js" import { XAI } from "../../src/providers.js" import { recordedTests } from "../recorded-test.js" import { queuedPoll } from "./queued-recording.js" diff --git a/packages/ai/test/recorded-scenarios.ts b/packages/ai/test/recorded-scenarios.ts index fa4bc612e45f..cc2bf6bbb71d 100644 --- a/packages/ai/test/recorded-scenarios.ts +++ b/packages/ai/test/recorded-scenarios.ts @@ -16,7 +16,7 @@ import { type LanguageModel, } from "../src/effect.js" import { LLMClient } from "../src/route.js" -import { Tool } from "../src/tool.js" +import { tool } from "../src/tool.js" export const weatherToolName = "get_weather" @@ -43,7 +43,7 @@ export const weatherTool = ToolDefinition.make({ }, }) -export const weatherRuntimeTool = Tool.make({ +export const weatherRuntimeTool = tool({ description: weatherTool.description, parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ temperature: Schema.Number, condition: Schema.String }), diff --git a/packages/ai/test/speech.test.ts b/packages/ai/test/speech.test.ts index 139a3134a8b2..a30b39f1942b 100644 --- a/packages/ai/test/speech.test.ts +++ b/packages/ai/test/speech.test.ts @@ -1,7 +1,7 @@ import { describe, expect } from "bun:test" import { Effect, Layer, Stream } from "effect" import { Base64 } from "effect/encoding" -import { Speech, SpeechClient, SpeechEvent } from "../src/effect.js" +import { Speech, SpeechClient, SpeechEvent } from "../src/experimental.js" import { Cartesia, Deepgram, ElevenLabs, Google, OpenAI } from "../src/providers.js" import { it } from "./lib/effect.js" import { dynamicResponse } from "./lib/http.js" diff --git a/packages/ai/test/speech.types.ts b/packages/ai/test/speech.types.ts index 0a4f56841616..1b5793cb1024 100644 --- a/packages/ai/test/speech.types.ts +++ b/packages/ai/test/speech.types.ts @@ -1,5 +1,5 @@ import type { Stream } from "effect" -import { Speech, SpeechModel, type SpeechEvent, type SpeechOptions } from "../src/effect.js" +import { Speech, SpeechModel, type SpeechEvent, type SpeechOptions } from "../src/experimental.js" import { ElevenLabs, OpenAI, Runway } from "../src/providers.js" type StreamItem = T extends Stream.Stream ? A : never diff --git a/packages/ai/test/testing-media.test.ts b/packages/ai/test/testing-media.test.ts index 79f18eeef0c5..6645b2a99528 100644 --- a/packages/ai/test/testing-media.test.ts +++ b/packages/ai/test/testing-media.test.ts @@ -1,23 +1,18 @@ import { describe, expect, test } from "bun:test" import { Effect, Layer, Stream } from "effect" +import { AIError, Decision, DecisionResponse, Image, ImageResponse, Media, RateLimitError } from "../src/effect.js" import { - AIError, - Decision, - DecisionResponse, - Image, - ImageResponse, - Media, - RateLimitError, Speech, SpeechResponse, Transcription, TranscriptionResponse, Video, VideoResponse, -} from "../src/effect.js" +} from "../src/experimental.js" import { AI } from "../src/index.js" import { OpenAI, Runway } from "../src/providers.js" -import { TestDecision, TestImage, TestSpeech, TestTranscription, TestVideo } from "../src/testing.js" +import { TestDecision, TestImage } from "../src/testing.js" +import { TestSpeech, TestTranscription, TestVideo } from "../src/experimental/testing.js" import { testEffect } from "./lib/effect.js" const openai = OpenAI.configure({ apiKey: "test" }) @@ -113,13 +108,17 @@ describe("media test clients", () => { ) expect((await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })).image).toBe(png) - const generation = await ai.video.start({ model: runway, prompt: "A kite" }) - expect((await ai.video.resume(runway, generation.token).then((resumed) => resumed.await())).video).toBe(mp4) + const generation = await ai.experimental.video.start({ model: runway, prompt: "A kite" }) expect( - await ai.bytes((await ai.speech.generate({ model: openai.speech("gpt-4o-mini-tts"), text: "Hi" })).audio), + (await ai.experimental.video.resume(runway, generation.token).then((resumed) => resumed.await())).video, + ).toBe(mp4) + expect( + await ai.bytes( + (await ai.experimental.speech.generate({ model: openai.speech("gpt-4o-mini-tts"), text: "Hi" })).audio, + ), ).toEqual(Uint8Array.from([4, 5, 6])) const deltas = await Array.fromAsync( - ai.transcription.stream({ model: openai.transcription("gpt-4o-mini-transcribe"), audio }), + ai.experimental.transcription.stream({ model: openai.transcription("gpt-4o-mini-transcribe"), audio }), ) expect(deltas.map((event) => event.type)).toEqual(["finish"]) const decided = await ai.decision.generate({ diff --git a/packages/ai/test/testing.test.ts b/packages/ai/test/testing.test.ts index 0beec864cc2a..c994877dabac 100644 --- a/packages/ai/test/testing.test.ts +++ b/packages/ai/test/testing.test.ts @@ -337,7 +337,9 @@ describe("TestLLM first-class client", () => { ), ).toBe(failure) expect(observed).toEqual(events) - expect(yield* llm.generate(request).pipe(Effect.flip)).toBe(failure) + const generated = yield* llm.generate(request).pipe(Effect.flip) + expect(generated.reason).toBe(failure.reason) + expect(generated.partial?.text).toBe("partial") const defect = new Error("Broken fixture responder") yield* llm.serve(() => { diff --git a/packages/ai/test/tool-runtime.test.ts b/packages/ai/test/tool-runtime.test.ts index cf038f6fa3c8..51b2f24b5d49 100644 --- a/packages/ai/test/tool-runtime.test.ts +++ b/packages/ai/test/tool-runtime.test.ts @@ -16,7 +16,7 @@ import { Auth, LLMClient } from "../src/route.js" import * as AnthropicMessages from "../src/protocols/anthropic-messages.js" import * as OpenAIChat from "../src/protocols/openai-chat.js" import * as OpenAIResponses from "../src/protocols/openai-responses.js" -import { Tool, ToolFailure, type ToolExecuteContext } from "../src/tool.js" +import { ToolFailure, tool, type ToolExecuteContext } from "../src/tool.js" import { ToolRuntime } from "../src/tool-runtime.js" import { it } from "./lib/effect.js" import * as TestToolRuntime from "./lib/tool-runtime.js" @@ -39,7 +39,7 @@ const weatherFailureCause = new Error("weather lookup denied") test("dispatches namespaced calls by qualified identity", async () => { let context: ToolExecuteContext | undefined - const lookup = Tool.make({ + const lookup = tool({ description: "Look up a customer.", parameters: Schema.Struct({}), success: Schema.String, @@ -58,7 +58,7 @@ test("dispatches namespaced calls by qualified identity", async () => { expect(result.events).toEqual([expect.objectContaining({ type: "tool-result", namespace: "crm", name: "lookup" })]) }) -const get_weather = Tool.make({ +const get_weather = tool({ description: "Get current weather for a city.", parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ temperature: Schema.Number, condition: Schema.String }), @@ -70,7 +70,7 @@ const get_weather = Tool.make({ }), }) -const schema_only_weather = Tool.make({ +const schema_only_weather = tool({ description: "Get current weather for a city.", parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ temperature: Schema.Number, condition: Schema.String }), @@ -175,7 +175,7 @@ describe("LLMClient tools", () => { it.effect("projects encoded typed tool success into canonical model content", () => Effect.gen(function* () { const calls: unknown[] = [] - const projected = Tool.make({ + const projected = tool({ description: "Project an encoded success.", parameters: Schema.Struct({ prefix: Schema.String }), success: Schema.Struct({ count: Schema.NumberFromString }), @@ -207,7 +207,7 @@ describe("LLMClient tools", () => { it.effect("preserves provider metadata on dispatched tool results", () => Effect.gen(function* () { - const tool = Tool.make({ + const text = tool({ description: "Return text.", parameters: Schema.Struct({}), success: Schema.String, @@ -215,14 +215,14 @@ describe("LLMClient tools", () => { }) const providerMetadata = { google: { thoughtSignature: "provider_sig" } } const dispatched = yield* ToolRuntime.dispatch( - { tool }, - LLMEvent.toolCall({ id: "call_1", name: "tool", input: {}, providerMetadata }), + { text }, + LLMEvent.toolCall({ id: "call_1", name: "text", input: {}, providerMetadata }), ) expect(dispatched.events).toEqual([ LLMEvent.toolResult({ id: "call_1", - name: "tool", + name: "text", result: { type: "text", value: "hello" }, output: { structured: "hello", content: [{ type: "text", text: "hello" }] }, providerMetadata, @@ -255,13 +255,13 @@ describe("LLMClient tools", () => { it.effect("uses the narrow default projection for encoded typed success", () => Effect.gen(function* () { - const text = Tool.make({ + const text = tool({ description: "Return text.", parameters: Schema.Struct({}), success: Schema.String, execute: () => Effect.succeed("hello"), }) - const json = Tool.make({ + const json = tool({ description: "Return JSON.", parameters: Schema.Struct({}), success: Schema.Struct({ ok: Schema.Boolean }), @@ -279,7 +279,7 @@ describe("LLMClient tools", () => { it.effect("can retain model media while redacting duplicated structured payloads", () => Effect.gen(function* () { - const image = Tool.make({ + const image = tool({ description: "Return an image.", parameters: Schema.Struct({}), success: Schema.Struct({ mime: Schema.String, data: Schema.String }), @@ -360,7 +360,7 @@ describe("LLMClient tools", () => { it.effect("settles projected URL files as canonical tool results", () => Effect.gen(function* () { - const remote = Tool.make({ + const remote = tool({ description: "Return a remote file.", parameters: Schema.Struct({}), success: Schema.Struct({ ok: Schema.Boolean }), @@ -389,7 +389,7 @@ describe("LLMClient tools", () => { const [typed] = toDefinitions({ get_weather }) const schema = { type: "object", properties: { result: { type: "string" } } } as const const [dynamic] = toDefinitions({ - dynamic: Tool.make({ description: "Dynamic tool.", jsonSchema: { type: "object" }, outputSchema: schema }), + dynamic: tool({ description: "Dynamic tool.", jsonSchema: { type: "object" }, outputSchema: schema }), }) expect(typed?.outputSchema).toMatchObject({ @@ -406,7 +406,7 @@ describe("LLMClient tools", () => { it.effect("preserves content tool results from dynamic tools", () => Effect.gen(function* () { - const screenshot = Tool.make({ + const screenshot = tool({ description: "Capture a screenshot.", jsonSchema: { type: "object", properties: {} }, execute: () => @@ -446,7 +446,7 @@ describe("LLMClient tools", () => { it.effect("does not mistake dynamic tool output fields for dispatcher state", () => Effect.gen(function* () { const callerOwned = { type: "json" as const, value: { ok: true }, events: ["caller-owned"] } - const eventful = Tool.make({ + const eventful = tool({ description: "Return an events field.", jsonSchema: { type: "object", properties: {} }, execute: () => Effect.succeed(callerOwned), @@ -472,7 +472,7 @@ describe("LLMClient tools", () => { it.effect("projects malformed tagged dynamic output as opaque JSON", () => Effect.gen(function* () { const malformed = { type: "content", value: [{ type: "text" }] } - const dynamic = Tool.make({ + const dynamic = tool({ description: "Return caller-defined JSON.", jsonSchema: { type: "object", properties: {} }, execute: () => Effect.succeed(malformed), @@ -518,7 +518,7 @@ describe("LLMClient tools", () => { it.effect("passes tool call context to execute", () => Effect.gen(function* () { let context: ToolExecuteContext | undefined - const contextual = Tool.make({ + const contextual = tool({ description: "Capture tool context.", parameters: Schema.Struct({ value: Schema.String }), success: Schema.Struct({ ok: Schema.Boolean }), diff --git a/packages/ai/test/tool-schema-projection.test.ts b/packages/ai/test/tool-schema-projection.test.ts index 018680d98d53..ff28f017fa77 100644 --- a/packages/ai/test/tool-schema-projection.test.ts +++ b/packages/ai/test/tool-schema-projection.test.ts @@ -3,7 +3,7 @@ import { Effect, Schema, SchemaGetter } from "effect" import { LLM } from "../src/effect.js" import { AnthropicMessages, Gemini, OpenAIChat, OpenAIResponses } from "../src/protocols.js" import { ToolSchemaProjection } from "../src/protocols/utils/tool-schema.js" -import { Tool, toDefinitions } from "../src/tool.js" +import { toDefinitions, tool } from "../src/tool.js" import { Auth } from "../src/route.js" import { compileRequest } from "../src/route/client.js" import { it } from "./lib/effect.js" @@ -32,14 +32,14 @@ const reversed = Token.pipe( describe("tool schema projections", () => { test("only normalizes typed empty input structs, preserving raw schemas and output schemas", () => { const schema = { not: { type: "null" } } - const definitions = Tool.toDefinitions({ - typed: Tool.make({ + const definitions = toDefinitions({ + typed: tool({ description: "Typed", parameters: Schema.Struct({}), success: Schema.Struct({}), execute: () => Effect.succeed({}), }), - raw: Tool.make({ description: "Raw", jsonSchema: schema, execute: () => Effect.succeed({}) }), + raw: tool({ description: "Raw", jsonSchema: schema, execute: () => Effect.succeed({}) }), }) expect(definitions[0]?.inputSchema).toEqual({ type: "object", properties: {}, additionalProperties: false }) expect(definitions[0]?.outputSchema).toEqual(schema) @@ -49,9 +49,9 @@ describe("tool schema projections", () => { test("retains empty input descriptions and preserves named outputs and explicit raw schemas", () => { const parameters = Schema.Struct({}).annotate({ identifier: "Ping", description: "No arguments" }) const raw = { $ref: "#/$defs/Raw", $defs: { Raw: { not: { type: "null" }, description: "Raw schema" } } } - const definitions = Tool.toDefinitions({ - typed: Tool.make({ description: "Ping", parameters, success: parameters, execute: () => Effect.succeed({}) }), - raw: Tool.make({ description: "Raw", jsonSchema: raw, execute: () => Effect.succeed({}) }), + const definitions = toDefinitions({ + typed: tool({ description: "Ping", parameters, success: parameters, execute: () => Effect.succeed({}) }), + raw: tool({ description: "Raw", jsonSchema: raw, execute: () => Effect.succeed({}) }), }) expect(definitions[0]?.inputSchema).toEqual({ type: "object", @@ -67,33 +67,33 @@ describe("tool schema projections", () => { }) test("normalizes inputs whose encoded side is an empty struct", () => { - const definitions = Tool.toDefinitions({ - defaulted: Tool.make({ description: "Defaulted", parameters: defaulted, success: defaulted }), - named: Tool.make({ + const definitions = toDefinitions({ + defaulted: tool({ description: "Defaulted", parameters: defaulted, success: defaulted }), + named: tool({ description: "Named", parameters: defaulted.annotate({ identifier: "Defaulted" }), success: Schema.String, }), - encodedMetadata: Tool.make({ + encodedMetadata: tool({ description: "Encoded metadata", parameters: Schema.Struct({}) .annotate({ identifier: "Ping", title: "Ping", description: "No arguments" }) .pipe(Schema.decodeTo(Token, fromEmpty)), success: Schema.String, }), - decodedCheck: Tool.make({ + decodedCheck: tool({ description: "Decoded check", parameters: defaulted.check(Schema.makeFilter(() => true, { toJsonSchema: () => ({ minProperties: 1 }) })), success: Schema.String, }), - reversed: Tool.make({ description: "Reversed", parameters: reversed, success: Schema.String }), - encodedCheck: Tool.make({ + reversed: tool({ description: "Reversed", parameters: reversed, success: Schema.String }), + encodedCheck: tool({ description: "Encoded check", parameters: Schema.Struct({}).check(Schema.isMinProperties(1)), success: Schema.String, }), // A filter without a JSON Schema form emits nothing, so the input still describes an empty object. - encodedFilter: Tool.make({ + encodedFilter: tool({ description: "Encoded filter", parameters: Schema.Struct({}).check(Schema.makeFilter(() => true)), success: Schema.String, @@ -161,27 +161,27 @@ describe("tool schema projections", () => { LLM.request({ model: scenario.route.with({ auth: Auth.bearer("test") }).model({ id: "test-model" }), prompt: "Use a tool.", - tools: Tool.toDefinitions({ - ping: Tool.make({ + tools: toDefinitions({ + ping: tool({ description: "Ping", parameters: Schema.Struct({}), success: Schema.String, execute: () => Effect.succeed("pong"), }), - lookup: Tool.make({ + lookup: tool({ description: "Lookup", parameters: Schema.Struct({ query: Schema.String }), success: Schema.String, execute: (input) => Effect.succeed(input.query), }), - raw: Tool.make({ description: "Raw", jsonSchema: raw, execute: () => Effect.succeed("raw") }), - reversed: Tool.make({ + raw: tool({ description: "Raw", jsonSchema: raw, execute: () => Effect.succeed("raw") }), + reversed: tool({ description: "Reversed", parameters: reversed, success: Schema.String, execute: () => Effect.succeed("reversed"), }), - checked: Tool.make({ + checked: tool({ description: "Checked", parameters: Schema.Struct({}).check(Schema.isMinProperties(1)), success: Schema.String, @@ -289,7 +289,7 @@ describe("tool schema projections", () => { }), ).pipe(Effect.map((prepared) => prepared.body.tools?.[0]?.function.parameters)) const parameterless = toDefinitions({ - lookup: Tool.make({ + lookup: tool({ description: "Lookup data.", parameters: Schema.Struct({}).annotate({ description: "No input." }), success: Schema.String, diff --git a/packages/ai/test/tool.types.ts b/packages/ai/test/tool.types.ts index bc5dcfd9c44e..85f16c40054a 100644 --- a/packages/ai/test/tool.types.ts +++ b/packages/ai/test/tool.types.ts @@ -1,8 +1,7 @@ import { Effect, Schema } from "effect" -import { LLM, LLMRequest, ToolRuntime, toDefinitions } from "../src/effect.js" +import { LLM, LLMRequest, ToolRuntime, toDefinitions, tool, type ExecutableTool } from "../src/effect.js" import * as OpenAIChat from "../src/protocols/openai-chat.js" import { Auth } from "../src/route.js" -import { Tool } from "../src/tool.js" import { AI } from "../src/index.js" const request = LLM.request({ @@ -10,20 +9,20 @@ const request = LLM.request({ prompt: "Use the tool.", }) -const executable = Tool.make({ +const executable = tool({ description: "Get weather.", parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ forecast: Schema.String }), execute: (input) => Effect.succeed({ forecast: input.city }), }) -const schemaOnly = Tool.make({ +const schemaOnly = tool({ description: "Get weather.", parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ forecast: Schema.String }), }) -Tool.make({ +tool({ description: "Encode success before projection.", parameters: Schema.Struct({ city: Schema.String }), success: Schema.Struct({ forecast: Schema.NumberFromString }), @@ -42,7 +41,7 @@ LLM.stream({ request, tools: { schemaOnly } }) const code = Schema.Struct({ code: Schema.String }) -Tool.make({ +tool({ description: "Run JavaScript.", parameters: code, success: Schema.String, @@ -57,11 +56,11 @@ AI.tool({ execute: (input) => input.code, }) -Tool.make({ +tool({ description: "Run JavaScript.", - // @ts-expect-error A freeform tool's only parameter must be a string. parameters: Schema.Struct({ code: Schema.Number }), success: Schema.String, + // @ts-expect-error A freeform tool's only parameter must be a string. freeform: { type: "text" }, }) @@ -80,3 +79,19 @@ AI.tool({ freeform: { type: "text" }, execute: () => undefined, }) + +const sum = { + description: "Add two numbers.", + parameters: Schema.Struct({ a: Schema.Number, b: Schema.Number }), + success: Schema.Number, + toModelOutput: ({ output }: { readonly output: number }) => [{ type: "text" as const, text: String(output) }], +} +const declared: AI.Tool = AI.tool(sum) +const effectSum: ExecutableTool = tool({ ...sum, execute: ({ a, b }) => Effect.succeed(a + b) }) +const promiseSum: AI.ExecutableTool = AI.tool({ ...sum, execute: async ({ a, b }) => a + b }) +toDefinitions({ declared, effectSum, promiseSum, dynamic: AI.tool({ description: "Look up.", jsonSchema: {} }) }) + +// @ts-expect-error The Effect tool's execute returns an Effect. +tool({ ...sum, execute: ({ a, b }) => a + b }) +// @ts-expect-error The execute result must match `success`. +AI.tool({ ...sum, execute: async () => "3" }) diff --git a/packages/ai/test/transcription.test.ts b/packages/ai/test/transcription.test.ts index 05c4f6a42299..74030febf12d 100644 --- a/packages/ai/test/transcription.test.ts +++ b/packages/ai/test/transcription.test.ts @@ -2,7 +2,8 @@ import { describe, expect } from "bun:test" import { Effect, Fiber, Layer, Stream } from "effect" import * as TestClock from "effect/testing/TestClock" import { HttpClientRequest } from "effect/http" -import { Media, Transcription, TranscriptionClient, type TranscriptionEvent } from "../src/effect.js" +import { Media } from "../src/effect.js" +import { Transcription, TranscriptionClient, type TranscriptionEvent } from "../src/experimental.js" import { AssemblyAI, Deepgram, ElevenLabs, Google, OpenAI } from "../src/providers.js" import { it } from "./lib/effect.js" import { dynamicResponse, json, observe, type Call } from "./lib/http.js" diff --git a/packages/ai/test/transcription.types.ts b/packages/ai/test/transcription.types.ts index c9522953853c..903e0b8f8e07 100644 --- a/packages/ai/test/transcription.types.ts +++ b/packages/ai/test/transcription.types.ts @@ -1,11 +1,11 @@ import type { Stream } from "effect" +import { Media } from "../src/effect.js" import { - Media, Transcription, TranscriptionModel, type TranscriptionEvent, type TranscriptionOptions, -} from "../src/effect.js" +} from "../src/experimental.js" import { AssemblyAI, Deepgram, OpenAI } from "../src/providers.js" type StreamItem = T extends Stream.Stream ? A : never diff --git a/packages/ai/test/video.test.ts b/packages/ai/test/video.test.ts index 3aef30e0582d..3fe4d4ef77e8 100644 --- a/packages/ai/test/video.test.ts +++ b/packages/ai/test/video.test.ts @@ -1,7 +1,8 @@ import { describe, expect } from "bun:test" import { Effect, Fiber, Layer, Stream } from "effect" import * as TestClock from "effect/testing/TestClock" -import { Media, Video, VideoClient, type GenerationEvent, type VideoEvent } from "../src/effect.js" +import { Media, type GenerationEvent } from "../src/effect.js" +import { Video, VideoClient, type VideoEvent } from "../src/experimental.js" import { Google, Runway, XAI } from "../src/providers.js" import { it } from "./lib/effect.js" import { dynamicResponse, json, observe, settle, type Call, type HandlerInput } from "./lib/http.js" @@ -1043,15 +1044,33 @@ describe("Video / queued result", () => { ) } - it.effect("rejects a status that only matches an inherited property", () => + it.effect("keeps polling through unknown statuses, including inherited property names", () => Effect.gen(function* () { - const error = yield* Video.resume( - XAI.configure({ apiKey: "test", baseURL: "https://xai.test/v1" }).video("grok-imagine-video-1.5"), - { requestID: "req_1" }, - ).pipe(Effect.flip) - expect(error.reason._tag).toBe("InvalidProviderOutput") - expect(error.message).toBe('Unknown generation status "constructor"') - expect(error.reason.body).toBe(JSON.stringify({ status: "constructor" })) - }).pipe(Effect.provide(layer((input) => Effect.succeed(json(input, { status: "constructor" }))))), + const calls: Array = [] + const response = yield* settle( + Video.generate( + { + model: Runway.configure({ apiKey: "test", baseURL: "https://runway.test/v1" }).video("gen4.5"), + prompt: "x", + }, + { poll: { interval: "1 second" } }, + ), + 3, + ).pipe( + Effect.provide( + layer((input) => + Effect.gen(function* () { + const { call, nth } = yield* observe(calls, input) + if (call.method === "POST") return json(input, { id: "task_1" }) + if (nth === 1) return json(input, { id: "task_1", status: "WARMING_UP" }) + if (nth === 2) return json(input, { id: "task_1", status: "constructor" }) + return json(input, { id: "task_1", status: "SUCCEEDED", output: ["https://runway.test/out.mp4"] }) + }), + ), + ), + ) + expect(response.video.source).toMatchObject({ type: "url", url: "https://runway.test/out.mp4" }) + expect(calls.map((call) => call.method)).toEqual(["POST", "GET", "GET", "GET", "GET"]) + }), ) }) diff --git a/packages/ai/test/video.types.ts b/packages/ai/test/video.types.ts index f7ac2b81129d..9e854672b1c7 100644 --- a/packages/ai/test/video.types.ts +++ b/packages/ai/test/video.types.ts @@ -1,7 +1,6 @@ import { Effect } from "effect" +import { Generation, Media } from "../src/effect.js" import { - Generation, - Media, Video, VideoClient, VideoModel, @@ -9,7 +8,7 @@ import { type VideoModelOptions, type VideoOptions, type VideoRequestFor, -} from "../src/effect.js" +} from "../src/experimental.js" import type { Service } from "../src/video-client.js" import { Anthropic, Google, OpenAI, Runway, XAI } from "../src/providers.js" diff --git a/packages/ai/tsconfig.types.json b/packages/ai/tsconfig.types.json index 911f47029d01..fd12c46e32a2 100644 --- a/packages/ai/tsconfig.types.json +++ b/packages/ai/tsconfig.types.json @@ -8,6 +8,8 @@ "include": [ "example/**/*.ts", "test/**/*.types.ts", + "test/loop.test.ts", + "test/promise.test.ts", "test/testing.test.ts", "test/testing-media.test.ts", "test/provider/checkpoint.test.ts" diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md index 5918a0f328a8..928eccf179e8 100644 --- a/packages/app/AGENTS.md +++ b/packages/app/AGENTS.md @@ -15,6 +15,13 @@ - App (from `packages/app`): `bun dev -- --port 4444` - Open `http://localhost:4444` to verify UI changes (it targets the backend at `http://localhost:4096`). +## Insecure Origins (HTTP LAN) + +The Web UI is served over plain HTTP on non-localhost LAN and Tailscale origins (`isSecureContext === false`). This rule applies across `app`, `ui`, `session-ui` and `gui-plugins` window code. + +- Never call `crypto.randomUUID()` directly in renderer or browser code; it is `[SecureContext]`-only and throws `TypeError: crypto.randomUUID is not a function` on plain HTTP origins. Always use `uuid()` from `@opencode/util/uuid`. +- Guard any other `[SecureContext]`-only Web API (`crypto.subtle`, `navigator.clipboard`, `navigator.serviceWorker`) with a non-secure fallback. + ## SolidJS - Always prefer `createStore` over multiple `createSignal` calls diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index cb2a0c7db6d2..ef5fc0f6ba60 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -463,6 +463,40 @@ story("keeps toolbar focus rings whole and keyboard-only", async ({ mount, page await expect(variant).toHaveCSS("outline-style", "none") }) +story("keeps command selection on the keyboard until the pointer moves", async ({ mount, page }) => { + const component = await mount("opencode-composer-flow--slash-suggestions") + + const input = component.getByRole("textbox", { name: "Prompt", exact: true }) + + const menu = component.locator('[data-component="composer-suggestions"]') + + const test = menu.getByRole("button", { name: "/test", exact: true }) + + const review = menu.getByRole("button", { name: "/review", exact: true }) + + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + await expect(test).toHaveAttribute("data-active", "") + + const box = await review.boundingBox() + + if (!box) throw new Error("Missing review command") + + await input.press("Escape") + await expect(menu).toHaveCount(0) + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2) + await input.fill("/") + await expect(test).toHaveAttribute("data-active", "") + await expect(review).toHaveCSS("background-color", "rgba(0, 0, 0, 0)") + + // Layout changes can deliver pointer events without any actual mouse movement. + await review.dispatchEvent("pointermove", { movementX: 0, movementY: 0 }) + await expect(test).toHaveAttribute("data-active", "") + + await page.mouse.move(box.x + box.width / 2 + 2, box.y + box.height / 2) + await expect(review).toHaveAttribute("data-active", "") + await expect(test).not.toHaveAttribute("data-active") +}) + story("grows suggestions while preserving visible timeline context", async ({ mount }) => { const component = await mount("opencode-composer-flow--constrained-command-suggestions") const boundary = component.locator('[data-slot="composer-suggestion-boundary-story"]') diff --git a/packages/app/component-tests/session-question-dock.spec.ts b/packages/app/component-tests/session-question-dock.spec.ts index f2df5f7cb259..a9bd0538125d 100644 --- a/packages/app/component-tests/session-question-dock.spec.ts +++ b/packages/app/component-tests/session-question-dock.spec.ts @@ -2,6 +2,70 @@ import type { Locator } from "@playwright/test" import type { MotionKnob } from "@opencode/ui/motion-tuning" import { expect, sourceURL, story } from "../../stories/playwright/story" +for (const variant of ["classic", "experimental"] as const) { + story(`${variant} answer cards allow text selection without changing answers`, async ({ mount, page }) => { + await page.addInitScript( + (enabled) => localStorage.setItem("settings.v3", JSON.stringify({ general: { newQuestionUI: enabled } })), + variant === "experimental", + ) + + const component = await mount("app-current-session-surface--question-request") + + const question = component.locator('[data-component="dock-prompt"][data-kind="question"]') + + const wide = question.getByRole("radio", { name: /Wide/ }) + + await expect(question.getByRole("radio", { name: /Focused/ })).toBeFocused() + await page.evaluate(() => document.fonts.ready.then(() => undefined)) + + const drag = async (text: Locator) => { + await text.scrollIntoViewIfNeeded() + + const box = await text.boundingBox() + + expect(box).not.toBeNull() + await page.mouse.move(box!.x + 1, box!.y + box!.height / 2) + await page.mouse.down() + await page.mouse.move(box!.x + box!.width - 1, box!.y + box!.height / 2, { steps: 12 }) + await page.mouse.up() + await expect.poll(() => page.evaluate(() => window.getSelection()?.toString().trim())).toBe(await text.innerText()) + } + + for (const slot of ["option-label", "option-description"]) { + await drag(wide.locator(`[data-slot="${slot}"] bdi`)) + await expect(wide).not.toBeChecked() + } + + await wide.locator('[data-slot="option-description"] bdi').click({ modifiers: ["Shift"] }) + await expect(wide).not.toBeChecked() + await wide.click({ position: { x: 4, y: 4 } }) + await expect(wide).toBeChecked() + await question.getByRole("radio", { name: /Focused/ }).click() + await drag(wide.locator('[data-slot="option-description"] bdi')) + await expect(wide).not.toBeChecked() + + const mark = await wide.locator('[data-slot="question-option-check"]').boundingBox() + + expect(mark).not.toBeNull() + await page.mouse.move(mark!.x + mark!.width / 2, mark!.y + mark!.height / 2) + await page.mouse.down() + await page.mouse.move(mark!.x + mark!.width / 2 + 1, mark!.y + mark!.height / 2) + await page.mouse.up() + await expect(wide).toBeChecked() + await question.getByRole("button", { name: "Next", exact: true }).click() + + const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) + + await expect(files).toBeFocused() + await files.click() + await expect(files).toBeChecked() + await drag(files.locator('[data-slot="option-label"] bdi')) + await expect(files).toBeChecked() + await files.click({ position: { x: 4, y: 4 } }) + await expect(files).not.toBeChecked() + }) +} + story( "uses the original question cards by default and submits selected and custom answers", async ({ mount, page }) => { @@ -32,7 +96,9 @@ story( const submit = question.getByRole("button", { name: "Submit", exact: true }) expect(await submit.evaluate((button) => button.getBoundingClientRect().width)).toBe(width) await expect(shortcuts).toHaveText(["1", "2", "3", "4"]) - await files.click() + await page.keyboard.down(" ") + await page.keyboard.down(" ") + await page.keyboard.up(" ") await terminal.click() await expect(files).toBeChecked() await expect(terminal).toBeChecked() diff --git a/packages/app/component-tests/timeline-virtualizer.fixture.tsx b/packages/app/component-tests/timeline-virtualizer.fixture.tsx index d7b667667fa7..c25e0d34a74e 100644 --- a/packages/app/component-tests/timeline-virtualizer.fixture.tsx +++ b/packages/app/component-tests/timeline-virtualizer.fixture.tsx @@ -19,7 +19,7 @@ export function mountTimelineVirtualizer(input: { document.body.appendChild(host) function Fixture() { - const [state, setState] = createStore({ pinned: true, ready: false }) + const [state, setState] = createStore({ pinned: true, ready: false, grown: false }) const rows = Array.from( { length: input.count }, @@ -31,6 +31,7 @@ export function mountTimelineVirtualizer(input: { let viewport!: HTMLDivElement let content!: HTMLDivElement let container!: HTMLDivElement + let scrollToEnd = () => {} const timeline = createTimelineVirtualizer({ sessionKey: () => "cold-reveal-fixture", @@ -50,9 +51,10 @@ export function mountTimelineVirtualizer(input: { viewport = element resize.observe(element, { box: "border-box" }) }, - setContentRef: (element) => { - content = element - reveal.observe(element, { attributes: true, attributeFilter: ["style"] }) + onContentResize: () => { + if (content) return + content = host.querySelector("[data-timeline-virtual-content]")! + reveal.observe(content, { attributes: true, attributeFilter: ["style"] }) }, onPin: () => setState("pinned", true), onUnpin: () => setState("pinned", false), @@ -65,6 +67,9 @@ export function mountTimelineVirtualizer(input: { onUserScroll: () => {}, onHistoryScroll: () => {}, canRenderImmediately: () => input.immediate ?? false, + setScrollToEnd: (fn) => { + scrollToEnd = fn + }, }) const resize = new ResizeObserver((entries) => { @@ -117,6 +122,12 @@ export function mountTimelineVirtualizer(input: { > Reconnect ready rows + +

diff --git a/packages/app/component-tests/timeline-virtualizer.spec.ts b/packages/app/component-tests/timeline-virtualizer.spec.ts index 994570d69467..bece9cd84f0c 100644 --- a/packages/app/component-tests/timeline-virtualizer.spec.ts +++ b/packages/app/component-tests/timeline-virtualizer.spec.ts @@ -89,6 +89,45 @@ story("treats the reachable end as the end under page zoom", async ({ page }) => await expect(controls).toHaveAttribute("data-pinned", "true") }) +story("leaves a reader who scrolled up in place after a scroll to the zoomed end", async ({ page }) => { + // At 110% the end the browser reaches sits more than a pixel short of scrollHeight - clientHeight. TanStack kept + // scrolling toward that max on every frame for five seconds, so a row that grew meanwhile pulled the reader back down. + await page.evaluate(async (fixture) => { + document.documentElement.style.zoom = "1.1" + const { mountTimelineVirtualizer } = await import(fixture) + mountTimelineVirtualizer({ count: 40, rowHeight: 59.3, immediate: true, viewportHeight: 200.5 }) + }, fixture) + const root = page.getByTestId("timeline-virtualizer-fixture") + await root.getByRole("button", { name: "Complete Markdown", exact: true }).click() + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + const viewport = root.locator("[data-scrollable]") + const distance = () => viewport.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop) + expect(await distance()).toBeGreaterThan(1.01) + + // A scroll command settles or scrolls again on its next frame. + const frames = () => + page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))) + + await root.getByRole("button", { name: "Scroll to end", exact: true }).click() + await frames() + // The wheel and the scroll it causes arrive together. A wheel alone would leave an earlier arrival at the end free to + // pin again once that scroll settles. + await viewport.evaluate( + (element) => + new Promise((resolve) => { + element.addEventListener("scroll", resolve, { once: true }) + element.dispatchEvent(new WheelEvent("wheel", { deltaY: -1, bubbles: true })) + element.scrollTop -= 40 + }), + ) + await expect(root.getByTestId("timeline-controls")).toHaveAttribute("data-pinned", "false") + const height = await viewport.evaluate((element) => element.scrollHeight) + await root.getByRole("button", { name: "Grow last row", exact: true }).click() + await expect.poll(() => viewport.evaluate((element) => element.scrollHeight)).toBeGreaterThan(height + 30) + await frames() + expect(await distance()).toBeGreaterThan(70) +}) + for (const input of [ { name: "offset-only", count: 1, rowHeight: 600, reveal: { scrollTop: 0 } }, { name: "zero-height", count: 4, rowHeight: 60, reveal: {} }, diff --git a/packages/app/e2e/regression/command-palette.spec.ts b/packages/app/e2e/regression/command-palette.spec.ts index bfadd05f5711..a1b01d6bab06 100644 --- a/packages/app/e2e/regression/command-palette.spec.ts +++ b/packages/app/e2e/regression/command-palette.spec.ts @@ -6,6 +6,7 @@ import { openPaletteWorkspace, paletteSession, } from "../utils/command-palette" +import { mockWorkspace } from "../utils/workspace" test.use({ serviceWorkers: "block", permissions: ["clipboard-read", "clipboard-write"] }) @@ -130,6 +131,29 @@ test("titlebar search lists recent sessions and opens the typed match", async ({ await expect(page.getByRole("heading", { name: paletteSession.title, exact: true })).toBeVisible() }) +test("a working session keeps its project avatar in Search sessions and shows its activity ring in place of its age", async ({ + page, +}) => { + const working = { id: "ses_palette_working", title: "Working session" } + const idle = { id: "ses_palette_idle", title: "Idle session" } + await mockWorkspace(page, { + name: "PaletteActivity", + sessions: [working, idle], + sessionStatus: { [working.id]: { type: "running" } }, + }) + await page.goto("/") + await page.getByRole("banner").getByRole("button", { name: "Search sessions", exact: true }).click() + const dialog = page.getByRole("dialog") + const workingRow = dialog.getByRole("option", { name: /Working session/ }) + const idleRow = dialog.getByRole("option", { name: /Idle session/ }) + await expect(workingRow.locator('[data-component="activity-ring"]')).toBeVisible() + await expect(workingRow.locator('[data-component="project-avatar-v2"]')).toBeVisible() + await expect(workingRow.locator(".command-palette-meta")).toHaveText("Working") + await expect(idleRow.locator('[data-component="activity-ring"]')).toHaveCount(0) + await expect(idleRow.locator('[data-component="project-avatar-v2"]')).toBeVisible() + await expect(idleRow.locator(".command-palette-meta")).not.toHaveText("Working") +}) + test("Search commands lists only commands and runs the chosen one", async ({ page }) => { const { dialog, input } = await openCommandPalette(page, true) await input.fill("search commands") diff --git a/packages/app/e2e/regression/home.spec.ts b/packages/app/e2e/regression/home.spec.ts index 3ef6662e0bca..dee6a3655ce2 100644 --- a/packages/app/e2e/regression/home.spec.ts +++ b/packages/app/e2e/regression/home.spec.ts @@ -39,6 +39,41 @@ test("Home keeps the session list in every interface mode", async ({ page }) => } }) +test("a working Home session keeps its project avatar and shows its activity ring at the end of the row", async ({ + page, +}) => { + const working = { id: "ses_home_working", title: "Working session" } + const idle = { id: "ses_home_idle", title: "Idle session" } + await mockWorkspace(page, { + name: "HomeActivity", + sessions: [working, idle], + sessionStatus: { [working.id]: { type: "running" } }, + }) + await page.goto("/") + const ring = row(page, working.title).locator('[data-component="activity-ring"]') + await expect(ring).toBeVisible() + await expect(row(page, working.title).locator('[data-component="project-avatar-v2"]')).toBeVisible() + await expect(row(page, idle.title).locator('[data-component="activity-ring"]')).toHaveCount(0) + + // The ring trails the title rather than standing in for the avatar. + const title = await row(page, working.title).getByText(working.title, { exact: true }).boundingBox() + const box = await ring.boundingBox() + expect(box!.x).toBeGreaterThan(title!.x + title!.width) +}) + +test("Home lists projects and sessions when stored state hides every server", async ({ page }) => { + await mockStressTimeline(page) + await seed(page, { usedProjects: { local: [fixture.project.id] } }) + // A second seed merges into the server entry the first one wrote. + await seed(page, { storage: { "opencode.global.dat:server": { hidden: { [fixture.serverKey]: true } } } }) + await page.goto("/") + + await expect( + page.locator('[data-component="home-project-row"]').filter({ hasText: fixture.project.name }), + ).toBeVisible() + await expect(row(page, fixture.expected.targetTitle)).toBeVisible() +}) + test("the session context menu renames, exports, and deletes a Home session", async ({ page }) => { await openHome(page) const target = row(page, fixture.expected.targetTitle) diff --git a/packages/app/e2e/regression/mobile-session.spec.ts b/packages/app/e2e/regression/mobile-session.spec.ts index 7af867b036ae..f5209a13b5cc 100644 --- a/packages/app/e2e/regression/mobile-session.spec.ts +++ b/packages/app/e2e/regression/mobile-session.spec.ts @@ -347,6 +347,7 @@ test.describe("touch", () => { await expect(page).toHaveURL(new RegExp(`/session/${fixture.sourceID}$`)) await expect(drawer).toBeHidden() await expect(trigger).toContainText(fixture.expected.sourceTitle) + await expect(trigger).toBeFocused() await trigger.click() await drawer.getByRole("button", { name: "Home", exact: true }).click() await expect(page).toHaveURL("/") diff --git a/packages/app/e2e/regression/multi-server.spec.ts b/packages/app/e2e/regression/multi-server.spec.ts index 288cc0b1aa18..1caa8e119cf1 100644 --- a/packages/app/e2e/regression/multi-server.spec.ts +++ b/packages/app/e2e/regression/multi-server.spec.ts @@ -233,7 +233,7 @@ test("a project's auto-accept choice overrides the default in both directions", onPermissionReply: (reply) => replies.push(reply.permissionID), }, }) - await seed(page, { tabs: [api.id, web.id] }) + await seed(page, { tabs: [api.id, web.id], usedProjects: { local: ["proj_api", "proj_web"] } }) const dock = page.locator('[data-component="dock-prompt"][data-kind="permission"]') const settings = page.getByTestId("settings-screen") diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts index d69d13418d36..b19900317bc3 100644 --- a/packages/app/e2e/regression/new-session.spec.ts +++ b/packages/app/e2e/regression/new-session.spec.ts @@ -2,7 +2,14 @@ import { expect, test, type Locator, type Page } from "@playwright/test" import type { OpenCodeEvent, WorktreeDirectory } from "@opencode/client/promise" import { draftHref, expectPath, NO_PROVIDER, project, provider, seed, sessionHref, T0 } from "../utils/app" import { mockOpenCodeServer } from "../utils/mock-server" -import { newSessionLocation, openDraft, openSession, openWorktreeDraft, type WorkspaceInput } from "../utils/workspace" +import { + newSessionLocation, + newSessionWorktree, + openDraft, + openSession, + openWorktreeDraft, + type WorkspaceInput, +} from "../utils/workspace" const directory = "C:/OpenCode/WorkspacePending" @@ -52,19 +59,32 @@ test("the new session screen does not show session details", async ({ page }) => }) test("the location shortcut keeps cycling after hovering its icon", async ({ page }) => { - const view = await openDraft(page, { name: "LocationShortcut" }) + const existing = "C:/OpenCode/LocationShortcut/.worktrees/quiet-river" + + const view = await openDraft(page, { + name: "LocationShortcut", + worktrees: () => [{ directory: "C:/OpenCode/LocationShortcut" }, { directory: existing, strategy: "git" }], + }) + const modifier = await page.evaluate(() => (/Mac/i.test(navigator.platform) ? "Meta" : "Control")) + const path = page.locator('[data-slot="new-session-location-path"]') + const icon = page.locator('[data-slot="new-session-location-icon"]') + + // The worktree trigger already says Local, so the local path has no icon of its own. + await expect(path).toHaveText(view.directory) + await expect(icon).toHaveCount(0) + await newSessionWorktree(page).click() + await page.getByRole("option", { name: /^quiet-river / }).click() await expect(view.editor).toBeFocused() + await expect(path).toHaveText(existing) + await icon.hover() + await expect(page.getByRole("tooltip")).toContainText("Toggle session location") await view.editor.press(`${modifier}+Alt+KeyL`) - await expect(newSessionLocation(page)).toContainText("New worktree") + await expect(newSessionWorktree(page)).toHaveText("Local") + await expect(icon).toHaveCount(0) await expect(view.editor).toBeFocused() await view.editor.press(`${modifier}+Alt+KeyL`) - await expect(newSessionLocation(page)).not.toContainText("New worktree") - await expect(page.locator('[data-slot="new-session-location-path"]')).toHaveText(view.directory) - await page.locator('[data-slot="new-session-location-icon"]').hover() - await expect(page.getByRole("tooltip")).toContainText("Toggle session location") - await view.editor.press(`${modifier}+Alt+KeyL`) - await expect(newSessionLocation(page)).toContainText("New worktree") + await expect(newSessionWorktree(page)).toContainText("New worktree") await expect(view.editor).toBeFocused() }) @@ -172,7 +192,10 @@ test("the combined location picker shows checkout branches and chooses the base await expect(page.getByRole("option")).toHaveCount(1) await page.getByRole("option", { name: /Custom project C:\/OpenCode\/BranchContext/ }).click() await expect(view.editor).toBeFocused() + await expect(screen.getByRole("button", { name: "Local", exact: true })).toBeVisible() + // The local checkout's branch is context, not a control: the app cannot switch it. await expect(screen.getByText("timeline-quotes", { exact: true })).toBeVisible() + await expect(screen.getByRole("button", { name: "timeline-quotes", exact: true })).toHaveCount(0) await expect(screen.getByRole("button", { name: /from / })).toHaveCount(0) await select(/^New worktree/) await expect(base).toBeVisible() @@ -191,7 +214,7 @@ test("the combined location picker shows checkout branches and chooses the base .toEqual([expect.objectContaining({ body: expect.objectContaining({ text: "Use the selected base" }) })]) }) -test("the checkout branch opens the current project's worktree step", async ({ page }) => { +test("the worktree trigger opens the current project's worktree step", async ({ page }) => { const existing = "C:/OpenCode/BranchWorktrees/.worktrees/quiet-river" const view = await openDraft(page, { @@ -201,13 +224,14 @@ test("the checkout branch opens the current project's worktree step", async ({ p }) const screen = page.locator('[data-component="new-session"]') - const branch = screen.getByRole("button", { name: "dev", exact: true }) + // The app cannot switch the checkout branch, so the local checkout names the mode instead of "dev". + const local = newSessionWorktree(page) const dialog = page.getByRole("dialog") const search = dialog.getByRole("combobox", { name: "Search worktrees", exact: true }) const options = dialog.getByRole("option") const back = dialog.getByRole("button", { name: "Back to projects", exact: true }) - await branch.click() + await local.click() await expect(search).toBeFocused() await expect(back).toHaveText("Run session in") await expect(options.locator(".command-palette-title")).toHaveText([ @@ -228,7 +252,7 @@ test("the checkout branch opens the current project's worktree step", async ({ p await expect(view.editor).toBeFocused() // Escape also steps back first, then closes. - await branch.focus() + await local.focus() await page.keyboard.press("Enter") await expect(search).toBeFocused() await search.press("Escape") @@ -236,11 +260,11 @@ test("the checkout branch opens the current project's worktree step", async ({ p await projects.press("Escape") await expect(dialog).toHaveCount(0) - await branch.click() + await local.click() await options.filter({ hasText: "quiet-river" }).click() await expect(dialog).toHaveCount(0) - await expect(newSessionLocation(page)).toContainText("quiet-river") - await expect(screen.getByRole("button", { name: "quiet-river-branch", exact: true })).toBeVisible() + await expect(newSessionWorktree(page)).toContainText("quiet-river") + await expect(screen.getByText("quiet-river-branch", { exact: true })).toBeVisible() await expect(view.editor).toBeFocused() }) @@ -499,9 +523,7 @@ test("a pending worktree session keeps Session as its mobile title until the gen const label = page.locator('[data-slot="mobile-tab-title"]') await expect(label).toHaveText("Session") const pending = await submitPending(page, mock) - await expect( - page.locator('[data-slot="mobile-tabs-trigger"] [data-component="session-progress-indicator-v2"]'), - ).toBeVisible() + await expect(page.locator('[data-slot="mobile-tabs-trigger"] [data-component="activity-ring"]')).toBeVisible() mock.worktree.resolve({ status: 200, json: { directory: workspace } }) await expect(pending.shimmer).toHaveCount(0) await expect(submit(page)).toBeEnabled() @@ -621,7 +643,7 @@ for (const row of [ if (row.followUp) return await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible() - await expect(newSessionLocation(page)).toContainText("New worktree") + await expect(newSessionWorktree(page)).toContainText("New worktree") await expect(pending.message).toHaveCount(0) await expect(tabLink(page, pending.sessionID)).toHaveCount(0) expect(mock.creates).toEqual([]) @@ -638,7 +660,7 @@ test("retains the draft and reuses the created workspace after session creation await expect(page.getByText("Failed to create session", { exact: true })).toBeVisible() await expect(editor(page)).toHaveText(text) await expect(submit(page)).toBeEnabled() - await expect(newSessionLocation(page)).toContainText("pending-workspace") + await expect(newSessionWorktree(page)).toContainText("pending-workspace") await expect(pending.shimmer).toHaveCount(0) await expect(pending.message).toHaveCount(0) expect(mock.creates).toEqual([expect.objectContaining({ id: pending.sessionID, location: { directory: workspace } })]) @@ -686,7 +708,7 @@ test("restores the draft after closing and revisiting a pending session that fai await expect(page.getByText("Failed to create worktree", { exact: true })).toBeVisible() await expect(editor(page)).toHaveText(`${text}\n\n${followUp}`) await expect(submit(page)).toBeEnabled() - await expect(newSessionLocation(page)).toContainText("New worktree") + await expect(newSessionWorktree(page)).toContainText("New worktree") await expect(page.locator(`[data-titlebar-tab-link][href="${draftHref(draftID)}"]`)).toHaveCount(1) await expect(tab).toHaveCount(0) await expect(pending.message).toHaveCount(0) diff --git a/packages/app/e2e/regression/review.spec.ts b/packages/app/e2e/regression/review.spec.ts index 00141a7a520f..94456f7393c1 100644 --- a/packages/app/e2e/regression/review.spec.ts +++ b/packages/app/e2e/regression/review.spec.ts @@ -151,6 +151,27 @@ test("a rejected Git init releases its session's button without showing an error await expect(init).toBeEnabled() }) +test("opens file picker launchers when randomUUID is unavailable on insecure HTTP origins", async ({ page }) => { + await page.addInitScript(() => { + Object.defineProperty(globalThis, "isSecureContext", { configurable: true, value: false }) + Object.defineProperty(globalThis.crypto, "randomUUID", { configurable: true, value: undefined }) + }) + + await openSession(page, { + name: "ReviewOpenFileInsecure", + seed: { panes: { ses_reviewopenfileinsecure: { review: true } } }, + }) + + const panel = page.locator("#review-panel") + const tab = panel.getByRole("tab", { name: "Open file", exact: true }) + await openFileLauncher(panel) + await expect(tab).toHaveAttribute("aria-selected", "true") + await expect(panel.getByRole("combobox", { name: "Filter files" })).toBeFocused() + + await openFileLauncher(panel) + await expect(tab).toHaveCount(2) +}) + test("open file tab browses, searches, and tracks missing files", async ({ page }) => { const searches: { query: string; dirs?: string; limit?: number; directory: string }[] = [] const directory = "C:/OpenCode/ReviewOpenFile" diff --git a/packages/app/e2e/regression/session-header.spec.ts b/packages/app/e2e/regression/session-header.spec.ts index 73d2adcc6a07..f79134d14316 100644 --- a/packages/app/e2e/regression/session-header.spec.ts +++ b/packages/app/e2e/regression/session-header.spec.ts @@ -214,7 +214,9 @@ test.describe("location", () => { sessions: [{ id: "ses_location", title: "Location session", directory: worktree }], } - test("collapses the worktree name before the project and only then truncates the title", async ({ page }) => { + test("collapses the worktree name, then the project, then the usage details, and only then truncates the title", async ({ + page, + }) => { await page.setViewportSize({ width: 1440, height: 900 }) await page.clock.install() await openSession(page, { @@ -228,22 +230,27 @@ test.describe("location", () => { const row = header.locator(".session-header-layout") const review = page.getByRole("button", { name: "Toggle review", exact: true }) const tooltip = page.getByRole("tooltip") + const usage = header.getByRole("button", { name: "Toggle session context", exact: true }) + const usageMenu = header.getByRole("button", { name: "View context usage", exact: true }) await expect(header.getByRole("button", { name: "More options", exact: true })).toBeVisible() await expect(project).toHaveText("Location") await expect(worktreeName).toHaveText("quiet-falcon") // Keep the viewport fixed: a pane can narrow a session independently of the window. for (const state of [ - { width: 1000, project: true, worktree: true, truncated: false }, - { width: 680, project: true, worktree: false, truncated: false }, - { width: 600, project: false, worktree: false, truncated: false }, - { width: 490, project: false, worktree: false, truncated: true }, - { width: 680, project: true, worktree: false, truncated: false }, - { width: 1000, project: true, worktree: true, truncated: false }, + { width: 1000, project: true, worktree: true, usage: true, truncated: false }, + { width: 680, project: true, worktree: false, usage: true, truncated: false }, + { width: 600, project: false, worktree: false, usage: true, truncated: false }, + { width: 550, project: false, worktree: false, usage: false, truncated: false }, + { width: 490, project: false, worktree: false, usage: false, truncated: true }, + { width: 680, project: true, worktree: false, usage: true, truncated: false }, + { width: 1000, project: true, worktree: true, usage: true, truncated: false }, ]) { await row.evaluate((element, width) => (element.style.inlineSize = `${width}px`), state.width) await expect(project).toBeVisible({ visible: state.project }) await expect(worktreeName).toBeVisible({ visible: state.worktree }) + await expect(usage).toBeVisible({ visible: state.usage }) + await expect(usageMenu).toBeVisible({ visible: !state.usage }) await expect(header.locator(".session-location-worktree-icon")).toBeVisible() await expect .poll(() => header.getByRole("heading").evaluate((element) => element.scrollWidth > element.clientWidth)) @@ -307,6 +314,20 @@ test.describe("location", () => { await location.click() await expect(page.locator('[data-slot="session-location-card"]')).toBeVisible() await expect(tooltip).toBeHidden() + await page.keyboard.press("Escape") + await expect(page.locator('[data-slot="session-location-card"]')).toBeHidden() + + // The compact usage opens its details in a menu, which also opens the context panel. + await row.evaluate((element) => (element.style.inlineSize = "490px")) + await usageMenu.click() + const details = page.getByRole("menu", { name: "View context usage", exact: true }) + await expect(details).toContainText("Tokens0") + await expect(details).toContainText("Cost$0.00") + await expect(details).toContainText("Context0%") + await page.screenshot({ path: test.info().outputPath("usage-menu.png") }) + await details.getByRole("menuitem", { name: "View context usage", exact: true }).click() + await expect(details).toBeHidden() + await expect(page.getByRole("tab", { name: "Context", exact: true })).toHaveAttribute("aria-selected", "true") }) test("collapses to the project avatar when there is no worktree", async ({ page }) => { diff --git a/packages/app/e2e/regression/session-summary.spec.ts b/packages/app/e2e/regression/session-summary.spec.ts index f9cce652afad..46db7a42b3ee 100644 --- a/packages/app/e2e/regression/session-summary.spec.ts +++ b/packages/app/e2e/regression/session-summary.spec.ts @@ -557,6 +557,8 @@ test("MCP rows toggle once per action and keep sign-in, errors, and management a } }) .toEqual({ width: 6, height: 6, alignment: 0, gap: 8 }) + // Like every other control in the menu, a row that toggles its server keeps the default cursor. + await expect(row("figma")).not.toHaveCSS("cursor", "pointer") await page.screenshot({ path: test.info().outputPath("mcp-toggles.png"), animations: "disabled" }) for (const [index, target] of ["label", "dot", "padding", "control", "keyboard"].entries()) { @@ -567,7 +569,11 @@ test("MCP rows toggle once per action and keep sign-in, errors, and management a ? await holdRoute(page, /\/api\/experimental\/mcp\/figma\/disconnect(?:\?|$)/, { method: "POST" }) : undefined - if (target === "label") await row("figma").locator('[data-slot="truncated-text-label"]').click() + if (target === "label") { + await row("figma").locator('[data-slot="truncated-text-label"]').click() + // A name that fits has nothing to reveal, so a click on it leaves no focus ring of its own. + await expect(row("figma").locator('[data-component="tooltip-v2-trigger"]')).not.toBeFocused() + } if (target === "dot") await row("figma").locator(".session-service-dot").click() @@ -673,11 +679,15 @@ test("Extensions lists open on hover, hold course into the open list, and follow test("Extensions lists open config files and skills in a side tab and start setup sessions", async ({ page }) => { const global = "C:/Users/kit/.config/opencode/opencode.jsonc" const skill = `${fixture.directory}/.opencode/skills/release-notes/SKILL.md` + let builtinReads = 0 await mockStressTimeline(page, { mcp: [{ name: "atlas-search", status: { status: "connected" } }], plugins: [], - skills: [{ id: "release-notes", name: "release-notes", path: skill, content: "Release notes" }], + skills: [ + { id: "opencode", name: "OpenCode", path: "/builtin/opencode.md", content: "# Built-in OpenCode guide" }, + { id: "release-notes", name: "release-notes", path: skill, content: "Release notes" }, + ], configEntries: [ { type: "document", @@ -689,6 +699,16 @@ test("Extensions lists open config files and skills in a side tab and start setu ], fileContent: (path) => ({ type: "text", content: `contents:${path}` }), }) + + await page.route(/\/api\/fs\/read\/opencode\.md(\?|$)/, (route) => { + builtinReads += 1 + + return route.fulfill({ + status: 404, + json: { message: "Location not found: /builtin" }, + headers: cors, + }) + }) await page.goto(sessionHref(fixture.targetID)) const trigger = page.getByRole("button", { name: "Session details", exact: true }) const summary = page.getByRole("dialog", { name: "Session details", exact: true }) @@ -705,6 +725,15 @@ test("Extensions lists open config files and skills in a side tab and start setu await expect(page.getByRole("tab", { name: "opencode.jsonc", exact: true })).toHaveAttribute("aria-selected", "true") await expect(page.getByText("contents:opencode.jsonc", { exact: true })).toBeVisible() + await trigger.click() + await row("Skills").hover() + await list("Skills").getByRole("button", { name: "OpenCode", exact: true }).click() + await expect(summary).toBeHidden() + await expect(page.getByRole("tab", { name: "opencode.md", exact: true })).toHaveAttribute("aria-selected", "true") + await expect(page.getByRole("heading", { name: "Built-in OpenCode guide", exact: true })).toBeVisible() + await expect(page.getByText("Failed to load file", { exact: true })).toHaveCount(0) + expect(builtinReads).toBe(0) + await trigger.click() await row("Skills").hover() await list("Skills").getByRole("button", { name: "release-notes", exact: true }).click() @@ -841,7 +870,14 @@ test("long MCP lists stay in the viewport in a real RTL locale", async ({ page } await summary.getByRole("button", { name: "MCP", exact: true }).click() const menu = page.getByRole("group", { name: "MCP", exact: true }) await expect(menu.locator(".session-mcp-row")).toHaveCount(30) - await expect.poll(() => menu.evaluate((element) => element.scrollHeight > element.clientHeight)).toBe(true) + const list = menu.locator("[data-scrollable]") + await expect.poll(() => list.evaluate((element) => element.scrollHeight > element.clientHeight)).toBe(true) + // Long names truncate; the list only scrolls vertically. + expect(await list.evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0) + // The submenu shows and moves without motion unless its Knobs toggle is on. + expect( + await page.locator(".session-service-flyout").evaluate((element) => getComputedStyle(element).transitionDuration), + ).toBe("0s") await expect .poll(async () => { const bounds = (await menu.boundingBox())! diff --git a/packages/app/e2e/regression/settings-search.spec.ts b/packages/app/e2e/regression/settings-search.spec.ts index 9706862f8b75..0f882095ef45 100644 --- a/packages/app/e2e/regression/settings-search.spec.ts +++ b/packages/app/e2e/regression/settings-search.spec.ts @@ -311,8 +311,12 @@ test("section search takes typed input, clears in place, and escapes in steps", }) for (const count of [0, 7, 8]) { - test(`Projects search appears from 8 projects (${count} projects)`, async ({ page }) => { - const view = await open(page, { count }) + test(`Projects search appears from 8 added projects (${count} projects)`, async ({ page }) => { + const view = await open(page, { + count, + seed: { usedProjects: { local: Array.from({ length: count }, (_, index) => `proj_search_${index}`) } }, + }) + await view.settings.getByRole("tab", { name: "Projects", exact: true }).click() const search = view.settings.getByRole("searchbox", { name: "Search projects", exact: true }) const projects = view.settings.getByRole("button", { name: /^OpenCode / }) diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 133c22f45b9b..de157215d686 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -3,6 +3,8 @@ import type { ConfigEntry, OpenCodeEvent, SessionMessageInfo, WorktreeDirectory import { NO_PROVIDER, REMOTE_SERVER, SERVER, holdRoute, project, seed, session } from "../utils/app" import { mockMissingLocation, mockOpenCodeServer } from "../utils/mock-server" import { mockRemoteServer, mockWorkspace, openSession, openSettings, type WorkspaceInput } from "../utils/workspace" +import { recordNotifications } from "../utils/notifications" +import { installSseTransport } from "../utils/sse-transport" const directory = "C:/Projects/settings-demo" @@ -94,6 +96,146 @@ test("a settings page survives refresh", async ({ page }) => { await expect(page).toHaveURL("/settings?tab=appearance") }) +test("Questions settings default independently of old Permissions settings and survive reload", async ({ page }) => { + const { settings } = await open(page, { + seed: { + settings: { + notifications: { agent: false, permissions: false, errors: true }, + sounds: { permissionsEnabled: false, permissions: "alert-05" }, + }, + }, + }) + + await settings.getByRole("tab", { name: "Notifications", exact: true }).click() + await expect(settings.locator('[data-slot="settings-row-title"]')).toHaveText([ + "Agent", + "Permissions", + "Questions", + "Errors", + "Agent", + "Permissions", + "Questions", + "Errors", + "Interface", + ]) + const questions = settings.getByRole("switch", { name: "Questions", exact: true }) + + const permissions = settings.locator('[data-action="settings-notifications-permissions"]').getByRole("switch") + + const questionSound = settings.locator('[data-action="settings-sounds-questions"]') + + const permissionSound = settings.locator('[data-action="settings-sounds-permissions"]') + + await expect(questions).toBeChecked() + await expect(permissions).not.toBeChecked() + await expect(questionSound).toHaveText("Staplebops 05") + await expect(permissionSound).toHaveText("None") + await questions.locator("..").locator('[data-slot="switch-control"]').click() + await expect(questions).not.toBeChecked() + await questionSound.click() + await page.getByRole("option", { name: "Alert 02", exact: true }).click() + await expect(questionSound).toHaveText("Alert 02") + + await page.reload() + await expect(questions).not.toBeChecked() + await expect(questionSound).toHaveText("Alert 02") + await expect(permissions).not.toBeChecked() + await expect(permissionSound).toHaveText("None") + await questions.locator("..").locator('[data-slot="switch-control"]').click() + await questionSound.click() + await page.getByRole("option", { name: "None", exact: true }).click() + await expect(questions).toBeChecked() + await expect(questionSound).toHaveText("None") + await settings.getByRole("combobox", { name: "Search", exact: true }).fill("Questions") + await expect(settings.locator('[data-setting-target="settings-notifications-questions"]')).toBeVisible() + await expect(settings.locator('[data-setting-target="settings-sounds-questions"]')).toBeVisible() +}) + +test("request events use real Questions settings without disabling Permissions alerts", async ({ page }) => { + const recorded = await recordNotifications(page) + + const transport = await installSseTransport(page, { server: SERVER }) + + const workspace = await openSession(page, { + name: "Request notifications", + seed: { settings: { sounds: { agentEnabled: false, permissions: "alert-01", questions: "alert-02" } } }, + }) + + await transport.waitForConnection() + await page.getByRole("button", { name: "Home", exact: true }).click() + await page.getByRole("button", { name: "Settings", exact: true }).click() + const settings = page.getByTestId("settings-screen") + + await settings.getByRole("tab", { name: "Notifications", exact: true }).click() + const questions = settings.getByRole("switch", { name: "Questions", exact: true }) + + await expect(questions).toBeChecked() + + const event = ( + kind: "question" | "mcp-elicitation" | "websearch.provider" | "permission", + index: number, + ): OpenCodeEvent => { + const base = { + id: `evt_request_${index}`, + created: 1700000001000 + index, + location: { directory: workspace.directory }, + } + + if (kind === "permission") + return { + ...base, + type: "permission.asked", + data: { + id: `per_request_${index}`, + sessionID: workspace.session.id, + action: "shell", + resources: ["echo hello"], + metadata: {}, + }, + } + + return { + ...base, + type: "form.created", + data: { + form: { + id: `frm_request_${index}`, + sessionID: workspace.session.id, + title: "Input", + metadata: { kind }, + fields: [{ key: "answer", type: "string", title: "Continue?" }], + }, + }, + } + } + + await transport.send(event("question", 1)) + await expect + .poll(() => recorded.notifications) + .toEqual([{ title: "Question requires an answer", body: "Request notifications" }]) + await expect.poll(() => recorded.sounds).toEqual([expect.stringContaining("alert-02")]) + + await settings.locator('[data-action="settings-sounds-questions"]').click() + await page.getByRole("option", { name: "None", exact: true }).click() + await expect(settings.locator('[data-action="settings-sounds-questions"]')).toHaveText("None") + const previews = recorded.sounds.slice() + + await transport.send(event("mcp-elicitation", 2)) + await expect + .poll(() => recorded.notifications.map((item) => item.title)) + .toEqual(["Question requires an answer", "Input requested"]) + + await questions.locator("..").locator('[data-slot="switch-control"]').click() + await expect(questions).not.toBeChecked() + await transport.burst([event("question", 3), event("permission", 4), event("websearch.provider", 5)]) + await expect + .poll(() => recorded.notifications.map((item) => item.title)) + .toEqual(["Question requires an answer", "Input requested", "Permission required", "Permission required"]) + await expect + .poll(() => recorded.sounds) + .toEqual([...previews, expect.stringContaining("alert-01"), expect.stringContaining("alert-01")]) +}) + for (const locale of ["en", "ar"]) { test(`background activity alignment stays physical and persists (${locale})`, async ({ page }) => { const id = "ses_activity_settings" @@ -349,11 +491,45 @@ test("project list menus rename, edit, add, and stay inside the scrollport", asy await settings.getByRole("tab", { name: "Projects", exact: true }).click() const panel = settings.getByRole("tabpanel") const list = panel.getByRole("list") - await expect(list.getByRole("listitem")).toHaveCount(4) - const card = list.getByRole("listitem").filter({ hasText: "rebase" }) + await expect(list.getByRole("listitem")).toHaveCount(1) + await expect(list.getByRole("button", { name: "rebase", exact: true })).toBeVisible() + const others = panel.getByRole("button", { name: "Other projects", exact: true }) + await expect(others).toContainText("3") + await expect(others).toHaveAttribute("aria-expanded", "false") + await others.click() + await expect(others).toHaveAttribute("aria-expanded", "true") + await expect(panel.getByRole("listitem")).toHaveCount(4) + await others.click() + const search = panel.getByRole("searchbox", { name: "Search projects" }) + await search.fill("/projects/dinocms") + await expect(panel.getByRole("listitem")).toHaveCount(1) + await expect(panel.getByRole("button", { name: "dinocms", exact: true })).toBeVisible() + await expect(panel.getByRole("heading", { name: "Other projects", exact: true })).toBeVisible() + await search.fill("") + await expect(panel.getByRole("listitem")).toHaveCount(1) + await others.click() + await expect(panel.getByRole("listitem")).toHaveCount(4) + + const addTrigger = panel + .getByRole("listitem") + .filter({ hasText: "dinocms" }) + .getByRole("button", { name: "More options", exact: true }) + + await addTrigger.focus() + await addTrigger.press("Enter") + const menu = page.getByRole("menu") + await expect(menu.getByRole("menuitem")).toHaveText(["Add project", "Edit", "Rename"]) + const addProject = menu.getByRole("menuitem", { name: "Add project", exact: true }) + await expect(addProject).toBeFocused() + await addProject.press("Enter") + await expect(menu).toBeHidden() + await expect(others).toContainText("2") + const addedProjects = panel.getByRole("list").filter({ hasText: "rebase" }) + await expect(addedProjects.getByRole("listitem")).toHaveCount(2) + await expect(addedProjects.getByRole("button", { name: "dinocms", exact: true })).toBeFocused() + const card = panel.getByRole("listitem").filter({ hasText: "rebase" }) const more = card.getByRole("button", { name: "More options", exact: true }) await more.click() - const menu = page.getByRole("menu") await expect(menu.getByRole("menuitem")).toHaveText(["Edit", "Rename", "Clear notifications"]) await menu.getByRole("menuitem", { name: "Edit", exact: true }).click() await expect(panel.getByRole("heading", { name: "rebase", exact: true })).toBeVisible() @@ -403,6 +579,8 @@ test("project list menus rename, edit, add, and stay inside the scrollport", asy await select.click() await expect(picker).toBeHidden() await expect(panel.getByRole("heading", { name: "added", exact: true })).toBeVisible() + await page.getByRole("button", { name: "Home", exact: true }).click() + await expect(page.locator('[data-component="home-project-row"]').filter({ hasText: "dinocms" })).toBeVisible() }) test("project settings open as a nested view that keeps its route", async ({ page }) => { diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts index cddaca53d54e..fcd31ce8af3c 100644 --- a/packages/app/e2e/regression/tabs.spec.ts +++ b/packages/app/e2e/regression/tabs.spec.ts @@ -4,6 +4,7 @@ import { NO_PROVIDER, REMOTE_SERVER, SERVER, + T0, draftHref, expectPath, holdRoute, @@ -578,8 +579,19 @@ test("vertical tabs resize, scroll, show shortcut hints, and navigate", async ({ await resize(-380, "260px") const scroll = sidebar.locator('[data-slot="vertical-tabs-scroll"]') + + // The list feathers only the edges with more rows past them. + const feather = () => + scroll.evaluate((element) => { + const style = getComputedStyle(element) + + return [style.getPropertyValue("--vertical-tabs-fade-top"), style.getPropertyValue("--vertical-tabs-fade-bottom")] + }) + + await expect.poll(feather).toEqual(["0px", "16px"]) await scroll.evaluate((element) => element.scrollTo(0, element.scrollHeight)) await expect(tabB).toBeInViewport({ ratio: 1 }) + await expect.poll(feather).toEqual(["16px", "0px"]) await page.locator("html").evaluate((element) => element.setAttribute("dir", "rtl")) const home = sidebar.locator('[data-action="vertical-tabs-home"]') @@ -1234,6 +1246,43 @@ test("⌘W closes the session tab again once the window loses focus after the si await expect(sessions.alphaTab).toHaveCount(0) }) +test("⌘W in the side panel closes its last New tab with the panel, and only then the session tab", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }) + const alpha = { id: "ses_side_new_alpha", title: "Side new alpha" } + const beta = { id: "ses_side_new_beta", title: "Side new beta" } + await openSession(page, { name: "SideCloseNewTab", sessions: [alpha, beta] }) + + const panel = page.locator("#review-panel") + const toggle = page.getByRole("button", { name: "Toggle review", exact: true }) + const newTab = panel.getByRole("tab", { name: "New tab", exact: true }) + const composer = page.getByRole("textbox", { name: "Prompt", exact: true }) + const alphaTab = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(alpha.id)}"])`) + + await composer.click() + await page.keyboard.press("ControlOrMeta+Shift+R") + await expect(newTab).toHaveAttribute("aria-selected", "true") + await expect.poll(() => panel.evaluate((element) => element.contains(document.activeElement))).toBe(true) + // A launcher row in the New tab view holds focus as ⌘W removes it. + await panel.getByRole("button", { name: /^Open file/ }).focus() + + // The New tab was the panel's last tab, so closing it closes the panel too, and focus goes back. + await page.keyboard.press("ControlOrMeta+w") + await expect(newTab).toHaveCount(0) + await expect(toggle).toHaveAttribute("aria-expanded", "false") + await expect(composer).toBeFocused() + + // One press too many closes nothing rather than the session. + await page.keyboard.press("ControlOrMeta+w") + await expect(alphaTab).toHaveCount(1) + await expectPath(page, sessionHref(alpha.id)) + + // With no panel open, ⌘W from the composer closes the session tab. + await composer.click() + await page.keyboard.press("ControlOrMeta+w") + await expectPath(page, sessionHref(beta.id)) + await expect(alphaTab).toHaveCount(0) +}) + // Windows has no native menu bar: the titlebar menu owns Paste, which only the desktop edit action can perform. test("the Windows titlebar menu pastes through the desktop edit action", async ({ page }) => { await mockWorkspace(page, { name: "WindowsMenu", sessions: [] }) @@ -1323,6 +1372,27 @@ test("loads a tab's transcript while the pointer rests on it, and not when it pa expect(requested.filter((id) => id === b.id)).toHaveLength(1) }) +test("⌘W in a focused Context tab closes it, then the panel, and keeps the session tab", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }) + const alpha = { id: "ses_side_context_alpha", title: "Side context alpha" } + const beta = { id: "ses_side_context_beta", title: "Side context beta" } + await openSession(page, { name: "SideCloseContext", sessions: [alpha, beta] }) + + const panel = page.locator("#review-panel") + const toggle = page.getByRole("button", { name: "Toggle review", exact: true }) + const context = panel.getByRole("tab", { name: "Context", exact: true }) + const alphaTab = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(alpha.id)}"])`) + + await page.getByRole("button", { name: "Toggle session context" }).click() + await expect(context).toHaveAttribute("aria-selected", "true") + await panel.click({ position: { x: 100, y: 300 } }) + await page.keyboard.press("ControlOrMeta+w") + await expect(context).toHaveCount(0) + await expect(toggle).toHaveAttribute("aria-expanded", "false") + await expect(alphaTab).toHaveCount(1) + await expectPath(page, sessionHref(alpha.id)) +}) + // Closes Alpha's side tabs with ⌘W until the side panel empties and collapses, as an overshooting hand would. async function emptySidePanel(page: Page) { await page.setViewportSize({ width: 1440, height: 900 }) @@ -1356,3 +1426,43 @@ async function emptySidePanel(page: Page) { return { beta, alphaTab: page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(alpha.id)}"])`) } } + +test("opening a session from the inbox keeps the list's scroll position and rows", async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 480 }) + + const sessions = Array.from({ length: 24 }, (_, index) => ({ + id: `ses_inbox_${String(index).padStart(2, "0")}`, + title: `Inbox session ${index}`, + time: { created: T0, updated: T0 + index, idle: T0 + index }, + })) + + await mockWorkspace(page, { + name: "Inbox", + sessions, + seed: { + settings: { appearance: { tabLayout: "inbox" } }, + tabs: [], + // Every seeded session finished a run after the inbox was first used, so Recent lists them all. + storage: { "opencode.global.dat:sidebar.inbox": { workingExpanded: true, since: 0 } }, + }, + }) + await page.goto("/") + + const list = page.locator('[data-slot="sidebar-inbox-scroll"]') + const items = list.locator('[data-slot="sidebar-inbox-item"]') + const target = items.filter({ hasText: "Inbox session 0" }) + await expect(items).toHaveCount(sessions.length) + await list.evaluate((element) => element.scrollTo(0, element.scrollHeight)) + await expect(target).toBeInViewport({ ratio: 1 }) + const offset = await list.evaluate((element) => element.scrollTop) + expect(offset).toBeGreaterThan(0) + const row = await target.elementHandle() + + await target.click() + await expectPath(page, sessionHref("ses_inbox_00")) + await expect(target).toHaveAttribute("data-state", "active") + // Opening a session loads it into the client, which updates every section. + await expect(page.locator('[data-component="composer-editor"]')).toBeEditable() + expect(await target.evaluate((element, before) => element === before, row)).toBe(true) + expect(await list.evaluate((element) => element.scrollTop)).toBe(offset) +}) diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts index 4e8fb868bde7..472d84c78339 100644 --- a/packages/app/e2e/regression/timeline-history.spec.ts +++ b/packages/app/e2e/regression/timeline-history.spec.ts @@ -5,12 +5,15 @@ import { trackPageErrors } from "../utils/errors" import { fixture, installTimelineSettings, mockStressTimeline } from "../utils/session-fixture" import { assistantMessage, + historyMessages, messageUpdated, + partUpdated, sessionID, setupTimeline, status, textPart, userMessage, + validateTimelineMessages, } from "../utils/timeline" import { expectSessionTitle } from "../utils/waits" import { openSession } from "../utils/workspace" @@ -413,6 +416,92 @@ test.describe("timeline history", () => { } }) } + + test("pages the timeline from the composer, resuming follow at the end and loading history at the top", async ({ + page, + }) => { + const messages = validateTimelineMessages([ + ...historyMessages(30), + userMessage(), + assistantMessage([textPart("prt_page_keys_text", "Paging from the composer")], { completed: false }), + ]) + + const older: string[] = [] + + const timeline = await setupTimeline(page, { + reducedMotion: true, + message: (_, id) => messages.find((message) => message.id === id), + pageMessages: (_, limit, before) => { + const end = before ? messages.findIndex((message) => message.id === before) : messages.length + const start = Math.max(0, end - limit) + + return { items: messages.slice(start, end), cursor: start > 0 ? messages[start]!.id : undefined } + }, + onMessages: (request) => { + if (request.before && request.phase === "start") older.push(request.before) + }, + }) + + const scroller = timelineScroller(page) + const editor = page.locator('[data-component="composer-editor"]') + const suggestions = page.locator('[data-component="composer-suggestions"]') + const top = () => scroller.evaluate((element) => element.scrollTop) + + const fromEnd = () => + scroller.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop) + + const caret = () => + editor.evaluate((element) => { + const selection = window.getSelection()! + const range = document.createRange() + range.setStart(element, 0) + range.setEnd(selection.anchorNode!, selection.anchorOffset) + + return range.toString().length + }) + + await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + await expect.poll(fromEnd).toBeLessThanOrEqual(1) + await editor.click() + + // An open popup keeps the page keys: the timeline stays put and the query stays open. + await page.keyboard.type("/") + await expect(suggestions).toBeVisible() + const resting = await top() + await editor.press("PageUp") + expect(await top()).toBe(resting) + await expect(suggestions).toBeVisible() + await expect(editor).toHaveText("/") + await editor.press("Escape") + await expect(suggestions).toBeHidden() + await editor.press("Backspace") + + await page.keyboard.type("keep this draft") + + const pageHeight = await page + .locator('[data-slot="session-timeline-visible"]') + .evaluate((element) => element.clientHeight) + + await editor.press("PageUp") + await expect.poll(top).toBeLessThan(resting - pageHeight * 0.6) + expect(resting - (await top())).toBeLessThan(pageHeight) + await expect(editor).toBeFocused() + await expect(editor).toHaveText("keep this draft") + expect(await caret()).toBe("keep this draft".length) + + // Paging back to the end follows new content again, as a wheel scroll there does. + for (let index = 0; index < 10 && (await fromEnd()) > 1; index++) await editor.press("PageDown") + await expect.poll(fromEnd).toBeLessThanOrEqual(1) + await timeline.send(partUpdated(textPart("prt_page_keys_tail", "Arrived after paging down.\n\n".repeat(20)))) + await timeline.waitForPart("prt_page_keys_tail") + await expect.poll(fromEnd).toBeLessThanOrEqual(1) + + // Paging to the top loads the older page, as scrolling there does. + for (let index = 0; index < 30 && (await top()) > 1; index++) await editor.press("PageUp") + await expect.poll(() => older[0]).toBe(messages[messages.length - 40]!.id) + await expect(editor).toBeFocused() + await expect(editor).toHaveText("keep this draft") + }) }) declare global { diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 707e47552e0c..ef0608d0c8a4 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -15,6 +15,7 @@ import { inboxDelivered, inboxEnqueued, messageUpdated, + partDelta, partUpdated, reasoningPart, renderedPartID, @@ -1010,6 +1011,33 @@ test.describe("Working", () => { }) }) +test("grows a streaming row without a ResizeObserver loop error", async ({ page }) => { + // Each streamed paragraph grows its row. An observer on the content that holds every row saw that height inside the + // row observer's own delivery, and Chrome reported every such frame as an uncaught error. + await page.addInitScript(() => { + window.addEventListener("error", (event) => { + if (!event.message.startsWith("ResizeObserver loop")) return + document.documentElement.dataset.resizeObserverLoops = String( + Number(document.documentElement.dataset.resizeObserverLoops ?? 0) + 1, + ) + }) + }) + + const timeline = await setupTimeline(page, { + messages: [userMessage(), assistantMessage([textPart("prt_growth", "Streaming.")], { completed: false })], + }) + + const text = page.locator(`[data-timeline-part-id="${renderedPartID("prt_growth")}"]`) + + for (const line of [1, 2, 3, 4, 5, 6]) { + await timeline.send(partDelta("prt_growth", `\n\nParagraph ${line}.`)) + await expect(text).toContainText(`Paragraph ${line}.`) + } + + await expect(text.locator("p")).toHaveCount(7) + expect(await page.evaluate(() => document.documentElement.dataset.resizeObserverLoops)).toBeUndefined() +}) + test.describe("background shortcut", () => { test("offers a standalone running subagent to the background with Ctrl+B", async ({ page }) => { await setupTimeline(page, { diff --git a/packages/app/e2e/utils/mock-api.ts b/packages/app/e2e/utils/mock-api.ts index 1f236218f81b..bdac71face9a 100644 --- a/packages/app/e2e/utils/mock-api.ts +++ b/packages/app/e2e/utils/mock-api.ts @@ -1,5 +1,6 @@ import { Predicate, Schema, SchemaGetter } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api" +import { PersistentPty } from "@opencode/schema/persistent-pty" import { Pty } from "@opencode/schema/pty" import { Worktree } from "@opencode/schema/worktree" @@ -69,6 +70,18 @@ export class MockPtyNotFound extends Schema.TaggedError()("PtyN message: Schema.String, }) {} +// The server's error when a service it needs, such as the opencode-pty daemon, cannot run. +export class MockServiceUnavailable extends Schema.TaggedError()("ServiceUnavailableError", { + message: Schema.String, + service: Schema.optional(Schema.String), +}) {} + +// The server's error for a feature the connected opencode-pty daemon lacks, such as `rename`. +export class MockPtyFeatureUnsupported extends Schema.TaggedError()( + "PtyFeatureUnsupportedError", + { feature: Schema.String, message: Schema.String }, +) {} + // The server's error for a request without its password. export class MockUnauthorized extends Schema.TaggedError()("UnauthorizedError", { message: Schema.String, @@ -83,6 +96,17 @@ const Unsupported = MockUnsupported.pipe(HttpApiSchema.status(501)) const PtyMissing = [MockNotFound.pipe(HttpApiSchema.status(404)), MockPtyNotFound.pipe(HttpApiSchema.status(404))] +const PersistentPtyUnavailable = MockServiceUnavailable.pipe(HttpApiSchema.status(503)) + +const PersistentPtyMissing = [MockPtyNotFound.pipe(HttpApiSchema.status(404)), PersistentPtyUnavailable] + +// `PersistentPty.UpdateInput` once terminal renaming lands; the schema still requires `size`. +const PersistentPtyUpdate = Schema.Struct({ + attachmentID: Schema.optional(Schema.String), + size: Schema.optional(Schema.Struct({ cols: Schema.Number, rows: Schema.Number })), + title: Schema.optional(Schema.NullOr(Schema.String)), +}) + const Group = HttpApiGroup.make("mock") .add(HttpApiEndpoint.get("info", "/api/info", { success: Json })) .add( @@ -291,6 +315,57 @@ const Group = HttpApiGroup.make("mock") error: PtyMissing, }), ) + .add( + HttpApiEndpoint.get("persistentPtyList", "/api/experimental/session/:sessionID/terminal", { + params: SessionParams, + success: Json, + error: PersistentPtyUnavailable, + }), + ) + .add( + HttpApiEndpoint.post("persistentPtyCreate", "/api/experimental/session/:sessionID/terminal", { + params: SessionParams, + payload: PersistentPty.CreateInput, + success: Json, + error: PersistentPtyUnavailable, + }), + ) + .add( + HttpApiEndpoint.get("persistentPtyGet", "/api/experimental/persistent-pty/:ptyID", { + params: PtyParams, + success: Json, + error: PersistentPtyMissing, + }), + ) + .add( + HttpApiEndpoint.put("persistentPtyUpdate", "/api/experimental/persistent-pty/:ptyID", { + params: PtyParams, + payload: PersistentPtyUpdate, + success: Json, + error: [...PersistentPtyMissing, MockPtyFeatureUnsupported.pipe(HttpApiSchema.status(501))], + }), + ) + .add( + HttpApiEndpoint.delete("persistentPtyRemove", "/api/experimental/persistent-pty/:ptyID", { + params: PtyParams, + success: NoContent, + error: PersistentPtyMissing, + }), + ) + .add( + HttpApiEndpoint.get("persistentPtySnapshot", "/api/experimental/persistent-pty/:ptyID/snapshot", { + params: PtyParams, + success: Json, + error: PersistentPtyMissing, + }), + ) + .add( + HttpApiEndpoint.post("persistentPtyConnectToken", "/api/experimental/persistent-pty/:ptyID/connect-token", { + params: PtyParams, + success: Json, + error: PersistentPtyMissing, + }), + ) .add( HttpApiEndpoint.get("sessionList", "/api/session", { query: Query, @@ -321,6 +396,12 @@ const Group = HttpApiGroup.make("mock") success: NoContent, }), ) + .add( + HttpApiEndpoint.post("sessionView", "/api/session/:sessionID/view", { + params: SessionParams, + success: NoContent, + }), + ) .add( HttpApiEndpoint.post("sessionShell", "/api/session/:sessionID/shell", { params: SessionParams, diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index 0ccbbcdf5c00..900708d5f3ad 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -12,11 +12,14 @@ import { MockBadRequest, MockInternal, MockNotFound, + MockPtyFeatureUnsupported, MockPtyNotFound, + MockServiceUnavailable, MockShellNotFound, MockUnauthorized, MockUnsupported, } from "./mock-api" +import { createPersistentPty, type MockPersistentPtyConfig, type MockServerEvent } from "./persistent-pty" import { installSseTransport } from "./sse-transport" type Resolvable = T | (() => T) @@ -147,6 +150,9 @@ export interface MockServerConfig { // Serves `/api/pty*` and mock PTY WebSockets. Created IDs are the first unused `${prefix}` (prefix must start with "pty"). // `directory` is the owning workspace (Location); `cwd` is the reported working directory (default: `directory`). pty?: { prefix?: string; initial?: { id: string; title: string; directory?: string; cwd?: string }[] } + // Serves the session-scoped persistent PTY routes and their connect WebSockets (`e2e/utils/persistent-pty.ts`). + // Without it, those routes answer 503 like a server whose opencode-pty daemon cannot run. + persistentPty?: MockPersistentPtyConfig // Answers 500 InvalidDirectory when a request names a directory this server does not own. strictDirectory?: boolean // Answers 401 UnauthorizedError unless a request carries this password; a function may change it mid-test. @@ -305,7 +311,7 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) { // Delivers events on this server's mock stream; buffered until the app connects. // An origin served by an SSE transport receives the events as one burst on its active connection. - const push = (payloads: readonly OpenCodeEvent[]) => + const push = (payloads: readonly MockServerEvent[]) => page.evaluate( ({ server, payloads }) => { // SAFETY: only the init script, `installSseTransport`, and benchmarks write these globals, in the declared shapes. @@ -322,7 +328,7 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) { ) // Server-side events the mock publishes itself; delivery failures other than a missing document fail the test. - const emit = (events: OpenCodeEvent[]) => + const emit = (events: MockServerEvent[]) => void push(events).catch((cause: unknown) => { if (page.isClosed() || retryableDelivery(cause)) return throw cause @@ -482,7 +488,15 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) { ) } - return { server, pty: transport.pty, push } + if (config.persistentPty) { + const host = new URL(server).host + await page.routeWebSocket( + (url) => url.host === host && /^\/api\/experimental\/persistent-pty\/[^/]+\/connect$/.test(url.pathname), + (ws) => transport.persistentPty.connect(ws), + ) + } + + return { server, pty: transport.pty, persistentPty: transport.persistentPty, push } } // Answers every Location-scoped request for `directory` as the server does once that folder is deleted. @@ -535,15 +549,19 @@ export async function mockServers(page: Page, servers: Record void = () => {}) { +export function createMockServerHandler( + config: MockServerConfig, + emit: (events: MockServerEvent[]) => void = () => {}, +) { const pty = createPty(config) + const persistentPty = createPersistentPty({ config: config.persistentPty, directory: config.directory }, emit) const web = HttpRouter.toWebHandler( HttpApiBuilder.layer(MockApi).pipe( @@ -553,6 +571,7 @@ export function createMockServerHandler(config: MockServerConfig, emit: (events: nextCursor: 0, sessionCreates: 0, pty, + persistentPty, emit, mcp: new Map(), attempts: new Map(), @@ -563,7 +582,7 @@ export function createMockServerHandler(config: MockServerConfig, emit: (events: { disableLogger: true }, ) - return { ...web, pty } + return { ...web, pty, persistentPty } } const corsHeaders = { @@ -736,7 +755,8 @@ function mockHandlers( nextCursor: number sessionCreates: number pty: ReturnType - emit: (events: OpenCodeEvent[]) => void + persistentPty: ReturnType + emit: (events: MockServerEvent[]) => void // MCP status overrides by `\n`, and OAuth attempt creation times by attempt ID. mcp: Map attempts: Map @@ -765,6 +785,25 @@ function mockHandlers( ), ) + const persistentPtyEnabled = Effect.suspend(() => + config.persistentPty && state.persistentPty.capability !== false + ? Effect.void + : Effect.fail(new MockServiceUnavailable({ message: "opencode-pty is not available", service: "opencode-pty" })), + ) + + const findPersistentPty = (id: string) => + persistentPtyEnabled.pipe( + Effect.andThen(() => + Effect.suspend(() => { + const found = state.persistentPty.find(id) + + return found + ? Effect.succeed(found) + : Effect.fail(new MockPtyNotFound({ ptyID: id, message: `PTY session not found: ${id}` })) + }), + ), + ) + const mcpServers = (directory: string) => (Predicate.isFunction(config.mcp) ? config.mcp(directory) : (config.mcp ?? [])).map((server) => { if (!Predicate.isObject(server)) return server @@ -880,6 +919,10 @@ function mockHandlers( hostname: config.hostname, urls: config.server ? [config.server] : [], paths: { tmp: "/tmp/opencode" }, + capabilities: + state.persistentPty.capability === undefined + ? undefined + : { persistentPty: state.persistentPty.capability }, }), config: () => Effect.succeed(configEntries), reference: () => Effect.succeed({ location: location(config), data: [] }), @@ -1241,6 +1284,57 @@ function mockHandlers( return { location: location(config, directory), data: { ticket, expires_in: 60 } } }), ), + persistentPtyList: (ctx) => + persistentPtyEnabled.pipe(Effect.map(() => ({ data: state.persistentPty.list(ctx.params.sessionID) }))), + persistentPtyCreate: (ctx) => + persistentPtyEnabled.pipe( + Effect.map(() => { + const session = config.sessions.find((item) => item.id === ctx.params.sessionID) + const directory = session ? currentSession(session, config.directory).location.directory : undefined + + return { + data: state.persistentPty.create(ctx.params.sessionID, { + ...ctx.payload, + cwd: ctx.payload.cwd ?? directory, + }), + } + }), + ), + persistentPtyGet: (ctx) => findPersistentPty(ctx.params.ptyID).pipe(Effect.map((data) => ({ data }))), + persistentPtyUpdate: (ctx) => + findPersistentPty(ctx.params.ptyID).pipe( + Effect.flatMap((found) => + ctx.payload.title !== undefined && !state.persistentPty.renameSupported + ? Effect.fail( + new MockPtyFeatureUnsupported({ + feature: "rename", + message: "Terminal renaming will be available after OpenCode's terminal service restarts", + }), + ) + : Effect.sync(() => ({ data: state.persistentPty.update(found.id, ctx.payload) })), + ), + ), + persistentPtyRemove: (ctx) => + findPersistentPty(ctx.params.ptyID).pipe( + Effect.map((found) => { + state.persistentPty.remove(found.id) + + return HttpApiSchema.NoContent.make() + }), + ), + persistentPtySnapshot: (ctx) => + findPersistentPty(ctx.params.ptyID).pipe( + Effect.map((found) => ({ data: state.persistentPty.snapshot(found.id) })), + ), + persistentPtyConnectToken: (ctx) => + findPersistentPty(ctx.params.ptyID).pipe( + Effect.map((found) => ({ + data: { + ticket: state.persistentPty.issue(found.id, Object.fromEntries(Object.entries(ctx.request.headers))), + expires_in: 60, + }, + })), + ), sessionList: (ctx) => { const sessions = config.sessions .filter( @@ -1315,6 +1409,7 @@ function mockHandlers( }), sessionRemove: () => noContent, sessionShell: () => noContent, + sessionView: () => noContent, sessionForm: (ctx) => Effect.succeed({ data: resolve(config.forms ?? []).filter( diff --git a/packages/app/e2e/utils/notifications.ts b/packages/app/e2e/utils/notifications.ts new file mode 100644 index 000000000000..6b6f3cd51a4d --- /dev/null +++ b/packages/app/e2e/utils/notifications.ts @@ -0,0 +1,51 @@ +import type { Page } from "@playwright/test" + +export async function recordNotifications(page: Page) { + const notifications: { title: string; body?: string }[] = [] + + const sounds: string[] = [] + + await page.exposeBinding("recordNotification", (_source, notification: { title: string; body?: string }) => { + notifications.push(notification) + }) + await page.exposeBinding("recordNotificationSound", (_source, src: string) => { + sounds.push(src) + }) + await page.addInitScript(() => { + // SAFETY: exposeBinding above installs these callbacks before the app starts. + const host: Window & { + recordNotification?: (notification: { title: string; body?: string }) => Promise + recordNotificationSound?: (src: string) => Promise + } = window + + document.hasFocus = () => false + Object.defineProperty(window, "Notification", { + value: class extends EventTarget { + static permission = "granted" + onclick: (() => void) | null = null + + constructor(title: string, options?: NotificationOptions) { + super() + void host.recordNotification!({ title, body: options?.body }) + } + + close() {} + }, + }) + Object.defineProperty(window, "Audio", { + value: class { + currentTime = 0 + + constructor(readonly src: string) {} + + play() { + return host.recordNotificationSound!(this.src) + } + + pause() {} + }, + }) + }) + + return { notifications, sounds } +} diff --git a/packages/app/e2e/utils/persistent-pty.ts b/packages/app/e2e/utils/persistent-pty.ts new file mode 100644 index 000000000000..4f1355d4c1e6 --- /dev/null +++ b/packages/app/e2e/utils/persistent-pty.ts @@ -0,0 +1,542 @@ +import type { WebSocketRoute } from "@playwright/test" +import type { OpenCodeEvent } from "@opencode/client/promise" +import type { PersistentPty } from "@opencode/schema/persistent-pty" +import { Predicate } from "effect" + +// Serves the session-scoped persistent PTY routes (`/api/experimental/.../terminal`, `/api/experimental/persistent-pty`) +// and their connect WebSockets, like a server backed by the opencode-pty daemon. +export type MockPersistentPtyConfig = { + // `server.info().capabilities.persistentPty`; omitted by default, like a server that predates the field. `false` + // also makes the routes answer 503 like a server without the daemon. + capability?: boolean + // Whether PUT renames (the daemon lists the `rename` feature). When false, a title update answers 501 + // PtyFeatureUnsupportedError. Default true. + renameSupported?: boolean + // Terminals that exist before the page loads; they publish no events. + initial?: MockPersistentPtySeed[] +} + +export type MockPersistentPtySeed = { + // Default: the next `pty_persistent_`. + id?: string + sessionID: string + // The create title (default "Terminal"). + title?: string + userTitle?: string | null + command?: string + args?: string[] + // Default: the server directory. + cwd?: string + size?: { cols: number; rows: number } + // Output the terminal already wrote; snapshots replay it as their checkpoint. + output?: string + foregroundProcess?: string | null +} + +// `PersistentPty.Info`, with the `userTitle` that terminal renaming adds. +export type MockPersistentPtyInfo = { + id: string + title: string + userTitle: string | null + command: string + args: string[] + cwd: string + status: "running" | "exited" + pid: number + exitCode?: number + sessionID: string + foregroundProcess: string | null + size: { cols: number; rows: number } + output: { head: number; tail: number } +} + +// `PersistentPty.UpdateInput` once renaming lands: `size` optional, `title: null` clears the user title. +export type MockPersistentPtyUpdate = { + attachmentID?: string + size?: { cols: number; rows: number } + title?: string | null +} + +// Published on rename; not yet part of `OpenCodeEvent`. +export type MockPersistentPtyUpdated = { + id: string + created: number + type: "persistent-pty.updated" + data: { sessionID: string; terminal: MockPersistentPtyInfo } +} + +export type MockServerEvent = OpenCodeEvent | MockPersistentPtyUpdated + +// The JSON text frames the server sends; output travels as binary frames. +export type MockPersistentPtyMessage = + | { + type: "attached" + attachmentID: string + inputProtocol: 0 | 1 + info: MockPersistentPtyInfo + role: "controller" | "observer" + generation: number + replay: { requestedOffset: number; availableOffset: number; endOffset: number; truncated: boolean } + } + | { type: "replay_complete"; endOffset: number } + | { type: "resized"; cols: number; rows: number; generation: number; checkpoint: string } + | { type: "controller_changed"; attachmentID?: string; generation: number } + | { type: "exited"; exitCode?: number; finalOffset: number } + | { type: "title_changed"; title: string } + +// One decoded `input_protocol=1` frame: type 0 takes control at a size, type 1 also writes `data`. +export type MockPersistentPtyFrame = { type: 0 | 1; cols: number; rows: number; data: string } + +export type MockPersistentPtySocket = { + id: string + attachmentID: string + url: URL + cursor: number + takeover: boolean + role: "controller" | "observer" + inputProtocol: 0 | 1 + frames: MockPersistentPtyFrame[] + // Text written to the terminal (type 1 frame data, or raw messages without the input protocol). + input: string[] + // JSON control messages sent to the client, in order. + messages: MockPersistentPtyMessage[] + closed: boolean + close(code?: number, reason?: string): Promise +} + +export type MockPersistentPty = { + // Read by `/api/info`; tests may change both mid-test. + capability: boolean | undefined + renameSupported: boolean + // Live terminals in creation order. + terminals: MockPersistentPtyInfo[] + created: MockPersistentPtyInfo[] + removed: string[] + updates: { id: string; body: MockPersistentPtyUpdate }[] + tokens: { id: string; headers: Record; ticket: string }[] + sockets: MockPersistentPtySocket[] + // Connects refused because the terminal, or an unused ticket issued for it, was missing. + rejected: { id: string; url: URL; reason: string }[] + // A terminal created by another client: it appears through `persistent-pty.added`. + add(seed: MockPersistentPtySeed): MockPersistentPtyInfo + // Shell output: advances `output.tail` and streams to every open socket of the terminal. + output(id: string, data: string | Uint8Array): void + // The shell exits: `exited` on every socket, which then closes, then the server removes the terminal. + exit(id: string, exitCode?: number | null): void + // Another client closed the terminal: its sockets close and `persistent-pty.removed` is published. + remove(id: string): void + // Another attachment (default "mock-other-client"), or none, takes control: `controller_changed` on every socket. + takeControl(id: string, attachmentID?: string | null): void + // The canonical size changes: `resized` with a checkpoint on every socket. + resize(id: string, size: { cols: number; rows: number }): void + // The shell sets its OSC title: `title_changed` when the effective title changes. + setOscTitle(id: string, title: string): void + // Another client renames the terminal (`null` clears): `title_changed` and `persistent-pty.updated`. + rename(id: string, title: string | null): void + // The current controller's attachment ID. + controller(id: string): string | undefined + // Closes the terminal's open sockets, as a dropped connection does. + close(id: string, code?: number, reason?: string): Promise + // The server restarts and adopts the daemon: terminals and output stay, open sockets close (1012) and unused tickets + // expire. The event stream is not touched; use `installSseTransport(...).disconnect()` to drop it as well. + restart(): Promise +} + +type Terminal = { + info: MockPersistentPtyInfo + createTitle: string + oscTitle: string + bytes: Uint8Array + controller?: string + generation: number +} + +type Connection = MockPersistentPtySocket & { ws: WebSocketRoute } + +const DEFAULT_SIZE = { cols: 80, rows: 24 } + +const OTHER_CLIENT = "mock-other-client" + +export function createPersistentPty( + input: { config?: MockPersistentPtyConfig; directory: string }, + emit: (events: MockServerEvent[]) => void, +) { + const terminals = new Map() + const tickets: { id: string; ticket: string }[] = [] + const counters = { id: 0, ticket: 0, event: 0 } + const connections: Connection[] = [] + const encoder = new TextEncoder() + + const event = (type: T) => { + counters.event += 1 + + return { id: `evt_mock_persistent_pty_${counters.event}`, created: Date.now(), type } + } + + const open = (id: string) => connections.filter((item) => item.id === id && !item.closed) + + const send = (connection: Connection, message: MockPersistentPtyMessage | Uint8Array) => { + if (connection.closed) return + + if (message instanceof Uint8Array) return connection.ws.send(Buffer.from(message)) + connection.messages.push(message) + connection.ws.send(JSON.stringify(message)) + } + + const broadcast = (id: string, message: MockPersistentPtyMessage | Uint8Array) => + open(id).forEach((item) => send(item, message)) + + // Server-side closes release control here instead of relying on Playwright's `onClose`. + const close = (items: Connection[], code: number, reason: string) => { + const closing = items.filter((item) => !item.closed) + closing.forEach((item) => (item.closed = true)) + closing.forEach(release) + + return Promise.all(closing.map((item) => item.ws.close({ code, reason }))).then(() => undefined) + } + + // Like the daemon, control passes to the most recent remaining attachment. A late close of a replaced socket that + // shares the controller's attachment ID is an observer by then, so it leaves the new controller alone. + const release = (connection: Connection) => { + const terminal = terminals.get(connection.id) + + if (!terminal || connection.role !== "controller" || terminal.controller !== connection.attachmentID) return + setController(terminal, open(connection.id).at(-1)?.attachmentID) + } + + const get = (id: string) => { + const found = terminals.get(id) + + if (!found) throw new Error(`No persistent PTY ${id}`) + + return found + } + + const effectiveTitle = (terminal: Terminal) => terminal.info.userTitle || terminal.oscTitle || terminal.createTitle + + const retitle = (terminal: Terminal) => { + const title = effectiveTitle(terminal) + + if (title === terminal.info.title) return + terminal.info.title = title + broadcast(terminal.info.id, { type: "title_changed", title }) + } + + const checkpoint = (terminal: Terminal) => Buffer.from(terminal.bytes).toString("base64") + + const setController = (terminal: Terminal, attachmentID: string | undefined) => { + terminal.generation += 1 + terminal.controller = attachmentID + connections + .filter((item) => item.id === terminal.info.id) + .forEach((item) => (item.role = item.attachmentID === attachmentID ? "controller" : "observer")) + broadcast(terminal.info.id, { + type: "controller_changed", + attachmentID, + generation: terminal.generation, + }) + } + + const resize = (terminal: Terminal, size: { cols: number; rows: number }) => { + if (terminal.info.size.cols === size.cols && terminal.info.size.rows === size.rows) return + terminal.info.size = { cols: size.cols, rows: size.rows } + broadcast(terminal.info.id, { + type: "resized", + cols: size.cols, + rows: size.rows, + generation: terminal.generation, + checkpoint: checkpoint(terminal), + }) + } + + // Skips IDs that a seed claims or that a terminal used, live or removed. + const allocate = (): string => { + counters.id += 1 + const id = `pty_persistent_${counters.id}` + + if (terminals.has(id) || pty.removed.includes(id) || input.config?.initial?.some((seed) => seed.id === id)) { + return allocate() + } + + return id + } + + const build = (seed: MockPersistentPtySeed) => { + const id = seed.id ?? allocate() + + if (!id.startsWith("pty")) throw new Error(`Persistent PTY IDs must start with "pty": ${id}`) + const bytes = encoder.encode(seed.output ?? "") + const createTitle = seed.title ?? "Terminal" + + const terminal: Terminal = { + createTitle, + oscTitle: "", + bytes, + generation: 0, + info: { + id, + title: seed.userTitle || createTitle, + userTitle: seed.userTitle ?? null, + command: seed.command ?? "cmd.exe", + args: seed.args ?? [], + cwd: seed.cwd ?? input.directory, + status: "running", + pid: 1, + sessionID: seed.sessionID, + foregroundProcess: seed.foregroundProcess ?? null, + size: seed.size ?? DEFAULT_SIZE, + output: { head: 0, tail: bytes.length }, + }, + } + + terminals.set(id, terminal) + + return terminal.info + } + + const drop = (terminal: Terminal) => { + terminals.delete(terminal.info.id) + pty.terminals.splice(pty.terminals.indexOf(terminal.info), 1) + pty.removed.push(terminal.info.id) + tickets.splice(0, tickets.length, ...tickets.filter((item) => item.id !== terminal.info.id)) + void close(open(terminal.info.id), 1000, "") + emit([ + { ...event("persistent-pty.removed"), data: { sessionID: terminal.info.sessionID, ptyID: terminal.info.id } }, + ]) + } + + const added = (info: MockPersistentPtyInfo) => { + pty.terminals.push(info) + pty.created.push(info) + emit([{ ...event("persistent-pty.added"), data: { sessionID: info.sessionID, terminal: info } }]) + + return info + } + + const rename = (terminal: Terminal, title: string | null) => { + terminal.info.userTitle = title || null + retitle(terminal) + emit([ + { ...event("persistent-pty.updated"), data: { sessionID: terminal.info.sessionID, terminal: terminal.info } }, + ]) + } + + // Type 0 and type 1 frames both make the sender controller at the frame's size, as the daemon does. + const interact = (connection: Connection, size: { cols: number; rows: number }, data?: Uint8Array) => { + const terminal = terminals.get(connection.id) + + if (!terminal || connection.closed) return + + if (terminal.controller !== connection.attachmentID) setController(terminal, connection.attachmentID) + resize(terminal, size) + + if (data) connection.input.push(new TextDecoder().decode(data)) + } + + const pty: MockPersistentPty = { + capability: input.config?.capability, + renameSupported: input.config?.renameSupported ?? true, + terminals: [], + created: [], + removed: [], + updates: [], + tokens: [], + sockets: connections, + rejected: [], + add: (seed) => added(build(seed)), + output(id, data) { + const terminal = get(id) + const bytes = Predicate.isString(data) ? encoder.encode(data) : data + const next = new Uint8Array(terminal.bytes.length + bytes.length) + next.set(terminal.bytes) + next.set(bytes, terminal.bytes.length) + terminal.bytes = next + terminal.info.output = { head: terminal.info.output.head, tail: next.length } + + if (bytes.length > 0) broadcast(id, bytes) + }, + exit(id, exitCode) { + const terminal = get(id) + terminal.info.status = "exited" + terminal.info.exitCode = exitCode ?? undefined + broadcast(id, { + type: "exited", + exitCode: exitCode ?? undefined, + finalOffset: terminal.info.output.tail, + }) + drop(terminal) + }, + remove: (id) => drop(get(id)), + takeControl: (id, attachmentID = OTHER_CLIENT) => setController(get(id), attachmentID ?? undefined), + resize: (id, size) => resize(get(id), size), + setOscTitle(id, title) { + const terminal = get(id) + terminal.oscTitle = title + retitle(terminal) + }, + rename: (id, title) => rename(get(id), title), + controller: (id) => get(id).controller, + close: (id, code = 1011, reason = "mock socket closed") => close(open(id), code, reason), + restart() { + tickets.splice(0) + terminals.forEach((terminal) => (terminal.controller = undefined)) + + return close(connections, 1012, "server restarted") + }, + } + + pty.terminals.push(...(input.config?.initial ?? []).map(build)) + + return Object.assign(pty, { + find: (id: string) => terminals.get(id)?.info, + list: (sessionID: string) => pty.terminals.filter((item) => item.sessionID === sessionID), + create(sessionID: string, body: PersistentPty.CreateInput) { + return added( + build({ + sessionID, + title: body.title, + cwd: body.cwd, + command: body.command, + args: [...body.args], + size: body.size, + }), + ) + }, + // Resizes when `size` is present and renames when `title` is present, like the server's update handler. + update(id: string, body: MockPersistentPtyUpdate) { + const terminal = get(id) + pty.updates.push({ id, body }) + + if (body.size) resize(terminal, body.size) + + if (body.title !== undefined) rename(terminal, body.title) + + return terminal.info + }, + snapshot(id: string) { + const terminal = get(id) + + return { + info: terminal.info, + text: new TextDecoder().decode(terminal.bytes), + checkpoint: checkpoint(terminal), + cursor: { x: 0, y: 0 }, + } + }, + issue(id: string, headers: Record) { + counters.ticket += 1 + const ticket = `e2e-persistent-ticket-${counters.ticket}` + tickets.push({ id, ticket }) + pty.tokens.push({ id, headers, ticket }) + + return ticket + }, + // Follows the server's connect handler: `attached`, the replay from `cursor` as one binary frame, then + // `replay_complete`; a controller attachment then broadcasts `controller_changed`. + connect(ws: WebSocketRoute) { + const url = new URL(ws.url()) + const id = decodeURIComponent(url.pathname.split("/")[4] ?? "") + const terminal = terminals.get(id) + const ticket = url.searchParams.get("ticket") + const index = tickets.findIndex((item) => item.id === id && item.ticket === ticket) + const cursor = Number(url.searchParams.get("cursor") ?? "0") + + const reason = + !terminal || pty.capability === false + ? "terminal unavailable" + : index < 0 + ? "No unused ticket was issued for this terminal" + : !Number.isSafeInteger(cursor) || cursor < 0 + ? "Invalid cursor" + : undefined + + if (!terminal || reason) { + pty.rejected.push({ id, url, reason: reason ?? "terminal unavailable" }) + + return ws.close({ + code: reason === "terminal unavailable" ? 4404 : 1008, + reason: reason ?? "terminal unavailable", + }) + } + + tickets.splice(index, 1) + const role = url.searchParams.get("role") === "observer" ? "observer" : "controller" + const takeover = url.searchParams.get("takeover") === "true" + const attachmentID = url.searchParams.get("attachment_id") ?? crypto.randomUUID() + + if (role === "controller" && terminal.controller && terminal.controller !== attachmentID && !takeover) { + pty.rejected.push({ id, url, reason: "terminal already has a controller" }) + + return ws.close({ code: 4404, reason: "terminal unavailable" }) + } + + const connection: Connection = { + ws, + id, + attachmentID, + url, + cursor, + takeover, + role, + inputProtocol: url.searchParams.get("input_protocol") === "1" ? 1 : 0, + frames: [], + input: [], + messages: [], + closed: false, + close: (code = 1011, reason = "mock socket closed") => close([connection], code, reason), + } + + ws.onMessage((message) => { + const data = Predicate.isString(message) ? Buffer.from(message) : message + + if (connection.inputProtocol === 0) return interact(connection, terminal.info.size, data) + + if (data.byteLength < 5) return + const type = data[0] + const cols = data.readUInt16BE(1) + const rows = data.readUInt16BE(3) + + if ((type !== 0 && type !== 1) || cols === 0 || rows === 0) return + const payload = data.subarray(5) + connection.frames.push({ type, cols, rows, data: type === 1 ? new TextDecoder().decode(payload) : "" }) + interact(connection, { cols, rows }, type === 1 ? payload : undefined) + }) + ws.onClose(() => { + if (connection.closed) return + connection.closed = true + release(connection) + }) + connections.push(connection) + + if (role === "controller" && terminal.controller !== attachmentID) { + terminal.generation += 1 + terminal.controller = attachmentID + } + + connection.role = terminal.controller === attachmentID ? "controller" : "observer" + const start = Math.max(terminal.info.output.head, Math.min(cursor, terminal.bytes.length)) + + send(connection, { + type: "attached", + attachmentID, + inputProtocol: connection.inputProtocol, + info: terminal.info, + role: connection.role, + generation: terminal.generation, + replay: { + requestedOffset: cursor, + availableOffset: start, + endOffset: terminal.bytes.length, + truncated: false, + }, + }) + + if (start < terminal.bytes.length) send(connection, terminal.bytes.subarray(start)) + send(connection, { type: "replay_complete", endOffset: terminal.bytes.length }) + + if (role !== "controller") return + connections.filter((item) => item.id === id && item !== connection).forEach((item) => (item.role = "observer")) + broadcast(id, { type: "controller_changed", attachmentID, generation: terminal.generation }) + }, + }) +} diff --git a/packages/app/e2e/utils/workspace.ts b/packages/app/e2e/utils/workspace.ts index 7a0035674817..cc3e86992b43 100644 --- a/packages/app/e2e/utils/workspace.ts +++ b/packages/app/e2e/utils/workspace.ts @@ -87,11 +87,16 @@ export async function openDraft(page: Page, input: WorkspaceInput & { draftID?: // Opens a draft on the local project with "New worktree" selected. Worktree creation stays pending until the test // resolves `worktree`; POST order (`worktree`, `session`, `prompt`), worktree requests, session creates and prompts are // recorded. The draft tab comes first, then a tab per session. -// The new-session trigger that shows the draft's project and worktree and opens the location dialog. +// The new-session trigger that shows the draft's project and opens the location dialog on its projects. export function newSessionLocation(page: Page) { return page.locator('[data-component="new-session"] [data-action="prompt-project"]') } +// The new-session trigger that shows the draft's worktree, or Local, and opens the project's worktree step. +export function newSessionWorktree(page: Page) { + return page.locator('[data-component="new-session"] [data-action="prompt-worktree"]') +} + export async function openWorktreeDraft(page: Page, input: WorkspaceInput & { draftID?: string }) { const worktree = Promise.withResolvers<{ status: number; json: unknown }>() const calls: string[] = [] @@ -139,13 +144,10 @@ export async function openWorktreeDraft(page: Page, input: WorkspaceInput & { dr await page.goto(draftHref(draftID)) const editor = page.locator('[data-component="composer-editor"]') await expect(editor).toBeVisible({ timeout: APP_READY_TIMEOUT }) - await newSessionLocation(page).click() - // The dialog opens on projects; → lists the current project's worktrees. - const search = page.getByRole("combobox", { name: "Search projects", exact: true }) - await expect(search).toBeFocused() - await search.press("ArrowRight") + await newSessionWorktree(page).click() + await expect(page.getByRole("combobox", { name: "Search worktrees", exact: true })).toBeFocused() await page.getByRole("option", { name: /^New worktree/ }).click() - await expect(newSessionLocation(page)).toContainText("New worktree") + await expect(newSessionWorktree(page)).toContainText("New worktree") await expect(editor).toBeEditable() return { ...workspace, draftID, editor, worktree, calls, worktreeRequests, creates, prompts } diff --git a/packages/app/src/composer/attachments/attachments.ts b/packages/app/src/composer/attachments/attachments.ts index f8953eb10a1f..989275182dbc 100644 --- a/packages/app/src/composer/attachments/attachments.ts +++ b/packages/app/src/composer/attachments/attachments.ts @@ -2,7 +2,7 @@ import { onCleanup, onMount } from "solid-js" import { createStore } from "solid-js/store" import { makeEventListener } from "@solid-primitives/event-listener" import { createBlobReference } from "@/runtime/persistence/drafts" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" import type { ComposerPrompt } from "../types" import type { ImageAttachmentPart, PathAttachmentPart } from "../state" import type { AttachmentDestination } from "./destination" diff --git a/packages/app/src/composer/attachments/destination.ts b/packages/app/src/composer/attachments/destination.ts index 76d583c961f7..7cd1578f2243 100644 --- a/packages/app/src/composer/attachments/destination.ts +++ b/packages/app/src/composer/attachments/destination.ts @@ -2,7 +2,7 @@ import type { Accessor } from "solid-js" import { useServer } from "@/runtime/server/current" import { useServerSDK } from "@/runtime/server/client" import { authTokenFromCredentials } from "@/runtime/server/api" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" import { useWorkspaceLocation } from "@/workspaces/location" import type { ComposerControls } from "../adapter" diff --git a/packages/app/src/composer/comment-note.ts b/packages/app/src/composer/comment-note.ts index 227c4c4591b0..47ed31c5fcb6 100644 --- a/packages/app/src/composer/comment-note.ts +++ b/packages/app/src/composer/comment-note.ts @@ -1,7 +1,7 @@ import type { SessionMessageUser } from "@opencode/client/promise" import { Option, Schema } from "effect" import { Persistence } from "@/runtime/persistence/schema" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" import { FileSelection } from "@/workspaces/files/types" import { durableNote, LegacyBrowserNote, NoteComment, QuoteComment, type ContextItem } from "./schema" diff --git a/packages/app/src/composer/comments.tsx b/packages/app/src/composer/comments.tsx index 10b04218f99f..64537a1015e9 100644 --- a/packages/app/src/composer/comments.tsx +++ b/packages/app/src/composer/comments.tsx @@ -7,7 +7,7 @@ import { Persist, persisted } from "@/runtime/persistence/storage" import { useServerSDK } from "@/runtime/server/client" import type { ServerScope } from "@/runtime/server/scope" import { createScopedCache } from "@/runtime/server/scoped-cache" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" import type { SelectedLineRange } from "@/workspaces/files/model" import { useWorkspaceLocation } from "@/workspaces/location" import { CommentStore, type LineComment } from "./schema" @@ -80,9 +80,12 @@ function group(comments: LineComment[]) { } function createCommentSessionState(store: Store, setStore: SetStoreFunction) { - const [state, setState] = createStore({ - focus: null as CommentFocus | null, - active: null as CommentFocus | null, + const [state, setState] = createStore<{ + focus: CommentFocus | null + active: CommentFocus | null + }>({ + focus: null, + active: null, }) // Reuse the previous array when contents are unchanged so consumers keep a stable diff --git a/packages/app/src/composer/editor/actions.test.ts b/packages/app/src/composer/editor/actions.test.ts index eb877b03e5be..9d3ebc5332d3 100644 --- a/packages/app/src/composer/editor/actions.test.ts +++ b/packages/app/src/composer/editor/actions.test.ts @@ -104,4 +104,47 @@ describe("Composer store", () => { ]) expect(prompt.state.cursor).toBe(9) }) + + test("inserts consecutive mentions without a range and replaces typed triggers after an existing mention", () => { + const prompt = createComposerEditorActions( + createStore({ + prompt: [{ type: "text", content: "", start: 0, end: 0 }], + context: { items: [] }, + }), + ) + + prompt.addMention({ type: "file", path: "src/a.ts", content: "@src/a.ts", start: 0, end: 0 }) + prompt.addMention({ type: "file", path: "src/b.ts", content: "@src/b.ts", start: 0, end: 0 }) + + expect(prompt.state.prompt).toEqual([ + { type: "file", path: "src/a.ts", content: "@src/a.ts", start: 0, end: 9 }, + { type: "text", content: " ", start: 9, end: 10 }, + { type: "file", path: "src/b.ts", content: "@src/b.ts", start: 10, end: 19 }, + { type: "text", content: " ", start: 19, end: 20 }, + ]) + expect(prompt.state.cursor).toBe(20) + + prompt.addText("@src/c") + prompt.addMention({ type: "file", path: "src/c.ts", content: "@src/c.ts", start: 0, end: 0 }) + + expect(prompt.state.prompt).toEqual([ + { type: "file", path: "src/a.ts", content: "@src/a.ts", start: 0, end: 9 }, + { type: "text", content: " ", start: 9, end: 10 }, + { type: "file", path: "src/b.ts", content: "@src/b.ts", start: 10, end: 19 }, + { type: "text", content: " ", start: 19, end: 20 }, + { type: "file", path: "src/c.ts", content: "@src/c.ts", start: 20, end: 29 }, + { type: "text", content: " ", start: 29, end: 30 }, + ]) + expect(prompt.state.cursor).toBe(30) + + prompt.setPrompt([{ type: "file", path: "src/a.ts", content: "@src/a.ts", start: 0, end: 9 }], 9) + prompt.addMention({ type: "file", path: "src/b.ts", content: "@src/b.ts", start: 0, end: 0 }) + + expect(prompt.state.prompt).toEqual([ + { type: "file", path: "src/a.ts", content: "@src/a.ts", start: 0, end: 9 }, + { type: "file", path: "src/b.ts", content: "@src/b.ts", start: 9, end: 18 }, + { type: "text", content: " ", start: 18, end: 19 }, + ]) + expect(prompt.state.cursor).toBe(19) + }) }) diff --git a/packages/app/src/composer/editor/actions.ts b/packages/app/src/composer/editor/actions.ts index c1b06fd62e60..9d07c455516c 100644 --- a/packages/app/src/composer/editor/actions.ts +++ b/packages/app/src/composer/editor/actions.ts @@ -80,14 +80,19 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) { mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart, range?: { start: number; end: number }, ) { - const text = store() - .prompt.map((part) => ("content" in part ? part.content : "")) - .join("") - - const end = range?.end ?? store().cursor ?? text.length - const start = range?.start ?? text.slice(0, end).lastIndexOf("@") - setStore()("prompt", insertMention(store().prompt, start < 0 ? end : start, end, mention)) - setStore()("cursor", (start < 0 ? end : start) + mention.content.length + 1) + const prompt = withOffsets(store().prompt) + const length = promptLength(prompt) + const end = range?.end ?? Math.min(store().cursor ?? length, length) + + const part = prompt.find( + (item): item is Extract => + item.type === "text" && end >= item.start && end <= item.end, + ) + + const index = part ? part.content.slice(0, end - part.start).lastIndexOf("@") : -1 + const start = range?.start ?? (part && index >= 0 ? part.start + index : end) + setStore()("prompt", insertMention(prompt, start, end, mention)) + setStore()("cursor", start + mention.content.length + 1) clearRetry() }, removeAttachment(id: string) { @@ -132,28 +137,36 @@ function insertMention( end: number, mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart, ): ComposerPrompt { - if (start === 0 && end === 0) { - return withOffsets([mention, { type: "text", content: " ", start: 0, end: 0 }, ...prompt]) - } - let position = 0 + let inserted = false const parts = prompt.flatMap((part) => { if (isAttachment(part)) return [part] const partStart = position position += part.content.length - if (part.type !== "text" || start < partStart || end > position) return [part] - const before = part.content.slice(0, start - partStart) - const after = part.content.slice(end - partStart) + if (inserted) return [part] - return [ - ...(before ? [{ type: "text" as const, content: before, start: 0, end: 0 }] : []), - mention, - { type: "text" as const, content: ` ${after}`, start: 0, end: 0 }, - ] + if (part.type === "text" && start >= partStart && end <= position) { + inserted = true + const before = part.content.slice(0, start - partStart) + const after = part.content.slice(end - partStart) + + return [ + ...(before ? [{ type: "text" as const, content: before, start: 0, end: 0 }] : []), + mention, + { type: "text" as const, content: ` ${after}`, start: 0, end: 0 }, + ] + } + + if (start !== end || start > partStart) return [part] + inserted = true + + return [mention, { type: "text", content: " ", start: 0, end: 0 }, part] }) + if (!inserted && start === end) parts.push(mention, { type: "text", content: " ", start: 0, end: 0 }) + return withOffsets(parts) } diff --git a/packages/app/src/composer/editor/editor.tsx b/packages/app/src/composer/editor/editor.tsx index 7c7fad0f3771..ed030bfb1d89 100644 --- a/packages/app/src/composer/editor/editor.tsx +++ b/packages/app/src/composer/editor/editor.tsx @@ -423,6 +423,7 @@ export function ComposerEditor(props: ComposerEditorProps) { {(control) => ( - + {(option) => ( - + {option.label} )} @@ -1323,9 +1335,11 @@ function ComposerEditorPopover(props: { type="button" data-suggestion-id={item.id} data-active={props.activeID === item.id ? "" : undefined} - class="flex h-7 w-full shrink-0 items-center gap-2 rounded-md px-2 py-1 text-start hover:bg-v2-overlay-simple-overlay-hover" + class="flex h-7 w-full shrink-0 items-center gap-2 rounded-md px-2 py-1 text-start" classList={{ "bg-v2-overlay-simple-overlay-hover": props.activeID === item.id }} - onPointerMove={() => props.onActiveChange(item)} + onPointerMove={(event) => { + if (event.movementX || event.movementY) props.onActiveChange(item) + }} onClick={() => props.onSelect(item)} >
diff --git a/packages/app/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index 452fed263476..0044a37e4161 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -166,7 +166,7 @@ export function createComposerEditor(input: { ) } - const [found, setFound] = createStore<{ files: ComposerSuggestion[] }>({ files: [] }) + const [found, setFound] = createStore<{ query?: string; files: ComposerSuggestion[] }>({ files: [] }) let fileQuery: string | undefined let fileAbort = new AbortController() onCleanup(() => abort(fileAbort)) @@ -181,7 +181,7 @@ export function createComposerEditor(input: { fileAbort = controller if (query === undefined || !query.trim() || /\s/.test(query)) { - if (found.files.length) setFound("files", []) + if (found.files.length) setFound({ query: undefined, files: [] }) return } @@ -189,7 +189,7 @@ export function createComposerEditor(input: { const timer = setTimeout( () => void Promise.resolve(input.searchContextFiles(query, controller.signal)).then( - (files) => !controller.signal.aborted && setFound("files", files), + (files) => !controller.signal.aborted && setFound({ query, files }), () => undefined, ), 150, @@ -263,6 +263,12 @@ export function createComposerEditor(input: { })), ) + // Files from the previous query stay listed while the next search runs, but the keyboard can't highlight or pick them. + const stale = (item: ComposerSuggestion) => + state.popover.type === "context" && item.kind === "file" && !item.recent && found.query !== state.popover.query + + const selectable = () => suggestions().flatMap((item) => (stale(item) ? [] : [item.id])) + const suggestions = () => { if (state.popover.type !== "history") return list().flat() const query = state.popover.query.trim().toLowerCase() @@ -324,6 +330,8 @@ export function createComposerEditor(input: { } function dispatch(event: ComposerInteractionEvent) { + if (event.type === "popover.active" && !selectable().includes(event.id)) return false + if (event.type === "popover.close") cancelFocus() if ( @@ -398,7 +406,7 @@ export function createComposerEditor(input: { key: event.key, ctrl: event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey, composing: event.isComposing, - ids: suggestions().map((item) => item.id), + ids: selectable(), empty: draft.state.prompt.every((part) => !("content" in part) || part.content.length === 0), }) @@ -413,6 +421,21 @@ export function createComposerEditor(input: { if (handled) return true + // The suggestion lists don't page, and a page key must not move the caret out of the query or page the timeline. + if ( + state.popover.type !== "closed" && + (event.key === "PageUp" || event.key === "PageDown") && + !event.shiftKey && + !event.altKey && + !event.ctrlKey && + !event.metaKey && + !event.isComposing + ) { + event.preventDefault() + + return true + } + if (event.key === "Escape" && input.view.submit.queue?.editing()) { event.preventDefault() input.view.submit.queue.cancelEdit() @@ -452,9 +475,9 @@ export function createComposerEditor(input: { createEffect(() => { if (state.popover.type === "closed") return - const ids = suggestions().map((item) => item.id) + const ids = selectable() - if (state.popover.activeID ? ids.includes(state.popover.activeID) : ids.length === 0) return + if (state.popover.activeID ? state.popover.chosen && ids.includes(state.popover.activeID) : ids.length === 0) return dispatch({ type: "popover.results", ids }) }) diff --git a/packages/app/src/composer/suggestions/machine.test.ts b/packages/app/src/composer/suggestions/machine.test.ts index ec1a268998ed..3663461dafc5 100644 --- a/packages/app/src/composer/suggestions/machine.test.ts +++ b/packages/app/src/composer/suggestions/machine.test.ts @@ -146,9 +146,28 @@ test.each<{ name: "loops active popover items with arrow keys", from: { popover: { type: "context", query: "", activeID: "second" } }, event: key("ArrowDown", { ids: ["first", "second"] }), - popover: { type: "context", query: "", activeID: "first" }, + popover: { type: "context", query: "", activeID: "first", chosen: true }, handled: true, }, + { + name: "moves a highlight the user didn't choose to the first row when results reorder", + from: { popover: { type: "context", query: "se", activeID: "server" } }, + event: { type: "popover.results", ids: ["session", "server"] }, + popover: { type: "context", query: "se", activeID: "session", chosen: false }, + }, + { + name: "keeps a chosen highlight when results reorder", + from: { popover: { type: "context", query: "se", activeID: "server", chosen: true } }, + event: { type: "popover.results", ids: ["session", "server"] }, + popover: { type: "context", query: "se", activeID: "server", chosen: true }, + }, + { + name: "forgets the chosen highlight when the query changes", + from: { popover: { type: "context", query: "se", activeID: "server", chosen: true } }, + event: { type: "input.changed", value: "@ses" }, + draft: persisted("@ses"), + popover: { type: "context", query: "ses" }, + }, ])("$name", (row) => { const result = transitionComposer( { ...createComposerInteractionState(), ...row.from }, diff --git a/packages/app/src/composer/suggestions/machine.ts b/packages/app/src/composer/suggestions/machine.ts index 33c7a48b93b9..617845935596 100644 --- a/packages/app/src/composer/suggestions/machine.ts +++ b/packages/app/src/composer/suggestions/machine.ts @@ -5,10 +5,10 @@ export type ComposerInteractionState = { mode: "normal" | "shell" popover: | { type: "closed" } - | { type: "context"; query: string; activeID?: string } - | { type: "command-inline"; query: string; activeID?: string } - | { type: "command-menu"; query: string; activeID?: string } - | { type: "history"; query: string; activeID?: string } + | { type: "context"; query: string; activeID?: string; chosen?: boolean } + | { type: "command-inline"; query: string; activeID?: string; chosen?: boolean } + | { type: "command-menu"; query: string; activeID?: string; chosen?: boolean } + | { type: "history"; query: string; activeID?: string; chosen?: boolean } drag: "idle" | "active" focus: "editor" | "command-search" | "history-search" | "external" activeContextID?: string @@ -176,11 +176,11 @@ function queryChanged(state: ComposerInteractionState, query: string): ComposerE if (state.popover.type === "closed") return unchanged(state) if (state.popover.type === "history") - return changed({ ...state, popover: { ...state.popover, query, activeID: undefined } }) + return changed({ ...state, popover: { ...state.popover, query, activeID: undefined, chosen: undefined } }) const popover = state.popover.type === "context" ? "context" : "command" - return changed({ ...state, popover: { ...state.popover, query, activeID: undefined } }, [ + return changed({ ...state, popover: { ...state.popover, query, activeID: undefined, chosen: undefined } }, [ { type: "popover.filter", popover, query }, ]) } @@ -188,21 +188,28 @@ function queryChanged(state: ComposerInteractionState, query: string): ComposerE function resultsChanged(state: ComposerInteractionState, ids: string[]): ComposerEditorTransition { if (state.popover.type === "closed") return unchanged(state) - const activeID = state.popover.activeID && ids.includes(state.popover.activeID) ? state.popover.activeID : ids[0] + // Until the user picks a row, the highlight follows the first row as results arrive and reorder. + const kept = + !!state.popover.activeID && + ids.includes(state.popover.activeID) && + (state.popover.chosen || state.popover.type === "history") + + const activeID = kept ? state.popover.activeID : ids[0] if (activeID === state.popover.activeID) return unchanged(state) return changed( - { ...state, popover: { ...state.popover, activeID } }, + { ...state, popover: { ...state.popover, activeID, chosen: kept && state.popover.chosen } }, state.popover.type === "history" && activeID ? [{ type: "history.preview", id: activeID }] : [], ) } function activeChanged(state: ComposerInteractionState, id: string): ComposerEditorTransition { - if (state.popover.type === "closed" || state.popover.activeID === id) return unchanged(state) + if (state.popover.type === "closed" || (state.popover.activeID === id && state.popover.chosen)) + return unchanged(state) return changed( - { ...state, popover: { ...state.popover, activeID: id } }, + { ...state, popover: { ...state.popover, activeID: id, chosen: true } }, state.popover.type === "history" ? [{ type: "history.preview", id }] : [], ) } @@ -296,7 +303,7 @@ function keyDown( : index return changed( - { ...state, popover: { ...state.popover, activeID: event.ids[next] } }, + { ...state, popover: { ...state.popover, activeID: event.ids[next], chosen: true } }, state.popover.type === "history" ? [{ type: "history.preview", id: event.ids[next] }] : [], true, ) diff --git a/packages/app/src/home/projects/reveal.ts b/packages/app/src/home/projects/reveal.ts index 5de6f8369ff9..d9bf5c048ef4 100644 --- a/packages/app/src/home/projects/reveal.ts +++ b/packages/app/src/home/projects/reveal.ts @@ -1,6 +1,6 @@ import { useLanguage } from "@/runtime/i18n/language" import { usePlatform } from "@/runtime/platform/platform" -import { ServerConnection } from "@/runtime/server/registry" +import { ServerConnection, useServers } from "@/runtime/server/registry" import { displayName } from "@opencode/ui/project-avatar" import { errorMessage } from "@/shell/layout/helpers" import type { LocalProject } from "@/shell/state/layout" @@ -9,9 +9,10 @@ import { showToast } from "@/shell/notifications/toast" export function useRevealProject() { const language = useLanguage() const platform = usePlatform() + const servers = useServers() const available = (conn: ServerConnection.Any) => - platform.platform === "desktop" && !!platform.revealPath && ServerConnection.local(conn) + platform.platform === "desktop" && !!platform.revealPath && servers.local(conn) return { available, diff --git a/packages/app/src/home/projects/view.tsx b/packages/app/src/home/projects/view.tsx index 93e231f8509d..46cdcb13fd68 100644 --- a/packages/app/src/home/projects/view.tsx +++ b/packages/app/src/home/projects/view.tsx @@ -1,5 +1,6 @@ import { createMemo, For, type JSX, onCleanup, Show, splitProps } from "solid-js" import { createStore } from "solid-js/store" +import { createResizeObserver } from "@solid-primitives/resize-observer" import { Popover } from "@kobalte/core/popover" import { displayName, @@ -149,7 +150,17 @@ export function HomeProjectsView(props: HomeProjectsViewProps) { } function HomeProjectsPanel(props: HomeProjectsViewProps) { + let observer: MutationObserver | undefined + let frame = 0 const [contextMenu, setContextMenu] = createStore<{ open: string | undefined }>({ open: undefined }) + const updateFades = (element: HTMLDivElement) => { + element.toggleAttribute("data-fade-top", element.scrollTop > 0) + element.toggleAttribute("data-fade-bottom", element.scrollTop + element.clientHeight < element.scrollHeight - 1) + } + onCleanup(() => { + observer?.disconnect() + cancelAnimationFrame(frame) + }) const contextMenuProps = { contextMenuOpen: (id: string) => contextMenu.open === id, @@ -197,8 +208,19 @@ function HomeProjectsPanel(props: HomeProjectsViewProps) {
-
-
+
+
{ + createResizeObserver(element, () => updateFades(element)) + observer = new MutationObserver(() => updateFades(element)) + observer.observe(element, { childList: true, subtree: true }) + frame = requestAnimationFrame(() => updateFades(element)) + }} + onScroll={(event) => updateFades(event.currentTarget)} + > ( - + <> + {/* A busy session shows its activity ring instead of the unread dot. */} + + + + + )} /> ) } -function HomeSessionLeading(props: { record: HomeSessionRecord; open: boolean; unread: boolean; loading: boolean }) { +function HomeSessionLeading(props: { record: HomeSessionRecord; open: boolean; unread: boolean }) { return (
@@ -264,7 +269,6 @@ function HomeSessionLeading(props: { record: HomeSessionRecord; open: boolean; u project={props.record.project} directory={props.record.session.location.directory} unread={props.unread} - loading={props.loading} />
) @@ -472,7 +476,7 @@ function HomeSessionSearchResultRow( props.onSearchSelect(props.record, { background: true }) }} > - +
@@ -622,7 +626,7 @@ function HomeSessionRow( class="flex h-10 min-w-0 w-full flex-1 items-center py-3 ps-1.5 pe-3 md:ps-3" classList={{ "gap-1.5": props.desktop, "gap-2": !props.desktop, "md:pe-10": SHOW_HOME_SESSION_ARCHIVE }} > - +
- +
location(project()) : undefined} - /> - } + branch={} onboarding={onboardingReady() && !onboarding.used && props.workspace.bar.visible()} onClick={() => location()} + onWorktree={project().id && project().vcs === "git" ? () => location(project()) : undefined} /> )} @@ -280,7 +275,10 @@ function fitPath(value: string, width: number, font: string) { } } -/** The composer tray: combined location picker, Git context, and the session's directory. */ +const TRIGGER = + "flex h-7 items-center gap-1.5 rounded-sm text-start ps-1.5 pe-2 text-v2-text-text-muted transition-colors hover:bg-v2-overlay-simple-overlay-hover hover:text-v2-text-text-base focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:text-v2-text-text-base focus-visible:outline-none" + +/** The composer tray: project and worktree pickers, Git context, and the session's directory. */ function NewSessionLocation(props: { project: PromptProject /** "main", "create", or a worktree directory. */ @@ -289,6 +287,8 @@ function NewSessionLocation(props: { branch?: JSX.Element onboarding: boolean onClick: () => void + /** Opens the project's worktree step; without it the project has no worktrees to choose. */ + onWorktree?: () => void }) { const language = useLanguage() const command = useCommand() @@ -312,61 +312,85 @@ function NewSessionLocation(props: { return (
-
- -
- - {language.t("workspace.onboarding.title")} -
- {language.t("workspace.onboarding.description")} -
- ) : ( - language.t("session.new.workspace.trigger.tooltip") - ) - } - contentClass={props.onboarding ? "max-w-[280px]" : undefined} - class="flex min-w-0 max-w-full" - > - - + {displayName(props.project)} + + + + {(onWorktree) => ( + <> + + +
+ + {language.t("workspace.onboarding.title")} +
+ + {language.t("workspace.onboarding.description")} + +
+ ) : ( + language.t("session.location.worktree") + ) + } + contentClass={props.onboarding ? "max-w-[280px]" : undefined} + class="flex min-w-12 shrink-[1000]" + > + + + + )} + +
{props.branch}
{/* An open tooltip can outlive this row; keep its path instead of a stale Show accessor. */} @@ -390,7 +414,7 @@ function NewSessionLocation(props: { const style = getComputedStyle(row) setLayout({ - width: row.clientWidth - (icon?.clientWidth ?? 0) - parseFloat(style.columnGap), + width: row.clientWidth - (icon ? icon.clientWidth + parseFloat(style.columnGap) : 0), font: style.font, }) }) @@ -398,24 +422,23 @@ function NewSessionLocation(props: { class="flex min-w-0 flex-1 items-center justify-end gap-1.5" dir="ltr" > - - {language.t("session.location.toggle")} - + {/* The worktree trigger already says Local, so only a worktree marks its path. */} + + + {language.t("session.location.toggle")} + + + } + > + + - } - > - - - - + +
void - /** Opens the project's worktree picker; the checkout branch is static text without it. */ - onWorktree?: () => void -}) { +export function NewSessionBranch(props: { workspace: NewSessionWorkspaceController; onDone: () => void }) { const language = useLanguage() const [state, setState] = createStore({ open: false, truncated: false }) @@ -69,9 +64,6 @@ export function NewSessionBranch(props: { ? language.t("session.new.workspace.fromBranch", { branch: props.workspace.bar.branch() ?? "" }) : props.workspace.bar.branch() - // A truncated name keeps its full-text tooltip; otherwise the clickable checkout branch explains its action. - const hint = () => !creating() && !!props.onWorktree && !state.truncated - const observe = (element: HTMLSpanElement) => createResizeObserver(element, () => setState("truncated", element.scrollWidth > element.clientWidth)) @@ -79,39 +71,20 @@ export function NewSessionBranch(props: { - - - {label()} - -
- } - > - -
+
+ + + {label()} + +
} > (script === "Aran" ? "Arab" : scrip export const DESKTOP_NATIVE_ENGLISH = { "desktop.microphoneUsage": "OpenCode uses your microphone for voice calls.", + "desktop.documentsFolderUsage": + "OpenCode uses files in your Documents folder for projects you open and commands you run there.", + "desktop.desktopFolderUsage": "OpenCode uses files on your Desktop for projects you open and commands you run there.", + "desktop.downloadsFolderUsage": + "OpenCode uses files in your Downloads folder for projects you open and commands you run there.", + "desktop.networkVolumesUsage": + "OpenCode uses files on network volumes for projects you open and commands you run there.", + "desktop.removableVolumesUsage": + "OpenCode uses files on removable volumes for projects you open and commands you run there.", "desktop.menu.app": "OpenCode", "desktop.menu.file": "File", "desktop.menu.edit": "Edit", @@ -302,6 +313,9 @@ export const DESKTOP_NATIVE_ENGLISH = { "desktop.picker.error.notSelected": "File was not selected by the picker", "desktop.picker.error.sizeLimit": "Selected attachments exceed the {{limit}} MB limit", + + "desktop.contextMenu.spellcheck": "Spellcheck", + "desktop.contextMenu.spellcheckLanguages": "Spellcheck Languages", } as const export type DesktopNativeKey = keyof typeof DESKTOP_NATIVE_ENGLISH @@ -310,6 +324,7 @@ export type DesktopNativeMessages = Record export type DesktopNativeBundle = { locale: DesktopNativeLocale; messages: DesktopNativeMessages } +// SAFETY: DESKTOP_NATIVE_ENGLISH is a const literal, so its own keys are exactly DesktopNativeKey. export const DESKTOP_NATIVE_KEYS = Object.keys(DESKTOP_NATIVE_ENGLISH) as DesktopNativeKey[] export const DESKTOP_NATIVE_MAX_PAYLOAD_BYTES = 64 * 1024 @@ -320,35 +335,24 @@ export function createDesktopNativeBundle( ): DesktopNativeBundle { return { locale, + // SAFETY: the entries map every DesktopNativeKey to a string, which is exactly DesktopNativeMessages. messages: Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key) => [key, translate(key)])) as DesktopNativeMessages, } } -export function parseDesktopNativeBundle(value: unknown): DesktopNativeBundle | undefined { - if (!value || typeof value !== "object" || Array.isArray(value)) return undefined - - try { - if (new TextEncoder().encode(JSON.stringify(value)).byteLength > DESKTOP_NATIVE_MAX_PAYLOAD_BYTES) return undefined - } catch { - return undefined - } +const DesktopNativeBundleSchema = Schema.Struct({ + locale: Schema.Literals(DESKTOP_NATIVE_LOCALES), + messages: Schema.Record(Schema.Literals(DESKTOP_NATIVE_KEYS), Schema.String), +}).check( + Schema.makeFilter( + (bundle) => new TextEncoder().encode(JSON.stringify(bundle)).byteLength <= DESKTOP_NATIVE_MAX_PAYLOAD_BYTES, + ), +) - const bundle = value as { locale?: unknown; messages?: unknown } +const decodeDesktopNativeBundle = Schema.decodeUnknownOption(DesktopNativeBundleSchema, { onExcessProperty: "error" }) - if (!DESKTOP_NATIVE_LOCALES.some((locale) => locale === bundle.locale)) return undefined - - if (!bundle.messages || typeof bundle.messages !== "object" || Array.isArray(bundle.messages)) return undefined - const messages = bundle.messages as Record - const keys = Object.keys(messages) - - if (keys.length !== DESKTOP_NATIVE_KEYS.length) return undefined - - if (!DESKTOP_NATIVE_KEYS.every((key) => typeof messages[key] === "string")) return undefined - - if (!keys.every((key) => key in DESKTOP_NATIVE_ENGLISH)) return undefined - - return bundle as DesktopNativeBundle -} +/** Validates a bundle the renderer sent over IPC: a supported locale, exactly the native keys, and a bounded size. */ +export const parseDesktopNativeBundle = flow(decodeDesktopNativeBundle, Option.getOrUndefined) export function formatDesktopNativeMessage(message: string, params?: Record) { if (!params) return message diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 2015d1d75e48..f70ffa20665f 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -550,6 +550,8 @@ export const dict = { "error.chain.configInvalidWithMessage": "Config file at {{path}} is invalid: {{message}}", "notification.permission.title": "Permission required", + "notification.question.title": "Question requires an answer", + "notification.elicitation.title": "Input requested", "notification.session.responseReady.title": "Response ready", "notification.session.error.title": "Session error", @@ -665,6 +667,7 @@ export const dict = { "session.new.project.new": "New project", "session.new.project.search": "Search projects", "session.new.project.add": "Add project", + "session.new.project.trigger.tooltip": "Choose project", "session.new.worktree.creating": "Creating worktree", "session.new.workspace.runIn": "Run session in", "session.new.workspace.triggerLocal": "Local", @@ -809,6 +812,7 @@ export const dict = { "settings.tab.about": "About", "settings.about.version": "Version {{version}}", "settings.about.devVersion": "development", + "settings.about.copyVersionFailed": "Failed to copy version", "settings.about.license": "Released under the MIT License", "settings.about.writtenByNames": "Written by {{names}}", "settings.about.illustratedByNames": "Illustrated by {{names}}", @@ -876,6 +880,7 @@ export const dict = { "settings.server.preferences.websearch.description": "Select the search provider agents use to search the web", "settings.projects.title": "Projects", "settings.projects.description": "Manage projects and their settings", + "settings.projects.other": "Other projects", "settings.projects.empty": "No projects found", "settings.projects.empty.title": "No projects yet", "settings.projects.empty.description": "Add a project to get started", @@ -1002,6 +1007,8 @@ export const dict = { "settings.general.row.followUpBehavior.steer": "Steer", "settings.general.row.pinchZoom.title": "Pinch to zoom", "settings.general.row.pinchZoom.description": "Allow trackpad pinch and Ctrl-scroll gestures to zoom", + "settings.general.row.spellcheck.title": "Spellcheck", + "settings.general.row.spellcheck.description": "Underline misspelled words while typing", "sound.option.none": "None", "sound.option.alert01": "Alert 01", @@ -1055,6 +1062,8 @@ export const dict = { "Show system notification when the agent is complete or needs attention", "settings.general.notifications.permissions.title": "Permissions", "settings.general.notifications.permissions.description": "Show system notification when a permission is required", + "settings.general.notifications.questions.title": "Questions", + "settings.general.notifications.questions.description": "Show system notification when the agent asks a question", "settings.general.notifications.errors.title": "Errors", "settings.general.notifications.errors.description": "Show system notification when an error occurs", @@ -1062,6 +1071,8 @@ export const dict = { "settings.general.sounds.agent.description": "Play sound when the agent is complete or needs attention", "settings.general.sounds.permissions.title": "Permissions", "settings.general.sounds.permissions.description": "Play sound when a permission is required", + "settings.general.sounds.questions.title": "Questions", + "settings.general.sounds.questions.description": "Play sound when the agent asks a question", "settings.general.sounds.errors.title": "Errors", "settings.general.sounds.errors.description": "Play sound when an error occurs", "settings.general.sounds.interface.title": "Interface", diff --git a/packages/app/src/runtime/i18n/hr.ts b/packages/app/src/runtime/i18n/hr.ts index 08b53b437b64..f47a46269e71 100644 --- a/packages/app/src/runtime/i18n/hr.ts +++ b/packages/app/src/runtime/i18n/hr.ts @@ -72,7 +72,7 @@ const desktop = [ ] export const dict = { - ...Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key, index) => [key, desktop[index]])), + ...Object.fromEntries(desktop.map((value, index) => [DESKTOP_NATIVE_KEYS[index], value])), "command.category.suggested": "Predloženo", "command.category.view": "Prikaz", "command.category.project": "Projekt", diff --git a/packages/app/src/runtime/i18n/hu.ts b/packages/app/src/runtime/i18n/hu.ts index dfbf1b404766..989c665c6db8 100644 --- a/packages/app/src/runtime/i18n/hu.ts +++ b/packages/app/src/runtime/i18n/hu.ts @@ -72,7 +72,7 @@ const desktop = [ ] export const dict = { - ...Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key, index) => [key, desktop[index]])), + ...Object.fromEntries(desktop.map((value, index) => [DESKTOP_NATIVE_KEYS[index], value])), "command.category.suggested": "Javasolt", "command.category.view": "Nézet", "command.category.project": "Projekt", diff --git a/packages/app/src/runtime/i18n/is.ts b/packages/app/src/runtime/i18n/is.ts index d59bed90c736..a38af244fd62 100644 --- a/packages/app/src/runtime/i18n/is.ts +++ b/packages/app/src/runtime/i18n/is.ts @@ -72,7 +72,7 @@ const desktop = [ ] export const dict = { - ...Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key, index) => [key, desktop[index]])), + ...Object.fromEntries(desktop.map((value, index) => [DESKTOP_NATIVE_KEYS[index], value])), "command.category.suggested": "Tillögur", "command.category.view": "Skoða", "command.category.project": "Verkefni", diff --git a/packages/app/src/runtime/i18n/lt.ts b/packages/app/src/runtime/i18n/lt.ts index 34758c917e13..c4533c4e294b 100644 --- a/packages/app/src/runtime/i18n/lt.ts +++ b/packages/app/src/runtime/i18n/lt.ts @@ -72,7 +72,7 @@ const desktop = [ ] export const dict = { - ...Object.fromEntries(DESKTOP_NATIVE_KEYS.map((key, index) => [key, desktop[index]])), + ...Object.fromEntries(desktop.map((value, index) => [DESKTOP_NATIVE_KEYS[index], value])), "command.category.suggested": "Siūloma", "command.category.view": "Rodinys", "command.category.project": "Projektas", diff --git a/packages/app/src/runtime/platform/platform.tsx b/packages/app/src/runtime/platform/platform.tsx index ecbf0b2eb427..38a12334f229 100644 --- a/packages/app/src/runtime/platform/platform.tsx +++ b/packages/app/src/runtime/platform/platform.tsx @@ -108,6 +108,12 @@ type PlatformBase = { /** Allow native pinch/Ctrl-scroll zoom gestures (desktop only) */ setPinchZoomEnabled?(enabled: boolean): Promise | void + /** Get whether the native spellchecker underlines misspelled words (desktop only) */ + getSpellcheckEnabled?(): Promise + + /** Turn the native spellchecker on or off (desktop only) */ + setSpellcheckEnabled?(enabled: boolean): Promise + /** Run a desktop-only menu action from the app chrome */ runDesktopMenuAction?(action: DesktopMenuAction): Promise | void diff --git a/packages/app/src/runtime/plugin/host-apis.tsx b/packages/app/src/runtime/plugin/host-apis.tsx index 3b180b1e9592..b7a5dab43c9f 100644 --- a/packages/app/src/runtime/plugin/host-apis.tsx +++ b/packages/app/src/runtime/plugin/host-apis.tsx @@ -16,6 +16,7 @@ import { useDialog } from "@opencode/ui/context/dialog" import { useTheme } from "@opencode/ui/theme/context" import { toaster } from "@opencode/ui/toast" import { base64Encode } from "@opencode/util/encode" +import { uuid } from "@opencode/util/uuid" import { type App, type Layout, @@ -535,7 +536,7 @@ export function createPluginAttachment(apis: HostApis) { return live().data }, get local() { - return ServerConnection.local(listed()) + return servers.local(listed()) }, get builtin() { return ServerConnection.builtin(listed()) @@ -1023,7 +1024,7 @@ export function createPluginAttachment(apis: HostApis) { id: error ? settings.sounds.errors() : settings.sounds.agent(), })) - const key = `plugin:${plugin}\0${options.id ?? crypto.randomUUID()}` + const key = `plugin:${plugin}\0${options.id ?? uuid()}` const result = { notification: false, sound: false } const session = options.session diff --git a/packages/app/src/runtime/plugin/panel-menu.ts b/packages/app/src/runtime/plugin/panel-menu.ts index 9bcc15fe395e..56b03dd228d6 100644 --- a/packages/app/src/runtime/plugin/panel-menu.ts +++ b/packages/app/src/runtime/plugin/panel-menu.ts @@ -1,15 +1,29 @@ import { createMemo } from "solid-js" -import { MenuItem } from "@opencode/plugin/gui" +import { MenuItem, type SessionPanelMenuItem } from "@opencode/plugin/gui" import { usePluginHost } from "./host" -/** The side region's + menu: every plugin's `session.panel` item, in order. */ -export function createSessionPanelMenu() { +export type SessionPanelMenuEntry = { + readonly key: string + readonly item: SessionPanelMenuItem +} + +/** The side region's + menu entries, keyed by `${plugin}:${id}` in display order. */ +export function createSessionPanelMenuEntries() { const host = usePluginHost() return createMemo(() => host - .list(MenuItem) - .flatMap((item) => (item.menu === "session.panel" ? [item] : [])) - .toSorted((a, b) => (a.order ?? 0) - (b.order ?? 0)), + .items(MenuItem) + .flatMap((entry): SessionPanelMenuEntry[] => + entry.value.menu === "session.panel" ? [{ key: `${entry.plugin}:${entry.value.id}`, item: entry.value }] : [], + ) + .toSorted((a, b) => (a.item.order ?? 0) - (b.item.order ?? 0)), ) } + +/** The side region's + menu: every plugin's `session.panel` item, in order. */ +export function createSessionPanelMenu() { + const entries = createSessionPanelMenuEntries() + + return createMemo(() => entries().map((entry) => entry.item)) +} diff --git a/packages/app/src/runtime/plugin/panel-trigger.tsx b/packages/app/src/runtime/plugin/panel-trigger.tsx index acb84d9bca24..fb6bbd278efb 100644 --- a/packages/app/src/runtime/plugin/panel-trigger.tsx +++ b/packages/app/src/runtime/plugin/panel-trigger.tsx @@ -97,16 +97,18 @@ export function PanelTrigger(props: { const compactClose = () => tooltip( props.onClose(props.value)} aria-label={language.t("common.closeTab")} />) - // The close button `closable` asks for; a plain one by default. - const close = () => { - const closable = props.tab.closable + const closable = createMemo(() => props.tab.closable) - if (closable === false) return undefined + // Memoized by `closable` mode so a refreshed RegionEntry never recreates the button mid-click. + const close = createMemo(() => { + const mode = closable() - if (closable === "compact") return compactClose() + if (mode === false) return undefined - return closeButton(closable === "hover") - } + if (mode === "compact") return compactClose() + + return closeButton(mode === "hover") + }) return (
input.tabs().all() const providers = createMemo(() => host.items(BuiltinPanel).filter((item) => item.value.region === input.region)) - const entries = createMemo(() => - providers().flatMap((item) => { - const prefix = `${item.plugin}:` - const open = stored().flatMap((key) => (key.startsWith(prefix) ? [key.slice(prefix.length)] : [])) - - return item.value.list(panelInput(input.view, input.screen, { open })).map( - (tab): RegionEntry => ({ - key: panelKey(item.plugin, tab.id), - plugin: item.plugin, - tab, - provider: item.value, - }), - ) - }), + const entries = createMemo( + (previous) => { + const prior = new Map(previous.map((entry) => [entry.key, entry])) + + return providers().flatMap((item) => { + const prefix = `${item.plugin}:` + const open = stored().flatMap((key) => (key.startsWith(prefix) ? [key.slice(prefix.length)] : [])) + + return item.value.list(panelInput(input.view, input.screen, { open })).map((tab): RegionEntry => { + const key = panelKey(item.plugin, tab.id) + const existing = prior.get(key) + + if (existing && existing.tab === tab && existing.provider === item.value) return existing + + return { + key, + plugin: item.plugin, + tab, + provider: item.value, + } + }) + }) + }, + [], + { equals: same }, ) const byKey = createMemo(() => new Map(entries().map((entry) => [entry.key, entry]))) @@ -327,12 +338,29 @@ export function createRegion(input: { if (state.adding.some((value) => !live(value))) setState("adding", (list) => list.filter(live)) }) + const empty = createMemo(() => strip().length === 0) + + // Focus leaves before the close starts, back to where it was; otherwise the panel hands it to its toggle. + const giveBackFocus = () => { + const inside = !!document.getElementById("review-panel")?.contains(document.activeElement) + const back = returnFocus + returnFocus = undefined + + if (inside && back?.isConnected) back.focus({ preventScroll: true }) + } + + // Emptying the region closes it, so focus goes back as the user's own close would give it. + const emptied = () => { + giveBackFocus() + input.onEmptied?.() + } + // Closing the last New tab of a strip with no tabs closes the region, as closing its last tab does. const dismissNewTab = (id: string) => batch(() => { setState("adding", (list) => list.filter((value) => value.id !== id)) - if (stored().length === 0 && !state.adding.some(live)) input.onEmptied?.() + if (empty() && !state.adding.some(live)) emptied() }) return { @@ -342,7 +370,7 @@ export function createRegion(input: { /** The drawn strip of the pane that holds the selected tab, by key. */ keys: () => panes[activePane()].keys(), /** The strip holds no tab, hidden ones included. */ - empty: createMemo(() => strip().length === 0), + empty, entry: (key: string) => byKey().get(key), active, selected: createMemo(() => { @@ -396,12 +424,7 @@ export function createRegion(input: { const focused = document.activeElement if (side.opened()) { - const inside = !!document.getElementById("review-panel")?.contains(focused) - const back = returnFocus - returnFocus = undefined - - // Focus leaves before the close starts, back to where it was; otherwise the panel hands it to its toggle. - if (inside && back?.isConnected) back.focus({ preventScroll: true }) + giveBackFocus() side.toggle() return @@ -431,7 +454,7 @@ export function createRegion(input: { batch(() => { input.tabs().close(key) - if (last) input.onEmptied?.() + if (last) emptied() }) if (entry) diff --git a/packages/app/src/runtime/plugin/side-region.tsx b/packages/app/src/runtime/plugin/side-region.tsx index 7d249cd99097..f12dfe06c031 100644 --- a/packages/app/src/runtime/plugin/side-region.tsx +++ b/packages/app/src/runtime/plugin/side-region.tsx @@ -30,11 +30,12 @@ import { import { useCommand } from "@/shell/commands/command" import { guardClosingFocus } from "@/shell/panel-motion" import { useLanguage } from "@/runtime/i18n/language" +import { same } from "@/runtime/persistence/equality" import { useLayout } from "@/shell/state/layout" import { useSessionLayout } from "@/session/session-layout" import type { Sizing } from "@/session/helpers" import { PanelTrigger } from "./panel-trigger" -import { createSessionPanelMenu } from "./panel-menu" +import { createSessionPanelMenuEntries, type SessionPanelMenuEntry } from "./panel-menu" import { RegionContent, type Region, type RegionPane } from "./panels" import { PluginSlot } from "./render" import { createTabStripScroll } from "./tab-strip-scroll" @@ -201,9 +202,9 @@ export function PaneTabs(props: { }) { const language = useLanguage() const { tabs } = useSessionLayout() - const menu = createSessionPanelMenu() - const primary = createMemo(() => menu().find((item) => item.primary)) - const launchers = createMemo(() => menu().filter((item) => !item.primary && !item.opened)) + const menu = createSessionPanelMenuEntries() + const primary = createMemo(() => menu().find((entry) => entry.item.primary)?.item) + const launchers = createMemo(() => menu().filter((entry) => !entry.item.primary && !entry.item.opened)) // The next tab this pane's "+" menu opens lands in this pane. const target = () => tabs().target(props.pane.id) @@ -331,7 +332,7 @@ export function PaneTabs(props: {
0} @@ -495,9 +496,11 @@ function AddButton(props: { item: SessionPanelMenuItem; onChoose: () => void }): ) } -function AddMenu(props: { items: readonly SessionPanelMenuItem[]; onChoose: () => void }): JSX.Element { +function AddMenu(props: { items: readonly SessionPanelMenuEntry[]; onChoose: () => void }): JSX.Element { const language = useLanguage() const command = useCommand() + const keys = createMemo(() => props.items.map((entry) => entry.key), [], { equals: same }) + const byKey = createMemo(() => new Map(props.items.map((entry) => [entry.key, entry.item]))) // A chosen item runs once the closing menu has returned focus to "+", and the tab strip has passed it on to the // selected tab. Releasing that focus first lets the item move it where its tab needs it, e.g. into a new terminal, // without the strip taking it back for the tab it remembers. @@ -530,27 +533,35 @@ function AddMenu(props: { items: readonly SessionPanelMenuItem[]; onChoose: () = }) }} > - - {(item) => { - const keybind = createMemo(() => (item.keybind ? command.keybindParts(item.keybind) : [])) - - return ( - (chosen = item)} - shortcut={ - 0}> - - - } - > -
- {(icon) => } - {item.title} -
-
- ) - }} + + {(key) => ( + + {(item) => { + const keybind = createMemo(() => { + const bind = item().keybind + + return bind ? command.keybindParts(bind) : [] + }) + + return ( + (chosen = item())} + shortcut={ + 0}> + + + } + > +
+ {(icon) => } + {item().title} +
+
+ ) + }} +
+ )}
@@ -561,14 +572,21 @@ function AddMenu(props: { items: readonly SessionPanelMenuItem[]; onChoose: () = /** The + menu items as rows, then the session's recently closed tabs, in the new tab view. */ function Launchers(props: { - items: readonly SessionPanelMenuItem[] + items: readonly SessionPanelMenuEntry[] onChoose: () => void closed: { entries: readonly ClosedSideTab[]; onReopen: (key: string) => void } }): JSX.Element { + const keys = createMemo(() => props.items.map((entry) => entry.key), [], { equals: same }) + const byKey = createMemo(() => new Map(props.items.map((entry) => [entry.key, entry.item]))) + return (
- {(item) => } + + {(key) => ( + {(item) => } + )} +
diff --git a/packages/app/src/runtime/server/api.ts b/packages/app/src/runtime/server/api.ts index 5da5f219b344..249607d33c09 100644 --- a/packages/app/src/runtime/server/api.ts +++ b/packages/app/src/runtime/server/api.ts @@ -1,10 +1,4 @@ -import { - OpenCode, - type MessageListInput, - type OpenCodeClient, - type SessionInboxListInput, - type SessionMessageGetInput, -} from "@opencode/client/promise" +import { OpenCode, withMediaRefs, type MediaRequestOptions } from "@opencode/client/promise" import type { ServerConnection } from "@/runtime/server/registry" import { decode64 } from "@/runtime/persistence/base64" @@ -25,12 +19,8 @@ export function authFromToken(token: string | null) { } } -export const MEDIA_URI_CAPABILITY = "experimental-media-uri" - -export const CAPABILITIES_HEADER = "X-OpenCode-Capabilities" - /** `mediaRefs: false` reads stored media as inline bytes, for callers such as export that need self-contained messages. */ -export type ServerRequestOptions = OpenCode.RequestOptions & { readonly mediaRefs?: false } +export type ServerRequestOptions = MediaRequestOptions export function createApiForServer(input: { server: ServerConnection.HttpBase; fetch?: typeof globalThis.fetch }) { return withMediaRefs( @@ -48,42 +38,6 @@ export function createApiForServer(input: { server: ServerConnection.HttpBase; f ) } -/** - * Only the message and inbox reads can return stored media as `media:` refs, so only they carry the capability. - * A custom header makes a cross-origin request preflighted, which every other request must keep avoiding. - */ -function withMediaRefs(api: OpenCodeClient) { - return { - ...api, - message: { - ...api.message, - list: (input: MessageListInput, options?: ServerRequestOptions) => - api.message.list(input, mediaRefOptions(options)), - }, - session: { - ...api.session, - message: { - ...api.session.message, - get: (input: SessionMessageGetInput, options?: ServerRequestOptions) => - api.session.message.get(input, mediaRefOptions(options)), - }, - inbox: { - ...api.session.inbox, - list: (input: SessionInboxListInput, options?: ServerRequestOptions) => - api.session.inbox.list(input, mediaRefOptions(options)), - }, - }, - } -} - -function mediaRefOptions(options: ServerRequestOptions | undefined): OpenCode.RequestOptions | undefined { - if (options?.mediaRefs === false) return options - const headers = new Headers(options?.headers) - headers.set(CAPABILITIES_HEADER, MEDIA_URI_CAPABILITY) - - return { ...options, headers } -} - /** * The server's ranged read of one file, for media elements. They cannot send the Authorization header, and a credential * never goes in a DOM URL, so a server that needs a password has none: its media downloads through the API instead. diff --git a/packages/app/src/runtime/server/current.tsx b/packages/app/src/runtime/server/current.tsx index 93a9ca805463..18c254b9e28d 100644 --- a/packages/app/src/runtime/server/current.tsx +++ b/packages/app/src/runtime/server/current.tsx @@ -14,7 +14,9 @@ const context = createSimpleContext({ return { conn, key, - isLocal: ServerConnection.local(props.conn), + get isLocal() { + return props.ctx.isLocal + }, ctx: props.ctx, get health() { return global.servers.health[key] diff --git a/packages/app/src/runtime/server/data.test.ts b/packages/app/src/runtime/server/data.test.ts index 48e6a47a8e57..47b8d07998dd 100644 --- a/packages/app/src/runtime/server/data.test.ts +++ b/packages/app/src/runtime/server/data.test.ts @@ -2,7 +2,14 @@ import { expect, test } from "bun:test" import type { SessionInfo } from "@opencode/client/promise" import { createSessionMutations } from "./data" -const session = { id: "ses_test" } as SessionInfo +const session: SessionInfo = { + id: "ses_test", + projectID: "project", + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 0, updated: 0 }, + location: { directory: "/project" }, +} test("keeps a removed session hidden after its deletion event, for lists cached before it", async () => { const release = Promise.withResolvers() @@ -38,3 +45,12 @@ test("rolls back a failed removal", async () => { await expect(request).rejects.toThrow("offline") expect(mutation.apply([session])).toEqual([session]) }) + +test("treats SessionNotFoundError on removal as already deleted", async () => { + const mutation = createSessionMutations(async () => { + throw JSON.parse('{"_tag":"SessionNotFoundError","sessionID":"ses_test","message":"Session not found: ses_test"}') + }) + + await expect(mutation.remove(session.id)).resolves.toBeUndefined() + expect(mutation.apply([session])).toEqual([]) +}) diff --git a/packages/app/src/runtime/server/data.ts b/packages/app/src/runtime/server/data.ts index 5c9739a9eb37..e7a62be24bd5 100644 --- a/packages/app/src/runtime/server/data.ts +++ b/packages/app/src/runtime/server/data.ts @@ -1,11 +1,13 @@ import type { Data } from "@opencode/client/solid" -import type { OpenCodeEvent, SessionInfo } from "@opencode/client/promise" +import { isSessionNotFoundError, type OpenCodeEvent, type SessionInfo } from "@opencode/client/promise" import { onCleanup } from "solid-js" import { createStore } from "solid-js/store" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" type SessionMutation = { readonly id: string; readonly type: "remove"; readonly sessionID: string } +const REMOVED_SESSION_LIMIT = 512 + // The events on which the server advances a session's `time.updated` to the event's time. const SESSION_ACTIVITY = [ "session.inbox.enqueued", @@ -27,8 +29,13 @@ const SESSION_ACTIVITY = [ export function createDesktopData(input: { data: Data; remove: (sessionID: string) => Promise }) { const mutation = createSessionMutations(input.remove) - const [activity, setActivity] = createStore>({}) - onCleanup(input.data.on("session.deleted", (event) => mutation.deleted(event.data.sessionID))) + const [activity, setActivity] = createStore>({}) + onCleanup( + input.data.on("session.deleted", (event) => { + setActivity(event.data.sessionID, undefined) + mutation.deleted(event.data.sessionID) + }), + ) // Lists loaded earlier (the Home index, the live store, search results) learn each session's newer // `time.updated` from its events, so they rank sessions in the server's order without reloading. @@ -53,7 +60,11 @@ export function createDesktopData(input: { data: Data; remove: (sessionID: strin ...input.data.session, list: () => apply(input.data.session.list()), apply, - remove: mutation.remove, + remove: (sessionID: string) => + mutation.remove(sessionID).then(() => { + setActivity(sessionID, undefined) + input.data.session.forget(sessionID) + }), }, } } @@ -65,6 +76,9 @@ export function createSessionMutations(remove: (sessionID: string) => Promise current.filter((mutation) => mutation.id !== id)) } + const append = (current: readonly SessionMutation[], next: SessionMutation) => + [...current.filter((mutation) => mutation.sessionID !== next.sessionID), next].slice(-REMOVED_SESSION_LIMIT) + return { apply(sessions: readonly SessionInfo[]) { const removed = new Set( @@ -75,21 +89,20 @@ export function createSessionMutations(remove: (sessionID: string) => Promise [...current, mutation]) + setStore("session", (current) => append(current, mutation)) return Promise.resolve() .then(() => remove(sessionID)) .catch((error) => { + if (isSessionNotFoundError(error)) return + clear(mutation.id) throw error }) }, // Keep the deleted session hidden: cached lists such as the Home index still hold it until they refetch. deleted(sessionID: string) { - setStore("session", (current) => [ - ...current.filter((mutation) => mutation.sessionID !== sessionID), - { id: uuid(), type: "remove", sessionID }, - ]) + setStore("session", (current) => append(current, { id: uuid(), type: "remove", sessionID })) }, } } diff --git a/packages/app/src/runtime/server/global-sync/utils.test.ts b/packages/app/src/runtime/server/global-sync/utils.test.ts index 2a39fce84f0c..7849a3de9608 100644 --- a/packages/app/src/runtime/server/global-sync/utils.test.ts +++ b/packages/app/src/runtime/server/global-sync/utils.test.ts @@ -4,7 +4,7 @@ import { directoryKey, normalizeAgentList, normalizeProjectInfo, normalizeProvid describe("normalizeAgentList", () => { test("adapts current agents to the app agent shape", () => { - const result = normalizeAgentList([ + const agents: AgentListOutput["data"] = [ { id: "build", name: "Build", @@ -16,7 +16,9 @@ describe("normalizeAgentList", () => { system: "Build software", permissions: [{ action: "read", resource: "*", effect: "allow" }], }, - ] as AgentListOutput["data"]) + ] + + const result = normalizeAgentList(agents) expect(result).toEqual([ { @@ -39,38 +41,44 @@ describe("normalizeAgentList", () => { }) describe("normalizeProviderList", () => { - test("groups current models into the app provider catalog", () => { - const result = normalizeProviderList( - [{ id: "openai", name: "OpenAI", package: "@ai-sdk/openai" }] as ProviderListOutput["data"], - [ - { - id: "gpt-5", - modelID: "gpt-5", - providerID: "openai", - name: "GPT-5", - capabilities: { tools: true, input: ["text", "image"], output: ["text"] }, - variants: [{ id: "high" }], - time: { released: 1 }, - cost: [{ input: 1, output: 2, cache: { read: 0.1, write: 0.2 } }], - status: "active", - enabled: true, - limit: { context: 128_000, output: 8_192 }, - }, - { - id: "gpt-old", - modelID: "gpt-old", - providerID: "openai", - name: "GPT Old", - capabilities: { tools: false, input: ["text"], output: ["text"] }, - variants: [], - time: { released: 0 }, - cost: [], - status: "deprecated", - enabled: true, - limit: { context: 1, output: 1 }, - }, - ] as ModelListOutput["data"], - ) + test.each([ + [0, ""], + [Date.UTC(2026, 8, 1), "2026-09-01"], + ])("groups models with release time %p into the app catalog", (released, release_date) => { + const providers: ProviderListOutput["data"] = [ + { id: "openai", name: "OpenAI", activation: "auto", package: "@ai-sdk/openai" }, + ] + + const models: ModelListOutput["data"] = [ + { + id: "gpt-5", + modelID: "gpt-5", + providerID: "openai", + name: "GPT-5", + capabilities: { tools: true, input: ["text", "image"], output: ["text"] }, + variants: [{ id: "high" }], + time: { released }, + cost: [{ input: 1, output: 2, cache: { read: 0.1, write: 0.2 } }], + status: "active", + enabled: true, + limit: { context: 128_000, output: 8_192 }, + }, + { + id: "gpt-old", + modelID: "gpt-old", + providerID: "openai", + name: "GPT Old", + capabilities: { tools: false, input: ["text"], output: ["text"] }, + variants: [], + time: { released: 0 }, + cost: [], + status: "deprecated", + enabled: true, + limit: { context: 1, output: 1 }, + }, + ] + + const result = normalizeProviderList(providers, models) expect(result.connected).toEqual(["openai"]) expect(result.default).toEqual({ openai: "gpt-5" }) @@ -78,19 +86,59 @@ describe("normalizeProviderList", () => { expect(result.all.get("openai")?.models["gpt-5"]).toMatchObject({ id: "gpt-5", providerID: "openai", - capabilities: { toolcall: true, attachment: true }, + release_date, + capabilities: { toolcall: true, attachment: true, reasoning: true }, cost: { input: 1, output: 2 }, variants: { high: {} }, }) }) + + test.each([ + ["effort variant", [{ id: "low" }], undefined, true], + ["toggle variant", [{ id: "none" }, { id: "thinking" }], undefined, true], + ["reasoningField without variants", [], { reasoningField: "reasoning_content" }, true], + ["no variants or reasoningField", [], undefined, false], + ["disabled-only none variant", [{ id: "none" }], undefined, false], + ] as const)("derives reasoning capability from %s", (_, variants, compatibility, expected) => { + const providers: ProviderListOutput["data"] = [ + { id: "opencode", name: "OpenCode", activation: "auto", package: "@opencode/ai/providers/openai-compatible" }, + ] + + const models: ModelListOutput["data"] = [ + { + id: "model", + modelID: "model", + providerID: "opencode", + name: "Model", + compatibility, + capabilities: { tools: true, input: ["text"], output: ["text"] }, + variants: [...variants], + time: { released: 1 }, + cost: [], + status: "active", + enabled: true, + limit: { context: 128_000, output: 8_192 }, + }, + ] + + const result = normalizeProviderList(providers, models) + + expect(result.all.get("opencode")?.models.model?.capabilities.reasoning).toBe(expected) + }) }) describe("normalizeProjectInfo", () => { test("keeps the project VCS backend", () => { - const project = { id: "prj", canonical: "/repo", time: { created: 1, updated: 1, active: 1 }, sandboxes: [] } - expect(normalizeProjectInfo({ ...project, vcs: "git" } as Project).vcs).toBe("git") - expect(normalizeProjectInfo({ ...project, vcs: "hg" } as Project).vcs).toBe("hg") - expect(normalizeProjectInfo(project as Project).vcs).toBeUndefined() + const project: Project = { + id: "prj", + canonical: "/repo", + time: { created: 1, updated: 1, active: 1 }, + sandboxes: [], + } + + expect(normalizeProjectInfo({ ...project, vcs: "git" }).vcs).toBe("git") + expect(normalizeProjectInfo({ ...project, vcs: "hg" }).vcs).toBe("hg") + expect(normalizeProjectInfo(project).vcs).toBeUndefined() }) }) diff --git a/packages/app/src/runtime/server/global-sync/utils.ts b/packages/app/src/runtime/server/global-sync/utils.ts index af36458c609d..b6ad6d66a2cf 100644 --- a/packages/app/src/runtime/server/global-sync/utils.ts +++ b/packages/app/src/runtime/server/global-sync/utils.ts @@ -10,17 +10,22 @@ const providerCatalogs = new WeakMap< WeakMap >() +function isLegacyAgentList(input: AgentListOutput["data"] | Agent[]): input is Agent[] { + return input.every((agent) => !("request" in agent)) +} + export function normalizeAgentList(input: AgentListOutput["data"] | Agent[]): Agent[] { - if (input.every((agent) => !("request" in agent))) return input as Agent[] + if (isLegacyAgentList(input)) return input - return (input as AgentListOutput["data"]).map((agent) => ({ + return input.map((agent) => ({ name: agent.id, description: agent.description, mode: agent.mode, hidden: agent.hidden, - temperature: - typeof agent.request.settings.temperature === "number" ? agent.request.settings.temperature : undefined, - topP: typeof agent.request.settings.topP === "number" ? agent.request.settings.topP : undefined, + temperature: Number.isFinite(agent.request.settings.temperature) + ? Number(agent.request.settings.temperature) + : undefined, + topP: Number.isFinite(agent.request.settings.topP) ? Number(agent.request.settings.topP) : undefined, color: agent.color, permission: agent.permissions.map((rule) => ({ permission: rule.action, @@ -79,7 +84,11 @@ export function normalizeProviderList( family: model.family, capabilities: { temperature: false, - reasoning: false, + // Always-on reasoning models may expose no selectable variants yet still stream reasoning via reasoningField; + // a disabled-only `none` variant does not count as reasoning support. + reasoning: + model.compatibility?.reasoningField !== undefined || + model.variants.some((variant) => variant.id !== "none"), attachment: model.capabilities.input.some((item) => item !== "text"), toolcall: model.capabilities.tools, input: { @@ -110,7 +119,7 @@ export function normalizeProviderList( status: model.status, options: model.settings ?? {}, headers: model.headers ?? {}, - release_date: new Date(model.time.released).toISOString().slice(0, 10), + release_date: model.time.released === 0 ? "" : new Date(model.time.released).toISOString().slice(0, 10), variants: Object.fromEntries(model.variants.map((variant) => [variant.id, variant.settings ?? {}])), } } diff --git a/packages/app/src/runtime/server/media.ts b/packages/app/src/runtime/server/media.ts index 7dddc1de67fd..e654003fa3fd 100644 --- a/packages/app/src/runtime/server/media.ts +++ b/packages/app/src/runtime/server/media.ts @@ -1,13 +1,6 @@ -import type { OpenCodeClient } from "@opencode/client/promise" +import { mediaHashFromUri, type OpenCodeClient } from "@opencode/client/promise" -const MEDIA_REF = /^media:([0-9a-f]{64})$/ - -/** The blob hash in a `media:` ref, the only form the server sends stored media in. */ -export function mediaHashFromUri(uri: string | undefined): string | undefined { - if (!uri) return undefined - - return MEDIA_REF.exec(uri)?.[1] -} +export { mediaHashFromUri } export type MediaCache = { peek(uri: string, mime?: string): string | undefined diff --git a/packages/app/src/runtime/server/registry.test.ts b/packages/app/src/runtime/server/registry.test.ts index 5f42989b7268..00d11271dc86 100644 --- a/packages/app/src/runtime/server/registry.test.ts +++ b/packages/app/src/runtime/server/registry.test.ts @@ -1,5 +1,12 @@ import { expect, test } from "bun:test" -import { canRemoveServer, createServerProjects, resolveServerList, ServerConnection, serverLabel } from "./registry" +import { + canRemoveServer, + createServerProjects, + resolveServerList, + resolveVisibleServers, + ServerConnection, + serverLabel, +} from "./registry" import { Schema } from "effect" import { ServerState } from "./persistence" import { createStore } from "solid-js/store" @@ -52,24 +59,36 @@ test("startup auth_token credentials override a persisted same-url server; witho expect(kept[0]?.type === "http" ? kept[0].authToken : true).toBeUndefined() }) -test("treats WSL sidecars as remote server connections", () => { +test("treats WSL and mismatched-port loopback servers as remote connections", () => { + const windowsSidecar = "http://127.0.0.1:28894" + expect( - ServerConnection.local({ - type: "plugin", - key: "wsl:Debian", - plugin: "wsl", - state: "ready", - connecting: false, - authenticationRequired: false, - managed: false, - http: { url: "http://127.0.0.1:4097" }, - }), + ServerConnection.local( + { + type: "plugin", + key: "wsl:Debian", + plugin: "wsl", + state: "ready", + connecting: false, + authenticationRequired: false, + managed: false, + http: { url: "http://127.0.0.1:4097" }, + }, + windowsSidecar, + ), ).toBe(false) - expect(ServerConnection.local({ type: "sidecar", variant: "base", http: { url: "http://127.0.0.1:4096" } })).toBe( - true, + expect( + ServerConnection.local({ type: "sidecar", variant: "base", http: { url: windowsSidecar } }), + ).toBe(true) + expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:28894" } }, windowsSidecar)).toBe(true) + expect(ServerConnection.local({ type: "http", http: { url: "http://[::1]:28894" } }, windowsSidecar)).toBe(true) + expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:4096" } }, windowsSidecar)).toBe(false) + expect(ServerConnection.local({ type: "http", http: { url: "http://127.0.0.1:4096" } }, windowsSidecar)).toBe(false) + expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:49374" } }, windowsSidecar)).toBe(false) + expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:4096" } })).toBe(false) + expect(ServerConnection.local({ type: "http", http: { url: "https://server.example.test" } }, windowsSidecar)).toBe( + false, ) - expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:4096" } })).toBe(true) - expect(ServerConnection.local({ type: "http", http: { url: "https://server.example.test" } })).toBe(false) }) test("keeps exact persisted server identities and prevents removing provided servers", () => { @@ -87,6 +106,21 @@ test("keeps exact persisted server identities and prevents removing provided ser expect(canRemoveServer({ key, stored, provided: [{ type: "http", http: { url: key } }] })).toBe(false) }) +test("hidden servers are left out, but never every server: the built-in one, otherwise the first, stays shown", () => { + const sidecar: ServerConnection.Sidecar = { type: "sidecar", variant: "base", http: { url: "http://127.0.0.1:4096" } } + const remote: ServerConnection.Http = { type: "http", http: { url: "https://apollo.example.test" } } + const other: ServerConnection.Http = { type: "http", http: { url: "https://zeus.example.test" } } + + const hide = (...servers: ServerConnection.Any[]) => + Object.fromEntries(servers.map((server) => [ServerConnection.key(server), true])) + + expect(resolveVisibleServers({ servers: [sidecar, remote], hidden: {} })).toEqual([sidecar, remote]) + expect(resolveVisibleServers({ servers: [sidecar, remote], hidden: hide(sidecar) })).toEqual([remote]) + expect(resolveVisibleServers({ servers: [remote, sidecar], hidden: hide(remote, sidecar) })).toEqual([sidecar]) + expect(resolveVisibleServers({ servers: [remote, other], hidden: hide(remote, other) })).toEqual([remote]) + expect(resolveVisibleServers({ servers: [], hidden: hide(remote) })).toEqual([]) +}) + /** The server props a project store follows, which the test changes. */ type ProjectScopeProps = { server: ServerConnection.Key; canonicalLocalServer?: ServerConnection.Key } diff --git a/packages/app/src/runtime/server/registry.tsx b/packages/app/src/runtime/server/registry.tsx index 8bbd24e45d49..1255b36a9d0e 100644 --- a/packages/app/src/runtime/server/registry.tsx +++ b/packages/app/src/runtime/server/registry.tsx @@ -38,10 +38,13 @@ export function serverLabel(conn: ServerConnection.Any, current?: { hostname?: s return serverName(conn) } -function isLocalHost(url: string) { - const host = url.replace(/^https?:\/\//, "").split(":")[0] +function loopbackOrigin(url: string) { + if (!URL.canParse(url)) return + const parsed = new URL(url) - if (host === "localhost" || host === "127.0.0.1") return "local" + if (parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1" && parsed.hostname !== "[::1]") return + + return `${parsed.protocol}//127.0.0.1:${parsed.port || (parsed.protocol === "https:" ? "443" : "80")}` } // Project data comes from the server; this keeps which projects this client has used and the last one. @@ -130,6 +133,21 @@ export function canRemoveServer(input: { return input.stored.some((server) => server.http.url === input.key) } +/** + * The servers Home lists. Home needs at least one, so when every server is flagged hidden (stored by an older + * build, or edited by hand) the built-in server, otherwise the first, is shown anyway. + */ +export function resolveVisibleServers(input: { + servers: Array + hidden: StoredState["hidden"] +}): Array { + const visible = input.servers.filter((conn) => !input.hidden[ServerConnection.key(conn)]) + + if (visible.length > 0 || input.servers.length === 0) return visible + + return [input.servers.find(ServerConnection.builtin) ?? input.servers[0]] +} + export namespace ServerConnection { type Base = { displayName?: string; label?: string } @@ -192,8 +210,18 @@ export namespace ServerConnection { return true } - export const local = (conn?: Any) => - !!conn && (builtin(conn) || (conn.type === "http" && isLocalHost(conn.http.url) === "local")) + // The desktop sidecar, or a loopback http connection on the same port as the app's own server. Other loopback + // ports may belong to a WSL server, tunnel, or container with a separate filesystem. + export const local = (conn?: Any, ownUrl?: string) => { + if (!conn) return false + + if (builtin(conn)) return true + + if (conn.type !== "http" || !ownUrl) return false + const origin = loopbackOrigin(conn.http.url) + + return !!origin && origin === loopbackOrigin(ownUrl) + } } export const { use: useServers, provider: ServersProvider } = createSimpleContext({ @@ -216,7 +244,16 @@ export const { use: useServers, provider: ServersProvider } = createSimpleContex return resolveServerList({ stored: store.list, props: props.servers }) }) - const visibleServers = createMemo(() => allServers().filter((conn) => !store.hidden[ServerConnection.key(conn)])) + const visibleServers = createMemo(() => resolveVisibleServers({ servers: allServers(), hidden: store.hidden })) + + // Clears the hidden flag of any server shown despite it, so the stored flags say what Home shows. + function unhideShown(servers: Array) { + for (const conn of resolveVisibleServers({ servers, hidden: store.hidden })) { + const key = ServerConnection.key(conn) + + if (store.hidden[key]) setStore("hidden", key, false) + } + } function add(input: ServerConnection.Http) { const url_ = normalizeServerUrl(input.http.url) @@ -241,9 +278,18 @@ export const { use: useServers, provider: ServersProvider } = createSimpleContex const list = store.list.filter((x) => x.http.url !== key) batch(() => { setStore("list", list) + // Removing the only shown server must not leave the rest all hidden. + unhideShown(resolveServerList({ stored: list, props: props.servers })) }) } + function setHidden(key: ServerConnection.Key, hidden: boolean) { + // Home always lists at least one server, so hiding the only shown one does nothing. + if (hidden && visibleServers().every((conn) => ServerConnection.key(conn) === key)) return + + setStore("hidden", key, hidden) + } + function canRemove(key: ServerConnection.Key) { return canRemoveServer({ key, provided: props.servers, stored: store.list }) } @@ -265,6 +311,9 @@ export const { use: useServers, provider: ServersProvider } = createSimpleContex const current = (conn: ServerConnection.Any) => ServerConnection.builtin(conn) || ServerConnection.key(conn) === props.canonicalLocalServer + const ownUrl = () => props.servers?.find(ServerConnection.builtin)?.http.url ?? props.canonicalLocalServer + const local = (conn?: ServerConnection.Any) => ServerConnection.local(conn, ownUrl()) + const label = (conn: ServerConnection.Any) => serverLabel( conn, @@ -284,16 +333,16 @@ export const { use: useServers, provider: ServersProvider } = createSimpleContex // state wait on this, but the provider must not block first render on storage. hydrated, isHidden(key: ServerConnection.Key) { - return store.hidden[key] ?? false - }, - setHidden(key: ServerConnection.Key, hidden: boolean) { - setStore("hidden", key, hidden) + return !!store.hidden[key] && !visibleServers().some((conn) => ServerConnection.key(conn) === key) }, + setHidden, add, remove, canRemove, scope, current, + ownUrl, + local, /** The name switchers, menus and titles show. */ label, /** The name a list row shows next to its item: nothing for the current server or when it is the only one. */ diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index 4624a878374b..aab15bff34f6 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -70,7 +70,13 @@ export const { use: useGlobal, provider: GlobalProvider } = createSimpleContext( const serverCtx = createRoot((dispose) => { serverCtxDisposers.set(key, dispose) - return createServerController(conn, server.scope(key), server.projects.forServer(key), notificationCoordinator) + return createServerController( + conn, + server.scope(key), + () => server.local(conn), + server.projects.forServer(key), + notificationCoordinator, + ) }, owner) serverCtxs.set(key, serverCtx) @@ -185,6 +191,7 @@ function createGlobalModels() { function createServerController( conn: ServerConnection.Any, scope: ServerScope, + isLocal: Accessor, projects: ReturnType, notificationCoordinator: ReturnType, ) { @@ -321,14 +328,13 @@ function createServerController( }) } - const isLocal = - (conn?.type === "sidecar" && conn.variant === "base") || (conn?.type === "http" && isLocalHost(conn.http.url)) - return { data, sdk, sync, - isLocal, + get isLocal() { + return isLocal() + }, projects: { list, unique, @@ -367,12 +373,6 @@ export function useServerCtx(server: Accessor) export type ServerCtx = ReturnType -function isLocalHost(url: string) { - const host = url.replace(/^https?:\/\//, "").split(":")[0] - - if (host === "localhost" || host === "127.0.0.1") return "local" -} - /** What an HTTP server's controller authenticates with; other servers keep one controller per id. */ function credentials(conn: ServerConnection.Any) { return conn.type === "http" ? `${conn.http.url}\n${conn.http.password ?? ""}` : "" diff --git a/packages/app/src/session/commands/use-session-commands.tsx b/packages/app/src/session/commands/use-session-commands.tsx index 680cb6d67035..2d953398c3f3 100644 --- a/packages/app/src/session/commands/use-session-commands.tsx +++ b/packages/app/src/session/commands/use-session-commands.tsx @@ -83,8 +83,9 @@ export const useSessionCommands = (actions: SessionCommandContext) => { const inSide = actions.region.focus // ⌘T and ⌘W inside the side region open and close its tabs, unless the focused panel binds the key itself there. const sideKey = (event: KeyboardEvent) => inSide(event) && !pluginClaims(event) - // ⌘W on the side panel's last tab closes the panel and moves focus out of it, where one press too many would close - // the session tab. Until the user moves on, by clicking, focusing, another key, or another session, ⌘W closes nothing. + // ⌘W on the side panel's last tab, or on a panel with nothing left to close, closes the panel and moves focus out of + // it, where one press too many would close the session tab. Until the user moves on, by clicking, focusing, another + // key, or another session, ⌘W closes nothing. // The close moves focus synchronously, before this is set, so its own focusin does not clear it. const [emptied, setEmptied] = createSignal(false) const resetEmptied = () => setEmptied(false) @@ -235,11 +236,23 @@ export const useSessionCommands = (actions: SessionCommandContext) => { return pane === "side" || pane === "split" ? pane : undefined } + // With nothing left to close, ⌘W closes the side panel itself, as an editor closes the focused pane before the window. const closeTab = () => { - if (actions.region.closeNewTab(focusedPane())) return + if (actions.region.closeNewTab(focusedPane())) { + const panel = document.getElementById("review-panel") + + // A launcher row that held focus is gone; focus stays in the panel so closing it next returns focus. Closing the + // strip's last New tab closes the panel too, which already gave focus back. + if (panel && actions.session.layout.view().side.opened() && !panel.contains(document.activeElement)) + panel.focus({ preventScroll: true, focusVisible: false }) + + return + } + const tab = closableTab() - if (tab) actions.region.close(tab) + if (tab) return actions.region.close(tab) + actions.region.toggle() } const openSideTab = () => actions.region.openNewTab(focusedPane()) diff --git a/packages/app/src/session/composer/controller.ts b/packages/app/src/session/composer/controller.ts index 3160b8ee3a20..8b6a460a1238 100644 --- a/packages/app/src/session/composer/controller.ts +++ b/packages/app/src/session/composer/controller.ts @@ -62,8 +62,14 @@ export function createSessionComposerController(input: { if (!editor?.isConnected || !region.showComposer() || region.child() || dialog.active) return const active = document.activeElement - // A control chosen while the session was loading owns focus now. - if (active && active !== document.body && active !== editor && !active.matches("[data-titlebar-tab-link]")) + // A control chosen while the session was loading owns focus now. The tab link that opened the session + // passes focus on, unless it sits in a dialog, such as the mobile tabs drawer reopened before the composer. + if ( + active && + active !== document.body && + active !== editor && + (!active.matches("[data-titlebar-tab-link]") || active.closest('[role="dialog"]')) + ) return editor.focus({ preventScroll: true }) setCursorPosition(editor, adapter.state.cursor() ?? promptLength(adapter.state.current())) diff --git a/packages/app/src/session/composer/queue-panel.tsx b/packages/app/src/session/composer/queue-panel.tsx index 70471efc504d..7ab76db8d2c2 100644 --- a/packages/app/src/session/composer/queue-panel.tsx +++ b/packages/app/src/session/composer/queue-panel.tsx @@ -197,7 +197,7 @@ function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: nu data-component={leaving() ? undefined : "session-queue-row"} data-leaving={leaving() || undefined} aria-busy={leaving() ? undefined : entry().pending} - class="group/queue-row mb-px flex h-8 shrink-0 items-center justify-between gap-2 rounded-md py-1 ps-0.5 pe-2" + class="group/queue-row mb-px flex h-8 shrink-0 items-center justify-between gap-2 rounded-md py-1 ps-0.5 pe-1" classList={{ "bg-v2-overlay-simple-overlay-hover": editing(), "opacity-60": sortable.isDragSource(), @@ -241,7 +241,7 @@ function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: nu
void props.queue.steer(props.id)} > {props.queue.working() ? language.t("session.queue.steer") : language.t("session.queue.send")} @@ -274,7 +274,7 @@ function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: nu } disabled={props.queue.busy()} @@ -288,7 +288,7 @@ function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: nu } disabled={props.queue.busy()} diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index b4ea7cb5e9f5..a9302e32fc14 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -20,7 +20,7 @@ import { showToast } from "@/shell/notifications/toast" import { errorMessage } from "@/shell/layout/helpers" import { useLocal } from "@/providers/models/selection" import { usePlatform } from "@/runtime/platform/platform" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" import { contextItemKey } from "@/composer/schema" import type { QuoteSource } from "@/composer/quote-source" import type { ComposerQuoteAnchor } from "@opencode/plugin/gui" @@ -173,6 +173,24 @@ export function createActiveSessionRegion(input: { const target = path.find((item): item is HTMLElement => item instanceof HTMLElement) const active = activeElement() + // As in chat apps, page keys in the composer page the conversation, even when the draft itself overflows. An open + // suggestion popup has already claimed them, and modified page keys keep their native meaning. + if ( + promptRef && + active === promptRef && + (event.key === "PageUp" || event.key === "PageDown") && + !event.shiftKey && + !event.altKey && + !event.ctrlKey && + !event.metaKey && + !event.isComposing + ) { + event.preventDefault() + input.timeline.actions.page(event.key === "PageUp" ? -1 : 1) + + return + } + if ( path.some((item) => item instanceof HTMLElement && item.closest("[data-prevent-autofocus]") !== null) || editable(target) || diff --git a/packages/app/src/session/header/fit.ts b/packages/app/src/session/header/fit.ts index c14cec878291..e8b9fc0beaa6 100644 --- a/packages/app/src/session/header/fit.ts +++ b/packages/app/src/session/header/fit.ts @@ -1,16 +1,19 @@ import { onCleanup, onMount } from "solid-js" import { createStore } from "solid-js/store" -/** Fits the location names before allowing the session title to truncate. */ +/** Fits the location names, then the actions' details, before allowing the session title to truncate. */ export function createSessionHeaderFit() { - const [store, setStore] = createStore({ collapse: 0 }) + const [store, setStore] = createStore({ collapse: 0, compact: false }) let root!: HTMLDivElement + // Compact actions drop their details, so their last expanded width is what expanding them again takes back. + let expandedActions = 0 onMount(() => { const fit = () => { const location = root.querySelector(".session-header-location") const title = root.querySelector(".session-header-title") const measure = root.querySelector(".session-header-title-measure > span") + const actions = root.querySelector(".session-header-actions") const trigger = root.querySelector('[data-slot="session-location-trigger"]') const project = trigger?.querySelector('[data-slot="session-location-project"]') const worktree = trigger?.querySelector('[data-slot="session-location-worktree"]') @@ -56,16 +59,25 @@ export function createSessionHeaderFit() { Math.max(0, children.length - 1) * Number.parseFloat(getComputedStyle(title).columnGap), ) - // Everything outside these two sections is reserved for actions, separators and their spacing. - const available = location.getBoundingClientRect().width + title.getBoundingClientRect().width - titleWidth - setStore( - "collapse", - Math.min(expanded, limit) <= available - ? 0 - : worktree && Math.min(expanded - worktreeWidth, limit) <= available - ? 1 - : 2, - ) + const actionsWidth = actions?.getBoundingClientRect().width ?? 0 + + if (!store.compact) expandedActions = actionsWidth + + // Everything outside these two sections is reserved for actions, separators and their spacing. Candidates are + // fitted against expanded actions, so compact actions expand again once the title fits beside them. + const available = + location.getBoundingClientRect().width + + title.getBoundingClientRect().width - + titleWidth - + (store.compact ? Math.max(0, expandedActions - actionsWidth) : 0) + + const fits = (width: number) => Math.min(width, limit) <= available + + const collapse = fits(expanded) ? 0 : worktree && fits(expanded - worktreeWidth) ? 1 : 2 + setStore({ + collapse, + compact: !!actions && collapse === 2 && !fits(expanded - worktreeWidth - projectWidth), + }) } const resize = new ResizeObserver(fit) @@ -96,5 +108,9 @@ export function createSessionHeaderFit() { get collapse() { return store.collapse }, + /** The title does not fit even with the location collapsed, so the actions show without their details. */ + get compact() { + return store.compact + }, } } diff --git a/packages/app/src/session/requests/session-question-dock-classic.tsx b/packages/app/src/session/requests/session-question-dock-classic.tsx index 5d5dedb05906..4d90c980c5e3 100644 --- a/packages/app/src/session/requests/session-question-dock-classic.tsx +++ b/packages/app/src/session/requests/session-question-dock-classic.tsx @@ -47,22 +47,57 @@ function Option(props: { description?: string number: number disabled: boolean - ref?: (el: HTMLButtonElement) => void + ref?: (el: HTMLDivElement) => void onFocus?: VoidFunction onClick: VoidFunction }) { + let pointer: { x: number; y: number } | undefined + return ( - +
) } @@ -126,7 +161,7 @@ export const SessionQuestionDockClassic: Component<{ request: FormInfo; onSubmit let optionsRef: HTMLDivElement | undefined let customRef: HTMLButtonElement | undefined let customInput: HTMLInputElement | undefined - let optsRef: HTMLButtonElement[] = [] + let optsRef: HTMLDivElement[] = [] let replied = false let focusFrame: number | undefined diff --git a/packages/app/src/session/requests/session-question-dock-experimental.tsx b/packages/app/src/session/requests/session-question-dock-experimental.tsx index 42add84d42e4..7949c6873a92 100644 --- a/packages/app/src/session/requests/session-question-dock-experimental.tsx +++ b/packages/app/src/session/requests/session-question-dock-experimental.tsx @@ -194,23 +194,47 @@ function Option(props: { shortcut?: string disabled: boolean tabbable: boolean - ref?: (el: HTMLButtonElement) => void + ref?: (el: HTMLDivElement) => void onFocus?: VoidFunction onClick: VoidFunction }) { + let pointer: { x: number; y: number } | undefined + return ( - +
) } @@ -270,7 +294,7 @@ export const SessionQuestionDockExperimental: Component<{ request: FormInfo; onS let customRow: HTMLDivElement | undefined let highlightRef: HTMLSpanElement | undefined let customInput: HTMLInputElement | undefined - let optsRef: HTMLButtonElement[] = [] + let optsRef: HTMLDivElement[] = [] let replied = false const question = createMemo(() => questions()[store.tab]) diff --git a/packages/app/src/session/screen.tsx b/packages/app/src/session/screen.tsx index d21d60f4f873..f32fb2421f2b 100644 --- a/packages/app/src/session/screen.tsx +++ b/packages/app/src/session/screen.tsx @@ -314,7 +314,7 @@ function SessionScreenContent(props: { pinned={timeline.view.pinned()} centered={screen.centered()} reserveReviewToggle={!sideVisible()} - setContentRef={timeline.view.setContentRef} + onContentResize={timeline.view.contentResized} bottomInset={timeline.inset()} setVisibleRef={timeline.view.setVisibleRef} anchor={timeline.view.anchor} @@ -322,6 +322,7 @@ function SessionScreenContent(props: { setRevealPart={timeline.view.setRevealPart} reveal={timeline.view.reveal} setScrollToEnd={timeline.view.setScrollToEnd} + setPage={timeline.view.setPage} search={ diff --git a/packages/app/src/session/session-identity-header.tsx b/packages/app/src/session/session-identity-header.tsx index 13395c0fadea..5077b936be69 100644 --- a/packages/app/src/session/session-identity-header.tsx +++ b/packages/app/src/session/session-identity-header.tsx @@ -67,7 +67,12 @@ export function SessionTitleHeader(props: ParentProps) { } export function SessionHeaderLayout( - props: ParentProps<{ title: string | undefined; location: JSX.Element; actions?: JSX.Element }>, + props: ParentProps<{ + title: string | undefined + location: JSX.Element + /** Receives the fit: `compact` while the title needs the room the actions' details take. */ + actions?: (fit: { readonly compact: boolean }) => JSX.Element + }>, ) { const fit = createSessionHeaderFit() @@ -81,8 +86,7 @@ export function SessionHeaderLayout( {props.children}
- {/* Each read of a JSX prop renders it again, so the actions render once, from the condition's value. */} - {(actions) =>
{actions()}
}
+ {(actions) =>
{actions()(fit)}
}
) diff --git a/packages/app/src/session/session-panel-width.test.ts b/packages/app/src/session/session-panel-width.test.ts index 7510e426258e..938a9064651b 100644 --- a/packages/app/src/session/session-panel-width.test.ts +++ b/packages/app/src/session/session-panel-width.test.ts @@ -11,8 +11,9 @@ test.each([ ["never drops below the chat panel minimum on small windows", 1600, 0, false, false, 450], ["skips clamping before the layout is measured", 1600, undefined, false, false, 1600], ["lets a dragged width leave the side pane its hard minimum, split diffs included", 1600, 1700, true, true, 1380], - ["keeps a dragged width below the default minimum", 320, 700, true, true, 320], - ["never drops a dragged width below the hard chat minimum", 1600, 0, false, true, 320], + ["keeps a dragged width below the default minimum", 420, 900, true, true, 420], + ["never drops a dragged width below the hard chat minimum", 1600, 0, false, true, 400], + ["raises a width dragged below the hard chat minimum before it rose", 320, 1700, false, true, 400], ])("%s", (_name, width, available, split, resized, expected) => { expect(clampSessionPanelWidth({ width, available, split, resized })).toBe(expected) }) diff --git a/packages/app/src/session/session-panel-width.ts b/packages/app/src/session/session-panel-width.ts index 9afe75e9994f..e4c5f3c0ec48 100644 --- a/packages/app/src/session/session-panel-width.ts +++ b/packages/app/src/session/session-panel-width.ts @@ -4,8 +4,9 @@ // minimum for the review pane and let the chat panel take everything else. // Until the user drags the divider, the default width keeps roomier minimums // (wider still for split diffs); a drag can take either side down to the hard -// minimum. -export const SESSION_PANEL_WIDTH_MIN = 320 +// minimum. The chat minimum leaves the session header room for its title beside +// its controls, macOS traffic lights included. +export const SESSION_PANEL_WIDTH_MIN = 400 const SIDE_PANE_WIDTH_MIN = 320 @@ -28,7 +29,8 @@ export function sessionPanelWidthCss(input: { width: number; split: boolean; res const minimum = input.resized ? SESSION_PANEL_WIDTH_MIN : SESSION_PANEL_WIDTH_FIT const pane = input.resized ? SIDE_PANE_WIDTH_MIN : input.split ? REVIEW_PANE_WIDTH_FIT_SPLIT : REVIEW_PANE_WIDTH_FIT - return `min(${input.width}px, max(${minimum}px, 100% - ${pane + 8}px))` + // The outer floor raises a width stored below the minimum, e.g. dragged before it rose. + return `max(${SESSION_PANEL_WIDTH_MIN}px, min(${input.width}px, max(${minimum}px, 100% - ${pane + 8}px)))` } // `available` is undefined until the layout row is first measured; render the @@ -39,7 +41,9 @@ export function clampSessionPanelWidth(input: { split: boolean resized: boolean }) { - if (input.available === undefined) return input.width + const width = Math.max(SESSION_PANEL_WIDTH_MIN, input.width) - return Math.min(input.width, sessionPanelWidthMax({ ...input, available: input.available })) + if (input.available === undefined) return width + + return Math.min(width, sessionPanelWidthMax({ ...input, available: input.available })) } diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts index ecda24665300..d1c5d928d5f7 100644 --- a/packages/app/src/session/timeline/interaction.ts +++ b/packages/app/src/session/timeline/interaction.ts @@ -23,7 +23,6 @@ export function createSessionTimelineInteraction(session: SessionModel) { inset: number refs: { scroller: HTMLDivElement | undefined - content: HTMLDivElement | undefined dock: HTMLDivElement | undefined visible: HTMLDivElement | undefined } @@ -41,7 +40,6 @@ export function createSessionTimelineInteraction(session: SessionModel) { inset: 0, refs: { scroller: undefined, - content: undefined, dock: undefined, visible: undefined, }, @@ -68,6 +66,8 @@ export function createSessionTimelineInteraction(session: SessionModel) { let scrollToEnd = (_behavior?: ScrollBehavior) => {} + let page = (_direction: 1 | -1) => {} + let scrollMark = 0 let messageMark = 0 let scrollStateFrame: (() => void) | undefined @@ -359,13 +359,6 @@ export function createSessionTimelineInteraction(session: SessionModel) { { defer: true }, ), ) - createResizeObserver( - () => state.refs.content, - () => { - if (scroller) scheduleScrollState(scroller) - fill() - }, - ) createResizeObserver( () => state.refs.dock, (_rect, _element, entry) => { @@ -402,6 +395,7 @@ export function createSessionTimelineInteraction(session: SessionModel) { return { actions: { navigateMessage, + page: (direction: 1 | -1) => page(direction), revealMessage: (id: string, partID?: string) => revealMessage(id, partID), revealPart: (target: string) => revealPart(target), resume, @@ -423,10 +417,9 @@ export function createSessionTimelineInteraction(session: SessionModel) { pinned, selectionInteraction, scheduleScrollState, - setContentRef: (element: HTMLDivElement | undefined) => { - setState("refs", "content", element) - + contentResized: () => { if (scroller) scheduleScrollState(scroller) + fill() }, setDockRef: (element: HTMLDivElement | undefined) => { setState("refs", "dock", element) @@ -451,6 +444,9 @@ export function createSessionTimelineInteraction(session: SessionModel) { setScrollToEnd: (scroll: (behavior?: ScrollBehavior) => void) => { scrollToEnd = scroll }, + setPage: (scroll: (direction: 1 | -1) => void) => { + page = scroll + }, unpin, }, } diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index 71e0dc311a73..122e28620a44 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -91,13 +91,14 @@ type MessageTimelineProps = { pinned: boolean centered: boolean reserveReviewToggle: boolean - setContentRef: (el: HTMLDivElement) => void + onContentResize: () => void bottomInset?: number setVisibleRef?: (el: HTMLDivElement | undefined) => void anchor: (id: string) => string setRevealMessage?: (fn: (id: string, partID?: string) => void) => void setRevealPart?: (fn: (target: string) => boolean) => void setScrollToEnd?: (fn: (behavior?: ScrollBehavior) => void) => void + setPage?: (fn: (direction: 1 | -1) => void) => void reveal?: { target: () => string | undefined; done: () => void } search?: JSX.Element } @@ -192,7 +193,7 @@ function MessageTimelineView( scroll: () => props.scroll, onResumeScroll: props.onResumeScroll, setScrollRef: props.setScrollRef, - setContentRef: props.setContentRef, + onContentResize: props.onContentResize, bottomInset: () => props.bottomInset ?? 0, setVisibleRef: props.setVisibleRef, onScheduleScrollState: props.onScheduleScrollState, @@ -252,6 +253,7 @@ function MessageTimelineView( setRevealMessage: props.setRevealMessage, setRevealPart: props.setRevealPart, setScrollToEnd: props.setScrollToEnd, + setPage: props.setPage, reveal: props.reveal, }) @@ -546,7 +548,7 @@ function MessageTimelineView( } - actions={ + actions={(fit) => ( {(_id) => ( <> @@ -563,13 +565,16 @@ function MessageTimelineView( get active() { return props.active !== false }, + get compact() { + return fit.compact + }, }} /> )} - } + )} > {(value) => ( diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx index 4574b78a1f76..201caf3fe4cf 100644 --- a/packages/app/src/session/timeline/virtualizer.tsx +++ b/packages/app/src/session/timeline/virtualizer.tsx @@ -75,7 +75,8 @@ type Input = { scroll: Accessor<{ overflow: boolean; jump: boolean }> onResumeScroll: (behavior?: ScrollBehavior) => void setScrollRef: (element: HTMLDivElement | undefined) => void - setContentRef: (element: HTMLDivElement) => void + /** The rows' content changed height. */ + onContentResize: () => void /** Height of the composer region floating over the timeline's bottom edge, where the timeline fades out. */ bottomInset?: Accessor setVisibleRef?: (element: HTMLDivElement | undefined) => void @@ -92,6 +93,8 @@ type Input = { setRevealMessage?: (fn: (id: string, partID?: string) => void) => void setRevealPart?: (fn: (target: string) => boolean) => void setScrollToEnd?: (fn: (behavior?: ScrollBehavior) => void) => void + /** Pages the timeline for keys pressed outside it, such as PageUp in the composer. */ + setPage?: (fn: (direction: 1 | -1) => void) => void /** A tool call the route asks this timeline to open on; `done` clears it once revealed. */ reveal?: { target: () => string | undefined; done: () => void } } @@ -552,8 +555,6 @@ export function createTimelineVirtualizer(input: Input) { const root = listRoot() if (root) input.setScrollRef(root) - - if (virtualContent) input.setContentRef(virtualContent) input.setVisibleRef?.(visibleArea()) queueMicrotask(() => { if (!active() || !root?.isConnected) return @@ -602,6 +603,18 @@ export function createTimelineVirtualizer(input: Input) { virtualizer.scrollToOffset(Math.max(root.scrollTop, root.scrollHeight - root.clientHeight * 2)) virtualizer.scrollToEnd({ behavior }) }) + input.setPage?.((direction) => { + const root = listRoot() + + if (!active() || !root?.isConnected) return + prepareNavigation() + input.onUserScroll(root) + + if (direction < 0) input.onUnpin() + // Like the timeline's own PageUp: 80% of a page, measured above the composer that covers its bottom. The scroll + // event then pins at the end or loads older history near the top, as a wheel scroll does. + virtualizer.scrollToOffset(root.scrollTop + direction * (visibleArea()?.clientHeight || root.clientHeight) * 0.8) + }) }) createEffect( @@ -616,6 +629,15 @@ export function createTimelineVirtualizer(input: Input) { ), ) + // The content is as tall as the rows the virtualizer sizes, so it reports that height rather than the session + // observing the element. A ResizeObserver there sees the height a row's own observer commits during its delivery, and + // Chrome reports every such frame as "ResizeObserver loop completed with undelivered notifications." + createEffect( + on([active, () => virtualizer.getTotalSize() - rendering.scrollAdjustment], () => { + if (active()) input.onContentResize() + }), + ) + // Only the viewport carries the inset as a variable, for its fade and scroll padding. The variable does not inherit // (see index.css): the inset changes on every frame while the composer region grows, and an inherited variable would // restyle every rendered row each time. @@ -1016,11 +1038,7 @@ export function createTimelineVirtualizer(input: Input) {
{ - virtualContent = element - - if (active()) input.setContentRef(element) - }} + ref={virtualContent} style={{ height: `${virtualizer.getTotalSize() - rendering.scrollAdjustment}px`, position: "relative", @@ -1082,6 +1100,7 @@ export function createTimelineVirtualizer(input: Input) { input.setRevealMessage?.(() => {}) input.setRevealPart?.(() => false) input.setScrollToEnd?.(() => {}) + input.setPage?.(() => {}) } }) diff --git a/packages/app/src/settings/about/about.tsx b/packages/app/src/settings/about/about.tsx index 01ce931d7640..65b05282de9b 100644 --- a/packages/app/src/settings/about/about.tsx +++ b/packages/app/src/settings/about/about.tsx @@ -1,5 +1,7 @@ -import { createResource } from "solid-js" +import { createEffect, createResource, onCleanup } from "solid-js" +import { createStore } from "solid-js/store" import { useDialog } from "@opencode/ui/context/dialog" +import { Tooltip } from "@opencode/ui/tooltip" import { useLanguage } from "@/runtime/i18n/language" import { usePlatform } from "@/runtime/platform/platform" import { ExternalLink } from "@/runtime/platform/external-link" @@ -34,6 +36,9 @@ export function SettingsAbout(props: { active: boolean }) { const language = useLanguage() const platform = usePlatform() const dialog = useDialog() + const [copy, setCopy] = createStore({ pending: false, copied: false, forceCopied: false }) + const version = () => platform.version ?? language.t("settings.about.devVersion") + const versionLabel = () => language.t("settings.about.version", { version: version() }) const [otherContributors] = createResource( () => props.active || undefined, @@ -41,6 +46,34 @@ export function SettingsAbout(props: { active: boolean }) { { initialValue: FALLBACK_OTHER_CONTRIBUTORS }, ) + createEffect(() => { + if (!copy.copied) return + + const close = setTimeout(() => setCopy("forceCopied", false), 2000) + const reset = setTimeout(() => setCopy("copied", false), 2120) + + onCleanup(() => { + clearTimeout(close) + clearTimeout(reset) + }) + }) + + const copyVersion = async () => { + if (copy.pending) return + + setCopy({ pending: true, copied: false, forceCopied: false }) + + await (platform.writeClipboardText?.(versionLabel()) ?? navigator.clipboard.writeText(versionLabel())) + .then(() => setCopy({ copied: true, forceCopied: true })) + .catch(() => + showToast({ + variant: "error", + title: language.t("settings.about.copyVersionFailed"), + }), + ) + .finally(() => setCopy("pending", false)) + } + const credit = (name: string) => ( {name} @@ -72,11 +105,27 @@ export function SettingsAbout(props: { active: boolean }) { return (
-

- {language.t("settings.about.version", { - version: platform.version ?? language.t("settings.about.devVersion"), - })} -

+
+ + + +

{language.t("settings.about.license")}

diff --git a/packages/app/src/settings/general/controllers.ts b/packages/app/src/settings/general/controllers.ts index ccc0cd0960fa..6a27226f47bf 100644 --- a/packages/app/src/settings/general/controllers.ts +++ b/packages/app/src/settings/general/controllers.ts @@ -177,6 +177,12 @@ export function createSoundSettingsController() { (value) => settings.sounds.setPermissionsEnabled(value), (id) => settings.sounds.setPermissions(id), ), + questions: channel( + settings.sounds.questionsEnabled, + settings.sounds.questions, + (value) => settings.sounds.setQuestionsEnabled(value), + (id) => settings.sounds.setQuestions(id), + ), errors: channel( settings.sounds.errorsEnabled, settings.sounds.errors, diff --git a/packages/app/src/settings/general/general.tsx b/packages/app/src/settings/general/general.tsx index 7d35c9098364..b60849019d30 100644 --- a/packages/app/src/settings/general/general.tsx +++ b/packages/app/src/settings/general/general.tsx @@ -249,6 +249,17 @@ export const SettingsGeneral: Component = () => { void update.catch(() => setPinchZoom(!checked)) } + const [spellcheck, { mutate: setSpellcheck }] = createResource( + () => desktop() && "getSpellcheckEnabled" in platform, + () => platform.getSpellcheckEnabled?.().catch(() => true) ?? true, + { initialValue: true }, + ) + + const onSpellcheckChange = (checked: boolean) => { + setSpellcheck(checked) + void platform.setSpellcheckEnabled?.(checked).catch(() => setSpellcheck(!checked)) + } + const GeneralSection = () => (

{language.t("settings.general.section.general")}

@@ -282,6 +293,14 @@ export const SettingsGeneral: Component = () => {
+ +
+ +
+
diff --git a/packages/app/src/settings/model.test.ts b/packages/app/src/settings/model.test.ts index e1041cdbf790..2d0899926e88 100644 --- a/packages/app/src/settings/model.test.ts +++ b/packages/app/src/settings/model.test.ts @@ -112,12 +112,14 @@ describe("settings schema", () => { keybinds: {}, permissions: { autoApprove: false, autoApproveProjects: {} }, workspaces: { defaultDestination: "last-used", lastUsed: {} }, - notifications: { agent: false, permissions: true, errors: false }, + notifications: { agent: false, permissions: true, questions: true, errors: false }, sounds: { agentEnabled: true, agent: "staplebops-01", permissionsEnabled: true, permissions: "staplebops-02", + questionsEnabled: true, + questions: "staplebops-05", errorsEnabled: true, errors: "nope-03", interfaceEnabled: true, @@ -165,7 +167,7 @@ describe("settings schema", () => { expect(settings.permissions).toEqual({ autoApprove: true, autoApproveProjects: { on: true, off: false } }) expect(settings.workspaces).toEqual({ defaultDestination: "new", lastUsed: { good: "workspace" } }) expect(settings.keybinds).toEqual({ good: "ctrl+k" }) - expect(settings.notifications).toEqual({ agent: false, permissions: true, errors: true }) + expect(settings.notifications).toEqual({ agent: false, permissions: true, questions: true, errors: true }) expect(settings.sounds).toMatchObject({ agent: "custom", agentEnabled: false, permissions: "staplebops-02" }) expect(decode(encode(settings))).toEqual(settings) }) diff --git a/packages/app/src/settings/model.tsx b/packages/app/src/settings/model.tsx index eaac96dbdd64..5e8f8f164c59 100644 --- a/packages/app/src/settings/model.tsx +++ b/packages/app/src/settings/model.tsx @@ -169,6 +169,7 @@ const workspacesSchema = Persistence.struct({ const notificationsSchema = Persistence.struct({ agent: Schema.Boolean, permissions: Schema.Boolean, + questions: Schema.Boolean, errors: Schema.Boolean, }) @@ -177,6 +178,8 @@ const soundsSchema = Persistence.struct({ agent: Schema.String, permissionsEnabled: Schema.Boolean, permissions: Schema.String, + questionsEnabled: Schema.Boolean, + questions: Schema.String, errorsEnabled: Schema.Boolean, errors: Schema.String, interfaceEnabled: Schema.optional(Schema.Boolean), @@ -310,12 +313,14 @@ export const defaultSettings: Settings = { keybinds: {}, permissions: { autoApprove: false, autoApproveProjects: {} }, workspaces: { defaultDestination: "last-used", lastUsed: {} }, - notifications: { agent: false, permissions: true, errors: false }, + notifications: { agent: false, permissions: true, questions: true, errors: false }, sounds: { agentEnabled: true, agent: "staplebops-01", permissionsEnabled: true, permissions: "staplebops-02", + questionsEnabled: true, + questions: "staplebops-05", errorsEnabled: true, errors: "nope-03", interfaceEnabled: true, @@ -540,6 +545,10 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont setPermissions(value: boolean) { setStore("notifications", "permissions", value) }, + questions: withFallback(() => store.notifications?.questions, defaultSettings.notifications.questions), + setQuestions(value: boolean) { + setStore("notifications", "questions", value) + }, errors: withFallback(() => store.notifications?.errors, defaultSettings.notifications.errors), setErrors(value: boolean) { setStore("notifications", "errors", value) @@ -565,6 +574,14 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont setPermissions(value: string) { setStore("sounds", "permissions", value) }, + questionsEnabled: withFallback(() => store.sounds?.questionsEnabled, defaultSettings.sounds.questionsEnabled), + setQuestionsEnabled(value: boolean) { + setStore("sounds", "questionsEnabled", value) + }, + questions: withFallback(() => store.sounds?.questions, defaultSettings.sounds.questions), + setQuestions(value: string) { + setStore("sounds", "questions", value) + }, errorsEnabled: withFallback(() => store.sounds?.errorsEnabled, defaultSettings.sounds.errorsEnabled), setErrorsEnabled(value: boolean) { setStore("sounds", "errorsEnabled", value) diff --git a/packages/app/src/settings/navigation.tsx b/packages/app/src/settings/navigation.tsx index e16d716f8dd9..0f2c32bdaebd 100644 --- a/packages/app/src/settings/navigation.tsx +++ b/packages/app/src/settings/navigation.tsx @@ -116,7 +116,7 @@ export function SettingsNavigation(props: { - + {(group) => (
diff --git a/packages/app/src/settings/notifications/notifications.tsx b/packages/app/src/settings/notifications/notifications.tsx index 66ef8a6a6d33..e0a658bae6bf 100644 --- a/packages/app/src/settings/notifications/notifications.tsx +++ b/packages/app/src/settings/notifications/notifications.tsx @@ -23,6 +23,11 @@ const soundSettings = { title: "settings.general.sounds.permissions.title", description: "settings.general.sounds.permissions.description", }, + questions: { + action: "settings-sounds-questions", + title: "settings.general.sounds.questions.title", + description: "settings.general.sounds.questions.description", + }, errors: { action: "settings-sounds-errors", title: "settings.general.sounds.errors.title", @@ -31,7 +36,7 @@ const soundSettings = { } as const const SoundSetting: Component<{ - kind: "agent" | "permissions" | "errors" + kind: "agent" | "permissions" | "questions" | "errors" channel: SoundSettingsController["agent"] }> = (props) => { const language = useLanguage() @@ -100,6 +105,21 @@ export const SettingsNotifications: Component = () => {
+ +
+ settings.notifications.setQuestions(checked)} + > + {language.t("settings.general.notifications.questions.title")} + +
+
+ { + [] = [ target: "settings-pinch-zoom", available: "desktop", }, + { + tab: "general", + label: "settings.general.row.spellcheck.title", + target: "settings-spellcheck", + keywords: "spelling spell check dictionary", + available: "desktop", + }, { tab: "general", label: "settings.general.row.mobileTitlebarBottom.title", @@ -172,6 +179,14 @@ export const clientSettings: Entry[] = [ description: "settings.general.notifications.permissions.description", keywords: "desktop notifications permissions", }, + { + tab: "notifications", + label: "settings.general.notifications.questions.title", + target: "settings-notifications-questions", + section: "settings.general.section.notifications", + description: "settings.general.notifications.questions.description", + keywords: "desktop notifications questions mcp elicitation input", + }, { tab: "notifications", label: "settings.general.notifications.errors.title", @@ -196,6 +211,14 @@ export const clientSettings: Entry[] = [ description: "settings.general.sounds.permissions.description", keywords: "sound audio permissions", }, + { + tab: "notifications", + label: "settings.general.sounds.questions.title", + target: "settings-sounds-questions", + section: "settings.general.section.sounds", + description: "settings.general.sounds.questions.description", + keywords: "sound audio questions mcp elicitation input", + }, { tab: "notifications", label: "settings.general.sounds.errors.title", diff --git a/packages/app/src/settings/search.css b/packages/app/src/settings/search.css index bbfae1035aeb..efa563b35e97 100644 --- a/packages/app/src/settings/search.css +++ b/packages/app/src/settings/search.css @@ -4,6 +4,11 @@ min-height: 0; } +/* Only results scroll inside the search; with the nav list below it, the list absorbs a short sidebar. */ +.settings-search[data-empty="true"] { + flex-shrink: 0; +} + .settings-search[data-empty="true"] [data-slot="text-input-v2-icon-button"] { visibility: hidden; } diff --git a/packages/app/src/settings/settings.css b/packages/app/src/settings/settings.css index 8fffd4c8f5eb..3f61e0ac2de2 100644 --- a/packages/app/src/settings/settings.css +++ b/packages/app/src/settings/settings.css @@ -85,9 +85,54 @@ flex-direction: column; gap: 16px; overflow-y: auto; + overscroll-behavior: contain; min-height: 0; } +@property --settings-nav-fade-start { + syntax: ""; + inherits: false; + initial-value: 0px; +} + +@property --settings-nav-fade-end { + syntax: ""; + inherits: false; + initial-value: 0px; +} + +/* Each edge fades in once content is hidden behind it. A list that does not overflow has no scroll timeline, so it keeps both lengths at 0. */ +@supports (animation-timeline: scroll()) { + .settings-nav-groups { + mask-image: linear-gradient( + to bottom, + transparent, + #000 var(--settings-nav-fade-start), + #000 calc(100% - var(--settings-nav-fade-end)), + transparent + ); + animation: + settings-nav-fade-start linear both, + settings-nav-fade-end linear both; + animation-timeline: scroll(self), scroll(self); + animation-range: + 0 24px, + calc(100% - 24px) 100%; + } +} + +@keyframes settings-nav-fade-start { + to { + --settings-nav-fade-start: 24px; + } +} + +@keyframes settings-nav-fade-end { + from { + --settings-nav-fade-end: 24px; + } +} + .settings-nav-groups [data-slot="tabs-v2-trigger-wrapper"] { width: 100%; height: 28px; @@ -232,6 +277,55 @@ gap: 14px; } +.settings-about-version-line { + display: flex; + align-items: center; + justify-content: center; +} + +.settings-about-version { + position: relative; + isolation: isolate; + display: inline-flex; + min-height: 24px; + align-items: center; + margin-block: -2px; + padding: 0; + border: 0; + border-radius: 4px; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; + transition: color 120ms ease; +} + +.settings-about-version::before { + position: absolute; + z-index: -1; + inset-block: 0; + inset-inline: -6px; + border-radius: 4px; + background: transparent; + content: ""; + transition: background-color 120ms ease; +} + +.settings-about-version:hover, +.settings-about-version:focus-visible { + color: var(--v2-text-text-base); + outline: none; +} + +.settings-about-version:hover::before, +.settings-about-version:focus-visible::before { + background: var(--v2-background-bg-layer-02); +} + +.settings-about-version:disabled { + cursor: default; +} + .settings-about-credits, .settings-about-publication, .settings-about-details { diff --git a/packages/app/src/settings/shell.tsx b/packages/app/src/settings/shell.tsx index c7f68832bc9c..659bc4067a56 100644 --- a/packages/app/src/settings/shell.tsx +++ b/packages/app/src/settings/shell.tsx @@ -179,7 +179,7 @@ export function SettingsScreen() { if (!root || event.ctrlKey || !event.deltaY || !(event.target instanceof Element)) return // The page scrolls inside its panel, so a wheel over the gutters or sidebar would otherwise do nothing. - if (event.target.closest(".settings-content") || scrollsNatively(event.target, root, event.deltaY)) return + if (event.target.closest(".settings-content") || insideScroller(event.target, root)) return const panel = root.querySelector(".settings-content > .settings-panel") if (!panel) return @@ -210,11 +210,12 @@ export function SettingsScreen() { ) } -function scrollsNatively(target: Element, root: Element, deltaY: number) { +// An overflowing scroller owns the wheel even at its edges, so reaching the end of the nav list does not scroll the page. +function insideScroller(target: Element, root: Element) { for (let node: Element | null = target; node && node !== root; node = node.parentElement) { if (!/auto|scroll/.test(getComputedStyle(node).overflowY)) continue - if (deltaY < 0 ? node.scrollTop > 0 : node.scrollHeight - node.clientHeight - node.scrollTop > 1) return true + if (node.scrollHeight - node.clientHeight > 1) return true } return false diff --git a/packages/app/src/settings/surface.tsx b/packages/app/src/settings/surface.tsx index 15da98cb1fd5..e893a21d0926 100644 --- a/packages/app/src/settings/surface.tsx +++ b/packages/app/src/settings/surface.tsx @@ -4,7 +4,7 @@ import { createStore } from "solid-js/store" import { createSimpleContext } from "@opencode/ui/context" import { useLayout, type LayoutRoute } from "@/shell/state/layout" import { useTabs } from "@/shell/tabs/tabs" -import { ServerConnection } from "@/runtime/server/registry" +import { useServers } from "@/runtime/server/registry" import { useCommand } from "@/shell/commands/command" import { createSettingsPages } from "@/runtime/plugin/settings-pages" import { useSettingsServers } from "./servers/inventory" @@ -38,6 +38,7 @@ export const { use: useSettingsSurface, provider: SettingsSurfaceProvider } = cr const layout = useLayout() const command = useCommand() const servers = useSettingsServers() + const registry = useServers() const tabs = useTabs() const location = useLocation<{ @@ -76,7 +77,7 @@ export const { use: useSettingsSurface, provider: SettingsSurfaceProvider } = cr return ( list.find((item) => item.key === key) ?? - list.find((item) => !!item.connection && ServerConnection.local(item.connection)) ?? + list.find((item) => !!item.connection && registry.local(item.connection)) ?? list[0] ) }) diff --git a/packages/app/src/settings/workspaces/project-options.tsx b/packages/app/src/settings/workspaces/project-options.tsx index 6e38025a79b5..a131d8f73ae9 100644 --- a/packages/app/src/settings/workspaces/project-options.tsx +++ b/packages/app/src/settings/workspaces/project-options.tsx @@ -9,6 +9,7 @@ import { ServerConnection } from "@/runtime/server/registry" import type { LocalProject } from "@/shell/state/layout" import { fileManagerApp } from "@/home/projects/file-manager" import { useRevealProject } from "@/home/projects/reveal" +import { pathKey } from "@/workspaces/path-key" export const ProjectOptions: Component<{ server: ServerConnection.Any @@ -17,6 +18,7 @@ export const ProjectOptions: Component<{ onOpenChange?: (open: boolean) => void onEdit?: () => void onRename?: () => void + onAdd?: () => void class?: string size?: "small" | "normal" | "large" }> = (props) => { @@ -28,6 +30,11 @@ export const ProjectOptions: Component<{ const directories = () => [props.project.worktree, ...(props.project.sandboxes ?? [])] + const added = () => + context() + .projects.used() + .some((project) => pathKey(project.worktree) === pathKey(props.project.worktree)) + const hasUnread = () => directories().some((directory) => context().notification.project.hasUnread(directory)) const clearNotifications = () => { @@ -35,14 +42,13 @@ export const ProjectOptions: Component<{ directories().forEach((directory) => notification.project.markViewed(directory)) } + const addProject = () => { + props.onAdd?.() + context().projects.touch(props.project.worktree) + } + return ( - + + + {language.t("home.project.add")} + {(edit) => {language.t("common.edit")}} @@ -60,11 +69,15 @@ export const ProjectOptions: Component<{ {(rename) => {language.t("common.rename")}} - revealProject.reveal(props.server, props.project)}>{language.t(fileManagerApp(platform.os ?? "unknown").actionLabel)} + revealProject.reveal(props.server, props.project)}> + {language.t(fileManagerApp(platform.os ?? "unknown").actionLabel)} + + + + + {language.t("sidebar.project.clearNotifications")} + - - {language.t("sidebar.project.clearNotifications")} - diff --git a/packages/app/src/settings/workspaces/project-row.tsx b/packages/app/src/settings/workspaces/project-row.tsx index e53d58604871..cadffa622dc3 100644 --- a/packages/app/src/settings/workspaces/project-row.tsx +++ b/packages/app/src/settings/workspaces/project-row.tsx @@ -1,4 +1,4 @@ -import { Show } from "solid-js" +import { Show, onMount } from "solid-js" import { createStore } from "solid-js/store" import { InlineInput } from "@opencode/ui/inline-input" import { getFilename } from "@opencode/util/path" @@ -16,18 +16,26 @@ export function SettingsProjectRow(props: { project: LocalProject server: ServerConnection.Any onOpen: (project: LocalProject) => void + onAdd?: () => void + onMount?: (button: HTMLButtonElement) => void }) { const language = useLanguage() const global = useGlobal() - const [store, setStore] = createStore({ + const [store, setStore] = createStore<{ + menu: boolean + editor?: { draft: string; saving: boolean } + }>({ menu: false, - editor: undefined as { draft: string; saving: boolean } | undefined, }) let button: HTMLButtonElement | undefined let input: HTMLInputElement | undefined + onMount(() => { + if (button) props.onMount?.(button) + }) + const openEditor = () => { setStore("editor", { draft: displayName(props.project), saving: false }) requestAnimationFrame(() => { @@ -147,6 +155,7 @@ export function SettingsProjectRow(props: { onOpenChange={(open) => setStore("menu", open)} onEdit={() => props.onOpen(props.project)} onRename={openEditor} + onAdd={props.onAdd} />
diff --git a/packages/app/src/settings/workspaces/projects.tsx b/packages/app/src/settings/workspaces/projects.tsx index 8935345f1e7b..e887da6125c7 100644 --- a/packages/app/src/settings/workspaces/projects.tsx +++ b/packages/app/src/settings/workspaces/projects.tsx @@ -1,4 +1,4 @@ -import { Show, createEffect, createMemo, type Component, type JSX } from "solid-js" +import { Show, createEffect, createMemo, on, type Component, type JSX } from "solid-js" import { Key } from "@solid-primitives/keyed" import { createStore } from "solid-js/store" import { Button } from "@opencode/ui/button" @@ -16,6 +16,7 @@ import { SettingsSearchField } from "../search-field" import { SettingsProjectRow } from "./project-row" import "@/settings/search.css" import "@/settings/settings.css" +import "./project.css" export const SettingsProjects: Component<{ server: ServerConnection.Any @@ -26,21 +27,42 @@ export const SettingsProjects: Component<{ const language = useLanguage() const global = useGlobal() const pickDirectory = useDirectoryPicker() - const [store, setStore] = createStore({ filter: "" }) + const [store, setStore] = createStore({ filter: "", others: false }) const context = createMemo(() => global.ensureServerCtx(props.server)) - const projects = createMemo(() => context().projects.list()) - const searchable = createMemo(() => projects().length > 7) - const filtered = createMemo(() => { - const query = searchable() ? store.filter.trim().toLowerCase() : "" + let focus: string | undefined - return query ? projects().filter((project) => displayName(project).toLowerCase().includes(query)) : projects() - }) + const projects = createMemo(() => context().projects.unique()) + + const used = createMemo( + () => + new Set( + context() + .projects.used() + .map((project) => project.id), + ), + ) + + const others = createMemo(() => projects().filter((project) => !used().has(project.id))) + const searchable = createMemo(() => projects().length > 7 || others().length > 0) + const query = createMemo(() => (searchable() ? store.filter.trim().toLowerCase() : "")) + + const filtered = createMemo(() => + projects().filter( + (project) => + !query() || [displayName(project), project.worktree].some((value) => value.toLowerCase().includes(query())), + ), + ) + + const added = createMemo(() => filtered().filter((project) => used().has(project.id))) + const otherResults = createMemo(() => filtered().filter((project) => !used().has(project.id))) createEffect(() => { if (!searchable()) setStore("filter", "") }) + createEffect(on(context, () => setStore("others", false))) + const addProject = () => pickDirectory({ server: props.server, @@ -108,9 +130,7 @@ export const SettingsProjects: Component<{ class="settings-project-empty-card flex flex-col items-center gap-2 py-24 text-center" > -
- {language.t("settings.projects.empty.title")} -
+
{language.t("settings.projects.empty.title")}
{language.t("settings.projects.empty.description")}
@@ -121,12 +141,67 @@ export const SettingsProjects: Component<{ } > -
- - {(project) => ( - - )} - +
+ 0}> +
+ + {(project) => ( + { + if (focus !== project().worktree) return + focus = undefined + requestAnimationFrame(() => button.focus()) + }} + /> + )} + +
+
+ 0}> + {language.t("settings.projects.other")} + } + > + + + +
+ + {(project) => ( + (focus = project().worktree)} + /> + )} + +
+
+
diff --git a/packages/app/src/shell/commands/dialog.tsx b/packages/app/src/shell/commands/dialog.tsx index fed41df6dc03..4c4da75ad500 100644 --- a/packages/app/src/shell/commands/dialog.tsx +++ b/packages/app/src/shell/commands/dialog.tsx @@ -8,7 +8,10 @@ import { createStore } from "solid-js/store" import { formatKeybindParts } from "@/shell/commands/command" import { useLanguage } from "@/runtime/i18n/language" import { useTabs } from "@/shell/tabs/tabs" -import { SessionTabAvatar } from "@/shell/layout/session-tab-avatar" +import { ActivityRing } from "@opencode/ui/activity-ring" +import { SessionTabAvatarView } from "@/shell/layout/session-tab-avatar" +import { useSessionTabAvatarState } from "@/shell/layout/project-avatar-state" +import type { ServerConnection } from "@/runtime/server/registry" import { getRelativeTime } from "@/shell/time" import { createCommandPaletteFileEntry, createCommandPaletteModel, type CommandPaletteEntry } from "./palette" import { createCommandPaletteSearch, matchesCommandPaletteEntry } from "./search" @@ -157,55 +160,90 @@ function PaletteRow(props: { - -
-
- - - - {(session) => ( - - )} - -
-
- - - - - {(description) => ( - - - - )} - -
-
- - - {getRelativeTime(new Date(props.item.updated!).toISOString(), props.language.t)} - - + + {(session) => ( + + )} ) } + +function PaletteSessionRow(props: { + item: CommandPaletteEntry + server: ServerConnection.Key + directory: string + sessionID: string + language: ReturnType + sessionOpen: boolean +}) { + const status = useSessionTabAvatarState( + () => props.server, + () => props.sessionID, + () => true, + ) + + return ( + <> +
+
+ + + {/* A busy session shows its activity ring instead of the unread dot, as session tabs do. */} + +
+
+ + + + + {(description) => ( + + + + )} + +
+
+ {/* The project avatar stays put; a working session shows its activity ring where its age would be. */} + + {(updated) => ( + + {getRelativeTime(new Date(updated()).toISOString(), props.language.t)} + + )} + + } + > + + {props.language.t("session.timeline.working")} + + + + + ) +} diff --git a/packages/app/src/shell/layout/project-avatar-state.ts b/packages/app/src/shell/layout/project-avatar-state.ts index 52d2b017e863..64fb792bedf9 100644 --- a/packages/app/src/shell/layout/project-avatar-state.ts +++ b/packages/app/src/shell/layout/project-avatar-state.ts @@ -7,8 +7,9 @@ import { projectSettingsKey, useSettings } from "@/settings/model" type ServerData = ReturnType["ensureServerCtx"]>["data"] +// Without a server (no session in view) the session reads as idle and read. export function useSessionTabAvatarState( - server: Accessor, + server: Accessor, sessionId: Accessor, root?: Accessor, snapshot?: Accessor, diff --git a/packages/app/src/shell/layout/session-tab-avatar.tsx b/packages/app/src/shell/layout/session-tab-avatar.tsx index 8e00136a4c95..1178ed8d6265 100644 --- a/packages/app/src/shell/layout/session-tab-avatar.tsx +++ b/packages/app/src/shell/layout/session-tab-avatar.tsx @@ -1,6 +1,4 @@ import type { LocalProject } from "@/shell/state/layout" -import type { ServerConnection } from "@/runtime/server/registry" -import { useSessionTabAvatarState } from "@/shell/layout/project-avatar-state" import { displayName, getProjectAvatarGenerated, @@ -8,51 +6,17 @@ import { getProjectAvatarVariant, ProjectAvatar, } from "@opencode/ui/project-avatar" -import { SessionProgressIndicatorV2 } from "@opencode/session-ui/v2/session-progress-indicator-v2" -import { Show } from "solid-js" - -export function SessionTabAvatar(props: { - project?: LocalProject - directory: string - sessionId: string - server: ServerConnection.Key -}) { - const state = useSessionTabAvatarState( - () => props.server, - () => props.sessionId, - () => true, - ) +// The project avatar never changes while a session works: callers show `ActivityRing` at the row's trailing edge, as +// session tabs do. +export function SessionTabAvatarView(props: { project?: LocalProject; directory: string; unread: boolean }) { return ( - ) } - -export function SessionTabAvatarView(props: { - project?: LocalProject - directory: string - unread: boolean - loading?: boolean -}) { - return ( - - } - > - - - ) -} diff --git a/packages/app/src/shell/notifications/coordinator.ts b/packages/app/src/shell/notifications/coordinator.ts index 24e6d42df56b..5449356c0e9d 100644 --- a/packages/app/src/shell/notifications/coordinator.ts +++ b/packages/app/src/shell/notifications/coordinator.ts @@ -1,13 +1,20 @@ import { onCleanup } from "solid-js" +import { Predicate } from "effect" + +type FocusLock = { pending: boolean; release?: VoidFunction } const FOCUS_LOCK = "opencode:notification-focus" +const DELIVERY_LOCK = "opencode:notification-delivery" + const MAX_CLAIMED = 500 export function createNotificationCoordinator() { const locks = typeof navigator === "undefined" ? undefined : navigator.locks + const claimed = new Set() - const focus = { pending: false, release: undefined as (() => void) | undefined } + + const focus: FocusLock = { pending: false } const updateFocus = () => { if (typeof document === "undefined" || !document.hasFocus()) { @@ -47,7 +54,7 @@ export function createNotificationCoordinator() { }) } - const once = async (kind: "sound" | "system", eventID: string, run: () => Promise | void) => { + const once = async (kind: "sound" | "system", eventID: string, run: () => Promise | void) => { const key = `${kind}:${eventID}` const execute = async () => { @@ -60,18 +67,21 @@ export function createNotificationCoordinator() { } return { - sound(eventID: string, run: () => Promise | void) { + sound(eventID: string, run: () => Promise | void) { return once("sound", eventID, run) }, - system(eventID: string, run: () => Promise | void) { + system(eventID: string, run: () => Promise | void) { return once("system", eventID, async () => { if (typeof document !== "undefined" && document.hasFocus()) return if (!locks) return run() - await locks.request(FOCUS_LOCK, { mode: "exclusive", ifAvailable: true }, async (lock) => { - if (!lock) return - await run() - }) + // Another alert holding the focus lock must not look like a focused app window. + await locks.request(DELIVERY_LOCK, () => + locks.request(FOCUS_LOCK, { mode: "exclusive", ifAvailable: true }, async (lock) => { + if (!lock) return + await run() + }), + ) }) }, } @@ -84,7 +94,7 @@ function claim(kind: "sound" | "system", eventID: string, claimed: Set) try { const storageKey = `opencode:notification-${kind}` const value: unknown = JSON.parse(localStorage.getItem(storageKey) ?? "[]") - const events = Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [] + const events = Array.isArray(value) ? value.filter(Predicate.isString) : [] if (events.includes(eventID)) { claimed.add(eventID) diff --git a/packages/app/src/shell/notifications/notification.tsx b/packages/app/src/shell/notifications/notification.tsx index 78a4f3e6829f..7804b3ed9cf6 100644 --- a/packages/app/src/shell/notifications/notification.tsx +++ b/packages/app/src/shell/notifications/notification.tsx @@ -1,12 +1,12 @@ import { createEffect, createMemo, onCleanup, untrack } from "solid-js" import { createStore } from "solid-js/store" import { Schema } from "effect" -import type { SessionInfo } from "@opencode/client/promise" +import { isSessionNotFoundError, type SessionInfo } from "@opencode/client/promise" import type { ServerSDK } from "@/runtime/server/client" import type { Data } from "@opencode/client/solid" import { usePlatform } from "@/runtime/platform/platform" import { useLanguage } from "@/runtime/i18n/language" -import { useSettings } from "@/settings/model" +import { projectSettingsKey, useSettings } from "@/settings/model" import { Persist, persisted, removePersisted } from "@/runtime/persistence/storage" import { Persistence } from "@/runtime/persistence/schema" import { playSoundById } from "@/shell/notifications/sound" @@ -17,6 +17,13 @@ import { useServer } from "@/runtime/server/current" type NotificationTabs = Pick, "addSessionTab" | "rememberSessionRoute" | "select"> +const requestTitles = { + permission: "notification.permission.title", + question: "notification.question.title", + "mcp-elicitation": "notification.elicitation.title", + "websearch.provider": "notification.permission.title", +} as const + export function openNotificationSession(tabs: NotificationTabs, server: ServerConnection.Key, sessionID: string) { const tab = tabs.addSessionTab({ server, sessionId: sessionID }) @@ -201,7 +208,14 @@ export function createServerNotificationState(input: { viewRetryTimer = undefined viewRetryAttempt = 0 }, - () => { + (error) => { + if (isSessionNotFoundError(error)) { + acknowledged.delete(root) + input.data.session.forget(root) + + return + } + if (acknowledged.get(root) !== idle) return acknowledged.delete(root) @@ -280,7 +294,67 @@ export function createServerNotificationState(input: { }) } + const handleRequest = async (kind: keyof typeof requestTitles, sessionID: string, requestID: string) => { + const session = await lookup(sessionID) + + if (!session || disposed.value) return + + const target = sessionIDHasOpenTab(tabs.store, input.key, sessionID) + ? sessionID + : input.data.session.root(sessionID) + + if (!sessionIDHasOpenTab(tabs.store, input.key, target)) return + + const category = kind === "question" || kind === "mcp-elicitation" ? "questions" : "permissions" + + const pending = () => { + if (disposed.value) return false + + if (kind !== "permission") return input.data.session.form.list(sessionID)?.some((form) => form.id === requestID) + + if (settings.permissions.autoApproves(projectSettingsKey(input.sdk.scope, session.projectID))) return false + + return input.data.session.permission.list(sessionID)?.some((request) => request.id === requestID) + } + + if (!pending()) return + + const key = `${input.key}\0${kind}:${requestID}` + + if (settings.sounds[`${category}Enabled`]()) { + void input.coordinator.sound(key, () => { + if (pending()) return playSoundById(settings.sounds[category]()) + }) + } + + if (!settings.notifications[category]()) return + + void input.coordinator.system(key, () => { + if (!pending()) return + + return platform.notify(language.t(requestTitles[kind]), session.title ?? sessionID, () => + openNotificationSession(tabs, input.key, target), + ) + }) + } + const unsub = input.sdk.event.listen((event) => { + if (event.type === "permission.asked") { + void handleRequest("permission", event.data.sessionID, event.data.id) + + return + } + + if (event.type === "form.created") { + const kind = event.data.form.metadata?.kind + + if (kind === "question" || kind === "mcp-elicitation" || kind === "websearch.provider") { + void handleRequest(kind, event.data.form.sessionID, event.data.form.id) + } + + return + } + if (event.type === "session.execution.failed") { handleSessionError(event.data.sessionID, event.id) diff --git a/packages/app/src/shell/tabs/tabs.tsx b/packages/app/src/shell/tabs/tabs.tsx index efb426706de8..3b7f4249edaf 100644 --- a/packages/app/src/shell/tabs/tabs.tsx +++ b/packages/app/src/shell/tabs/tabs.tsx @@ -8,7 +8,7 @@ import { usePluginServers } from "@/runtime/plugin/servers" import { createEffect, getOwner, onCleanup, startTransition } from "solid-js" import { useLocation, useNavigate } from "@solidjs/router" import { usePlatform } from "@/runtime/platform/platform" -import { uuid } from "@/runtime/persistence/uuid" +import { uuid } from "@opencode/util/uuid" import { SessionTabsRemovedDetail } from "@/shell/titlebar/session-events" import { sessionHref } from "@/shell/routes/session" import { createTabMemory } from "./memory" diff --git a/packages/app/src/shell/titlebar/inbox.tsx b/packages/app/src/shell/titlebar/inbox.tsx index a67e6dbf3843..850ec4f5f211 100644 --- a/packages/app/src/shell/titlebar/inbox.tsx +++ b/packages/app/src/shell/titlebar/inbox.tsx @@ -103,8 +103,10 @@ export function SidebarInbox() { ) } - const rows = (list: InboxEntry[]) => ( - entry.key)}> + // Takes an accessor so only the For tracks the section. Reading it here would recreate the For, remounting every + // row on any session change and resetting the list's scroll. + const rows = (list: () => InboxEntry[]) => ( + entry.key)}> {(key) => ( {(entry) => ( @@ -133,7 +135,7 @@ export function SidebarInbox() { 0}>
- {rows(sections().needs)} + {rows(() => sections().needs)}
0}> - {rows(sections().inbox)} + {rows(() => sections().inbox)}
0}>
- {rows(sections().archived)} + {rows(() => sections().archived)}
@@ -176,7 +178,7 @@ export function SidebarInbox() { />
{/* A collapsed shelf still shows the session that is open. */} - {rows(sections().working.filter((entry) => state.workingExpanded || inbox.selected(entry)))} + {rows(() => sections().working.filter((entry) => state.workingExpanded || inbox.selected(entry)))}
diff --git a/packages/app/src/shell/titlebar/recently-closed-tabs-menu.tsx b/packages/app/src/shell/titlebar/recently-closed-tabs-menu.tsx index f80419c59bdf..7a7891424935 100644 --- a/packages/app/src/shell/titlebar/recently-closed-tabs-menu.tsx +++ b/packages/app/src/shell/titlebar/recently-closed-tabs-menu.tsx @@ -234,7 +234,7 @@ function RecentlyClosedTabItem(props: { entry: Pick; return ( - + -
- {props.data.path} -
+ {(path) => ( +
+ {/* Break after separators so long paths wrap between folder names, not mid-name. */} + + + {(part) => ( + <> + {part} + + + )} + + +
+ )}
diff --git a/packages/app/src/shell/titlebar/tab-strip.tsx b/packages/app/src/shell/titlebar/tab-strip.tsx index 4c1e42116689..37f1c2296bd3 100644 --- a/packages/app/src/shell/titlebar/tab-strip.tsx +++ b/packages/app/src/shell/titlebar/tab-strip.tsx @@ -1,4 +1,5 @@ -import { createEffect, createMemo, createResource, For, onCleanup, Show } from "solid-js" +import { createEffect, createMemo, createResource, For, onCleanup, onMount, Show } from "solid-js" +import { createResizeObserver } from "@solid-primitives/resize-observer" import { createStore } from "solid-js/store" import { DragDropProvider, PointerSensor } from "@dnd-kit/solid" import { isSortable, useSortable } from "@dnd-kit/solid/sortable" @@ -228,6 +229,7 @@ function SessionTabEntry(props: { pending() || !ctx || props.active || + ctx.data.session.missing(id) || (!session() && !persisted()?.title) || ctx.sdk.connection.status() !== "connected" ) @@ -392,6 +394,22 @@ export function TitlebarTabStrip(props: { const command = useCommand() const vertical = () => props.orientation === "vertical" let listRef!: HTMLDivElement + let scrollRef!: HTMLDivElement + // Each vertical edge feathers by as much as there is left to scroll past it, so it appears and leaves without a jump. + const [fade, setFade] = createStore({ top: 0, bottom: 0 }) + + const measureFade = () => + setFade({ + top: Math.min(16, Math.round(scrollRef.scrollTop)), + bottom: Math.min( + 16, + Math.max(0, Math.round(scrollRef.scrollHeight - scrollRef.clientHeight - scrollRef.scrollTop)), + ), + }) + + onMount(() => { + if (vertical()) createResizeObserver([scrollRef, listRef], measureFade) + }) const [visibility, setVisibility] = createStore>({}) const [unread, setUnread] = createStore>({}) const visibleTabs = createMemo(() => props.tabs.filter((tab) => tab.type === "draft" || visibility[tabKey(tab)])) @@ -482,12 +500,21 @@ export function TitlebarTabStrip(props: { classList={{ "min-h-0 overflow-hidden": vertical() }} >
{ + if (vertical()) measureFade() + }} > event.target instanceof Element && - !!event.target.closest('[data-slot="tab-close"], [contenteditable="true"], [contenteditable="plaintext-only"]'), + !!event.target.closest( + '[data-slot="tab-close"], [contenteditable="true"], [contenteditable="plaintext-only"]', + ), }), ]} modifiers={[ diff --git a/packages/app/src/shell/titlebar/titlebar.css b/packages/app/src/shell/titlebar/titlebar.css index 2b77904f3b4b..a47026a8d1eb 100644 --- a/packages/app/src/shell/titlebar/titlebar.css +++ b/packages/app/src/shell/titlebar/titlebar.css @@ -10,11 +10,23 @@ [data-slot="vertical-tabs-sidebar"] [data-slot="vertical-tabs-scroll"] { min-height: 0; - /* Leave enough space to scroll the final tab clear of the fade above Settings. */ padding-block-end: 16px; - scroll-padding-block-end: 16px; - -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 16px), transparent); - mask-image: linear-gradient(to bottom, black calc(100% - 16px), transparent); + /* Keyboard navigation scrolls a tab clear of the feathered edges, which TitlebarTabStrip sizes from the scroll. */ + scroll-padding-block: 16px; + -webkit-mask-image: linear-gradient( + to bottom, + transparent, + black var(--vertical-tabs-fade-top, 0px), + black calc(100% - var(--vertical-tabs-fade-bottom, 0px)), + transparent + ); + mask-image: linear-gradient( + to bottom, + transparent, + black var(--vertical-tabs-fade-top, 0px), + black calc(100% - var(--vertical-tabs-fade-bottom, 0px)), + transparent + ); } [data-slot="mobile-tabs-trigger"][aria-expanded="true"] { diff --git a/packages/app/src/shell/titlebar/titlebar.tsx b/packages/app/src/shell/titlebar/titlebar.tsx index 7ac8d8b1685a..96995e467edf 100644 --- a/packages/app/src/shell/titlebar/titlebar.tsx +++ b/packages/app/src/shell/titlebar/titlebar.tsx @@ -28,8 +28,9 @@ import type { ComposerState } from "@/composer/persistence" import "./titlebar.css" import { MobileDrawer, MobileDrawerContent, MobileDrawerLabel, MobileDrawerTrigger } from "@/shell/mobile-drawer" import { sessionTabTitle } from "./tab-title" -import { SessionTabAvatar } from "@/shell/layout/session-tab-avatar" -import { SessionProgressIndicatorV2 } from "@opencode/session-ui/v2/session-progress-indicator-v2" +import { SessionTabAvatarView } from "@/shell/layout/session-tab-avatar" +import { useSessionTabAvatarState } from "@/shell/layout/project-avatar-state" +import { ActivityRing } from "@opencode/ui/activity-ring" import { RecentlyClosedTabsMenu } from "./recently-closed-tabs-menu" import { useSettingsDialog } from "@/settings/command" import { rootSession } from "@/shell/routes/session" @@ -497,7 +498,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { type="button" data-titlebar-tab-action data-action="vertical-tabs-search" - class="group flex h-7 w-full shrink-0 items-center gap-1.5 rounded-[6px] ps-1.5 pe-2 text-[13px] leading-4 text-v2-text-text-faint hover:text-v2-text-text-base" + class="group flex h-7 w-full shrink-0 items-center gap-1.5 rounded-[6px] ps-1.5 pe-2 text-[13px] leading-4 text-v2-text-text-faint" onClick={() => command.trigger("sessions.search")} > @@ -528,6 +529,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { id: "sessions.search", title: language.t("command.session.search"), category: language.t("command.category.session"), + keybind: "mod+shift+f", onSelect: async () => { const { DialogSessionSearch } = await import("@/shell/commands/session-search") void dialog.show(() => ) @@ -583,6 +585,13 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { const [mobileTabs, setMobileTabs] = createStore({ open: false, settings: false }) + // The current tab's project avatar stays put; while it works, its activity ring shows beside the tab count. + const currentStatus = useSessionTabAvatarState( + () => currentTab()?.server, + () => session()?.id ?? "", + () => true, + ) + const currentProject = createMemo(() => { const tab = currentTab() const value = session() @@ -666,26 +675,18 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) { tab().type === "draft" ? ( ) : ( - +
diff --git a/packages/console/app/vite.config.ts b/packages/console/app/vite.config.ts index 33455acc5edb..98cd38487ba7 100644 --- a/packages/console/app/vite.config.ts +++ b/packages/console/app/vite.config.ts @@ -15,6 +15,11 @@ export default defineConfig({ }, }), ], + environments: { + // Nitro copies public/ with fs.cp, which keeps the symlinks into packages/ui as links. + // Letting Vite copy it first writes real files. + client: { build: { copyPublicDir: true } }, + }, server: { allowedHosts: true, port: 3001, diff --git a/packages/core/package.json b/packages/core/package.json index 8db9a34683ff..e3ac935d5aac 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -44,6 +44,10 @@ "node": "./src/pty/pty.node.ts", "default": "./src/pty/pty.bun.ts" }, + "#claude-agent-sdk": { + "workerd": "./src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts", + "default": "./src/plugin/provider/claude-agent/claude/agent-sdk.ts" + }, "#persistent-pty-binary": { "workerd": "./src/persistent-pty/binary.workerd.ts", "bun": "./src/persistent-pty/binary.bun.ts", @@ -72,9 +76,9 @@ }, "devDependencies": { "@ai-sdk/openai-compatible": "2.0.41", + "@anthropic-ai/claude-agent-sdk": "0.3.301", "@effect/platform-node": "catalog:", "@effect/sql-sqlite-bun": "catalog:", - "@modelcontextprotocol/server": "2.3.1", "@opencode/http-recorder": "workspace:*", "@parcel/watcher-darwin-arm64": "2.5.1", "@parcel/watcher-darwin-x64": "2.5.1", @@ -99,6 +103,7 @@ "@lydell/node-pty": "catalog:", "@modelcontextprotocol/client": "2.3.1", "@modelcontextprotocol/core": "2.3.1", + "@modelcontextprotocol/server": "2.3.1", "@opencode/pty": "0.3.3", "@opencode/ai": "workspace:*", "@opencode/codemode": "workspace:*", @@ -125,5 +130,13 @@ "mime-types": "3.0.2", "which": "6.0.1", "zod": "catalog:" + }, + "peerDependencies": { + "@anthropic-ai/claude-agent-sdk": "0.3.301" + }, + "peerDependenciesMeta": { + "@anthropic-ai/claude-agent-sdk": { + "optional": true + } } } diff --git a/packages/core/script/benchmark-snapshot-session.ts b/packages/core/script/benchmark-snapshot-session.ts index ac5493a9e4c8..0ebbfd478d6e 100644 --- a/packages/core/script/benchmark-snapshot-session.ts +++ b/packages/core/script/benchmark-snapshot-session.ts @@ -136,7 +136,7 @@ const run = (snapshots: Layer.Layer) => delayed( kind === "text" ? TestLLM.text("Done.", `text-${call}`) - : TestLLM.tool(call, kind, { path: files[edits % files.length] }), + : TestLLM.toolCall(call, kind, { path: files[edits % files.length] }), ), ) yield* steps.attempt({ diff --git a/packages/core/script/build.ts b/packages/core/script/build.ts index e7c33cc188de..328214c88df9 100644 --- a/packages/core/script/build.ts +++ b/packages/core/script/build.ts @@ -23,6 +23,7 @@ const result = await Bun.build({ external: [ "#sqlite", "#pty", + "#claude-agent-sdk", "#persistent-pty-binary", "#fff", "#photon-wasm", diff --git a/packages/core/src/codemode/execution.ts b/packages/core/src/codemode/execution.ts new file mode 100644 index 000000000000..b41e0de4e85a --- /dev/null +++ b/packages/core/src/codemode/execution.ts @@ -0,0 +1,7 @@ +export * as CodeModeExecution from "./execution.js" + +import type { Context as ToolContext } from "@opencode/schema/tool" +import { Context } from "effect" + +/** The `execute` call a Code Mode program runs under, so extensions can act for its session like a tool does. */ +export class Service extends Context.Service()("@opencode/CodeModeExecution") {} diff --git a/packages/core/src/codemode/fetch.ts b/packages/core/src/codemode/fetch.ts new file mode 100644 index 000000000000..06d163012f8e --- /dev/null +++ b/packages/core/src/codemode/fetch.ts @@ -0,0 +1,78 @@ +export * as CodeModeFetch from "./fetch.js" + +import { Extension } from "@opencode/codemode" +import { isRecord } from "@opencode/util/record" +import { Effect } from "effect" +import { Permission } from "../permission.js" +import { CodeModeExecution } from "./execution.js" + +const TIMEOUT_MS = 30_000 + +type Init = { + readonly method?: string + readonly headers?: Record | Array<[string, string]> + readonly body?: string | Uint8Array | URLSearchParams +} + +const fetch = (input: string | URL, init: Init = {}) => + Effect.gen(function* () { + const url = String(input) + if (URL.parse(url)?.protocol === "file:") + return yield* Effect.fail(new Error("fetch cannot be used for filesystem access.")) + const execution = yield* CodeModeExecution.Service + const permission = yield* Permission.Service + // The same rules as the webfetch tool, so a URL denied there is denied here. + yield* permission + .assert({ + action: "webfetch", + resources: [url], + save: ["*"], + metadata: display([input, init]), + sessionID: execution.sessionID, + agent: execution.agent, + source: { type: "tool", messageID: execution.messageID, id: execution.id }, + }) + .pipe( + // The feedback is the user talking to the model, so it must reach the program as the error's message. + Effect.catchTag("Permission.CorrectedError", (error) => + Effect.fail(new Error(`The user rejected fetching ${url}: ${error.feedback}`)), + ), + ) + return yield* Effect.tryPromise({ try: () => send(input, init), catch: (error) => error }) + }) + +const send = async (input: string | URL, init: Init) => { + const response = await globalThis.fetch(input, { + method: init.method, + headers: init.headers, + body: init.body, + signal: AbortSignal.timeout(TIMEOUT_MS), + }) + const bytes = await response.bytes() + const headers = Object.fromEntries(response.headers) + const text = () => new TextDecoder().decode(bytes) + return { + url: response.url, + status: response.status, + statusText: response.statusText, + ok: response.ok, + redirected: response.redirected, + headers: { + get: (name: string) => headers[name.toLowerCase()] ?? null, + has: (name: string) => name.toLowerCase() in headers, + entries: () => Object.entries(headers), + }, + text: async () => text(), + json: async () => JSON.parse(text()) as unknown, + bytes: async () => bytes, + } +} + +export const extension = Extension.make({ name: "fetch", globals: { fetch: Extension.async(fetch) } }) + +/** What to show for a fetch call: its method and URL. */ +export const display = (args: ReadonlyArray) => { + const [input, init] = args + const method = isRecord(init) && typeof init.method === "string" ? init.method.toUpperCase() : "GET" + return { method, url: String(input) } +} diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index d8208aee7ee7..1fd67439350a 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -1,5 +1,6 @@ export * as CodeModeTool from "./tool.js" +import { ToolFailure } from "@opencode/ai/effect" import { CodeMode, Namespace, Tool } from "@opencode/codemode" import type { Content, @@ -11,9 +12,12 @@ import type { Result, } from "@opencode/schema/tool" import { Clock, Context, Effect, Ref, Schema, Semaphore } from "effect" +import { toSessionError } from "../session/to-session-error.js" import { definition, normalizedName } from "../tool/runtime.js" +import { Permission } from "../permission.js" import { CodeModeCatalog } from "./catalog.js" -import { CodeModeWeb } from "./web.js" +import { CodeModeExecution } from "./execution.js" +import { CodeModeFetch } from "./fetch.js" const ExecuteFile = Schema.Struct({ data: Schema.String, @@ -80,6 +84,7 @@ const description = [ export const create = ( inventory: Inventory, executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect, + permission: Permission.Interface, ) => { return { name: "execute", @@ -120,7 +125,14 @@ export const create = ( executeTool: (name, tool, input) => Effect.gen(function* () { const index = yield* Ref.getAndUpdate(callIndex, (index) => index + 1) - const executed = yield* executeTool(name, tool, input, context) + // The program sees the same failure text the model gets for a direct call. + const executed = yield* executeTool(name, tool, input, { + ...context, + // Progress replaces the execute call's own, so an inner tool's updates would hide the call rows. + progress: () => Effect.void, + }).pipe( + Effect.mapError((error) => new ToolFailure({ message: toSessionError(error).message, error })), + ) const content = resultContent(executed) const outputFileParts = outputFiles(content) if (outputFileParts.length > 0) @@ -133,6 +145,8 @@ export const create = ( Effect.onError(() => lock.withPermit(Ref.get(trailing).pipe(Effect.flatMap((pending) => (pending ? publish : Effect.void)))), ), + Effect.provideService(CodeModeExecution.Service, context), + Effect.provideService(Permission.Service, permission), ) const toolCalls = yield* Ref.get(calls) const collected = (yield* Ref.get(files)) @@ -194,7 +208,7 @@ function progressHooks(record: (update: (items: Array) => Array { switch (call.name) { case "fetch": - return start(call, { tool: call.name, status: "running", input: CodeModeWeb.display(call.args) }) + return start(call, { tool: call.name, status: "running", input: CodeModeFetch.display(call.args) }) default: return Effect.void } @@ -248,15 +262,15 @@ function renderCatalog(root: CatalogNode): ReadonlyArray>() +const runtimes = new WeakMap>() function runtime(inventory: Inventory) { const cached = runtimes.get(inventory) if (cached) return cached const tools = inventoryTools(inventory) - const created = CodeMode.make({ + const created = CodeMode.make({ tools, - extensions: [CodeModeWeb.extension], + extensions: [CodeModeFetch.extension], hooks: runHooks, }) runtimes.set(inventory, created) diff --git a/packages/core/src/codemode/web.ts b/packages/core/src/codemode/web.ts deleted file mode 100644 index 5dba1df38f90..000000000000 --- a/packages/core/src/codemode/web.ts +++ /dev/null @@ -1,50 +0,0 @@ -export * as CodeModeWeb from "./web.js" - -import { Extension } from "@opencode/codemode" -import { isRecord } from "@opencode/util/record" - -const TIMEOUT_MS = 30_000 - -type Init = { - readonly method?: string - readonly headers?: Record | Array<[string, string]> - readonly body?: string | Uint8Array | URLSearchParams -} - -const fetch = async (input: string | URL, init: Init = {}) => { - if (URL.parse(String(input))?.protocol === "file:") - throw new Error("fetch cannot be used for filesystem access.") - const response = await globalThis.fetch(input, { - method: init.method, - headers: init.headers, - body: init.body, - signal: AbortSignal.timeout(TIMEOUT_MS), - }) - const bytes = await response.bytes() - const headers = Object.fromEntries(response.headers) - const text = () => new TextDecoder().decode(bytes) - return { - url: response.url, - status: response.status, - statusText: response.statusText, - ok: response.ok, - redirected: response.redirected, - headers: { - get: (name: string) => headers[name.toLowerCase()] ?? null, - has: (name: string) => name.toLowerCase() in headers, - entries: () => Object.entries(headers), - }, - text: async () => text(), - json: async () => JSON.parse(text()) as unknown, - bytes: async () => bytes, - } -} - -export const extension = Extension.make({ name: "web", globals: { fetch } }) - -/** What to show for a fetch call: its method and URL. */ -export const display = (args: ReadonlyArray) => { - const [input, init] = args - const method = isRecord(init) && typeof init.method === "string" ? init.method.toUpperCase() : "GET" - return { method, url: String(input) } -} diff --git a/packages/core/src/config/plugin/provider.ts b/packages/core/src/config/plugin/provider.ts index d07637b2dac8..327bf9e73541 100644 --- a/packages/core/src/config/plugin/provider.ts +++ b/packages/core/src/config/plugin/provider.ts @@ -104,7 +104,9 @@ export const Plugin = define({ const providerID = definition.providerID for (const [id, config] of Object.entries(item.models ?? {})) { const source = definition.models.get(id) - const inherit = source?.inherit || !models.get(providerID, id) + const existing = models.get(providerID, id) + const hadVariants = (existing?.variants.length ?? 0) > 0 + const inherit = source?.inherit || !existing overlay( models, models.provider.get(providerID)?.provider.package, @@ -123,7 +125,8 @@ export const Plugin = define({ if ( config.variants === undefined && config.capabilities?.reasoning === undefined && - (!source?.base || repackaged) + // Custom models start without variants, so non-empty variants here came from an earlier transform. + ((!source?.base && !hadVariants) || repackaged) ) models.update(providerID, id, (model) => { model.variants = [ diff --git a/packages/core/src/instructions/index.ts b/packages/core/src/instructions/index.ts index 315f8b785067..9c37aade9cd1 100644 --- a/packages/core/src/instructions/index.ts +++ b/packages/core/src/instructions/index.ts @@ -158,14 +158,23 @@ export function diff(observed: ReadResult, previous?: Values): Effect.Effect>) { - return render( - value.flatMap((source) => { - if (!Object.hasOwn(values, source.key)) return [] - const text = source.initial(values[source.key]) - return text === undefined ? [] : [text] - }), - ) +/** One source's rendered text, keyed so consumers can tell the sources apart. */ +export interface Rendered { + readonly key: Key + readonly text: string +} + +export function renderInitial(value: List, values: Readonly>): ReadonlyArray { + return value.flatMap((source) => { + if (!Object.hasOwn(values, source.key)) return [] + const text = source.initial(values[source.key]) + return text === undefined ? [] : [{ key: source.key, text }] + }) +} + +/** The text models see for rendered sources. */ +export function join(rendered: ReadonlyArray) { + return render(rendered.map((part) => part.text)) } export function renderUpdate( diff --git a/packages/core/src/persistent-pty/index.ts b/packages/core/src/persistent-pty/index.ts index 90c0014de64a..ed32f155d9db 100644 --- a/packages/core/src/persistent-pty/index.ts +++ b/packages/core/src/persistent-pty/index.ts @@ -2,10 +2,11 @@ export * as PersistentPty from "./index.js" import { stat } from "node:fs/promises" import path from "node:path" -import { Context, Effect, Layer, Schema } from "effect" +import { Context, Effect, Layer, Schema, Stream } from "effect" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Added, Handoff, PersistentPty, ReadLines, Removed, type ReadResult } from "@opencode/schema/persistent-pty" import { Session } from "@opencode/schema/session" +import { SessionEvent } from "@opencode/schema/session-event" import { Bus } from "../bus.js" import { Pty } from "@opencode/schema/pty" import { Global } from "@opencode/util/global" @@ -338,6 +339,38 @@ const makeLayer = (options: Options = {}) => ) } + const removeSession = (sessionID: Session.ID) => + list(sessionID).pipe( + Effect.flatMap((terminals) => + Effect.forEach( + terminals, + (terminal) => + remove(terminal.id).pipe( + Effect.catchTags({ + "PersistentPty.NotFoundError": () => Effect.void, + "PersistentPty.UnavailableError": (error) => + Effect.logWarning("failed to remove deleted session's terminal", { + sessionID, + id: terminal.id, + error: error.message, + }), + }), + ), + { discard: true }, + ), + ), + Effect.catchTag("PersistentPty.UnavailableError", (error) => + Effect.logWarning("failed to list deleted session's terminals", { sessionID, error: error.message }), + ), + Effect.ensuring(Effect.sync(() => current.delete(sessionID))), + ) + + // Errors are handled per event so one failed cleanup does not end the subscription. + yield* bus.subscribe(SessionEvent.Deleted).pipe( + Stream.runForEach((event) => removeSession(event.data.sessionID)), + Effect.forkScoped({ startImmediately: true }), + ) + const attach = Effect.fn("PersistentPty.attach")(function* ( id: Pty.ID, input: Parameters[1], diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index 8a01fb384def..6ee27e4aeb94 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -99,6 +99,7 @@ import { GoalPlugin } from "./goal.js" import { ModelsDevPlugin } from "./models-dev.js" import { McpCodeModeDefaultsPlugin } from "./mcp-codemode-defaults.js" import { ProviderPlugins } from "./provider.js" +import { DynamicProviderPlugin } from "./provider/dynamic.js" import { OpencodePlugin } from "./provider/opencode.js" import { WebSearchPlugins } from "./websearch/index.js" import { SkillPlugin } from "./skill.js" @@ -276,6 +277,8 @@ const post = [ ConfigCompatibilityPlugin.Plugin, ConfigSkillPlugin.Plugin, ConfigProviderPlugin.Plugin, + // Run the dynamic npm SDK loader after SDK, instance, and external plugins register their `sdk` hooks. + DynamicProviderPlugin, ConfigWebSearchPlugin.Plugin, ConfigPolicyPlugin.Plugin, ] as const satisfies readonly InternalPlugin[] diff --git a/packages/core/src/plugin/provider.ts b/packages/core/src/plugin/provider.ts index 60501ab4beaa..f08ae559e5c9 100644 --- a/packages/core/src/plugin/provider.ts +++ b/packages/core/src/plugin/provider.ts @@ -2,11 +2,11 @@ import { AmazonBedrockPlugin } from "./provider/amazon-bedrock.js" import { AzurePlugin } from "./provider/azure.js" import { CerebrasPlugin } from "./provider/cerebras.js" import { ChatGPTPlugin } from "./provider/chatgpt.js" +import { ClaudeAgentPlugin } from "./provider/claude-agent/index.js" import { CloudflareAIGatewayPlugin } from "./provider/cloudflare-ai-gateway.js" import { CloudflareWorkersAIPlugin } from "./provider/cloudflare-workers-ai.js" import { DatabricksPlugin } from "./provider/databricks.js" import { DigitalOceanPlugin } from "./provider/digitalocean.js" -import { DynamicProviderPlugin } from "./provider/dynamic.js" import { GithubCopilotPlugin } from "./provider/github-copilot.js" import { GitLabPlugin } from "./provider/gitlab.js" import { GoogleVertexPlugin } from "./provider/google-vertex.js" @@ -60,5 +60,5 @@ export const ProviderPlugins: PluginInternal.InternalPlugin[] = [ VLLMPlugin, XAIPlugin, ZenmuxPlugin, - DynamicProviderPlugin, + ClaudeAgentPlugin, ] diff --git a/packages/core/src/plugin/provider/claude-agent/aisdk.ts b/packages/core/src/plugin/provider/claude-agent/aisdk.ts new file mode 100644 index 000000000000..1802cb8760bf --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/aisdk.ts @@ -0,0 +1,33 @@ +export * as ClaudeAISDK from "./aisdk.js" + +import type { Context } from "@opencode/plugin/effect/plugin" +import { Effect } from "effect" +import { ClaudeQueryOptions } from "./claude/query-options.js" +import type { ClaudeSessions } from "./claude/sessions.js" +import { ClaudeAgentLanguageModel } from "./language-model/claude-agent-language-model.js" +import { ClaudeProvider } from "./provider.js" + +export const register = Effect.fn("ClaudeAISDK.register")(function* (ctx: Context, sessions: ClaudeSessions.Interface) { + const context = yield* Effect.context() + const run = Effect.runPromiseWith(context) + const dependencies: ClaudeAgentLanguageModel.Dependencies = { + run: (request, signal) => run(sessions.run(request), { signal }), + } + yield* ctx.aisdk.hook( + "sdk", + (evt) => + Effect.sync(() => { + if (evt.package !== ClaudeProvider.PACKAGE) return + // opencode spreads the model's settings into options, next to the configured headers and body + const connection = ClaudeQueryOptions.connectionEnv({ + settings: evt.options, + headers: evt.options.headers, + body: evt.options.body, + }) + evt.sdk = { + languageModel: (modelID: string) => new ClaudeAgentLanguageModel.Model(modelID, dependencies, connection), + } + }), + { providerID: ClaudeProvider.ID }, + ) +}) diff --git a/packages/core/src/plugin/provider/claude-agent/claude/agent-sdk.ts b/packages/core/src/plugin/provider/claude-agent/claude/agent-sdk.ts new file mode 100644 index 000000000000..4c37d1e89f9d --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/agent-sdk.ts @@ -0,0 +1 @@ +export * from "@anthropic-ai/claude-agent-sdk" diff --git a/packages/core/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts b/packages/core/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts new file mode 100644 index 000000000000..6f83c9da032a --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts @@ -0,0 +1,4 @@ +export type * from "@anthropic-ai/claude-agent-sdk" + +// workerd cannot spawn the claude process, and the Claude Agent plugin skips itself there. +throw new Error("The Claude Agent SDK is unavailable on the workerd runtime") diff --git a/packages/core/src/plugin/provider/claude-agent/claude/fork.ts b/packages/core/src/plugin/provider/claude-agent/claude/fork.ts new file mode 100644 index 000000000000..3da0bd6c83a6 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/fork.ts @@ -0,0 +1,34 @@ +export * as ClaudeFork from "./fork.js" + +import { ClaudeSDK } from "./sdk.js" + +export interface Result { + readonly sessionID: string + readonly messages: ReadonlyMap +} + +// The SDK gives forked messages fresh UUIDs. Verify the copied prefix before mapping checkpoints onto them. +export async function create(sessionID: string, messageID: string): Promise { + const { deleteSession, forkSession, getSessionMessages } = await ClaudeSDK.load() + const source = await getSessionMessages(sessionID) + const end = source.findIndex((message) => message.uuid === messageID) + if (end < 0) return + const fork = await forkSession(sessionID, { upToMessageId: messageID }) + try { + const copied = await getSessionMessages(fork.sessionId) + if (copied.length !== end + 1) throw new Error("Claude fork did not preserve the requested history boundary") + const messages = new Map() + for (let i = 0; i < copied.length; i++) { + const before = source[i]! + const after = copied[i]! + if (before.type !== after.type || JSON.stringify(before.message) !== JSON.stringify(after.message)) { + throw new Error("Claude fork changed the copied conversation") + } + messages.set(before.uuid, after.uuid) + } + return { sessionID: fork.sessionId, messages } + } catch (error) { + await deleteSession(fork.sessionId) + throw error + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/io.ts b/packages/core/src/plugin/provider/claude-agent/claude/io.ts new file mode 100644 index 000000000000..d71878e0eae9 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/io.ts @@ -0,0 +1,32 @@ +export * as ClaudeIO from "./io.js" + +import type { Options } from "@anthropic-ai/claude-agent-sdk" +import { which } from "../../../../util/which.js" +import { ClaudeFork } from "./fork.js" +import { ClaudeSDK } from "./sdk.js" + +// Everything that reaches outside opencode. Tests swap it for a fake `claude`. +export interface Interface { + // Undefined uses the SDK's own spawn + readonly spawn?: Options["spawnClaudeCodeProcess"] + readonly which: () => string | undefined + // Before our isolation settings + readonly env: () => Record + readonly sessionExists: (sessionID: string) => Promise + readonly fork: (sessionID: string, messageID: string) => Promise + readonly remove: (sessionID: string) => Promise +} + +export const real: Interface = { + which: () => process.env.OPENCODE_CLAUDE_PATH || which("claude") || undefined, + env: () => process.env, + sessionExists: async (sessionID) => { + const { getSessionInfo } = await ClaudeSDK.load() + return (await getSessionInfo(sessionID)) !== undefined + }, + fork: ClaudeFork.create, + remove: async (sessionID) => { + const { deleteSession } = await ClaudeSDK.load() + await deleteSession(sessionID) + }, +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/probe.ts b/packages/core/src/plugin/provider/claude-agent/claude/probe.ts new file mode 100644 index 000000000000..a2f0e0c2854c --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/probe.ts @@ -0,0 +1,117 @@ +export * as ClaudeProbe from "./probe.js" + +import type { AccountInfo, ModelInfo, Options, Query } from "@anthropic-ai/claude-agent-sdk" +import { Effect, Schema } from "effect" +import { ClaudeSDK } from "./sdk.js" + +export interface Model extends ModelInfo { + contextWindow?: number +} + +export interface Result { + readonly version: string | undefined + readonly account: AccountInfo + readonly models: readonly Model[] +} + +export class ProbeError extends Schema.TaggedError()("ClaudeProbe.ProbeError", { + cause: Schema.Defect(), +}) {} + +// Older binaries silently ignore verbatimPrompts and can interpret user text as Claude commands. +const MINIMUM_VERSION = "2.1.248" +// Older binaries do not support summary-only context usage. Their models keep the conservative fallback. +const CONTEXT_DISCOVERY_VERSION = "2.1.257" + +export function versionError(version: string | undefined) { + if (version && atLeast(version, MINIMUM_VERSION)) return + const message = version + ? `Claude Code ${version} is too old; ${MINIMUM_VERSION} or later is required.` + : "Claude Code did not report its version, so compatibility could not be checked." + return new Error(`${message} Run \`claude update\`.`) +} + +// Compares release numbers like 2.1.248. A pre-release or build suffix is ignored. +function atLeast(version: string, minimum: string) { + const parse = (value: string) => value.split(/[-+]/)[0].split(".").map(Number) + const current = parse(version) + const required = parse(minimum) + const index = required.findIndex((part, position) => (current[position] ?? 0) !== part) + return index === -1 || (current[index] ?? 0) > required[index] +} + +// The input never sends a message, so no model call is made and no tokens are used. +export const run = Effect.fn("ClaudeProbe.run")(function* (options: Options) { + const stop = Promise.withResolvers() + return yield* Effect.acquireUseRelease( + Effect.tryPromise({ + try: async () => { + const { query } = await ClaudeSDK.load() + return query({ prompt: waitFor(stop.promise), options: { ...options, persistSession: false } }) + }, + catch: (cause) => new ProbeError({ cause }), + }), + (session) => + Effect.gen(function* () { + const init = yield* Effect.tryPromise({ + try: () => session.initializationResult(), + catch: (cause) => new ProbeError({ cause }), + }).pipe( + Effect.timeoutOrElse({ + duration: "30 seconds", + orElse: () => Effect.fail(new ProbeError({ cause: new Error("claude did not start within 30 seconds") })), + }), + ) + // No prompt is sent here, so an old Claude Code can still list its models. + // The version is checked when a chat starts, and that chat's error tells the user to update. + const version = init.claude_code_version + const models: Model[] = init.models.map((model) => ({ ...model })) + if (version && atLeast(version, CONTEXT_DISCOVERY_VERSION)) yield* discoverContext(session, models) + return { version, account: init.account, models } satisfies Result + }), + (session) => + Effect.sync(() => { + stop.resolve() + session.close() + }), + ) +}) + +// Sets each model's context window in place, so models discovered before a timeout keep theirs. +const discoverContext = Effect.fn("ClaudeProbe.discoverContext")( + function* (session: Query, models: readonly Model[]) { + for (const model of models) { + if (model.value === "default") continue + yield* Effect.tryPromise(async () => { + await session.setModel(model.value) + const usage = await session.getContextUsage({ detail: "summary" }) + // rawMaxTokens is capacity; maxTokens can reflect Claude's own compaction window. + if (!Number.isSafeInteger(usage.rawMaxTokens) || usage.rawMaxTokens <= 0) { + throw new Error("Claude Code did not report a valid context window") + } + model.contextWindow = usage.rawMaxTokens + }).pipe( + Effect.catch((error) => + Effect.logWarning("Claude Code context discovery failed", { + model: model.value, + cause: error.cause, + }), + ), + ) + } + }, + Effect.timeoutOrElse({ + duration: "30 seconds", + // A stuck control must not become a login failure. Closing this query cancels the pending request. + orElse: () => + Effect.logWarning("Claude Code context discovery timed out; undiscovered models use conservative limits"), + }), +) + +export function isLoggedIn(account: AccountInfo) { + return account.tokenSource !== "none" || account.apiKeySource !== undefined +} + +async function* waitFor(done: Promise): AsyncGenerator { + await done +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts b/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts new file mode 100644 index 000000000000..ef0a9b875419 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/query-options.ts @@ -0,0 +1,109 @@ +export * as ClaudeQueryOptions from "./query-options.js" + +import type { LanguageModelV3FunctionTool } from "@ai-sdk/provider" +import type { Options } from "@anthropic-ai/claude-agent-sdk" +import { ToolHooks } from "../tools/hooks.js" +import type { PendingTools } from "../tools/pending.js" +import { ToolServer } from "../tools/server.js" +import type { ClaudeIO } from "./io.js" + +// Claude Code features that duplicate opencode's. opencode's version wins (specs/v2/claude-agent-provider.md, "Turned Off"). +const ISOLATION_ENV = { + CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", + CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", + DISABLE_AUTO_COMPACT: "1", + CLAUDE_CODE_ENABLE_AWAY_SUMMARY: "0", + ENABLE_TOOL_SEARCH: "false", + CLAUDE_CODE_DISABLE_ADVISOR_TOOL: "1", + // Raised so opencode's own truncation applies instead + MAX_MCP_OUTPUT_TOKENS: "200000", + // Skips OAuth, so the subscription would not be used + CLAUDE_CODE_SIMPLE: undefined, + // A shell-level effort override would take precedence over OpenCode's live effort settings. + CLAUDE_CODE_EFFORT_LEVEL: undefined, + // Caps every OpenCode tool call, which would fail subagents and permission prompts that run longer + MCP_TOOL_TIMEOUT: undefined, +} + +export function connectionEnv(connection: { + readonly settings?: Readonly> + readonly headers?: Readonly> + readonly body?: Readonly> +}): Record { + const env: Record = {} + const settings = connection.settings ?? {} + if (typeof settings.baseURL === "string") env.ANTHROPIC_BASE_URL = settings.baseURL + if (typeof settings.apiKey === "string") env.ANTHROPIC_API_KEY = settings.apiKey + if (typeof settings.authToken === "string") env.ANTHROPIC_AUTH_TOKEN = settings.authToken + if (typeof settings.headerTimeout === "number") env.API_TIMEOUT_MS = String(settings.headerTimeout) + if (typeof settings.chunkTimeout === "number") env.CLAUDE_STREAM_IDLE_TIMEOUT_MS = String(settings.chunkTimeout) + const headers: string[] = [] + for (const [name, value] of Object.entries(connection.headers ?? {})) { + headers.push(`${name}: ${value}`) + } + if (headers.length > 0) env.ANTHROPIC_CUSTOM_HEADERS = headers.join("\n") + if (connection.body !== undefined && Object.keys(connection.body).length > 0) { + env.CLAUDE_CODE_EXTRA_BODY = JSON.stringify(connection.body) + } + return env +} + +export function base(input: { + executable: string + io: ClaudeIO.Interface + connection?: Readonly> +}): Options { + return { + pathToClaudeCodeExecutable: input.executable, + spawnClaudeCodeProcess: input.io.spawn, + env: { ...input.io.env(), ...input.connection, ...ISOLATION_ENV }, + settingSources: [], + settings: { disableAllHooks: true }, + // Without summaries, OpenCode has no reasoning text to display + thinking: { type: "adaptive", display: "summarized" }, + strictMcpConfig: true, + skills: [], + tools: [], + permissionMode: "dontAsk", + allowedTools: ["mcp__opencode__*"], + verbatimPrompts: true, + } +} + +export async function session(input: { + readonly executable: string + readonly io: ClaudeIO.Interface + readonly connection?: Readonly> + readonly directory: string + readonly model: string + readonly effort?: Options["effort"] + readonly maxOutputTokens?: number + readonly system: NonNullable + readonly tools: readonly LanguageModelV3FunctionTool[] + readonly pending: PendingTools.Interface + // Side calls run without saving a transcript + readonly persist: boolean + readonly resume?: string +}): Promise { + const options: Options = { + ...base(input), + cwd: input.directory, + model: input.model, + effort: input.effort, + systemPrompt: input.system, + includePartialMessages: true, + persistSession: input.persist, + hooks: ToolHooks.make(input.pending), + mcpServers: {}, + } + if (input.maxOutputTokens !== undefined) { + options.env = { ...options.env, CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(input.maxOutputTokens) } + } + if (input.tools.length > 0) options.mcpServers = { opencode: await ToolServer.make(input.tools, input.pending) } + if (input.resume !== undefined) { + options.resume = input.resume + return options + } + options.sessionId = crypto.randomUUID() + return options +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/sdk.ts b/packages/core/src/plugin/provider/claude-agent/claude/sdk.ts new file mode 100644 index 000000000000..959f7ab33b54 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/sdk.ts @@ -0,0 +1,17 @@ +export * as ClaudeSDK from "./sdk.js" + +import type * as SDK from "@anthropic-ai/claude-agent-sdk" + +// Loaded on first use, so opencode starts without loading the SDK. +let sdk: Promise | undefined + +export function load() { + sdk ??= import("#claude-agent-sdk").catch((cause) => { + // Let the next request try again, for example after the SDK is installed. + sdk = undefined + throw new Error("Claude Agent SDK isn't installed. Install @anthropic-ai/claude-agent-sdk to use Claude Agent.", { + cause, + }) + }) + return sdk +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/session.ts b/packages/core/src/plugin/provider/claude-agent/claude/session.ts new file mode 100644 index 000000000000..afdf9acdde97 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/session.ts @@ -0,0 +1,162 @@ +export * as ClaudeSession from "./session.js" + +import type { LanguageModelV3FunctionTool } from "@ai-sdk/provider" +import type { Options, SDKMessage, SDKResultMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk" +import { ToolNames } from "../tools/names.js" +import { ClaudeProbe } from "./probe.js" +import { ClaudeSDK } from "./sdk.js" + +interface Turn { + readonly drained: PromiseWithResolvers + readonly messages: SDKMessage[] + wake?: () => void + finished: boolean +} + +export type Interface = Awaited> + +export async function start(options: Options) { + const { query } = await ClaudeSDK.load() + let input!: ReadableStreamDefaultController + const prompt = new ReadableStream({ + start(controller) { + input = controller + }, + }) + const session = query({ prompt, options }) + let turn: Turn | undefined + let initialized = false + let ended = false + let failure: unknown + let stopping: Promise | undefined + let persisted = false + const ready = session.initializationResult().then((init): ClaudeProbe.Result => { + const error = ClaudeProbe.versionError(init.claude_code_version) + if (error) throw error + initialized = true + return { version: init.claude_code_version!, account: init.account, models: init.models } + }) + // A cancel during startup can stop the session before anything awaits ready. + ready.catch(() => {}) + + function finishTurn() { + if (!turn) return + turn.finished = true + turn.drained.resolve() + } + + // The only reader of the SDK iterator, including while a turn is being cancelled. + async function readAll() { + try { + for await (const message of session) { + if (turn) { + turn.messages.push(message) + turn.wake?.() + } + if (message.type === "assistant" || message.type === "result") persisted = true + if (message.type === "result") finishTurn() + } + } catch (error) { + failure = error + } finally { + ended = true + finishTurn() + turn?.wake?.() + } + } + const pump = readAll() + + async function interrupt() { + const active = turn + if (!active || active.finished || ended) return + await session.interrupt() + // interrupt() resolves before the result and transcript flush, so wait for the drain before another turn starts. + await active.drained.promise + } + + async function shutdown() { + try { + if (initialized && !ended) { + await session.interrupt() + if (turn && !turn.finished) await turn.drained.promise + } + input.close() + // An uninitialized process has no conversation to flush. + if (!initialized) session.close() + await pump + } finally { + session.close() + } + } + + function stop() { + if (!stopping) stopping = shutdown() + return stopping + } + + function begin(content: SDKUserMessage["message"]["content"], uuid = crypto.randomUUID()) { + if (ended || stopping) throw failure ?? new Error("Claude Code session has stopped") + if (turn && !turn.finished) throw new Error("Claude Code is still finishing the previous turn") + turn = { drained: Promise.withResolvers(), messages: [], finished: false } + input.enqueue({ type: "user", uuid, message: { role: "user", content }, parent_tool_use_id: null }) + } + + async function readStep( + emit: (message: SDKMessage) => void, + tools: readonly LanguageModelV3FunctionTool[], + ): Promise { + const active = turn + if (!active) throw new Error("No Claude turn to read") + let calledTools = false + while (true) { + const message = active.messages.shift() + if (!message) { + if (ended) throw failure ?? new Error("Claude Code stopped before finishing its reply") + await new Promise((resolve) => { + active.wake = resolve + }) + continue + } + emit(message) + if (message.type === "assistant" && message.parent_tool_use_id === null) { + for (const part of message.message.content) { + // Calls to tools we did not offer get Claude Code's own error, and the turn continues without OpenCode. + if (part.type === "tool_use" && ToolNames.original(part.name, tools)) calledTools = true + } + } + const replyEnded = + message.type === "stream_event" && message.parent_tool_use_id === null && message.event.type === "message_stop" + if (calledTools && replyEnded) return "tools" + if (message.type === "result") return message + } + } + + return { + id: options.resume ?? options.sessionId!, + ready, + get ended() { + return ended + }, + get persisted() { + return persisted + }, + get running() { + return !!turn && !turn.finished + }, + begin, + readStep, + addUser(content: SDKUserMessage["message"]["content"], uuid: NonNullable) { + input.enqueue({ + type: "user", + uuid, + priority: "next", + message: { role: "user", content }, + parent_tool_use_id: null, + }) + }, + interrupt, + stop, + setModel: (model: string) => session.setModel(model), + setEffort: (effort: Options["effort"]) => session.applyFlagSettings({ effortLevel: effort ?? null }), + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/sessions.ts b/packages/core/src/plugin/provider/claude-agent/claude/sessions.ts new file mode 100644 index 000000000000..b9204b05766d --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/sessions.ts @@ -0,0 +1,467 @@ +export * as ClaudeSessions from "./sessions.js" + +import type { Options, SDKMessage } from "@anthropic-ai/claude-agent-sdk" +import type { + LanguageModelV3FunctionTool, + LanguageModelV3Prompt, + LanguageModelV3TextPart, + LanguageModelV3ToolCallPart, +} from "@ai-sdk/provider" +import { Effect, Fiber, Semaphore } from "effect" +import { ClaudeIO } from "./io.js" +import type { ClaudeStatus } from "./status.js" +import { ClaudeQueryOptions } from "./query-options.js" +import { ClaudeSession } from "./session.js" +import { SessionRecord } from "../sync/record.js" +import { Checkpoints } from "../sync/checkpoints.js" +import { SyncDecision } from "../sync/decide.js" +import { CatchUp } from "../sync/catch-up.js" +import { ConvertToClaudeMessage } from "../language-model/convert-to-claude-message.js" +import { PendingTools } from "../tools/pending.js" +import { ToolNames } from "../tools/names.js" +import { ToolResult } from "../tools/result.js" + +export const HANDOVER_MS = 10_000 +export const IDLE_MS = 5 * 60_000 + +export interface Request { + // Only primary calls have one. Side calls run in a throwaway process. + readonly sessionID?: string + // Native OpenCode fork lineage, or the session supplying a compaction/generate snapshot. + readonly sourceID?: string + readonly compaction?: boolean + readonly model: string + readonly effort?: Options["effort"] + readonly maxOutputTokens?: number + readonly connection?: Readonly> + readonly system: NonNullable + readonly prompt: LanguageModelV3Prompt + readonly tools: readonly LanguageModelV3FunctionTool[] + readonly emit: (message: SDKMessage) => void +} + +interface LiveProcess { + readonly session: ClaudeSession.Interface + readonly pending: PendingTools.Interface + model: string + effort?: Options["effort"] + // Settings that need a new process to change. Model and effort change on the running one. + readonly launch: string + waiting?: string[] +} + +interface ToolContinuation { + readonly end: number + readonly results: Array<{ id: string; result: ToolResult.Result }> +} + +interface Entry { + readonly lock: Semaphore.Semaphore + process?: LiveProcess + record?: SessionRecord.Record + idle?: Fiber.Fiber + active?: Fiber.Fiber +} + +export interface Interface { + readonly run: (request: Request) => Effect.Effect + // OpenCode stopped running the session, so a turn still waiting for tool results will not get them. + readonly idle: (sessionID: string) => Effect.Effect +} + +const launch = (request: Request) => + JSON.stringify([request.maxOutputTokens, request.connection, request.system, request.tools]) + +const toError = (error: unknown) => (error instanceof Error ? error : new Error(String(error))) +const attempt = (run: () => Promise) => Effect.tryPromise({ try: run, catch: toError }) +const attemptSync = (run: () => A) => Effect.try({ try: run, catch: toError }) + +export function registry() { + const entries = new Map() + // Side calls share startup/draining with chat, but are tracked only until their request ends. + const temporary = new Set() + let owners = 0 + let handover: Fiber.Fiber | undefined + + const interrupt = Effect.fn("ClaudeSessions.interrupt")(function* (entry: Entry) { + const process = entry.process + if (!process) return + yield* attempt(() => process.session.interrupt()) + process.pending.clear() + process.waiting = undefined + }, Effect.uninterruptible) + + const stop = Effect.fn("ClaudeSessions.stop")(function* (entry: Entry) { + const process = entry.process + if (!process) return + yield* attempt(() => process.session.stop()).pipe( + Effect.ensuring( + Effect.sync(() => { + process.pending.clear() + entry.process = undefined + }), + ), + ) + }, Effect.uninterruptible) + + const armIdle = Effect.fn("ClaudeSessions.armIdle")(function* (entry: Entry) { + if (entry.idle) yield* Fiber.interrupt(entry.idle) + entry.idle = yield* Effect.sleep(IDLE_MS).pipe( + Effect.andThen(entry.lock.withPermit(stop(entry))), + Effect.catch((error) => Effect.logWarning(error)), + Effect.forkDetach, + ) + }) + + const closeEntries = Effect.fn("ClaudeSessions.closeEntries")(function* () { + for (const entry of [...entries.values(), ...temporary]) { + if (entry.active) yield* Fiber.interrupt(entry.active) + // The active turn's finalizer can install a new idle timer. + if (entry.idle) yield* Fiber.interrupt(entry.idle) + yield* entry.lock.withPermit(stop(entry)).pipe(Effect.catch((error) => Effect.logWarning(error))) + } + entries.clear() + }) + + const cancelHandover = Effect.fn("ClaudeSessions.cancelHandover")(function* () { + if (!handover) return + yield* Fiber.interrupt(handover) + handover = undefined + }) + + const close = Effect.fn("ClaudeSessions.close")(function* () { + yield* cancelHandover() + yield* closeEntries() + }) + + const attach = Effect.fn("ClaudeSessions.attach")(function* (input: { + readonly io: ClaudeIO.Interface + readonly status: ClaudeStatus.Interface + readonly storage: SessionRecord.Storage + readonly directory: string + }) { + const records = SessionRecord.make(input.storage) + owners++ + yield* cancelHandover() + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + owners-- + if (owners !== 0) return + if (entries.size === 0 && temporary.size === 0) return + handover = yield* Effect.sleep(HANDOVER_MS).pipe(Effect.andThen(closeEntries()), Effect.forkDetach) + }), + ) + + const open = Effect.fn("ClaudeSessions.open")(function* (entry: Entry, request: Request) { + const starting = !entry.process + // A cancel can only land while waiting for ready, so a started process is always recorded and stopped. + const opened = yield* Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + if (!entry.process) { + const executable = input.io.which() + if (!executable) { + yield* input.status.report({ type: "missing" }) + return yield* Effect.fail(new Error("Install Claude Code and run `claude auth login` first")) + } + const pending = PendingTools.make() + const session = yield* attempt(async () => + ClaudeSession.start( + await ClaudeQueryOptions.session({ + executable, + io: input.io, + connection: request.connection, + directory: input.directory, + model: request.model, + effort: request.effort, + maxOutputTokens: request.maxOutputTokens, + system: request.system, + tools: request.tools, + pending, + persist: request.sessionID !== undefined, + resume: entry.record?.claudeSessionID, + }), + ), + ) + entry.process = { session, pending, model: request.model, effort: request.effort, launch: launch(request) } + } + const process = entry.process + const probe = yield* restore( + attempt(() => process.session.ready).pipe( + Effect.timeoutOrElse({ + duration: "30 seconds", + orElse: () => Effect.fail(new Error("claude did not start within 30 seconds")), + }), + ), + ).pipe(Effect.onError(() => stop(entry).pipe(Effect.ignore))) + return { process, probe } + }), + ) + const process = opened.process + // A new process reports its version, login and models, which keeps the model list current without a separate check. + if (starting) yield* input.status.report({ type: "ready", probe: opened.probe }) + // Apply controls before sending input or releasing parked tool results. + if (process.model !== request.model) { + yield* attempt(() => process.session.setModel(request.model)) + process.model = request.model + } + if (process.effort !== request.effort) { + yield* attempt(() => process.session.setEffort(request.effort)) + process.effort = request.effort + } + return process + }) + + const turn = Effect.fn("ClaudeSessions.turn")(function* ( + entry: Entry, + request: Request, + start: number, + continuation?: ToolContinuation, + ) { + // Validate before opening a process: a rejected rebuild must not pair an empty process with the old record. + const content = yield* attemptSync(() => { + if (request.sessionID || entry.record) return CatchUp.content(request.prompt, continuation?.end ?? start) + return ConvertToClaudeMessage.content(request.prompt) + }) + const live = yield* open(entry, request) + const session = live.session + + const addsUserMessage = !continuation || content.length > 0 + const userID = addsUserMessage ? crypto.randomUUID() : undefined + + const reply: Array = [] + const toolMessages = new Map() + const seen = new Set() + let messageID: string | undefined + const waiting: string[] = [] + + const emit = (message: SDKMessage) => { + if (message.type === "system" && message.subtype === "init" && request.tools.length > 0) { + const connected = message.mcp_servers.some( + (server) => server.name === "opencode" && server.status === "connected", + ) + if (!connected) throw new Error("The OpenCode tool server did not connect to Claude Code") + } + if ( + message.type === "assistant" && + message.parent_tool_use_id === null && + !message.error && + !seen.has(message.uuid) + ) { + seen.add(message.uuid) + messageID = message.uuid + for (const part of message.message.content) { + if (part.type === "text") { + reply.push({ type: "text", text: part.text }) + continue + } + if (part.type !== "tool_use") continue + const name = ToolNames.original(part.name, request.tools) + if (!name) continue + live.pending.expect(part.id, part.name) + waiting.push(part.id) + reply.push({ type: "tool-call", toolCallId: part.id, toolName: name, input: part.input }) + } + } + if (message.type === "user" && message.uuid && Array.isArray(message.message.content)) { + for (const part of message.message.content) { + if (part.type === "tool_result") toolMessages.set(part.tool_use_id, message.uuid) + } + } + request.emit(message) + } + + let completed = false + let interrupted = false + let started = false + let parked = false + const step = Effect.gen(function* () { + if (!continuation) session.begin(content, userID) + if (continuation) { + if (userID !== undefined) session.addUser(content, userID) + for (const item of continuation.results) { + live.pending.resolve(item.id, item.result) + } + } + started = true + const outcome = yield* attempt(() => session.readStep(emit, request.tools)) + parked = outcome === "tools" + completed = true + live.waiting = parked ? waiting : undefined + }) + + // A tool boundary ends only the OpenCode step; the Claude turn waits for the results. Anything else interrupts and drains it. + const interruptUnlessParked = Effect.gen(function* () { + if (parked) return + yield* interrupt(entry).pipe(Effect.orDie) + }) + + const saveRecord = Effect.gen(function* () { + if (!request.sessionID || !session.persisted || !started) return + const history = + completed || interrupted + ? Checkpoints.build({ + prompt: request.prompt, + previous: entry.record, + userID, + reply: completed ? reply : [], + messageID: completed ? messageID : undefined, + toolMessages, + }) + : undefined + entry.record = { claudeSessionID: session.id, history, interrupted: interrupted && !completed } + yield* records.set(request.sessionID, entry.record) + }) + + yield* step.pipe( + Effect.onInterrupt(() => + Effect.sync(() => { + interrupted = true + }), + ), + Effect.ensuring(interruptUnlessParked), + Effect.ensuring(saveRecord), + ) + }) + + const release = Effect.fn("ClaudeSessions.release")(function* (entry: Entry, request: Request) { + entry.active = undefined + if (!request.sessionID) { + yield* stop(entry).pipe(Effect.catch((error) => Effect.logWarning(error))) + const sessionID = entry.record?.claudeSessionID + if (sessionID) + yield* attempt(() => input.io.remove(sessionID)).pipe(Effect.catch((error) => Effect.logWarning(error))) + temporary.delete(entry) + return + } + // A turn waiting for tool results is still busy. Subagents, permission prompts and questions can take longer + // than IDLE_MS, so idle() starts the timer once OpenCode stops running the session. + if (entry.process?.waiting) return + yield* armIdle(entry) + }) + + const branch = Effect.fn("ClaudeSessions.branch")(function* ( + entry: Entry, + request: Request, + source?: SessionRecord.Record, + ) { + const boundary = SyncDecision.boundary(request.prompt, source) + if (!source || !boundary) return 0 + // Validate catch-up input before creating a forked transcript on disk. + yield* attemptSync(() => CatchUp.content(request.prompt, boundary.start)) + const fork = yield* attempt(() => input.io.fork(source.claudeSessionID, boundary.messageID)) + if (!fork) return 0 + const history = boundary.history.map((checkpoint) => ({ + hash: checkpoint.hash, + claudeMessageID: checkpoint.claudeMessageID ? fork.messages.get(checkpoint.claudeMessageID) : undefined, + })) + entry.record = { claudeSessionID: fork.sessionID, history } + return boundary.start + }, Effect.uninterruptible) + + const snapshot = Effect.fn("ClaudeSessions.snapshot")(function* (entry: Entry, request: Request) { + const sourceID = request.sourceID + if (!sourceID) return 0 + const source = entries.get(sourceID) + const copy = Effect.gen(function* () { + // Compaction ends the old primary context. Generate only takes a read-only snapshot. + if (request.compaction && source) yield* stop(source) + const record = source?.record ?? (yield* records.get(sourceID)) + return yield* branch(entry, request, record) + }) + // Hold the source only while copying its settled prefix, never during side-call inference. + if (!source) return yield* copy + return yield* source.lock.withPermit(copy) + }) + + const prepare = Effect.fn("ClaudeSessions.prepare")(function* (entry: Entry, request: Request) { + // Retire an exited or incompatible process first: once we continue its parked turn, open() must not replace it. + if (entry.process) { + const needsRestart = entry.process.session.ended || entry.process.launch !== launch(request) + if (needsRestart) yield* stop(entry) + } + + if (!request.sessionID) { + const start = yield* snapshot(entry, request) + return { start, continuation: undefined } + } + + if (!entry.record) entry.record = yield* records.get(request.sessionID) + const decision = SyncDecision.decide(request.prompt, entry.record) + const start = yield* Effect.gen(function* () { + if (decision.kind === "fresh" || decision.kind === "changed") { + yield* stop(entry) + const previous = entry.record + entry.record = undefined + if (decision.kind === "changed") return yield* branch(entry, request, previous) + if (!previous) return yield* snapshot(entry, request) + return decision.start + } + if (entry.process || !entry.record) return decision.start + const sessionID = entry.record.claudeSessionID + const exists = yield* attempt(() => input.io.sessionExists(sessionID)) + if (exists) return decision.start + entry.record = undefined + return 0 + }) + + const live = entry.process + if (!live || !live.session.running || !live.waiting) return { start, continuation: undefined } + const collected = yield* attemptSync(() => ToolResult.collect(request.prompt, start)) + const continuation: ToolContinuation = { end: collected.end, results: [] } + for (const id of live.waiting) { + const result = collected.results.get(id) + if (!result) { + yield* stop(entry) + entry.record = undefined + return { start: 0, continuation: undefined } + } + continuation.results.push({ id, result }) + } + if (collected.aborted) { + // A stopped OpenCode turn needs a fresh Claude turn; addUser would only steer the old one. + yield* interrupt(entry) + return { start, continuation: undefined } + } + return { start, continuation } + }) + + const entryFor = (request: Request) => { + if (request.sessionID) { + const existing = entries.get(request.sessionID) + if (existing) return existing + const entry: Entry = { lock: Semaphore.makeUnsafe(1) } + entries.set(request.sessionID, entry) + return entry + } + const entry: Entry = { lock: Semaphore.makeUnsafe(1) } + temporary.add(entry) + return entry + } + + const run = Effect.fn("ClaudeSessions.run")(function* (request: Request) { + const entry = entryFor(request) + yield* entry.lock.withPermit( + Effect.gen(function* () { + if (entry.idle) { + yield* Fiber.interrupt(entry.idle) + entry.idle = undefined + } + entry.active = yield* Effect.withFiber(Effect.succeed) + const prepared = yield* prepare(entry, request) + yield* turn(entry, request, prepared.start, prepared.continuation) + }).pipe(Effect.ensuring(release(entry, request))), + ) + }) + + const idle = Effect.fn("ClaudeSessions.idle")(function* (sessionID: string) { + const entry = entries.get(sessionID) + // Other processes already have a timer, and a running request starts one when it ends. + if (!entry?.process?.waiting || entry.active) return + yield* armIdle(entry) + }) + + return { run, idle } satisfies Interface + }) + + return { attach, close } +} diff --git a/packages/core/src/plugin/provider/claude-agent/claude/status.ts b/packages/core/src/plugin/provider/claude-agent/claude/status.ts new file mode 100644 index 000000000000..8711c5883037 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/claude/status.ts @@ -0,0 +1,50 @@ +export * as ClaudeStatus from "./status.js" + +import { Effect, Semaphore, SubscriptionRef } from "effect" +import type { ClaudeIO } from "./io.js" +import { ClaudeProbe } from "./probe.js" +import { ClaudeQueryOptions } from "./query-options.js" + +export type State = + | { readonly type: "checking" } + | { readonly type: "missing" } + | { readonly type: "failed"; readonly message: string } + | { readonly type: "ready"; readonly probe: ClaudeProbe.Result } + +export interface Interface { + readonly state: SubscriptionRef.SubscriptionRef + readonly refresh: () => Effect.Effect + // What a chat's own process found when it started + readonly report: (next: State) => Effect.Effect +} + +export const make = Effect.fn("ClaudeStatus.make")(function* ( + io: ClaudeIO.Interface, + connection: () => Effect.Effect>, +) { + const state = yield* SubscriptionRef.make({ type: "checking" }) + const lock = yield* Semaphore.make(1) + + // Serialized so a reconnect checks again after startup, rather than racing it with an older account snapshot. + const refresh = Effect.fn("ClaudeStatus.refresh")(function* () { + const executable = io.which() + if (!executable) return yield* SubscriptionRef.set(state, { type: "missing" }) + const env = yield* connection() + const next = yield* ClaudeProbe.run(ClaudeQueryOptions.base({ executable, io, connection: env })).pipe( + Effect.map((probe): State => ({ type: "ready", probe })), + Effect.catch((error) => + Effect.logWarning("Claude Code login check failed", { cause: error.cause }).pipe( + Effect.as({ + type: "failed", + message: error.cause instanceof Error ? error.cause.message : String(error.cause), + }), + ), + ), + ) + yield* SubscriptionRef.set(state, next) + }, lock.withPermit) + + const report = (next: State) => SubscriptionRef.set(state, next) + + return { state, refresh, report } satisfies Interface +}) diff --git a/packages/core/src/plugin/provider/claude-agent/index.ts b/packages/core/src/plugin/provider/claude-agent/index.ts new file mode 100644 index 000000000000..ea217f5e29d0 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/index.ts @@ -0,0 +1,48 @@ +import { define } from "@opencode/plugin/effect/plugin" +import { Effect, Option, Stream } from "effect" +import { ClaudeIO } from "./claude/io.js" +import { ClaudeSessions } from "./claude/sessions.js" +import { ClaudeStatus } from "./claude/status.js" +import { ClaudeAISDK } from "./aisdk.js" +import { ClaudeInstructions } from "./instructions.js" +import { ClaudeIntegration } from "./integration.js" +import { ClaudeProvider } from "./provider.js" +import { ClaudeSessionHooks } from "./session.js" +import { Environment } from "../../../environment/index.js" +import { EnvironmentUnavailable } from "../../../environment/unavailable.js" +import { Location } from "../../../location.js" +import type { PluginInternal } from "../../internal.js" + +export const ID = "opencode.provider.claude-agent" + +// Tests pass a fake ClaudeIO here. The registry lives outside setup's scope, so a reload can adopt its processes. +// Restart tests pass their own and close it, as an exiting opencode would. +export const make = (io: ClaudeIO.Interface, registry = ClaudeSessions.registry()) => + define({ + id: ID, + effect: Effect.fn("ClaudeAgent.Plugin")(function* (ctx) { + // Claude Agent runs the local `claude` binary, so skip it where opencode cannot start local processes. + const environment = yield* Effect.serviceOption(Environment.Service) + const location = yield* Effect.serviceOption(Location.Service) + if (Option.isSome(location) && location.value.workspaceID !== undefined) return + if (Option.isSome(environment) && environment.value.spawner === EnvironmentUnavailable.spawner) return + + const status = yield* ClaudeStatus.make(io, () => ClaudeProvider.connection(ctx)) + const sessions = yield* registry.attach({ io, status, storage: ctx.storage, directory: ctx.location.directory }) + yield* ctx.event + .subscribe({ + types: ["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"], + }) + .pipe( + Stream.runForEach((event) => sessions.idle(event.data.sessionID)), + Effect.forkScoped({ startImmediately: true }), + ) + yield* ClaudeProvider.register(ctx, status, io) + yield* ClaudeIntegration.register(ctx, status) + yield* ClaudeAISDK.register(ctx, sessions) + yield* ClaudeSessionHooks.register(ctx) + yield* ClaudeInstructions.register(ctx) + }), + } satisfies PluginInternal.InternalPlugin) + +export const ClaudeAgentPlugin = make(ClaudeIO.real) diff --git a/packages/core/src/plugin/provider/claude-agent/instructions.ts b/packages/core/src/plugin/provider/claude-agent/instructions.ts new file mode 100644 index 000000000000..74f7e8a90529 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/instructions.ts @@ -0,0 +1,54 @@ +export * as ClaudeInstructions from "./instructions.js" + +import type { SystemPart } from "@opencode/ai/effect" +import type { Context } from "@opencode/plugin/effect/plugin" +import { Effect, Option, Schema } from "effect" +import { ClaudeSystemPrompt } from "./language-model/system-prompt.js" +import { ClaudeProvider } from "./provider.js" + +const KINDS = ["context", "generate", "compaction"] as const + +const InstructionsMetadata = Schema.Struct({ + experimental: Schema.Struct({ + instructions: Schema.Array(Schema.Struct({ key: Schema.String, text: Schema.String })), + }), +}) + +// Claude Code writes its own date and environment, so OpenCode's would repeat them. +const SUPPLIED_BY_CLAUDE = new Set(["core/date", "core/environment"]) + +export const register = Effect.fn("ClaudeInstructions.register")(function* (ctx: Context) { + yield* Effect.forEach( + KINDS, + (kind) => + ctx.session.hook( + kind, + (event) => + Effect.gen(function* () { + const agent = yield* ctx.agent.get({ agentID: event.agent }).pipe(Effect.orDie) + // Read the role from the resolved agent, not by guessing which prompt text is a built-in. + event.options[ClaudeSystemPrompt.AGENT_OPTION] = agent.data.system ?? "" + event.options[ClaudeSystemPrompt.INSTRUCTIONS_OPTION] = instructions(event.system) + }), + { providerID: ClaudeProvider.ID }, + ), + { discard: true }, + ) +}) + +// The first part is OpenCode's own prompt, which Claude Code's prompt replaces. +function instructions(system: ReadonlyArray) { + const texts: string[] = [] + for (const part of system.slice(1)) { + const metadata = Schema.decodeUnknownOption(InstructionsMetadata)(part.metadata) + if (Option.isNone(metadata)) { + texts.push(part.text) + continue + } + for (const source of metadata.value.experimental.instructions) { + if (SUPPLIED_BY_CLAUDE.has(source.key)) continue + texts.push(source.text) + } + } + return texts.join("\n\n") +} diff --git a/packages/core/src/plugin/provider/claude-agent/integration.ts b/packages/core/src/plugin/provider/claude-agent/integration.ts new file mode 100644 index 000000000000..3e6f09490af5 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/integration.ts @@ -0,0 +1,69 @@ +export * as ClaudeIntegration from "./integration.js" + +import type { Context } from "@opencode/plugin/effect/plugin" +import { Effect, Stream, SubscriptionRef } from "effect" +import { Bus } from "../../../bus.js" +import { Credential } from "../../../credential.js" +import { Integration } from "../../../integration.js" +import type { IntegrationConnection } from "../../../integration/connection.js" +import { ClaudeProbe } from "./claude/probe.js" +import type { ClaudeStatus } from "./claude/status.js" +import { ClaudeProvider } from "./provider.js" + +export const METHOD_ID = "claude-login" + +// The login method only records that the user chose Claude Code. The login itself belongs to `claude`, and the plugin +// never sees a token (specs/v2/claude-agent-provider.md, "Login"). +export const register = Effect.fn("ClaudeIntegration.register")(function* ( + ctx: Context, + status: ClaudeStatus.Interface, +) { + yield* ctx.integration.transform((editor) => { + editor.update(ClaudeProvider.ID, (integration) => { + integration.name = "Claude Agent" + }) + editor.method.update({ + integrationID: ClaudeProvider.ID, + method: { id: METHOD_ID, type: "external", label: "Claude Code login (claude auth login)" }, + }) + }) + + yield* SubscriptionRef.changes(status.state).pipe( + Stream.runForEach((state) => + Effect.gen(function* () { + if (state.type === "checking") return + const connection = yield* ctx.integration.connection.active(ClaudeProvider.ID) + if (!connection) return + yield* ctx.integration.connection.status({ + integrationID: ClaudeProvider.ID, + connection, + status: problem(state), + }) + }), + ), + Effect.forkScoped, + ) + + // Check again when the user connects. opencode keeps a problem per connection, so a new connection starts with + // none, and the user may have just run `claude auth login`. + const bus = yield* Bus.Service + yield* bus.subscribe(Credential.Event.Switched).pipe( + Stream.filter((event) => event.data.integrationID === Integration.ID.make(ClaudeProvider.ID)), + Stream.runForEach(() => status.refresh()), + Effect.forkScoped({ startImmediately: true }), + ) +}) + +function problem(state: ClaudeStatus.State): IntegrationConnection.Status | undefined { + if (state.type === "missing") + return { + status: "needs_auth", + message: "Claude Code is not installed. Install it, then run `claude auth login`.", + url: "https://code.claude.com/docs/en/setup", + } + // The message already says what went wrong with Claude Code. + if (state.type === "failed") return { status: "needs_auth", message: state.message } + if (state.type === "ready" && !ClaudeProbe.isLoggedIn(state.probe.account)) + return { status: "needs_auth", message: "Claude Code is not logged in. Run `claude auth login` in a terminal." } + return undefined +} diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts b/packages/core/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts new file mode 100644 index 000000000000..336cce48b670 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts @@ -0,0 +1,39 @@ +export * as ClaudeAgentError from "./claude-agent-error.js" + +import type { SDKAssistantMessageError, SDKMessage, SDKRateLimitInfo } from "@anthropic-ai/claude-agent-sdk" + +// Keep request-local diagnostics until the terminal result. A usage warning alone +// is not a failed request, and Claude Code owns any retries before this result. +export function make() { + let code: SDKAssistantMessageError | undefined + let rejected: SDKRateLimitInfo | undefined + return (message: SDKMessage): Error | undefined => { + if (message.type === "rate_limit_event") { + rejected = message.rate_limit_info.status === "rejected" ? message.rate_limit_info : undefined + } + if (message.type === "assistant" && message.parent_tool_use_id === null && message.error) code = message.error + if (message.type !== "result") return + + const status = message.subtype === "success" ? (message.api_error_status ?? undefined) : undefined + const httpError = status !== undefined && status >= 400 + if (message.subtype === "success" && !message.is_error && !httpError) return + const result = message.subtype === "success" ? message.result : message.errors.join("\n") + const failure = + status !== undefined && status >= 500 + ? (status === 529 ? "Anthropic is overloaded (529)." : `Anthropic returned HTTP ${status}.`) + + " Claude Code exhausted its retries. Try again shortly." + : result + const limited = code === "rate_limit" || (rejected && status === 429) + const window = rejected?.rateLimitType?.replaceAll("_", " ") + const limit = + limited && !failure ? `Claude Code subscription limit reached${window ? ` (${window})` : ""}.` : failure + const reset = limited && rejected?.resetsAt ? ` Resets at ${new Date(rejected.resetsAt * 1000).toISOString()}.` : "" + const billing = code === "billing_error" ? " Check your Claude plan and extra-usage settings." : "" + const auth = code === "authentication_failed" ? " Run `claude auth login` in a terminal." : "" + const text = limit + reset + billing + auth + + if (text) return new Error(text) + if (status) return new Error(`Claude Code could not finish its reply (HTTP ${status})`) + return new Error("Claude Code could not finish its reply") + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts b/packages/core/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts new file mode 100644 index 000000000000..6d743a2a34c6 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts @@ -0,0 +1,113 @@ +export * as ClaudeAgentLanguageModel from "./claude-agent-language-model.js" + +import type { + LanguageModelV3, + LanguageModelV3CallOptions, + LanguageModelV3FunctionTool, + LanguageModelV3StreamResult, +} from "@ai-sdk/provider" +import type { ClaudeSessions } from "../claude/sessions.js" +import type { EffortLevel } from "@anthropic-ai/claude-agent-sdk" +import { Provider } from "@opencode/schema/provider" +import { ConvertClaudeStream } from "./convert-claude-stream.js" +import { RequestKind } from "./request-kind.js" +import { ClaudeSystemPrompt } from "./system-prompt.js" + +export interface Dependencies { + readonly run: (request: ClaudeSessions.Request, signal: AbortSignal) => Promise +} + +export class Model implements LanguageModelV3 { + readonly specificationVersion = "v3" + readonly provider = Provider.ID.claudeAgent + readonly supportedUrls = {} + + constructor( + readonly modelId: string, + readonly dependencies: Dependencies, + readonly connection: Readonly> = {}, + ) {} + + async doGenerate(_options: LanguageModelV3CallOptions): Promise { + throw new Error("Claude Agent models only support streaming") + } + + async doStream(options: LanguageModelV3CallOptions): Promise { + const abort = new AbortController() + const signal = options.abortSignal ? AbortSignal.any([abort.signal, options.abortSignal]) : abort.signal + const tools = + options.toolChoice?.type === "none" + ? [] + : (options.tools ?? []).filter((tool): tool is LanguageModelV3FunctionTool => tool.type === "function") + const headers = options.headers ?? {} + const kind = headers[RequestKind.HEADER] + const session = headers[RequestKind.SESSION_HEADER] + const settings = options.providerOptions?.[Provider.ID.claudeAgent] + const role = settings?.[ClaudeSystemPrompt.AGENT_OPTION] + const agent = typeof role === "string" ? role : undefined + const loaded = settings?.[ClaudeSystemPrompt.INSTRUCTIONS_OPTION] + const instructions = typeof loaded === "string" ? loaded : undefined + const effort = parseEffort(settings?.effort) + const primary = kind === "primary" + const branch = kind === "generate" || kind === "compaction" + const sessionID = primary ? session : undefined + // Conversation branches copy their source session and keep the Claude prompt. OpenCode supplies their task as user input. + const sourceID = primary ? headers[RequestKind.FORK_HEADER] : branch ? session : undefined + // Branches offer the chat's tools and system prompt so Claude reuses the chat's prompt cache. + const offered = primary || branch ? tools : [] + const convert = ConvertClaudeStream.make(offered) + // Titles are standalone tasks, so OpenCode's system prompt replaces Claude Code's. + const system = + primary || branch ? ClaudeSystemPrompt.make(agent, instructions) : ClaudeSystemPrompt.utility(options.prompt) + let cancelled = false + let task: Promise + const stream = new ReadableStream({ + start: (controller) => { + controller.enqueue({ type: "stream-start", warnings: [] }) + task = this.dependencies + .run( + { + sessionID, + sourceID, + compaction: kind === "compaction", + model: this.modelId, + effort, + maxOutputTokens: options.maxOutputTokens, + connection: this.connection, + system, + prompt: options.prompt, + tools: offered, + emit: (message) => { + if (cancelled) return + for (const part of convert(message)) controller.enqueue(part) + }, + }, + signal, + ) + .then( + () => { + if (!cancelled) controller.close() + }, + (error) => { + if (!cancelled) controller.error(error) + }, + ) + }, + cancel: () => { + cancelled = true + abort.abort() + return task + }, + }) + return { stream } + } +} + +const EFFORTS: readonly EffortLevel[] = ["low", "medium", "high", "xhigh", "max"] + +function parseEffort(value: unknown): EffortLevel | undefined { + if (value === undefined) return undefined + const effort = EFFORTS.find((effort) => value === effort) + if (effort !== undefined) return effort + throw new Error("Claude Agent effort must be low, medium, high, xhigh or max") +} diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts b/packages/core/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts new file mode 100644 index 000000000000..eb1f4fb333d6 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts @@ -0,0 +1,133 @@ +export * as ConvertClaudeStream from "./convert-claude-stream.js" + +import type { LanguageModelV3FunctionTool, LanguageModelV3StreamPart } from "@ai-sdk/provider" +import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk" +import { Provider } from "@opencode/schema/provider" +import { ClaudeUsage } from "./usage.js" +import { ToolNames } from "../tools/names.js" +import { ClaudeAgentError } from "./claude-agent-error.js" + +export function make(tools: readonly LanguageModelV3FunctionTool[]) { + const usage = ClaudeUsage.make() + const failure = ClaudeAgentError.make() + const streamed = new Set() + const blocks = new Map() + let messageID = "" + let calledTools = false + let metadata: Record | undefined + + return (message: SDKMessage): LanguageModelV3StreamPart[] => { + const parts: LanguageModelV3StreamPart[] = [] + const error = failure(message) + if (error) return [{ type: "error", error }] + if (message.type === "stream_event" && message.parent_tool_use_id === null) { + const event = message.event + switch (event.type) { + case "message_start": + messageID = event.message.id + metadata = undefined + streamed.add(messageID) + usage.update(messageID, event.message.usage) + parts.push({ type: "response-metadata", id: messageID, modelId: event.message.model }) + break + case "content_block_start": { + const block = event.content_block + const id = `${messageID}:${event.index}` + if (block.type === "text") { + blocks.set(event.index, "text") + parts.push({ type: "text-start", id }) + if (block.text) parts.push({ type: "text-delta", id, delta: block.text }) + break + } + if (block.type === "thinking") { + blocks.set(event.index, "reasoning") + parts.push({ type: "reasoning-start", id }) + if (block.thinking) parts.push({ type: "reasoning-delta", id, delta: block.thinking }) + } + break + } + case "content_block_delta": { + const id = `${messageID}:${event.index}` + const delta = event.delta + if (delta.type === "text_delta") { + parts.push({ type: "text-delta", id, delta: delta.text }) + break + } + if (delta.type === "thinking_delta" && delta.thinking) { + parts.push({ type: "reasoning-delta", id, delta: delta.thinking }) + } + break + } + case "content_block_stop": { + const kind = blocks.get(event.index) + if (kind) parts.push({ type: `${kind}-end`, id: `${messageID}:${event.index}`, providerMetadata: metadata }) + blocks.delete(event.index) + break + } + case "message_delta": + usage.update(messageID, event.usage) + break + case "message_stop": + // Must match ClaudeSession.readStep's tool boundary, or OpenCode's step ends without a finish event. + if (calledTools) { + parts.push({ + type: "finish", + finishReason: { unified: "tool-calls", raw: "tool_use" }, + usage: usage.snapshot(), + }) + } + break + } + } + if (message.type === "assistant" && message.parent_tool_use_id === null) { + // Synthetic API errors are diagnostics, not assistant answers. + if (message.error) return parts + // Stream events carry API message IDs; only the complete assistant message carries the transcript UUID. + metadata = { [Provider.ID.claudeAgent]: { sessionID: message.session_id, messageID: message.uuid } } + usage.update(message.message.id, message.message.usage) + for (const block of message.message.content) { + if (block.type !== "tool_use") continue + const toolName = ToolNames.original(block.name, tools) + if (!toolName) continue + calledTools = true + parts.push({ + type: "tool-call", + toolCallId: block.id, + toolName, + input: JSON.stringify(block.input), + providerMetadata: metadata, + }) + } + // Complete assistant messages repeat the streamed content. Only use them when nothing was streamed. + if (!streamed.has(message.message.id)) { + for (let i = 0; i < message.message.content.length; i++) { + const block = message.message.content[i]! + const id = `${message.uuid}:${i}` + if (block.type === "text") { + parts.push({ type: "text-start", id }) + parts.push({ type: "text-delta", id, delta: block.text }) + parts.push({ type: "text-end", id, providerMetadata: metadata }) + continue + } + if (block.type === "thinking") { + parts.push({ type: "reasoning-start", id }) + parts.push({ type: "reasoning-delta", id, delta: block.thinking }) + parts.push({ type: "reasoning-end", id }) + } + } + } + } + if (message.type === "result") { + if (message.num_turns === 1) usage.result(message.usage) + parts.push({ + type: "finish", + finishReason: { + unified: message.stop_reason === "max_tokens" ? "length" : "stop", + raw: message.stop_reason ?? undefined, + }, + usage: usage.snapshot(), + }) + } + return parts + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts b/packages/core/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts new file mode 100644 index 000000000000..4bfadc5eb1e1 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts @@ -0,0 +1,55 @@ +export * as ConvertToClaudeMessage from "./convert-to-claude-message.js" + +import type { LanguageModelV3FilePart, LanguageModelV3Prompt } from "@ai-sdk/provider" +import type { SDKUserMessage } from "@anthropic-ai/claude-agent-sdk" + +export type ContentBlock = Exclude[number] + +// Claude can't be given earlier turns, so their roles become text tags. Attachments stay real content blocks. +export function content(prompt: LanguageModelV3Prompt): ContentBlock[] { + const blocks: ContentBlock[] = [] + const history = prompt.some((message) => message.role === "assistant" || message.role === "tool") + for (const message of prompt) { + if (message.role === "system") continue + if (history) blocks.push({ type: "text", text: `<${message.role}>` }) + for (const part of message.content) { + if (part.type === "text") { + blocks.push({ type: "text", text: part.text }) + continue + } + if (part.type === "file") { + blocks.push(file(part)) + continue + } + if (part.type === "tool-call") { + const call = JSON.stringify({ id: part.toolCallId, name: part.toolName, input: part.input }) + blocks.push({ type: "text", text: `\n${call}\n` }) + continue + } + if (part.type === "tool-result") { + const result = JSON.stringify({ id: part.toolCallId, name: part.toolName, output: part.output }) + blocks.push({ type: "text", text: `\n${result}\n` }) + } + } + if (history) blocks.push({ type: "text", text: `` }) + } + return blocks +} + +function file(part: LanguageModelV3FilePart): ContentBlock { + const type = part.mediaType + if (type === "application/pdf") { + if (part.data instanceof URL) return { type: "document", source: { type: "url", url: part.data.href } } + return { type: "document", source: { type: "base64", media_type: type, data: base64(part.data) } } + } + if (type === "image/png" || type === "image/jpeg" || type === "image/gif" || type === "image/webp") { + if (part.data instanceof URL) return { type: "image", source: { type: "url", url: part.data.href } } + return { type: "image", source: { type: "base64", media_type: type, data: base64(part.data) } } + } + throw new Error(`Claude Code does not support ${type} attachments`) +} + +function base64(data: string | Uint8Array) { + if (typeof data === "string") return data + return Buffer.from(data).toString("base64") +} diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/request-kind.ts b/packages/core/src/plugin/provider/claude-agent/language-model/request-kind.ts new file mode 100644 index 000000000000..efc0813041c3 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/request-kind.ts @@ -0,0 +1,5 @@ +export * as RequestKind from "./request-kind.js" + +export const HEADER = "x-opencode-claude-agent-kind" +export const SESSION_HEADER = "x-opencode-session-id" +export const FORK_HEADER = "x-opencode-claude-agent-fork-source" diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/system-prompt.ts b/packages/core/src/plugin/provider/claude-agent/language-model/system-prompt.ts new file mode 100644 index 000000000000..2e7f00c9c4ef --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/system-prompt.ts @@ -0,0 +1,28 @@ +export * as ClaudeSystemPrompt from "./system-prompt.js" + +import type { Options } from "@anthropic-ai/claude-agent-sdk" +import type { LanguageModelV3Prompt } from "@ai-sdk/provider" + +export const AGENT_OPTION = "claudeCodeAgent" +export const INSTRUCTIONS_OPTION = "claudeCodeInstructions" + +const primary = { + type: "preset", + preset: "claude_code", + // Agent changes must take effect when a process resumes the same native session. + snapshot: false, + append: + "You are running in OpenCode through the Claude Code harness. Mention this only when asked.", +} satisfies Options["systemPrompt"] + +export function make(role?: string, instructions?: string) { + const blocks = [primary.append] + if (role) blocks.push("# Agent role (from OpenCode)\n" + role) + if (instructions) blocks.push(instructions) + return { ...primary, append: blocks.join("\n\n") } +} + +export function utility(prompt: LanguageModelV3Prompt) { + const blocks = prompt.filter((message) => message.role === "system").map((message) => message.content) + return blocks.join("\n\n") || "You are a text generation helper. Return only the requested output." +} diff --git a/packages/core/src/plugin/provider/claude-agent/language-model/usage.ts b/packages/core/src/plugin/provider/claude-agent/language-model/usage.ts new file mode 100644 index 000000000000..ae6d64b016ed --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/language-model/usage.ts @@ -0,0 +1,58 @@ +export * as ClaudeUsage from "./usage.js" + +import type { LanguageModelV3Usage } from "@ai-sdk/provider" + +interface Usage { + readonly input_tokens?: number | null + readonly cache_read_input_tokens?: number | null + readonly cache_creation_input_tokens?: number | null + readonly output_tokens?: number + readonly output_tokens_details?: { readonly thinking_tokens?: number } | null +} + +export function make() { + const messages = new Map() + let last: string | undefined + + function update(id: string, usage: Usage) { + const saved = messages.get(id) + const counts = saved ?? { input: 0, read: 0, write: 0, output: 0, reasoning: 0 } + if (!saved) { + messages.set(id, counts) + last = id + } + counts.input = Math.max(counts.input, usage.input_tokens ?? 0) + counts.read = Math.max(counts.read, usage.cache_read_input_tokens ?? 0) + counts.write = Math.max(counts.write, usage.cache_creation_input_tokens ?? 0) + counts.output = Math.max(counts.output, usage.output_tokens ?? 0) + counts.reasoning = Math.max(counts.reasoning, usage.output_tokens_details?.thinking_tokens ?? 0) + } + + return { + update, + result(usage: Usage) { + // Result usage sums the whole turn; only apply it when there was a single model call. + if (messages.size <= 1) update(last ?? "result", usage) + }, + snapshot(): LanguageModelV3Usage { + let output = 0 + let reasoning = 0 + for (const counts of messages.values()) { + output += counts.output + reasoning += counts.reasoning + } + // Context occupancy is the last API call's input, not the sum of repeated contexts. + const lastCall = last === undefined ? undefined : messages.get(last) + const inputTotal = lastCall ? lastCall.input + lastCall.read + lastCall.write : undefined + return { + inputTokens: { + total: inputTotal, + noCache: lastCall?.input, + cacheRead: lastCall?.read, + cacheWrite: lastCall?.write, + }, + outputTokens: { total: output, reasoning, text: output - reasoning }, + } + }, + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/provider.ts b/packages/core/src/plugin/provider/claude-agent/provider.ts new file mode 100644 index 000000000000..15ed23e5203d --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/provider.ts @@ -0,0 +1,141 @@ +export * as ClaudeProvider from "./provider.js" + +import type { AccountInfo } from "@anthropic-ai/claude-agent-sdk" +import type { Context } from "@opencode/plugin/effect/plugin" +import { Effect, Option, Schema, Stream, SubscriptionRef } from "effect" +import { Model } from "../../../model.js" +import { Provider } from "../../../provider.js" +import type { ClaudeIO } from "./claude/io.js" +import type { ClaudeProbe } from "./claude/probe.js" +import { ClaudeQueryOptions } from "./claude/query-options.js" +import type { ClaudeStatus } from "./claude/status.js" + +export const ID = Provider.ID.claudeAgent +export const PACKAGE = "@opencode/claude-agent" + +// The model list we keep between starts, so opencode can list models without running `claude` +const CatalogModel = Schema.Struct({ + id: Schema.String, + name: Schema.String, + efforts: Schema.Array(Schema.String), + contextWindow: Schema.optionalKey(Schema.Number), + resolvedModel: Schema.optionalKey(Schema.String), +}) +type CatalogModel = typeof CatalogModel.Type +const Catalog = Schema.Struct({ + priceSource: Schema.optionalKey(Provider.ID), + models: Schema.Array(CatalogModel), +}) +type Catalog = typeof Catalog.Type +const CATALOG_KEY = "models" + +// Mantle is Bedrock serving Anthropic's API, and opencode drops most of its `anthropic.…` IDs from Bedrock's list, +// so it uses Anthropic's prices. +const PRICE_SOURCES: Partial, Provider.ID>> = { + firstParty: Provider.ID.anthropic, + anthropicAws: Provider.ID.anthropic, + anthropicGoogleCloud: Provider.ID.anthropic, + mantle: Provider.ID.anthropic, + bedrock: Provider.ID.amazonBedrock, + vertex: Provider.ID.googleVertex, + foundry: Provider.ID.azure, +} + +export const register = Effect.fn("ClaudeProvider.register")(function* ( + ctx: Context, + status: ClaudeStatus.Interface, + io: ClaudeIO.Interface, +) { + const saved = Schema.decodeUnknownOption(Catalog)(yield* ctx.storage.get(CATALOG_KEY)) + const current = { catalog: Option.getOrElse(saved, (): Catalog => ({ models: [] })) } + + yield* ctx.provider.transform((editor) => { + const source = current.catalog.priceSource + const prices = source ? editor.get(source)?.models : undefined + editor.add({ + info: { + id: ID, + name: "Claude Agent", + activation: "auto", + package: Provider.aisdk(PACKAGE), + }, + models: current.catalog.models.map((model) => toModel(model, prices)), + }) + }) + + yield* SubscriptionRef.changes(status.state).pipe( + Stream.runForEach((state) => + Effect.gen(function* () { + if (state.type !== "ready") return + const baseURL = (yield* connection(ctx)).ANTHROPIC_BASE_URL ?? io.env().ANTHROPIC_BASE_URL + const next = { + priceSource: priceSource(state.probe.account, baseURL), + models: fromClaude(state.probe.models, current.catalog.models), + } + if (JSON.stringify(next) === JSON.stringify(current.catalog)) return + current.catalog = next + yield* ctx.storage.set(CATALOG_KEY, current.catalog) + yield* ctx.provider.reload() + }), + ), + Effect.forkScoped, + ) + + // Without a saved list there is no model to pick, so the first message that would fill it can never be sent. + if (current.catalog.models.length === 0 && (yield* ctx.integration.connection.active(ID))) { + yield* status.refresh().pipe(Effect.forkScoped) + } +}) + +export const connection = Effect.fn("ClaudeProvider.connection")(function* (ctx: Context) { + const provider = yield* ctx.provider.get({ providerID: ID }).pipe(Effect.option) + if (Option.isNone(provider)) return {} + const info = provider.value.data + return ClaudeQueryOptions.connectionEnv({ settings: info.settings, headers: info.headers, body: info.body }) +}) + +// Context windows only come from the full check, so a chat's startup report keeps the saved ones. +function fromClaude(models: readonly ClaudeProbe.Model[], saved: readonly CatalogModel[]): CatalogModel[] { + const known = new Map() + for (const model of saved) known.set(model.id, model.contextWindow) + const result: CatalogModel[] = [] + for (const model of models) { + // "default" follows Claude Code's own default, which can change under a running opencode session + if (model.value === "default") continue + result.push({ + id: model.value, + name: model.displayName, + efforts: model.supportedEffortLevels ?? [], + contextWindow: model.contextWindow ?? known.get(model.value), + resolvedModel: model.resolvedModel, + }) + } + return result +} + +// A subscription covers usage, and a custom base URL or an enterprise gateway can bill anything, so they show no cost. +function priceSource(account: AccountInfo, baseURL: string | undefined) { + if (baseURL) return + if (account.apiProvider === undefined) return + if (account.apiProvider === "firstParty" && account.apiKeySource === undefined) return + return PRICE_SOURCES[account.apiProvider] +} + +function toModel(model: CatalogModel, prices: ReadonlyMap | undefined): Model.Info { + const defaults = Model.Info.default(ID, Model.ID.make(model.id)) + // The 1M context version's price tiers are on the base model + const id = (model.resolvedModel ?? model.id).replace(/\[1m\]$/, "") + // Mantle names models `anthropic.claude-…`, and Vertex lists current models as `claude-…@default` + const priced = prices?.get(id) ?? prices?.get(id.replace(/^anthropic\./, "")) ?? prices?.get(`${id}@default`) + return { + ...defaults, + name: model.name, + // The SDK reports context windows before a prompt, but not output limits. 0 means unknown in OpenCode. + limit: { context: model.contextWindow ?? defaults.limit.context, output: 0 }, + // OpenCode picks the title model by family (Model.small). + family: model.id.includes("haiku") ? Model.Family.make("claude-haiku") : undefined, + capabilities: { tools: true, input: ["text", "image", "pdf"], output: ["text"] }, + variants: model.efforts.map((effort) => ({ id: Model.VariantID.make(effort), settings: { effort } })), + cost: priced?.cost ?? [], + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/session.ts b/packages/core/src/plugin/provider/claude-agent/session.ts new file mode 100644 index 000000000000..6a6b9640d948 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/session.ts @@ -0,0 +1,55 @@ +export * as ClaudeSessionHooks from "./session.js" + +import type { Context } from "@opencode/plugin/effect/plugin" +import { Effect, Schema } from "effect" +import { RequestKind } from "./language-model/request-kind.js" +import { ClaudeProvider } from "./provider.js" + +// OpenCode records stopped tools (including a plain permission rejection) with this structured error. +const isAborted = Schema.is(Schema.Struct({ error: Schema.Struct({ type: Schema.Literal("aborted") }) })) + +export const register = Effect.fn("ClaudeSessionHooks.register")(function* (ctx: Context) { + yield* ctx.session.hook( + "model.request", + (event) => + Effect.gen(function* () { + event.headers[RequestKind.HEADER] = event.kind + if (event.kind !== "primary") return + const session = yield* ctx.session.get({ sessionID: event.sessionID }).pipe(Effect.orDie) + if (session.fork) event.headers[RequestKind.FORK_HEADER] = session.fork.sessionID + }), + { providerID: ClaudeProvider.ID }, + ) + yield* ctx.session.hook( + "context", + (event) => + Effect.sync(() => { + // Let Claude choose its normal output budget. Later hooks can still set an explicit maxTokens. + // Compaction has its own hook, so it keeps OpenCode's summary budget. + delete event.options.maxTokens + // Preserve tool error status before the AI SDK bridge flattens error results to plain text. + event.messages = event.messages.map((message) => { + const content = message.content.map((part) => { + if (part.type !== "tool-result" || part.result.type !== "error") return part + const flags = { + ...part.providerMetadata?.[ClaudeProvider.ID], + toolError: true, + toolAborted: isAborted(part.result.value), + } + return { ...part, providerMetadata: { ...part.providerMetadata, [ClaudeProvider.ID]: flags } } + }) + return { ...message, content } + }) + }), + { providerID: ClaudeProvider.ID }, + ) + // Claude Code already retries API failures. Replaying the whole turn here also retries permanent billing errors. + yield* ctx.session.hook( + "retry", + (event) => + Effect.sync(() => { + event.decision = { retry: false } + }), + { providerID: ClaudeProvider.ID }, + ) +}) diff --git a/packages/core/src/plugin/provider/claude-agent/sync/catch-up.ts b/packages/core/src/plugin/provider/claude-agent/sync/catch-up.ts new file mode 100644 index 000000000000..2b7de43840d1 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/sync/catch-up.ts @@ -0,0 +1,21 @@ +export * as CatchUp from "./catch-up.js" + +import type { LanguageModelV3Prompt } from "@ai-sdk/provider" +import { ConvertToClaudeMessage } from "../language-model/convert-to-claude-message.js" +import { Fingerprint } from "./fingerprint.js" + +export function content(prompt: LanguageModelV3Prompt, start = 0): ConvertToClaudeMessage.ContentBlock[] { + const missed = prompt.slice(start) + const end = Fingerprint.groups(missed).findLast((group) => group.role !== "user")?.end ?? 0 + const blocks: ConvertToClaudeMessage.ContentBlock[] = [] + if (end > 0) { + blocks.push({ + type: "text", + text: "\nThe following is conversation history from OpenCode that you have not seen. Treat it as prior conversation, not a new request. Continue with the user messages after this checkpoint.", + }) + blocks.push(...ConvertToClaudeMessage.content(missed.slice(0, end))) + blocks.push({ type: "text", text: "" }) + } + blocks.push(...ConvertToClaudeMessage.content(missed.slice(end))) + return blocks +} diff --git a/packages/core/src/plugin/provider/claude-agent/sync/checkpoints.ts b/packages/core/src/plugin/provider/claude-agent/sync/checkpoints.ts new file mode 100644 index 000000000000..8b7a76938480 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/sync/checkpoints.ts @@ -0,0 +1,41 @@ +export * as Checkpoints from "./checkpoints.js" + +import type { LanguageModelV3Prompt, LanguageModelV3TextPart, LanguageModelV3ToolCallPart } from "@ai-sdk/provider" +import { Fingerprint } from "./fingerprint.js" +import type { SessionRecord } from "./record.js" + +export function build(input: { + prompt: LanguageModelV3Prompt + previous?: SessionRecord.Record + userID?: string + reply: Array + messageID?: string + toolMessages: Map +}) { + const history: SessionRecord.Checkpoint[] = [] + const groups = Fingerprint.groups(input.prompt) + for (let i = 0; i < groups.length; i++) { + const group = groups[i]! + const previous = input.previous?.history?.[i] + let claudeMessageID: string | undefined + if (previous && previous.hash === group.hash) claudeMessageID = previous.claudeMessageID + if (group.role === "tool") { + for (const message of input.prompt.slice(group.start, group.end)) { + if (message.role !== "tool") continue + for (const part of message.content) { + if (part.type !== "tool-result") continue + const toolMessage = input.toolMessages.get(part.toolCallId) + if (toolMessage !== undefined) claudeMessageID = toolMessage + } + } + } + const isLast = i === groups.length - 1 + if (isLast && input.userID) claudeMessageID = input.userID + history.push({ hash: group.hash, claudeMessageID }) + } + if (input.reply.length > 0) { + const replyGroup = Fingerprint.groups([{ role: "assistant", content: input.reply }])[0]! + history.push({ hash: replyGroup.hash, claudeMessageID: input.messageID }) + } + return history +} diff --git a/packages/core/src/plugin/provider/claude-agent/sync/decide.ts b/packages/core/src/plugin/provider/claude-agent/sync/decide.ts new file mode 100644 index 000000000000..d54f6e0f55a8 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/sync/decide.ts @@ -0,0 +1,58 @@ +export * as SyncDecision from "./decide.js" + +import type { LanguageModelV3Prompt } from "@ai-sdk/provider" +import { Fingerprint } from "./fingerprint.js" +import type { SessionRecord } from "./record.js" + +export function decide(prompt: LanguageModelV3Prompt, record?: SessionRecord.Record) { + const saved = record?.history ?? [] + const groups = Fingerprint.groups(prompt, record?.interrupted ? saved : undefined) + if (saved.length === 0) return { kind: "fresh", start: 0 } as const + + let matched = 0 + while (matched < saved.length && matched < groups.length) { + if (saved[matched]!.hash !== groups[matched]!.hash) break + matched++ + } + if (matched === 0) return { kind: "fresh", start: 0 } as const + // Changed histories need an isolated branch, or a rebuild when no safe checkpoint survives. + if (matched < saved.length) return { kind: "changed", start: 0 } as const + + // Claude's drained transcript owns the interrupted reply, not OpenCode's partial copy. + while (record?.interrupted && groups[matched]?.role === "assistant") { + const reply = prompt[groups[matched]!.start]! + if (reply.role !== "assistant" || reply.content.some((part) => part.type === "tool-call")) break + matched++ + } + const start = groups[matched]?.start ?? prompt.length + if (record?.interrupted && start === prompt.length) return { kind: "changed", start: 0 } as const + const missed = groups.slice(matched) + const kind = missed.some((group) => group.role !== "user") ? "catch-up" : "continue" + return { kind, start } as const +} + +// A branch must not end between a native tool call and its results. +export function boundary(prompt: LanguageModelV3Prompt, record?: SessionRecord.Record) { + const groups = Fingerprint.groups(prompt) + const history = record?.history ?? [] + const pending = new Set() + let found: { messageID: string; start: number; history: readonly SessionRecord.Checkpoint[] } | undefined + for (let i = 0; i < groups.length; i++) { + const group = groups[i]! + // Undo can resubmit identical input; keep the current user group for the new turn. + if (i === groups.length - 1 && group.role === "user") break + const checkpoint = history[i] + if (!checkpoint || checkpoint.hash !== group.hash) break + for (const message of prompt.slice(group.start, group.end)) { + if (message.role === "system") continue + for (const part of message.content) { + if (part.type === "tool-call") pending.add(part.toolCallId) + if (part.type === "tool-result") pending.delete(part.toolCallId) + } + } + if (checkpoint.claudeMessageID && pending.size === 0) { + found = { messageID: checkpoint.claudeMessageID, start: group.end, history: history.slice(0, i + 1) } + } + } + return found +} diff --git a/packages/core/src/plugin/provider/claude-agent/sync/fingerprint.ts b/packages/core/src/plugin/provider/claude-agent/sync/fingerprint.ts new file mode 100644 index 000000000000..2b4a93ee95cf --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/sync/fingerprint.ts @@ -0,0 +1,117 @@ +export * as Fingerprint from "./fingerprint.js" + +import { createHash } from "node:crypto" +import type { LanguageModelV3Message, LanguageModelV3Prompt } from "@ai-sdk/provider" + +export interface Group { + readonly hash: string + readonly role: "user" | "assistant" | "tool" + readonly start: number + readonly end: number +} + +function canonical(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]` + if (value !== null && typeof value === "object") { + const object = value as Record + const fields: string[] = [] + for (const key of Object.keys(object).sort()) { + if (object[key] !== undefined) fields.push(`${JSON.stringify(key)}:${canonical(object[key])}`) + } + return `{${fields.join(",")}}` + } + return JSON.stringify(value) ?? "null" +} + +function hash(value: unknown) { + return createHash("sha256").update(canonical(value)).digest("hex") +} + +// opencode sends thinking and provider options differently depending on the target model, so they don't count. +function visible(message: Exclude) { + const parts: unknown[] = [] + let text = "" + for (const part of message.content) { + if (part.type === "reasoning") continue + if (part.type === "text") { + text += part.text + continue + } + if (text) parts.push({ type: "text", text }) + text = "" + if (part.type === "file") { + const data = + part.data instanceof URL + ? part.data.href + : typeof part.data === "string" + ? part.data + : Buffer.from(part.data).toString("base64") + parts.push({ type: part.type, mediaType: part.mediaType, data }) + continue + } + if (part.type === "tool-call") { + parts.push({ type: part.type, id: part.toolCallId, name: part.toolName, input: part.input }) + continue + } + if (part.type === "tool-result") { + const output = { ...part.output } + if ("providerOptions" in output) delete output.providerOptions + if (output.type === "content") { + output.value = output.value.map((part) => { + const item = { ...part } + delete item.providerOptions + return item + }) + } + parts.push({ type: part.type, id: part.toolCallId, name: part.toolName, output }) + } + } + if (text) parts.push({ type: "text", text }) + return parts +} + +// OpenCode lowers tool attachments into this separate user message. +function isToolMedia(message: LanguageModelV3Message) { + return ( + message.role === "user" && + message.content.length > 1 && + message.content[0]?.type === "text" && + message.content[0].text === "Attached media from tool result:" && + message.content.slice(1).every((part) => part.type === "file") + ) +} + +export function groups(prompt: LanguageModelV3Prompt, prefix: readonly { readonly hash: string }[] = []): Group[] { + const groups: Group[] = [] + let i = 0 + while (i < prompt.length) { + const message = prompt[i]! + const start = i + i++ + if (message.role === "system") continue + const parts = visible(message) + if (parts.length === 0) continue + const members = [hash(parts)] + if (message.role === "user") { + while (i < prompt.length) { + // A submitted input remains a boundary even when a later user message arrives without a visible reply. + const checkpoint = prefix[groups.length] + if (checkpoint && hash({ role: message.role, members: members.toSorted() }) === checkpoint.hash) break + const next = prompt[i]! + if (next.role !== "user") break + members.push(hash(visible(next))) + i++ + } + members.sort() + } + if (message.role === "tool") { + const next = prompt[i] + if (next && next.role === "user" && isToolMedia(next)) { + members.push(hash(visible(next))) + i++ + } + } + groups.push({ hash: hash({ role: message.role, members }), role: message.role, start, end: i }) + } + return groups +} diff --git a/packages/core/src/plugin/provider/claude-agent/sync/record.ts b/packages/core/src/plugin/provider/claude-agent/sync/record.ts new file mode 100644 index 000000000000..749e2532c29a --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/sync/record.ts @@ -0,0 +1,28 @@ +export * as SessionRecord from "./record.js" + +import { Effect, Option, Schema } from "effect" + +const Checkpoint = Schema.Struct({ hash: Schema.String, claudeMessageID: Schema.optional(Schema.String) }) +export type Checkpoint = typeof Checkpoint.Type +const Record = Schema.Struct({ + claudeSessionID: Schema.String, + history: Schema.optional(Schema.Array(Checkpoint)), + // After cancellation, Claude owns the partial reply; history ends at the input it received. + interrupted: Schema.optional(Schema.Boolean), +}) +export type Record = typeof Record.Type + +export interface Storage { + readonly get: (key: string) => Effect.Effect + readonly set: (key: string, value: Record) => Effect.Effect +} + +export function make(storage: Storage) { + return { + get: Effect.fn("SessionRecord.get")(function* (sessionID: string) { + const saved = Schema.decodeUnknownOption(Record)(yield* storage.get(`sessions/${sessionID}`)) + return Option.getOrUndefined(saved) + }), + set: (sessionID: string, record: Record) => storage.set(`sessions/${sessionID}`, record), + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/tools/hooks.ts b/packages/core/src/plugin/provider/claude-agent/tools/hooks.ts new file mode 100644 index 000000000000..f9c900e7179c --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/tools/hooks.ts @@ -0,0 +1,23 @@ +export * as ToolHooks from "./hooks.js" + +import type { HookCallback, Options } from "@anthropic-ai/claude-agent-sdk" +import type { PendingTools } from "./pending.js" + +export function make(pending: PendingTools.Interface): Options["hooks"] { + const before: HookCallback = async (input) => { + if (input.hook_event_name === "PreToolUse") pending.before(input.tool_use_id, input.tool_name) + return {} + } + + const after: HookCallback = async (input) => { + if (input.hook_event_name !== "PostToolUse") return {} + const replacement = pending.after(input.tool_use_id) + if (!replacement) return {} + return { hookSpecificOutput: { hookEventName: "PostToolUse", updatedMCPToolOutput: replacement } } + } + + return { + PreToolUse: [{ hooks: [before] }], + PostToolUse: [{ hooks: [after] }], + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/tools/names.ts b/packages/core/src/plugin/provider/claude-agent/tools/names.ts new file mode 100644 index 000000000000..83958b5a4b01 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/tools/names.ts @@ -0,0 +1,30 @@ +export * as ToolNames from "./names.js" + +import { createHash } from "node:crypto" +import type { LanguageModelV3FunctionTool } from "@ai-sdk/provider" + +export const PREFIX = "mcp__opencode__" + +export function short(name: string) { + const limit = 64 - PREFIX.length + if (name.length <= limit && /^[a-zA-Z0-9_-]+$/.test(name)) return name + const hash = createHash("sha256").update(name).digest("hex").slice(0, 10) + return name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, limit - 11) + "_" + hash +} + +// Undefined for a tool we did not offer. Claude Code answers those calls itself, without our hooks or server. +export function original(name: string, tools: readonly LanguageModelV3FunctionTool[]) { + return tools.find((tool) => PREFIX + short(tool.name) === name)?.name +} + +// Claude Code cuts each MCP tool description at this many characters. +const DESCRIPTION_LIMIT = 2048 + +export function description(tool: LanguageModelV3FunctionTool) { + const text = tool.description ?? "" + if (tool.name !== "subagent" || text.length <= DESCRIPTION_LIMIT) return text.slice(0, DESCRIPTION_LIMIT) + // The subagent list comes last in a long description, so move it first to keep it after the cut. + const agents = text.indexOf("Available subagents:") + if (agents === -1) return text.slice(0, DESCRIPTION_LIMIT) + return (text.slice(agents) + "\n\n" + text.slice(0, agents)).slice(0, DESCRIPTION_LIMIT) +} diff --git a/packages/core/src/plugin/provider/claude-agent/tools/pending.ts b/packages/core/src/plugin/provider/claude-agent/tools/pending.ts new file mode 100644 index 000000000000..98ca7235ccf3 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/tools/pending.ts @@ -0,0 +1,72 @@ +export * as PendingTools from "./pending.js" + +import type { CallToolResult } from "@modelcontextprotocol/server" +import type { ToolResult } from "./result.js" + +interface Call { + readonly name: string + readonly result: PromiseWithResolvers +} + +export interface Interface { + readonly expect: (id: string, name: string) => void + readonly before: (id: string, name: string) => void + readonly call: (name: string) => Promise + readonly resolve: (id: string, result: ToolResult.Result) => void + readonly after: (id: string) => ToolResult.Result["replacement"] + readonly clear: () => void +} + +export function make(): Interface { + const calls = new Map() + const replacements = new Map() + let next: string | undefined + + function expect(id: string, name: string) { + const saved = calls.get(id) + const call = saved ?? { name, result: Promise.withResolvers() } + if (!saved) calls.set(id, call) + if (call.name !== name) throw new Error(`Mismatched Claude tool call ${id}`) + return call + } + + return { + expect, + before(id: string, name: string) { + expect(id, name) + next = id + }, + async call(name: string) { + const id = next + next = undefined + if (!id) throw new Error("Claude invoked an OpenCode tool without its PreToolUse ID") + const call = expect(id, name) + const result = await call.result.promise + if (result.replacement) replacements.set(id, result.replacement) + calls.delete(id) + return result.mcp + }, + resolve(id: string, result: ToolResult.Result) { + const call = calls.get(id) + if (!call) throw new Error(`No waiting Claude tool call ${id}`) + call.result.resolve(result) + }, + after(id: string) { + const replacement = replacements.get(id) + replacements.delete(id) + return replacement + }, + // Call only after interrupt-and-drain; resolving these handlers earlier can start another model call. + clear() { + for (const call of calls.values()) { + call.result.resolve({ + mcp: { isError: true, content: [{ type: "text", text: "Cancelled by user." }] }, + replacement: undefined, + }) + } + calls.clear() + replacements.clear() + next = undefined + }, + } +} diff --git a/packages/core/src/plugin/provider/claude-agent/tools/result.ts b/packages/core/src/plugin/provider/claude-agent/tools/result.ts new file mode 100644 index 000000000000..afdadf21c1a7 --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/tools/result.ts @@ -0,0 +1,110 @@ +export * as ToolResult from "./result.js" + +import type { + LanguageModelV3FilePart, + LanguageModelV3Prompt, + LanguageModelV3ToolResultOutput, + LanguageModelV3ToolResultPart, +} from "@ai-sdk/provider" +import type { CallToolResult } from "@modelcontextprotocol/server" +import { Provider } from "@opencode/schema/provider" +import { ConvertToClaudeMessage } from "../language-model/convert-to-claude-message.js" +import { Fingerprint } from "../sync/fingerprint.js" + +export interface Result { + readonly mcp: CallToolResult + readonly replacement: ConvertToClaudeMessage.ContentBlock[] | undefined +} + +export function convert( + output: LanguageModelV3ToolResultOutput, + files: readonly LanguageModelV3FilePart[] = [], + failed = false, +): Result { + const parts: Array<{ type: "text"; text: string } | LanguageModelV3FilePart> = [] + switch (output.type) { + case "text": + case "error-text": + parts.push({ type: "text", text: output.value }) + break + case "json": + case "error-json": + parts.push({ type: "text", text: JSON.stringify(output.value) }) + break + case "execution-denied": + parts.push({ type: "text", text: output.reason ?? "Tool execution was denied by the user." }) + break + case "content": + for (const part of output.value) { + if (part.type === "text") { + parts.push({ type: "text", text: part.text }) + continue + } + if (part.type === "image-data" || part.type === "file-data") { + parts.push({ type: "file", mediaType: part.mediaType, data: part.data }) + continue + } + if (part.type === "image-url") { + // Only picks an image block. URL images are sent without a media type. + parts.push({ type: "file", mediaType: "image/png", data: new URL(part.url) }) + continue + } + throw new Error(`Claude Code does not support ${part.type} tool output`) + } + break + } + parts.push(...files) + const content = ConvertToClaudeMessage.content([{ role: "user", content: parts }]) + const isError = + failed || output.type === "error-text" || output.type === "error-json" || output.type === "execution-denied" + const mcp: CallToolResult = { content: [], isError } + let replace = false + for (const block of content) { + if (block.type === "text") { + mcp.content.push({ type: "text", text: block.text }) + continue + } + if (block.type === "image" && block.source.type === "base64") { + mcp.content.push({ type: "image", mimeType: block.source.media_type, data: block.source.data }) + continue + } + replace = true + mcp.content.push({ type: "text", text: "Attached document or image follows." }) + } + // The PostToolUse hook replaces tool_result.content, so it needs content blocks rather than an MCP envelope. + return { mcp, replacement: replace ? content : undefined } +} + +export function collect(prompt: LanguageModelV3Prompt, start: number) { + const results = new Map() + let end = start + let aborted = false + for (const group of Fingerprint.groups(prompt.slice(start))) { + if (group.role !== "tool") break + const messages = prompt.slice(start + group.start, start + group.end) + const tools: LanguageModelV3ToolResultPart[] = [] + const files: LanguageModelV3FilePart[] = [] + for (const message of messages) { + if (message.role === "tool") { + for (const part of message.content) { + if (part.type === "tool-result") tools.push(part) + } + } + if (message.role === "user") { + for (const part of message.content) { + if (part.type === "file") files.push(part) + } + } + } + // OpenCode puts the group's media in a following user message; attach it to the group's last result. + for (let i = 0; i < tools.length; i++) { + const tool = tools[i]! + const flags = tool.providerOptions?.[Provider.ID.claudeAgent] + if (flags?.toolAborted === true) aborted = true + const isLast = i === tools.length - 1 + results.set(tool.toolCallId, convert(tool.output, isLast ? files : [], flags?.toolError === true)) + } + end = start + group.end + } + return { results, end, aborted } +} diff --git a/packages/core/src/plugin/provider/claude-agent/tools/server.ts b/packages/core/src/plugin/provider/claude-agent/tools/server.ts new file mode 100644 index 000000000000..997c13061abf --- /dev/null +++ b/packages/core/src/plugin/provider/claude-agent/tools/server.ts @@ -0,0 +1,34 @@ +export * as ToolServer from "./server.js" + +import type { LanguageModelV3FunctionTool } from "@ai-sdk/provider" +import type { McpSdkServerConfigWithInstance } from "@anthropic-ai/claude-agent-sdk" +import type { Tool } from "@modelcontextprotocol/server" +import { ToolNames } from "./names.js" +import type { PendingTools } from "./pending.js" + +export async function make( + tools: readonly LanguageModelV3FunctionTool[], + pending: PendingTools.Interface, +): Promise { + // Loaded on first use, so opencode starts without loading the MCP SDK. + const { Server } = await import("@modelcontextprotocol/server") + const server = new Server({ name: "opencode", version: "1.0.0" }, { capabilities: { tools: {} } }) + const definitions = tools.map( + (tool): Tool => ({ + name: ToolNames.short(tool.name), + description: ToolNames.description(tool), + inputSchema: tool.inputSchema as Tool["inputSchema"], + // Claude serializes non-read-only tools, so each handler takes the ID from the preceding hook. + annotations: { readOnlyHint: false }, + _meta: { "anthropic/alwaysLoad": true, "anthropic/maxResultSizeChars": 500_000 }, + }), + ) + server.setRequestHandler("tools/list", async () => ({ tools: definitions })) + server.setRequestHandler("tools/call", async (request) => { + const name = ToolNames.PREFIX + request.params.name + if (!ToolNames.original(name, tools)) throw new Error(`Claude Code called an unregistered OpenCode tool: ${name}`) + return pending.call(name) + }) + // Claude Agent SDK bundles its own MCP SDK types; its public instance type also names the higher-level McpServer. + return { type: "sdk", name: "opencode", instance: server as unknown as McpSdkServerConfigWithInstance["instance"] } +} diff --git a/packages/core/src/schedule/check.ts b/packages/core/src/schedule/check.ts index aea13b2ee3ad..d628e29d4ae0 100644 --- a/packages/core/src/schedule/check.ts +++ b/packages/core/src/schedule/check.ts @@ -344,7 +344,7 @@ const scanShell = Effect.fnUntraced(function* (command: string) { .resolve({ path: location.directory, kind: "directory" }) .pipe(Effect.mapError((error) => error.message)) const shell = yield* shellSelect.resolve({ priority: "compat" }) - const parsed = yield* ShellParse.scanPortable(command, shell, target.absolute).pipe( + const parsed = yield* ShellParse.scan(command, shell, target.absolute).pipe( Effect.mapError((error) => error.message), ) const directories = yield* Effect.forEach(parsed.directories, (directory) => diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index 917d08819b2b..4874e45b0cf1 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -23,6 +23,7 @@ import { Agent } from "../agent.js" import { Bus } from "../bus.js" import { Database } from "../database/database.js" import { llmClient } from "../effect/app-node-platform.js" +import { Instructions } from "../instructions/index.js" import { Model } from "../model.js" import { State } from "../state.js" import { Token } from "../util/token.js" @@ -379,7 +380,7 @@ export const layer = Layer.effect( firstID: context.messages[0]?.id, keepID: anchor.id, model: context.model.ref, - initial: context.initial, + initial: Instructions.join(context.initial), tailLimit: tailLimit(settings.keep, model.cap), failures, usage, @@ -949,7 +950,7 @@ export const node = makeLocationNode({ * conversation: a compaction or revert since replaced its start, or the model or instructions changed. */ const heldIndex = (held: Precomputed, context: SessionContext.Loaded) => { - if (held.firstID !== context.messages[0]?.id || held.initial !== context.initial) return -1 + if (held.firstID !== context.messages[0]?.id || held.initial !== Instructions.join(context.initial)) return -1 if (held.model.providerID !== context.model.ref.providerID || held.model.id !== context.model.ref.id) return -1 if (held.model.variant !== context.model.ref.variant) return -1 return context.messages.findIndex((message) => message.id === held.keepID) diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index 42ae72d053af..99c54114942e 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -36,7 +36,7 @@ export interface Loaded { readonly session: SessionSchema.Info readonly agent: Agent.Selection & { readonly info: Agent.Info } readonly model: SessionRunnerModel.Resolved - readonly initial: string + readonly initial: ReadonlyArray readonly messages: ReadonlyArray readonly tools: Tool.Snapshot } diff --git a/packages/core/src/session/model-request.ts b/packages/core/src/session/model-request.ts index 739d7c0d16e2..9ad26e3ead68 100644 --- a/packages/core/src/session/model-request.ts +++ b/packages/core/src/session/model-request.ts @@ -27,6 +27,7 @@ import { Cause, Context, Effect, Layer, Result, Stream } from "effect" import { HttpClientRequest, HttpClientResponse } from "effect/http" import { makeLocationNode } from "@opencode/util/effect/app-node" import { App } from "../app.js" +import { Instructions } from "../instructions/index.js" import { Permission } from "../permission.js" import { PluginHooks } from "../plugin/hooks.js" import { QuestionTool } from "../tool/plugin/question.js" @@ -100,20 +101,23 @@ export const baseTranscript = (input: { readonly agent: Agent.Info readonly model: SessionRunnerModel.Resolved readonly tools: Tool.Snapshot - readonly initial: string + readonly initial: ReadonlyArray readonly messages: ReadonlyArray }) => { const providerMetadataKey = input.model.model.route.providerMetadataKey ?? input.model.model.provider return { providerMetadataKey, system: [ - input.agent.system - ? input.agent.system - : SessionSystemPrompt.make(input.tools.definitions.map((tool) => tool.name)), - input.initial, - ] - .filter((part) => part.length > 0) - .map(SystemPart.make), + SystemPart.make( + input.agent.system + ? input.agent.system + : SessionSystemPrompt.make(input.tools.definitions.map((tool) => tool.name)), + ), + { + ...SystemPart.make(Instructions.join(input.initial)), + metadata: { experimental: { instructions: input.initial } }, + }, + ].filter((part) => part.text.length > 0), messages: toLLMMessages(input.messages, input.model.ref, providerMetadataKey), } } diff --git a/packages/core/src/shell/parse.ts b/packages/core/src/shell/parse.ts index 356fbb6705af..ef0f25c20756 100644 --- a/packages/core/src/shell/parse.ts +++ b/packages/core/src/shell/parse.ts @@ -1,16 +1,19 @@ export * as ShellParse from "./parse.js" -import { Effect } from "effect" +import { Effect, Result } from "effect" +import fs from "fs" import os from "os" import path from "path" import { ShellScan } from "./scan.js" import { ShellSelect } from "./select.js" import { Wildcard } from "../util/wildcard.js" -type Part = { type: string; text: string; unquotedTilde?: boolean } +type Part = { type: string; text: string; raw: string; unquotedTilde?: boolean } const CWD = new Set(["cd", "chdir", "popd", "pushd", "push-location", "set-location"]) const POWERSHELL_PATH_FLAG_RE = /^-(?:p(?:ath|at|a)?|lp|l(?:i(?:t(?:e(?:r(?:a(?:l(?:p(?:a(?:t(?:h)?)?)?)?)?)?)?)?)?)?|psp(?:a(?:t(?:h)?)?)?):?$/i +const POWERSHELL_LITERAL_FLAG_RE = /^-(?:lp|l(?:i(?:t(?:e(?:r(?:a(?:l(?:p(?:a(?:t(?:h)?)?)?)?)?)?)?)?)?)?|psp(?:a(?:t(?:h)?)?)?):?$/i +const POWERSHELL_STACK_FLAG_RE = /^-(?:stack(?:name|nam|na|n)?|st):?$/i export type Result = { commands: Array<{ resource: string; save: string }> @@ -172,6 +175,13 @@ export function scan(command: string, shell: string, cwd: string): Effect.Effect for (const item of scanned.commands) { // Declarations are skipped as standalone permission resources, while nested substitutions remain. if (item.declaration) continue + if (item.redirectPrefixEnd !== undefined) { + const head = item.resource.slice(0, item.redirectPrefixEnd) + const next = item.resource[item.redirectPrefixEnd] + const separator = next === "\t" || next === "\n" ? next : " " + output.commands.push({ resource: item.resource, save: `${head}${separator}*` }) + continue + } const words = item.redirectWordCount === undefined ? item.rawWords : item.rawWords.slice(0, item.redirectWordCount) // Bare statement-head foreach blocks act as PowerShell control flow rather than cmdlet invocations. if ( @@ -186,29 +196,33 @@ export function scan(command: string, shell: string, cwd: string): Effect.Effect ? words.flatMap((raw, index): Part[] => { const text = !raw.includes("`$") && /['"`]/.test(raw) ? (item.words[index] ?? raw) : raw.replaceAll("`$", "\0") - if (!/^-[A-Za-z_?][\w?-]*(?::|$)/.test(raw)) return [{ type: "word", text }] + if (!/^-[A-Za-z_?][\w?-]*(?::|$)/.test(raw)) return [{ type: "word", text, raw }] const colon = text.indexOf(":") - if (colon >= 0) + if (colon >= 0) { + const rawColon = raw.indexOf(":") return colon + 1 < text.length ? [ - { type: "command_parameter", text: text.slice(0, colon) }, - { type: "word", text: text.slice(colon + 1) }, + { type: "command_parameter", text: text.slice(0, colon), raw: raw.slice(0, rawColon) }, + { type: "word", text: text.slice(colon + 1), raw: rawColon >= 0 ? raw.slice(rawColon + 1) : raw }, ] - : [{ type: "command_parameter", text: text.slice(0, colon) }] - return [{ type: "command_parameter", text }] + : [{ type: "command_parameter", text: text.slice(0, colon), raw }] + } + return [{ type: "command_parameter", text, raw }] }) : item.rawWords.map((raw, index): Part => { const word = item.words[index] ?? raw return { type: "word", text: isStaticBashWord(raw) ? word.replaceAll("$", "\0") : "$", + raw, unquotedTilde: raw.startsWith("~"), } }) - const directoryCommand = unwrapDirectoryCommand(words, parts, powershell) + const directoryCommand = unwrapDirectoryCommand(powershell ? words : item.rawWords, parts, powershell) if (directoryCommand) { - output.directories.push(...directoryArgs(directoryCommand, powershell, cwd, shell)) - if (directoryCommand === parts) continue + const resolved = directoryArgs(directoryCommand, powershell, cwd, shell) + output.directories.push(...resolved.directories) + if (directoryCommand === parts && resolved.complete) continue } const selected = prefix(words.slice(0, PREFIX_LENGTH)) const conventional = `${selected.join(" ")} *` @@ -217,14 +231,16 @@ export function scan(command: string, shell: string, cwd: string): Effect.Effect const save = !powershell || end === undefined || Wildcard.match(item.resource, conventional) ? conventional - : (() => { - const boundary = - item.wordEnds?.find( - (value) => value >= end && (value >= item.resource.length || /\s/.test(item.resource[value])), - ) ?? end - const separator = /^\s+(?:`(?:\r\n|\r|\n)\s*)?/.exec(item.resource.slice(boundary))?.[0] - return `${item.resource.slice(0, boundary)}${separator ?? " "}*` - })() + : item.resource[end] === "(" + ? `${item.resource.slice(0, end)}(*` + : (() => { + const boundary = + item.wordEnds?.find( + (value) => value >= end && (value >= item.resource.length || /\s/.test(item.resource[value])), + ) ?? end + const separator = /^\s+(?:`(?:\r\n|\r|\n)\s*)?/.exec(item.resource.slice(boundary))?.[0] + return `${item.resource.slice(0, boundary)}${separator ?? " "}*` + })() output.commands.push({ resource: item.resource, save, @@ -234,8 +250,6 @@ export function scan(command: string, shell: string, cwd: string): Effect.Effect }) } -export const scanPortable = scan - function unwrapDirectoryCommand(rawWords: string[], parts: Part[], powershell: boolean) { const head = powershell ? rawWords[0]?.toLowerCase() : rawWords[0] if (CWD.has(head ?? "")) return parts @@ -256,24 +270,58 @@ function unwrapDirectoryCommand(rawWords: string[], parts: Part[], powershell: b function isStaticBashWord(raw: string) { let quote: "'" | '"' | "$'" | undefined + let segmentStarted = false + let segmentLeadingDot = false + let segmentGlob = false + let hasAnsiEscape = false + let hasUnquotedGlob = false + const braces: boolean[] = [] + const recordChar = (char: string, unquotedGlob = false) => { + if (unquotedGlob) hasUnquotedGlob = true + if (hasAnsiEscape && hasUnquotedGlob) return false + if (char === "/") { + segmentStarted = false + segmentLeadingDot = false + segmentGlob = false + return true + } + if (!segmentStarted) { + segmentStarted = true + segmentLeadingDot = char === "." + } + if (unquotedGlob) segmentGlob = true + return !(segmentLeadingDot && segmentGlob) + } + for (let index = 0; index < raw.length; index++) { const char = raw[index] const next = raw[index + 1] ?? "" if (quote === "'") { - if (char === "'") quote = undefined + if (char === "'") { + quote = undefined + continue + } + if (!recordChar(char)) return false continue } if (quote === "$'") { if (char === "\\") { + hasAnsiEscape = true + if (hasUnquotedGlob) return false index++ continue } - if (char === "'") quote = undefined + if (char === "'") { + quote = undefined + continue + } + if (!recordChar(char)) return false continue } if (quote === '"') { if (char === "\\" && '$`"\\\n'.includes(next)) { index++ + if (next !== "\n" && !recordChar(next)) return false continue } if (char === '"') { @@ -282,10 +330,12 @@ function isStaticBashWord(raw: string) { } if (char === "`" || (char === "$" && (/[A-Za-z_0-9@*#?$!({[-]/.test(next) || raw.startsWith("\\\n", index + 1)))) return false + if (!recordChar(char)) return false continue } if (char === "\\") { index++ + if (next !== "\n" && !recordChar(next)) return false continue } if (char === "'") { @@ -312,53 +362,165 @@ function isStaticBashWord(raw: string) { (char === "$" && (/[A-Za-z_0-9@*#?$!({[-]/.test(next) || raw.startsWith("\\\n", index + 1))) ) return false + if (char === "{") { + braces.push(false) + if (!recordChar(char)) return false + continue + } + if (braces.length > 0 && (char === "," || (char === "." && next === "."))) { + braces[braces.length - 1] = true + } + if (char === "}" && braces.length > 0) { + if (braces.pop()) return false + if (!recordChar(char)) return false + continue + } + if (!recordChar(char, char === "*" || char === "?" || char === "[")) return false } return quote === undefined } +function hasPowerShellDotWildcard(raw: string) { + let quote: "'" | '"' | undefined + let segmentStarted = false + let segmentLeadingDot = false + let segmentGlob = false + let hasQuoteEscape = false + let hasUnquotedGlob = false + const recordChar = (char: string, unquotedGlob = false) => { + if (unquotedGlob) hasUnquotedGlob = true + if (hasQuoteEscape && hasUnquotedGlob) return true + if (char === "/" || char === "\\") { + segmentStarted = false + segmentLeadingDot = false + segmentGlob = false + return false + } + if (!segmentStarted) { + segmentStarted = true + segmentLeadingDot = char === "." + } + if (unquotedGlob) segmentGlob = true + return segmentLeadingDot && segmentGlob + } + + for (let index = 0; index < raw.length; index++) { + const char = raw[index] + const next = raw[index + 1] ?? "" + if (quote === "'") { + if (char === "'" && next === "'") { + index++ + if (recordChar("'")) return true + continue + } + if (char === "'") { + quote = undefined + continue + } + if (recordChar(char)) return true + continue + } + if (quote === '"') { + if (char === "`") { + hasQuoteEscape = true + if (hasUnquotedGlob) return true + index++ + continue + } + if (char === '"' && next === '"') { + index++ + if (recordChar('"')) return true + continue + } + if (char === '"') { + quote = undefined + continue + } + if (recordChar(char)) return true + continue + } + if (char === "`") { + index++ + if (recordChar(next)) return true + continue + } + if (char === "'" || char === '"') { + quote = char + continue + } + if (recordChar(char, char === "*" || char === "?" || char === "[")) return true + } + return false +} + function directoryArgs(command: Part[], powershell: boolean, cwd: string, shell: string) { + const head = command[0]?.text.toLowerCase() ?? "" + if (head === "popd" || head === "pop-location") return { directories: [], complete: false } + if (!powershell) { let endOfOptions = false - return command - .slice(1) - .filter((part) => { - if (endOfOptions) return true - if (part.text === "--") { - endOfOptions = true - return false - } - return !part.text.startsWith("-") - }) - .map((part) => directoryArgument(part.text, powershell, cwd, shell, part.unquotedTilde)) - .filter((part) => part !== undefined) + const operands = command.slice(1).filter((part) => { + if (endOfOptions) return true + if (part.text === "--") { + endOfOptions = true + return false + } + if (part.text === "-") return true + return !part.text.startsWith("-") + }) + if (operands.length === 0) return { directories: [], complete: false } + const resolved = operands.map((part) => + part.text === "-" ? undefined : directoryArgument(part.text, false, cwd, shell, part.unquotedTilde), + ) + const directories = resolved.filter((item): item is string => item !== undefined) + return { directories, complete: directories.length === operands.length } } const directories: string[] = [] - let path = false + let pathFlag = false + let literalFlag = false let endOfParameters = false + let sawOperand = false + let complete = true for (const part of command.slice(1)) { if (!endOfParameters && part.text === "--") { endOfParameters = true continue } - if (path) { - const value = directoryArgument(part.text, powershell, cwd, shell) + if (pathFlag) { + sawOperand = true + const value = + !literalFlag && (hasPowerShellDotWildcard(part.raw) || part.text === "-" || part.text === "+") + ? undefined + : directoryArgument(part.text, true, cwd, shell) if (value) directories.push(value) - path = false + if (!value) complete = false + pathFlag = false + literalFlag = false continue } if (!endOfParameters && part.type === "command_parameter") { - path = POWERSHELL_PATH_FLAG_RE.test(part.text) + if (POWERSHELL_STACK_FLAG_RE.test(part.text)) { + complete = false + return { directories, complete } + } + pathFlag = POWERSHELL_PATH_FLAG_RE.test(part.text) + literalFlag = POWERSHELL_LITERAL_FLAG_RE.test(part.text) continue } - const value = directoryArgument(part.text, powershell, cwd, shell) + sawOperand = true + const value = + hasPowerShellDotWildcard(part.raw) || (!endOfParameters && (part.raw === "-" || part.raw === "+")) + ? undefined + : directoryArgument(part.text, true, cwd, shell) if (value) directories.push(value) + if (!value) complete = false } - return directories + return { directories, complete: sawOperand && complete } } function directoryArgument(value: string, powershell: boolean, cwd: string, shell: string, unquotedTilde = false) { - if (!powershell) return expandKnownDirectory(value, false, unquotedTilde) + if (!powershell) return expandKnownDirectory(value, false, cwd, unquotedTilde) const quote = value[0] const text = (quote === '"' || quote === "'") && value.at(-1) === quote ? value.slice(1, -1) : value @@ -375,10 +537,11 @@ function directoryArgument(value: string, powershell: boolean, cwd: string, shel return path.dirname(shell) }), true, + cwd, ) } -function expandKnownDirectory(value: string, powershell: boolean, unquotedTilde = false) { +function expandKnownDirectory(value: string, powershell: boolean, cwd: string, unquotedTilde = false) { // Unknown shell expressions cannot be resolved safely during permission analysis. if (value.includes("$") || value.includes("`") || (powershell && value.startsWith("("))) return const resolved = value.replaceAll("\0", "$") @@ -387,21 +550,52 @@ function expandKnownDirectory(value: string, powershell: boolean, unquotedTilde return path.join(os.homedir(), resolved.slice(2)) } if (unquotedTilde && process.platform !== "win32") { - const userMatch = /^~([A-Za-z0-9._-]+)(?=$|\/)/.exec(resolved) + if (resolved === "~+") return cwd + if (resolved.startsWith("~+/")) return path.join(cwd, resolved.slice(3)) + if (/^~(?:[-+](?:\d+)?|\d+)(?=$|\/)/.test(resolved)) return + const userMatch = /^~([A-Za-z_][A-Za-z0-9._-]*)(?=$|\/)/.exec(resolved) if (userMatch) { const user = userMatch[1] - const home = - user === "root" - ? process.platform === "darwin" - ? "/var/root" - : "/root" - : path.join(process.platform === "darwin" ? "/Users" : "/home", user) + const home = resolveUserHome(user) + if (!home) return return path.join(home, resolved.slice(user.length + 1)) } } return resolved } +let cachedPasswdHomes: ReadonlyMap | undefined + +function passwdHomes() { + if (cachedPasswdHomes) return cachedPasswdHomes + const content = Result.try(() => fs.readFileSync("/etc/passwd", "utf8")) + const entries = Result.isSuccess(content) + ? content.success.split("\n").flatMap((line): Array<[string, string]> => { + if (!line || line.startsWith("#")) return [] + const fields = line.split(":") + const name = fields[0] + const home = fields[5] + return name && home ? [[name, home]] : [] + }) + : [] + cachedPasswdHomes = new Map(entries) + return cachedPasswdHomes +} + +function resolveUserHome(user: string) { + const current = Result.try(() => os.userInfo()) + if (Result.isSuccess(current) && current.success.username === user && current.success.homedir) { + return current.success.homedir + } + const fromPasswd = passwdHomes().get(user) + if (fromPasswd) return fromPasswd + if (process.platform === "darwin") { + const candidate = path.join("/Users", user) + const exists = Result.try(() => fs.statSync(candidate).isDirectory()) + if (Result.isSuccess(exists) && exists.success) return candidate + } +} + function environment(key: string) { if (process.platform !== "win32") return process.env[key] const name = Object.keys(process.env).find((item) => item.toLowerCase() === key.toLowerCase()) diff --git a/packages/core/src/shell/scan.ts b/packages/core/src/shell/scan.ts index bad56f3e95ba..a8ad405f9941 100644 --- a/packages/core/src/shell/scan.ts +++ b/packages/core/src/shell/scan.ts @@ -19,8 +19,10 @@ type Command = { wordEnds?: number[] statementHead?: true declaration?: true - // Words after a trailing redirect are destinations in the legacy command span. + // Words before the first redirect when redirects appear between arguments. redirectWordCount?: number + // Exclusive prefix end relative to resource for commandless or group redirects. + redirectPrefixEnd?: number } // Opaque describes a parsing limitation, not a permission decision. @@ -185,9 +187,8 @@ type BashState = { wordStart: number wordEnd: number commandStart: number | undefined - commandEnd: number - resourceEnd: number | undefined redirectWordCount: number | undefined + redirectPrefixEnd: number | undefined // Posix shells such as Dash read `&>` as `&` and `>`, so later words would start another command there. ampersandRedirectWords: number | undefined commandWordIndex: number @@ -195,8 +196,10 @@ type BashState = { assignmentHeadUnsafe: boolean invalid: OpaqueReason | undefined redirectTarget: boolean + dupRedirect: boolean hereString: boolean hasRedirect: boolean + hasFileRedirect: boolean compoundEnd: boolean // A list operator (&&, ||, |, |&) still awaits its right-hand command. dangling: boolean @@ -286,10 +289,14 @@ function finishBashWord(state: BashState) { state.words.push(state.word) // Unquoted trailing continuations are ignored syntax, not part of the raw token. state.rawWords.push(state.input.slice(state.wordStart, state.wordEnd)) - state.commandEnd = state.wordEnd } - if (state.hereString && state.resourceEnd === undefined) state.commandEnd = state.wordEnd + if (state.redirectTarget) { + if (!state.dupRedirect || !/^(?:\d+-?|-)$/.test(state.input.slice(state.wordStart, state.wordEnd))) + state.hasFileRedirect = true + state.redirectPrefixEnd ??= state.wordEnd + } state.redirectTarget = false + state.dupRedirect = false state.hereString = false state.word = "" state.literal = "" @@ -369,14 +376,15 @@ function finishBashCommand(state: BashState, boundary = false, newline = false) const inHeader = bashInHeader(state) if (name >= 0 && !state.words[name]) state.invalid ??= "invalid-structure" if (name >= 0 && !inHeader) { - const resource = state.input - .slice(state.commandStart, state.resourceEnd ?? state.wordEnd) - .replace(/^[ \t\n]+|[ \t\n]+$/g, "") + const resource = state.input.slice(state.commandStart, state.wordEnd).replace(/^[ \t\n]+|[ \t\n]+$/g, "") const command: Command = { resource, words: state.words.slice(name), rawWords: state.rawWords.slice(name), - ...(name === 0 && BASH_DECLARATIONS.has(state.rawWords[0]) && resource.startsWith(state.rawWords[0]) + ...(name === 0 && + !state.hasRedirect && + BASH_DECLARATIONS.has(state.rawWords[0]) && + resource.startsWith(state.rawWords[0]) ? { declaration: true as const } : {}), ...(state.redirectWordCount !== undefined && state.redirectWordCount < state.words.length @@ -424,11 +432,42 @@ function finishBashCommand(state: BashState, boundary = false, newline = false) for (const heredoc of state.heredocs) { if (heredoc.owned) continue heredoc.owned = true - if (newline && state.resourceEnd === undefined) { + if (newline) { heredoc.command = command heredoc.start = state.commandStart } } + } else if ( + name < 0 && + !inHeader && + state.commandStart !== undefined && + (state.hasFileRedirect || (state.hasRedirect && !state.compoundEnd)) + ) { + const rawSpan = state.input.slice(state.commandStart, state.wordEnd) + const leading = /^[ \t\n]+/.exec(rawSpan)?.[0].length ?? 0 + const resource = rawSpan.slice(leading).replace(/[ \t\n]+$/g, "") + if (resource) { + const prefixEnd = + state.redirectPrefixEnd !== undefined + ? Math.max(1, Math.min(resource.length, state.redirectPrefixEnd - state.commandStart - leading)) + : resource.length + const prefixToken = resource.slice(0, prefixEnd) + const command: Command = { + resource, + words: [prefixToken], + rawWords: [prefixToken], + redirectPrefixEnd: prefixEnd, + } + state.commands.push(command) + for (const heredoc of state.heredocs) { + if (heredoc.owned) continue + heredoc.owned = true + if (newline) { + heredoc.command = command + heredoc.start = state.commandStart + } + } + } } for (const heredoc of state.heredocs) heredoc.owned = true if (boundary && !state.words.length && !state.hasRedirect && !state.compoundEnd && !inHeader) @@ -440,9 +479,11 @@ function finishBashCommand(state: BashState, boundary = false, newline = false) state.rawWords.length = 0 state.commandWordIndex = -1 state.commandStart = undefined + state.dupRedirect = false state.hasRedirect = false - state.resourceEnd = undefined + state.hasFileRedirect = false state.redirectWordCount = undefined + state.redirectPrefixEnd = undefined state.ampersandRedirectWords = undefined state.compoundEnd = false state.dangling = false @@ -475,17 +516,18 @@ function scanBash( wordStart: start, wordEnd: start, commandStart: undefined, - commandEnd: start, - resourceEnd: undefined, redirectWordCount: undefined, + redirectPrefixEnd: undefined, ampersandRedirectWords: undefined, commandWordIndex: -1, assignmentWord: false, assignmentHeadUnsafe: false, invalid: undefined, redirectTarget: false, + dupRedirect: false, hereString: false, hasRedirect: false, + hasFileRedirect: false, compoundEnd: false, dangling: false, outer, @@ -681,8 +723,6 @@ function scanBashOperatorOrSeparator( const fdPrefix = state.wordStarted && !state.assignmentHeadUnsafe && /^(?:\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/.test(state.word) if (fdPrefix) { - // A continuation separates the legacy number token from the redirect descriptor. - if (state.wordEnd < index) state.commandEnd = state.wordEnd state.word = "" state.literal = "" state.output = "" @@ -690,23 +730,24 @@ function scanBashOperatorOrSeparator( } if (!fdPrefix) finishBashWord(state) if (redirect.startsWith("&") && context.dialect === "posix") state.ampersandRedirectWords ??= state.words.length - // Trailing redirects wrap a whole list/pipeline in the legacy grammar, not its last command. - // Prefix redirects remain part of the command, and later words remain redirect destinations. if (state.redirectWordCount === undefined && state.commandWordIndex >= 0) { state.redirectWordCount = state.words.length } - if (state.dangling && redirect !== "<<<" && state.commandWordIndex >= 0) { - state.resourceEnd ??= state.commandEnd - } if (redirect === "<<" || redirect === "<<-") { const delimiter = bashHeredocDelimiter(input, index + redirect.length, redirect === "<<-") if (!delimiter) return { kind: "opaque", reason: "invalid-redirect" } + state.hasFileRedirect = true + state.redirectPrefixEnd ??= + " \t".includes(input[index + redirect.length] ?? "") ? index + redirect.length : delimiter.end + 1 state.heredocs.push(delimiter) state.wordEnd = delimiter.end + 1 state.redirectTarget = false + state.dupRedirect = false return delimiter.end } + if (" \t\n".includes(input[index + redirect.length] ?? "")) state.redirectPrefixEnd ??= index + redirect.length state.redirectTarget = true + state.dupRedirect = redirect === "<&" || redirect === ">&" state.hereString = redirect === "<<<" return index + redirect.length - 1 } @@ -1838,6 +1879,9 @@ function scanPowerShellList( let clause: PowerShellClause = initialClause let after: "do" | "if" | "try" | undefined let indexable: false | "variable" | "closed" | "member" = false + let memberChainStart: number | undefined + let hasMemberAccess = false + let hasFileRedirect = false let stopParsing = false let commandEnd = start let statementHead = true @@ -1846,6 +1890,11 @@ function scanPowerShellList( let dangling = false let invocation = false + const resetMember = () => { + indexable = false + memberChainStart = undefined + hasMemberAccess = false + } const finishWord = (end: number) => { if (!started) return // Generic tokens can spell stop-parsing with escapes or embedded quotes; literal strings cannot. @@ -1861,7 +1910,7 @@ function scanPowerShellList( ) stopParsing = true if (!redirectTarget) { - if (!words.length && !invocation && !expression) segment = wordStart + if (!words.length && !invocation) segment = wordStart words.push(word) rawWords.push(input.slice(wordStart, end)) wordEnds.push(end) @@ -1874,13 +1923,13 @@ function scanPowerShellList( } const finishCommand = (end: number, required = false) => { finishWord(end) - if (words.length && !expression && !clause) + if (words.length && ((!expression && !clause) || hasFileRedirect)) commands.push({ resource: input.slice(segment, commandEnd).trimEnd(), words: [...words], rawWords: [...rawWords], wordEnds: wordEnds.map((value) => value - segment), - ...(statementHead && !invocation ? { statementHead: true as const } : {}), + ...(statementHead && !invocation && !expression && !clause ? { statementHead: true as const } : {}), }) else if ( (!expression && !clause && invocation) || @@ -1894,11 +1943,12 @@ function scanPowerShellList( rawWords.length = 0 wordEnds.length = 0 redirectTarget = false + hasFileRedirect = false invocation = false expression = initialExpression clause = initialClause after = undefined - indexable = false + resetMember() stopParsing = false } @@ -1960,8 +2010,13 @@ function scanPowerShellList( if (char === "'" || char === '"') { if (!started && words.length === 0 && !invocation) expression = true quote = char - standalone = atBoundary || (expression && !redirectTarget) || (indexable === "member" && /[.:]$/.test(word)) - if (!standalone) indexable = false + const dynamicMember = indexable === "member" && /[.:]$/.test(started ? word : (words.at(-1) ?? "")) + standalone = atBoundary || (expression && !redirectTarget) || dynamicMember + if (dynamicMember) hasMemberAccess = true + else if (standalone) { + memberChainStart = index + hasMemberAccess = false + } else resetMember() started = true continue } @@ -1973,7 +2028,7 @@ function scanPowerShellList( // At a token boundary escaped whitespace is trivia, not a new argument. else if (!atBoundary || !rawSpace) { started = true - indexable = false + if (!(indexable === "member" && /[\p{L}\p{Nl}\d_]/u.test(escape.value))) resetMember() word += escape.value } index = escape.end @@ -1998,7 +2053,7 @@ function scanPowerShellList( if (started) finishWord(index) const end = input.indexOf("#>", index + 2) if (end < 0) return { kind: "opaque", reason: "invalid-structure" } - if (!memberOperator) indexable = false + if (!memberOperator) resetMember() index = end + 1 continue } @@ -2035,7 +2090,8 @@ function scanPowerShellList( if (redirectTarget || words.length === 0 || (clause && clause !== "member")) return { kind: "opaque", reason: "invalid-redirect" } redirectTarget = !redirect.includes("&") - indexable = false + if (redirectTarget) hasFileRedirect = true + resetMember() index += redirect.length - 1 commandEnd = index + 1 continue @@ -2104,7 +2160,8 @@ function scanPowerShellList( rawWords.length = 0 wordEnds.length = 0 expression = false - indexable = false + hasFileRedirect = false + resetMember() if (!assign || char !== "=") index++ continue } @@ -2121,6 +2178,8 @@ function scanPowerShellList( started = true index = literal.end finishWord(index + 1) + memberChainStart = wordStart + hasMemberAccess = false indexable = "closed" continue } @@ -2128,7 +2187,15 @@ function scanPowerShellList( const end = powerShellBracedVariable(input, index, skipped) if (end === undefined) return { kind: "opaque", reason: "invalid-structure" } if (!started && !words.length && !invocation && hash !== "switch") expression = true - indexable = atBoundary || (indexable === "member" && /[.:]$/.test(word)) ? "closed" : false + const dynamicMember = indexable === "member" && /[.:]$/.test(started ? word : (words.at(-1) ?? "")) + if (dynamicMember) { + indexable = "closed" + hasMemberAccess = true + } else if (atBoundary) { + memberChainStart = index + hasMemberAccess = false + indexable = "closed" + } else resetMember() word += input.slice(index, end + 1) started = true index = end @@ -2149,7 +2216,17 @@ function scanPowerShellList( ? index : undefined if (opener !== undefined) { + const tokenIndex = index const openChar = input[opener] + const prevMemberWord = started ? word : (words.at(-1) ?? "") + const dynamicMemberOpener = indexable === "member" && /[.:]$/.test(prevMemberWord) + const priorIndexable = Boolean(indexable) + const isMethodCall = + char === "(" && + opener === tokenIndex && + memberChainStart !== undefined && + ((indexable === "member" && started && !/[.:]$/.test(word)) || + (indexable === "closed" && !started && hasMemberAccess)) const standaloneBlock = atBoundary || inExpression || char === "(" || openChar === "{" const blockClose = openChar === "(" ? ")" : openChar === "[" ? "]" : "}" const blockHash = @@ -2179,12 +2256,28 @@ function scanPowerShellList( started = true word += input.slice(index, result.end + 1) index = result.end - if (openChar === "[") { + if (isMethodCall && memberChainStart !== undefined) { + finishWord(index + 1) + const callResource = input.slice(memberChainStart, result.end + 1) + const head = input.slice(memberChainStart, opener) + const args = input.slice(opener, result.end + 1) + nestedCommands.push({ + resource: callResource, + words: [head, args], + rawWords: [head, args], + wordEnds: [head.length, callResource.length], + }) indexable = "closed" + hasMemberAccess = false + } else if (openChar === "[") { + indexable = "closed" + if (!priorIndexable) memberChainStart = tokenIndex if (input[index + 1] !== "[") finishWord(index + 1) } else if (standaloneBlock) { finishWord(index + 1) indexable = "closed" + if (!dynamicMemberOpener) memberChainStart = tokenIndex + hasMemberAccess = dynamicMemberOpener } if ((clause === "paren" && char === "(") || (clause && clause !== "paren" && char === "{")) { const completed = clause === "do" || clause === "if" || clause === "try" ? clause : undefined @@ -2210,8 +2303,9 @@ function scanPowerShellList( continue } if (/\s/.test(char) && char !== "\n" && char !== "\r") { + const memberOperator = indexable === "member" && /[.:]$/.test(started ? word : (words.at(-1) ?? "")) finishWord(index) - indexable = false + if (!memberOperator) resetMember() continue } const next = input[index + 1] @@ -2235,12 +2329,12 @@ function scanPowerShellList( if ((clause && clause !== "member") || prev.endsWith(",") || memberOperator) { finishWord(index) index += separator.length - 1 - if (!memberOperator) indexable = false + if (!memberOperator) resetMember() continue } if (!started && !words.length && !invocation) { index += separator.length - 1 - indexable = false + resetMember() continue } } @@ -2252,39 +2346,53 @@ function scanPowerShellList( } if (!started && !words.length && !invocation && hash !== "switch" && testAt(POWERSHELL_EXPRESSION_RE, input, index)) expression = true - if ((atBoundary || (indexable === "member" && /[.:]$/.test(word))) && char === "$") - indexable = testAt(POWERSHELL_INDEXABLE_VAR_RE, input, index + 1) ? "variable" : false - else if (indexable === "closed") + const prevMember = started ? word : (words.at(-1) ?? "") + if ((atBoundary || (indexable === "member" && /[.:]$/.test(prevMember))) && char === "$") { + if (testAt(POWERSHELL_INDEXABLE_VAR_RE, input, index + 1)) { + if (indexable === "member" && /[.:]$/.test(prevMember)) hasMemberAccess = true + else { + memberChainStart = index + hasMemberAccess = false + } + indexable = "variable" + } else resetMember() + } else if (indexable === "closed") { indexable = - (char === "." && input[index + 1] !== "." && !/\s/.test(input[index + 1] ?? "")) || - (!started && char === ":" && input[index + 1] === ":" && !/\s/.test(input[index + 2] ?? "")) || + (char === "." && input[index + 1] !== "." && (!/\s/.test(input[index + 1] ?? "") || inExpression)) || + (!started && char === ":" && input[index + 1] === ":") || (!started && char === "?" && input[index + 1] === "." && input[index + 2] !== "." && - !/\s/.test(input[index + 2] ?? "")) + (!/\s/.test(input[index + 2] ?? "") || inExpression)) ? "member" : !started && char === "?" && input[index + 1] === "[" ? "closed" : false - else if (indexable === "variable") + if (indexable === "member") hasMemberAccess = true + else if (!indexable) resetMember() + } else if (indexable === "variable") { indexable = - (char === "." && input[index + 1] !== "." && !/\s/.test(input[index + 1] ?? "")) || - (char === ":" && input[index + 1] === ":" && !/\s/.test(input[index + 2] ?? "")) + (char === "." && input[index + 1] !== "." && (!/\s/.test(input[index + 1] ?? "") || inExpression)) || + (char === ":" && input[index + 1] === ":") ? "member" : (char === "." && input[index + 1] === ".") || !/[\p{L}\p{Nl}\d_:?]/u.test(char) ? false : "variable" - else if (indexable === "member") + if (indexable === "member") hasMemberAccess = true + else if (!indexable) resetMember() + } else if (indexable === "member") { indexable = char === "." && input[index + 1] === "." ? false - : (char === "." && !/\s/.test(input[index + 1] ?? "")) || + : (char === "." && (!/\s/.test(input[index + 1] ?? "") || inExpression)) || (char === ":" && (input[index + 1] === ":" || input[index - 1] === ":")) || (char === "?" && input[index + 1] === "." && input[index + 2] !== ".") || /[\p{L}\p{Nl}\d_]/u.test(char) ? "member" : false + if (!indexable) resetMember() + } after = undefined started = true dangling = false diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 201c19f5e459..156a05bcef1c 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -86,6 +86,7 @@ const layer = Layer.effect( Effect.gen(function* () { const hooks = yield* PluginHooks.Service const image = yield* Image.Service + const permission = yield* Permission.Service type NormalizedItem = Tool.Content | "decode" | "size" const normalizeImages = Effect.fnUntraced(function* (content: ReadonlyArray) { @@ -283,10 +284,13 @@ const layer = Layer.effect( const cached = catalog?.data === data && catalog.names === names ? catalog : undefined const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } const codeModeTool = codeModeEnabled - ? CodeModeTool.create(codeModeInventory, (name, tool, input, context) => - beforeExecute(name, input, context).pipe( - Effect.flatMap((event) => executeTool(tool, name, event.input, context)), - ), + ? CodeModeTool.create( + codeModeInventory, + (name, tool, input, context) => + beforeExecute(name, input, context).pipe( + Effect.flatMap((event) => executeTool(tool, name, event.input, context)), + ), + permission, ) : undefined const codeModeCatalog = !codeModeEnabled @@ -413,5 +417,5 @@ function namespaceError(name: string) { export const node = makeLocationNode({ service: Service, layer, - deps: [PluginHooks.node, Image.node], + deps: [PluginHooks.node, Image.node, Permission.node], }) diff --git a/packages/core/test/config/compaction.test.ts b/packages/core/test/config/compaction.test.ts index e8837c58fbb1..3721023f7f4c 100644 --- a/packages/core/test/config/compaction.test.ts +++ b/packages/core/test/config/compaction.test.ts @@ -170,7 +170,7 @@ const input = (tokens: number) => { model: resolved, messages, agent: { id: Agent.defaultID, info: Agent.Info.default(Agent.defaultID) }, - initial: "", + initial: [], tools: { definitions: [], execute: () => Effect.die("unused") }, }, } diff --git a/packages/core/test/config/provider.test.ts b/packages/core/test/config/provider.test.ts index 2acd4a9e3c88..deb5b7b21d0f 100644 --- a/packages/core/test/config/provider.test.ts +++ b/packages/core/test/config/provider.test.ts @@ -818,6 +818,57 @@ describe("ConfigProviderPlugin.Plugin", () => { }), ) + it.effect("preserves plugin-supplied variants on custom models when config omits variants", () => + Effect.gen(function* () { + const models = yield* Model.Service + const customID = Provider.ID.make("custom") + const perModelID = Provider.ID.make("per-model") + const customTiers = ["none", "low", "medium", "xhigh"].map((id) => ({ + id: Model.VariantID.make(id), + settings: { reasoningEffort: id }, + })) + yield* models.transform((editor) => { + for (const id of ["plain", "same-package"]) + editor.update(customID, Model.ID.make(id), (model) => { + model.variants = structuredClone(customTiers) + }) + editor.update(perModelID, Model.ID.make("only-model-package"), (model) => { + model.variants = structuredClone(customTiers) + }) + }) + yield* addPlugin([ + new Document({ + type: "document", + info: decode({ + providers: { + custom: { + package: "aisdk:@ai-sdk/openai-compatible", + models: { + plain: { name: "Plain" }, + "same-package": { package: "aisdk:@ai-sdk/openai-compatible" }, + }, + }, + "per-model": { + models: { + "only-model-package": { package: "aisdk:@ai-sdk/openai-compatible" }, + }, + }, + }, + }), + }), + ]) + + const ids = (providerID: Provider.ID, id: string) => + models + .get(providerID, Model.ID.make(id)) + .pipe(Effect.map((model) => required(model).variants.map((variant) => variant.id))) + const expected = customTiers.map((variant) => variant.id) + expect(yield* ids(customID, "plain")).toEqual(expected) + expect(yield* ids(customID, "same-package")).toEqual(expected) + expect(yield* ids(perModelID, "only-model-package")).toEqual(expected) + }), + ) + it.effect("respells inherited variants when config moves a catalog model to another package", () => Effect.gen(function* () { const providers = yield* Provider.Service diff --git a/packages/core/test/fixture/persistent-pty-daemon.ts b/packages/core/test/fixture/persistent-pty-daemon.ts new file mode 100644 index 000000000000..0555dd286995 --- /dev/null +++ b/packages/core/test/fixture/persistent-pty-daemon.ts @@ -0,0 +1,123 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises" +import net from "node:net" +import os from "node:os" +import path from "node:path" +import { Effect } from "effect" + +export const pong = { type: "pong", instance_id: "test", pid: process.pid, protocol: 7 } + +export function temporaryDirectory() { + return Effect.acquireRelease( + Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "opencode-pty-test-"))), + (directory) => Effect.promise(() => rm(directory, { recursive: true, force: true })), + ) +} + +export function listen( + socketPath: string, + handle: (socket: net.Socket, request: Record, token: string) => object | undefined, +) { + return Effect.acquireRelease( + Effect.promise(async () => { + const sockets = new Set() + const server = net.createServer((socket) => { + sockets.add(socket) + socket.once("close", () => sockets.delete(socket)) + void readRequest(socket) + .then((envelope) => { + const response = + envelope.request.op === "own" ? { type: "owned" } : handle(socket, envelope.request, envelope.token) + if (response) socket.write(frame(response)) + }) + .catch(() => socket.destroy()) + }) + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(socketPath, resolve) + }) + return { + close: () => { + sockets.forEach((socket) => socket.destroy()) + return close(server) + }, + } + }), + (server) => Effect.promise(server.close), + ) +} + +function readRequest(socket: net.Socket) { + return new Promise((resolve, reject) => { + let pending = Buffer.alloc(0) + const cleanup = () => { + socket.off("data", onData) + socket.off("end", onEnd) + socket.off("error", onError) + } + const onData = (value: Buffer) => { + pending = Buffer.concat([pending, value]) + if (pending.length < 4) return + const length = pending.readUInt32BE(0) + if (pending.length < length + 4) return + cleanup() + resolve(pending.subarray(4, length + 4)) + } + const onEnd = () => { + cleanup() + reject(new Error("connection closed before request")) + } + const onError = (error: Error) => { + cleanup() + reject(error) + } + socket.on("data", onData) + socket.on("end", onEnd) + socket.on("error", onError) + }).then((payload) => { + const envelope: unknown = JSON.parse(payload.toString("utf8")) + if (!isRecord(envelope) || typeof envelope.token !== "string" || !isRecord(envelope.request)) + throw new Error("Invalid test daemon envelope") + return { token: envelope.token, request: envelope.request } + }) +} + +function frame(value: object) { + const payload = Buffer.from(JSON.stringify(value)) + const output = Buffer.allocUnsafe(payload.length + 4) + output.writeUInt32BE(payload.length) + payload.copy(output, 4) + return output +} + +export function writeRegistration(directory: string, socket: string, instance = "test", token = "test") { + return writeFile( + path.join(directory, "service.json"), + JSON.stringify({ instance_id: instance, pid: process.pid, protocol: 7, socket, token }), + ) +} + +export function terminal(id: number, groupID = "ses_test") { + return { + id, + pid: null, + title: "test", + foreground_process: null, + group_id: groupID, + command: ["test"], + cwd: "/tmp", + cols: 80, + rows: 24, + lifecycle: { status: "running" }, + output_head: 0, + output_tail: 0, + } +} + +function close(server: net.Server) { + if (!server.listening) return Promise.resolve() + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} diff --git a/packages/core/test/instruction-state.test.ts b/packages/core/test/instruction-state.test.ts index 13abc3867827..0d12d39cbe70 100644 --- a/packages/core/test/instruction-state.test.ts +++ b/packages/core/test/instruction-state.test.ts @@ -274,7 +274,10 @@ describe("InstructionState", () => { const assembled = yield* preview(db, sessionID, instructions) - expect(assembled).toEqual({ initial: "Changed context", update: "" }) + expect(assembled).toEqual({ + initial: [{ key: Instructions.Key.make("test/context"), text: "Changed context" }], + update: "", + }) expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents) expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual(beforeBlobs) expect( @@ -314,7 +317,7 @@ describe("InstructionState", () => { const assembled = yield* preview(db, sessionID, instructions) - expect(assembled.initial).toBe("Initial context") + expect(assembled.initial).toEqual([{ key: Instructions.Key.make("test/context"), text: "Initial context" }]) expect(assembled.update).toBe("Private update") expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents) expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual(beforeBlobs) @@ -344,8 +347,10 @@ describe("InstructionState", () => { const assembled = yield* preview(db, sessionID, instructions) - expect(assembled.initial).toContain("Initial context") - expect(assembled.initial).toContain("Retired context") + expect(assembled.initial).toEqual([ + { key: Instructions.Key.make("test/current"), text: "Initial context" }, + { key: Instructions.Key.make("test/retired"), text: "Retired context" }, + ]) expect(assembled.update).toContain("Changed context") expect(assembled.update).toContain("Removed Retired context") }), @@ -393,7 +398,7 @@ describe("InstructionState", () => { const instructions = source("test/context", Effect.succeed("Initial context")) expect(yield* preview(db, sessionID, instructions)).toEqual({ - initial: "Initial context", + initial: [{ key: Instructions.Key.make("test/context"), text: "Initial context" }], update: "", }) expect(yield* instructionEvents(db, sessionID)).toEqual([]) @@ -418,7 +423,7 @@ describe("InstructionState", () => { const beforeState = yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie) expect(yield* preview(db, sessionID, instructions)).toEqual({ - initial: "Committed context", + initial: [{ key: Instructions.Key.make("test/context"), text: "Committed context" }], update: "", }) expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents) diff --git a/packages/core/test/instructions/index.test.ts b/packages/core/test/instructions/index.test.ts index 4b02a925082d..cc144b192a46 100644 --- a/packages/core/test/instructions/index.test.ts +++ b/packages/core/test/instructions/index.test.ts @@ -47,7 +47,9 @@ describe("Instructions", () => { delta: { "core/date": hash }, blobs: { [hash]: "2026-07-09" }, }) - expect(Instructions.renderInitial(instructions, { "core/date": "2026-07-09" })).toBe("Today's date: 2026-07-09") + expect(Instructions.join(Instructions.renderInitial(instructions, { "core/date": "2026-07-09" }))).toBe( + "Today's date: 2026-07-09", + ) }), ) @@ -189,9 +191,9 @@ describe("Instructions", () => { source({ key: "core/location", value: "location" }), ]) - expect(Instructions.renderInitial(instructions, { "core/date": "date", "core/location": "location" })).toBe( - "date\n\nlocation", - ) + expect( + Instructions.join(Instructions.renderInitial(instructions, { "core/date": "date", "core/location": "location" })), + ).toBe("date\n\nlocation") }) test("rejects duplicate source keys", () => { diff --git a/packages/core/test/lib/instructions.ts b/packages/core/test/lib/instructions.ts index 060bb7683f36..00ef3a0ad2c1 100644 --- a/packages/core/test/lib/instructions.ts +++ b/packages/core/test/lib/instructions.ts @@ -20,7 +20,7 @@ export const readInitial = (instructions: Instructions.List) => ), ), ) - return { ...current, text: Instructions.renderInitial(instructions, current.values) } + return { ...current, text: Instructions.join(Instructions.renderInitial(instructions, current.values)) } }) export const readUpdate = (instructions: Instructions.List, previous: State) => diff --git a/packages/core/test/lib/permission.ts b/packages/core/test/lib/permission.ts index d44f32d0e1a1..447c778da8be 100644 --- a/packages/core/test/lib/permission.ts +++ b/packages/core/test/lib/permission.ts @@ -3,3 +3,10 @@ import { Effect, Layer } from "effect" export const permissionLayer = (overrides: Partial = {}) => Layer.mock(Permission.Service, { close: Effect.void, ...overrides }) + +export const permissionService = (overrides: Partial = {}) => + Effect.runSync( + Effect.gen(function* () { + return yield* Permission.Service + }).pipe(Effect.provide(permissionLayer(overrides))), + ) diff --git a/packages/core/test/mcp.test.ts b/packages/core/test/mcp.test.ts index dff5b6af96d8..89480a7c6e75 100644 --- a/packages/core/test/mcp.test.ts +++ b/packages/core/test/mcp.test.ts @@ -1619,7 +1619,6 @@ it.live("discovers and reads MCP resources through Code Mode", () => 'return await tools.opencode.read_mcp_resource({ server: "resources", uri: "docs://gone" })', ) expect(gone.metadata?.error).toBe(true) - expect(gone.output.output).toContain("Unable to read MCP resource resources:docs://gone") expect(gone.output.output).toContain("Resource not found") const missing = yield* run( 'return await tools.opencode.read_mcp_resource({ server: "missing", uri: "docs://readme" })', diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index 99340d1f90cc..442c1bea06ae 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -521,9 +521,9 @@ describe("shell scanner permission impact", () => { command: "printf ok && git status > output", approved: ["printf *", "git status *"], exact: ["printf ok", "git status"], - denied: "git status", + denied: "git status *", savedEffect: ["allow", "allow"], - exactEffect: ["allow", "allow"], + exactEffect: ["allow", "ask"], deniedEffect: ["deny", "deny"], }, { @@ -532,9 +532,9 @@ describe("shell scanner permission impact", () => { command: "printf ok | cat < input > output", approved: ["printf *", "cat *"], exact: ["printf ok", "cat"], - denied: "cat", + denied: "cat *", savedEffect: ["allow", "allow"], - exactEffect: ["allow", "allow"], + exactEffect: ["allow", "ask"], deniedEffect: ["deny", "deny"], }, { @@ -543,10 +543,10 @@ describe("shell scanner permission impact", () => { command: "FOO=bar > output; printf done", approved: ["printf *"], exact: ["printf done"], - denied: "FOO=bar > output; printf done", - savedEffect: ["ask", "allow"], - exactEffect: ["ask", "allow"], - deniedEffect: ["deny", "allow"], + denied: "FOO=bar > output", + savedEffect: ["ask", "ask"], + exactEffect: ["ask", "ask"], + deniedEffect: ["deny", "deny"], }, { name: "assignment redirect with an approved command substitution", @@ -555,9 +555,9 @@ describe("shell scanner permission impact", () => { approved: ["git describe *"], exact: ["git describe --tags"], denied: "VERSION=$(git describe --tags) > build/version.txt", - savedEffect: ["ask", "allow"], - exactEffect: ["ask", "allow"], - deniedEffect: ["deny", "allow"], + savedEffect: ["ask", "ask"], + exactEffect: ["ask", "ask"], + deniedEffect: ["deny", "deny"], }, { name: "substitution in a saved prefix", @@ -603,6 +603,39 @@ describe("shell scanner permission impact", () => { exactEffect: ["allow", "ask"], deniedEffect: ["deny", "allow"], }, + { + name: "trailing redirect after list operator", + shell: "bash", + command: "true && cat > secret", + approved: ["true *", "cat *"], + exact: ["true", "cat"], + denied: "* > secret*", + savedEffect: ["allow", "allow"], + exactEffect: ["allow", "ask"], + deniedEffect: ["allow", "deny"], + }, + { + name: "commandless redirect write", + shell: "zsh", + command: ">> ~/.zshrc <<< 'x'", + approved: [">> *"], + exact: [">> ~/.zshrc <<< 'x'"], + denied: ">> *", + savedEffect: ["allow", "allow"], + exactEffect: ["allow", "allow"], + deniedEffect: ["deny", "deny"], + }, + { + name: "PowerShell .NET method invocation", + shell: "pwsh", + command: '[IO.File]::Delete("C:\\victim")', + approved: ["[IO.File]::Delete(*"], + exact: ['[IO.File]::Delete("C:\\victim")'], + denied: "*Delete(*", + savedEffect: ["allow", "allow"], + exactEffect: ["allow", "allow"], + deniedEffect: ["deny", "deny"], + }, ] as const) { for (const scenario of [ { name: "no approval", saved: [], rules: [], expected: ["ask", "ask"] }, @@ -718,14 +751,31 @@ describe("shell scanner permission impact", () => { name: "assignment redirect prefix", shell: "bash", command: "FOO=bar > output; printf done", - grants: [["printf *"], ["printf *"]], - // Identical saved rules cover only the native resource, regardless of which parser saved them. + grants: [ + ["printf *"], + ["FOO=bar > *", "printf *"], + ], repeat: [ ["ask", "allow"], ["ask", "allow"], ], - next: "printf next", - nextEffect: ["allow", "allow"], + next: "FOO=bar rm -rf /", + nextEffect: ["ask", "ask"], + }, + { + name: "PowerShell method prefix", + shell: "pwsh", + command: '[IO.File]::Delete("C:\\first")', + grants: [ + ["[IO.File]::Delete(*"], + ["[IO.File]::Delete(*"], + ], + repeat: [ + ["allow", "allow"], + ["allow", "allow"], + ], + next: '[IO.File]::WriteAllText("C:\\first", "x")', + nextEffect: ["ask", "ask"], }, { name: "PowerShell tab prefix", diff --git a/packages/core/test/persistent-pty-daemon.test.ts b/packages/core/test/persistent-pty-daemon.test.ts index 8c0ffc9c7bff..931abbb613ca 100644 --- a/packages/core/test/persistent-pty-daemon.test.ts +++ b/packages/core/test/persistent-pty-daemon.test.ts @@ -1,16 +1,13 @@ import { expect } from "bun:test" import { spawn } from "node:child_process" import { existsSync } from "node:fs" -import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises" -import net from "node:net" -import os from "node:os" +import { mkdir, stat, writeFile } from "node:fs/promises" import path from "node:path" import { Effect } from "effect" import { makeDaemonTransport } from "../src/persistent-pty/daemon" +import { listen, pong, temporaryDirectory, terminal, writeRegistration } from "./fixture/persistent-pty-daemon" import { it } from "./lib/effect" -const pong = { type: "pong", instance_id: "test", pid: process.pid, protocol: 7 } - it.live("rediscovers a same-protocol daemon after its registration rotates", () => Effect.gen(function* () { const { root, directory } = yield* temporaryRuntime() @@ -248,119 +245,3 @@ function temporaryRuntime() { return { root, directory } }) } - -function temporaryDirectory() { - return Effect.acquireRelease( - Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "opencode-pty-test-"))), - (directory) => Effect.promise(() => rm(directory, { recursive: true, force: true })), - ) -} - -function listen( - socketPath: string, - handle: (socket: net.Socket, request: Record, token: string) => object | undefined, -) { - return Effect.acquireRelease( - Effect.promise(async () => { - const sockets = new Set() - const server = net.createServer((socket) => { - sockets.add(socket) - socket.once("close", () => sockets.delete(socket)) - void readRequest(socket) - .then((envelope) => { - const response = - envelope.request.op === "own" ? { type: "owned" } : handle(socket, envelope.request, envelope.token) - if (response) socket.write(frame(response)) - }) - .catch(() => socket.destroy()) - }) - await new Promise((resolve, reject) => { - server.once("error", reject) - server.listen(socketPath, resolve) - }) - return { - close: () => { - sockets.forEach((socket) => socket.destroy()) - return close(server) - }, - } - }), - (server) => Effect.promise(server.close), - ) -} - -function readRequest(socket: net.Socket) { - return new Promise((resolve, reject) => { - let pending = Buffer.alloc(0) - const cleanup = () => { - socket.off("data", onData) - socket.off("end", onEnd) - socket.off("error", onError) - } - const onData = (value: Buffer) => { - pending = Buffer.concat([pending, value]) - if (pending.length < 4) return - const length = pending.readUInt32BE(0) - if (pending.length < length + 4) return - cleanup() - resolve(pending.subarray(4, length + 4)) - } - const onEnd = () => { - cleanup() - reject(new Error("connection closed before request")) - } - const onError = (error: Error) => { - cleanup() - reject(error) - } - socket.on("data", onData) - socket.on("end", onEnd) - socket.on("error", onError) - }).then((payload) => { - const envelope: unknown = JSON.parse(payload.toString("utf8")) - if (!isRecord(envelope) || typeof envelope.token !== "string" || !isRecord(envelope.request)) - throw new Error("Invalid test daemon envelope") - return { token: envelope.token, request: envelope.request } - }) -} - -function frame(value: object) { - const payload = Buffer.from(JSON.stringify(value)) - const output = Buffer.allocUnsafe(payload.length + 4) - output.writeUInt32BE(payload.length) - payload.copy(output, 4) - return output -} - -function writeRegistration(directory: string, socket: string, instance = "test", token = "test") { - return writeFile( - path.join(directory, "service.json"), - JSON.stringify({ instance_id: instance, pid: process.pid, protocol: 7, socket, token }), - ) -} - -function terminal(id: number) { - return { - id, - pid: null, - title: "test", - foreground_process: null, - group_id: "ses_test", - command: ["test"], - cwd: "/tmp", - cols: 80, - rows: 24, - lifecycle: { status: "running" }, - output_head: 0, - output_tail: 0, - } -} - -function close(server: net.Server) { - if (!server.listening) return Promise.resolve() - return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))) -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value) -} diff --git a/packages/core/test/persistent-pty-session.test.ts b/packages/core/test/persistent-pty-session.test.ts new file mode 100644 index 000000000000..16a36db7dcaf --- /dev/null +++ b/packages/core/test/persistent-pty-session.test.ts @@ -0,0 +1,154 @@ +import { describe, expect } from "bun:test" +import { mkdir } from "node:fs/promises" +import path from "node:path" +import { Effect, Fiber, Layer, Option, Stream } from "effect" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Database } from "@opencode/core/database/database" +import { Bus } from "@opencode/core/bus" +import { Instance } from "@opencode/core/instance/service" +import { Location } from "@opencode/core/location" +import { PersistentPty } from "@opencode/core/persistent-pty" +import { Project } from "@opencode/core/project" +import { AbsolutePath } from "@opencode/core/schema" +import { Session } from "@opencode/core/session" +import { SessionExecution } from "@opencode/core/session/execution" +import { SessionModelTransport } from "@opencode/core/session/model-transport" +import { SessionProjector } from "@opencode/core/session/projector" +import { SessionStore } from "@opencode/core/session/store" +import { SessionEnvironment } from "@opencode/core/session/environment" +import { LocationServiceMap } from "@opencode/core/location-services" +import { Removed } from "@opencode/schema/persistent-pty" +import { listen, pong, temporaryDirectory, terminal, writeRegistration } from "./fixture/persistent-pty-daemon" +import { it } from "./lib/effect" +import { globalProjectNode } from "./lib/project" +import { offlineModels } from "./fixture/models" +import { tmpdirScoped } from "./fixture/tmpdir" + +const transport = Layer.succeed( + SessionModelTransport.Service, + SessionModelTransport.Service.of({ + bind: () => ({ execute: () => Effect.die("Unexpected WebSocket execution") }), + close: () => Effect.void, + closeAll: Effect.void, + }), +) + +describe("PersistentPty session cleanup", () => { + it.live("removes a deleted session's terminals", () => + Effect.gen(function* () { + const daemon = yield* fakeDaemon() + yield* Effect.gen(function* () { + const session = yield* Session.Service + const pty = yield* PersistentPty.Service + const bus = yield* Bus.Service + const directory = yield* tmpdirScoped() + const location = Location.Ref.make({ directory: AbsolutePath.make(directory.path) }) + const deleted = yield* session.create({ location }) + const kept = yield* session.create({ location }) + const terminal = yield* pty.create(deleted.id, { args: [], cwd: directory.path, title: "deleted", env: {} }) + const other = yield* pty.create(kept.id, { args: [], cwd: directory.path, title: "kept", env: {} }) + const removed = yield* nextRemoved(bus) + + yield* session.remove(deleted.id) + + expect((yield* Fiber.join(removed)).data).toEqual({ sessionID: deleted.id, ptyID: terminal.id }) + expect(yield* pty.list(deleted.id)).toEqual([]) + expect((yield* pty.list()).map((item) => item.id)).toEqual([other.id]) + }).pipe(Effect.provide(layer(daemon))) + }), + ) + + it.live("keeps cleaning up later deletions after a terminal fails to stop", () => + Effect.gen(function* () { + const daemon = yield* fakeDaemon() + yield* Effect.gen(function* () { + const session = yield* Session.Service + const pty = yield* PersistentPty.Service + const bus = yield* Bus.Service + const directory = yield* tmpdirScoped() + const location = Location.Ref.make({ directory: AbsolutePath.make(directory.path) }) + const first = yield* session.create({ location }) + const second = yield* session.create({ location }) + const stuck = yield* pty.create(first.id, { args: [], cwd: directory.path, title: "stuck", env: {} }) + const terminal = yield* pty.create(second.id, { args: [], cwd: directory.path, title: "second", env: {} }) + yield* pty.control(stuck.id, "att", 80, 24) + daemon.failTerminate.add(stuck.id) + const removed = yield* nextRemoved(bus) + + yield* session.remove(first.id) + yield* session.remove(second.id) + + expect((yield* Fiber.join(removed)).data).toEqual({ sessionID: second.id, ptyID: terminal.id }) + expect((yield* pty.list()).map((item) => item.id)).toEqual([stuck.id]) + // The fake daemon rejects read_rows, so a stale selection would fail instead of returning null. + expect(yield* pty.read(first.id)).toBeNull() + }).pipe(Effect.provide(layer(daemon))) + }), + ) +}) + +const nextRemoved = (bus: Bus.Interface) => + bus.subscribe(Removed).pipe(Stream.runHead, Effect.map(Option.getOrThrow), Effect.forkScoped({ startImmediately: true })) + +// An in-process opencode-pty that the layer adopts through a handoff, so no daemon is spawned. +const fakeDaemon = Effect.fn(function* () { + const base = yield* temporaryDirectory() + const root = path.join(base, "root") + const directory = path.join(root, "inherited") + const socket = path.join(base, "daemon.sock") + const terminals: ReturnType[] = [] + const failTerminate = new Set() + let nextID = 1 + yield* listen(socket, (_socket, request) => { + if (request.op === "ping") return pong + if (request.op === "list") return { type: "terminals", terminals } + if (request.op === "create") { + const created = terminal(nextID++, String(request.group_id)) + terminals.push(created) + return { type: "created", terminal: created } + } + if (request.op === "control") return { type: "ok" } + if (request.op === "terminate") { + if (failTerminate.has(`pty_persistent_${request.id}`)) return { type: "error", message: "terminate failed" } + const index = terminals.findIndex((item) => item.id === request.id) + if (index === -1) return { type: "error", message: `terminal not found: ${String(request.id)}` } + terminals.splice(index, 1) + return { type: "ok" } + } + return { type: "error", message: `unexpected request: ${String(request.op)}` } + }) + yield* Effect.promise(async () => { + await mkdir(directory, { recursive: true }) + await writeRegistration(directory, socket) + }) + return { + failTerminate, + options: { + root, + handoff: { directory, instanceID: "test", ticket: "ticket", expiresAt: Date.now() + 60_000 }, + }, + } +}) + +const layer = (daemon: { readonly options: PersistentPty.Options }) => + AppNodeBuilder.build( + LayerNode.group([ + Database.node, + Bus.node, + SessionProjector.node, + SessionStore.node, + SessionEnvironment.node, + Session.node, + Instance.node, + LocationServiceMap.node, + PersistentPty.node, + ]), + [ + Project.node.replace(globalProjectNode), + SessionExecution.node.replace(SessionExecution.noopLayer), + SessionModelTransport.node.replace(transport), + PersistentPty.node.replace(PersistentPty.configured(daemon.options)), + offlineModels, + ], + ) diff --git a/packages/core/test/plugin/goal.test.ts b/packages/core/test/plugin/goal.test.ts index 39455f77f792..73bdb518e3ba 100644 --- a/packages/core/test/plugin/goal.test.ts +++ b/packages/core/test/plugin/goal.test.ts @@ -504,7 +504,7 @@ function withTools(verdicts: ReturnType) { const last = JSON.stringify(request.messages.at(-1)) return last.includes("tool") && !last.includes("untrusted_objective") ? TestLLM.text("Checked.", "work") - : TestLLM.tool(`call-${verdicts.asked()}`, "missing_tool", {}) + : TestLLM.toolCall(`call-${verdicts.asked()}`, "missing_tool", {}) } } diff --git a/packages/core/test/plugin/provider/claude-agent/claude/branches.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/branches.test.ts new file mode 100644 index 000000000000..5731c26a1b9c --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/branches.test.ts @@ -0,0 +1,286 @@ +import { describe, expect } from "bun:test" +import { Effect, Fiber } from "effect" +import { SessionRecord } from "@opencode/core/plugin/provider/claude-agent/sync/record" +import { RequestKind } from "@opencode/core/plugin/provider/claude-agent/language-model/request-kind" +import { it } from "../../../../lib/effect" +import { FakeClaude } from "../lib/fake-claude" +import { TestSessions } from "../lib/sessions" +import { TestTools } from "../lib/tools" + +const first = TestSessions.prompt("Remember the marker COPPER-OTTER. Reply only with that marker.") + +describe("Claude history branches", () => { + it.effect("a failed compaction deletes its temporary branch and keeps the unmodified primary history resumable", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "billing-error" }), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const before = yield* SessionRecord.make(test.storage).get("session-a") + const reply = yield* TestSessions.reply(test.model, TestSessions.followup("Summarize"), "session-a", "compaction") + const error = reply.find((part) => part.type === "error") + expect(String(error?.error)).toContain("extra usage") + expect(claude.removed).toEqual([claude.forks[0]!.sessionID]) + expect(yield* SessionRecord.make(test.storage).get("session-a")).toEqual(before) + expect(TestSessions.text(yield* TestSessions.reply(test.model, TestSessions.followup())).trim()).toBe( + "COPPER-OTTER", + ) + expect(claude.runs[2]!.args).toContain(`--resume=${before!.claudeSessionID}`) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("an unsupported attachment in changed history fails with its own message before forking", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const edited = TestSessions.followup() + edited[2] = { role: "assistant", content: [{ type: "text", text: "An edited reply" }] } + edited[3] = { role: "user", content: [{ type: "file", mediaType: "image/svg+xml", data: "PHN2Zy8+" }] } + const error = yield* TestSessions.reply(test.model, edited).pipe(Effect.flip) + expect(String(error.cause)).toContain("Claude Code does not support image/svg+xml attachments") + expect(claude.forks).toHaveLength(0) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("a fork finds its source after reload and rebuilds safely if that transcript has disappeared", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + FakeClaude.expectInterrupt(), + ]) + const saved = TestSessions.storage() + const old = yield* TestSessions.start(claude, saved) + yield* TestSessions.reply(old.model, first) + yield* TestSessions.reply(old.model, TestSessions.followup()) + const source = (yield* SessionRecord.make(saved).get("session-a"))! + yield* old.registry.close() + const next = yield* TestSessions.start(claude, saved) + const fork = (sessionID: string) => + Effect.promise(async () => { + const result = await next.model.doStream({ + prompt: TestSessions.followup("A forked question"), + headers: { + [RequestKind.HEADER]: "primary", + [RequestKind.SESSION_HEADER]: sessionID, + [RequestKind.FORK_HEADER]: "session-a", + }, + }) + return TestSessions.collect(result.stream) + }) + yield* fork("child-a") + expect(claude.forks[0]!.source).toBe(source.claudeSessionID) + expect(claude.runs[1]!.args).toContain(`--resume=${claude.forks[0]!.sessionID}`) + claude.transcripts.delete(source.claudeSessionID) + yield* fork("child-b") + expect(claude.forks).toHaveLength(1) + expect(claude.runs[2]!.args.some((arg) => arg.startsWith("--resume="))).toBe(false) + const rebuilt = JSON.stringify( + claude.runs[2]!.received.find((message) => message.type === "user").message.content, + ) + expect(rebuilt).toContain("COPPER-OTTER") + expect(rebuilt).toContain("A forked question") + yield* next.registry.close() + claude.check() + }), + ) + + it.effect("undo resends an unchanged question, then branches again using remapped checkpoints", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const records = SessionRecord.make(test.storage) + yield* TestSessions.reply(test.model, first) + yield* TestSessions.reply(test.model, TestSessions.followup()) + const original = (yield* records.get("session-a"))! + yield* TestSessions.reply(test.model, TestSessions.followup()) + const branch = (yield* records.get("session-a"))! + expect(claude.forks[0]!.boundary).toBe(original.history![1]!.claudeMessageID!) + expect(claude.runs[1]!.received.find((message) => message.type === "user").message.content).toEqual([ + { type: "text", text: "What was the marker? Reply only with it." }, + ]) + expect(branch.claudeSessionID).not.toBe(original.claudeSessionID) + expect(branch.history![1]!.claudeMessageID).not.toBe(original.history![1]!.claudeMessageID) + const reply = yield* TestSessions.reply(test.model, TestSessions.followup("Another replacement")) + expect(claude.forks).toHaveLength(2) + expect(claude.forks[1]).toMatchObject({ + source: branch.claudeSessionID, + boundary: branch.history![1]!.claudeMessageID, + }) + expect(claude.runs[2]!.received.find((message) => message.type === "user").message.content).toEqual([ + { type: "text", text: "Another replacement" }, + ]) + expect(reply.find((part) => part.type === "text-end")?.providerMetadata?.["claude-agent"]?.sessionID).toBe( + claude.forks[1]!.sessionID, + ) + expect(claude.removed).toHaveLength(0) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("an edited earlier reply forks before it and sends the edited history", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const prompt = TestSessions.followup() + prompt[2] = { role: "assistant", content: [{ type: "text", text: "REVISED-MARKER" }] } + yield* TestSessions.reply(test.model, prompt) + expect(claude.forks).toHaveLength(1) + expect(claude.runs[1]!.args).toContain(`--resume=${claude.forks[0]!.sessionID}`) + const user = JSON.stringify(claude.runs[1]!.received.find((message) => message.type === "user").message.content) + expect(user).toContain("REVISED-MARKER") + expect(user).not.toContain("COPPER-OTTER") + yield* test.registry.close() + claude.check() + }), + ) + + it.effect( + "cancelling one generate branch leaves another and the primary session usable, and deletes both temporary branches", + () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "text-cancel" }), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "utility" }), + FakeClaude.expectInterrupt(), + FakeClaude.expectInterrupt({ recording: "text-cancel" }), + FakeClaude.expectInterrupt(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const before = yield* SessionRecord.make(test.storage).get("session-a") + const stream = yield* TestSessions.stream( + test.model, + TestSessions.followup("Write a long answer"), + "session-a", + "generate", + ) + const reader = stream.stream.getReader() + yield* Effect.addFinalizer(() => Effect.promise(() => reader.cancel().catch(() => {}))) + yield* Effect.promise(async () => { + for (;;) { + const part = await reader.read() + if (part.done) throw new Error("Generate ended before cancellation") + if (part.value.type === "text-delta") break + } + }) + const other = yield* TestSessions.reply( + test.model, + TestSessions.followup("Reply only LILAC-HERON"), + "session-a", + "generate", + ) + expect(TestSessions.text(other).trim()).toBe("LILAC-HERON") + expect(claude.forks).toHaveLength(2) + yield* Effect.promise(() => reader.cancel()) + expect(new Set(claude.removed)).toEqual(new Set(claude.forks.map((fork) => fork.sessionID))) + expect(yield* SessionRecord.make(test.storage).get("session-a")).toEqual(before) + expect(claude.runs[0]!.received.some((message) => message.request?.subtype === "interrupt")).toBe(false) + expect(TestSessions.text(yield* TestSessions.reply(test.model, TestSessions.followup())).trim()).toBe( + "COPPER-OTTER", + ) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("compaction drains a parked tool turn and the next primary request starts from the summary alone", () => + Effect.gen(function* () { + const cancel = FakeClaude.replay("tools-waiting-cancel") + const nextUser = cancel.findIndex((step, i) => i > 1 && step.type === "exchange" && step.input.type === "user") + const steps = cancel.slice(0, nextUser) + const terminal = steps.findIndex( + (step) => step.type === "exchange" && step.replies.some((message) => message.type === "result"), + ) + const ending = steps[terminal]! + if (ending.type !== "exchange") throw new Error("Missing recorded terminal result") + const drain = Promise.withResolvers() + steps[terminal] = { ...ending, beforeResult: drain.promise } + const claude = FakeClaude.make([ + ...steps, + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "utility" }), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* Effect.addFinalizer(() => Effect.sync(() => drain.resolve())) + const prompt = TestTools.prompt() + TestTools.append(prompt, yield* TestTools.step(test.model, prompt), () => ({ + type: "execution-denied", + reason: "Compacted", + })) + const summary = yield* TestSessions.reply(test.model, prompt, "session-a", "compaction").pipe(Effect.forkChild) + yield* Effect.promise(() => claude.started(steps[terminal]!)) + expect(claude.forks).toHaveLength(0) + expect(claude.runs).toHaveLength(1) + drain.resolve() + yield* Fiber.join(summary) + expect(claude.forks).toHaveLength(1) + expect(claude.removed).toEqual([claude.forks[0]!.sessionID]) + const compacted = TestSessions.prompt( + "Only SUMMARY-HERON remains.", + ) + yield* TestSessions.reply(test.model, compacted) + expect(claude.runs[2]!.args.some((arg) => arg.startsWith("--resume="))).toBe(false) + const input = JSON.stringify(claude.runs[2]!.received.find((message) => message.type === "user").message.content) + expect(input).toContain("SUMMARY-HERON") + expect(input).not.toContain("lookup") + yield* test.registry.close() + claude.check() + }), + ) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/probe.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/probe.test.ts new file mode 100644 index 000000000000..62ae4bf08432 --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/probe.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, test } from "bun:test" +import { Effect, Fiber } from "effect" +import { TestClock } from "effect/testing" +import { ClaudeProbe } from "@opencode/core/plugin/provider/claude-agent/claude/probe" +import { ClaudeQueryOptions } from "@opencode/core/plugin/provider/claude-agent/claude/query-options" +import { it } from "../../../../lib/effect" +import { FakeClaude } from "../lib/fake-claude" +import { FakeIO } from "../lib/fake-io" + +describe("login check", () => { + it.effect("discovers each model's capacity without sending a prompt", () => + Effect.gen(function* () { + const steps = FakeClaude.replay("startup") + const context = steps.find( + (step) => step.type === "exchange" && step.input.request?.subtype === "get_context_usage", + ) + if (context?.type !== "exchange") throw new Error("Missing context recording") + // Claude's auto-compaction window is not the model's capacity. + context.replies[0].response.response.maxTokens = 200_000 + const claude = FakeClaude.make(steps) + const result = yield* ClaudeProbe.run( + ClaudeQueryOptions.base({ executable: FakeIO.EXECUTABLE, io: FakeIO.make({ claude }) }), + ) + expect(result.models.find((model) => model.value === "opus")?.contextWindow).toBe(1_000_000) + expect(result.models.find((model) => model.value === "claude-opus-4-6")?.contextWindow).toBe(200_000) + expect(claude.runs[0]!.received.some((message) => message.type === "user")).toBe(false) + claude.check() + }), + ) + + it.effect("keeps the login and other limits when one model reports an invalid capacity", () => + Effect.gen(function* () { + const steps = FakeClaude.replay("startup") + const context = steps.find( + (step) => step.type === "exchange" && step.input.request?.subtype === "get_context_usage", + ) + if (context?.type !== "exchange") throw new Error("Missing context recording") + context.replies[0].response.response.rawMaxTokens = 0 + const claude = FakeClaude.make(steps) + const result = yield* ClaudeProbe.run( + ClaudeQueryOptions.base({ executable: FakeIO.EXECUTABLE, io: FakeIO.make({ claude }) }), + ) + expect(ClaudeProbe.isLoggedIn(result.account)).toBe(true) + expect(result.models.find((model) => model.value === "opus")?.contextWindow).toBeUndefined() + expect(result.models.find((model) => model.value === "sonnet")?.contextWindow).toBe(1_000_000) + claude.check() + }), + ) + + it.effect("closes stuck context discovery without turning it into a login failure", () => + Effect.gen(function* () { + const steps = FakeClaude.replay("startup").slice(0, 3) + const context = { ...steps[2]!, hold: new Promise(() => {}) } + steps[2] = context + const claude = FakeClaude.make(steps) + const check = yield* ClaudeProbe.run( + ClaudeQueryOptions.base({ executable: FakeIO.EXECUTABLE, io: FakeIO.make({ claude }) }), + ).pipe(Effect.forkScoped) + yield* Effect.promise(() => claude.started(context)) + yield* TestClock.adjust("30 seconds") + const result = yield* Fiber.join(check) + expect(ClaudeProbe.isLoggedIn(result.account)).toBe(true) + expect(result.models.find((model) => model.value === "opus")?.contextWindow).toBeUndefined() + yield* Effect.promise(() => claude.runs[0]!.closed) + expect(() => claude.check()).toThrow("1 script steps did not finish") + }), + ) + + it.effect("times out a stuck startup and closes the process", () => + Effect.gen(function* () { + const startup = FakeClaude.expectStartup({ hold: new Promise(() => {}) }) + const claude = FakeClaude.make([startup]) + const io = FakeIO.make({ claude }) + const check = yield* ClaudeProbe.run(ClaudeQueryOptions.base({ executable: FakeIO.EXECUTABLE, io })).pipe( + Effect.flip, + Effect.forkScoped, + ) + yield* Effect.promise(() => claude.started(startup)) + yield* TestClock.adjust("30 seconds") + const error = yield* Fiber.join(check) + expect(String(error.cause)).toContain("did not start within 30 seconds") + yield* Effect.promise(() => claude.runs[0]!.closed) + }), + ) +}) + +describe("compatibility and login", () => { + test("only 2.1.248 or later is compatible", () => { + expect(ClaudeProbe.versionError("2.1.248")).toBeUndefined() + expect(ClaudeProbe.versionError("2.1.247")?.message).toContain("claude update") + expect(ClaudeProbe.versionError(undefined)?.message).toContain("claude update") + }) + + test("only a missing credential counts as logged out", () => { + expect(ClaudeProbe.isLoggedIn({ tokenSource: "none", apiProvider: "firstParty" })).toBe(false) + expect(ClaudeProbe.isLoggedIn({ tokenSource: "none", apiKeySource: "ANTHROPIC_API_KEY" })).toBe(true) + expect(ClaudeProbe.isLoggedIn({ subscriptionType: "Claude Team", apiProvider: "firstParty" })).toBe(true) + }) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/recorder.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/recorder.test.ts new file mode 100644 index 000000000000..b487a740aa21 --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/recorder.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from "bun:test" +import { readdirSync, readFileSync } from "node:fs" +import path from "node:path" +import { Recorder } from "../lib/recorder" + +describe("recording privacy", () => { + test("checked-in recordings contain no thinking blocks or deltas", () => { + const directory = path.join(import.meta.dir, "../fixtures/recordings") + for (const name of readdirSync(directory)) { + if (!name.endsWith(".jsonl")) continue + const lines = readFileSync(path.join(directory, name), "utf8").trim().split("\n") + for (const line of lines) { + // Compare booleans so failures cannot print the offending content. + const unchanged = JSON.stringify(Recorder.parse(line)) === JSON.stringify(JSON.parse(line)) + expect(unchanged, name).toBe(true) + } + } + }) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/session.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/session.test.ts new file mode 100644 index 000000000000..c1fa17cd5ecd --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/session.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from "bun:test" +import { ClaudeQueryOptions } from "@opencode/core/plugin/provider/claude-agent/claude/query-options" +import { ClaudeSession } from "@opencode/core/plugin/provider/claude-agent/claude/session" +import { FakeClaude } from "../lib/fake-claude" +import { FakeIO } from "../lib/fake-io" + +describe("Claude session", () => { + test.each([0, 1])("exit code %i before a result reports failure and allows cleanup", async (code) => { + const turn = FakeClaude.expectTurn({ hold: new Promise(() => {}) }) + const claude = FakeClaude.make([FakeClaude.expectStartup(), turn]) + const session = await ClaudeSession.start({ + ...ClaudeQueryOptions.base({ executable: FakeIO.EXECUTABLE, io: FakeIO.make({ claude }) }), + sessionId: crypto.randomUUID(), + }) + try { + await session.ready + session.begin([{ type: "text", text: "Reply with a marker." }]) + await claude.started(turn) + await claude.runs[0]!.exit(code) + const message = code === 0 ? "Claude Code stopped before finishing its reply" : "code 1" + await expect(session.readStep(() => {}, [])).rejects.toThrow(message) + await session.interrupt() + expect(claude.runs[0]!.received.some((message) => message.request?.subtype === "interrupt")).toBe(false) + } finally { + await session.stop() + } + await claude.runs[0]!.closed + expect(() => claude.check()).toThrow("1 script steps did not finish") + }) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/sessions.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/sessions.test.ts new file mode 100644 index 000000000000..042971cae606 --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/sessions.test.ts @@ -0,0 +1,430 @@ +import { describe, expect } from "bun:test" +import { Effect, Fiber } from "effect" +import { TestClock } from "effect/testing" +import { ClaudeSessions } from "@opencode/core/plugin/provider/claude-agent/claude/sessions" +import { ClaudeAgentLanguageModel } from "@opencode/core/plugin/provider/claude-agent/language-model/claude-agent-language-model" +import { RequestKind } from "@opencode/core/plugin/provider/claude-agent/language-model/request-kind" +import { ClaudeSystemPrompt } from "@opencode/core/plugin/provider/claude-agent/language-model/system-prompt" +import { SessionRecord } from "@opencode/core/plugin/provider/claude-agent/sync/record" +import { it } from "../../../../lib/effect" +import { FakeClaude } from "../lib/fake-claude" +import { TestSessions } from "../lib/sessions" +import { TestTools } from "../lib/tools" +import { Recorder } from "../lib/recorder" + +const first = TestSessions.prompt("Remember the marker COPPER-OTTER. Reply only with that marker.") + +describe("Claude sessions", () => { + it.effect("streams consecutive turns once, on one process, with per-turn usage", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const one = yield* TestSessions.reply(test.model, first) + const two = yield* TestSessions.reply(test.model, TestSessions.followup()) + expect(TestSessions.text(one)).toBe("COPPER-OTTER") + expect(TestSessions.text(two)).toBe("COPPER-OTTER") + const finish = two.find((part) => part.type === "finish")! + const usage = Recorder.result("text", 1).usage + expect(finish.usage.inputTokens).toEqual({ + total: usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens, + noCache: usage.input_tokens, + cacheRead: usage.cache_read_input_tokens, + cacheWrite: usage.cache_creation_input_tokens, + }) + expect(finish.usage.outputTokens.total).toBe(usage.output_tokens) + expect(claude.runs).toHaveLength(1) + const users = claude.runs[0]!.received.filter((message) => message.type === "user") + expect(users).toHaveLength(2) + expect(users[1].message.content).toEqual([{ type: "text", text: "What was the marker? Reply only with it." }]) + expect(users[0].client_composed).toBe(true) + yield* test.registry.close() + yield* Effect.promise(() => claude.runs[0]!.closed) + claude.check() + }), + ) + + it.effect("a missing Claude transcript is rebuilt from history, even after a rejected attachment", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const before = (yield* SessionRecord.make(test.storage).get("session-a"))! + yield* test.registry.close() + const registry = ClaudeSessions.registry() + yield* Effect.addFinalizer(() => registry.close()) + const sessions = yield* registry.attach({ + ...test.input, + io: { ...test.input.io, sessionExists: async () => false }, + }) + const model = yield* TestSessions.model(sessions) + const prompt = TestSessions.followup("Inspect this image") + prompt.push({ role: "user", content: [{ type: "file", mediaType: "image/svg+xml", data: "PHN2Zy8+" }] }) + const error = yield* TestSessions.reply(model, prompt).pipe(Effect.flip) + expect(String(error.cause)).toContain("Claude Code does not support image/svg+xml attachments") + yield* TestSessions.reply(model, TestSessions.followup()) + expect(claude.runs).toHaveLength(2) + expect(claude.runs[1]!.args.some((arg) => arg.startsWith("--resume="))).toBe(false) + const user = claude.runs[1]!.received.find((message) => message.type === "user") + expect(JSON.stringify(user.message.content)).toContain("") + expect(JSON.stringify(user.message.content)).toContain("COPPER-OTTER") + expect(JSON.stringify(user.message.content)).not.toContain("image/svg+xml") + const after = (yield* SessionRecord.make(test.storage).get("session-a"))! + expect(after.claudeSessionID).not.toBe(before.claudeSessionID) + yield* registry.close() + claude.check() + }), + ) + + it.effect("cancellation drains past the interrupt receipt before accepting another turn", () => + Effect.gen(function* () { + const drain = Promise.withResolvers() + const interrupt = FakeClaude.expectInterrupt({ recording: "text-cancel", beforeResult: drain.promise }) + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "text-cancel" }), + interrupt, + FakeClaude.expectTurn({ recording: "text-cancel", index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const result = yield* TestSessions.stream(test.model, first) + const reader = result.stream.getReader() + // Wait for real partial text + const partial = yield* Effect.promise(async () => { + for (;;) { + const part = await reader.read() + if (part.done) throw new Error("Reply ended before any text") + if (part.value.type === "text-delta") return part.value.delta + } + }) + const cancel = yield* Effect.promise(() => reader.cancel()).pipe(Effect.forkScoped({ startImmediately: true })) + yield* Effect.promise(() => claude.started(interrupt)) + const prompt = [ + ...first, + { role: "assistant" as const, content: [{ type: "text" as const, text: partial }] }, + { role: "user" as const, content: [{ type: "text" as const, text: "Continue" }] }, + ] + const next = yield* TestSessions.reply(test.model, prompt).pipe(Effect.forkScoped({ startImmediately: true })) + expect(claude.runs[0]!.received.filter((message) => message.type === "user")).toHaveLength(1) + drain.resolve() + yield* Fiber.join(cancel) + expect(TestSessions.text(yield* Fiber.join(next))).toBe("COPPER-OTTER") + // Claude's transcript already holds the partial reply, so only the new input is sent on the same process. + expect(claude.runs).toHaveLength(1) + const users = claude.runs[0]!.received.filter((message) => message.type === "user") + expect(users[1].message.content).toEqual([{ type: "text", text: "Continue" }]) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("cancelled history resumes after a registry restart without replaying the partial reply", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "text-cancel" }), + FakeClaude.expectInterrupt({ recording: "text-cancel" }), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "text-cancel", index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const result = yield* TestSessions.stream(test.model, first) + const reader = result.stream.getReader() + yield* Effect.promise(async () => { + for (;;) { + const part = await reader.read() + if (part.done) throw new Error("Reply ended before any text") + if (part.value.type === "text-delta") break + } + await reader.cancel() + }) + const saved = (yield* SessionRecord.make(test.storage).get("session-a"))! + expect(saved.interrupted).toBe(true) + yield* test.registry.close() + const registry = ClaudeSessions.registry() + yield* Effect.addFinalizer(() => registry.close()) + const sessions = yield* registry.attach(test.input) + const model = yield* TestSessions.model(sessions) + // OpenCode may save no assistant text when cancellation happens early. + const prompt = [...first, { role: "user" as const, content: [{ type: "text" as const, text: "Continue" }] }] + expect(TestSessions.text(yield* TestSessions.reply(model, prompt))).toBe("COPPER-OTTER") + expect(claude.runs[1]!.args).toContain(`--resume=${saved.claudeSessionID}`) + const user = claude.runs[1]!.received.find((message) => message.type === "user") + expect(user.message.content).toEqual([{ type: "text", text: "Continue" }]) + const after = (yield* SessionRecord.make(test.storage).get("session-a"))! + expect(after.interrupted).toBe(false) + yield* registry.close() + claude.check() + }), + ) + + it.effect("chat keeps the Claude Code preset when OpenCode's built-in prompt changes", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const prompt = TestSessions.followup() + prompt[0] = { role: "system", content: "A changed OpenCode built-in agent prompt" } + yield* TestSessions.reply(test.model, prompt) + expect(claude.runs).toHaveLength(1) + const run = claude.runs[0]! + const init = run.received.find((message) => message.request?.subtype === "initialize").request + expect(init.systemPrompt).toBeUndefined() + expect(JSON.stringify(run.received)).not.toContain("A changed OpenCode built-in agent prompt") + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("a turn arriving during idle shutdown waits for the old process, then resumes its session", () => + Effect.gen(function* () { + const release = Promise.withResolvers() + const stop = FakeClaude.expectInterrupt({ hold: release.promise }) + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + stop, + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "text-resume" }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + const id = claude.runs[0]!.args.find((arg) => arg.startsWith("--session-id="))!.split("=")[1] + const timeout = yield* TestClock.adjust(ClaudeSessions.IDLE_MS).pipe( + Effect.forkScoped({ startImmediately: true }), + ) + yield* Effect.promise(() => claude.started(stop)) + const next = yield* TestSessions.reply(test.model, TestSessions.followup()).pipe( + Effect.forkScoped({ startImmediately: true }), + ) + expect(claude.runs).toHaveLength(1) + release.resolve() + yield* Fiber.join(timeout) + expect(TestSessions.text(yield* Fiber.join(next))).toBe("COPPER-OTTER") + yield* Effect.promise(() => claude.runs[0]!.closed) + expect(claude.runs).toHaveLength(2) + expect(claude.runs[1]!.args).toContain(`--resume=${id}`) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("cancelling during startup closes it and does not save a nonexistent session", () => + Effect.gen(function* () { + const startup = FakeClaude.expectStartup({ hold: new Promise(() => {}) }) + const claude = FakeClaude.make([ + startup, + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const stream = yield* TestSessions.stream(test.model, first) + yield* Effect.promise(() => claude.started(startup)) + yield* Effect.promise(() => stream.stream.cancel()) + yield* Effect.promise(() => claude.runs[0]!.closed) + expect(test.storage.data.size).toBe(0) + expect(TestSessions.text(yield* TestSessions.reply(test.model, first))).toBe("COPPER-OTTER") + expect(claude.runs[1]!.args.some((arg) => arg.startsWith("--resume="))).toBe(false) + yield* test.registry.close() + expect(() => claude.check()).toThrow("1 script steps did not finish") + }), + ) + + it.effect("chat checks compatibility before sending a prompt", () => + Effect.gen(function* () { + const startup = FakeClaude.expectStartup() + startup.reply.claude_code_version = "2.1.247" + const claude = FakeClaude.make([startup]) + const test = yield* TestSessions.start(claude) + const error = yield* TestSessions.reply(test.model, first).pipe(Effect.flip) + expect(String(error.cause)).toContain("claude update") + expect(claude.runs[0]!.received.some((message) => message.type === "user")).toBe(false) + yield* Effect.promise(() => claude.runs[0]!.closed) + claude.check() + }), + ) + + it.effect("changes model and effort live, and resumes when the output limit changes or is cleared", () => + Effect.gen(function* () { + const controls = FakeClaude.replay("controls").filter( + (step) => + step.type === "exchange" && ["set_model", "apply_flag_settings"].includes(step.input.request?.subtype), + ) + const recorded = (index: number) => FakeClaude.expectTurn({ recording: "controls", index }) + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + recorded(0), + controls[0]!, + recorded(1), + controls[1]!, + recorded(2), + controls[2]!, + controls[3]!, + recorded(3), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + recorded(4), + FakeClaude.expectInterrupt(), + FakeClaude.expectStartup(), + recorded(4), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const prompt = TestSessions.prompt("Remember CONTROL-OTTER. Reply only CONTROL-OTTER.") + const settings = [ + { model: "haiku", effort: "low", maxOutputTokens: 2048 }, + { model: "haiku", effort: "high", maxOutputTokens: 2048 }, + { model: "haiku", maxOutputTokens: 2048 }, + { model: "sonnet", effort: "low", maxOutputTokens: 2048 }, + { model: "sonnet", effort: "low", maxOutputTokens: 4096 }, + { model: "sonnet", effort: "low" }, + ] + for (const setting of settings) { + const model = new ClaudeAgentLanguageModel.Model(setting.model, test.model.dependencies) + const result = yield* Effect.promise(() => + model.doStream({ + prompt, + maxOutputTokens: setting.maxOutputTokens, + providerOptions: { "claude-agent": setting.effort ? { effort: setting.effort } : {} }, + headers: { [RequestKind.HEADER]: "primary", [RequestKind.SESSION_HEADER]: "session-a" }, + }), + ) + expect(TestSessions.text(yield* Effect.promise(() => TestSessions.collect(result.stream)))).toBe( + "CONTROL-OTTER", + ) + prompt.push( + { role: "assistant", content: [{ type: "text", text: "CONTROL-OTTER" }] }, + { role: "user", content: [{ type: "text", text: "What was the marker? Reply only with it." }] }, + ) + } + expect(claude.runs).toHaveLength(3) + const id = claude.runs[0]!.args.find((arg) => arg.startsWith("--session-id="))!.split("=")[1] + const requests = claude.runs[0]!.received.map((message) => message.request) + expect(requests).toContainEqual({ subtype: "set_model", model: "sonnet" }) + expect(requests).toContainEqual({ subtype: "apply_flag_settings", settings: { effortLevel: "high" } }) + expect(requests).toContainEqual({ subtype: "apply_flag_settings", settings: { effortLevel: null } }) + expect(claude.runs[0]!.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBe("2048") + expect(claude.runs[1]!.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBe("4096") + expect(claude.runs[2]!.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBeUndefined() + for (const run of claude.runs.slice(1)) { + expect(run.args).toContain("--model=sonnet") + expect(run.args).toContain(`--resume=${id}`) + } + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("titles use their own task prompt in a throwaway session that leaves the chat alone", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "utility" }), + FakeClaude.expectInterrupt(), + FakeClaude.expectTurn({ index: 1 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + yield* TestSessions.reply(test.model, first) + yield* TestSessions.reply(test.model, TestSessions.followup(), "session-a", "title") + expect(TestSessions.text(yield* TestSessions.reply(test.model, TestSessions.followup()))).toBe("COPPER-OTTER") + expect(claude.runs).toHaveLength(2) + const title = claude.runs[1]! + const init = title.received.find((message) => message.request?.subtype === "initialize").request + expect(init.systemPrompt).toEqual(["You are a concise test assistant."]) + expect(title.args).toContain("--no-session-persistence") + expect(test.storage.data.size).toBe(1) + yield* test.registry.close() + claude.check() + }), + ) + + // Claude's prompt cache only matches when tools and system prompt are identical, so branches must not drop them. + it.effect("conversation branches send the chat's tools and system prompt, and a tool call ends the branch", () => + Effect.gen(function* () { + // The branch replays a recorded tool call that is stopped while waiting for its result. + const waiting = FakeClaude.replay("tools-waiting-cancel") + const resumed = waiting.findIndex( + (step, index) => index > 1 && step.type === "exchange" && step.input.type === "user", + ) + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn(), + ...waiting.slice(0, resumed), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + // OpenCode's session hooks set these on chats and branches alike. + const settings = { + "claude-agent": { + [ClaudeSystemPrompt.AGENT_OPTION]: "AGENT-ROLE", + [ClaudeSystemPrompt.INSTRUCTIONS_OPTION]: "OPENCODE-INSTRUCTIONS", + }, + } + yield* TestTools.step(test.model, first, TestTools.tools, "primary", settings) + const parts = yield* TestTools.step(test.model, TestSessions.followup(), TestTools.tools, "generate", settings) + const chat = claude.runs[0]!.received.find((message) => message.request?.subtype === "initialize").request + const branch = claude.runs[1]!.received.find((message) => message.request?.subtype === "initialize").request + expect(chat.sdkMcpServers).toEqual(["opencode"]) + expect(branch.sdkMcpServers).toEqual(chat.sdkMcpServers) + expect(chat.appendSystemPrompt).toContain("AGENT-ROLE") + expect(chat.appendSystemPrompt).toContain("OPENCODE-INSTRUCTIONS") + expect(branch.appendSystemPrompt).toBe(chat.appendSystemPrompt) + // The reply ends at the tool call, and the throwaway process and fork are cleaned up. + expect(parts.filter((part) => part.type === "tool-call")).toHaveLength(2) + yield* Effect.promise(() => claude.runs[1]!.closed) + expect(claude.removed).toEqual([claude.forks[0]!.sessionID]) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("closing the registry interrupts and drains a running side call", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "text-cancel" }), + FakeClaude.expectInterrupt({ recording: "text-cancel" }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const stream = yield* TestSessions.stream(test.model, first, "session-a", "generate") + const reader = stream.stream.getReader() + yield* Effect.addFinalizer(() => Effect.promise(() => reader.cancel().catch(() => {}))) + yield* Effect.promise(async () => { + for (;;) { + const part = await reader.read() + if (part.done) throw new Error("Reply ended before shutdown could be tested") + if (part.value.type === "text-delta") break + } + }) + yield* test.registry.close() + yield* Effect.promise(() => claude.runs[0]!.closed) + expect(test.storage.data.size).toBe(0) + claude.check() + }), + ) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/status.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/status.test.ts new file mode 100644 index 000000000000..50df3cef03ed --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/status.test.ts @@ -0,0 +1,67 @@ +import { describe, expect } from "bun:test" +import { Effect, Fiber, SubscriptionRef } from "effect" +import { ClaudeProbe } from "@opencode/core/plugin/provider/claude-agent/claude/probe" +import { ClaudeStatus } from "@opencode/core/plugin/provider/claude-agent/claude/status" +import { it } from "../../../../lib/effect" +import { FakeClaude } from "../lib/fake-claude" +import { FakeIO } from "../lib/fake-io" + +describe("login status", () => { + it.effect("finds claude when it is installed after the plugin starts", () => + Effect.gen(function* () { + const claude = FakeClaude.make([FakeClaude.expectStartup()]) + let executable: string | undefined + const io = { ...FakeIO.make({ claude }), which: () => executable } + const status = yield* ClaudeStatus.make(io, () => Effect.succeed({})) + + yield* status.refresh() + expect(yield* SubscriptionRef.get(status.state)).toEqual({ type: "missing" }) + + executable = FakeIO.EXECUTABLE + yield* status.refresh() + expect((yield* SubscriptionRef.get(status.state)).type).toBe("ready") + claude.check() + }), + ) + + it.effect("a reconnect waits for the startup check, then publishes the new login", () => + Effect.gen(function* () { + const hold = Promise.withResolvers() + const atStart = FakeClaude.expectStartup({ recording: "startup-logged-out", hold: hold.promise }) + const onConnect = FakeClaude.expectStartup() + const claude = FakeClaude.make([atStart, onConnect]) + const status = yield* ClaudeStatus.make(FakeIO.make({ claude }), () => Effect.succeed({})) + + const startup = yield* status.refresh().pipe(Effect.forkScoped) + yield* Effect.promise(() => claude.started(atStart)) + const reconnect = yield* status.refresh().pipe(Effect.forkScoped({ startImmediately: true })) + expect(claude.runs).toHaveLength(1) + + hold.resolve() + yield* Fiber.join(startup) + yield* Fiber.join(reconnect) + const state = yield* SubscriptionRef.get(status.state) + expect(state.type).toBe("ready") + if (state.type !== "ready") throw new Error("login check did not finish") + expect(ClaudeProbe.isLoggedIn(state.probe.account)).toBe(true) + claude.check() + }), + ) + + it.effect("reports a failed startup and recovers on the next check", () => + Effect.gen(function* () { + const claude = FakeClaude.make([FakeClaude.expectStartup({ exitCode: 1 }), FakeClaude.expectStartup()]) + const status = yield* ClaudeStatus.make(FakeIO.make({ claude }), () => Effect.succeed({})) + + yield* status.refresh() + const failed = yield* SubscriptionRef.get(status.state) + expect(failed.type).toBe("failed") + if (failed.type !== "failed") throw new Error("startup failure was not reported") + expect(failed.message).toContain("code 1") + + yield* status.refresh() + expect((yield* SubscriptionRef.get(status.state)).type).toBe("ready") + claude.check() + }), + ) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/sync.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/sync.test.ts new file mode 100644 index 000000000000..02c0146edf03 --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/sync.test.ts @@ -0,0 +1,70 @@ +import { describe, expect } from "bun:test" +import type { LanguageModelV3Prompt } from "@ai-sdk/provider" +import { Effect } from "effect" +import { SessionRecord } from "@opencode/core/plugin/provider/claude-agent/sync/record" +import { it } from "../../../../lib/effect" +import { FakeClaude } from "../lib/fake-claude" +import { TestSessions } from "../lib/sessions" + +describe("recorded history sync", () => { + it.effect("catches up once, saves transcript boundaries, then continues without replaying history", () => + Effect.gen(function* () { + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + FakeClaude.expectTurn({ recording: "sync" }), + FakeClaude.expectTurn({ recording: "sync", index: 1 }), + FakeClaude.expectTurn({ recording: "sync", index: 2 }), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const history: LanguageModelV3Prompt = [ + { role: "user", content: [{ type: "text", text: "Give me a marker." }] }, + { role: "assistant", content: [{ type: "text", text: "My marker is LILAC-HERON." }] }, + ] + const ask = Effect.fn(function* (text: string) { + history.push({ role: "user", content: [{ type: "text", text }] }) + const parts = yield* TestSessions.reply(test.model, history) + const reply = TestSessions.text(parts) + history.push({ role: "assistant", content: [{ type: "text", text: reply }] }) + return reply + }) + yield* ask("Remember COPPER-OTTER too. Reply only with COPPER-OTTER.") + history.push( + { role: "user", content: [{ type: "text", text: "Read the marker file." }] }, + { + role: "assistant", + content: [{ type: "tool-call", toolCallId: "marker-read", toolName: "read", input: { path: "marker.txt" } }], + }, + { + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: "marker-read", + toolName: "read", + output: { type: "text", value: "LEMON-IBIS" }, + }, + ], + }, + { role: "assistant", content: [{ type: "text", text: "I read the file successfully." }] }, + ) + yield* ask("List all three markers from our conversation, including the file. Output only the markers.") + yield* ask("Repeat those three markers.") + expect(claude.runs).toHaveLength(1) + const users = claude.runs[0]!.received.filter((message) => message.type === "user") + expect(JSON.stringify(users[0].message.content)).toContain("LILAC-HERON") + expect(JSON.stringify(users[1].message.content)).toContain("LEMON-IBIS") + expect(JSON.stringify(users[1].message.content)).not.toContain("LILAC-HERON") + expect(users[2].message.content).toEqual([{ type: "text", text: "Repeat those three markers." }]) + const record = (yield* SessionRecord.make(test.storage).get("session-a"))! + expect(record.history).toHaveLength(12) + expect(record.history![2]!.claudeMessageID).toBe(users[0].uuid) + expect(record.history![8]!.claudeMessageID).toBe(users[1].uuid) + expect(record.history![10]!.claudeMessageID).toBe(users[2].uuid) + // Catch-up's interior messages don't claim independent transcript boundaries. + expect(record.history![5]!.claudeMessageID).toBeUndefined() + yield* test.registry.close() + claude.check() + }), + ) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/claude/tools.test.ts b/packages/core/test/plugin/provider/claude-agent/claude/tools.test.ts new file mode 100644 index 000000000000..8d1b852efce5 --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/claude/tools.test.ts @@ -0,0 +1,364 @@ +import { describe, expect } from "bun:test" +import { Effect, Exit, Fiber, Scope } from "effect" +import { TestClock } from "effect/testing" +import { ClaudeSessions } from "@opencode/core/plugin/provider/claude-agent/claude/sessions" +import { it } from "../../../../lib/effect" +import { FakeClaude } from "../lib/fake-claude" +import { TestSessions } from "../lib/sessions" +import { TestTools } from "../lib/tools" +import { Recorder } from "../lib/recorder" + +describe("Claude tool steps", () => { + it.effect("two tool steps keep one turn alive past the idle timeout and match every result to its call", () => + Effect.gen(function* () { + const claude = FakeClaude.make(FakeClaude.replay("tools")) + const test = yield* TestSessions.start(claude) + const prompt = TestTools.prompt() + const steps = [] + for (let i = 0; i < 3; i++) { + // Subagents and unanswered permission prompts can keep OpenCode's tools running this long. + yield* TestClock.adjust(ClaudeSessions.IDLE_MS * 2) + const parts = yield* TestTools.step(test.model, prompt) + steps.push(parts) + TestTools.append(prompt, parts, TestTools.output) + } + expect(steps[0]!.filter((part) => part.type === "tool-call")).toHaveLength(2) + expect(steps[1]!.find((part) => part.type === "tool-call")?.toolName).toBe("confirm") + expect(TestSessions.text(steps[2]!)).toBe("COPPER-OTTER") + expect(claude.runs).toHaveLength(1) + const received = claude.runs[0]!.received + expect(received.filter((message) => message.type === "user")).toHaveLength(1) + expect(received.some((message) => message.request?.subtype === "interrupt")).toBe(false) + const outputs = received + .filter((message) => message.response?.response?.mcp_response) + .map((message) => message.response.response.mcp_response.result) + expect(outputs.map((result) => result.content[0].text)).toEqual(["LILAC-HERON", "LEMON-IBIS", "COPPER-OTTER"]) + const usage = Recorder.load("tools").filter( + (line) => + line.from === "claude" && line.message.type === "stream_event" && line.message.event.type === "message_delta", + ) + for (let i = 0; i < steps.length; i++) { + const recorded = usage[i]! + if (recorded.from !== "claude") throw new Error("Expected Claude usage") + expect(steps[i]!.find((part) => part.type === "finish")?.usage.outputTokens.total).toBe( + recorded.message.event.usage.output_tokens, + ) + } + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("plugin reload hands over the process with its pending handlers; without a reload it shuts down", () => + Effect.gen(function* () { + const claude = FakeClaude.make(FakeClaude.replay("tools")) + const base = yield* TestSessions.start(FakeClaude.make([])) + const input = { ...base.input, io: { ...base.input.io, spawn: claude.spawn } } + const registry = ClaudeSessions.registry() + yield* Effect.addFinalizer(() => registry.close()) + const scope = yield* Scope.make() + const old = yield* registry.attach(input).pipe(Effect.provideService(Scope.Scope, scope)) + const prompt = TestTools.prompt() + TestTools.append(prompt, yield* TestTools.step(yield* TestSessions.model(old), prompt), TestTools.output) + yield* Scope.close(scope, Exit.void) + yield* TestClock.adjust(ClaudeSessions.HANDOVER_MS - 1) + const next = yield* Scope.make() + const fresh = yield* TestSessions.model( + yield* registry.attach(input).pipe(Effect.provideService(Scope.Scope, next)), + ) + TestTools.append(prompt, yield* TestTools.step(fresh, prompt), TestTools.output) + expect(TestSessions.text(yield* TestTools.step(fresh, prompt))).toBe("COPPER-OTTER") + expect(claude.runs).toHaveLength(1) + yield* Scope.close(next, Exit.void) + yield* TestClock.adjust(ClaudeSessions.HANDOVER_MS) + yield* Effect.promise(() => claude.runs[0]!.closed) + claude.check() + }), + ) + + it.effect("closing the registry waits for a running tool call to drain, without answering it", () => + Effect.gen(function* () { + const cancel = FakeClaude.replay("tools-waiting-cancel") + const nextUser = cancel.findIndex( + (step, index) => index > 1 && step.type === "exchange" && step.input.type === "user", + ) + const steps = cancel.slice(0, nextUser) + const drain = Promise.withResolvers() + const terminal = steps.findIndex( + (step) => step.type === "exchange" && step.replies.some((message) => message.type === "result"), + ) + const ending = steps[terminal]! + if (ending.type !== "exchange") throw new Error("Missing interrupt result recording") + steps[terminal] = { ...ending, beforeResult: drain.promise } + const claude = FakeClaude.make(steps) + const test = yield* TestSessions.start(claude) + yield* Effect.addFinalizer(() => Effect.sync(() => drain.resolve())) + const prompt = TestTools.prompt() + yield* TestTools.step(test.model, prompt) + let stopped = false + const close = yield* test.registry.close().pipe( + Effect.andThen( + Effect.sync(() => { + stopped = true + }), + ), + Effect.forkChild, + ) + yield* Effect.promise(() => claude.started(steps[terminal]!)) + yield* Effect.yieldNow + expect(stopped).toBe(false) + const call = Recorder.load("tools-waiting-cancel").find( + (line) => line.from === "claude" && line.message.request?.message?.method === "tools/call", + ) + if (!call || call.from !== "claude") throw new Error("Missing recorded MCP call") + expect(claude.runs[0]!.received.some((message) => message.response?.request_id === call.message.request_id)).toBe( + false, + ) + drain.resolve() + yield* Fiber.join(close) + expect(claude.runs[0]!.received.filter((message) => message.request?.subtype === "interrupt")).toHaveLength(1) + claude.check() + }), + ) + + it.effect("a turn left waiting for tool results stops IDLE_MS after OpenCode stops running the session", () => + Effect.gen(function* () { + const cancel = FakeClaude.replay("tools-waiting-cancel") + const nextUser = cancel.findIndex( + (step, index) => index > 1 && step.type === "exchange" && step.input.type === "user", + ) + const claude = FakeClaude.make(cancel.slice(0, nextUser)) + const test = yield* TestSessions.start(claude) + yield* TestTools.step(test.model, TestTools.prompt()) + yield* test.sessions.idle("session-a") + yield* TestClock.adjust(ClaudeSessions.IDLE_MS) + yield* Effect.promise(() => claude.runs[0]!.closed) + claude.check() + }), + ) + + it.effect("a process exit while OpenCode runs tools resumes with their saved results", () => + Effect.gen(function* () { + const steps = FakeClaude.replay("tools-cancel") + const interrupt = steps.findIndex( + (step) => step.type === "exchange" && step.input.request?.subtype === "interrupt", + ) + // The first process exits instead of receiving an orderly interrupt. Keep the recorded resume. + const claude = FakeClaude.make([...steps.slice(0, interrupt), ...steps.slice(interrupt + 1)]) + const test = yield* TestSessions.start(claude) + const prompt = TestTools.prompt() + TestTools.append(prompt, yield* TestTools.step(test.model, prompt), TestTools.output) + yield* Effect.promise(() => claude.runs[0]!.exit(1)) + expect(TestSessions.text(yield* TestTools.step(test.model, prompt))).toContain("CANCELLED-OTTER") + const resumed = claude.runs[1]! + const user = resumed.received.find((message) => message.type === "user") + expect(JSON.stringify(user.message.content)).toContain("LILAC-HERON") + expect(JSON.stringify(user.message.content)).toContain("LEMON-IBIS") + expect(resumed.args.some((arg) => arg.startsWith("--resume="))).toBe(true) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("results that do not answer every waiting call stop the turn and rebuild from the full history", () => + Effect.gen(function* () { + const claude = FakeClaude.make(FakeClaude.replay("tools-cancel")) + const test = yield* TestSessions.start(claude) + const prompt = TestTools.prompt() + TestTools.append(prompt, yield* TestTools.step(test.model, prompt), TestTools.output) + const results = prompt.at(-1)! + if (results.role !== "tool") throw new Error("Expected tool results") + // Drop the second lookup's result, so one waiting call has no answer. + results.content.pop() + prompt.push({ + role: "user", + content: [{ type: "text", text: "Do not call any tools. Reply only with CANCELLED-OTTER." }], + }) + expect(TestSessions.text(yield* TestTools.step(test.model, prompt))).toContain("CANCELLED-OTTER") + expect(claude.runs).toHaveLength(2) + expect(claude.runs[0]!.received.filter((message) => message.request?.subtype === "interrupt")).toHaveLength(1) + const rebuilt = claude.runs[1]! + expect(rebuilt.args.some((arg) => arg.startsWith("--resume="))).toBe(false) + const user = JSON.stringify(rebuilt.received.find((message) => message.type === "user").message.content) + expect(user).toContain("") + expect(user).toContain("LILAC-HERON") + expect(user).not.toContain("LEMON-IBIS") + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("active-turn steering delivers tool feedback and new input through the SDK queue", () => + Effect.gen(function* () { + const claude = FakeClaude.make(FakeClaude.replay("tools-continue")) + const test = yield* TestSessions.start(claude) + const prompt = TestTools.prompt() + TestTools.append(prompt, yield* TestTools.step(test.model, prompt), () => ({ + type: "execution-denied", + reason: "Cancelled by user.", + })) + prompt.push({ + role: "user", + content: [ + { + type: "text", + text: "The calls were cancelled. Do not call any more tools. Reply only with CONTINUED-OTTER.", + }, + ], + }) + expect(TestSessions.text(yield* TestTools.step(test.model, prompt)).trim()).toBe("CONTINUED-OTTER") + expect(claude.runs).toHaveLength(1) + const messages = claude.runs[0]!.received + expect(messages.some((message) => message.request?.subtype === "interrupt")).toBe(false) + expect(messages.filter((message) => message.type === "user").at(-1).priority).toBe("next") + expect(messages.filter((message) => message.type === "user").at(-1).message.content).toEqual( + prompt.at(-1)!.content, + ) + const results = messages.filter((message) => message.response?.response?.mcp_response?.result) + expect(results).toHaveLength(2) + for (const message of results) + expect(message.response.response.mcp_response.result).toEqual({ + isError: true, + content: [{ type: "text", text: "Cancelled by user." }], + }) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("an aborted tool drains the old turn before sending a fresh user message on the same process", () => + Effect.gen(function* () { + const steps = FakeClaude.replay("tools-abort") + const drain = Promise.withResolvers() + const terminal = steps.findIndex( + (step) => step.type === "exchange" && step.replies.some((message) => message.type === "result"), + ) + const ending = steps[terminal]! + if (ending.type !== "exchange") throw new Error("Missing interrupt result recording") + steps[terminal] = { ...ending, beforeResult: drain.promise } + const claude = FakeClaude.make(steps) + const test = yield* TestSessions.start(claude) + yield* Effect.addFinalizer(() => Effect.sync(() => drain.resolve())) + const prompt = TestTools.prompt() + const first = yield* TestTools.step(test.model, prompt) + TestTools.append(prompt, first, () => ({ type: "execution-denied", reason: "Cancelled by user." }), { + "claude-agent": { toolError: true, toolAborted: true }, + }) + prompt.push({ + role: "user", + content: [ + { + type: "text", + text: "The calls were cancelled. Do not call any more tools. Reply only with CONTINUED-OTTER.", + }, + ], + }) + const next = yield* TestTools.step(test.model, prompt).pipe(Effect.forkChild) + yield* Effect.promise(() => claude.started(steps[terminal]!)) + const messages = claude.runs[0]!.received + // The interrupt receipt is insufficient: no new input until the terminal result flushes. + expect(messages.filter((message) => message.type === "user")).toHaveLength(1) + expect(messages.some((message) => message.response?.response?.mcp_response?.result?.content)).toBe(false) + drain.resolve() + expect(TestSessions.text(yield* Fiber.join(next)).trim()).toBe("CONTINUED-OTTER") + expect(claude.runs).toHaveLength(1) + expect(messages.filter((message) => message.request?.subtype === "interrupt")).toHaveLength(1) + const user = messages.filter((message) => message.type === "user").at(-1) + expect(user.priority).toBeUndefined() + expect(JSON.stringify(user.message.content)).toContain("Cancelled by user.") + expect(user.message.content.at(-1)).toEqual(prompt.at(-1)!.content[0]) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("tool images and PDFs reach Claude as image and document content", () => + Effect.gen(function* () { + // Only the first process: the recording goes on to change the tool list. + const steps = FakeClaude.replay("tools-media") + const restart = steps.findIndex((step, index) => index > 0 && step.type === "startup") + const claude = FakeClaude.make(steps.slice(0, restart)) + const test = yield* TestSessions.start(claude) + const tools = [ + { ...TestTools.tools[0]!, name: "attachment", inputSchema: { type: "object" as const, properties: {} } }, + ] + const prompt = TestSessions.prompt("Call attachment once. Report the image color and the marker from its PDF.") + TestTools.append(prompt, yield* TestTools.step(test.model, prompt, tools), () => ({ + type: "text", + value: "Read the attached image and PDF.", + })) + const image = yield* Effect.promise(() => Bun.file(new URL("../fixtures/red.png", import.meta.url)).bytes()) + const pdf = yield* Effect.promise(() => Bun.file(new URL("../fixtures/marker.pdf", import.meta.url)).bytes()) + prompt.push({ + role: "user", + content: [ + { type: "text", text: "Attached media from tool result:" }, + { type: "file", mediaType: "image/png", data: image }, + { type: "file", mediaType: "application/pdf", data: pdf }, + ], + }) + yield* TestTools.step(test.model, prompt, tools) + const replacement = claude.runs[0]!.received.find( + (message) => message.response?.response?.hookSpecificOutput?.updatedMCPToolOutput, + ) + expect(replacement.response.response.hookSpecificOutput.updatedMCPToolOutput).toEqual([ + { type: "text", text: "Read the attached image and PDF." }, + { + type: "image", + source: { type: "base64", media_type: "image/png", data: Buffer.from(image).toString("base64") }, + }, + { + type: "document", + source: { type: "base64", media_type: "application/pdf", data: Buffer.from(pdf).toString("base64") }, + }, + ]) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("a last step without tools stops the parked turn and resumes with the saved result", () => + Effect.gen(function* () { + const claude = FakeClaude.make(FakeClaude.replay("max-steps")) + const test = yield* TestSessions.start(claude) + const lookup = [{ ...TestTools.tools[0]!, inputSchema: { type: "object" as const, properties: {} } }] + const prompt = TestSessions.prompt("Call lookup once, then call it again, then report the marker.") + TestTools.append(prompt, yield* TestTools.step(test.model, prompt, lookup), () => ({ + type: "text", + value: "STEP-OTTER", + })) + prompt.push({ role: "user", content: [{ type: "text", text: "MAXIMUM STEPS REACHED. Respond with text only." }] }) + yield* TestTools.step(test.model, prompt, []) + expect(claude.runs).toHaveLength(2) + const final = claude.runs[1]! + expect(final.args.some((arg) => arg.startsWith("--resume="))).toBe(true) + const init = final.received.find((message) => message.request?.subtype === "initialize").request + expect(init.sdkMcpServers).toBeUndefined() + expect(JSON.stringify(final.received.find((message) => message.type === "user").message.content)).toContain( + "STEP-OTTER", + ) + yield* test.registry.close() + claude.check() + }), + ) + + it.effect("an unavailable OpenCode server fails closed", () => + Effect.gen(function* () { + const turn = FakeClaude.expectTurn() + const init = turn.replies.find((message) => message.type === "system" && message.subtype === "init") + init.mcp_servers = [{ name: "opencode", status: "failed" }] + const claude = FakeClaude.make([ + FakeClaude.expectStartup(), + turn, + FakeClaude.expectInterrupt(), + FakeClaude.expectInterrupt(), + ]) + const test = yield* TestSessions.start(claude) + const error = yield* TestTools.step(test.model, TestTools.prompt()).pipe(Effect.flip) + expect(String(error.cause)).toContain("OpenCode tool server did not connect") + expect(claude.runs).toHaveLength(1) + yield* test.registry.close() + claude.check() + }), + ) +}) diff --git a/packages/core/test/plugin/provider/claude-agent/fixtures/marker.pdf b/packages/core/test/plugin/provider/claude-agent/fixtures/marker.pdf new file mode 100644 index 000000000000..a06d95a8156b Binary files /dev/null and b/packages/core/test/plugin/provider/claude-agent/fixtures/marker.pdf differ diff --git a/packages/core/test/plugin/provider/claude-agent/fixtures/recordings/billing-error.jsonl b/packages/core/test/plugin/provider/claude-agent/fixtures/recordings/billing-error.jsonl new file mode 100644 index 000000000000..9a1fbb42735a --- /dev/null +++ b/packages/core/test/plugin/provider/claude-agent/fixtures/recordings/billing-error.jsonl @@ -0,0 +1,11 @@ +{"claudeCode":"2.1.302","sdk":"0.3.301","date":"2026-10-17","note":"Trimmed from a real failed compaction that hit a billing error. It can't be re-recorded on demand."} +{"from":"sdk","message":{"type":"user","uuid":"edadf65f-1bca-4f6d-99cb-95dcab4c0854","message":{"role":"user","content":[{"type":"text","text":"You MUST summarize the conversation above into a structured summary that will be given to another agent to resume the work.\n\nSummarize only what the user and the assistant said and did. Leave out instructions and setup the assistant was given rather than told by the user: repository conventions, instruction files such as AGENTS.md, and environment details like the session ID. The next agent receives current versions of all of these separately.\n\nYou MUST use this format for your response (you may omit sections that aren't applicable). Do not include the