mirror of
https://fastgit.cc/https://github.com/anomalyco/opencode
synced 2026-05-04 07:40:39 +08:00
Compare commits
96 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bf841ab7a | ||
|
|
49727e3eab | ||
|
|
592c6ef97f | ||
|
|
00579f0ec1 | ||
|
|
69d516c7fa | ||
|
|
bedeb626b2 | ||
|
|
a4c14dbb2d | ||
|
|
036b24791d | ||
|
|
93b71477e6 | ||
|
|
1357319f6f | ||
|
|
e729eed34d | ||
|
|
2e5fdd8cef | ||
|
|
21f15f15c1 | ||
|
|
c6344c5714 | ||
|
|
7505fa61b9 | ||
|
|
77bb5af092 | ||
|
|
0c4fe73cbf | ||
|
|
e132f6183d | ||
|
|
e06ebb6780 | ||
|
|
66d99ba527 | ||
|
|
f2021a85d6 | ||
|
|
7d54f893c9 | ||
|
|
e1f80c0067 | ||
|
|
4ff13d3290 | ||
|
|
832d8da453 | ||
|
|
b5d61b77f7 | ||
|
|
790e9947bd | ||
|
|
2056781cf7 | ||
|
|
ed5f76d849 | ||
|
|
93102dc84b | ||
|
|
e2920ac262 | ||
|
|
aa5e39e744 | ||
|
|
296cc41a07 | ||
|
|
482239b848 | ||
|
|
17b07877e5 | ||
|
|
dedaa34dc1 | ||
|
|
5785ded6e2 | ||
|
|
d1876e3031 | ||
|
|
9fa3e0a0ec | ||
|
|
47c327641b | ||
|
|
81583cddbd | ||
|
|
d16ae1fc4e | ||
|
|
14e00a06b6 | ||
|
|
5cc44c872e | ||
|
|
cadc5982f1 | ||
|
|
6aa157cfe6 | ||
|
|
9fff9a37d0 | ||
|
|
b289fd9dc7 | ||
|
|
13d4a802ac | ||
|
|
c4ae3e429c | ||
|
|
e9cb360cb7 | ||
|
|
596d4e4490 | ||
|
|
45451095f7 | ||
|
|
aae354c951 | ||
|
|
4cddda3e16 | ||
|
|
834aa036a4 | ||
|
|
6d1b6a6fb1 | ||
|
|
e78fe8dcba | ||
|
|
f62d826037 | ||
|
|
342f4239e4 | ||
|
|
5141fe8d7d | ||
|
|
3a9dd306db | ||
|
|
e32b6e2cc2 | ||
|
|
fab0e5de04 | ||
|
|
61105b487f | ||
|
|
6f584ec641 | ||
|
|
3a2b2f13f2 | ||
|
|
be13e71fb9 | ||
|
|
dd0c049119 | ||
|
|
ee2b57958d | ||
|
|
4178b3c6ae | ||
|
|
2c2752ee02 | ||
|
|
5a17f44da4 | ||
|
|
354e55ecef | ||
|
|
10735f93ca | ||
|
|
ccaebdcd16 | ||
|
|
2bbd7a167a | ||
|
|
f12d470b33 | ||
|
|
0835170224 | ||
|
|
3530885f48 | ||
|
|
a071a2b7f4 | ||
|
|
b2f2c9ac37 | ||
|
|
631722213b | ||
|
|
80b25c79bb | ||
|
|
3d9c5b4adf | ||
|
|
a3064e2c32 | ||
|
|
275bc4d2c8 | ||
|
|
39106718ed | ||
|
|
02cfdfbf5b | ||
|
|
1ec71e419b | ||
|
|
5fbbdcaf64 | ||
|
|
2b6afe90d0 | ||
|
|
5f34dcc792 | ||
|
|
681abcbf2d | ||
|
|
603e81ef5a | ||
|
|
fb0a200ecf |
60
.github/workflows/duplicate-issues.yml
vendored
Normal file
60
.github/workflows/duplicate-issues.yml
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
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]
|
||||
|
||||
If none of these address your specific case, please let us know how this issue differs.'
|
||||
|
||||
If no clear duplicates are found, do not comment."
|
||||
53
.github/workflows/guidelines-check.yml
vendored
Normal file
53
.github/workflows/guidelines-check.yml
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
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."
|
||||
4
.github/workflows/publish.yml
vendored
4
.github/workflows/publish.yml
vendored
@@ -52,16 +52,14 @@ 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
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
|
||||
10
.opencode/agent/git-committer.md
Normal file
10
.opencode/agent/git-committer.md
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
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.
|
||||
92
STATS.md
92
STATS.md
@@ -1,47 +1,49 @@
|
||||
# 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) |
|
||||
| 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) |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode/cloud-core",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/cloud-function",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/cloud-web",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"private": true,
|
||||
"description": "",
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/function",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"name": "opencode",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -126,7 +126,7 @@ if (!snapshot) {
|
||||
"",
|
||||
].join("\n")
|
||||
|
||||
for (const pkg of ["opencode", "opencode-bin"]) {
|
||||
for (const pkg of ["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`
|
||||
|
||||
@@ -5,6 +5,7 @@ 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
|
||||
@@ -14,6 +15,11 @@ export namespace Agent {
|
||||
mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]),
|
||||
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(),
|
||||
@@ -31,6 +37,15 @@ 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",
|
||||
@@ -41,17 +56,20 @@ export namespace Agent {
|
||||
todowrite: false,
|
||||
},
|
||||
options: {},
|
||||
permission: agentPermission,
|
||||
mode: "subagent",
|
||||
},
|
||||
build: {
|
||||
name: "build",
|
||||
tools: {},
|
||||
options: {},
|
||||
permission: agentPermission,
|
||||
mode: "primary",
|
||||
},
|
||||
plan: {
|
||||
name: "plan",
|
||||
options: {},
|
||||
permission: agentPermission,
|
||||
tools: {
|
||||
write: false,
|
||||
edit: false,
|
||||
@@ -70,25 +88,30 @@ export namespace Agent {
|
||||
item = result[key] = {
|
||||
name: key,
|
||||
mode: "all",
|
||||
permission: agentPermission,
|
||||
options: {},
|
||||
tools: {},
|
||||
}
|
||||
const { model, prompt, tools, description, temperature, top_p, mode, ...extra } = value
|
||||
const { model, prompt, tools, description, temperature, top_p, mode, permission, ...extra } = value
|
||||
item.options = {
|
||||
...item.options,
|
||||
...extra,
|
||||
}
|
||||
if (value.model) item.model = Provider.parseModel(value.model)
|
||||
if (value.prompt) item.prompt = value.prompt
|
||||
if (value.tools)
|
||||
if (model) item.model = Provider.parseModel(model)
|
||||
if (prompt) item.prompt = prompt
|
||||
if (tools)
|
||||
item.tools = {
|
||||
...item.tools,
|
||||
...value.tools,
|
||||
...tools,
|
||||
}
|
||||
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
|
||||
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 ?? {})
|
||||
}
|
||||
}
|
||||
return result
|
||||
})
|
||||
@@ -131,3 +154,32 @@ 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
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ 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"
|
||||
|
||||
@@ -141,7 +141,6 @@ 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()
|
||||
|
||||
@@ -12,7 +12,7 @@ export function FormatError(input: unknown) {
|
||||
}
|
||||
if (Config.InvalidError.isInstance(input))
|
||||
return [
|
||||
`Config file at ${input.data.path} is invalid`,
|
||||
`Config file at ${input.data.path} is invalid` + (input.data.message ? `: ${input.data.message}` : ""),
|
||||
...(input.data.issues?.map((issue) => "↳ " + issue.message + " " + issue.path.join(".")) ?? []),
|
||||
].join("\n")
|
||||
|
||||
|
||||
@@ -105,11 +105,15 @@ export namespace Config {
|
||||
result.plugin = result.plugin || []
|
||||
result.plugin.push(
|
||||
...[
|
||||
...(await Filesystem.globUp("plugin/*.ts", Global.Path.config, Global.Path.config)),
|
||||
...(await Filesystem.globUp(".opencode/plugin/*.ts", app.path.cwd, app.path.root)),
|
||||
...(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)),
|
||||
].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"
|
||||
@@ -164,6 +168,9 @@ 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(),
|
||||
@@ -174,6 +181,13 @@ 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({
|
||||
@@ -243,9 +257,6 @@ 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"),
|
||||
@@ -418,14 +429,14 @@ export namespace Config {
|
||||
return load(text, filepath)
|
||||
}
|
||||
|
||||
async function load(text: string, filepath: string) {
|
||||
async function load(text: string, configFilepath: string) {
|
||||
text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
|
||||
return process.env[varName] || ""
|
||||
})
|
||||
|
||||
const fileMatches = text.match(/\{file:[^}]+\}/g)
|
||||
if (fileMatches) {
|
||||
const configDir = path.dirname(filepath)
|
||||
const configDir = path.dirname(configFilepath)
|
||||
const lines = text.split("\n")
|
||||
|
||||
for (const match of fileMatches) {
|
||||
@@ -438,7 +449,20 @@ 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()).trim()
|
||||
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()
|
||||
// escape newlines/quotes, strip outer quotes
|
||||
text = text.replace(match, JSON.stringify(fileContent).slice(1, -1))
|
||||
}
|
||||
@@ -463,7 +487,7 @@ export namespace Config {
|
||||
.join("\n")
|
||||
|
||||
throw new JsonError({
|
||||
path: filepath,
|
||||
path: configFilepath,
|
||||
message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
|
||||
})
|
||||
}
|
||||
@@ -472,21 +496,21 @@ export namespace Config {
|
||||
if (parsed.success) {
|
||||
if (!parsed.data.$schema) {
|
||||
parsed.data.$schema = "https://opencode.ai/config.json"
|
||||
await Bun.write(filepath, JSON.stringify(parsed.data, null, 2))
|
||||
await Bun.write(configFilepath, 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, filepath)
|
||||
data.plugin[i] = import.meta.resolve(plugin, configFilepath)
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
throw new InvalidError({ path: filepath, issues: parsed.error.issues })
|
||||
throw new InvalidError({ path: configFilepath, issues: parsed.error.issues })
|
||||
}
|
||||
export const JsonError = NamedError.create(
|
||||
"ConfigJsonError",
|
||||
@@ -501,6 +525,7 @@ export namespace Config {
|
||||
z.object({
|
||||
path: z.string(),
|
||||
issues: z.custom<z.ZodIssue[]>().optional(),
|
||||
message: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ 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"]
|
||||
|
||||
function truthy(key: string) {
|
||||
const value = process.env[key]?.toLowerCase()
|
||||
|
||||
@@ -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: item.environment,
|
||||
env: { ...process.env, ...item.environment },
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
})
|
||||
|
||||
@@ -25,9 +25,10 @@ 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 = "6"
|
||||
const CACHE_VERSION = "8"
|
||||
|
||||
const version = await Bun.file(path.join(Global.Path.cache, "version"))
|
||||
.text()
|
||||
|
||||
@@ -21,6 +21,9 @@ 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,
|
||||
|
||||
@@ -94,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}`.cwd(Global.Path.bin).nothrow()
|
||||
await $`unzip -o -q ${zipPath}`.quiet().cwd(Global.Path.bin).nothrow()
|
||||
await fs.rm(zipPath, { force: true })
|
||||
|
||||
const extractedPath = path.join(Global.Path.bin, "vscode-eslint-main")
|
||||
@@ -269,7 +269,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}`.cwd(Global.Path.bin).nothrow()
|
||||
await $`unzip -o -q ${zipPath}`.quiet().cwd(Global.Path.bin).nothrow()
|
||||
|
||||
await fs.rm(zipPath, {
|
||||
force: true,
|
||||
@@ -371,7 +371,7 @@ export namespace LSPServer {
|
||||
await Bun.file(tempPath).write(downloadResponse)
|
||||
|
||||
if (ext === "zip") {
|
||||
await $`unzip -o -q ${tempPath}`.cwd(Global.Path.bin).nothrow()
|
||||
await $`unzip -o -q ${tempPath}`.quiet().cwd(Global.Path.bin).nothrow()
|
||||
} else {
|
||||
await $`tar -xf ${tempPath}`.cwd(Global.Path.bin).nothrow()
|
||||
}
|
||||
@@ -490,7 +490,7 @@ export namespace LSPServer {
|
||||
const zipPath = path.join(Global.Path.bin, "clangd.zip")
|
||||
await Bun.file(zipPath).write(downloadResponse)
|
||||
|
||||
await $`unzip -o -q ${zipPath}`.cwd(Global.Path.bin).nothrow()
|
||||
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", ""))
|
||||
|
||||
@@ -82,11 +82,13 @@ 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,
|
||||
@@ -155,7 +157,7 @@ export namespace Permission {
|
||||
public readonly permissionID: string,
|
||||
public readonly toolCallID?: string,
|
||||
) {
|
||||
super(`The user rejected permission to use this functionality`)
|
||||
super(`The user rejected permission to use this specific tool call. You may try again with different parameters.`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,33 +83,19 @@ export namespace ProviderTransform {
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function options(providerID: string, modelID: string): Record<string, any> | undefined {
|
||||
if (modelID.includes("gpt-5")) {
|
||||
if (providerID === "azure") {
|
||||
return {
|
||||
reasoning_effort: "minimal",
|
||||
text_verbosity: "verbose",
|
||||
}
|
||||
}
|
||||
return {
|
||||
reasoningEffort: "minimal",
|
||||
textVerbosity: "low",
|
||||
// reasoningSummary: "auto",
|
||||
// include: ["reasoning.encrypted_content"],
|
||||
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"
|
||||
}
|
||||
}
|
||||
// if (modelID.includes("claude")) {
|
||||
// return {
|
||||
// thinking: {
|
||||
// type: "enabled",
|
||||
// budgetTokens: 32000,
|
||||
// },
|
||||
// }
|
||||
// }
|
||||
// if (_providerID === "bedrock") {
|
||||
// return {
|
||||
// reasoningConfig: { type: "enabled", budgetTokens: 32000 },
|
||||
// }
|
||||
// }
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +296,47 @@ 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({
|
||||
@@ -551,6 +592,36 @@ 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({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import path from "path"
|
||||
import { spawn } from "child_process"
|
||||
import { Decimal } from "decimal.js"
|
||||
import { z, ZodSchema } from "zod"
|
||||
import {
|
||||
@@ -42,6 +43,8 @@ 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"
|
||||
|
||||
export namespace Session {
|
||||
const log = Log.create({ service: "session" })
|
||||
@@ -522,7 +525,9 @@ export namespace Session {
|
||||
t.execute(args, {
|
||||
sessionID: input.sessionID,
|
||||
abort: new AbortController().signal,
|
||||
agent: input.agent!,
|
||||
messageID: userMsg.id,
|
||||
extra: { bypassCwdCheck: true },
|
||||
metadata: async () => {},
|
||||
}),
|
||||
)
|
||||
@@ -665,14 +670,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.length === 1 && !session.parentID && isDefaultTitle(session.title)) {
|
||||
if (msgs.filter((m) => m.info.role === "user").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),
|
||||
...ProviderTransform.options(input.providerID, small.info.id, input.sessionID),
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
@@ -764,11 +769,11 @@ export namespace Session {
|
||||
|
||||
const enabledTools = pipe(
|
||||
agent.tools,
|
||||
mergeDeep(await ToolRegistry.enabled(input.providerID, input.modelID)),
|
||||
mergeDeep(await ToolRegistry.enabled(input.providerID, input.modelID, agent)),
|
||||
mergeDeep(input.tools ?? {}),
|
||||
)
|
||||
for (const item of await ToolRegistry.tools(input.providerID, input.modelID)) {
|
||||
if (enabledTools[item.id] === false) continue
|
||||
if (Wildcard.all(item.id, enabledTools) === false) continue
|
||||
tools[item.id] = tool({
|
||||
id: item.id as any,
|
||||
description: item.description,
|
||||
@@ -790,6 +795,7 @@ 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") {
|
||||
@@ -829,7 +835,7 @@ export namespace Session {
|
||||
}
|
||||
|
||||
for (const [key, item] of Object.entries(await MCP.tools())) {
|
||||
if (enabledTools[key] === false) continue
|
||||
if (Wildcard.all(key, enabledTools) === false) continue
|
||||
const execute = item.execute
|
||||
if (!execute) continue
|
||||
item.execute = async (args, opts) => {
|
||||
@@ -865,7 +871,7 @@ export namespace Session {
|
||||
: undefined,
|
||||
topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
||||
options: {
|
||||
...ProviderTransform.options(input.providerID, input.modelID),
|
||||
...ProviderTransform.options(input.providerID, input.modelID, input.sessionID),
|
||||
...model.info.options,
|
||||
...agent.options,
|
||||
},
|
||||
@@ -961,7 +967,7 @@ export namespace Session {
|
||||
content: x,
|
||||
}),
|
||||
),
|
||||
...MessageV2.toModelMessage(msgs),
|
||||
...MessageV2.toModelMessage(msgs.filter((m) => !(m.info.role === "assistant" && m.info.error))),
|
||||
],
|
||||
tools: model.info.tool_call === false ? undefined : tools,
|
||||
model: wrapLanguageModel({
|
||||
@@ -993,6 +999,122 @@ 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 script = `
|
||||
[[ -f ~/.zshrc ]] && source ~/.zshrc 2>/dev/null || true
|
||||
[[ -f ~/.bashrc ]] && source ~/.bashrc 2>/dev/null || true
|
||||
eval "${input.command}"
|
||||
`
|
||||
const proc = spawn(process.env["SHELL"] ?? "bash", ["-c", "-l", script], {
|
||||
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
|
||||
|
||||
@@ -1,76 +1,80 @@
|
||||
You are an expert AI programming assistant
|
||||
When asked for your name, you must respond with "opencode".
|
||||
Follow the user's requirements carefully & to the letter.
|
||||
Your name is opencode
|
||||
Keep your answers short and impersonal.
|
||||
<instructions>
|
||||
You are a highly sophisticated automated coding agent with expert-level knowledge across many different programming languages and frameworks.
|
||||
The user will ask a question, or ask you to perform a task, and it may require lots of research to answer correctly. There is a selection of tools that let you perform actions or retrieve helpful context to answer the user's question.
|
||||
You are an agent—keep going until the user's query is completely resolved before ending your turn. ONLY stop if solved or genuinely blocked.
|
||||
Take action when possible; the user expects you to do useful work without unnecessary questions.
|
||||
After any parallel, read-only context gathering, give a concise progress update and what's next.
|
||||
Avoid repetition across turns: don't restate unchanged plans or sections (like the todo list) verbatim; provide delta updates or only the parts that changed.
|
||||
Tool batches: You MUST preface each batch with a one-sentence why/what/outcome preamble.
|
||||
Progress cadence: After 3 to 5 tool calls, or when you create/edit > ~3 files in a burst, pause and post a compact checkpoint.
|
||||
Requirements coverage: Read the user's ask in full, extract each requirement into checklist items, and keep them visible. Do not omit a requirement. If something cannot be done with available tools, note why briefly and propose a viable alternative.
|
||||
Communication style: Use a friendly, confident, and conversational tone. Prefer short sentences, contractions, and concrete language. Keep it skimmable and encouraging, not formal or robotic. A tiny touch of personality is okay; avoid overusing exclamations or emoji. Avoid empty filler like "Sounds good!", "Great!", "Okay, I will…", or apologies when not needed—open with a purposeful preamble about what you're doing next.
|
||||
<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.
|
||||
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 until you have completed the task fully. Don't give up unless you are sure the request cannot be fulfilled with the tools you have. It's YOUR RESPONSIBILITY to make sure that you have done all you can to collect necessary context.
|
||||
Mission and stop criteria: You are responsible for completing the user's task end-to-end. Continue working until the goal is satisfied or you are truly blocked by missing information. Do not defer actions back to the user if you can execute them yourself with available tools. Only ask a clarifying question when essential to proceed.
|
||||
Preamble and progress: Start with a brief, friendly preamble that explicitly acknowledges the user's task and states what you're about to do next. Make it engaging and tailored to the repo/task; keep it to a single sentence. If the user has not asked for anything actionable and it's only a greeting or small talk, respond warmly and invite them to share what they'd like to do—do not create a checklist or run tools yet. Use the preamble only once per task; if the previous assistant message already included a preamble for this task, skip it this turn. Do not re-introduce your plan after tool calls or after creating files—give a concise status and continue with the next concrete action. For multi-step tasks, keep a lightweight checklist and weave progress updates into your narration. Batch independent, read-only operations together; after a batch, share a concise progress note and what's next. If you say you will do something, execute it in the same turn using tools.
|
||||
<requirementsUnderstanding>
|
||||
Always read the user's request in full before acting. Extract the explicit requirements and any reasonable implicit requirements.
|
||||
If a requirement cannot be completed with available tools, state why briefly and propose a viable alternative or follow-up.
|
||||
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.
|
||||
|
||||
</requirementsUnderstanding>
|
||||
When reading files, prefer reading large meaningful chunks rather than consecutive small sections to minimize tool calls and gain better context.
|
||||
Don't make assumptions about the situation- gather context first, then perform the task or answer the question.
|
||||
Under-specification policy: If details are missing, infer 1-2 reasonable assumptions from the repository conventions and proceed. Note assumptions briefly and continue; ask only when truly blocked.
|
||||
Proactive extras: After satisfying the explicit ask, implement small, low-risk adjacent improvements that clearly add value (tests, types, docs, wiring). If a follow-up is larger or risky, list it as next steps.
|
||||
Anti-laziness: Avoid generic restatements and high-level advice. Prefer concrete edits, running tools, and verifying outcomes over suggesting what the user should do.
|
||||
<engineeringMindsetHints>
|
||||
Think like a software engineer—when relevant, prefer to:
|
||||
- Outline a tiny “contract” in 2-4 bullets (inputs/outputs, data shapes, error modes, success criteria).
|
||||
- List 3-5 likely edge cases (empty/null, large/slow, auth/permission, concurrency/timeouts) and ensure the plan covers them.
|
||||
- Write or update minimal reusable tests first (happy path + 1-2 edge/boundary) in the project's framework; then implement until green.
|
||||
## 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
|
||||
|
||||
</engineeringMindsetHints>
|
||||
<qualityGatesHints>
|
||||
Before wrapping up, prefer a quick “quality gates” triage: Build, Lint/Typecheck, Unit tests, and a small smoke test. Ensure there are no syntax/type errors across the project; fix them or clearly call out any intentionally deferred ones. Report deltas only (PASS/FAIL). Include a brief “requirements coverage” line mapping each requirement to its status (Done/Deferred + reason).
|
||||
## 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.
|
||||
|
||||
</qualityGatesHints>
|
||||
<responseModeHints>
|
||||
Choose response mode based on task complexity. Prefer a lightweight answer when it's a greeting, small talk, or a trivial/direct Q&A that doesn't require tools or edits: keep it short, skip todo lists and progress checkpoints, and avoid tool calls unless necessary. Use the full engineering workflow (checklist, phases, checkpoints) when the task is multi-step, requires edits/builds/tests, or has ambiguity/unknowns. Escalate from light to full only when needed; if you escalate, say so briefly and continue.
|
||||
## 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.
|
||||
|
||||
</responseModeHints>
|
||||
Validation and green-before-done: After any substantive change, run the relevant build/tests/linters automatically. For runnable code that you created or edited, immediately run a test to validate the code works (fast, minimal input) yourself using terminal tools. Prefer automated code-based tests where possible. Then provide optional fenced code blocks with commands for larger or platform-specific runs. Don't end a turn with a broken build if you can fix it. If failures occur, iterate up to three targeted fixes; if still failing, summarize the root cause, options, and exact failing output. For non-critical checks (e.g., a flaky health check), retry briefly (2-3 attempts with short backoff) and then proceed with the next step, noting the flake.
|
||||
Never invent file paths, APIs, or commands. Verify with tools (search/read/list) before acting when uncertain.
|
||||
Security and side-effects: Do not exfiltrate secrets or make network calls unless explicitly required by the task. Prefer local actions first.
|
||||
Reproducibility and dependencies: Follow the project's package manager and configuration; prefer minimal, pinned, widely-used libraries and update manifests or lockfiles appropriately. Prefer adding or updating tests when you change public behavior.
|
||||
Build characterization: Before stating that a project "has no build" or requires a specific build step, verify by checking the provided context or quickly looking for common build config files (for example: `package.json`, `pnpm-lock.yaml`, `requirements.txt`, `pyproject.toml`, `setup.py`, `Makefile`, `Dockerfile`, `build.gradle`, `pom.xml`). If uncertain, say what you know based on the available evidence and proceed with minimal setup instructions; note that you can adapt if additional build configs exist.
|
||||
Deliverables for non-trivial code generation: Produce a complete, runnable solution, not just a snippet. Create the necessary source files plus a small runner or test/benchmark harness when relevant, a minimal `README.md` with usage and troubleshooting, and a dependency manifest (for example, `package.json`, `requirements.txt`, `pyproject.toml`) updated or added as appropriate. If you intentionally choose not to create one of these artifacts, briefly say why.
|
||||
Don't repeat yourself after a tool call, pick up where you left off.
|
||||
You don't need to read a file if it's already provided in context.
|
||||
</instructions>
|
||||
<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.
|
||||
Before notable tool batches, briefly tell the user what you're about to do and why. After the results return, briefly interpret them and state what you'll do next. Don't narrate every trivial call.
|
||||
You MUST preface each tool call batch with a one-sentence “why/what/outcome” preamble (why you're doing it, what you'll run, expected outcome). If you make many tool calls in a row, you MUST checkpoint progress after roughly every 3-5 calls: what you ran, key results, and what you'll do next. If you create or edit more than ~3 files in a burst, checkpoint immediately with a compact bullet summary.
|
||||
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. Parallelize read-only, independent operations only; do not parallelize edits or dependent steps.
|
||||
Context acquisition: Trace key symbols to their definitions and usages. Read sufficiently large, meaningful chunks to avoid missing context. Prefer semantic or codebase search when you don't know the exact string; prefer exact search or direct reads when you do. Avoid redundant reads when the content is already attached and sufficient.
|
||||
Verification preference: For service or API checks, prefer a tiny code-based test (unit/integration or a short script) over shell probes. Use shell probes (e.g., curl) only as optional documentation or quick one-off sanity checks, and mark them as optional.
|
||||
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. If the file has a scheme like untitled: or vscode-userdata:, then use a URI with the scheme.
|
||||
You don't currently have any tools available for editing files. If the user asks you to edit a file, you can ask the user to enable editing tools or print a codeblock with the suggested changes.
|
||||
You don't currently have any tools available for running terminal commands. If the user asks you to run a terminal command, you can ask the user to enable terminal tools or print a codeblock with the suggested command.
|
||||
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>
|
||||
## 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.
|
||||
@@ -109,6 +113,19 @@ In the code block, use a line comment with '...existing code...' to indicate cod
|
||||
{ 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.
|
||||
|
||||
@@ -5,14 +5,14 @@ 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 = 30000
|
||||
const MAX_OUTPUT_LENGTH = 30_000
|
||||
const DEFAULT_TIMEOUT = 1 * 60 * 1000
|
||||
const MAX_TIMEOUT = 10 * 60 * 1000
|
||||
|
||||
@@ -40,20 +40,8 @@ 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 = (() => {
|
||||
const value = cfg.permission?.bash
|
||||
if (!value)
|
||||
return {
|
||||
"*": "allow",
|
||||
}
|
||||
if (typeof value === "string")
|
||||
return {
|
||||
"*": value,
|
||||
}
|
||||
return value
|
||||
})()
|
||||
const permissions = await Agent.get(ctx.agent).then((x) => x.permission.bash)
|
||||
|
||||
let needsAsk = false
|
||||
for (const node of tree.rootNode.descendantsOfType("command")) {
|
||||
@@ -93,17 +81,10 @@ export const BashTool = Tool.define("bash", {
|
||||
|
||||
// always allow cd if it passes above check
|
||||
if (!needsAsk && command[0] !== "cd") {
|
||||
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"
|
||||
})()
|
||||
const action = Wildcard.all(node.text, permissions)
|
||||
if (action === "deny") {
|
||||
throw new Error(
|
||||
"The user has specifically restricted access to this command, you are not allowed to execute it.",
|
||||
`The user has specifically restricted access to this command, you are not allowed to execute it. Here is the configuration: ${JSON.stringify(permissions)}`,
|
||||
)
|
||||
}
|
||||
if (action === "ask") needsAsk = true
|
||||
@@ -113,6 +94,7 @@ 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,
|
||||
@@ -126,7 +108,6 @@ export const BashTool = Tool.define("bash", {
|
||||
const process = exec(params.command, {
|
||||
cwd: app.path.cwd,
|
||||
signal: ctx.abort,
|
||||
maxBuffer: MAX_OUTPUT_LENGTH,
|
||||
timeout,
|
||||
})
|
||||
|
||||
@@ -174,6 +155,11 @@ 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: {
|
||||
|
||||
@@ -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 cfg = await Config.get()
|
||||
const agent = await Agent.get(ctx.agent)
|
||||
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 (cfg.permission?.edit === "ask") {
|
||||
if (agent.permission.edit === "ask") {
|
||||
await Permission.ask({
|
||||
type: "edit",
|
||||
sessionID: ctx.sessionID,
|
||||
@@ -77,12 +77,13 @@ export const EditTool = Tool.define("edit", {
|
||||
contentNew = replace(contentOld, params.oldString, params.newString, params.replaceAll)
|
||||
|
||||
diff = trimDiff(createTwoFilesPatch(filePath, filePath, contentOld, contentNew))
|
||||
if (cfg.permission?.edit === "ask") {
|
||||
if (agent.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,
|
||||
|
||||
@@ -24,7 +24,7 @@ export const ReadTool = Tool.define("read", {
|
||||
filepath = path.join(process.cwd(), filepath)
|
||||
}
|
||||
const app = App.info()
|
||||
if (!Filesystem.contains(app.path.cwd, filepath)) {
|
||||
if (!ctx.extra?.["bypassCwdCheck"] && !Filesystem.contains(app.path.cwd, filepath)) {
|
||||
throw new Error(`File ${filepath} is not in the current working directory`)
|
||||
}
|
||||
|
||||
@@ -98,8 +98,6 @@ function isImageFile(filePath: string): string | false {
|
||||
return "GIF"
|
||||
case ".bmp":
|
||||
return "BMP"
|
||||
case ".svg":
|
||||
return "SVG"
|
||||
case ".webp":
|
||||
return "WebP"
|
||||
default:
|
||||
|
||||
@@ -7,7 +7,6 @@ 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 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.
|
||||
- This tool cannot read binary files, including images
|
||||
- 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.
|
||||
|
||||
@@ -11,7 +11,7 @@ import { TodoWriteTool, TodoReadTool } from "./todo"
|
||||
import { WebFetchTool } from "./webfetch"
|
||||
import { WriteTool } from "./write"
|
||||
import { InvalidTool } from "./invalid"
|
||||
import { Config } from "../config/config"
|
||||
import type { Agent } from "../agent/agent"
|
||||
|
||||
export namespace ToolRegistry {
|
||||
const ALL = [
|
||||
@@ -66,23 +66,31 @@ export namespace ToolRegistry {
|
||||
return result
|
||||
}
|
||||
|
||||
export async function enabled(_providerID: string, _modelID: string): Promise<Record<string, boolean>> {
|
||||
const cfg = await Config.get()
|
||||
export async function enabled(
|
||||
_providerID: string,
|
||||
modelID: string,
|
||||
agent: Agent.Info,
|
||||
): Promise<Record<string, boolean>> {
|
||||
const result: Record<string, boolean> = {}
|
||||
result["patch"] = false
|
||||
|
||||
if (cfg.permission?.edit === "deny") {
|
||||
if (agent.permission.edit === "deny") {
|
||||
result["edit"] = false
|
||||
result["patch"] = false
|
||||
result["write"] = false
|
||||
}
|
||||
if (cfg?.permission?.bash === "deny") {
|
||||
if (agent.permission.bash["*"] === "deny" && Object.keys(agent.permission.bash).length === 1) {
|
||||
result["bash"] = false
|
||||
}
|
||||
if (cfg?.permission?.webfetch === "deny") {
|
||||
if (agent.permission.webfetch === "deny") {
|
||||
result["webfetch"] = false
|
||||
}
|
||||
|
||||
if (modelID.includes("qwen")) {
|
||||
result["todowrite"] = false
|
||||
result["todoread"] = false
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
@@ -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:
|
||||
Example usage (NOTE: The agents below are fictional examples for illustration only - use the actual agents listed above):
|
||||
|
||||
<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 with the code-reviewer agent
|
||||
assistant: Uses the Task tool to launch the code-reviewer agent
|
||||
</example>
|
||||
|
||||
<example>
|
||||
|
||||
@@ -7,8 +7,10 @@ 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> {
|
||||
|
||||
@@ -28,6 +28,7 @@ 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,
|
||||
|
||||
@@ -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 cfg = await Config.get()
|
||||
if (cfg.permission?.edit === "ask")
|
||||
const agent = await Agent.get(ctx.agent)
|
||||
if (agent.permission.edit === "ask")
|
||||
await Permission.ask({
|
||||
type: "write",
|
||||
sessionID: ctx.sessionID,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sortBy, pipe } from "remeda"
|
||||
|
||||
export namespace Wildcard {
|
||||
export function match(str: string, pattern: string) {
|
||||
const regex = new RegExp(
|
||||
@@ -11,4 +13,16 @@ 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ const ctx = {
|
||||
sessionID: "test",
|
||||
messageID: "",
|
||||
toolCallID: "",
|
||||
agent: "build",
|
||||
abort: AbortSignal.any([]),
|
||||
metadata: () => {},
|
||||
}
|
||||
@@ -33,7 +34,7 @@ describe("tool.bash", () => {
|
||||
|
||||
test("cd ../ should fail outside of project root", async () => {
|
||||
await App.provide({ cwd: projectRoot }, async () => {
|
||||
await expect(
|
||||
expect(
|
||||
bash.execute(
|
||||
{
|
||||
command: "cd ../",
|
||||
|
||||
@@ -8,6 +8,7 @@ const ctx = {
|
||||
sessionID: "test",
|
||||
messageID: "",
|
||||
toolCallID: "",
|
||||
agent: "build",
|
||||
abort: AbortSignal.any([]),
|
||||
metadata: () => {},
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/plugin",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
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
|
||||
configured_endpoints: 36
|
||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-a881262c7de4ab59bdfbfc6e30a23c47dee465d7270ffb867b760b0103aff8ed.yml
|
||||
openapi_spec_hash: 7dbb6f96f5c26a25c849e50298f58586
|
||||
config_hash: 8d85a768523cff92b85ef06c443d49fa
|
||||
|
||||
@@ -111,6 +111,7 @@ 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>
|
||||
@@ -120,6 +121,7 @@ Methods:
|
||||
- <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>
|
||||
|
||||
@@ -72,21 +72,25 @@ func (r *AppService) Providers(ctx context.Context, opts ...option.RequestOption
|
||||
}
|
||||
|
||||
type Agent struct {
|
||||
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:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// agentJSON contains the JSON metadata for the struct [Agent]
|
||||
type agentJSON struct {
|
||||
Mode apijson.Field
|
||||
Name apijson.Field
|
||||
Options apijson.Field
|
||||
Permission apijson.Field
|
||||
Tools apijson.Field
|
||||
Description apijson.Field
|
||||
Model apijson.Field
|
||||
@@ -121,6 +125,78 @@ 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"`
|
||||
|
||||
@@ -149,15 +149,17 @@ 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"`
|
||||
Prompt string `json:"prompt"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
Tools map[string]bool `json:"tools"`
|
||||
TopP float64 `json:"top_p"`
|
||||
JSON configAgentBuildJSON `json:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// configAgentBuildJSON contains the JSON metadata for the struct
|
||||
@@ -167,6 +169,7 @@ type configAgentBuildJSON struct {
|
||||
Disable apijson.Field
|
||||
Mode apijson.Field
|
||||
Model apijson.Field
|
||||
Permission apijson.Field
|
||||
Prompt apijson.Field
|
||||
Temperature apijson.Field
|
||||
Tools apijson.Field
|
||||
@@ -199,17 +202,135 @@ 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"`
|
||||
Prompt string `json:"prompt"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
Tools map[string]bool `json:"tools"`
|
||||
TopP float64 `json:"top_p"`
|
||||
JSON configAgentGeneralJSON `json:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// configAgentGeneralJSON contains the JSON metadata for the struct
|
||||
@@ -219,6 +340,7 @@ type configAgentGeneralJSON struct {
|
||||
Disable apijson.Field
|
||||
Mode apijson.Field
|
||||
Model apijson.Field
|
||||
Permission apijson.Field
|
||||
Prompt apijson.Field
|
||||
Temperature apijson.Field
|
||||
Tools apijson.Field
|
||||
@@ -251,17 +373,135 @@ 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"`
|
||||
Prompt string `json:"prompt"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
Tools map[string]bool `json:"tools"`
|
||||
TopP float64 `json:"top_p"`
|
||||
JSON configAgentPlanJSON `json:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// configAgentPlanJSON contains the JSON metadata for the struct [ConfigAgentPlan]
|
||||
@@ -270,6 +510,7 @@ type configAgentPlanJSON struct {
|
||||
Disable apijson.Field
|
||||
Mode apijson.Field
|
||||
Model apijson.Field
|
||||
Permission apijson.Field
|
||||
Prompt apijson.Field
|
||||
Temperature apijson.Field
|
||||
Tools apijson.Field
|
||||
@@ -302,6 +543,122 @@ 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:"-"`
|
||||
@@ -681,15 +1038,17 @@ 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"`
|
||||
Prompt string `json:"prompt"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
Tools map[string]bool `json:"tools"`
|
||||
TopP float64 `json:"top_p"`
|
||||
JSON configModeBuildJSON `json:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// configModeBuildJSON contains the JSON metadata for the struct [ConfigModeBuild]
|
||||
@@ -698,6 +1057,7 @@ type configModeBuildJSON struct {
|
||||
Disable apijson.Field
|
||||
Mode apijson.Field
|
||||
Model apijson.Field
|
||||
Permission apijson.Field
|
||||
Prompt apijson.Field
|
||||
Temperature apijson.Field
|
||||
Tools apijson.Field
|
||||
@@ -730,17 +1090,135 @@ 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"`
|
||||
Prompt string `json:"prompt"`
|
||||
Temperature float64 `json:"temperature"`
|
||||
Tools map[string]bool `json:"tools"`
|
||||
TopP float64 `json:"top_p"`
|
||||
JSON configModePlanJSON `json:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// configModePlanJSON contains the JSON metadata for the struct [ConfigModePlan]
|
||||
@@ -749,6 +1227,7 @@ type configModePlanJSON struct {
|
||||
Disable apijson.Field
|
||||
Mode apijson.Field
|
||||
Model apijson.Field
|
||||
Permission apijson.Field
|
||||
Prompt apijson.Field
|
||||
Temperature apijson.Field
|
||||
Tools apijson.Field
|
||||
@@ -781,6 +1260,122 @@ 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"`
|
||||
@@ -897,10 +1492,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"`
|
||||
@@ -909,10 +1504,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
|
||||
@@ -1138,6 +1733,8 @@ type KeybindsConfig struct {
|
||||
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:"-"`
|
||||
@@ -1184,6 +1781,7 @@ type keybindsConfigJSON struct {
|
||||
SwitchMode apijson.Field
|
||||
SwitchModeReverse apijson.Field
|
||||
ThemeList apijson.Field
|
||||
ThinkingBlocks apijson.Field
|
||||
ToolDetails apijson.Field
|
||||
raw string
|
||||
ExtraFields map[string]apijson.Field
|
||||
|
||||
@@ -46,6 +46,18 @@ 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...)
|
||||
@@ -154,6 +166,18 @@ 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...)
|
||||
@@ -964,11 +988,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{}].
|
||||
ProviderMetadata interface{} `json:"providerMetadata"`
|
||||
Snapshot string `json:"snapshot"`
|
||||
Metadata interface{} `json:"metadata"`
|
||||
Mime string `json:"mime"`
|
||||
Name string `json:"name"`
|
||||
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].
|
||||
@@ -987,29 +1011,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
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
func (r partJSON) RawJSON() string {
|
||||
@@ -1163,27 +1187,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"`
|
||||
Type ReasoningPartType `json:"type,required"`
|
||||
ProviderMetadata map[string]interface{} `json:"providerMetadata"`
|
||||
Time ReasoningPartTime `json:"time"`
|
||||
JSON reasoningPartJSON `json:"-"`
|
||||
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:"-"`
|
||||
}
|
||||
|
||||
// reasoningPartJSON contains the JSON metadata for the struct [ReasoningPart]
|
||||
type reasoningPartJSON struct {
|
||||
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
|
||||
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
|
||||
}
|
||||
|
||||
func (r *ReasoningPart) UnmarshalJSON(data []byte) (err error) {
|
||||
@@ -1196,20 +1220,6 @@ 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"`
|
||||
@@ -1233,6 +1243,20 @@ 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"`
|
||||
@@ -2274,6 +2298,14 @@ 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"`
|
||||
@@ -2348,6 +2380,15 @@ 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"`
|
||||
|
||||
@@ -35,6 +35,34 @@ 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"
|
||||
@@ -275,6 +303,35 @@ 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,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/sdk",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
|
||||
@@ -19,6 +19,8 @@ import type {
|
||||
SessionDeleteResponses,
|
||||
SessionGetData,
|
||||
SessionGetResponses,
|
||||
SessionUpdateData,
|
||||
SessionUpdateResponses,
|
||||
SessionInitData,
|
||||
SessionInitResponses,
|
||||
SessionAbortData,
|
||||
@@ -35,6 +37,8 @@ import type {
|
||||
SessionChatResponses,
|
||||
SessionMessageData,
|
||||
SessionMessageResponses,
|
||||
SessionShellData,
|
||||
SessionShellResponses,
|
||||
SessionRevertData,
|
||||
SessionRevertResponses,
|
||||
SessionUnrevertData,
|
||||
@@ -224,6 +228,20 @@ 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,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze the app and create an AGENTS.md file
|
||||
*/
|
||||
@@ -316,6 +334,20 @@ 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
|
||||
*/
|
||||
|
||||
@@ -912,6 +912,15 @@ export type AgentConfig = {
|
||||
*/
|
||||
description?: string
|
||||
mode?: string
|
||||
permission?: {
|
||||
edit?: string
|
||||
bash?:
|
||||
| string
|
||||
| {
|
||||
[key: string]: string
|
||||
}
|
||||
webfetch?: string
|
||||
}
|
||||
[key: string]:
|
||||
| unknown
|
||||
| string
|
||||
@@ -921,6 +930,15 @@ export type AgentConfig = {
|
||||
}
|
||||
| boolean
|
||||
| string
|
||||
| {
|
||||
edit?: string
|
||||
bash?:
|
||||
| string
|
||||
| {
|
||||
[key: string]: string
|
||||
}
|
||||
webfetch?: string
|
||||
}
|
||||
| undefined
|
||||
}
|
||||
|
||||
@@ -1061,6 +1079,13 @@ export type Agent = {
|
||||
mode: string
|
||||
topP?: number
|
||||
temperature?: number
|
||||
permission: {
|
||||
edit: string
|
||||
bash: {
|
||||
[key: string]: string
|
||||
}
|
||||
webfetch?: string
|
||||
}
|
||||
model?: {
|
||||
modelID: string
|
||||
providerID: string
|
||||
@@ -1215,6 +1240,26 @@ 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 SessionInitData = {
|
||||
body?: {
|
||||
messageID: string
|
||||
@@ -1411,6 +1456,30 @@ 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
|
||||
|
||||
@@ -7,7 +7,7 @@ console.log("=== Generating Stainless SDK ===")
|
||||
console.log(process.cwd())
|
||||
|
||||
await $`rm -rf go`
|
||||
await $`bun run ../../opencode/src/index.ts generate > openapi.json`
|
||||
await $`bun run --conditions=development ../../opencode/src/index.ts generate > openapi.json`
|
||||
await $`stl builds create --branch dev --pull --allow-empty --+target go`
|
||||
|
||||
await $`rm -rf ../go`
|
||||
|
||||
@@ -124,6 +124,8 @@ 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
|
||||
|
||||
|
||||
@@ -45,14 +45,6 @@ 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)
|
||||
@@ -81,13 +73,25 @@ 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, "modes", agentsStr, "url", url)
|
||||
slog.Debug("TUI launched", "app", appInfoStr, "agents_count", len(agents), "url", url)
|
||||
|
||||
go func() {
|
||||
err = clipboard.Init()
|
||||
|
||||
@@ -49,6 +49,7 @@ type App struct {
|
||||
InitialSession *string
|
||||
compactCancel context.CancelFunc
|
||||
IsLeaderSequence bool
|
||||
IsBashMode bool
|
||||
}
|
||||
|
||||
func (a *App) Agent() *opencode.Agent {
|
||||
@@ -71,12 +72,17 @@ type ModelSelectedMsg struct {
|
||||
Provider opencode.Provider
|
||||
Model opencode.Model
|
||||
}
|
||||
|
||||
type AgentSelectedMsg struct {
|
||||
Agent opencode.Agent
|
||||
AgentName string
|
||||
}
|
||||
|
||||
type SessionClearedMsg struct{}
|
||||
type CompactSessionMsg struct{}
|
||||
type SendPrompt = Prompt
|
||||
type SendBash = struct {
|
||||
Command string
|
||||
}
|
||||
type SetEditorContentMsg struct {
|
||||
Text string
|
||||
}
|
||||
@@ -272,6 +278,7 @@ 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()
|
||||
}
|
||||
|
||||
@@ -293,29 +300,86 @@ func (a *App) CycleRecentModel() (*App, tea.Cmd) {
|
||||
}
|
||||
nextIndex := 0
|
||||
for i, recentModel := range recentModels {
|
||||
if a.Provider != nil && a.Model != nil && recentModel.ProviderID == a.Provider.ID && recentModel.ModelID == a.Model.ID {
|
||||
if a.Provider != nil && a.Model != nil && recentModel.ProviderID == a.Provider.ID &&
|
||||
recentModel.ModelID == a.Model.ID {
|
||||
nextIndex = (i + 1) % len(recentModels)
|
||||
break
|
||||
}
|
||||
}
|
||||
for range recentModels {
|
||||
currentRecentModel := recentModels[nextIndex%len(recentModels)]
|
||||
provider, model := findModelByProviderAndModelID(a.Providers, currentRecentModel.ProviderID, currentRecentModel.ModelID)
|
||||
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)))
|
||||
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[:nextIndex%len(recentModels)], recentModels[nextIndex%len(recentModels)+1:]...)
|
||||
recentModels = append(
|
||||
recentModels[:nextIndex%len(recentModels)],
|
||||
recentModels[nextIndex%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"))
|
||||
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) 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,
|
||||
@@ -422,10 +486,19 @@ 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 {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
@@ -682,6 +755,38 @@ func (a *App) SendPrompt(ctx context.Context, prompt Prompt) (*App, tea.Cmd) {
|
||||
return a, tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
func (a *App) SendBash(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 bash command", "error", err)
|
||||
return toast.NewErrorToast("Failed to submit bash 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 {
|
||||
@@ -718,6 +823,17 @@ 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 {
|
||||
|
||||
@@ -16,6 +16,11 @@ 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"`
|
||||
@@ -29,6 +34,7 @@ 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"`
|
||||
@@ -42,6 +48,7 @@ func NewState() *State {
|
||||
Agent: "build",
|
||||
AgentModel: make(map[string]AgentModel),
|
||||
RecentlyUsedModels: make([]ModelUsage, 0),
|
||||
RecentlyUsedAgents: make([]AgentUsage, 0),
|
||||
MessageHistory: make([]Prompt, 0),
|
||||
}
|
||||
}
|
||||
@@ -83,6 +90,42 @@ 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 {
|
||||
|
||||
@@ -31,6 +31,7 @@ type EditorComponent interface {
|
||||
tea.Model
|
||||
tea.ViewModel
|
||||
Content() string
|
||||
Cursor() *tea.Cursor
|
||||
Lines() int
|
||||
Value() string
|
||||
Length() int
|
||||
@@ -38,6 +39,7 @@ 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)
|
||||
@@ -341,6 +343,14 @@ 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(
|
||||
@@ -348,10 +358,6 @@ 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).
|
||||
@@ -407,6 +413,10 @@ 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 == "" {
|
||||
@@ -484,6 +494,16 @@ 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.SendBash{Command: command}))
|
||||
return m, tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
func (m *editorComponent) Clear() (tea.Model, tea.Cmd) {
|
||||
m.textarea.Reset()
|
||||
m.historyIndex = -1
|
||||
@@ -694,6 +714,7 @@ func NewEditorComponent(app *app.App) EditorComponent {
|
||||
ta.Prompt = " "
|
||||
ta.ShowLineNumbers = false
|
||||
ta.CharLimit = -1
|
||||
ta.VirtualCursor = false
|
||||
ta = updateTextareaStyles(ta)
|
||||
|
||||
m := &editorComponent{
|
||||
|
||||
@@ -183,6 +183,8 @@ func renderContentBlock(
|
||||
if renderer.borderRight {
|
||||
style = style.BorderRightForeground(borderColor)
|
||||
}
|
||||
} else {
|
||||
style = style.PaddingLeft(renderer.paddingLeft + 1).PaddingRight(renderer.paddingRight + 1)
|
||||
}
|
||||
|
||||
content = style.Render(content)
|
||||
@@ -325,7 +327,9 @@ func renderText(
|
||||
|
||||
// wrap styled text
|
||||
styledText := result.String()
|
||||
wrappedText := ansi.WordwrapWc(styledText, width-6, " -")
|
||||
styledText = strings.ReplaceAll(styledText, "-", "\u2011")
|
||||
wrappedText := ansi.WordwrapWc(styledText, width-6, " ")
|
||||
wrappedText = strings.ReplaceAll(wrappedText, "\u2011", "-")
|
||||
content = base.Width(width - 6).Render(wrappedText)
|
||||
}
|
||||
|
||||
|
||||
@@ -386,12 +386,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
fileParts,
|
||||
agentParts,
|
||||
)
|
||||
content = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
content,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
m.cache.Set(key, content)
|
||||
}
|
||||
if content != "" {
|
||||
@@ -468,12 +462,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
[]opencode.AgentPart{},
|
||||
toolCallParts...,
|
||||
)
|
||||
content = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
content,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
m.cache.Set(key, content)
|
||||
}
|
||||
} else {
|
||||
@@ -490,12 +478,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
[]opencode.AgentPart{},
|
||||
toolCallParts...,
|
||||
)
|
||||
content = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
content,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
}
|
||||
if content != "" {
|
||||
partCount++
|
||||
@@ -536,12 +518,6 @@ 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 {
|
||||
@@ -552,12 +528,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
permission,
|
||||
width,
|
||||
)
|
||||
content = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
content,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
}
|
||||
if content != "" {
|
||||
partCount++
|
||||
@@ -586,12 +556,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
[]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)
|
||||
@@ -625,12 +589,6 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
[]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)
|
||||
@@ -645,12 +603,6 @@ 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
|
||||
}
|
||||
@@ -742,12 +694,6 @@ 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
|
||||
@@ -916,12 +862,6 @@ func (m *messagesComponent) renderHeader() string {
|
||||
BorderForeground(t.BackgroundElement()).
|
||||
BorderStyle(lipgloss.ThickBorder()).
|
||||
Render(header)
|
||||
header = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
header,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
|
||||
return "\n" + header + "\n"
|
||||
}
|
||||
@@ -1213,7 +1153,7 @@ func NewMessagesComponent(app *app.App) MessagesComponent {
|
||||
if app.State.ScrollSpeed != nil && *app.State.ScrollSpeed > 0 {
|
||||
vp.MouseWheelDelta = *app.State.ScrollSpeed
|
||||
} else {
|
||||
vp.MouseWheelDelta = 4
|
||||
vp.MouseWheelDelta = 2
|
||||
}
|
||||
|
||||
// Default to showing tool details, hidden thinking blocks
|
||||
|
||||
@@ -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,8 +1,8 @@
|
||||
package dialog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/v2/key"
|
||||
tea "github.com/charmbracelet/bubbletea/v2"
|
||||
@@ -19,9 +19,10 @@ import (
|
||||
|
||||
const (
|
||||
numVisibleAgents = 10
|
||||
minAgentDialogWidth = 54
|
||||
maxAgentDialogWidth = 108
|
||||
maxDescriptionLength = 80
|
||||
minAgentDialogWidth = 40
|
||||
maxAgentDialogWidth = 60
|
||||
maxDescriptionLength = 60
|
||||
maxRecentAgents = 5
|
||||
)
|
||||
|
||||
// AgentDialog interface for the agent selection dialog
|
||||
@@ -31,7 +32,7 @@ type AgentDialog interface {
|
||||
|
||||
type agentDialog struct {
|
||||
app *app.App
|
||||
allAgents []opencode.Agent
|
||||
allAgents []agentSelectItem
|
||||
width int
|
||||
height int
|
||||
modal *modal.Modal
|
||||
@@ -39,24 +40,31 @@ type agentDialog struct {
|
||||
dialogWidth int
|
||||
}
|
||||
|
||||
// agentItem is a custom list item for agent selections
|
||||
type agentItem struct {
|
||||
agent opencode.Agent
|
||||
// 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 agentItem) Render(
|
||||
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 {
|
||||
itemStyle = itemStyle.Foreground(t.Primary())
|
||||
// Use agent color for highlighting when selected (visual improvement)
|
||||
agentColor := util.GetAgentColor(a.agentIndex)
|
||||
itemStyle = itemStyle.Foreground(agentColor)
|
||||
}
|
||||
|
||||
descStyle := baseStyle.
|
||||
@@ -66,25 +74,43 @@ func (a agentItem) Render(
|
||||
// Calculate available width (accounting for padding and margins)
|
||||
availableWidth := width - 2 // Account for left padding
|
||||
|
||||
agentName := a.agent.Name
|
||||
description := a.agent.Description
|
||||
if description == "" {
|
||||
description = fmt.Sprintf("(%s)", a.agent.Mode)
|
||||
agentName := a.displayName
|
||||
|
||||
// For user agents and subagents, show description; for built-in, show mode
|
||||
var displayText string
|
||||
if a.description != "" && (a.mode == "all" || a.mode == "subagent") {
|
||||
// User agent or subagent with description
|
||||
displayText = a.description
|
||||
} else {
|
||||
// Built-in without description - show mode
|
||||
switch a.mode {
|
||||
case "primary":
|
||||
displayText = "(built-in)"
|
||||
case "all":
|
||||
displayText = "(user)"
|
||||
default:
|
||||
displayText = ""
|
||||
}
|
||||
}
|
||||
|
||||
separator := " - "
|
||||
|
||||
// Calculate how much space we have for the description
|
||||
// Calculate how much space we have for the description (visual improvement)
|
||||
nameAndSeparatorLength := len(agentName) + len(separator)
|
||||
descriptionMaxLength := availableWidth - nameAndSeparatorLength
|
||||
|
||||
// Truncate description if it's too long
|
||||
if len(description) > descriptionMaxLength && descriptionMaxLength > 3 {
|
||||
description = description[:descriptionMaxLength-3] + "..."
|
||||
// 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 + description)
|
||||
descPart := descStyle.Render(separator + displayText)
|
||||
combinedText := namePart + descPart
|
||||
|
||||
return baseStyle.
|
||||
@@ -94,8 +120,7 @@ func (a agentItem) Render(
|
||||
Render(combinedText)
|
||||
}
|
||||
|
||||
func (a agentItem) Selectable() bool {
|
||||
// All agents in the dialog are selectable (subagents are filtered out)
|
||||
func (a agentSelectItem) Selectable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -122,32 +147,43 @@ func (a *agentDialog) Init() tea.Cmd {
|
||||
|
||||
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.(agentItem); ok {
|
||||
return a, tea.Sequence(
|
||||
util.CmdHandler(modal.CloseModalMsg{}),
|
||||
util.CmdHandler(
|
||||
app.AgentSelectedMsg{
|
||||
Agent: item.agent,
|
||||
}),
|
||||
)
|
||||
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
|
||||
|
||||
case tea.WindowSizeMsg:
|
||||
a.width = msg.Width
|
||||
a.height = msg.Height
|
||||
a.searchDialog.SetWidth(a.dialogWidth)
|
||||
a.searchDialog.SetHeight(msg.Height)
|
||||
}
|
||||
|
||||
updatedDialog, cmd := a.searchDialog.Update(msg)
|
||||
@@ -155,20 +191,38 @@ func (a *agentDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
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 []opencode.Agent) int {
|
||||
func (a *agentDialog) calculateOptimalWidth(agents []agentSelectItem) int {
|
||||
maxWidth := minAgentDialogWidth
|
||||
|
||||
for _, agent := range agents {
|
||||
// Calculate the width needed for this item: "AgentName - Description"
|
||||
itemWidth := len(agent.Name)
|
||||
if agent.Description != "" {
|
||||
itemWidth += len(agent.Description) + 3 // " - "
|
||||
// Calculate the width needed for this item: "AgentName - Description" (visual improvement)
|
||||
itemWidth := len(agent.displayName)
|
||||
if agent.description != "" && (agent.mode == "all" || agent.mode == "subagent") {
|
||||
// User agent or subagent - use description (capped to maxDescriptionLength)
|
||||
descLength := len(agent.description)
|
||||
if descLength > maxDescriptionLength {
|
||||
descLength = maxDescriptionLength
|
||||
}
|
||||
itemWidth += descLength + 3 // " - "
|
||||
} else {
|
||||
itemWidth += len(string(agent.Mode)) + 3 // " (mode)"
|
||||
// Built-in without description - use mode
|
||||
var modeText string
|
||||
switch agent.mode {
|
||||
case "primary":
|
||||
modeText = "(built-in)"
|
||||
case "all":
|
||||
modeText = "(user)"
|
||||
}
|
||||
itemWidth += len(modeText) + 3 // " - "
|
||||
}
|
||||
|
||||
if itemWidth > maxWidth {
|
||||
@@ -177,22 +231,37 @@ func (a *agentDialog) calculateOptimalWidth(agents []opencode.Agent) int {
|
||||
}
|
||||
|
||||
maxWidth = min(maxWidth, maxAgentDialogWidth)
|
||||
|
||||
return maxWidth
|
||||
}
|
||||
|
||||
func (a *agentDialog) setupAllAgents() {
|
||||
// Get agents from the app, filtering out subagents
|
||||
a.allAgents = []opencode.Agent{}
|
||||
for _, agent := range a.app.Agents {
|
||||
if agent.Mode != "subagent" {
|
||||
a.allAgents = append(a.allAgents, agent)
|
||||
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
|
||||
// Calculate optimal width based on all agents (visual improvement)
|
||||
a.dialogWidth = a.calculateOptimalWidth(a.allAgents)
|
||||
|
||||
// Ensure minimum width to prevent textinput issues
|
||||
@@ -201,6 +270,7 @@ func (a *agentDialog) setupAllAgents() {
|
||||
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)
|
||||
}
|
||||
@@ -210,42 +280,43 @@ func (a *agentDialog) sortAgents() {
|
||||
agentA := a.allAgents[i]
|
||||
agentB := a.allAgents[j]
|
||||
|
||||
// Current agent goes first
|
||||
if agentA.Name == a.app.Agent().Name {
|
||||
// Current agent goes first (your preference)
|
||||
if agentA.name == a.app.Agent().Name {
|
||||
return true
|
||||
}
|
||||
if agentB.Name == a.app.Agent().Name {
|
||||
if agentB.name == a.app.Agent().Name {
|
||||
return false
|
||||
}
|
||||
|
||||
// Alphabetical order for all other agents
|
||||
return agentA.Name < agentB.Name
|
||||
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()
|
||||
}
|
||||
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]opencode.Agent)
|
||||
agentMap := make(map[string]agentSelectItem)
|
||||
|
||||
for _, agent := range a.allAgents {
|
||||
// Search by name
|
||||
searchStr := agent.Name
|
||||
// Only include non-subagents in search
|
||||
if agent.mode == "subagent" {
|
||||
continue
|
||||
}
|
||||
searchStr := agent.name
|
||||
agentNames = append(agentNames, searchStr)
|
||||
agentMap[searchStr] = agent
|
||||
|
||||
// Search by description if available
|
||||
if agent.Description != "" {
|
||||
searchStr = fmt.Sprintf("%s %s", agent.Name, agent.Description)
|
||||
agentNames = append(agentNames, searchStr)
|
||||
agentMap[searchStr] = agent
|
||||
}
|
||||
}
|
||||
|
||||
matches := fuzzy.RankFindFold(query, agentNames)
|
||||
@@ -257,25 +328,55 @@ func (a *agentDialog) buildSearchResults(query string) []list.Item {
|
||||
for _, match := range matches {
|
||||
agent := agentMap[match.Target]
|
||||
// Create a unique key to avoid duplicates
|
||||
key := agent.Name
|
||||
key := agent.name
|
||||
if seenAgents[key] {
|
||||
continue
|
||||
}
|
||||
seenAgents[key] = true
|
||||
items = append(items, agentItem{agent: agent})
|
||||
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
|
||||
|
||||
items = append(items, list.HeaderItem("Agents"))
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// Add all agents (subagents are already filtered out)
|
||||
// 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 {
|
||||
items = append(items, agentItem{agent: agent})
|
||||
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
|
||||
@@ -285,10 +386,65 @@ func (a *agentDialog) Render(background string) string {
|
||||
return a.modal.Render(a.View(), background)
|
||||
}
|
||||
|
||||
func (s *agentDialog) Close() tea.Cmd {
|
||||
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,
|
||||
|
||||
@@ -6,6 +6,7 @@ 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"
|
||||
@@ -110,6 +111,9 @@ 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 {
|
||||
@@ -123,69 +127,128 @@ 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:
|
||||
switch msg.String() {
|
||||
case "enter":
|
||||
if s.deleteConfirmation >= 0 {
|
||||
s.deleteConfirmation = -1
|
||||
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")
|
||||
s.updateListItems()
|
||||
return s, nil
|
||||
default:
|
||||
var cmd tea.Cmd
|
||||
s.renameInput, cmd = s.renameInput.Update(msg)
|
||||
return s, cmd
|
||||
}
|
||||
if _, idx := s.list.GetSelectedItem(); idx >= 0 && idx < len(s.sessions) {
|
||||
selectedSession := s.sessions[idx]
|
||||
} 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":
|
||||
return s, tea.Sequence(
|
||||
util.CmdHandler(modal.CloseModalMsg{}),
|
||||
util.CmdHandler(app.SessionSelectedMsg(&selectedSession)),
|
||||
util.CmdHandler(app.SessionClearedMsg{}),
|
||||
)
|
||||
}
|
||||
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
|
||||
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
|
||||
s.updateListItems()
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
case "esc":
|
||||
if s.deleteConfirmation >= 0 {
|
||||
s.deleteConfirmation = -1
|
||||
s.updateListItems()
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var cmd tea.Cmd
|
||||
listModel, cmd := s.list.Update(msg)
|
||||
s.list = listModel.(list.List[sessionItem])
|
||||
return s, cmd
|
||||
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
|
||||
}
|
||||
|
||||
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")
|
||||
leftHelp := keyStyle("n") + mutedStyle(" new session") + " " + keyStyle("r") + mutedStyle(" rename")
|
||||
rightHelp := keyStyle("x/del") + mutedStyle(" delete session")
|
||||
|
||||
bgColor := t.BackgroundPanel()
|
||||
@@ -203,6 +266,39 @@ 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()
|
||||
|
||||
@@ -229,7 +325,22 @@ 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
|
||||
}
|
||||
|
||||
@@ -272,6 +383,8 @@ 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),
|
||||
|
||||
@@ -670,6 +670,28 @@ 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) {
|
||||
@@ -1577,6 +1599,12 @@ 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)
|
||||
@@ -1587,6 +1615,12 @@ 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)
|
||||
}
|
||||
@@ -2045,6 +2079,109 @@ 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}
|
||||
@@ -2076,11 +2213,49 @@ func wrapInterfaces(content []any, width int) [][]any {
|
||||
if !inSpaces {
|
||||
// End of a word
|
||||
if lineW > 0 && lineW+wordW > width {
|
||||
lines = append(lines, word)
|
||||
lineW = wordW
|
||||
// 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
|
||||
}
|
||||
} else {
|
||||
lines[len(lines)-1] = append(lines[len(lines)-1], word...)
|
||||
lineW += wordW
|
||||
// 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
|
||||
}
|
||||
}
|
||||
word = nil
|
||||
wordW = 0
|
||||
@@ -2110,11 +2285,49 @@ 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 {
|
||||
lines = append(lines, word)
|
||||
lineW = wordW
|
||||
// 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
|
||||
}
|
||||
} else {
|
||||
lines[len(lines)-1] = append(lines[len(lines)-1], word...)
|
||||
lineW += wordW
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
if spaceW > 0 {
|
||||
|
||||
75
packages/tui/internal/components/textarea/textarea_test.go
Normal file
75
packages/tui/internal/components/textarea/textarea_test.go
Normal file
@@ -0,0 +1,75 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,8 @@ 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
|
||||
@@ -149,6 +151,23 @@ 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 {
|
||||
@@ -187,7 +206,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
// 3. Handle completions trigger
|
||||
if keyString == "/" &&
|
||||
!a.showCompletionDialog &&
|
||||
a.editor.Value() == "" {
|
||||
a.editor.Value() == "" &&
|
||||
!a.app.IsBashMode {
|
||||
a.showCompletionDialog = true
|
||||
|
||||
updated, cmd := a.editor.Update(msg)
|
||||
@@ -205,7 +225,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
|
||||
// Handle file completions trigger
|
||||
if keyString == "@" &&
|
||||
!a.showCompletionDialog {
|
||||
!a.showCompletionDialog &&
|
||||
!a.app.IsBashMode {
|
||||
a.showCompletionDialog = true
|
||||
|
||||
updated, cmd := a.editor.Update(msg)
|
||||
@@ -221,6 +242,11 @@ 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":
|
||||
@@ -355,6 +381,11 @@ 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
|
||||
@@ -371,6 +402,9 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
a.showCompletionDialog = false
|
||||
a.app, cmd = a.app.SendPrompt(context.Background(), msg)
|
||||
cmds = append(cmds, cmd)
|
||||
case app.SendBash:
|
||||
a.app, cmd = a.app.SendBash(context.Background(), msg.Command)
|
||||
cmds = append(cmds, cmd)
|
||||
case app.SetEditorContentMsg:
|
||||
// Set the editor content without sending
|
||||
a.editor.SetValueWithAttachments(msg.Text)
|
||||
@@ -597,31 +631,9 @@ 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:
|
||||
// Find the agent index
|
||||
for i, agent := range a.app.Agents {
|
||||
if agent.Name == msg.Agent.Name {
|
||||
a.app.AgentIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
a.app.State.Agent = msg.Agent.Name
|
||||
|
||||
// Switch to the agent's preferred model if available
|
||||
if model, ok := a.app.State.AgentModel[msg.Agent.Name]; ok {
|
||||
for _, provider := range a.app.Providers {
|
||||
if provider.ID == model.ProviderID {
|
||||
a.app.Provider = &provider
|
||||
for _, m := range provider.Models {
|
||||
if m.ID == model.ModelID {
|
||||
a.app.Model = &m
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
cmds = append(cmds, a.app.SaveState())
|
||||
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())
|
||||
@@ -748,15 +760,17 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return a, tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
func (a Model) View() string {
|
||||
func (a Model) View() (string, *tea.Cursor) {
|
||||
t := theme.CurrentTheme()
|
||||
|
||||
var mainLayout string
|
||||
|
||||
var editorX int
|
||||
var editorY int
|
||||
if a.app.Session.ID == "" {
|
||||
mainLayout = a.home()
|
||||
mainLayout, editorX, editorY = a.home()
|
||||
} else {
|
||||
mainLayout = a.chat()
|
||||
mainLayout, editorX, editorY = a.chat()
|
||||
}
|
||||
mainLayout = styles.NewStyle().
|
||||
Background(t.Background()).
|
||||
@@ -780,7 +794,12 @@ func (a Model) View() string {
|
||||
if theme.CurrentThemeUsesAnsiColors() {
|
||||
mainLayout = util.ConvertRGBToAnsi16Colors(mainLayout)
|
||||
}
|
||||
return mainLayout + "\n" + a.status.View()
|
||||
|
||||
cursor := a.editor.Cursor()
|
||||
cursor.Position.X += editorX
|
||||
cursor.Position.Y += editorY
|
||||
|
||||
return mainLayout + "\n" + a.status.View(), cursor
|
||||
}
|
||||
|
||||
func (a Model) Cleanup() {
|
||||
@@ -807,7 +826,7 @@ func (a Model) openFile(filepath string) (tea.Model, tea.Cmd) {
|
||||
return a, cmd
|
||||
}
|
||||
|
||||
func (a Model) home() string {
|
||||
func (a Model) home() (string, int, int) {
|
||||
t := theme.CurrentTheme()
|
||||
effectiveWidth := a.width - 4
|
||||
baseStyle := styles.NewStyle().Background(t.Background())
|
||||
@@ -899,14 +918,21 @@ func (a Model) home() string {
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
|
||||
editorX := (effectiveWidth - editorWidth) / 2
|
||||
editorX := max(0, (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,
|
||||
a.editor.Content(),
|
||||
content,
|
||||
mainLayout,
|
||||
)
|
||||
}
|
||||
@@ -924,10 +950,10 @@ func (a Model) home() string {
|
||||
)
|
||||
}
|
||||
|
||||
return mainLayout
|
||||
return mainLayout, editorX + 5, editorY + 2
|
||||
}
|
||||
|
||||
func (a Model) chat() string {
|
||||
func (a Model) chat() (string, int, int) {
|
||||
effectiveWidth := a.width - 4
|
||||
t := theme.CurrentTheme()
|
||||
editorView := a.editor.View()
|
||||
@@ -944,14 +970,20 @@ func (a Model) chat() string {
|
||||
)
|
||||
|
||||
mainLayout := messagesView + "\n" + editorView
|
||||
editorX := (effectiveWidth - editorWidth) / 2
|
||||
editorX := max(0, (effectiveWidth-editorWidth)/2)
|
||||
editorY := a.height - editorHeight
|
||||
|
||||
if lines > 1 {
|
||||
editorY := a.height - editorHeight
|
||||
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,
|
||||
a.editor.Content(),
|
||||
content,
|
||||
mainLayout,
|
||||
)
|
||||
}
|
||||
@@ -970,7 +1002,7 @@ func (a Model) chat() string {
|
||||
)
|
||||
}
|
||||
|
||||
return mainLayout
|
||||
return mainLayout, editorX + 5, editorY + 2
|
||||
}
|
||||
|
||||
func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
|
||||
@@ -1149,6 +1181,7 @@ func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
|
||||
case commands.ModelListCommand:
|
||||
modelDialog := dialog.NewModelDialog(a.app)
|
||||
a.modal = modelDialog
|
||||
|
||||
case commands.AgentListCommand:
|
||||
agentDialog := dialog.NewAgentDialog(a.app)
|
||||
a.modal = agentDialog
|
||||
|
||||
@@ -3,6 +3,7 @@ package util
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
@@ -85,6 +86,8 @@ 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")
|
||||
|
||||
@@ -105,5 +108,6 @@ func ToMarkdown(content string, width int, backgroundColor compat.AdaptiveColor)
|
||||
}
|
||||
}
|
||||
content = strings.Join(lines, "\n")
|
||||
content = strings.ReplaceAll(content, "\u2011", "-")
|
||||
return strings.TrimSuffix(content, "\n")
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
)
|
||||
|
||||
var SUPPORTED_IDES = []struct {
|
||||
Search string
|
||||
Search string
|
||||
ShortName string
|
||||
}{
|
||||
{"Windsurf", "Windsurf"},
|
||||
{"Visual Studio Code", "VS Code"},
|
||||
{"Visual Studio Code", "vscode"},
|
||||
{"Cursor", "Cursor"},
|
||||
{"VSCodium", "VSCodium"},
|
||||
}
|
||||
@@ -27,4 +27,5 @@ func Ide() string {
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@opencode/web",
|
||||
"type": "module",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"dev:remote": "sst shell --stage=dev --target=Web astro dev",
|
||||
|
||||
@@ -318,6 +318,22 @@ Control which tools are available in this agent with the `tools` config. You can
|
||||
}
|
||||
```
|
||||
|
||||
You can also use wildcards to control multiple tools at once. For example, to disable all tools from an MCP server:
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"agent": {
|
||||
"readonly": {
|
||||
"tools": {
|
||||
"mymcp_*": false,
|
||||
"write": false,
|
||||
"edit": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If no tools are specified, all tools are enabled by default.
|
||||
|
||||
---
|
||||
@@ -342,6 +358,147 @@ Here are all the tools can be controlled through the agent config.
|
||||
|
||||
---
|
||||
|
||||
### Permissions
|
||||
|
||||
Permissions control what actions an agent can take.
|
||||
|
||||
- edit, bash, webfetch
|
||||
|
||||
Each permission can be set to allow, ask, or deny.
|
||||
|
||||
- allow, ask, deny
|
||||
|
||||
Configure permissions globally in opencode.json.
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"permission": {
|
||||
"edit": "ask",
|
||||
"bash": "allow",
|
||||
"webfetch": "deny"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can override permissions per agent in JSON.
|
||||
|
||||
```json title="opencode.json" {7-18}
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"agent": {
|
||||
"build": {
|
||||
"permission": {
|
||||
"edit": "allow",
|
||||
"bash": {
|
||||
"*": "allow",
|
||||
"git push": "ask",
|
||||
"terraform *": "deny"
|
||||
},
|
||||
"webfetch": "ask"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You can also set permissions in Markdown agents.
|
||||
|
||||
```markdown title="~/.config/opencode/agent/review.md"
|
||||
---
|
||||
description: Code review without edits
|
||||
mode: subagent
|
||||
permission:
|
||||
edit: deny
|
||||
bash: ask
|
||||
webfetch: deny
|
||||
---
|
||||
|
||||
Only analyze code and suggest changes.
|
||||
```
|
||||
|
||||
Bash permissions support granular patterns for fine-grained control.
|
||||
|
||||
```json title="Allow most, ask for risky, deny terraform"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"permission": {
|
||||
"bash": {
|
||||
"*": "allow",
|
||||
"git push": "ask",
|
||||
"terraform *": "deny"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you provide a granular bash map, the default becomes ask unless you set \* explicitly.
|
||||
|
||||
```json title="Granular defaults to ask"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"permission": {
|
||||
"bash": {
|
||||
"git status": "allow"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Agent-level permissions merge over global settings.
|
||||
|
||||
- Global sets defaults; agent overrides when specified
|
||||
|
||||
Specific bash rules can override a global default.
|
||||
|
||||
```json title="Global ask, agent allows safe commands"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"permission": { "bash": "ask" },
|
||||
"agent": {
|
||||
"build": {
|
||||
"permission": {
|
||||
"bash": { "git status": "allow", "*": "ask" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Permissions affect tool availability and prompts differently.
|
||||
|
||||
- deny hides tools (edit also hides write/patch); ask prompts; allow runs
|
||||
|
||||
For quick reference, here are common setups.
|
||||
|
||||
```json title="Read-only reviewer"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"agent": {
|
||||
"review": {
|
||||
"permission": { "edit": "deny", "bash": "deny", "webfetch": "allow" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json title="Planning agent that can browse but cannot change code"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"agent": {
|
||||
"plan": {
|
||||
"permission": { "edit": "deny", "bash": "deny", "webfetch": "ask" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the full permissions guide for more patterns.
|
||||
|
||||
- /docs/permissions
|
||||
|
||||
---
|
||||
|
||||
### Mode
|
||||
|
||||
Control the agent's mode with the `mode` config. The `mode` option is used to determine how the agent can be used.
|
||||
@@ -371,7 +528,7 @@ For example, with OpenAI's reasoning models, you can control the reasoning effor
|
||||
"agent": {
|
||||
"deep-thinker": {
|
||||
"description": "Agent that uses high reasoning effort for complex problems",
|
||||
"model": "openai/gpt-5-turbo",
|
||||
"model": "openai/gpt-5-turbo",
|
||||
"reasoningEffort": "high",
|
||||
"textVerbosity": "low"
|
||||
}
|
||||
|
||||
@@ -95,6 +95,16 @@ Here are all available slash commands:
|
||||
|
||||
---
|
||||
|
||||
### Bash commands
|
||||
|
||||
Start a line with `!` to run a shell command. The output is added to the conversation as a tool result.
|
||||
|
||||
```bash frame="none"
|
||||
!ls -la
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Editor setup
|
||||
|
||||
Both the `/editor` and `/export` commands use the editor specified in your `EDITOR` environment variable.
|
||||
@@ -232,10 +242,10 @@ opencode github run
|
||||
|
||||
##### Flags
|
||||
|
||||
| Flag | Description |
|
||||
| --------- | ------------------------------------------------ |
|
||||
| `--event` | GitHub mock event to run the agent for |
|
||||
| `--token` | GitHub personal access token |
|
||||
| Flag | Description |
|
||||
| --------- | -------------------------------------- |
|
||||
| `--event` | GitHub mock event to run the agent for |
|
||||
| `--token` | GitHub personal access token |
|
||||
|
||||
---
|
||||
|
||||
@@ -289,9 +299,9 @@ This starts an HTTP server that provides API access to opencode functionality wi
|
||||
|
||||
#### Flags
|
||||
|
||||
| Flag | Short | Description |
|
||||
| ------------ | ----- | ------------------------------------------ |
|
||||
| `--port` | `-p` | Port to listen on |
|
||||
| Flag | Short | Description |
|
||||
| ------------ | ----- | --------------------- |
|
||||
| `--port` | `-p` | Port to listen on |
|
||||
| `--hostname` | `-h` | Hostname to listen on |
|
||||
|
||||
---
|
||||
@@ -318,8 +328,8 @@ opencode upgrade v0.1.48
|
||||
|
||||
#### Flags
|
||||
|
||||
| Flag | Short | Description |
|
||||
| ---------- | ----- | --------------------------------------------------------- |
|
||||
| Flag | Short | Description |
|
||||
| ---------- | ----- | ----------------------------------------------------------------- |
|
||||
| `--method` | `-m` | The installation method that was used; curl, npm, pnpm, bun, brew |
|
||||
|
||||
---
|
||||
@@ -337,5 +347,5 @@ The opencode CLI takes the following global flags.
|
||||
| `--prompt` | `-p` | Prompt to use |
|
||||
| `--model` | `-m` | Model to use in the form of provider/model |
|
||||
| `--mode` | | Mode to use |
|
||||
| `--port` | | Port to listen on |
|
||||
| `--hostname` | | Hostname to listen on |
|
||||
| `--port` | | Port to listen on |
|
||||
| `--hostname` | | Hostname to listen on |
|
||||
|
||||
@@ -64,6 +64,36 @@ If you've configured a [custom provider](/docs/providers#custom), the `provider_
|
||||
|
||||
---
|
||||
|
||||
## Configure models
|
||||
|
||||
You can globally configure a model's options through the config.
|
||||
|
||||
```jsonc title="opencode.jsonc" {7-11}
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"provider": {
|
||||
"openai": {
|
||||
"models": {
|
||||
"gpt-5": {
|
||||
"options": {
|
||||
"reasoningEffort": "high",
|
||||
"textVerbosity": "low",
|
||||
"reasoningSummary": "auto",
|
||||
"include": ["reasoning.encrypted_content"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Here we are setting global options for the `gpt-5` model when used through the `openai` provider.
|
||||
|
||||
You can also configure these options for any agents that you are using. The agent config overrides any global options here. [Learn more](/docs/agents/#additional).
|
||||
|
||||
---
|
||||
|
||||
## Loading models
|
||||
|
||||
When opencode starts up, it checks for models in the following priority order:
|
||||
|
||||
@@ -21,6 +21,8 @@ Permissions are configured in your `opencode.json` file under the `permission` k
|
||||
| `bash` | Control bash command execution |
|
||||
| `webfetch` | Control web content fetching |
|
||||
|
||||
They can also be configured per agent, see [Agent Configuration](/docs/agents#agent-configuration) for more details.
|
||||
|
||||
---
|
||||
|
||||
### edit
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "opencode",
|
||||
"displayName": "opencode",
|
||||
"description": "opencode for VS Code",
|
||||
"version": "0.4.24",
|
||||
"version": "0.4.44",
|
||||
"publisher": "sst-dev",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
Reference in New Issue
Block a user