Compare commits

..
1 Commits
Author SHA1 Message Date
opencode 48e12ade76 release: v0.4.13 2025-08-11 05:51:06 +00:00
120 changed files with 3170 additions and 6083 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
- uses: oven-sh/setup-bun@v1
with:
bun-version: 1.2.19
bun-version: 1.2.17
- run: bun install
-60
View File
@@ -1,60 +0,0 @@
name: Duplicate Issue Detection
on:
issues:
types: [opened]
jobs:
check-duplicates:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Install opencode
run: curl -fsSL https://opencode.ai/install | bash
- name: Check for duplicate issues
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
OPENCODE_PERMISSION: |
{
"bash": {
"gh issue*": "allow",
"*": "deny"
},
"webfetch": "deny"
}
run: |
opencode run -m anthropic/claude-sonnet-4-20250514 "A new issue has been created: '${{ github.event.issue.title }}'
Issue number:
${{ github.event.issue.number }}
Issue body:
${{ github.event.issue.body }}
Please search through existing issues (excluding #${{ github.event.issue.number }}) in this repository to find any potential duplicates of this new issue.
Consider:
1. Similar titles or descriptions
2. Same error messages or symptoms
3. Related functionality or components
4. Similar feature requests
If you find any potential duplicates, please comment on the new issue with:
- A brief explanation of why it might be a duplicate
- Links to the potentially duplicate issues
- A suggestion to check those issues first
Use this format for the comment:
'This issue might be a duplicate of existing issues. Please check:
- #[issue_number]: [brief description of similarity]
Feel free to ignore if none of these address your specific case.'
If no clear duplicates are found, do not comment."
-53
View File
@@ -1,53 +0,0 @@
name: Guidelines Check
on:
# Disabled - uncomment to re-enable
# pull_request_target:
# types: [opened, synchronize]
jobs:
check-guidelines:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Install opencode
run: curl -fsSL https://opencode.ai/install | bash
- name: Check PR guidelines compliance
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
OPENCODE_PERMISSION: '{ "bash": { "gh*": "allow", "gh pr review*": "deny", "*": "deny" } }'
run: |
opencode run -m anthropic/claude-sonnet-4-20250514 "A new pull request has been created: '${{ github.event.pull_request.title }}'
<pr-number>
${{ github.event.pull_request.number }}
</pr-number>
<pr-description>
${{ github.event.pull_request.body }}
</pr-description>
Please check all the code changes in this pull request against the guidelines in AGENTS.md file in this repository. Diffs are important but make sure you read the entire file to get proper context. Make it clear the suggestions are merely suggestions and the human can decide what to do
Use the gh cli to create comments on the files for the violations. Try to leave the comment on the exact line number. If you have a suggested fix include it in a suggestion code block.
Command MUST be like this.
```
gh api \
--method POST \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/comments \
-f 'body=[summary of issue]' -f 'commit_id=${{ github.event.pull_request.head.sha }}' -f 'path=[path-to-file]' -F "line=[line]" -f 'side=RIGHT'
```
Only create comments for actual violations. If the code follows all guidelines, don't run any gh commands."
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.2.19
bun-version: 1.2.17
- run: git fetch --force --tags
- run: bun install -g @vscode/vsce
+3 -1
View File
@@ -52,14 +52,16 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y pacman-package-manager
- name: Setup SSH for AUR
run: |
mkdir -p ~/.ssh
echo "${{ secrets.AUR_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H aur.archlinux.org >> ~/.ssh/known_hosts
git config --global user.email "opencode@sst.dev"
git config --global user.name "opencode"
ssh-keyscan -H aur.archlinux.org >> ~/.ssh/known_hosts || true
- name: Install dependencies
run: bun install
-1
View File
@@ -6,4 +6,3 @@ node_modules
.vscode
openapi.json
playground
tmp
-10
View File
@@ -1,10 +0,0 @@
---
description: Use this agent when you are asked to commit and push code changes to a git repository.
mode: subagent
---
You commit and push to git
Commit messages should be brief since they are used to generate release notes.
Messages should say WHY the change was made and not WHAT was changed.
+44 -49
View File
@@ -1,51 +1,46 @@
# Download Stats
| Date | GitHub Downloads | npm Downloads | Total |
| ---------- | ---------------- | ---------------- | ----------------- |
| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) |
| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) |
| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) |
| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) |
| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) |
| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) |
| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) |
| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) |
| 2025-07-08 | 38,052 (+4,286) | 64,468 (+4,774) | 102,520 (+9,060) |
| 2025-07-09 | 40,924 (+2,872) | 67,935 (+3,467) | 108,859 (+6,339) |
| 2025-07-10 | 43,796 (+2,872) | 71,402 (+3,467) | 115,198 (+6,339) |
| 2025-07-11 | 46,982 (+3,186) | 77,462 (+6,060) | 124,444 (+9,246) |
| 2025-07-12 | 49,302 (+2,320) | 82,177 (+4,715) | 131,479 (+7,035) |
| 2025-07-13 | 50,803 (+1,501) | 86,394 (+4,217) | 137,197 (+5,718) |
| 2025-07-14 | 53,283 (+2,480) | 87,860 (+1,466) | 141,143 (+3,946) |
| 2025-07-15 | 57,590 (+4,307) | 91,036 (+3,176) | 148,626 (+7,483) |
| 2025-07-16 | 62,313 (+4,723) | 95,258 (+4,222) | 157,571 (+8,945) |
| 2025-07-17 | 66,684 (+4,371) | 100,048 (+4,790) | 166,732 (+9,161) |
| 2025-07-18 | 70,379 (+3,695) | 102,587 (+2,539) | 172,966 (+6,234) |
| 2025-07-19 | 73,497 (+3,117) | 105,904 (+3,317) | 179,401 (+6,434) |
| 2025-07-20 | 76,453 (+2,956) | 109,044 (+3,140) | 185,497 (+6,096) |
| 2025-07-21 | 80,197 (+3,744) | 113,537 (+4,493) | 193,734 (+8,237) |
| 2025-07-22 | 84,251 (+4,054) | 118,073 (+4,536) | 202,324 (+8,590) |
| 2025-07-23 | 88,589 (+4,338) | 121,436 (+3,363) | 210,025 (+7,701) |
| 2025-07-24 | 92,469 (+3,880) | 124,091 (+2,655) | 216,560 (+6,535) |
| 2025-07-25 | 96,417 (+3,948) | 126,985 (+2,894) | 223,402 (+6,842) |
| 2025-07-26 | 100,646 (+4,229) | 131,411 (+4,426) | 232,057 (+8,655) |
| 2025-07-27 | 102,644 (+1,998) | 134,736 (+3,325) | 237,380 (+5,323) |
| 2025-07-28 | 105,446 (+2,802) | 136,016 (+1,280) | 241,462 (+4,082) |
| 2025-07-29 | 108,998 (+3,552) | 137,542 (+1,526) | 246,540 (+5,078) |
| 2025-07-30 | 113,544 (+4,546) | 140,317 (+2,775) | 253,861 (+7,321) |
| 2025-07-31 | 118,339 (+4,795) | 143,344 (+3,027) | 261,683 (+7,822) |
| 2025-08-01 | 123,539 (+5,200) | 146,680 (+3,336) | 270,219 (+8,536) |
| 2025-08-02 | 127,864 (+4,325) | 149,236 (+2,556) | 277,100 (+6,881) |
| 2025-08-03 | 131,397 (+3,533) | 150,451 (+1,215) | 281,848 (+4,748) |
| 2025-08-04 | 136,266 (+4,869) | 153,260 (+2,809) | 289,526 (+7,678) |
| 2025-08-05 | 141,596 (+5,330) | 155,752 (+2,492) | 297,348 (+7,822) |
| 2025-08-06 | 147,067 (+5,471) | 158,309 (+2,557) | 305,376 (+8,028) |
| 2025-08-07 | 152,591 (+5,524) | 160,889 (+2,580) | 313,480 (+8,104) |
| 2025-08-08 | 158,187 (+5,596) | 163,448 (+2,559) | 321,635 (+8,155) |
| 2025-08-09 | 162,770 (+4,583) | 165,721 (+2,273) | 328,491 (+6,856) |
| 2025-08-10 | 165,695 (+2,925) | 167,109 (+1,388) | 332,804 (+4,313) |
| 2025-08-11 | 169,297 (+3,602) | 167,953 (+844) | 337,250 (+4,446) |
| 2025-08-12 | 176,307 (+7,010) | 171,876 (+3,923) | 348,183 (+10,933) |
| 2025-08-13 | 182,997 (+6,690) | 177,182 (+5,306) | 360,179 (+11,996) |
| 2025-08-14 | 189,063 (+6,066) | 179,741 (+2,559) | 368,804 (+8,625) |
| 2025-08-15 | 193,608 (+4,545) | 181,792 (+2,051) | 375,400 (+6,596) |
| Date | GitHub Downloads | npm Downloads | Total |
| ---------- | ---------------- | ---------------- | ---------------- |
| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) |
| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) |
| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) |
| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) |
| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) |
| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) |
| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) |
| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) |
| 2025-07-08 | 38,052 (+4,286) | 64,468 (+4,774) | 102,520 (+9,060) |
| 2025-07-09 | 40,924 (+2,872) | 67,935 (+3,467) | 108,859 (+6,339) |
| 2025-07-10 | 43,796 (+2,872) | 71,402 (+3,467) | 115,198 (+6,339) |
| 2025-07-11 | 46,982 (+3,186) | 77,462 (+6,060) | 124,444 (+9,246) |
| 2025-07-12 | 49,302 (+2,320) | 82,177 (+4,715) | 131,479 (+7,035) |
| 2025-07-13 | 50,803 (+1,501) | 86,394 (+4,217) | 137,197 (+5,718) |
| 2025-07-14 | 53,283 (+2,480) | 87,860 (+1,466) | 141,143 (+3,946) |
| 2025-07-15 | 57,590 (+4,307) | 91,036 (+3,176) | 148,626 (+7,483) |
| 2025-07-16 | 62,313 (+4,723) | 95,258 (+4,222) | 157,571 (+8,945) |
| 2025-07-17 | 66,684 (+4,371) | 100,048 (+4,790) | 166,732 (+9,161) |
| 2025-07-18 | 70,379 (+3,695) | 102,587 (+2,539) | 172,966 (+6,234) |
| 2025-07-19 | 73,497 (+3,117) | 105,904 (+3,317) | 179,401 (+6,434) |
| 2025-07-20 | 76,453 (+2,956) | 109,044 (+3,140) | 185,497 (+6,096) |
| 2025-07-21 | 80,197 (+3,744) | 113,537 (+4,493) | 193,734 (+8,237) |
| 2025-07-22 | 84,251 (+4,054) | 118,073 (+4,536) | 202,324 (+8,590) |
| 2025-07-23 | 88,589 (+4,338) | 121,436 (+3,363) | 210,025 (+7,701) |
| 2025-07-24 | 92,469 (+3,880) | 124,091 (+2,655) | 216,560 (+6,535) |
| 2025-07-25 | 96,417 (+3,948) | 126,985 (+2,894) | 223,402 (+6,842) |
| 2025-07-26 | 100,646 (+4,229) | 131,411 (+4,426) | 232,057 (+8,655) |
| 2025-07-27 | 102,644 (+1,998) | 134,736 (+3,325) | 237,380 (+5,323) |
| 2025-07-28 | 105,446 (+2,802) | 136,016 (+1,280) | 241,462 (+4,082) |
| 2025-07-29 | 108,998 (+3,552) | 137,542 (+1,526) | 246,540 (+5,078) |
| 2025-07-30 | 113,544 (+4,546) | 140,317 (+2,775) | 253,861 (+7,321) |
| 2025-07-31 | 118,339 (+4,795) | 143,344 (+3,027) | 261,683 (+7,822) |
| 2025-08-01 | 123,539 (+5,200) | 146,680 (+3,336) | 270,219 (+8,536) |
| 2025-08-02 | 127,864 (+4,325) | 149,236 (+2,556) | 277,100 (+6,881) |
| 2025-08-03 | 131,397 (+3,533) | 150,451 (+1,215) | 281,848 (+4,748) |
| 2025-08-04 | 136,266 (+4,869) | 153,260 (+2,809) | 289,526 (+7,678) |
| 2025-08-05 | 141,596 (+5,330) | 155,752 (+2,492) | 297,348 (+7,822) |
| 2025-08-06 | 147,067 (+5,471) | 158,309 (+2,557) | 305,376 (+8,028) |
| 2025-08-07 | 152,591 (+5,524) | 160,889 (+2,580) | 313,480 (+8,104) |
| 2025-08-08 | 158,187 (+5,596) | 163,448 (+2,559) | 321,635 (+8,155) |
| 2025-08-09 | 162,770 (+4,583) | 165,721 (+2,273) | 328,491 (+6,856) |
| 2025-08-10 | 165,695 (+2,925) | 167,109 (+1,388) | 332,804 (+4,313) |
+19 -26
View File
@@ -13,7 +13,7 @@
},
"cloud/core": {
"name": "@opencode/cloud-core",
"version": "0.4.19",
"version": "0.0.0",
"dependencies": {
"@aws-sdk/client-sts": "3.782.0",
"drizzle-orm": "0.41.0",
@@ -27,7 +27,7 @@
},
"cloud/function": {
"name": "@opencode/cloud-function",
"version": "0.4.19",
"version": "0.3.130",
"dependencies": {
"@ai-sdk/anthropic": "2.0.0",
"@ai-sdk/openai": "2.0.2",
@@ -47,7 +47,7 @@
},
"cloud/web": {
"name": "@opencode/cloud-web",
"version": "0.4.19",
"version": "0.0.0",
"dependencies": {
"@kobalte/core": "0.13.9",
"@openauthjs/solid": "0.0.0-20250322224806",
@@ -66,7 +66,7 @@
},
"packages/function": {
"name": "@opencode/function",
"version": "0.4.19",
"version": "0.4.1",
"dependencies": {
"@octokit/auth-app": "8.0.1",
"@octokit/rest": "22.0.0",
@@ -81,7 +81,7 @@
},
"packages/opencode": {
"name": "opencode",
"version": "0.4.19",
"version": "0.4.1",
"bin": {
"opencode": "./bin/opencode",
},
@@ -113,7 +113,6 @@
"tree-sitter-bash": "0.23.3",
"turndown": "7.2.0",
"vscode-jsonrpc": "8.2.1",
"web-tree-sitter": "0.22.6",
"xdg-basedir": "5.1.0",
"yargs": "18.0.0",
"zod": "catalog:",
@@ -121,6 +120,7 @@
},
"devDependencies": {
"@ai-sdk/amazon-bedrock": "2.2.10",
"@ai-sdk/anthropic": "1.2.12",
"@octokit/webhooks-types": "7.6.1",
"@standard-schema/spec": "1.0.0",
"@tsconfig/bun": "1.0.7",
@@ -134,7 +134,7 @@
},
"packages/plugin": {
"name": "@opencode-ai/plugin",
"version": "0.4.19",
"version": "0.4.1",
"dependencies": {
"@opencode-ai/sdk": "workspace:*",
},
@@ -146,7 +146,7 @@
},
"packages/sdk/js": {
"name": "@opencode-ai/sdk",
"version": "0.4.19",
"version": "0.4.1",
"devDependencies": {
"@hey-api/openapi-ts": "0.80.1",
"@tsconfig/node22": "catalog:",
@@ -155,9 +155,9 @@
},
"packages/web": {
"name": "@opencode/web",
"version": "0.4.19",
"version": "0.4.1",
"dependencies": {
"@astrojs/cloudflare": "12.6.3",
"@astrojs/cloudflare": "^12.5.4",
"@astrojs/markdown-remark": "6.3.1",
"@astrojs/solid-js": "5.1.0",
"@astrojs/starlight": "0.34.3",
@@ -190,9 +190,6 @@
"sharp",
"esbuild",
"protobufjs",
"tree-sitter",
"web-tree-sitter",
"tree-sitter-bash",
],
"catalog": {
"@hono/zod-validator": "0.4.2",
@@ -233,11 +230,11 @@
"@apidevtools/json-schema-ref-parser": ["@apidevtools/json-schema-ref-parser@11.9.3", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ=="],
"@astrojs/cloudflare": ["@astrojs/cloudflare@12.6.3", "", { "dependencies": { "@astrojs/internal-helpers": "0.7.1", "@astrojs/underscore-redirects": "1.0.0", "@cloudflare/workers-types": "^4.20250507.0", "tinyglobby": "^0.2.13", "vite": "^6.3.5", "wrangler": "^4.14.1" }, "peerDependencies": { "astro": "^5.0.0" } }, "sha512-xhJptF5tU2k5eo70nIMyL1Udma0CqmUEnGSlGyFflLqSY82CRQI6nWZ/xZt0ZvmXuErUjIx0YYQNfZsz5CNjLQ=="],
"@astrojs/cloudflare": ["@astrojs/cloudflare@12.6.0", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/underscore-redirects": "1.0.0", "@cloudflare/workers-types": "^4.20250507.0", "tinyglobby": "^0.2.13", "vite": "^6.3.5", "wrangler": "^4.14.1" }, "peerDependencies": { "astro": "^5.0.0" } }, "sha512-pQ8bokC59GEiXvyXpC4swBNoL7C/EknP+82KFzQwgR/Aeo5N1oPiAoPHgJbpPya/YF4E26WODdCQfBQDvLRfuw=="],
"@astrojs/compiler": ["@astrojs/compiler@2.12.2", "", {}, "sha512-w2zfvhjNCkNMmMMOn5b0J8+OmUaBL1o40ipMvqcG6NRpdC+lKxmTi48DT8Xw0SzJ3AfmeFLB45zXZXtmbsjcgw=="],
"@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.7.1", "", {}, "sha512-7dwEVigz9vUWDw3nRwLQ/yH/xYovlUA0ZD86xoeKEBmkz9O6iELG1yri67PgAPW6VLL/xInA4t7H0CK6VmtkKQ=="],
"@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
"@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.1", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/prism": "3.2.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.1.0", "js-yaml": "^4.1.0", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.1", "remark-smartypants": "^3.0.2", "shiki": "^3.0.0", "smol-toml": "^1.3.1", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.1", "vfile": "^6.0.3" } }, "sha512-c5F5gGrkczUaTVgmMW9g1YMJGzOtRvjjhw6IfGuxarM6ct09MpwysP10US729dy07gg8y+ofVifezvP3BNsWZg=="],
@@ -911,7 +908,7 @@
"@types/babel__traverse": ["@types/babel__traverse@7.20.7", "", { "dependencies": { "@babel/types": "^7.20.7" } }, "sha512-dkO5fhS7+/oos4ciWxyEyjWe48zmG6wbCheo/G2ZnHx4fs3EU6YC6UM8rk56gAjNJ9P3MTH2jo5jb92/K6wbng=="],
"@types/bun": ["@types/bun@1.2.20", "", { "dependencies": { "bun-types": "1.2.20" } }, "sha512-dX3RGzQ8+KgmMw7CsW4xT5ITBSCrSbfHc36SNT31EOUg/LA9JWq0VDdEXDRSe1InVWpd2yLUM1FUF/kEOyTzYA=="],
"@types/bun": ["@types/bun@1.2.19", "", { "dependencies": { "bun-types": "1.2.19" } }, "sha512-d9ZCmrH3CJ2uYKXQIUuZ/pUnTqIvLDS0SK7pFmbx8ma+ziH/FRMoAq5bYpRG7y+w1gl+HgyNZbtqgMq4W4e2Lg=="],
"@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=="],
@@ -2485,8 +2482,6 @@
"web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="],
"web-tree-sitter": ["web-tree-sitter@0.22.6", "", {}, "sha512-hS87TH71Zd6mGAmYCvlgxeGDjqd9GTeqXNqTT+u0Gs51uIozNIaaq/kUAbV/Zf56jb2ZOyG8BxZs2GG9wbLi6Q=="],
"webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
"whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
@@ -2575,8 +2570,6 @@
"@astrojs/cloudflare/vite": ["vite@6.3.5", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ=="],
"@astrojs/markdown-remark/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
"@astrojs/mdx/@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.3", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/prism": "3.3.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.1.0", "js-yaml": "^4.1.0", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", "remark-smartypants": "^3.0.2", "shiki": "^3.2.1", "smol-toml": "^1.3.4", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.1", "vfile": "^6.0.3" } }, "sha512-DDRtD1sPvAuA7ms2btc9A7/7DApKqgLMNrE6kh5tmkfy8utD0Z738gqd3p5aViYYdUtHIyEJ1X4mCMxfCfu15w=="],
"@astrojs/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
@@ -2757,16 +2750,12 @@
"@tufjs/models/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
"@types/bun/bun-types": ["bun-types@1.2.20", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-pxTnQYOrKvdOwyiyd/7sMt9yFOenN004Y6O4lCcCUoKVej48FS5cvTw9geRaEcB9TsDZaJKAxPTVvi8tFsVuXA=="],
"ai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@3.0.1", "", { "dependencies": { "@ai-sdk/provider": "2.0.0", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-/iP1sKc6UdJgGH98OCly7sWJKv+J9G47PnTjIj40IJMUQKwDrUMyf7zOOfRtPwSuNifYhSoJQ4s1WltI65gJ/g=="],
"ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"anymatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
"astro/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
"astro/diff": ["diff@5.2.0", "", {}, "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A=="],
"astro/esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="],
@@ -2839,6 +2828,8 @@
"nypm/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"opencode/@ai-sdk/anthropic": ["@ai-sdk/anthropic@1.2.12", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8" }, "peerDependencies": { "zod": "^3.0.0" } }, "sha512-YSzjlko7JvuiyQFmI9RN1tNZdEiZxc+6xld/0tq/VkJaHpEzGAb1yiNxxvmYVcjvfu/PcvCxAAYXmTYQQ63IHQ=="],
"opencode/@openauthjs/openauth": ["@openauthjs/openauth@0.4.3", "", { "dependencies": { "@standard-schema/spec": "1.0.0-beta.3", "aws4fetch": "1.0.20", "jose": "5.9.6" }, "peerDependencies": { "arctic": "^2.2.2", "hono": "^4.0.0" } }, "sha512-RlnjqvHzqcbFVymEwhlUEuac4utA5h4nhSK/i2szZuQmxTIqbGUxZ+nM+avM+VV4Ing+/ZaNLKILoXS3yrkOOw=="],
"opencontrol/@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.6.1", "", { "dependencies": { "content-type": "^1.0.5", "cors": "^2.8.5", "eventsource": "^3.0.2", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "pkce-challenge": "^4.1.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" } }, "sha512-oxzMzYCkZHMntzuyerehK3fV6A2Kwh5BD6CGEJSVDU2QNEhfLOptf2X7esQgaHZXHZY0oHmMsOtIDLP71UJXgA=="],
@@ -2943,8 +2934,6 @@
"@astrojs/cloudflare/vite/esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="],
"@astrojs/mdx/@astrojs/markdown-remark/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
"@astrojs/mdx/@astrojs/markdown-remark/@astrojs/prism": ["@astrojs/prism@3.3.0", "", { "dependencies": { "prismjs": "^1.30.0" } }, "sha512-q8VwfU/fDZNoDOf+r7jUnMC2//H2l0TuQ6FkGJL8vD8nw/q5KiL3DS1KKBI3QhI9UQhpJ5dc7AtqfbXWuOgLCQ=="],
"@astrojs/solid-js/vite/esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="],
@@ -3071,6 +3060,10 @@
"local-pkg/pkg-types/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"opencode/@ai-sdk/anthropic/@ai-sdk/provider": ["@ai-sdk/provider@1.1.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="],
"opencode/@ai-sdk/anthropic/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@2.2.8", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="],
"opencode/@openauthjs/openauth/@standard-schema/spec": ["@standard-schema/spec@1.0.0-beta.3", "", {}, "sha512-0ifF3BjA1E8SY9C+nUew8RefNOIq0cDlYALPty4rhUm8Rrl6tCM8hBT4bhGhx7I7iXD0uAgt50lgo8dD73ACMw=="],
"opencode/@openauthjs/openauth/aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="],
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/cloud-core",
"version": "0.5.2",
"version": "0.4.13",
"private": true,
"type": "module",
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/cloud-function",
"version": "0.5.2",
"version": "0.4.13",
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/cloud-web",
"version": "0.5.2",
"version": "0.4.13",
"private": true,
"description": "",
"type": "module",
+3 -6
View File
@@ -3,11 +3,11 @@
"name": "opencode",
"private": true,
"type": "module",
"packageManager": "bun@1.2.19",
"packageManager": "bun@1.2.14",
"scripts": {
"dev": "bun run --conditions=development packages/opencode/src/index.ts",
"typecheck": "bun run --filter='*' typecheck",
"generate": "(cd packages/sdk && ./js/script/generate.ts) && (cd packages/sdk/stainless && ./generate.ts)",
"stainless": "./scripts/stainless",
"postinstall": "./script/hooks"
},
"workspaces": {
@@ -46,10 +46,7 @@
"trustedDependencies": [
"esbuild",
"protobufjs",
"sharp",
"tree-sitter",
"tree-sitter-bash",
"web-tree-sitter"
"sharp"
],
"patchedDependencies": {}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/function",
"version": "0.5.2",
"version": "0.4.13",
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "0.5.2",
"version": "0.4.13",
"name": "opencode",
"type": "module",
"private": true,
@@ -16,6 +16,7 @@
},
"devDependencies": {
"@ai-sdk/amazon-bedrock": "2.2.10",
"@ai-sdk/anthropic": "1.2.12",
"@octokit/webhooks-types": "7.6.1",
"@standard-schema/spec": "1.0.0",
"@tsconfig/bun": "1.0.7",
@@ -52,7 +53,6 @@
"remeda": "catalog:",
"tree-sitter": "0.22.4",
"tree-sitter-bash": "0.23.3",
"web-tree-sitter": "0.22.6",
"turndown": "7.2.0",
"vscode-jsonrpc": "8.2.1",
"xdg-basedir": "5.1.0",
+2 -3
View File
@@ -97,7 +97,7 @@ if (!snapshot) {
const macX64Sha = await $`sha256sum ./dist/opencode-darwin-x64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
const macArm64Sha = await $`sha256sum ./dist/opencode-darwin-arm64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
/* AUR package - commented out as AUR is down
// AUR package
const pkgbuild = [
"# Maintainer: dax",
"# Maintainer: adam",
@@ -126,7 +126,7 @@ if (!snapshot) {
"",
].join("\n")
for (const pkg of ["opencode-bin"]) {
for (const pkg of ["opencode", "opencode-bin"]) {
await $`rm -rf ./dist/aur-${pkg}`
await $`git clone ssh://aur@aur.archlinux.org/${pkg}.git ./dist/aur-${pkg}`
await $`cd ./dist/aur-${pkg} && git checkout master`
@@ -136,7 +136,6 @@ if (!snapshot) {
await $`cd ./dist/aur-${pkg} && git commit -m "Update to v${version}"`
if (!dry) await $`cd ./dist/aur-${pkg} && git push`
}
*/
// Homebrew formula
const homebrewFormula = [
+9 -66
View File
@@ -5,7 +5,6 @@ import { Provider } from "../provider/provider"
import { generateObject, type ModelMessage } from "ai"
import PROMPT_GENERATE from "./generate.txt"
import { SystemPrompt } from "../session/system"
import { mergeDeep } from "remeda"
export namespace Agent {
export const Info = z
@@ -13,14 +12,8 @@ export namespace Agent {
name: z.string(),
description: z.string().optional(),
mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]),
builtIn: z.boolean(),
topP: z.number().optional(),
temperature: z.number().optional(),
permission: z.object({
edit: Config.Permission,
bash: z.record(z.string(), Config.Permission),
webfetch: Config.Permission.optional(),
}),
model: z
.object({
modelID: z.string(),
@@ -38,15 +31,6 @@ export namespace Agent {
const state = App.state("agent", async () => {
const cfg = await Config.get()
const defaultPermission: Info["permission"] = {
edit: "allow",
bash: {
"*": "allow",
},
webfetch: "allow",
}
const agentPermission = mergeAgentPermissions(defaultPermission, cfg.permission ?? {})
const result: Record<string, Info> = {
general: {
name: "general",
@@ -57,29 +41,23 @@ export namespace Agent {
todowrite: false,
},
options: {},
permission: agentPermission,
mode: "subagent",
builtIn: true,
},
build: {
name: "build",
tools: {},
options: {},
permission: agentPermission,
mode: "primary",
builtIn: true,
},
plan: {
name: "plan",
options: {},
permission: agentPermission,
tools: {
write: false,
edit: false,
patch: false,
},
mode: "primary",
builtIn: true,
},
}
for (const [key, value] of Object.entries(cfg.agent ?? {})) {
@@ -92,31 +70,25 @@ export namespace Agent {
item = result[key] = {
name: key,
mode: "all",
permission: agentPermission,
options: {},
tools: {},
builtIn: false,
}
const { model, prompt, tools, description, temperature, top_p, mode, permission, ...extra } = value
const { model, prompt, tools, description, temperature, top_p, mode, ...extra } = value
item.options = {
...item.options,
...extra,
}
if (model) item.model = Provider.parseModel(model)
if (prompt) item.prompt = prompt
if (tools)
if (value.model) item.model = Provider.parseModel(value.model)
if (value.prompt) item.prompt = value.prompt
if (value.tools)
item.tools = {
...item.tools,
...tools,
...value.tools,
}
if (description) item.description = description
if (temperature != undefined) item.temperature = temperature
if (top_p != undefined) item.topP = top_p
if (mode) item.mode = mode
if (permission ?? cfg.permission) {
item.permission = mergeAgentPermissions(cfg.permission ?? {}, permission ?? {})
}
if (value.description) item.description = value.description
if (value.temperature != undefined) item.temperature = value.temperature
if (value.top_p != undefined) item.topP = value.top_p
if (value.mode) item.mode = value.mode
}
return result
})
@@ -159,32 +131,3 @@ export namespace Agent {
return result.object
}
}
function mergeAgentPermissions(basePermission: any, overridePermission: any): Agent.Info["permission"] {
const merged = mergeDeep(basePermission ?? {}, overridePermission ?? {}) as any
let mergedBash
if (merged.bash) {
if (typeof merged.bash === "string") {
mergedBash = {
"*": merged.bash,
}
}
// if granular permissions are provided, default to "ask"
if (typeof merged.bash === "object") {
mergedBash = mergeDeep(
{
"*": "ask",
},
merged.bash,
)
}
}
const result: Agent.Info["permission"] = {
edit: merged.edit ?? "allow",
webfetch: merged.webfetch ?? "allow",
bash: mergedBash ?? { "*": "allow" },
}
return result
}
+84
View File
@@ -0,0 +1,84 @@
import { generatePKCE } from "@openauthjs/openauth/pkce"
import { Auth } from "./index"
export namespace AuthAnthropic {
const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
export async function authorize(mode: "max" | "console") {
const pkce = await generatePKCE()
const url = new URL(
`https://${mode === "console" ? "console.anthropic.com" : "claude.ai"}/oauth/authorize`,
import.meta.url,
)
url.searchParams.set("code", "true")
url.searchParams.set("client_id", CLIENT_ID)
url.searchParams.set("response_type", "code")
url.searchParams.set("redirect_uri", "https://console.anthropic.com/oauth/code/callback")
url.searchParams.set("scope", "org:create_api_key user:profile user:inference")
url.searchParams.set("code_challenge", pkce.challenge)
url.searchParams.set("code_challenge_method", "S256")
url.searchParams.set("state", pkce.verifier)
return {
url: url.toString(),
verifier: pkce.verifier,
}
}
export async function exchange(code: string, verifier: string) {
const splits = code.split("#")
const result = await fetch("https://console.anthropic.com/v1/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code: splits[0],
state: splits[1],
grant_type: "authorization_code",
client_id: CLIENT_ID,
redirect_uri: "https://console.anthropic.com/oauth/code/callback",
code_verifier: verifier,
}),
})
if (!result.ok) throw new ExchangeFailed()
const json = await result.json()
return {
refresh: json.refresh_token as string,
access: json.access_token as string,
expires: Date.now() + json.expires_in * 1000,
}
}
export async function access() {
const info = await Auth.get("anthropic")
if (!info || info.type !== "oauth") return
if (info.access && info.expires > Date.now()) return info.access
const response = await fetch("https://console.anthropic.com/v1/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "refresh_token",
refresh_token: info.refresh,
client_id: CLIENT_ID,
}),
})
if (!response.ok) return
const json = await response.json()
await Auth.set("anthropic", {
type: "oauth",
refresh: json.refresh_token as string,
access: json.access_token as string,
expires: Date.now() + json.expires_in * 1000,
})
return json.access_token as string
}
export class ExchangeFailed extends Error {
constructor() {
super("Exchange failed")
}
}
}
+19
View File
@@ -0,0 +1,19 @@
import { Global } from "../global"
import { lazy } from "../util/lazy"
import path from "path"
export const AuthCopilot = lazy(async () => {
const file = Bun.file(path.join(Global.Path.state, "plugin", "copilot.ts"))
const exists = await file.exists()
const response = fetch("https://raw.githubusercontent.com/sst/opencode-github-copilot/refs/heads/main/auth.ts")
.then((x) => Bun.write(file, x))
.catch(() => {})
if (!exists) {
const worked = await response
if (!worked) return
}
const result = await import(file.name!).catch(() => {})
if (!result) return
return result.AuthCopilot
})
+16 -22
View File
@@ -4,31 +4,25 @@ import fs from "fs/promises"
import { z } from "zod"
export namespace Auth {
export const Oauth = z
.object({
type: z.literal("oauth"),
refresh: z.string(),
access: z.string(),
expires: z.number(),
})
.openapi({ ref: "OAuth" })
export const Oauth = z.object({
type: z.literal("oauth"),
refresh: z.string(),
access: z.string(),
expires: z.number(),
})
export const Api = z
.object({
type: z.literal("api"),
key: z.string(),
})
.openapi({ ref: "ApiAuth" })
export const Api = z.object({
type: z.literal("api"),
key: z.string(),
})
export const WellKnown = z
.object({
type: z.literal("wellknown"),
key: z.string(),
token: z.string(),
})
.openapi({ ref: "WellKnownAuth" })
export const WellKnown = z.object({
type: z.literal("wellknown"),
key: z.string(),
token: z.string(),
})
export const Info = z.discriminatedUnion("type", [Oauth, Api, WellKnown]).openapi({ ref: "Auth" })
export const Info = z.discriminatedUnion("type", [Oauth, Api, WellKnown])
export type Info = z.infer<typeof Info>
const filepath = path.join(Global.Path.data, "auth.json")
+217 -154
View File
@@ -1,3 +1,5 @@
import { AuthAnthropic } from "../../auth/anthropic"
import { AuthCopilot } from "../../auth/copilot"
import { Auth } from "../../auth"
import { cmd } from "./cmd"
import * as prompts from "@clack/prompts"
@@ -8,8 +10,6 @@ import { map, pipe, sortBy, values } from "remeda"
import path from "path"
import os from "os"
import { Global } from "../../global"
import { Plugin } from "../../plugin"
import { App } from "../../app/app"
export const AuthCommand = cmd({
command: "auth",
@@ -75,179 +75,242 @@ export const AuthLoginCommand = cmd({
type: "string",
}),
async handler(args) {
await App.provide({ cwd: process.cwd() }, async () => {
UI.empty()
prompts.intro("Add credential")
if (args.url) {
const wellknown = await fetch(`${args.url}/.well-known/opencode`).then((x) => x.json())
prompts.log.info(`Running \`${wellknown.auth.command.join(" ")}\``)
const proc = Bun.spawn({
cmd: wellknown.auth.command,
stdout: "pipe",
})
const exit = await proc.exited
if (exit !== 0) {
prompts.log.error("Failed")
prompts.outro("Done")
return
}
const token = await new Response(proc.stdout).text()
await Auth.set(args.url, {
type: "wellknown",
key: wellknown.auth.env,
token: token.trim(),
})
prompts.log.success("Logged into " + args.url)
UI.empty()
prompts.intro("Add credential")
if (args.url) {
const wellknown = await fetch(`${args.url}/.well-known/opencode`).then((x) => x.json())
prompts.log.info(`Running \`${wellknown.auth.command.join(" ")}\``)
const proc = Bun.spawn({
cmd: wellknown.auth.command,
stdout: "pipe",
})
const exit = await proc.exited
if (exit !== 0) {
prompts.log.error("Failed")
prompts.outro("Done")
return
}
await ModelsDev.refresh().catch(() => {})
const providers = await ModelsDev.get()
const priority: Record<string, number> = {
anthropic: 0,
"github-copilot": 1,
openai: 2,
google: 3,
openrouter: 4,
vercel: 5,
}
let provider = await prompts.autocomplete({
message: "Select provider",
maxItems: 8,
options: [
...pipe(
providers,
values(),
sortBy(
(x) => priority[x.id] ?? 99,
(x) => x.name ?? x.id,
),
map((x) => ({
label: x.name,
value: x.id,
hint: priority[x.id] === 0 ? "recommended" : undefined,
})),
const token = await new Response(proc.stdout).text()
await Auth.set(args.url, {
type: "wellknown",
key: wellknown.auth.env,
token: token.trim(),
})
prompts.log.success("Logged into " + args.url)
prompts.outro("Done")
return
}
await ModelsDev.refresh().catch(() => {})
const providers = await ModelsDev.get()
const priority: Record<string, number> = {
anthropic: 0,
"github-copilot": 1,
openai: 2,
google: 3,
openrouter: 4,
vercel: 5,
}
let provider = await prompts.autocomplete({
message: "Select provider",
maxItems: 8,
options: [
...pipe(
providers,
values(),
sortBy(
(x) => priority[x.id] ?? 99,
(x) => x.name ?? x.id,
),
map((x) => ({
label: x.name,
value: x.id,
hint: priority[x.id] === 0 ? "recommended" : undefined,
})),
),
{
value: "other",
label: "Other",
},
],
})
if (prompts.isCancel(provider)) throw new UI.CancelledError()
if (provider === "other") {
provider = await prompts.text({
message: "Enter provider id",
validate: (x) => (x && x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
})
if (prompts.isCancel(provider)) throw new UI.CancelledError()
provider = provider.replace(/^@ai-sdk\//, "")
if (prompts.isCancel(provider)) throw new UI.CancelledError()
prompts.log.warn(
`This only stores a credential for ${provider} - you will need configure it in opencode.json, check the docs for examples.`,
)
}
if (provider === "amazon-bedrock") {
prompts.log.info(
"Amazon bedrock can be configured with standard AWS environment variables like AWS_BEARER_TOKEN_BEDROCK, AWS_PROFILE or AWS_ACCESS_KEY_ID",
)
prompts.outro("Done")
return
}
if (provider === "anthropic") {
const method = await prompts.select({
message: "Login method",
options: [
{
value: "other",
label: "Other",
label: "Claude Pro/Max",
value: "max",
},
{
label: "Create API Key",
value: "console",
},
{
label: "Manually enter API Key",
value: "api",
},
],
})
if (prompts.isCancel(method)) throw new UI.CancelledError()
if (prompts.isCancel(provider)) throw new UI.CancelledError()
const plugin = await Plugin.list().then((x) => x.find((x) => x.auth?.provider === provider))
if (plugin && plugin.auth) {
let index = 0
if (plugin.auth.methods.length > 1) {
const method = await prompts.select({
message: "Login method",
options: [
...plugin.auth.methods.map((x, index) => ({
label: x.label,
value: index.toString(),
})),
],
})
if (prompts.isCancel(method)) throw new UI.CancelledError()
index = parseInt(method)
if (method === "max") {
// some weird bug where program exits without this
await new Promise((resolve) => setTimeout(resolve, 10))
const { url, verifier } = await AuthAnthropic.authorize("max")
prompts.note("Trying to open browser...")
try {
await open(url)
} catch (e) {
prompts.log.error(
"Failed to open browser perhaps you are running without a display or X server, please open the following URL in your browser:",
)
}
const method = plugin.auth.methods[index]
if (method.type === "oauth") {
await new Promise((resolve) => setTimeout(resolve, 10))
const authorize = await method.authorize()
prompts.log.info(url)
if (authorize.url) {
try {
await open(authorize.url)
} catch (e) {}
prompts.log.info("Go to: " + authorize.url)
}
if (authorize.method === "auto") {
if (authorize.instructions) {
prompts.log.info(authorize.instructions)
}
const spinner = prompts.spinner()
spinner.start("Waiting for authorization...")
const result = await authorize.callback()
if (result.type === "failed") {
spinner.stop("Failed to authorize", 1)
}
if (result.type === "success") {
await Auth.set(provider, {
type: "oauth",
refresh: result.refresh,
access: result.access,
expires: result.expires,
})
spinner.stop("Login successful")
}
}
if (authorize.method === "code") {
const code = await prompts.text({
message: "Paste the authorization code here: ",
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
})
if (prompts.isCancel(code)) throw new UI.CancelledError()
const result = await authorize.callback(code)
if (result.type === "failed") {
prompts.log.error("Failed to authorize")
}
if (result.type === "success") {
await Auth.set(provider, {
type: "oauth",
refresh: result.refresh,
access: result.access,
expires: result.expires,
})
prompts.log.success("Login successful")
}
}
prompts.outro("Done")
return
}
}
if (provider === "other") {
provider = await prompts.text({
message: "Enter provider id",
validate: (x) => (x && x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
const code = await prompts.text({
message: "Paste the authorization code here: ",
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
})
if (prompts.isCancel(provider)) throw new UI.CancelledError()
provider = provider.replace(/^@ai-sdk\//, "")
if (prompts.isCancel(provider)) throw new UI.CancelledError()
prompts.log.warn(
`This only stores a credential for ${provider} - you will need configure it in opencode.json, check the docs for examples.`,
)
}
if (prompts.isCancel(code)) throw new UI.CancelledError()
if (provider === "amazon-bedrock") {
prompts.log.info(
"Amazon bedrock can be configured with standard AWS environment variables like AWS_BEARER_TOKEN_BEDROCK, AWS_PROFILE or AWS_ACCESS_KEY_ID",
)
try {
const credentials = await AuthAnthropic.exchange(code, verifier)
await Auth.set("anthropic", {
type: "oauth",
refresh: credentials.refresh,
access: credentials.access,
expires: credentials.expires,
})
prompts.log.success("Login successful")
} catch {
prompts.log.error("Invalid code")
}
prompts.outro("Done")
return
}
if (provider === "vercel") {
prompts.log.info("You can create an api key in the dashboard")
if (method === "console") {
// some weird bug where program exits without this
await new Promise((resolve) => setTimeout(resolve, 10))
const { url, verifier } = await AuthAnthropic.authorize("console")
prompts.note("Trying to open browser...")
try {
await open(url)
} catch (e) {
prompts.log.error(
"Failed to open browser perhaps you are running without a display or X server, please open the following URL in your browser:",
)
}
prompts.log.info(url)
const code = await prompts.text({
message: "Paste the authorization code here: ",
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
})
if (prompts.isCancel(code)) throw new UI.CancelledError()
try {
const credentials = await AuthAnthropic.exchange(code, verifier)
const accessToken = credentials.access
const response = await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key", {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json, text/plain, */*",
},
})
if (!response.ok) {
throw new Error("Failed to create API key")
}
const json = await response.json()
await Auth.set("anthropic", {
type: "api",
key: json.raw_key,
})
prompts.log.success("Login successful - API key created and saved")
} catch (error) {
prompts.log.error("Invalid code or failed to create API key")
}
prompts.outro("Done")
return
}
}
const copilot = await AuthCopilot()
if (provider === "github-copilot" && copilot) {
await new Promise((resolve) => setTimeout(resolve, 10))
const deviceInfo = await copilot.authorize()
prompts.note(`Please visit: ${deviceInfo.verification}\nEnter code: ${deviceInfo.user}`)
const spinner = prompts.spinner()
spinner.start("Waiting for authorization...")
while (true) {
await new Promise((resolve) => setTimeout(resolve, deviceInfo.interval * 1000))
const response = await copilot.poll(deviceInfo.device)
if (response.status === "pending") continue
if (response.status === "success") {
await Auth.set("github-copilot", {
type: "oauth",
refresh: response.refresh,
access: response.access,
expires: response.expires,
})
spinner.stop("Login successful")
break
}
if (response.status === "failed") {
spinner.stop("Failed to authorize", 1)
break
}
}
const key = await prompts.password({
message: "Enter your API key",
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
})
if (prompts.isCancel(key)) throw new UI.CancelledError()
await Auth.set(provider, {
type: "api",
key,
})
prompts.outro("Done")
return
}
if (provider === "vercel") {
prompts.log.info("You can create an api key in the dashboard")
}
const key = await prompts.password({
message: "Enter your API key",
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
})
if (prompts.isCancel(key)) throw new UI.CancelledError()
await Auth.set(provider, {
type: "api",
key,
})
prompts.outro("Done")
},
})
+2 -6
View File
@@ -188,17 +188,13 @@ export const GithubInstallCommand = cmd({
const info = await $`git remote get-url origin`.quiet().nothrow().text()
// match https or git pattern
// ie. https://github.com/sst/opencode.git
// ie. https://github.com/sst/opencode
// ie. git@github.com:sst/opencode.git
// ie. git@github.com:sst/opencode
// ie. ssh://git@github.com/sst/opencode.git
// ie. ssh://git@github.com/sst/opencode
const parsed = info.match(/^(?:(?:https?|ssh):\/\/)?(?:git@)?github\.com[:/]([^/]+)\/([^/.]+?)(?:\.git)?$/)
const parsed = info.match(/git@github\.com:(.*)\.git/) ?? info.match(/github\.com\/(.*)\.git/)
if (!parsed) {
prompts.log.error(`Could not find git repository. Please run this command from a git repository.`)
throw new UI.CancelledError()
}
const [, owner, repo] = parsed
const [owner, repo] = parsed[1].split("/")
return { owner, repo, root: app.path.root }
}
+2 -26
View File
@@ -12,9 +12,8 @@ import { Bus } from "../../bus"
import { Log } from "../../util/log"
import { FileWatcher } from "../../file/watch"
import { Ide } from "../../ide"
import { Agent } from "../../agent/agent"
import { Flag } from "../../flag/flag"
import { Session } from "../../session"
declare global {
const OPENCODE_TUI_PATH: string
@@ -40,16 +39,6 @@ export const TuiCommand = cmd({
alias: ["m"],
describe: "model to use in the format of provider/model",
})
.option("continue", {
alias: ["c"],
describe: "continue the last session",
type: "boolean",
})
.option("session", {
alias: ["s"],
describe: "session id to continue",
type: "string",
})
.option("prompt", {
alias: ["p"],
type: "string",
@@ -80,19 +69,6 @@ export const TuiCommand = cmd({
return
}
const result = await bootstrap({ cwd }, async (app) => {
const sessionID = await (async () => {
if (args.continue) {
const list = Session.list()
const first = await list.next()
await list.return()
if (first.done) return
return first.value.id
}
if (args.session) {
return args.session
}
return undefined
})()
FileWatcher.init()
const providers = await Provider.list()
if (Object.keys(providers).length === 0) {
@@ -130,7 +106,6 @@ export const TuiCommand = cmd({
...(args.model ? ["--model", args.model] : []),
...(args.prompt ? ["--prompt", args.prompt] : []),
...(args.mode ? ["--mode", args.mode] : []),
...(sessionID ? ["--session", sessionID] : []),
],
cwd,
stdout: "inherit",
@@ -141,6 +116,7 @@ export const TuiCommand = cmd({
CGO_ENABLED: "0",
OPENCODE_SERVER: server.url.toString(),
OPENCODE_APP_INFO: JSON.stringify(app),
OPENCODE_AGENTS: JSON.stringify(await Agent.list()),
},
onExit: () => {
server.stop()
+1 -1
View File
@@ -12,7 +12,7 @@ export function FormatError(input: unknown) {
}
if (Config.InvalidError.isInstance(input))
return [
`Config file at ${input.data.path} is invalid` + (input.data.message ? `: ${input.data.message}` : ""),
`Config file at ${input.data.path} is invalid`,
...(input.data.issues?.map((issue) => "↳ " + issue.message + " " + issue.path.join(".")) ?? []),
].join("\n")
+38 -86
View File
@@ -105,15 +105,11 @@ export namespace Config {
result.plugin = result.plugin || []
result.plugin.push(
...[
...(await Filesystem.globUp("plugin/*.{ts,js}", Global.Path.config, Global.Path.config)),
...(await Filesystem.globUp(".opencode/plugin/*.{ts,js}", app.path.cwd, app.path.root)),
...(await Filesystem.globUp("plugin/*.ts", Global.Path.config, Global.Path.config)),
...(await Filesystem.globUp(".opencode/plugin/*.ts", app.path.cwd, app.path.root)),
].map((x) => "file://" + x),
)
if (Flag.OPENCODE_PERMISSION) {
result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.OPENCODE_PERMISSION))
}
// Handle migration from autoshare to share field
if (result.autoshare === true && !result.share) {
result.share = "auto"
@@ -127,12 +123,6 @@ export namespace Config {
if (result.keybinds?.switch_mode_reverse && !result.keybinds.switch_agent_reverse) {
result.keybinds.switch_agent_reverse = result.keybinds.switch_mode_reverse
}
if (result.keybinds?.switch_agent && !result.keybinds.agent_cycle) {
result.keybinds.agent_cycle = result.keybinds.switch_agent
}
if (result.keybinds?.switch_agent_reverse && !result.keybinds.agent_cycle_reverse) {
result.keybinds.agent_cycle_reverse = result.keybinds.switch_agent_reverse
}
if (!result.username) {
const os = await import("os")
@@ -174,9 +164,6 @@ export namespace Config {
export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
export type Mcp = z.infer<typeof Mcp>
export const Permission = z.union([z.literal("ask"), z.literal("allow"), z.literal("deny")])
export type Permission = z.infer<typeof Permission>
export const Agent = z
.object({
model: z.string().optional(),
@@ -187,13 +174,6 @@ export namespace Config {
disable: z.boolean().optional(),
description: z.string().optional().describe("Description of when to use the agent"),
mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]).optional(),
permission: z
.object({
edit: Permission.optional(),
bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
webfetch: Permission.optional(),
})
.optional(),
})
.catchall(z.any())
.openapi({
@@ -205,12 +185,15 @@ export namespace Config {
.object({
leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
app_help: z.string().optional().default("<leader>h").describe("Show help dialog"),
app_exit: z.string().optional().default("ctrl+c,<leader>q").describe("Exit the application"),
switch_mode: z.string().optional().default("none").describe("@deprecated use switch_agent. Next mode"),
switch_mode_reverse: z
.string()
.optional()
.default("none")
.describe("@deprecated use switch_agent_reverse. Previous mode"),
switch_agent: z.string().optional().default("tab").describe("Next agent"),
switch_agent_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
project_init: z.string().optional().default("<leader>i").describe("Create/update AGENTS.md"),
tool_details: z.string().optional().default("<leader>d").describe("Toggle tool details"),
thinking_blocks: z.string().optional().default("<leader>b").describe("Toggle thinking blocks"),
session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
@@ -218,12 +201,18 @@ export namespace Config {
session_unshare: z.string().optional().default("none").describe("Unshare current session"),
session_interrupt: z.string().optional().default("esc").describe("Interrupt current session"),
session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
session_child_cycle: z.string().optional().default("ctrl+right").describe("Cycle to next child session"),
session_child_cycle_reverse: z
.string()
.optional()
.default("ctrl+left")
.describe("Cycle to previous child session"),
tool_details: z.string().optional().default("<leader>d").describe("Toggle tool details"),
model_list: z.string().optional().default("<leader>m").describe("List available models"),
theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
file_list: z.string().optional().default("<leader>f").describe("List files"),
file_close: z.string().optional().default("esc").describe("Close file"),
file_search: z.string().optional().default("<leader>/").describe("Search file"),
file_diff_toggle: z.string().optional().default("<leader>v").describe("Split/unified diff"),
project_init: z.string().optional().default("<leader>i").describe("Create/update AGENTS.md"),
input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
input_submit: z.string().optional().default("enter").describe("Submit input"),
input_newline: z.string().optional().default("shift+enter,ctrl+j").describe("Insert newline in input"),
messages_page_up: z.string().optional().default("pgup").describe("Scroll messages up by one page"),
messages_page_down: z.string().optional().default("pgdown").describe("Scroll messages down by one page"),
messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
@@ -232,42 +221,16 @@ export namespace Config {
.optional()
.default("ctrl+alt+d")
.describe("Scroll messages down by half page"),
messages_previous: z.string().optional().default("ctrl+up").describe("Navigate to previous message"),
messages_next: z.string().optional().default("ctrl+down").describe("Navigate to next message"),
messages_first: z.string().optional().default("ctrl+g").describe("Navigate to first message"),
messages_last: z.string().optional().default("ctrl+alt+g").describe("Navigate to last message"),
messages_layout_toggle: z.string().optional().default("<leader>p").describe("Toggle layout"),
messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
messages_revert: z.string().optional().default("none").describe("@deprecated use messages_undo. Revert message"),
messages_undo: z.string().optional().default("<leader>u").describe("Undo message"),
messages_redo: z.string().optional().default("<leader>r").describe("Redo message"),
model_list: z.string().optional().default("<leader>m").describe("List available models"),
model_cycle_recent: z.string().optional().default("f2").describe("Next recent model"),
model_cycle_recent_reverse: z.string().optional().default("shift+f2").describe("Previous recent model"),
agent_list: z.string().optional().default("<leader>a").describe("List agents"),
agent_cycle: z.string().optional().default("tab").describe("Next agent"),
agent_cycle_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
input_submit: z.string().optional().default("enter").describe("Submit input"),
input_newline: z.string().optional().default("shift+enter,ctrl+j").describe("Insert newline in input"),
// Deprecated commands
switch_mode: z.string().optional().default("none").describe("@deprecated use agent_cycle. Next mode"),
switch_mode_reverse: z
.string()
.optional()
.default("none")
.describe("@deprecated use agent_cycle_reverse. Previous mode"),
switch_agent: z.string().optional().default("tab").describe("@deprecated use agent_cycle. Next agent"),
switch_agent_reverse: z
.string()
.optional()
.default("shift+tab")
.describe("@deprecated use agent_cycle_reverse. Previous agent"),
file_list: z.string().optional().default("none").describe("@deprecated Currently not available. List files"),
file_close: z.string().optional().default("none").describe("@deprecated Close file"),
file_search: z.string().optional().default("none").describe("@deprecated Search file"),
file_diff_toggle: z.string().optional().default("none").describe("@deprecated Split/unified diff"),
messages_previous: z.string().optional().default("none").describe("@deprecated Navigate to previous message"),
messages_next: z.string().optional().default("none").describe("@deprecated Navigate to next message"),
messages_layout_toggle: z.string().optional().default("none").describe("@deprecated Toggle layout"),
messages_revert: z.string().optional().default("none").describe("@deprecated use messages_undo. Revert message"),
app_exit: z.string().optional().default("ctrl+c,<leader>q").describe("Exit the application"),
})
.strict()
.openapi({
@@ -279,6 +242,9 @@ export namespace Config {
})
export type Layout = z.infer<typeof Layout>
export const Permission = z.union([z.literal("ask"), z.literal("allow"), z.literal("deny")])
export type Permission = z.infer<typeof Permission>
export const Info = z
.object({
$schema: z.string().optional().describe("JSON schema reference for configuration validation"),
@@ -328,7 +294,7 @@ export namespace Config {
.record(
ModelsDev.Provider.partial()
.extend({
models: z.record(ModelsDev.Model.partial()).optional(),
models: z.record(ModelsDev.Model.partial()),
options: z
.object({
apiKey: z.string().optional(),
@@ -451,14 +417,14 @@ export namespace Config {
return load(text, filepath)
}
async function load(text: string, configFilepath: string) {
async function load(text: string, filepath: string) {
text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
return process.env[varName] || ""
})
const fileMatches = text.match(/\{file:[^}]+\}/g)
if (fileMatches) {
const configDir = path.dirname(configFilepath)
const configDir = path.dirname(filepath)
const lines = text.split("\n")
for (const match of fileMatches) {
@@ -471,20 +437,7 @@ export namespace Config {
filePath = path.join(os.homedir(), filePath.slice(2))
}
const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(configDir, filePath)
const fileContent = (
await Bun.file(resolvedPath)
.text()
.catch((error) => {
const errMsg = `bad file reference: "${match}"`
if (error.code === "ENOENT") {
throw new InvalidError(
{ path: configFilepath, message: errMsg + ` ${resolvedPath} does not exist` },
{ cause: error },
)
}
throw new InvalidError({ path: configFilepath, message: errMsg }, { cause: error })
})
).trim()
const fileContent = (await Bun.file(resolvedPath).text()).trim()
// escape newlines/quotes, strip outer quotes
text = text.replace(match, JSON.stringify(fileContent).slice(1, -1))
}
@@ -509,7 +462,7 @@ export namespace Config {
.join("\n")
throw new JsonError({
path: configFilepath,
path: filepath,
message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
})
}
@@ -518,21 +471,21 @@ export namespace Config {
if (parsed.success) {
if (!parsed.data.$schema) {
parsed.data.$schema = "https://opencode.ai/config.json"
await Bun.write(configFilepath, JSON.stringify(parsed.data, null, 2))
await Bun.write(filepath, JSON.stringify(parsed.data, null, 2))
}
const data = parsed.data
if (data.plugin) {
for (let i = 0; i < data.plugin?.length; i++) {
const plugin = data.plugin[i]
try {
data.plugin[i] = import.meta.resolve(plugin, configFilepath)
data.plugin[i] = import.meta.resolve(plugin, filepath)
} catch (err) {}
}
}
return data
}
throw new InvalidError({ path: configFilepath, issues: parsed.error.issues })
throw new InvalidError({ path: filepath, issues: parsed.error.issues })
}
export const JsonError = NamedError.create(
"ConfigJsonError",
@@ -547,7 +500,6 @@ export namespace Config {
z.object({
path: z.string(),
issues: z.custom<z.ZodIssue[]>().optional(),
message: z.string().optional(),
}),
)
-2
View File
@@ -3,8 +3,6 @@ export namespace Flag {
export const OPENCODE_DISABLE_WATCHER = truthy("OPENCODE_DISABLE_WATCHER")
export const OPENCODE_CONFIG = process.env["OPENCODE_CONFIG"]
export const OPENCODE_DISABLE_AUTOUPDATE = truthy("OPENCODE_DISABLE_AUTOUPDATE")
export const OPENCODE_PERMISSION = process.env["OPENCODE_PERMISSION"]
export const OPENCODE_DISABLE_DEFAULT_PLUGINS = truthy("OPENCODE_DISABLE_DEFAULT_PLUGINS")
function truthy(key: string) {
const value = process.env[key]?.toLowerCase()
+3 -9
View File
@@ -76,7 +76,7 @@ export const prettier: Info = {
export const biome: Info = {
name: "biome",
command: [BunProc.which(), "x", "@biomejs/biome", "format", "--write", "$FILE"],
command: [BunProc.which(), "x", "biome", "format", "--write", "$FILE"],
environment: {
BUN_BE_BUN: "1",
},
@@ -110,14 +110,8 @@ export const biome: Info = {
],
async enabled() {
const app = App.info()
const configs = ["biome.json", "biome.jsonc"]
for (const config of configs) {
const found = await Filesystem.findUp(config, app.path.cwd, app.path.root)
if (found.length > 0) {
return true
}
}
return false
const items = await Filesystem.findUp("biome.json", app.path.cwd, app.path.root)
return items.length > 0
},
}
+1 -1
View File
@@ -71,7 +71,7 @@ export namespace Format {
const proc = Bun.spawn({
cmd: item.command.map((x) => x.replace("$FILE", file)),
cwd: App.info().path.cwd,
env: { ...process.env, ...item.environment },
env: item.environment,
stdout: "ignore",
stderr: "ignore",
})
+1 -2
View File
@@ -25,10 +25,9 @@ await Promise.all([
fs.mkdir(Global.Path.config, { recursive: true }),
fs.mkdir(Global.Path.state, { recursive: true }),
fs.mkdir(Global.Path.log, { recursive: true }),
fs.mkdir(Global.Path.bin, { recursive: true }),
])
const CACHE_VERSION = "8"
const CACHE_VERSION = "6"
const version = await Bun.file(path.join(Global.Path.cache, "version"))
.text()
-5
View File
@@ -21,9 +21,6 @@ import { GithubCommand } from "./cli/cmd/github"
const cancel = new AbortController()
try {
} catch (e) {}
process.on("unhandledRejection", (e) => {
Log.Default.error("rejection", {
e: e instanceof Error ? e.message : e,
@@ -61,8 +58,6 @@ const cli = yargs(hideBin(process.argv))
})(),
})
process.env["OPENCODE"] = "1"
Log.Default.info("opencode", {
version: Installation.VERSION,
args: process.argv.slice(2),
+4 -11
View File
@@ -126,26 +126,19 @@ export namespace LSPClient {
input.path = path.isAbsolute(input.path) ? input.path : path.resolve(app.path.cwd, input.path)
const file = Bun.file(input.path)
const text = await file.text()
const extension = path.extname(input.path)
const languageId = LANGUAGE_EXTENSIONS[extension] ?? "plaintext"
const version = files[input.path]
if (version !== undefined) {
const next = version + 1
files[input.path] = next
log.info("textDocument/didChange", { path: input.path, version: next })
await connection.sendNotification("textDocument/didChange", {
diagnostics.delete(input.path)
await connection.sendNotification("textDocument/didClose", {
textDocument: {
uri: `file://` + input.path,
version: next,
},
contentChanges: [{ text }],
})
return
}
log.info("textDocument/didOpen", input)
diagnostics.delete(input.path)
const extension = path.extname(input.path)
const languageId = LANGUAGE_EXTENSIONS[extension] ?? "plaintext"
await connection.sendNotification("textDocument/didOpen", {
textDocument: {
uri: `file://` + input.path,
-1
View File
@@ -94,7 +94,6 @@ export const LANGUAGE_EXTENSIONS: Record<string, string> = {
".yml": "yaml",
".mjs": "javascript",
".cjs": "javascript",
".vue": "vue",
".zig": "zig",
".zon": "zig",
} as const
+5 -160
View File
@@ -65,67 +65,6 @@ export namespace LSPServer {
},
}
export const Vue: Info = {
id: "vue",
extensions: [".vue"],
root: NearestRoot([
"tsconfig.json",
"jsconfig.json",
"package.json",
"pnpm-lock.yaml",
"yarn.lock",
"bun.lockb",
"bun.lock",
"vite.config.ts",
"vite.config.js",
"nuxt.config.ts",
"nuxt.config.js",
"vue.config.js",
]),
async spawn(_, root) {
let binary = Bun.which("vue-language-server")
const args: string[] = []
if (!binary) {
const js = path.join(
Global.Path.bin,
"node_modules",
"@vue",
"language-server",
"bin",
"vue-language-server.js",
)
if (!(await Bun.file(js).exists())) {
await Bun.spawn([BunProc.which(), "install", "@vue/language-server"], {
cwd: Global.Path.bin,
env: {
...process.env,
BUN_BE_BUN: "1",
},
stdout: "pipe",
stderr: "pipe",
stdin: "pipe",
}).exited
}
binary = BunProc.which()
args.push("run", js)
}
args.push("--stdio")
const proc = spawn(binary, args, {
cwd: root,
env: {
...process.env,
BUN_BE_BUN: "1",
},
})
return {
process: proc,
initialization: {
// Leave empty; the server will auto-detect workspace TypeScript.
},
}
},
}
export const ESLint: Info = {
id: "eslint",
root: NearestRoot([
@@ -142,7 +81,7 @@ export namespace LSPServer {
".eslintrc.json",
"package.json",
]),
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue"],
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
async spawn(app, root) {
const eslint = await Bun.resolve("eslint", app.path.cwd).catch(() => {})
if (!eslint) return
@@ -155,7 +94,7 @@ export namespace LSPServer {
const zipPath = path.join(Global.Path.bin, "vscode-eslint.zip")
await Bun.file(zipPath).write(response)
await $`unzip -o -q ${zipPath}`.quiet().cwd(Global.Path.bin).nothrow()
await $`unzip -o -q ${zipPath}`.cwd(Global.Path.bin).nothrow()
await fs.rm(zipPath, { force: true })
const extractedPath = path.join(Global.Path.bin, "vscode-eslint-main")
@@ -271,24 +210,7 @@ export namespace LSPServer {
extensions: [".py", ".pyi"],
root: NearestRoot(["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"]),
async spawn(_, root) {
let binary = Bun.which("pyright-langserver")
const args = []
if (!binary) {
const js = path.join(Global.Path.bin, "node_modules", "pyright", "dist", "pyright-langserver.js")
if (!(await Bun.file(js).exists())) {
await Bun.spawn([BunProc.which(), "install", "pyright"], {
cwd: Global.Path.bin,
env: {
...process.env,
BUN_BE_BUN: "1",
},
}).exited
}
binary = BunProc.which()
args.push(...["run", js])
}
args.push("--stdio")
const proc = spawn(binary, args, {
const proc = spawn(BunProc.which(), ["x", "pyright-langserver", "--stdio"], {
cwd: root,
env: {
...process.env,
@@ -330,7 +252,7 @@ export namespace LSPServer {
const zipPath = path.join(Global.Path.bin, "elixir-ls.zip")
await Bun.file(zipPath).write(response)
await $`unzip -o -q ${zipPath}`.quiet().cwd(Global.Path.bin).nothrow()
await $`unzip -o -q ${zipPath}`.cwd(Global.Path.bin).nothrow()
await fs.rm(zipPath, {
force: true,
@@ -432,7 +354,7 @@ export namespace LSPServer {
await Bun.file(tempPath).write(downloadResponse)
if (ext === "zip") {
await $`unzip -o -q ${tempPath}`.quiet().cwd(Global.Path.bin).nothrow()
await $`unzip -o -q ${tempPath}`.cwd(Global.Path.bin).nothrow()
} else {
await $`tar -xf ${tempPath}`.cwd(Global.Path.bin).nothrow()
}
@@ -499,81 +421,4 @@ export namespace LSPServer {
}
},
}
export const Clangd: Info = {
id: "clangd",
root: NearestRoot(["compile_commands.json", "compile_flags.txt", ".clangd", "CMakeLists.txt", "Makefile"]),
extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"],
async spawn(_, root) {
let bin = Bun.which("clangd", {
PATH: process.env["PATH"] + ":" + Global.Path.bin,
})
if (!bin) {
log.info("downloading clangd from GitHub releases")
const releaseResponse = await fetch("https://api.github.com/repos/clangd/clangd/releases/latest")
if (!releaseResponse.ok) {
log.error("Failed to fetch clangd release info")
return
}
const release = await releaseResponse.json()
const platform = process.platform
let assetName = ""
if (platform === "darwin") {
assetName = "clangd-mac-"
} else if (platform === "linux") {
assetName = "clangd-linux-"
} else if (platform === "win32") {
assetName = "clangd-windows-"
} else {
log.error(`Platform ${platform} is not supported by clangd auto-download`)
return
}
assetName += release.tag_name + ".zip"
const asset = release.assets.find((a: any) => a.name === assetName)
if (!asset) {
log.error(`Could not find asset ${assetName} in latest clangd release`)
return
}
const downloadUrl = asset.browser_download_url
const downloadResponse = await fetch(downloadUrl)
if (!downloadResponse.ok) {
log.error("Failed to download clangd")
return
}
const zipPath = path.join(Global.Path.bin, "clangd.zip")
await Bun.file(zipPath).write(downloadResponse)
await $`unzip -o -q ${zipPath}`.quiet().cwd(Global.Path.bin).nothrow()
await fs.rm(zipPath, { force: true })
const extractedDir = path.join(Global.Path.bin, assetName.replace(".zip", ""))
bin = path.join(extractedDir, "bin", "clangd" + (platform === "win32" ? ".exe" : ""))
if (!(await Bun.file(bin).exists())) {
log.error("Failed to extract clangd binary")
return
}
if (platform !== "win32") {
await $`chmod +x ${bin}`.nothrow()
}
log.info(`installed clangd`, { bin })
}
return {
process: spawn(bin, ["--background-index", "--clang-tidy"], {
cwd: root,
}),
}
},
}
}
+1 -2
View File
@@ -149,8 +149,7 @@ export namespace MCP {
for (const [clientName, client] of Object.entries(await clients())) {
for (const [toolName, tool] of Object.entries(await client.tools())) {
const sanitizedClientName = clientName.replace(/\s+/g, "_")
const sanitizedToolName = toolName.replace(/[-\s]+/g, "_")
result[sanitizedClientName + "_" + sanitizedToolName] = tool
result[sanitizedClientName + "_" + toolName] = tool
}
}
return result
+4 -7
View File
@@ -62,7 +62,7 @@ export namespace Permission {
async (state) => {
for (const pending of Object.values(state.pending)) {
for (const item of Object.values(pending)) {
item.reject(new RejectedError(item.info.sessionID, item.info.id, item.info.callID, item.info.metadata))
item.reject(new RejectedError(item.info.sessionID, item.info.id, item.info.callID))
}
}
},
@@ -82,13 +82,11 @@ export namespace Permission {
sessionID: input.sessionID,
messageID: input.messageID,
toolCallID: input.callID,
pattern: input.pattern,
})
if (approved[input.sessionID]?.[input.pattern ?? input.type]) return
const info: Info = {
id: Identifier.ascending("permission"),
type: input.type,
pattern: input.pattern,
sessionID: input.sessionID,
messageID: input.messageID,
callID: input.callID,
@@ -105,7 +103,7 @@ export namespace Permission {
}).then((x) => x.status)
) {
case "deny":
throw new RejectedError(info.sessionID, info.id, info.callID, info.metadata)
throw new RejectedError(info.sessionID, info.id, info.callID)
case "allow":
return
}
@@ -131,7 +129,7 @@ export namespace Permission {
if (!match) return
delete pending[input.sessionID][input.permissionID]
if (input.response === "reject") {
match.reject(new RejectedError(input.sessionID, input.permissionID, match.info.callID, match.info.metadata))
match.reject(new RejectedError(input.sessionID, input.permissionID, match.info.callID))
return
}
match.resolve()
@@ -156,9 +154,8 @@ export namespace Permission {
public readonly sessionID: string,
public readonly permissionID: string,
public readonly toolCallID?: string,
public readonly metadata?: Record<string, any>,
) {
super(`The user rejected permission to use this specific tool call. You may try again with different parameters.`)
super(`The user rejected permission to use this functionality`)
}
}
}
+7 -19
View File
@@ -6,7 +6,6 @@ import { Log } from "../util/log"
import { createOpencodeClient } from "@opencode-ai/sdk"
import { Server } from "../server/server"
import { BunProc } from "../bun"
import { Flag } from "../flag/flag"
export namespace Plugin {
const log = Log.create({ service: "plugin" })
@@ -18,17 +17,7 @@ export namespace Plugin {
})
const config = await Config.get()
const hooks = []
const input = {
client,
app,
$: Bun.$,
}
const plugins = [...(config.plugin ?? [])]
if (!Flag.OPENCODE_DISABLE_DEFAULT_PLUGINS) {
plugins.push("opencode-copilot-auth")
plugins.push("opencode-anthropic-auth")
}
for (let plugin of plugins) {
for (let plugin of config.plugin ?? []) {
log.info("loading plugin", { path: plugin })
if (!plugin.startsWith("file://")) {
const [pkg, version] = plugin.split("@")
@@ -36,19 +25,22 @@ export namespace Plugin {
}
const mod = await import(plugin)
for (const [_name, fn] of Object.entries<PluginInstance>(mod)) {
const init = await fn(input)
const init = await fn({
client,
app,
$: Bun.$,
})
hooks.push(init)
}
}
return {
hooks,
input,
}
})
export async function trigger<
Name extends Exclude<keyof Required<Hooks>, "auth" | "event">,
Name extends keyof Required<Hooks>,
Input = Parameters<Required<Hooks>[Name]>[0],
Output = Parameters<Required<Hooks>[Name]>[1],
>(name: Name, input: Input, output: Output): Promise<Output> {
@@ -64,10 +56,6 @@ export namespace Plugin {
return output
}
export async function list() {
return state().then((x) => x.hooks)
}
export function init() {
Bus.subscribeAll(async (input) => {
const hooks = await state().then((x) => x.hooks)
+88 -18
View File
@@ -5,7 +5,8 @@ import { mergeDeep, sortBy } from "remeda"
import { NoSuchModelError, type LanguageModel, type Provider as SDK } from "ai"
import { Log } from "../util/log"
import { BunProc } from "../bun"
import { Plugin } from "../plugin"
import { AuthAnthropic } from "../auth/anthropic"
import { AuthCopilot } from "../auth/copilot"
import { ModelsDev } from "./models"
import { NamedError } from "../util/error"
import { Auth } from "../auth"
@@ -25,13 +26,93 @@ export namespace Provider {
type Source = "env" | "config" | "custom" | "api"
const CUSTOM_LOADERS: Record<string, CustomLoader> = {
async anthropic() {
async anthropic(provider) {
const access = await AuthAnthropic.access()
if (!access) return { autoload: false }
for (const model of Object.values(provider.models)) {
model.cost = {
input: 0,
output: 0,
}
}
return {
autoload: false,
autoload: true,
options: {
headers: {
"anthropic-beta":
"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
apiKey: "",
async fetch(input: any, init: any) {
const access = await AuthAnthropic.access()
const headers = {
...init.headers,
authorization: `Bearer ${access}`,
"anthropic-beta": "oauth-2025-04-20",
}
delete headers["x-api-key"]
return fetch(input, {
...init,
headers,
})
},
},
}
},
"github-copilot": async (provider) => {
const copilot = await AuthCopilot()
if (!copilot) return { autoload: false }
let info = await Auth.get("github-copilot")
if (!info || info.type !== "oauth") return { autoload: false }
if (provider && provider.models) {
for (const model of Object.values(provider.models)) {
model.cost = {
input: 0,
output: 0,
}
}
}
return {
autoload: true,
options: {
apiKey: "",
async fetch(input: any, init: any) {
const info = await Auth.get("github-copilot")
if (!info || info.type !== "oauth") return
if (!info.access || info.expires < Date.now()) {
const tokens = await copilot.access(info.refresh)
if (!tokens) throw new Error("GitHub Copilot authentication expired")
await Auth.set("github-copilot", {
type: "oauth",
...tokens,
})
info.access = tokens.access
}
let isAgentCall = false
let isVisionRequest = false
try {
const body = typeof init.body === "string" ? JSON.parse(init.body) : init.body
if (body?.messages) {
isAgentCall = body.messages.some((msg: any) => msg.role && ["tool", "assistant"].includes(msg.role))
isVisionRequest = body.messages.some(
(msg: any) =>
Array.isArray(msg.content) && msg.content.some((part: any) => part.type === "image_url"),
)
}
} catch {}
const headers: Record<string, string> = {
...init.headers,
...copilot.HEADERS,
Authorization: `Bearer ${info.access}`,
"Openai-Intent": "conversation-edits",
"X-Initiator": isAgentCall ? "agent" : "user",
}
if (isVisionRequest) {
headers["Copilot-Vision-Request"] = "true"
}
delete headers["x-api-key"]
return fetch(input, {
...init,
headers,
})
},
},
}
@@ -259,17 +340,6 @@ export namespace Provider {
}
}
for (const plugin of await Plugin.list()) {
if (!plugin.auth) continue
const providerID = plugin.auth.provider
if (disabled.has(providerID)) continue
const auth = await Auth.get(providerID)
if (!auth) continue
if (!plugin.auth.loader) continue
const options = await plugin.auth.loader(() => Auth.get(providerID) as any, database[plugin.auth.provider])
mergeProvider(plugin.auth.provider, options ?? {}, "custom")
}
// load config
for (const [providerID, provider] of configProviders) {
mergeProvider(providerID, provider.options ?? {}, "config")
@@ -378,7 +448,7 @@ export namespace Provider {
}
}
const priority = ["gemini-2.5-pro-preview", "gpt-5", "claude-sonnet-4"]
const priority = ["gemini-2.5-pro-preview", "codex-mini", "claude-sonnet-4"]
export function sort(models: ModelsDev.Model[]) {
return sortBy(
models,
+20 -13
View File
@@ -74,7 +74,6 @@ export namespace ProviderTransform {
export function temperature(_providerID: string, modelID: string) {
if (modelID.toLowerCase().includes("qwen")) return 0.55
if (modelID.toLowerCase().includes("claude")) return 1
return 0
}
@@ -83,19 +82,27 @@ export namespace ProviderTransform {
return undefined
}
export function options(providerID: string, modelID: string, sessionID: string): Record<string, any> | undefined {
const result: Record<string, any> = {}
if (providerID === "openai") {
result["promptCacheKey"] = sessionID
}
if (modelID.includes("gpt-5") && !modelID.includes("gpt-5-chat")) {
result["reasoningEffort"] = "minimal"
if (providerID !== "azure") {
result["textVerbosity"] = "low"
export function options(_providerID: string, modelID: string) {
if (modelID.includes("gpt-5")) {
return {
reasoningEffort: "minimal",
textVerbosity: "low",
// reasoningSummary: "auto",
// include: ["reasoning.encrypted_content"],
}
}
return result
// if (modelID.includes("claude")) {
// return {
// thinking: {
// type: "enabled",
// budgetTokens: 32000,
// },
// }
// }
// if (_providerID === "bedrock") {
// return {
// reasoningConfig: { type: "enabled", budgetTokens: 32000 },
// }
// }
}
}
+4 -171
View File
@@ -20,7 +20,6 @@ import { callTui, TuiRoute } from "./tui"
import { Permission } from "../permission"
import { lazy } from "../util/lazy"
import { Agent } from "../agent/agent"
import { Auth } from "../auth"
const ERRORS = {
400: {
@@ -89,7 +88,7 @@ export namespace Server {
version: "0.0.3",
description: "opencode api",
},
openapi: "3.1.1",
openapi: "3.0.0",
},
}),
)
@@ -248,34 +247,6 @@ export namespace Server {
return c.json(session)
},
)
.get(
"/session/:id/children",
describeRoute({
description: "Get a session's children",
operationId: "session.children",
responses: {
200: {
description: "List of children",
content: {
"application/json": {
schema: resolver(Session.Info.array()),
},
},
},
},
}),
zValidator(
"param",
z.object({
id: z.string(),
}),
),
async (c) => {
const sessionID = c.req.valid("param").id
const session = await Session.children(sessionID)
return c.json(session)
},
)
.post(
"/session",
describeRoute({
@@ -293,18 +264,8 @@ export namespace Server {
},
},
}),
zValidator(
"json",
z
.object({
parentID: z.string().optional(),
title: z.string().optional(),
})
.optional(),
),
async (c) => {
const body = c.req.valid("json") ?? {}
const session = await Session.create(body.parentID, body.title)
const session = await Session.create()
return c.json(session)
},
)
@@ -335,47 +296,6 @@ export namespace Server {
return c.json(true)
},
)
.patch(
"/session/:id",
describeRoute({
description: "Update session properties",
operationId: "session.update",
responses: {
200: {
description: "Successfully updated session",
content: {
"application/json": {
schema: resolver(Session.Info),
},
},
},
},
}),
zValidator(
"param",
z.object({
id: z.string(),
}),
),
zValidator(
"json",
z.object({
title: z.string().optional(),
}),
),
async (c) => {
const sessionID = c.req.valid("param").id
const updates = c.req.valid("json")
const updatedSession = await Session.update(sessionID, (session) => {
if (updates.title !== undefined) {
session.title = updates.title
}
})
return c.json(updatedSession)
},
)
.post(
"/session/:id/init",
describeRoute({
@@ -631,36 +551,6 @@ export namespace Server {
return c.json(msg)
},
)
.post(
"/session/:id/shell",
describeRoute({
description: "Run a shell command",
operationId: "session.shell",
responses: {
200: {
description: "Created message",
content: {
"application/json": {
schema: resolver(MessageV2.Assistant),
},
},
},
},
}),
zValidator(
"param",
z.object({
id: z.string().openapi({ description: "Session ID" }),
}),
),
zValidator("json", Session.CommandInput.omit({ sessionID: true })),
async (c) => {
const sessionID = c.req.valid("param").id
const body = c.req.valid("json")
const msg = await Session.shell({ ...body, sessionID })
return c.json(msg)
},
)
.post(
"/session/:id/revert",
describeRoute({
@@ -1137,7 +1027,7 @@ export namespace Server {
.post(
"/tui/execute-command",
describeRoute({
description: "Execute a TUI command (e.g. agent_cycle)",
description: "Execute a TUI command (e.g. switch_agent)",
operationId: "tui.executeCommand",
responses: {
200: {
@@ -1158,64 +1048,7 @@ export namespace Server {
),
async (c) => c.json(await callTui(c)),
)
.post(
"/tui/show-toast",
describeRoute({
description: "Show a toast notification in the TUI",
operationId: "tui.showToast",
responses: {
200: {
description: "Toast notification shown successfully",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
},
}),
zValidator(
"json",
z.object({
title: z.string().optional(),
message: z.string(),
variant: z.enum(["info", "success", "warning", "error"]),
}),
),
async (c) => c.json(await callTui(c)),
)
.route("/tui/control", TuiRoute)
.put(
"/auth/:id",
describeRoute({
description: "Set authentication credentials",
operationId: "auth.set",
responses: {
200: {
description: "Successfully set authentication credentials",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
...ERRORS,
},
}),
zValidator(
"param",
z.object({
id: z.string(),
}),
),
zValidator("json", Auth.Info),
async (c) => {
const id = c.req.valid("param").id
const info = c.req.valid("json")
await Auth.set(id, info)
return c.json(true)
},
)
return result
})
@@ -1229,7 +1062,7 @@ export namespace Server {
version: "1.0.0",
description: "opencode api",
},
openapi: "3.1.1",
openapi: "3.0.0",
},
})
return result
+12 -151
View File
@@ -1,5 +1,4 @@
import path from "path"
import { spawn } from "child_process"
import { Decimal } from "decimal.js"
import { z, ZodSchema } from "zod"
import {
@@ -43,9 +42,6 @@ import { ToolRegistry } from "../tool/registry"
import { Plugin } from "../plugin"
import { Agent } from "../agent/agent"
import { Permission } from "../permission"
import { Wildcard } from "../util/wildcard"
import { ulid } from "ulid"
import { defer } from "../util/defer"
export namespace Session {
const log = Log.create({ service: "session" })
@@ -163,12 +159,12 @@ export namespace Session {
},
)
export async function create(parentID?: string, title?: string) {
export async function create(parentID?: string) {
const result: Info = {
id: Identifier.descending("session"),
version: Installation.VERSION,
parentID,
title: title ?? createDefaultTitle(!!parentID),
title: createDefaultTitle(!!parentID),
time: {
created: Date.now(),
updated: Date.now(),
@@ -526,9 +522,7 @@ export namespace Session {
t.execute(args, {
sessionID: input.sessionID,
abort: new AbortController().signal,
agent: input.agent!,
messageID: userMsg.id,
extra: { bypassCwdCheck: true },
metadata: async () => {},
}),
)
@@ -671,14 +665,14 @@ export namespace Session {
const lastSummary = msgs.findLast((msg) => msg.info.role === "assistant" && msg.info.summary === true)
if (lastSummary) msgs = msgs.filter((msg) => msg.info.id >= lastSummary.info.id)
if (msgs.filter((m) => m.info.role === "user").length === 1 && !session.parentID && isDefaultTitle(session.title)) {
if (msgs.length === 1 && !session.parentID && isDefaultTitle(session.title)) {
const small = (await Provider.getSmallModel(input.providerID)) ?? model
generateText({
maxOutputTokens: small.info.reasoning ? 1024 : 20,
providerOptions: {
[input.providerID]: {
...small.info.options,
...ProviderTransform.options(input.providerID, small.info.id, input.sessionID),
...ProviderTransform.options(input.providerID, small.info.id),
},
},
messages: [
@@ -764,22 +758,17 @@ export namespace Session {
sessionID: input.sessionID,
}
await updateMessage(assistantMsg)
await using _ = defer(async () => {
if (assistantMsg.time.completed) return
await Storage.remove(`session/message/${input.sessionID}/${assistantMsg.id}`)
await Bus.publish(MessageV2.Event.Removed, { sessionID: input.sessionID, messageID: assistantMsg.id })
})
const tools: Record<string, AITool> = {}
const processor = createProcessor(assistantMsg, model.info)
const enabledTools = pipe(
agent.tools,
mergeDeep(await ToolRegistry.enabled(input.providerID, input.modelID, agent)),
mergeDeep(await ToolRegistry.enabled(input.providerID, input.modelID)),
mergeDeep(input.tools ?? {}),
)
for (const item of await ToolRegistry.tools(input.providerID, input.modelID)) {
if (Wildcard.all(item.id, enabledTools) === false) continue
if (enabledTools[item.id] === false) continue
tools[item.id] = tool({
id: item.id as any,
description: item.description,
@@ -801,7 +790,6 @@ export namespace Session {
abort: options.abortSignal!,
messageID: assistantMsg.id,
callID: options.toolCallId,
agent: agent.name,
metadata: async (val) => {
const match = processor.partFromToolCall(options.toolCallId)
if (match && match.state.status === "running") {
@@ -841,7 +829,7 @@ export namespace Session {
}
for (const [key, item] of Object.entries(await MCP.tools())) {
if (Wildcard.all(key, enabledTools) === false) continue
if (enabledTools[key] === false) continue
const execute = item.execute
if (!execute) continue
item.execute = async (args, opts) => {
@@ -877,7 +865,7 @@ export namespace Session {
: undefined,
topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
options: {
...ProviderTransform.options(input.providerID, input.modelID, input.sessionID),
...ProviderTransform.options(input.providerID, input.modelID),
...model.info.options,
...agent.options,
},
@@ -973,7 +961,7 @@ export namespace Session {
content: x,
}),
),
...MessageV2.toModelMessage(msgs.filter((m) => !(m.info.role === "assistant" && m.info.error))),
...MessageV2.toModelMessage(msgs),
],
tools: model.info.tool_call === false ? undefined : tools,
model: wrapLanguageModel({
@@ -1005,134 +993,6 @@ export namespace Session {
return result
}
export const CommandInput = z.object({
sessionID: Identifier.schema("session"),
agent: z.string(),
command: z.string(),
})
export type CommandInput = z.infer<typeof CommandInput>
export async function shell(input: CommandInput) {
using abort = lock(input.sessionID)
const msg: MessageV2.Assistant = {
id: Identifier.ascending("message"),
sessionID: input.sessionID,
system: [],
mode: input.agent,
cost: 0,
path: {
cwd: App.info().path.cwd,
root: App.info().path.root,
},
time: {
created: Date.now(),
},
role: "assistant",
tokens: {
input: 0,
output: 0,
reasoning: 0,
cache: { read: 0, write: 0 },
},
modelID: "",
providerID: "",
}
await updateMessage(msg)
const part: MessageV2.Part = {
type: "tool",
id: Identifier.ascending("part"),
messageID: msg.id,
sessionID: input.sessionID,
tool: "bash",
callID: ulid(),
state: {
status: "running",
time: {
start: Date.now(),
},
input: {
command: input.command,
},
},
}
await updatePart(part)
const app = App.info()
const shell = process.env["SHELL"] ?? "bash"
const shellName = path.basename(shell)
const scripts: Record<string, string> = {
nu: input.command,
fish: `eval "${input.command}"`,
}
const script =
scripts[shellName] ??
`[[ -f ~/.zshrc ]] && source ~/.zshrc >/dev/null 2>&1 || true
[[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
eval "${input.command}"`
const isFishOrNu = shellName === "fish" || shellName === "nu"
const args = isFishOrNu ? ["-c", script] : ["-c", "-l", script]
const proc = spawn(shell, args, {
cwd: app.path.cwd,
signal: abort.signal,
env: {
...process.env,
TERM: "dumb",
},
})
let output = ""
proc.stdout?.on("data", (chunk) => {
output += chunk.toString()
if (part.state.status === "running") {
part.state.metadata = {
output: output,
description: "",
}
updatePart(part)
}
})
proc.stderr?.on("data", (chunk) => {
output += chunk.toString()
if (part.state.status === "running") {
part.state.metadata = {
output: output,
description: "",
}
updatePart(part)
}
})
await new Promise<void>((resolve) => {
proc.on("close", () => {
resolve()
})
})
msg.time.completed = Date.now()
await updateMessage(msg)
if (part.state.status === "running") {
part.state = {
status: "completed",
time: {
...part.state.time,
end: Date.now(),
},
input: part.state.input,
title: "",
metadata: {
output,
description: "",
},
output,
}
await updatePart(part)
}
return { info: msg, parts: [part] }
}
function createProcessor(assistantMsg: MessageV2.Assistant, model: ModelsDev.Model) {
const toolcalls: Record<string, MessageV2.ToolPart> = {}
let snapshot: string | undefined
@@ -1147,7 +1007,7 @@ export namespace Session {
async process(stream: StreamTextResult<Record<string, AITool>, never>) {
try {
let currentText: MessageV2.TextPart | undefined
let reasoningMap: Record<string, MessageV2.ReasoningPart> = {}
// let reasoningMap: Record<string, MessageV2.ReasoningPart> = {}
for await (const value of stream.fullStream) {
log.info("part", {
@@ -1157,6 +1017,7 @@ export namespace Session {
case "start":
break
/*
case "reasoning-start":
if (value.id in reasoningMap) {
continue
@@ -1194,6 +1055,7 @@ export namespace Session {
delete reasoningMap[value.id]
}
break
*/
case "tool-input-start":
const part = await updatePart({
@@ -1268,7 +1130,6 @@ export namespace Session {
status: "error",
input: value.input,
error: (value.error as any).toString(),
metadata: value.error instanceof Permission.RejectedError ? value.error.metadata : undefined,
time: {
start: match.state.time.start,
end: Date.now(),
@@ -64,7 +64,6 @@ export namespace MessageV2 {
status: z.literal("error"),
input: z.record(z.any()),
error: z.string(),
metadata: z.record(z.any()).optional(),
time: z.object({
start: z.number(),
end: z.number(),
@@ -1,18 +1,24 @@
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
If the user asks for help or wants to give feedback inform them of the following:
- /help: Get help with using opencode
- To give feedback, users should report the issue at https://github.com/sst/opencode/issues
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
# Tone and style
You should be concise, direct, and to the point.
You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail.
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
<example>
user: 2 + 2
assistant: 4
@@ -50,18 +56,18 @@ assistant: [runs ls and sees foo.c, bar.c, baz.c]
user: which file contains the implementation of foo?
assistant: src/foo.c
</example>
When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface.
<example>
user: write tests for new feature
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
</example>
# Proactiveness
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
- Doing the right thing when asked, including taking actions and follow-up actions
- Not surprising the user with actions you take without asking
1. Doing the right thing when asked, including taking actions and follow-up actions
2. Not surprising the user with actions you take without asking
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
# Following conventions
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
@@ -75,7 +81,7 @@ When making changes to files, first understand the file's code conventions. Mimi
# Task Management
You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
You have access to the TodoWrite and TodoRead tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
@@ -121,24 +127,27 @@ I've found some existing telemetry code. Let me mark the first todo as in_progre
[Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
</example>
# Doing tasks
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
- Use the TodoWrite tool to plan the task if required
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
- Implement the solution using all tools available to you
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CLAUDE.md so that you will know to run it next time.
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
# Tool usage policy
- When doing file search, prefer to use the Task tool in order to reduce context usage.
- You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description.
- When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response.
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
# Code References
@@ -149,3 +158,4 @@ When referencing specific functions or pieces of code include the pattern `file_
user: Where are errors from the client handled?
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
</example>
@@ -1,143 +0,0 @@
You are an expert AI programming assistant
Your name is opencode
Keep your answers short and impersonal.
<gptAgentInstructions>
You are a highly sophisticated coding agent with expert-level knowledge across programming languages and frameworks.
You are an agent - you must keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
You MUST iterate and keep going until the problem is solved.
You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.
Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
You will be given some context and attachments along with the user prompt. You can use them if they are relevant to the task, and ignore them if not.
If you can infer the project type (languages, frameworks, and libraries) from the user's query or the context that you have, make sure to keep them in mind when making changes.
Use multiple tools as needed, and do not give up until the task is complete or impossible.
NEVER print codeblocks for file changes or terminal commands unless explicitly requested - use the appropriate tool.
Do not repeat yourself after tool calls; continue from where you left off.
You must use webfetch tool to recursively gather all information from URL's provided to you by the user, as well as any links you find in the content of those pages.
</gptAgentInstructions>
<structuredWorkflow>
# Workflow
1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
3. Develop a clear, step-by-step plan. Break down the fix into manageable,
incremental steps - use the todo tool to track your progress.
4. Implement the fix incrementally. Make small, testable code changes.
5. Debug as needed. Use debugging techniques to isolate and resolve issues.
6. Test frequently. Run tests after each change to verify correctness.
7. Iterate until the root cause is fixed and all tests pass.
8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
**CRITICAL - Before ending your turn:**
- Review and update the todo list, marking completed, skipped (with explanations), or blocked items.
## 1. Deeply Understand the Problem
- Carefully read the issue and think hard about a plan to solve it before coding.
- Break down the problem into manageable parts. Consider the following:
- What is the expected behavior?
- What are the edge cases?
- What are the potential pitfalls?
- How does this fit into the larger context of the codebase?
- What are the dependencies and interactions with other parts of the codee
## 2. Codebase Investigation
- Explore relevant files and directories.
- Search for key functions, classes, or variables related to the issue.
- Read and understand relevant code snippets.
- Identify the root cause of the problem.
- Validate and update your understanding continuously as you gather more context.
## 3. Develop a Detailed Plan
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
- Create a todo list to track your progress.
- Each time you check off a step, update the todo list.
- Make sure that you ACTUALLY continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next.
## 4. Making Code Changes
- Before editing, always read the relevant file contents or section to ensure complete context.
- Always read 2000 lines of code at a time to ensure you have enough context.
- If a patch is not applied correctly, attempt to reapply it.
- Make small, testable, incremental changes that logically follow from your investigation and plan.
- Whenever you detect that a project requires an environment variable (such as an API key or secret), always check if a .env file exists in the project root. If it does not exist, automatically create a .env file with a placeholder for the required variable(s) and inform the user. Do this proactively, without waiting for the user to request it.
## 5. Debugging
- Make code changes only if you have high confidence they can solve the problem
- When debugging, try to determine the root cause rather than addressing symptoms
- Debug for as long as needed to identify the root cause and identify a fix
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
- To test hypotheses, you can also add test statements or functions
- Revisit your assumptions if unexpected behavior occurs.
</structuredWorkflow>
<communicationGuidelines>
Always communicate clearly and concisely in a warm and friendly yet professional tone. Use upbeat language and sprinkle in light, witty humor where appropriate.
If the user corrects you, do not immediately assume they are right. Think deeply about their feedback and how you can incorporate it into your solution. Stand your ground if you have the evidence to support your conclusion.
</communicationGuidelines>
<codeSearchInstructions>
These instructions only apply when the question is about the user's workspace.
First, analyze the developer's request to determine how complicated their task is. Leverage any of the tools available to you to gather the context needed to provided a complete and accurate response. Keep your search focused on the developer's request, and don't run extra tools if the developer's request clearly can be satisfied by just one.
If the developer wants to implement a feature and they have not specified the relevant files, first break down the developer's request into smaller concepts and think about the kinds of files you need to grasp each concept.
If you aren't sure which tool is relevant, you can call multiple tools. You can call tools repeatedly to take actions or gather as much context as needed.
Don't make assumptions about the situation. Gather enough context to address the developer's request without going overboard.
Think step by step:
1. Read the provided relevant workspace information (code excerpts, file names, and symbols) to understand the user's workspace.
2. Consider how to answer the user's prompt based on the provided information and your specialized coding knowledge. Always assume that the user is asking about the code in their workspace instead of asking a general programming question. Prefer using variables, functions, types, and classes from the workspace over those from the standard library.
3. Generate a response that clearly and accurately answers the user's question. In your response, add fully qualified links for referenced symbols (example: [`namespace.VariableName`](path/to/file.ts)) and links for files (example: [path/to/file](path/to/file.ts)) so that the user can open them.
Remember that you MUST add links for all referenced symbols from the workspace and fully qualify the symbol name in the link, for example: [`namespace.functionName`](path/to/util.ts).
Remember that you MUST add links for all workspace files, for example: [path/to/file.js](path/to/file.js)
</codeSearchInstructions>
<codeSearchToolUseInstructions>
These instructions only apply when the question is about the user's workspace.
Unless it is clear that the user's question relates to the current workspace, you should avoid using the code search tools and instead prefer to answer the user's question directly.
Remember that you can call multiple tools in one response.
Use semantic_search to search for high level concepts or descriptions of functionality in the user's question. This is the best place to start if you don't know where to look or the exact strings found in the codebase.
Prefer search_workspace_symbols over grep_search when you have precise code identifiers to search for.
Prefer grep_search over semantic_search when you have precise keywords to search for.
The tools file_search, grep_search, and get_changed_files are deterministic and comprehensive, so do not repeatedly invoke them with the same arguments.
</codeSearchToolUseInstructions>
When suggesting code changes or new content, use Markdown code blocks.
To start a code block, use 4 backticks.
After the backticks, add the programming language name.
If the code modifies an existing file or should be placed at a specific location, add a line comment with 'filepath:' and the file path.
If you want the user to decide where to place the code, do not add the file path comment.
In the code block, use a line comment with '...existing code...' to indicate code that is already present in the file.
````languageId
// filepath: /path/to/file
// ...existing code...
{ changed code }
// ...existing code...
{ changed code }
// ...existing code...
````
<toolUseInstructions>
If the user is requesting a code sample, you can answer it directly without using any tools.
When using a tool, follow the JSON schema very carefully and make sure to include ALL required properties.
No need to ask permission before using a tool.
NEVER say the name of a tool to a user. For example, instead of saying that you'll use the run_in_terminal tool, say "I'll run the command in a terminal".
If you think running multiple tools can answer the user's question, prefer calling them in parallel whenever possible, but do not call semantic_search in parallel.
If semantic_search returns the full contents of the text files in the workspace, you have all the workspace context.
You can use the grep_search to get an overview of a file by searching for a string within that one file, instead of using read_file many times.
If you don't know exactly the string or filename pattern you're looking for, use semantic_search to do a semantic search across the workspace.
When invoking a tool that takes a file path, always use the absolute file path.
Tools can be disabled by the user. You may see tools used previously in the conversation that are not currently available. Be careful to only use the tools that are currently available to you.
</toolUseInstructions>
<outputFormatting>
Use proper Markdown formatting in your answers. When referring to a filename or symbol in the user's workspace, wrap it in backticks.
When sharing setup or run steps for the user to execute, render commands in fenced code blocks with an appropriate language tag (`bash`, `sh`, `powershell`, `python`, etc.). Keep one command per line; avoid prose-only representations of commands.
Keep responses conversational and fun—use a brief, friendly preamble that acknowledges the goal and states what you're about to do next. Avoid literal scaffold labels like "Plan:", "Task receipt:", or "Actions:"; instead, use short paragraphs and, when helpful, concise bullet lists. Do not start with filler acknowledgements (e.g., "Sounds good", "Great", "Okay, I will…"). For multi-step tasks, maintain a lightweight checklist implicitly and weave progress into your narration.
For section headers in your response, use level-2 Markdown headings (`##`) for top-level sections and level-3 (`###`) for subsections. Choose titles dynamically to match the task and content. Do not hard-code fixed section names; create only the sections that make sense and only when they have non-empty content. Keep headings short and descriptive (e.g., "actions taken", "files changed", "how to run", "performance", "notes"), and order them naturally (actions > artifacts > how to run > performance > notes) when applicable. You may add a tasteful emoji to a heading when it improves scannability; keep it minimal and professional. Headings must start at the beginning of the line with `## ` or `### `, have a blank line before and after, and must not be inside lists, block quotes, or code fences.
When listing files created/edited, include a one-line purpose for each file when helpful. In performance sections, base any metrics on actual runs from this session; note the hardware/OS context and mark estimates clearly—never fabricate numbers. In "Try it" sections, keep commands copyable; comments starting with `#` are okay, but put each command on its own line.
If platform-specific acceleration applies, include an optional speed-up fenced block with commands. Close with a concise completion summary describing what changed and how it was verified (build/tests/linters), plus any follow-ups.
<example>
The class `Person` is in `src/models/person.ts`.
</example>
Use KaTeX for math equations in your answers.
Wrap inline math equations in $.
Wrap more complex blocks of math equations in $$.
</outputFormatting>
+10 -35
View File
@@ -13,7 +13,7 @@ import PROMPT_GEMINI from "./prompt/gemini.txt"
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
import PROMPT_TITLE from "./prompt/title.txt"
import PROMPT_COPILOT_GPT_5 from "./prompt/copilot-gpt-5.txt"
import PROMPT_CODEX from "./prompt/codex.txt"
export namespace SystemPrompt {
export function header(providerID: string) {
@@ -22,7 +22,7 @@ export namespace SystemPrompt {
}
export function provider(modelID: string) {
if (modelID.includes("gpt-5")) return [PROMPT_COPILOT_GPT_5]
if (modelID.includes("gpt-5")) return [PROMPT_CODEX]
if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
if (modelID.includes("claude")) return [PROMPT_ANTHROPIC]
@@ -54,53 +54,28 @@ export namespace SystemPrompt {
]
}
const LOCAL_RULE_FILES = [
const CUSTOM_FILES = [
"AGENTS.md",
"CLAUDE.md",
"CONTEXT.md", // deprecated
]
const GLOBAL_RULE_FILES = [
path.join(Global.Path.config, "AGENTS.md"),
path.join(os.homedir(), ".claude", "CLAUDE.md"),
]
export async function custom() {
const { cwd, root } = App.info().path
const config = await Config.get()
const paths = new Set<string>()
for (const localRuleFile of LOCAL_RULE_FILES) {
const matches = await Filesystem.findUp(localRuleFile, cwd, root)
if (matches.length > 0) {
matches.forEach((path) => paths.add(path))
break
}
for (const item of CUSTOM_FILES) {
const matches = await Filesystem.findUp(item, cwd, root)
matches.forEach((path) => paths.add(path))
}
for (const globalRuleFile of GLOBAL_RULE_FILES) {
if (await Bun.file(globalRuleFile).exists()) {
paths.add(globalRuleFile)
break
}
}
paths.add(path.join(Global.Path.config, "AGENTS.md"))
paths.add(path.join(os.homedir(), ".claude", "CLAUDE.md"))
if (config.instructions) {
for (let instruction of config.instructions) {
if (instruction.startsWith("~/")) {
instruction = path.join(os.homedir(), instruction.slice(2))
}
let matches: string[] = []
if (path.isAbsolute(instruction)) {
matches = await Array.fromAsync(
new Bun.Glob(path.basename(instruction)).scan({
cwd: path.dirname(instruction),
absolute: true,
onlyFiles: true,
}),
).catch(() => [])
} else {
matches = await Filesystem.globUp(instruction, cwd, root).catch(() => [])
}
for (const instruction of config.instructions) {
const matches = await Filesystem.globUp(instruction, cwd, root).catch(() => [])
matches.forEach((path) => paths.add(path))
}
}
+1 -2
View File
@@ -43,7 +43,6 @@ export namespace Snapshot {
}
await $`git --git-dir ${git} add .`.quiet().cwd(app.path.cwd).nothrow()
const hash = await $`git --git-dir ${git} write-tree`.quiet().cwd(app.path.cwd).nothrow().text()
log.info("tracking", { hash, cwd: app.path.cwd, git })
return hash.trim()
}
@@ -65,7 +64,7 @@ export namespace Snapshot {
.split("\n")
.map((x) => x.trim())
.filter(Boolean)
.map((x) => path.join(app.path.root, x)),
.map((x) => path.join(app.path.cwd, x)),
}
}
+30 -33
View File
@@ -5,42 +5,25 @@ import { Tool } from "./tool"
import DESCRIPTION from "./bash.txt"
import { App } from "../app/app"
import { Permission } from "../permission"
import { Config } from "../config/config"
import { Filesystem } from "../util/filesystem"
import { lazy } from "../util/lazy"
import { Log } from "../util/log"
import { Wildcard } from "../util/wildcard"
import { $ } from "bun"
import { Agent } from "../agent/agent"
const MAX_OUTPUT_LENGTH = 30_000
const MAX_OUTPUT_LENGTH = 30000
const DEFAULT_TIMEOUT = 1 * 60 * 1000
const MAX_TIMEOUT = 10 * 60 * 1000
const log = Log.create({ service: "bash-tool" })
const parser = lazy(async () => {
try {
const { default: Parser } = await import("tree-sitter")
const Bash = await import("tree-sitter-bash")
const p = new Parser()
p.setLanguage(Bash.language as any)
return p
} catch (e) {
const { default: Parser } = await import("web-tree-sitter")
const { default: treeWasm } = await import("web-tree-sitter/tree-sitter.wasm" as string, { with: { type: "wasm" } })
await Parser.init({
locateFile() {
return treeWasm
},
})
const { default: bashWasm } = await import("tree-sitter-bash/tree-sitter-bash.wasm" as string, {
with: { type: "wasm" },
})
const bashLanguage = await Parser.Language.load(bashWasm)
const p = new Parser()
p.setLanguage(bashLanguage)
return p
}
const { default: Parser } = await import("tree-sitter")
const Bash = await import("tree-sitter-bash")
const p = new Parser()
p.setLanguage(Bash.language as any)
return p
})
export const BashTool = Tool.define("bash", {
@@ -57,8 +40,20 @@ export const BashTool = Tool.define("bash", {
async execute(params, ctx) {
const timeout = Math.min(params.timeout ?? DEFAULT_TIMEOUT, MAX_TIMEOUT)
const app = App.info()
const cfg = await Config.get()
const tree = await parser().then((p) => p.parse(params.command))
const permissions = await Agent.get(ctx.agent).then((x) => x.permission.bash)
const permissions = (() => {
const value = cfg.permission?.bash
if (!value)
return {
"*": "allow",
}
if (typeof value === "string")
return {
"*": value,
}
return value
})()
let needsAsk = false
for (const node of tree.rootNode.descendantsOfType("command")) {
@@ -98,10 +93,17 @@ export const BashTool = Tool.define("bash", {
// always allow cd if it passes above check
if (!needsAsk && command[0] !== "cd") {
const action = Wildcard.all(node.text, permissions)
const action = (() => {
for (const [pattern, value] of Object.entries(permissions)) {
const match = Wildcard.match(node.text, pattern)
log.info("checking", { text: node.text.trim(), pattern, match })
if (match) return value
}
return "ask"
})()
if (action === "deny") {
throw new Error(
`The user has specifically restricted access to this command, you are not allowed to execute it. Here is the configuration: ${JSON.stringify(permissions)}`,
"The user has specifically restricted access to this command, you are not allowed to execute it.",
)
}
if (action === "ask") needsAsk = true
@@ -111,7 +113,6 @@ export const BashTool = Tool.define("bash", {
if (needsAsk) {
await Permission.ask({
type: "bash",
pattern: params.command,
sessionID: ctx.sessionID,
messageID: ctx.messageID,
callID: ctx.callID,
@@ -125,6 +126,7 @@ export const BashTool = Tool.define("bash", {
const process = exec(params.command, {
cwd: app.path.cwd,
signal: ctx.abort,
maxBuffer: MAX_OUTPUT_LENGTH,
timeout,
})
@@ -172,11 +174,6 @@ export const BashTool = Tool.define("bash", {
},
})
if (output.length > MAX_OUTPUT_LENGTH) {
output = output.slice(0, MAX_OUTPUT_LENGTH)
output += "\n\n(Output was truncated due to length limit)"
}
return {
title: params.command,
metadata: {
+23
View File
@@ -59,6 +59,10 @@ When the user asks you to create a new git commit, follow these steps carefully:
3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
- Add relevant untracked files to the staging area.
- Create the commit with a message ending with:
🤖 Generated with [opencode](https://opencode.ai)
Co-Authored-By: opencode <noreply@opencode.ai>
- Run git status to make sure the commit succeeded.
4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
@@ -72,6 +76,17 @@ Important notes:
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
- Return an empty response - the user will see the git output directly
- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
<example>
git commit -m "$(cat <<'EOF'
Commit message here.
🤖 Generated with [opencode](https://opencode.ai)
Co-Authored-By: opencode <noreply@opencode.ai>
EOF
)"
</example>
# Creating pull requests
Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
@@ -110,6 +125,14 @@ gh pr create --title "the pr title" --body "$(cat <<'EOF'
## Summary
<1-3 bullet points>
## Test plan
[Checklist of TODOs for testing the pull request...]
🤖 Generated with [opencode](https://opencode.ai)
EOF
)"
</example>
Important:
- NEVER update the git config
- Return the PR URL when you're done, so the user can see it
+5 -9
View File
@@ -14,8 +14,8 @@ import { App } from "../app/app"
import { File } from "../file"
import { Bus } from "../bus"
import { FileTime } from "../file/time"
import { Config } from "../config/config"
import { Filesystem } from "../util/filesystem"
import { Agent } from "../agent/agent"
export const EditTool = Tool.define("edit", {
description: DESCRIPTION,
@@ -40,7 +40,7 @@ export const EditTool = Tool.define("edit", {
throw new Error(`File ${filePath} is not in the current working directory`)
}
const agent = await Agent.get(ctx.agent)
const cfg = await Config.get()
let diff = ""
let contentOld = ""
let contentNew = ""
@@ -48,7 +48,7 @@ export const EditTool = Tool.define("edit", {
if (params.oldString === "") {
contentNew = params.newString
diff = trimDiff(createTwoFilesPatch(filePath, filePath, contentOld, contentNew))
if (agent.permission.edit === "ask") {
if (cfg.permission?.edit === "ask") {
await Permission.ask({
type: "edit",
sessionID: ctx.sessionID,
@@ -77,13 +77,12 @@ export const EditTool = Tool.define("edit", {
contentNew = replace(contentOld, params.oldString, params.newString, params.replaceAll)
diff = trimDiff(createTwoFilesPatch(filePath, filePath, contentOld, contentNew))
if (agent.permission.edit === "ask") {
if (cfg.permission?.edit === "ask") {
await Permission.ask({
type: "edit",
sessionID: ctx.sessionID,
messageID: ctx.messageID,
callID: ctx.callID,
pattern: filePath,
title: "Edit this file: " + filePath,
metadata: {
filePath,
@@ -189,10 +188,7 @@ export const LineTrimmedReplacer: Replacer = function* (content, find) {
let matchEndIndex = matchStartIndex
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length
if (k < searchLines.length - 1) {
matchEndIndex += 1 // Add newline character except for the last line
}
matchEndIndex += originalLines[i + k].length + 1
}
yield content.substring(matchStartIndex, matchEndIndex)
+3 -1
View File
@@ -24,7 +24,7 @@ export const ReadTool = Tool.define("read", {
filepath = path.join(process.cwd(), filepath)
}
const app = App.info()
if (!ctx.extra?.["bypassCwdCheck"] && !Filesystem.contains(app.path.cwd, filepath)) {
if (!Filesystem.contains(app.path.cwd, filepath)) {
throw new Error(`File ${filepath} is not in the current working directory`)
}
@@ -98,6 +98,8 @@ function isImageFile(filePath: string): string | false {
return "GIF"
case ".bmp":
return "BMP"
case ".svg":
return "SVG"
case ".webp":
return "WebP"
default:
+2 -1
View File
@@ -7,6 +7,7 @@ Usage:
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
- Any lines longer than 2000 characters will be truncated
- Results are returned using cat -n format, with line numbers starting at 1
- This tool cannot read binary files, including images
- This tool allows opencode to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as opencode is a multimodal LLM.
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.
+6 -14
View File
@@ -11,7 +11,7 @@ import { TodoWriteTool, TodoReadTool } from "./todo"
import { WebFetchTool } from "./webfetch"
import { WriteTool } from "./write"
import { InvalidTool } from "./invalid"
import type { Agent } from "../agent/agent"
import { Config } from "../config/config"
export namespace ToolRegistry {
const ALL = [
@@ -66,31 +66,23 @@ export namespace ToolRegistry {
return result
}
export async function enabled(
_providerID: string,
modelID: string,
agent: Agent.Info,
): Promise<Record<string, boolean>> {
export async function enabled(_providerID: string, _modelID: string): Promise<Record<string, boolean>> {
const cfg = await Config.get()
const result: Record<string, boolean> = {}
result["patch"] = false
if (agent.permission.edit === "deny") {
if (cfg.permission?.edit === "deny") {
result["edit"] = false
result["patch"] = false
result["write"] = false
}
if (agent.permission.bash["*"] === "deny" && Object.keys(agent.permission.bash).length === 1) {
if (cfg?.permission?.bash === "deny") {
result["bash"] = false
}
if (agent.permission.webfetch === "deny") {
if (cfg?.permission?.webfetch === "deny") {
result["webfetch"] = false
}
if (modelID.includes("qwen")) {
result["todowrite"] = false
result["todoread"] = false
}
return result
}
+3 -3
View File
@@ -23,11 +23,11 @@ export const TaskTool = Tool.define("task", async () => {
subagent_type: z.string().describe("The type of specialized agent to use for this task"),
}),
async execute(params, ctx) {
const agent = await Agent.get(params.subagent_type)
if (!agent) throw new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`)
const session = await Session.create(ctx.sessionID, params.description + ` (@${agent.name} subagent)`)
const session = await Session.create(ctx.sessionID)
const msg = await Session.getMessage(ctx.sessionID, ctx.messageID)
if (msg.info.role !== "assistant") throw new Error("Not an assistant message")
const agent = await Agent.get(params.subagent_type)
if (!agent) throw new Error(`Unknown agent type: ${params.subagent_type} is not a valid agent type`)
const messageID = Identifier.ascending("message")
const parts: Record<string, MessageV2.ToolPart> = {}
const unsub = Bus.subscribe(MessageV2.Event.PartUpdated, async (evt) => {
+3 -3
View File
@@ -1,4 +1,4 @@
Launch a new agent to handle complex, multi-step tasks autonomously.
Launch a new agent to handle complex, multi-step tasks autonomously.
Available agent types and the tools they have access to:
{agents}
@@ -23,7 +23,7 @@ Usage notes:
5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
Example usage (NOTE: The agents below are fictional examples for illustration only - use the actual agents listed above):
Example usage:
<example_agent_descriptions>
"code-reviewer": use this agent after you are done writing a signficant piece of code
@@ -48,7 +48,7 @@ function isPrime(n) {
Since a signficant piece of code was written and the task was completed, now use the code-reviewer agent to review the code
</commentary>
assistant: Now let me use the code-reviewer agent to review the code
assistant: Uses the Task tool to launch the code-reviewer agent
assistant: Uses the Task tool to launch the with the code-reviewer agent
</example>
<example>
+26 -43
View File
@@ -1,70 +1,53 @@
const parser = async () => {
try {
const { default: Parser } = await import("tree-sitter")
const Bash = await import("tree-sitter-bash")
const p = new Parser()
p.setLanguage(Bash.language as any)
return p
} catch (e) {
const { default: Parser } = await import("web-tree-sitter")
const { default: treeWasm } = await import("web-tree-sitter/tree-sitter.wasm" as string, { with: { type: "wasm" } })
await Parser.init({
locateFile() {
return treeWasm
},
})
const { default: bashWasm } = await import("tree-sitter-bash/tree-sitter-bash.wasm" as string, {
with: { type: "wasm" },
})
const bashLanguage = await Parser.Language.load(bashWasm)
const p = new Parser()
p.setLanguage(bashLanguage)
return p
}
}
import Parser from "tree-sitter";
import Bash from "tree-sitter-bash";
const sourceCode = `cd --foo foo/bar && echo "hello" && cd ../baz`
const parser = new Parser();
parser.setLanguage(Bash.language as any);
const tree = await parser().then((p) => p.parse(sourceCode))
const sourceCode = `cd --foo foo/bar && echo "hello" && cd ../baz`;
const tree = parser.parse(sourceCode);
// Function to extract commands and arguments
function extractCommands(node: any): Array<{ command: string; args: string[] }> {
const commands: Array<{ command: string; args: string[] }> = []
function extractCommands(
node: any,
): Array<{ command: string; args: string[] }> {
const commands: Array<{ command: string; args: string[] }> = [];
function traverse(node: any) {
if (node.type === "command") {
const commandNode = node.child(0)
const commandNode = node.child(0);
if (commandNode) {
const command = commandNode.text
const args: string[] = []
const command = commandNode.text;
const args: string[] = [];
// Extract arguments
for (let i = 1; i < node.childCount; i++) {
const child = node.child(i)
const child = node.child(i);
if (child && child.type === "word") {
args.push(child.text)
args.push(child.text);
}
}
commands.push({ command, args })
commands.push({ command, args });
}
}
// Traverse children
for (let i = 0; i < node.childCount; i++) {
traverse(node.child(i))
traverse(node.child(i));
}
}
traverse(node)
return commands
traverse(node);
return commands;
}
// Extract and display commands
console.log("Source code: " + sourceCode)
const commands = extractCommands(tree.rootNode)
console.log("Extracted commands:")
console.log("Source code: " + sourceCode);
const commands = extractCommands(tree.rootNode);
console.log("Extracted commands:");
commands.forEach((cmd, index) => {
console.log(`${index + 1}. Command: ${cmd.command}`)
console.log(` Args: [${cmd.args.join(", ")}]`)
})
console.log(`${index + 1}. Command: ${cmd.command}`);
console.log(` Args: [${cmd.args.join(", ")}]`);
});
-2
View File
@@ -7,10 +7,8 @@ export namespace Tool {
export type Context<M extends Metadata = Metadata> = {
sessionID: string
messageID: string
agent: string
callID?: string
abort: AbortSignal
extra?: { [key: string]: any }
metadata(input: { title?: string; metadata?: M }): void
}
export interface Info<Parameters extends StandardSchemaV1 = StandardSchemaV1, M extends Metadata = Metadata> {
-1
View File
@@ -28,7 +28,6 @@ export const WebFetchTool = Tool.define("webfetch", {
if (cfg.permission?.webfetch === "ask")
await Permission.ask({
type: "webfetch",
pattern: params.url,
sessionID: ctx.sessionID,
messageID: ctx.messageID,
callID: ctx.callID,
+3 -3
View File
@@ -8,8 +8,8 @@ import { App } from "../app/app"
import { Bus } from "../bus"
import { File } from "../file"
import { FileTime } from "../file/time"
import { Config } from "../config/config"
import { Filesystem } from "../util/filesystem"
import { Agent } from "../agent/agent"
export const WriteTool = Tool.define("write", {
description: DESCRIPTION,
@@ -28,8 +28,8 @@ export const WriteTool = Tool.define("write", {
const exists = await file.exists()
if (exists) await FileTime.assert(ctx.sessionID, filepath)
const agent = await Agent.get(ctx.agent)
if (agent.permission.edit === "ask")
const cfg = await Config.get()
if (cfg.permission?.edit === "ask")
await Permission.ask({
type: "write",
sessionID: ctx.sessionID,
-12
View File
@@ -1,12 +0,0 @@
export function defer<T extends () => void | Promise<void>>(
fn: T,
): T extends () => Promise<void> ? { [Symbol.asyncDispose]: () => Promise<void> } : { [Symbol.dispose]: () => void } {
return {
[Symbol.dispose]() {
fn()
},
[Symbol.asyncDispose]() {
return Promise.resolve(fn())
},
} as any
}
-14
View File
@@ -1,5 +1,3 @@
import { sortBy, pipe } from "remeda"
export namespace Wildcard {
export function match(str: string, pattern: string) {
const regex = new RegExp(
@@ -13,16 +11,4 @@ export namespace Wildcard {
)
return regex.test(str)
}
export function all(input: string, patterns: Record<string, any>) {
const sorted = pipe(patterns, Object.entries, sortBy([([key]) => key.length, "asc"], [([key]) => key, "asc"]))
let result = undefined
for (const [pattern, value] of sorted) {
if (match(input, pattern)) {
result = value
continue
}
}
return result
}
}
+1 -2
View File
@@ -8,7 +8,6 @@ const ctx = {
sessionID: "test",
messageID: "",
toolCallID: "",
agent: "build",
abort: AbortSignal.any([]),
metadata: () => {},
}
@@ -34,7 +33,7 @@ describe("tool.bash", () => {
test("cd ../ should fail outside of project root", async () => {
await App.provide({ cwd: projectRoot }, async () => {
expect(
await expect(
bash.execute(
{
command: "cd ../",
-1
View File
@@ -8,7 +8,6 @@ const ctx = {
sessionID: "test",
messageID: "",
toolCallID: "",
agent: "build",
abort: AbortSignal.any([]),
metadata: () => {},
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/plugin",
"version": "0.5.2",
"version": "0.4.13",
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit"
+1 -54
View File
@@ -1,14 +1,4 @@
import type {
Event,
createOpencodeClient,
App,
Model,
Provider,
Permission,
UserMessage,
Part,
Auth,
} from "@opencode-ai/sdk"
import type { Event, createOpencodeClient, App, Model, Provider, Permission, UserMessage, Part } from "@opencode-ai/sdk"
import type { BunShell } from "./shell"
export type PluginInput = {
@@ -20,49 +10,6 @@ export type Plugin = (input: PluginInput) => Promise<Hooks>
export interface Hooks {
event?: (input: { event: Event }) => Promise<void>
auth?: {
provider: string
loader?: (auth: () => Promise<Auth>, provider: Provider) => Promise<Record<string, any>>
methods: (
| {
type: "oauth"
label: string
authorize(): Promise<
{ url: string; instructions: string } & (
| {
method: "auto"
callback(): Promise<
| {
type: "success"
refresh: string
access: string
expires: number
}
| {
type: "failed"
}
>
}
| {
method: "code"
callback(code: string): Promise<
| {
type: "success"
refresh: string
access: string
expires: number
}
| {
type: "failed"
}
>
}
)
>
}
| { type: "api"; label: string }
)[]
}
/**
* Called when a new message is received
*/
+4 -4
View File
@@ -1,4 +1,4 @@
configured_endpoints: 39
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-b751e5c3cd3ab7fc61b18fbbfd6092b7264ea2ee305858aa538b884e7c492090.yml
openapi_spec_hash: a61f8b1d9b834cf321f0cb7805cc8522
config_hash: eab3723c4c2232a6ba1821151259d6da
configured_endpoints: 34
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-b86cf7bb8df4f60ebe8b8f51e281c8076cfdccc8554178c1b78beca4b025f0ff.yml
openapi_spec_hash: 47633b7481d91708643ea7b43fffffe6
config_hash: bd7f6435ed0c0005f373b5526c07a055
-5
View File
@@ -111,19 +111,15 @@ Response Types:
Methods:
- <code title="post /session">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.New">New</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="patch /session/{id}">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Update">Update</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionUpdateParams">SessionUpdateParams</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /session">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.List">List</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="delete /session/{id}">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Delete">Delete</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/abort">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Abort">Abort</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/message">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Chat">Chat</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionChatParams">SessionChatParams</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AssistantMessage">AssistantMessage</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /session/{id}/children">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Children">Children</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /session/{id}">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/init">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Init">Init</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionInitParams">SessionInitParams</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /session/{id}/message/{messageID}">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Message">Message</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, messageID <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionMessageResponse">SessionMessageResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /session/{id}/message">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Messages">Messages</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionMessagesResponse">SessionMessagesResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/revert">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Revert">Revert</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionRevertParams">SessionRevertParams</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/share">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Share">Share</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/shell">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Shell">Shell</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionShellParams">SessionShellParams</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AssistantMessage">AssistantMessage</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/summarize">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Summarize">Summarize</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionSummarizeParams">SessionSummarizeParams</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /session/{id}/unrevert">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Unrevert">Unrevert</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="delete /session/{id}/share">client.Session.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SessionService.Unshare">Unshare</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, id <a href="https://pkg.go.dev/builtin#string">string</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
@@ -149,5 +145,4 @@ Methods:
- <code title="post /tui/open-models">client.Tui.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TuiService.OpenModels">OpenModels</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /tui/open-sessions">client.Tui.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TuiService.OpenSessions">OpenSessions</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /tui/open-themes">client.Tui.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TuiService.OpenThemes">OpenThemes</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /tui/show-toast">client.Tui.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TuiService.ShowToast">ShowToast</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TuiShowToastParams">TuiShowToastParams</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /tui/submit-prompt">client.Tui.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TuiService.SubmitPrompt">SubmitPrompt</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
+9 -87
View File
@@ -72,27 +72,21 @@ func (r *AppService) Providers(ctx context.Context, opts ...option.RequestOption
}
type Agent struct {
BuiltIn bool `json:"builtIn,required"`
Mode AgentMode `json:"mode,required"`
Name string `json:"name,required"`
Options map[string]interface{} `json:"options,required"`
Permission AgentPermission `json:"permission,required"`
Tools map[string]bool `json:"tools,required"`
Description string `json:"description"`
Model AgentModel `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
TopP float64 `json:"topP"`
JSON agentJSON `json:"-"`
Mode AgentMode `json:"mode,required"`
Name string `json:"name,required"`
Tools map[string]bool `json:"tools,required"`
Description string `json:"description"`
Model AgentModel `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
TopP float64 `json:"topP"`
JSON agentJSON `json:"-"`
}
// agentJSON contains the JSON metadata for the struct [Agent]
type agentJSON struct {
BuiltIn apijson.Field
Mode apijson.Field
Name apijson.Field
Options apijson.Field
Permission apijson.Field
Tools apijson.Field
Description apijson.Field
Model apijson.Field
@@ -127,78 +121,6 @@ func (r AgentMode) IsKnown() bool {
return false
}
type AgentPermission struct {
Bash map[string]AgentPermissionBash `json:"bash,required"`
Edit AgentPermissionEdit `json:"edit,required"`
Webfetch AgentPermissionWebfetch `json:"webfetch"`
JSON agentPermissionJSON `json:"-"`
}
// agentPermissionJSON contains the JSON metadata for the struct [AgentPermission]
type agentPermissionJSON struct {
Bash apijson.Field
Edit apijson.Field
Webfetch apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *AgentPermission) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r agentPermissionJSON) RawJSON() string {
return r.raw
}
type AgentPermissionBash string
const (
AgentPermissionBashAsk AgentPermissionBash = "ask"
AgentPermissionBashAllow AgentPermissionBash = "allow"
AgentPermissionBashDeny AgentPermissionBash = "deny"
)
func (r AgentPermissionBash) IsKnown() bool {
switch r {
case AgentPermissionBashAsk, AgentPermissionBashAllow, AgentPermissionBashDeny:
return true
}
return false
}
type AgentPermissionEdit string
const (
AgentPermissionEditAsk AgentPermissionEdit = "ask"
AgentPermissionEditAllow AgentPermissionEdit = "allow"
AgentPermissionEditDeny AgentPermissionEdit = "deny"
)
func (r AgentPermissionEdit) IsKnown() bool {
switch r {
case AgentPermissionEditAsk, AgentPermissionEditAllow, AgentPermissionEditDeny:
return true
}
return false
}
type AgentPermissionWebfetch string
const (
AgentPermissionWebfetchAsk AgentPermissionWebfetch = "ask"
AgentPermissionWebfetchAllow AgentPermissionWebfetch = "allow"
AgentPermissionWebfetchDeny AgentPermissionWebfetch = "deny"
)
func (r AgentPermissionWebfetch) IsKnown() bool {
switch r {
case AgentPermissionWebfetchAsk, AgentPermissionWebfetchAllow, AgentPermissionWebfetchDeny:
return true
}
return false
}
type AgentModel struct {
ModelID string `json:"modelID,required"`
ProviderID string `json:"providerID,required"`
+100 -713
View File
@@ -149,17 +149,15 @@ func (r configAgentJSON) RawJSON() string {
type ConfigAgentBuild struct {
// Description of when to use the agent
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigAgentBuildMode `json:"mode"`
Model string `json:"model"`
Permission ConfigAgentBuildPermission `json:"permission"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
ExtraFields map[string]interface{} `json:"-,extras"`
JSON configAgentBuildJSON `json:"-"`
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigAgentBuildMode `json:"mode"`
Model string `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
JSON configAgentBuildJSON `json:"-"`
}
// configAgentBuildJSON contains the JSON metadata for the struct
@@ -169,7 +167,6 @@ type configAgentBuildJSON struct {
Disable apijson.Field
Mode apijson.Field
Model apijson.Field
Permission apijson.Field
Prompt apijson.Field
Temperature apijson.Field
Tools apijson.Field
@@ -202,135 +199,17 @@ func (r ConfigAgentBuildMode) IsKnown() bool {
return false
}
type ConfigAgentBuildPermission struct {
Bash ConfigAgentBuildPermissionBashUnion `json:"bash"`
Edit ConfigAgentBuildPermissionEdit `json:"edit"`
Webfetch ConfigAgentBuildPermissionWebfetch `json:"webfetch"`
JSON configAgentBuildPermissionJSON `json:"-"`
}
// configAgentBuildPermissionJSON contains the JSON metadata for the struct
// [ConfigAgentBuildPermission]
type configAgentBuildPermissionJSON struct {
Bash apijson.Field
Edit apijson.Field
Webfetch apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigAgentBuildPermission) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configAgentBuildPermissionJSON) RawJSON() string {
return r.raw
}
// Union satisfied by [ConfigAgentBuildPermissionBashString] or
// [ConfigAgentBuildPermissionBashMap].
type ConfigAgentBuildPermissionBashUnion interface {
implementsConfigAgentBuildPermissionBashUnion()
}
func init() {
apijson.RegisterUnion(
reflect.TypeOf((*ConfigAgentBuildPermissionBashUnion)(nil)).Elem(),
"",
apijson.UnionVariant{
TypeFilter: gjson.String,
Type: reflect.TypeOf(ConfigAgentBuildPermissionBashString("")),
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(ConfigAgentBuildPermissionBashMap{}),
},
)
}
type ConfigAgentBuildPermissionBashString string
const (
ConfigAgentBuildPermissionBashStringAsk ConfigAgentBuildPermissionBashString = "ask"
ConfigAgentBuildPermissionBashStringAllow ConfigAgentBuildPermissionBashString = "allow"
ConfigAgentBuildPermissionBashStringDeny ConfigAgentBuildPermissionBashString = "deny"
)
func (r ConfigAgentBuildPermissionBashString) IsKnown() bool {
switch r {
case ConfigAgentBuildPermissionBashStringAsk, ConfigAgentBuildPermissionBashStringAllow, ConfigAgentBuildPermissionBashStringDeny:
return true
}
return false
}
func (r ConfigAgentBuildPermissionBashString) implementsConfigAgentBuildPermissionBashUnion() {}
type ConfigAgentBuildPermissionBashMap map[string]ConfigAgentBuildPermissionBashMapItem
func (r ConfigAgentBuildPermissionBashMap) implementsConfigAgentBuildPermissionBashUnion() {}
type ConfigAgentBuildPermissionBashMapItem string
const (
ConfigAgentBuildPermissionBashMapAsk ConfigAgentBuildPermissionBashMapItem = "ask"
ConfigAgentBuildPermissionBashMapAllow ConfigAgentBuildPermissionBashMapItem = "allow"
ConfigAgentBuildPermissionBashMapDeny ConfigAgentBuildPermissionBashMapItem = "deny"
)
func (r ConfigAgentBuildPermissionBashMapItem) IsKnown() bool {
switch r {
case ConfigAgentBuildPermissionBashMapAsk, ConfigAgentBuildPermissionBashMapAllow, ConfigAgentBuildPermissionBashMapDeny:
return true
}
return false
}
type ConfigAgentBuildPermissionEdit string
const (
ConfigAgentBuildPermissionEditAsk ConfigAgentBuildPermissionEdit = "ask"
ConfigAgentBuildPermissionEditAllow ConfigAgentBuildPermissionEdit = "allow"
ConfigAgentBuildPermissionEditDeny ConfigAgentBuildPermissionEdit = "deny"
)
func (r ConfigAgentBuildPermissionEdit) IsKnown() bool {
switch r {
case ConfigAgentBuildPermissionEditAsk, ConfigAgentBuildPermissionEditAllow, ConfigAgentBuildPermissionEditDeny:
return true
}
return false
}
type ConfigAgentBuildPermissionWebfetch string
const (
ConfigAgentBuildPermissionWebfetchAsk ConfigAgentBuildPermissionWebfetch = "ask"
ConfigAgentBuildPermissionWebfetchAllow ConfigAgentBuildPermissionWebfetch = "allow"
ConfigAgentBuildPermissionWebfetchDeny ConfigAgentBuildPermissionWebfetch = "deny"
)
func (r ConfigAgentBuildPermissionWebfetch) IsKnown() bool {
switch r {
case ConfigAgentBuildPermissionWebfetchAsk, ConfigAgentBuildPermissionWebfetchAllow, ConfigAgentBuildPermissionWebfetchDeny:
return true
}
return false
}
type ConfigAgentGeneral struct {
// Description of when to use the agent
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigAgentGeneralMode `json:"mode"`
Model string `json:"model"`
Permission ConfigAgentGeneralPermission `json:"permission"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
ExtraFields map[string]interface{} `json:"-,extras"`
JSON configAgentGeneralJSON `json:"-"`
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigAgentGeneralMode `json:"mode"`
Model string `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
JSON configAgentGeneralJSON `json:"-"`
}
// configAgentGeneralJSON contains the JSON metadata for the struct
@@ -340,7 +219,6 @@ type configAgentGeneralJSON struct {
Disable apijson.Field
Mode apijson.Field
Model apijson.Field
Permission apijson.Field
Prompt apijson.Field
Temperature apijson.Field
Tools apijson.Field
@@ -373,135 +251,17 @@ func (r ConfigAgentGeneralMode) IsKnown() bool {
return false
}
type ConfigAgentGeneralPermission struct {
Bash ConfigAgentGeneralPermissionBashUnion `json:"bash"`
Edit ConfigAgentGeneralPermissionEdit `json:"edit"`
Webfetch ConfigAgentGeneralPermissionWebfetch `json:"webfetch"`
JSON configAgentGeneralPermissionJSON `json:"-"`
}
// configAgentGeneralPermissionJSON contains the JSON metadata for the struct
// [ConfigAgentGeneralPermission]
type configAgentGeneralPermissionJSON struct {
Bash apijson.Field
Edit apijson.Field
Webfetch apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigAgentGeneralPermission) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configAgentGeneralPermissionJSON) RawJSON() string {
return r.raw
}
// Union satisfied by [ConfigAgentGeneralPermissionBashString] or
// [ConfigAgentGeneralPermissionBashMap].
type ConfigAgentGeneralPermissionBashUnion interface {
implementsConfigAgentGeneralPermissionBashUnion()
}
func init() {
apijson.RegisterUnion(
reflect.TypeOf((*ConfigAgentGeneralPermissionBashUnion)(nil)).Elem(),
"",
apijson.UnionVariant{
TypeFilter: gjson.String,
Type: reflect.TypeOf(ConfigAgentGeneralPermissionBashString("")),
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(ConfigAgentGeneralPermissionBashMap{}),
},
)
}
type ConfigAgentGeneralPermissionBashString string
const (
ConfigAgentGeneralPermissionBashStringAsk ConfigAgentGeneralPermissionBashString = "ask"
ConfigAgentGeneralPermissionBashStringAllow ConfigAgentGeneralPermissionBashString = "allow"
ConfigAgentGeneralPermissionBashStringDeny ConfigAgentGeneralPermissionBashString = "deny"
)
func (r ConfigAgentGeneralPermissionBashString) IsKnown() bool {
switch r {
case ConfigAgentGeneralPermissionBashStringAsk, ConfigAgentGeneralPermissionBashStringAllow, ConfigAgentGeneralPermissionBashStringDeny:
return true
}
return false
}
func (r ConfigAgentGeneralPermissionBashString) implementsConfigAgentGeneralPermissionBashUnion() {}
type ConfigAgentGeneralPermissionBashMap map[string]ConfigAgentGeneralPermissionBashMapItem
func (r ConfigAgentGeneralPermissionBashMap) implementsConfigAgentGeneralPermissionBashUnion() {}
type ConfigAgentGeneralPermissionBashMapItem string
const (
ConfigAgentGeneralPermissionBashMapAsk ConfigAgentGeneralPermissionBashMapItem = "ask"
ConfigAgentGeneralPermissionBashMapAllow ConfigAgentGeneralPermissionBashMapItem = "allow"
ConfigAgentGeneralPermissionBashMapDeny ConfigAgentGeneralPermissionBashMapItem = "deny"
)
func (r ConfigAgentGeneralPermissionBashMapItem) IsKnown() bool {
switch r {
case ConfigAgentGeneralPermissionBashMapAsk, ConfigAgentGeneralPermissionBashMapAllow, ConfigAgentGeneralPermissionBashMapDeny:
return true
}
return false
}
type ConfigAgentGeneralPermissionEdit string
const (
ConfigAgentGeneralPermissionEditAsk ConfigAgentGeneralPermissionEdit = "ask"
ConfigAgentGeneralPermissionEditAllow ConfigAgentGeneralPermissionEdit = "allow"
ConfigAgentGeneralPermissionEditDeny ConfigAgentGeneralPermissionEdit = "deny"
)
func (r ConfigAgentGeneralPermissionEdit) IsKnown() bool {
switch r {
case ConfigAgentGeneralPermissionEditAsk, ConfigAgentGeneralPermissionEditAllow, ConfigAgentGeneralPermissionEditDeny:
return true
}
return false
}
type ConfigAgentGeneralPermissionWebfetch string
const (
ConfigAgentGeneralPermissionWebfetchAsk ConfigAgentGeneralPermissionWebfetch = "ask"
ConfigAgentGeneralPermissionWebfetchAllow ConfigAgentGeneralPermissionWebfetch = "allow"
ConfigAgentGeneralPermissionWebfetchDeny ConfigAgentGeneralPermissionWebfetch = "deny"
)
func (r ConfigAgentGeneralPermissionWebfetch) IsKnown() bool {
switch r {
case ConfigAgentGeneralPermissionWebfetchAsk, ConfigAgentGeneralPermissionWebfetchAllow, ConfigAgentGeneralPermissionWebfetchDeny:
return true
}
return false
}
type ConfigAgentPlan struct {
// Description of when to use the agent
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigAgentPlanMode `json:"mode"`
Model string `json:"model"`
Permission ConfigAgentPlanPermission `json:"permission"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
ExtraFields map[string]interface{} `json:"-,extras"`
JSON configAgentPlanJSON `json:"-"`
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigAgentPlanMode `json:"mode"`
Model string `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
JSON configAgentPlanJSON `json:"-"`
}
// configAgentPlanJSON contains the JSON metadata for the struct [ConfigAgentPlan]
@@ -510,7 +270,6 @@ type configAgentPlanJSON struct {
Disable apijson.Field
Mode apijson.Field
Model apijson.Field
Permission apijson.Field
Prompt apijson.Field
Temperature apijson.Field
Tools apijson.Field
@@ -543,122 +302,6 @@ func (r ConfigAgentPlanMode) IsKnown() bool {
return false
}
type ConfigAgentPlanPermission struct {
Bash ConfigAgentPlanPermissionBashUnion `json:"bash"`
Edit ConfigAgentPlanPermissionEdit `json:"edit"`
Webfetch ConfigAgentPlanPermissionWebfetch `json:"webfetch"`
JSON configAgentPlanPermissionJSON `json:"-"`
}
// configAgentPlanPermissionJSON contains the JSON metadata for the struct
// [ConfigAgentPlanPermission]
type configAgentPlanPermissionJSON struct {
Bash apijson.Field
Edit apijson.Field
Webfetch apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigAgentPlanPermission) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configAgentPlanPermissionJSON) RawJSON() string {
return r.raw
}
// Union satisfied by [ConfigAgentPlanPermissionBashString] or
// [ConfigAgentPlanPermissionBashMap].
type ConfigAgentPlanPermissionBashUnion interface {
implementsConfigAgentPlanPermissionBashUnion()
}
func init() {
apijson.RegisterUnion(
reflect.TypeOf((*ConfigAgentPlanPermissionBashUnion)(nil)).Elem(),
"",
apijson.UnionVariant{
TypeFilter: gjson.String,
Type: reflect.TypeOf(ConfigAgentPlanPermissionBashString("")),
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(ConfigAgentPlanPermissionBashMap{}),
},
)
}
type ConfigAgentPlanPermissionBashString string
const (
ConfigAgentPlanPermissionBashStringAsk ConfigAgentPlanPermissionBashString = "ask"
ConfigAgentPlanPermissionBashStringAllow ConfigAgentPlanPermissionBashString = "allow"
ConfigAgentPlanPermissionBashStringDeny ConfigAgentPlanPermissionBashString = "deny"
)
func (r ConfigAgentPlanPermissionBashString) IsKnown() bool {
switch r {
case ConfigAgentPlanPermissionBashStringAsk, ConfigAgentPlanPermissionBashStringAllow, ConfigAgentPlanPermissionBashStringDeny:
return true
}
return false
}
func (r ConfigAgentPlanPermissionBashString) implementsConfigAgentPlanPermissionBashUnion() {}
type ConfigAgentPlanPermissionBashMap map[string]ConfigAgentPlanPermissionBashMapItem
func (r ConfigAgentPlanPermissionBashMap) implementsConfigAgentPlanPermissionBashUnion() {}
type ConfigAgentPlanPermissionBashMapItem string
const (
ConfigAgentPlanPermissionBashMapAsk ConfigAgentPlanPermissionBashMapItem = "ask"
ConfigAgentPlanPermissionBashMapAllow ConfigAgentPlanPermissionBashMapItem = "allow"
ConfigAgentPlanPermissionBashMapDeny ConfigAgentPlanPermissionBashMapItem = "deny"
)
func (r ConfigAgentPlanPermissionBashMapItem) IsKnown() bool {
switch r {
case ConfigAgentPlanPermissionBashMapAsk, ConfigAgentPlanPermissionBashMapAllow, ConfigAgentPlanPermissionBashMapDeny:
return true
}
return false
}
type ConfigAgentPlanPermissionEdit string
const (
ConfigAgentPlanPermissionEditAsk ConfigAgentPlanPermissionEdit = "ask"
ConfigAgentPlanPermissionEditAllow ConfigAgentPlanPermissionEdit = "allow"
ConfigAgentPlanPermissionEditDeny ConfigAgentPlanPermissionEdit = "deny"
)
func (r ConfigAgentPlanPermissionEdit) IsKnown() bool {
switch r {
case ConfigAgentPlanPermissionEditAsk, ConfigAgentPlanPermissionEditAllow, ConfigAgentPlanPermissionEditDeny:
return true
}
return false
}
type ConfigAgentPlanPermissionWebfetch string
const (
ConfigAgentPlanPermissionWebfetchAsk ConfigAgentPlanPermissionWebfetch = "ask"
ConfigAgentPlanPermissionWebfetchAllow ConfigAgentPlanPermissionWebfetch = "allow"
ConfigAgentPlanPermissionWebfetchDeny ConfigAgentPlanPermissionWebfetch = "deny"
)
func (r ConfigAgentPlanPermissionWebfetch) IsKnown() bool {
switch r {
case ConfigAgentPlanPermissionWebfetchAsk, ConfigAgentPlanPermissionWebfetchAllow, ConfigAgentPlanPermissionWebfetchDeny:
return true
}
return false
}
type ConfigExperimental struct {
Hook ConfigExperimentalHook `json:"hook"`
JSON configExperimentalJSON `json:"-"`
@@ -1038,17 +681,15 @@ func (r configModeJSON) RawJSON() string {
type ConfigModeBuild struct {
// Description of when to use the agent
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigModeBuildMode `json:"mode"`
Model string `json:"model"`
Permission ConfigModeBuildPermission `json:"permission"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
ExtraFields map[string]interface{} `json:"-,extras"`
JSON configModeBuildJSON `json:"-"`
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigModeBuildMode `json:"mode"`
Model string `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
JSON configModeBuildJSON `json:"-"`
}
// configModeBuildJSON contains the JSON metadata for the struct [ConfigModeBuild]
@@ -1057,7 +698,6 @@ type configModeBuildJSON struct {
Disable apijson.Field
Mode apijson.Field
Model apijson.Field
Permission apijson.Field
Prompt apijson.Field
Temperature apijson.Field
Tools apijson.Field
@@ -1090,135 +730,17 @@ func (r ConfigModeBuildMode) IsKnown() bool {
return false
}
type ConfigModeBuildPermission struct {
Bash ConfigModeBuildPermissionBashUnion `json:"bash"`
Edit ConfigModeBuildPermissionEdit `json:"edit"`
Webfetch ConfigModeBuildPermissionWebfetch `json:"webfetch"`
JSON configModeBuildPermissionJSON `json:"-"`
}
// configModeBuildPermissionJSON contains the JSON metadata for the struct
// [ConfigModeBuildPermission]
type configModeBuildPermissionJSON struct {
Bash apijson.Field
Edit apijson.Field
Webfetch apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigModeBuildPermission) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configModeBuildPermissionJSON) RawJSON() string {
return r.raw
}
// Union satisfied by [ConfigModeBuildPermissionBashString] or
// [ConfigModeBuildPermissionBashMap].
type ConfigModeBuildPermissionBashUnion interface {
implementsConfigModeBuildPermissionBashUnion()
}
func init() {
apijson.RegisterUnion(
reflect.TypeOf((*ConfigModeBuildPermissionBashUnion)(nil)).Elem(),
"",
apijson.UnionVariant{
TypeFilter: gjson.String,
Type: reflect.TypeOf(ConfigModeBuildPermissionBashString("")),
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(ConfigModeBuildPermissionBashMap{}),
},
)
}
type ConfigModeBuildPermissionBashString string
const (
ConfigModeBuildPermissionBashStringAsk ConfigModeBuildPermissionBashString = "ask"
ConfigModeBuildPermissionBashStringAllow ConfigModeBuildPermissionBashString = "allow"
ConfigModeBuildPermissionBashStringDeny ConfigModeBuildPermissionBashString = "deny"
)
func (r ConfigModeBuildPermissionBashString) IsKnown() bool {
switch r {
case ConfigModeBuildPermissionBashStringAsk, ConfigModeBuildPermissionBashStringAllow, ConfigModeBuildPermissionBashStringDeny:
return true
}
return false
}
func (r ConfigModeBuildPermissionBashString) implementsConfigModeBuildPermissionBashUnion() {}
type ConfigModeBuildPermissionBashMap map[string]ConfigModeBuildPermissionBashMapItem
func (r ConfigModeBuildPermissionBashMap) implementsConfigModeBuildPermissionBashUnion() {}
type ConfigModeBuildPermissionBashMapItem string
const (
ConfigModeBuildPermissionBashMapAsk ConfigModeBuildPermissionBashMapItem = "ask"
ConfigModeBuildPermissionBashMapAllow ConfigModeBuildPermissionBashMapItem = "allow"
ConfigModeBuildPermissionBashMapDeny ConfigModeBuildPermissionBashMapItem = "deny"
)
func (r ConfigModeBuildPermissionBashMapItem) IsKnown() bool {
switch r {
case ConfigModeBuildPermissionBashMapAsk, ConfigModeBuildPermissionBashMapAllow, ConfigModeBuildPermissionBashMapDeny:
return true
}
return false
}
type ConfigModeBuildPermissionEdit string
const (
ConfigModeBuildPermissionEditAsk ConfigModeBuildPermissionEdit = "ask"
ConfigModeBuildPermissionEditAllow ConfigModeBuildPermissionEdit = "allow"
ConfigModeBuildPermissionEditDeny ConfigModeBuildPermissionEdit = "deny"
)
func (r ConfigModeBuildPermissionEdit) IsKnown() bool {
switch r {
case ConfigModeBuildPermissionEditAsk, ConfigModeBuildPermissionEditAllow, ConfigModeBuildPermissionEditDeny:
return true
}
return false
}
type ConfigModeBuildPermissionWebfetch string
const (
ConfigModeBuildPermissionWebfetchAsk ConfigModeBuildPermissionWebfetch = "ask"
ConfigModeBuildPermissionWebfetchAllow ConfigModeBuildPermissionWebfetch = "allow"
ConfigModeBuildPermissionWebfetchDeny ConfigModeBuildPermissionWebfetch = "deny"
)
func (r ConfigModeBuildPermissionWebfetch) IsKnown() bool {
switch r {
case ConfigModeBuildPermissionWebfetchAsk, ConfigModeBuildPermissionWebfetchAllow, ConfigModeBuildPermissionWebfetchDeny:
return true
}
return false
}
type ConfigModePlan struct {
// Description of when to use the agent
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigModePlanMode `json:"mode"`
Model string `json:"model"`
Permission ConfigModePlanPermission `json:"permission"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
ExtraFields map[string]interface{} `json:"-,extras"`
JSON configModePlanJSON `json:"-"`
Description string `json:"description"`
Disable bool `json:"disable"`
Mode ConfigModePlanMode `json:"mode"`
Model string `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
TopP float64 `json:"top_p"`
JSON configModePlanJSON `json:"-"`
}
// configModePlanJSON contains the JSON metadata for the struct [ConfigModePlan]
@@ -1227,7 +749,6 @@ type configModePlanJSON struct {
Disable apijson.Field
Mode apijson.Field
Model apijson.Field
Permission apijson.Field
Prompt apijson.Field
Temperature apijson.Field
Tools apijson.Field
@@ -1260,122 +781,6 @@ func (r ConfigModePlanMode) IsKnown() bool {
return false
}
type ConfigModePlanPermission struct {
Bash ConfigModePlanPermissionBashUnion `json:"bash"`
Edit ConfigModePlanPermissionEdit `json:"edit"`
Webfetch ConfigModePlanPermissionWebfetch `json:"webfetch"`
JSON configModePlanPermissionJSON `json:"-"`
}
// configModePlanPermissionJSON contains the JSON metadata for the struct
// [ConfigModePlanPermission]
type configModePlanPermissionJSON struct {
Bash apijson.Field
Edit apijson.Field
Webfetch apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigModePlanPermission) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configModePlanPermissionJSON) RawJSON() string {
return r.raw
}
// Union satisfied by [ConfigModePlanPermissionBashString] or
// [ConfigModePlanPermissionBashMap].
type ConfigModePlanPermissionBashUnion interface {
implementsConfigModePlanPermissionBashUnion()
}
func init() {
apijson.RegisterUnion(
reflect.TypeOf((*ConfigModePlanPermissionBashUnion)(nil)).Elem(),
"",
apijson.UnionVariant{
TypeFilter: gjson.String,
Type: reflect.TypeOf(ConfigModePlanPermissionBashString("")),
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(ConfigModePlanPermissionBashMap{}),
},
)
}
type ConfigModePlanPermissionBashString string
const (
ConfigModePlanPermissionBashStringAsk ConfigModePlanPermissionBashString = "ask"
ConfigModePlanPermissionBashStringAllow ConfigModePlanPermissionBashString = "allow"
ConfigModePlanPermissionBashStringDeny ConfigModePlanPermissionBashString = "deny"
)
func (r ConfigModePlanPermissionBashString) IsKnown() bool {
switch r {
case ConfigModePlanPermissionBashStringAsk, ConfigModePlanPermissionBashStringAllow, ConfigModePlanPermissionBashStringDeny:
return true
}
return false
}
func (r ConfigModePlanPermissionBashString) implementsConfigModePlanPermissionBashUnion() {}
type ConfigModePlanPermissionBashMap map[string]ConfigModePlanPermissionBashMapItem
func (r ConfigModePlanPermissionBashMap) implementsConfigModePlanPermissionBashUnion() {}
type ConfigModePlanPermissionBashMapItem string
const (
ConfigModePlanPermissionBashMapAsk ConfigModePlanPermissionBashMapItem = "ask"
ConfigModePlanPermissionBashMapAllow ConfigModePlanPermissionBashMapItem = "allow"
ConfigModePlanPermissionBashMapDeny ConfigModePlanPermissionBashMapItem = "deny"
)
func (r ConfigModePlanPermissionBashMapItem) IsKnown() bool {
switch r {
case ConfigModePlanPermissionBashMapAsk, ConfigModePlanPermissionBashMapAllow, ConfigModePlanPermissionBashMapDeny:
return true
}
return false
}
type ConfigModePlanPermissionEdit string
const (
ConfigModePlanPermissionEditAsk ConfigModePlanPermissionEdit = "ask"
ConfigModePlanPermissionEditAllow ConfigModePlanPermissionEdit = "allow"
ConfigModePlanPermissionEditDeny ConfigModePlanPermissionEdit = "deny"
)
func (r ConfigModePlanPermissionEdit) IsKnown() bool {
switch r {
case ConfigModePlanPermissionEditAsk, ConfigModePlanPermissionEditAllow, ConfigModePlanPermissionEditDeny:
return true
}
return false
}
type ConfigModePlanPermissionWebfetch string
const (
ConfigModePlanPermissionWebfetchAsk ConfigModePlanPermissionWebfetch = "ask"
ConfigModePlanPermissionWebfetchAllow ConfigModePlanPermissionWebfetch = "allow"
ConfigModePlanPermissionWebfetchDeny ConfigModePlanPermissionWebfetch = "deny"
)
func (r ConfigModePlanPermissionWebfetch) IsKnown() bool {
switch r {
case ConfigModePlanPermissionWebfetchAsk, ConfigModePlanPermissionWebfetchAllow, ConfigModePlanPermissionWebfetchDeny:
return true
}
return false
}
type ConfigPermission struct {
Bash ConfigPermissionBashUnion `json:"bash"`
Edit ConfigPermissionEdit `json:"edit"`
@@ -1492,10 +897,10 @@ func (r ConfigPermissionWebfetch) IsKnown() bool {
}
type ConfigProvider struct {
Models map[string]ConfigProviderModel `json:"models,required"`
ID string `json:"id"`
API string `json:"api"`
Env []string `json:"env"`
Models map[string]ConfigProviderModel `json:"models"`
Name string `json:"name"`
Npm string `json:"npm"`
Options ConfigProviderOptions `json:"options"`
@@ -1504,10 +909,10 @@ type ConfigProvider struct {
// configProviderJSON contains the JSON metadata for the struct [ConfigProvider]
type configProviderJSON struct {
Models apijson.Field
ID apijson.Field
API apijson.Field
Env apijson.Field
Models apijson.Field
Name apijson.Field
Npm apijson.Field
Options apijson.Field
@@ -1655,25 +1060,19 @@ func (r ConfigShare) IsKnown() bool {
}
type KeybindsConfig struct {
// Next agent
AgentCycle string `json:"agent_cycle,required"`
// Previous agent
AgentCycleReverse string `json:"agent_cycle_reverse,required"`
// List agents
AgentList string `json:"agent_list,required"`
// Exit the application
AppExit string `json:"app_exit,required"`
// Show help dialog
AppHelp string `json:"app_help,required"`
// Open external editor
EditorOpen string `json:"editor_open,required"`
// @deprecated Close file
// Close file
FileClose string `json:"file_close,required"`
// @deprecated Split/unified diff
// Split/unified diff
FileDiffToggle string `json:"file_diff_toggle,required"`
// @deprecated Currently not available. List files
// List files
FileList string `json:"file_list,required"`
// @deprecated Search file
// Search file
FileSearch string `json:"file_search,required"`
// Clear input field
InputClear string `json:"input_clear,required"`
@@ -1695,15 +1094,15 @@ type KeybindsConfig struct {
MessagesHalfPageUp string `json:"messages_half_page_up,required"`
// Navigate to last message
MessagesLast string `json:"messages_last,required"`
// @deprecated Toggle layout
// Toggle layout
MessagesLayoutToggle string `json:"messages_layout_toggle,required"`
// @deprecated Navigate to next message
// Navigate to next message
MessagesNext string `json:"messages_next,required"`
// Scroll messages down by one page
MessagesPageDown string `json:"messages_page_down,required"`
// Scroll messages up by one page
MessagesPageUp string `json:"messages_page_up,required"`
// @deprecated Navigate to previous message
// Navigate to previous message
MessagesPrevious string `json:"messages_previous,required"`
// Redo message
MessagesRedo string `json:"messages_redo,required"`
@@ -1711,10 +1110,6 @@ type KeybindsConfig struct {
MessagesRevert string `json:"messages_revert,required"`
// Undo message
MessagesUndo string `json:"messages_undo,required"`
// Next recent model
ModelCycleRecent string `json:"model_cycle_recent,required"`
// Previous recent model
ModelCycleRecentReverse string `json:"model_cycle_recent_reverse,required"`
// List available models
ModelList string `json:"model_list,required"`
// Create/update AGENTS.md
@@ -1733,18 +1128,16 @@ type KeybindsConfig struct {
SessionShare string `json:"session_share,required"`
// Unshare current session
SessionUnshare string `json:"session_unshare,required"`
// @deprecated use agent_cycle. Next agent
// Next agent
SwitchAgent string `json:"switch_agent,required"`
// @deprecated use agent_cycle_reverse. Previous agent
// Previous agent
SwitchAgentReverse string `json:"switch_agent_reverse,required"`
// @deprecated use agent_cycle. Next mode
// @deprecated use switch_agent. Next mode
SwitchMode string `json:"switch_mode,required"`
// @deprecated use agent_cycle_reverse. Previous mode
// @deprecated use switch_agent_reverse. Previous mode
SwitchModeReverse string `json:"switch_mode_reverse,required"`
// List available themes
ThemeList string `json:"theme_list,required"`
// Toggle thinking blocks
ThinkingBlocks string `json:"thinking_blocks,required"`
// Toggle tool details
ToolDetails string `json:"tool_details,required"`
JSON keybindsConfigJSON `json:"-"`
@@ -1752,54 +1145,48 @@ type KeybindsConfig struct {
// keybindsConfigJSON contains the JSON metadata for the struct [KeybindsConfig]
type keybindsConfigJSON struct {
AgentCycle apijson.Field
AgentCycleReverse apijson.Field
AgentList apijson.Field
AppExit apijson.Field
AppHelp apijson.Field
EditorOpen apijson.Field
FileClose apijson.Field
FileDiffToggle apijson.Field
FileList apijson.Field
FileSearch apijson.Field
InputClear apijson.Field
InputNewline apijson.Field
InputPaste apijson.Field
InputSubmit apijson.Field
Leader apijson.Field
MessagesCopy apijson.Field
MessagesFirst apijson.Field
MessagesHalfPageDown apijson.Field
MessagesHalfPageUp apijson.Field
MessagesLast apijson.Field
MessagesLayoutToggle apijson.Field
MessagesNext apijson.Field
MessagesPageDown apijson.Field
MessagesPageUp apijson.Field
MessagesPrevious apijson.Field
MessagesRedo apijson.Field
MessagesRevert apijson.Field
MessagesUndo apijson.Field
ModelCycleRecent apijson.Field
ModelCycleRecentReverse apijson.Field
ModelList apijson.Field
ProjectInit apijson.Field
SessionCompact apijson.Field
SessionExport apijson.Field
SessionInterrupt apijson.Field
SessionList apijson.Field
SessionNew apijson.Field
SessionShare apijson.Field
SessionUnshare apijson.Field
SwitchAgent apijson.Field
SwitchAgentReverse apijson.Field
SwitchMode apijson.Field
SwitchModeReverse apijson.Field
ThemeList apijson.Field
ThinkingBlocks apijson.Field
ToolDetails apijson.Field
raw string
ExtraFields map[string]apijson.Field
AppExit apijson.Field
AppHelp apijson.Field
EditorOpen apijson.Field
FileClose apijson.Field
FileDiffToggle apijson.Field
FileList apijson.Field
FileSearch apijson.Field
InputClear apijson.Field
InputNewline apijson.Field
InputPaste apijson.Field
InputSubmit apijson.Field
Leader apijson.Field
MessagesCopy apijson.Field
MessagesFirst apijson.Field
MessagesHalfPageDown apijson.Field
MessagesHalfPageUp apijson.Field
MessagesLast apijson.Field
MessagesLayoutToggle apijson.Field
MessagesNext apijson.Field
MessagesPageDown apijson.Field
MessagesPageUp apijson.Field
MessagesPrevious apijson.Field
MessagesRedo apijson.Field
MessagesRevert apijson.Field
MessagesUndo apijson.Field
ModelList apijson.Field
ProjectInit apijson.Field
SessionCompact apijson.Field
SessionExport apijson.Field
SessionInterrupt apijson.Field
SessionList apijson.Field
SessionNew apijson.Field
SessionShare apijson.Field
SessionUnshare apijson.Field
SwitchAgent apijson.Field
SwitchAgentReverse apijson.Field
SwitchMode apijson.Field
SwitchModeReverse apijson.Field
ThemeList apijson.Field
ToolDetails apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *KeybindsConfig) UnmarshalJSON(data []byte) (err error) {
+123 -121
View File
@@ -54,13 +54,13 @@ type EventListResponse struct {
// [EventListResponseEventMessageRemovedProperties],
// [EventListResponseEventMessagePartUpdatedProperties],
// [EventListResponseEventMessagePartRemovedProperties],
// [EventListResponseEventStorageWriteProperties], [Permission],
// [EventListResponseEventStorageWriteProperties],
// [EventListResponseEventFileEditedProperties], [interface{}], [Permission],
// [EventListResponseEventPermissionRepliedProperties],
// [EventListResponseEventFileEditedProperties],
// [EventListResponseEventSessionUpdatedProperties],
// [EventListResponseEventSessionDeletedProperties],
// [EventListResponseEventSessionIdleProperties],
// [EventListResponseEventSessionErrorProperties], [interface{}],
// [EventListResponseEventSessionErrorProperties],
// [EventListResponseEventFileWatcherUpdatedProperties],
// [EventListResponseEventIdeInstalledProperties].
Properties interface{} `json:"properties,required"`
@@ -100,11 +100,12 @@ func (r *EventListResponse) UnmarshalJSON(data []byte) (err error) {
// [EventListResponseEventMessageUpdated], [EventListResponseEventMessageRemoved],
// [EventListResponseEventMessagePartUpdated],
// [EventListResponseEventMessagePartRemoved],
// [EventListResponseEventStorageWrite], [EventListResponseEventPermissionUpdated],
// [EventListResponseEventPermissionReplied], [EventListResponseEventFileEdited],
// [EventListResponseEventStorageWrite], [EventListResponseEventFileEdited],
// [EventListResponseEventServerConnected],
// [EventListResponseEventPermissionUpdated],
// [EventListResponseEventPermissionReplied],
// [EventListResponseEventSessionUpdated], [EventListResponseEventSessionDeleted],
// [EventListResponseEventSessionIdle], [EventListResponseEventSessionError],
// [EventListResponseEventServerConnected],
// [EventListResponseEventFileWatcherUpdated],
// [EventListResponseEventIdeInstalled].
func (r EventListResponse) AsUnion() EventListResponseUnion {
@@ -116,11 +117,12 @@ func (r EventListResponse) AsUnion() EventListResponseUnion {
// [EventListResponseEventMessageUpdated], [EventListResponseEventMessageRemoved],
// [EventListResponseEventMessagePartUpdated],
// [EventListResponseEventMessagePartRemoved],
// [EventListResponseEventStorageWrite], [EventListResponseEventPermissionUpdated],
// [EventListResponseEventPermissionReplied], [EventListResponseEventFileEdited],
// [EventListResponseEventStorageWrite], [EventListResponseEventFileEdited],
// [EventListResponseEventServerConnected],
// [EventListResponseEventPermissionUpdated],
// [EventListResponseEventPermissionReplied],
// [EventListResponseEventSessionUpdated], [EventListResponseEventSessionDeleted],
// [EventListResponseEventSessionIdle], [EventListResponseEventSessionError],
// [EventListResponseEventServerConnected],
// [EventListResponseEventFileWatcherUpdated] or
// [EventListResponseEventIdeInstalled].
type EventListResponseUnion interface {
@@ -166,6 +168,16 @@ func init() {
Type: reflect.TypeOf(EventListResponseEventStorageWrite{}),
DiscriminatorValue: "storage.write",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventFileEdited{}),
DiscriminatorValue: "file.edited",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventServerConnected{}),
DiscriminatorValue: "server.connected",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventPermissionUpdated{}),
@@ -176,11 +188,6 @@ func init() {
Type: reflect.TypeOf(EventListResponseEventPermissionReplied{}),
DiscriminatorValue: "permission.replied",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventFileEdited{}),
DiscriminatorValue: "file.edited",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventSessionUpdated{}),
@@ -201,11 +208,6 @@ func init() {
Type: reflect.TypeOf(EventListResponseEventSessionError{}),
DiscriminatorValue: "session.error",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventServerConnected{}),
DiscriminatorValue: "server.connected",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventFileWatcherUpdated{}),
@@ -649,6 +651,105 @@ func (r EventListResponseEventStorageWriteType) IsKnown() bool {
return false
}
type EventListResponseEventFileEdited struct {
Properties EventListResponseEventFileEditedProperties `json:"properties,required"`
Type EventListResponseEventFileEditedType `json:"type,required"`
JSON eventListResponseEventFileEditedJSON `json:"-"`
}
// eventListResponseEventFileEditedJSON contains the JSON metadata for the struct
// [EventListResponseEventFileEdited]
type eventListResponseEventFileEditedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEdited) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventFileEdited) implementsEventListResponse() {}
type EventListResponseEventFileEditedProperties struct {
File string `json:"file,required"`
JSON eventListResponseEventFileEditedPropertiesJSON `json:"-"`
}
// eventListResponseEventFileEditedPropertiesJSON contains the JSON metadata for
// the struct [EventListResponseEventFileEditedProperties]
type eventListResponseEventFileEditedPropertiesJSON struct {
File apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEditedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventFileEditedType string
const (
EventListResponseEventFileEditedTypeFileEdited EventListResponseEventFileEditedType = "file.edited"
)
func (r EventListResponseEventFileEditedType) IsKnown() bool {
switch r {
case EventListResponseEventFileEditedTypeFileEdited:
return true
}
return false
}
type EventListResponseEventServerConnected struct {
Properties interface{} `json:"properties,required"`
Type EventListResponseEventServerConnectedType `json:"type,required"`
JSON eventListResponseEventServerConnectedJSON `json:"-"`
}
// eventListResponseEventServerConnectedJSON contains the JSON metadata for the
// struct [EventListResponseEventServerConnected]
type eventListResponseEventServerConnectedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventServerConnected) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventServerConnectedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventServerConnected) implementsEventListResponse() {}
type EventListResponseEventServerConnectedType string
const (
EventListResponseEventServerConnectedTypeServerConnected EventListResponseEventServerConnectedType = "server.connected"
)
func (r EventListResponseEventServerConnectedType) IsKnown() bool {
switch r {
case EventListResponseEventServerConnectedTypeServerConnected:
return true
}
return false
}
type EventListResponseEventPermissionUpdated struct {
Properties Permission `json:"properties,required"`
Type EventListResponseEventPermissionUpdatedType `json:"type,required"`
@@ -752,66 +853,6 @@ func (r EventListResponseEventPermissionRepliedType) IsKnown() bool {
return false
}
type EventListResponseEventFileEdited struct {
Properties EventListResponseEventFileEditedProperties `json:"properties,required"`
Type EventListResponseEventFileEditedType `json:"type,required"`
JSON eventListResponseEventFileEditedJSON `json:"-"`
}
// eventListResponseEventFileEditedJSON contains the JSON metadata for the struct
// [EventListResponseEventFileEdited]
type eventListResponseEventFileEditedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEdited) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventFileEdited) implementsEventListResponse() {}
type EventListResponseEventFileEditedProperties struct {
File string `json:"file,required"`
JSON eventListResponseEventFileEditedPropertiesJSON `json:"-"`
}
// eventListResponseEventFileEditedPropertiesJSON contains the JSON metadata for
// the struct [EventListResponseEventFileEditedProperties]
type eventListResponseEventFileEditedPropertiesJSON struct {
File apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEditedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventFileEditedType string
const (
EventListResponseEventFileEditedTypeFileEdited EventListResponseEventFileEditedType = "file.edited"
)
func (r EventListResponseEventFileEditedType) IsKnown() bool {
switch r {
case EventListResponseEventFileEditedTypeFileEdited:
return true
}
return false
}
type EventListResponseEventSessionUpdated struct {
Properties EventListResponseEventSessionUpdatedProperties `json:"properties,required"`
Type EventListResponseEventSessionUpdatedType `json:"type,required"`
@@ -1188,45 +1229,6 @@ func (r EventListResponseEventSessionErrorType) IsKnown() bool {
return false
}
type EventListResponseEventServerConnected struct {
Properties interface{} `json:"properties,required"`
Type EventListResponseEventServerConnectedType `json:"type,required"`
JSON eventListResponseEventServerConnectedJSON `json:"-"`
}
// eventListResponseEventServerConnectedJSON contains the JSON metadata for the
// struct [EventListResponseEventServerConnected]
type eventListResponseEventServerConnectedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventServerConnected) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventServerConnectedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventServerConnected) implementsEventListResponse() {}
type EventListResponseEventServerConnectedType string
const (
EventListResponseEventServerConnectedTypeServerConnected EventListResponseEventServerConnectedType = "server.connected"
)
func (r EventListResponseEventServerConnectedType) IsKnown() bool {
switch r {
case EventListResponseEventServerConnectedTypeServerConnected:
return true
}
return false
}
type EventListResponseEventFileWatcherUpdated struct {
Properties EventListResponseEventFileWatcherUpdatedProperties `json:"properties,required"`
Type EventListResponseEventFileWatcherUpdatedType `json:"type,required"`
@@ -1374,21 +1376,21 @@ const (
EventListResponseTypeMessagePartUpdated EventListResponseType = "message.part.updated"
EventListResponseTypeMessagePartRemoved EventListResponseType = "message.part.removed"
EventListResponseTypeStorageWrite EventListResponseType = "storage.write"
EventListResponseTypeFileEdited EventListResponseType = "file.edited"
EventListResponseTypeServerConnected EventListResponseType = "server.connected"
EventListResponseTypePermissionUpdated EventListResponseType = "permission.updated"
EventListResponseTypePermissionReplied EventListResponseType = "permission.replied"
EventListResponseTypeFileEdited EventListResponseType = "file.edited"
EventListResponseTypeSessionUpdated EventListResponseType = "session.updated"
EventListResponseTypeSessionDeleted EventListResponseType = "session.deleted"
EventListResponseTypeSessionIdle EventListResponseType = "session.idle"
EventListResponseTypeSessionError EventListResponseType = "session.error"
EventListResponseTypeServerConnected EventListResponseType = "server.connected"
EventListResponseTypeFileWatcherUpdated EventListResponseType = "file.watcher.updated"
EventListResponseTypeIdeInstalled EventListResponseType = "ide.installed"
)
func (r EventListResponseType) IsKnown() bool {
switch r {
case EventListResponseTypeInstallationUpdated, EventListResponseTypeLspClientDiagnostics, EventListResponseTypeMessageUpdated, EventListResponseTypeMessageRemoved, EventListResponseTypeMessagePartUpdated, EventListResponseTypeMessagePartRemoved, EventListResponseTypeStorageWrite, EventListResponseTypePermissionUpdated, EventListResponseTypePermissionReplied, EventListResponseTypeFileEdited, EventListResponseTypeSessionUpdated, EventListResponseTypeSessionDeleted, EventListResponseTypeSessionIdle, EventListResponseTypeSessionError, EventListResponseTypeServerConnected, EventListResponseTypeFileWatcherUpdated, EventListResponseTypeIdeInstalled:
case EventListResponseTypeInstallationUpdated, EventListResponseTypeLspClientDiagnostics, EventListResponseTypeMessageUpdated, EventListResponseTypeMessageRemoved, EventListResponseTypeMessagePartUpdated, EventListResponseTypeMessagePartRemoved, EventListResponseTypeStorageWrite, EventListResponseTypeFileEdited, EventListResponseTypeServerConnected, EventListResponseTypePermissionUpdated, EventListResponseTypePermissionReplied, EventListResponseTypeSessionUpdated, EventListResponseTypeSessionDeleted, EventListResponseTypeSessionIdle, EventListResponseTypeSessionError, EventListResponseTypeFileWatcherUpdated, EventListResponseTypeIdeInstalled:
return true
}
return false
+63 -130
View File
@@ -46,18 +46,6 @@ func (r *SessionService) New(ctx context.Context, opts ...option.RequestOption)
return
}
// Update session properties
func (r *SessionService) Update(ctx context.Context, id string, body SessionUpdateParams, opts ...option.RequestOption) (res *Session, err error) {
opts = append(r.Options[:], opts...)
if id == "" {
err = errors.New("missing required id parameter")
return
}
path := fmt.Sprintf("session/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, body, &res, opts...)
return
}
// List all sessions
func (r *SessionService) List(ctx context.Context, opts ...option.RequestOption) (res *[]Session, err error) {
opts = append(r.Options[:], opts...)
@@ -102,30 +90,6 @@ func (r *SessionService) Chat(ctx context.Context, id string, body SessionChatPa
return
}
// Get a session's children
func (r *SessionService) Children(ctx context.Context, id string, opts ...option.RequestOption) (res *[]Session, err error) {
opts = append(r.Options[:], opts...)
if id == "" {
err = errors.New("missing required id parameter")
return
}
path := fmt.Sprintf("session/%s/children", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return
}
// Get session
func (r *SessionService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Session, err error) {
opts = append(r.Options[:], opts...)
if id == "" {
err = errors.New("missing required id parameter")
return
}
path := fmt.Sprintf("session/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return
}
// Analyze the app and create an AGENTS.md file
func (r *SessionService) Init(ctx context.Context, id string, body SessionInitParams, opts ...option.RequestOption) (res *bool, err error) {
opts = append(r.Options[:], opts...)
@@ -190,18 +154,6 @@ func (r *SessionService) Share(ctx context.Context, id string, opts ...option.Re
return
}
// Run a shell command
func (r *SessionService) Shell(ctx context.Context, id string, body SessionShellParams, opts ...option.RequestOption) (res *AssistantMessage, err error) {
opts = append(r.Options[:], opts...)
if id == "" {
err = errors.New("missing required id parameter")
return
}
path := fmt.Sprintf("session/%s/shell", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return
}
// Summarize the session
func (r *SessionService) Summarize(ctx context.Context, id string, body SessionSummarizeParams, opts ...option.RequestOption) (res *bool, err error) {
opts = append(r.Options[:], opts...)
@@ -1012,11 +964,11 @@ type Part struct {
// This field can have the runtime type of [[]string].
Files interface{} `json:"files"`
Hash string `json:"hash"`
Mime string `json:"mime"`
Name string `json:"name"`
// This field can have the runtime type of [map[string]interface{}].
Metadata interface{} `json:"metadata"`
Mime string `json:"mime"`
Name string `json:"name"`
Snapshot string `json:"snapshot"`
ProviderMetadata interface{} `json:"providerMetadata"`
Snapshot string `json:"snapshot"`
// This field can have the runtime type of [FilePartSource], [AgentPartSource].
Source interface{} `json:"source"`
// This field can have the runtime type of [ToolPartState].
@@ -1035,29 +987,29 @@ type Part struct {
// partJSON contains the JSON metadata for the struct [Part]
type partJSON struct {
ID apijson.Field
MessageID apijson.Field
SessionID apijson.Field
Type apijson.Field
CallID apijson.Field
Cost apijson.Field
Filename apijson.Field
Files apijson.Field
Hash apijson.Field
Metadata apijson.Field
Mime apijson.Field
Name apijson.Field
Snapshot apijson.Field
Source apijson.Field
State apijson.Field
Synthetic apijson.Field
Text apijson.Field
Time apijson.Field
Tokens apijson.Field
Tool apijson.Field
URL apijson.Field
raw string
ExtraFields map[string]apijson.Field
ID apijson.Field
MessageID apijson.Field
SessionID apijson.Field
Type apijson.Field
CallID apijson.Field
Cost apijson.Field
Filename apijson.Field
Files apijson.Field
Hash apijson.Field
Mime apijson.Field
Name apijson.Field
ProviderMetadata apijson.Field
Snapshot apijson.Field
Source apijson.Field
State apijson.Field
Synthetic apijson.Field
Text apijson.Field
Time apijson.Field
Tokens apijson.Field
Tool apijson.Field
URL apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r partJSON) RawJSON() string {
@@ -1211,27 +1163,27 @@ func (r PartType) IsKnown() bool {
}
type ReasoningPart struct {
ID string `json:"id,required"`
MessageID string `json:"messageID,required"`
SessionID string `json:"sessionID,required"`
Text string `json:"text,required"`
Time ReasoningPartTime `json:"time,required"`
Type ReasoningPartType `json:"type,required"`
Metadata map[string]interface{} `json:"metadata"`
JSON reasoningPartJSON `json:"-"`
ID string `json:"id,required"`
MessageID string `json:"messageID,required"`
SessionID string `json:"sessionID,required"`
Text string `json:"text,required"`
Type ReasoningPartType `json:"type,required"`
ProviderMetadata map[string]interface{} `json:"providerMetadata"`
Time ReasoningPartTime `json:"time"`
JSON reasoningPartJSON `json:"-"`
}
// reasoningPartJSON contains the JSON metadata for the struct [ReasoningPart]
type reasoningPartJSON struct {
ID apijson.Field
MessageID apijson.Field
SessionID apijson.Field
Text apijson.Field
Time apijson.Field
Type apijson.Field
Metadata apijson.Field
raw string
ExtraFields map[string]apijson.Field
ID apijson.Field
MessageID apijson.Field
SessionID apijson.Field
Text apijson.Field
Type apijson.Field
ProviderMetadata apijson.Field
Time apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ReasoningPart) UnmarshalJSON(data []byte) (err error) {
@@ -1244,6 +1196,20 @@ func (r reasoningPartJSON) RawJSON() string {
func (r ReasoningPart) implementsPart() {}
type ReasoningPartType string
const (
ReasoningPartTypeReasoning ReasoningPartType = "reasoning"
)
func (r ReasoningPartType) IsKnown() bool {
switch r {
case ReasoningPartTypeReasoning:
return true
}
return false
}
type ReasoningPartTime struct {
Start float64 `json:"start,required"`
End float64 `json:"end"`
@@ -1267,20 +1233,6 @@ func (r reasoningPartTimeJSON) RawJSON() string {
return r.raw
}
type ReasoningPartType string
const (
ReasoningPartTypeReasoning ReasoningPartType = "reasoning"
)
func (r ReasoningPartType) IsKnown() bool {
switch r {
case ReasoningPartTypeReasoning:
return true
}
return false
}
type Session struct {
ID string `json:"id,required"`
Time SessionTime `json:"time,required"`
@@ -2047,12 +1999,11 @@ func (r toolStateCompletedTimeJSON) RawJSON() string {
}
type ToolStateError struct {
Error string `json:"error,required"`
Input map[string]interface{} `json:"input,required"`
Status ToolStateErrorStatus `json:"status,required"`
Time ToolStateErrorTime `json:"time,required"`
Metadata map[string]interface{} `json:"metadata"`
JSON toolStateErrorJSON `json:"-"`
Error string `json:"error,required"`
Input map[string]interface{} `json:"input,required"`
Status ToolStateErrorStatus `json:"status,required"`
Time ToolStateErrorTime `json:"time,required"`
JSON toolStateErrorJSON `json:"-"`
}
// toolStateErrorJSON contains the JSON metadata for the struct [ToolStateError]
@@ -2061,7 +2012,6 @@ type toolStateErrorJSON struct {
Input apijson.Field
Status apijson.Field
Time apijson.Field
Metadata apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
@@ -2324,14 +2274,6 @@ func (r sessionMessagesResponseJSON) RawJSON() string {
return r.raw
}
type SessionUpdateParams struct {
Title param.Field[string] `json:"title"`
}
func (r SessionUpdateParams) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type SessionChatParams struct {
ModelID param.Field[string] `json:"modelID,required"`
Parts param.Field[[]SessionChatParamsPartUnion] `json:"parts,required"`
@@ -2406,15 +2348,6 @@ func (r SessionRevertParams) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type SessionShellParams struct {
Agent param.Field[string] `json:"agent,required"`
Command param.Field[string] `json:"command,required"`
}
func (r SessionShellParams) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type SessionSummarizeParams struct {
ModelID param.Field[string] `json:"modelID,required"`
ProviderID param.Field[string] `json:"providerID,required"`
-101
View File
@@ -35,34 +35,6 @@ func TestSessionNew(t *testing.T) {
}
}
func TestSessionUpdateWithOptionalParams(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := opencode.NewClient(
option.WithBaseURL(baseURL),
)
_, err := client.Session.Update(
context.TODO(),
"id",
opencode.SessionUpdateParams{
Title: opencode.F("title"),
},
)
if err != nil {
var apierr *opencode.Error
if errors.As(err, &apierr) {
t.Log(string(apierr.DumpRequest(true)))
}
t.Fatalf("err should be nil: %s", err.Error())
}
}
func TestSessionList(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
@@ -174,50 +146,6 @@ func TestSessionChatWithOptionalParams(t *testing.T) {
}
}
func TestSessionChildren(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := opencode.NewClient(
option.WithBaseURL(baseURL),
)
_, err := client.Session.Children(context.TODO(), "id")
if err != nil {
var apierr *opencode.Error
if errors.As(err, &apierr) {
t.Log(string(apierr.DumpRequest(true)))
}
t.Fatalf("err should be nil: %s", err.Error())
}
}
func TestSessionGet(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := opencode.NewClient(
option.WithBaseURL(baseURL),
)
_, err := client.Session.Get(context.TODO(), "id")
if err != nil {
var apierr *opencode.Error
if errors.As(err, &apierr) {
t.Log(string(apierr.DumpRequest(true)))
}
t.Fatalf("err should be nil: %s", err.Error())
}
}
func TestSessionInit(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
@@ -347,35 +275,6 @@ func TestSessionShare(t *testing.T) {
}
}
func TestSessionShell(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := opencode.NewClient(
option.WithBaseURL(baseURL),
)
_, err := client.Session.Shell(
context.TODO(),
"id",
opencode.SessionShellParams{
Agent: opencode.F("agent"),
Command: opencode.F("command"),
},
)
if err != nil {
var apierr *opencode.Error
if errors.As(err, &apierr) {
t.Log(string(apierr.DumpRequest(true)))
}
t.Fatalf("err should be nil: %s", err.Error())
}
}
func TestSessionSummarize(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
+1 -36
View File
@@ -47,7 +47,7 @@ func (r *TuiService) ClearPrompt(ctx context.Context, opts ...option.RequestOpti
return
}
// Execute a TUI command (e.g. agent_cycle)
// Execute a TUI command (e.g. switch_agent)
func (r *TuiService) ExecuteCommand(ctx context.Context, body TuiExecuteCommandParams, opts ...option.RequestOption) (res *bool, err error) {
opts = append(r.Options[:], opts...)
path := "tui/execute-command"
@@ -87,14 +87,6 @@ func (r *TuiService) OpenThemes(ctx context.Context, opts ...option.RequestOptio
return
}
// Show a toast notification in the TUI
func (r *TuiService) ShowToast(ctx context.Context, body TuiShowToastParams, opts ...option.RequestOption) (res *bool, err error) {
opts = append(r.Options[:], opts...)
path := "tui/show-toast"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return
}
// Submit the prompt
func (r *TuiService) SubmitPrompt(ctx context.Context, opts ...option.RequestOption) (res *bool, err error) {
opts = append(r.Options[:], opts...)
@@ -118,30 +110,3 @@ type TuiExecuteCommandParams struct {
func (r TuiExecuteCommandParams) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type TuiShowToastParams struct {
Message param.Field[string] `json:"message,required"`
Variant param.Field[TuiShowToastParamsVariant] `json:"variant,required"`
Title param.Field[string] `json:"title"`
}
func (r TuiShowToastParams) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
type TuiShowToastParamsVariant string
const (
TuiShowToastParamsVariantInfo TuiShowToastParamsVariant = "info"
TuiShowToastParamsVariantSuccess TuiShowToastParamsVariant = "success"
TuiShowToastParamsVariantWarning TuiShowToastParamsVariant = "warning"
TuiShowToastParamsVariantError TuiShowToastParamsVariant = "error"
)
func (r TuiShowToastParamsVariant) IsKnown() bool {
switch r {
case TuiShowToastParamsVariantInfo, TuiShowToastParamsVariantSuccess, TuiShowToastParamsVariantWarning, TuiShowToastParamsVariantError:
return true
}
return false
}
-26
View File
@@ -171,32 +171,6 @@ func TestTuiOpenThemes(t *testing.T) {
}
}
func TestTuiShowToastWithOptionalParams(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := opencode.NewClient(
option.WithBaseURL(baseURL),
)
_, err := client.Tui.ShowToast(context.TODO(), opencode.TuiShowToastParams{
Message: opencode.F("message"),
Variant: opencode.F(opencode.TuiShowToastParamsVariantInfo),
Title: opencode.F("title"),
})
if err != nil {
var apierr *opencode.Error
if errors.As(err, &apierr) {
t.Log(string(apierr.DumpRequest(true)))
}
t.Fatalf("err should be nil: %s", err.Error())
}
}
func TestTuiSubmitPrompt(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/sdk",
"version": "0.5.2",
"version": "0.4.13",
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit"
+1 -85
View File
@@ -19,10 +19,6 @@ import type {
SessionDeleteResponses,
SessionGetData,
SessionGetResponses,
SessionUpdateData,
SessionUpdateResponses,
SessionChildrenData,
SessionChildrenResponses,
SessionInitData,
SessionInitResponses,
SessionAbortData,
@@ -39,8 +35,6 @@ import type {
SessionChatResponses,
SessionMessageData,
SessionMessageResponses,
SessionShellData,
SessionShellResponses,
SessionRevertData,
SessionRevertResponses,
SessionUnrevertData,
@@ -79,11 +73,6 @@ import type {
TuiClearPromptResponses,
TuiExecuteCommandData,
TuiExecuteCommandResponses,
TuiShowToastData,
TuiShowToastResponses,
AuthSetData,
AuthSetResponses,
AuthSetErrors,
} from "./types.gen.js"
import { client as _heyApiClient } from "./client.gen.js"
@@ -212,10 +201,6 @@ class Session extends _HeyApiClient {
return (options?.client ?? this._client).post<SessionCreateResponses, SessionCreateErrors, ThrowOnError>({
url: "/session",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
})
}
@@ -239,30 +224,6 @@ class Session extends _HeyApiClient {
})
}
/**
* Update session properties
*/
public update<ThrowOnError extends boolean = false>(options: Options<SessionUpdateData, ThrowOnError>) {
return (options.client ?? this._client).patch<SessionUpdateResponses, unknown, ThrowOnError>({
url: "/session/{id}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
})
}
/**
* Get a session's children
*/
public children<ThrowOnError extends boolean = false>(options: Options<SessionChildrenData, ThrowOnError>) {
return (options.client ?? this._client).get<SessionChildrenResponses, unknown, ThrowOnError>({
url: "/session/{id}/children",
...options,
})
}
/**
* Analyze the app and create an AGENTS.md file
*/
@@ -355,20 +316,6 @@ class Session extends _HeyApiClient {
})
}
/**
* Run a shell command
*/
public shell<ThrowOnError extends boolean = false>(options: Options<SessionShellData, ThrowOnError>) {
return (options.client ?? this._client).post<SessionShellResponses, unknown, ThrowOnError>({
url: "/session/{id}/shell",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
})
}
/**
* Revert a message
*/
@@ -524,7 +471,7 @@ class Tui extends _HeyApiClient {
}
/**
* Execute a TUI command (e.g. agent_cycle)
* Execute a TUI command (e.g. switch_agent)
*/
public executeCommand<ThrowOnError extends boolean = false>(options?: Options<TuiExecuteCommandData, ThrowOnError>) {
return (options?.client ?? this._client).post<TuiExecuteCommandResponses, unknown, ThrowOnError>({
@@ -536,36 +483,6 @@ class Tui extends _HeyApiClient {
},
})
}
/**
* Show a toast notification in the TUI
*/
public showToast<ThrowOnError extends boolean = false>(options?: Options<TuiShowToastData, ThrowOnError>) {
return (options?.client ?? this._client).post<TuiShowToastResponses, unknown, ThrowOnError>({
url: "/tui/show-toast",
...options,
headers: {
"Content-Type": "application/json",
...options?.headers,
},
})
}
}
class Auth extends _HeyApiClient {
/**
* Set authentication credentials
*/
public set<ThrowOnError extends boolean = false>(options: Options<AuthSetData, ThrowOnError>) {
return (options.client ?? this._client).put<AuthSetResponses, AuthSetErrors, ThrowOnError>({
url: "/auth/{id}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
})
}
}
export class OpencodeClient extends _HeyApiClient {
@@ -595,5 +512,4 @@ export class OpencodeClient extends _HeyApiClient {
find = new Find({ client: this._client })
file = new File({ client: this._client })
tui = new Tui({ client: this._client })
auth = new Auth({ client: this._client })
}
+137 -345
View File
@@ -22,15 +22,18 @@ export type Event =
| ({
type: "storage.write"
} & EventStorageWrite)
| ({
type: "file.edited"
} & EventFileEdited)
| ({
type: "server.connected"
} & EventServerConnected)
| ({
type: "permission.updated"
} & EventPermissionUpdated)
| ({
type: "permission.replied"
} & EventPermissionReplied)
| ({
type: "file.edited"
} & EventFileEdited)
| ({
type: "session.updated"
} & EventSessionUpdated)
@@ -43,9 +46,6 @@ export type Event =
| ({
type: "session.error"
} & EventSessionError)
| ({
type: "server.connected"
} & EventServerConnected)
| ({
type: "file.watcher.updated"
} & EventFileWatcherUpdated)
@@ -54,14 +54,14 @@ export type Event =
} & EventIdeInstalled)
export type EventInstallationUpdated = {
type: "installation.updated"
type: string
properties: {
version: string
}
}
export type EventLspClientDiagnostics = {
type: "lsp.client.diagnostics"
type: string
properties: {
serverID: string
path: string
@@ -69,7 +69,7 @@ export type EventLspClientDiagnostics = {
}
export type EventMessageUpdated = {
type: "message.updated"
type: string
properties: {
info: Message
}
@@ -86,7 +86,7 @@ export type Message =
export type UserMessage = {
id: string
sessionID: string
role: "user"
role: string
time: {
created: number
}
@@ -95,7 +95,7 @@ export type UserMessage = {
export type AssistantMessage = {
id: string
sessionID: string
role: "assistant"
role: string
time: {
created: number
completed?: number
@@ -135,7 +135,7 @@ export type AssistantMessage = {
}
export type ProviderAuthError = {
name: "ProviderAuthError"
name: string
data: {
providerID: string
message: string
@@ -143,28 +143,28 @@ export type ProviderAuthError = {
}
export type UnknownError = {
name: "UnknownError"
name: string
data: {
message: string
}
}
export type MessageOutputLengthError = {
name: "MessageOutputLengthError"
name: string
data: {
[key: string]: unknown
}
}
export type MessageAbortedError = {
name: "MessageAbortedError"
name: string
data: {
[key: string]: unknown
}
}
export type EventMessageRemoved = {
type: "message.removed"
type: string
properties: {
sessionID: string
messageID: string
@@ -172,7 +172,7 @@ export type EventMessageRemoved = {
}
export type EventMessagePartUpdated = {
type: "message.part.updated"
type: string
properties: {
part: Part
}
@@ -211,7 +211,7 @@ export type TextPart = {
id: string
sessionID: string
messageID: string
type: "text"
type: string
text: string
synthetic?: boolean
time?: {
@@ -224,7 +224,7 @@ export type ReasoningPart = {
id: string
sessionID: string
messageID: string
type: "reasoning"
type: string
text: string
metadata?: {
[key: string]: unknown
@@ -239,7 +239,7 @@ export type FilePart = {
id: string
sessionID: string
messageID: string
type: "file"
type: string
mime: string
filename?: string
url: string
@@ -256,7 +256,7 @@ export type FilePartSource =
export type FileSource = {
text: FilePartSourceText
type: "file"
type: string
path: string
}
@@ -268,7 +268,7 @@ export type FilePartSourceText = {
export type SymbolSource = {
text: FilePartSourceText
type: "symbol"
type: string
path: string
range: Range
name: string
@@ -290,7 +290,7 @@ export type ToolPart = {
id: string
sessionID: string
messageID: string
type: "tool"
type: string
callID: string
tool: string
state: ToolState
@@ -311,11 +311,11 @@ export type ToolState =
} & ToolStateError)
export type ToolStatePending = {
status: "pending"
status: string
}
export type ToolStateRunning = {
status: "running"
status: string
input?: unknown
title?: string
metadata?: {
@@ -327,7 +327,7 @@ export type ToolStateRunning = {
}
export type ToolStateCompleted = {
status: "completed"
status: string
input: {
[key: string]: unknown
}
@@ -343,14 +343,11 @@ export type ToolStateCompleted = {
}
export type ToolStateError = {
status: "error"
status: string
input: {
[key: string]: unknown
}
error: string
metadata?: {
[key: string]: unknown
}
time: {
start: number
end: number
@@ -361,14 +358,14 @@ export type StepStartPart = {
id: string
sessionID: string
messageID: string
type: "step-start"
type: string
}
export type StepFinishPart = {
id: string
sessionID: string
messageID: string
type: "step-finish"
type: string
cost: number
tokens: {
input: number
@@ -385,7 +382,7 @@ export type SnapshotPart = {
id: string
sessionID: string
messageID: string
type: "snapshot"
type: string
snapshot: string
}
@@ -393,7 +390,7 @@ export type PatchPart = {
id: string
sessionID: string
messageID: string
type: "patch"
type: string
hash: string
files: Array<string>
}
@@ -402,7 +399,7 @@ export type AgentPart = {
id: string
sessionID: string
messageID: string
type: "agent"
type: string
name: string
source?: {
value: string
@@ -412,7 +409,7 @@ export type AgentPart = {
}
export type EventMessagePartRemoved = {
type: "message.part.removed"
type: string
properties: {
sessionID: string
messageID: string
@@ -421,15 +418,29 @@ export type EventMessagePartRemoved = {
}
export type EventStorageWrite = {
type: "storage.write"
type: string
properties: {
key: string
content?: unknown
}
}
export type EventFileEdited = {
type: string
properties: {
file: string
}
}
export type EventServerConnected = {
type: string
properties: {
[key: string]: unknown
}
}
export type EventPermissionUpdated = {
type: "permission.updated"
type: string
properties: Permission
}
@@ -450,7 +461,7 @@ export type Permission = {
}
export type EventPermissionReplied = {
type: "permission.replied"
type: string
properties: {
sessionID: string
permissionID: string
@@ -458,15 +469,8 @@ export type EventPermissionReplied = {
}
}
export type EventFileEdited = {
type: "file.edited"
properties: {
file: string
}
}
export type EventSessionUpdated = {
type: "session.updated"
type: string
properties: {
info: Session
}
@@ -493,21 +497,21 @@ export type Session = {
}
export type EventSessionDeleted = {
type: "session.deleted"
type: string
properties: {
info: Session
}
}
export type EventSessionIdle = {
type: "session.idle"
type: string
properties: {
sessionID: string
}
}
export type EventSessionError = {
type: "session.error"
type: string
properties: {
sessionID?: string
error?:
@@ -526,23 +530,16 @@ export type EventSessionError = {
}
}
export type EventServerConnected = {
type: "server.connected"
properties: {
[key: string]: unknown
}
}
export type EventFileWatcherUpdated = {
type: "file.watcher.updated"
type: string
properties: {
file: string
event: "rename" | "change"
event: string
}
}
export type EventIdeInstalled = {
type: "ide.installed"
type: string
properties: {
ide: string
}
@@ -572,9 +569,6 @@ export type Config = {
* Theme name to use for the interface
*/
theme?: string
/**
* Custom keybind configurations
*/
keybinds?: KeybindsConfig
plugin?: Array<string>
snapshot?: boolean
@@ -633,7 +627,7 @@ export type Config = {
env?: Array<string>
id?: string
npm?: string
models?: {
models: {
[key: string]: {
id?: string
name?: string
@@ -689,7 +683,7 @@ export type Config = {
lsp?: {
[key: string]:
| {
disabled: true
disabled: boolean
}
| {
command: Array<string>
@@ -707,18 +701,15 @@ export type Config = {
* Additional instruction files or patterns to include
*/
instructions?: Array<string>
/**
* @deprecated Always uses stretch layout.
*/
layout?: LayoutConfig
permission?: {
edit?: "ask" | "allow" | "deny"
edit?: string
bash?:
| ("ask" | "allow" | "deny")
| string
| {
[key: string]: "ask" | "allow" | "deny"
[key: string]: string
}
webfetch?: "ask" | "allow" | "deny"
webfetch?: string
}
experimental?: {
hook?: {
@@ -750,29 +741,25 @@ export type KeybindsConfig = {
*/
app_help: string
/**
* Exit the application
* @deprecated use switch_agent. Next mode
*/
app_exit: string
switch_mode: string
/**
* @deprecated use switch_agent_reverse. Previous mode
*/
switch_mode_reverse: string
/**
* Next agent
*/
switch_agent: string
/**
* Previous agent
*/
switch_agent_reverse: string
/**
* Open external editor
*/
editor_open: string
/**
* List available themes
*/
theme_list: string
/**
* Create/update AGENTS.md
*/
project_init: string
/**
* Toggle tool details
*/
tool_details: string
/**
* Toggle thinking blocks
*/
thinking_blocks: string
/**
* Export session to editor
*/
@@ -802,73 +789,37 @@ export type KeybindsConfig = {
*/
session_compact: string
/**
* Cycle to next child session
* Toggle tool details
*/
session_child_cycle: string
/**
* Cycle to previous child session
*/
session_child_cycle_reverse: string
/**
* Scroll messages up by one page
*/
messages_page_up: string
/**
* Scroll messages down by one page
*/
messages_page_down: string
/**
* Scroll messages up by half page
*/
messages_half_page_up: string
/**
* Scroll messages down by half page
*/
messages_half_page_down: string
/**
* Navigate to first message
*/
messages_first: string
/**
* Navigate to last message
*/
messages_last: string
/**
* Copy message
*/
messages_copy: string
/**
* Undo message
*/
messages_undo: string
/**
* Redo message
*/
messages_redo: string
tool_details: string
/**
* List available models
*/
model_list: string
/**
* Next recent model
* List available themes
*/
model_cycle_recent: string
theme_list: string
/**
* Previous recent model
* List files
*/
model_cycle_recent_reverse: string
file_list: string
/**
* List agents
* Close file
*/
agent_list: string
file_close: string
/**
* Next agent
* Search file
*/
agent_cycle: string
file_search: string
/**
* Previous agent
* Split/unified diff
*/
agent_cycle_reverse: string
file_diff_toggle: string
/**
* Create/update AGENTS.md
*/
project_init: string
/**
* Clear input field
*/
@@ -886,53 +837,61 @@ export type KeybindsConfig = {
*/
input_newline: string
/**
* @deprecated use agent_cycle. Next mode
* Scroll messages up by one page
*/
switch_mode: string
messages_page_up: string
/**
* @deprecated use agent_cycle_reverse. Previous mode
* Scroll messages down by one page
*/
switch_mode_reverse: string
messages_page_down: string
/**
* @deprecated use agent_cycle. Next agent
* Scroll messages up by half page
*/
switch_agent: string
messages_half_page_up: string
/**
* @deprecated use agent_cycle_reverse. Previous agent
* Scroll messages down by half page
*/
switch_agent_reverse: string
messages_half_page_down: string
/**
* @deprecated Currently not available. List files
*/
file_list: string
/**
* @deprecated Close file
*/
file_close: string
/**
* @deprecated Search file
*/
file_search: string
/**
* @deprecated Split/unified diff
*/
file_diff_toggle: string
/**
* @deprecated Navigate to previous message
* Navigate to previous message
*/
messages_previous: string
/**
* @deprecated Navigate to next message
* Navigate to next message
*/
messages_next: string
/**
* @deprecated Toggle layout
* Navigate to first message
*/
messages_first: string
/**
* Navigate to last message
*/
messages_last: string
/**
* Toggle layout
*/
messages_layout_toggle: string
/**
* Copy message
*/
messages_copy: string
/**
* @deprecated use messages_undo. Revert message
*/
messages_revert: string
/**
* Undo message
*/
messages_undo: string
/**
* Redo message
*/
messages_redo: string
/**
* Exit the application
*/
app_exit: string
}
export type AgentConfig = {
@@ -948,16 +907,7 @@ export type AgentConfig = {
* Description of when to use the agent
*/
description?: string
mode?: "subagent" | "primary" | "all"
permission?: {
edit?: "ask" | "allow" | "deny"
bash?:
| ("ask" | "allow" | "deny")
| {
[key: string]: "ask" | "allow" | "deny"
}
webfetch?: "ask" | "allow" | "deny"
}
mode?: string
[key: string]:
| unknown
| string
@@ -966,16 +916,7 @@ export type AgentConfig = {
[key: string]: boolean
}
| boolean
| ("subagent" | "primary" | "all")
| {
edit?: "ask" | "allow" | "deny"
bash?:
| ("ask" | "allow" | "deny")
| {
[key: string]: "ask" | "allow" | "deny"
}
webfetch?: "ask" | "allow" | "deny"
}
| string
| undefined
}
@@ -1017,7 +958,7 @@ export type McpLocalConfig = {
/**
* Type of MCP server connection
*/
type: "local"
type: string
/**
* Command and arguments to run the MCP server
*/
@@ -1038,7 +979,7 @@ export type McpRemoteConfig = {
/**
* Type of MCP server connection
*/
type: "remote"
type: string
/**
* URL of the remote MCP server
*/
@@ -1065,7 +1006,7 @@ export type _Error = {
export type TextPartInput = {
id?: string
type: "text"
type: string
text: string
synthetic?: boolean
time?: {
@@ -1076,7 +1017,7 @@ export type TextPartInput = {
export type FilePartInput = {
id?: string
type: "file"
type: string
mime: string
filename?: string
url: string
@@ -1085,7 +1026,7 @@ export type FilePartInput = {
export type AgentPartInput = {
id?: string
type: "agent"
type: string
name: string
source?: {
value: string
@@ -1113,17 +1054,9 @@ export type File = {
export type Agent = {
name: string
description?: string
mode: "subagent" | "primary" | "all"
builtIn: boolean
mode: string
topP?: number
temperature?: number
permission: {
edit: "ask" | "allow" | "deny"
bash: {
[key: string]: "ask" | "allow" | "deny"
}
webfetch?: "ask" | "allow" | "deny"
}
model?: {
modelID: string
providerID: string
@@ -1137,35 +1070,6 @@ export type Agent = {
}
}
export type Auth =
| ({
type: "oauth"
} & OAuth)
| ({
type: "api"
} & ApiAuth)
| ({
type: "wellknown"
} & WellKnownAuth)
export type OAuth = {
type: "oauth"
refresh: string
access: string
expires: number
}
export type ApiAuth = {
type: "api"
key: string
}
export type WellKnownAuth = {
type: "wellknown"
key: string
token: string
}
export type EventSubscribeData = {
body?: never
path?: never
@@ -1247,10 +1151,7 @@ export type SessionListResponses = {
export type SessionListResponse = SessionListResponses[keyof SessionListResponses]
export type SessionCreateData = {
body?: {
parentID?: string
title?: string
}
body?: never
path?: never
query?: never
url: "/session"
@@ -1310,44 +1211,6 @@ export type SessionGetResponses = {
export type SessionGetResponse = SessionGetResponses[keyof SessionGetResponses]
export type SessionUpdateData = {
body?: {
title?: string
}
path: {
id: string
}
query?: never
url: "/session/{id}"
}
export type SessionUpdateResponses = {
/**
* Successfully updated session
*/
200: Session
}
export type SessionUpdateResponse = SessionUpdateResponses[keyof SessionUpdateResponses]
export type SessionChildrenData = {
body?: never
path: {
id: string
}
query?: never
url: "/session/{id}/children"
}
export type SessionChildrenResponses = {
/**
* List of children
*/
200: Array<Session>
}
export type SessionChildrenResponse = SessionChildrenResponses[keyof SessionChildrenResponses]
export type SessionInitData = {
body?: {
messageID: string
@@ -1544,30 +1407,6 @@ export type SessionMessageResponses = {
export type SessionMessageResponse = SessionMessageResponses[keyof SessionMessageResponses]
export type SessionShellData = {
body?: {
agent: string
command: string
}
path: {
/**
* Session ID
*/
id: string
}
query?: never
url: "/session/{id}/shell"
}
export type SessionShellResponses = {
/**
* Created message
*/
200: AssistantMessage
}
export type SessionShellResponse = SessionShellResponses[keyof SessionShellResponses]
export type SessionRevertData = {
body?: {
messageID: string
@@ -1940,53 +1779,6 @@ export type TuiExecuteCommandResponses = {
export type TuiExecuteCommandResponse = TuiExecuteCommandResponses[keyof TuiExecuteCommandResponses]
export type TuiShowToastData = {
body?: {
title?: string
message: string
variant: "info" | "success" | "warning" | "error"
}
path?: never
query?: never
url: "/tui/show-toast"
}
export type TuiShowToastResponses = {
/**
* Toast notification shown successfully
*/
200: boolean
}
export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses]
export type AuthSetData = {
body?: Auth
path: {
id: string
}
query?: never
url: "/auth/{id}"
}
export type AuthSetErrors = {
/**
* Bad request
*/
400: _Error
}
export type AuthSetError = AuthSetErrors[keyof AuthSetErrors]
export type AuthSetResponses = {
/**
* Successfully set authentication credentials
*/
200: boolean
}
export type AuthSetResponse = AuthSetResponses[keyof AuthSetResponses]
export type ClientOptions = {
baseUrl: `${string}://${string}` | (string & {})
}
-26
View File
@@ -2,34 +2,8 @@ import { createClient } from "./gen/client/client.js"
import { type Config } from "./gen/client/types.js"
import { OpencodeClient } from "./gen/sdk.gen.js"
export * from "./gen/types.gen.js"
import { spawn } from "child_process"
export function createOpencodeClient(config?: Config) {
const client = createClient(config)
return new OpencodeClient({ client })
}
export type ServerConfig = {
host?: string
port?: number
}
export async function createOpencodeServer(config?: ServerConfig) {
config = Object.assign(
{
host: "127.0.0.1",
port: 4096,
},
config ?? {},
)
const proc = spawn(`opencode`, [`serve`, `--host=${config.host}`, `--port=${config.port}`])
const url = `http://${config.host}:${config.port}`
return {
url,
close() {
proc.kill()
},
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ console.log("=== Generating Stainless SDK ===")
console.log(process.cwd())
await $`rm -rf go`
await $`bun run --conditions=development ../../opencode/src/index.ts generate > openapi.json`
await $`bun run ../../opencode/src/index.ts generate > openapi.json`
await $`stl builds create --branch dev --pull --allow-empty --+target go`
await $`rm -rf ../go`
-5
View File
@@ -113,9 +113,7 @@ resources:
toolStateError: ToolStateError
methods:
get: get /session/{id}
list: get /session
children: get /session/{id}/children
create: post /session
delete: delete /session/{id}
init: post /session/{id}/init
@@ -126,8 +124,6 @@ resources:
message: get /session/{id}/message/{messageID}
messages: get /session/{id}/message
chat: post /session/{id}/message
shell: post /session/{id}/shell
update: patch /session/{id}
revert: post /session/{id}/revert
unrevert: post /session/{id}/unrevert
@@ -148,7 +144,6 @@ resources:
openThemes: post /tui/open-themes
openModels: post /tui/open-models
executeCommand: post /tui/execute-command
showToast: post /tui/show-toast
settings:
disable_mock_tests: true
+10 -15
View File
@@ -32,7 +32,6 @@ func main() {
var model *string = flag.String("model", "", "model to begin with")
var prompt *string = flag.String("prompt", "", "prompt to begin with")
var agent *string = flag.String("agent", "", "agent to begin with")
var sessionID *string = flag.String("session", "", "session ID")
flag.Parse()
url := os.Getenv("OPENCODE_SERVER")
@@ -45,6 +44,14 @@ func main() {
os.Exit(1)
}
agentsStr := os.Getenv("OPENCODE_AGENTS")
var agents []opencode.Agent
err = json.Unmarshal([]byte(agentsStr), &agents)
if err != nil {
slog.Error("Failed to unmarshal modes", "error", err)
os.Exit(1)
}
stat, err := os.Stdin.Stat()
if err != nil {
slog.Error("Failed to stat stdin", "error", err)
@@ -73,25 +80,13 @@ func main() {
option.WithBaseURL(url),
)
// Fetch agents from the /agent endpoint
agentsPtr, err := httpClient.App.Agents(context.Background())
if err != nil {
slog.Error("Failed to fetch agents", "error", err)
os.Exit(1)
}
if agentsPtr == nil {
slog.Error("No agents returned from server")
os.Exit(1)
}
agents := *agentsPtr
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
apiHandler := util.NewAPILogHandler(ctx, httpClient, "tui", slog.LevelDebug)
logger := slog.New(apiHandler)
slog.SetDefault(logger)
slog.Debug("TUI launched", "app", appInfoStr, "agents_count", len(agents), "url", url)
slog.Debug("TUI launched", "app", appInfoStr, "modes", agentsStr, "url", url)
go func() {
err = clipboard.Init()
@@ -101,7 +96,7 @@ func main() {
}()
// Create main context for the application
app_, err := app.New(ctx, version, appInfo, agents, httpClient, model, prompt, agent, sessionID)
app_, err := app.New(ctx, version, appInfo, agents, httpClient, model, prompt, agent)
if err != nil {
panic(err)
}
+18 -220
View File
@@ -46,10 +46,8 @@ type App struct {
InitialModel *string
InitialPrompt *string
InitialAgent *string
InitialSession *string
compactCancel context.CancelFunc
IsLeaderSequence bool
IsBashMode bool
}
func (a *App) Agent() *opencode.Agent {
@@ -72,17 +70,9 @@ type ModelSelectedMsg struct {
Provider opencode.Provider
Model opencode.Model
}
type AgentSelectedMsg struct {
AgentName string
}
type SessionClearedMsg struct{}
type CompactSessionMsg struct{}
type SendPrompt = Prompt
type SendShell = struct {
Command string
}
type SetEditorContentMsg struct {
Text string
}
@@ -102,7 +92,6 @@ func New(
initialModel *string,
initialPrompt *string,
initialAgent *string,
initialSession *string,
) (*App, error) {
util.RootPath = appInfo.Path.Root
util.CwdPath = appInfo.Path.Cwd
@@ -183,21 +172,20 @@ func New(
slog.Debug("Loaded config", "config", configInfo)
app := &App{
Info: appInfo,
Agents: agents,
Version: version,
StatePath: appStatePath,
Config: configInfo,
State: appState,
Client: httpClient,
AgentIndex: agentIndex,
Session: &opencode.Session{},
Messages: []Message{},
Commands: commands.LoadFromConfig(configInfo),
InitialModel: initialModel,
InitialPrompt: initialPrompt,
InitialAgent: initialAgent,
InitialSession: initialSession,
Info: appInfo,
Agents: agents,
Version: version,
StatePath: appStatePath,
Config: configInfo,
State: appState,
Client: httpClient,
AgentIndex: agentIndex,
Session: &opencode.Session{},
Messages: []Message{},
Commands: commands.LoadFromConfig(configInfo),
InitialModel: initialModel,
InitialPrompt: initialPrompt,
InitialAgent: initialAgent,
}
return app, nil
@@ -278,7 +266,6 @@ func (a *App) cycleMode(forward bool) (*App, tea.Cmd) {
}
a.State.Agent = a.Agent().Name
a.State.UpdateAgentUsage(a.Agent().Name)
return a, a.SaveState()
}
@@ -290,110 +277,6 @@ func (a *App) SwitchAgentReverse() (*App, tea.Cmd) {
return a.cycleMode(false)
}
func (a *App) cycleRecentModel(forward bool) (*App, tea.Cmd) {
recentModels := a.State.RecentlyUsedModels
if len(recentModels) > 5 {
recentModels = recentModels[:5]
}
if len(recentModels) < 2 {
return a, toast.NewInfoToast("Need at least 2 recent models to cycle")
}
nextIndex := 0
prevIndex := 0
for i, recentModel := range recentModels {
if a.Provider != nil && a.Model != nil && recentModel.ProviderID == a.Provider.ID &&
recentModel.ModelID == a.Model.ID {
nextIndex = (i + 1) % len(recentModels)
prevIndex = (i - 1 + len(recentModels)) % len(recentModels)
break
}
}
targetIndex := nextIndex
if !forward {
targetIndex = prevIndex
}
for range recentModels {
currentRecentModel := recentModels[targetIndex%len(recentModels)]
provider, model := findModelByProviderAndModelID(
a.Providers,
currentRecentModel.ProviderID,
currentRecentModel.ModelID,
)
if provider != nil && model != nil {
a.Provider, a.Model = provider, model
a.State.AgentModel[a.Agent().Name] = AgentModel{
ProviderID: provider.ID,
ModelID: model.ID,
}
return a, tea.Sequence(
a.SaveState(),
toast.NewSuccessToast(
fmt.Sprintf("Switched to %s (%s)", model.Name, provider.Name),
),
)
}
recentModels = append(
recentModels[:targetIndex%len(recentModels)],
recentModels[targetIndex%len(recentModels)+1:]...)
if len(recentModels) < 2 {
a.State.RecentlyUsedModels = recentModels
return a, tea.Sequence(
a.SaveState(),
toast.NewInfoToast("Not enough valid recent models to cycle"),
)
}
}
a.State.RecentlyUsedModels = recentModels
return a, toast.NewErrorToast("Recent model not found")
}
func (a *App) CycleRecentModel() (*App, tea.Cmd) {
return a.cycleRecentModel(true)
}
func (a *App) CycleRecentModelReverse() (*App, tea.Cmd) {
return a.cycleRecentModel(false)
}
func (a *App) SwitchToAgent(agentName string) (*App, tea.Cmd) {
// Find the agent index by name
for i, agent := range a.Agents {
if agent.Name == agentName {
a.AgentIndex = i
break
}
}
// Set up model for the new agent
modelID := a.Agent().Model.ModelID
providerID := a.Agent().Model.ProviderID
if modelID == "" {
if model, ok := a.State.AgentModel[a.Agent().Name]; ok {
modelID = model.ModelID
providerID = model.ProviderID
}
}
if modelID != "" {
for _, provider := range a.Providers {
if provider.ID == providerID {
a.Provider = &provider
for _, model := range provider.Models {
if model.ID == modelID {
a.Model = &model
break
}
}
break
}
}
}
a.State.Agent = a.Agent().Name
a.State.UpdateAgentUsage(agentName)
return a, a.SaveState()
}
// findModelByFullID finds a model by its full ID in the format "provider/model"
func findModelByFullID(
providers []opencode.Provider,
@@ -498,27 +381,7 @@ func (a *App) InitializeProvider() tea.Cmd {
}
}
// Priority 3: Current agent's preferred model
if selectedProvider == nil && a.Agent().Model.ModelID != "" {
if provider, model := findModelByProviderAndModelID(providers, a.Agent().Model.ProviderID, a.Agent().Model.ModelID); provider != nil &&
model != nil {
selectedProvider = provider
selectedModel = model
slog.Debug(
"Selected model from current agent",
"provider",
provider.ID,
"model",
model.ID,
"agent",
a.Agent().Name,
)
} else {
slog.Debug("Agent model not found", "provider", a.Agent().Model.ProviderID, "model", a.Agent().Model.ModelID, "agent", a.Agent().Name)
}
}
// Priority 4: Recent model usage (most recently used model)
// Priority 3: Recent model usage (most recently used model)
if selectedProvider == nil && len(a.State.RecentlyUsedModels) > 0 {
recentUsage := a.State.RecentlyUsedModels[0] // Most recent is first
if provider, model := findModelByProviderAndModelID(providers, recentUsage.ProviderID, recentUsage.ModelID); provider != nil &&
@@ -537,7 +400,7 @@ func (a *App) InitializeProvider() tea.Cmd {
}
}
// Priority 5: State-based model (backwards compatibility)
// Priority 4: State-based model (backwards compatibility)
if selectedProvider == nil && a.State.Provider != "" && a.State.Model != "" {
if provider, model := findModelByProviderAndModelID(providers, a.State.Provider, a.State.Model); provider != nil &&
model != nil {
@@ -549,7 +412,7 @@ func (a *App) InitializeProvider() tea.Cmd {
}
}
// Priority 6: Internal priority fallback (Anthropic preferred, then first available)
// Priority 5: Internal priority fallback (Anthropic preferred, then first available)
if selectedProvider == nil {
// Try Anthropic first as internal priority
if provider := findProviderByID(providers, "anthropic"); provider != nil {
@@ -594,28 +457,6 @@ func (a *App) InitializeProvider() tea.Cmd {
Provider: *selectedProvider,
Model: *selectedModel,
}))
// Load initial session if provided
if a.InitialSession != nil && *a.InitialSession != "" {
cmds = append(cmds, func() tea.Msg {
// Find the session by ID
sessions, err := a.ListSessions(context.Background())
if err != nil {
slog.Error("Failed to list sessions for initial session", "error", err)
return toast.NewErrorToast("Failed to load initial session")()
}
for _, session := range sessions {
if session.ID == *a.InitialSession {
return SessionSelectedMsg(&session)
}
}
slog.Warn("Initial session not found", "sessionID", *a.InitialSession)
return toast.NewErrorToast("Session not found: " + *a.InitialSession)()
})
}
if a.InitialPrompt != nil && *a.InitialPrompt != "" {
cmds = append(cmds, util.CmdHandler(SendPrompt{Text: *a.InitialPrompt}))
}
@@ -645,7 +486,7 @@ func (a *App) IsBusy() bool {
if casted, ok := lastMessage.Info.(opencode.AssistantMessage); ok {
return casted.Time.Completed == 0
}
return false
return true
}
func (a *App) SaveState() tea.Cmd {
@@ -769,38 +610,6 @@ func (a *App) SendPrompt(ctx context.Context, prompt Prompt) (*App, tea.Cmd) {
return a, tea.Batch(cmds...)
}
func (a *App) SendShell(ctx context.Context, command string) (*App, tea.Cmd) {
var cmds []tea.Cmd
if a.Session.ID == "" {
session, err := a.CreateSession(ctx)
if err != nil {
return a, toast.NewErrorToast(err.Error())
}
a.Session = session
cmds = append(cmds, util.CmdHandler(SessionCreatedMsg{Session: session}))
}
cmds = append(cmds, func() tea.Msg {
_, err := a.Client.Session.Shell(
context.Background(),
a.Session.ID,
opencode.SessionShellParams{
Agent: opencode.F(a.Agent().Name),
Command: opencode.F(command),
},
)
if err != nil {
slog.Error("Failed to submit shell command", "error", err)
return toast.NewErrorToast("Failed to submit shell command")()
}
return nil
})
// The actual response will come through SSE
// For now, just return success
return a, tea.Batch(cmds...)
}
func (a *App) Cancel(ctx context.Context, sessionID string) error {
// Cancel any running compact operation
if a.compactCancel != nil {
@@ -837,17 +646,6 @@ func (a *App) DeleteSession(ctx context.Context, sessionID string) error {
return nil
}
func (a *App) UpdateSession(ctx context.Context, sessionID string, title string) error {
_, err := a.Client.Session.Update(ctx, sessionID, opencode.SessionUpdateParams{
Title: opencode.F(title),
})
if err != nil {
slog.Error("Failed to update session", "error", err)
return err
}
return nil
}
func (a *App) ListMessages(ctx context.Context, sessionId string) ([]Message, error) {
response, err := a.Client.Session.Messages(ctx, sessionId)
if err != nil {
+2 -45
View File
@@ -16,11 +16,6 @@ type ModelUsage struct {
LastUsed time.Time `toml:"last_used"`
}
type AgentUsage struct {
AgentName string `toml:"agent_name"`
LastUsed time.Time `toml:"last_used"`
}
type AgentModel struct {
ProviderID string `toml:"provider_id"`
ModelID string `toml:"model_id"`
@@ -34,10 +29,9 @@ type State struct {
Model string `toml:"model"`
Agent string `toml:"agent"`
RecentlyUsedModels []ModelUsage `toml:"recently_used_models"`
RecentlyUsedAgents []AgentUsage `toml:"recently_used_agents"`
MessagesRight bool `toml:"messages_right"`
SplitDiff bool `toml:"split_diff"`
MessageHistory []Prompt `toml:"message_history"`
ShowToolDetails *bool `toml:"show_tool_details"`
ShowThinkingBlocks *bool `toml:"show_thinking_blocks"`
}
func NewState() *State {
@@ -46,7 +40,6 @@ func NewState() *State {
Agent: "build",
AgentModel: make(map[string]AgentModel),
RecentlyUsedModels: make([]ModelUsage, 0),
RecentlyUsedAgents: make([]AgentUsage, 0),
MessageHistory: make([]Prompt, 0),
}
}
@@ -88,42 +81,6 @@ func (s *State) RemoveModelFromRecentlyUsed(providerID, modelID string) {
}
}
// UpdateAgentUsage updates the recently used agents list with the specified agent
func (s *State) UpdateAgentUsage(agentName string) {
now := time.Now()
// Check if this agent is already in the list
for i, usage := range s.RecentlyUsedAgents {
if usage.AgentName == agentName {
s.RecentlyUsedAgents[i].LastUsed = now
usage := s.RecentlyUsedAgents[i]
copy(s.RecentlyUsedAgents[1:i+1], s.RecentlyUsedAgents[0:i])
s.RecentlyUsedAgents[0] = usage
return
}
}
newUsage := AgentUsage{
AgentName: agentName,
LastUsed: now,
}
// Prepend to slice and limit to last 20 entries
s.RecentlyUsedAgents = append([]AgentUsage{newUsage}, s.RecentlyUsedAgents...)
if len(s.RecentlyUsedAgents) > 20 {
s.RecentlyUsedAgents = s.RecentlyUsedAgents[:20]
}
}
func (s *State) RemoveAgentFromRecentlyUsed(agentName string) {
for i, usage := range s.RecentlyUsedAgents {
if usage.AgentName == agentName {
s.RecentlyUsedAgents = append(s.RecentlyUsedAgents[:i], s.RecentlyUsedAgents[i+1:]...)
return
}
}
}
func (s *State) AddPromptToHistory(prompt Prompt) {
s.MessageHistory = append([]Prompt{prompt}, s.MessageHistory...)
if len(s.MessageHistory) > 50 {
+83 -81
View File
@@ -64,13 +64,12 @@ func (r CommandRegistry) Sorted() []Command {
commands = append(commands, command)
}
slices.SortFunc(commands, func(a, b Command) int {
// Priority order: session_new, session_share, model_list, agent_list, app_help first, app_exit last
// Priority order: session_new, session_share, model_list, app_help first, app_exit last
priorityOrder := map[CommandName]int{
SessionNewCommand: 0,
AppHelpCommand: 1,
SessionShareCommand: 2,
ModelListCommand: 3,
AgentListCommand: 4,
}
aPriority, aHasPriority := priorityOrder[a.Name]
@@ -107,41 +106,42 @@ func (r CommandRegistry) Matches(msg tea.KeyPressMsg, leader bool) []Command {
}
const (
AppHelpCommand CommandName = "app_help"
AppExitCommand CommandName = "app_exit"
ThemeListCommand CommandName = "theme_list"
ProjectInitCommand CommandName = "project_init"
EditorOpenCommand CommandName = "editor_open"
ToolDetailsCommand CommandName = "tool_details"
ThinkingBlocksCommand CommandName = "thinking_blocks"
SessionNewCommand CommandName = "session_new"
SessionListCommand CommandName = "session_list"
SessionShareCommand CommandName = "session_share"
SessionUnshareCommand CommandName = "session_unshare"
SessionInterruptCommand CommandName = "session_interrupt"
SessionCompactCommand CommandName = "session_compact"
SessionExportCommand CommandName = "session_export"
SessionChildCycleCommand CommandName = "session_child_cycle"
SessionChildCycleReverseCommand CommandName = "session_child_cycle_reverse"
MessagesPageUpCommand CommandName = "messages_page_up"
MessagesPageDownCommand CommandName = "messages_page_down"
MessagesHalfPageUpCommand CommandName = "messages_half_page_up"
MessagesHalfPageDownCommand CommandName = "messages_half_page_down"
MessagesFirstCommand CommandName = "messages_first"
MessagesLastCommand CommandName = "messages_last"
MessagesCopyCommand CommandName = "messages_copy"
MessagesUndoCommand CommandName = "messages_undo"
MessagesRedoCommand CommandName = "messages_redo"
ModelListCommand CommandName = "model_list"
ModelCycleRecentCommand CommandName = "model_cycle_recent"
ModelCycleRecentReverseCommand CommandName = "model_cycle_recent_reverse"
AgentListCommand CommandName = "agent_list"
AgentCycleCommand CommandName = "agent_cycle"
AgentCycleReverseCommand CommandName = "agent_cycle_reverse"
InputClearCommand CommandName = "input_clear"
InputPasteCommand CommandName = "input_paste"
InputSubmitCommand CommandName = "input_submit"
InputNewlineCommand CommandName = "input_newline"
AppHelpCommand CommandName = "app_help"
SwitchAgentCommand CommandName = "switch_agent"
SwitchAgentReverseCommand CommandName = "switch_agent_reverse"
EditorOpenCommand CommandName = "editor_open"
SessionNewCommand CommandName = "session_new"
SessionListCommand CommandName = "session_list"
SessionShareCommand CommandName = "session_share"
SessionUnshareCommand CommandName = "session_unshare"
SessionInterruptCommand CommandName = "session_interrupt"
SessionCompactCommand CommandName = "session_compact"
SessionExportCommand CommandName = "session_export"
ToolDetailsCommand CommandName = "tool_details"
ModelListCommand CommandName = "model_list"
ThemeListCommand CommandName = "theme_list"
FileListCommand CommandName = "file_list"
FileCloseCommand CommandName = "file_close"
FileSearchCommand CommandName = "file_search"
FileDiffToggleCommand CommandName = "file_diff_toggle"
ProjectInitCommand CommandName = "project_init"
InputClearCommand CommandName = "input_clear"
InputPasteCommand CommandName = "input_paste"
InputSubmitCommand CommandName = "input_submit"
InputNewlineCommand CommandName = "input_newline"
MessagesPageUpCommand CommandName = "messages_page_up"
MessagesPageDownCommand CommandName = "messages_page_down"
MessagesHalfPageUpCommand CommandName = "messages_half_page_up"
MessagesHalfPageDownCommand CommandName = "messages_half_page_down"
MessagesPreviousCommand CommandName = "messages_previous"
MessagesNextCommand CommandName = "messages_next"
MessagesFirstCommand CommandName = "messages_first"
MessagesLastCommand CommandName = "messages_last"
MessagesLayoutToggleCommand CommandName = "messages_layout_toggle"
MessagesCopyCommand CommandName = "messages_copy"
MessagesUndoCommand CommandName = "messages_undo"
MessagesRedoCommand CommandName = "messages_redo"
AppExitCommand CommandName = "app_exit"
)
func (k Command) Matches(msg tea.KeyPressMsg, leader bool) bool {
@@ -180,6 +180,16 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
Keybindings: parseBindings("<leader>h"),
Trigger: []string{"help"},
},
{
Name: SwitchAgentCommand,
Description: "next agent",
Keybindings: parseBindings("tab"),
},
{
Name: SwitchAgentReverseCommand,
Description: "previous agent",
Keybindings: parseBindings("shift+tab"),
},
{
Name: EditorOpenCommand,
Description: "open editor",
@@ -226,66 +236,45 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
Keybindings: parseBindings("<leader>c"),
Trigger: []string{"compact", "summarize"},
},
{
Name: SessionChildCycleCommand,
Description: "cycle to next child session",
Keybindings: parseBindings("ctrl+right"),
},
{
Name: SessionChildCycleReverseCommand,
Description: "cycle to previous child session",
Keybindings: parseBindings("ctrl+left"),
},
{
Name: ToolDetailsCommand,
Description: "toggle tool details",
Keybindings: parseBindings("<leader>d"),
Trigger: []string{"details"},
},
{
Name: ThinkingBlocksCommand,
Description: "toggle thinking blocks",
Keybindings: parseBindings("<leader>b"),
Trigger: []string{"thinking"},
},
{
Name: ModelListCommand,
Description: "list models",
Keybindings: parseBindings("<leader>m"),
Trigger: []string{"models"},
},
{
Name: ModelCycleRecentCommand,
Description: "next recent model",
Keybindings: parseBindings("f2"),
},
{
Name: ModelCycleRecentReverseCommand,
Description: "previous recent model",
Keybindings: parseBindings("shift+f2"),
},
{
Name: AgentListCommand,
Description: "list agents",
Keybindings: parseBindings("<leader>a"),
Trigger: []string{"agents"},
},
{
Name: AgentCycleCommand,
Description: "next agent",
Keybindings: parseBindings("tab"),
},
{
Name: AgentCycleReverseCommand,
Description: "previous agent",
Keybindings: parseBindings("shift+tab"),
},
{
Name: ThemeListCommand,
Description: "list themes",
Keybindings: parseBindings("<leader>t"),
Trigger: []string{"themes"},
},
// {
// Name: FileListCommand,
// Description: "list files",
// Keybindings: parseBindings("<leader>f"),
// Trigger: []string{"files"},
// },
{
Name: FileCloseCommand,
Description: "close file",
Keybindings: parseBindings("esc"),
},
{
Name: FileSearchCommand,
Description: "search file",
Keybindings: parseBindings("<leader>/"),
},
{
Name: FileDiffToggleCommand,
Description: "split/unified diff",
Keybindings: parseBindings("<leader>v"),
},
{
Name: ProjectInitCommand,
Description: "create/update AGENTS.md",
@@ -332,7 +321,16 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
Description: "half page down",
Keybindings: parseBindings("ctrl+alt+d"),
},
{
Name: MessagesPreviousCommand,
Description: "previous message",
Keybindings: parseBindings("ctrl+up"),
},
{
Name: MessagesNextCommand,
Description: "next message",
Keybindings: parseBindings("ctrl+down"),
},
{
Name: MessagesFirstCommand,
Description: "first message",
@@ -343,7 +341,11 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
Description: "last message",
Keybindings: parseBindings("ctrl+alt+g"),
},
{
Name: MessagesLayoutToggleCommand,
Description: "toggle layout",
Keybindings: parseBindings("<leader>p"),
},
{
Name: MessagesCopyCommand,
Description: "copy message",
+159 -74
View File
@@ -27,11 +27,54 @@ import (
"github.com/sst/opencode/internal/util"
)
type AttachmentInsertedMsg struct{}
// unescapeClipboardText trims surrounding quotes from clipboard text and returns the inner content.
// It avoids interpreting backslash escape sequences unless the text is explicitly quoted.
func (m *editorComponent) unescapeClipboardText(s string) string {
t := strings.TrimSpace(s)
if len(t) >= 2 {
first := t[0]
last := t[len(t)-1]
if (first == '"' && last == '"') || (first == '\'' && last == '\'') {
if u, err := strconv.Unquote(t); err == nil {
return u
}
return t[1 : len(t)-1]
}
}
return t
}
// pathExists checks if the given path exists. Relative paths are resolved against the app CWD.
// Supports expanding '~' to the user's home directory.
func (m *editorComponent) pathExists(p string) bool {
if p == "" {
return false
}
if strings.HasPrefix(p, "~") {
if home, err := os.UserHomeDir(); err == nil {
if p == "~" {
p = home
} else if strings.HasPrefix(p, "~/") {
p = filepath.Join(home, p[2:])
}
}
}
check := p
if !filepath.IsAbs(check) {
check = filepath.Join(m.app.Info.Path.Cwd, check)
}
if _, err := os.Stat(check); err == nil {
return true
}
return false
}
type EditorComponent interface {
tea.Model
tea.ViewModel
Content() string
Cursor() *tea.Cursor
Lines() int
Value() string
Length() int
@@ -39,7 +82,6 @@ type EditorComponent interface {
Focus() (tea.Model, tea.Cmd)
Blur()
Submit() (tea.Model, tea.Cmd)
SubmitBash() (tea.Model, tea.Cmd)
Clear() (tea.Model, tea.Cmd)
Paste() (tea.Model, tea.Cmd)
Newline() (tea.Model, tea.Cmd)
@@ -155,60 +197,123 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
}
case tea.PasteMsg:
text := string(msg)
// Normalize clipboard text first
textRaw := string(msg)
text := m.unescapeClipboardText(textRaw)
if filePath := strings.TrimSpace(strings.TrimPrefix(text, "@")); strings.HasPrefix(text, "@") && filePath != "" {
statPath := filePath
if !filepath.IsAbs(filePath) {
statPath = filepath.Join(m.app.Info.Path.Cwd, filePath)
// Case 1: pasted content contains one or more inline @paths -> insert attachments inline
// We scan the raw pasted text to preserve original content around attachments.
if strings.Contains(textRaw, "@") {
last := 0
idx := 0
inserted := 0
for idx < len(textRaw) {
r, size := utf8.DecodeRuneInString(textRaw[idx:])
if r != '@' {
idx += size
continue
}
// Insert preceding chunk before attempting to consume a path
if idx > last {
m.textarea.InsertRunesFromUserInput([]rune(textRaw[last:idx]))
}
// Extract candidate path after '@' up to whitespace
start := idx + size
end := start
for end < len(textRaw) {
nr, ns := utf8.DecodeRuneInString(textRaw[end:])
if nr == ' ' || nr == '\t' || nr == '\n' || nr == '\r' {
break
}
end += ns
}
if end > start {
raw := textRaw[start:end]
// Trim common trailing punctuation that may follow paths in prose
trimmed := strings.TrimRight(raw, ",.;:)]}\\\"'?!")
suffix := raw[len(trimmed):]
p := filepath.Clean(trimmed)
if m.pathExists(p) {
att := m.createAttachmentFromPath(p)
if att != nil {
m.textarea.InsertAttachment(att)
if suffix != "" {
m.textarea.InsertRunesFromUserInput([]rune(suffix))
}
// Insert a trailing space only if the next rune isn't already whitespace
insertSpace := true
if end < len(textRaw) {
nr, _ := utf8.DecodeRuneInString(textRaw[end:])
if nr == ' ' || nr == '\t' || nr == '\n' || nr == '\r' {
insertSpace = false
}
}
if insertSpace {
m.textarea.InsertString(" ")
}
inserted++
last = end
idx = end
continue
}
}
}
// No valid path -> keep the '@' literally
m.textarea.InsertRune('@')
last = start
idx = start
}
if _, err := os.Stat(statPath); err == nil {
attachment := m.createAttachmentFromPath(filePath)
if attachment != nil {
m.textarea.InsertAttachment(attachment)
// Insert any trailing content after the last processed segment
if last < len(textRaw) {
m.textarea.InsertRunesFromUserInput([]rune(textRaw[last:]))
}
if inserted > 0 {
return m, util.CmdHandler(AttachmentInsertedMsg{})
}
}
// Case 2: user typed '@' and then pasted a valid path -> replace '@' with attachment
at := m.textarea.LastRuneIndex('@')
if at != -1 && at == m.textarea.CursorColumn()-1 {
p := filepath.Clean(text)
if m.pathExists(p) {
cur := m.textarea.CursorColumn()
m.textarea.ReplaceRange(at, cur, "")
att := m.createAttachmentFromPath(p)
if att != nil {
m.textarea.InsertAttachment(att)
m.textarea.InsertString(" ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
}
}
}
text = strings.ReplaceAll(text, "\\", "")
text, err := strconv.Unquote(`"` + text + `"`)
if err != nil {
slog.Error("Failed to unquote text", "error", err)
text := string(msg)
if m.shouldSummarizePastedText(text) {
m.handleLongPaste(text)
} else {
m.textarea.InsertRunesFromUserInput([]rune(msg))
// Case 3: plain path pasted (e.g., drag-and-drop) -> attach if image or PDF
{
p := filepath.Clean(text)
if m.pathExists(p) {
mime := getMediaTypeFromExtension(strings.ToLower(filepath.Ext(p)))
if strings.HasPrefix(mime, "image/") || mime == "application/pdf" {
if att := m.createAttachmentFromFile(p); att != nil {
m.textarea.InsertAttachment(att)
m.textarea.InsertString(" ")
return m, util.CmdHandler(AttachmentInsertedMsg{})
}
}
}
return m, nil
}
if _, err := os.Stat(text); err != nil {
slog.Error("Failed to paste file", "error", err)
text := string(msg)
if m.shouldSummarizePastedText(text) {
m.handleLongPaste(text)
} else {
m.textarea.InsertRunesFromUserInput([]rune(msg))
}
return m, nil
}
filePath := text
attachment := m.createAttachmentFromFile(filePath)
if attachment == nil {
if m.shouldSummarizePastedText(text) {
m.handleLongPaste(text)
} else {
m.textarea.InsertRunesFromUserInput([]rune(msg))
}
// Default: do not auto-convert. Insert raw text or summarize long pastes.
if m.shouldSummarizePastedText(textRaw) {
m.handleLongPaste(textRaw)
return m, nil
}
m.textarea.InsertAttachment(attachment)
m.textarea.InsertString(" ")
m.textarea.InsertRunesFromUserInput([]rune(textRaw))
return m, nil
case tea.ClipboardMsg:
text := string(msg)
// Check if the pasted text is long and should be summarized
@@ -235,7 +340,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if atIndex == -1 {
// Should not happen, but as a fallback, just insert.
m.textarea.InsertString(msg.Item.Value + " ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
}
// The range to replace is from the '@' up to the current cursor position.
@@ -249,13 +354,13 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
attachment := m.createAttachmentFromPath(filePath)
m.textarea.InsertAttachment(attachment)
m.textarea.InsertString(" ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
case "symbols":
atIndex := m.textarea.LastRuneIndex('@')
if atIndex == -1 {
// Should not happen, but as a fallback, just insert.
m.textarea.InsertString(msg.Item.Value + " ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
}
cursorCol := m.textarea.CursorColumn()
@@ -289,13 +394,13 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
m.textarea.InsertAttachment(attachment)
m.textarea.InsertString(" ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
case "agents":
atIndex := m.textarea.LastRuneIndex('@')
if atIndex == -1 {
// Should not happen, but as a fallback, just insert.
m.textarea.InsertString(msg.Item.Value + " ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
}
cursorCol := m.textarea.CursorColumn()
@@ -313,8 +418,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.textarea.InsertAttachment(attachment)
m.textarea.InsertString(" ")
return m, nil
return m, util.CmdHandler(AttachmentInsertedMsg{})
default:
slog.Debug("Unknown provider", "provider", msg.Item.ProviderID)
return m, nil
@@ -343,14 +447,6 @@ func (m *editorComponent) Content() string {
Padding(0, 0, 0, 1).
Bold(true)
prompt := promptStyle.Render(">")
borderForeground := t.Border()
if m.app.IsLeaderSequence {
borderForeground = t.Accent()
}
if m.app.IsBashMode {
borderForeground = t.Secondary()
prompt = promptStyle.Render("!")
}
m.textarea.SetWidth(width - 6)
textarea := lipgloss.JoinHorizontal(
@@ -358,6 +454,10 @@ func (m *editorComponent) Content() string {
prompt,
m.textarea.View(),
)
borderForeground := t.Border()
if m.app.IsLeaderSequence {
borderForeground = t.Accent()
}
textarea = styles.NewStyle().
Background(t.BackgroundElement()).
Width(width).
@@ -413,10 +513,6 @@ func (m *editorComponent) Content() string {
return content
}
func (m *editorComponent) Cursor() *tea.Cursor {
return m.textarea.Cursor()
}
func (m *editorComponent) View() string {
width := m.width
if m.app.Session.ID == "" {
@@ -494,16 +590,6 @@ func (m *editorComponent) Submit() (tea.Model, tea.Cmd) {
return m, tea.Batch(cmds...)
}
func (m *editorComponent) SubmitBash() (tea.Model, tea.Cmd) {
command := m.textarea.Value()
var cmds []tea.Cmd
updated, cmd := m.Clear()
m = updated.(*editorComponent)
cmds = append(cmds, cmd)
cmds = append(cmds, util.CmdHandler(app.SendShell{Command: command}))
return m, tea.Batch(cmds...)
}
func (m *editorComponent) Clear() (tea.Model, tea.Cmd) {
m.textarea.Reset()
m.historyIndex = -1
@@ -714,7 +800,6 @@ func NewEditorComponent(app *app.App) EditorComponent {
ta.Prompt = " "
ta.ShowLineNumbers = false
ta.CharLimit = -1
ta.VirtualCursor = false
ta = updateTextareaStyles(ta)
m := &editorComponent{
@@ -0,0 +1,277 @@
package chat
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/charmbracelet/bubbles/v2/spinner"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/completions"
"github.com/sst/opencode/internal/components/dialog"
"github.com/sst/opencode/internal/components/textarea"
"github.com/sst/opencode/internal/styles"
)
func newTestEditor() *editorComponent {
m := &editorComponent{
app: &app.App{},
textarea: textarea.New(),
spinner: spinner.New(),
}
return m
}
func TestPasteAtPathWithTrailingComma_PreservesPunctuation_NoDoubleSpace(t *testing.T) {
m := newTestEditor()
p := createTempTextFile(t, "", "pc.txt", "x")
paste := "See @" + p + ", next"
_, cmd := m.Update(tea.PasteMsg(paste))
if cmd == nil {
t.Fatalf("expected command to be returned for comma punctuation paste")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg for comma punctuation paste")
}
if len(m.textarea.GetAttachments()) != 1 {
t.Fatalf("expected 1 attachment, got %d", len(m.textarea.GetAttachments()))
}
v := m.Value()
if !strings.Contains(v, ", next") {
t.Fatalf("expected comma and following text to be preserved, got: %q", v)
}
if strings.Contains(v, ", next") {
t.Fatalf("did not expect double space after comma, got: %q", v)
}
}
func TestPasteAtPathWithTrailingQuestion_PreservesPunctuation_NoDoubleSpace(t *testing.T) {
m := newTestEditor()
p := createTempTextFile(t, "", "pq.txt", "x")
paste := "Check @" + p + "? Done"
_, cmd := m.Update(tea.PasteMsg(paste))
if cmd == nil {
t.Fatalf("expected command to be returned for question punctuation paste")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg for question punctuation paste")
}
if len(m.textarea.GetAttachments()) != 1 {
t.Fatalf("expected 1 attachment, got %d", len(m.textarea.GetAttachments()))
}
v := m.Value()
if !strings.Contains(v, "? Done") {
t.Fatalf("expected question mark and following text to be preserved, got: %q", v)
}
if strings.Contains(v, "? Done") {
t.Fatalf("did not expect double space after question mark, got: %q", v)
}
}
func TestPasteMultipleInlineAtPaths_AttachesEach(t *testing.T) {
m := newTestEditor()
dir := t.TempDir()
p1 := createTempTextFile(t, dir, "m1.txt", "one")
p2 := createTempTextFile(t, dir, "m2.txt", "two")
// Build a paste with text around, two @paths, and punctuation after the first
paste := "Please check @" + p1 + ", and also @" + p2 + " thanks"
_, cmd := m.Update(tea.PasteMsg(paste))
if cmd == nil {
t.Fatalf("expected command to be returned for multi inline paste")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg for multi inline paste")
}
atts := m.textarea.GetAttachments()
if len(atts) != 2 {
t.Fatalf("expected 2 attachments, got %d", len(atts))
}
v := m.Value()
if !strings.Contains(v, "Please check") || !strings.Contains(v, "and also") || !strings.Contains(v, "thanks") {
t.Fatalf("expected surrounding text to be preserved, got: %q", v)
}
}
func createTempTextFile(t *testing.T, dir, name, content string) string {
t.Helper()
if dir == "" {
td, err := os.MkdirTemp("", "editor-test-*")
if err != nil {
t.Fatalf("failed to make temp dir: %v", err)
}
dir = td
}
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatalf("failed to write temp file: %v", err)
}
abs, err := filepath.Abs(p)
if err != nil {
t.Fatalf("failed to get abs path: %v", err)
}
return abs
}
func createTempBinFile(t *testing.T, dir, name string, data []byte) string {
t.Helper()
if dir == "" {
td, err := os.MkdirTemp("", "editor-test-*")
if err != nil {
t.Fatalf("failed to make temp dir: %v", err)
}
dir = td
}
p := filepath.Join(dir, name)
if err := os.WriteFile(p, data, 0o600); err != nil {
t.Fatalf("failed to write temp bin file: %v", err)
}
abs, err := filepath.Abs(p)
if err != nil {
t.Fatalf("failed to get abs path: %v", err)
}
return abs
}
func TestPasteStartsWithAt_AttachesAndEmitsMsg(t *testing.T) {
m := newTestEditor()
p := createTempTextFile(t, "", "a.txt", "hello")
_, cmd := m.Update(tea.PasteMsg("@" + p))
if cmd == nil {
t.Fatalf("expected command to be returned")
}
msg := cmd()
if _, ok := msg.(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg, got %T", msg)
}
atts := m.textarea.GetAttachments()
if len(atts) != 1 {
t.Fatalf("expected 1 attachment, got %d", len(atts))
}
if v := m.Value(); !strings.HasSuffix(v, " ") {
t.Fatalf("expected trailing space after attachment, got value: %q", v)
}
}
func TestPasteAfterAt_ReplacesAtWithAttachment(t *testing.T) {
m := newTestEditor()
p := createTempTextFile(t, "", "b.txt", "hello")
m.textarea.SetValue("@")
// Cursor should be at the end after SetValue; paste absolute path
_, cmd := m.Update(tea.PasteMsg(p))
if cmd == nil {
t.Fatalf("expected command to be returned")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg from paste after '@'")
}
// Ensure the raw '@' rune was removed (attachment inserted in its place)
if m.textarea.LastRuneIndex('@') != -1 {
t.Fatalf("'@' rune should have been removed from the text slice")
}
if len(m.textarea.GetAttachments()) != 1 {
t.Fatalf("expected 1 attachment inserted")
}
if v := m.Value(); !strings.HasSuffix(v, " ") {
t.Fatalf("expected trailing space after attachment, got value: %q", v)
}
}
func TestPlainTextPaste_NoAttachment_NoMsg(t *testing.T) {
m := newTestEditor()
_, cmd := m.Update(tea.PasteMsg("hello"))
if cmd != nil {
t.Fatalf("expected no command for plain text paste")
}
if got := m.Value(); got != "hello" {
t.Fatalf("expected value 'hello', got %q", got)
}
if len(m.textarea.GetAttachments()) != 0 {
t.Fatalf("expected no attachments for plain text paste")
}
}
func TestPlainPathPng_AttachesImage(t *testing.T) {
m := newTestEditor()
// Minimal bytes; content isn't validated, extension determines mime
p := createTempBinFile(t, "", "img.png", []byte{0x89, 'P', 'N', 'G'})
_, cmd := m.Update(tea.PasteMsg(p))
if cmd == nil {
t.Fatalf("expected command to be returned for image path paste")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg for image path paste")
}
atts := m.textarea.GetAttachments()
if len(atts) != 1 {
t.Fatalf("expected 1 attachment, got %d", len(atts))
}
if atts[0].MediaType != "image/png" {
t.Fatalf("expected image/png mime, got %q", atts[0].MediaType)
}
if v := m.Value(); !strings.HasSuffix(v, " ") {
t.Fatalf("expected trailing space after attachment, got value: %q", v)
}
}
func TestPlainPathPdf_AttachesPDF(t *testing.T) {
m := newTestEditor()
p := createTempBinFile(t, "", "doc.pdf", []byte("%PDF-1.4"))
_, cmd := m.Update(tea.PasteMsg(p))
if cmd == nil {
t.Fatalf("expected command to be returned for pdf path paste")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg for pdf path paste")
}
atts := m.textarea.GetAttachments()
if len(atts) != 1 {
t.Fatalf("expected 1 attachment, got %d", len(atts))
}
if atts[0].MediaType != "application/pdf" {
t.Fatalf("expected application/pdf mime, got %q", atts[0].MediaType)
}
if v := m.Value(); !strings.HasSuffix(v, " ") {
t.Fatalf("expected trailing space after attachment, got value: %q", v)
}
}
func TestCompletionFiles_InsertsAttachment_EmitsMsg(t *testing.T) {
m := newTestEditor()
p := createTempTextFile(t, "", "c.txt", "hello")
m.textarea.SetValue("@")
item := completions.CompletionSuggestion{
ProviderID: "files",
Value: p,
Display: func(_ styles.Style) string { return p },
}
// Build the completion selected message as if the user selected from the dialog
msg := dialog.CompletionSelectedMsg{Item: item, SearchString: "@"}
_, cmd := m.Update(msg)
if cmd == nil {
t.Fatalf("expected command to be returned")
}
if _, ok := cmd().(AttachmentInsertedMsg); !ok {
t.Fatalf("expected AttachmentInsertedMsg from files completion selection")
}
if len(m.textarea.GetAttachments()) != 1 {
t.Fatalf("expected 1 attachment inserted from completion selection")
}
if v := m.Value(); !strings.HasSuffix(v, " ") {
t.Fatalf("expected trailing space after attachment, got value: %q", v)
}
}
@@ -14,7 +14,6 @@ import (
"github.com/muesli/reflow/truncate"
"github.com/sst/opencode-sdk-go"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/commands"
"github.com/sst/opencode/internal/components/diff"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
@@ -184,8 +183,6 @@ func renderContentBlock(
if renderer.borderRight {
style = style.BorderRightForeground(borderColor)
}
} else {
style = style.PaddingLeft(renderer.paddingLeft + 1).PaddingRight(renderer.paddingRight + 1)
}
content = style.Render(content)
@@ -212,7 +209,6 @@ func renderText(
width int,
extra string,
isThinking bool,
isQueued bool,
fileParts []opencode.FilePart,
agentParts []opencode.AgentPart,
toolCalls ...opencode.ToolPart,
@@ -224,17 +220,14 @@ func renderText(
var content string
switch casted := message.(type) {
case opencode.AssistantMessage:
backgroundColor = t.Background()
bg := t.Background()
if isThinking {
backgroundColor = t.BackgroundPanel()
bg = t.BackgroundPanel()
}
ts = time.UnixMilli(int64(casted.Time.Created))
if casted.Time.Completed > 0 {
ts = time.UnixMilli(int64(casted.Time.Completed))
}
content = util.ToMarkdown(text, width, backgroundColor)
content = util.ToMarkdown(text, width, bg)
if isThinking {
content = styles.NewStyle().Background(backgroundColor).Foreground(t.TextMuted()).Render("Thinking") + "\n\n" + content
content = styles.NewStyle().Background(bg).Foreground(t.TextMuted()).Render("Thinking") + "\n\n" + content
}
case opencode.UserMessage:
ts = time.UnixMilli(int64(casted.Time.Created))
@@ -329,14 +322,8 @@ func renderText(
// wrap styled text
styledText := result.String()
styledText = strings.ReplaceAll(styledText, "-", "\u2011")
wrappedText := ansi.WordwrapWc(styledText, width-6, " ")
wrappedText = strings.ReplaceAll(wrappedText, "\u2011", "-")
wrappedText := ansi.WordwrapWc(styledText, width-6, " -")
content = base.Width(width - 6).Render(wrappedText)
if isQueued {
queuedStyle := styles.NewStyle().Background(t.Accent()).Foreground(t.BackgroundPanel()).Bold(true).Padding(0, 1)
content = queuedStyle.Render("QUEUED") + "\n\n" + content
}
}
timestamp := ts.
@@ -345,12 +332,8 @@ func renderText(
if time.Now().Format("02 Jan 2006") == timestamp[:11] {
timestamp = timestamp[12:]
}
timestamp = styles.NewStyle().
Background(backgroundColor).
Foreground(t.TextMuted()).
Render(" (" + timestamp + ")")
// Check if this is an assistant message with agent information
// Check if this is an assistant message with mode (agent) information
var modelAndAgentSuffix string
if assistantMsg, ok := message.(opencode.AssistantMessage); ok && assistantMsg.Mode != "" {
// Find the agent index by name to get the correct color
@@ -366,25 +349,22 @@ func renderText(
agentColor := util.GetAgentColor(agentIndex)
// Style the agent name with the same color as status bar
agentName := cases.Title(language.Und).String(assistantMsg.Mode)
styledAgentName := styles.NewStyle().
Background(backgroundColor).
Foreground(agentColor).
Render(agentName + " ")
styledModelID := styles.NewStyle().
Background(backgroundColor).
Foreground(t.TextMuted()).
Render(assistantMsg.ModelID)
modelAndAgentSuffix = styledAgentName + styledModelID
agentName := strings.Title(assistantMsg.Mode)
styledAgentName := styles.NewStyle().Foreground(agentColor).Bold(true).Render(agentName)
modelAndAgentSuffix = fmt.Sprintf(" | %s | %s", assistantMsg.ModelID, styledAgentName)
}
var info string
if modelAndAgentSuffix != "" {
info = modelAndAgentSuffix + timestamp
// For assistant messages: "timestamp | modelID | agentName"
info = fmt.Sprintf("%s%s", timestamp, modelAndAgentSuffix)
} else {
info = author + timestamp
// For user messages: "author (timestamp)"
info = fmt.Sprintf("%s (%s)", author, timestamp)
}
info = styles.NewStyle().Foreground(t.TextMuted()).Render(info)
if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
content = content + "\n\n"
for _, toolCall := range toolCalls {
title := renderToolTitle(toolCall, width-2)
style := styles.NewStyle()
@@ -392,30 +372,25 @@ func renderText(
style = style.Foreground(t.Error())
}
title = style.Render(title)
title = "\n∟ " + title
title = "∟ " + title + "\n"
content = content + title
}
}
sections := []string{content}
sections := []string{content, info}
if extra != "" {
sections = append(sections, "\n"+extra+"\n")
sections = append(sections, "\n"+extra)
}
sections = append(sections, info)
content = strings.Join(sections, "\n")
switch message.(type) {
case opencode.UserMessage:
borderColor := t.Secondary()
if isQueued {
borderColor = t.Accent()
}
return renderContentBlock(
app,
content,
width,
WithTextColor(t.Text()),
WithBorderColor(borderColor),
WithBorderColor(t.Secondary()),
)
case opencode.AssistantMessage:
if isThinking {
@@ -480,8 +455,6 @@ func renderToolDetails(
backgroundColor := t.BackgroundPanel()
borderColor := t.BackgroundPanel()
defaultStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6).Render
baseStyle := styles.NewStyle().Background(backgroundColor).Foreground(t.Text()).Render
mutedStyle := styles.NewStyle().Background(backgroundColor).Foreground(t.TextMuted()).Render
permissionContent := ""
if permission.ID != "" {
@@ -566,17 +539,6 @@ func renderToolDetails(
title := renderToolTitle(toolCall, width)
title = style.Render(title)
content := title + "\n" + body
if toolCall.State.Status == opencode.ToolPartStateStatusError {
errorStyle := styles.NewStyle().
Background(backgroundColor).
Foreground(t.Error()).
Padding(1, 2).
Width(width - 4)
errorContent := errorStyle.Render(toolCall.State.Error)
content += "\n" + errorContent
}
if permissionContent != "" {
permissionContent = styles.NewStyle().
Background(backgroundColor).
@@ -605,15 +567,14 @@ func renderToolDetails(
}
}
case "bash":
if command, ok := toolInputMap["command"].(string); ok {
body = fmt.Sprintf("```console\n$ %s\n", command)
output := metadata["output"]
if output != nil {
body += ansi.Strip(fmt.Sprintf("%s", output))
}
body += "```"
body = util.ToMarkdown(body, width, backgroundColor)
command := toolInputMap["command"].(string)
body = fmt.Sprintf("```console\n$ %s\n", command)
output := metadata["output"]
if output != nil {
body += ansi.Strip(fmt.Sprintf("%s", output))
}
body += "```"
body = util.ToMarkdown(body, width, backgroundColor)
case "webfetch":
if format, ok := toolInputMap["format"].(string); ok && result != nil {
body = *result
@@ -657,12 +618,6 @@ func renderToolDetails(
steps = append(steps, step)
}
body = strings.Join(steps, "\n")
body += "\n\n"
body += baseStyle(app.Keybind(commands.SessionChildCycleCommand)) +
mutedStyle(", ") +
baseStyle(app.Keybind(commands.SessionChildCycleReverseCommand)) +
mutedStyle(" navigate child sessions")
}
body = defaultStyle(body)
default:
@@ -682,17 +637,11 @@ func renderToolDetails(
}
if error != "" {
errorContent := styles.NewStyle().
body = styles.NewStyle().
Width(width - 6).
Foreground(t.Error()).
Background(backgroundColor).
Render(error)
if body == "" {
body = errorContent
} else {
body += "\n\n" + errorContent
}
}
if body == "" && error == "" && result != nil {
@@ -723,8 +672,6 @@ func renderToolDetails(
func renderToolName(name string) string {
switch name {
case "bash":
return "Shell"
case "webfetch":
return "Fetch"
case "invalid":
+116 -156
View File
@@ -33,7 +33,6 @@ type MessagesComponent interface {
HalfPageUp() (tea.Model, tea.Cmd)
HalfPageDown() (tea.Model, tea.Cmd)
ToolDetailsVisible() bool
ThinkingBlocksVisible() bool
GotoTop() (tea.Model, tea.Cmd)
GotoBottom() (tea.Model, tea.Cmd)
CopyLastMessage() (tea.Model, tea.Cmd)
@@ -42,21 +41,20 @@ type MessagesComponent interface {
}
type messagesComponent struct {
width, height int
app *app.App
header string
viewport viewport.Model
clipboard []string
cache *PartCache
loading bool
showToolDetails bool
showThinkingBlocks bool
rendering bool
dirty bool
tail bool
partCount int
lineCount int
selection *selection
width, height int
app *app.App
header string
viewport viewport.Model
clipboard []string
cache *PartCache
loading bool
showToolDetails bool
rendering bool
dirty bool
tail bool
partCount int
lineCount int
selection *selection
}
type selection struct {
@@ -96,7 +94,6 @@ func (s selection) coords(offset int) *selection {
}
type ToggleToolDetailsMsg struct{}
type ToggleThinkingBlocksMsg struct{}
func (m *messagesComponent) Init() tea.Cmd {
return tea.Batch(m.viewport.Init())
@@ -163,12 +160,7 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, m.renderView()
case ToggleToolDetailsMsg:
m.showToolDetails = !m.showToolDetails
m.app.State.ShowToolDetails = &m.showToolDetails
return m, tea.Batch(m.renderView(), m.app.SaveState())
case ToggleThinkingBlocksMsg:
m.showThinkingBlocks = !m.showThinkingBlocks
m.app.State.ShowThinkingBlocks = &m.showThinkingBlocks
return m, tea.Batch(m.renderView(), m.app.SaveState())
return m, m.renderView()
case app.SessionLoadedMsg, app.SessionClearedMsg:
m.cache.Clear()
m.tail = true
@@ -180,8 +172,6 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.tail = true
return m, m.renderView()
}
case app.SessionSelectedMsg:
m.viewport.GotoBottom()
case app.MessageRevertedMsg:
if msg.Session.ID == m.app.Session.ID {
m.cache.Clear()
@@ -197,19 +187,10 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.Properties.Info.SessionID == m.app.Session.ID {
cmds = append(cmds, m.renderView())
}
case opencode.EventListResponseEventSessionError:
if msg.Properties.SessionID == m.app.Session.ID {
cmds = append(cmds, m.renderView())
}
case opencode.EventListResponseEventMessagePartUpdated:
if msg.Properties.Part.SessionID == m.app.Session.ID {
cmds = append(cmds, m.renderView())
}
case opencode.EventListResponseEventMessageRemoved:
if msg.Properties.SessionID == m.app.Session.ID {
m.cache.Clear()
cmds = append(cmds, m.renderView())
}
case opencode.EventListResponseEventMessagePartRemoved:
if msg.Properties.SessionID == m.app.Session.ID {
// Clear the cache when a part is removed to ensure proper re-rendering
@@ -304,7 +285,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
for _, message := range m.app.Messages {
var content string
var cached bool
error := ""
switch casted := message.Info.(type) {
case opencode.UserMessage:
@@ -375,8 +355,10 @@ func (m *messagesComponent) renderView() tea.Cmd {
)
author := m.app.Config.Username
isQueued := casted.ID > lastAssistantMessage
key := m.cache.GenerateKey(casted.ID, part.Text, width, files, author, isQueued)
if casted.ID > lastAssistantMessage {
author += " [queued]"
}
key := m.cache.GenerateKey(casted.ID, part.Text, width, files, author)
content, cached = m.cache.Get(key)
if !cached {
content = renderText(
@@ -388,10 +370,15 @@ func (m *messagesComponent) renderView() tea.Cmd {
width,
files,
false,
isQueued,
fileParts,
agentParts,
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
m.cache.Set(key, content)
}
if content != "" {
@@ -409,7 +396,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
revertedToolCount = 0
}
hasTextPart := false
hasContent := false
for partIndex, p := range message.Parts {
switch part := p.(type) {
case opencode.TextPart:
@@ -452,7 +438,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
}
if finished {
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails, toolCallParts)
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails)
content, cached = m.cache.Get(key)
if !cached {
content = renderText(
@@ -464,11 +450,16 @@ func (m *messagesComponent) renderView() tea.Cmd {
width,
"",
false,
false,
[]opencode.FilePart{},
[]opencode.AgentPart{},
toolCallParts...,
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
m.cache.Set(key, content)
}
} else {
@@ -481,17 +472,21 @@ func (m *messagesComponent) renderView() tea.Cmd {
width,
"",
false,
false,
[]opencode.FilePart{},
[]opencode.AgentPart{},
toolCallParts...,
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
}
if content != "" {
partCount++
lineCount += lipgloss.Height(content) + 1
blocks = append(blocks, content)
hasContent = true
}
case opencode.ToolPart:
if reverted {
@@ -526,6 +521,12 @@ func (m *messagesComponent) renderView() tea.Cmd {
permission,
width,
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
m.cache.Set(key, content)
}
} else {
@@ -536,44 +537,54 @@ func (m *messagesComponent) renderView() tea.Cmd {
permission,
width,
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
}
if content != "" {
partCount++
lineCount += lipgloss.Height(content) + 1
blocks = append(blocks, content)
hasContent = true
}
case opencode.ReasoningPart:
if reverted {
continue
}
if !m.showThinkingBlocks {
continue
}
text := "..."
if part.Text != "" {
text := part.Text
content = renderText(
m.app,
message.Info,
text,
casted.ModelID,
m.showToolDetails,
width,
"",
true,
false,
[]opencode.FilePart{},
[]opencode.AgentPart{},
)
partCount++
lineCount += lipgloss.Height(content) + 1
blocks = append(blocks, content)
hasContent = true
text = part.Text
}
content = renderText(
m.app,
message.Info,
text,
casted.ModelID,
m.showToolDetails,
width,
"",
true,
[]opencode.FilePart{},
[]opencode.AgentPart{},
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
partCount++
lineCount += lipgloss.Height(content) + 1
blocks = append(blocks, content)
}
}
}
switch err := casted.Error.AsUnion().(type) {
error := ""
if assistant, ok := message.Info.(opencode.AssistantMessage); ok {
switch err := assistant.Error.AsUnion().(type) {
case nil:
case opencode.AssistantMessageErrorMessageOutputLengthError:
error = "Message output length exceeded"
@@ -584,25 +595,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
case opencode.UnknownError:
error = err.Data.Message
}
if !hasContent && error == "" && !reverted {
content = renderText(
m.app,
message.Info,
"Generating...",
casted.ModelID,
m.showToolDetails,
width,
"",
false,
false,
[]opencode.FilePart{},
[]opencode.AgentPart{},
)
partCount++
lineCount += lipgloss.Height(content) + 1
blocks = append(blocks, content)
}
}
if error != "" && !reverted {
@@ -613,6 +605,12 @@ func (m *messagesComponent) renderView() tea.Cmd {
width,
WithBorderColor(t.Error()),
)
error = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
error,
styles.WhitespaceStyle(t.Background()),
)
blocks = append(blocks, error)
lineCount += lipgloss.Height(error) + 1
}
@@ -704,6 +702,12 @@ func (m *messagesComponent) renderView() tea.Cmd {
m.app.CurrentPermission,
width,
)
content = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
content,
styles.WhitespaceStyle(t.Background()),
)
if content != "" {
partCount++
lineCount += lipgloss.Height(content) + 1
@@ -784,17 +788,8 @@ func (m *messagesComponent) renderHeader() string {
headerWidth := m.width
t := theme.CurrentTheme()
bgColor := t.Background()
borderColor := t.BackgroundElement()
isChildSession := m.app.Session.ParentID != ""
if isChildSession {
bgColor = t.BackgroundElement()
borderColor = t.Accent()
}
base := styles.NewStyle().Foreground(t.Text()).Background(bgColor).Render
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(bgColor).Render
base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
sessionInfo := ""
tokens := float64(0)
@@ -826,44 +821,20 @@ func (m *messagesComponent) renderHeader() string {
sessionInfoText := formatTokensAndCost(tokens, contextWindow, cost, isSubscriptionModel)
sessionInfo = styles.NewStyle().
Foreground(t.TextMuted()).
Background(bgColor).
Background(t.Background()).
Render(sessionInfoText)
shareEnabled := m.app.Config.Share != opencode.ConfigShareDisabled
navHint := ""
if isChildSession {
navHint = base(" "+m.app.Keybind(commands.SessionChildCycleReverseCommand)) + muted(" back")
}
headerTextWidth := headerWidth
if isChildSession {
headerTextWidth -= lipgloss.Width(navHint)
} else if !shareEnabled {
headerTextWidth -= lipgloss.Width(sessionInfoText)
if !shareEnabled {
// +1 is to ensure there is always at least one space between header and session info
headerTextWidth -= len(sessionInfoText) + 1
}
headerText := util.ToMarkdown(
"# "+m.app.Session.Title,
headerTextWidth,
bgColor,
t.Background(),
)
if isChildSession {
headerText = layout.Render(
layout.FlexOptions{
Background: &bgColor,
Direction: layout.Row,
Justify: layout.JustifySpaceBetween,
Align: layout.AlignStretch,
Width: headerTextWidth,
},
layout.FlexItem{
View: headerText,
},
layout.FlexItem{
View: navHint,
},
)
}
var items []layout.FlexItem
if shareEnabled {
@@ -876,9 +847,10 @@ func (m *messagesComponent) renderHeader() string {
items = []layout.FlexItem{{View: headerText}, {View: sessionInfo}}
}
background := t.Background()
headerRow := layout.Render(
layout.FlexOptions{
Background: &bgColor,
Background: &background,
Direction: layout.Row,
Justify: layout.JustifySpaceBetween,
Align: layout.AlignStretch,
@@ -894,16 +866,22 @@ func (m *messagesComponent) renderHeader() string {
header := strings.Join(headerLines, "\n")
header = styles.NewStyle().
Background(bgColor).
Background(t.Background()).
Width(headerWidth).
PaddingLeft(2).
PaddingRight(2).
BorderLeft(true).
BorderRight(true).
BorderBackground(t.Background()).
BorderForeground(borderColor).
BorderForeground(t.BackgroundElement()).
BorderStyle(lipgloss.ThickBorder()).
Render(header)
header = lipgloss.PlaceHorizontal(
m.width,
lipgloss.Center,
header,
styles.WhitespaceStyle(t.Background()),
)
return "\n" + header + "\n"
}
@@ -948,7 +926,7 @@ func formatTokensAndCost(
formattedCost := fmt.Sprintf("$%.2f", cost)
return fmt.Sprintf(
" %s/%d%% (%s)",
"%s/%d%% (%s)",
formattedTokens,
int(percentage),
formattedCost,
@@ -957,22 +935,20 @@ func formatTokensAndCost(
func (m *messagesComponent) View() string {
t := theme.CurrentTheme()
bgColor := t.Background()
if m.loading {
return lipgloss.Place(
m.width,
m.height,
lipgloss.Center,
lipgloss.Center,
styles.NewStyle().Background(bgColor).Render(""),
styles.WhitespaceStyle(bgColor),
styles.NewStyle().Background(t.Background()).Render(""),
styles.WhitespaceStyle(t.Background()),
)
}
viewport := m.viewport.View()
return styles.NewStyle().
Background(bgColor).
Background(t.Background()).
Render(m.header + "\n" + viewport)
}
@@ -1000,10 +976,6 @@ func (m *messagesComponent) ToolDetailsVisible() bool {
return m.showToolDetails
}
func (m *messagesComponent) ThinkingBlocksVisible() bool {
return m.showThinkingBlocks
}
func (m *messagesComponent) GotoTop() (tea.Model, tea.Cmd) {
m.viewport.GotoTop()
return m, nil
@@ -1197,26 +1169,14 @@ func NewMessagesComponent(app *app.App) MessagesComponent {
if app.State.ScrollSpeed != nil && *app.State.ScrollSpeed > 0 {
vp.MouseWheelDelta = *app.State.ScrollSpeed
} else {
vp.MouseWheelDelta = 2
}
// Default to showing tool details, hidden thinking blocks
showToolDetails := true
if app.State.ShowToolDetails != nil {
showToolDetails = *app.State.ShowToolDetails
}
showThinkingBlocks := false
if app.State.ShowThinkingBlocks != nil {
showThinkingBlocks = *app.State.ShowThinkingBlocks
vp.MouseWheelDelta = 4
}
return &messagesComponent{
app: app,
viewport: vp,
showToolDetails: showToolDetails,
showThinkingBlocks: showThinkingBlocks,
cache: NewPartCache(),
tail: true,
app: app,
viewport: vp,
showToolDetails: true,
cache: NewPartCache(),
tail: true,
}
}
@@ -83,10 +83,10 @@ func (c *commandsComponent) View() string {
}
commandsToShow = append(commandsToShow,
// empty line
// commands.Command{
// Name: "",
// Description: "",
// },
commands.Command{
Name: "",
Description: "",
},
commands.Command{
Name: commands.CommandName(util.Ide()),
Description: "open opencode",
@@ -1,452 +0,0 @@
package dialog
import (
"sort"
"strings"
"github.com/charmbracelet/bubbles/v2/key"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/lithammer/fuzzysearch/fuzzy"
"github.com/sst/opencode-sdk-go"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/components/list"
"github.com/sst/opencode/internal/components/modal"
"github.com/sst/opencode/internal/layout"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
)
const (
numVisibleAgents = 10
minAgentDialogWidth = 40
maxAgentDialogWidth = 60
maxDescriptionLength = 60
maxRecentAgents = 5
)
// AgentDialog interface for the agent selection dialog
type AgentDialog interface {
layout.Modal
}
type agentDialog struct {
app *app.App
allAgents []agentSelectItem
width int
height int
modal *modal.Modal
searchDialog *SearchDialog
dialogWidth int
}
// agentSelectItem combines the visual improvements with code patterns
type agentSelectItem struct {
name string
displayName string
description string
mode string // "primary", "subagent", "all"
isCurrent bool
agentIndex int
agent opencode.Agent // Keep original agent for compatibility
}
func (a agentSelectItem) Render(
selected bool,
width int,
baseStyle styles.Style,
) string {
t := theme.CurrentTheme()
itemStyle := baseStyle.
Background(t.BackgroundPanel()).
Foreground(t.Text())
if selected {
// Use agent color for highlighting when selected (visual improvement)
agentColor := util.GetAgentColor(a.agentIndex)
itemStyle = itemStyle.Foreground(agentColor)
}
descStyle := baseStyle.
Foreground(t.TextMuted()).
Background(t.BackgroundPanel())
// Calculate available width (accounting for padding and margins)
availableWidth := width - 2 // Account for left padding
agentName := a.displayName
// Determine if agent is built-in or custom using the agent's builtIn field
var displayText string
if a.agent.BuiltIn {
displayText = "(built-in)"
} else {
if a.description != "" {
displayText = a.description
} else {
displayText = "(user)"
}
}
separator := " - "
// Calculate how much space we have for the description (visual improvement)
nameAndSeparatorLength := len(agentName) + len(separator)
descriptionMaxLength := availableWidth - nameAndSeparatorLength
// Cap description length to the maximum allowed
if descriptionMaxLength > maxDescriptionLength {
descriptionMaxLength = maxDescriptionLength
}
// Truncate description if it's too long (visual improvement)
if len(displayText) > descriptionMaxLength && descriptionMaxLength > 3 {
displayText = displayText[:descriptionMaxLength-3] + "..."
}
namePart := itemStyle.Render(agentName)
descPart := descStyle.Render(separator + displayText)
combinedText := namePart + descPart
return baseStyle.
Background(t.BackgroundPanel()).
PaddingLeft(1).
Width(width).
Render(combinedText)
}
func (a agentSelectItem) Selectable() bool {
return true
}
type agentKeyMap struct {
Enter key.Binding
Escape key.Binding
}
var agentKeys = agentKeyMap{
Enter: key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("enter", "select agent"),
),
Escape: key.NewBinding(
key.WithKeys("esc"),
key.WithHelp("esc", "close"),
),
}
func (a *agentDialog) Init() tea.Cmd {
a.setupAllAgents()
return a.searchDialog.Init()
}
func (a *agentDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
a.width = msg.Width
a.height = msg.Height
a.searchDialog.SetWidth(a.dialogWidth)
a.searchDialog.SetHeight(msg.Height)
case SearchSelectionMsg:
// Handle selection from search dialog
if item, ok := msg.Item.(agentSelectItem); ok {
if !item.isCurrent {
// Switch to selected agent (using their better pattern)
return a, tea.Sequence(
util.CmdHandler(modal.CloseModalMsg{}),
util.CmdHandler(app.AgentSelectedMsg{AgentName: item.name}),
)
}
}
return a, util.CmdHandler(modal.CloseModalMsg{})
case SearchCancelledMsg:
return a, util.CmdHandler(modal.CloseModalMsg{})
case SearchRemoveItemMsg:
if item, ok := msg.Item.(agentSelectItem); ok {
if a.isAgentInRecentSection(item, msg.Index) {
a.app.State.RemoveAgentFromRecentlyUsed(item.name)
items := a.buildDisplayList(a.searchDialog.GetQuery())
a.searchDialog.SetItems(items)
return a, a.app.SaveState()
}
}
return a, nil
case SearchQueryChangedMsg:
// Update the list based on search query
items := a.buildDisplayList(msg.Query)
a.searchDialog.SetItems(items)
return a, nil
}
updatedDialog, cmd := a.searchDialog.Update(msg)
a.searchDialog = updatedDialog.(*SearchDialog)
return a, cmd
}
func (a *agentDialog) SetSize(width, height int) {
a.width = width
a.height = height
}
func (a *agentDialog) View() string {
return a.searchDialog.View()
}
func (a *agentDialog) calculateOptimalWidth(agents []agentSelectItem) int {
maxWidth := minAgentDialogWidth
for _, agent := range agents {
// Calculate the width needed for this item: "AgentName - Description" (visual improvement)
itemWidth := len(agent.displayName)
if agent.agent.BuiltIn {
itemWidth += len("(built-in)") + 3 // " - "
} else {
if agent.description != "" {
descLength := len(agent.description)
if descLength > maxDescriptionLength {
descLength = maxDescriptionLength
}
itemWidth += descLength + 3 // " - "
} else {
itemWidth += len("(user)") + 3 // " - "
}
}
if itemWidth > maxWidth {
maxWidth = itemWidth
}
}
maxWidth = min(maxWidth, maxAgentDialogWidth)
return maxWidth
}
func (a *agentDialog) setupAllAgents() {
currentAgentName := a.app.Agent().Name
// Build agent items from app.Agents (no API call needed) - their pattern
a.allAgents = make([]agentSelectItem, 0, len(a.app.Agents))
for i, agent := range a.app.Agents {
if agent.Mode == "subagent" {
continue // Skip subagents entirely
}
isCurrent := agent.Name == currentAgentName
// Create display name (capitalize first letter)
displayName := strings.Title(agent.Name)
a.allAgents = append(a.allAgents, agentSelectItem{
name: agent.Name,
displayName: displayName,
description: agent.Description, // Keep for search but don't use in display
mode: string(agent.Mode),
isCurrent: isCurrent,
agentIndex: i,
agent: agent, // Keep original for compatibility
})
}
a.sortAgents()
// Calculate optimal width based on all agents (visual improvement)
a.dialogWidth = a.calculateOptimalWidth(a.allAgents)
// Ensure minimum width to prevent textinput issues
a.dialogWidth = max(a.dialogWidth, minAgentDialogWidth)
a.searchDialog = NewSearchDialog("Search agents...", numVisibleAgents)
a.searchDialog.SetWidth(a.dialogWidth)
// Build initial display list (empty query shows grouped view)
items := a.buildDisplayList("")
a.searchDialog.SetItems(items)
}
func (a *agentDialog) sortAgents() {
sort.Slice(a.allAgents, func(i, j int) bool {
agentA := a.allAgents[i]
agentB := a.allAgents[j]
// Current agent goes first (your preference)
if agentA.name == a.app.Agent().Name {
return true
}
if agentB.name == a.app.Agent().Name {
return false
}
// Alphabetical order for all other agents
return agentA.name < agentB.name
})
}
// buildDisplayList creates the list items based on search query
func (a *agentDialog) buildDisplayList(query string) []list.Item {
if query != "" {
// Search mode: use fuzzy matching
return a.buildSearchResults(query)
} else {
// Grouped mode: show Recent agents section and alphabetical list (their pattern)
return a.buildGroupedResults()
}
}
// buildSearchResults creates a flat list of search results using fuzzy matching
func (a *agentDialog) buildSearchResults(query string) []list.Item {
agentNames := []string{}
agentMap := make(map[string]agentSelectItem)
for _, agent := range a.allAgents {
// Only include non-subagents in search
if agent.mode == "subagent" {
continue
}
searchStr := agent.name
agentNames = append(agentNames, searchStr)
agentMap[searchStr] = agent
}
matches := fuzzy.RankFindFold(query, agentNames)
sort.Sort(matches)
items := []list.Item{}
seenAgents := make(map[string]bool)
for _, match := range matches {
agent := agentMap[match.Target]
// Create a unique key to avoid duplicates
key := agent.name
if seenAgents[key] {
continue
}
seenAgents[key] = true
items = append(items, agent)
}
return items
}
// buildGroupedResults creates a grouped list with Recent agents section and categorized agents
func (a *agentDialog) buildGroupedResults() []list.Item {
var items []list.Item
// Add Recent section (their pattern)
recentAgents := a.getRecentAgents(maxRecentAgents)
if len(recentAgents) > 0 {
items = append(items, list.HeaderItem("Recent"))
for _, agent := range recentAgents {
items = append(items, agent)
}
}
// Create map of recent agent names for filtering
recentAgentNames := make(map[string]bool)
for _, recent := range recentAgents {
recentAgentNames[recent.name] = true
}
// Only show non-subagents (primary/user) in the main section
mainAgents := make([]agentSelectItem, 0)
for _, agent := range a.allAgents {
if !recentAgentNames[agent.name] {
mainAgents = append(mainAgents, agent)
}
}
// Sort main agents alphabetically
sort.Slice(mainAgents, func(i, j int) bool {
return mainAgents[i].name < mainAgents[j].name
})
// Add main agents section
if len(mainAgents) > 0 {
items = append(items, list.HeaderItem("Agents"))
for _, agent := range mainAgents {
items = append(items, agent)
}
}
return items
}
func (a *agentDialog) Render(background string) string {
return a.modal.Render(a.View(), background)
}
func (a *agentDialog) Close() tea.Cmd {
return nil
}
// getRecentAgents returns the most recently used agents (their pattern)
func (a *agentDialog) getRecentAgents(limit int) []agentSelectItem {
var recentAgents []agentSelectItem
// Get recent agents from app state
for _, usage := range a.app.State.RecentlyUsedAgents {
if len(recentAgents) >= limit {
break
}
// Find the corresponding agent
for _, agent := range a.allAgents {
if agent.name == usage.AgentName {
recentAgents = append(recentAgents, agent)
break
}
}
}
// If no recent agents, use the current agent
if len(recentAgents) == 0 {
currentAgentName := a.app.Agent().Name
for _, agent := range a.allAgents {
if agent.name == currentAgentName {
recentAgents = append(recentAgents, agent)
break
}
}
}
return recentAgents
}
func (a *agentDialog) isAgentInRecentSection(agent agentSelectItem, index int) bool {
// Only check if we're in grouped mode (no search query)
if a.searchDialog.GetQuery() != "" {
return false
}
recentAgents := a.getRecentAgents(maxRecentAgents)
if len(recentAgents) == 0 {
return false
}
// Index 0 is the "Recent" header, so recent agents are at indices 1 to len(recentAgents)
if index >= 1 && index <= len(recentAgents) {
if index-1 < len(recentAgents) {
recentAgent := recentAgents[index-1]
return recentAgent.name == agent.name
}
}
return false
}
func NewAgentDialog(app *app.App) AgentDialog {
dialog := &agentDialog{
app: app,
}
dialog.setupAllAgents()
dialog.modal = modal.New(
modal.WithTitle("Select Agent"),
modal.WithMaxWidth(dialog.dialogWidth+4),
)
return dialog
}
@@ -99,10 +99,7 @@ func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
baseStyle := styles.NewStyle().Background(t.BackgroundElement())
// Ensure stable provider order just in case
sort.SliceStable(
itemsByProvider,
func(i, j int) bool { return itemsByProvider[i].idx < itemsByProvider[j].idx },
)
sort.SliceStable(itemsByProvider, func(i, j int) bool { return itemsByProvider[i].idx < itemsByProvider[j].idx })
final := make([]completions.CompletionSuggestion, 0)
for _, entry := range itemsByProvider {
@@ -170,16 +167,6 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
value := c.pseudoSearchTextArea.Value()
width := lipgloss.Width(value)
triggerWidth := lipgloss.Width(c.trigger)
if msg.String() == "space" || msg.String() == " " {
item, i := c.list.GetSelectedItem()
if i > -1 {
return c, c.complete(item)
}
// If no exact match, close the dialog
return c, c.close()
}
// Only close on backspace when there are no characters left, unless we're back to just the trigger
if (msg.String() != "backspace" && msg.String() != "ctrl+h") || (width <= triggerWidth && value != c.trigger) {
return c, c.close()
@@ -0,0 +1,236 @@
package dialog
import (
"log/slog"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/sst/opencode/internal/completions"
"github.com/sst/opencode/internal/components/list"
"github.com/sst/opencode/internal/components/modal"
"github.com/sst/opencode/internal/layout"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
)
const (
findDialogWidth = 76
)
type FindSelectedMsg struct {
FilePath string
}
type FindDialogCloseMsg struct{}
type findInitialSuggestionsMsg struct {
suggestions []completions.CompletionSuggestion
}
type FindDialog interface {
layout.Modal
tea.Model
tea.ViewModel
SetWidth(width int)
SetHeight(height int)
IsEmpty() bool
}
// findItem is a custom list item for file suggestions
type findItem struct {
suggestion completions.CompletionSuggestion
}
func (f findItem) Render(
selected bool,
width int,
baseStyle styles.Style,
) string {
t := theme.CurrentTheme()
itemStyle := baseStyle.
Background(t.BackgroundPanel()).
Foreground(t.TextMuted())
if selected {
itemStyle = itemStyle.Foreground(t.Primary())
}
return itemStyle.PaddingLeft(1).Render(f.suggestion.Display(itemStyle))
}
func (f findItem) Selectable() bool {
return true
}
type findDialogComponent struct {
completionProvider completions.CompletionProvider
allSuggestions []completions.CompletionSuggestion
width, height int
modal *modal.Modal
searchDialog *SearchDialog
dialogWidth int
}
func (f *findDialogComponent) Init() tea.Cmd {
return tea.Batch(
f.loadInitialSuggestions(),
f.searchDialog.Init(),
)
}
func (f *findDialogComponent) loadInitialSuggestions() tea.Cmd {
return func() tea.Msg {
items, err := f.completionProvider.GetChildEntries("")
if err != nil {
slog.Error("Failed to get initial completion items", "error", err)
return findInitialSuggestionsMsg{suggestions: []completions.CompletionSuggestion{}}
}
return findInitialSuggestionsMsg{suggestions: items}
}
}
func (f *findDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case findInitialSuggestionsMsg:
// Handle initial suggestions setup
f.allSuggestions = msg.suggestions
// Calculate dialog width
f.dialogWidth = f.calculateDialogWidth()
// Initialize search dialog with calculated width
f.searchDialog = NewSearchDialog("Search files...", 10)
f.searchDialog.SetWidth(f.dialogWidth)
// Convert to list items
items := make([]list.Item, len(f.allSuggestions))
for i, suggestion := range f.allSuggestions {
items[i] = findItem{suggestion: suggestion}
}
f.searchDialog.SetItems(items)
// Update modal with calculated width
f.modal = modal.New(
modal.WithTitle("Find Files"),
modal.WithMaxWidth(f.dialogWidth+4),
)
return f, f.searchDialog.Init()
case []completions.CompletionSuggestion:
// Store suggestions and convert to findItem for the search dialog
f.allSuggestions = msg
items := make([]list.Item, len(msg))
for i, suggestion := range msg {
items[i] = findItem{suggestion: suggestion}
}
f.searchDialog.SetItems(items)
return f, nil
case SearchSelectionMsg:
// Handle selection from search dialog - now we can directly access the suggestion
if item, ok := msg.Item.(findItem); ok {
return f, f.selectFile(item.suggestion)
}
return f, nil
case SearchCancelledMsg:
return f, f.Close()
case SearchQueryChangedMsg:
// Update completion items based on search query
return f, func() tea.Msg {
items, err := f.completionProvider.GetChildEntries(msg.Query)
if err != nil {
slog.Error("Failed to get completion items", "error", err)
return []completions.CompletionSuggestion{}
}
return items
}
case tea.WindowSizeMsg:
f.width = msg.Width
f.height = msg.Height
// Recalculate width based on new viewport size
oldWidth := f.dialogWidth
f.dialogWidth = f.calculateDialogWidth()
if oldWidth != f.dialogWidth {
f.searchDialog.SetWidth(f.dialogWidth)
// Update modal max width too
f.modal = modal.New(
modal.WithTitle("Find Files"),
modal.WithMaxWidth(f.dialogWidth+4),
)
}
f.searchDialog.SetHeight(msg.Height)
}
// Forward all other messages to the search dialog
updatedDialog, cmd := f.searchDialog.Update(msg)
f.searchDialog = updatedDialog.(*SearchDialog)
return f, cmd
}
func (f *findDialogComponent) View() string {
return f.searchDialog.View()
}
func (f *findDialogComponent) calculateDialogWidth() int {
// Use fixed width unless viewport is smaller
if f.width > 0 && f.width < findDialogWidth+10 {
return f.width - 10
}
return findDialogWidth
}
func (f *findDialogComponent) SetWidth(width int) {
f.width = width
f.searchDialog.SetWidth(f.dialogWidth)
}
func (f *findDialogComponent) SetHeight(height int) {
f.height = height
}
func (f *findDialogComponent) IsEmpty() bool {
return f.searchDialog.GetQuery() == ""
}
func (f *findDialogComponent) selectFile(item completions.CompletionSuggestion) tea.Cmd {
return tea.Sequence(
f.Close(),
util.CmdHandler(FindSelectedMsg{
FilePath: item.Value,
}),
)
}
func (f *findDialogComponent) Render(background string) string {
return f.modal.Render(f.View(), background)
}
func (f *findDialogComponent) Close() tea.Cmd {
f.searchDialog.SetQuery("")
f.searchDialog.Blur()
return util.CmdHandler(modal.CloseModalMsg{})
}
func NewFindDialog(completionProvider completions.CompletionProvider) FindDialog {
component := &findDialogComponent{
completionProvider: completionProvider,
dialogWidth: findDialogWidth,
allSuggestions: []completions.CompletionSuggestion{},
}
// Create search dialog and modal with fixed width
component.searchDialog = NewSearchDialog("Search files...", 10)
component.searchDialog.SetWidth(findDialogWidth)
component.modal = modal.New(
modal.WithTitle("Find Files"),
modal.WithMaxWidth(findDialogWidth+4),
)
return component
}
@@ -0,0 +1,184 @@
package dialog
import (
"github.com/charmbracelet/bubbles/v2/key"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/charmbracelet/lipgloss/v2"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
)
// InitDialogCmp is a component that asks the user if they want to initialize the project.
type InitDialogCmp struct {
width, height int
selected int
keys initDialogKeyMap
}
// NewInitDialogCmp creates a new InitDialogCmp.
func NewInitDialogCmp() InitDialogCmp {
return InitDialogCmp{
selected: 0,
keys: initDialogKeyMap{},
}
}
type initDialogKeyMap struct {
Tab key.Binding
Left key.Binding
Right key.Binding
Enter key.Binding
Escape key.Binding
Y key.Binding
N key.Binding
}
// ShortHelp implements key.Map.
func (k initDialogKeyMap) ShortHelp() []key.Binding {
return []key.Binding{
key.NewBinding(
key.WithKeys("tab", "left", "right"),
key.WithHelp("tab/←/→", "toggle selection"),
),
key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("enter", "confirm"),
),
key.NewBinding(
key.WithKeys("esc", "q"),
key.WithHelp("esc/q", "cancel"),
),
key.NewBinding(
key.WithKeys("y", "n"),
key.WithHelp("y/n", "yes/no"),
),
}
}
// FullHelp implements key.Map.
func (k initDialogKeyMap) FullHelp() [][]key.Binding {
return [][]key.Binding{k.ShortHelp()}
}
// Init implements tea.Model.
func (m InitDialogCmp) Init() tea.Cmd {
return nil
}
// Update implements tea.Model.
func (m InitDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case key.Matches(msg, key.NewBinding(key.WithKeys("esc"))):
return m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})
case key.Matches(msg, key.NewBinding(key.WithKeys("tab", "left", "right", "h", "l"))):
m.selected = (m.selected + 1) % 2
return m, nil
case key.Matches(msg, key.NewBinding(key.WithKeys("enter"))):
return m, util.CmdHandler(CloseInitDialogMsg{Initialize: m.selected == 0})
case key.Matches(msg, key.NewBinding(key.WithKeys("y"))):
return m, util.CmdHandler(CloseInitDialogMsg{Initialize: true})
case key.Matches(msg, key.NewBinding(key.WithKeys("n"))):
return m, util.CmdHandler(CloseInitDialogMsg{Initialize: false})
}
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
}
return m, nil
}
// View implements tea.Model.
func (m InitDialogCmp) View() string {
t := theme.CurrentTheme()
baseStyle := styles.NewStyle().Foreground(t.Text())
// Calculate width needed for content
maxWidth := 60 // Width for explanation text
title := baseStyle.
Foreground(t.Primary()).
Bold(true).
Width(maxWidth).
Padding(0, 1).
Render("Initialize Project")
explanation := baseStyle.
Foreground(t.Text()).
Width(maxWidth).
Padding(0, 1).
Render("Initialization generates a new AGENTS.md file that contains information about your codebase, this file serves as memory for each project, you can freely add to it to help the agents be better at their job.")
question := baseStyle.
Foreground(t.Text()).
Width(maxWidth).
Padding(1, 1).
Render("Would you like to initialize this project?")
maxWidth = min(maxWidth, m.width-10)
yesStyle := baseStyle
noStyle := baseStyle
if m.selected == 0 {
yesStyle = yesStyle.
Background(t.Primary()).
Foreground(t.Background()).
Bold(true)
noStyle = noStyle.
Background(t.Background()).
Foreground(t.Primary())
} else {
noStyle = noStyle.
Background(t.Primary()).
Foreground(t.Background()).
Bold(true)
yesStyle = yesStyle.
Background(t.Background()).
Foreground(t.Primary())
}
yes := yesStyle.Padding(0, 3).Render("Yes")
no := noStyle.Padding(0, 3).Render("No")
buttons := lipgloss.JoinHorizontal(lipgloss.Center, yes, baseStyle.Render(" "), no)
buttons = baseStyle.
Width(maxWidth).
Padding(1, 0).
Render(buttons)
content := lipgloss.JoinVertical(
lipgloss.Left,
title,
baseStyle.Width(maxWidth).Render(""),
explanation,
question,
buttons,
baseStyle.Width(maxWidth).Render(""),
)
return baseStyle.Padding(1, 2).
Border(lipgloss.RoundedBorder()).
BorderBackground(t.Background()).
BorderForeground(t.TextMuted()).
Width(lipgloss.Width(content) + 4).
Render(content)
}
// SetSize sets the size of the component.
func (m *InitDialogCmp) SetSize(width, height int) {
m.width = width
m.height = height
}
// CloseInitDialogMsg is a message that is sent when the init dialog is closed.
type CloseInitDialogMsg struct {
Initialize bool
}
// ShowInitDialogMsg is a message that is sent to show the init dialog.
type ShowInitDialogMsg struct {
Show bool
}
@@ -6,7 +6,6 @@ import (
"slices"
"github.com/charmbracelet/bubbles/v2/textinput"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/muesli/reflow/truncate"
"github.com/sst/opencode-sdk-go"
@@ -111,9 +110,6 @@ type sessionDialog struct {
list list.List[sessionItem]
app *app.App
deleteConfirmation int // -1 means no confirmation, >= 0 means confirming deletion of session at this index
renameMode bool
renameInput textinput.Model
renameIndex int // index of session being renamed
}
func (s *sessionDialog) Init() tea.Cmd {
@@ -127,128 +123,69 @@ func (s *sessionDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
s.height = msg.Height
s.list.SetMaxWidth(layout.Current.Container.Width - 12)
case tea.KeyPressMsg:
if s.renameMode {
switch msg.String() {
case "enter":
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) && idx == s.renameIndex {
newTitle := s.renameInput.Value()
if strings.TrimSpace(newTitle) != "" {
sessionToUpdate := s.sessions[idx]
return s, tea.Sequence(
func() tea.Msg {
ctx := context.Background()
err := s.app.UpdateSession(ctx, sessionToUpdate.ID, newTitle)
if err != nil {
return toast.NewErrorToast("Failed to rename session: " + err.Error())()
}
s.sessions[idx].Title = newTitle
s.renameMode = false
s.modal.SetTitle("Switch Session")
s.updateListItems()
return toast.NewSuccessToast("Session renamed successfully")()
},
)
}
}
s.renameMode = false
s.modal.SetTitle("Switch Session")
switch msg.String() {
case "enter":
if s.deleteConfirmation >= 0 {
s.deleteConfirmation = -1
s.updateListItems()
return s, nil
default:
var cmd tea.Cmd
s.renameInput, cmd = s.renameInput.Update(msg)
return s, cmd
}
} else {
switch msg.String() {
case "enter":
if s.deleteConfirmation >= 0 {
s.deleteConfirmation = -1
s.updateListItems()
return s, nil
}
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
selectedSession := s.sessions[idx]
return s, tea.Sequence(
util.CmdHandler(modal.CloseModalMsg{}),
util.CmdHandler(app.SessionSelectedMsg(&selectedSession)),
)
}
case "n":
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
selectedSession := s.sessions[idx]
return s, tea.Sequence(
util.CmdHandler(modal.CloseModalMsg{}),
util.CmdHandler(app.SessionClearedMsg{}),
util.CmdHandler(app.SessionSelectedMsg(&selectedSession)),
)
case "r":
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
s.renameMode = true
s.renameIndex = idx
s.setupRenameInput(s.sessions[idx].Title)
s.modal.SetTitle("Rename Session")
s.updateListItems()
return s, textinput.Blink
}
case "x", "delete", "backspace":
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
if s.deleteConfirmation == idx {
// Second press - actually delete the session
sessionToDelete := s.sessions[idx]
return s, tea.Sequence(
func() tea.Msg {
s.sessions = slices.Delete(s.sessions, idx, idx+1)
s.deleteConfirmation = -1
s.updateListItems()
return nil
},
s.deleteSession(sessionToDelete.ID),
)
} else {
// First press - enter delete confirmation mode
s.deleteConfirmation = idx
s.updateListItems()
return s, nil
}
}
case "esc":
if s.deleteConfirmation >= 0 {
s.deleteConfirmation = -1
}
case "n":
return s, tea.Sequence(
util.CmdHandler(modal.CloseModalMsg{}),
util.CmdHandler(app.SessionClearedMsg{}),
)
case "x", "delete", "backspace":
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
if s.deleteConfirmation == idx {
// Second press - actually delete the session
sessionToDelete := s.sessions[idx]
return s, tea.Sequence(
func() tea.Msg {
s.sessions = slices.Delete(s.sessions, idx, idx+1)
s.deleteConfirmation = -1
s.updateListItems()
return nil
},
s.deleteSession(sessionToDelete.ID),
)
} else {
// First press - enter delete confirmation mode
s.deleteConfirmation = idx
s.updateListItems()
return s, nil
}
}
case "esc":
if s.deleteConfirmation >= 0 {
s.deleteConfirmation = -1
s.updateListItems()
return s, nil
}
}
}
if !s.renameMode {
var cmd tea.Cmd
listModel, cmd := s.list.Update(msg)
s.list = listModel.(list.List[sessionItem])
return s, cmd
}
return s, nil
var cmd tea.Cmd
listModel, cmd := s.list.Update(msg)
s.list = listModel.(list.List[sessionItem])
return s, cmd
}
func (s *sessionDialog) Render(background string) string {
if s.renameMode {
// Show rename input instead of list
t := theme.CurrentTheme()
renameView := s.renameInput.View()
mutedStyle := styles.NewStyle().Foreground(t.TextMuted()).Background(t.BackgroundPanel()).Render
helpText := mutedStyle("Enter to confirm, Esc to cancel")
helpText = styles.NewStyle().PaddingLeft(1).PaddingTop(1).Render(helpText)
content := strings.Join([]string{renameView, helpText}, "\n")
return s.modal.Render(content, background)
}
listView := s.list.View()
t := theme.CurrentTheme()
keyStyle := styles.NewStyle().Foreground(t.Text()).Background(t.BackgroundPanel()).Render
mutedStyle := styles.NewStyle().Foreground(t.TextMuted()).Background(t.BackgroundPanel()).Render
leftHelp := keyStyle("n") + mutedStyle(" new session") + " " + keyStyle("r") + mutedStyle(" rename")
leftHelp := keyStyle("n") + mutedStyle(" new session")
rightHelp := keyStyle("x/del") + mutedStyle(" delete session")
bgColor := t.BackgroundPanel()
@@ -266,39 +203,6 @@ func (s *sessionDialog) Render(background string) string {
return s.modal.Render(content, background)
}
func (s *sessionDialog) setupRenameInput(currentTitle string) {
t := theme.CurrentTheme()
bgColor := t.BackgroundPanel()
textColor := t.Text()
textMutedColor := t.TextMuted()
s.renameInput = textinput.New()
s.renameInput.SetValue(currentTitle)
s.renameInput.Focus()
s.renameInput.CharLimit = 100
s.renameInput.SetWidth(layout.Current.Container.Width - 20)
s.renameInput.Styles.Blurred.Placeholder = styles.NewStyle().
Foreground(textMutedColor).
Background(bgColor).
Lipgloss()
s.renameInput.Styles.Blurred.Text = styles.NewStyle().
Foreground(textColor).
Background(bgColor).
Lipgloss()
s.renameInput.Styles.Focused.Placeholder = styles.NewStyle().
Foreground(textMutedColor).
Background(bgColor).
Lipgloss()
s.renameInput.Styles.Focused.Text = styles.NewStyle().
Foreground(textColor).
Background(bgColor).
Lipgloss()
s.renameInput.Styles.Focused.Prompt = styles.NewStyle().
Background(bgColor).
Lipgloss()
}
func (s *sessionDialog) updateListItems() {
_, currentIdx := s.list.GetSelectedItem()
@@ -325,22 +229,7 @@ func (s *sessionDialog) deleteSession(sessionID string) tea.Cmd {
}
}
// ReopenSessionModalMsg is emitted when the session modal should be reopened
type ReopenSessionModalMsg struct{}
func (s *sessionDialog) Close() tea.Cmd {
if s.renameMode {
// If in rename mode, exit rename mode and return a command to reopen the modal
s.renameMode = false
s.modal.SetTitle("Switch Session")
s.updateListItems()
// Return a command that will reopen the session modal
return func() tea.Msg {
return ReopenSessionModalMsg{}
}
}
// Normal close behavior
return nil
}
@@ -383,8 +272,6 @@ func NewSessionDialog(app *app.App) SessionDialog {
list: listComponent,
app: app,
deleteConfirmation: -1,
renameMode: false,
renameIndex: -1,
modal: modal.New(
modal.WithTitle("Switch Session"),
modal.WithMaxWidth(layout.Current.Container.Width-8),
@@ -0,0 +1,281 @@
package fileviewer
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/commands"
"github.com/sst/opencode/internal/components/dialog"
"github.com/sst/opencode/internal/components/diff"
"github.com/sst/opencode/internal/layout"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
"github.com/sst/opencode/internal/viewport"
)
type DiffStyle int
const (
DiffStyleSplit DiffStyle = iota
DiffStyleUnified
)
type Model struct {
app *app.App
width, height int
viewport viewport.Model
filename *string
content *string
isDiff *bool
diffStyle DiffStyle
}
type fileRenderedMsg struct {
content string
}
func New(app *app.App) Model {
vp := viewport.New()
m := Model{
app: app,
viewport: vp,
diffStyle: DiffStyleUnified,
}
if app.State.SplitDiff {
m.diffStyle = DiffStyleSplit
}
return m
}
func (m Model) Init() tea.Cmd {
return m.viewport.Init()
}
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case fileRenderedMsg:
m.viewport.SetContent(msg.content)
return m, util.CmdHandler(app.FileRenderedMsg{
FilePath: *m.filename,
})
case dialog.ThemeSelectedMsg:
return m, m.render()
case tea.KeyMsg:
switch msg.String() {
// TODO
}
}
vp, cmd := m.viewport.Update(msg)
m.viewport = vp
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
func (m Model) View() string {
if !m.HasFile() {
return ""
}
header := *m.filename
header = styles.NewStyle().
Padding(1, 2).
Width(m.width).
Background(theme.CurrentTheme().BackgroundElement()).
Foreground(theme.CurrentTheme().Text()).
Render(header)
t := theme.CurrentTheme()
close := m.app.Key(commands.FileCloseCommand)
diffToggle := m.app.Key(commands.FileDiffToggleCommand)
if m.isDiff == nil || *m.isDiff == false {
diffToggle = ""
}
layoutToggle := m.app.Key(commands.MessagesLayoutToggleCommand)
background := t.Background()
footer := layout.Render(
layout.FlexOptions{
Background: &background,
Direction: layout.Row,
Justify: layout.JustifyCenter,
Align: layout.AlignStretch,
Width: m.width - 2,
Gap: 5,
},
layout.FlexItem{
View: close,
},
layout.FlexItem{
View: layoutToggle,
},
layout.FlexItem{
View: diffToggle,
},
)
footer = styles.NewStyle().Background(t.Background()).Padding(0, 1).Render(footer)
return header + "\n" + m.viewport.View() + "\n" + footer
}
func (m *Model) Clear() (Model, tea.Cmd) {
m.filename = nil
m.content = nil
m.isDiff = nil
return *m, m.render()
}
func (m *Model) ToggleDiff() (Model, tea.Cmd) {
switch m.diffStyle {
case DiffStyleSplit:
m.diffStyle = DiffStyleUnified
default:
m.diffStyle = DiffStyleSplit
}
return *m, m.render()
}
func (m *Model) DiffStyle() DiffStyle {
return m.diffStyle
}
func (m Model) HasFile() bool {
return m.filename != nil && m.content != nil
}
func (m Model) Filename() string {
if m.filename == nil {
return ""
}
return *m.filename
}
func (m *Model) SetSize(width, height int) (Model, tea.Cmd) {
if m.width != width || m.height != height {
m.width = width
m.height = height
m.viewport.SetWidth(width)
m.viewport.SetHeight(height - 4)
return *m, m.render()
}
return *m, nil
}
func (m *Model) SetFile(filename string, content string, isDiff bool) (Model, tea.Cmd) {
m.filename = &filename
m.content = &content
m.isDiff = &isDiff
return *m, m.render()
}
func (m *Model) render() tea.Cmd {
if m.filename == nil || m.content == nil {
m.viewport.SetContent("")
return nil
}
return func() tea.Msg {
t := theme.CurrentTheme()
var rendered string
if m.isDiff != nil && *m.isDiff {
diffResult := ""
var err error
if m.diffStyle == DiffStyleSplit {
diffResult, err = diff.FormatDiff(
*m.filename,
*m.content,
diff.WithWidth(m.width),
)
} else if m.diffStyle == DiffStyleUnified {
diffResult, err = diff.FormatUnifiedDiff(
*m.filename,
*m.content,
diff.WithWidth(m.width),
)
}
if err != nil {
rendered = styles.NewStyle().
Foreground(t.Error()).
Render(fmt.Sprintf("Error rendering diff: %v", err))
} else {
rendered = strings.TrimRight(diffResult, "\n")
}
} else {
rendered = util.RenderFile(
*m.filename,
*m.content,
m.width,
)
}
rendered = styles.NewStyle().
Width(m.width).
Background(t.BackgroundPanel()).
Render(rendered)
return fileRenderedMsg{
content: rendered,
}
}
}
func (m *Model) ScrollTo(line int) {
m.viewport.SetYOffset(line)
}
func (m *Model) ScrollToBottom() {
m.viewport.GotoBottom()
}
func (m *Model) ScrollToTop() {
m.viewport.GotoTop()
}
func (m *Model) PageUp() (Model, tea.Cmd) {
m.viewport.ViewUp()
return *m, nil
}
func (m *Model) PageDown() (Model, tea.Cmd) {
m.viewport.ViewDown()
return *m, nil
}
func (m *Model) HalfPageUp() (Model, tea.Cmd) {
m.viewport.HalfViewUp()
return *m, nil
}
func (m *Model) HalfPageDown() (Model, tea.Cmd) {
m.viewport.HalfViewDown()
return *m, nil
}
func (m Model) AtTop() bool {
return m.viewport.AtTop()
}
func (m Model) AtBottom() bool {
return m.viewport.AtBottom()
}
func (m Model) ScrollPercent() float64 {
return m.viewport.ScrollPercent()
}
func (m Model) TotalLineCount() int {
return m.viewport.TotalLineCount()
}
func (m Model) VisibleLineCount() int {
return m.viewport.VisibleLineCount()
}
+12 -17
View File
@@ -173,13 +173,7 @@ func (c *listComponent[T]) moveUp() {
}
}
// If no selectable item found above, wrap to the bottom
for i := len(c.items) - 1; i > c.selectedIdx; i-- {
if c.isSelectable(c.items[i]) {
c.selectedIdx = i
return
}
}
// If no selectable item found above, stay at current position
}
// moveDown moves the selection down, skipping non-selectable items
@@ -189,19 +183,20 @@ func (c *listComponent[T]) moveDown() {
}
originalIdx := c.selectedIdx
// First try moving down from current position
for i := c.selectedIdx + 1; i < len(c.items); i++ {
if c.isSelectable(c.items[i]) {
c.selectedIdx = i
for {
if c.selectedIdx < len(c.items)-1 {
c.selectedIdx++
} else {
break
}
if c.isSelectable(c.items[c.selectedIdx]) {
return
}
}
// If no selectable item found below, wrap to the top
for i := 0; i < originalIdx; i++ {
if c.isSelectable(c.items[i]) {
c.selectedIdx = i
return
// Prevent infinite loop
if c.selectedIdx == originalIdx {
break
}
}
}
@@ -138,18 +138,15 @@ func TestCtrlNavigation(t *testing.T) {
func TestNavigationBoundaries(t *testing.T) {
list := createTestList()
// Test up arrow at first item (should wrap to last item)
// Test up arrow at first item (should stay at 0)
upKey := tea.KeyPressMsg{Code: tea.KeyUp}
updatedModel, _ := list.Update(upKey)
list = updatedModel.(*listComponent[testItem])
_, idx := list.GetSelectedItem()
if idx != 2 {
t.Errorf("Expected to wrap to index 2 when pressing up at first item, got %d", idx)
if idx != 0 {
t.Errorf("Expected to stay at index 0 when pressing up at first item, got %d", idx)
}
// Move to first item
list.SetSelectedIndex(0)
// Move to last item
downKey := tea.KeyPressMsg{Code: tea.KeyDown}
updatedModel, _ = list.Update(downKey)
@@ -161,12 +158,12 @@ func TestNavigationBoundaries(t *testing.T) {
t.Errorf("Expected to be at index 2, got %d", idx)
}
// Test down arrow at last item (should wrap to first item)
// Test down arrow at last item (should stay at 2)
updatedModel, _ = list.Update(downKey)
list = updatedModel.(*listComponent[testItem])
_, idx = list.GetSelectedItem()
if idx != 0 {
t.Errorf("Expected to wrap to index 0 when pressing down at last item, got %d", idx)
if idx != 2 {
t.Errorf("Expected to stay at index 2 when pressing down at last item, got %d", idx)
}
}
@@ -211,39 +208,3 @@ func TestEmptyList(t *testing.T) {
t.Error("Expected IsEmpty() to return true for empty list")
}
}
func TestWrapAroundNavigation(t *testing.T) {
list := createTestList()
// Start at first item (index 0)
_, idx := list.GetSelectedItem()
if idx != 0 {
t.Errorf("Expected to start at index 0, got %d", idx)
}
// Press up arrow - should wrap to last item (index 2)
upKey := tea.KeyPressMsg{Code: tea.KeyUp}
updatedModel, _ := list.Update(upKey)
list = updatedModel.(*listComponent[testItem])
_, idx = list.GetSelectedItem()
if idx != 2 {
t.Errorf("Expected to wrap to index 2 when pressing up from first item, got %d", idx)
}
// Press down arrow - should wrap to first item (index 0)
downKey := tea.KeyPressMsg{Code: tea.KeyDown}
updatedModel, _ = list.Update(downKey)
list = updatedModel.(*listComponent[testItem])
_, idx = list.GetSelectedItem()
if idx != 0 {
t.Errorf("Expected to wrap to index 0 when pressing down from last item, got %d", idx)
}
// Navigate to middle and verify normal navigation still works
updatedModel, _ = list.Update(downKey)
list = updatedModel.(*listComponent[testItem])
_, idx = list.GetSelectedItem()
if idx != 1 {
t.Errorf("Expected to move to index 1, got %d", idx)
}
}
@@ -132,7 +132,7 @@ func (m *statusComponent) View() string {
modeForeground = t.BackgroundPanel()
}
command := m.app.Commands[commands.AgentCycleCommand]
command := m.app.Commands[commands.SwitchAgentCommand]
kb := command.Keybindings[0]
key := kb.Key
if kb.RequiresLeader {
@@ -670,28 +670,6 @@ func (m *Model) InsertAttachment(att *attachment.Attachment) {
m.SetCursorColumn(m.col)
}
// removeAttachmentAtCursor replaces the attachment at or immediately before the
// cursor with its textual display and positions the cursor at the end of the
// inserted text. Returns true if an attachment was removed.
func (m *Model) removeAttachmentAtCursor() bool {
att, startIdx, _ := m.isAttachmentAtCursor()
if att == nil {
return false
}
// Replace the attachment element with the display runes
before := m.value[m.row][:startIdx]
after := m.value[m.row][startIdx+1:]
replacement := runesToInterfaces([]rune(att.Display))
newRow := make([]any, 0, len(before)+len(replacement)+len(after))
newRow = append(newRow, before...)
newRow = append(newRow, replacement...)
newRow = append(newRow, after...)
m.value[m.row] = newRow
m.col = startIdx + len(replacement)
m.SetCursorColumn(m.col)
return true
}
// ReplaceRange replaces text from startCol to endCol on the current row with the given string.
// This preserves attachments outside the replaced range.
func (m *Model) ReplaceRange(startCol, endCol int, replacement string) {
@@ -1599,12 +1577,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
}
m.deleteBeforeCursor()
case key.Matches(msg, m.KeyMap.DeleteCharacterBackward):
// If the cursor is at or just after an attachment, convert it to text instead of deleting
if att, _, _ := m.isAttachmentAtCursor(); att != nil {
if m.removeAttachmentAtCursor() {
break
}
}
m.col = clamp(m.col, 0, len(m.value[m.row]))
if m.col <= 0 {
m.mergeLineAbove(m.row)
@@ -1615,12 +1587,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
m.SetCursorColumn(m.col - 1)
}
case key.Matches(msg, m.KeyMap.DeleteCharacterForward):
// If the cursor is on an attachment, convert it to text instead of deleting
if att, _, _ := m.isAttachmentAtCursor(); att != nil {
if m.removeAttachmentAtCursor() {
break
}
}
if len(m.value[m.row]) > 0 && m.col < len(m.value[m.row]) {
m.value[m.row] = slices.Delete(m.value[m.row], m.col, m.col+1)
}
@@ -2079,109 +2045,6 @@ func itemWidth(item any) int {
return 0
}
// forceWrapAttachment splits an attachment's display text across multiple lines
func forceWrapAttachment(att *attachment.Attachment, width int) [][]any {
if width <= 0 {
return [][]any{{att}}
}
display := att.Display
displayRunes := []rune(display)
if len(displayRunes) <= width {
return [][]any{{att}}
}
var lines [][]any
start := 0
for start < len(displayRunes) {
// Calculate how many runes fit in this line
end := start + width
if end > len(displayRunes) {
end = len(displayRunes)
}
// Create a wrapped attachment for this segment
wrappedAtt := &attachment.Attachment{
ID: att.ID,
Type: att.Type,
Display: string(displayRunes[start:end]),
URL: att.URL,
Filename: att.Filename,
MediaType: att.MediaType,
Source: att.Source,
}
lines = append(lines, []any{wrappedAtt})
start = end
}
return lines
}
// forceWrapWord splits a word that's too long to fit within the given width
func forceWrapWord(word []any, width int) [][]any {
if width <= 0 || len(word) == 0 {
return [][]any{word}
}
var lines [][]any
currentLine := []any{}
currentWidth := 0
for _, item := range word {
if att, ok := item.(*attachment.Attachment); ok {
// Handle attachment that might be too wide
attWidth := uniseg.StringWidth(att.Display)
// If the attachment display is too wide, split it
if attWidth > width {
// Finish current line if it has content
if len(currentLine) > 0 {
lines = append(lines, currentLine)
currentLine = []any{}
currentWidth = 0
}
// Split the attachment display across multiple lines
wrappedAttachment := forceWrapAttachment(att, width)
lines = append(lines, wrappedAttachment...)
continue
}
// If adding this attachment would exceed the width, start a new line
if currentWidth+attWidth > width && len(currentLine) > 0 {
lines = append(lines, currentLine)
currentLine = []any{}
currentWidth = 0
}
currentLine = append(currentLine, item)
currentWidth += attWidth
} else if r, ok := item.(rune); ok {
itemWidth := rw.RuneWidth(r)
// If adding this rune would exceed the width, start a new line
if currentWidth+itemWidth > width && len(currentLine) > 0 {
lines = append(lines, currentLine)
currentLine = []any{}
currentWidth = 0
}
currentLine = append(currentLine, item)
currentWidth += itemWidth
}
}
// Add the last line if it has content
if len(currentLine) > 0 {
lines = append(lines, currentLine)
}
return lines
}
func wrapInterfaces(content []any, width int) [][]any {
if width <= 0 {
return [][]any{content}
@@ -2213,49 +2076,11 @@ func wrapInterfaces(content []any, width int) [][]any {
if !inSpaces {
// End of a word
if lineW > 0 && lineW+wordW > width {
// If the word itself is too long to fit on a line, force-wrap it
if wordW > width {
wrappedLines := forceWrapWord(word, width)
lines = append(lines, wrappedLines...)
// Calculate width of the last wrapped line
lastLine := wrappedLines[len(wrappedLines)-1]
lineW = 0
for _, item := range lastLine {
if r, ok := item.(rune); ok {
lineW += rw.RuneWidth(r)
} else if att, ok := item.(*attachment.Attachment); ok {
lineW += uniseg.StringWidth(att.Display)
}
}
} else {
lines = append(lines, word)
lineW = wordW
}
lines = append(lines, word)
lineW = wordW
} else {
// Check if the word needs to be force-wrapped even when it fits on the current line
if wordW > width {
currentLine := lines[len(lines)-1]
wrappedWord := forceWrapWord(word, width-lineW)
if len(wrappedWord) > 0 {
lines[len(lines)-1] = append(currentLine, wrappedWord[0]...)
for i := 1; i < len(wrappedWord); i++ {
lines = append(lines, wrappedWord[i])
}
// Calculate width of the last wrapped line
lastLine := wrappedWord[len(wrappedWord)-1]
lineW = 0
for _, item := range lastLine {
if r, ok := item.(rune); ok {
lineW += rw.RuneWidth(r)
} else if att, ok := item.(*attachment.Attachment); ok {
lineW += uniseg.StringWidth(att.Display)
}
}
}
} else {
lines[len(lines)-1] = append(lines[len(lines)-1], word...)
lineW += wordW
}
lines[len(lines)-1] = append(lines[len(lines)-1], word...)
lineW += wordW
}
word = nil
wordW = 0
@@ -2285,49 +2110,11 @@ func wrapInterfaces(content []any, width int) [][]any {
// Handle any remaining word/spaces at the end of the content.
if wordW > 0 {
if lineW > 0 && lineW+wordW > width {
// If the word itself is too long to fit on a line, force-wrap it
if wordW > width {
wrappedLines := forceWrapWord(word, width)
lines = append(lines, wrappedLines...)
// Calculate width of the last wrapped line
lastLine := wrappedLines[len(wrappedLines)-1]
lineW = 0
for _, item := range lastLine {
if r, ok := item.(rune); ok {
lineW += rw.RuneWidth(r)
} else if att, ok := item.(*attachment.Attachment); ok {
lineW += uniseg.StringWidth(att.Display)
}
}
} else {
lines = append(lines, word)
lineW = wordW
}
lines = append(lines, word)
lineW = wordW
} else {
// Check if the word needs to be force-wrapped even when it fits on the current line
if wordW > width {
currentLine := lines[len(lines)-1]
wrappedWord := forceWrapWord(word, width-lineW)
if len(wrappedWord) > 0 {
lines[len(lines)-1] = append(currentLine, wrappedWord[0]...)
for i := 1; i < len(wrappedWord); i++ {
lines = append(lines, wrappedWord[i])
}
// Calculate width of the last wrapped line
lastLine := wrappedWord[len(wrappedWord)-1]
lineW = 0
for _, item := range lastLine {
if r, ok := item.(rune); ok {
lineW += rw.RuneWidth(r)
} else if att, ok := item.(*attachment.Attachment); ok {
lineW += uniseg.StringWidth(att.Display)
}
}
}
} else {
lines[len(lines)-1] = append(lines[len(lines)-1], word...)
lineW += wordW
}
lines[len(lines)-1] = append(lines[len(lines)-1], word...)
lineW += wordW
}
}
if spaceW > 0 {
@@ -1,75 +0,0 @@
package textarea
import (
"testing"
"github.com/sst/opencode/internal/attachment"
)
func TestRemoveAttachmentAtCursor_ConvertsToText_WhenCursorAfterAttachment(t *testing.T) {
m := New()
m.InsertString("a ")
att := &attachment.Attachment{ID: "1", Display: "@file.txt"}
m.InsertAttachment(att)
m.InsertString(" b")
// Position cursor immediately after the attachment (index 3: 'a',' ',att,' ', 'b')
m.SetCursorColumn(3)
if ok := m.removeAttachmentAtCursor(); !ok {
t.Fatalf("expected removal to occur")
}
got := m.Value()
want := "a @file.txt b"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestRemoveAttachmentAtCursor_ConvertsToText_WhenCursorOnAttachment(t *testing.T) {
m := New()
m.InsertString("x ")
att := &attachment.Attachment{ID: "2", Display: "@img.png"}
m.InsertAttachment(att)
m.InsertString(" y")
// Position cursor on the attachment token (index 2: 'x',' ',att,' ', 'y')
m.SetCursorColumn(2)
if ok := m.removeAttachmentAtCursor(); !ok {
t.Fatalf("expected removal to occur")
}
got := m.Value()
want := "x @img.png y"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestRemoveAttachmentAtCursor_StartOfLine(t *testing.T) {
m := New()
att := &attachment.Attachment{ID: "3", Display: "@a.txt"}
m.InsertAttachment(att)
m.InsertString(" tail")
// Position cursor immediately after the attachment at start of line (index 1)
m.SetCursorColumn(1)
if ok := m.removeAttachmentAtCursor(); !ok {
t.Fatalf("expected removal to occur at start of line")
}
if got := m.Value(); got != "@a.txt tail" {
t.Fatalf("unexpected value: %q", got)
}
}
func TestRemoveAttachmentAtCursor_NoAttachment_NoChange(t *testing.T) {
m := New()
m.InsertString("hello world")
col := m.CursorColumn()
if ok := m.removeAttachmentAtCursor(); ok {
t.Fatalf("did not expect removal to occur")
}
if m.Value() != "hello world" || m.CursorColumn() != col {
t.Fatalf("value or cursor unexpectedly changed")
}
}
+116 -294
View File
@@ -23,6 +23,7 @@ import (
"github.com/sst/opencode/internal/components/chat"
cmdcomp "github.com/sst/opencode/internal/components/commands"
"github.com/sst/opencode/internal/components/dialog"
"github.com/sst/opencode/internal/components/fileviewer"
"github.com/sst/opencode/internal/components/modal"
"github.com/sst/opencode/internal/components/status"
"github.com/sst/opencode/internal/components/toast"
@@ -58,8 +59,6 @@ const interruptDebounceTimeout = 1 * time.Second
const exitDebounceTimeout = 1 * time.Second
type Model struct {
tea.Model
tea.CursorModel
width, height int
app *app.App
modal layout.Modal
@@ -77,6 +76,7 @@ type Model struct {
interruptKeyState InterruptKeyState
exitKeyState ExitKeyState
messagesRight bool
fileViewer fileviewer.Model
}
func (a Model) Init() tea.Cmd {
@@ -92,6 +92,13 @@ func (a Model) Init() tea.Cmd {
cmds = append(cmds, a.status.Init())
cmds = append(cmds, a.completions.Init())
cmds = append(cmds, a.toastManager.Init())
cmds = append(cmds, a.fileViewer.Init())
// Check if we should show the init dialog
cmds = append(cmds, func() tea.Msg {
shouldShow := a.app.Info.Git && a.app.Info.Time.Initialized > 0
return dialog.ShowInitDialogMsg{Show: shouldShow}
})
return tea.Batch(cmds...)
}
@@ -142,23 +149,6 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
if a.app.IsBashMode {
if keyString == "backspace" && a.editor.Length() == 0 {
a.app.IsBashMode = false
return a, nil
}
if keyString == "enter" || keyString == "esc" || keyString == "ctrl+c" {
a.app.IsBashMode = false
if keyString == "enter" {
updated, cmd := a.editor.SubmitBash()
a.editor = updated.(chat.EditorComponent)
cmds = append(cmds, cmd)
}
return a, tea.Batch(cmds...)
}
}
// 1. Handle active modal
if a.modal != nil {
switch keyString {
@@ -197,8 +187,7 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// 3. Handle completions trigger
if keyString == "/" &&
!a.showCompletionDialog &&
a.editor.Value() == "" &&
!a.app.IsBashMode {
a.editor.Value() == "" {
a.showCompletionDialog = true
updated, cmd := a.editor.Update(msg)
@@ -216,8 +205,7 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Handle file completions trigger
if keyString == "@" &&
!a.showCompletionDialog &&
!a.app.IsBashMode {
!a.showCompletionDialog {
a.showCompletionDialog = true
updated, cmd := a.editor.Update(msg)
@@ -233,11 +221,6 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return a, tea.Sequence(cmds...)
}
if keyString == "!" && a.editor.Value() == "" {
a.app.IsBashMode = true
return a, nil
}
if a.showCompletionDialog {
switch keyString {
case "tab", "enter", "esc", "ctrl+c", "up", "down", "ctrl+p", "ctrl+n":
@@ -372,11 +355,6 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
a.modal = nil
return a, cmd
case dialog.ReopenSessionModalMsg:
// Reopen the session modal (used when exiting rename mode)
sessionDialog := dialog.NewSessionDialog(a.app)
a.modal = sessionDialog
return a, nil
case commands.ExecuteCommandMsg:
updated, cmd := a.executeCommand(commands.Command(msg))
return updated, cmd
@@ -391,41 +369,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return a, toast.NewErrorToast(msg.Error())
case app.SendPrompt:
a.showCompletionDialog = false
// If we're in a child session, switch back to parent before sending prompt
if a.app.Session.ParentID != "" {
parentSession, err := a.app.Client.Session.Get(context.Background(), a.app.Session.ParentID)
if err != nil {
slog.Error("Failed to get parent session", "error", err)
return a, toast.NewErrorToast("Failed to get parent session")
}
a.app.Session = parentSession
a.app, cmd = a.app.SendPrompt(context.Background(), msg)
cmds = append(cmds, tea.Sequence(
util.CmdHandler(app.SessionSelectedMsg(parentSession)),
cmd,
))
} else {
a.app, cmd = a.app.SendPrompt(context.Background(), msg)
cmds = append(cmds, cmd)
}
case app.SendShell:
// If we're in a child session, switch back to parent before sending prompt
if a.app.Session.ParentID != "" {
parentSession, err := a.app.Client.Session.Get(context.Background(), a.app.Session.ParentID)
if err != nil {
slog.Error("Failed to get parent session", "error", err)
return a, toast.NewErrorToast("Failed to get parent session")
}
a.app.Session = parentSession
a.app, cmd = a.app.SendShell(context.Background(), msg.Command)
cmds = append(cmds, tea.Sequence(
util.CmdHandler(app.SessionSelectedMsg(parentSession)),
cmd,
))
} else {
a.app, cmd = a.app.SendShell(context.Background(), msg.Command)
cmds = append(cmds, cmd)
}
a.app, cmd = a.app.SendPrompt(context.Background(), msg)
cmds = append(cmds, cmd)
case app.SetEditorContentMsg:
// Set the editor content without sending
a.editor.SetValueWithAttachments(msg.Text)
@@ -437,6 +382,9 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
a.app.Messages = []app.Message{}
case dialog.CompletionDialogCloseMsg:
a.showCompletionDialog = false
case chat.AttachmentInsertedMsg:
// Close completion dialog when the editor inserts an attachment
a.showCompletionDialog = false
case opencode.EventListResponseEventInstallationUpdated:
return a, toast.NewSuccessToast(
"opencode updated to "+msg.Properties.Version+", restart to apply.",
@@ -607,6 +555,12 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
slog.Error("Server error", "name", err.Name, "message", err.Data.Message)
return a, toast.NewErrorToast(err.Data.Message, toast.WithTitle(string(err.Name)))
}
case opencode.EventListResponseEventFileWatcherUpdated:
if a.fileViewer.HasFile() {
if a.fileViewer.Filename() == msg.Properties.File {
return a.openFile(msg.Properties.File)
}
}
case tea.WindowSizeMsg:
msg.Height -= 2 // Make space for the status bar
a.width, a.height = msg.Width, msg.Height
@@ -645,10 +599,6 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
a.app.State.UpdateModelUsage(msg.Provider.ID, msg.Model.ID)
cmds = append(cmds, a.app.SaveState())
case app.AgentSelectedMsg:
updated, cmd := a.app.SwitchToAgent(msg.AgentName)
a.app = updated
cmds = append(cmds, cmd)
case dialog.ThemeSelectedMsg:
a.app.State.Theme = msg.ThemeName
cmds = append(cmds, a.app.SaveState())
@@ -668,6 +618,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Reset exit key state after timeout
a.exitKeyState = ExitKeyIdle
a.editor.SetExitKeyInDebounce(false)
case dialog.FindSelectedMsg:
return a.openFile(msg.FilePath)
case tea.PasteMsg, tea.ClipboardMsg:
// Paste events: prioritize modal if active, otherwise editor
if a.modal != nil {
@@ -735,45 +687,6 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
updated, cmd := a.executeCommand(commands.Command(command))
a = updated.(Model)
cmds = append(cmds, cmd)
case "/tui/show-toast":
var body struct {
Title string `json:"title,omitempty"`
Message string `json:"message"`
Variant string `json:"variant"`
}
json.Unmarshal((msg.Body), &body)
var toastCmd tea.Cmd
switch body.Variant {
case "info":
if body.Title != "" {
toastCmd = toast.NewInfoToast(body.Message, toast.WithTitle(body.Title))
} else {
toastCmd = toast.NewInfoToast(body.Message)
}
case "success":
if body.Title != "" {
toastCmd = toast.NewSuccessToast(body.Message, toast.WithTitle(body.Title))
} else {
toastCmd = toast.NewSuccessToast(body.Message)
}
case "warning":
if body.Title != "" {
toastCmd = toast.NewErrorToast(body.Message, toast.WithTitle(body.Title))
} else {
toastCmd = toast.NewErrorToast(body.Message)
}
case "error":
if body.Title != "" {
toastCmd = toast.NewErrorToast(body.Message, toast.WithTitle(body.Title))
} else {
toastCmd = toast.NewErrorToast(body.Message)
}
default:
slog.Error("Invalid toast variant", "variant", body.Variant)
return a, nil
}
cmds = append(cmds, toastCmd)
default:
break
@@ -805,20 +718,22 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds = append(cmds, cmd)
}
fv, cmd := a.fileViewer.Update(msg)
a.fileViewer = fv
cmds = append(cmds, cmd)
return a, tea.Batch(cmds...)
}
func (a Model) View() (string, *tea.Cursor) {
func (a Model) View() string {
t := theme.CurrentTheme()
var mainLayout string
var editorX int
var editorY int
if a.app.Session.ID == "" {
mainLayout, editorX, editorY = a.home()
mainLayout = a.home()
} else {
mainLayout, editorX, editorY = a.chat()
mainLayout = a.chat()
}
mainLayout = styles.NewStyle().
Background(t.Background()).
@@ -842,19 +757,34 @@ func (a Model) View() (string, *tea.Cursor) {
if theme.CurrentThemeUsesAnsiColors() {
mainLayout = util.ConvertRGBToAnsi16Colors(mainLayout)
}
cursor := a.editor.Cursor()
cursor.Position.X += editorX
cursor.Position.Y += editorY
return mainLayout + "\n" + a.status.View(), cursor
return mainLayout + "\n" + a.status.View()
}
func (a Model) Cleanup() {
a.status.Cleanup()
}
func (a Model) home() (string, int, int) {
func (a Model) openFile(filepath string) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
response, err := a.app.Client.File.Read(
context.Background(),
opencode.FileReadParams{
Path: opencode.F(filepath),
},
)
if err != nil {
slog.Error("Failed to read file", "error", err)
return a, toast.NewErrorToast("Failed to read file")
}
a.fileViewer, cmd = a.fileViewer.SetFile(
filepath,
response.Content,
response.Type == "patch",
)
return a, cmd
}
func (a Model) home() string {
t := theme.CurrentTheme()
effectiveWidth := a.width - 4
baseStyle := styles.NewStyle().Background(t.Background())
@@ -946,21 +876,14 @@ func (a Model) home() (string, int, int) {
styles.WhitespaceStyle(t.Background()),
)
editorX := max(0, (effectiveWidth-editorWidth)/2)
editorX := (effectiveWidth - editorWidth) / 2
editorY := (a.height / 2) + (mainHeight / 2) - 2
if editorLines > 1 {
content := a.editor.Content()
editorHeight := lipgloss.Height(content)
if editorY+editorHeight > a.height {
difference := (editorY + editorHeight) - a.height
editorY -= difference
}
mainLayout = layout.PlaceOverlay(
editorX,
editorY,
content,
a.editor.Content(),
mainLayout,
)
}
@@ -978,10 +901,10 @@ func (a Model) home() (string, int, int) {
)
}
return mainLayout, editorX + 5, editorY + 2
return mainLayout
}
func (a Model) chat() (string, int, int) {
func (a Model) chat() string {
effectiveWidth := a.width - 4
t := theme.CurrentTheme()
editorView := a.editor.View()
@@ -998,20 +921,14 @@ func (a Model) chat() (string, int, int) {
)
mainLayout := messagesView + "\n" + editorView
editorX := max(0, (effectiveWidth-editorWidth)/2)
editorY := a.height - editorHeight
editorX := (effectiveWidth - editorWidth) / 2
if lines > 1 {
content := a.editor.Content()
editorHeight := lipgloss.Height(content)
if editorY+editorHeight > a.height {
difference := (editorY + editorHeight) - a.height
editorY -= difference
}
editorY := a.height - editorHeight
mainLayout = layout.PlaceOverlay(
editorX,
editorY,
content,
a.editor.Content(),
mainLayout,
)
}
@@ -1030,7 +947,7 @@ func (a Model) chat() (string, int, int) {
)
}
return mainLayout, editorX + 5, editorY + 2
return mainLayout
}
func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
@@ -1042,11 +959,11 @@ func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
case commands.AppHelpCommand:
helpDialog := dialog.NewHelpDialog(a.app)
a.modal = helpDialog
case commands.AgentCycleCommand:
case commands.SwitchAgentCommand:
updated, cmd := a.app.SwitchAgent()
a.app = updated
cmds = append(cmds, cmd)
case commands.AgentCycleReverseCommand:
case commands.SwitchAgentReverseCommand:
updated, cmd := a.app.SwitchAgentReverse()
a.app = updated
cmds = append(cmds, cmd)
@@ -1141,122 +1058,6 @@ func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
}
// TODO: block until compaction is complete
a.app.CompactSession(context.Background())
case commands.SessionChildCycleCommand:
if a.app.Session.ID == "" {
return a, nil
}
cmds = append(cmds, func() tea.Msg {
parentSessionID := a.app.Session.ID
var parentSession *opencode.Session
if a.app.Session.ParentID != "" {
parentSessionID = a.app.Session.ParentID
session, err := a.app.Client.Session.Get(context.Background(), parentSessionID)
if err != nil {
slog.Error("Failed to get parent session", "error", err)
return toast.NewErrorToast("Failed to get parent session")
}
parentSession = session
} else {
parentSession = a.app.Session
}
children, err := a.app.Client.Session.Children(context.Background(), parentSessionID)
if err != nil {
slog.Error("Failed to get session children", "error", err)
return toast.NewErrorToast("Failed to get session children")
}
// Reverse sort the children (newest first)
slices.Reverse(*children)
// Create combined array: [parent, child1, child2, ...]
sessions := []*opencode.Session{parentSession}
for i := range *children {
sessions = append(sessions, &(*children)[i])
}
if len(sessions) == 1 {
return toast.NewInfoToast("No child sessions available")
}
// Find current session index in combined array
currentIndex := -1
for i, session := range sessions {
if session.ID == a.app.Session.ID {
currentIndex = i
break
}
}
// If session not found, default to parent (shouldn't happen)
if currentIndex == -1 {
currentIndex = 0
}
// Cycle to next session (parent or child)
nextIndex := (currentIndex + 1) % len(sessions)
nextSession := sessions[nextIndex]
return app.SessionSelectedMsg(nextSession)
})
case commands.SessionChildCycleReverseCommand:
if a.app.Session.ID == "" {
return a, nil
}
cmds = append(cmds, func() tea.Msg {
parentSessionID := a.app.Session.ID
var parentSession *opencode.Session
if a.app.Session.ParentID != "" {
parentSessionID = a.app.Session.ParentID
session, err := a.app.Client.Session.Get(context.Background(), parentSessionID)
if err != nil {
slog.Error("Failed to get parent session", "error", err)
return toast.NewErrorToast("Failed to get parent session")
}
parentSession = session
} else {
parentSession = a.app.Session
}
children, err := a.app.Client.Session.Children(context.Background(), parentSessionID)
if err != nil {
slog.Error("Failed to get session children", "error", err)
return toast.NewErrorToast("Failed to get session children")
}
// Reverse sort the children (newest first)
slices.Reverse(*children)
// Create combined array: [parent, child1, child2, ...]
sessions := []*opencode.Session{parentSession}
for i := range *children {
sessions = append(sessions, &(*children)[i])
}
if len(sessions) == 1 {
return toast.NewInfoToast("No child sessions available")
}
// Find current session index in combined array
currentIndex := -1
for i, session := range sessions {
if session.ID == a.app.Session.ID {
currentIndex = i
break
}
}
// If session not found, default to parent (shouldn't happen)
if currentIndex == -1 {
currentIndex = 0
}
// Cycle to previous session (parent or child)
nextIndex := (currentIndex - 1 + len(sessions)) % len(sessions)
nextSession := sessions[nextIndex]
return app.SessionSelectedMsg(nextSession)
})
case commands.SessionExportCommand:
if a.app.Session.ID == "" {
return a, toast.NewErrorToast("No active session to export.")
@@ -1315,32 +1116,27 @@ func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
}
cmds = append(cmds, util.CmdHandler(chat.ToggleToolDetailsMsg{}))
cmds = append(cmds, toast.NewInfoToast(message))
case commands.ThinkingBlocksCommand:
message := "Thinking blocks are now visible"
if a.messages.ThinkingBlocksVisible() {
message = "Thinking blocks are now hidden"
}
cmds = append(cmds, util.CmdHandler(chat.ToggleThinkingBlocksMsg{}))
cmds = append(cmds, toast.NewInfoToast(message))
case commands.ModelListCommand:
modelDialog := dialog.NewModelDialog(a.app)
a.modal = modelDialog
case commands.AgentListCommand:
agentDialog := dialog.NewAgentDialog(a.app)
a.modal = agentDialog
case commands.ModelCycleRecentCommand:
slog.Debug("ModelCycleRecentCommand triggered")
updated, cmd := a.app.CycleRecentModel()
a.app = updated
cmds = append(cmds, cmd)
case commands.ModelCycleRecentReverseCommand:
updated, cmd := a.app.CycleRecentModelReverse()
a.app = updated
cmds = append(cmds, cmd)
case commands.ThemeListCommand:
themeDialog := dialog.NewThemeDialog()
a.modal = themeDialog
// case commands.FileListCommand:
// a.editor.Blur()
// findDialog := dialog.NewFindDialog(a.fileProvider)
// cmds = append(cmds, findDialog.Init())
// a.modal = findDialog
case commands.FileCloseCommand:
a.fileViewer, cmd = a.fileViewer.Clear()
cmds = append(cmds, cmd)
case commands.FileDiffToggleCommand:
a.fileViewer, cmd = a.fileViewer.ToggleDiff()
cmds = append(cmds, cmd)
a.app.State.SplitDiff = a.fileViewer.DiffStyle() == fileviewer.DiffStyleSplit
cmds = append(cmds, a.app.SaveState())
case commands.FileSearchCommand:
return a, nil
case commands.ProjectInitCommand:
cmds = append(cmds, a.app.InitializeProject(context.Background()))
case commands.InputClearCommand:
@@ -1371,21 +1167,45 @@ func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
case commands.MessagesPageUpCommand:
updated, cmd := a.messages.PageUp()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
if a.fileViewer.HasFile() {
a.fileViewer, cmd = a.fileViewer.PageUp()
cmds = append(cmds, cmd)
} else {
updated, cmd := a.messages.PageUp()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
}
case commands.MessagesPageDownCommand:
updated, cmd := a.messages.PageDown()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
if a.fileViewer.HasFile() {
a.fileViewer, cmd = a.fileViewer.PageDown()
cmds = append(cmds, cmd)
} else {
updated, cmd := a.messages.PageDown()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
}
case commands.MessagesHalfPageUpCommand:
updated, cmd := a.messages.HalfPageUp()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
if a.fileViewer.HasFile() {
a.fileViewer, cmd = a.fileViewer.HalfPageUp()
cmds = append(cmds, cmd)
} else {
updated, cmd := a.messages.HalfPageUp()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
}
case commands.MessagesHalfPageDownCommand:
updated, cmd := a.messages.HalfPageDown()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
if a.fileViewer.HasFile() {
a.fileViewer, cmd = a.fileViewer.HalfPageDown()
cmds = append(cmds, cmd)
} else {
updated, cmd := a.messages.HalfPageDown()
a.messages = updated.(chat.MessagesComponent)
cmds = append(cmds, cmd)
}
case commands.MessagesLayoutToggleCommand:
a.messagesRight = !a.messagesRight
a.app.State.MessagesRight = a.messagesRight
cmds = append(cmds, a.app.SaveState())
case commands.MessagesCopyCommand:
updated, cmd := a.messages.CopyLastMessage()
a.messages = updated.(chat.MessagesComponent)
@@ -1435,6 +1255,8 @@ func NewModel(app *app.App) tea.Model {
toastManager: toast.NewToastManager(),
interruptKeyState: InterruptKeyIdle,
exitKeyState: ExitKeyIdle,
fileViewer: fileviewer.New(app),
messagesRight: app.State.MessagesRight,
}
return model
-4
View File
@@ -3,7 +3,6 @@ package util
import (
"fmt"
"path/filepath"
"regexp"
"strings"
"unicode"
@@ -86,8 +85,6 @@ func Extension(path string) string {
func ToMarkdown(content string, width int, backgroundColor compat.AdaptiveColor) string {
r := styles.GetMarkdownRenderer(width-6, backgroundColor)
content = strings.ReplaceAll(content, RootPath+"/", "")
hyphenRegex := regexp.MustCompile(`-([^ \-|]|$)`)
content = hyphenRegex.ReplaceAllString(content, "\u2011$1")
rendered, _ := r.Render(content)
lines := strings.Split(rendered, "\n")
@@ -108,6 +105,5 @@ func ToMarkdown(content string, width int, backgroundColor compat.AdaptiveColor)
}
}
content = strings.Join(lines, "\n")
content = strings.ReplaceAll(content, "\u2011", "-")
return strings.TrimSuffix(content, "\n")
}

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