Compare commits

..
80 Commits
Author SHA1 Message Date
opencode 502e85b903 release: v1.0.107
Update Nix Hashes / update (push) Has been cancelled
2025-11-24 07:06:41 +00:00
Aiden ClineandGitHub ac1e2bfd49 bump copilot plugin, give better error message for copilot (#4678) 2025-11-24 00:40:15 -06:00
Aiden Cline b9b071c744 fix: fatal: undefined is not an object (evaluating 'color.buffer') 2025-11-23 23:56:15 -06:00
GitHub Action 83186b6fed chore: format code 2025-11-24 04:55:13 +00:00
a3a239967f nix: bundle js dist with bun and patch tree-sitter wasm paths (#4644)
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
Co-authored-by: Github Action <action@github.com>
2025-11-23 22:54:29 -06:00
b4fd4bb257 fix: add explicit fallback model and prevent direct opencode provider calls (#4653)
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2025-11-23 22:51:15 -06:00
GitHub Action eb009d5959 chore: format code 2025-11-23 20:59:37 +00:00
Frank 4a81bd0f50 wip: zen 2025-11-23 15:58:55 -05:00
Frank bbc9142fc5 wip: zen 2025-11-23 15:21:47 -05:00
Aiden Cline 7413c2715c tweak: slight improvements to title gen 2025-11-23 14:04:39 -06:00
Dax Raad 7579c3bb15 ci: remove log 2025-11-23 15:00:29 -05:00
Dax Raad 24683058fd ci: ignore 2025-11-23 14:56:24 -05:00
Dax Raad bf81e3108c ci: ignore 2025-11-23 14:56:24 -05:00
Dax Raad 5ade90416e ci: ignore 2025-11-23 14:44:05 -05:00
GitHub Action 8f2a8086c0 chore: format code 2025-11-23 19:37:19 +00:00
Dax Raad 38b70f7877 ci: secret 2025-11-23 14:36:36 -05:00
Dax Raadandopencode 5e112a17a5 token 2025-11-23 19:35:39 +00:00
Dax Raadandopencode 59a3e7e3cc ci: ignore 2025-11-23 19:35:39 +00:00
Github Actionandopencode 2c93f065cb Update Nix flake.lock and hashes 2025-11-23 19:35:39 +00:00
opencode 488d33c1ed release: v1.0.106
Update Nix Hashes / update (push) Has been cancelled
2025-11-23 19:35:38 +00:00
Dax Raad de4660ac12 ci: ignore 2025-11-23 14:28:10 -05:00
Aiden Cline 27ae341684 fix bash tool wsl 2025-11-23 12:29:15 -06:00
Github Action 25b3846694 Update Nix flake.lock and hashes 2025-11-23 17:57:34 +00:00
Dax Raad 8e2f9f6544 ci: stuff 2025-11-23 12:55:33 -05:00
Github Action 76b5870f89 Update Nix flake.lock and hashes 2025-11-23 17:45:24 +00:00
Dax Raad 604891e793 ci: stuff 2025-11-23 12:43:23 -05:00
Dax Raad 5814df7eaa sync 2025-11-23 12:43:23 -05:00
Aiden Cline 2509d03f42 tweak: fix bool 2025-11-23 11:43:09 -06:00
Github Action a256df9823 Update Nix flake.lock and hashes 2025-11-23 17:09:33 +00:00
Dax Raad af96ec5a30 ignore: update @solidjs/start dependency and fix console redirect handling
Updates the @solidjs/start dependency to latest version and removes deprecated getResponseHeaders usage from auth callback. Also adds error handling for workspace ID lookup to prevent redirect failures.
2025-11-23 12:07:28 -05:00
GitHub Action 55df80b80e ignore: update download stats 2025-11-23 2025-11-23 12:04:01 +00:00
7d11986a0a feature: optional selectedListItemText element in themes and luminance-based fallback to solve 4369 (#4572)
Co-authored-by: knanao <nao.7ken@gmail.com>
Co-authored-by: knanao <k@knanao.com>
2025-11-23 01:51:07 -06:00
Aiden Cline d75d90c53e ci: fix action 2025-11-23 01:36:45 -06:00
Tyler LimbachandGitHub 35fead2eca fix: make tui session text respect theme fg (#4618) (#4620) 2025-11-23 01:34:31 -06:00
Github Action 9bb2efd3ef Update Nix flake.lock and hashes 2025-11-23 07:31:17 +00:00
Aiden ClineandGitHub 30ffcaa667 tweak: start bundling in some ai-sdk packages (#4649) 2025-11-23 01:29:20 -06:00
ba11455786 fix: prevent permission shortcuts when ctrl/meta pressed (#4631)
Co-authored-by: terakael <terakael@gmail.com>
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
2025-11-22 23:58:10 -06:00
Dax Raad d69ba27f84 fix suspense 2025-11-23 00:16:06 -05:00
Dax Raad 448b72d046 fix logout 2025-11-23 00:12:58 -05:00
Dax Raad d96d89bcb8 fix logout 2025-11-22 23:59:50 -05:00
Dax Raad 7a013d4f40 fixed 2025-11-22 23:56:37 -05:00
GitHub Action e4597df3b9 chore: format code 2025-11-23 04:54:26 +00:00
Dax Raad 2b014fcd75 fix auth 2025-11-22 23:53:41 -05:00
Github Action c2bf6975f8 Update Nix flake.lock and hashes 2025-11-23 00:44:43 +00:00
Sebastian Herrlinger 733e1f79ac bump opentui to v0.1.49
- fix stdin handling for suspend/resume
- fix textarea cursor movement segfault for wcdwidth (alacritty/tmux)
2025-11-23 01:42:33 +01:00
GitHub Action 2a6cbfd5fd chore: format code 2025-11-23 00:20:07 +00:00
Adam 6173b69a8b wip(share): more styling 2025-11-22 18:19:02 -06:00
opencode fc72cfe784 release: v1.0.105
Update Nix Hashes / update (push) Has been cancelled
2025-11-22 22:39:18 +00:00
Dax Raad 768c81cdfd core: prevent concurrent bun package installs that could cause corruption or conflicts 2025-11-22 17:32:53 -05:00
Dax Raad bcea8ed593 tui: fix message completion timing and duration display in session view 2025-11-22 17:28:50 -05:00
GitHub Action f93bb1dd21 chore: format code 2025-11-22 22:27:23 +00:00
b92e8510f9 fix: auto upgrade toast message (#4625)
Co-authored-by: Dax Raad <d@ironbay.co>
Co-authored-by: opencode <opencode@sst.dev>
2025-11-22 16:26:46 -06:00
opencode 1b692ec7eb release: v1.0.104
Update Nix Hashes / update (push) Has been cancelled
2025-11-22 20:03:20 +00:00
Dax Raad 4c97e2e8bb reset cache 2025-11-22 14:56:35 -05:00
Dax Raad b652198979 load desktop app 2025-11-22 14:40:11 -05:00
Dax Raad 31c4a1d853 docs: add Docker installation option for OpenCode 2025-11-22 14:13:04 -05:00
Goni ZahavyandGitHub 6afdb5c0e5 tui: added ctrl-z terminal suspension support (#3983) 2025-11-22 12:48:23 -06:00
bdcf864678 proper fix for image attachments (#4562)
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
2025-11-22 12:47:57 -06:00
opencode 0dd5039668 release: v1.0.103
Update Nix Hashes / update (push) Has been cancelled
2025-11-22 18:21:49 +00:00
Dax Raad a0831eade1 tui: remove bullet prefix from timestamps in session view for cleaner display 2025-11-22 13:11:08 -05:00
GitHub Action f1dc9818b6 chore: format code 2025-11-22 18:04:34 +00:00
Dax Raad b52b7c6ded more flickering fixes 2025-11-22 13:03:44 -05:00
Dax Raadandopencode e03a41144a tui: keep assistant footer from crashing after compaction 2025-11-22 18:00:54 +00:00
opencode 37bb07e7a3 release: v1.0.100
Update Nix Hashes / update (push) Has been cancelled
2025-11-22 18:00:54 +00:00
Dax Raad 78a6325b64 improve model footer 2025-11-22 12:54:02 -05:00
GitHub Action c96923d2c9 chore: format code 2025-11-22 17:50:32 +00:00
59742fbfee Showed end time for agent loop and changed message time to show date if not current day (#4503)
Co-authored-by: GitHub Action <action@github.com>
2025-11-22 11:49:50 -06:00
Dax Raadandopencode 2938a25ec5 sync 2025-11-22 16:43:47 +00:00
opencode d163eb3888 release: v1.0.99
Update Nix Hashes / update (push) Has been cancelled
2025-11-22 16:43:46 +00:00
Dax Raad 75c29d4d1c summary optimizaitons 2025-11-22 11:32:49 -05:00
Dax Raad e103fb1f93 ci: add Node.js setup to deploy workflow for consistent runtime environment 2025-11-22 10:47:18 -05:00
Dax Raad bd79ff87cc fix missing vite 2025-11-22 10:45:06 -05:00
Dax Raad ac21ec2f46 upgrade bun lock version 2025-11-22 10:42:09 -05:00
Github Action 5bcf017c10 Update Nix flake.lock and hashes 2025-11-22 15:41:29 +00:00
85d99198b5 Use devinxi-ed Solid Start (#4635)
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Dax Raad <d@ironbay.co>
2025-11-22 10:39:25 -05:00
GitHub Action 7f183f7404 ignore: update download stats 2025-11-22 2025-11-22 12:04:02 +00:00
opencode 85284df725 release: v1.0.98
Update Nix Hashes / update (push) Has been cancelled
2025-11-22 06:00:23 +00:00
Dax Raad 87054ee983 fix flickering/layout shift during work 2025-11-22 00:49:35 -05:00
GitHub Action 81245c2548 chore: format code 2025-11-22 05:15:55 +00:00
Dax Raad 6f82b321d8 tauri 2025-11-22 00:15:01 -05:00
146 changed files with 7884 additions and 1622 deletions
+4
View File
@@ -17,6 +17,10 @@ jobs:
- uses: ./.github/actions/setup-bun
- uses: actions/setup-node@v4
with:
node-version: "24"
- run: bun sst deploy --stage=${{ github.ref_name }}
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
- name: Check for duplicate issues
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
OPENCODE_PERMISSION: |
{
+2
View File
@@ -147,3 +147,5 @@
| 2025-11-19 | 804,409 (+12,846) | 747,624 (+15,080) | 1,552,033 (+27,926) |
| 2025-11-20 | 814,620 (+10,211) | 757,907 (+10,283) | 1,572,527 (+20,494) |
| 2025-11-21 | 826,309 (+11,689) | 769,307 (+11,400) | 1,595,616 (+23,089) |
| 2025-11-22 | 837,269 (+10,960) | 780,996 (+11,689) | 1,618,265 (+22,649) |
| 2025-11-23 | 846,609 (+9,340) | 795,069 (+14,073) | 1,641,678 (+23,413) |
+445 -559
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -116,6 +116,8 @@ const gatewayKv = new sst.cloudflare.Kv("GatewayKv")
// CONSOLE
////////////////
const bucket = new sst.cloudflare.Bucket("ConsoleData")
const AWS_SES_ACCESS_KEY_ID = new sst.Secret("AWS_SES_ACCESS_KEY_ID")
const AWS_SES_SECRET_ACCESS_KEY = new sst.Secret("AWS_SES_SECRET_ACCESS_KEY")
@@ -132,6 +134,7 @@ new sst.cloudflare.x.SolidStart("Console", {
domain,
path: "packages/console/app",
link: [
bucket,
database,
AUTH_API_URL,
STRIPE_WEBHOOK_SECRET,
+17
View File
@@ -0,0 +1,17 @@
import { SECRET } from "./secret"
import { domain } from "./stage"
const storage = new sst.cloudflare.Bucket("EnterpriseStorage")
const enterprise = new sst.cloudflare.x.SolidStart("Enterprise", {
domain: "enterprise." + domain,
path: "packages/enterprise",
buildCommand: "bun run build:cloudflare",
environment: {
OPENCODE_STORAGE_ADAPTER: "r2",
OPENCODE_STORAGE_ACCOUNT_ID: sst.cloudflare.DEFAULT_ACCOUNT_ID,
OPENCODE_STORAGE_ACCESS_KEY_ID: SECRET.R2AccessKey.value,
OPENCODE_STORAGE_SECRET_ACCESS_KEY: SECRET.R2SecretKey.value,
OPENCODE_STORAGE_BUCKET: storage.name,
},
})
+4
View File
@@ -0,0 +1,4 @@
export const SECRET = {
R2AccessKey: new sst.Secret("R2AccessKey", "unknown"),
R2SecretKey: new sst.Secret("R2SecretKey", "unknown"),
}
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env bun
import solidPlugin from "./node_modules/@opentui/solid/scripts/solid-plugin"
import path from "path"
import fs from "fs"
const dir = process.cwd()
const parser = fs.realpathSync(path.join(dir, "node_modules/@opentui/core/parser.worker.js"))
const worker = "./src/cli/cmd/tui/worker.ts"
const version = process.env.OPENCODE_VERSION ?? "local"
const channel = process.env.OPENCODE_CHANNEL ?? "local"
fs.rmSync(path.join(dir, "dist"), { recursive: true, force: true })
const result = await Bun.build({
entrypoints: ["./src/index.ts", worker, parser],
outdir: "./dist",
target: "bun",
sourcemap: "none",
tsconfig: "./tsconfig.json",
plugins: [solidPlugin],
external: ["@opentui/core"],
define: {
OPENCODE_VERSION: `'${version}'`,
OPENCODE_CHANNEL: `'${channel}'`,
// Leave undefined so runtime picks bundled/dist worker or fallback in code.
OPENCODE_WORKER_PATH: "undefined",
OTUI_TREE_SITTER_WORKER_PATH: 'new URL("./cli/cmd/tui/parser.worker.js", import.meta.url).href',
},
})
if (!result.success) {
console.error("bundle failed")
for (const log of result.logs) console.error(log)
process.exit(1)
}
const parserOut = path.join(dir, "dist/src/cli/cmd/tui/parser.worker.js")
fs.mkdirSync(path.dirname(parserOut), { recursive: true })
await Bun.write(parserOut, Bun.file(parser))
+1 -1
View File
@@ -1,3 +1,3 @@
{
"nodeModules": "sha256-HILcNy8B0k++ObGwUrD9dM0n9MvASR4AiyxmKSv3LV8="
"nodeModules": "sha256-/ZkyVHgRMjhzBpnDNTR6X+TomtTMarVU7gmq9Z8Czr8="
}
+60 -35
View File
@@ -1,4 +1,4 @@
{ lib, stdenv, stdenvNoCC, bun, fzf, ripgrep, makeBinaryWrapper }:
{ lib, stdenvNoCC, bun, fzf, ripgrep, makeBinaryWrapper }:
args:
let
scripts = args.scripts;
@@ -28,64 +28,89 @@ stdenvNoCC.mkDerivation (finalAttrs: {
makeBinaryWrapper
];
configurePhase = ''
runHook preConfigure
cp -R ${finalAttrs.node_modules}/. .
runHook postConfigure
'';
env.MODELS_DEV_API_JSON = args.modelsDev;
env.OPENCODE_VERSION = args.version;
env.OPENCODE_CHANNEL = "stable";
dontConfigure = true;
buildPhase = ''
runHook preBuild
cp ${scripts + "/bun-build.ts"} bun-build.ts
cp -r ${finalAttrs.node_modules}/node_modules .
cp -r ${finalAttrs.node_modules}/packages .
substituteInPlace bun-build.ts \
--replace '@VERSION@' "${finalAttrs.version}"
(
cd packages/opencode
export BUN_COMPILE_TARGET=${args.target}
bun --bun bun-build.ts
chmod -R u+w ./node_modules
mkdir -p ./node_modules/@opencode-ai
rm -f ./node_modules/@opencode-ai/{script,sdk,plugin}
ln -s $(pwd)/../../packages/script ./node_modules/@opencode-ai/script
ln -s $(pwd)/../../packages/sdk/js ./node_modules/@opencode-ai/sdk
ln -s $(pwd)/../../packages/plugin ./node_modules/@opencode-ai/plugin
cp ${./bundle.ts} ./bundle.ts
chmod +x ./bundle.ts
bun run ./bundle.ts
)
runHook postBuild
'';
dontStrip = true;
installPhase = ''
runHook preInstall
cd packages/opencode
if [ ! -f opencode ]; then
echo "ERROR: opencode binary not found in $(pwd)"
ls -la
exit 1
fi
if [ ! -f opencode-worker.js ]; then
echo "ERROR: opencode worker bundle not found in $(pwd)"
ls -la
if [ ! -d dist ]; then
echo "ERROR: dist directory missing after bundle step"
exit 1
fi
install -Dm755 opencode $out/bin/opencode
install -Dm644 opencode-worker.js $out/bin/opencode-worker.js
if [ -f opencode-assets.manifest ]; then
while IFS= read -r asset; do
[ -z "$asset" ] && continue
if [ ! -f "$asset" ]; then
echo "ERROR: referenced asset \"$asset\" missing"
exit 1
fi
install -Dm644 "$asset" "$out/bin/$(basename "$asset")"
done < opencode-assets.manifest
mkdir -p $out/lib/opencode
cp -r dist $out/lib/opencode/
chmod -R u+w $out/lib/opencode/dist
# Select bundled worker assets deterministically (sorted find output)
worker_file=$(find "$out/lib/opencode/dist" -type f \( -path '*/tui/worker.*' -o -name 'worker.*' \) | sort | head -n1)
parser_worker_file=$(find "$out/lib/opencode/dist" -type f -name 'parser.worker.*' | sort | head -n1)
if [ -z "$worker_file" ]; then
echo "ERROR: bundled worker not found"
exit 1
fi
main_wasm=$(printf '%s\n' "$out"/lib/opencode/dist/tree-sitter-*.wasm | sort | head -n1)
wasm_list=$(find "$out/lib/opencode/dist" -maxdepth 1 -name 'tree-sitter-*.wasm' -print)
for patch_file in "$worker_file" "$parser_worker_file"; do
[ -z "$patch_file" ] && continue
[ ! -f "$patch_file" ] && continue
if [ -n "$wasm_list" ] && grep -q 'tree-sitter' "$patch_file"; then
# Rewrite wasm references to absolute store paths to avoid runtime resolve failures.
bun --bun ${scripts + "/patch-wasm.ts"} "$patch_file" "$main_wasm" $wasm_list
fi
done
mkdir -p $out/lib/opencode/node_modules
cp -r ../../node_modules/.bun $out/lib/opencode/node_modules/
mkdir -p $out/lib/opencode/node_modules/@opentui
mkdir -p $out/bin
makeWrapper ${bun}/bin/bun $out/bin/opencode \
--add-flags "run" \
--add-flags "$out/lib/opencode/dist/src/index.js" \
--prefix PATH : ${lib.makeBinPath [ fzf ripgrep ]} \
--argv0 opencode
runHook postInstall
'';
postFixup = ''
wrapProgram "$out/bin/opencode" --prefix PATH : ${lib.makeBinPath [ fzf ripgrep ]}
postInstall = ''
for pkg in $out/lib/opencode/node_modules/.bun/@opentui+core-* $out/lib/opencode/node_modules/.bun/@opentui+solid-* $out/lib/opencode/node_modules/.bun/@opentui+core@* $out/lib/opencode/node_modules/.bun/@opentui+solid@*; do
if [ -d "$pkg" ]; then
pkgName=$(basename "$pkg" | sed 's/@opentui+\([^@]*\)@.*/\1/')
ln -sf ../.bun/$(basename "$pkg")/node_modules/@opentui/$pkgName \
$out/lib/opencode/node_modules/@opentui/$pkgName
fi
done
'';
meta = {
+24 -7
View File
@@ -24,15 +24,13 @@ for (const entry of directories) {
if (!info.isDirectory()) {
continue
}
const marker = entry.lastIndexOf("@")
if (marker <= 0) {
const parsed = parseEntry(entry)
if (!parsed) {
continue
}
const slug = entry.slice(0, marker).replace(/\+/g, "/")
const version = entry.slice(marker + 1)
const list = versions.get(slug) ?? []
list.push({ dir: full, version, label: entry })
versions.set(slug, list)
const list = versions.get(parsed.name) ?? []
list.push({ dir: full, version: parsed.version, label: entry })
versions.set(parsed.name, list)
}
const semverModule = (await import(join(bunRoot, "node_modules/semver"))) as
@@ -79,6 +77,12 @@ for (const [slug, entry] of Array.from(selections.entries()).sort((a, b) => a[0]
await mkdir(parent, { recursive: true })
const linkPath = join(parent, leaf)
const desired = join(entry.dir, "node_modules", slug)
const exists = await lstat(desired)
.then((info) => info.isDirectory())
.catch(() => false)
if (!exists) {
continue
}
const relativeTarget = relative(parent, desired)
const resolved = relativeTarget.length === 0 ? "." : relativeTarget
await rm(linkPath, { recursive: true, force: true })
@@ -94,3 +98,16 @@ for (const line of rewrites.slice(0, 20)) {
if (rewrites.length > 20) {
console.log(" ...")
}
function parseEntry(label: string) {
const marker = label.startsWith("@") ? label.indexOf("@", 1) : label.indexOf("@")
if (marker <= 0) {
return null
}
const name = label.slice(0, marker).replace(/\+/g, "/")
const version = label.slice(marker + 1)
if (!name || !version) {
return null
}
return { name, version }
}
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bun
import fs from "fs"
import path from "path"
/**
* Rewrite tree-sitter wasm references inside a JS file to absolute paths.
* argv: [node, script, file, mainWasm, ...wasmPaths]
*/
const [, , file, mainWasm, ...wasmPaths] = process.argv
if (!file || !mainWasm) {
console.error("usage: patch-wasm <file> <mainWasm> [wasmPaths...]")
process.exit(1)
}
const content = fs.readFileSync(file, "utf8")
const byName = new Map<string, string>()
for (const wasm of wasmPaths) {
const name = path.basename(wasm)
byName.set(name, wasm)
}
let next = content
for (const [name, wasmPath] of byName) {
next = next.replaceAll(name, wasmPath)
}
next = next.replaceAll("tree-sitter.wasm", mainWasm).replaceAll("web-tree-sitter/tree-sitter.wasm", mainWasm)
// Collapse any relative prefixes before absolute store paths (e.g., "../../../..//nix/store/...")
next = next.replace(/(\.\/)+/g, "./")
next = next.replace(/(\.\.\/)+\/?(\/nix\/store[^"']+)/g, "/$2")
next = next.replace(/(["'])\/{2,}(\/nix\/store[^"']+)(["'])/g, "$1/$2$3")
next = next.replace(/(["'])\/\/(nix\/store[^"']+)(["'])/g, "$1/$2$3")
if (next !== content) fs.writeFileSync(file, next)
+1 -4
View File
@@ -48,7 +48,7 @@
"vite": "7.1.4",
"@solidjs/meta": "0.29.4",
"@solidjs/router": "0.15.4",
"@solidjs/start": "1.2.0",
"@solidjs/start": "https://pkg.pr.new/@solidjs/start@dfb2020",
"solid-js": "1.9.10",
"vite-plugin-solid": "2.11.10"
}
@@ -82,9 +82,6 @@
"tree-sitter-bash",
"web-tree-sitter"
],
"patchedDependencies": {
"@solidjs/start@1.1.7": "patches/@solidjs%2Fstart@1.1.7.patch"
},
"overrides": {
"@types/bun": "catalog:",
"@types/node": "catalog:"
-1
View File
@@ -3,7 +3,6 @@ dist
.output
.vercel
.netlify
.vinxi
app.config.timestamp_*.js
# Environment
-23
View File
@@ -1,23 +0,0 @@
import { defineConfig } from "@solidjs/start/config"
export default defineConfig({
middleware: "./src/middleware.ts",
vite: {
server: {
allowedHosts: true,
},
build: {
rollupOptions: {
external: ["cloudflare:workers"],
},
minify: false,
},
},
server: {
compatibilityDate: "2024-09-19",
preset: "cloudflare_module",
cloudflare: {
nodeCompat: true,
},
},
})
+9 -6
View File
@@ -1,15 +1,16 @@
{
"name": "@opencode-ai/console-app",
"version": "1.0.97",
"version": "1.0.107",
"type": "module",
"scripts": {
"typecheck": "tsgo --noEmit",
"dev": "vinxi dev --host 0.0.0.0",
"dev": "vite dev --host 0.0.0.0",
"dev:remote": "VITE_AUTH_URL=https://auth.dev.opencode.ai bun sst shell --stage=dev bun dev",
"build": "./script/generate-sitemap.ts && vinxi build && ../../opencode/script/schema.ts ./.output/public/config.json",
"start": "vinxi start"
"build": "./script/generate-sitemap.ts && vite build && ../../opencode/script/schema.ts ./.output/public/config.json",
"start": "vite start"
},
"dependencies": {
"@cloudflare/vite-plugin": "1.15.2",
"@ibm/plex": "6.4.1",
"@jsx-email/render": "1.1.1",
"@kobalte/core": "catalog:",
@@ -21,13 +22,15 @@
"@solidjs/router": "catalog:",
"@solidjs/start": "catalog:",
"chart.js": "4.5.1",
"nitro": "3.0.1-alpha.1",
"solid-js": "catalog:",
"vinxi": "^0.5.7",
"vite": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@typescript/native-preview": "catalog:",
"typescript": "catalog:",
"@typescript/native-preview": "catalog:"
"wrangler": "4.50.0"
},
"engines": {
"node": ">=22"
@@ -1,4 +1,4 @@
import { useSession } from "vinxi/http"
import { useSession } from "@solidjs/start/http"
export interface AuthSession {
account?: Record<
+4
View File
@@ -1 +1,5 @@
/// <reference types="@solidjs/start/env" />
export declare module "@solidjs/start/server" {
export type APIEvent = { request: Request }
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { defineMiddleware } from "vinxi/http"
import { createMiddleware } from "@solidjs/start/middleware"
export default defineMiddleware({
export default createMiddleware({
onBeforeResponse() {},
})
@@ -19,6 +19,7 @@ export async function GET(input: APIEvent) {
return {
...value,
account: {
...value.account,
[id]: {
id,
email: decoded.subject.properties.email,
@@ -0,0 +1,17 @@
import { redirect } from "@solidjs/router"
import { APIEvent } from "@solidjs/start"
import { useAuthSession } from "~/context/auth.session"
export async function GET(event: APIEvent) {
const auth = await useAuthSession()
const current = auth.data.current
if (current)
await auth.update((val) => {
delete val.account?.[current]
const first = Object.keys(val.account ?? {})[0]
val.current = first
event!.locals.actor = undefined
return val
})
return redirect("/zen")
}
@@ -0,0 +1,7 @@
import { APIEvent } from "@solidjs/start"
import { useAuthSession } from "~/context/auth.session"
export async function GET(input: APIEvent) {
const session = await useAuthSession()
return Response.json(session.data)
}
+2 -2
View File
@@ -1,6 +1,6 @@
import "./index.css"
import { Title, Meta, Link } from "@solidjs/meta"
import { HttpHeader } from "@solidjs/start"
// import { HttpHeader } from "@solidjs/start"
import video from "../asset/lander/opencode-min.mp4"
import videoPoster from "../asset/lander/opencode-poster.png"
import { IconCopy, IconCheck } from "../component/icon"
@@ -42,7 +42,7 @@ export default function Home() {
return (
<main data-page="opencode">
<HttpHeader name="Cache-Control" value="public, max-age=1, s-maxage=3600, stale-while-revalidate=86400" />
{/*<HttpHeader name="Cache-Control" value="public, max-age=1, s-maxage=3600, stale-while-revalidate=86400" />*/}
<Title>OpenCode | The AI coding agent built for the terminal</Title>
<Link rel="canonical" href={config.baseUrl} />
<Link rel="icon" type="image/svg+xml" href="/favicon.svg" />
@@ -12,6 +12,7 @@
[data-slot="item"] {
color: var(--color-danger);
text-decoration: none;
}
}
}
@@ -1,4 +1,4 @@
import { action, redirect } from "@solidjs/router"
import { action } from "@solidjs/router"
import { getRequestEvent } from "solid-js/web"
import { useAuthSession } from "~/context/auth.session"
import { Dropdown } from "~/component/dropdown"
@@ -17,18 +17,15 @@ const logout = action(async () => {
event!.locals.actor = undefined
return val
})
throw redirect("/zen")
})
}, "auth.logout")
export function UserMenu(props: { email: string | null | undefined }) {
return (
<div data-component="user-menu">
<Dropdown trigger={props.email ?? ""} align="right">
<form action={logout} method="post">
<button type="submit" formaction={logout} data-slot="item">
Logout
</button>
</form>
<a href="/auth/logout" data-slot="item">
Logout
</a>
</Dropdown>
</div>
)
@@ -1,7 +1,7 @@
import "./index.css"
import { createAsync, query, redirect } from "@solidjs/router"
import { Title, Meta, Link } from "@solidjs/meta"
import { HttpHeader } from "@solidjs/start"
// import { HttpHeader } from "@solidjs/start"
import zenLogoLight from "../../asset/zen-ornate-light.svg"
import { config } from "~/config"
import zenLogoDark from "../../asset/zen-ornate-dark.svg"
@@ -21,20 +21,21 @@ import { getLastSeenWorkspaceID } from "../workspace/common"
const checkLoggedIn = query(async () => {
"use server"
const workspaceID = await getLastSeenWorkspaceID()
const workspaceID = await getLastSeenWorkspaceID().catch(() => {})
if (workspaceID) throw redirect(`/workspace/${workspaceID}`)
}, "checkLoggedIn.get")
export default function Home() {
createAsync(() => checkLoggedIn())
const loggedin = createAsync(() => checkLoggedIn())
return (
<main data-page="zen">
<HttpHeader name="Cache-Control" value="public, max-age=1, s-maxage=3600, stale-while-revalidate=86400" />
{/*<HttpHeader name="Cache-Control" value="public, max-age=1, s-maxage=3600, stale-while-revalidate=86400" />*/}
<Title>OpenCode Zen | A curated set of reliable optimized models for coding agents</Title>
<Link rel="canonical" href={`${config.baseUrl}/zen`} />
<Link rel="icon" type="image/svg+xml" href="/favicon-zen.svg" />
<Meta property="og:image" content="/social-share-zen.png" />
<Meta name="twitter:image" content="/social-share-zen.png" />
<Meta name="opencode:auth" content={loggedin() ? "true" : "false"} />
<div data-component="container">
<Header zen />
@@ -0,0 +1,26 @@
import { Resource, waitUntil } from "@opencode-ai/console-resource"
export function createDataDumper(sessionId: string, requestId: string) {
if (Resource.App.stage !== "production") return
let data: Record<string, any> = {}
let modelName: string | undefined
return {
provideModel: (model?: string) => (modelName = model),
provideRequest: (request: string) => (data.request = request),
provideResponse: (response: string) => (data.response = response),
provideStream: (chunk: string) => (data.response = (data.response ?? "") + chunk),
flush: () => {
if (!modelName) return
const str = new Date().toISOString().replace(/[^0-9]/g, "")
const yyyymmdd = str.substring(0, 8)
const hh = str.substring(8, 10)
waitUntil(
Resource.ConsoleData.put(`${yyyymmdd}/${hh}/${modelName}/${sessionId}/${requestId}.json`, JSON.stringify(data)),
)
},
}
}
@@ -19,6 +19,7 @@ import { googleHelper } from "./provider/google"
import { openaiHelper } from "./provider/openai"
import { oaCompatHelper } from "./provider/openai-compatible"
import { createRateLimiter } from "./rateLimiter"
import { createDataDumper } from "./dataDumper"
type ZenData = Awaited<ReturnType<typeof ZenData.list>>
type RetryOptions = {
@@ -48,16 +49,19 @@ export async function handler(
try {
const url = input.request.url
const body = await input.request.json()
const ip = input.request.headers.get("x-real-ip") ?? ""
const model = opts.parseModel(url, body)
const isStream = opts.parseIsStream(url, body)
const ip = input.request.headers.get("x-real-ip") ?? ""
const sessionId = input.request.headers.get("x-opencode-session") ?? ""
const requestId = input.request.headers.get("x-opencode-request") ?? ""
logger.metric({
is_tream: isStream,
session: input.request.headers.get("x-opencode-session"),
request: input.request.headers.get("x-opencode-request"),
session: sessionId,
request: requestId,
})
const zenData = ZenData.list()
const modelInfo = validateModel(zenData, model)
const dataDumper = createDataDumper(sessionId, requestId)
const rateLimiter = createRateLimiter(modelInfo.id, modelInfo.rateLimit, ip)
await rateLimiter?.check()
@@ -104,10 +108,14 @@ export async function handler(
})
}
return { providerInfo, authInfo, res, startTimestamp }
return { providerInfo, authInfo, reqBody, res, startTimestamp }
}
const { providerInfo, authInfo, res, startTimestamp } = await retriableRequest()
const { providerInfo, authInfo, reqBody, res, startTimestamp } = await retriableRequest()
// Store model request
dataDumper?.provideModel(providerInfo.storeModel)
dataDumper?.provideRequest(reqBody)
// Scrub response headers
const resHeaders = new Headers()
@@ -126,6 +134,8 @@ export async function handler(
const body = JSON.stringify(responseConverter(json))
logger.metric({ response_length: body.length })
logger.debug("RESPONSE: " + body)
dataDumper?.provideResponse(body)
dataDumper?.flush()
await rateLimiter?.track()
await trackUsage(authInfo, modelInfo, providerInfo, json.usage)
await reload(authInfo)
@@ -155,6 +165,7 @@ export async function handler(
response_length: responseLength,
"timestamp.last_byte": Date.now(),
})
dataDumper?.flush()
await rateLimiter?.track()
const usage = usageParser.retrieve()
if (usage) {
@@ -174,6 +185,7 @@ export async function handler(
}
responseLength += value.length
buffer += decoder.decode(value, { stream: true })
dataDumper?.provideStream(buffer)
const parts = buffer.split(providerInfo.streamSeparator)
buffer = parts.pop() ?? ""
+1 -1
View File
@@ -12,7 +12,7 @@
"allowJs": true,
"strict": true,
"noEmit": true,
"types": ["vinxi/types/client"],
"types": ["vite/client"],
"isolatedModules": true,
"paths": {
"~/*": ["./src/*"]
+25
View File
@@ -0,0 +1,25 @@
import { defineConfig, PluginOption } from "vite"
import { solidStart } from "@solidjs/start/config"
import { nitro } from "nitro/vite"
export default defineConfig({
plugins: [
solidStart() as PluginOption,
nitro({
compatibilityDate: "2024-09-19",
preset: "cloudflare_module",
cloudflare: {
nodeCompat: true,
},
}),
],
server: {
allowedHosts: true,
},
build: {
rollupOptions: {
external: ["cloudflare:workers"],
},
minify: false,
},
})
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/console-core",
"version": "1.0.97",
"version": "1.0.107",
"private": true,
"type": "module",
"dependencies": {
+1
View File
@@ -32,6 +32,7 @@ export namespace ZenData {
model: z.string(),
weight: z.number().optional(),
disabled: z.boolean().optional(),
storeModel: z.string().optional(),
}),
),
})
+10
View File
@@ -74,6 +74,14 @@ declare module "sst" {
type: "sst.sst.Secret"
value: string
}
R2AccessKey: {
type: "sst.sst.Secret"
value: string
}
R2SecretKey: {
type: "sst.sst.Secret"
value: string
}
STRIPE_SECRET_KEY: {
type: "sst.sst.Secret"
value: string
@@ -112,6 +120,8 @@ declare module "sst" {
AuthApi: cloudflare.Service
AuthStorage: cloudflare.KVNamespace
Bucket: cloudflare.R2Bucket
ConsoleData: cloudflare.R2Bucket
EnterpriseStorage: cloudflare.R2Bucket
GatewayKv: cloudflare.KVNamespace
LogProcessor: cloudflare.Service
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-ai/console-function",
"version": "1.0.97",
"version": "1.0.107",
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
+10
View File
@@ -74,6 +74,14 @@ declare module "sst" {
type: "sst.sst.Secret"
value: string
}
R2AccessKey: {
type: "sst.sst.Secret"
value: string
}
R2SecretKey: {
type: "sst.sst.Secret"
value: string
}
STRIPE_SECRET_KEY: {
type: "sst.sst.Secret"
value: string
@@ -112,6 +120,8 @@ declare module "sst" {
AuthApi: cloudflare.Service
AuthStorage: cloudflare.KVNamespace
Bucket: cloudflare.R2Bucket
ConsoleData: cloudflare.R2Bucket
EnterpriseStorage: cloudflare.R2Bucket
GatewayKv: cloudflare.KVNamespace
LogProcessor: cloudflare.Service
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-ai/console-mail",
"version": "1.0.97",
"version": "1.0.107",
"dependencies": {
"@jsx-email/all": "2.2.3",
"@jsx-email/cli": "1.4.3",
@@ -1,4 +1,5 @@
import { env } from "cloudflare:workers"
export { waitUntil } from "cloudflare:workers"
export const Resource = new Proxy(
{},
+52 -40
View File
@@ -2,54 +2,66 @@ import type { KVNamespaceListOptions, KVNamespaceListResult, KVNamespacePutOptio
import { Resource as ResourceBase } from "sst"
import Cloudflare from "cloudflare"
export const waitUntil = async (fn: () => Promise<void>) => {
await fn()
}
export const Resource = new Proxy(
{},
{
get(_target, prop: keyof typeof ResourceBase) {
const value = ResourceBase[prop]
// @ts-ignore
if ("type" in value && value.type === "sst.cloudflare.Kv") {
const client = new Cloudflare({
apiToken: ResourceBase.CLOUDFLARE_API_TOKEN.value,
})
if ("type" in value) {
// @ts-ignore
const namespaceId = value.namespaceId
const accountId = ResourceBase.CLOUDFLARE_DEFAULT_ACCOUNT_ID.value
return {
get: (k: string | string[]) => {
const isMulti = Array.isArray(k)
return client.kv.namespaces
.bulkGet(namespaceId, {
keys: Array.isArray(k) ? k : [k],
if (value.type === "sst.cloudflare.Bucket") {
return {
put: async () => {},
}
}
// @ts-ignore
if (value.type === "sst.cloudflare.Kv") {
const client = new Cloudflare({
apiToken: ResourceBase.CLOUDFLARE_API_TOKEN.value,
})
// @ts-ignore
const namespaceId = value.namespaceId
const accountId = ResourceBase.CLOUDFLARE_DEFAULT_ACCOUNT_ID.value
return {
get: (k: string | string[]) => {
const isMulti = Array.isArray(k)
return client.kv.namespaces
.bulkGet(namespaceId, {
keys: Array.isArray(k) ? k : [k],
account_id: accountId,
})
.then((result) => (isMulti ? new Map(Object.entries(result?.values ?? {})) : result?.values?.[k]))
},
put: (k: string, v: string, opts?: KVNamespacePutOptions) =>
client.kv.namespaces.values.update(namespaceId, k, {
account_id: accountId,
})
.then((result) => (isMulti ? new Map(Object.entries(result?.values ?? {})) : result?.values?.[k]))
},
put: (k: string, v: string, opts?: KVNamespacePutOptions) =>
client.kv.namespaces.values.update(namespaceId, k, {
account_id: accountId,
value: v,
expiration: opts?.expiration,
expiration_ttl: opts?.expirationTtl,
metadata: opts?.metadata,
}),
delete: (k: string) =>
client.kv.namespaces.values.delete(namespaceId, k, {
account_id: accountId,
}),
list: (opts?: KVNamespaceListOptions): Promise<KVNamespaceListResult<unknown, string>> =>
client.kv.namespaces.keys
.list(namespaceId, {
account_id: accountId,
prefix: opts?.prefix ?? undefined,
})
.then((result) => {
return {
keys: result.result,
list_complete: true,
cacheStatus: null,
}
value: v,
expiration: opts?.expiration,
expiration_ttl: opts?.expirationTtl,
metadata: opts?.metadata,
}),
delete: (k: string) =>
client.kv.namespaces.values.delete(namespaceId, k, {
account_id: accountId,
}),
list: (opts?: KVNamespaceListOptions): Promise<KVNamespaceListResult<unknown, string>> =>
client.kv.namespaces.keys
.list(namespaceId, {
account_id: accountId,
prefix: opts?.prefix ?? undefined,
})
.then((result) => {
return {
keys: result.result,
list_complete: true,
cacheStatus: null,
}
}),
}
}
}
return value
+10
View File
@@ -74,6 +74,14 @@ declare module "sst" {
type: "sst.sst.Secret"
value: string
}
R2AccessKey: {
type: "sst.sst.Secret"
value: string
}
R2SecretKey: {
type: "sst.sst.Secret"
value: string
}
STRIPE_SECRET_KEY: {
type: "sst.sst.Secret"
value: string
@@ -112,6 +120,8 @@ declare module "sst" {
AuthApi: cloudflare.Service
AuthStorage: cloudflare.KVNamespace
Bucket: cloudflare.R2Bucket
ConsoleData: cloudflare.R2Bucket
EnterpriseStorage: cloudflare.R2Bucket
GatewayKv: cloudflare.KVNamespace
LogProcessor: cloudflare.Service
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-ai/desktop",
"version": "1.0.97",
"version": "1.0.107",
"description": "",
"type": "module",
"scripts": {
+3 -3
View File
@@ -5,7 +5,7 @@ import { useSync } from "./sync"
import { makePersisted } from "@solid-primitives/storage"
import { TextSelection } from "./local"
import { pipe, sumBy } from "remeda"
import { AssistantMessage } from "@opencode-ai/sdk"
import { AssistantMessage, UserMessage } from "@opencode-ai/sdk"
import { useParams } from "@solidjs/router"
import { base64Encode } from "@/utils"
@@ -123,8 +123,8 @@ export const { use: useSession, provider: SessionProvider } = createSimpleContex
user: userMessages,
last: lastUserMessage,
active: activeMessage,
setActive(id: string | undefined) {
setStore("messageId", id)
setActive(message: UserMessage | undefined) {
setStore("messageId", message?.id)
},
},
usage: {
+24 -9
View File
@@ -1,4 +1,4 @@
import { For, onCleanup, onMount, Show, Match, Switch, createResource } from "solid-js"
import { For, onCleanup, onMount, Show, Match, Switch, createResource, createMemo } from "solid-js"
import { useLocal, type LocalFile } from "@/context/local"
import { createStore } from "solid-js/store"
import { getDirectory, getFilename } from "@/utils"
@@ -12,7 +12,8 @@ import { DiffChanges } from "@opencode-ai/ui/diff-changes"
import { ProgressCircle } from "@opencode-ai/ui/progress-circle"
import { Tabs } from "@opencode-ai/ui/tabs"
import { Code } from "@opencode-ai/ui/code"
import { SessionTimeline } from "@opencode-ai/ui/session-timeline"
import { SessionTurn } from "@opencode-ai/ui/session-turn"
import { MessageNav } from "@opencode-ai/ui/message-nav"
import { SessionReview } from "@opencode-ai/ui/session-review"
import { SelectDialog } from "@opencode-ai/ui/select-dialog"
import {
@@ -255,6 +256,8 @@ export default function Page() {
return typeof draggable.id === "string" ? draggable.id : undefined
}
const wide = createMemo(() => layout.review.state() === "tab" || !session.diffs().length)
return (
<div class="relative bg-background-base size-full overflow-x-hidden">
<DragDropProvider
@@ -330,14 +333,26 @@ export default function Page() {
flex: layout.review.state() === "pane",
}}
>
<div class="relative shrink-0 px-6 py-3 flex flex-col gap-6 flex-1 min-h-0 w-full max-w-xl mx-auto">
<div class="relative shrink-0 px-6 py-3 flex flex-col gap-6 flex-1 min-h-0 w-full max-w-2xl mx-auto">
<Switch>
<Match when={session.id}>
<SessionTimeline
sessionID={session.id!}
expanded={layout.review.state() === "tab" || !session.diffs().length}
classes={{ root: "pb-20", container: "pb-20" }}
/>
<div class="flex items-start justify-start h-full min-h-0">
<Show when={session.messages.user().length > 1}>
<MessageNav
classList={{ "mt-1.5 mr-3": wide(), "mt-3 mr-8": !wide() }}
messages={session.messages.user()}
current={session.messages.active()}
onMessageSelect={session.messages.setActive}
size={wide() ? "normal" : "compact"}
working={session.working()}
/>
</Show>
<SessionTurn
sessionID={session.id!}
messageID={session.messages.active()?.id!}
classes={{ root: "pb-20 flex-1 min-w-0", content: "pb-20" }}
/>
</div>
</Match>
<Match when={true}>
<div class="size-full flex flex-col pb-45 justify-end items-start gap-4 flex-[1_0_0] self-stretch">
@@ -456,7 +471,7 @@ export default function Page() {
</DragOverlay>
</DragDropProvider>
<Show when={session.layout.tabs.active}>
<div class="absolute inset-x-0 px-6 max-w-2xl flex flex-col justify-center items-center z-50 mx-auto bottom-6">
<div class="absolute inset-x-0 px-6 max-w-2xl flex flex-col justify-center items-center z-50 mx-auto bottom-8">
<PromptInput
ref={(el) => {
inputRef = el
+1 -1
View File
@@ -9,7 +9,7 @@ export default defineConfig({
"@": path.resolve(__dirname, "./src"),
},
},
plugins: [tailwindcss(), solidPlugin()],
plugins: [tailwindcss(), solidPlugin()] as any,
server: {
host: "0.0.0.0",
allowedHosts: true,
-2
View File
@@ -3,8 +3,6 @@ dist
.output
.vercel
.netlify
.vinxi
app.config.timestamp_*.js
# Environment
.env
-12
View File
@@ -1,12 +0,0 @@
import { defineConfig } from "@solidjs/start/config"
import tailwindcss from "@tailwindcss/vite"
export default defineConfig({
vite: {
plugins: [tailwindcss() as any],
server: {
host: "0.0.0.0",
allowedHosts: true,
},
},
})
+9 -6
View File
@@ -1,13 +1,14 @@
{
"name": "@opencode-ai/enterprise",
"version": "1.0.97",
"version": "1.0.107",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsgo --noEmit",
"dev": "vinxi dev",
"build": "vinxi build",
"start": "vinxi start"
"dev": "vite dev",
"build": "vite build",
"build:cloudflare": "OPENCODE_DEPLOYMENT_TARGET=cloudflare vite build",
"start": "vite start"
},
"dependencies": {
"@opencode-ai/util": "workspace:*",
@@ -18,16 +19,18 @@
"hono": "catalog:",
"hono-openapi": "catalog:",
"luxon": "catalog:",
"nitro": "3.0.1-alpha.1",
"solid-js": "catalog:",
"vinxi": "^0.5.7",
"zod": "catalog:"
},
"devDependencies": {
"@cloudflare/workers-types": "catalog:",
"@tailwindcss/vite": "catalog:",
"@typescript/native-preview": "catalog:",
"@types/luxon": "catalog:",
"tailwindcss": "catalog:",
"typescript": "catalog:"
"typescript": "catalog:",
"vite": "catalog:"
},
"engines": {
"node": ">=22"
+4
View File
@@ -1 +1,5 @@
/// <reference types="@solidjs/start/env" />
export declare module "@solidjs/start/server" {
export type APIEvent = { request: Request }
}
@@ -1,5 +1,5 @@
import { FileDiff, Message, Part, Session, SessionStatus } from "@opencode-ai/sdk"
import { SessionTimeline } from "@opencode-ai/ui/session-timeline"
import { FileDiff, Message, Part, Session, SessionStatus, UserMessage } from "@opencode-ai/sdk"
import { SessionTurn } from "@opencode-ai/ui/session-turn"
import { SessionReview } from "@opencode-ai/ui/session-review"
import { DataProvider, useData } from "@opencode-ai/ui/context"
import { createAsync, query, RouteDefinition, useParams } from "@solidjs/router"
@@ -10,6 +10,8 @@ import { IconButton } from "@opencode-ai/ui/icon-button"
import { iife } from "@opencode-ai/util/iife"
import { Binary } from "@opencode-ai/util/binary"
import { DateTime } from "luxon"
import { MessageNav } from "@opencode-ai/ui/message-nav"
import { createStore } from "solid-js/store"
const getData = query(async (sessionID) => {
const data = await Share.data(sessionID)
@@ -40,7 +42,6 @@ const getData = query(async (sessionID) => {
message: {},
part: {},
}
for (const item of data) {
switch (item.type) {
case "session":
@@ -82,14 +83,28 @@ export default function () {
<DataProvider data={data()}>
{iife(() => {
const data = useData()
const [store, setStore] = createStore({
messageId: undefined as string | undefined,
})
const match = createMemo(() => Binary.search(data.session, params.sessionID!, (s) => s.id))
if (!match().found) throw new Error(`Session ${params.sessionID} not found`)
const info = createMemo(() => data.session[match().index])
const firstUserMessage = createMemo(() =>
data.message[params.sessionID!]?.filter((m) => m.role === "user")?.at(0),
const messages = createMemo(() =>
params.sessionID ? (data.message[params.sessionID]?.filter((m) => m.role === "user") ?? []) : [],
)
const provider = createMemo(() => firstUserMessage()?.model?.providerID)
const model = createMemo(() => firstUserMessage()?.model?.modelID)
const firstUserMessage = createMemo(() => messages().at(0))
const activeMessage = createMemo(
() => messages().find((m) => m.id === store.messageId) ?? firstUserMessage(),
)
function setActiveMessage(message: UserMessage | undefined) {
if (message) {
setStore("messageId", message.id)
} else {
setStore("messageId", undefined)
}
}
const provider = createMemo(() => activeMessage()?.model?.providerID)
const model = createMemo(() => activeMessage()?.model?.modelID)
const diffs = createMemo(() => data.session_diff[params.sessionID!] ?? [])
return (
@@ -145,15 +160,26 @@ export default function () {
</div>
<div class="text-left text-16-medium text-text-strong">{info().title}</div>
</div>
<SessionTimeline
sessionID={params.sessionID!}
classes={{ root: "grow", content: "flex flex-col justify-between", container: "pb-20" }}
expanded
>
<div class="flex items-center justify-center pb-8 shrink-0">
<Logo class="w-58.5 opacity-12" />
</div>
</SessionTimeline>
<div class="flex items-start justify-start h-full min-h-0">
<Show when={messages().length > 1}>
<MessageNav
classList={{ "mt-3 mr-3": true }}
messages={messages()}
current={activeMessage()}
onMessageSelect={setActiveMessage}
size={!diffs().length ? "normal" : "compact"}
/>
</Show>
<SessionTurn
sessionID={params.sessionID!}
messageID={store.messageId ?? firstUserMessage()!.id!}
classes={{ root: "grow", content: "flex flex-col justify-between", container: "pb-20" }}
>
<div class="flex items-center justify-center pb-8 shrink-0">
<Logo class="w-58.5 opacity-12" />
</div>
</SessionTurn>
</div>
</div>
<Show when={diffs().length}>
<div class="relative grow px-6 pt-14 flex-1 min-h-0 border-l border-border-weak-base">
+131
View File
@@ -0,0 +1,131 @@
/* This file is auto-generated by SST. Do not edit. */
/* tslint:disable */
/* eslint-disable */
/* deno-fmt-ignore-file */
import "sst"
declare module "sst" {
export interface Resource {
ADMIN_SECRET: {
type: "sst.sst.Secret"
value: string
}
AUTH_API_URL: {
type: "sst.sst.Linkable"
value: string
}
AWS_SES_ACCESS_KEY_ID: {
type: "sst.sst.Secret"
value: string
}
AWS_SES_SECRET_ACCESS_KEY: {
type: "sst.sst.Secret"
value: string
}
CLOUDFLARE_API_TOKEN: {
type: "sst.sst.Secret"
value: string
}
CLOUDFLARE_DEFAULT_ACCOUNT_ID: {
type: "sst.sst.Secret"
value: string
}
Console: {
type: "sst.cloudflare.SolidStart"
url: string
}
Database: {
database: string
host: string
password: string
port: number
type: "sst.sst.Linkable"
username: string
}
Desktop: {
type: "sst.cloudflare.StaticSite"
url: string
}
EMAILOCTOPUS_API_KEY: {
type: "sst.sst.Secret"
value: string
}
GITHUB_APP_ID: {
type: "sst.sst.Secret"
value: string
}
GITHUB_APP_PRIVATE_KEY: {
type: "sst.sst.Secret"
value: string
}
GITHUB_CLIENT_ID_CONSOLE: {
type: "sst.sst.Secret"
value: string
}
GITHUB_CLIENT_SECRET_CONSOLE: {
type: "sst.sst.Secret"
value: string
}
GOOGLE_CLIENT_ID: {
type: "sst.sst.Secret"
value: string
}
HONEYCOMB_API_KEY: {
type: "sst.sst.Secret"
value: string
}
R2AccessKey: {
type: "sst.sst.Secret"
value: string
}
R2SecretKey: {
type: "sst.sst.Secret"
value: string
}
STRIPE_SECRET_KEY: {
type: "sst.sst.Secret"
value: string
}
STRIPE_WEBHOOK_SECRET: {
type: "sst.sst.Linkable"
value: string
}
Web: {
type: "sst.cloudflare.Astro"
url: string
}
ZEN_MODELS1: {
type: "sst.sst.Secret"
value: string
}
ZEN_MODELS2: {
type: "sst.sst.Secret"
value: string
}
ZEN_MODELS3: {
type: "sst.sst.Secret"
value: string
}
ZEN_MODELS4: {
type: "sst.sst.Secret"
value: string
}
}
}
// cloudflare
import * as cloudflare from "@cloudflare/workers-types"
declare module "sst" {
export interface Resource {
Api: cloudflare.Service
AuthApi: cloudflare.Service
AuthStorage: cloudflare.KVNamespace
Bucket: cloudflare.R2Bucket
ConsoleData: cloudflare.R2Bucket
EnterpriseStorage: cloudflare.R2Bucket
GatewayKv: cloudflare.KVNamespace
LogProcessor: cloudflare.Service
}
}
import "sst"
export {}
+1 -1
View File
@@ -11,7 +11,7 @@
"allowJs": true,
"noEmit": true,
"strict": true,
"types": ["vinxi/types/client"],
"types": ["@cloudflare/workers-types", "vite/client"],
"isolatedModules": true,
"paths": {
"~/*": ["./src/*"]
+26
View File
@@ -0,0 +1,26 @@
import { defineConfig, PluginOption } from "vite"
import { solidStart } from "@solidjs/start/config"
import { nitro } from "nitro/vite"
import tailwindcss from "@tailwindcss/vite"
const nitroConfig: any = (() => {
const target = process.env.OPENCODE_DEPLOYMENT_TARGET
if (target === "cloudflare") {
return {
compatibilityDate: "2024-09-19",
preset: "cloudflare_module",
cloudflare: {
nodeCompat: true,
},
}
}
return {}
})()
export default defineConfig({
plugins: [tailwindcss(), solidStart() as PluginOption, nitro(nitroConfig)],
server: {
host: "0.0.0.0",
allowedHosts: true,
},
})
+6 -6
View File
@@ -1,7 +1,7 @@
id = "opencode"
name = "OpenCode"
description = "The AI coding agent built for the terminal"
version = "1.0.97"
version = "1.0.107"
schema_version = 1
authors = ["Anomaly"]
repository = "https://github.com/sst/opencode"
@@ -11,26 +11,26 @@ name = "OpenCode"
icon = "./icons/opencode.svg"
[agent_servers.opencode.targets.darwin-aarch64]
archive = "https://github.com/sst/opencode/releases/download/v1.0.97/opencode-darwin-arm64.zip"
archive = "https://github.com/sst/opencode/releases/download/v1.0.107/opencode-darwin-arm64.zip"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.darwin-x86_64]
archive = "https://github.com/sst/opencode/releases/download/v1.0.97/opencode-darwin-x64.zip"
archive = "https://github.com/sst/opencode/releases/download/v1.0.107/opencode-darwin-x64.zip"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.linux-aarch64]
archive = "https://github.com/sst/opencode/releases/download/v1.0.97/opencode-linux-arm64.zip"
archive = "https://github.com/sst/opencode/releases/download/v1.0.107/opencode-linux-arm64.zip"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.linux-x86_64]
archive = "https://github.com/sst/opencode/releases/download/v1.0.97/opencode-linux-x64.zip"
archive = "https://github.com/sst/opencode/releases/download/v1.0.107/opencode-linux-x64.zip"
cmd = "./opencode"
args = ["acp"]
[agent_servers.opencode.targets.windows-x86_64]
archive = "https://github.com/sst/opencode/releases/download/v1.0.97/opencode-windows-x64.zip"
archive = "https://github.com/sst/opencode/releases/download/v1.0.107/opencode-windows-x64.zip"
cmd = "./opencode.exe"
args = ["acp"]
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-ai/function",
"version": "1.0.97",
"version": "1.0.107",
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
+10
View File
@@ -74,6 +74,14 @@ declare module "sst" {
type: "sst.sst.Secret"
value: string
}
R2AccessKey: {
type: "sst.sst.Secret"
value: string
}
R2SecretKey: {
type: "sst.sst.Secret"
value: string
}
STRIPE_SECRET_KEY: {
type: "sst.sst.Secret"
value: string
@@ -112,6 +120,8 @@ declare module "sst" {
AuthApi: cloudflare.Service
AuthStorage: cloudflare.KVNamespace
Bucket: cloudflare.R2Bucket
ConsoleData: cloudflare.R2Bucket
EnterpriseStorage: cloudflare.R2Bucket
GatewayKv: cloudflare.KVNamespace
LogProcessor: cloudflare.Service
}
+11 -5
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "1.0.97",
"version": "1.0.107",
"name": "opencode",
"type": "module",
"private": true,
@@ -18,8 +18,6 @@
"./*": "./src/*.ts"
},
"devDependencies": {
"@ai-sdk/amazon-bedrock": "2.2.10",
"@ai-sdk/google-vertex": "3.0.16",
"@babel/core": "7.28.4",
"@octokit/webhooks-types": "7.6.1",
"@parcel/watcher-darwin-arm64": "2.5.1",
@@ -44,7 +42,14 @@
"@actions/core": "1.11.1",
"@actions/github": "6.0.1",
"@agentclientprotocol/sdk": "0.5.1",
"@ai-sdk/amazon-bedrock": "3.0.57",
"@ai-sdk/anthropic": "2.0.45",
"@ai-sdk/azure": "2.0.73",
"@ai-sdk/google": "2.0.42",
"@ai-sdk/google-vertex": "3.0.74",
"@ai-sdk/mcp": "0.0.8",
"@ai-sdk/openai": "2.0.71",
"@ai-sdk/openai-compatible": "1.0.27",
"@clack/prompts": "1.0.0-alpha.1",
"@hono/standard-validator": "0.1.5",
"@hono/zod-validator": "catalog:",
@@ -56,8 +61,9 @@
"@opencode-ai/script": "workspace:*",
"@opencode-ai/sdk": "workspace:*",
"@opencode-ai/util": "workspace:*",
"@opentui/core": "0.1.47",
"@opentui/solid": "0.1.47",
"@openrouter/ai-sdk-provider": "1.2.5",
"@opentui/core": "0.1.49",
"@opentui/solid": "0.1.49",
"@parcel/watcher": "2.5.1",
"@pierre/precision-diffs": "catalog:",
"@solid-primitives/event-bus": "1.1.2",
+24
View File
@@ -4,9 +4,12 @@ import { Log } from "../util/log"
import path from "path"
import { NamedError } from "../util/error"
import { readableStreamToText } from "bun"
import { createRequire } from "module"
import { Lock } from "../util/lock"
export namespace BunProc {
const log = Log.create({ service: "bun" })
const req = createRequire(import.meta.url)
export async function run(cmd: string[], options?: Bun.SpawnOptions.OptionsObject<any, any, any>) {
log.info("running", {
@@ -58,6 +61,9 @@ export namespace BunProc {
)
export async function install(pkg: string, version = "latest") {
// Use lock to ensure only one install at a time
using _ = await Lock.write("bun-install")
const mod = path.join(Global.Path.cache, "node_modules", pkg)
const pkgjson = Bun.file(path.join(Global.Path.cache, "package.json"))
const parsed = await pkgjson.json().catch(async () => {
@@ -125,4 +131,22 @@ export namespace BunProc {
await Bun.write(pkgjson.name!, JSON.stringify(parsed, null, 2))
return mod
}
export async function resolve(pkg: string) {
const local = workspace(pkg)
if (local) return local
const dir = path.join(Global.Path.cache, "node_modules", pkg)
const pkgjson = Bun.file(path.join(dir, "package.json"))
const exists = await pkgjson.exists()
if (exists) return dir
}
function workspace(pkg: string) {
try {
const target = req.resolve(`${pkg}/package.json`)
return path.dirname(target)
} catch {
return
}
}
}
+24
View File
@@ -342,6 +342,21 @@ function App() {
dialog.clear()
},
},
{
title: "Suspend terminal",
value: "terminal.suspend",
keybind: "terminal_suspend",
category: "System",
onSelect: () => {
process.once("SIGCONT", () => {
renderer.resume()
})
renderer.suspend()
// pid=0 means send the signal to all processes in the process group
process.kill(0, "SIGTSTP")
},
},
])
createEffect(() => {
@@ -411,6 +426,15 @@ function App() {
})
})
event.on(Installation.Event.UpdateAvailable.type, (evt) => {
toast.show({
variant: "info",
title: "Update Available",
message: `OpenCode v${evt.properties.version} is available. Run 'opencode upgrade' to update manually.`,
duration: 10000,
})
})
return (
<box
width={dimensions().width}
@@ -5,7 +5,7 @@ import { createMemo, createResource, createEffect, onMount, For, Show } from "so
import { createStore } from "solid-js/store"
import { useSDK } from "@tui/context/sdk"
import { useSync } from "@tui/context/sync"
import { useTheme } from "@tui/context/theme"
import { useTheme, selectedForeground } from "@tui/context/theme"
import { SplitBorder } from "@tui/component/border"
import { useCommandDialog } from "@tui/component/dialog-command"
import { Locale } from "@/util/locale"
@@ -455,7 +455,7 @@ export function Autocomplete(props: {
{...SplitBorder}
borderColor={theme.border}
>
<box backgroundColor={theme.backgroundElement} height={height()}>
<box backgroundColor={theme.backgroundMenu} height={height()}>
<For
each={options()}
fallback={
@@ -471,11 +471,11 @@ export function Autocomplete(props: {
backgroundColor={index() === store.selected ? theme.primary : undefined}
flexDirection="row"
>
<text fg={index() === store.selected ? theme.background : theme.text} flexShrink={0}>
<text fg={index() === store.selected ? selectedForeground(theme) : theme.text} flexShrink={0}>
{option.display}
</text>
<Show when={option.description}>
<text fg={index() === store.selected ? theme.background : theme.textMuted} wrapMode="none">
<text fg={index() === store.selected ? selectedForeground(theme) : theme.textMuted} wrapMode="none">
{option.description}
</text>
</Show>
@@ -791,10 +791,17 @@ export function Prompt(props: PromptProps) {
height={1}
border={["bottom"]}
borderColor={theme.backgroundElement}
customBorderChars={{
...EmptyBorder,
horizontal: "▀",
}}
customBorderChars={
theme.background.a != 0
? {
...EmptyBorder,
horizontal: "▀",
}
: {
...EmptyBorder,
horizontal: " ",
}
}
/>
</box>
<box flexDirection="row" justifyContent="space-between">
@@ -94,6 +94,7 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
const agent = agents().find((x) => x.name === name)
if (agent?.color) return RGBA.fromHex(agent.color)
const index = agents().findIndex((x) => x.name === name)
if (index === -1) return colors()[0]
return colors()[index % colors().length]
},
}
@@ -33,7 +33,7 @@ import { createStore, produce } from "solid-js/store"
import { Global } from "@/global"
import { Filesystem } from "@/util/filesystem"
type Theme = {
type ThemeColors = {
primary: RGBA
secondary: RGBA
accent: RGBA
@@ -43,9 +43,11 @@ type Theme = {
info: RGBA
text: RGBA
textMuted: RGBA
selectedListItemText: RGBA
background: RGBA
backgroundPanel: RGBA
backgroundElement: RGBA
backgroundMenu: RGBA
border: RGBA
borderActive: RGBA
borderSubtle: RGBA
@@ -86,6 +88,27 @@ type Theme = {
syntaxPunctuation: RGBA
}
type Theme = ThemeColors & {
_hasSelectedListItemText: boolean
}
export function selectedForeground(theme: Theme): RGBA {
// If theme explicitly defines selectedListItemText, use it
if (theme._hasSelectedListItemText) {
return theme.selectedListItemText
}
// For transparent backgrounds, calculate contrast based on primary color
if (theme.background.a === 0) {
const { r, g, b } = theme.primary
const luminance = 0.299 * r + 0.587 * g + 0.114 * b
return luminance > 0.5 ? RGBA.fromInts(0, 0, 0) : RGBA.fromInts(255, 255, 255)
}
// Fall back to background color
return theme.background
}
type HexColor = `#${string}`
type RefName = string
type Variant = {
@@ -96,7 +119,10 @@ type ColorValue = HexColor | RefName | Variant | RGBA
type ThemeJson = {
$schema?: string
defs?: Record<string, HexColor | RefName>
theme: Record<keyof Theme, ColorValue>
theme: Omit<Record<keyof ThemeColors, ColorValue>, "selectedListItemText" | "backgroundMenu"> & {
selectedListItemText?: ColorValue
backgroundMenu?: ColorValue
}
}
export const DEFAULT_THEMES: Record<string, ThemeJson> = {
@@ -137,19 +163,44 @@ function resolveTheme(theme: ThemeJson, mode: "dark" | "light") {
if (defs[c]) {
return resolveColor(defs[c])
} else if (theme.theme[c as keyof Theme]) {
return resolveColor(theme.theme[c as keyof Theme])
} else if (theme.theme[c as keyof ThemeColors] !== undefined) {
return resolveColor(theme.theme[c as keyof ThemeColors]!)
} else {
throw new Error(`Color reference "${c}" not found in defs or theme`)
}
}
return resolveColor(c[mode])
}
return Object.fromEntries(
Object.entries(theme.theme).map(([key, value]) => {
return [key, resolveColor(value)]
}),
) as Theme
const resolved = Object.fromEntries(
Object.entries(theme.theme)
.filter(([key]) => key !== "selectedListItemText" && key !== "backgroundMenu")
.map(([key, value]) => {
return [key, resolveColor(value)]
}),
) as Partial<ThemeColors>
// Handle selectedListItemText separately since it's optional
const hasSelectedListItemText = theme.theme.selectedListItemText !== undefined
if (hasSelectedListItemText) {
resolved.selectedListItemText = resolveColor(theme.theme.selectedListItemText!)
} else {
// Backward compatibility: if selectedListItemText is not defined, use background color
// This preserves the current behavior for all existing themes
resolved.selectedListItemText = resolved.background
}
// Handle backgroundMenu - optional with fallback to backgroundElement
if (theme.theme.backgroundMenu !== undefined) {
resolved.backgroundMenu = resolveColor(theme.theme.backgroundMenu)
} else {
resolved.backgroundMenu = resolved.backgroundElement
}
return {
...resolved,
_hasSelectedListItemText: hasSelectedListItemText,
} as Theme
}
export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
@@ -288,11 +339,13 @@ function generateSystem(colors: TerminalColors, mode: "dark" | "light"): ThemeJs
// Text colors
text: fg,
textMuted,
selectedListItemText: bg,
// Background colors
background: bg,
backgroundPanel: grays[2],
backgroundElement: grays[3],
backgroundMenu: grays[3],
// Border colors
borderSubtle: grays[6],
@@ -6,8 +6,6 @@ import {
For,
Match,
on,
onCleanup,
onMount,
Show,
Switch,
useContext,
@@ -45,7 +43,6 @@ import type { TaskTool } from "@/tool/task"
import { useKeyboard, useRenderer, useTerminalDimensions, type BoxProps, type JSX } from "@opentui/solid"
import { useSDK } from "@tui/context/sdk"
import { useCommandDialog } from "@tui/component/dialog-command"
import { Shimmer } from "@tui/ui/shimmer"
import { useKeybind } from "@tui/context/keybind"
import { Header } from "./header"
import { parsePatch } from "diff"
@@ -64,8 +61,6 @@ import { Clipboard } from "../../util/clipboard"
import { Toast, useToast } from "../../ui/toast"
import { useKV } from "../../context/kv.tsx"
import { Editor } from "../../util/editor"
import { Global } from "@/global"
import fs from "fs/promises"
import stripAnsi from "strip-ansi"
addDefaultParsers(parsers.parsers)
@@ -84,6 +79,7 @@ const context = createContext<{
width: number
conceal: () => boolean
showThinking: () => boolean
showTimestamps: () => boolean
}>()
function use() {
@@ -106,10 +102,15 @@ export function Session() {
return messages().findLast((x) => x.role === "assistant" && !x.time.completed)?.id
})
const lastAssistant = createMemo(() => {
return messages().findLast((x) => x.role === "assistant")
})
const dimensions = useTerminalDimensions()
const [sidebar, setSidebar] = createSignal<"show" | "hide" | "auto">(kv.get("sidebar", "auto"))
const [conceal, setConceal] = createSignal(true)
const [showThinking, setShowThinking] = createSignal(true)
const [showTimestamps, setShowTimestamps] = createSignal(kv.get("timestamps", "hide") === "show")
const wide = createMemo(() => dimensions().width > 120)
const sidebarVisible = createMemo(() => sidebar() === "show" || (sidebar() === "auto" && wide()))
@@ -176,6 +177,7 @@ export function Session() {
const first = permissions()[0]
if (first) {
const response = iife(() => {
if (evt.ctrl || evt.meta) return
if (evt.name === "return") return "once"
if (evt.name === "a") return "always"
if (evt.name === "d") return "reject"
@@ -404,6 +406,19 @@ export function Session() {
dialog.clear()
},
},
{
title: "Toggle timestamps",
value: "session.toggle.timestamps",
category: "Session",
onSelect: (dialog) => {
setShowTimestamps((prev) => {
const next = !prev
kv.set("timestamps", next ? "show" : "hide")
return next
})
dialog.clear()
},
},
{
title: "Toggle thinking blocks",
value: "session.toggle.thinking",
@@ -513,7 +528,6 @@ export function Session() {
return
}
console.log(text)
const base64 = Buffer.from(text).toString("base64")
const osc52 = `\x1b]52;c;${base64}\x07`
const finalOsc52 = process.env["TMUX"] ? `\x1bPtmux;\x1b${osc52}\x1b\\` : osc52
@@ -714,6 +728,7 @@ export function Session() {
},
conceal,
showThinking,
showTimestamps,
}}
>
<box flexDirection="row" paddingBottom={1} paddingTop={1} paddingLeft={2} paddingRight={2} gap={2}>
@@ -846,7 +861,7 @@ export function Session() {
</Match>
<Match when={message.role === "assistant"}>
<AssistantMessage
last={pending() === message.id}
last={lastAssistant()?.id === message.id}
message={message as AssistantMessage}
parts={sync.data.part[message.id] ?? []}
/>
@@ -893,6 +908,7 @@ function UserMessage(props: {
index: number
pending?: string
}) {
const ctx = use()
const text = createMemo(() => props.parts.flatMap((x) => (x.type === "text" && !x.synthetic ? [x] : []))[0])
const files = createMemo(() => props.parts.flatMap((x) => (x.type === "file" ? [x] : [])))
const sync = useSync()
@@ -951,7 +967,13 @@ function UserMessage(props: {
{sync.data.config.username ?? "You"}{" "}
<Show
when={queued()}
fallback={<span style={{ fg: theme.textMuted }}>{Locale.time(props.message.time.created)}</span>}
fallback={
<span style={{ fg: theme.textMuted }}>
{ctx.showTimestamps()
? Locale.todayTimeOrDateTime(props.message.time.created)
: Locale.time(props.message.time.created)}
</span>
}
>
<span style={{ bg: theme.accent, fg: theme.backgroundPanel, bold: true }}> QUEUED </span>
</Show>
@@ -976,12 +998,20 @@ function AssistantMessage(props: { message: AssistantMessage; parts: Part[]; las
const local = useLocal()
const { theme } = useTheme()
const sync = useSync()
const status = createMemo(
() =>
sync.data.session_status[props.message.sessionID] ?? {
type: "idle",
},
)
const messages = createMemo(() => sync.data.message[props.message.sessionID] ?? [])
const final = createMemo(() => {
return props.message.finish && !["tool-calls", "unknown"].includes(props.message.finish)
})
const duration = createMemo(() => {
if (!final()) return 0
if (!props.message.time.completed) return 0
const user = messages().find((x) => x.role === "user" && x.id === props.message.parentID)
if (!user) return 0
return props.message.time.completed - user.time.created
})
return (
<>
<For each={props.parts}>
@@ -1014,57 +1044,15 @@ function AssistantMessage(props: { message: AssistantMessage; parts: Part[]; las
</box>
</Show>
<Switch>
<Match when={props.last && status().type !== "idle" && false}>
<box paddingLeft={3} flexDirection="row" gap={1} marginTop={1}>
<text fg={local.agent.color(props.message.mode)}>{Locale.titlecase(props.message.mode)}</text>
<Shimmer text={props.message.modelID} color={theme.text} />
{(() => {
const retry = createMemo(() => {
const s = status()
if (s.type !== "retry") return
return s
})
const message = createMemo(() => {
const r = retry()
if (!r) return
if (r.message.includes("exceeded your current quota") && r.message.includes("gemini"))
return "gemini 3 way too hot right now"
if (r.message.length > 50) return r.message.slice(0, 50) + "..."
return r.message
})
const [seconds, setSeconds] = createSignal(0)
onMount(() => {
const timer = setInterval(() => {
const next = retry()?.next
if (next) setSeconds(Math.round((next - Date.now()) / 1000))
}, 1000)
onCleanup(() => {
clearInterval(timer)
})
})
return (
<Show when={retry()}>
<text fg={theme.error}>
{message()} [retrying {seconds() > 0 ? `in ${seconds()}s ` : ""}
attempt #{retry()!.attempt}]
</text>
</Show>
)
})()}
</box>
</Match>
<Match
when={
(props.message.time.completed &&
props.parts.some((item) => item.type === "step-finish" && item.reason !== "tool-calls")) ||
props.last
}
>
<Match when={props.last || final()}>
<box paddingLeft={3}>
<text marginTop={1}>
<span style={{ fg: local.agent.color(props.message.mode) }}>{Locale.titlecase(props.message.mode)}</span>{" "}
<span style={{ fg: theme.textMuted }}>{props.message.modelID}</span>
<span style={{ fg: local.agent.color(props.message.mode) }}></span>{" "}
<span style={{ fg: theme.text }}>{Locale.titlecase(props.message.mode)}</span>{" "}
<span style={{ fg: theme.textMuted }}>{props.message.modelID}</span>
<Show when={duration()}>
<span style={{ fg: theme.textMuted }}> {Locale.duration(duration())}</span>
</Show>
</text>
</box>
</Match>
@@ -1110,7 +1098,7 @@ function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: Ass
function TextPart(props: { last: boolean; part: TextPart; message: AssistantMessage }) {
const ctx = use()
const { syntax } = useTheme()
const { theme, syntax } = useTheme()
return (
<Show when={props.part.text.trim()}>
<box id={"text-" + props.part.id} paddingLeft={3} marginTop={1} flexShrink={0}>
@@ -1121,6 +1109,7 @@ function TextPart(props: { last: boolean; part: TextPart; message: AssistantMess
syntaxStyle={syntax()}
content={props.part.text.trim()}
conceal={ctx.conceal()}
fg={theme.text}
/>
</box>
</Show>
@@ -1535,7 +1524,6 @@ ToolRegistry.register<typeof EditTool>({
const ft = createMemo(() => filetype(props.input.filePath))
createEffect(() => console.log(props.metadata.diagnostics))
const diagnostics = createMemo(() => {
const arr = props.metadata.diagnostics?.[props.input.filePath ?? ""] ?? []
return arr.filter((x) => x.severity === 1).slice(0, 3)
+14 -9
View File
@@ -58,16 +58,14 @@ export const TuiThreadCommand = cmd({
// Resolve relative paths against PWD to preserve behavior when using --cwd flag
const baseCwd = process.env.PWD ?? process.cwd()
const cwd = args.project ? path.resolve(baseCwd, args.project) : process.cwd()
const defaultWorker = new URL("./worker.ts", import.meta.url)
// Nix build creates a bundled worker next to the binary; prefer it when present.
const localWorker = new URL("./worker.ts", import.meta.url)
const distWorker = new URL("./cli/cmd/tui/worker.js", import.meta.url)
const execDir = path.dirname(process.execPath)
const bundledWorker = path.join(execDir, "opencode-worker.js")
const hasBundledWorker = await Bun.file(bundledWorker).exists()
const workerPath = (() => {
const workerPath = await iife(async () => {
if (typeof OPENCODE_WORKER_PATH !== "undefined") return OPENCODE_WORKER_PATH
if (hasBundledWorker) return bundledWorker
return defaultWorker
})()
if (await Bun.file(distWorker).exists()) return distWorker
return localWorker
})
try {
process.chdir(cwd)
} catch (e) {
@@ -99,7 +97,8 @@ export const TuiThreadCommand = cmd({
if (!args.prompt) return piped
return piped ? piped + "\n" + args.prompt : args.prompt
})
await tui({
const tuiPromise = tui({
url: server.url,
args: {
continue: args.continue,
@@ -112,5 +111,11 @@ export const TuiThreadCommand = cmd({
await client.call("shutdown", undefined)
},
})
setTimeout(() => {
client.call("checkUpgrade", { directory: cwd }).catch(() => {})
}, 1000)
await tuiPromise
},
})
@@ -38,7 +38,7 @@ export function DialogAlert(props: DialogAlertProps) {
dialog.clear()
}}
>
<text fg={theme.background}>ok</text>
<text fg={theme.selectedListItemText}>ok</text>
</box>
</box>
</box>
@@ -53,7 +53,9 @@ export function DialogConfirm(props: DialogConfirmProps) {
dialog.clear()
}}
>
<text fg={key === store.active ? theme.background : theme.textMuted}>{Locale.titlecase(key)}</text>
<text fg={key === store.active ? theme.selectedListItemText : theme.textMuted}>
{Locale.titlecase(key)}
</text>
</box>
)}
</For>
@@ -28,7 +28,7 @@ export function DialogHelp() {
</box>
<box flexDirection="row" justifyContent="flex-end" paddingBottom={1}>
<box paddingLeft={3} paddingRight={3} backgroundColor={theme.primary} onMouseUp={() => dialog.clear()}>
<text fg={theme.background}>ok</text>
<text fg={theme.selectedListItemText}>ok</text>
</box>
</box>
</box>
@@ -1,5 +1,5 @@
import { InputRenderable, RGBA, ScrollBoxRenderable, TextAttributes } from "@opentui/core"
import { useTheme } from "@tui/context/theme"
import { useTheme, selectedForeground } from "@tui/context/theme"
import { entries, filter, flatMap, groupBy, pipe, take } from "remeda"
import { batch, createEffect, createMemo, For, Show, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
@@ -262,32 +262,29 @@ function Option(props: {
onMouseOver?: () => void
}) {
const { theme } = useTheme()
const fg = selectedForeground(theme)
return (
<>
<Show when={props.current}>
<text
flexShrink={0}
fg={props.active ? theme.background : props.current ? theme.primary : theme.text}
marginRight={0.5}
>
<text flexShrink={0} fg={props.active ? fg : props.current ? theme.primary : theme.text} marginRight={0.5}>
</text>
</Show>
<text
flexGrow={1}
fg={props.active ? theme.background : props.current ? theme.primary : theme.text}
fg={props.active ? fg : props.current ? theme.primary : theme.text}
attributes={props.active ? TextAttributes.BOLD : undefined}
overflow="hidden"
wrapMode="none"
paddingLeft={3}
>
{Locale.truncate(props.title, 62)}
<span style={{ fg: props.active ? theme.background : theme.textMuted }}> {props.description}</span>
<span style={{ fg: props.active ? fg : theme.textMuted }}> {props.description}</span>
</text>
<Show when={props.footer}>
<box flexShrink={0}>
<text fg={props.active ? theme.background : theme.textMuted}>{props.footer}</text>
<text fg={props.active ? fg : theme.textMuted}>{props.footer}</text>
</box>
</Show>
</>
+8 -2
View File
@@ -26,8 +26,6 @@ process.on("uncaughtException", (e) => {
})
})
upgrade()
let server: Bun.Server<undefined>
export const rpc = {
async server(input: { port: number; hostname: string }) {
@@ -42,6 +40,14 @@ export const rpc = {
throw e
}
},
async checkUpgrade(input: { directory: string }) {
await Instance.provide({
directory: input.directory,
fn: async () => {
await upgrade().catch(() => {})
},
})
},
async shutdown() {
Log.Default.info("worker shutting down")
await Instance.disposeAll()
+6 -1
View File
@@ -5,10 +5,15 @@ import { Installation } from "@/installation"
export async function upgrade() {
const config = await Config.global()
if (config.autoupdate === false || Flag.OPENCODE_DISABLE_AUTOUPDATE) return
const latest = await Installation.latest().catch(() => {})
if (!latest) return
if (Installation.VERSION === latest) return
if (config.autoupdate === false || Flag.OPENCODE_DISABLE_AUTOUPDATE) {
await Bus.publish(Installation.Event.UpdateAvailable, { version: latest })
return
}
const method = await Installation.method()
if (method === "unknown") return
await Installation.upgrade(method, latest)
+1
View File
@@ -430,6 +430,7 @@ export namespace Config {
history_next: z.string().optional().default("down").describe("Next history item"),
session_child_cycle: z.string().optional().default("<leader>right").describe("Next child session"),
session_child_cycle_reverse: z.string().optional().default("<leader>left").describe("Previous child session"),
terminal_suspend: z.string().optional().default("ctrl+z").describe("Suspend terminal"),
})
.strict()
.meta({
+1 -1
View File
@@ -30,7 +30,7 @@ await Promise.all([
fs.mkdir(Global.Path.bin, { recursive: true }),
])
const CACHE_VERSION = "9"
const CACHE_VERSION = "11"
const version = await Bun.file(path.join(Global.Path.cache, "version"))
.text()
@@ -22,6 +22,12 @@ export namespace Installation {
version: z.string(),
}),
),
UpdateAvailable: Bus.event(
"installation.update-available",
z.object({
version: z.string(),
}),
),
}
export const Info = z
+1 -1
View File
@@ -28,7 +28,7 @@ export namespace Plugin {
}
const plugins = [...(config.plugin ?? [])]
if (!Flag.OPENCODE_DISABLE_DEFAULT_PLUGINS) {
plugins.push("opencode-copilot-auth@0.0.5")
plugins.push("opencode-copilot-auth@0.0.7")
plugins.push("opencode-anthropic-auth@0.0.2")
}
for (let plugin of plugins) {
+40 -19
View File
@@ -530,13 +530,18 @@ export namespace Provider {
const existing = s.sdk.get(key)
if (existing) return existing
let installedPath: string
if (!pkg.startsWith("file://")) {
installedPath = await BunProc.install(pkg, "latest")
} else {
log.info("loading local provider", { pkg })
installedPath = pkg
}
const installedPath = await (async () => {
if (pkg.startsWith("file://")) {
log.info("loading local provider", { pkg })
return pkg
}
const resolved = await BunProc.resolve(pkg)
if (resolved) {
log.info("using preinstalled provider", { providerID: provider.id, pkg })
return resolved
}
return BunProc.install(pkg, "latest")
})()
// The `google-vertex-anthropic` provider points to the `@ai-sdk/google-vertex` package.
// Ref: https://github.com/sst/models.dev/blob/0a87de42ab177bebad0620a889e2eb2b4a5dd4ab/providers/google-vertex-anthropic/provider.toml
@@ -658,20 +663,36 @@ export namespace Provider {
}
const provider = await state().then((state) => state.providers[providerID])
if (!provider) return
let priority = ["claude-haiku-4-5", "claude-haiku-4.5", "3-5-haiku", "3.5-haiku", "gemini-2.5-flash", "gpt-5-nano"]
// claude-haiku-4.5 is considered a premium model in github copilot, we shouldn't use premium requests for title gen
if (providerID === "github-copilot") {
priority = priority.filter((m) => m !== "claude-haiku-4.5")
}
if (providerID === "opencode" || providerID === "local") {
priority = ["gpt-5-nano"]
}
for (const item of priority) {
for (const model of Object.keys(provider.info.models)) {
if (model.includes(item)) return getModel(providerID, model)
if (provider) {
let priority = [
"claude-haiku-4-5",
"claude-haiku-4.5",
"3-5-haiku",
"3.5-haiku",
"gemini-2.5-flash",
"gpt-5-nano",
]
// claude-haiku-4.5 is considered a premium model in github copilot, we shouldn't use premium requests for title gen
if (providerID === "github-copilot") {
priority = priority.filter((m) => m !== "claude-haiku-4.5")
}
if (providerID.startsWith("opencode")) {
priority = ["gpt-5-nano"]
}
for (const item of priority) {
for (const model of Object.keys(provider.info.models)) {
if (model.includes(item)) return getModel(providerID, model)
}
}
}
// Check if opencode provider is available before using it
const opencodeProvider = await state().then((state) => state.providers["opencode"])
if (opencodeProvider && opencodeProvider.info.models["gpt-5-nano"]) {
return getModel("opencode", "gpt-5-nano")
}
return undefined
}
const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
+28 -6
View File
@@ -128,12 +128,7 @@ export namespace ProviderTransform {
return undefined
}
export function options(
providerID: string,
modelID: string,
npm: string,
sessionID: string,
): Record<string, any> | undefined {
export function options(providerID: string, modelID: string, npm: string, sessionID: string): Record<string, any> {
const result: Record<string, any> = {}
// switch to providerID later, for now use this
@@ -175,6 +170,25 @@ export namespace ProviderTransform {
return result
}
export function smallOptions(input: { providerID: string; modelID: string }) {
const options: Record<string, any> = {}
if (input.providerID === "openai" || input.modelID.includes("gpt-5")) {
if (input.modelID.includes("5.1")) {
options["reasoningEffort"] = "low"
} else {
options["reasoningEffort"] = "minimal"
}
}
if (input.providerID === "google") {
options["thinkingConfig"] = {
thinkingBudget: 0,
}
}
return options
}
export function providerOptions(npm: string | undefined, providerID: string, options: { [x: string]: any }) {
switch (npm) {
case "@ai-sdk/openai":
@@ -258,4 +272,12 @@ export namespace ProviderTransform {
return schema
}
export function error(providerID: string, message: string) {
if (providerID === "github-copilot" && message.includes("The requested model is not supported")) {
message +=
"\n\nMake sure the model is enabled in your copilot settings: https://github.com/settings/copilot/features"
}
return message
}
}
+11 -5
View File
@@ -15,6 +15,7 @@ import { Log } from "../util/log"
import { ProviderTransform } from "@/provider/transform"
import { SessionProcessor } from "./processor"
import { fn } from "@/util/fn"
import { mergeDeep, pipe } from "remeda"
export namespace SessionCompaction {
const log = Log.create({ service: "session.compaction" })
@@ -96,7 +97,7 @@ export namespace SessionCompaction {
abort: AbortSignal
}) {
const model = await Provider.getModel(input.model.providerID, input.model.modelID)
const system = [...SystemPrompt.summarize(model.providerID)]
const system = [...SystemPrompt.compaction(model.providerID)]
const msg = (await Session.updateMessage({
id: Identifier.ascending("message"),
role: "assistant",
@@ -137,10 +138,15 @@ export namespace SessionCompaction {
},
// set to 0, we handle loop
maxRetries: 0,
providerOptions: ProviderTransform.providerOptions(model.npm, model.providerID, {
...ProviderTransform.options(model.providerID, model.modelID, model.npm ?? "", input.sessionID),
...model.info.options,
}),
providerOptions: ProviderTransform.providerOptions(
model.npm,
model.providerID,
pipe(
{},
mergeDeep(ProviderTransform.options(model.providerID, model.modelID, model.npm ?? "", input.sessionID)),
mergeDeep(model.info.options),
),
),
headers: model.info.headers,
abortSignal: input.abort,
tools: model.info.tool_call ? {} : undefined,
+3 -1
View File
@@ -8,6 +8,7 @@ import { LSP } from "../lsp"
import { Snapshot } from "@/snapshot"
import { fn } from "@/util/fn"
import { Storage } from "@/storage/storage"
import { ProviderTransform } from "@/provider/transform"
export namespace MessageV2 {
export const OutputLengthError = NamedError.create("MessageOutputLengthError", z.object({}))
@@ -737,9 +738,10 @@ export namespace MessageV2 {
{ cause: e },
).toObject()
case APICallError.isInstance(e):
const message = ProviderTransform.error(ctx.providerID, e.message)
return new MessageV2.APIError(
{
message: e.message,
message,
statusCode: e.statusCode,
isRetryable: e.isRetryable,
responseHeaders: e.responseHeaders,
+40 -41
View File
@@ -197,7 +197,7 @@ export namespace SessionPrompt {
const message = await createUserMessage(input)
await Session.touch(input.sessionID)
if (input.noReply) {
if (input.noReply === true) {
return message
}
@@ -489,11 +489,12 @@ export namespace SessionPrompt {
? (agent.temperature ?? ProviderTransform.temperature(model.providerID, model.modelID))
: undefined,
topP: agent.topP ?? ProviderTransform.topP(model.providerID, model.modelID),
options: {
...ProviderTransform.options(model.providerID, model.modelID, model.npm ?? "", sessionID),
...model.info.options,
...agent.options,
},
options: pipe(
{},
mergeDeep(ProviderTransform.options(model.providerID, model.modelID, model.npm ?? "", sessionID)),
mergeDeep(model.info.options),
mergeDeep(agent.options),
),
},
)
@@ -533,7 +534,7 @@ export namespace SessionPrompt {
}
},
headers: {
...(model.providerID === "opencode"
...(model.providerID.startsWith("opencode")
? {
"x-opencode-session": sessionID,
"x-opencode-request": lastUser.id,
@@ -906,22 +907,32 @@ export namespace SessionPrompt {
extra: { bypassCwdCheck: true, ...info.model },
metadata: async () => {},
})
pieces.push(
{
id: Identifier.ascending("part"),
messageID: info.id,
sessionID: input.sessionID,
type: "text",
synthetic: true,
text: result.output,
},
{
pieces.push({
id: Identifier.ascending("part"),
messageID: info.id,
sessionID: input.sessionID,
type: "text",
synthetic: true,
text: result.output,
})
if (result.attachments?.length) {
pieces.push(
...result.attachments.map((attachment) => ({
...attachment,
synthetic: true,
filename: attachment.filename ?? part.filename,
messageID: info.id,
sessionID: input.sessionID,
})),
)
} else {
pieces.push({
...part,
id: part.id ?? Identifier.ascending("part"),
messageID: info.id,
sessionID: input.sessionID,
},
)
})
}
})
.catch((error) => {
log.error("failed to read file", { error })
@@ -1384,7 +1395,6 @@ export namespace SessionPrompt {
return result
}
// TODO: wire this back up
async function ensureTitle(input: {
session: Session.Info
message: MessageV2.WithParts
@@ -1400,24 +1410,15 @@ export namespace SessionPrompt {
if (!isFirst) return
const small =
(await Provider.getSmallModel(input.providerID)) ?? (await Provider.getModel(input.providerID, input.modelID))
const options = {
...ProviderTransform.options(small.providerID, small.modelID, small.npm ?? "", input.session.id),
...small.info.options,
}
if (small.providerID === "openai" || small.modelID.includes("gpt-5")) {
if (small.modelID.includes("5.1")) {
options["reasoningEffort"] = "low"
} else {
options["reasoningEffort"] = "minimal"
}
}
if (small.providerID === "google") {
options["thinkingConfig"] = {
thinkingBudget: 0,
}
}
const options = pipe(
{},
mergeDeep(ProviderTransform.options(small.providerID, small.modelID, small.npm ?? "", input.session.id)),
mergeDeep(ProviderTransform.smallOptions({ providerID: small.providerID, modelID: small.modelID })),
mergeDeep(small.info.options),
)
await generateText({
maxOutputTokens: small.info.reasoning ? 1500 : 20,
// use higher # for reasoning models since reasoning tokens eat up a lot of the budget
maxOutputTokens: small.info.reasoning ? 3000 : 20,
providerOptions: ProviderTransform.providerOptions(small.npm, small.providerID, options),
messages: [
...SystemPrompt.title(small.providerID).map(
@@ -1427,10 +1428,8 @@ export namespace SessionPrompt {
}),
),
{
role: "user" as const,
content: `
The following is the text to summarize:
`,
role: "user",
content: "Generate a title for this conversation:\n",
},
...MessageV2.toModelMessage([
{
@@ -0,0 +1,10 @@
You are a helpful AI assistant tasked with summarizing conversations.
When asked to summarize, provide a detailed but concise summary of the conversation.
Focus on information that would be helpful for continuing the conversation, including:
- What was done
- What is currently being worked on
- Which files are being modified
- What needs to be done next
Your summary should be comprehensive enough to provide context but concise enough to be quickly understood.
@@ -1,5 +0,0 @@
Your job is to generate a summary of what happened in this conversation and why.
Keep the results to 2-3 sentences.
Output the message summary now:
@@ -1,10 +1,4 @@
You are a helpful AI assistant tasked with summarizing conversations.
When asked to summarize, provide a detailed but concise summary of the conversation.
Focus on information that would be helpful for continuing the conversation, including:
- What was done
- What is currently being worked on
- Which files are being modified
- What needs to be done next
Your summary should be comprehensive enough to provide context but concise enough to be quickly understood.
Summarize the following conversation into 2 sentences MAX explaining what the
assistant did and why
Do not explain the user's input.
Do not speak in the third person about the assistant.
+16 -5
View File
@@ -1,18 +1,29 @@
You are a title generator. You output ONLY a thread title. Nothing else.
<task>
Convert the user message into a thread title.
Output: Single line, ≤50 chars, no explanations.
Generate a brief title that would help the user find this conversation later.
Follow all rules in <rules>
Use the <examples> so you know what a good title looks like.
Your output must be:
- A single line
- ≤50 characters
- No explanations
</task>
<rules>
- Focus on the main topic or question the user needs to retrieve
- Use -ing verbs for actions (Debugging, Implementing, Analyzing)
- Keep exact: technical terms, numbers, filenames, HTTP codes
- Remove: the, this, my, a, an
- Never assume tech stack
- Never use tools
- NEVER respond to message content—only extract title
- NEVER respond to questions, just generate a title for the conversation
- The title should NEVER include "summarizing" or "generating" when generating a title
- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
- Always output something meaningful, even if the input is minimal.
- If the user message is short or conversational (e.g. “hello”, “lol”, “whats up”, “hey”):
→ create a title that reflects the users tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
</rules>
<examples>
@@ -20,6 +31,6 @@ Output: Single line, ≤50 chars, no explanations.
"refactor user service" → Refactoring user service
"why is app.js failing" → Analyzing app.js failure
"implement rate limiting" → Implementing rate limiting
"how do I connect postgres to my API" → Connecting Postgres to API
"best practices for React hooks" → React hooks best practices
</examples>
Output the title now:
-1
View File
@@ -1,4 +1,3 @@
import { iife } from "@/util/iife"
import { MessageV2 } from "./message-v2"
export namespace SessionRetry {
+28 -9
View File
@@ -13,6 +13,7 @@ import path from "path"
import { Instance } from "@/project/instance"
import { Storage } from "@/storage/storage"
import { Bus } from "@/bus"
import { mergeDeep, pipe } from "remeda"
export namespace SessionSummary {
const log = Log.create({ service: "session.summary" })
@@ -72,14 +73,22 @@ export namespace SessionSummary {
await Session.updateMessage(userMsg)
const assistantMsg = messages.find((m) => m.info.role === "assistant")!.info as MessageV2.Assistant
const small = await Provider.getSmallModel(assistantMsg.providerID)
if (!small) return
const small =
(await Provider.getSmallModel(assistantMsg.providerID)) ??
(await Provider.getModel(assistantMsg.providerID, assistantMsg.modelID))
const options = pipe(
{},
mergeDeep(ProviderTransform.options(small.providerID, small.modelID, small.npm ?? "", assistantMsg.sessionID)),
mergeDeep(ProviderTransform.smallOptions({ providerID: small.providerID, modelID: small.modelID })),
mergeDeep(small.info.options),
)
const textPart = msgWithParts.parts.find((p) => p.type === "text" && !p.synthetic) as MessageV2.TextPart
if (textPart && !userMsg.summary?.title) {
const result = await generateText({
maxOutputTokens: small.info.reasoning ? 1500 : 20,
providerOptions: ProviderTransform.providerOptions(small.npm, small.providerID, {}),
providerOptions: ProviderTransform.providerOptions(small.npm, small.providerID, options),
messages: [
...SystemPrompt.title(small.providerID).map(
(x): ModelMessage => ({
@@ -115,18 +124,28 @@ export namespace SessionSummary {
.findLast((m) => m.info.role === "assistant")
?.parts.findLast((p) => p.type === "text")?.text
if (!summary || diffs.length > 0) {
for (const msg of messages) {
for (const part of msg.parts) {
if (part.type === "tool" && part.state.status === "completed") {
part.state.output = "[TOOL OUTPUT PRUNED]"
}
}
}
const result = await generateText({
model: small.language,
maxOutputTokens: 100,
providerOptions: ProviderTransform.providerOptions(small.npm, small.providerID, options),
messages: [
...SystemPrompt.summarize(small.providerID).map(
(x): ModelMessage => ({
role: "system",
content: x,
}),
),
...MessageV2.toModelMessage(messages),
{
role: "user",
content: `
Summarize the following conversation into 2 sentences MAX explaining what the assistant did and why. Do not explain the user's input. Do not speak in the third person about the assistant.
<conversation>
${JSON.stringify(MessageV2.toModelMessage(messages))}
</conversation>
`,
content: `Summarize the above conversation according to your system prompts.`,
},
],
headers: small.info.headers,
+10
View File
@@ -13,6 +13,7 @@ import PROMPT_POLARIS from "./prompt/polaris.txt"
import PROMPT_BEAST from "./prompt/beast.txt"
import PROMPT_GEMINI from "./prompt/gemini.txt"
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
import PROMPT_COMPACTION from "./prompt/compaction.txt"
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
import PROMPT_TITLE from "./prompt/title.txt"
import PROMPT_CODEX from "./prompt/codex.txt"
@@ -116,6 +117,15 @@ export namespace SystemPrompt {
return Promise.all(found).then((result) => result.filter(Boolean))
}
export function compaction(providerID: string) {
switch (providerID) {
case "anthropic":
return [PROMPT_ANTHROPIC_SPOOF.trim(), PROMPT_COMPACTION]
default:
return [PROMPT_COMPACTION]
}
}
export function summarize(providerID: string) {
switch (providerID) {
case "anthropic":
+6
View File
@@ -70,6 +70,12 @@ export const BashTool = Tool.define("bash", async () => {
return "/bin/zsh"
}
if (process.platform === "win32") {
// Let Bun / Node pick COMSPEC (usually cmd.exe)
// or explicitly:
return process.env.COMSPEC || true
}
const bash = Bun.which("bash")
if (bash) {
return bash
+44 -2
View File
@@ -3,9 +3,29 @@ export namespace Locale {
return str.replace(/\b\w/g, (c) => c.toUpperCase())
}
export function time(input: number) {
export function time(input: number): string {
const date = new Date(input)
return date.toLocaleTimeString()
return date.toLocaleTimeString(undefined, { timeStyle: "short" })
}
export function datetime(input: number): string {
const date = new Date(input)
const localTime = time(input)
const localDate = date.toLocaleDateString()
return `${localTime} · ${localDate}`
}
export function todayTimeOrDateTime(input: number): string {
const date = new Date(input)
const now = new Date()
const isToday =
date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth() && date.getDate() === now.getDate()
if (isToday) {
return time(input)
} else {
return datetime(input)
}
}
export function number(num: number): string {
@@ -17,6 +37,28 @@ export namespace Locale {
return num.toString()
}
export function duration(input: number) {
if (input < 1000) {
return `${input}ms`
}
if (input < 60000) {
return `${(input / 1000).toFixed(1)}s`
}
if (input < 3600000) {
const minutes = Math.floor(input / 60000)
const seconds = Math.floor((input % 60000) / 1000)
return `${minutes}m ${seconds}s`
}
if (input < 86400000) {
const hours = Math.floor(input / 3600000)
const minutes = Math.floor((input % 3600000) / 60000)
return `${hours}h ${minutes}m`
}
const hours = Math.floor(input / 3600000)
const days = Math.floor((input % 3600000) / 86400000)
return `${days}d ${hours}h`
}
export function truncate(str: string, len: number): string {
if (str.length <= len) return str
return str.slice(0, len - 1) + "…"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/plugin",
"version": "1.0.97",
"version": "1.0.107",
"type": "module",
"scripts": {
"typecheck": "tsgo --noEmit",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode-ai/sdk",
"version": "1.0.97",
"version": "1.0.107",
"type": "module",
"scripts": {
"typecheck": "tsgo --noEmit",
+12
View File
@@ -7,6 +7,13 @@ export type EventInstallationUpdated = {
}
}
export type EventInstallationUpdateAvailable = {
type: "installation.update-available"
properties: {
version: string
}
}
export type EventLspClientDiagnostics = {
type: "lsp.client.diagnostics"
properties: {
@@ -642,6 +649,7 @@ export type EventFileWatcherUpdated = {
export type Event =
| EventInstallationUpdated
| EventInstallationUpdateAvailable
| EventLspClientDiagnostics
| EventLspUpdated
| EventMessageUpdated
@@ -846,6 +854,10 @@ export type KeybindsConfig = {
* Previous child session
*/
session_child_cycle_reverse?: string
/**
* Suspend terminal
*/
terminal_suspend?: string
}
export type AgentConfig = {
+12
View File
@@ -39,6 +39,9 @@ class Resource:
class Console:
type: str
url: str
class ConsoleData:
name: str
type: str
class Database:
database: str
host: str
@@ -52,6 +55,9 @@ class Resource:
class EMAILOCTOPUS_API_KEY:
type: str
value: str
class EnterpriseStorage:
name: str
type: str
class GITHUB_APP_ID:
type: str
value: str
@@ -75,6 +81,12 @@ class Resource:
value: str
class LogProcessor:
type: str
class R2AccessKey:
type: str
value: str
class R2SecretKey:
type: str
value: str
class STRIPE_SECRET_KEY:
type: str
value: str
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-ai/slack",
"version": "1.0.97",
"version": "1.0.107",
"type": "module",
"scripts": {
"dev": "bun run src/index.ts",
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+7
View File
@@ -0,0 +1,7 @@
# Tauri + Vanilla TS
This template should help get you started developing with Tauri in vanilla HTML, CSS and Typescript.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
+35
View File
@@ -0,0 +1,35 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="/src/styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri App</title>
<script type="module" src="/src/main.ts" defer></script>
</head>
<body>
<main class="container">
<h1>Welcome to Tauri</h1>
<div class="row">
<a href="https://vite.dev" target="_blank">
<img src="/src/assets/vite.svg" class="logo vite" alt="Vite logo" />
</a>
<a href="https://tauri.app" target="_blank">
<img src="/src/assets/tauri.svg" class="logo tauri" alt="Tauri logo" />
</a>
<a href="https://www.typescriptlang.org/docs" target="_blank">
<img src="/src/assets/typescript.svg" class="logo typescript" alt="typescript logo" />
</a>
</div>
<p>Click on the Tauri logo to learn more about the framework</p>
<form class="row" id="greet-form">
<input id="greet-input" placeholder="Enter a name..." />
<button type="submit">Greet</button>
</form>
<p id="greet-msg"></p>
</main>
</body>
</html>
+21
View File
@@ -0,0 +1,21 @@
{
"name": "@opencode-ai/tauri",
"private": true,
"version": "1.0.107",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@tauri-apps/cli": "^2",
"vite": "^6.0.3",
"typescript": "~5.6.2"
}
}
+7
View File
@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
+5224
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "opencode"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "opencode_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

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