Compare commits

...

39 Commits

Author SHA1 Message Date
Dax Raad
8bf36d174b update beast prompt for openai models 2025-07-29 22:15:13 -04:00
Dax Raad
9bedd62da4 experimental well-known auth support 2025-07-29 19:30:51 -04:00
Yordis Prieto
4c34b69ae6 chore: fix test to have deterministic testing (#1401) 2025-07-29 17:54:22 -05:00
Dax Raad
7e9ac35666 remove min/max in tool schemas 2025-07-29 17:39:47 -04:00
Frank
4a46144419 convert share backend to hono app 2025-07-29 16:39:48 -04:00
adamdotdevin
a129e122aa feat: show git diff in reverted messages 2025-07-29 13:11:38 -05:00
Yordis Prieto
c0ee6a6d05 fix: update file name extraction in uploads test to use __filename (#1395) 2025-07-29 12:28:44 -05:00
Yordis Prieto
68ae0d107c fix: improve handling of global File object in uploads tests (#1394) 2025-07-29 11:30:39 -05:00
Yordis Prieto
df63008a94 chore: fix null handling in multipartFormRequestOptions test (#1385) 2025-07-29 11:17:03 -05:00
Andrea Grandi
3bd2b340c8 feat: show current git branch in status bar, and make it responsive (#1339)
Co-authored-by: adamdotdevin <2363879+adamdottv@users.noreply.github.com>
2025-07-29 11:15:04 -05:00
Dax Raad
df03e182d2 strip todo tool instructions from non anthropic models 2025-07-29 11:56:53 -04:00
Jacob Hands
862a50d61d feat: add OPENCODE_CONFIG env var for specifying a custom config file (#1370) 2025-07-29 11:03:11 -04:00
GitHub Action
a7cfd36b07 ignore: update download stats 2025-07-29 2025-07-29 12:04:40 +00:00
Aiden Cline
c165360e17 fix: task type error (#1384) 2025-07-29 06:18:34 -05:00
Dax Raad
9cb0f21b4e trim opencode title 2025-07-28 23:24:38 -04:00
Dax Raad
9c9cbb3e81 wip: undo properly remove messages from UI 2025-07-28 22:58:31 -04:00
Dax Raad
c24fbb4292 wip: snapshot 2025-07-28 22:58:31 -04:00
Jay V
99dfe65862 docs: share page hide patch part 2025-07-28 20:04:00 -04:00
Jay V
4506e5a824 docs: adding 2025-07-28 20:00:30 -04:00
Jay V
b65172a2b7 Tweak auth cli copy 2025-07-28 20:00:30 -04:00
Dax Raad
081f100c93 ignore: tweak 2025-07-28 12:20:37 -04:00
Dax Raad
f2bdb8159f fix phantom tool call failed messages and empty text parts with some models 2025-07-28 12:19:38 -04:00
GitHub Action
10d749a85e ignore: update download stats 2025-07-28 2025-07-28 12:04:21 +00:00
Frank
a07d149e28 vscode: add cmd+shift+esc keybinding 2025-07-27 15:54:45 -04:00
Frank
3eb982c8cd vscode: bring oc terminal to front if already opened 2025-07-27 14:57:45 -04:00
Frank
45c4e0b8f8 show opencode button in vscode when focused on terminal 2025-07-27 14:44:14 -04:00
Aiden Cline
b18b646f8e fix: attachment bugs (#1335) 2025-07-27 12:21:31 -05:00
Frank
9741a6703c fix input format affected by installing vscode extension 2025-07-27 11:56:18 -04:00
Frank
27a079d9cb simplify github action 2025-07-27 09:56:09 -04:00
GitHub Action
2eeb987680 ignore: update download stats 2025-07-27 2025-07-27 12:04:15 +00:00
Aiden Cline
e827294c9b docs: document small_model cfg option (#1347) 2025-07-26 16:56:38 -05:00
Dax Raad
7cf4ed6ad6 ci: fix opencode github 2025-07-26 10:02:31 -04:00
Aiden Cline
ad8a4bc744 fix: strip thinking blocks from title (#1325) 2025-07-26 08:29:04 -05:00
GitHub Action
2630104f18 ignore: update download stats 2025-07-26 2025-07-26 12:03:59 +00:00
Frank
670f470eee wip: github actions 2025-07-26 02:49:05 -04:00
Frank
c2b3c52b76 wip: github action 2025-07-26 01:03:23 -04:00
Frank
a007d65f62 wip: github actions 2025-07-25 20:27:42 -04:00
Didier Durand
2c924b9fdb fixing various typos in text. (#1185) 2025-07-25 20:20:01 -04:00
Dax Raad
e8eaa77bf1 better mcp support - should fix hanging when streamable http server is added 2025-07-25 19:19:47 -04:00
85 changed files with 2064 additions and 1069 deletions

View File

@@ -7,12 +7,11 @@ on:
jobs:
opencode:
if: |
startsWith(github.event.comment.body, 'opencode') ||
startsWith(github.event.comment.body, 'hi opencode') ||
startsWith(github.event.comment.body, 'hey opencode') ||
contains(github.event.comment.body, '@opencode-agent')
contains(github.event.comment.body, '/oc') ||
contains(github.event.comment.body, '/opencode')
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: Checkout repository
@@ -25,4 +24,4 @@ jobs:
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
with:
model: anthropic/claude-sonnet-4-20250514
model: anthropic/claude-sonnet-4-20250514

View File

@@ -97,7 +97,7 @@ $ bun run packages/opencode/src/index.ts
It's very similar to Claude Code in terms of capability. Here are the key differences:
- 100% open source
- Not coupled to any provider. Although Anthropic is recommended, opencode can be used with OpenAI, Google or even local models. As models evolve the gaps between them will close and pricing will drop so being provider agnostic is important.
- Not coupled to any provider. Although Anthropic is recommended, opencode can be used with OpenAI, Google or even local models. As models evolve the gaps between them will close and pricing will drop so being provider-agnostic is important.
- A focus on TUI. opencode is built by neovim users and the creators of [terminal.shop](https://terminal.shop); we are going to push the limits of what's possible in the terminal.
- A client/server architecture. This for example can allow opencode to run on your computer, while you can drive it remotely from a mobile app. Meaning that the TUI frontend is just one of the possible clients.

View File

@@ -27,3 +27,7 @@
| 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) |

View File

@@ -14,6 +14,7 @@
"dependencies": {
"@octokit/auth-app": "8.0.1",
"@octokit/rest": "22.0.0",
"hono": "catalog:",
"jose": "6.0.11",
},
"devDependencies": {
@@ -41,7 +42,7 @@
"decimal.js": "10.5.0",
"diff": "8.0.2",
"gray-matter": "4.0.3",
"hono": "4.7.10",
"hono": "catalog:",
"hono-openapi": "0.4.8",
"isomorphic-git": "1.32.1",
"open": "10.1.2",
@@ -133,6 +134,7 @@
"catalog": {
"@types/node": "22.13.9",
"ai": "5.0.0-beta.21",
"hono": "4.7.10",
"typescript": "5.8.2",
"zod": "3.25.49",
},

View File

@@ -2,73 +2,77 @@
A GitHub Action that integrates [opencode](https://opencode.ai) directly into your GitHub workflow.
Start your comment with `hey opencode`, and opencode will take action via your GitHub Actions runner.
Mention `/opencode` in your comment, and opencode will execute tasks within your GitHub Actions runner.
## Features
#### Triage and explain issues
#### Explain an issues
Leave the following comment on a GitHub issue. `opencode` will read the entire thread, including all comments, and reply with a clear explanation.
```
hey opencode, explain this issue
/opencode explain this issue
```
#### Fix or implement issues - opencode will create a PR with the changes.
#### Fix an issues
Leave the following comment on a GitHub issue. opencode will create a new branch, implement the changes, and open a PR with the changes.
```
hi opencode, fix this
/opencode fix this
```
- Review PRs and make changes
#### Review PRs and make changes
Leave the following comment on a GitHub PR. opencode will implement the requested change and commit it to the same PR.
```
Delete the attachment from S3 when the note is removed @opencode-agent
Delete the attachment from S3 when the note is removed /oc
```
## Installation
Run the following command in the terminal from your GitHub repo:
```
```bash
opencode github install
```
This will walk you through installing the GitHub app, configuring the workflow, and setting up secrets.
This will walk you through installing the GitHub app, creating the workflow, and setting up secrets.
### Manual Setup
1. Install the GitHub app https://github.com/apps/opencode-agent. Make sure it is installed on the target repository.
2. Add the following workflow file to `.github/workflows/opencode.yml` in your repo. Set the appropriate `model` and required API keys in `env`.
```yml
name: opencode
```yml
name: opencode
on:
issue_comment:
types: [created]
on:
issue_comment:
types: [created]
jobs:
opencode:
if: |
startsWith(github.event.comment.body, 'opencode') ||
startsWith(github.event.comment.body, 'hi opencode') ||
startsWith(github.event.comment.body, 'hey opencode') ||
contains(github.event.comment.body, '@opencode-agent')
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
jobs:
opencode:
if: |
contains(github.event.comment.body, '/oc') ||
contains(github.event.comment.body, '/opencode')
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run opencode
uses: sst/opencode/github@latest
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
with:
model: anthropic/claude-sonnet-4-20250514
```
- name: Run opencode
uses: sst/opencode/github@latest
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
with:
model: anthropic/claude-sonnet-4-20250514
```
3. Store the API keys in secrets. In your organization or project **settings**, expand **Secrets and variables** on the left and select **Actions**. Add the required API keys.
@@ -82,32 +86,32 @@ To test locally:
1. Navigate to a test repo (e.g. `hello-world`):
```
cd hello-world
```
```bash
cd hello-world
```
2. Run:
```
MODEL=anthropic/claude-sonnet-4-20250514 \
ANTHROPIC_API_KEY=sk-ant-api03-1234567890 \
GITHUB_RUN_ID=dummy \
bun /path/to/opencode/packages/opencode/src/index.ts github run \
--token 'github_pat_1234567890' \
--event '{"eventName":"issue_comment",...}'
```
```bash
MODEL=anthropic/claude-sonnet-4-20250514 \
ANTHROPIC_API_KEY=sk-ant-api03-1234567890 \
GITHUB_RUN_ID=dummy \
bun /path/to/opencode/packages/opencode/src/index.ts github run \
--token 'github_pat_1234567890' \
--event '{"eventName":"issue_comment",...}'
```
- `MODEL`: The model used by opencode. Same as the `MODEL` defined in the GitHub workflow.
- `ANTHROPIC_API_KEY`: Your model provider API key. Same as the keys defined in the GitHub workflow.
- `GITHUB_RUN_ID`: Dummy value to emulate GitHub action environment.
- `/path/to/opencode`: Path to your cloned opencode repo. `bun /path/to/opencode/packages/opencode/src/index.ts` runs your local version of `opencode`.
- `--token`: A GitHub persontal access token. This token is used to verify you have `admin` or `write` access to the test repo. Generate a token [here](https://github.com/settings/personal-access-tokens).
- `--event`: Mock GitHub event payload (see templates below).
- `MODEL`: The model used by opencode. Same as the `MODEL` defined in the GitHub workflow.
- `ANTHROPIC_API_KEY`: Your model provider API key. Same as the keys defined in the GitHub workflow.
- `GITHUB_RUN_ID`: Dummy value to emulate GitHub action environment.
- `/path/to/opencode`: Path to your cloned opencode repo. `bun /path/to/opencode/packages/opencode/src/index.ts` runs your local version of `opencode`.
- `--token`: A GitHub persontal access token. This token is used to verify you have `admin` or `write` access to the test repo. Generate a token [here](https://github.com/settings/personal-access-tokens).
- `--event`: Mock GitHub event payload (see templates below).
#### Issue comment event
### Issue comment event
```
--event '{"eventName":"issue_comment","repo":{"owner":"sst","repo":"hello-world"},"actor":"fwang","payload":{"issue":{"number":4},"comment":{"id":1,"body":"hey opencode, summarize thread"}}}'
--event '{"eventName":"issue_comment","repo":{"owner":"sst","repo":"hello-world"},"actor":"fwang","payload":{"issue":{"number":4},"comment":{"id":1,"body":"hey opencode, summarize thread"}}}'
```
Replace:
@@ -118,16 +122,16 @@ Replace:
- `"number":4` with the GitHub issue id
- `"body":"hey opencode, summarize thread"` with comment body
#### Issue comment with image attachment.
### Issue comment with image attachment.
```
--event '{"eventName":"issue_comment","repo":{"owner":"sst","repo":"hello-world"},"actor":"fwang","payload":{"issue":{"number":4},"comment":{"id":1,"body":"hey opencode, what is in my image ![Image](https://github.com/user-attachments/assets/xxxxxxxx)"}}}'
--event '{"eventName":"issue_comment","repo":{"owner":"sst","repo":"hello-world"},"actor":"fwang","payload":{"issue":{"number":4},"comment":{"id":1,"body":"hey opencode, what is in my image ![Image](https://github.com/user-attachments/assets/xxxxxxxx)"}}}'
```
Replace the image URL `https://github.com/user-attachments/assets/xxxxxxxx` with a valid GitHub attachment (you can generate one by commenting with an image in any issue).
#### PR comment event
### PR comment event
```
--event '{"eventName":"issue_comment","repo":{"owner":"sst","repo":"hello-world"},"actor":"fwang","payload":{"issue":{"number":4,"pull_request":{}},"comment":{"id":1,"body":"hey opencode, summarize thread"}}}'
--event '{"eventName":"issue_comment","repo":{"owner":"sst","repo":"hello-world"},"actor":"fwang","payload":{"issue":{"number":4,"pull_request":{}},"comment":{"id":1,"body":"hey opencode, summarize thread"}}}'
```

View File

@@ -7,7 +7,7 @@ branding:
inputs:
model:
description: "Model to use"
required: false
required: true
share:
description: "Share the opencode session (defaults to true for public repos)"

View File

@@ -20,6 +20,10 @@
}
},
"mcp": {
"context7": {
"type": "remote",
"url": "https://mcp.context7.com/sse"
},
"weather": {
"type": "local",
"command": ["opencode", "x", "@h1deya/mcp-server-weather"]

View File

@@ -15,10 +15,11 @@
"packages/*"
],
"catalog": {
"typescript": "5.8.2",
"@types/node": "22.13.9",
"zod": "3.25.49",
"ai": "5.0.0-beta.21"
"ai": "5.0.0-beta.21",
"hono": "4.7.10",
"typescript": "5.8.2",
"zod": "3.25.49"
}
},
"devDependencies": {

View File

@@ -12,6 +12,7 @@
"dependencies": {
"@octokit/auth-app": "8.0.1",
"@octokit/rest": "22.0.0",
"hono": "catalog:",
"jose": "6.0.11"
}
}

View File

@@ -1,3 +1,4 @@
import { Hono } from "hono"
import { DurableObject } from "cloudflare:workers"
import { randomUUID } from "node:crypto"
import { jwtVerify, createRemoteJWKSet } from "jose"
@@ -111,165 +112,156 @@ export class SyncServer extends DurableObject<Env> {
}
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url)
const splits = url.pathname.split("/")
const method = splits[1]
if (request.method === "GET" && method === "") {
return new Response("Hello, world!", {
headers: { "Content-Type": "text/plain" },
})
export default new Hono<{ Bindings: Env }>()
.get("/", (c) => c.text("Hello, world!"))
.post("/share_create", async (c) => {
const body = await c.req.json<{ sessionID: string }>()
const sessionID = body.sessionID
const short = SyncServer.shortName(sessionID)
const id = c.env.SYNC_SERVER.idFromName(short)
const stub = c.env.SYNC_SERVER.get(id)
const secret = await stub.share(sessionID)
return c.json({
secret,
url: `https://${c.env.WEB_DOMAIN}/s/${short}`,
})
})
.post("/share_delete", async (c) => {
const body = await c.req.json<{ sessionID: string; secret: string }>()
const sessionID = body.sessionID
const secret = body.secret
const id = c.env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
const stub = c.env.SYNC_SERVER.get(id)
await stub.assertSecret(secret)
await stub.clear()
return c.json({})
})
.post("/share_delete_admin", async (c) => {
const id = c.env.SYNC_SERVER.idFromName("oVF8Rsiv")
const stub = c.env.SYNC_SERVER.get(id)
await stub.clear()
return c.json({})
})
.post("/share_sync", async (c) => {
const body = await c.req.json<{
sessionID: string
secret: string
key: string
content: any
}>()
const name = SyncServer.shortName(body.sessionID)
const id = c.env.SYNC_SERVER.idFromName(name)
const stub = c.env.SYNC_SERVER.get(id)
await stub.assertSecret(body.secret)
await stub.publish(body.key, body.content)
return c.json({})
})
.get("/share_poll", async (c) => {
const upgradeHeader = c.req.header("Upgrade")
if (!upgradeHeader || upgradeHeader !== "websocket") {
return c.text("Error: Upgrade header is required", { status: 426 })
}
const id = c.req.query("id")
console.log("share_poll", id)
if (!id) return c.text("Error: Share ID is required", { status: 400 })
const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
return stub.fetch(c.req.raw)
})
.get("/share_data", async (c) => {
const id = c.req.query("id")
console.log("share_data", id)
if (!id) return c.text("Error: Share ID is required", { status: 400 })
const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
const data = await stub.getData()
if (request.method === "POST" && method === "share_create") {
const body = await request.json<any>()
const sessionID = body.sessionID
const short = SyncServer.shortName(sessionID)
const id = env.SYNC_SERVER.idFromName(short)
const stub = env.SYNC_SERVER.get(id)
const secret = await stub.share(sessionID)
return new Response(
JSON.stringify({
secret,
url: `https://${env.WEB_DOMAIN}/s/${short}`,
}),
{
headers: { "Content-Type": "application/json" },
},
)
}
if (request.method === "POST" && method === "share_delete") {
const body = await request.json<any>()
const sessionID = body.sessionID
const secret = body.secret
const id = env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
const stub = env.SYNC_SERVER.get(id)
await stub.assertSecret(secret)
await stub.clear()
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "POST" && method === "share_delete_admin") {
const id = env.SYNC_SERVER.idFromName("oVF8Rsiv")
const stub = env.SYNC_SERVER.get(id)
await stub.clear()
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "POST" && method === "share_sync") {
const body = await request.json<{
sessionID: string
secret: string
key: string
content: any
}>()
const name = SyncServer.shortName(body.sessionID)
const id = env.SYNC_SERVER.idFromName(name)
const stub = env.SYNC_SERVER.get(id)
await stub.assertSecret(body.secret)
await stub.publish(body.key, body.content)
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "GET" && method === "share_poll") {
const upgradeHeader = request.headers.get("Upgrade")
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Error: Upgrade header is required", {
status: 426,
})
let info
const messages: Record<string, any> = {}
data.forEach((d) => {
const [root, type, ...splits] = d.key.split("/")
if (root !== "session") return
if (type === "info") {
info = d.content
return
}
const id = url.searchParams.get("id")
console.log("share_poll", id)
if (!id) return new Response("Error: Share ID is required", { status: 400 })
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
return stub.fetch(request)
}
if (type === "message") {
messages[d.content.id] = {
parts: [],
...d.content,
}
}
if (type === "part") {
messages[d.content.messageID].parts.push(d.content)
}
})
if (request.method === "GET" && method === "share_data") {
const id = url.searchParams.get("id")
console.log("share_data", id)
if (!id) return new Response("Error: Share ID is required", { status: 400 })
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
const data = await stub.getData()
return c.json({ info, messages })
})
/**
* Used by the GitHub action to get GitHub installation access token given the OIDC token
*/
.post("/exchange_github_app_token", async (c) => {
const EXPECTED_AUDIENCE = "opencode-github-action"
const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
let info
const messages: Record<string, any> = {}
data.forEach((d) => {
const [root, type, ...splits] = d.key.split("/")
if (root !== "session") return
if (type === "info") {
info = d.content
return
}
if (type === "message") {
messages[d.content.id] = {
parts: [],
...d.content,
}
}
if (type === "part") {
messages[d.content.messageID].parts.push(d.content)
}
// get Authorization header
const token = c.req.header("Authorization")?.replace(/^Bearer /, "")
if (!token) return c.json({ error: "Authorization header is required" }, { status: 401 })
// verify token
const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
let owner, repo
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: GITHUB_ISSUER,
audience: EXPECTED_AUDIENCE,
})
return new Response(
JSON.stringify({
info,
messages,
}),
{
headers: { "Content-Type": "application/json" },
},
)
const sub = payload.sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
const parts = sub.split(":")[1].split("/")
owner = parts[0]
repo = parts[1]
} catch (err) {
console.error("Token verification failed:", err)
return c.json({ error: "Invalid or expired token" }, { status: 403 })
}
/**
* Used by the GitHub action to get GitHub installation access token given the OIDC token
*/
if (request.method === "POST" && method === "exchange_github_app_token") {
const EXPECTED_AUDIENCE = "opencode-github-action"
const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
// Create app JWT token
const auth = createAppAuth({
appId: Resource.GITHUB_APP_ID.value,
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
})
const appAuth = await auth({ type: "app" })
// Lookup installation
const octokit = new Octokit({ auth: appAuth.token })
const { data: installation } = await octokit.apps.getRepoInstallation({ owner, repo })
// Get installation token
const installationAuth = await auth({ type: "installation", installationId: installation.id })
return c.json({ token: installationAuth.token })
})
/**
* Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
*/
.post("/exchange_github_app_token_with_pat", async (c) => {
const body = await c.req.json<{ owner: string; repo: string }>()
const owner = body.owner
const repo = body.repo
try {
// get Authorization header
const authHeader = request.headers.get("Authorization")
const authHeader = c.req.header("Authorization")
const token = authHeader?.replace(/^Bearer /, "")
if (!token)
return new Response(JSON.stringify({ error: "Authorization header is required" }), {
status: 401,
headers: { "Content-Type": "application/json" },
})
if (!token) throw new Error("Authorization header is required")
// verify token
const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
let owner, repo
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: GITHUB_ISSUER,
audience: EXPECTED_AUDIENCE,
})
const sub = payload.sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
const parts = sub.split(":")[1].split("/")
owner = parts[0]
repo = parts[1]
} catch (err) {
console.error("Token verification failed:", err)
return new Response(JSON.stringify({ error: "Invalid or expired token" }), {
status: 403,
headers: { "Content-Type": "application/json" },
})
}
// Verify permissions
const userClient = new Octokit({ auth: token })
const { data: repoData } = await userClient.repos.get({ owner, repo })
if (!repoData.permissions.admin && !repoData.permissions.push && !repoData.permissions.maintain)
throw new Error("User does not have write permissions")
// Create app JWT token
// Get installation token
const auth = createAppAuth({
appId: Resource.GITHUB_APP_ID.value,
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
@@ -277,99 +269,49 @@ export default {
const appAuth = await auth({ type: "app" })
// Lookup installation
const octokit = new Octokit({ auth: appAuth.token })
const { data: installation } = await octokit.apps.getRepoInstallation({ owner, repo })
const appClient = new Octokit({ auth: appAuth.token })
const { data: installation } = await appClient.apps.getRepoInstallation({ owner, repo })
// Get installation token
const installationAuth = await auth({ type: "installation", installationId: installation.id })
return new Response(JSON.stringify({ token: installationAuth.token }), {
headers: { "Content-Type": "application/json" },
})
return c.json({ token: installationAuth.token })
} catch (e: any) {
let error = e
if (e instanceof Error) {
error = e.message
}
return c.json({ error }, { status: 401 })
}
})
/**
* Used by the opencode CLI to check if the GitHub app is installed
*/
.get("/get_github_app_installation", async (c) => {
const owner = c.req.query("owner")
const repo = c.req.query("repo")
/**
* Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
*/
if (request.method === "POST" && method === "exchange_github_app_token_with_pat") {
const body = await request.json<any>()
const owner = body.owner
const repo = body.repo
const auth = createAppAuth({
appId: Resource.GITHUB_APP_ID.value,
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
})
const appAuth = await auth({ type: "app" })
try {
// get Authorization header
const authHeader = request.headers.get("Authorization")
const token = authHeader?.replace(/^Bearer /, "")
if (!token) throw new Error("Authorization header is required")
// Verify permissions
const userClient = new Octokit({ auth: token })
const { data: repoData } = await userClient.repos.get({ owner, repo })
if (!repoData.permissions.admin && !repoData.permissions.push && !repoData.permissions.maintain)
throw new Error("User does not have write permissions")
// Get installation token
const auth = createAppAuth({
appId: Resource.GITHUB_APP_ID.value,
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
})
const appAuth = await auth({ type: "app" })
// Lookup installation
const appClient = new Octokit({ auth: appAuth.token })
const { data: installation } = await appClient.apps.getRepoInstallation({ owner, repo })
// Get installation token
const installationAuth = await auth({ type: "installation", installationId: installation.id })
return new Response(JSON.stringify({ token: installationAuth.token }), {
headers: { "Content-Type": "application/json" },
})
} catch (e: any) {
let error = e
if (e instanceof Error) {
error = e.message
}
return new Response(JSON.stringify({ error }), {
status: 401,
headers: { "Content-Type": "application/json" },
})
// Lookup installation
const octokit = new Octokit({ auth: appAuth.token })
let installation
try {
const ret = await octokit.apps.getRepoInstallation({ owner, repo })
installation = ret.data
} catch (err) {
if (err instanceof Error && err.message.includes("Not Found")) {
// not installed
} else {
throw err
}
}
/**
* Used by the opencode CLI to check if the GitHub app is installed
*/
if (request.method === "GET" && method === "get_github_app_installation") {
const owner = url.searchParams.get("owner")
const repo = url.searchParams.get("repo")
const auth = createAppAuth({
appId: Resource.GITHUB_APP_ID.value,
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
})
const appAuth = await auth({ type: "app" })
// Lookup installation
const octokit = new Octokit({ auth: appAuth.token })
let installation
try {
const ret = await octokit.apps.getRepoInstallation({ owner, repo })
installation = ret.data
} catch (err) {
if (err instanceof Error && err.message.includes("Not Found")) {
// not installed
} else {
throw err
}
}
return new Response(JSON.stringify({ installation }), {
headers: { "Content-Type": "application/json" },
})
}
return new Response("Not Found", { status: 404 })
},
}
return c.json({ installation })
})
.all("*", (c) => c.text("Not Found"))

View File

@@ -40,7 +40,7 @@
"decimal.js": "10.5.0",
"diff": "8.0.2",
"gray-matter": "4.0.3",
"hono": "4.7.10",
"hono": "catalog:",
"hono-openapi": "0.4.8",
"isomorphic-git": "1.32.1",
"open": "10.1.2",

View File

@@ -16,7 +16,13 @@ export namespace Auth {
key: z.string(),
})
export const Info = z.discriminatedUnion("type", [Oauth, Api])
export const WellKnown = z.object({
type: z.literal("wellknown"),
key: z.string(),
token: z.string(),
})
export const Info = z.discriminatedUnion("type", [Oauth, Api, WellKnown])
export type Info = z.infer<typeof Info>
const filepath = path.join(Global.Path.data, "auth.json")

View File

@@ -61,17 +61,45 @@ export const AuthListCommand = cmd({
prompts.log.info(`${provider} ${UI.Style.TEXT_DIM}${envVar}`)
}
prompts.outro(`${activeEnvVars.length} environment variables`)
prompts.outro(`${activeEnvVars.length} environment variable` + (activeEnvVars.length === 1 ? "" : "s"))
}
},
})
export const AuthLoginCommand = cmd({
command: "login",
command: "login [url]",
describe: "log in to a provider",
async handler() {
UI.empty()
builder: (yargs) =>
yargs.positional("url", {
describe: "opencode auth provider",
type: "string",
}),
async handler(args) {
prompts.intro("Add credential")
if (args.url) {
const wellknown = await fetch(`${args.url}/.well-known/opencode`).then((x) => x.json())
prompts.log.info(`Running \`${wellknown.auth.command.join(" ")}\``)
const proc = Bun.spawn({
cmd: wellknown.auth.command,
stdout: "pipe",
})
const exit = await proc.exited
if (exit !== 0) {
prompts.log.error("Failed")
prompts.outro("Done")
return
}
const token = await new Response(proc.stdout).text()
await Auth.set(args.url, {
type: "wellknown",
key: wellknown.auth.env,
token: token.trim(),
})
prompts.log.success("Logged into " + args.url)
prompts.outro("Done")
return
}
UI.empty()
const providers = await ModelsDev.get()
const priority: Record<string, number> = {
anthropic: 0,

View File

@@ -4,7 +4,7 @@ import { cmd } from "../cmd"
export const SnapshotCommand = cmd({
command: "snapshot",
builder: (yargs) => yargs.command(TrackCommand).command(PatchCommand).demandCommand(),
builder: (yargs) => yargs.command(TrackCommand).command(PatchCommand).command(DiffCommand).demandCommand(),
async handler() {},
})
@@ -31,3 +31,18 @@ const PatchCommand = cmd({
})
},
})
const DiffCommand = cmd({
command: "diff <hash>",
builder: (yargs) =>
yargs.positional("hash", {
type: "string",
description: "hash",
demandOption: true,
}),
async handler(args) {
await bootstrap({ cwd: process.cwd() }, async () => {
console.log(await Snapshot.diff(args.hash))
})
},
})

View File

@@ -1,14 +1,10 @@
import { Server } from "../../server/server"
import fs from "fs/promises"
import type { CommandModule } from "yargs"
export const GenerateCommand = {
command: "generate",
handler: async () => {
const specs = await Server.openapi()
const dir = "gen"
await fs.rmdir(dir, { recursive: true }).catch(() => {})
await fs.mkdir(dir, { recursive: true })
process.stdout.write(JSON.stringify(specs, null, 2))
},
} satisfies CommandModule

View File

@@ -156,21 +156,23 @@ export const GithubInstallCommand = cmd({
step2 =
"Configure OIDC in AWS - https://docs.github.com/en/actions/how-tos/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services"
} else {
const url = `https://github.com/organizations/${app.owner}/settings/secrets/actions`
const env = providers[provider].env
const envStr =
env.length === 1
? `\`${env[0]}\` secret`
: `\`${[env.slice(0, -1).join("\`, \`"), ...env.slice(-1)].join("\` and \`")}\` secrets`
step2 = `Add ${envStr} for ${providers[provider].name} - ${url}`
step2 = [
` 2. Add the following secrets in org or repo (${app.owner}/${app.repo}) settings`,
"",
...providers[provider].env.map((e) => ` - ${e}`),
].join("\n")
}
prompts.outro(
[
"Next steps:",
` 1. Commit "${WORKFLOW_FILE}" file and push`,
` 2. ${step2}`,
" 3. Learn how to use the GitHub agent - https://docs.opencode.ai/docs/github/getting-started",
"",
` 1. Commit the \`${WORKFLOW_FILE}\` file and push`,
step2,
"",
" 3. Go to a GitHub issue and comment `/oc summarize` to see the agent in action",
"",
" Learn more about the GitHub agent - https://opencode.ai/docs/github/#usage-examples",
].join("\n"),
)
}
@@ -272,7 +274,7 @@ export const GithubInstallCommand = cmd({
// Wait for installation
s.message("Waiting for GitHub app to be installed")
const MAX_RETRIES = 60
const MAX_RETRIES = 120
let retries = 0
do {
const installation = await getInstallation()
@@ -316,18 +318,15 @@ on:
jobs:
opencode:
if: |
startsWith(github.event.comment.body, 'opencode') ||
startsWith(github.event.comment.body, 'hi opencode') ||
startsWith(github.event.comment.body, 'hey opencode') ||
contains(github.event.comment.body, '@opencode-agent')
contains(github.event.comment.body, '/oc') ||
contains(github.event.comment.body, '/opencode')
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run opencode
uses: sst/opencode/github@latest${envStr}
@@ -459,8 +458,9 @@ export const GithubRunCommand = cmd({
`${response}\n\nCloses #${issueId}${footer({ image: true })}`,
)
await updateComment(`Created PR #${pr}${footer({ image: true })}`)
} else {
await updateComment(`${response}${footer({ image: true })}`)
}
await updateComment(`${response}${footer({ image: true })}`)
}
} catch (e: any) {
exitCode = 1
@@ -508,16 +508,10 @@ export const GithubRunCommand = cmd({
async function getUserPrompt() {
let prompt = (() => {
const body = payload.comment.body
if (body.match("@opencode-agent")) return body
const match = body.match(/^(?:hey|hi)?\s*opencode(?:-agent)?,?\s*(.*)$/is)
if (match?.[1] === undefined)
throw new Error(
"Command must mention @opencode-agent, or start with `opencode`, `hi opencode`, or `hey opencode` followed by instructions",
)
if (match[1] === "") return "Summarize this thread"
return match[1]
const body = payload.comment.body.trim()
if (body === "/opencode" || body === "/oc") return "Summarize this thread"
if (body.includes("/opencode") || body.includes("/oc")) return body
throw new Error("Comments must mention `/opencode` or `/oc`")
})()
// Handle images

View File

@@ -113,7 +113,7 @@ export const TuiCommand = cmd({
})
;(async () => {
if (Installation.VERSION === "dev") return
if (Installation.isDev()) return
if (Installation.isSnapshot()) return
const config = await Config.global()
if (config.autoupdate === false) return
@@ -123,19 +123,15 @@ export const TuiCommand = cmd({
const method = await Installation.method()
if (method === "unknown") return
await Installation.upgrade(method, latest)
.then(() => {
Bus.publish(Installation.Event.Updated, { version: latest })
})
.then(() => Bus.publish(Installation.Event.Updated, { version: latest }))
.catch(() => {})
})()
;(async () => {
if (Ide.alreadyInstalled()) return
const ide = await Ide.ide()
const ide = Ide.ide()
if (ide === "unknown") return
await Ide.install(ide)
.then(() => {
Bus.publish(Ide.Event.Installed, { ide })
})
.then(() => Bus.publish(Ide.Event.Installed, { ide }))
.catch(() => {})
})()

View File

@@ -10,11 +10,14 @@ import fs from "fs/promises"
import { lazy } from "../util/lazy"
import { NamedError } from "../util/error"
import matter from "gray-matter"
import { Flag } from "../flag/flag"
import { Auth } from "../auth"
export namespace Config {
const log = Log.create({ service: "config" })
export const state = App.state("config", async (app) => {
const auth = await Auth.all()
let result = await global()
for (const file of ["opencode.jsonc", "opencode.json"]) {
const found = await Filesystem.findUp(file, app.path.cwd, app.path.root)
@@ -23,6 +26,20 @@ export namespace Config {
}
}
// Override with custom config if provided
if (Flag.OPENCODE_CONFIG) {
result = mergeDeep(result, await load(Flag.OPENCODE_CONFIG))
log.debug("loaded custom config", { path: Flag.OPENCODE_CONFIG })
}
for (const [key, value] of Object.entries(auth)) {
if (value.type === "wellknown") {
process.env[value.key] = value.token
const wellknown = await fetch(`${key}/.well-known/opencode`).then((x) => x.json())
result = mergeDeep(result, await loadRaw(JSON.stringify(wellknown.config ?? {}), process.cwd()))
}
}
result.agent = result.agent || {}
const markdownAgents = [
...(await Filesystem.globUp("agent/*.md", Global.Path.config, Global.Path.config)),
@@ -300,7 +317,10 @@ export namespace Config {
throw new JsonError({ path: configPath }, { cause: err })
})
if (!text) return {}
return loadRaw(text, configPath)
}
async function loadRaw(text: string, configPath: string) {
text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
return process.env[varName] || ""
})

View File

@@ -1,6 +1,7 @@
export namespace Flag {
export const OPENCODE_AUTO_SHARE = truthy("OPENCODE_AUTO_SHARE")
export const OPENCODE_DISABLE_WATCHER = truthy("OPENCODE_DISABLE_WATCHER")
export const OPENCODE_CONFIG = process.env["OPENCODE_CONFIG"]
function truthy(key: string) {
const value = process.env[key]?.toLowerCase()

View File

@@ -1,10 +1,15 @@
import { $ } from "bun"
import { spawn } from "bun"
import { z } from "zod"
import { NamedError } from "../util/error"
import { Log } from "../util/log"
import { Bus } from "../bus"
const SUPPORTED_IDES = ["Windsurf", "Visual Studio Code", "Cursor", "VSCodium"] as const
const SUPPORTED_IDES = [
{ name: "Windsurf" as const, cmd: "windsurf" },
{ name: "Visual Studio Code" as const, cmd: "code" },
{ name: "Cursor" as const, cmd: "cursor" },
{ name: "VSCodium" as const, cmd: "codium" },
]
export namespace Ide {
const log = Log.create({ service: "ide" })
@@ -18,8 +23,6 @@ export namespace Ide {
),
}
export type Ide = Awaited<ReturnType<typeof ide>>
export const AlreadyInstalledError = NamedError.create("AlreadyInstalledError", z.object({}))
export const InstallFailedError = NamedError.create(
@@ -29,11 +32,11 @@ export namespace Ide {
}),
)
export async function ide() {
export function ide() {
if (process.env["TERM_PROGRAM"] === "vscode") {
const v = process.env["GIT_ASKPASS"]
for (const ide of SUPPORTED_IDES) {
if (v?.includes(ide)) return ide
if (v?.includes(ide.name)) return ide.name
}
}
return "unknown"
@@ -43,32 +46,29 @@ export namespace Ide {
return process.env["OPENCODE_CALLER"] === "vscode"
}
export async function install(ide: Ide) {
const cmd = (() => {
switch (ide) {
case "Windsurf":
return $`windsurf --install-extension sst-dev.opencode`
case "Visual Studio Code":
return $`code --install-extension sst-dev.opencode`
case "Cursor":
return $`cursor --install-extension sst-dev.opencode`
case "VSCodium":
return $`codium --install-extension sst-dev.opencode`
default:
throw new Error(`Unknown IDE: ${ide}`)
}
})()
// TODO: check OPENCODE_CALLER
const result = await cmd.quiet().throws(false)
export async function install(ide: (typeof SUPPORTED_IDES)[number]["name"]) {
const cmd = SUPPORTED_IDES.find((i) => i.name === ide)?.cmd
if (!cmd) throw new Error(`Unknown IDE: ${ide}`)
const p = spawn([cmd, "--install-extension", "sst-dev.opencode"], {
stdout: "pipe",
stderr: "pipe",
})
await p.exited
const stdout = await new Response(p.stdout).text()
const stderr = await new Response(p.stderr).text()
log.info("installed", {
ide,
stdout: result.stdout.toString(),
stderr: result.stderr.toString(),
stdout,
stderr,
})
if (result.exitCode !== 0)
throw new InstallFailedError({
stderr: result.stderr.toString("utf8"),
})
if (result.stdout.toString().includes("already installed")) throw new AlreadyInstalledError({})
if (p.exitCode !== 0) {
throw new InstallFailedError({ stderr })
}
if (stdout.includes("already installed")) {
throw new AlreadyInstalledError({})
}
}
}

View File

@@ -1,5 +1,7 @@
import { experimental_createMCPClient, type Tool } from "ai"
import { Experimental_StdioMCPTransport } from "ai/mcp-stdio"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { App } from "../app/app"
import { Config } from "../config/config"
import { Log } from "../util/log"
@@ -32,15 +34,28 @@ export namespace MCP {
}
log.info("found", { key, type: mcp.type })
if (mcp.type === "remote") {
const client = await experimental_createMCPClient({
name: key,
transport: {
type: "sse",
url: mcp.url,
headers: mcp.headers,
},
}).catch(() => {})
if (!client) {
const transports = [
new StreamableHTTPClientTransport(new URL(mcp.url), {
requestInit: {
headers: mcp.headers,
},
}),
new SSEClientTransport(new URL(mcp.url), {
requestInit: {
headers: mcp.headers,
},
}),
]
for (const transport of transports) {
const client = await experimental_createMCPClient({
name: key,
transport,
}).catch(() => {})
if (!client) continue
clients[key] = client
break
}
if (!clients[key])
Bus.publish(Session.Event.Error, {
error: {
name: "UnknownError",
@@ -49,16 +64,13 @@ export namespace MCP {
},
},
})
continue
}
clients[key] = client
}
if (mcp.type === "local") {
const [cmd, ...args] = mcp.command
const client = await experimental_createMCPClient({
name: key,
transport: new Experimental_StdioMCPTransport({
transport: new StdioClientTransport({
stderr: "ignore",
command: cmd,
args,

View File

@@ -43,6 +43,10 @@ export namespace Server {
export type Routes = ReturnType<typeof app>
export const Event = {
Connected: Bus.event("server.connected", z.object({})),
}
function app() {
const app = new Hono()
@@ -109,7 +113,10 @@ export namespace Server {
log.info("event connected")
return streamSSE(c, async (stream) => {
stream.writeSSE({
data: JSON.stringify({}),
data: JSON.stringify({
type: "server.connected",
properties: {},
}),
})
const unsub = Bus.subscribeAll(async (event) => {
await stream.writeSSE({

View File

@@ -67,6 +67,7 @@ export namespace Session {
messageID: z.string(),
partID: z.string().optional(),
snapshot: z.string().optional(),
diff: z.string().optional(),
})
.optional(),
})
@@ -419,9 +420,7 @@ export namespace Session {
case "file:":
// have to normalize, symbol search returns absolute paths
// Decode the pathname since URL constructor doesn't automatically decode it
const pathname = decodeURIComponent(url.pathname)
const relativePath = pathname.replace(app.path.cwd, ".")
const filePath = path.join(app.path.cwd, relativePath)
const filePath = decodeURIComponent(url.pathname)
if (part.mime === "text/plain") {
let offset: number | undefined = undefined
@@ -501,7 +500,7 @@ export namespace Session {
messageID: userMsg.id,
sessionID: input.sessionID,
type: "text",
text: `Called the Read tool with the following input: {\"filePath\":\"${pathname}\"}`,
text: `Called the Read tool with the following input: {\"filePath\":\"${filePath}\"}`,
synthetic: true,
},
{
@@ -541,8 +540,6 @@ export namespace Session {
for (const part of userParts) {
await updatePart(part)
}
// mark session as updated since a message has been added to it
await update(input.sessionID, (_draft) => {})
if (isLocked(input.sessionID)) {
return new Promise((resolve) => {
@@ -567,6 +564,7 @@ export namespace Session {
const [preserve, remove] = splitWhen(msgs, (x) => x.info.id === messageID)
msgs = preserve
for (const msg of remove) {
if (msg.info.id === userMsg.id) continue
await Storage.remove(`session/message/${input.sessionID}/${msg.info.id}`)
await Bus.publish(MessageV2.Event.Removed, { sessionID: input.sessionID, messageID: msg.info.id })
}
@@ -578,11 +576,15 @@ export namespace Session {
for (const part of removeParts) {
await Storage.remove(`session/part/${input.sessionID}/${last.info.id}/${part.id}`)
await Bus.publish(MessageV2.Event.PartRemoved, {
sessionID: input.sessionID,
messageID: last.info.id,
partID: part.id,
})
}
}
await update(input.sessionID, (draft) => {
draft.revert = undefined
})
}
const previous = msgs.filter((x) => x.info.role === "assistant").at(-1)?.info as MessageV2.Assistant
@@ -640,7 +642,9 @@ export namespace Session {
.then((result) => {
if (result.text)
return Session.update(input.sessionID, (draft) => {
draft.title = result.text
const cleaned = result.text.replace(/<think>[\s\S]*?<\/think>\s*/g, "")
const title = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
draft.title = title.trim()
})
})
.catch(() => {})
@@ -882,7 +886,7 @@ export namespace Session {
case "tool-input-start":
const part = await updatePart({
id: Identifier.ascending("part"),
id: toolCalls[value.id]?.id ?? Identifier.ascending("part"),
messageID: assistantMsg.id,
sessionID: assistantMsg.sessionID,
type: "tool",
@@ -1029,17 +1033,17 @@ export namespace Session {
case "text":
if (currentText) {
currentText.text += value.text
await updatePart(currentText)
if (currentText.text) await updatePart(currentText)
}
break
case "text-end":
if (currentText && currentText.text) {
if (currentText) {
currentText.text = currentText.text.trimEnd()
currentText.time = {
start: Date.now(),
end: Date.now(),
}
currentText.text = currentText.text.trimEnd()
await updatePart(currentText)
}
currentText = undefined
@@ -1160,6 +1164,7 @@ export namespace Session {
const session = await get(input.sessionID)
revert.snapshot = session.revert?.snapshot ?? (await Snapshot.track())
await Snapshot.revert(patches)
if (revert.snapshot) revert.diff = await Snapshot.diff(revert.snapshot)
return update(input.sessionID, (draft) => {
draft.revert = revert
})

View File

@@ -284,6 +284,7 @@ export namespace MessageV2 {
PartRemoved: Bus.event(
"message.part.removed",
z.object({
sessionID: z.string(),
messageID: z.string(),
partID: z.string(),
}),

View File

@@ -1,4 +1,6 @@
You are opencode, an autonomous agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
# Beast Mode 3.1
You are opencode, an agent - please keep going until the users 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.
@@ -6,25 +8,26 @@ 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. Use the TodoWrite and TodoRead tools to track and manage steps. Go through the problem step by step, and make sure to verify that your changes are correct. Once each step is finished mark it as completed with the TodoWrite tool. NEVER end your turn without having truly and completely solved the problem, use the TodoRead tool to make sure all steps are complete, 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. If a step is impossible to complete, mark it as cancelled using the TodoWrite tool.
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.
THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH.
You must use the webfetch tool to recursively gather all information from URLs provided to you by the user, as well as any links you find in the content of those pages.
You must use the 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.
Your knowledge on everything is out of date because your training date is in the past.
Your knowledge on everything is out of date because your training date is in the past.
You CANNOT successfully complete this task without using Bing to verify your understanding of third party packages and dependencies is up to date. You must use the webfetch tool to search bing for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need.
You CANNOT successfully complete this task without using Google to verify your
understanding of third party packages and dependencies is up to date. You must use the webfetch tool to search google for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need.
If the user request is "resume" or "continue" or "try again",use the TodoRead tool to find the next pending step. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all steps are marked as complete or cancelled. Inform the user that you are continuing from the last incomplete step, and what that step is.
Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.
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. Use the sequential thinking tool if available. 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, update the plan and iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; run the build, and verify that the changes you made actually build; make sure you handle all edge cases, and run existing tests if they are provided.
If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.
You MUST plan extensively before each tool call, and reflect extensively on the outcomes of the previous tool calls. DO NOT do this entire process by making tool calls only, as this can impair your ability to solve the problem and think insightfully.
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. Use the sequential thinking tool if available. 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 keep working until the problem is completely solved, and all steps in the todo list are complete. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.
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 MUST use the ToolRead tool to verify that all steps are complete or cancelled before ending your turn. If any steps are incomplete, you MUST continue working on them until they are all complete.
You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.
You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
@@ -38,7 +41,7 @@ You are a highly capable and autonomous agent, and you can definitely solve this
- What are the dependencies and interactions with other parts of the code?
3. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
4. Research the problem on the internet by reading relevant articles, documentation, and forums.
5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using standard markdown format. Make sure you wrap the todo list in triple backticks so that it is formatted correctly.
5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using emoji's to indicate the status of each item.
6. Implement the fix incrementally. Make small, testable code changes.
7. Debug as needed. Use debugging techniques to isolate and resolve issues.
8. Test frequently. Run tests after each change to verify correctness.
@@ -49,12 +52,12 @@ Refer to the detailed sections below for more information on each step.
## 1. Fetch Provided URLs
- If the user provides a URL, use the `webfetch` tool to retrieve the content of the provided URL.
- After fetching, review the content returned by the fetch tool.
- After fetching, review the content returned by the webfetch tool.
- If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links.
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
## 2. Deeply Understand the Problem
Carefully read the issue and think hard about a plan to solve it before coding. Use the sequential thinking tool if available.
Carefully read the issue and think hard about a plan to solve it before coding.
## 3. Codebase Investigation
- Explore relevant files and directories.
@@ -64,49 +67,49 @@ Carefully read the issue and think hard about a plan to solve it before coding.
- Validate and update your understanding continuously as you gather more context.
## 4. Internet Research
- Use the `webfetch` tool to search bing by fetching the URL `https://www.bing.com/search?q=your+search+query`.
- Use the `webfetch` tool to search google by fetching the URL `https://www.google.com/search?q=your+search+query`.
- After fetching, review the content returned by the fetch tool.
- If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links.
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
- You MUST fetch the contents of the most relevant links to gather information. Do not rely on the summary that you find in the search results.
- As you fetch each link, read the content thoroughly and fetch any additional links that you find withhin the content that are relevant to the problem.
- Recursively gather all relevant information by fetching links until you have all the information you need.
## 5. Develop a Detailed Plan
## 5. Develop a Detailed Plan
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
- Add steps using the TodoWrite tool.
- Each time you complete a step, mark it as complete using the TodoWrite tool.
- Each time you check off a step, use the TodoRead tool and display the updated todo list to the user in markdown format.
- You MUST 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.
- You may only end your turn when all steps in the todo list are marked as complete or cancelled.
- Create a todo list in markdown format to track your progress.
- Each time you complete a step, check it off using `[x]` syntax.
- Each time you check off a step, display the updated todo list to the user.
- Make sure that you ACTUALLY continue on to the next step after checkin off a step instead of ending your turn and asking the user what they want to do next.
## 6. 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.
- When using the edit tool, include 3-5 lines of unchanged code before and after the string you want to replace, to make it unambiguous which part of the file should be edited.
- If a patch or edit is not applied correctly, attempt to reapply it.
- Always validate that your changes build and pass tests after each change.
- If the build fails or test fail, debug why before proceeding, update the plan as needed.
- 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.
## 7. Debugging
- Use the `lsp_diagnostics` tool to check for any problems in the code.
- 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.
- 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.
# How to create a Todo List
Use the following format to show the todo list:
```markdown
- [ ] Step 1: Description of the first step
- [ ] Step 2: Description of the second step
- [ ] Step 3: Description of the third step
```
Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above.
Use the following format to create a todo list:
```markdown
- [ ] Step 1: Description of the first step
- [ ] Step 2: Description of the second step
- [ ] Step 3: Description of the third step
```
Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above. Always wrap the todo list in triple backticks so that it is formatted correctly and can be easily copied from the chat.
Always show the completed todo list to the user as the last item in your message, so that they can see that you have addressed all of the steps.
# Communication Guidelines
Always communicate clearly and concisely in a casual, friendly yet professional tone.
Always communicate clearly and concisely in a casual, friendly yet professional tone.
<examples>
"Let me fetch the URL you provided to gather more information."
"Ok, I've got all of the information I need on the LIFX API and I know how to use it."
@@ -115,3 +118,44 @@ Always communicate clearly and concisely in a casual, friendly yet professional
"OK! Now let's run the tests to make sure everything is working correctly."
"Whelp - I see we have some problems. Let's fix those up."
</examples>
- Respond with clear, direct answers. Use bullet points and code blocks for structure. - Avoid unnecessary explanations, repetition, and filler.
- Always write code directly to the correct files.
- Do not display code to the user unless they specifically ask for it.
- Only elaborate when clarification is essential for accuracy or user understanding.
# Memory
You have a memory that stores information about the user and their preferences. This memory is used to provide a more personalized experience. You can access and update this memory as needed. The memory is stored in a file called `.github/instructions/memory.instruction.md`. If the file is empty, you'll need to create it.
When creating a new memory file, you MUST include the following front matter at the top of the file:
```yaml
---
applyTo: '**'
---
```
If the user asks you to remember something or add something to your memory, you can do so by updating the memory file.
# Reading Files and Folders
**Always check if you have already read a file, folder, or workspace structure before reading it again.**
- If you have already read the content and it has not changed, do NOT re-read it.
- Only re-read files or folders if:
- You suspect the content has changed since your last read.
- You have made edits to the file or folder.
- You encounter an error that suggests the context may be stale or incomplete.
- Use your internal memory and previous context to avoid redundant reads.
- This will save time, reduce unnecessary operations, and make your workflow more efficient.
# Writing Prompts
If you are asked to write a prompt, you should always generate the prompt in markdown format.
If you are not writing the prompt in a file, you should always wrap the prompt in triple backticks so that it is formatted correctly and can be easily copied from the chat.
Remember that todo lists must always be written in markdown format and must always be wrapped in triple backticks.
# Git
If the user tells you to stage and commit, you may do so.
You are NEVER allowed to stage and commit files automatically.

View File

@@ -1,3 +1,3 @@
<system-reminder>
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make edits).
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received (for example, to make edits).
</system-reminder>

View File

@@ -0,0 +1,109 @@
You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
If the user asks for help or wants to give feedback inform them of the following:
- /help: Get help with using opencode
- To give feedback, users should report the issue at https://github.com/sst/opencode/issues
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
# Tone and style
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
<example>
user: 2 + 2
assistant: 4
</example>
<example>
user: what is 2+2?
assistant: 4
</example>
<example>
user: is 11 a prime number?
assistant: Yes
</example>
<example>
user: what command should I run to list files in the current directory?
assistant: ls
</example>
<example>
user: what command should I run to watch files in the current directory?
assistant: [use the ls tool to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
npm run dev
</example>
<example>
user: How many golf balls fit inside a jetta?
assistant: 150000
</example>
<example>
user: what files are in the directory src/?
assistant: [runs ls and sees foo.c, bar.c, baz.c]
user: which file contains the implementation of foo?
assistant: src/foo.c
</example>
<example>
user: write tests for new feature
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
</example>
# Proactiveness
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
1. Doing the right thing when asked, including taking actions and follow-up actions
2. Not surprising the user with actions you take without asking
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
# Following conventions
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
# Code style
- IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked
# Doing tasks
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
- Implement the solution using all tools available to you
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
# Tool usage policy
- When doing file search, prefer to use the Task tool in order to reduce context usage.
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
# Code References
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
<example>
user: Where are errors from the client handled?
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
</example>

View File

@@ -10,7 +10,7 @@ You are generating titles for a coding assistant conversation.
- Max 50 chars, single line
- Focus on the specific action or question
- Keep technical terms, numbers, and filenames exactly as written
- Preserve HTTP status codes (401, 404, 500, etc) as numbers
- Preserve HTTP status codes (401, 404, 500, etc.) as numbers
- For file references, include the filename
- Avoid filler words: the, this, my, a, an, properly
- NEVER assume their tech stack or domain

View File

@@ -7,6 +7,7 @@ import path from "path"
import os from "os"
import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
import PROMPT_ANTHROPIC_WITHOUT_TODO from "./prompt/qwen.txt"
import PROMPT_BEAST from "./prompt/beast.txt"
import PROMPT_GEMINI from "./prompt/gemini.txt"
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
@@ -21,7 +22,8 @@ export namespace SystemPrompt {
export function provider(modelID: string) {
if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
return [PROMPT_ANTHROPIC]
if (modelID.includes("claude")) return [PROMPT_ANTHROPIC]
return [PROMPT_ANTHROPIC_WITHOUT_TODO]
}
export async function environment() {

View File

@@ -94,6 +94,13 @@ export namespace Snapshot {
}
}
export async function diff(hash: string) {
const app = App.info()
const git = gitdir()
const result = await $`git --git-dir=${git} diff ${hash} -- .`.quiet().cwd(app.path.root).text()
return result.trim()
}
function gitdir() {
const app = App.info()
return path.join(app.path.data, "snapshots")

View File

@@ -11,7 +11,7 @@ export const BashTool = Tool.define("bash", {
description: DESCRIPTION,
parameters: z.object({
command: z.string().describe("The command to execute"),
timeout: z.number().min(0).max(MAX_TIMEOUT).describe("Optional timeout in milliseconds").optional(),
timeout: z.number().describe("Optional timeout in milliseconds").optional(),
description: z
.string()
.describe(

View File

@@ -14,8 +14,8 @@ export const ReadTool = Tool.define("read", {
description: DESCRIPTION,
parameters: z.object({
filePath: z.string().describe("The path to the file to read"),
offset: z.number().describe("The line number to start reading from (0-based)").optional(),
limit: z.number().describe("The number of lines to read (defaults to 2000)").optional(),
offset: z.coerce.number().describe("The line number to start reading from (0-based)").optional(),
limit: z.coerce.number().describe("The number of lines to read (defaults to 2000)").optional(),
}),
async execute(params, ctx) {
let filePath = params.filePath

View File

@@ -69,7 +69,13 @@ export namespace ToolRegistry {
patch: false,
}
}
if (modelID.toLowerCase().includes("qwen")) {
if (
modelID.toLowerCase().includes("qwen") ||
modelID.includes("gpt-") ||
modelID.includes("o1") ||
modelID.includes("o3")
) {
return {
patch: false,
todowrite: false,

View File

@@ -70,7 +70,7 @@ export const TaskTool = Tool.define("task", async () => {
metadata: {
summary: result.parts.filter((x) => x.type === "tool"),
},
output: result.parts.findLast((x) => x.type === "text")!.text,
output: result.parts.findLast((x) => x.type === "text")?.text ?? "",
}
},
}

View File

@@ -4,7 +4,7 @@ import DESCRIPTION_WRITE from "./todowrite.txt"
import { App } from "../app/app"
const TodoInfo = z.object({
content: z.string().min(1).describe("Brief description of the task"),
content: z.string().describe("Brief description of the task"),
status: z.enum(["pending", "in_progress", "completed", "cancelled"]).describe("Current status of the task"),
priority: z.enum(["high", "medium", "low"]).describe("Priority level of the task"),
id: z.string().describe("Unique identifier for the todo item"),

View File

@@ -14,12 +14,7 @@ export const WebFetchTool = Tool.define("webfetch", {
format: z
.enum(["text", "markdown", "html"])
.describe("The format to return the content in (text, markdown, or html)"),
timeout: z
.number()
.min(0)
.max(MAX_TIMEOUT / 1000)
.describe("Optional timeout in seconds (max 120)")
.optional(),
timeout: z.number().describe("Optional timeout in seconds (max 120)").optional(),
}),
async execute(params, ctx) {
// Validate URL

View File

@@ -0,0 +1 @@
// Test fixture for ListTool

View File

@@ -0,0 +1 @@
// Test fixture for ListTool

View File

@@ -0,0 +1 @@
// Test fixture for ListTool

View File

@@ -1,17 +1,9 @@
// Bun Snapshot v1, https://goo.gl/fbAQLP
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots
exports[`tool.ls basic 1`] = `
"- /home/thdxr/dev/projects/sst/opencode/js/example/
- home/
- thdxr/
- dev/
- projects/
- sst/
- opencode/
- js/
- example/
- ink.tsx
- broken.ts
- cli.ts
"packages/opencode/test/fixtures/example/
broken.ts
cli.ts
ink.tsx
"
`;

View File

@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
import { App } from "../../src/app/app"
import { GlobTool } from "../../src/tool/glob"
import { ListTool } from "../../src/tool/ls"
import path from "path"
const ctx = {
sessionID: "test",
@@ -12,9 +13,12 @@ const ctx = {
const glob = await GlobTool.init()
const list = await ListTool.init()
const projectRoot = path.join(__dirname, "../..")
const fixturePath = path.join(__dirname, "../fixtures/example")
describe("tool.glob", () => {
test("truncate", async () => {
await App.provide({ cwd: process.cwd() }, async () => {
await App.provide({ cwd: projectRoot }, async () => {
let result = await glob.execute(
{
pattern: "../../node_modules/**/*",
@@ -26,7 +30,7 @@ describe("tool.glob", () => {
})
})
test("basic", async () => {
await App.provide({ cwd: process.cwd() }, async () => {
await App.provide({ cwd: projectRoot }, async () => {
let result = await glob.execute(
{
pattern: "*.json",
@@ -44,9 +48,12 @@ describe("tool.glob", () => {
describe("tool.ls", () => {
test("basic", async () => {
const result = await App.provide({ cwd: process.cwd() }, async () => {
return await list.execute({ path: "./example", ignore: [".git"] }, ctx)
const result = await App.provide({ cwd: projectRoot }, async () => {
return await list.execute({ path: fixturePath, ignore: [".git"] }, ctx)
})
expect(result.output).toMatchSnapshot()
// Normalize absolute path to relative for consistent snapshots
const normalizedOutput = result.output.replace(fixturePath, "packages/opencode/test/fixtures/example")
expect(normalizedOutput).toMatchSnapshot()
})
})

View File

@@ -1,4 +1,4 @@
configured_endpoints: 26
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-5748199af356c3243a46a466e73b5d0bab7eaa0c56895e1d0f903d637f61d0bb.yml
openapi_spec_hash: c04f6b6be54b05d9b1283c24e870163b
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-62d8fccba4eb8dc3a80434e0849eab3352e49fb96a718bb7b6d17ed8e582b716.yml
openapi_spec_hash: 4ff9376cf9634e91731e63fe482ea532
config_hash: 1ae82c93499b9f0b9ba828b8919f9cb3

View File

@@ -41,7 +41,6 @@ Methods:
Types:
- <code><a href="./src/resources/find.ts">Match</a></code>
- <code><a href="./src/resources/find.ts">Symbol</a></code>
- <code><a href="./src/resources/find.ts">FindFilesResponse</a></code>
- <code><a href="./src/resources/find.ts">FindSymbolsResponse</a></code>

View File

@@ -46,7 +46,6 @@ import {
FindSymbolsResponse,
FindTextParams,
FindTextResponse,
Match,
Symbol,
} from './resources/find';
import {
@@ -789,7 +788,6 @@ export declare namespace Opencode {
export {
Find as Find,
type Match as Match,
type Symbol as Symbol,
type FindFilesResponse as FindFilesResponse,
type FindSymbolsResponse as FindSymbolsResponse,

View File

@@ -77,6 +77,8 @@ export interface Mode {
model?: Mode.Model;
prompt?: string;
temperature?: number;
}
export namespace Mode {

View File

@@ -20,6 +20,11 @@ export interface Config {
*/
$schema?: string;
/**
* Modes configuration, see https://opencode.ai/docs/modes
*/
agent?: Config.Agent;
/**
* @deprecated Use 'share' field instead. Share newly created sessions
* automatically
@@ -97,6 +102,33 @@ export interface Config {
}
export namespace Config {
/**
* Modes configuration, see https://opencode.ai/docs/modes
*/
export interface Agent {
general?: Agent.General;
[k: string]: Agent.AgentConfig | undefined;
}
export namespace Agent {
export interface General extends ConfigAPI.ModeConfig {
description: string;
}
export interface AgentConfig extends ConfigAPI.ModeConfig {
description: string;
}
}
export interface AgentConfig extends ConfigAPI.ModeConfig {
description: string;
}
export interface AgentConfig extends ConfigAPI.ModeConfig {
description: string;
}
export interface Experimental {
hook?: Experimental.Hook;
}
@@ -438,10 +470,14 @@ export interface McpRemoteConfig {
}
export interface ModeConfig {
disable?: boolean;
model?: string;
prompt?: string;
temperature?: number;
tools?: { [key: string]: boolean };
}

View File

@@ -17,23 +17,36 @@ export class Event extends APIResource {
}
export type EventListResponse =
| EventListResponse.EventLspClientDiagnostics
| EventListResponse.EventPermissionUpdated
| EventListResponse.EventFileEdited
| EventListResponse.EventInstallationUpdated
| EventListResponse.EventLspClientDiagnostics
| EventListResponse.EventMessageUpdated
| EventListResponse.EventMessageRemoved
| EventListResponse.EventMessagePartUpdated
| EventListResponse.EventMessagePartRemoved
| EventListResponse.EventStorageWrite
| EventListResponse.EventPermissionUpdated
| EventListResponse.EventFileEdited
| EventListResponse.EventSessionUpdated
| EventListResponse.EventSessionDeleted
| EventListResponse.EventSessionIdle
| EventListResponse.EventSessionError
| EventListResponse.EventServerConnected
| EventListResponse.EventFileWatcherUpdated
| EventListResponse.EventIdeInstalled;
export namespace EventListResponse {
export interface EventInstallationUpdated {
properties: EventInstallationUpdated.Properties;
type: 'installation.updated';
}
export namespace EventInstallationUpdated {
export interface Properties {
version: string;
}
}
export interface EventLspClientDiagnostics {
properties: EventLspClientDiagnostics.Properties;
@@ -48,56 +61,6 @@ export namespace EventListResponse {
}
}
export interface EventPermissionUpdated {
properties: EventPermissionUpdated.Properties;
type: 'permission.updated';
}
export namespace EventPermissionUpdated {
export interface Properties {
id: string;
metadata: { [key: string]: unknown };
sessionID: string;
time: Properties.Time;
title: string;
}
export namespace Properties {
export interface Time {
created: number;
}
}
}
export interface EventFileEdited {
properties: EventFileEdited.Properties;
type: 'file.edited';
}
export namespace EventFileEdited {
export interface Properties {
file: string;
}
}
export interface EventInstallationUpdated {
properties: EventInstallationUpdated.Properties;
type: 'installation.updated';
}
export namespace EventInstallationUpdated {
export interface Properties {
version: string;
}
}
export interface EventMessageUpdated {
properties: EventMessageUpdated.Properties;
@@ -147,6 +110,8 @@ export namespace EventListResponse {
messageID: string;
partID: string;
sessionID: string;
}
}
@@ -164,6 +129,44 @@ export namespace EventListResponse {
}
}
export interface EventPermissionUpdated {
properties: EventPermissionUpdated.Properties;
type: 'permission.updated';
}
export namespace EventPermissionUpdated {
export interface Properties {
id: string;
metadata: { [key: string]: unknown };
sessionID: string;
time: Properties.Time;
title: string;
}
export namespace Properties {
export interface Time {
created: number;
}
}
}
export interface EventFileEdited {
properties: EventFileEdited.Properties;
type: 'file.edited';
}
export namespace EventFileEdited {
export interface Properties {
file: string;
}
}
export interface EventSessionUpdated {
properties: EventSessionUpdated.Properties;
@@ -226,6 +229,12 @@ export namespace EventListResponse {
}
}
export interface EventServerConnected {
properties: unknown;
type: 'server.connected';
}
export interface EventFileWatcherUpdated {
properties: EventFileWatcherUpdated.Properties;

View File

@@ -27,42 +27,6 @@ export class Find extends APIResource {
}
}
export interface Match {
absolute_offset: number;
line_number: number;
lines: Match.Lines;
path: Match.Path;
submatches: Array<Match.Submatch>;
}
export namespace Match {
export interface Lines {
text: string;
}
export interface Path {
text: string;
}
export interface Submatch {
end: number;
match: Submatch.Match;
start: number;
}
export namespace Submatch {
export interface Match {
text: string;
}
}
}
export interface Symbol {
kind: number;
@@ -105,7 +69,45 @@ export type FindFilesResponse = Array<string>;
export type FindSymbolsResponse = Array<Symbol>;
export type FindTextResponse = Array<Match>;
export type FindTextResponse = Array<FindTextResponse.FindTextResponseItem>;
export namespace FindTextResponse {
export interface FindTextResponseItem {
absolute_offset: number;
line_number: number;
lines: FindTextResponseItem.Lines;
path: FindTextResponseItem.Path;
submatches: Array<FindTextResponseItem.Submatch>;
}
export namespace FindTextResponseItem {
export interface Lines {
text: string;
}
export interface Path {
text: string;
}
export interface Submatch {
end: number;
match: Submatch.Match;
start: number;
}
export namespace Submatch {
export interface Match {
text: string;
}
}
}
}
export interface FindFilesParams {
query: string;
@@ -121,7 +123,6 @@ export interface FindTextParams {
export declare namespace Find {
export {
type Match as Match,
type Symbol as Symbol,
type FindFilesResponse as FindFilesResponse,
type FindSymbolsResponse as FindSymbolsResponse,

View File

@@ -31,7 +31,6 @@ export {
} from './file';
export {
Find,
type Match,
type Symbol,
type FindFilesResponse,
type FindSymbolsResponse,

View File

@@ -270,6 +270,8 @@ export namespace Session {
export interface Revert {
messageID: string;
diff?: string;
partID?: string;
snapshot?: string;
@@ -541,6 +543,8 @@ export interface SessionChatParams {
mode?: string;
system?: string;
tools?: { [key: string]: boolean };
}

9
packages/sdk/sst-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* This file is auto-generated by SST. Do not edit. */
/* tslint:disable */
/* eslint-disable */
/* deno-fmt-ignore-file */
/// <reference path="../../sst-env.d.ts" />
import "sst"
export {}

View File

@@ -77,6 +77,7 @@ describe('resource session', () => {
providerID: 'providerID',
messageID: 'msg',
mode: 'mode',
system: 'system',
tools: { foo: true },
});
});

View File

@@ -18,7 +18,7 @@ describe('form data validation', () => {
});
test('null', async () => {
await expect(() =>
await expect(
multipartFormRequestOptions(
{
body: {

View File

@@ -51,7 +51,7 @@ describe('toFile', () => {
});
it('extracts a file name from a ReadStream', async () => {
const input = fs.createReadStream('tests/uploads.test.ts');
const input = fs.createReadStream(__filename);
const file = await toFile(input);
expect(file.name).toEqual('uploads.test.ts');
});
@@ -78,8 +78,6 @@ describe('missing File error message', () => {
let prevNodeFile: unknown;
beforeEach(() => {
// The file shim captures the global File object when it's first imported.
// Reset modules before each test so we can test the error thrown when it's undefined.
jest.resetModules();
const buffer = require('node:buffer');
// @ts-ignore
prevGlobalFile = globalThis.File;
@@ -93,7 +91,6 @@ describe('missing File error message', () => {
// @ts-ignore
globalThis.File = prevGlobalFile;
require('node:buffer').File = prevNodeFile;
jest.resetModules();
});
test('is thrown', async () => {

View File

@@ -101,8 +101,9 @@ func main() {
panic(err)
}
tuiModel := tui.NewModel(app_).(*tui.Model)
program := tea.NewProgram(
tui.NewModel(app_),
tuiModel,
tea.WithAltScreen(),
tea.WithMouseCellMotion(),
)
@@ -132,6 +133,7 @@ func main() {
go func() {
sig := <-sigChan
slog.Info("Received signal, shutting down gracefully", "signal", sig)
tuiModel.Cleanup()
program.Quit()
}()
@@ -141,5 +143,6 @@ func main() {
slog.Error("TUI error", "error", err)
}
tuiModel.Cleanup()
slog.Info("TUI exited", "result", result)
}

View File

@@ -5,12 +5,12 @@ go 1.24.0
require (
github.com/BurntSushi/toml v1.5.0
github.com/alecthomas/chroma/v2 v2.18.0
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbles/v2 v2.0.0-beta.1
github.com/charmbracelet/bubbletea/v2 v2.0.0-beta.4
github.com/charmbracelet/glamour v0.10.0
github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.3
github.com/charmbracelet/x/ansi v0.9.3
github.com/fsnotify/fsnotify v1.8.0
github.com/google/uuid v1.6.0
github.com/lithammer/fuzzysearch v1.1.8
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6
@@ -37,7 +37,6 @@ require (
github.com/charmbracelet/x/input v0.3.7 // indirect
github.com/charmbracelet/x/windows v0.2.1 // indirect
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/getkin/kin-openapi v0.127.0 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect

View File

@@ -20,8 +20,6 @@ github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWp
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbles/v2 v2.0.0-beta.1 h1:swACzss0FjnyPz1enfX56GKkLiuKg5FlyVmOLIlU2kE=
github.com/charmbracelet/bubbles/v2 v2.0.0-beta.1/go.mod h1:6HamsBKWqEC/FVHuQMHgQL+knPyvHH55HwJDHl/adMw=
github.com/charmbracelet/bubbletea/v2 v2.0.0-beta.4 h1:UgUuKKvBwgqm2ZEL+sKv/OLeavrUb4gfHgdxe6oIOno=

View File

@@ -777,7 +777,7 @@ var seed = flag.Int64("seed", 0, "random seed (0 to autoselect)")
// the seed flag was set.
func genRandomData(logfn func(int64), length int) randTest {
// We'll use a random source. However, we give the user the option
// to override it to a specific value for reproduceability.
// to override it to a specific value for reproducibility.
s := *seed
if s == 0 {
s = time.Now().UnixNano()

View File

@@ -206,7 +206,7 @@ func buildKeysTable(flags int, term string) map[string]Key {
table["\x1bOc"] = Key{Code: KeyRight, Mod: ModCtrl}
table["\x1bOd"] = Key{Code: KeyLeft, Mod: ModCtrl}
//nolint:godox
// TODO: invistigate if shift-ctrl arrow keys collide with DECCKM keys i.e.
// TODO: investigate if shift-ctrl arrow keys collide with DECCKM keys i.e.
// "\x1bOA", "\x1bOB", "\x1bOC", "\x1bOD"
// URxvt modifier CSI ~ keys

View File

@@ -311,13 +311,13 @@ func read(t Format) (buf []byte, err error) {
format = cFmtUnicodeText
}
// check if clipboard is avaliable for the requested format
// check if clipboard is available for the requested format
r, _, err := isClipboardFormatAvailable.Call(format)
if r == 0 {
return nil, errUnavailable
}
// try again until open clipboard successed
// try again until open clipboard succeeds
for {
r, _, _ = openClipboard.Call()
if r == 0 {

View File

@@ -4,7 +4,6 @@ import (
"encoding/base64"
"fmt"
"log/slog"
"net/url"
"os"
"path/filepath"
"strconv"
@@ -732,7 +731,7 @@ func (m *editorComponent) createAttachmentFromFile(filePath string) *attachment.
ID: uuid.NewString(),
Type: "file",
Display: "@" + filePath,
URL: fmt.Sprintf("file://./%s", filePath),
URL: fmt.Sprintf("file://%s", absolutePath),
Filename: filePath,
MediaType: mediaType,
Source: &attachment.FileSource{
@@ -783,7 +782,7 @@ func (m *editorComponent) createAttachmentFromPath(filePath string) *attachment.
ID: uuid.NewString(),
Type: "file",
Display: "@" + filePath,
URL: fmt.Sprintf("file://./%s", url.PathEscape(filePath)),
URL: fmt.Sprintf("file://%s", absolutePath),
Filename: filePath,
MediaType: mediaType,
Source: &attachment.FileSource{

View File

@@ -5,6 +5,8 @@ import (
"fmt"
"log/slog"
"slices"
"sort"
"strconv"
"strings"
tea "github.com/charmbracelet/bubbletea/v2"
@@ -14,6 +16,7 @@ import (
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/commands"
"github.com/sst/opencode/internal/components/dialog"
"github.com/sst/opencode/internal/components/diff"
"github.com/sst/opencode/internal/components/toast"
"github.com/sst/opencode/internal/layout"
"github.com/sst/opencode/internal/styles"
@@ -190,6 +193,12 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.Properties.Part.SessionID == m.app.Session.ID {
cmds = append(cmds, m.renderView())
}
case opencode.EventListResponseEventMessagePartRemoved:
if msg.Properties.SessionID == m.app.Session.ID {
// Clear the cache when a part is removed to ensure proper re-rendering
m.cache.Clear()
cmds = append(cmds, m.renderView())
}
case renderCompleteMsg:
m.partCount = msg.partCount
m.lineCount = msg.lineCount
@@ -281,6 +290,9 @@ func (m *messagesComponent) renderView() tea.Cmd {
if part.Synthetic {
continue
}
if part.Text == "" {
continue
}
remainingParts := message.Parts[partIndex+1:]
fileParts := make([]opencode.FilePart, 0)
for _, part := range remainingParts {
@@ -365,6 +377,9 @@ func (m *messagesComponent) renderView() tea.Cmd {
if reverted {
continue
}
if strings.TrimSpace(part.Text) == "" {
continue
}
hasTextPart = true
finished := part.Time.End > 0
remainingParts := message.Parts[partIndex+1:]
@@ -557,6 +572,36 @@ func (m *messagesComponent) renderView() tea.Cmd {
hint += revertedStyle.Render(" (or /redo) to restore")
content += "\n" + hint
if m.app.Session.Revert.Diff != "" {
t := theme.CurrentTheme()
s := styles.NewStyle().Background(t.BackgroundPanel())
green := s.Foreground(t.Success()).Render
red := s.Foreground(t.Error()).Render
content += "\n"
stats, err := diff.ParseStats(m.app.Session.Revert.Diff)
if err != nil {
slog.Error("Failed to parse diff stats", "error", err)
} else {
var files []string
for file := range stats {
files = append(files, file)
}
sort.Strings(files)
for _, file := range files {
fileStats := stats[file]
display := file
if fileStats.Added > 0 {
display += green(" +" + strconv.Itoa(int(fileStats.Added)))
}
if fileStats.Removed > 0 {
display += red(" -" + strconv.Itoa(int(fileStats.Removed)))
}
content += "\n" + display
}
}
}
content = styles.NewStyle().
Background(t.BackgroundPanel()).
Width(width - 6).

View File

@@ -0,0 +1,58 @@
package diff
import (
"bufio"
"fmt"
"strings"
)
type DiffStats struct {
Added int
Removed int
Modified int
}
func ParseStats(diff string) (map[string]DiffStats, error) {
stats := make(map[string]DiffStats)
var currentFile string
scanner := bufio.NewScanner(strings.NewReader(diff))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "---") {
continue
} else if strings.HasPrefix(line, "+++") {
parts := strings.SplitN(line, " ", 2)
if len(parts) == 2 {
currentFile = strings.TrimPrefix(parts[1], "b/")
}
continue
}
if strings.HasPrefix(line, "@@") {
continue
}
if currentFile == "" {
continue
}
fileStats := stats[currentFile]
switch {
case strings.HasPrefix(line, "+"):
fileStats.Added++
case strings.HasPrefix(line, "-"):
fileStats.Removed++
}
stats[currentFile] = fileStats
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading diff string: %w", err)
}
for file, fileStats := range stats {
fileStats.Modified = fileStats.Added + fileStats.Removed
stats[file] = fileStats
}
return stats, nil
}

View File

@@ -2,42 +2,63 @@ package status
import (
"os"
"os/exec"
"path/filepath"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/charmbracelet/lipgloss/v2"
"github.com/charmbracelet/lipgloss/v2/compat"
"github.com/fsnotify/fsnotify"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/commands"
"github.com/sst/opencode/internal/layout"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
)
type GitBranchUpdatedMsg struct {
Branch string
}
type StatusComponent interface {
tea.Model
tea.ViewModel
Cleanup()
}
type statusComponent struct {
app *app.App
width int
cwd string
app *app.App
width int
cwd string
branch string
watcher *fsnotify.Watcher
done chan struct{}
lastUpdate time.Time
}
func (m statusComponent) Init() tea.Cmd {
return nil
func (m *statusComponent) Init() tea.Cmd {
return m.startGitWatcher()
}
func (m statusComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
func (m *statusComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
return m, nil
case GitBranchUpdatedMsg:
if m.branch != msg.Branch {
m.branch = msg.Branch
}
// Continue watching for changes (persistent watcher)
return m, m.watchForGitChanges()
}
return m, nil
}
func (m statusComponent) logo() string {
func (m *statusComponent) logo() string {
t := theme.CurrentTheme()
base := styles.NewStyle().Foreground(t.TextMuted()).Background(t.BackgroundElement()).Render
emphasis := styles.NewStyle().
@@ -47,23 +68,56 @@ func (m statusComponent) logo() string {
Render
open := base("open")
code := emphasis("code ")
version := base(m.app.Version)
code := emphasis("code")
version := base(" " + m.app.Version)
content := open + code
if m.width > 40 {
content += version
}
return styles.NewStyle().
Background(t.BackgroundElement()).
Padding(0, 1).
Render(open + code + version)
Render(content)
}
func (m statusComponent) View() string {
func (m *statusComponent) collapsePath(path string, maxWidth int) string {
if lipgloss.Width(path) <= maxWidth {
return path
}
const ellipsis = ".."
ellipsisLen := len(ellipsis)
if maxWidth <= ellipsisLen {
if maxWidth > 0 {
return "..."[:maxWidth]
}
return ""
}
separator := string(filepath.Separator)
parts := strings.Split(path, separator)
if len(parts) == 1 {
return path[:maxWidth-ellipsisLen] + ellipsis
}
truncatedPath := parts[len(parts)-1]
for i := len(parts) - 2; i >= 0; i-- {
part := parts[i]
if len(truncatedPath)+len(separator)+len(part)+ellipsisLen > maxWidth {
return ellipsis + separator + truncatedPath
}
truncatedPath = part + separator + truncatedPath
}
return truncatedPath
}
func (m *statusComponent) View() string {
t := theme.CurrentTheme()
logo := m.logo()
cwd := styles.NewStyle().
Foreground(t.TextMuted()).
Background(t.BackgroundPanel()).
Padding(0, 1).
Render(m.cwd)
logoWidth := lipgloss.Width(logo)
var modeBackground compat.AdaptiveColor
var modeForeground compat.AdaptiveColor
@@ -113,28 +167,182 @@ func (m statusComponent) View() string {
BorderBackground(t.BackgroundPanel()).
Render(mode)
mode = styles.NewStyle().
faintStyle := styles.NewStyle().
Faint(true).
Background(t.BackgroundPanel()).
Foreground(t.TextMuted())
mode = faintStyle.Render(key+" ") + mode
modeWidth := lipgloss.Width(mode)
availableWidth := m.width - logoWidth - modeWidth
branchSuffix := ""
if m.branch != "" {
branchSuffix = ":" + m.branch
}
maxCwdWidth := availableWidth - lipgloss.Width(branchSuffix)
cwdDisplay := m.collapsePath(m.cwd, maxCwdWidth)
if m.branch != "" && availableWidth > lipgloss.Width(cwdDisplay)+lipgloss.Width(branchSuffix) {
cwdDisplay += faintStyle.Render(branchSuffix)
}
cwd := styles.NewStyle().
Foreground(t.TextMuted()).
Render(key+" ") +
mode
Background(t.BackgroundPanel()).
Padding(0, 1).
Render(cwdDisplay)
space := max(
0,
m.width-lipgloss.Width(logo)-lipgloss.Width(cwd)-lipgloss.Width(mode),
background := t.BackgroundPanel()
status := layout.Render(
layout.FlexOptions{
Background: &background,
Direction: layout.Row,
Justify: layout.JustifySpaceBetween,
Align: layout.AlignStretch,
Width: m.width,
},
layout.FlexItem{
View: logo + cwd,
},
layout.FlexItem{
View: mode,
},
)
spacer := styles.NewStyle().Background(t.BackgroundPanel()).Width(space).Render("")
status := logo + cwd + spacer + mode
blank := styles.NewStyle().Background(t.Background()).Width(m.width).Render("")
return blank + "\n" + status
}
func (m *statusComponent) startGitWatcher() tea.Cmd {
cmd := util.CmdHandler(
GitBranchUpdatedMsg{Branch: getCurrentGitBranch(m.app.Info.Path.Root)},
)
if err := m.initWatcher(); err != nil {
return cmd
}
return tea.Batch(cmd, m.watchForGitChanges())
}
func (m *statusComponent) initWatcher() error {
gitDir := filepath.Join(m.app.Info.Path.Root, ".git")
headFile := filepath.Join(gitDir, "HEAD")
if info, err := os.Stat(gitDir); err != nil || !info.IsDir() {
return err
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
if err := watcher.Add(headFile); err != nil {
watcher.Close()
return err
}
// Also watch the ref file if HEAD points to a ref
refFile := getGitRefFile(m.app.Info.Path.Cwd)
if refFile != headFile && refFile != "" {
if _, err := os.Stat(refFile); err == nil {
watcher.Add(refFile) // Ignore error, HEAD watching is sufficient
}
}
m.watcher = watcher
m.done = make(chan struct{})
return nil
}
func (m *statusComponent) watchForGitChanges() tea.Cmd {
if m.watcher == nil {
return nil
}
return tea.Cmd(func() tea.Msg {
for {
select {
case event, ok := <-m.watcher.Events:
branch := getCurrentGitBranch(m.app.Info.Path.Root)
if !ok {
return GitBranchUpdatedMsg{Branch: branch}
}
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) {
// Debounce updates to prevent excessive refreshes
now := time.Now()
if now.Sub(m.lastUpdate) < 100*time.Millisecond {
continue
}
m.lastUpdate = now
if strings.HasSuffix(event.Name, "HEAD") {
m.updateWatchedFiles()
}
return GitBranchUpdatedMsg{Branch: branch}
}
case <-m.watcher.Errors:
// Continue watching even on errors
case <-m.done:
return GitBranchUpdatedMsg{Branch: ""}
}
}
})
}
func (m *statusComponent) updateWatchedFiles() {
if m.watcher == nil {
return
}
refFile := getGitRefFile(m.app.Info.Path.Root)
headFile := filepath.Join(m.app.Info.Path.Root, ".git", "HEAD")
if refFile != headFile && refFile != "" {
if _, err := os.Stat(refFile); err == nil {
// Try to add the new ref file (ignore error if already watching)
m.watcher.Add(refFile)
}
}
}
func getCurrentGitBranch(cwd string) string {
cmd := exec.Command("git", "branch", "--show-current")
cmd.Dir = cwd
output, err := cmd.Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(output))
}
func getGitRefFile(cwd string) string {
headFile := filepath.Join(cwd, ".git", "HEAD")
content, err := os.ReadFile(headFile)
if err != nil {
return ""
}
headContent := strings.TrimSpace(string(content))
if after, ok := strings.CutPrefix(headContent, "ref: "); ok {
// HEAD points to a ref file
refPath := after
return filepath.Join(cwd, ".git", refPath)
}
// HEAD contains a direct commit hash
return headFile
}
func (m *statusComponent) Cleanup() {
if m.done != nil {
close(m.done)
}
if m.watcher != nil {
m.watcher.Close()
}
}
func NewStatusCmp(app *app.App) StatusComponent {
statusComponent := &statusComponent{
app: app,
app: app,
lastUpdate: time.Now(),
}
homePath, err := os.UserHomeDir()

View File

@@ -0,0 +1,100 @@
package status
import (
"os"
"path/filepath"
"testing"
"time"
)
func TestGetCurrentGitBranch(t *testing.T) {
// Test in current directory (should be a git repo)
branch := getCurrentGitBranch(".")
if branch == "" {
t.Skip("Not in a git repository, skipping test")
}
t.Logf("Current branch: %s", branch)
}
func TestGetGitRefFile(t *testing.T) {
// Create a temporary git directory structure for testing
tmpDir := t.TempDir()
gitDir := filepath.Join(tmpDir, ".git")
err := os.MkdirAll(gitDir, 0755)
if err != nil {
t.Fatal(err)
}
// Test case 1: HEAD points to a ref
headFile := filepath.Join(gitDir, "HEAD")
err = os.WriteFile(headFile, []byte("ref: refs/heads/main\n"), 0644)
if err != nil {
t.Fatal(err)
}
refFile := getGitRefFile(tmpDir)
expected := filepath.Join(gitDir, "refs", "heads", "main")
if refFile != expected {
t.Errorf("Expected %s, got %s", expected, refFile)
}
// Test case 2: HEAD contains a direct commit hash
err = os.WriteFile(headFile, []byte("abc123def456\n"), 0644)
if err != nil {
t.Fatal(err)
}
refFile = getGitRefFile(tmpDir)
if refFile != headFile {
t.Errorf("Expected %s, got %s", headFile, refFile)
}
}
func TestFileWatcherIntegration(t *testing.T) {
// This test requires being in a git repository
if getCurrentGitBranch(".") == "" {
t.Skip("Not in a git repository, skipping integration test")
}
// Test that the file watcher setup doesn't crash
tmpDir := t.TempDir()
gitDir := filepath.Join(tmpDir, ".git")
err := os.MkdirAll(gitDir, 0755)
if err != nil {
t.Fatal(err)
}
headFile := filepath.Join(gitDir, "HEAD")
err = os.WriteFile(headFile, []byte("ref: refs/heads/main\n"), 0644)
if err != nil {
t.Fatal(err)
}
// Create the refs directory and file
refsDir := filepath.Join(gitDir, "refs", "heads")
err = os.MkdirAll(refsDir, 0755)
if err != nil {
t.Fatal(err)
}
mainRef := filepath.Join(refsDir, "main")
err = os.WriteFile(mainRef, []byte("abc123def456\n"), 0644)
if err != nil {
t.Fatal(err)
}
// Test that we can create a watcher without crashing
// This is a basic smoke test
done := make(chan bool, 1)
go func() {
time.Sleep(100 * time.Millisecond)
done <- true
}()
select {
case <-done:
// Test passed - no crash
case <-time.After(1 * time.Second):
t.Error("Test timed out")
}
}

View File

@@ -71,12 +71,11 @@ type Model struct {
symbolsProvider completions.CompletionProvider
showCompletionDialog bool
leaderBinding *key.Binding
// isLeaderSequence bool
toastManager *toast.ToastManager
interruptKeyState InterruptKeyState
exitKeyState ExitKeyState
messagesRight bool
fileViewer fileviewer.Model
toastManager *toast.ToastManager
interruptKeyState InterruptKeyState
exitKeyState ExitKeyState
messagesRight bool
fileViewer fileviewer.Model
}
func (a Model) Init() tea.Cmd {
@@ -402,6 +401,58 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
a.app.Messages[messageIndex] = message
}
}
case opencode.EventListResponseEventMessagePartRemoved:
slog.Info("message part removed", "session", msg.Properties.SessionID, "message", msg.Properties.MessageID, "part", msg.Properties.PartID)
if msg.Properties.SessionID == a.app.Session.ID {
messageIndex := slices.IndexFunc(a.app.Messages, func(m app.Message) bool {
switch casted := m.Info.(type) {
case opencode.UserMessage:
return casted.ID == msg.Properties.MessageID
case opencode.AssistantMessage:
return casted.ID == msg.Properties.MessageID
}
return false
})
if messageIndex > -1 {
message := a.app.Messages[messageIndex]
partIndex := slices.IndexFunc(message.Parts, func(p opencode.PartUnion) bool {
switch casted := p.(type) {
case opencode.TextPart:
return casted.ID == msg.Properties.PartID
case opencode.FilePart:
return casted.ID == msg.Properties.PartID
case opencode.ToolPart:
return casted.ID == msg.Properties.PartID
case opencode.StepStartPart:
return casted.ID == msg.Properties.PartID
case opencode.StepFinishPart:
return casted.ID == msg.Properties.PartID
}
return false
})
if partIndex > -1 {
// Remove the part at partIndex
message.Parts = append(message.Parts[:partIndex], message.Parts[partIndex+1:]...)
a.app.Messages[messageIndex] = message
}
}
}
case opencode.EventListResponseEventMessageRemoved:
slog.Info("message removed", "session", msg.Properties.SessionID, "message", msg.Properties.MessageID)
if msg.Properties.SessionID == a.app.Session.ID {
messageIndex := slices.IndexFunc(a.app.Messages, func(m app.Message) bool {
switch casted := m.Info.(type) {
case opencode.UserMessage:
return casted.ID == msg.Properties.MessageID
case opencode.AssistantMessage:
return casted.ID == msg.Properties.MessageID
}
return false
})
if messageIndex > -1 {
a.app.Messages = append(a.app.Messages[:messageIndex], a.app.Messages[messageIndex+1:]...)
}
}
case opencode.EventListResponseEventMessageUpdated:
if msg.Properties.Info.SessionID == a.app.Session.ID {
matchIndex := slices.IndexFunc(a.app.Messages, func(m app.Message) bool {
@@ -598,6 +649,10 @@ func (a Model) View() string {
return mainLayout + "\n" + a.status.View()
}
func (a Model) Cleanup() {
a.status.Cleanup()
}
func (a Model) openFile(filepath string) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
response, err := a.app.Client.File.Read(

View File

@@ -270,7 +270,7 @@ func (m Model) GetContent() string {
return strings.Join(m.lines, "\n")
}
// calculateLine taking soft wraping into account, returns the total viewable
// calculateLine taking soft wrapping into account, returns the total viewable
// lines and the real-line index for the given yoffset.
func (m Model) calculateLine(yoffset int) (total, idx int) {
if !m.SoftWrap {

View File

@@ -1,4 +1,4 @@
configured_endpoints: 26
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-5748199af356c3243a46a466e73b5d0bab7eaa0c56895e1d0f903d637f61d0bb.yml
openapi_spec_hash: c04f6b6be54b05d9b1283c24e870163b
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-62d8fccba4eb8dc3a80434e0849eab3352e49fb96a718bb7b6d17ed8e582b716.yml
openapi_spec_hash: 4ff9376cf9634e91731e63fe482ea532
config_hash: 1ae82c93499b9f0b9ba828b8919f9cb3

View File

@@ -36,14 +36,14 @@ Methods:
Response Types:
- <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#Match">Match</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#Symbol">Symbol</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#FindTextResponse">FindTextResponse</a>
Methods:
- <code title="get /find/file">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Files">Files</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <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#FindFilesParams">FindFilesParams</a>) ([]<a href="https://pkg.go.dev/builtin#string">string</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find/symbol">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Symbols">Symbols</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <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#FindSymbolsParams">FindSymbolsParams</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#Symbol">Symbol</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Text">Text</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <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#FindTextParams">FindTextParams</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#Match">Match</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Text">Text</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <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#FindTextParams">FindTextParams</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#FindTextResponse">FindTextResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
# File

View File

@@ -146,11 +146,12 @@ func (r appTimeJSON) RawJSON() string {
}
type Mode struct {
Name string `json:"name,required"`
Tools map[string]bool `json:"tools,required"`
Model ModeModel `json:"model"`
Prompt string `json:"prompt"`
JSON modeJSON `json:"-"`
Name string `json:"name,required"`
Tools map[string]bool `json:"tools,required"`
Model ModeModel `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
JSON modeJSON `json:"-"`
}
// modeJSON contains the JSON metadata for the struct [Mode]
@@ -159,6 +160,7 @@ type modeJSON struct {
Tools apijson.Field
Model apijson.Field
Prompt apijson.Field
Temperature apijson.Field
raw string
ExtraFields map[string]apijson.Field
}

View File

@@ -43,6 +43,8 @@ func (r *ConfigService) Get(ctx context.Context, opts ...option.RequestOption) (
type Config struct {
// JSON schema reference for configuration validation
Schema string `json:"$schema"`
// Modes configuration, see https://opencode.ai/docs/modes
Agent ConfigAgent `json:"agent"`
// @deprecated Use 'share' field instead. Share newly created sessions
// automatically
Autoshare bool `json:"autoshare"`
@@ -81,6 +83,7 @@ type Config struct {
// configJSON contains the JSON metadata for the struct [Config]
type configJSON struct {
Schema apijson.Field
Agent apijson.Field
Autoshare apijson.Field
Autoupdate apijson.Field
DisabledProviders apijson.Field
@@ -108,6 +111,50 @@ func (r configJSON) RawJSON() string {
return r.raw
}
// Modes configuration, see https://opencode.ai/docs/modes
type ConfigAgent struct {
General ConfigAgentGeneral `json:"general"`
ExtraFields map[string]ConfigAgent `json:"-,extras"`
JSON configAgentJSON `json:"-"`
}
// configAgentJSON contains the JSON metadata for the struct [ConfigAgent]
type configAgentJSON struct {
General apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigAgent) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configAgentJSON) RawJSON() string {
return r.raw
}
type ConfigAgentGeneral struct {
Description string `json:"description,required"`
JSON configAgentGeneralJSON `json:"-"`
ModeConfig
}
// configAgentGeneralJSON contains the JSON metadata for the struct
// [ConfigAgentGeneral]
type configAgentGeneralJSON struct {
Description apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *ConfigAgentGeneral) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r configAgentGeneralJSON) RawJSON() string {
return r.raw
}
type ConfigExperimental struct {
Hook ConfigExperimentalHook `json:"hook"`
JSON configExperimentalJSON `json:"-"`
@@ -716,16 +763,20 @@ func (r McpRemoteConfigType) IsKnown() bool {
}
type ModeConfig struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
Tools map[string]bool `json:"tools"`
JSON modeConfigJSON `json:"-"`
Disable bool `json:"disable"`
Model string `json:"model"`
Prompt string `json:"prompt"`
Temperature float64 `json:"temperature"`
Tools map[string]bool `json:"tools"`
JSON modeConfigJSON `json:"-"`
}
// modeConfigJSON contains the JSON metadata for the struct [ModeConfig]
type modeConfigJSON struct {
Disable apijson.Field
Model apijson.Field
Prompt apijson.Field
Temperature apijson.Field
Tools apijson.Field
raw string
ExtraFields map[string]apijson.Field

View File

@@ -48,19 +48,19 @@ func (r *EventService) ListStreaming(ctx context.Context, opts ...option.Request
type EventListResponse struct {
// This field can have the runtime type of
// [EventListResponseEventLspClientDiagnosticsProperties],
// [EventListResponseEventPermissionUpdatedProperties],
// [EventListResponseEventFileEditedProperties],
// [EventListResponseEventInstallationUpdatedProperties],
// [EventListResponseEventLspClientDiagnosticsProperties],
// [EventListResponseEventMessageUpdatedProperties],
// [EventListResponseEventMessageRemovedProperties],
// [EventListResponseEventMessagePartUpdatedProperties],
// [EventListResponseEventMessagePartRemovedProperties],
// [EventListResponseEventStorageWriteProperties],
// [EventListResponseEventPermissionUpdatedProperties],
// [EventListResponseEventFileEditedProperties],
// [EventListResponseEventSessionUpdatedProperties],
// [EventListResponseEventSessionDeletedProperties],
// [EventListResponseEventSessionIdleProperties],
// [EventListResponseEventSessionErrorProperties],
// [EventListResponseEventSessionErrorProperties], [interface{}],
// [EventListResponseEventFileWatcherUpdatedProperties],
// [EventListResponseEventIdeInstalledProperties].
Properties interface{} `json:"properties,required"`
@@ -95,31 +95,32 @@ func (r *EventListResponse) UnmarshalJSON(data []byte) (err error) {
// specific types for more type safety.
//
// Possible runtime types of the union are
// [EventListResponseEventLspClientDiagnostics],
// [EventListResponseEventPermissionUpdated], [EventListResponseEventFileEdited],
// [EventListResponseEventInstallationUpdated],
// [EventListResponseEventLspClientDiagnostics],
// [EventListResponseEventMessageUpdated], [EventListResponseEventMessageRemoved],
// [EventListResponseEventMessagePartUpdated],
// [EventListResponseEventMessagePartRemoved],
// [EventListResponseEventStorageWrite], [EventListResponseEventSessionUpdated],
// [EventListResponseEventStorageWrite], [EventListResponseEventPermissionUpdated],
// [EventListResponseEventFileEdited], [EventListResponseEventSessionUpdated],
// [EventListResponseEventSessionDeleted], [EventListResponseEventSessionIdle],
// [EventListResponseEventSessionError],
// [EventListResponseEventSessionError], [EventListResponseEventServerConnected],
// [EventListResponseEventFileWatcherUpdated],
// [EventListResponseEventIdeInstalled].
func (r EventListResponse) AsUnion() EventListResponseUnion {
return r.union
}
// Union satisfied by [EventListResponseEventLspClientDiagnostics],
// [EventListResponseEventPermissionUpdated], [EventListResponseEventFileEdited],
// [EventListResponseEventInstallationUpdated],
// Union satisfied by [EventListResponseEventInstallationUpdated],
// [EventListResponseEventLspClientDiagnostics],
// [EventListResponseEventMessageUpdated], [EventListResponseEventMessageRemoved],
// [EventListResponseEventMessagePartUpdated],
// [EventListResponseEventMessagePartRemoved],
// [EventListResponseEventStorageWrite], [EventListResponseEventSessionUpdated],
// [EventListResponseEventStorageWrite], [EventListResponseEventPermissionUpdated],
// [EventListResponseEventFileEdited], [EventListResponseEventSessionUpdated],
// [EventListResponseEventSessionDeleted], [EventListResponseEventSessionIdle],
// [EventListResponseEventSessionError], [EventListResponseEventFileWatcherUpdated]
// or [EventListResponseEventIdeInstalled].
// [EventListResponseEventSessionError], [EventListResponseEventServerConnected],
// [EventListResponseEventFileWatcherUpdated] or
// [EventListResponseEventIdeInstalled].
type EventListResponseUnion interface {
implementsEventListResponse()
}
@@ -128,26 +129,16 @@ func init() {
apijson.RegisterUnion(
reflect.TypeOf((*EventListResponseUnion)(nil)).Elem(),
"type",
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventLspClientDiagnostics{}),
DiscriminatorValue: "lsp.client.diagnostics",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventPermissionUpdated{}),
DiscriminatorValue: "permission.updated",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventFileEdited{}),
DiscriminatorValue: "file.edited",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventInstallationUpdated{}),
DiscriminatorValue: "installation.updated",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventLspClientDiagnostics{}),
DiscriminatorValue: "lsp.client.diagnostics",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventMessageUpdated{}),
@@ -173,6 +164,16 @@ func init() {
Type: reflect.TypeOf(EventListResponseEventStorageWrite{}),
DiscriminatorValue: "storage.write",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventPermissionUpdated{}),
DiscriminatorValue: "permission.updated",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventFileEdited{}),
DiscriminatorValue: "file.edited",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventSessionUpdated{}),
@@ -193,6 +194,11 @@ func init() {
Type: reflect.TypeOf(EventListResponseEventSessionError{}),
DiscriminatorValue: "session.error",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventServerConnected{}),
DiscriminatorValue: "server.connected",
},
apijson.UnionVariant{
TypeFilter: gjson.JSON,
Type: reflect.TypeOf(EventListResponseEventFileWatcherUpdated{}),
@@ -206,6 +212,66 @@ func init() {
)
}
type EventListResponseEventInstallationUpdated struct {
Properties EventListResponseEventInstallationUpdatedProperties `json:"properties,required"`
Type EventListResponseEventInstallationUpdatedType `json:"type,required"`
JSON eventListResponseEventInstallationUpdatedJSON `json:"-"`
}
// eventListResponseEventInstallationUpdatedJSON contains the JSON metadata for the
// struct [EventListResponseEventInstallationUpdated]
type eventListResponseEventInstallationUpdatedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventInstallationUpdated) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventInstallationUpdatedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventInstallationUpdated) implementsEventListResponse() {}
type EventListResponseEventInstallationUpdatedProperties struct {
Version string `json:"version,required"`
JSON eventListResponseEventInstallationUpdatedPropertiesJSON `json:"-"`
}
// eventListResponseEventInstallationUpdatedPropertiesJSON contains the JSON
// metadata for the struct [EventListResponseEventInstallationUpdatedProperties]
type eventListResponseEventInstallationUpdatedPropertiesJSON struct {
Version apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventInstallationUpdatedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventInstallationUpdatedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventInstallationUpdatedType string
const (
EventListResponseEventInstallationUpdatedTypeInstallationUpdated EventListResponseEventInstallationUpdatedType = "installation.updated"
)
func (r EventListResponseEventInstallationUpdatedType) IsKnown() bool {
switch r {
case EventListResponseEventInstallationUpdatedTypeInstallationUpdated:
return true
}
return false
}
type EventListResponseEventLspClientDiagnostics struct {
Properties EventListResponseEventLspClientDiagnosticsProperties `json:"properties,required"`
Type EventListResponseEventLspClientDiagnosticsType `json:"type,required"`
@@ -268,215 +334,6 @@ func (r EventListResponseEventLspClientDiagnosticsType) IsKnown() bool {
return false
}
type EventListResponseEventPermissionUpdated struct {
Properties EventListResponseEventPermissionUpdatedProperties `json:"properties,required"`
Type EventListResponseEventPermissionUpdatedType `json:"type,required"`
JSON eventListResponseEventPermissionUpdatedJSON `json:"-"`
}
// eventListResponseEventPermissionUpdatedJSON contains the JSON metadata for the
// struct [EventListResponseEventPermissionUpdated]
type eventListResponseEventPermissionUpdatedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventPermissionUpdated) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventPermissionUpdatedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventPermissionUpdated) implementsEventListResponse() {}
type EventListResponseEventPermissionUpdatedProperties struct {
ID string `json:"id,required"`
Metadata map[string]interface{} `json:"metadata,required"`
SessionID string `json:"sessionID,required"`
Time EventListResponseEventPermissionUpdatedPropertiesTime `json:"time,required"`
Title string `json:"title,required"`
JSON eventListResponseEventPermissionUpdatedPropertiesJSON `json:"-"`
}
// eventListResponseEventPermissionUpdatedPropertiesJSON contains the JSON metadata
// for the struct [EventListResponseEventPermissionUpdatedProperties]
type eventListResponseEventPermissionUpdatedPropertiesJSON struct {
ID apijson.Field
Metadata apijson.Field
SessionID apijson.Field
Time apijson.Field
Title apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventPermissionUpdatedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventPermissionUpdatedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventPermissionUpdatedPropertiesTime struct {
Created float64 `json:"created,required"`
JSON eventListResponseEventPermissionUpdatedPropertiesTimeJSON `json:"-"`
}
// eventListResponseEventPermissionUpdatedPropertiesTimeJSON contains the JSON
// metadata for the struct [EventListResponseEventPermissionUpdatedPropertiesTime]
type eventListResponseEventPermissionUpdatedPropertiesTimeJSON struct {
Created apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventPermissionUpdatedPropertiesTime) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventPermissionUpdatedPropertiesTimeJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventPermissionUpdatedType string
const (
EventListResponseEventPermissionUpdatedTypePermissionUpdated EventListResponseEventPermissionUpdatedType = "permission.updated"
)
func (r EventListResponseEventPermissionUpdatedType) IsKnown() bool {
switch r {
case EventListResponseEventPermissionUpdatedTypePermissionUpdated:
return true
}
return false
}
type EventListResponseEventFileEdited struct {
Properties EventListResponseEventFileEditedProperties `json:"properties,required"`
Type EventListResponseEventFileEditedType `json:"type,required"`
JSON eventListResponseEventFileEditedJSON `json:"-"`
}
// eventListResponseEventFileEditedJSON contains the JSON metadata for the struct
// [EventListResponseEventFileEdited]
type eventListResponseEventFileEditedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEdited) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventFileEdited) implementsEventListResponse() {}
type EventListResponseEventFileEditedProperties struct {
File string `json:"file,required"`
JSON eventListResponseEventFileEditedPropertiesJSON `json:"-"`
}
// eventListResponseEventFileEditedPropertiesJSON contains the JSON metadata for
// the struct [EventListResponseEventFileEditedProperties]
type eventListResponseEventFileEditedPropertiesJSON struct {
File apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEditedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventFileEditedType string
const (
EventListResponseEventFileEditedTypeFileEdited EventListResponseEventFileEditedType = "file.edited"
)
func (r EventListResponseEventFileEditedType) IsKnown() bool {
switch r {
case EventListResponseEventFileEditedTypeFileEdited:
return true
}
return false
}
type EventListResponseEventInstallationUpdated struct {
Properties EventListResponseEventInstallationUpdatedProperties `json:"properties,required"`
Type EventListResponseEventInstallationUpdatedType `json:"type,required"`
JSON eventListResponseEventInstallationUpdatedJSON `json:"-"`
}
// eventListResponseEventInstallationUpdatedJSON contains the JSON metadata for the
// struct [EventListResponseEventInstallationUpdated]
type eventListResponseEventInstallationUpdatedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventInstallationUpdated) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventInstallationUpdatedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventInstallationUpdated) implementsEventListResponse() {}
type EventListResponseEventInstallationUpdatedProperties struct {
Version string `json:"version,required"`
JSON eventListResponseEventInstallationUpdatedPropertiesJSON `json:"-"`
}
// eventListResponseEventInstallationUpdatedPropertiesJSON contains the JSON
// metadata for the struct [EventListResponseEventInstallationUpdatedProperties]
type eventListResponseEventInstallationUpdatedPropertiesJSON struct {
Version apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventInstallationUpdatedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventInstallationUpdatedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventInstallationUpdatedType string
const (
EventListResponseEventInstallationUpdatedTypeInstallationUpdated EventListResponseEventInstallationUpdatedType = "installation.updated"
)
func (r EventListResponseEventInstallationUpdatedType) IsKnown() bool {
switch r {
case EventListResponseEventInstallationUpdatedTypeInstallationUpdated:
return true
}
return false
}
type EventListResponseEventMessageUpdated struct {
Properties EventListResponseEventMessageUpdatedProperties `json:"properties,required"`
Type EventListResponseEventMessageUpdatedType `json:"type,required"`
@@ -687,6 +544,7 @@ func (r EventListResponseEventMessagePartRemoved) implementsEventListResponse()
type EventListResponseEventMessagePartRemovedProperties struct {
MessageID string `json:"messageID,required"`
PartID string `json:"partID,required"`
SessionID string `json:"sessionID,required"`
JSON eventListResponseEventMessagePartRemovedPropertiesJSON `json:"-"`
}
@@ -695,6 +553,7 @@ type EventListResponseEventMessagePartRemovedProperties struct {
type eventListResponseEventMessagePartRemovedPropertiesJSON struct {
MessageID apijson.Field
PartID apijson.Field
SessionID apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
@@ -783,6 +642,155 @@ func (r EventListResponseEventStorageWriteType) IsKnown() bool {
return false
}
type EventListResponseEventPermissionUpdated struct {
Properties EventListResponseEventPermissionUpdatedProperties `json:"properties,required"`
Type EventListResponseEventPermissionUpdatedType `json:"type,required"`
JSON eventListResponseEventPermissionUpdatedJSON `json:"-"`
}
// eventListResponseEventPermissionUpdatedJSON contains the JSON metadata for the
// struct [EventListResponseEventPermissionUpdated]
type eventListResponseEventPermissionUpdatedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventPermissionUpdated) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventPermissionUpdatedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventPermissionUpdated) implementsEventListResponse() {}
type EventListResponseEventPermissionUpdatedProperties struct {
ID string `json:"id,required"`
Metadata map[string]interface{} `json:"metadata,required"`
SessionID string `json:"sessionID,required"`
Time EventListResponseEventPermissionUpdatedPropertiesTime `json:"time,required"`
Title string `json:"title,required"`
JSON eventListResponseEventPermissionUpdatedPropertiesJSON `json:"-"`
}
// eventListResponseEventPermissionUpdatedPropertiesJSON contains the JSON metadata
// for the struct [EventListResponseEventPermissionUpdatedProperties]
type eventListResponseEventPermissionUpdatedPropertiesJSON struct {
ID apijson.Field
Metadata apijson.Field
SessionID apijson.Field
Time apijson.Field
Title apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventPermissionUpdatedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventPermissionUpdatedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventPermissionUpdatedPropertiesTime struct {
Created float64 `json:"created,required"`
JSON eventListResponseEventPermissionUpdatedPropertiesTimeJSON `json:"-"`
}
// eventListResponseEventPermissionUpdatedPropertiesTimeJSON contains the JSON
// metadata for the struct [EventListResponseEventPermissionUpdatedPropertiesTime]
type eventListResponseEventPermissionUpdatedPropertiesTimeJSON struct {
Created apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventPermissionUpdatedPropertiesTime) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventPermissionUpdatedPropertiesTimeJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventPermissionUpdatedType string
const (
EventListResponseEventPermissionUpdatedTypePermissionUpdated EventListResponseEventPermissionUpdatedType = "permission.updated"
)
func (r EventListResponseEventPermissionUpdatedType) IsKnown() bool {
switch r {
case EventListResponseEventPermissionUpdatedTypePermissionUpdated:
return true
}
return false
}
type EventListResponseEventFileEdited struct {
Properties EventListResponseEventFileEditedProperties `json:"properties,required"`
Type EventListResponseEventFileEditedType `json:"type,required"`
JSON eventListResponseEventFileEditedJSON `json:"-"`
}
// eventListResponseEventFileEditedJSON contains the JSON metadata for the struct
// [EventListResponseEventFileEdited]
type eventListResponseEventFileEditedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEdited) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventFileEdited) implementsEventListResponse() {}
type EventListResponseEventFileEditedProperties struct {
File string `json:"file,required"`
JSON eventListResponseEventFileEditedPropertiesJSON `json:"-"`
}
// eventListResponseEventFileEditedPropertiesJSON contains the JSON metadata for
// the struct [EventListResponseEventFileEditedProperties]
type eventListResponseEventFileEditedPropertiesJSON struct {
File apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventFileEditedProperties) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventFileEditedPropertiesJSON) RawJSON() string {
return r.raw
}
type EventListResponseEventFileEditedType string
const (
EventListResponseEventFileEditedTypeFileEdited EventListResponseEventFileEditedType = "file.edited"
)
func (r EventListResponseEventFileEditedType) IsKnown() bool {
switch r {
case EventListResponseEventFileEditedTypeFileEdited:
return true
}
return false
}
type EventListResponseEventSessionUpdated struct {
Properties EventListResponseEventSessionUpdatedProperties `json:"properties,required"`
Type EventListResponseEventSessionUpdatedType `json:"type,required"`
@@ -1159,6 +1167,45 @@ func (r EventListResponseEventSessionErrorType) IsKnown() bool {
return false
}
type EventListResponseEventServerConnected struct {
Properties interface{} `json:"properties,required"`
Type EventListResponseEventServerConnectedType `json:"type,required"`
JSON eventListResponseEventServerConnectedJSON `json:"-"`
}
// eventListResponseEventServerConnectedJSON contains the JSON metadata for the
// struct [EventListResponseEventServerConnected]
type eventListResponseEventServerConnectedJSON struct {
Properties apijson.Field
Type apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *EventListResponseEventServerConnected) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r eventListResponseEventServerConnectedJSON) RawJSON() string {
return r.raw
}
func (r EventListResponseEventServerConnected) implementsEventListResponse() {}
type EventListResponseEventServerConnectedType string
const (
EventListResponseEventServerConnectedTypeServerConnected EventListResponseEventServerConnectedType = "server.connected"
)
func (r EventListResponseEventServerConnectedType) IsKnown() bool {
switch r {
case EventListResponseEventServerConnectedTypeServerConnected:
return true
}
return false
}
type EventListResponseEventFileWatcherUpdated struct {
Properties EventListResponseEventFileWatcherUpdatedProperties `json:"properties,required"`
Type EventListResponseEventFileWatcherUpdatedType `json:"type,required"`
@@ -1299,26 +1346,27 @@ func (r EventListResponseEventIdeInstalledType) IsKnown() bool {
type EventListResponseType string
const (
EventListResponseTypeLspClientDiagnostics EventListResponseType = "lsp.client.diagnostics"
EventListResponseTypePermissionUpdated EventListResponseType = "permission.updated"
EventListResponseTypeFileEdited EventListResponseType = "file.edited"
EventListResponseTypeInstallationUpdated EventListResponseType = "installation.updated"
EventListResponseTypeLspClientDiagnostics EventListResponseType = "lsp.client.diagnostics"
EventListResponseTypeMessageUpdated EventListResponseType = "message.updated"
EventListResponseTypeMessageRemoved EventListResponseType = "message.removed"
EventListResponseTypeMessagePartUpdated EventListResponseType = "message.part.updated"
EventListResponseTypeMessagePartRemoved EventListResponseType = "message.part.removed"
EventListResponseTypeStorageWrite EventListResponseType = "storage.write"
EventListResponseTypePermissionUpdated EventListResponseType = "permission.updated"
EventListResponseTypeFileEdited EventListResponseType = "file.edited"
EventListResponseTypeSessionUpdated EventListResponseType = "session.updated"
EventListResponseTypeSessionDeleted EventListResponseType = "session.deleted"
EventListResponseTypeSessionIdle EventListResponseType = "session.idle"
EventListResponseTypeSessionError EventListResponseType = "session.error"
EventListResponseTypeServerConnected EventListResponseType = "server.connected"
EventListResponseTypeFileWatcherUpdated EventListResponseType = "file.watcher.updated"
EventListResponseTypeIdeInstalled EventListResponseType = "ide.installed"
)
func (r EventListResponseType) IsKnown() bool {
switch r {
case EventListResponseTypeLspClientDiagnostics, EventListResponseTypePermissionUpdated, EventListResponseTypeFileEdited, EventListResponseTypeInstallationUpdated, EventListResponseTypeMessageUpdated, EventListResponseTypeMessageRemoved, EventListResponseTypeMessagePartUpdated, EventListResponseTypeMessagePartRemoved, EventListResponseTypeStorageWrite, EventListResponseTypeSessionUpdated, EventListResponseTypeSessionDeleted, EventListResponseTypeSessionIdle, EventListResponseTypeSessionError, EventListResponseTypeFileWatcherUpdated, EventListResponseTypeIdeInstalled:
case EventListResponseTypeInstallationUpdated, EventListResponseTypeLspClientDiagnostics, EventListResponseTypeMessageUpdated, EventListResponseTypeMessageRemoved, EventListResponseTypeMessagePartUpdated, EventListResponseTypeMessagePartRemoved, EventListResponseTypeStorageWrite, EventListResponseTypePermissionUpdated, EventListResponseTypeFileEdited, EventListResponseTypeSessionUpdated, EventListResponseTypeSessionDeleted, EventListResponseTypeSessionIdle, EventListResponseTypeSessionError, EventListResponseTypeServerConnected, EventListResponseTypeFileWatcherUpdated, EventListResponseTypeIdeInstalled:
return true
}
return false

View File

@@ -50,126 +50,13 @@ func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts
}
// Find text in files
func (r *FindService) Text(ctx context.Context, query FindTextParams, opts ...option.RequestOption) (res *[]Match, err error) {
func (r *FindService) Text(ctx context.Context, query FindTextParams, opts ...option.RequestOption) (res *[]FindTextResponse, err error) {
opts = append(r.Options[:], opts...)
path := "find"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return
}
type Match struct {
AbsoluteOffset float64 `json:"absolute_offset,required"`
LineNumber float64 `json:"line_number,required"`
Lines MatchLines `json:"lines,required"`
Path MatchPath `json:"path,required"`
Submatches []MatchSubmatch `json:"submatches,required"`
JSON matchJSON `json:"-"`
}
// matchJSON contains the JSON metadata for the struct [Match]
type matchJSON struct {
AbsoluteOffset apijson.Field
LineNumber apijson.Field
Lines apijson.Field
Path apijson.Field
Submatches apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *Match) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r matchJSON) RawJSON() string {
return r.raw
}
type MatchLines struct {
Text string `json:"text,required"`
JSON matchLinesJSON `json:"-"`
}
// matchLinesJSON contains the JSON metadata for the struct [MatchLines]
type matchLinesJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *MatchLines) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r matchLinesJSON) RawJSON() string {
return r.raw
}
type MatchPath struct {
Text string `json:"text,required"`
JSON matchPathJSON `json:"-"`
}
// matchPathJSON contains the JSON metadata for the struct [MatchPath]
type matchPathJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *MatchPath) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r matchPathJSON) RawJSON() string {
return r.raw
}
type MatchSubmatch struct {
End float64 `json:"end,required"`
Match MatchSubmatchesMatch `json:"match,required"`
Start float64 `json:"start,required"`
JSON matchSubmatchJSON `json:"-"`
}
// matchSubmatchJSON contains the JSON metadata for the struct [MatchSubmatch]
type matchSubmatchJSON struct {
End apijson.Field
Match apijson.Field
Start apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *MatchSubmatch) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r matchSubmatchJSON) RawJSON() string {
return r.raw
}
type MatchSubmatchesMatch struct {
Text string `json:"text,required"`
JSON matchSubmatchesMatchJSON `json:"-"`
}
// matchSubmatchesMatchJSON contains the JSON metadata for the struct
// [MatchSubmatchesMatch]
type matchSubmatchesMatchJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *MatchSubmatchesMatch) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r matchSubmatchesMatchJSON) RawJSON() string {
return r.raw
}
type Symbol struct {
Kind float64 `json:"kind,required"`
Location SymbolLocation `json:"location,required"`
@@ -285,6 +172,123 @@ func (r symbolLocationRangeStartJSON) RawJSON() string {
return r.raw
}
type FindTextResponse struct {
AbsoluteOffset float64 `json:"absolute_offset,required"`
LineNumber float64 `json:"line_number,required"`
Lines FindTextResponseLines `json:"lines,required"`
Path FindTextResponsePath `json:"path,required"`
Submatches []FindTextResponseSubmatch `json:"submatches,required"`
JSON findTextResponseJSON `json:"-"`
}
// findTextResponseJSON contains the JSON metadata for the struct
// [FindTextResponse]
type findTextResponseJSON struct {
AbsoluteOffset apijson.Field
LineNumber apijson.Field
Lines apijson.Field
Path apijson.Field
Submatches apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponse) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseJSON) RawJSON() string {
return r.raw
}
type FindTextResponseLines struct {
Text string `json:"text,required"`
JSON findTextResponseLinesJSON `json:"-"`
}
// findTextResponseLinesJSON contains the JSON metadata for the struct
// [FindTextResponseLines]
type findTextResponseLinesJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponseLines) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseLinesJSON) RawJSON() string {
return r.raw
}
type FindTextResponsePath struct {
Text string `json:"text,required"`
JSON findTextResponsePathJSON `json:"-"`
}
// findTextResponsePathJSON contains the JSON metadata for the struct
// [FindTextResponsePath]
type findTextResponsePathJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponsePath) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponsePathJSON) RawJSON() string {
return r.raw
}
type FindTextResponseSubmatch struct {
End float64 `json:"end,required"`
Match FindTextResponseSubmatchesMatch `json:"match,required"`
Start float64 `json:"start,required"`
JSON findTextResponseSubmatchJSON `json:"-"`
}
// findTextResponseSubmatchJSON contains the JSON metadata for the struct
// [FindTextResponseSubmatch]
type findTextResponseSubmatchJSON struct {
End apijson.Field
Match apijson.Field
Start apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponseSubmatch) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseSubmatchJSON) RawJSON() string {
return r.raw
}
type FindTextResponseSubmatchesMatch struct {
Text string `json:"text,required"`
JSON findTextResponseSubmatchesMatchJSON `json:"-"`
}
// findTextResponseSubmatchesMatchJSON contains the JSON metadata for the struct
// [FindTextResponseSubmatchesMatch]
type findTextResponseSubmatchesMatchJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponseSubmatchesMatch) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseSubmatchesMatchJSON) RawJSON() string {
return r.raw
}
type FindFilesParams struct {
Query param.Field[string] `query:"query,required"`
}

View File

@@ -1073,6 +1073,7 @@ func (r sessionTimeJSON) RawJSON() string {
type SessionRevert struct {
MessageID string `json:"messageID,required"`
Diff string `json:"diff"`
PartID string `json:"partID"`
Snapshot string `json:"snapshot"`
JSON sessionRevertJSON `json:"-"`
@@ -1081,6 +1082,7 @@ type SessionRevert struct {
// sessionRevertJSON contains the JSON metadata for the struct [SessionRevert]
type sessionRevertJSON struct {
MessageID apijson.Field
Diff apijson.Field
PartID apijson.Field
Snapshot apijson.Field
raw string
@@ -2039,6 +2041,7 @@ type SessionChatParams struct {
ProviderID param.Field[string] `json:"providerID,required"`
MessageID param.Field[string] `json:"messageID"`
Mode param.Field[string] `json:"mode"`
System param.Field[string] `json:"system"`
Tools param.Field[map[string]bool] `json:"tools"`
}

View File

@@ -131,6 +131,7 @@ func TestSessionChatWithOptionalParams(t *testing.T) {
ProviderID: opencode.F("providerID"),
MessageID: opencode.F("msg"),
Mode: opencode.F("mode"),
System: opencode.F("system"),
Tools: opencode.F(map[string]bool{
"foo": true,
}),

View File

@@ -68,10 +68,12 @@ export default defineConfig({
"docs/modes",
"docs/agents",
"docs/rules",
"docs/github",
"docs/config",
"docs/models",
"docs/themes",
"docs/keybinds",
// "docs/providers",
"docs/enterprise",
"docs/mcp-servers",
"docs/troubleshooting",

View File

@@ -342,6 +342,7 @@ export default function Share(props: {
msg.parts.filter((x, index) => {
if (x.type === "step-start" && index > 0) return false
if (x.type === "snapshot") return false
if (x.type === "patch") return false
if (x.type === "step-finish") return false
if (x.type === "text" && x.synthetic === true) return false
if (x.type === "tool" && x.tool === "todoread") return false

View File

@@ -34,6 +34,17 @@ This is also safe to be checked into Git and uses the same schema as the global
---
### Custom config file
You can specify a custom config file using the `OPENCODE_CONFIG` environment variable. This takes precedence over the global and project configs.
```bash
export OPENCODE_CONFIG=/path/to/my/custom-config.json
opencode run "Hello world"
```
---
## Schema
The config file has a schema that's defined in [**`opencode.ai/config.json`**](https://opencode.ai/config.json).
@@ -63,16 +74,19 @@ opencode comes with two built-in modes: _build_, the default with all tools enab
### Models
You can configure the providers and models you want to use in your opencode config through the `provider` and `model` options.
You can configure the providers and models you want to use in your opencode config through the `provider`, `model` and `small_model` options.
```json title="opencode.json"
{
"$schema": "https://opencode.ai/config.json",
"provider": {},
"model": ""
"model": "anthropic/claude-sonnet-4-20250514",
"small_model": "anthropic/claude-3-5-haiku-20241022"
}
```
The `small_model` option configures a separate model for lightweight tasks like summarization and title generation. By default, opencode tries to use a cheaper model if one is available from your provider, otherwise it falls back to your main model.
You can also configure [local models](/docs/models#local). [Learn more](/docs/models).
---

View File

@@ -0,0 +1,100 @@
---
title: GitHub
description: Use opencode in GitHub Issues and Pull-Requests
---
opencode integrates directly into your GitHub workflow. Mention `/opencode` or `/oc` in your comment, and opencode will execute tasks within your GitHub Actions runner.
---
## Features
- **Triage Issues**: Ask opencode to look into an issue and explain it to you.
- **Fix and Implement**: Ask opencode to fix an issue or implement a feature. And it will work in a new branch and submits a PR with all the changes.
- **Secure**: opencode runs inside your GitHub's runners.
---
## Installation
Run the following command in the terminal from your GitHub repo:
```bash
opencode github install
```
This will walk you through installing the GitHub app, creating the workflow, and setting up secrets.
---
### Manual Setup
1. Install the GitHub app https://github.com/apps/opencode-agent. Make sure it is installed on the target repository.
2. Add the following workflow file to `.github/workflows/opencode.yml` in your repo. Set the appropriate `model` and required API keys in `env`.
```yml
name: opencode
on:
issue_comment:
types: [created]
jobs:
opencode:
if: |
contains(github.event.comment.body, '/oc') ||
contains(github.event.comment.body, '/opencode')
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run opencode
uses: sst/opencode/github@latest
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
with:
model: anthropic/claude-sonnet-4-20250514
# share: true
```
3. Store the API keys in secrets. In your organization or project **settings**, expand **Secrets and variables** on the left and select **Actions**. Add the required API keys.
---
## Configuration
- `model`: The model used by opencode. Takes the format of `provider/model` (**required**)
- `share`: Share the session. Sessions are shared by default for public repos.
---
## Usage Examples
- Explain an issue
Leave the following comment on a GitHub issue. `opencode` will read the entire thread, including all comments, and reply with a clear explanation.
```
/opencode explain this issue
```
- Fix an issue
Leave the following comment on a GitHub issue. opencode will create a new branch, implement the changes, and open a PR with the changes.
```
/opencode fix this
```
- Review PRs and make changes
Leave the following comment on a GitHub PR. opencode will implement the requested change and commit it to the same PR.
```
Delete the attachment from S3 when the note is removed /oc
```

View File

@@ -1,6 +1,6 @@
---
title: IDE
description: Using opencode with VS Code, Cursor, and other IDEs
description: The opencode extension for VS Code, Cursor, and other IDEs
---
opencode integrates with VS Code, Cursor, or any IDE that supports a terminal. Just run `opencode` in the terminal to get started.
@@ -9,7 +9,8 @@ opencode integrates with VS Code, Cursor, or any IDE that supports a terminal. J
## Usage
- **Quick Launch**: Open opencode with `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux), or click the opencode button in the UI.
- **Quick Launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open opencode in a split terminal view, or focus an existing terminal session if one is already running.
- **New Session**: Use `Cmd+Shift+Esc` (Mac) or `Ctrl+Shift+Esc` (Windows/Linux) to start a new opencode terminal session, even if one is already open. You can also click the opencode button in the UI.
- **Context Awareness**: Automatically share your current selection or tab with opencode.
- **File Reference Shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references. For example, `@File#L37-42`.

View File

@@ -0,0 +1,7 @@
---
title: Providers
description: Using any LLM provider in opencode.
---
opencode uses the [AI SDK](https://ai-sdk.dev/) and [Models.dev](https://models.dev) to support for **75+ LLM providers** and it supports running local models.

View File

@@ -1,16 +1,17 @@
# opencode VS Code Extension
A VS Code extension that integrates [opencode](https://opencode.ai) directly into your development environment.
A Visual Studio Code extension that integrates [opencode](https://opencode.ai) directly into your development workflow.
## Prerequisites
This extension requires [opencode](https://opencode.ai) to be installed on your system. Visit [opencode.ai](https://opencode.ai) for installation instructions.
This extension requires the [opencode CLI](https://opencode.ai) to be installed on your system. Visit [opencode.ai](https://opencode.ai) for installation instructions.
## Features
- **Cmd+Escape**: Launch opencode in a split terminal view
- **Alt+Cmd+K**: Send selected code to opencode's prompt
- **Tab awareness**: opencode automatically detects which files you have open
- **Quick Launch**: Use `Cmd+Esc` (Mac) or `Ctrl+Esc` (Windows/Linux) to open opencode in a split terminal view, or focus an existing terminal session if one is already running.
- **New Session**: Use `Cmd+Shift+Esc` (Mac) or `Ctrl+Shift+Esc` (Windows/Linux) to start a new opencode terminal session, even if one is already open. You can also click the opencode button in the UI.
- **Context Awareness**: Automatically share your current selection or tab with opencode.
- **File Reference Shortcuts**: Use `Cmd+Option+K` (Mac) or `Alt+Ctrl+K` (Linux/Windows) to insert file references. For example, `@File#L37-42`.
## Support

View File

@@ -26,7 +26,15 @@
"commands": [
{
"command": "opencode.openTerminal",
"title": "Open Terminal with Opencode",
"title": "Open opencode",
"icon": {
"light": "images/button-dark.svg",
"dark": "images/button-light.svg"
}
},
{
"command": "opencode.openNewTerminal",
"title": "Open opencode in new tab",
"icon": {
"light": "images/button-dark.svg",
"dark": "images/button-light.svg"
@@ -40,8 +48,7 @@
"menus": {
"editor/title": [
{
"command": "opencode.openTerminal",
"when": "editorTextFocus",
"command": "opencode.openNewTerminal",
"group": "navigation"
}
]
@@ -55,6 +62,14 @@
"win": "ctrl+escape",
"linux": "ctrl+escape"
},
{
"command": "opencode.openNewTerminal",
"title": "Run opencode",
"key": "cmd+shift+escape",
"mac": "cmd+shift+escape",
"win": "ctrl+shift+escape",
"linux": "ctrl+shift+escape"
},
{
"command": "opencode.addFilepathToTerminal",
"title": "opencode: Insert At-Mentioned",

View File

@@ -3,11 +3,42 @@ export function deactivate() {}
import * as vscode from "vscode"
export function activate(context: vscode.ExtensionContext) {
const TERMINAL_NAME = "opencode"
const TERMINAL_NAME = "opencode"
export function activate(context: vscode.ExtensionContext) {
let openNewTerminalDisposable = vscode.commands.registerCommand("opencode.openNewTerminal", async () => {
await openTerminal()
})
// Register command to open terminal in split screen and run opencode
let openTerminalDisposable = vscode.commands.registerCommand("opencode.openTerminal", async () => {
// An opencode terminal already exists => focus it
const existingTerminal = vscode.window.terminals.find((t) => t.name === TERMINAL_NAME)
if (existingTerminal) {
existingTerminal.show()
return
}
await openTerminal()
})
let addFilepathDisposable = vscode.commands.registerCommand("opencode.addFilepathToTerminal", async () => {
const fileRef = getActiveFile()
if (!fileRef) return
const terminal = vscode.window.activeTerminal
if (!terminal) return
if (terminal.name === TERMINAL_NAME) {
// @ts-ignore
const port = terminal.creationOptions.env?.["_EXTENSION_OPENCODE_PORT"]
port ? await appendPrompt(parseInt(port), fileRef) : terminal.sendText(fileRef)
terminal.show()
}
})
context.subscriptions.push(openTerminalDisposable, addFilepathDisposable)
async function openTerminal() {
// Create a new terminal in split screen
const port = Math.floor(Math.random() * (65535 - 16384 + 1)) + 16384
const terminal = vscode.window.createTerminal({
@@ -50,64 +81,46 @@ export function activate(context: vscode.ExtensionContext) {
await appendPrompt(port, `In ${fileRef}`)
terminal.show()
}
})
// Register command to add filepath to terminal
let addFilepathDisposable = vscode.commands.registerCommand("opencode.addFilepathToTerminal", async () => {
const fileRef = getActiveFile()
if (!fileRef) return
const terminal = vscode.window.activeTerminal
if (!terminal) return
if (terminal.name === TERMINAL_NAME) {
// @ts-ignore
const port = terminal.creationOptions.env?.["_EXTENSION_OPENCODE_PORT"]
port ? await appendPrompt(parseInt(port), fileRef) : terminal.sendText(fileRef)
terminal.show()
}
})
context.subscriptions.push(openTerminalDisposable, addFilepathDisposable)
}
async function appendPrompt(port: number, text: string) {
await fetch(`http://localhost:${port}/tui/append-prompt`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text }),
})
}
function getActiveFile() {
const activeEditor = vscode.window.activeTextEditor
if (!activeEditor) return
const document = activeEditor.document
const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri)
if (!workspaceFolder) return
// Get the relative path from workspace root
const relativePath = vscode.workspace.asRelativePath(document.uri)
let filepathWithAt = `@${relativePath}`
// Check if there's a selection and add line numbers
const selection = activeEditor.selection
if (!selection.isEmpty) {
// Convert to 1-based line numbers
const startLine = selection.start.line + 1
const endLine = selection.end.line + 1
if (startLine === endLine) {
// Single line selection
filepathWithAt += `#L${startLine}`
} else {
// Multi-line selection
filepathWithAt += `#L${startLine}-${endLine}`
}
}
return filepathWithAt
async function appendPrompt(port: number, text: string) {
await fetch(`http://localhost:${port}/tui/append-prompt`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text }),
})
}
function getActiveFile() {
const activeEditor = vscode.window.activeTextEditor
if (!activeEditor) return
const document = activeEditor.document
const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri)
if (!workspaceFolder) return
// Get the relative path from workspace root
const relativePath = vscode.workspace.asRelativePath(document.uri)
let filepathWithAt = `@${relativePath}`
// Check if there's a selection and add line numbers
const selection = activeEditor.selection
if (!selection.isEmpty) {
// Convert to 1-based line numbers
const startLine = selection.start.line + 1
const endLine = selection.end.line + 1
if (startLine === endLine) {
// Single line selection
filepathWithAt += `#L${startLine}`
} else {
// Multi-line selection
filepathWithAt += `#L${startLine}-${endLine}`
}
}
return filepathWithAt
}
}

9
sdks/vscode/sst-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* This file is auto-generated by SST. Do not edit. */
/* tslint:disable */
/* eslint-disable */
/* deno-fmt-ignore-file */
/// <reference path="../../sst-env.d.ts" />
import "sst"
export {}